content
stringlengths
10
4.9M
/* * @Author: <NAME> * @Date: 2019-12-12 15:09:32 * @LastEditTime: 2019-12-12 17:15:05 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \ant-design-pro\src\services\request.tsx */ import {requestJson} from "@/utils/request" export async function commonProxy(params: any){ const url=params.url; params={body:{...params},method:'POST'}; requestJson(url,params); }
/** * Desplaza una columna hacia abajo. * @param tab tablero del juego complica a desplazar. */ private void despColAbajo(Tablero tab) { this.fichaDesplazada = tab.getCasilla(0, this.col); for (int f = 0; f < ReglasComplica.FILAS_CO - 1; f++) { Ficha aux = tab.getCasilla(f + 1, this.col); tab.setFicha(f, this.col, aux); } tab.setFicha(ReglasComplica.FILAS_CO - 1, this.col, this.color); this.fil = ReglasComplica.FILAS_CO - 1; }
#ifndef STOUT_SMEAR_H_ #define STOUT_SMEAR_H_ #include "hila.h" #include "gauge/staples.h" ///////////////////////////////////////////////////////////////////////////// /// Do stout smearing for the gauge fields /// res = U * exp( Algebra (U * Staples) ) template <typename T> void stout_smear1(const GaugeField<T> &U, Field<T> &s, float coeff, Direction d) { staplesum(U, s, d, ALL); onsites(ALL) { s[X] = exp(coeff * (s[X] * U[d][X].dagger()).project_to_algebra()) * U[d][X]; } } template <typename T> void stout_smear1(const GaugeField<T> &U, GaugeField<T> &stout, float coeff) { foralldir(d) stout_smear1(U,stout[d],coeff,d); // stout_smear1(U,stout[e_t],coeff,e_t); } template <typename T> void stout_smear(const GaugeField<T> &U, GaugeField<T> &stout, float coeff, int iter) { stout = U; if (iter > 0) { stout_smear1(U,stout,coeff); GaugeField<T> tmp; for (int i=1; i<iter; i++) { stout_smear1(stout,tmp,coeff); stout = tmp; // std::swap(stout,tmp); } } } #endif
<reponame>vertoforce/tinygo package loader // This file constructs a new temporary GOROOT directory by merging both the // standard Go GOROOT and the GOROOT from TinyGo using symlinks. import ( "crypto/sha512" "encoding/hex" "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "path" "path/filepath" "runtime" "sync" "github.com/tinygo-org/tinygo/compileopts" "github.com/tinygo-org/tinygo/goenv" ) var gorootCreateMutex sync.Mutex // GetCachedGoroot creates a new GOROOT by merging both the standard GOROOT and // the GOROOT from TinyGo using lots of symbolic links. func GetCachedGoroot(config *compileopts.Config) (string, error) { goroot := goenv.Get("GOROOT") if goroot == "" { return "", errors.New("could not determine GOROOT") } tinygoroot := goenv.Get("TINYGOROOT") if tinygoroot == "" { return "", errors.New("could not determine TINYGOROOT") } // Determine the location of the cached GOROOT. version, err := goenv.GorootVersionString(goroot) if err != nil { return "", err } // This hash is really a cache key, that contains (hopefully) enough // information to make collisions unlikely during development. // By including the Go version and TinyGo version, cache collisions should // not happen outside of development. hash := sha512.New512_256() fmt.Fprintln(hash, goroot) fmt.Fprintln(hash, version) fmt.Fprintln(hash, goenv.Version) fmt.Fprintln(hash, tinygoroot) gorootsHash := hash.Sum(nil) gorootsHashHex := hex.EncodeToString(gorootsHash[:]) cachedgorootName := "goroot-" + version + "-" + gorootsHashHex cachedgoroot := filepath.Join(goenv.Get("GOCACHE"), cachedgorootName) if needsSyscallPackage(config.BuildTags()) { cachedgoroot += "-syscall" } // Do not try to create the cached GOROOT in parallel, that's only a waste // of I/O bandwidth and thus speed. Instead, use a mutex to make sure only // one goroutine does it at a time. // This is not a way to ensure atomicity (a different TinyGo invocation // could be creating the same directory), but instead a way to avoid // creating it many times in parallel when running tests in parallel. gorootCreateMutex.Lock() defer gorootCreateMutex.Unlock() if _, err := os.Stat(cachedgoroot); err == nil { return cachedgoroot, nil } err = os.MkdirAll(goenv.Get("GOCACHE"), 0777) if err != nil { return "", err } tmpgoroot, err := ioutil.TempDir(goenv.Get("GOCACHE"), cachedgorootName+".tmp") if err != nil { return "", err } // Remove the temporary directory if it wasn't moved to the right place // (for example, when there was an error). defer os.RemoveAll(tmpgoroot) for _, name := range []string{"bin", "lib", "pkg"} { err = symlink(filepath.Join(goroot, name), filepath.Join(tmpgoroot, name)) if err != nil { return "", err } } err = mergeDirectory(goroot, tinygoroot, tmpgoroot, "", pathsToOverride(needsSyscallPackage(config.BuildTags()))) if err != nil { return "", err } err = os.Rename(tmpgoroot, cachedgoroot) if err != nil { if os.IsExist(err) { // Another invocation of TinyGo also seems to have created a GOROOT. // Use that one instead. Our new GOROOT will be automatically // deleted by the defer above. return cachedgoroot, nil } if runtime.GOOS == "windows" && os.IsPermission(err) { // On Windows, a rename with a destination directory that already // exists does not result in an IsExist error, but rather in an // access denied error. To be sure, check for this case by checking // whether the target directory exists. if _, err := os.Stat(cachedgoroot); err == nil { return cachedgoroot, nil } } return "", err } return cachedgoroot, nil } // mergeDirectory merges two roots recursively. The tmpgoroot is the directory // that will be created by this call by either symlinking the directory from // goroot or tinygoroot, or by creating the directory and merging the contents. func mergeDirectory(goroot, tinygoroot, tmpgoroot, importPath string, overrides map[string]bool) error { if mergeSubdirs, ok := overrides[importPath+"/"]; ok { if !mergeSubdirs { // This directory and all subdirectories should come from the TinyGo // root, so simply make a symlink. newname := filepath.Join(tmpgoroot, "src", importPath) oldname := filepath.Join(tinygoroot, "src", importPath) return symlink(oldname, newname) } // Merge subdirectories. Start by making the directory to merge. err := os.Mkdir(filepath.Join(tmpgoroot, "src", importPath), 0777) if err != nil { return err } // Symlink all files from TinyGo, and symlink directories from TinyGo // that need to be overridden. tinygoEntries, err := ioutil.ReadDir(filepath.Join(tinygoroot, "src", importPath)) if err != nil { return err } for _, e := range tinygoEntries { if e.IsDir() { // A directory, so merge this thing. err := mergeDirectory(goroot, tinygoroot, tmpgoroot, path.Join(importPath, e.Name()), overrides) if err != nil { return err } } else { // A file, so symlink this. newname := filepath.Join(tmpgoroot, "src", importPath, e.Name()) oldname := filepath.Join(tinygoroot, "src", importPath, e.Name()) err := symlink(oldname, newname) if err != nil { return err } } } // Symlink all directories from $GOROOT that are not part of the TinyGo // overrides. gorootEntries, err := ioutil.ReadDir(filepath.Join(goroot, "src", importPath)) if err != nil { return err } for _, e := range gorootEntries { if !e.IsDir() { // Don't merge in files from Go. Otherwise we'd end up with a // weird syscall package with files from both roots. continue } if _, ok := overrides[path.Join(importPath, e.Name())+"/"]; ok { // Already included above, so don't bother trying to create this // symlink. continue } newname := filepath.Join(tmpgoroot, "src", importPath, e.Name()) oldname := filepath.Join(goroot, "src", importPath, e.Name()) err := symlink(oldname, newname) if err != nil { return err } } } return nil } // needsSyscallPackage returns whether the syscall package should be overriden // with the TinyGo version. This is the case on some targets. func needsSyscallPackage(buildTags []string) bool { for _, tag := range buildTags { if tag == "baremetal" || tag == "darwin" || tag == "nintendoswitch" { return true } } return false } // The boolean indicates whether to merge the subdirs. True means merge, false // means use the TinyGo version. func pathsToOverride(needsSyscallPackage bool) map[string]bool { paths := map[string]bool{ "/": true, "device/": false, "examples/": false, "internal/": true, "internal/bytealg/": false, "internal/reflectlite/": false, "internal/task/": false, "machine/": false, "os/": true, "reflect/": false, "runtime/": false, "sync/": true, "testing/": true, } if needsSyscallPackage { paths["syscall/"] = true // include syscall/js } return paths } // symlink creates a symlink or something similar. On Unix-like systems, it // always creates a symlink. On Windows, it tries to create a symlink and if // that fails, creates a hardlink or directory junction instead. // // Note that while Windows 10 does support symlinks and allows them to be // created using os.Symlink, it requires developer mode to be enabled. // Therefore provide a fallback for when symlinking is not possible. // Unfortunately this fallback only works when TinyGo is installed on the same // filesystem as the TinyGo cache and the Go installation (which is usually the // C drive). func symlink(oldname, newname string) error { symlinkErr := os.Symlink(oldname, newname) if runtime.GOOS == "windows" && symlinkErr != nil { // Fallback for when developer mode is disabled. // Note that we return the symlink error even if something else fails // later on. This is because symlinks are the easiest to support // (they're also used on Linux and MacOS) and enabling them is easy: // just enable developer mode. st, err := os.Stat(oldname) if err != nil { return symlinkErr } if st.IsDir() { // Make a directory junction. There may be a way to do this // programmatically, but it involves a lot of magic. Use the mklink // command built into cmd instead (mklink is a builtin, not an // external command). err := exec.Command("cmd", "/k", "mklink", "/J", newname, oldname).Run() if err != nil { return symlinkErr } } else { // Try making a hard link. err := os.Link(oldname, newname) if err != nil { // Making a hardlink failed. Try copying the file as a last // fallback. inf, err := os.Open(oldname) if err != nil { return err } defer inf.Close() outf, err := os.Create(newname) if err != nil { return err } defer outf.Close() _, err = io.Copy(outf, inf) if err != nil { os.Remove(newname) return err } // File was copied. } } return nil // success } return symlinkErr }
The epidemiology of personality disorders in the Sao Paulo Megacity general population Introduction Most studies on the epidemiology of personality disorders (PDs) have been conducted in high-income countries and may not represent what happens in most part of the world. In the last decades, population growth has been concentrated in low- and middle-income countries, with rapid urbanization, increasing inequalities and escalation of violence. Our aim is to estimate the prevalence of PDs in the Sao Paulo Metropolitan Area, one of the largest megacities of the world. We examined sociodemographic correlates, the influence of urban stressors, the comorbidity with other mental disorders, functional impairment and treatment. Methods A representative household sample of 2,942 adults was interviewed using the WHO-Composite International Diagnostic Interview and the International Personality Disorder Examination-Screening Questionnaire. Diagnoses were multiply imputed, and analyses used multivariable regression. Results and discussion Prevalence estimates were 4.3% (Cluster A), 2.7% (Cluster B), 4.6% (Cluster C) and 6.8% (any PD). Cumulative exposure to violence was associated with all PDs except Cluster A, although urbanicity, migration and neighborhood social deprivation were not significant predictors. Comorbidity was the rule, and all clusters were associated with other mental disorders. Lack of treatment is a reality in Greater Sao Paulo, and this is especially true for PDs. With the exception of Cluster C, non-comorbid PDs remained largely untreated in spite of functional impairment independent of other mental disorders. Conclusion Personality disorders are prevalent, clinically significant and undertreated, and public health strategies must address the unmet needs of these subjects. Our results may reflect what happens in other developing world megacities, and future studies are expected in other low- and middle-income countries.
def _decode_config(c, num_variables): def bits(c): n = 1 << (num_variables - 1) for __ in range(num_variables): yield 1 if c & n else -1 n >>= 1 return tuple(bits(c))
def nce_loss(inputs, weights, biases, labels, sample, unigram_prob): epsilon = 1e-10 batch_size, embedding_size = inputs.shape num_sampled = k = sample.shape[0] wc = inputs unigram_prob = tf.convert_to_tensor(unigram_prob) w0 = tf.reshape(tf.nn.embedding_lookup(weights, labels), [batch_size, embedding_size]) b0 = tf.nn.embedding_lookup(biases, labels) P_w0 = tf.reshape(tf.nn.embedding_lookup(unigram_prob, labels), [batch_size, 1]) wx = tf.nn.embedding_lookup(weights, sample) bx = tf.reshape(tf.nn.embedding_lookup(biases, sample), [num_sampled, 1]) P_wx = tf.reshape(tf.nn.embedding_lookup(unigram_prob, sample), [num_sampled, 1]) s = tf.matmul(wc, w0, transpose_b=True) s = tf.reshape(tf.diag_part(s), [batch_size, 1]) + b0 P_w0_wc = tf.sigmoid(s - tf.log(k*P_w0)) s = tf.matmul(wc, wx, transpose_b=True) bx = tf.tile(bx, [1, batch_size]) bx = tf.transpose(bx) s += bx P_wx = tf.transpose(tf.tile(P_wx, [1, batch_size])) P_wx_wc = tf.sigmoid(s - tf.log(k*P_wx)) A = tf.log(P_w0_wc + epsilon) B = tf.reshape(tf.reduce_sum(tf.log(1 - P_wx_wc + epsilon), axis=1), [batch_size, 1]) return tf.scalar_mul(-1, tf.add(A, B))
<filename>code/honest_ur.py #from rvor_functions import move_on_edge, rotate_over_node from robot_functions import * from requests import post from json import loads def main(): print('protocol begins') ''' each clock follows these sequences of instruction: state = 'state name' set state function movement or rotation get states function sync clock function ''' # !!! make sure robot eyes are looking at left # if not, protocol does not work as expected init_eyes_motor(eyes_speed) # init values state = 'initial' special_node_reached = 0 print('\t' + 'state: ' + str(state).upper()) if us.connected: us.mode = 'US-DIST-CM' if ir.connected: ir.mode = 'IR-PROX' previous_state = state # query the server to start print('connect to server') start() # after that each robot uses an own counter # in this way all the robot operations are synchronized begin_time = int(time()) while True: # print current state for debugging if (previous_state != state): print('\t' + 'state: ' + str(state).upper()) previous_state = state if state == 'initial': # notify to server the intention of moving blocked_last_move = set_node_info(state) if blocked_last_move: print('robot is blocked in last move') state = 'stopped' #turned = True set_node_info(state, turned=1, stopped=1) # move robot on the other side of the node # because no other robots could come from the opposite direction, # since M block them cross_marker() rotate_over_node() else: # robot moves cross_marker() # a robot may can collide with another in state done, but in this case motors stop move_on_edge() # then it "looks around" to collect the states of the other robots on the same node # actually, these states have been stored before, with the call of set_node_info function performed by each robot neighbors_states, blocked_last_move = get_node_info() # after that robot moved, it syncronize its clock waiting the remaining time begin_time = wait_clock(begin_time) # no more than one robot for a node can be in state stopped if len(neighbors_states) == 1 and neighbors_states[0] == 'stopped': print('met a robot in state stopped') state = 'done' set_node_info(state, turned=1, stopped=1) # move robot on the other side of the node # take the place of stopped robot cross_marker() rotate_over_node() # no more than one robot in state initial can reach M, # without first reach a stopped robot elif len(neighbors_states) == 0 and blocked_last_move: state = 'stopped' #turned = True set_node_info(state, turned=1, stopped=1) # move robot on the other side of the node # because no other robots could come from the opposite direction, # since M block them cross_marker() rotate_over_node() # [TODO] change this condition elif is_special_node(): special_node_reached += 1 nbr_star_robots = get_state_robots(neighbors_states, robot_state='star') if special_node_reached == 2 and nbr_star_robots == 0: state = 'star' # move robot in the middle of the curve # because other robots could arrive from both the direction # but when they arrived from the same direction, they must go straight on cross_marker() # [TODO] # unfortunately node is small, the exact time to rotate is important # to avoid robots to bump one to each other rotate_over_node(time_out=4.5) elif state == 'stopped': # during this time, other robots perform a set sleep(2) neighbors_states, blocked_last_move = get_node_info() # no more than one robot reach a stopped robot if len(neighbors_states) == 1 and neighbors_states[0] == 'initial': print('met a robot in state initial') begin_time = wait_clock(begin_time) # a stopped robot rotated over node, so direction is changed # new state is set in next state state = 'collect' elif len(neighbors_states) == 1 and neighbors_states[0] == 'collect': print('met a robot in state collect') # wait a clock, during this time collect robot is rotating over the node begin_time = wait_clock(begin_time, nbr_clocks=2) # a stopped robot rotated over node, so direction is changed # new state is set in next state first_returning_robot = True state = 'return' else: begin_time = wait_clock(begin_time) ''' elif len(neighbors_states) == 1 and neighbors_states[0] == 'check': print('met a robot in state check') # a stopped robot rotated over node, so direction is changed #turned = True state = 'return' ''' # wait only if the state remain stopped, otherwise start moving, see others state # else: # begin_time = wait_clock(begin_time) elif state == 'collect': # notify to server the intention of moving blocked_last_move = set_node_info(state) if blocked_last_move: print('robot is blocked in last move') state = 'return' set_node_info(state, turned=1, stopped=1) cross_marker() rotate_over_node() else: # robot moves cross_marker() # a robot may can collide with another in state done or in state star, # but in this case motors stop move_on_edge() neighbors_states, blocked_last_move = get_node_info() nbr_done_robots = get_state_robots(neighbors_states, robot_state='done') begin_time = wait_clock(begin_time) # if found exactly one neighbor in state stopped or all the neighbors in state done if (len(neighbors_states) == 1 and neighbors_states[0] == 'stopped') or (nbr_done_robots > 0 and nbr_done_robots == len(neighbors_states)): if neighbors_states[0] == 'stopped': print('met a robot in state stopped') else: print('met ' + str(nbr_done_robots) + ' robots in state done') # if nbr of done robots is odd if nbr_done_robots % 2 == 1: # note that this case never happen when the nbr of robots is 3 state = 'done' # [TODO] try to think how more that two robots can exit the node else: # for simplicity we consider only the case of max 3 robots # this means that robot reachs a marker while only one stopped robot is on the other side of the node # meanwhile, a stopped robot, meeting a collect robot, became return #motor_m.run_to_abs_pos(position_sp = 45) cross_marker() # rotate over node in order to reach other robot # robot should stop due to collision avoidance setting #rotate_over_node(collision_distance=collision_avoidance_distance) rotate_over_node(time_out=3) #motor_m.run_to_abs_pos(position_sp = 0) # sync, during this time stopped robot waits begin_time = wait_clock(begin_time) # no need to check state # complete node rotate_over_node(time_to_settle=0) first_returning_robot = False state = 'return' # notify the change of direction (turned = 1) set_node_info(state, turned=1, stopped=1) elif blocked_last_move: print('collect robot meets M') cross_marker() rotate_over_node() state = 'return' elif state == 'return': neighbors_states, blocked_last_move = get_node_info() nbr_star_robots = get_state_robots(neighbors_states, robot_state = 'star') nbr_done_robots = get_state_robots(neighbors_states, robot_state = 'done') if nbr_star_robots == 1: print('met a robot in state star') # [TODO] solve following for this case if nbr_done_robots == 1: state = 'gathering' set_node_info(state, stopped=1) else: # no need to check if M is over next node set_node_info(state) # collection of more robots has been implemented by setting all these robots # in state return, before moving a robot check if it is not the first returning robot # ie it is not over a marker, it's over black line # (we assume that no more than 2 robots are returning) #if not is_not_color_black( [color.value()] ): # color must be in COL-REFLECT mode if not first_returning_robot: # color must be in COL-REFLECT mode print('I\'m the second returning robot') sleep(0.5) # complete the edge move_on_edge(collision_distance=-1, time_to_settle=0) cross_marker() robot_collision = move_on_edge() # sync neighbors_states, blocked_last_move = get_node_info() begin_time = wait_clock(begin_time) nbr_done_robots = get_state_robots(neighbors_states, robot_state = 'done') # returning robot perform gathering if nbr_done_robots >= 1: # the first one move for some seconds, to leave some space for the incoming robot if not robot_collision: print('first returning robot performs gathering') cross_marker() move_on_edge(collision_distance=-1, time_out=2) else: print('second returning robot performs gathering') # the second one move for at most 2 seconds, but is stops if it detects a collision sleep(1.5) move_on_edge(time_out=2) # in both case, perform gathering state = 'gathering' set_node_info(state, stopped=1) elif state == 'done': # no need to set it neighbors_states, blocked_last_move = get_node_info() begin_time = wait_clock(begin_time) # no more than one robot reach a done robot if len(neighbors_states) >= 1 and neighbors_states[0] == 'return': print('met a robot in state return') # a stopped robot rotated over node, so direction is changed # new state is set in next state state = 'gathering' set_node_info(state, stopped=1) elif state == 'gathering': # protocol ends break if __name__ == '__main__': main()
// Load logger targets based on user's configuration func loadLoggers() { auditEndpoint, ok := os.LookupEnv("MINIO_AUDIT_LOGGER_HTTP_ENDPOINT") if ok { logger.AddAuditTarget(http.New(auditEndpoint, NewCustomHTTPTransport())) } loggerEndpoint, ok := os.LookupEnv("MINIO_LOGGER_HTTP_ENDPOINT") if ok { logger.AddTarget(http.New(loggerEndpoint, NewCustomHTTPTransport())) } else { for _, l := range globalServerConfig.Logger.HTTP { if l.Enabled { logger.AddTarget(http.New(l.Endpoint, NewCustomHTTPTransport())) } } } if globalServerConfig.Logger.Console.Enabled { logger.AddTarget(console.New()) } }
// Path return the path of the mountpoint of the named filesystem // if no volume with name exists, an empty path and an error is returned func (s *Module) path(name string) (filesystem.Pool, filesystem.Volume, pkg.Volume, error) { for _, pool := range s.ssds { if _, err := pool.Mounted(); err != nil { continue } filesystems, err := pool.Volumes() if err != nil { return nil, nil, pkg.Volume{}, err } for _, fs := range filesystems { if fs.Name() == name { usage, err := fs.Usage() if err != nil { return nil, nil, pkg.Volume{}, err } return pool, fs, pkg.Volume{ Name: fs.Name(), Path: fs.Path(), Usage: pkg.Usage{ Size: gridtypes.Unit(usage.Size), Used: gridtypes.Unit(usage.Used), }, }, nil } } } return nil, nil, pkg.Volume{}, errors.Wrapf(os.ErrNotExist, "subvolume '%s' not found", name) }
Are you currently developing or maintaining a medium to large-sized program written in a functional language, such as Haskell, F#, OCaml, or Lisp? Chris Bogart is a PhD student doing a study of functional programmers, as part of a research internship at Microsoft, and would like the opportunity to look over your shoulder while you do debugging or coding on your project. Here's what he says: I'm looking for people with at least a year's experience doing functional programming, and who are currently working on a real project (i.e. for some purpose other than learning functional programming). I'm only allowed to use people who can work in the US (because of the gratuity, which is taxable income). I'd simply come watch you work, and ask a few questions along the way. You'd do whatever you would normally be doing. If you're near Seattle or Portland, I'd come to your office for a couple of hours. If you're not near Seattle or Portland, then we'd set you up with LiveMeeting or some other remote screencast software so I can watch you from here. Obviously security concerns are an issue - I will not share any proprietary information that I learn about while visiting you. In exchange for your help, Microsoft will offer you your pick of free software off its gratuity list (which has about 50 items, including Visual Studio Professional, Word for Mac, XBOX 360 games) or any book from MS Press. We're doing this because expert functional programmers have not been studied much. We plan to share our findings through academic publications, to help tool developers create debugging tools that are genuinely helpful in real-world settings. I'm hoping to finish my observations by August 8th, so please contact me immediately if you're interested!
<reponame>yijunyu/demo-fast #include "breadthfirstsearch.h" #include "graph/digraph.h" #include "graph/vertex.h" #include "graph/arc.h" #include "property/propertymap.h" #include <deque> namespace Algora { BreadthFirstSearch::BreadthFirstSearch(bool computeValues) : PropertyComputingAlgorithm<bool, int>(computeValues), startVertex(0), maxBfsNumber(-1), onVertexDiscovered(vertexTrue), onArcDiscovered(arcTrue), vertexStopCondition(vertexFalse), arcStopCondition(arcFalse) { } BreadthFirstSearch::~BreadthFirstSearch() { } bool BreadthFirstSearch::prepare() { return PropertyComputingAlgorithm<bool, int>::prepare() && ( startVertex == 0 || diGraph->containsVertex(startVertex)); } void BreadthFirstSearch::run() { if (startVertex == 0) { startVertex = diGraph->getAnyVertex(); } std::deque<Vertex*> queue; PropertyMap<bool> discovered(false); PropertyMap<int> *bfsNumber = propertyMap; maxBfsNumber = 0; queue.push_back(startVertex); discovered[startVertex] = true; if (computePropertyValues) { (*bfsNumber)[startVertex] = maxBfsNumber; } bool stop = false; while (!stop && !queue.empty()) { Vertex *curr = queue.front(); queue.pop_front(); stop |= vertexStopCondition(curr); if (stop) { break; } diGraph->mapOutgoingArcsUntil(curr, [&](Arc *a) { bool consider = onArcDiscovered(a); stop |= arcStopCondition(a); if (stop || !consider) { return; } Vertex *head = a->getHead(); if (!discovered(head)) { if (!onVertexDiscovered(head)) { return; } queue.push_back(a->getHead()); discovered[head] = true; maxBfsNumber++; if (computePropertyValues) { (*bfsNumber)[head] = maxBfsNumber; } } }, [&](const Arc *) { return stop; }); } } bool BreadthFirstSearch::deliver() { return maxBfsNumber + 1 == (int) diGraph->getSize(); } void BreadthFirstSearch::onDiGraphSet() { maxBfsNumber = -1; } }
class SourceResolver: """A helper class that is used to read and store the discord.py source lines.""" PATH = pathlib.Path(os.path.dirname(inspect.getfile(discord))) def __init__(self): self.source = defaultdict(list) def __contains__(self, item): return resolve_line(item, self.source) def __getitem__(self, item): return self.source[item] @staticmethod def resolve_source_object(file: Path): """Given a PosixPath object, this returns an object that is compatible to :meth:`~inspect.getsourcelines`. This also covers the `__init__.py` files of Python modules. # TODO: Find a way to resolve the contents of `__main__.py` """ parts = file.parts name = file.name.rpartition('.')[0] if file.parts[-2] == 'commands': # we're in discord.ext.commands obj = (getattr(commands, name) if parts[-1] != '__init__.py' else commands) else: # we're in discord obj = (getattr(discord, name) if parts[-1] != '__init__.py' else commands) return name, obj @staticmethod def cleanup_code(code: list): """Cleans up a list containing source lines and returns a cleaned-up version with stripped lines and removed new line characters.""" # We must pay attention to the following aspects: # # First of all, there are lines that may only contain # a new line character or some whitespaces. these must # be removed. # Further, we need to strip all unnecessary indents from # the source lines as well as remove new line characters. # And last but not least, every file contains license information # and an encoding declaration. These need to be removed. try: start = code.index('"""\n') + 1 end = code[start:].index('"""\n') + 4 except ValueError: start, end = 0, 0 code = [ line.replace('\n', '').strip() for line in code[end:] if line != '\n' or line.strip() ] return code def read_source(self): for file in list(self.PATH.glob('*.py')) + list(self.PATH.joinpath('ext/commands').glob('*.py')): try: name, obj = self.resolve_source_object(file) except (AttributeError, TypeError): continue lines = inspect.getsourcelines(obj)[0] obj = self.cleanup_code(lines) self.source[name] = obj
/* Called when the model's window has been reshaped. */ void myReshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(65.0, (GLfloat) w / (GLfloat) h, 1.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -5.0); glScalef(1.5, 1.5, 1.5); }
#include <stdio.h> // #include <conio.h> int main() { int a [1000] ; int i=0; int maxima=0, minima=0, extremum=0 ; int array_count; // printf ("Enter Array Count"); scanf("%d", &array_count); for (i=0; i< array_count; i++) { // printf ("Enter Array index %0d value", i); scanf("%d", a+i); } // printf ("Array is \n"); // for (i = 0; i<10; i++) // { // printf ("%0d ", a[i]); // } for (i = 0; i<array_count; i++) { if ( (i==0) || (i == array_count-1) ) continue; // printf ("\ni=%0d, a[i-1]=%0d, a[i]=%0d, a[i+1]=%0d", i, a[i-1], a[i], a[i+1]); if ( (a[i-1] < a[i]) && (a[i] > a[i+1]) ) { maxima++; // printf ("\n\t Maxima = %0d", maxima); } if ( (a[i-1] > a[i]) && (a[i] < a[i+1]) ) { minima++; // printf ("\n\t MINIma = %0d", minima); } } extremum = maxima + minima; // printf ("\n Total number of maxima=%0d, minima=%0d and extremum = %0d\n", maxima, minima, extremum); printf ("%d", extremum); return(0); }
#include "WinGiant/All.hpp" using namespace WinGiant; int main() { UTIL::ProcessRunOnce once(L"YourSuperLongName"); if (!once.canRun()) { printf("one process exists, exit me!\n"); return 0; } printf("I'm the only one!\n"); ::Sleep(10*1000); printf("I'm the only one, exit!\n"); return 0; }
<filename>src/main/java/com/boohee/utility/Event.java package com.boohee.utility; public class Event { public static final String AndroidNetworkError = "AndroidNetworkError"; public static final String AndroidNoConnectionError = "AndroidNoConnectionError"; public static final String AndroidServerError = "AndroidServerError"; public static final String AndroidTimeoutError = "AndroidTimeoutError"; public static final String BINGO_CLICKCHANGECOURSE = "bingo_clickChangeCourse"; public static final String BINGO_CLICKRESETCOURSE = "bingo_clickResetCourse"; public static final String BINGO_SHARECOURSESTAT = "bingo_shareCourseStat"; public static final String BINGO_VIEWCOURSEDOC = "bingo_viewCourseDoc"; public static final String BINGO_VIEWCOURSEHISTORY = "bingo_viewCourseHistory"; public static final String BINGO_VIEWCOURSESTAT = "bingo_viewCourseStat"; public static final String BINGO_VIEWSTEPHISTORY = "bingo_viewStepHistory"; public static final String CLUB_CLICK_CLUB = "club_clickClub"; public static final String CLUB_VIEW_EVENT = "club_viewEvent"; public static final String CLUB_VIEW_HOT_STATUS = "club_viewHotStatus"; public static final String CLUB_VIEW_KNOWLEAGE = "club_viewKnowleage"; public static final String CLUB_VIEW_STATUS = "club_viewStatus"; public static final String CLUB_VIEW_USERS = "club_viewUsers"; public static final String DIET_SHARE_BOOHEE = "tool_shareDietToStatus"; public static final String DIET_SHARE_CLICK = "tool_clickShareDiet"; public static final String DIET_SHARE_SNS = "tool_shareDietToSNS"; public static final String HOME_CHECK_IN = "bingo_viewCheckinPage"; public static final String HOME_CHECK_IN_CLICK = "bingo_clickCheckin"; public static final String HOME_CLICKCHCEKIN = "home_clickChcekIn"; public static final String HOME_CLICKHEADIMAGE = "home_clickHeadImage"; public static final String HOME_CLICK_HEAD_IMAGE = "home_clickHeadImage"; public static final String HOME_CLICK_MORE_TIPS = "bingo_clickMoreTips"; public static final String HOME_CLICK_MORE_TOPIC = "home_clickMoreTopic"; public static final String HOME_CLICK_RECOMMEND_AD = "home_clickRecommendAd"; public static final String HOME_CLICK_RECOMMEND_USER = "home_clickRecommendAd"; public static final String HOME_CLICK_SCHOOL = "home_clickSchool"; public static final String HOME_CLICK_SEARCH_FOOD = "home_clickSearchFood"; public static final String HOME_CLICK_SUCCESS_STORY = "home_clickSuccessStory"; public static final String HOME_CLICK_THIN_PLAN = "home_clickThinPlan"; public static final String HOME_CLICK_TOPIC = "home_clickTopic"; public static final String HOME_CONSULTOR = "bingo_clickConversations"; public static final String HOME_DIAMOND = "bingo_viewRedeemPage"; public static final String HOME_DIET_PLAN = "bingo_clickDiet"; public static final String HOME_DOWN_PICTURE = "bingo_downloadPicture"; public static final String HOME_DUSHOU = "bingo_clickEvent"; public static final String HOME_HOMEPAGE = "home_homePage"; public static final String HOME_OPEN_PICTURE = "bingo_openPicture"; public static final String HOME_PAGE = "bingo_homePage"; public static final String HOME_SPORT_PLAN = "bingo_clickExercise"; public static final String HOME_TIPS = "bingo_clickTips"; public static final String HOME_WEIGHT_RECORD = "bingo_clickWeightRecord"; public static final String MINE_ACCOUNT = "mine_clickAccount"; public static final String MINE_ADD_DIET_RECORD_OK = "mine_addDietRecordOK"; public static final String MINE_ADD_OTHER_RECORD_OK = "mine_addOtherRecordOK"; public static final String MINE_ADD_RECORD_OK = "mine_addRecordOK"; public static final String MINE_ADD_SHARE_OK = "mine_addShareOK"; public static final String MINE_ADD_SPORT_RECORD_OK = "mine_addSpotrRecordOK"; public static final String MINE_ADD_WEIGHT_RECORD_OK = "mine_addWeightRecordOK"; public static final String MINE_ALL_RECORD_OK = "mine_allRecordOK"; public static final String MINE_CLEAR_CACHE = "mine_clickClearCache"; public static final String MINE_CLICKADDRESSPAGE = "mine_clickAddressPage"; public static final String MINE_CLICKCARTPAGE = "mine_clickCartPage"; public static final String MINE_CLICKFINEFRIEND = "mine_clickFineFriend"; public static final String MINE_CLICKFRIENDPAGE = "mine_clickFriendPage"; public static final String MINE_CLICKGIFTCOUPONS = "mine_clickGiftCoupons"; public static final String MINE_CLICKHEALTHREPORT = "mine_clickHealthReport"; public static final String MINE_CLICKMYTIMELINE = "mine_clickMyTimeline"; public static final String MINE_CLICKNICE = "mine_clickNice"; public static final String MINE_CLICKORDERPAGE = "mine_clickOrderPage"; public static final String MINE_CLICKSYNCDATA = "mine_clickSyncData"; public static final String MINE_CLICKTHINPLAN = "mine_clickThinPlan"; public static final String MINE_CLICK_CLOSE_ALARM_BUTTON = "mine_clickCloseAlarmButton"; public static final String MINE_CLICK_SHARE = "mine_clickShare"; public static final String MINE_FAVORITE = "mine_clickFavorite"; public static final String MINE_RANK = "mine_clickRank"; public static final String MINE_REDEEM = "mine_clickRedeem"; public static final String MINE_UPDATE_MC_RECORD_OK = "mine_updateMcRecordOK"; public static final String MINE_VIEW_BROADCASTS_DETAIL_PAGE = "mine_viewBroadcastsDetialPage"; public static final String MINE_VIEW_BROADCASTS_LIST_PAGE = "mine_viewBroadcastsListPage"; public static final String MINE_VIEW_CLIENT_SERVICE_PAGE = "mine_viewClientServicePage"; public static final String MINE_VIEW_DIAMOND_BANK_PAGE = "mine_viewDiamondBankPage"; public static final String MINE_VIEW_REMIND_LIST_PAGE = "mine_viewRemindListPage"; public static final String OTHER_CLICKALERTPAGE = "other_clickAlertPage"; public static final String OTHER_CLICKAPNPAGE = "other_clickApnPage"; public static final String OTHER_CLICKMSGPAGE = "other_clickMsgPage"; public static final String OTHER_CLICKMYPAGE = "other_clickMyPage"; public static final String OTHER_CLICKPLUS = "other_clickPlus"; public static final String OTHER_CLICKPLUSBREAKFAST = "other_clickPlusBreakfast"; public static final String OTHER_CLICKPLUSDINNER = "other_clickPlusDinner"; public static final String OTHER_CLICKPLUSLUNCH = "other_clickPlusLunch"; public static final String OTHER_CLICKPLUSMC = "other_clickPlusMc"; public static final String OTHER_CLICKPLUSPOST = "other_clickPlusPost"; public static final String OTHER_CLICKPLUSSNACK = "other_clickPlusSnack"; public static final String OTHER_CLICKPLUSSPORT = "other_clickPlusSport"; public static final String OTHER_CLICKPLUSWAIST = "other_clickPlusWaist"; public static final String OTHER_CLICKPLUSWEIGHT = "other_clickPlusWeight"; public static final String OTHER_CLICKREMIND = "other_clickRemind"; public static final String OTHER_RECEIVEREMIND = "other_receiveRemind"; public static final String OTHER_VIEWBROADCASTSCONTENT = "other_viewBroadcastsContent"; public static final String OTHER_VIEWBROADCASTSLIST = "other_viewBroadcastsList"; public static final String PLAN_FOOD_QUICKRECORD = "plan_food_quickrecord"; public static final String RECORD_WEIGHT_STATUS_SHARE = "record_weight_status_share"; public static final String SERVICE_CLICK_BUY_RECIPE = "service_clickBuyRecipe"; public static final String SERVICE_CLICK_BUY_SMART = "service_clickBuySmart"; public static final String SERVICE_HOME_PAGE = "service_homePage"; public static final String SERVICE_VIEW_SMART_PAGE = "service_viewSmartPage"; public static final String SERVICE_VIEWs_RECIPE_PAGE = "service_viewRecipePage"; public static final String SHOP_CLICKCLIENTSERVICEPAGE = "shop_clickClientServicePage"; public static final String SHOP_CLICKMORECOMMENTS = "shop_clickMoreComments"; public static final String SHOP_CLICKPRODUCTSERVICE = "shop_clickProductService"; public static final String SHOP_CLICKQUICKBUY = "shop_clickQuickBuy"; public static final String SHOP_CLICK_BUY = "shop_clickBuy"; public static final String SHOP_CLICK_CALCULATE_BILL = "shop_clickCalculateBill"; public static final String SHOP_CLICK_CART = "shop_clickCart"; public static final String SHOP_CLICK_PAYMENT = "shop_clickPayment"; public static final String SHOP_CLICK_SUBMITORDER = "shop_clickSubmitOrder"; public static final String SHOP_HOMEPAGE = "shop_homePage"; public static final String SHOP_SPECIAL_LIST_PAGE = "shop_viewSpecialListPage"; public static final String SHOP_VIEW_CATE_LIST_PAGE = "shop_viewCateListPage"; public static final String SHOP_VIEW_PRODUCT_DETAIL_PAGE = "shop_viewProductDetialPage"; public static final String STATUS_ADD_ATTITUTE_OK = "status_addAttitudeOK"; public static final String STATUS_ADD_COMMENT_OK = "status_addCommentOK"; public static final String STATUS_ADD_INTERACT_OK = "status_addInteractOK"; public static final String STATUS_ADD_REOST_OK = "status_addReostOK"; public static final String STATUS_ADD_SHARE_OK = "status_addShareOK"; public static final String STATUS_ADD_STATUS_OK = "status_addStatusOK"; public static final String STATUS_HOMEPAGE = "status_homePage"; public static final String STATUS_SAVE_IMAGE_OK = "status_saveImageOK"; public static final String STATUS_SEND_PAGE = "status_sendPage"; public static final String STATUS_UPLOAD_IMAGE_FAILUE = "status_uploadImageFailure"; public static final String STATUS_VIEW_COMMENT_PAGE = "status_viewCommentPage"; public static final String STATUS_VIEW_FIND_FRIEND_PAGE = "status_viewFindFriendPage"; public static final String STATUS_VIEW_FLIP_CONTENT = "status_viewFlipContent"; public static final String STATUS_VIEW_FRIEND_PAGE = "status_viewFriendPage"; public static final String STATUS_VIEW_GROUP_HOME_PAGE = "status_viewGroupHomePage"; public static final String STATUS_VIEW_GROUP_INTRODUCE_PAGE = "status_viewGroupIntroducePage"; public static final String STATUS_VIEW_GROUP_STATUS_PAGE = "status_viewGroupStatusPage"; public static final String STATUS_VIEW_MESSAGE_CATE = "status_viewMessageCate"; public static final String STATUS_VIEW_MESSAGE_LST = "status_viewMessageList"; public static final String STATUS_VIEW_USER_PAGE = "status_viewUserPage"; public static final String STEPS_DETAIL = "steps_detail"; public static final String STEPS_SHARE = "steps_share"; public static final String TOOL_DAILYANALYZE = "tool_dailyanalyze"; public static final String TOOL_DAILYANALYZE_ASK = "tool_dailyanalyze_ask"; public static final String TOOL_DAILYANALYZE_SHARE = "tool_dailyanalyze_share"; public static final String TOOL_FOODANDSPORT_ABSTRACT = "tool_foodandsport_abstract"; public static final String TOOL_FOODANDSPORT_ABSTRACTSHARE = "tool_foodandsport_abstractshare"; public static final String TOOL_FOODANDSPORT_ADDFOOD = "tool_foodandsport_addfood"; public static final String TOOL_FOODANDSPORT_COPY = "tool_foodandsport_copy"; public static final String TOOL_FOODANDSPORT_COPYDONE = "tool_foodandsport_copydone"; public static final String TOOL_FOODANDSPORT_ENTER = "tool_foodandsport_enter"; public static final String TOOL_FOODANDSPORT_FAVORITETAB = "tool_foodandsport_favoritetab"; public static final String TOOL_FOODANDSPORT_MINETAB = "tool_foodandsport_minetab"; public static final String TOOL_FOODANDSPORT_SPORT = "tool_foodandsport_sport"; public static final String TOOL_FOODANDSPORT_SPORTSEARCH = "tool_foodandsport_sportsearch"; public static final String TOOL_FOOD_AND_SPORT = "tool_foodandsport"; public static final String TOOL_GRIRTH = "tool_girth"; public static final String TOOL_MY_FOOD = "tool_myfood"; public static final String TOOL_PERIED = "tool_period"; public static final String TOOL_QUICK_GIRTH = "tool_quickgirth"; public static final String TOOL_SEARCH_FOOD = "tool_searchfood"; public static final String TOOL_SEARCH_SPORT = "tool_searchSport"; public static final String TOOL_VIEW_CATE_LIST_PAGE = "tool_viewFoodCateListPage"; public static final String TOOL_VIEW_FOOD_CATE_PAGE = "tool_viewFoodCatePage"; public static final String TOOL_VIEW_FOOD_DETAIL_PAGE = "tool_viewFoodDetialPage"; public static final String TOOL_VIEW_FOOD_HOME_PAGE = "tool_viewFoodHomePage"; public static final String TOOL_VIEW_RECIPE_CATE_LIST_PAGE = "tool_viewRecipeCateListPage"; public static final String TOOL_VIEW_RECIPE_CATE_PAGE = "tool_viewRecipeCatePage"; public static final String TOOL_VIEW_SPORT_DETAIL_PAGE = "tool_viewSportDetialPage"; public static final String TOOL_VIEW_SPORT_HOME_PAGE = "tool_viewSportHomePage"; public static final String TOOL_WEIGHT_ENTER = "tool_weight"; public static final String TOOL_WEIGHT_QUICKRECORD = "tool_quickweight"; public static final String bingo_checkSportCourse = "bingo_checkSportCourse"; public static final String bingo_clickBindingScalse = "bingo_clickBindingScalse"; public static final String bingo_clickChangeDiet = "bingo_clickChangeDiet"; public static final String bingo_clickCopyDiet = "bingo_clickCopyDiet"; public static final String bingo_clickCourseDownload = "bingo_clickCourseDownload"; public static final String bingo_clickCourseVideo = "bingo_clickCourseVideo"; public static final String bingo_clickDateDiet = "bingo_clickDateDiet"; public static final String bingo_clickNewDiet = "bingo_clickNewDiet"; public static final String bingo_clickSteps = "bingo_clickSteps"; public static final String bingo_clickTmDiet = "bingo_clickTmDiet"; public static final String bingo_clickWeight = "bingo_clickWeight"; public static final String bingo_playSportCourseVideo = "bingo_playSportCourseVideo"; public static final String bingo_set_wallPaper = "bingo_setWallpaper"; public static final String bingo_shareHistorySportCourse = "bingo_shareHistorySportCourse"; public static final String bingo_sharePicture = "bingo_sharePicture"; public static final String bingo_shareSportCourse = "bingo_shareSportCourse"; public static final String bingo_uncheckSportCourse = "bingo_uncheckSportCourse"; public static final String bingo_viewCourseDetail = "bingo_viewCourseDetail"; public static final String bingo_viewDownloadList = "bingo_viewDownloadList"; public static final String bingo_viewHistorySportCourse = "bingo_viewHistorySportCourse"; public static final String bingo_viewNextSportCourse = "bingo_viewNextSportCourse"; public static final String bingo_viewScalsePage = "bingo_viewScalsePage"; public static final String bingo_viewSportCourse = "bingo_viewSportCourse"; public static final String challenge_clickCheckComment = "challenge_clickCheckComment"; public static final String challenge_clickCheckDiamond = "challenge_clickCheckDiamond"; public static final String challenge_clickCheckShare = "challenge_clickCheckShare"; public static final String challenge_clickItem = "challenge_clickItem"; public static final String challenge_clickMore = "challenge_clickMore"; public static final String challenge_clickWalkDiamond = "challenge_clickWalkDiamond"; public static final String challenge_viewCheckRank = "challenge_viewCheckRank"; public static final String challenge_viewDetails = "challenge_viewDetails"; public static final String challenge_viewWalkStatus = "challenge_viewWalkStatus"; public static final String discovery_clickItemPage = "discovery_clickItemPage"; public static final String discovery_clickMoreItem = "discovery_clickMoreItem"; public static final String discovery_homePage = "discovery_homePage"; public static final String mine_clickBadge = "mine_clickBadge"; public static final String mine_clickFollowers = "mine_clickFollowers"; public static final String mine_clickFood = "mine_clickFood"; public static final String mine_clickFriends = "mine_clickFriends"; public static final String mine_clickSetting = "mine_clickSetting"; public static final String mine_clickStatus = "mine_clickStatus"; public static final String mine_clickWeekReport = "mine_clickWeekReport"; public static final String mine_homePage = "mine_homePage"; public static final String ohter_clickSearchUser = "ohter_clickSearchUser"; public static final String other_clickRemind = "other_clickRemind"; public static final String other_clickSearch = "other_clickSearch"; public static final String other_clickSearchContent = "other_clickSearchContent"; public static final String other_clickSearchTopic = "other_clickSearchTopic"; public static final String other_receiveRemind = "other_receiveRemind"; public static final String shop_clickBigBanner = "shop_clickBigBanner"; public static final String shop_clickCart = "shop_clickCart"; public static final String shop_clickCategory = "shop_clickCategory"; public static final String shop_clickListBanner = "shop_clickListBanner"; public static final String shop_clickOrder = "shop_clickOrder"; public static final String status_betHome = "status_betHome"; public static final String status_clickBetEvent = "status_clickBetEvent"; public static final String status_clickBlock = "status_clickBlock"; public static final String status_clickCategoryBanner = "status_clickCategoryBanner"; public static final String status_clickCategoryItem = "status_clickCategoryItem"; public static final String status_clickCategoryMore = "status_clickCategoryMore"; public static final String status_clickCheckin = "status_clickCheckin"; public static final String status_clickKnowledges = "status_clickKnowledges"; public static final String status_clickMoreContent = "status_clickMoreContent"; public static final String status_clickMoreTopic = "status_clickMoreTopic"; public static final String status_clickSuccessStory = "status_clickSuccessStory"; public static final String status_clickTopContent = "status_clickTopContent"; public static final String status_clickTopShop = "status_clickTopShop"; public static final String status_clickTopStory = "status_clickTopStory"; public static final String status_click_more_topic = "status_clickMoreTopic"; public static final String status_click_small_ad = "status_clickSmallPic"; public static final String status_client_story = "status_clientStory"; public static final String status_favoritePage = "status_favoritePage"; public static final String status_friendTimeline = "status_friendTimeline"; public static final String status_hotTimeline = "status_hotTimeline"; public static final String status_imPage = "status_imPage"; public static final String status_todayContent = "status_todayContent"; public static final String status_top_pic = "status_clickTopPic"; public static final String status_viewCheckinPage = "status_viewCheckinPage"; public static final String stauts_click_topic = "status_clickTopic"; public static final String ststus_viewRedeemPage = "ststus_viewRedeemPage"; public static final String tinker_combine_failed = "tinker_combine_failed"; public static final String tinker_combine_success = "tinker_success"; public static final String tinker_crash_protect = "tinker_crash_protect"; public static final String tinker_downloaded = "tinker_downloaded"; public static final String tinker_error_no_space = "tinker_error_no_space"; public static final String tinker_error_patch_noexits = "tinker_error_patch_noexits"; public static final String tinker_load_exception = "tinker_load_exception"; public static final String tinker_onPatchReceived = "tinker_onPatchReceived"; public static final String tool_addDietRecordOK = "tool_addDietRecordOK"; public static final String tool_addOtherRecordOK = "tool_addOtherRecordOK"; public static final String tool_addSportRecordOK = "tool_addSportRecordOK"; public static final String tool_addWeightRecordOK = "tool_addWeightRecordOK"; public static final String tool_circumference_arm = "tool_circumference_arm"; public static final String tool_circumference_ass = "tool_circumference_ass"; public static final String tool_circumference_chest = "tool_circumference_chest"; public static final String tool_circumference_leg = "tool_circumference_leg"; public static final String tool_circumference_shank = "tool_circumference_shank"; public static final String tool_circumference_waist = "tool_circumference_waist"; public static final String tool_clickCalorie = "tool_clickCalorie"; public static final String tool_clickHomeTab = "tool_clickHomeTab"; public static final String tool_clickMC = "tool_clickMC"; public static final String tool_clickWaist = "tool_clickWaist"; public static final String tool_clickWeight = "tool_clickWeight"; public static final String tool_foodandsport_barchart = "tool_foodandsport_barchart"; public static final String tool_foodandsport_breakfast = "tool_foodandsport_breakfast"; public static final String tool_foodandsport_calendar = "tool_foodandsport_calendar"; public static final String tool_foodandsport_copydiet = "tool_foodandsport_copydiet"; public static final String tool_foodandsport_dinner = "tool_foodandsport_dinner"; public static final String tool_foodandsport_extrabreakfastmeal = "tool_foodandsport_extrabreakfastmeal"; public static final String tool_foodandsport_extradinnermeal = "tool_foodandsport_extradinnermeal"; public static final String tool_foodandsport_extralunchmeal = "tool_foodandsport_extralunchmeal"; public static final String tool_foodandsport_favoritefood = "tool_foodandsport_favoritefood"; public static final String tool_foodandsport_fooddetail = "tool_foodandsport_fooddetail"; public static final String tool_foodandsport_lunch = "tool_foodandsport_lunch"; public static final String tool_homePage = "tool_homePage"; public static final String tool_myfood_mycustom = "tool_myfood_mycustom"; public static final String tool_myfood_myfavorite = "tool_myfood_myfavorite"; public static final String tool_myfood_myupload = "tool_myfood_myupload"; public static final String tool_myfood_upload = "tool_myfood_upload"; public static final String tool_recordOK = "tool_recordOK"; public static final String tool_searchfood_assistadd = "tool_searchfood_assistadd"; public static final String tool_searchfood_canceladd = "tool_searchfood_canceladd"; public static final String tool_searchfood_customfood = "tool_searchfood_customfood"; public static final String tool_searchfood_scan = "tool_searchfood_scan"; public static final String tool_updateMcRecordOK = "tool_updateMcRecordOK"; public static final String tool_weight_addphoto = "tool_weight_addphoto"; public static final String tool_weight_curve = "tool_weight_curve"; public static final String tool_weight_curveweek = "tool_weight_curveweek"; public static final String tool_weight_curveyear = "tool_weight_curveyear"; public static final String tool_weight_deletephoto = "tool_weight_deletephoto"; public static final String tool_weight_rotate = "tool_weight_rotate"; }
/* Copyright (c) <2009> <<NAME>> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely */ #ifndef __dAutomataState_h_ #define __dAutomataState_h_ #if (_MSC_VER >= 1400) # pragma warning (disable: 4201) // warning C4201: nonstandard extension used : nameless struct/union #endif class dAutomataState { public: enum TransitionType { EMPTY = 0, CHARACTER, CHARACTER_SET, NESTED_CHARACTER_INC, NESTED_CHARACTER_DEC, NESTED_CHARACTER_INIT, }; class dCharacter { public: dCharacter (); dCharacter (int symbol); dCharacter (int info, TransitionType type); union { int m_symbol; struct { int m_info : 16; int m_type : 16; }; }; }; class dTransition { public: dTransition (dCharacter character, dAutomataState* const targeState); dCharacter GetCharater () const; dAutomataState* GetState() const; private: dCharacter m_character; dAutomataState* m_targetdAutomataState; }; dAutomataState (int id); ~dAutomataState (); void dAutomataState::GetStateArray (dList<dAutomataState*>& statesList); int m_id; int m_mark; bool m_exitState; dList<dTransition> m_transtions; dList<dAutomataState*> m_myNFANullStates; }; #endif
Study on Constitutive Model of 20CrMnTi Gear Steel in Cutting Process Flow stress data is important base data in using the analytical method and the finite element method to analyze the metal cutting process.In the present study, a comprehensive method combining with four methods of material mechanics tests, SHTB impact tests, two-dimensional orthogonal slot milling experiments and reverse solving is used to determine constitutive model (flow stress model) as a function of the "three-high" (high strain , temperature and strain rate) in metal cutting. The constitutive model of 20CrMnTi gear steel (hardened to170±5HB) which is one of China’s main gear steels in cutting deformation is established by using this method, and experimental results show that the model’s accuracy is high. Practice has proved that the methodology of constitutive model determination for metal cutting deformation, proposed in the present study, has advantages when compared with using one method alone, and is more suitable to establish flow data for the various materials in the metal cutting process.
MILITANTS have attacked two Syrian security offices in the western city of Homs with guns and suicide bombers, killing at least 42 people including a senior officer. The attackers killed the head of military security and 29 others at one of its headquarters in the city and 12 more people at a branch of state security in attacks that began early Saturday morning, the Syrian Observatory for Human Rights said. Syrian state television reported that clashes had rocked the districts of al- Ghouta and al-Mohata, where the two targets were located, before three suicide bombers detonated their explosives at each place. It said the attacks had killed 32 people including General Hassan Daaboul, the head of the military security branch. The jihadist rebel alliance Tahrir al-Sham said in a social networking post that five suicide bombers had carried out the attack but it stopped short of explicitly claiming responsibility. “Five suicide bombers attacked two branches of state security and military security in Homs ... thanks be to God,” the group said in a statement on the Telegram social network. Tahrir al-Sham was formed earlier this year from several groups including Jabhat Fateh al-Sham, which was formerly known as the Nusra Front and was al Qaeda’s Syrian branch until it broke formal allegiance to the global jihadist movement in 2016. Since it was formed, Tahrir al-Sham has fought other rebel groups, including some that fight under the banner of the Free Syrian Army, as well as a faction linked to Islamic State, in northwest Syria. It was critical of FSA groups for taking part in peace talks. Islamic State, which on Friday carried out a suicide bombing near the town of al-Bab in northwest Syria, has also carried out attacks in Homs before. Homs is under the control of the government of President Bashar al-Assad except for one district which is held by more moderate rebels.
<gh_stars>1-10 package daemon // // note: contains code snippets from github.com/docker import ( "io" "strconv" "os" "os/user" "strings" "bufio" "errors" "io/ioutil" "path/filepath" ) const ( UnixPasswdPath = "/etc/passwd" UnixGroupPath = "/etc/group" ) func Mkdir(path string, mode os.FileMode, group string) (error) { if fi, err := os.Lstat(path); err == nil { if fi.IsDir() { // ok, make sure rights are correct ChangeGroup(path, group) return nil } else { return errors.New(path + " exists and does not appear to be a directory.") } } else { // assume file does not exist if err2 := os.MkdirAll(path, mode); err2 == nil { ChangeGroup(path, group) return nil } else { return err2 } } } func RootCheck() (error) { if u, err := user.Current() ; err != nil { return err } else { if u.Uid != "0" { return errors.New(os.Args[0] + " must be run as root.") } else { return nil } } } func WriteSpecFile(filename, jsonContent string) (error) { path := filepath.Dir(filename) if _, err1 := os.Lstat(path); err1 != nil { if err2 := os.MkdirAll(path, 0750); err2 != nil { return err2 } os.Chmod(path, 0750) ChangeGroup(path, "docker") } err := ioutil.WriteFile(filename, []byte(jsonContent), 0640) ChangeGroup(path, "docker") return err } func ChangeGroup(path string, name string) error { gid, err := lookupGidByName(name) if err != nil { return err } else { return os.Chown(path, 0, gid) } } func lookupGidByName(name string) (int, error) { groupFile := UnixGroupPath groups, err := ParseGroupFile(groupFile, name) if err != nil { return -1, err } if groups != nil && len(groups) > 0 { return groups[0].Gid, nil } else { return -1, errors.New("Group " + name + " not found") } } func GetPasswd() (io.ReadCloser, error) { return os.Open(unixPasswdPath) } func GetGroupPath() (string, error) { return unixGroupPath, nil } func ParseGroupFile(path, name string) ([]Group, error) { if group, err := os.Open(path); err != nil { return nil, err } else { defer group.Close() return ParseGroupFilter(group, name) } } func ParseGroupFilter(r io.Reader, name string) ([]Group, error) { if r == nil { return nil, errors.New("nil source for group-formatted data") } var ( s = bufio.NewScanner(r) out = []Group{} ) for s.Scan() { if err := s.Err(); err != nil { return nil, err } text := s.Text() if text == "" { continue } // see: man 5 group // group_name:password:GID:user_list // Name:Pass:Gid:List // root:x:0:root // adm:x:4:root,adm,daemon p := Group{} parseLine( text, &p.Name, &p.Pass, &p.Gid, &p.List, ) if p.Name == name { out = append(out, p) } } return out, nil } type Group struct { Name string Pass string Gid int List []string } func parseLine(line string, v ...interface{}) { if line == "" { return } parts := strings.Split(line, ":") for i, p := range parts { if len(v) <= i { // if we have more "parts" than we have places to put them, bail for great "tolerance" of naughty configuration files break } switch e := v[i].(type) { case *string: // "root", "adm", "/bin/bash" *e = p case *int: // "0", "4", "1000" // ignore string to int conversion errors, for great "tolerance" of naughty configuration files *e, _ = strconv.Atoi(p) case *[]string: // "", "root", "root,adm,daemon" if p != "" { *e = strings.Split(p, ",") } else { *e = []string{} } default: // panic, because this is a programming/logic error, not a runtime one panic("parseLine expects only pointers! argument " + strconv.Itoa(i) + " is not a pointer!") } } }
def find_start_comp_nodes(network): start_comp_nodes = [] for node in network.nodes(): if network.node[node]['type'] == 'c' and network.node[node]['start']: start_comp_nodes.append(node) return set(start_comp_nodes)
package seedu.moolah.model.alias; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_ADD_WITH_ARGUMENTS; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_A_TO_B; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_B_TO_C; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_C_TO_A; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_NAME_ADD; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_NAME_ALIAS; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_NAME_CLEAR; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_NAME_DELETE; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_NAME_EDIT; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_NAME_EXIT; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_NAME_FIND; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_NAME_HELP; import static seedu.moolah.testutil.AliasTestUtil.ALIAS_NAME_LIST; import org.junit.jupiter.api.Test; import seedu.moolah.commons.exceptions.RecursiveAliasException; class AliasMappingsTest { @Test void aliasExists() { AliasMappings aliasMappings = new AliasMappings(); aliasMappings.addAlias(ALIAS_A_TO_B); aliasMappings.aliasWithNameExists(ALIAS_A_TO_B.getAliasName()); } @Test void aliasUsesReservedName_aliasUsesReservedName_returnsTrue() { AliasMappings aliasMappings = new AliasMappings(); assertTrue(aliasMappings.aliasUsesReservedName(ALIAS_NAME_ADD)); assertTrue(aliasMappings.aliasUsesReservedName(ALIAS_NAME_ALIAS)); assertTrue(aliasMappings.aliasUsesReservedName(ALIAS_NAME_CLEAR)); assertTrue(aliasMappings.aliasUsesReservedName(ALIAS_NAME_DELETE)); assertTrue(aliasMappings.aliasUsesReservedName(ALIAS_NAME_EDIT)); assertTrue(aliasMappings.aliasUsesReservedName(ALIAS_NAME_EXIT)); assertTrue(aliasMappings.aliasUsesReservedName(ALIAS_NAME_FIND)); assertTrue(aliasMappings.aliasUsesReservedName(ALIAS_NAME_HELP)); assertTrue(aliasMappings.aliasUsesReservedName(ALIAS_NAME_LIST)); } @Test void aliasUsesReservedName_aliasDoesNotUseReservedName_returnsFalse() { AliasMappings aliasMappings = new AliasMappings(); assertFalse(aliasMappings.aliasUsesReservedName(new Alias("somethingelse", "ignored"))); assertFalse(aliasMappings.aliasUsesReservedName(new Alias("anotherNotCommand", "ignored"))); } @Test void aliasCommandWordIsAlias_aliasCommandWordIsNotAliasNameOfExistingAlias_returnsFalse() { // returns true after alias with that name is added, false before AliasMappings aliasMappings = new AliasMappings(); assertFalse(aliasMappings.aliasCommandWordIsAlias(ALIAS_A_TO_B)); assertFalse(aliasMappings.aliasCommandWordIsAlias(ALIAS_B_TO_C)); assertFalse(aliasMappings.aliasCommandWordIsAlias(ALIAS_C_TO_A)); } @Test void aliasCommandWordIsAlias_aliasCommandWordIsAliasNameOfExistingAlias_returnsTrue() { // returns true after alias with that name is added, false before AliasMappings aliasMappings = new AliasMappings(); aliasMappings = aliasMappings.addAlias(ALIAS_A_TO_B); assertTrue(aliasMappings.aliasCommandWordIsAlias(ALIAS_C_TO_A)); AliasMappings aliasMappings1 = new AliasMappings(); aliasMappings1 = aliasMappings1.addAlias(ALIAS_B_TO_C); assertTrue(aliasMappings1.aliasCommandWordIsAlias(ALIAS_A_TO_B)); } @Test void addAlias_aliasChainsToItself_throwRecursiveAliasException() { // with other aliases in between assertThrows(RecursiveAliasException.class, () -> { new AliasMappings().addAlias(ALIAS_A_TO_B).addAlias(ALIAS_B_TO_C).addAlias(ALIAS_C_TO_A).validate(); }); } @Test void testEquals() { AliasMappings empty = new AliasMappings(); AliasMappings empty2 = new AliasMappings(); AliasMappings oneAlias = empty.addAlias(ALIAS_A_TO_B); AliasMappings oneAlias2 = empty2.addAlias(ALIAS_A_TO_B); AliasMappings oneAlias3 = empty.addAlias(new Alias("a", "b")); AliasMappings oneAlias4 = new AliasMappings().addAlias(ALIAS_ADD_WITH_ARGUMENTS); // different empty -> true assertEquals(empty, empty2); // different empty add same -> true assertEquals(oneAlias, oneAlias2); // same empty add similar -> true assertEquals(oneAlias, oneAlias3); // different alias inside -> false assertNotEquals(empty, oneAlias); assertNotEquals(oneAlias, oneAlias4); } }
def upgradedb(options): version = options.get('version') if version in ['1.1', '1.2']: sh("python -W ignore manage.py migrate maps 0001 --fake") sh("python -W ignore manage.py migrate avatar 0001 --fake") elif version is None: print("Please specify your GeoNode version") else: print("Upgrades from version {} are not yet supported.".format(version))
Ethnic Differences in Allele Distribution for the IL8 and IL1B Genes in Populations from Eastern India Populations from eastern India have been examined for the allele distribution at polymorphic sites in the IL8 and IL1B genes. Significant differences in allele frequencies between caste and tribal population groups were observed. However, there are no differences in allele frequencies among various subpopulations within caste or tribal groups. We argue that different caste populations from the same geographic location can be pooled for the purpose of population association studies.
We are weeks away from the much-anticipated release of the 5th climate report from the Intergovernmental Panel on Climate Change (IPCC). This organization has worked very hard to summarize the latest science on climate change, with thousands of donated hours from scientists around the globe. Although there are many other climate reports that synthesize the science, the IPCC is the largest and most comprehensive. I know many of the scientists who have taken on leadership author roles, without pay, to produce this document. We owe them our gratitude and congratulations. So, what will the report say? I will admit that I have not read the report (it hasn't been released). Early drafts have been leaked, primarily by people trying to disrupt the process. These early drafts allow us to predict what will be contained within the report. An alternative approach is to review the immense body of literature from which the report is drawn. Based on the literature I've reviewed, I will predict the central themes of the IPCC report. First, readers will likely find that this report is very similar to the last report (which was released in 2007). There will be slight changes to our confidence in certain observations. Climate models will have improved slightly, particularly in how they handle atmospheric particulates and cloud formation. A major effort since the last report has been the use of climate models to predict changes at the regional level. The report will likely say that this endeavor has had mixed success. The new report will describe how climate changes are continuing without abatement. In particular, temperatures are rising, oceans are heating, waters are rising, ice is melting, the oceans are acidifying, heat is even moving to the deepest parts of the oceans. Just as importantly, the report will show that these changes are largely human-caused. Some items are worse than we thought. In the last report, ice loss, particularly from Greenland, was a minor issue. Now, it is clear that not only Greenland, but also Antarctica are melting and this melt is raising sea levels. Furthermore, Arctic sea ice is being lost faster than previously reported. The new report will likely have continued questions. For instance, how will hurricanes change in a warming world (the most powerful hurricanes are becoming even more powerful, but the change in frequency is not known) is still an open question. Extreme weather will be a mixed bag. Some extreme weather has certainly increased (heat waves for instance, drought in certain areas, and heavy precipitation events). Changes to tornadoes and thunderstorms? That is one area that is highly uncertain. So, in short, since 2007 we have developed better tools, and we are more certain about how we are changing the climate. Other areas still vex us. But, it is clear we certainly know enough to take action to stop the coming changes to our climate. How does this square with my title? One continuing question is, how much and how fast will the climate change. Are we going to be in a "slow simmer" or a "fast boil"? The answer to this question rests on how sensitive the climate is. If the climate is not very sensitive, it means the Earth's temperature will change more slowly. A more sensitive Earth will have a more rapid temperature change. There is some belief that the IPCC will lower the range of climate sensitivity by a tiny amount. If my crystal ball is correct, the denialosphere will latch onto this, and will, unwittingly, be agreeing that the IPCC is correct; we are changing the climate. You cannot both accept the IPCC conclusions that humans are changing the climate and simultaneously claim that climate change is either not occurring or is natural. In the end, the contrarians will be in the "slow simmer" camp. So listen carefully to the Christopher Moncktons, James Inhofes, and Rush Limbaughs of this world. Wait for them to bring up the IPCC sensitivity and realize just how much they have conceded. But back to the IPCC; in a certain sense, the IPCC has done its job. For this fifth report, they have synthesized the science and provided enough evidence that action is warranted. How many more reports of this type do we need? Will a sixth report that confirms what we already know make much of a difference? Will a seventh? Do these reports need to be written every 5-6 years? Perhaps one a decade would be sufficient? These reports require enormous amounts of time and energy. Scientists who take authorship roles put their own research on hold, sometimes for years. Whatever the future holds for the IPCC, the history books will tell us we were warned. Time and time again, the world's best scientists have sent us clear messages. Whatever happens, whatever pathway we choose, whatever are the future climate disruptions, we owe these scientists, and the IPCC our deepest gratitude. Thanks.
/// Visits the references to the supplied entity in this file and returns whether visitation was /// ended by the callback returning `false`. pub fn visit_references<F: FnMut(Entity<'tu>, SourceRange<'tu>) -> bool>( &self, entity: Entity<'tu>, f: F ) -> bool { visit(self.tu, f, |v| unsafe { clang_findReferencesInFile(entity.raw, self.ptr, v) }) }
/* Copyright 2011, D. E. Shaw Research. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. * 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. * Neither the name of D. E. Shaw Research 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 _random123_ufixed01_dot_h_ #define _random123_ufixed01_dot_h_ #include "features/compilerfeatures.h" /** @defgroup u01fixedpt_closed_open_W_M The u01fixedpt conversion functions These functions convert unsigned W-bit integers to uniformly spaced real values (float or double) between 0.0 and 1.0 with mantissas of M bits. PLEASE THINK CAREFULLY BEFORE USING THESE FUNCTIONS. THEY MAY NOT BE WHAT YOU WANT. YOU MAY BE MUCH BETTER SERVED BY THE FUNCTIONS IN ./uniform.hpp. These functions produce a finite number *uniformly spaced* values in the range from 0.0 to 1.0 with uniform probability. The price of uniform spacing is that they may not utilize the entire space of possible outputs. E.g., u01fixedpt_closed_open_32_24 will never produce a non-zero value less than 2^-24, even though such values are representable in single-precision floating point. There are 12 functions, corresponding to the following choices: - W = 32 or 64 - M = 24 or 53 (float or double) - open0 or closed0 : whether the output is open or closed at 0.0 - open1 or closed1 : whether the output is open or closed at 1.0 The W=64 M=24 cases are not implemented. To obtain an M=24 float from a uint64_t, use a cast (possibly with right-shift and bitwise and) to convert some of the bits of the uint64_t to a uint32_t and then use u01fixedpt_x_y_32_24. Note that the 64-bit random integers produced by the Random123 library are random in "all the bits", so with a little extra effort you can obtain two floats this way -- one from the high bits and one from the low bits of the 64-bit value. If the output is open at one end, then the extreme value (0.0 or 1.0) will never be returned. Conversely, if the output is closed at one end, then the extreme value is a possible return value. The values returned are as follows. All values are returned with equal frequency, except as noted in the closed_closed case: closed_open: Let P=min(M,W) there are 2^P possible output values: {0, 1, 2, ..., 2^P-1}/2^P open_closed: Let P=min(M,W) there are 2^P possible values: {1, 2, ..., 2^P}/2^P open_open: Let P=min(M, W+1) there are 2^(P-1) possible values: {1, 3, 5, ..., 2^P-1}/2^P closed_closed: Let P=min(M, W-1) there are 1+2^P possible values: {0, 1, 2, ... 2^P}/2^P The extreme values (0.0 and 1.0) are returned with half the frequency of all others. On x86 hardware, especially on 32bit machines, the use of internal 80bit x87-style floating point may result in 'bonus' precision, which may cause closed intervals to not be really closed, i.e. the conversions below might not convert UINT{32,64}_MAX to 1.0. This sort of issue is likely to occur when storing the output of a u01fixedpt_*_32_24 function in a double, though one can imagine getting extra precision artifacts when going from 64_53 as well. Other artifacts may exist on some GPU hardware. The tests in kat_u01_main.h try to expose such issues, but caveat emptor. @{ @cond HIDDEN_FROM_DOXYGEN */ /* Hex floats were standardized by C in 1999, but weren't standardized by C++ until 2011. So, we're obliged to write out our constants in decimal, even though they're most naturally expressed in binary. We cross our fingers and hope that the compiler does the compile-time constant arithmetic properly. */ #define R123_0x1p_31f (1.f/(1024.f*1024.f*1024.f*2.f)) #define R123_0x1p_24f (128.f*R123_0x1p_31f) #define R123_0x1p_23f (256.f*R123_0x1p_31f) #define R123_0x1p_32 (1./(1024.*1024.*1024.*4.)) #define R123_0x1p_63 (2.*R123_0x1p_32*R123_0x1p_32) #define R123_0x1p_53 (1024.*R123_0x1p_63) #define R123_0x1p_52 (2048.*R123_0x1p_63) /** @endcond */ #ifndef R123_USE_U01_DOUBLE #define R123_USE_U01_DOUBLE #endif #ifdef __cplusplus extern "C"{ #endif /* narrowing conversions: uint32_t to float */ R123_CUDA_DEVICE R123_STATIC_INLINE float u01fixedpt_closed_closed_32_24(uint32_t i){ /* N.B. we ignore the high bit, so output is not monotonic */ return ((i&0x7fffffc0) + (i&0x40))*R123_0x1p_31f; /* 0x1.p-31f */ } R123_CUDA_DEVICE R123_STATIC_INLINE float u01fixedpt_closed_open_32_24(uint32_t i){ return (i>>8)*R123_0x1p_24f; /* 0x1.0p-24f; */ } R123_CUDA_DEVICE R123_STATIC_INLINE float u01fixedpt_open_closed_32_24(uint32_t i){ return (1+(i>>8))*R123_0x1p_24f; /* *0x1.0p-24f; */ } R123_CUDA_DEVICE R123_STATIC_INLINE float u01fixedpt_open_open_32_24(uint32_t i){ return (0.5f+(i>>9))*R123_0x1p_23f; /* 0x1.p-23f; */ } #if R123_USE_U01_DOUBLE /* narrowing conversions: uint64_t to double */ R123_CUDA_DEVICE R123_STATIC_INLINE double u01fixedpt_closed_closed_64_53(uint64_t i){ /* N.B. we ignore the high bit, so output is not monotonic */ return ((i&R123_64BIT(0x7ffffffffffffe00)) + (i&0x200))*R123_0x1p_63; /* 0x1.p-63; */ } R123_CUDA_DEVICE R123_STATIC_INLINE double u01fixedpt_closed_open_64_53(uint64_t i){ return (i>>11)*R123_0x1p_53; /* 0x1.0p-53; */ } R123_CUDA_DEVICE R123_STATIC_INLINE double u01fixedpt_open_closed_64_53(uint64_t i){ return (1+(i>>11))*R123_0x1p_53; /* 0x1.0p-53; */ } R123_CUDA_DEVICE R123_STATIC_INLINE double u01fixedpt_open_open_64_53(uint64_t i){ return (0.5+(i>>12))*R123_0x1p_52; /* 0x1.0p-52; */ } /* widening conversions: u32 to double */ R123_CUDA_DEVICE R123_STATIC_INLINE double u01fixedpt_closed_closed_32_53(uint32_t i){ /* j = i+(i&1) takes on 2^31+1 possible values with a 'trapezoid' distribution: p_j = 1 0 2 0 2 .... 2 0 2 0 1 j = 0 1 2 3 4 .... 2^32 by converting to double *before* doing the add, we don't wrap the high bit. */ return (((double)(i&1)) + i)*R123_0x1p_32; /* 0x1.p-32; */ } R123_CUDA_DEVICE R123_STATIC_INLINE double u01fixedpt_closed_open_32_53(uint32_t i){ return i*R123_0x1p_32; /* 0x1.p-32; */ } R123_CUDA_DEVICE R123_STATIC_INLINE double u01fixedpt_open_closed_32_53(uint32_t i){ return (1.+i)*R123_0x1p_32; /* 0x1.p-32; */ } R123_CUDA_DEVICE R123_STATIC_INLINE double u01fixedpt_open_open_32_53(uint32_t i){ return (0.5+i)*R123_0x1p_32; /* 0x1.p-32; */ } #endif /* R123_USE_U01_DOUBLE */ #ifdef __cplusplus } #endif /** @} */ #endif
/** * Adds a separator node to this clique tree. Currently, only a discrete * variable is possible for a separator node, since continuous variable must * occur that the leaf nodes. * * @param node * node from the original model that corresponds to the new * separator node * @return the separator node created and added to this clique tree */ private Separator addSeparator(BeliefNode node) { DiscreteVariable variable = (DiscreteVariable) node.getVariable(); Separator separator = new Separator(this, variable); addNode(separator); separators.put(variable, separator); return separator; }
<reponame>catdawg/assetchef<filename>assetchef/pluginapi/src/index.ts export { API_LEVEL, // plugin helpers OneFilePluginBase, OneFilePluginBaseInstance, // path IPathChangeEvent, IPathTreeRead, IPathTreeWrite, IPathTreeAsyncRead, IPathTreeAsyncWrite, ICancelListen, IAsyncTreeChangeListener, PathChangeQueue, PathEventType, PathInterfaceCombination, PathInterfaceProxy, PathUtils, PathRelationship, PathTree, OnQueueReset, IStageHandler, AsyncToSyncConverter, FSPathTree, // comm addPrefixToLogger, ILogger, LoggerLevel, // recipe plugin IRecipePlugin, IRecipePluginInstance, IRecipePluginInstanceSetupParams, // watch ICancelWatch, IFSWatch, IFSWatchListener, WatchmanFSWatch, // other ISchemaDefinition, // tests plugintests, timeout, winstonlogger, getCallTrackingLogger, TmpFolder, IPluginChange, IPluginSimpleTestCase, IPluginTestCase, IPluginTestCases, ILoggerTracer, MockFSWatch, RandomPathTreeChanger} from "@assetchef/core";
// Copyright (c) 2017-2021, University of Tennessee. All rights reserved. // SPDX-License-Identifier: BSD-3-Clause // This program is free software: you can redistribute it and/or modify it under // the terms of the BSD 3-Clause license. See the accompanying LICENSE file. #ifndef BLAS_FLOPS_HH #define BLAS_FLOPS_HH #include "blas.hh" namespace blas { // ============================================================================= // Level 1 BLAS // ----------------------------------------------------------------------------- inline double fmuls_asum( double n ) { return 0; } inline double fadds_asum( double n ) { return n-1; } // ----------------------------------------------------------------------------- inline double fmuls_axpy( double n ) { return n; } inline double fadds_axpy( double n ) { return n; } // ----------------------------------------------------------------------------- inline double fmuls_iamax( double n ) { return 0; } // n-1 compares, which are essentially adds (x > y is x - y > 0) inline double fadds_iamax( double n ) { return n-1; } // ----------------------------------------------------------------------------- inline double fmuls_nrm2( double n ) { return n; } inline double fadds_nrm2( double n ) { return n-1; } // ----------------------------------------------------------------------------- inline double fmuls_dot( double n ) { return n; } inline double fadds_dot( double n ) { return n-1; } // ----------------------------------------------------------------------------- inline double fmuls_scal( double n ) { return n; } inline double fadds_scal( double n ) { return 0; } // ============================================================================= // Level 2 BLAS // most formulas assume alpha=1, beta=0 or 1; otherwise add lower-order terms. // i.e., this is minimum flops and bandwidth that could be consumed. // ----------------------------------------------------------------------------- inline double fmuls_gemv( double m, double n ) { return m*n; } inline double fadds_gemv( double m, double n ) { return m*n; } // ----------------------------------------------------------------------------- inline double fmuls_trmv( double n ) { return 0.5*n*(n + 1); } inline double fadds_trmv( double n ) { return 0.5*n*(n - 1); } // ----------------------------------------------------------------------------- inline double fmuls_ger( double m, double n ) { return m*n; } inline double fadds_ger( double m, double n ) { return m*n; } // ----------------------------------------------------------------------------- inline double fmuls_gemm( double m, double n, double k ) { return m*n*k; } inline double fadds_gemm( double m, double n, double k ) { return m*n*k; } // ----------------------------------------------------------------------------- inline double fmuls_gbmm( double m, double n, double kl, double ku ) { return (m*kl + m*ku - kl*kl/2. - ku*ku/2. + m - kl/2. - ku/2.)*n; } inline double fadds_gbmm( double m, double n, double kl, double ku ) { return (m*kl + m*ku - kl*kl/2. - ku*ku/2. + m - kl/2. - ku/2.)*n; } // ----------------------------------------------------------------------------- inline double fmuls_hemm( blas::Side side, double m, double n ) { return (side == blas::Side::Left ? m*m*n : m*n*n); } inline double fadds_hemm( blas::Side side, double m, double n ) { return (side == blas::Side::Left ? m*m*n : m*n*n); } // ----------------------------------------------------------------------------- inline double fmuls_herk( double n, double k ) { return 0.5*k*n*(n+1); } inline double fadds_herk( double n, double k ) { return 0.5*k*n*(n+1); } // ----------------------------------------------------------------------------- inline double fmuls_her2k( double n, double k ) { return k*n*n; } inline double fadds_her2k( double n, double k ) { return k*n*n; } // ----------------------------------------------------------------------------- inline double fmuls_trmm( blas::Side side, double m, double n ) { if (side == blas::Side::Left) return 0.5*n*m*(m + 1); else return 0.5*m*n*(n + 1); } inline double fadds_trmm( blas::Side side, double m, double n ) { if (side == blas::Side::Left) return 0.5*n*m*(m - 1); else return 0.5*m*n*(n - 1); } //============================================================================== // template class. Example: // gflop< float >::gemm( m, n, k ) yields flops for sgemm. // gflop< std::complex<float> >::gemm( m, n, k ) yields flops for cgemm. //============================================================================== template< typename T > class Gbyte { public: // ---------------------------------------- // Level 1 BLAS // read x static double asum( double n ) { return 1e-9 * (n * sizeof(T)); } // read x, y; write y static double axpy( double n ) { return 1e-9 * (3*n * sizeof(T)); } // read x; write y static double copy( double n ) { return 1e-9 * (2*n * sizeof(T)); } // read x static double iamax( double n ) { return 1e-9 * (n * sizeof(T)); } // read x static double nrm2( double n ) { return 1e-9 * (n * sizeof(T)); } // read x, y static double dot( double n ) { return 1e-9 * (2*n * sizeof(T)); } // read x; write x static double scal( double n ) { return 1e-9 * (2*n * sizeof(T)); } // read x, y; write x, y static double swap( double n ) { return 1e-9 * (4*n * sizeof(T)); } // ---------------------------------------- // Level 2 BLAS // read A, x; write y static double gemv( double m, double n ) { return 1e-9 * ((m*n + m + n) * sizeof(T)); } // read A triangle, x; write y static double hemv( double n ) { return 1e-9 * ((0.5*(n+1)*n + 2*n) * sizeof(T)); } static double symv( double n ) { return hemv( n ); } // read A triangle, x; write x static double trmv( double n ) { return 1e-9 * ((0.5*(n+1)*n + 2*n) * sizeof(T)); } static double trsv( double n ) { return trmv( n ); } // read A, x, y; write A static double ger( double m, double n ) { return 1e-9 * ((2*m*n + m + n) * sizeof(T)); } // read A triangle, x; write A triangle static double her( double n ) { return 1e-9 * (((n+1)*n + n) * sizeof(T)); } static double syr( double n ) { return her( n ); } // read A triangle, x, y; write A triangle static double her2( double n ) { return 1e-9 * (((n+1)*n + n + n) * sizeof(T)); } static double syr2( double n ) { return her2( n ); } // ---------------------------------------- // Level 3 BLAS // read A, B, C; write C static double gemm( double m, double n, double k ) { return 1e-9 * ((m*k + k*n + 2*m*n) * sizeof(T)); } static double hemm( blas::Side side, double m, double n ) { // read A, B, C; write C double sizeA = (side == blas::Side::Left ? 0.5*m*(m+1) : 0.5*n*(n+1)); return 1e-9 * ((sizeA + 3*m*n) * sizeof(T)); } static double symm( blas::Side side, double m, double n ) { return hemm( side, m, n ); } static double herk( double n, double k ) { // read A, C; write C double sizeC = 0.5*n*(n+1); return 1e-9 * ((n*k + 2*sizeC) * sizeof(T)); } static double syrk( double n, double k ) { return herk( n, k ); } static double her2k( double n, double k ) { // read A, B, C; write C double sizeC = 0.5*n*(n+1); return 1e-9 * ((2*n*k + 2*sizeC) * sizeof(T)); } static double syr2k( double n, double k ) { return her2k( n, k ); } static double trmm( blas::Side side, double m, double n ) { // read A triangle, x; write x if (side == blas::Side::Left) return 1e-9 * ((0.5*(m+1)*m + 2*m*n) * sizeof(T)); else return 1e-9 * ((0.5*(n+1)*n + 2*m*n) * sizeof(T)); } static double trsm( blas::Side side, double m, double n ) { return trmm( side, m, n ); } }; //============================================================================== // Traits to lookup number of operations per multiply and add. template <typename T> class FlopTraits { public: static constexpr double mul_ops = 1; static constexpr double add_ops = 1; }; //------------------------------------------------------------------------------ // specialization for complex // flops = 6*muls + 2*adds template <typename T> class FlopTraits< std::complex<T> > { public: static constexpr double mul_ops = 6; static constexpr double add_ops = 2; }; //============================================================================== // template class. Example: // gflop< float >::gemm( m, n, k ) yields flops for sgemm. // gflop< std::complex<float> >::gemm( m, n, k ) yields flops for cgemm. //============================================================================== template< typename T > class Gflop { public: static constexpr double mul_ops = FlopTraits<T>::mul_ops; static constexpr double add_ops = FlopTraits<T>::add_ops; // ---------------------------------------- // Level 1 BLAS static double asum( double n ) { return 1e-9 * (mul_ops*fmuls_asum(n) + add_ops*fadds_asum(n)); } static double axpy( double n ) { return 1e-9 * (mul_ops*fmuls_axpy(n) + add_ops*fadds_axpy(n)); } static double copy( double n ) { return 0; } static double iamax( double n ) { return 1e-9 * (mul_ops*fmuls_iamax(n) + add_ops*fadds_iamax(n)); } static double nrm2( double n ) { return 1e-9 * (mul_ops*fmuls_nrm2(n) + add_ops*fadds_nrm2(n)); } static double dot( double n ) { return 1e-9 * (mul_ops*fmuls_dot(n) + add_ops*fadds_dot(n)); } static double scal( double n ) { return 1e-9 * (mul_ops*fmuls_scal(n) + add_ops*fadds_scal(n)); } static double swap( double n ) { return 0; } // ---------------------------------------- // Level 2 BLAS static double gemv(double m, double n) { return 1e-9 * (mul_ops*fmuls_gemv(m, n) + add_ops*fadds_gemv(m, n)); } static double symv(double n) { return gemv( n, n ); } static double hemv(double n) { return symv( n ); } static double trmv( double n ) { return 1e-9 * (mul_ops*fmuls_trmv(n) + add_ops*fadds_trmv(n)); } static double trsv( double n ) { return trmv( n ); } static double her( double n ) { return ger( n, n ); } static double syr( double n ) { return her( n ); } static double ger( double m, double n ) { return 1e-9 * (mul_ops*fmuls_ger(m, n) + add_ops*fadds_ger(m, n)); } static double her2( double n ) { return 2*ger( n, n ); } static double syr2( double n ) { return her2( n ); } // ---------------------------------------- // Level 3 BLAS static double gemm(double m, double n, double k) { return 1e-9 * (mul_ops*fmuls_gemm(m, n, k) + add_ops*fadds_gemm(m, n, k)); } static double gbmm(double m, double n, double k, double kl, double ku) { // gbmm works if and only if A is a square matrix: m == k. // todo: account for the non-suqare matrix A: m != k // assert(m == k); if (m != k) return nan("1234"); // use testsweeper's no_data_flag to print NA else return 1e-9 * (mul_ops*fmuls_gbmm(m, n, kl, ku) + add_ops*fadds_gbmm(m, n, kl, ku)); } static double hemm(blas::Side side, double m, double n) { return 1e-9 * (mul_ops*fmuls_hemm(side, m, n) + add_ops*fadds_hemm(side, m, n)); } static double hbmm(double m, double n, double kd) { return gbmm(m, n, m, kd, kd); } static double symm(blas::Side side, double m, double n) { return hemm( side, m, n ); } static double herk(double n, double k) { return 1e-9 * (mul_ops*fmuls_herk(n, k) + add_ops*fadds_herk(n, k)); } static double syrk(double n, double k) { return herk( n, k ); } static double her2k(double n, double k) { return 1e-9 * (mul_ops*fmuls_her2k(n, k) + add_ops*fadds_her2k(n, k)); } static double syr2k(double n, double k) { return her2k( n, k ); } static double trmm(blas::Side side, double m, double n) { return 1e-9 * (mul_ops*fmuls_trmm(side, m, n) + add_ops*fadds_trmm(side, m, n)); } static double trsm(blas::Side side, double m, double n) { return trmm( side, m, n ); } }; } // namespace blas #endif // #ifndef BLAS_FLOPS_HH
Charlie Sanders, a tight end for the Detroit Lions from 1968 to 1977 whose sticky fingers, fleet feet and shifty elusiveness helped redefine a position that had traditionally been reserved for stolid blockers, died on Thursday in Royal Oak, Mich., near Detroit. He was 68. The cause was cancer, the Lions said on their website. Big — he was 6 feet 4 inches and played at 225 pounds and above — fast, strong and sure-handed, he was a potent force in the conventional role of run blocker, but he was as much or more of a pass-catching threat, an unusual enough set of skills at the time that he was sometimes referred to as the Lions’ secret weapon. A prototype of the 21st-century tight end, a progenitor of the likes of Kellen Winslow and Tony Gonzalez, he led the Lions (or tied for the team lead) in receptions six times, and caught more passes, 336, than any other Lion in history until the record was surpassed in 1996 by Herman Moore, a player Sanders coached. He scored 31 touchdowns, and for his career, he averaged 14.3 yards per catch, a figure more typical of wide receivers than tight ends. He was selected for the Pro Bowl seven times, and for three consecutive seasons, 1969 through 1971, he was named a first-team All-Pro by The Associated Press.
/** * Date: 8/18/15 Time: 10:46 PM * * TODO - perhaps we should archive them in the future and/or move them to a compressed collection */ @Component class GameCleanup<ID extends Serializable, FEATURES, IMPL extends AbstractGame<ID, FEATURES>> { private static final Logger logger = LoggerFactory.getLogger(GameCleanup.class); private static final ZoneId GMT = ZoneId.of("GMT"); private static final int DAYS_BACK = 60; private final AbstractGameRepository<ID, FEATURES, IMPL> gameRepository; GameCleanup(final AbstractGameRepository<ID, FEATURES, IMPL> gameRepository) { this.gameRepository = gameRepository; } @SuppressWarnings("WeakerAccess") public void deleteOlderGames() { ZonedDateTime cutoff = ZonedDateTime.now(GMT).minusDays(DAYS_BACK); logger.info("Deleting games created before " + cutoff); logger.info("Deleted games count = {}", gameRepository.deleteByCreatedLessThan(cutoff.toInstant())); } }
import { join as pathJoin, dirname } from "path"; import * as fs from "fs"; import * as child_process from "child_process"; import * as textColors from "colors"; interface TestValue { type: "i32" | "i64"; value: string; } interface TestInstr { type: "invoke"; field: string; args: TestValue[] } interface TestFile { source_filename: string; commands: TestCmd[] } interface TestCmdModule { type: "module"; filename: string; } interface TestCmdAssertReturn { type: "assert_return" | "assert_return_canonical_nan" | "assert_return_arithmetic_nan"; action: TestInstr; expected: TestValue[]; } interface TestCmdAssertTrap { type: "assert_trap"; action: TestInstr; expected: TestValue[]; text: string; } interface TestCmdAssertExhaust { type: "assert_exhaustion"; action: TestInstr; expected: TestValue[]; } interface TestCmdAssertMalformed { type: "assert_malformed"; } interface TestCmdAssertInvalid { type: "assert_invalid"; } interface TestCmdAssertUninstantiable { type: "assert_uninstantiable" } interface TestCmdAction { type: "action"; action: TestInstr; } type TestCmd = (TestCmdModule | TestCmdAssertReturn | TestCmdAssertTrap | TestCmdAssertMalformed | TestCmdAssertInvalid | TestCmdAssertExhaust | TestCmdAction | TestCmdAssertUninstantiable) & {line: number}; function fixWSLPath(path) { path = path.replace(/(.):\\/g,(_,x)=>`/mnt/${x.toLowerCase()}/`); path = path.replace(/\\/g,"/"); return path; } let target = process.argv[2]; let testDirectory = pathJoin(__dirname,"../test/"); let testFileName = ""; let fileHeader = fs.readFileSync(__dirname + "/../resources/fileheader_test.lua").toString(); if (target.endsWith(".json")) { processTestFile(target); } else { // todo entire test directory } function processTestFile(filename: string) { let testFile: TestFile = JSON.parse(fs.readFileSync(filename).toString()); let commandQueue: TestCmd[] = []; console.log(`==========> ${testFile.source_filename}`); testFile.commands.forEach((cmd)=>{ switch (cmd.type) { case "module": compileAndRunTests(commandQueue); let wasm_file = pathJoin(dirname(filename),cmd.filename); compileModule(wasm_file); break; case "assert_malformed": // should not compile to binary case "assert_invalid": // compiled to binary but should be rejected by compiler / vm case "assert_uninstantiable": // start function should trap - I really don't care to test this. // Don't care. break; default: commandQueue.push(cmd); } }); compileAndRunTests(commandQueue); } function compileModule(file: string) { console.log("Compiling:",file); var file_index = file.match(/\.(\d+)\.wasm/)[1]; testFileName = `test${file_index}.lua`; let result = child_process.spawnSync(process.argv0,[ pathJoin(__dirname,"compile.js"), file, `${testDirectory}${testFileName}`, "correct-multiply" ]); if (result.status!=0) { console.log(result.stderr.toString()); throw new Error("compile failed"); } } function compileAndRunTests(commands: TestCmd[]) { if (commands.length>0) { console.log(`Running ${commands.length} tests...`); let compiled = commands.map(compileCommand).join("\n"); fs.writeFileSync(testDirectory+"test_run.lua",`local TEST_FILE = "${testFileName}"\n`+fileHeader+compiled); let result = child_process.spawnSync("bash",[ "-c", "luajit "+fixWSLPath(testDirectory+"test_run.lua") ]); console.log(textColors.red(result.stdout.toString())); if (result.status!=0) { console.log(result.stderr.toString()); throw new Error("execution failed"); } } commands.length = 0; } function compileCommand(cmd: TestCmd, test_num: number) { if ( cmd.type == "assert_return" || cmd.type == "assert_return_canonical_nan" || cmd.type == "assert_return_arithmetic_nan" || cmd.type == "assert_trap" || cmd.type == "assert_exhaustion" || cmd.type == "action" ) { let instr = cmd.action; if (instr.type != "invoke") { throw new Error("Unhandled instr type: "+instr.type); } if (cmd.type == "action") { return `invoke("${instr.field}",{${instr.args.map(compileValue).join(",")}})`; } else { let expected = cmd.type == "assert_trap" ? `"${cmd.text}"` : cmd.type == "assert_exhaustion" ? `"exhaustion"` : cmd.type == "assert_return_canonical_nan" || cmd.type == "assert_return_arithmetic_nan" ? "{(0/0)}" : `{${cmd.expected.map(compileValue).join(",")}}`; return `runTest(${cmd.line},"${instr.field}",{${instr.args.map(compileValue).join(",")}},${expected})`; } } else { console.log(cmd); throw new Error("Unhandled command: "+(<any>cmd).type); } } function compileValue(value: TestValue) { if (value.type=="i32") { return (+value.value)|0; } else if (value.type=="i64") { let num = BigInt(value.value); let low = Number(num & BigInt(0xFFFFFFFF))|0; let high = Number(num >> BigInt(32))|0; return `__LONG_INT__(${low},${high})`; } else if (value.type=="f32") { let convert_buffer = Buffer.alloc(4); convert_buffer.writeUInt32LE(+value.value,0); let float_val = convert_buffer.readFloatLE(0); return compileFloatValue(float_val); } else if (value.type=="f64") { let num = BigInt(value.value); let array = new BigInt64Array(1); array[0] = num; let float_val = new Float64Array(array.buffer)[0]; return compileFloatValue(float_val); } else { throw new Error("bad type "+value.type); } } function compileFloatValue(value: number) { if (value != value) { return "(0/0)" } if (value == 0 && 1/value == -Number.POSITIVE_INFINITY) { return "(-0)"; } if (value == Number.POSITIVE_INFINITY) { return "(1/0)" } if (value == Number.NEGATIVE_INFINITY) { return "(-1/0)" } return value.toString(); // eugh }
def p_dot(self): acceleration = self.fdmexec.GetAccelerations().GetPQRdot(1) return convert_jsbsim_angular_acceleration(acceleration)
<reponame>chradams/ESP32-Motors #if __has_include("config/LocalConfig.h") #include "config/LocalConfig.h" #else #include "config/DefaultConfig.h" #endif #include "CommandLayer.h" #include "ServoDriver.h" #include "StepperDriver.h" #include "BrushedMotorDriver.h" #include "OpBuffer.h" #define CORE_1 1 #define UPDATE_FREQ 60 #define UPDATE_DWELL 1000 / UPDATE_FREQ hw_timer_t *timerOpCode = NULL; CommandLayer *CommandLayer::instance = NULL; MotorDriver *CommandLayer::driver = NULL; CommandLayer::CommandLayer() { #if SERVO==1 driver = ServoDriver::getInstance(); #elif STEPPER==1 driver = StepperDriver::getInstance(); #elif BDC==1 driver = BrushedMotorDriver::getInstance(); #endif log_v("CommandLayer const\n"); } void CommandLayer::init() { CommandLayer::driver->isrStartIoDriver(); log_v("CommandLayer init\n"); } CommandLayer *CommandLayer::getInstance() { if (instance == NULL) { instance = new CommandLayer(); } return instance; } void CommandLayer::opcodeMove(signed int step_num, unsigned short step_rate, uint8_t motor_id) { CommandLayer::driver->motorMove(step_num, step_rate, motor_id); } void CommandLayer::opcodeGoto(signed int step_num, unsigned short step_rate, uint8_t motor_id) { CommandLayer::driver->motorGoTo(step_num, step_rate, motor_id); } void CommandLayer::opcodeStop(signed int wait_time, unsigned short precision, uint8_t motor_id) { CommandLayer::driver->motorStop(wait_time, precision, motor_id); } void CommandLayer::opcodeMotorSetting(MotorDriver::config_setting setting, uint32_t data1, uint32_t data2, uint8_t motor_id) { CommandLayer::driver->changeMotorSettings(setting, data1, data2, motor_id); } void CommandLayer::opcodeAbortCommand(uint8_t motor_id) { CommandLayer::driver->abortCommand(motor_id); } void CommandLayer::fetchMotorOpCode(uint8_t id) { //log_i("fetchMotorOpCode %d\n", id); parseSubmittOp(id, OpBuffer::getInstance()->getOp(id)); } void CommandLayer::FillDriverFromQueue() { /* delay(100); while (true) { for (int i = 0; (i < MAX_MOTORS); i++) { if (!driver->isMotorRunning(i)) { fetchMotorOpCode(i); } } delay(UPDATE_DWELL); } vTaskDelete(NULL); */ } void CommandLayer::parseSubmittOp(uint8_t id, Op *op) { if (op == NULL) return; //log_i("Code: %d", (int)(op->opcode)); switch (op->opcode) { case 'M': { opcodeMove(op->stepNum, op->stepRate, op->motorID); break; } case 'S': { opcodeStop(op->stepNum, op->stepRate, op->motorID); break; } case 'G': { opcodeGoto(op->stepNum, op->stepRate, op->motorID); break; } case 'U': { opcodeMotorSetting(MotorDriver::config_setting::MICROSTEPPING, op->stepRate, op->motorID, op->motorID); } default: //log_i("parseSubmittOp Unknown packet"); break; } } void CommandLayer::getNextOp(uint8_t driverId) { fetchMotorOpCode(driverId); } void CommandLayer::peekNextOp(uint8_t driverId) { Op *peekedOp = OpBuffer::getInstance()->peekOp(driverId); if (peekedOp == NULL) { return; } if (peekedOp->opcode == 'K') { opcodeAbortCommand(driverId); } }
/** Different type observers can be registered to the same observerId value */ @Test public void testAllObservers_ExclusiveObserverIds() { addAppUsageObserver(OBS_ID1, GROUP1, TIME_10_MIN); addUsageSessionObserver(OBS_ID1, GROUP1, TIME_30_MIN, TIME_1_MIN); addAppUsageLimitObserver(OBS_ID1, GROUP1, TIME_10_MIN, 0); assertTrue("Observer wasn't added", hasAppUsageObserver(UID, OBS_ID1)); assertTrue("Observer wasn't added", hasUsageSessionObserver(UID, OBS_ID1)); assertTrue("Observer wasn't added", hasAppUsageLimitObserver(UID, OBS_ID1)); AppTimeLimitController.UsageGroup appUsageGroup = mController.getAppUsageGroup(UID, OBS_ID1); AppTimeLimitController.UsageGroup sessionUsageGroup = mController.getSessionUsageGroup(UID, OBS_ID1); AppTimeLimitController.UsageGroup appUsageLimitGroup = getAppUsageLimitObserver( UID, OBS_ID1); assertEquals(TIME_10_MIN, appUsageGroup.getTimeLimitMs()); assertEquals(TIME_30_MIN, sessionUsageGroup.getTimeLimitMs()); assertEquals(TIME_10_MIN, appUsageLimitGroup.getTimeLimitMs()); }
def delete_port_postcommit(self, context): port = context.current device_id = port['device_id'] host = port[portbindings.HOST_ID] port_id = port['id'] network_id = port['network_id'] tenant_id = port['tenant_id'] device_owner = port['device_owner'] try: with self.eos_sync_lock: hostname = self._host_name(host) if device_owner == n_const.DEVICE_OWNER_DHCP: self.rpc.unplug_dhcp_port_from_network(device_id, hostname, port_id, network_id, tenant_id) else: self.rpc.unplug_host_from_network(device_id, hostname, port_id, network_id, tenant_id) except arista_exc.AristaRpcError: LOG.info(EOS_UNREACHABLE_MSG) raise ml2_exc.MechanismDriverError()
import React, { PureComponent } from 'react'; import { withTranslation } from 'react-i18next'; import classNames from 'classnames'; import Card from '@material-ui/core/Card'; import Typography from '@material-ui/core/Typography'; import BigNumber from 'bignumber.js'; import { createStyles, Theme, withStyles } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import ErrorOutlineIcon from '@material-ui/icons/ErrorOutline'; import { getPollData } from '@/utils/sdk'; import { POLL_STATUS } from '@/utils/constants'; import Link from '@material-ui/core/Link'; import { NavLink } from 'react-router-dom'; import BorderLinearProgress from '../../BorderLinearProgress'; const useStyles = (theme: Theme) => createStyles({ root: {}, text: { padding: theme.spacing(1) * 2, height: theme.spacing(1), }, cardCommon: { opacity: 0.5, }, cardInProgress: { opacity: 1, }, cardExecuted: { border: `1px solid ${theme.palette.primary.main}`, }, cardDefeated: { border: `1px solid ${theme.palette.secondary.light}`, opacity: 0.5, }, [theme.breakpoints.down('xs')]: { cardCommon: { transition: '.4s ease box-shadow', borderRadius: '4px', }, }, [theme.breakpoints.up('sm')]: { cardCommon: { transition: '.4s ease box-shadow', borderRadius: '4px', }, }, [theme.breakpoints.up('lg')]: { cardCommon: { transition: '.4s ease box-shadow', borderRadius: '4px', }, }, cardHover: { boxShadow: ` ${theme.spacing(1) * 0}px ${theme.spacing(1) * 1}px ${theme.spacing(1) * 3 }px ${theme.spacing(1) * 0}px rgba(0,0,0,0.2), ${theme.spacing(1) * 0}px ${theme.spacing(1) * 1}px ${theme.spacing(1) * 1 }px ${theme.spacing(1) * 0}px rgba(0,0,0,0.14), ${theme.spacing(1) * 0}px ${theme.spacing(1) * 2}px ${theme.spacing(1) * 1 }px -${theme.spacing(1) * 1}px rgba(0,0,0,0.12) `, cursor: 'pointer', }, cardNoHover: {}, media: { height: 140, }, mediaCover: { objectFit: 'cover', }, mediaContain: { objectFit: 'contain', }, [theme.breakpoints.down('sm')]: { header: { padding: theme.spacing(1), }, }, [theme.breakpoints.up('sm')]: { header: { padding: theme.spacing(1) * 2, }, }, header: { alignItems: 'center', borderBottom: '1px solid rgba(0, 0, 0, 0.075)', display: 'flex', }, content: { padding: theme.spacing(2), }, title: { fontWeight: 700, }, }); interface ExternalProps { key?: string; title: string; url: string; link: string; className?: string; id: number; id_on_chain: number; for_votes: number; against_votes: number; quorum_votes: number; status: number; end_time: string; creator: string; type_args_1: string; } interface InternalProps { t: any; classes: any; } interface Props extends ExternalProps, InternalProps { t: any; } interface PollCardState { displayHover: boolean; pollData: any; } class PollCard extends PureComponent<Props, PollCardState> { // eslint-disable-next-line react/static-property-placement static defaultProps = { key: undefined, title: undefined, url: undefined, link: undefined, id: undefined, id_on_chain: undefined, for_votes: undefined, against_votes: undefined, quorum_votes: undefined, status: undefined, end_time: undefined, creator: undefined, type_args_1: undefined, }; constructor(props: Props) { super(props); this.state = { displayHover: false, pollData: undefined, }; } componentDidMount() { const { id, id_on_chain, status, creator, type_args_1 } = this.props; if (status < POLL_STATUS.EXECUTED) { getPollData(creator, type_args_1).then((data) => { if (data && data.id === id) { this.setState({ pollData: data }); } }); } } onCardEnter = () => { this.setState({ displayHover: true }); }; onCardLeave = () => { this.setState({ displayHover: false }); }; render() { const { title, id, id_on_chain, url, for_votes = 0, against_votes = 0, quorum_votes = 0, status, end_time, classes, t, } = this.props; const yes = status === POLL_STATUS.ACTIVE && this.state.pollData ? this.state.pollData.for_votes : for_votes; const no = status === POLL_STATUS.ACTIVE && this.state.pollData ? this.state.pollData.against_votes : against_votes; // const total = 168171610282100220; const quorum = status === POLL_STATUS.ACTIVE && this.state.pollData && this.state.pollData.quorum_votes ? this.state.pollData.quorum_votes : quorum_votes; const total = new BigNumber(25 * Number(quorum)); const yesPercent = new BigNumber(yes).div(total).times(100).toFixed(2); const noPercent = new BigNumber(no).div(total).times(100).toFixed(2); const voted = new BigNumber(yes).plus(new BigNumber(no)); const votedPercent = voted.div(total).times(100).toFixed(2); return ( <Link component={NavLink} to={url} underline="none"> <div className={classNames(classes.cardCommon, { [classes.cardHover]: this.state.displayHover, [classes.cardNoHover]: !this.state.displayHover, [classes.cardInProgress]: status !== POLL_STATUS.EXECUTED, [classes.cardExecuted]: status === POLL_STATUS.EXECUTED, [classes.cardDefeated]: status === POLL_STATUS.DEFEATED, })} onMouseEnter={this.onCardEnter} onMouseLeave={this.onCardLeave} > <Card className={classes.cardRoom}> <div className={classes.header}> <Typography variant="h5" gutterBottom className={classes.title}> {title} </Typography> </div> <div className={classes.content}> <Typography variant="body2" gutterBottom> Id: {id_on_chain} </Typography> <Typography variant="body2" gutterBottom> {t('poll.status')}: {t(`poll.statusText.${status}`)} </Typography> <Typography variant="body2" gutterBottom> {t('poll.endTime')}:{' '} {new Date(parseInt(end_time, 10)).toLocaleString()}{' '}{new Date().toTimeString().slice(9, 17)} </Typography> <BorderLinearProgress variant="buffer" value={Math.min(Number(yesPercent), 100)} valueBuffer={Math.min( Number(noPercent) + Number(yesPercent), 100, )} style={{ marginBottom: 8 }} /> <Grid container alignItems="center" justify="space-between" wrap="nowrap" > <div> <Grid container alignItems="center"> {yes < no ? ( <ErrorOutlineIcon fontSize="small" color="secondary" style={{ marginRight: 4 }} /> ) : null} <Typography variant="body2" color="textPrimary"> {`${t('poll.voted')} ${votedPercent}%`} </Typography> </Grid> </div> <div> <Grid container alignItems="center" spacing={1}> <Grid item> <Typography variant="body2" color="primary"> {`${t('poll.yes')} ${yesPercent}%`} </Typography> </Grid> <Grid item> <Typography variant="body2" color="secondary"> {`${t('poll.no')} ${noPercent}%`} </Typography> </Grid> </Grid> </div> </Grid> </div> </Card> </div> </Link> ); } } export default withStyles(useStyles)(withTranslation()(PollCard));
I am a gadget girl and this fits my personality. I saw the Smaty Bluetooth Smart LED Light Bulb on Amazon Review Club and with the discount provided I thought it was a good time to dip my toe into the world of bluetooth household products. We are currently renters so I am not ready to get to deep into internet/bluetooth home automation but I do like the idea of controlling the lights remotely. Nice to have when leaving the house and the light switches are away from the outside door, it is dark out and you still want to be able to see to get to said door and still turn out the lights. I had hoped that this light would hook up to my Amazon Echo but I do not see that it is possible with this brand but that is OK as the price was right and the light is still very useful and fun. The product arrived safely packaged and was a snap to set up. You just download the app from your android or iphone provider or use the supplied q code to get the app link, turn on the light and the app finds the light automatically. You name the light and you are ready to go. You can control the colors of the light into limitless colors either manually or by color picker in the software. You can control the brightness and warmth of color from the app, make the light change or "dance" to music or pick a program of color changes or fades via the app. You can also create custom programs to suit your needs. I have not had a lot of time with this light yet but I am sure I will be buying more of these. I have some young grandchildren and can see that their parents are going to have to have these for bedtime/night light uses. I am sure there is a program or color to keep the monsters away!
def list_users(self): raise StoreMethodNotImplemented( 'this store does not handle listing users')
package xmlpull import ( "fmt" "io" ) var _ = fmt.Print // [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S? ('[' // (markupdecl | DeclSep)* ']' S?)? '>' // func (p *Parser) parseDocTypeDecl() (err error) { //ASSUMPTION: we have seen <!D err = p.ExpectStr("OCTYPE") if err != nil { err = p.NewXmlPullError(err.Error()) } if err == nil { err = p.ExpectS() } // do simple and crude scanning for end of doctype var decl []rune if err == nil { bracketLevel := 0 // normalizeIgnorableWS := p.tokenizing && !p.roundtripSupported // normalizedCR := false for err == nil { var ch rune ch, err = p.NextCh() if err != nil { break } if ch == '[' { bracketLevel++ } else if ch == ']' { bracketLevel-- } if ch == '>' && bracketLevel == 0 { break } //if normalizeIgnorableWS { // ... // } decl = append(decl, ch) } } if err == nil || err == io.EOF { p.docTypeDecl = string(decl) } return }
def parse_schema(schema_file): e = xml.etree.ElementTree.parse(schema_file) root = e.getroot() cols = [] for elem in root.findall(".//{http://genomic.elet.polimi.it/entities}field"): cols.append(elem.text) return cols
/// Returns a vector of (async::Time, zx::ClockUpdate, ClockUpdateReason) tuples describing the /// updates to make to a clock during the slew. The first update is guaranteed to be requested /// immediately. fn clock_updates(&self) -> Vec<(fasync::Time, zx::ClockUpdate, ClockUpdateReason)> { // Note: fuchsia_async time can be mocked independently so can't assume its equivalent to // the supplied monotonic time. let start_time = fasync::Time::now(); let finish_time = start_time + self.duration; // For large slews we expect the reduction in error bound while applying the correction to // exceed the growth in error bound due to oscillator error but there is no guarantee of // this. If error bound will increase through the slew, just use the worst case throughout. let begin_error_bound = cmp::max(self.start_error_bound, self.end_error_bound); // The final vector is composed of an initial update to start the slew... let mut updates = vec![( start_time, zx::ClockUpdate::new() .rate_adjust(self.total_rate_adjust()) .error_bounds(begin_error_bound), ClockUpdateReason::BeginSlew, )]; // ... intermediate updates to reduce the error bound if it reduces by more than the // threshold during the course of the slew ... if self.start_error_bound > self.end_error_bound + ERROR_BOUND_UPDATE { let bound_change = (self.start_error_bound - self.end_error_bound) as i64; let error_update_interval = zx::Duration::from_nanos( ((self.duration.into_nanos() as i128 * ERROR_BOUND_UPDATE as i128) / bound_change as i128) as i64, ); let mut i: i64 = 1; while start_time + error_update_interval * i < finish_time { updates.push(( start_time + error_update_interval * i, zx::ClockUpdate::new() .error_bounds(self.start_error_bound - ERROR_BOUND_UPDATE * i as u64), ClockUpdateReason::ReduceError, )); i += 1; } } // ... and a final update to return the rate to normal. updates.push(( finish_time, zx::ClockUpdate::new() .rate_adjust(self.base_rate_adjust) .error_bounds(self.end_error_bound), ClockUpdateReason::EndSlew, )); updates }
package controllers; import play.mvc.Controller; import play.mvc.With; import controllers.minifymod.GzipResponse; /** * Basic usage of gzipped outputstreams. By adding the Annotation * @With(GzipResponse.class) to your controller every single response will be * delivered gezipped if the client supports it */ @With(GzipResponse.class) public class Gzipped extends Controller { public static void index() { String text = "This site is gzipped (if your browser supports it)"; render("index.html", text); } }
/** * Create a number of new Datasets, having a particular dataset type. * * @param type dataset type * @param number amount of datasets to create */ private void createDatasetsWithType(DatasetType type, ServiceType serviceType, int number) { for (int x = 0; x < number; x++) { Dataset d = newEntity(serviceType); d.setType(type); getService(serviceType).create(d); } }
<reponame>Ostoic/distant_wow #pragma once #include <memory> #include "object.hpp" #include "detail/unit_descriptors.hpp" #include "types.hpp" namespace distant::wow::entities { enum class power_type { mana = 0, rage = 1, energy = 3, rune = 6 }; enum class faction { // alliance human = 1, dwarf = 3, night_elf = 4, gnome = 115, draenai = 1629, // horde orc = 2, undead = 5, tauren = 6, troll = 116, blood_elf = 1610 }; class unit : public object { public: // observers memory::address descriptors_base() const; std::size_t display_id() const override; optional_ref<unit> owner() const; optional_ref<unit> target() const; wow::guid target_guid() const; wow::flags flags() const; wow::flags other_flags() const; wow::uint health() const; wow::uint max_health() const; wow::uint power() const; wow::uint max_power() const; power_type power_type() const; faction faction() const; virtual bool is_player() const; float current_speed() const; float active_speed() const; float flight_speed() const; float walk_speed() const; float swim_speed() const; public: // mutators void set_owner(const object& new_owner); void set_target(const object& new_target); // Speed mutators void set_current_speed(float speed); void set_active_speed(float speed); void set_flight_speed(float speed); void set_walk_speed(float speed); void set_swim_speed(float speed); public: // {ctor} unit() = default; explicit unit(memory::address base); unit(unit&&) = default; unit(const unit&) = default; unit& operator=(const unit&) = default; unit& operator=(unit&&) = default; virtual ~unit() = default; protected: memory::address get_name_ptr() const override; void update_data() const override; private: // implementation functions friend class object; private: // descriptors mutable memory::address descriptors_base_; }; bool is_alliance(faction faction); bool is_horde(faction faction); //unit get_target(const unit& u); } //namespace distant::wow namespace distant::wow { using entities::unit; }
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> using namespace std; double dp[5002][2]; double mdp[5002][2]; double p[5002], ttp[5002]; int t[5002]; double res; int n, T; int main(){ cin >> n >> T; for(int i = 0;i < n;i++){ cin >> p[i] >> t[i]; p[i] /= 100; ttp[i] = pow(1-p[i], t[i]); } p[n] = 0; p[n+1] = 0; ttp[n] = ttp[n + 1] = 1; t[n] = 5002; t[n+1] = 5002; n++; dp[0][0] = 1; mdp[t[0]][0] += ttp[0]; dp[t[0]][1] += ttp[0]; for(int jj = 0;jj < n;jj++){ for(int i = 0;i <= T;i++){ int j = jj%2; dp[i][j] -= mdp[i][j]; dp[i+1][j^1] += dp[i][j] * p[jj]; if(i + t[jj]+1 < 5002){ mdp[i+t[jj]+1][j] += dp[i+1][j]*ttp[jj]; dp[i+t[jj]+1][j^1] += dp[i+1][j]*ttp[jj]; } dp[i+1][j] += dp[i][j] * (1-p[jj]); if(i == T)res += jj * dp[T][j]; mdp[i][j] = dp[i][j] = 0; } } printf("%.10lf\n", res); return 0; }
/** * A custom EditText that draws lines between each line of text that is displayed. */ public static class LinedEditText extends EditText { private Rect mRect; private Paint mPaint; // we need this constructor for LayoutInflater public LinedEditText(Context context, AttributeSet attrs) { super(context, attrs); mRect = new Rect(); mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(0x800000FF); } @Override protected void onDraw(Canvas canvas) { int count = getLineCount(); Rect r = mRect; Paint paint = mPaint; for (int i = 0; i < count; i++) { int baseline = getLineBounds(i, r); canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint); } super.onDraw(canvas); } }
/// Calculates the hash of the transaction also known as the txid pub fn hash(&self) -> Hash256 { let mut b = Vec::with_capacity(self.size()); self.write(&mut b).unwrap(); sha256d(&b) }
def _ray2d_vectorized( z, x, zgrad, xgrad, zend, xend, zsrc, xsrc, stepsize, max_step, honor_grid=False ): n = len(zend) rays = numpy.empty((n, max_step, 2), dtype=numpy.float64) counts = numpy.empty(n, dtype=numpy.int32) for i in prange(n): rays[i], counts[i] = _ray2d( z, x, zgrad, xgrad, zend[i], xend[i], zsrc, xsrc, stepsize, max_step, honor_grid, ) return rays, counts
One of the best and most underrated events at the CNE – Toronto’s end-of-the-summer exhibition – has got to be the butter sculptures. Each year the CNE invites local artists to huddle in a giant fridge with windows on one side that allows visitors at the Better Living Centre see the masterpieces as they’re being created. In years past, artists have sculpted everything from Darth Vader and Yoda to a larger-than-life Rob Ford – which is hard to imagine unless you’ve seen it yourself. Former Toronto Mayor Rob Ford visits the Rob Ford butter statue. Who knew you could create such uniquely original things out of butter? This year’s theme, celebrities, certainly opened the door for another Ford-like viral creation. And while the artists certainly didn’t disappoint, the real scene-stealer had to be one artists’ homage to Conrad, the celebrated dead raccoon whose memorial went viral back in July. How soon we forget how the little guy stole our hearts as he laid for 14 hours at Yonge and Church way back when the summer was still young. Is it a fitting tribute to the summer of 2015 in Toronto, or can you think of a better symbol?
. To evaluate the usefulness of ultrasound in the diagnosis of urologic complications in renal transplants, we reviewed the ultrasonographic studies performed in 107 renal transplants. Ultrasound disclosed 13 perirenal collection of fluid without hydronephrosis, 4 hydronephrosis without perirenal mass, 2 hydronephrosis from a perirenal fluid mass, 2 urinomas from polar infarction, 1 subcapsular hematoma, and 1 graft vascular atrophy. Ultrasound proved to be the most efficient technique in the diagnosis of hydronephrosis and perirenal fluid collection. Although it does not distinguish the nature of the latter, it permits control of diagnostic or therapeutic (75%) puncture. Moreover, it is useful in controlling percutaneous nephrostomy in transplant obstruction and permits its noninvasive follow-up.
__author__ = 'alisonbento' import src.base.arrayparsableentity as parsable import configs import src.resstatus as _status class Answer(parsable.ArrayParsableEntity): def __init__(self): self.status = 0 self.contents = {} def set_status(self, status): self.status = status def add_content(self, index, content): self.contents.update({index: content}) def to_array(self): print(self.status) array = { "status": self.status[0], "contents": self.contents } if configs.ANSWER_HUMAN_MODE: message = self.status[1] array.update({'message': message}) return array
/** * Class representing target server * @author novakm */ public class JetTarget implements Target { private final String name; private final String desc; private final String uri; /** * Constructor that sets instance variables according to given parameters * @param name - name of the target * @param desc - description of the target * @param uri - URI of the target */ public JetTarget (String name, String desc, String uri) { this.name = name; this.desc = desc; this.uri = uri; } /** * @return a string containg the name of the target. */ public String getName () { return name; } /** * @return a string containing descriptive information about * the target. */ public String getDescription () { return desc; } /** * @return a string containing URI of the server */ public String getServerUri () { return uri; } public String toString () { return name; } }
package coremain // This is CoreDNS' ascii LOGO, nothing fancy. It's generated with: // figlet -f slant CoreDNS // We're printing the logo line by line, hence splitting it up. var logo = []string{ ` ______ ____ _ _______`, ` / ____/___ ________ / __ \/ | / / ___/`, ` / / / __ \/ ___/ _ \/ / / / |/ /\__ \ `, `/ /___/ /_/ / / / __/ /_/ / /| /___/ / `, `\____/\____/_/ \___/_____/_/ |_//____/ `, } const marker = "~ "
Sony has found its Miles Morales and its villain for their animated Spider-Man movie! It’s been a while since we’ve heard any updates on Sony’s upcoming animated Spider-Man film. Since it was confirmed that Miles Morales would be the focus of the movie, fans have wondered who would be voicing him. Now, not only do we know who’s voicing Miles, but also who will be voicing the villain. In an exclusive report, The Hollywood Reporter has revealed that actor Shameik Moore will be voicing Miles Morales in the movie. The trade also reports that actor Liev Schreiber will join the cast as the antagonist. Moore rose to prominence for his role in Dope (2015), and is currently starring in the hit Netflix series, The Get Down. Schreiber, on the other hand, is best known for his role in Ray Donovan as the title character. Comic book fans may also remember that he portrayed Victor Creed (Sabertooth) in X-Men Origins: Wolverine (2009). These are two castings that should sit well with fans. Moore has a natural charm and wit that is very similar to that of Miles Morales. Meanwhile, Schreiber has an imposing presence that can make him very intimidating. The character of Miles Morales was originally introduced in Brian Michael Bendis’ Ultimate Comics: Spider-Man in 2011. Morales took up the mantle of Spider-Man following the death of the Ultimate Universe’s Peter Parker. So far, the two actors are the only cast members that are reportedly attached to the project. The film will be co-directed by Bob Persichetti and Peter Ramsey from a script by comedy duo Phil Lord and Chris Miller. Lord and Miller will also executive produce the movie. Sony’s animated Spider-Man flick is set to hit theaters on December 21, 2018.
<filename>src/math/matrix/LuDecompose.java /* Copyright 2017, 2018, 2019, 2020, 2021 <NAME> 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 math.matrix; import collection.TList; import math.CList; import math.Context; import math.ContextOrdered; /** * LU decompose using Doolittle method. * @author masao * @param <K> * @param <T> */ public class LuDecompose<K,T extends Context<K,T>&ContextOrdered<K,T>> { final CMatrix<K,T> target; public LuDecompose(CMatrix<K,T> target) { this.target=target.sfix(); } public LU<K,T> decompose() { LU<K,T> retval=new LU<>(exec()); return retval; } /** * execute decomposition with doolittle method. * @return L and U (get(0) and get(1), respectively) */ public TList<CMatrix<K,T>> exec() { target.assertSquare(); doolittle(); if (!target.nonZeroDiagonal()) throw new NonsingularMatrixException("non zero element found in diagonal of doolittle result : noticed by LuDecompose.lu()"); // keep this exception message simple, meaning not to include any variable, //because this exception will be used to detect nonsingular matrix and //in that case certain level of performance is needed for throwing this exception. return TList.sof(target.fillUpper(target.bb.zero()).fillDiagonal(target.bb.one()),target.fillLower(target.bb.zero())); } /** * doolittle method as a whole. * @return */ public CMatrix<K,T> doolittle() { doolittleSteps().forEach(m->doolittleStep(m)); return target; } public TList<CMatrix<K,T>> doolittleSteps() { return TList.range(0,target.minSize()-1).map(i->target.subMatrixLR(i,i)); } /** * one step of doolittle method.to complete doolittle method, use LuDecompose. * @param <K> * @param <T> * @param target * @return */ public static <K,T extends Context<K,T>&ContextOrdered<K,T>> CMatrix<K,T> doolittleStep(CMatrix<K,T> target){ if (target.get(0,0).isZero()) throw new PivotingMightBeRequiredException("lu decomposition encountered 0 diagonal element:"+ target.toString() +": notified from CMatrix.doolittleStep"); CList<K,T> lcolumn =target.subRows(1).subColumns(0,1).columns().get(0).reset(cl->cl.scale(target.get(0,0).inv())); CList<K,T> eliminator =target.subRows(0,1).subColumns(1).rows().get(0); TList<CList<K,T>> eliminated =target.subMatrixLR(1,1).rows(); lcolumn.body().pair(eliminated,(l,u)->u.reset(cl->cl.sub(eliminator.scale(l)))).forEach(r->{}); return target; } }
def scan_networks(self): self.start_scan_networks() for _ in range(10): time.sleep(2) APs = self.get_scan_networks() if APs: return APs return None
/* * Copyright DataStax, 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.datastax.oss.dsbulk.config.model; import com.datastax.oss.dsbulk.config.ConfigUtils; import com.typesafe.config.Config; import com.typesafe.config.ConfigObject; import com.typesafe.config.ConfigOrigin; import com.typesafe.config.ConfigValue; import com.typesafe.config.ConfigValueType; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.function.BiConsumer; public class SettingsGroupFactory { /** * A String comparator that places the following 3 sections on top of generated documentation: * * <ol> * <li>Common settings * <li>Connector settings * <li>Schema settings * </ol> */ private static final SettingsComparator POPULAR_SECTIONS_FIRST = new SettingsComparator("Common", "dsbulk.connector", "dsbulk.schema"); /** * A comparator for configuration entries that preserves the original order in which they are * found in the configuration file. Used for the driver section only. */ public static final Comparator<Entry<String, ConfigValue>> ORIGIN_COMPARATOR = (e1, e2) -> { if (e1.getKey().equals(e2.getKey())) { return 0; } ConfigOrigin o1 = e1.getValue().origin(); ConfigOrigin o2 = e2.getValue().origin(); int positionComparison = Integer.compare(o1.lineNumber(), o2.lineNumber()); if (positionComparison != 0) { return positionComparison; } // compare keys alphabetically return e1.getKey().compareTo(e2.getKey()); }; /** * Creates the configuration sections for DSBulk. The sections created here are used by the help * emitter in dsbulk-runner module, and by documentation generation tools found in dsbulk-docs * module. * * @param includeDriver Whether to include a driver section or not. */ public static Map<String, SettingsGroup> createDSBulkConfigurationGroups(boolean includeDriver) { Config referenceConfig = ConfigUtils.standaloneDSBulkReference(); List<String> commonSettings = parseCommonSettings(referenceConfig); List<String> preferredSettings = parsePreferredSettings(referenceConfig, commonSettings); SettingsComparator comparator = new SettingsComparator(preferredSettings); Map<String, SettingsGroup> groups = new TreeMap<>(POPULAR_SECTIONS_FIRST); // First add a group for the "commonly used settings". Want to show that first in our doc. groups.put("Common", new FixedSettingsGroup(commonSettings)); // Now add groups for every top-level setting section in DSBulk config ConfigObject dsbulkRoot = referenceConfig.getConfig("dsbulk").root(); addDsbulkSections(groups, dsbulkRoot, comparator); // Now add settings to DSBulk groups populateDsbulkSettings(groups, dsbulkRoot, "dsbulk"); if (includeDriver) { Config driverConfig = ConfigUtils.standaloneDriverReference().getConfig("datastax-java-driver"); SettingsGroup driverGroup = new OrderedSettingsGroup(); populateDriverGroup(driverGroup, driverConfig.root(), "datastax-java-driver"); groups.put("datastax-java-driver", driverGroup); } return groups; } @NonNull private static List<String> parseCommonSettings(@NonNull Config referenceConfig) { // Common settings (both global and those from connectors). List<String> commonSettings = new ArrayList<>(); // Add connector-specific common settings, after connector.name. commonSettings.add("dsbulk.connector.name"); visitConnectors( referenceConfig, (connectorName, connectorConfig) -> { if (connectorConfig.hasPath("metaSettings.docHints.commonSettings")) { connectorConfig.getStringList("metaSettings.docHints.commonSettings").stream() // connector common settings are unqualified .map(s -> String.format("dsbulk.connector.%s.%s", connectorName, s)) .forEach(commonSettings::add); } }); // DSBulk general common settings are already fully-qualified commonSettings.addAll( referenceConfig.getStringList("dsbulk.metaSettings.docHints.commonSettings")); return commonSettings; } @NonNull private static List<String> parsePreferredSettings( @NonNull Config referenceConfig, @NonNull List<String> commonSettings) { // Settings that should be placed near the top within their setting groups. It is a super-set of // commonSettings. List<String> preferredSettings = new ArrayList<>(commonSettings); preferredSettings.addAll( referenceConfig.getStringList("dsbulk.metaSettings.docHints.preferredSettings")); // Add connector-specific preferred settings. visitConnectors( referenceConfig, (connectorName, connectorConfig) -> { if (connectorConfig.hasPath("metaSettings.docHints.preferredSettings")) { connectorConfig.getStringList("metaSettings.docHints.preferredSettings").stream() .map(s -> String.format("dsbulk.connector.%s.%s", connectorName, s)) .forEach(preferredSettings::add); } }); return preferredSettings; } private static void addDsbulkSections( @NonNull Map<String, SettingsGroup> groups, @NonNull ConfigObject root, @NonNull Comparator<String> comparator) { for (Map.Entry<String, ConfigValue> entry : root.entrySet()) { String key = entry.getKey(); switch (key) { case "metaSettings": // never print meta-settings break; case "driver": // deprecated as of 1.4.0 break; case "connector": // "connector" group is special because we want a sub-section for each // particular connector. We subdivide each one level further. groups.put( "dsbulk." + key, new ContainerSettingsGroup("dsbulk." + key, false, comparator)); for (Map.Entry<String, ConfigValue> child : ((ConfigObject) entry.getValue()).entrySet()) { if (!ConfigUtils.isLeaf(child.getValue())) { groups.put( "dsbulk." + key + "." + child.getKey(), new ContainerSettingsGroup( "dsbulk." + key + "." + child.getKey(), true, comparator)); } } break; default: groups.put( "dsbulk." + key, new ContainerSettingsGroup("dsbulk." + key, true, comparator)); break; } } } private static void populateDsbulkSettings( @NonNull Map<String, SettingsGroup> groups, @NonNull ConfigObject root, @NonNull String rootPath) { for (Map.Entry<String, ConfigValue> entry : root.entrySet()) { String key = entry.getKey(); // Never add a setting under "metaSettings". if (key.equals("metaSettings")) { continue; } ConfigValue value = entry.getValue(); String fullKey = rootPath.isEmpty() ? key : rootPath + '.' + key; if (ConfigUtils.isLeaf(value)) { // Add the setting name to the first group that accepts it. for (SettingsGroup group : groups.values()) { if (group.addSetting(fullKey)) { // The setting was added to a group. Don't try adding to other groups. break; } } } else { populateDsbulkSettings(groups, (ConfigObject) value, fullKey); } } } private static void populateDriverGroup( @NonNull SettingsGroup driverGroup, @NonNull ConfigObject root, @NonNull String path) { Set<Entry<String, ConfigValue>> entries = new TreeSet<>(ORIGIN_COMPARATOR); entries.addAll(root.entrySet()); for (Entry<String, ConfigValue> entry : entries) { String key = entry.getKey(); String fullKey = path.isEmpty() ? key : path + '.' + key; ConfigValue value = ConfigUtils.getNullSafeValue(root.toConfig(), key); if (ConfigUtils.isLeaf(value)) { driverGroup.addSetting(fullKey); } else { populateDriverGroup(driverGroup, ((ConfigObject) value), fullKey); } } } /** * Walk through the setting sections for each connector and perform an action on the section. * * @param action the action to execute */ private static void visitConnectors(Config referenceConfig, BiConsumer<String, Config> action) { // Iterate through direct children of `connector`. Order is non-deterministic, so do // two passes: one to collect names of children and put in a sorted set, second to walk // through children in order. Set<String> connectorChildren = new TreeSet<>(); for (Map.Entry<String, ConfigValue> nonLeafEntry : referenceConfig.getObject("dsbulk.connector").entrySet()) { connectorChildren.add(nonLeafEntry.getKey()); } for (String connectorName : connectorChildren) { ConfigValue child = ConfigUtils.getNullSafeValue(referenceConfig, "dsbulk.connector." + connectorName); if (child.valueType() == ConfigValueType.OBJECT) { Config connectorConfig = ((ConfigObject) child).toConfig(); action.accept(connectorName, connectorConfig); } } } }
Somatic cell amplification of early pregnancy factors in the fallopian tube. This essay is concerned with the function of ovarian somatic cells, especially those of the cumulus oophorus, that are shed with the oocyte at the time of ovulation. Once dissociated from the surface of the oocyte(s), they remain in its close vicinity or that of the zygote(s) throughout the tubal sojourn. Most such follicular cells are not moribund or dead but continue to be synthetically active, although showing ultrastructural modification. Their secretions may include steroid hormones, prostaglandins and diverse peptides, molecules that would be presented locally to the endosalpinx. The cell suspension represents a potential route of amplification of early pregnancy signals from the embryo to influence the pattern of ovarian steroid secretion and perhaps that of folliculogenesis. Bearing in mind the relatively low concentration of hormones generated by the somatic cell suspension, vascular counter-current transfer of information is postulated from the Fallopian tube to the ipsilateral ovary. Molecular techniques are being applied as a means of examining endosalpingeal responses in four different experimental models in which the numbers and presumptive activity of suspended follicular cells are varied in pigs with spontaneous oestrous cycles. Because these animals ovulate on both ovaries, epithelial activity can be compared and contrasted between the two sides. In a final model, attempts are being made to generate early pregnancy responses in the absence of embryos by transplanting zygote-programmed cumulus cells from a mated donor into the Fallopian tube of an unmated recipient.
const hashes = ['# ', ' #']; const slashes = ['/* ', ' */']; const semicolons = [';; ', ' ;;']; const parens = ['(* ', ' *)']; const dashes = ['-- ', ' --']; const chevrons = ['<!--', ' -->']; const percents = ['%% ', ' %%']; // all the supported languages export const youcodeLanguage: { [lang: string]: string[] | undefined } = { 'php': hashes, 'html': chevrons, 'css': slashes, 'scss': slashes, 'javascript': slashes, 'javascriptreact': slashes, 'typescript': slashes, 'typescriptreact': slashes, 'sql': hashes, 'python': hashes, 'c': slashes, 'java': slashes, 'latex': percents, 'asm': hashes, 'coffeescript': hashes, 'cpp': slashes, 'csharp' : slashes, 'dockerfile': hashes, 'fsharp': parens, 'go': slashes, 'groovy': slashes, 'haskell': dashes, 'ini': semicolons, 'jade': slashes, 'less': slashes, 'lua': dashes, 'makefile': hashes, 'objective-c': slashes, 'ocaml': parens, 'perl': hashes, 'perl6': hashes, 'plaintext': hashes, 'powershell': hashes, 'r': hashes, 'ruby': hashes, 'rust': slashes, 'shellscript': hashes, 'swift': slashes, 'xsl': slashes, 'yaml': hashes, };
package main import ( "fmt" "log" "github.com/FoxComm/highlander/middlewarehouse/common/utils" "github.com/FoxComm/highlander/middlewarehouse/consumers" "github.com/FoxComm/highlander/middlewarehouse/consumers/customer-groups/agent" "github.com/FoxComm/highlander/middlewarehouse/consumers/customer-groups/consumer" "github.com/FoxComm/highlander/middlewarehouse/consumers/customer-groups/manager" "github.com/FoxComm/highlander/middlewarehouse/shared" "github.com/FoxComm/highlander/middlewarehouse/shared/mailchimp" "github.com/FoxComm/highlander/middlewarehouse/shared/phoenix" "github.com/FoxComm/metamorphosis" elastic "gopkg.in/olivere/elastic.v3" ) const ( MESSAGING_PLUGIN_NAME = "messaging" MESSAGING_SETTINGS_KEY_MAILCHIMP_API_KEY = "mailchimp_key" MESSAGING_SETTINGS_KEY_MAILCHIMP_LIST_ID = "mailchimp_customers_list_id" clientID = "customer-groups-01" groupID = "mwh-customer-groups-consumers" ) func main() { consumerConfig, err := consumers.MakeConsumerConfig() if err != nil { log.Panicf("Unable to parse consumer config with error %s", err.Error()) } agentConfig, err := makeAgentConfig() if err != nil { log.Panicf("Unable to parse agent config with error: %s", err.Error()) } phoenixConfig, err := shared.MakePhoenixConfig() if err != nil { log.Panicf("Unable to parse phoenix config with error: %s", err.Error()) } // new ES client esClient, err := elastic.NewClient( elastic.SetURL(agentConfig.ElasticURL), elastic.SetSniff(!utils.IsDebug()), ) if err != nil { log.Panicf("Unable to create ES client with error: %s", err.Error()) } // new Phoenix client phoenixClient := phoenix.NewPhoenixClient(phoenixConfig.URL, phoenixConfig.User, phoenixConfig.Password) mailchimpApiKey, mailchimpListID, err := getMailchimpSettings(phoenixClient) if err != nil { log.Panicf("Unable to get %s settings with error %s", MESSAGING_PLUGIN_NAME, err.Error()) } mailchimpDisabled := mailchimpApiKey == "" || mailchimpListID == "" if mailchimpDisabled { log.Printf("Mailchimp config is not complete. For mailchimp integration set up API key and Customers ist ID values in %s plugin settgins", MESSAGING_PLUGIN_NAME, ) } // new Mailchimp client chimpClient := mailchimp.NewClient(mailchimpApiKey, mailchimp.SetDebug(true)) // Customer Groups manager groupsManager := manager.NewGroupsManager( esClient, phoenixClient, chimpClient, manager.SetMailchimpListID(mailchimpListID), manager.SetMailchimpDisabled(mailchimpDisabled), manager.SetElasticQuerySize(1000), ) //Initialize and start polling agent groupsAgent := agent.NewAgent( phoenixClient, groupsManager, agent.SetTimeout(agentConfig.PollingInterval), ) groupsAgent.Run() // Initialize and start consumer cgc := consumer.NewCustomerGroupsConsumer(groupsManager) c, err := metamorphosis.NewConsumer(consumerConfig.ZookeeperURL, consumerConfig.SchemaRepositoryURL, consumerConfig.OffsetResetStrategy) if err != nil { log.Fatalf("Unable to connect to Kafka with error %s", err.Error()) } c.SetGroupID(groupID) c.SetClientID(clientID) c.RunTopic(consumerConfig.Topic, cgc.Handler) } func getMailchimpSettings(phoenixClient phoenix.PhoenixClient) (string, string, error) { plugins, err := phoenixClient.GetPlugins() if err != nil { log.Panicf("Couldn't get plugins list with error %s", err.Error()) } for _, plugin := range plugins { if plugin.Name == MESSAGING_PLUGIN_NAME { s, err := phoenixClient.GetPluginSettings(plugin.Name) if err != nil { log.Panicf("Couldn't get %s plugin settings with error %s", MESSAGING_PLUGIN_NAME, err.Error()) } mailchimpApiKey, ok := s[MESSAGING_SETTINGS_KEY_MAILCHIMP_API_KEY].(string) if !ok { return "", "", fmt.Errorf("%s is not a string. value: %v", MESSAGING_SETTINGS_KEY_MAILCHIMP_API_KEY, mailchimpApiKey) } mailchimpListID, ok := s[MESSAGING_SETTINGS_KEY_MAILCHIMP_LIST_ID].(string) if !ok { return "", "", fmt.Errorf("%s is not a string. value: %v", MESSAGING_SETTINGS_KEY_MAILCHIMP_LIST_ID, mailchimpListID) } return mailchimpApiKey, mailchimpListID, nil } } return "", "", nil }
/** Returns whether this should receive OS upgrades in given cloud */ public boolean shouldUpgradeOsIn(Cloud cloud) { if (cloud.reprovisionToUpgradeOs()) { return nodeType == NodeType.host; } return nodeType.isDockerHost(); }
#include "KeyboardInput.hpp" #include "entities/Entity.hpp" #include <cmath> #include <iostream> namespace systems { // -------------------------------------------------------------- // // When an entity is added to this system, a mapping from its logical // inputs directly to the methods that perform those actions is // created. This allows the update method to iterative through only // those keys that are currently pressed and directly invoke the // entity methods (if they exist). // // -------------------------------------------------------------- void KeyboardInput::addEntity(std::shared_ptr<entities::Entity> entity) { // Need to let the System class do its thing System::addEntity(entity); // // Build a mapping from this entity's keyboard inputs to the functions this system // can invoke for those inputs. This allows those functions to be directly // called when the keyboard inputs are seen. KeyToFunction map; for (auto&& input : entity->getComponent<components::Input>()->getInputs()) { switch (input) { case components::Input::Type::Forward: { std::function<void(std::chrono::milliseconds, components::Position*, components::Movement*)> f = std::bind(&KeyboardInput::moveForward, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); map.m_keyToFunction[m_typeToKeyMap[input]] = f; } break; case components::Input::Type::TurnLeft: { std::function<void(std::chrono::milliseconds, components::Position*, components::Movement*)> f = std::bind(&KeyboardInput::turnLeft, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); map.m_keyToFunction[m_typeToKeyMap[input]] = f; } break; case components::Input::Type::TurnRight: { std::function<void(std::chrono::milliseconds, components::Position*, components::Movement*)> f = std::bind(&KeyboardInput::turnRight, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3); map.m_keyToFunction[m_typeToKeyMap[input]] = f; } break; } } // Add after creating the map, to ensure the copy into the m_keyToFunctionMap is correctly made // with all the keys to functions setup. m_keyToFunctionMap[entity->getId()] = map; } void KeyboardInput::removeEntity(decltype(entities::Entity().getId()) entityId) { // Need to let the System class do its thing System::removeEntity(entityId); // Remove from out local key to function mapping m_keyToFunctionMap.erase(entityId); } // -------------------------------------------------------------- // // For each entity, check which inputs it has specified and // update based upon the current keyboard state. // // -------------------------------------------------------------- void KeyboardInput::update(std::chrono::milliseconds elapsedTime) { for (auto&& [key, keyEvent] : m_keysPressed) { for (auto&& [id, entity] : m_entities) { if (m_keyToFunctionMap[id].m_keyToFunction.find(key) != m_keyToFunctionMap[id].m_keyToFunction.end()) { auto position = entity->getComponent<components::Position>(); auto movement = entity->getComponent<components::Movement>(); m_keyToFunctionMap[id].m_keyToFunction[key](elapsedTime, position, movement); } } } } // -------------------------------------------------------------- // // These two methods are used to track which keys are currently // pressed. The reason for doing this is to hopefully making it // more efficient to process only the keyboard input events that // are active, instead of looping through all possible keyboard // keys and asking if they are pressed. // // -------------------------------------------------------------- void KeyboardInput::keyPressed(sf::Event::KeyEvent keyEvent) { m_keysPressed[keyEvent.code] = keyEvent; } void KeyboardInput::keyReleased(sf::Event::KeyEvent keyEvent) { m_keysPressed.erase(keyEvent.code); } void KeyboardInput::moveForward(std::chrono::milliseconds elapsedTime, components::Position* position, components::Movement* movement) { const float PI = 3.14159f; const float DEGREES_TO_RADIANS = PI / 180.0f; auto vectorX = std::cos(position->getOrientation() * DEGREES_TO_RADIANS); auto vectorY = std::sin(position->getOrientation() * DEGREES_TO_RADIANS); auto current = position->get(); position->set(sf::Vector2f( current.x + vectorX * elapsedTime.count() * movement->getAcceleration(), current.y + vectorY * elapsedTime.count() * movement->getAcceleration())); } void KeyboardInput::turnLeft(std::chrono::milliseconds elapsedTime, components::Position* position, components::Movement* movement) { position->setOrientation(position->getOrientation() - movement->getRotateRate() * elapsedTime.count()); } void KeyboardInput::turnRight(std::chrono::milliseconds elapsedTime, components::Position* position, components::Movement* movement) { position->setOrientation(position->getOrientation() + movement->getRotateRate() * elapsedTime.count()); } } // namespace systems
/** * 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. */ #include "Adaptor.hh" #include "OrcTest.hh" #include "orc/Exceptions.hh" #include "orc/Type.hh" #include "wrap/gtest-wrapper.h" #include "Reader.cc" #include "TypeImpl.hh" namespace orc { uint64_t checkIds(const Type* type, uint64_t next) { EXPECT_EQ(next, type->getColumnId()) << "Wrong id for " << type->toString(); next += 1; for (uint64_t child = 0; child < type->getSubtypeCount(); ++child) { next = checkIds(type->getSubtype(child), next) + 1; } EXPECT_EQ(next - 1, type->getMaximumColumnId()) << "Wrong maximum id for " << type->toString(); return type->getMaximumColumnId(); } TEST(TestType, simple) { std::unique_ptr<Type> myType = createStructType(); myType->addStructField("myInt", createPrimitiveType(INT)); myType->addStructField("myString", createPrimitiveType(STRING)); myType->addStructField("myFloat", createPrimitiveType(FLOAT)); myType->addStructField("list", createListType(createPrimitiveType(LONG))); myType->addStructField("bool", createPrimitiveType(BOOLEAN)); EXPECT_EQ(0, myType->getColumnId()); EXPECT_EQ(6, myType->getMaximumColumnId()); EXPECT_EQ(5, myType->getSubtypeCount()); EXPECT_EQ(STRUCT, myType->getKind()); EXPECT_EQ( "struct<myInt:int,myString:string,myFloat:float," "list:array<bigint>,bool:boolean>", myType->toString()); checkIds(myType.get(), 0); const Type* child = myType->getSubtype(0); EXPECT_EQ(1, child->getColumnId()); EXPECT_EQ(1, child->getMaximumColumnId()); EXPECT_EQ(INT, child->getKind()); EXPECT_EQ(0, child->getSubtypeCount()); child = myType->getSubtype(1); EXPECT_EQ(2, child->getColumnId()); EXPECT_EQ(2, child->getMaximumColumnId()); EXPECT_EQ(STRING, child->getKind()); EXPECT_EQ(0, child->getSubtypeCount()); child = myType->getSubtype(2); EXPECT_EQ(3, child->getColumnId()); EXPECT_EQ(3, child->getMaximumColumnId()); EXPECT_EQ(FLOAT, child->getKind()); EXPECT_EQ(0, child->getSubtypeCount()); child = myType->getSubtype(3); EXPECT_EQ(4, child->getColumnId()); EXPECT_EQ(5, child->getMaximumColumnId()); EXPECT_EQ(LIST, child->getKind()); EXPECT_EQ(1, child->getSubtypeCount()); EXPECT_EQ("array<bigint>", child->toString()); child = child->getSubtype(0); EXPECT_EQ(5, child->getColumnId()); EXPECT_EQ(5, child->getMaximumColumnId()); EXPECT_EQ(LONG, child->getKind()); EXPECT_EQ(0, child->getSubtypeCount()); child = myType->getSubtype(4); EXPECT_EQ(6, child->getColumnId()); EXPECT_EQ(6, child->getMaximumColumnId()); EXPECT_EQ(BOOLEAN, child->getKind()); EXPECT_EQ(0, child->getSubtypeCount()); } TEST(TestType, nested) { std::unique_ptr<Type> myType = createStructType(); { std::unique_ptr<Type> innerStruct = createStructType(); innerStruct->addStructField("col0", createPrimitiveType(INT)); std::unique_ptr<Type> unionType = createUnionType(); unionType->addUnionChild(std::move(innerStruct)); unionType->addUnionChild(createPrimitiveType(STRING)); myType->addStructField("myList", createListType(createMapType(createPrimitiveType(STRING), std::move(unionType)))); } // get a pointer to the bottom type const Type* listType = myType->getSubtype(0); const Type* mapType = listType->getSubtype(0); const Type* unionType = mapType->getSubtype(1); const Type* structType = unionType->getSubtype(0); const Type* intType = structType->getSubtype(0); // calculate the id of the child to make sure that we climb correctly EXPECT_EQ(6, intType->getColumnId()); EXPECT_EQ(6, intType->getMaximumColumnId()); EXPECT_EQ("int", intType->toString()); checkIds(myType.get(), 0); EXPECT_EQ(5, structType->getColumnId()); EXPECT_EQ(6, structType->getMaximumColumnId()); EXPECT_EQ("struct<col0:int>", structType->toString()); EXPECT_EQ(4, unionType->getColumnId()); EXPECT_EQ(7, unionType->getMaximumColumnId()); EXPECT_EQ("uniontype<struct<col0:int>,string>", unionType->toString()); EXPECT_EQ(2, mapType->getColumnId()); EXPECT_EQ(7, mapType->getMaximumColumnId()); EXPECT_EQ("map<string,uniontype<struct<col0:int>,string>>", mapType->toString()); EXPECT_EQ(1, listType->getColumnId()); EXPECT_EQ(7, listType->getMaximumColumnId()); EXPECT_EQ("array<map<string,uniontype<struct<col0:int>,string>>>", listType->toString()); EXPECT_EQ(0, myType->getColumnId()); EXPECT_EQ(7, myType->getMaximumColumnId()); EXPECT_EQ( "struct<myList:array<map<string,uniontype<struct<col0:int>," "string>>>>", myType->toString()); } TEST(TestType, selectedType) { std::unique_ptr<Type> myType = createStructType(); myType->addStructField("col0", createPrimitiveType(BYTE)); myType->addStructField("col1", createPrimitiveType(SHORT)); myType->addStructField("col2", createListType(createPrimitiveType(STRING))); myType->addStructField("col3", createMapType(createPrimitiveType(FLOAT), createPrimitiveType(DOUBLE))); std::unique_ptr<Type> unionType = createUnionType(); unionType->addUnionChild(createCharType(CHAR, 100)); unionType->addUnionChild(createCharType(VARCHAR, 200)); myType->addStructField("col4", std::move(unionType)); myType->addStructField("col5", createPrimitiveType(INT)); myType->addStructField("col6", createPrimitiveType(LONG)); myType->addStructField("col7", createDecimalType(10, 2)); checkIds(myType.get(), 0); EXPECT_EQ( "struct<col0:tinyint,col1:smallint,col2:array<string>," "col3:map<float,double>,col4:uniontype<char(100),varchar(200)>," "col5:int,col6:bigint,col7:decimal(10,2)>", myType->toString()); EXPECT_EQ(0, myType->getColumnId()); EXPECT_EQ(13, myType->getMaximumColumnId()); std::vector<bool> selected(14); selected[0] = true; selected[2] = true; std::unique_ptr<Type> cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<col1:smallint>", cutType->toString()); EXPECT_EQ(0, cutType->getColumnId()); EXPECT_EQ(13, cutType->getMaximumColumnId()); EXPECT_EQ(2, cutType->getSubtype(0)->getColumnId()); selected.assign(14, true); cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ( "struct<col0:tinyint,col1:smallint,col2:array<string>," "col3:map<float,double>,col4:uniontype<char(100),varchar(200)>," "col5:int,col6:bigint,col7:decimal(10,2)>", cutType->toString()); EXPECT_EQ(0, cutType->getColumnId()); EXPECT_EQ(13, cutType->getMaximumColumnId()); selected.assign(14, false); selected[0] = true; selected[8] = true; selected[10] = true; cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<col4:uniontype<varchar(200)>>", cutType->toString()); EXPECT_EQ(0, cutType->getColumnId()); EXPECT_EQ(13, cutType->getMaximumColumnId()); EXPECT_EQ(8, cutType->getSubtype(0)->getColumnId()); EXPECT_EQ(10, cutType->getSubtype(0)->getMaximumColumnId()); EXPECT_EQ(10, cutType->getSubtype(0)->getSubtype(0)->getColumnId()); selected.assign(14, false); selected[0] = true; selected[8] = true; cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<col4:uniontype<>>", cutType->toString()); selected.assign(14, false); selected[0] = true; cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<>", cutType->toString()); selected.assign(14, false); selected[0] = true; selected[3] = true; selected[4] = true; cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<col2:array<string>>", cutType->toString()); selected.assign(14, false); selected[0] = true; selected[3] = true; cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<col2:array<void>>", cutType->toString()); EXPECT_EQ(3, cutType->getSubtype(0)->getColumnId()); EXPECT_EQ(4, cutType->getSubtype(0)->getMaximumColumnId()); selected.assign(14, false); selected[0] = true; selected[5] = true; selected[6] = true; selected[7] = true; cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<col3:map<float,double>>", cutType->toString()); EXPECT_EQ(5, cutType->getSubtype(0)->getColumnId()); EXPECT_EQ(7, cutType->getSubtype(0)->getMaximumColumnId()); selected.assign(14, false); selected[0] = true; selected[5] = true; cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<col3:map<void,void>>", cutType->toString()); EXPECT_EQ(5, cutType->getSubtype(0)->getColumnId()); EXPECT_EQ(7, cutType->getSubtype(0)->getMaximumColumnId()); selected.assign(14, false); selected[0] = true; selected[5] = true; selected[6] = true; cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<col3:map<float,void>>", cutType->toString()); EXPECT_EQ(5, cutType->getSubtype(0)->getColumnId()); EXPECT_EQ(7, cutType->getSubtype(0)->getMaximumColumnId()); selected.assign(14, false); selected[0] = true; selected[5] = true; selected[7] = true; cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<col3:map<void,double>>", cutType->toString()); EXPECT_EQ(5, cutType->getSubtype(0)->getColumnId()); EXPECT_EQ(7, cutType->getSubtype(0)->getMaximumColumnId()); selected.assign(14, false); selected[0] = true; selected[1] = true; selected[13] = true; cutType = buildSelectedType(myType.get(), selected); EXPECT_EQ("struct<col0:tinyint,col7:decimal(10,2)>", cutType->toString()); EXPECT_EQ(1, cutType->getSubtype(0)->getColumnId()); EXPECT_EQ(1, cutType->getSubtype(0)->getMaximumColumnId()); EXPECT_EQ(13, cutType->getSubtype(1)->getColumnId()); EXPECT_EQ(13, cutType->getSubtype(1)->getMaximumColumnId()); } void expectLogicErrorDuringParse(std::string typeStr, const char* errMsg) { try { std::unique_ptr<Type> type = Type::buildTypeFromString(typeStr); FAIL() << "'" << typeStr << "'" << " should throw std::logic_error for invalid schema"; } catch (std::logic_error& e) { EXPECT_EQ(e.what(), std::string(errMsg)); } catch (...) { FAIL() << "Should only throw std::logic_error for invalid schema"; } } TEST(TestType, buildTypeFromString) { std::string typeStr = "struct<a:int,b:string,c:decimal(10,2),d:varchar(5)>"; std::unique_ptr<Type> type = Type::buildTypeFromString(typeStr); EXPECT_EQ(typeStr, type->toString()); typeStr = "map<boolean,float>"; type = Type::buildTypeFromString(typeStr); EXPECT_EQ(typeStr, type->toString()); typeStr = "uniontype<bigint,binary,timestamp>"; type = Type::buildTypeFromString(typeStr); EXPECT_EQ(typeStr, type->toString()); typeStr = "struct<a:bigint,b:struct<a:binary,b:timestamp>>"; type = Type::buildTypeFromString(typeStr); EXPECT_EQ(typeStr, type->toString()); typeStr = "struct<a:bigint,b:struct<a:binary,b:timestamp with local time zone>>"; type = Type::buildTypeFromString(typeStr); EXPECT_EQ(typeStr, type->toString()); typeStr = "struct<a:bigint,b:struct<a:binary,b:timestamp>,c:map<double,tinyint>>"; type = Type::buildTypeFromString(typeStr); EXPECT_EQ(typeStr, type->toString()); typeStr = "timestamp with local time zone"; type = Type::buildTypeFromString(typeStr); EXPECT_EQ(typeStr, type->toString()); expectLogicErrorDuringParse("foobar", "Unknown type foobar"); expectLogicErrorDuringParse("struct<col0:int>other", "Invalid type string."); expectLogicErrorDuringParse("array<>", "Unknown type "); expectLogicErrorDuringParse("array<int,string>", "Array type must contain exactly one sub type."); expectLogicErrorDuringParse("map<int,string,double>", "Map type must contain exactly two sub types."); expectLogicErrorDuringParse("int<>", "Invalid < after int type."); expectLogicErrorDuringParse("array(int)", "Missing < after array."); expectLogicErrorDuringParse("struct<struct<bigint>>", "Invalid struct type. No field name set."); expectLogicErrorDuringParse("struct<a:bigint;b:string>", "Missing comma after field."); } TEST(TestType, quotedFieldNames) { std::unique_ptr<Type> type = createStructType(); type->addStructField("foo bar", createPrimitiveType(INT)); type->addStructField("`some`thing`", createPrimitiveType(INT)); type->addStructField("1234567890_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", createPrimitiveType(INT)); type->addStructField("'!@#$%^&*()-=_+", createPrimitiveType(INT)); EXPECT_EQ( "struct<`foo bar`" ":int,```some``thing```:int," "1234567890_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ:int," "`'!@#$%^&*()-=_+`:int>", type->toString()); std::string typeStr = "struct<`foo bar`:int,```quotes```:double,`abc``def````ghi`:float>"; type = Type::buildTypeFromString(typeStr); EXPECT_EQ(3, type->getSubtypeCount()); EXPECT_EQ("foo bar", type->getFieldName(0)); EXPECT_EQ("`quotes`", type->getFieldName(1)); EXPECT_EQ("abc`def``ghi", type->getFieldName(2)); EXPECT_EQ(typeStr, type->toString()); expectLogicErrorDuringParse("struct<``:int>", "Empty quoted field name."); expectLogicErrorDuringParse("struct<`col0:int>", "Invalid field name. Unmatched quote"); } void testCorruptHelper(const proto::Type& type, const proto::Footer& footer, const char* errMsg) { try { convertType(type, footer); FAIL() << "Should throw ParseError for ill types"; } catch (ParseError& e) { EXPECT_EQ(e.what(), std::string(errMsg)); } catch (...) { FAIL() << "Should only throw ParseError for ill types"; } } TEST(TestType, testCorruptNestType) { proto::Footer footer; // not used proto::Type illListType; illListType.set_kind(proto::Type_Kind_LIST); testCorruptHelper(illListType, footer, "Illegal LIST type that doesn't contain one subtype"); illListType.add_subtypes(2); illListType.add_subtypes(3); testCorruptHelper(illListType, footer, "Illegal LIST type that doesn't contain one subtype"); proto::Type illMapType; illMapType.set_kind(proto::Type_Kind_MAP); illMapType.add_subtypes(2); testCorruptHelper(illMapType, footer, "Illegal MAP type that doesn't contain two subtypes"); illMapType.add_subtypes(3); illMapType.add_subtypes(4); testCorruptHelper(illMapType, footer, "Illegal MAP type that doesn't contain two subtypes"); proto::Type illUnionType; illUnionType.set_kind(proto::Type_Kind_UNION); testCorruptHelper(illUnionType, footer, "Illegal UNION type that doesn't contain any subtypes"); proto::Type illStructType; proto::Type structType; illStructType.set_kind(proto::Type_Kind_STRUCT); structType.set_kind(proto::Type_Kind_STRUCT); structType.add_subtypes(0); // construct a loop back to root structType.add_fieldnames("root"); illStructType.add_subtypes(1); illStructType.add_fieldnames("f1"); illStructType.add_subtypes(2); *(footer.add_types()) = illStructType; *(footer.add_types()) = structType; testCorruptHelper(illStructType, footer, "Illegal STRUCT type that contains less fieldnames than subtypes"); } void expectParseError(const proto::Footer& footer, const char* errMsg) { try { checkProtoTypes(footer); FAIL() << "Should throw ParseError for ill ids"; } catch (ParseError& e) { EXPECT_EQ(e.what(), std::string(errMsg)); } catch (...) { FAIL() << "Should only throw ParseError for ill ids"; } } TEST(TestType, testCheckProtoTypes) { proto::Footer footer; proto::Type rootType; expectParseError(footer, "Footer is corrupt: no types found"); rootType.set_kind(proto::Type_Kind_STRUCT); rootType.add_subtypes(1); // add a non existent type id rootType.add_fieldnames("f1"); *(footer.add_types()) = rootType; expectParseError(footer, "Footer is corrupt: types(1) not exists"); footer.clear_types(); rootType.clear_subtypes(); rootType.clear_fieldnames(); proto::Type structType; structType.set_kind(proto::Type_Kind_STRUCT); structType.add_subtypes(0); // construct a loop back to root structType.add_fieldnames("root"); rootType.add_subtypes(1); rootType.add_fieldnames("f1"); *(footer.add_types()) = rootType; *(footer.add_types()) = structType; expectParseError(footer, "Footer is corrupt: malformed link from type 1 to 0"); footer.clear_types(); rootType.clear_subtypes(); rootType.clear_fieldnames(); proto::Type listType; listType.set_kind(proto::Type_Kind_LIST); proto::Type mapType; mapType.set_kind(proto::Type_Kind_MAP); proto::Type unionType; unionType.set_kind(proto::Type_Kind_UNION); rootType.add_fieldnames("f1"); rootType.add_subtypes(1); // 0 -> 1 listType.add_subtypes(2); // 1 -> 2 mapType.add_subtypes(3); // 2 -> 3 unionType.add_subtypes(1); // 3 -> 1 *(footer.add_types()) = rootType; // 0 *(footer.add_types()) = listType; // 1 *(footer.add_types()) = mapType; // 2 *(footer.add_types()) = unionType; // 3 expectParseError(footer, "Footer is corrupt: malformed link from type 3 to 1"); footer.clear_types(); rootType.clear_subtypes(); rootType.clear_fieldnames(); proto::Type intType; intType.set_kind(proto::Type_Kind_INT); proto::Type strType; strType.set_kind(proto::Type_Kind_STRING); rootType.add_subtypes(2); rootType.add_fieldnames("f2"); rootType.add_subtypes(1); rootType.add_fieldnames("f1"); *(footer.add_types()) = rootType; *(footer.add_types()) = intType; *(footer.add_types()) = strType; expectParseError(footer, "Footer is corrupt: subType(0) >= subType(1) in types(0). (2 >= 1)"); footer.clear_types(); rootType.clear_subtypes(); rootType.clear_fieldnames(); rootType.set_kind(proto::Type_Kind_STRUCT); rootType.add_subtypes(1); *(footer.add_types()) = rootType; *(footer.add_types()) = intType; expectParseError(footer, "Footer is corrupt: STRUCT type 0 has 1 subTypes, but has 0 fieldNames"); // Should pass the check after adding the field name footer.clear_types(); rootType.add_fieldnames("f1"); *(footer.add_types()) = rootType; *(footer.add_types()) = intType; checkProtoTypes(footer); } } // namespace orc
def connect(self, host, port): self._logger.info('Connecting with server on {}:{}'.format(host, port)) self.server_address = (host, port) self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self._socket.connect((host, port)) except socket.error: self._logger.error( 'An error has ocurred connecting to the server address', exc_info=True) self._socket.close() raise self._logger.info('Connection established')
/* Simple DirectMedia Layer Copyright (C) 1997-2020 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef SDL_BWin_h_ #define SDL_BWin_h_ #ifdef __cplusplus extern "C" { #endif #include "../../SDL_internal.h" #include "SDL.h" #include "SDL_syswm.h" #include "SDL_bframebuffer.h" #ifdef __cplusplus } #endif #include <stdio.h> #include <AppKit.h> #include <InterfaceKit.h> #include <game/DirectWindow.h> #if SDL_VIDEO_OPENGL #include <opengl/GLView.h> #endif #include "SDL_events.h" #include "../../main/haiku/SDL_BApp.h" enum WinCommands { BWIN_MOVE_WINDOW, BWIN_RESIZE_WINDOW, BWIN_SHOW_WINDOW, BWIN_HIDE_WINDOW, BWIN_MAXIMIZE_WINDOW, BWIN_MINIMIZE_WINDOW, BWIN_RESTORE_WINDOW, BWIN_SET_TITLE, BWIN_SET_BORDERED, BWIN_SET_RESIZABLE, BWIN_FULLSCREEN }; class SDL_BWin:public BDirectWindow { public: /* Constructor/Destructor */ SDL_BWin(BRect bounds, window_look look, uint32 flags) : BDirectWindow(bounds, "Untitled", look, B_NORMAL_WINDOW_FEEL, flags) { _last_buttons = 0; #if SDL_VIDEO_OPENGL _SDL_GLView = NULL; _gl_type = 0; #endif _shown = false; _inhibit_resize = false; _mouse_focused = false; _prev_frame = NULL; /* Handle framebuffer stuff */ _connected = _connection_disabled = false; _buffer_created = _buffer_dirty = false; _trash_window_buffer = false; _buffer_locker = new BLocker(); _bitmap = NULL; _clips = NULL; _num_clips = 0; #ifdef DRAWTHREAD _draw_thread_id = spawn_thread(HAIKU_DrawThread, "drawing_thread", B_NORMAL_PRIORITY, (void*) this); resume_thread(_draw_thread_id); #endif } virtual ~ SDL_BWin() { Lock(); _connection_disabled = true; int32 result; #if SDL_VIDEO_OPENGL if (_SDL_GLView) { _SDL_GLView->UnlockGL(); RemoveChild(_SDL_GLView); /* Why was this outside the if statement before? */ } #endif Unlock(); #if SDL_VIDEO_OPENGL if (_SDL_GLView) { delete _SDL_GLView; } #endif delete _prev_frame; /* Clean up framebuffer stuff */ _buffer_locker->Lock(); #ifdef DRAWTHREAD wait_for_thread(_draw_thread_id, &result); #endif free(_clips); delete _buffer_locker; } /* * * * * OpenGL functionality * * * * */ #if SDL_VIDEO_OPENGL virtual BGLView *CreateGLView(Uint32 gl_flags) { Lock(); if (_SDL_GLView == NULL) { _SDL_GLView = new BGLView(Bounds(), "SDL GLView", B_FOLLOW_ALL_SIDES, (B_WILL_DRAW | B_FRAME_EVENTS), gl_flags); _gl_type = gl_flags; } AddChild(_SDL_GLView); _SDL_GLView->SetEventMask(B_POINTER_EVENTS | B_KEYBOARD_EVENTS, B_NO_POINTER_HISTORY); _SDL_GLView->EnableDirectMode(true); _SDL_GLView->LockGL(); /* "New" GLViews are created */ Unlock(); return (_SDL_GLView); } virtual void RemoveGLView() { Lock(); if(_SDL_GLView) { _SDL_GLView->UnlockGL(); RemoveChild(_SDL_GLView); } Unlock(); } virtual void SwapBuffers(void) { _SDL_GLView->UnlockGL(); _SDL_GLView->LockGL(); _SDL_GLView->SwapBuffers(); } #endif /* * * * * Framebuffering* * * * */ virtual void DirectConnected(direct_buffer_info *info) { if(!_connected && _connection_disabled) { return; } /* Determine if the pixel buffer is usable after this update */ _trash_window_buffer = _trash_window_buffer || ((info->buffer_state & B_BUFFER_RESIZED) || (info->buffer_state & B_BUFFER_RESET) || (info->driver_state == B_MODE_CHANGED)); LockBuffer(); switch(info->buffer_state & B_DIRECT_MODE_MASK) { case B_DIRECT_START: _connected = true; case B_DIRECT_MODIFY: if (info->clip_list_count > _num_clips) { if(_clips) { free(_clips); _clips = NULL; } } _num_clips = info->clip_list_count; if (_clips == NULL) _clips = (clipping_rect *)malloc(_num_clips*sizeof(clipping_rect)); if(_clips) { memcpy(_clips, info->clip_list, _num_clips*sizeof(clipping_rect)); _bits = (uint8*) info->bits; _row_bytes = info->bytes_per_row; _bounds = info->window_bounds; _bytes_per_px = info->bits_per_pixel / 8; _buffer_dirty = true; } break; case B_DIRECT_STOP: _connected = false; break; } #if SDL_VIDEO_OPENGL if(_SDL_GLView) { _SDL_GLView->DirectConnected(info); } #endif /* Call the base object directconnected */ BDirectWindow::DirectConnected(info); UnlockBuffer(); } /* * * * * Event sending * * * * */ /* Hook functions */ virtual void FrameMoved(BPoint origin) { /* Post a message to the BApp so that it can handle the window event */ BMessage msg(BAPP_WINDOW_MOVED); msg.AddInt32("window-x", (int)origin.x); msg.AddInt32("window-y", (int)origin.y); _PostWindowEvent(msg); /* Perform normal hook operations */ BDirectWindow::FrameMoved(origin); } virtual void FrameResized(float width, float height) { /* Post a message to the BApp so that it can handle the window event */ BMessage msg(BAPP_WINDOW_RESIZED); msg.AddInt32("window-w", (int)width + 1); msg.AddInt32("window-h", (int)height + 1); _PostWindowEvent(msg); /* Perform normal hook operations */ BDirectWindow::FrameResized(width, height); } virtual bool QuitRequested() { BMessage msg(BAPP_WINDOW_CLOSE_REQUESTED); _PostWindowEvent(msg); /* We won't allow a quit unless asked by DestroyWindow() */ return false; } virtual void WindowActivated(bool active) { BMessage msg(BAPP_KEYBOARD_FOCUS); /* Mouse focus sold separately */ msg.AddBool("focusGained", active); _PostWindowEvent(msg); } virtual void Zoom(BPoint origin, float width, float height) { BMessage msg(BAPP_MAXIMIZE); /* Closest thing to maximization Haiku has */ _PostWindowEvent(msg); /* Before the window zooms, record its size */ if( !_prev_frame ) _prev_frame = new BRect(Frame()); /* Perform normal hook operations */ BDirectWindow::Zoom(origin, width, height); } /* Member functions */ virtual void Show() { while(IsHidden()) { BDirectWindow::Show(); } _shown = true; BMessage msg(BAPP_SHOW); _PostWindowEvent(msg); } virtual void Hide() { BDirectWindow::Hide(); _shown = false; BMessage msg(BAPP_HIDE); _PostWindowEvent(msg); } virtual void Minimize(bool minimize) { BDirectWindow::Minimize(minimize); int32 minState = (minimize ? BAPP_MINIMIZE : BAPP_RESTORE); BMessage msg(minState); _PostWindowEvent(msg); } /* BView message interruption */ virtual void DispatchMessage(BMessage * msg, BHandler * target) { BPoint where; /* Used by mouse moved */ int32 buttons; /* Used for mouse button events */ int32 key; /* Used for key events */ switch (msg->what) { case B_MOUSE_MOVED: int32 transit; if (msg->FindPoint("where", &where) == B_OK && msg->FindInt32("be:transit", &transit) == B_OK) { _MouseMotionEvent(where, transit); } break; case B_MOUSE_DOWN: if (msg->FindInt32("buttons", &buttons) == B_OK) { _MouseButtonEvent(buttons, SDL_PRESSED); } break; case B_MOUSE_UP: if (msg->FindInt32("buttons", &buttons) == B_OK) { _MouseButtonEvent(buttons, SDL_RELEASED); } break; case B_MOUSE_WHEEL_CHANGED: float x, y; if (msg->FindFloat("be:wheel_delta_x", &x) == B_OK && msg->FindFloat("be:wheel_delta_y", &y) == B_OK) { _MouseWheelEvent((int)x, (int)y); } break; case B_KEY_DOWN: { int32 i = 0; int8 byte; int8 bytes[4] = { 0, 0, 0, 0 }; while (i < 4 && msg->FindInt8("byte", i, &byte) == B_OK) { bytes[i] = byte; i++; } if (msg->FindInt32("key", &key) == B_OK) { _KeyEvent((SDL_Scancode)key, &bytes[0], i, SDL_PRESSED); } } break; case B_UNMAPPED_KEY_DOWN: /* modifier keys are unmapped */ if (msg->FindInt32("key", &key) == B_OK) { _KeyEvent((SDL_Scancode)key, NULL, 0, SDL_PRESSED); } break; case B_KEY_UP: case B_UNMAPPED_KEY_UP: /* modifier keys are unmapped */ if (msg->FindInt32("key", &key) == B_OK) { _KeyEvent(key, NULL, 0, SDL_RELEASED); } break; default: /* move it after switch{} so it's always handled that way we keep Haiku features like: - CTRL+Q to close window (and other shortcuts) - PrintScreen to make screenshot into /boot/home - etc.. */ /* BDirectWindow::DispatchMessage(msg, target); */ break; } BDirectWindow::DispatchMessage(msg, target); } /* Handle command messages */ virtual void MessageReceived(BMessage* message) { switch (message->what) { /* Handle commands from SDL */ case BWIN_SET_TITLE: _SetTitle(message); break; case BWIN_MOVE_WINDOW: _MoveTo(message); break; case BWIN_RESIZE_WINDOW: _ResizeTo(message); break; case BWIN_SET_BORDERED: _SetBordered(message); break; case BWIN_SET_RESIZABLE: _SetResizable(message); break; case BWIN_SHOW_WINDOW: Show(); break; case BWIN_HIDE_WINDOW: Hide(); break; case BWIN_MAXIMIZE_WINDOW: BWindow::Zoom(); break; case BWIN_MINIMIZE_WINDOW: Minimize(true); break; case BWIN_RESTORE_WINDOW: _Restore(); break; case BWIN_FULLSCREEN: _SetFullScreen(message); break; default: /* Perform normal message handling */ BDirectWindow::MessageReceived(message); break; } } /* Accessor methods */ bool IsShown() { return _shown; } int32 GetID() { return _id; } uint32 GetRowBytes() { return _row_bytes; } int32 GetFbX() { return _bounds.left; } int32 GetFbY() { return _bounds.top; } bool ConnectionEnabled() { return !_connection_disabled; } bool Connected() { return _connected; } clipping_rect *GetClips() { return _clips; } int32 GetNumClips() { return _num_clips; } uint8* GetBufferPx() { return _bits; } int32 GetBytesPerPx() { return _bytes_per_px; } bool CanTrashWindowBuffer() { return _trash_window_buffer; } bool BufferExists() { return _buffer_created; } bool BufferIsDirty() { return _buffer_dirty; } BBitmap *GetBitmap() { return _bitmap; } #if SDL_VIDEO_OPENGL BGLView *GetGLView() { return _SDL_GLView; } Uint32 GetGLType() { return _gl_type; } #endif /* Setter methods */ void SetID(int32 id) { _id = id; } void SetBufferExists(bool bufferExists) { _buffer_created = bufferExists; } void LockBuffer() { _buffer_locker->Lock(); } void UnlockBuffer() { _buffer_locker->Unlock(); } void SetBufferDirty(bool bufferDirty) { _buffer_dirty = bufferDirty; } void SetTrashBuffer(bool trash) { _trash_window_buffer = trash; } void SetBitmap(BBitmap *bitmap) { _bitmap = bitmap; } private: /* Event redirection */ void _MouseMotionEvent(BPoint &where, int32 transit) { if(transit == B_EXITED_VIEW) { /* Change mouse focus */ if(_mouse_focused) { _MouseFocusEvent(false); } } else { /* Change mouse focus */ if (!_mouse_focused) { _MouseFocusEvent(true); } BMessage msg(BAPP_MOUSE_MOVED); msg.AddInt32("x", (int)where.x); msg.AddInt32("y", (int)where.y); _PostWindowEvent(msg); } } void _MouseFocusEvent(bool focusGained) { _mouse_focused = focusGained; BMessage msg(BAPP_MOUSE_FOCUS); msg.AddBool("focusGained", focusGained); _PostWindowEvent(msg); /* FIXME: Why were these here? if false: be_app->SetCursor(B_HAND_CURSOR); if true: SDL_SetCursor(NULL); */ } void _MouseButtonEvent(int32 buttons, Uint8 state) { int32 buttonStateChange = buttons ^ _last_buttons; if(buttonStateChange & B_PRIMARY_MOUSE_BUTTON) { _SendMouseButton(SDL_BUTTON_LEFT, state); } if(buttonStateChange & B_SECONDARY_MOUSE_BUTTON) { _SendMouseButton(SDL_BUTTON_RIGHT, state); } if(buttonStateChange & B_TERTIARY_MOUSE_BUTTON) { _SendMouseButton(SDL_BUTTON_MIDDLE, state); } _last_buttons = buttons; } void _SendMouseButton(int32 button, int32 state) { BMessage msg(BAPP_MOUSE_BUTTON); msg.AddInt32("button-id", button); msg.AddInt32("button-state", state); _PostWindowEvent(msg); } void _MouseWheelEvent(int32 x, int32 y) { /* Create a message to pass along to the BeApp thread */ BMessage msg(BAPP_MOUSE_WHEEL); msg.AddInt32("xticks", x); msg.AddInt32("yticks", y); _PostWindowEvent(msg); } void _KeyEvent(int32 keyCode, const int8 *keyUtf8, const ssize_t & len, int32 keyState) { /* Create a message to pass along to the BeApp thread */ BMessage msg(BAPP_KEY); msg.AddInt32("key-state", keyState); msg.AddInt32("key-scancode", keyCode); if (keyUtf8 != NULL) { msg.AddData("key-utf8", B_INT8_TYPE, (const void*)keyUtf8, len); } be_app->PostMessage(&msg); } void _RepaintEvent() { /* Force a repaint: Call the SDL exposed event */ BMessage msg(BAPP_REPAINT); _PostWindowEvent(msg); } void _PostWindowEvent(BMessage &msg) { msg.AddInt32("window-id", _id); be_app->PostMessage(&msg); } /* Command methods (functions called upon by SDL) */ void _SetTitle(BMessage *msg) { const char *title; if( msg->FindString("window-title", &title) != B_OK ) { return; } SetTitle(title); } void _MoveTo(BMessage *msg) { int32 x, y; if( msg->FindInt32("window-x", &x) != B_OK || msg->FindInt32("window-y", &y) != B_OK ) { return; } MoveTo(x, y); } void _ResizeTo(BMessage *msg) { int32 w, h; if( msg->FindInt32("window-w", &w) != B_OK || msg->FindInt32("window-h", &h) != B_OK ) { return; } ResizeTo(w, h); } void _SetBordered(BMessage *msg) { bool bEnabled; if(msg->FindBool("window-border", &bEnabled) != B_OK) { return; } SetLook(bEnabled ? B_TITLED_WINDOW_LOOK : B_NO_BORDER_WINDOW_LOOK); } void _SetResizable(BMessage *msg) { bool bEnabled; if(msg->FindBool("window-resizable", &bEnabled) != B_OK) { return; } if (bEnabled) { SetFlags(Flags() & ~(B_NOT_RESIZABLE | B_NOT_ZOOMABLE)); } else { SetFlags(Flags() | (B_NOT_RESIZABLE | B_NOT_ZOOMABLE)); } } void _Restore() { if(IsMinimized()) { Minimize(false); } else if(IsHidden()) { Show(); } else if(_prev_frame != NULL) { /* Zoomed */ MoveTo(_prev_frame->left, _prev_frame->top); ResizeTo(_prev_frame->Width(), _prev_frame->Height()); } } void _SetFullScreen(BMessage *msg) { bool fullscreen; if( msg->FindBool("fullscreen", &fullscreen) != B_OK ) { return; } SetFullScreen(fullscreen); } /* Members */ #if SDL_VIDEO_OPENGL BGLView * _SDL_GLView; Uint32 _gl_type; #endif int32 _last_buttons; int32 _id; /* Window id used by SDL_BApp */ bool _mouse_focused; /* Does this window have mouse focus? */ bool _shown; bool _inhibit_resize; BRect *_prev_frame; /* Previous position and size of the window */ /* Framebuffer members */ bool _connected, _connection_disabled, _buffer_created, _buffer_dirty, _trash_window_buffer; uint8 *_bits; uint32 _row_bytes; clipping_rect _bounds; BLocker *_buffer_locker; clipping_rect *_clips; uint32 _num_clips; int32 _bytes_per_px; thread_id _draw_thread_id; BBitmap *_bitmap; }; /* FIXME: * An explanation of framebuffer flags. * * _connected - Original variable used to let the drawing thread know * when changes are being made to the other framebuffer * members. * _connection_disabled - Used to signal to the drawing thread that the window * is closing, and the thread should exit. * _buffer_created - True if the current buffer is valid * _buffer_dirty - True if the window should be redrawn. * _trash_window_buffer - True if the window buffer needs to be trashed partway * through a draw cycle. Occurs when the previous * buffer provided by DirectConnected() is invalidated. */ #endif /* SDL_BWin_h_ */ /* vi: set ts=4 sw=4 expandtab: */
package frc.math; public class Vector { public double x; public double y; public Vector(double x, double y) { this.x = x; this.y = y; } public Vector add(Vector v) { return new Vector(x + v.x, y + v.y); } public Vector subtract(Vector v) { return new Vector(x - v.x, y - v.y); } public Vector multiply(double a) { return new Vector (x*a, y*a); } public Vector divide(double a) { return new Vector (x/a, y/a); } public double magnitude() { return Math.sqrt(x*x + y*y); } public Vector normalized() { return divide(magnitude()); } public Vector rotate(double theta) { double newX = (x * Math.cos(Math.toRadians(theta))) - (y * Math.sin(Math.toRadians(theta))); double newY = (x * Math.sin(Math.toRadians(theta))) + (y * Math.cos(Math.toRadians(theta))); return new Vector(newX, newY); } public Vector copy() { return new Vector(x, y); } public boolean equals(Object obj) { if (!(obj instanceof Vector)) { return false; } Vector other = (Vector) obj; return Math.abs(other.x - x) < 0.01 && Math.abs(other.y - y) < 0.01; } public String toString() { return x + ", " + y; } }
I have a fear of flying. When I travel, I do it by car. One of the many joys of driving across the States is checking out local restaurants, junk shops and record stores. So having a GPS-based record store locator in my cell phone is an utterly cool app that I can get behind. The Vinyl District has created software for the iPhone and Android that will lead you to indie record stores throughout the United States and United Kingdom. And it’s free. All you need to know about downloading the record store locator is at The Vinyl District’s website. This is a great tool, not only for music freaks, but for the surviving record stores out there. Technology doin’ the right thing. Put some good karma in that irritating plastic rectangle in your pocket. Thanks to Tim Broun
<reponame>IcePigZDB/pd<gh_stars>100-1000 // Copyright 2021 TiKV Project Authors. // // 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 checker import ( "github.com/pingcap/kvproto/pkg/pdpb" "github.com/pingcap/log" "github.com/tikv/pd/pkg/errs" "github.com/tikv/pd/server/core" "github.com/tikv/pd/server/schedule" "github.com/tikv/pd/server/schedule/labeler" "github.com/tikv/pd/server/schedule/operator" "github.com/tikv/pd/server/schedule/placement" ) // SplitChecker splits regions when the key range spans across rule/label boundary. type SplitChecker struct { PauseController cluster schedule.Cluster ruleManager *placement.RuleManager labeler *labeler.RegionLabeler } // NewSplitChecker creates a new SplitChecker. func NewSplitChecker(cluster schedule.Cluster, ruleManager *placement.RuleManager, labeler *labeler.RegionLabeler) *SplitChecker { return &SplitChecker{ cluster: cluster, ruleManager: ruleManager, labeler: labeler, } } // GetType returns the checker type. func (c *SplitChecker) GetType() string { return "split-checker" } // Check checks whether the region need to split and returns Operator to fix. func (c *SplitChecker) Check(region *core.RegionInfo) *operator.Operator { checkerCounter.WithLabelValues("split_checker", "check").Inc() if c.IsPaused() { checkerCounter.WithLabelValues("split_checker", "paused").Inc() return nil } start, end := region.GetStartKey(), region.GetEndKey() // We may consider to merge labeler split keys and rule split keys together // before creating operator. It can help to reduce operator count. However, // handle them separately helps to understand the reason for the split. desc := "labeler-split-region" keys := c.labeler.GetSplitKeys(start, end) if len(keys) == 0 && c.cluster.GetOpts().IsPlacementRulesEnabled() { desc = "rule-split-region" keys = c.ruleManager.GetSplitKeys(start, end) } if len(keys) == 0 { return nil } op, err := operator.CreateSplitRegionOperator(desc, region, 0, pdpb.CheckPolicy_USEKEY, keys) if err != nil { log.Debug("create split region operator failed", errs.ZapError(err)) return nil } return op }
/** * This class is just a simple wrapper for the API defined in the blog * article. Basically all it does is creating a JSON Object to request * the recognition and waits (synchronously) for the result. * * */ public class RecognitionAPI { private static final String TAG = RecognitionAPI.class.getName(); private static final String RECOGNITION_API_URL = "http://192.168.178.21:5050/predict"; public static String requestRecognition(Bitmap bitmap) throws Exception { String result = new String(); try { JSONObject jsonRequest = constructPredictionRequest(bitmap); HttpResponse response = makeSynchronousRequest(jsonRequest); result = evaluateResponse(response); } catch (Exception e) { Log.e(TAG, "Recognition failed!", e); throw e; } return result; } private static HttpResponse makeSynchronousRequest(JSONObject jsonRequest) throws IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(RECOGNITION_API_URL); httpPost.setEntity(new StringEntity(jsonRequest.toString())); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); return httpClient.execute(httpPost); } private static String evaluateResponse(HttpResponse response) throws IOException, JSONException { String result = new String(); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String entityContent = readEntityContentToString(entity); JSONObject jsonResponse = new JSONObject(entityContent); result = jsonResponse.getString("name"); } return result; } private static String readEntityContentToString(HttpEntity entity) throws IOException { StringBuilder result = new StringBuilder(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { result.append(line); } return result.toString(); } private static JSONObject constructPredictionRequest(Bitmap bitmap) throws JSONException { String base64encBitmap = ImageHelper.getBase64Jpeg(bitmap, 100); // Now create the object: JSONObject jsonObject = new JSONObject(); try { jsonObject.put("image", base64encBitmap); } catch (JSONException e) { Log.e(TAG, "Could not create Json object", e); throw e; } return jsonObject; } }
<reponame>yuyumimi/mic package com.mic.demo.service; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import org.springframework.stereotype.Service; @Service public class TestService { @SentinelResource(value = "sayHello") public String sayHello(String name)throws BlockException { int a=1/0; return "Hello, " + name; } }
/** * <p>An implementation of {@link Zombie.Configuration} which configures a custom {@link HttpClient} * to be used for executing requests with {@link ConfigEndpoint}.</p> * * @version 1.1.0 * <br><br> * @since 1.3.0 * <br><br> * @category test * <br><br> * @author <a href="http://sahan.me">Lahiru Sahan Jayasinghe</a> */ public class ZombieConfig extends Zombie.Configuration { @Override public HttpClient httpClient() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(params, 2 * 1000); //to simulate a socket timeout SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry); return new DefaultHttpClient(manager, params); } }
Always ready to up the body image ante, Vogue Italia's June issue celebrates curvy models, with a trio of plus-sized beauties posing for the cover. Tara Lynn , Candice Huffine and Robyn Lawley lean over plates of spaghetti in their lingerie, and inside, Marquita Pring is added to the mix for Steven Meisel's lens. The glossy's editor-in-chief Franca Sozzani recently told Women's Wear Daily, "We help [plus-size women] dress fashionably. We say: It's pointless for you to buy leggings, take this because this will look good on you. We help them choose. We don't talk about diets because they don't want to be on a diet, but it's not a ghetto. Why should these women slim down? Many of the women who have a few extra kilos are especially beautiful and also more feminine."
/** * Cria animais a partir de uma lista de forma transacional * @param animals * @return */ @PostMapping("/animais/lista") @Transactional public ResponseEntity<Object> createAnimais(@Validated @RequestBody Animais animais){ try { animalRepository.saveAll(animais.getAnimais()); } catch (Exception e) { return ResponseEntity.badRequest().body("Erro ao processar a lista. Nenhum registro persistido."); } StatusMessageResponse retorno = new StatusMessageResponse(); retorno.setMensagem("Inserido com sucesso"); return ResponseEntity.ok(animais); }
<reponame>Etchelon/gaiaproject<filename>Frontend/StarGate/src/frame/drawer/AppDrawer.tsx import { useAuth0 } from "@auth0/auth0-react"; import Divider from "@material-ui/core/Divider"; import List from "@material-ui/core/List"; import GamesIcon from "@material-ui/icons/Games"; import HistoryIcon from "@material-ui/icons/History"; import HomeIcon from "@material-ui/icons/Home"; import _ from "lodash"; import { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { UserInfoDto } from "../../dto/interfaces"; import ListItemLink from "../../utils/ListItemLink"; import { Nullable } from "../../utils/miscellanea"; import userInfoService from "../../utils/user-info.service"; import useStyles from "../appFrame.styles"; import { loadUserPreferences, selectUserPreferences } from "../store/active-user.slice"; import { ActiveUserState } from "../store/types"; import UserBox from "./user-box/UserBox"; interface AppSection { label: string; route: string; icon?: JSX.Element; protected?: boolean; } const APP_SECTIONS: AppSection[] = [ { label: "Home", route: "/", icon: <HomeIcon />, protected: true }, { label: "Games", route: "/games", icon: <GamesIcon />, protected: true }, { label: "History", route: "/history", icon: <HistoryIcon />, protected: true }, ]; const storageKey = (userId: string) => `USER_PREFERENCES_${userId}`; const AppDrawer = () => { const classes = useStyles(); const { isAuthenticated, user: auth0User } = useAuth0(); const [userInfo, setUserInfo] = useState<Nullable<UserInfoDto>>(null); const dispatch = useDispatch(); const userPreferences = useSelector(selectUserPreferences); useEffect(() => { if (!isAuthenticated) { return; } const userPreferencesStr = window.localStorage.getItem(storageKey(auth0User.sub)); if (userPreferencesStr) { const userPreferences_ = JSON.parse(userPreferencesStr) as ActiveUserState; dispatch(loadUserPreferences(userPreferences_)); } }, []); useEffect(() => { const sub = userInfoService.userInfo$.subscribe(user => setUserInfo(user)); return () => { sub.unsubscribe(); }; }, []); useEffect(() => { if (!isAuthenticated) { return; } const userPreferencesStr = JSON.stringify(userPreferences); window.localStorage.setItem(storageKey(auth0User.sub), userPreferencesStr); }, [isAuthenticated, userPreferences]); return ( <div className={classes.appDrawer}> <div className={classes.toolbar} /> <List> {_.chain(APP_SECTIONS) .filter(section => isAuthenticated || !section.protected) .map(section => <ListItemLink button key={section.label} primary={section.label} icon={section.icon} to={section.route} />) .value()} </List> <div className={classes.divider}> <Divider /> </div> <UserBox user={userInfo} /> </div> ); }; export default AppDrawer;
def create_stm_slice(d: Dict[str, DataFrame], start_index, slice_width, tensor_shape) -> Tuple[List[Tensor], np.array, Tensor, np.float64, timestamps.Timestamp]: dict_stm = copy.deepcopy(d) idcs = dict_stm.keys() for idx in idcs: dict_stm[idx] = dict_stm[idx][start_index: start_index + slice_width] slice_as_3d_np_arr = np.zeros([slice_width] + tensor_shape[1:]) for i, idx in enumerate(idcs): slice_as_3d_np_arr[:, :, i] = np.array(dict_stm[idx].drop("Label", axis=1)) xs_train: List[Tensor] = [] n_tensors: int = slice_width - tensor_shape[0] + 1 y_train: np.array = np.zeros(n_tensors - 1) xs_test: Tensor y_test: np.float64 for i in range(n_tensors): upper_idx = i + tensor_shape[0] if i < n_tensors - 1: xs_train.append(Tensor(slice_as_3d_np_arr[i: upper_idx, :, :])) y_train[i] = dict_stm["Price"]["Label"][upper_idx - 1] else: xs_test = Tensor(slice_as_3d_np_arr[i: upper_idx, :, :]) y_test = dict_stm["Price"]["Label"][upper_idx - 1] associated_index: timestamps.Timestamp = dict_stm["Price"].iloc[-2].name return xs_train, y_train, xs_test, y_test, associated_index
<reponame>webji/cmdbuildpy from .request import Request from .sessions import Sessions from .classes import Classes from .cards import ClassesCards from .lookuptypes import LookupTypes
/** * An near cache listener that eagerly populates the near cache as cache * entries are created/modified in the server. It uses a converter in order * to ship value and version information as well as the key. To avoid sharing * classes between client and server, it uses raw data in the converter. * This listener does not apply any filtering, so all keys are considered. */ @Deprecated @ClientListener(converterFactoryName = "___eager-key-value-version-converter", useRawData = true) private static class EagerNearCacheListener<K, V> { private static final Log log = LogFactory.getLog(EagerNearCacheListener.class); private final NearCache<K, V> cache; private final Marshaller marshaller; private EagerNearCacheListener(NearCache<K, V> cache, Marshaller marshaller) { this.cache = cache; this.marshaller = marshaller; } @ClientCacheEntryCreated @ClientCacheEntryModified @SuppressWarnings("unused") public void handleCreatedModifiedEvent(ClientCacheEntryCustomEvent<byte[]> e) { ByteBuffer in = ByteBuffer.wrap(e.getEventData()); byte[] keyBytes = extractElement(in); byte[] valueBytes = extractElement(in); K key = unmarshallObject(keyBytes, "key"); V value = unmarshallObject(valueBytes, "value"); long version = in.getLong(); if (key != null && value != null) { VersionedValueImpl<V> entry = new VersionedValueImpl<>(version, value); cache.put(key, entry); } } @SuppressWarnings("unchecked") private <T> T unmarshallObject(byte[] bytes, String element) { try { return (T) marshaller.objectFromByteBuffer(bytes); } catch (Exception e) { log.unableToUnmarshallBytesError(element, Util.toStr(bytes), e); return null; } } @ClientCacheEntryRemoved @SuppressWarnings("unused") public void handleRemovedEvent(ClientCacheEntryCustomEvent<byte[]> e) { ByteBuffer in = ByteBuffer.wrap(e.getEventData()); byte[] keyBytes = extractElement(in); K key = unmarshallObject(keyBytes, "key"); if (key != null) { cache.remove(key); } } @ClientCacheFailover @SuppressWarnings("unused") public void handleFailover(ClientCacheFailoverEvent e) { if (log.isTraceEnabled()) log.trace("Clear near cache after fail-over of server"); cache.clear(); } private static byte[] extractElement(ByteBuffer in) { int length = UnsignedNumeric.readUnsignedInt(in); byte[] element = new byte[length]; in.get(element); return element; } }
<filename>System/Library/Frameworks/Foundation.framework/NSConcreteObservationBuffer.h /* * This header is generated by classdump-dyld 1.0 * on Sunday, June 7, 2020 at 11:12:24 AM Mountain Standard Time * Operating System: Version 13.4.5 (Build 17L562) * Image Source: /System/Library/Frameworks/Foundation.framework/Foundation * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <Foundation/Foundation-Structs.h> #import <Foundation/NSObservationBuffer.h> @protocol OS_dispatch_queue; @class NSObject, NSOperationQueue, NSMutableArray; @interface NSConcreteObservationBuffer : NSObservationBuffer { NSObject*<OS_dispatch_queue> _inputQueue; NSOperationQueue* _outputQueue; long long _policy; int _state; opaque_pthread_mutex_t _lock; NSMutableArray* _dequeue; unsigned long long _maxCount; /*^block*/id _bufferFullHandler; BOOL _memoryPressureSensitive; BOOL _automaticallyEmitsObjects; } -(void)dealloc; -(id)initWithMaximumObjectCount:(unsigned long long)arg1 fullPolicy:(long long)arg2 outputQueue:(id)arg3 ; -(void)_receiveBox:(id)arg1 ; -(void)_alreadyOnQueueEmitObject; -(void)_alreadyOnQueueEmitAllObjects; -(void)_mergeChanges; -(/*^block*/id)bufferFullHandler; -(void)emitObject; -(void)emitAllObjects; -(void)setBufferFullHandler:(/*^block*/id)arg1 ; -(BOOL)automaticallyEmitsObjects; -(void)setAutomaticallyEmitsObjects:(BOOL)arg1 ; -(BOOL)isMemoryPressureSensitive; -(void)setMemoryPressureSensitive:(BOOL)arg1 ; @end
// Convert workbench DBUser to RDR Model private RdrResearcher toRdrResearcher(DbUser dbUser) { RdrResearcher researcher = new RdrResearcher(); researcher.setUserId((int) dbUser.getUserId()); if (null != researcher.getCreationTime()) { researcher.setCreationTime(dbUser.getCreationTime().toLocalDateTime().atOffset(offset)); } researcher.setModifiedTime(dbUser.getLastModifiedTime().toLocalDateTime().atOffset(offset)); researcher.setGivenName(dbUser.getGivenName()); researcher.setFamilyName(dbUser.getFamilyName()); researcher.setDegrees( dbUser.getDegreesEnum().stream() .map(RdrExportEnums::degreeToRdrDegree) .collect(Collectors.toList())); if (dbUser.getContactEmail() != null) { researcher.setEmail(dbUser.getContactEmail()); } if (dbUser.getAddress() != null) { researcher.setStreetAddress1(dbUser.getAddress().getStreetAddress1()); researcher.setStreetAddress2(dbUser.getAddress().getStreetAddress2()); researcher.setCity(dbUser.getAddress().getCity()); researcher.setState(dbUser.getAddress().getState()); researcher.setCountry(dbUser.getAddress().getCountry()); researcher.setZipCode(dbUser.getAddress().getZipCode()); } DbDemographicSurvey dbDemographicSurvey = dbUser.getDemographicSurvey(); if (null != dbDemographicSurvey) { researcher.setDisability( RdrExportEnums.disabilityToRdrDisability(dbDemographicSurvey.getDisabilityEnum())); researcher.setEducation( RdrExportEnums.educationToRdrEducation(dbDemographicSurvey.getEducationEnum())); researcher.setEthnicity( Optional.ofNullable(dbDemographicSurvey.getEthnicityEnum()) .map(RdrExportEnums::ethnicityToRdrEthnicity) .orElse(null)); researcher.setSexAtBirth( Optional.ofNullable( dbDemographicSurvey.getSexAtBirthEnum().stream() .map(RdrExportEnums::sexAtBirthToRdrSexAtBirth) .collect(Collectors.toList())) .orElse(new ArrayList<>())); researcher.setGender( Optional.ofNullable( dbDemographicSurvey.getGenderIdentityEnumList().stream() .map(RdrExportEnums::genderToRdrGender) .collect(Collectors.toList())) .orElse(new ArrayList<>())); researcher.setDisability( RdrExportEnums.disabilityToRdrDisability(dbDemographicSurvey.getDisabilityEnum())); researcher.setRace( Optional.ofNullable( dbDemographicSurvey.getRaceEnum().stream() .map(RdrExportEnums::raceToRdrRace) .collect(Collectors.toList())) .orElse(new ArrayList<>())); researcher.setLgbtqIdentity(dbDemographicSurvey.getLgbtqIdentity()); researcher.setIdentifiesAsLgbtq(dbDemographicSurvey.getIdentifiesAsLgbtq()); } researcher.setAffiliations(Collections.emptyList()); verifiedInstitutionalAffiliationDao .findFirstByUser(dbUser) .ifPresent( verifiedInstitutionalAffiliation -> { final InstitutionalRole roleEnum = verifiedInstitutionalAffiliation.getInstitutionalRoleEnum(); final String role = (roleEnum == InstitutionalRole.OTHER) ? verifiedInstitutionalAffiliation.getInstitutionalRoleOtherText() : roleEnum.toString(); researcher.setVerifiedInstitutionalAffiliation( new ResearcherVerifiedInstitutionalAffiliation() .institutionShortName( verifiedInstitutionalAffiliation.getInstitution().getShortName()) .institutionDisplayName( verifiedInstitutionalAffiliation.getInstitution().getDisplayName()) .institutionalRole(role)); }); return researcher; }
/** * @author Lukas Eder */ abstract class AbstractFunction<T> extends AbstractField<T> implements QOM.Function<T> { private final boolean applySchemaMapping; AbstractFunction(Name name, DataType<T> type, boolean applySchemaMapping) { super(name, type); this.applySchemaMapping = applySchemaMapping; } @Override public final void accept(Context<?> ctx) { switch (ctx.family()) { default: { acceptFunctionName(ctx, applySchemaMapping, getQualifiedName()); ctx.sql('(').visit(arguments()).sql(')'); break; } } } static void acceptFunctionName(Context<?> ctx, boolean applySchemaMapping, Name name) { if (applySchemaMapping && name.qualified()) { Schema mapped = getMappedSchema(ctx, DSL.schema(name.qualifier())); if (mapped != null) ctx.visit(mapped.getQualifiedName().append(name.unqualifiedName())); else ctx.visit(name.unqualifiedName()); } else ctx.visit(name); } abstract QueryPart arguments(); // ------------------------------------------------------------------------- // XXX: Query Object Model // ------------------------------------------------------------------------- }
package ksatriya import ( "net/http" "testing" "github.com/stretchr/testify/assert" ) func TestRoot(t *testing.T) { // new root root := NewRoot() assert.Equal(t, RootPathDefault+"/*filepath", root.Path()) assert.Equal(t, http.Dir(RootDirDefault), root.Dir()) // set path root.SetPath("/public") assert.Equal(t, "/public/*filepath", root.Path()) // set dir root.SetDir("public") assert.Equal(t, http.Dir("public"), root.Dir()) }
/** * Restores the property that the current left match ends where the current * right matches begin. * * The spans are assumed to be already in the same doc. * * If they're already aligned, this function does nothing. If they're out of * alignment (that is, left.end() != right.start()), advance the spans that is * lagging. Repeat until they are aligned, or one of the spans run out. * * After this function, we're on the first valid match found, or we're out of * matches for this document. * * @throws IOException */ private void realignPos() throws IOException { int leftEnd = left.endPosition(); int rightStart = right.startPosition(0); rightEnd = right.endPosition(0); indexInBucket = 0; while (leftEnd != rightStart) { if (rightStart < leftEnd) { while (rightStart < leftEnd) { int rightDoc = right.advanceBucket(leftEnd); if (rightDoc == SpansInBuckets.NO_MORE_BUCKETS) { leftStart = rightEnd = NO_MORE_POSITIONS; return; } rightStart = right.startPosition(0); rightEnd = right.endPosition(0); indexInBucket = 0; } } else { while (leftEnd < rightStart) { leftStart = left.nextStartPosition(); leftEnd = left.endPosition(); if (leftStart == NO_MORE_POSITIONS) { rightEnd = NO_MORE_POSITIONS; return; } } } } }
<filename>usr/src/servers/pm/calc_tables.c<gh_stars>1-10 #include <stdio.h> #include "pm.h" /* * calc_tables -- system call CALCTABLES (calc_tables) implementation * * Author Name : <NAME> * Course Name : CSC 502 : Principles of OS & Distributed Systems * Professor Name : Dr. <NAME> */ int calc_tables() { /* m_in is a global variable set to PM's incoming message. * m_in.m1_i1, m_in.m1_i2 and m_in.m1_i3 are the integer * parameter set in user library */ int i = m_in.m1_i1; int j = m_in.m1_i2; int k = m_in.m1_i3; printf("\n\nSYSTEM CALL CALCTABLES invoked (ITEMS=%d OPT_1=%d OPT_2=%d)\n\n", i, j, k); printf("OPT_1==0 & OPT_2==0 ==> Multiplication Table\n"); printf("OPT_1 >0 & OPT_2==0 ==> Summation Table\n"); printf("OPT_1==0 & OPT_2 >0 ==> Square Table\n"); printf("OPT_1 >0 & OPT_2 >0 ==> Cubic Table\n"); printf("\n"); if (i > 0) { int rows = i; int columns = rows; int row, column; if (j == 0 && k == 0) { for (row=0; row<=0; row=row+1) { printf(" %2d | ", row); for (column=1; column<=columns; column=column+1) { printf("%5d", 1*column); } printf("\n"); printf(" %s | ", "__"); for (column=1; column<=columns; column=column+1) { printf("%5s", "_____"); } printf("\n"); } for (row=1; row<=rows; row=row+1) { printf(" %2d | ", row); for (column=1; column<=columns; column=column+1) { printf("%5d", row*column); } printf("\n"); } } else if (j > 0 && k == 0) { printf(" %2s | %7s\n", "N", "SUM(1-N)"); printf(" %s | %7s\n", "__", "_______"); for (row=1; row<=rows; row=row+1) { printf(" %2d | %7d\n", row, ((row * (row+1))/2)); } } else if (j == 0 && k > 0) { printf(" %2s | %7s\n", "N", "N^2"); printf(" %s | %7s\n", "__", "_______"); for (row=1; row<=rows; row=row+1) { printf(" %2d | %7d\n", row, row*row); } } else if (j > 0 && k > 0) { printf(" %2s | %7s\n", "N", "N^3"); printf(" %s | %7s\n", "__", "_______"); for (row=1; row<=rows; row=row+1) { printf(" %2d | %7d\n", row, row*row*row); } } else { printf("ERROR: INVALID INPUTS %d %d %d", i, j, k); } } else { printf("ERROR: INVALID INPUTS %d %d %d", i, j, k); } printf("\n\n"); return 0; }
/** * Created by hesk on 15/12/15. * Test of API on the news feed */ public class NewsArticle extends BigScreenDemo { // protected HBEditorialClient clientApi; /* protected void defaultCompleteSlider(SliderLayout slide, List<ArticleData> list) { Iterator<ArticleData> it = list.iterator(); while (it.hasNext()) { ArticleData article = it.next(); NewsBurner textSliderView = new NewsBurner(this); textSliderView //feed .setID(article.getId()) .setPath(article._links.getSelf()); //add your extra information slide.addSlider(textSliderView); } }*/ /* protected Callback<ResponsePostW> res = new Callback<ResponsePostW>() { @Override public void success(ResponsePostW responsePostW, Response response) { try { defaultCompleteSlider(mDemoSlider, responsePostW.postList.getArticles()); } catch (Exception e) { e.printStackTrace(); } } @Override public void failure(RetrofitError error) { error.printStackTrace(); } };*/ @Override protected boolean shouldRequestAPIBeforeLayoutRender() { // clientApi = HBEditorialClient.getInstance(this); try { // clientApi.createFeedInterface().the_recent_page(1, res); } catch (Exception e) { e.printStackTrace(); } return true; } }
import time import dns import dns.exception import dns.name import dns.query import dns.resolver from dyn.tm.errors import DynectCreateError, DynectGetError from dyn.tm.session import DynectSession from dyn.tm.zones import Node, Zone, get_all_zones from flask import current_app def get_dynect_session(): dynect_session = DynectSession( current_app.config.get('ACME_DYN_CUSTOMER_NAME', ''), current_app.config.get('ACME_DYN_USERNAME', ''), current_app.config.get('ACME_DYN_PASSWORD', ''), ) return dynect_session def _has_dns_propagated(name, token): txt_records = [] try: dns_resolver = dns.resolver.Resolver() dns_resolver.nameservers = [get_authoritative_nameserver(name)] dns_response = dns_resolver.query(name, 'TXT') for rdata in dns_response: for txt_record in rdata.strings: txt_records.append(txt_record.decode("utf-8")) except dns.exception.DNSException: return False for txt_record in txt_records: if txt_record == token: return True return False def wait_for_dns_change(change_id, account_number=None): fqdn, token = change_id number_of_attempts = 10 for attempts in range(0, number_of_attempts): status = _has_dns_propagated(fqdn, token) current_app.logger.debug("Record status for fqdn: {}: {}".format(fqdn, status)) if status: break time.sleep(20) if not status: # TODO: Delete associated DNS text record here raise Exception("Unable to query DNS token for fqdn {}.".format(fqdn)) return def get_zone_name(domain): zones = get_all_zones() zone_name = "" for z in zones: if domain.endswith(z.name): # Find the most specific zone possible for the domain # Ex: If fqdn is a.b.c.com, there is a zone for c.com, # and a zone for b.c.com, we want to use b.c.com. if z.name.count(".") > zone_name.count("."): zone_name = z.name if not zone_name: raise Exception("No Dyn zone found for domain: {}".format(domain)) return zone_name def get_zones(account_number): get_dynect_session() zones = get_all_zones() zone_list = [] for zone in zones: zone_list.append(zone.name) return zone_list def create_txt_record(domain, token, account_number): get_dynect_session() zone_name = get_zone_name(domain) zone_parts = len(zone_name.split('.')) node_name = '.'.join(domain.split('.')[:-zone_parts]) fqdn = "{0}.{1}".format(node_name, zone_name) zone = Zone(zone_name) try: zone.add_record(node_name, record_type='TXT', txtdata="\"{}\"".format(token), ttl=5) zone.publish() current_app.logger.debug("TXT record created: {0}, token: {1}".format(fqdn, token)) except DynectCreateError as e: if "Cannot duplicate existing record data" in e.message: current_app.logger.debug( "Unable to add record. Domain: {}. Token: {}. " "Record already exists: {}".format(domain, token, e), exc_info=True ) else: raise change_id = (fqdn, token) return change_id def delete_txt_record(change_id, account_number, domain, token): get_dynect_session() if not domain: current_app.logger.debug("delete_txt_record: No domain passed") return zone_name = get_zone_name(domain) zone_parts = len(zone_name.split('.')) node_name = '.'.join(domain.split('.')[:-zone_parts]) fqdn = "{0}.{1}".format(node_name, zone_name) zone = Zone(zone_name) node = Node(zone_name, fqdn) try: all_txt_records = node.get_all_records_by_type('TXT') except DynectGetError: # No Text Records remain or host is not in the zone anymore because all records have been deleted. return for txt_record in all_txt_records: if txt_record.txtdata == ("{}".format(token)): current_app.logger.debug("Deleting TXT record name: {0}".format(fqdn)) txt_record.delete() zone.publish() def delete_acme_txt_records(domain): get_dynect_session() if not domain: current_app.logger.debug("delete_acme_txt_records: No domain passed") return acme_challenge_string = "_acme-challenge" if not domain.startswith(acme_challenge_string): current_app.logger.debug( "delete_acme_txt_records: Domain {} doesn't start with string {}. " "Cowardly refusing to delete TXT records".format(domain, acme_challenge_string)) return zone_name = get_zone_name(domain) zone_parts = len(zone_name.split('.')) node_name = '.'.join(domain.split('.')[:-zone_parts]) fqdn = "{0}.{1}".format(node_name, zone_name) zone = Zone(zone_name) node = Node(zone_name, fqdn) all_txt_records = node.get_all_records_by_type('TXT') for txt_record in all_txt_records: current_app.logger.debug("Deleting TXT record name: {0}".format(fqdn)) txt_record.delete() zone.publish() def get_authoritative_nameserver(domain): if current_app.config.get('ACME_DYN_GET_AUTHORATATIVE_NAMESERVER'): n = dns.name.from_text(domain) depth = 2 default = dns.resolver.get_default_resolver() nameserver = default.nameservers[0] last = False while not last: s = n.split(depth) last = s[0].to_unicode() == u'@' sub = s[1] query = dns.message.make_query(sub, dns.rdatatype.NS) response = dns.query.udp(query, nameserver) rcode = response.rcode() if rcode != dns.rcode.NOERROR: if rcode == dns.rcode.NXDOMAIN: raise Exception('%s does not exist.' % sub) else: raise Exception('Error %s' % dns.rcode.to_text(rcode)) if len(response.authority) > 0: rrset = response.authority[0] else: rrset = response.answer[0] rr = rrset[0] if rr.rdtype != dns.rdatatype.SOA: authority = rr.target nameserver = default.query(authority).rrset[0].to_text() depth += 1 return nameserver else: return "8.8.8.8"
// all locks will be released before returning // merge may fail if (1) too large combined; (2) didn't acquire lock before timeout static bool wormhole_try_merge(struct wormref * const ref, struct wormleaf * const leaf) { struct wormhole * const map = ref->map; while (rwlock_trylock_write_nr(&(map->metalock), 64) == false) ref->qstate = (u64)(map->hmap); struct wormleaf * const next = leaf->next; debug_assert(next); if (rwlock_trylock_write_nr(&(next->leaflock), 64)) { if ((leaf->nr_keys + next->nr_keys) <= WH_KPN) { wormhole_merge_ref(ref, leaf, next); return true; } rwlock_unlock_write(&(next->leaflock)); } rwlock_unlock_write(&(map->metalock)); rwlock_unlock_write(&(leaf->leaflock)); return false; }
/** * removes the MapCircle with the given id. if no such element is found, nothing happens. * * @param id * id of the map circle, may not be null */ private void removeMapCircleWithId(final String id) { synchronized (mapCircles) { if (mapCircles.containsKey(id)) { if (logger.isDebugEnabled()) { logger.debug("removing circle {}", id); } jsMapView.call("hideCircle", id); jsMapView.call("removeCircle", id); if (logger.isTraceEnabled()) { logger.trace("removing circle {}, after JS calls", id); } mapCircles.remove(id); } } }
<reponame>ctgriffiths/twister<gh_stars>10-100 /* File: AddUser.java ; This file is part of Twister. Version: 2.004 Copyright (C) 2012-2013 , Luxoft Authors: <NAME> <<EMAIL>> 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. */ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import com.twister.CustomDialog; public class AddUser extends JFrame{ private JPanel p; private javax.swing.JButton add; private javax.swing.JButton cancel; private javax.swing.JScrollPane groupscroll; private javax.swing.JLabel groupslabel; private javax.swing.JList groupslist; private javax.swing.JLabel userslabel; private javax.swing.JList userslist; private javax.swing.JScrollPane usersscroll; private String [] users,groups; private UserManagement um; private javax.swing.JButton listusers; private javax.swing.JTextField tusername; private javax.swing.JLabel username; public AddUser(int x,int y,String [] groups,UserManagement um){ this.um = um; this.groups = groups; setTitle("Add existing user to configuration"); setVisible(true); setBounds(x,y,420,340); setAlwaysOnTop(true); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); initComponents(); } private void initComponents() { p = new JPanel(); tusername = new javax.swing.JTextField(); listusers = new javax.swing.JButton(); username = new javax.swing.JLabel(); listusers.setText("List Users"); listusers.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { users = um.getUsers(); userslist.setModel(new javax.swing.AbstractListModel() { public int getSize() { return users.length; } public Object getElementAt(int i) { return users[i]; } }); } }); username.setText("Username:"); cancel = new javax.swing.JButton(); cancel.setText("Cancel"); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { AddUser.this.dispose(); } }); add = new javax.swing.JButton(); add.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(!tusername.getText().equals("")&&groupslist.getSelectedIndex()!=-1){ String [] selected = new String[groupslist.getSelectedValuesList().size()]; for(int i=0;i<groupslist.getSelectedValuesList().size();i++){ selected[i] = groupslist.getSelectedValuesList().get(i).toString(); } StringBuilder sb = new StringBuilder(); for(String st:selected){ sb.append(st); sb.append(","); } sb.setLength(sb.length()-1); um.addUser(tusername.getText(), sb.toString(),AddUser.this); } else { CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE,AddUser.this, "Warning", "Please set one user and one group"); return; } } }); userslabel = new javax.swing.JLabel(); usersscroll = new javax.swing.JScrollPane(); userslist = new javax.swing.JList(); userslist.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { tusername.setText(userslist.getSelectedValue().toString()); } }); groupslabel = new javax.swing.JLabel(); groupscroll = new javax.swing.JScrollPane(); groupslist = new javax.swing.JList(); cancel.setText("Cancel"); add.setText("Add"); userslabel.setText("Available users:"); userslist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); usersscroll.setViewportView(userslist); groupslabel.setText("Available groups:"); groupslist.setModel(new javax.swing.AbstractListModel() { public int getSize() { return groups.length; } public Object getElementAt(int i) { return groups[i]; } }); groupscroll.setViewportView(groupslist); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(p); p.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tusername) .addGroup(layout.createSequentialGroup() .addComponent(username) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(usersscroll, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(listusers) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(groupslabel) .addComponent(groupscroll)) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(67, 67, 67) .addComponent(add) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cancel) .addGap(10, 10, 10)))) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {add, cancel}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(groupslabel) .addComponent(username)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(tusername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(listusers) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(usersscroll, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)) .addComponent(groupscroll)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cancel) .addComponent(add)) .addContainerGap()) ); add(p); } }
<gh_stars>1-10 use crate::Uuid; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; pub fn uuid() -> Uuid { Uuid::new_v4() } pub fn random(len: usize) -> String { let chars = thread_rng().sample_iter(&Alphanumeric).take(len).collect(); String::from_utf8(chars).unwrap() } #[cfg(test)] mod tests { use super::*; #[test] fn generates_random() { assert_eq!(20, random(20).len()); } }
<reponame>78182648/blibli-go<filename>app/admin/main/aegis/service/service_test.go package service import ( "context" "flag" "testing" "go-common/app/admin/main/aegis/conf" "github.com/smartystreets/goconvey/convey" ) var ( s *Service cntx context.Context ) func init() { flag.Set("conf", "../cmd/aegis-admin.toml") flag.Parse() if err := conf.Init(); err != nil { panic(err) } s = New(conf.Conf) cntx = context.Background() } /* func TestMain(m *testing.M) { if os.Getenv("DEPLOY_ENV") != "" { flag.Set("app_id", "main.archive.aegis-admin") flag.Set("conf_token", "cad913269be022e1eb8c45a8d5408d78") flag.Set("tree_id", "60977") flag.Set("conf_version", "1") flag.Set("deploy_env", "uat") flag.Set("conf_host", "config.bilibili.co") flag.Set("conf_path", "/tmp") flag.Set("region", "sh") flag.Set("zone", "sh001") } else { flag.Set("conf", "../cmd/local.toml") } flag.Parse() if err := conf.Init(); err != nil { panic(err) } conf.Conf.AegisPub = &databus.Config{ // Key: "<KEY>", // Secret: "<KEY>", // Group: "databus_test_group", // Topic: "databus_test_topic", Key: "dbe67e6a4c36f877", Secret: "8c775ea242caa367ba5c876c04576571", Group: "Test1-MainCommonArch-P", Topic: "test1", Action: "pub", Name: "databus", Proto: "tcp", // Addr: "172.16.33.158:6205", Addr: "172.18.33.50:6205", Active: 10, Idle: 5, DialTimeout: xtime.Duration(time.Second), WriteTimeout: xtime.Duration(time.Second), ReadTimeout: xtime.Duration(time.Second), IdleTimeout: xtime.Duration(time.Minute), } s = New(conf.Conf) cntx = context.Background() m.Run() os.Exit(0) } */ func TestServicePing(t *testing.T) { var ( c = context.TODO() ) convey.Convey("Ping", t, func(ctx convey.C) { err := s.Ping(c) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) } func TestServiceClose(t *testing.T) { convey.Convey("Close", t, func(ctx convey.C) { //s.Close() //ctx.Convey("No return values", func(ctx convey.C) { //}) }) }
#include <THC/THC.h> #include <math.h> #include "cuda/roi_align_kernel.h" extern THCState *state; int roi_align_forward_cuda(int crop_height, int crop_width, float spatial_scale, THCudaTensor * features, THCudaTensor * rois, THCudaTensor * output) { // Grab the input tensor float * image_ptr = THCudaTensor_data(state, features); float * boxes_ptr = THCudaTensor_data(state, rois); float * crops_ptr = THCudaTensor_data(state, output); // Number of ROIs int num_boxes = THCudaTensor_size(state, rois, 0); int size_rois = THCudaTensor_size(state, rois, 1); if (size_rois != 5) { return 0; } // batch size int batch = THCudaTensor_size(state, features, 0); // data height int image_height = THCudaTensor_size(state, features, 2); // data width int image_width = THCudaTensor_size(state, features, 3); // Number of channels int depth = THCudaTensor_size(state, features, 1); cudaStream_t stream = THCState_getCurrentStream(state); float extrapolation_value = 0.0; ROIAlignForwardLaucher( image_ptr, boxes_ptr, num_boxes, batch, image_height, image_width, crop_height, crop_width, depth, extrapolation_value, crops_ptr, stream); return 1; } int roi_align_backward_cuda(int crop_height, int crop_width, float spatial_scale, THCudaTensor * top_grad, THCudaTensor * rois, THCudaTensor * bottom_grad) { // Grab the input tensor float * grads_ptr = THCudaTensor_data(state, top_grad); float * boxes_ptr = THCudaTensor_data(state, rois); float * grads_image_ptr = THCudaTensor_data(state, bottom_grad); // Number of ROIs int num_boxes = THCudaTensor_size(state, rois, 0); int size_rois = THCudaTensor_size(state, rois, 1); if (size_rois != 5) { return 0; } // batch size int batch = THCudaTensor_size(state, bottom_grad, 0); // data height int image_height = THCudaTensor_size(state, bottom_grad, 2); // data width int image_width = THCudaTensor_size(state, bottom_grad, 3); // Number of channels int depth = THCudaTensor_size(state, bottom_grad, 1); cudaStream_t stream = THCState_getCurrentStream(state); ROIAlignBackwardLaucher( grads_ptr, boxes_ptr, num_boxes, batch, image_height, image_width, crop_height, crop_width, depth, grads_image_ptr, stream); return 1; }
package io.probedock.maven.plugin.glassfish.model; import io.probedock.maven.plugin.glassfish.utils.Stringifier; import java.util.Set; import org.apache.maven.plugins.annotations.Parameter; /** * Represents a connector connection pool and configuration required its creation. * * @author <NAME> <EMAIL> * @author <NAME> <EMAIL> */ public class ConnectorConnectionPool implements Comparable<ConnectorConnectionPool> { /** * JNDI name of the connector connector pool */ @Parameter(required = true) private String jndiName; /** * Name of the resource adapter */ @Parameter(required = true) private String raname; /** * The name of the connection definition */ @Parameter(required = true) private String connectionDefinition; /** * Ping during creation of the connection pool */ @Parameter(defaultValue = "true") private Boolean ping = true; /** * Ping during creation of the connection pool */ @Parameter(defaultValue = "true") private Boolean isConnectValidateReq = true; @Parameter private Set<Property> properties; public String getJndiName() { return jndiName; } public void setJndiName(String jndiName) { this.jndiName = jndiName; } public String getRaname() { return raname; } public void setRaname(String raname) { this.raname = raname; } public String getConnectionDefinition() { return connectionDefinition; } public void setConnectionDefinition(String connectionDefinition) { this.connectionDefinition = connectionDefinition; } public Boolean getPing() { return ping; } public void setPing(Boolean ping) { this.ping = ping; } public Boolean getIsConnectValidateReq() { return isConnectValidateReq; } public void setIsConnectValidateReq(Boolean isConnectValidateReq) { this.isConnectValidateReq = isConnectValidateReq; } public Set<Property> getProperties() { return properties; } public void setProperties(Set<Property> properties) { this.properties = properties; } @Override public String toString() { return "connectionDefinition=" + connectionDefinition + ", " + "isConnectValidateReq=" + isConnectValidateReq + ", " + "jndiName=" + jndiName + ", " + "ping=" + ping + ", " + "properties=" + Stringifier.toString(properties) + ", " + "raname=" + raname; } @Override public int compareTo(ConnectorConnectionPool connectorConnectionPoolToCompare) { return jndiName.compareTo(connectorConnectionPoolToCompare.jndiName); } }
/** * Compare to method based on the maximum absolute error. * If two DataNodes have the same maxabserror the level and subsequently order in level get compared instead. * This way no two DataNodes in the same SiblinTree should ever be equal! * * This method specifically compares the error so the DataNodes can be stored in a convenient Sorted Structure based on error * (so the nodes with the lowest potential absolute error can be deleted first). * * @param o DataNode to compare To * @return -1 if this is smaller, 0 if equal, 1 if bigger than other DataNode (in regards to maximum absolute error) */ @Override public int compareTo(@NotNull DataNode o) { if (maxabserror == o.maxabserror){ if (level == o.level){ return Integer.compare(orderinlevel, o.orderinlevel); } return Integer.compare(level, o.level); } return Double.compare(maxabserror, o.maxabserror); }
package de.janitza.maven.gcs.api.config.loader; import java.security.PrivateKey; /** * Created with IntelliJ IDEA. * User: <NAME> <<EMAIL>> * Date: 10.02.15 * Time: 12:24 */ public interface IServiceAccountCredentials { String getAccountId(); PrivateKey getPrivateKey(); }
<reponame>ComputerArchitectureGroupPWr/JGenerilo /* * Copyright (c) 2010-2011 Brigham Young University * * This file is part of the BYU RapidSmith Tools. * * BYU RapidSmith Tools is free software: you may 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. * * BYU RapidSmith Tools 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. * * A copy of the GNU General Public License is included with the BYU * RapidSmith Tools. It can be found at doc/gpl2.txt. You may also * get a copy of the license at <http://www.gnu.org/licenses/>. * */ package edu.byu.ece.rapidSmith.bitstreamTools.bitstream; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * This class contains all of the information in a configuration bitstream header. * The bitstream header is the extra information added at the top of a true * bitstream and is used by Impact and other bitstream tools to figure out * what is in the actual bitstream. A bitstream header contains the following information: * - Name of the source NCD file * - the part name * - The date created * - The time created * - The length of the bitstream * <p/> * The length of the bitstream is not saved in this class. This is calculated based * on the actual contents of the bitstream. * <p/> * <p/> * TODO: update the toString method so that it prints the parsed fields of the header. */ public class BitstreamHeader { /** * A String version of the initial header of the bitstream header. */ public static final String INIT_HEADER = "0x0FF00FF00FF00FF000"; /** * A byte version of the initial header of the bitstream header. */ public static final byte[] INIT_HEADER_BYTES = {(byte) 0x0F, (byte) 0xF0, (byte) 0x0F, (byte) 0xF0, (byte) 0x0F, (byte) 0xF0, (byte) 0x0F, (byte) 0xF0, (byte) 0x00}; /** * Create a new bitstream header using the parameters given to fill the header fields * * @param sourceNCDFileName The String name of the source NCD file * @param partName The name of the part (currently this does not check to see if it is valid) * @param dateCreated The date the bitstream was created * @param timeCreated The time the bitstream was created */ public BitstreamHeader(String sourceNCDFileName, String partName, String dateCreated, String timeCreated) { _sourceNCDFileName = sourceNCDFileName; _partName = partName; _dateCreated = dateCreated; _timeCreated = timeCreated; } // TODO: Test this public BitstreamHeader(String ncd, String partName) { this(ncd, partName, new Date()); } // TODO: test this public BitstreamHeader(String ncd, String partName, Date date) { this(ncd, partName, // create a Date String DateFormat.getDateInstance().format(date), DateFormat.getTimeInstance().format(date) ); } /** * Returns the date the bitstream was created as a string year/month/day, for example: 2009/02/19. * * @return The date the bitstream was created as a string. */ public String getDateCreated() { return _dateCreated; } /** * Returns the raw bytes for a bitstream header and includes the * length of the bitstream in the header. The length is passed * in as a parameter rather than using the class bitstreamLength * member as this value may change when generating the bitstream. * <p/> * This method does NOT generate the sync word. * * @param bitstreamLength The length of the current bitstream header. * @return The list of bytes corresponding to the header. */ public List<Byte> getHeaderBytes(int length) { List<Byte> bytes = getHeaderBytesWithoutLength(); // Field 7, bytes in raw bitstream addCharacter(bytes, 'e'); bytes.add((byte) ((length & 0xff000000) >>> 24)); bytes.add((byte) ((length & 0xff0000) >>> 16)); bytes.add((byte) ((length & 0xff00) >>> 8)); bytes.add((byte) ((length & 0xff) >>> 0)); return bytes; } /** * This function will assemble the raw bytes of the header from the * values contained within this object. This method will NOT * add the length field of to the array (other methods are * available for adding the length). This method will also * NOT include the SYNC word. * <p/> * This method will also make sure that the header ends on * a 4 byte boundary so the sync word starts on a 4 byte * boundary. */ public List<Byte> getHeaderBytesWithoutLength() { Character nullChar = 0; List<Byte> bytes = new ArrayList<Byte>(); // Field 1, 2 bytes length, 9 bytes data addByteArrayField(bytes, INIT_HEADER_BYTES); // Field 2, 'a' addField(bytes, "a"); // Field 3, source NCD file name addField(bytes, _sourceNCDFileName + nullChar); // Field 4, 'b', part name addCharacter(bytes, 'b'); addField(bytes, _partName + nullChar); // Field 5, 'c', date created addCharacter(bytes, 'c'); addField(bytes, _dateCreated + nullChar); // Field 6, 'd', time created addCharacter(bytes, 'd'); addField(bytes, _timeCreated + nullChar); return bytes; } public String getPartName() { return _partName; } /** * Allows access to the source NCD filename and command parameters that generated the bitstream. * * @return The string of the name of the NCD file which was used to create the bitstream. */ public String getSourceNCDFileName() { return _sourceNCDFileName; } /** * Returns the time the bitstream was created in 24-hour format, for example: 16:12:04. * * @return The time the bitstream was created as a string. */ public String getTimeCreated() { return _timeCreated; } public String toString() { return toXML(); } /** * Creates a text string detailing all the fields in the header in ASCII and Hexadecimal * * @return A string representing the header object */ public String toXML() { StringBuffer output = new StringBuffer(); output.append("\n"); output.append("Field 1 (Initial Header) : <" + INIT_HEADER + "> 0x" + BitstreamUtils.toHexString(INIT_HEADER) + "\n"); output.append("Field 2 (Source NCD file) : <" + _sourceNCDFileName + "> 0x" + BitstreamUtils.toHexString(_sourceNCDFileName) + "\n"); output.append("Field 3 (Device name) : <" + this._partName + "> 0x" + BitstreamUtils.toHexString(_partName) + "\n"); output.append("Field 4 (Date created) : <" + this._dateCreated + "> 0x" + BitstreamUtils.toHexString(_dateCreated) + "\n"); output.append("Field 5 (Time created) : <" + this._timeCreated + "> 0x" + BitstreamUtils.toHexString(_timeCreated) + "\n"); return output.toString(); } protected static void addByteArrayField(List<Byte> bytes, byte[] byteArray) { int length = byteArray.length; bytes.add(((Integer) ((length & 0xff00) >> 8)).byteValue()); bytes.add(((Integer) (length & 0xff)).byteValue()); for (int i = 0; i < length; i++) { bytes.add((byte) (0xff & byteArray[i])); } } protected static void addCharacter(List<Byte> bytes, char character) { bytes.add((byte) (0xff & character)); } protected static void addField(List<Byte> bytes, String fieldData) { int length = fieldData.length(); bytes.add(((Integer) ((length & 0xff00) >> 8)).byteValue()); bytes.add(((Integer) (length & 0xff)).byteValue()); bytes.addAll(getLowerBytes(fieldData)); } /** * Takes a string and returns an ArrayList of bytes of the lower bytes of each character in the string. * * @param s The string to be converted. * @return An ArrayList of the lower bytes of the characters in the string. */ protected static ArrayList<Byte> getLowerBytes(String s) { ArrayList<Byte> bytes = new ArrayList<Byte>(); int len = s.length(); for (int i = 0; i < len; i++) { bytes.add(((Integer) (s.charAt(i) & 0xff)).byteValue()); } return bytes; } /** * This is the source NCD from which the bitstream was created. It may also include switches. */ protected String _sourceNCDFileName; /** * This is the target device name, which also includes the package. */ protected String _partName; /** * The date the bit file was created. */ protected String _dateCreated; /** * The time the bit file was created. */ protected String _timeCreated; }
/*! Returns \c true if this model can contain events of global type ID \a typeIndex. Otherwise returns \c false. The base model does not know anything about type IDs and always returns \c false. You should override this method if you implement \l typeId(). */ bool TimelineModel::handlesTypeId(int typeIndex) const { Q_UNUSED(typeIndex); return false; }
/** * Detects right clicks * * @param event */ export function isRightClick(event: MouseEvent | PointerEvent | TouchEvent) { return "which" in event ? event.which === 3 : "button" in event ? (event as any).button === 2 : false; }