repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
mooshak-dcc/mooshak-2
src/main/java/pt/up/fc/dcc/mooshak/client/form/admin/TextDateBox.java
package pt.up.fc.dcc.mooshak.client.form.admin; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import org.gwtbootstrap3.extras.datetimepicker.client.ui.base.events.ChangeDateEvent; import org.gwtbootstrap3.extras.datetimepicker.client.ui.base.events.ChangeDateHandler; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiTemplate; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import pt.up.fc.dcc.mooshak.client.widgets.CustomDateTimePicker; import pt.up.fc.dcc.mooshak.shared.commands.MooshakValue; public class TextDateBox extends Composite implements MooshakWidget { private static final long SECONDS_IN_MILLI = 1000; private static TextDateBoxUiBinder uiBinder = GWT.create(TextDateBoxUiBinder.class); @UiTemplate("TextDateBox.ui.xml") interface TextDateBoxUiBinder extends UiBinder<Widget, TextDateBox> { } @UiField CustomDateTimePicker dateTextBox; private String field = null; private boolean editing = false; private Date current = null; public TextDateBox() { initWidget(uiBinder.createAndBindUi(this)); dateTextBox.getTextBox().sinkEvents(Event.ONFOCUS | Event.ONBLUR); dateTextBox.addDomHandler(new BlurHandler() { @Override public void onBlur(BlurEvent event) { editing = false; if (current != null) { if (dateTextBox.getValue() == null || !current.equals(dateTextBox.getValue())) dateTextBox.fireEvent(new ChangeDateEvent(null)); return; } else if (dateTextBox.getValue() != null) { dateTextBox.fireEvent(new ChangeDateEvent(null)); } } }, BlurEvent.getType()); dateTextBox.addDomHandler(new FocusHandler() { @Override public void onFocus(FocusEvent event) { editing = true; } }, FocusEvent.getType()); } @Override public MooshakValue getValue() { Date date = dateTextBox.getValue(); String value = null; if (date != null) value = Long.toString(date.getTime() / SECONDS_IN_MILLI); return new MooshakValue(field, value); } @Override public void setValue(MooshakValue value) { if (isEditing()) return; setValue(value, false); } @Override public void setValue(MooshakValue value, boolean fireEvents) { if ("".equals(value.getSimple()) || value.getSimple() == null) { current = null; dateTextBox.setValue(null, fireEvents); } else { try { Date date = new Date(Long.parseLong(value.getSimple()) * SECONDS_IN_MILLI); current = date; dateTextBox.setValue(date, fireEvents); } catch (Exception cause) { final Logger logger = Logger.getLogger(""); logger.log(Level.INFO, "Parsing date as long", cause); } } field = value.getField(); } @Override public HandlerRegistration addValueChangeHandler(final ValueChangeHandler<MooshakValue> handler) { return dateTextBox.addChangeDateHandler(new ChangeDateHandler() { @Override public void onChangeDate(ChangeDateEvent evt) { String dateStr = dateTextBox.getTextBox().getValue(); String value = ""; if (dateStr != null) value = Long.toString(DateTimeFormat.getFormat("dd/MM/yyyy HH:mm:ss") .parse(dateStr).getTime() / SECONDS_IN_MILLI); ValueChangeEvent<MooshakValue> event = new ValueChangeEvent<MooshakValue>( new MooshakValue(field, value)) { }; handler.onValueChange(event); } }); } @Override public boolean isEditing() { return editing; } /** * Sets whether the date box is enabled. * * @param enabled * is the box enabled */ public void setEnabled(boolean enabled) { dateTextBox.setEnabled(enabled); } }
liuxing521a/xcnet
xcnet-common/src/test/java/org/itas/xcnet/common/Ext2Impl3.java
/** * */ package org.itas.xcnet.common; import org.itas.xcnet.common.Extension; import org.itas.xcnet.common.URL; /** * @author liuzhen<<EMAIL>> * @createTime 2015年5月13日上午10:23:53 */ @Extension("impl3") public class Ext2Impl3 implements Ext2 { @Override public String echo(URLHolder url, String s) { return "Ext2.Impl3-echo"; } @Override public String yell(URL url, String s) { return "Ext2.Impl3-yell"; } @Override public String bang(URL url, int i) { return "Ext2.Impl3-bang"; } }
eloemosynator/YbEasyCli
yb_sysprocs_rel.py
#!/usr/bin/env python3 """ USAGE: yb_sysprocs_rel.py [options] PURPOSE: All user "relations" (tables, views, & sequences) in all databases. OPTIONS: See the command line help message for all options. (yb_sysprocs_rel.py --help) Output: The report as a formatted table, pipe seperated value rows, or inserted into a database table. """ from yb_sp_report_util import SPReportUtil class report_rel(SPReportUtil): """Issue the ybsql commands used to create the column distribution report.""" config = { 'description': 'All user "relations" (tables, views, & sequences) in all databases.' , 'report_sp_location': 'sysviews' , 'report_default_order': 'db_name|schema_name|rel_name' , 'db_filter_args': {'database':'db_name', 'schema':'schema_name', 'rel':'rel_name'} , 'optional_args_multi': ['database', 'schema', 'rel'] , 'usage_example_extra': {'cmd_line_args': "--database_like '%dze%' --rel_like 'c1%'" } } def execute(self): return self.build({'_yb_util_filter' : self.db_filter_sql() }) def main(): # YB 4 looks to be throwing an eronious warning with these sys views which I'm stripping strip_warnings = [r'WARNING: Error querying database metadata.*(RETURN QUERY|FOR over EXECUTE statement)'] print(report_rel(strip_warnings=strip_warnings).execute()) exit(0) if __name__ == "__main__": main()
kwark/geotrellis
vector/src/main/scala/geotrellis/vector/triangulation/DelaunayStitcher.scala
<gh_stars>0 /* * Copyright 2018 Azavea * * 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 geotrellis.vector.triangulation import org.locationtech.jts.geom.Coordinate import geotrellis.vector.{Line, MultiLine, Point} import geotrellis.vector.RobustPredicates.{LEFTOF, ON, RIGHTOF} import geotrellis.vector.mesh.{HalfEdgeTable, IndexedPointSet} final class DelaunayStitcher( pointSet: IndexedPointSet, halfEdgeTable: HalfEdgeTable ) extends Serializable { val predicates = new TriangulationPredicates(pointSet, halfEdgeTable) import predicates._ import pointSet._ import halfEdgeTable._ def advance(e0: Int): Int = { var e = getNext(e0) while (!isCorner(e)) e = getNext(e) e } def reverse(e0: Int): Int = { var e = getPrev(e0) while (!isCorner(e)) e = getPrev(e) e } def advanceIfNotCorner(e0: Int): Int = { var e = e0 while (!isCorner(e)) e = getNext(e) e } /** * Finds, inserts, and returns the unique half edge on the boundary of the * convex hull of the two convex boundary loops given by left and right; the * returned edge points from right to left. Left and right must be correctly * initialized to be corners of their respective bounding loops (according to * Predicates.isCorner), and isLeftLinear/isRightLinear must be set to true if * the respective meshes have only boundary edges. * * To be clear, this algorithm is impartial to absolute position despite the * inputs being named left and right. It does, however, require that the * bounding loops represented by left and right be convex and mutually * non-intersecting. */ def insertBase(left0: Int, isLeftLinear: Boolean, right0: Int, isRightLinear: Boolean, debug: Boolean): Int = { if (debug) println("Finding base ...") var left = advanceIfNotCorner(left0) var right = advanceIfNotCorner(right0) // compute the lower common tangent of left and right var continue = true var base = createHalfEdges(getSrc(right), getSrc(left)) // Walking the base. Many problems can arise here. We're looking for // a base edge that is on the convex hull of the combined point sets // of the left and right sub-triangulations, with a src (dest) vertex // in the right (left) sub-triangulation. That means that no points // can lie to the left of the chosen base. We have to make our // decisions about what to do based on the local configuration around // left and right, which are half edges on the exterior bounding loop // of each triangulation. Induction assures us that exterior loops // are always wound clockwise and the loops are semi-convex (i.e., // e.dest is never left of e.prev, though possibly it is on e.prev). // For each left and right, there are 9 local configurations that // matter based on whether e.dest and e.prev.src are left of/right // of/on the current base. Because we always use advance and reverse // to navigate among corners of the bounding loops, the logic is // simplified a bit. Note that right and left are handled differently // due to the potential for "flat spots" on the combined convex hull, // which are defined to be convex hull edges with more than two points // of the combined point set lying on the line. The following tables // define our actions in the salient cases (spaces with dashes are // never encountered if the winding of the exterior boundary is indeed // clockwise): // // left.dest is ___ base // RIGHT OF ON LEFT OF // RIGHT OF OK OK ADVANCE // left.prev.src is ___ base ON REVERSE ???? ADVANCE // LEFT OF REVERSE ADVANCE ADVANCE // // right.dest is ___ base // RIGHT OF ON LEFT OF // RIGHT OF OK ADVANCE ADVANCE // right.prev.src is ___ base ON OK ???? ADVANCE // LEFT OF REVERSE REVERSE REVERSE // // Linear sub-triangulations pose a special case. Since, by virtue of // using advance and reverse, e's source vertex must be a corner, // e.dest and e.prev.src should always be *the same* vertex for linear // triangulations. Thus, both are right of, left of, or on the base // candidate. When both are left or right of base, we need no special // handling, but when both are on base, we only need to advance if // e.dest lies inside the line segment from base.src to base.dest. while(continue) { val ldRel = relativeTo(base, getDest(left)) if (debug) println(s"Candidate: ${getSrc(base)} -> ${getDest(base)}, left.dest: ${getDest(left)}") if (ldRel == LEFTOF) { if (debug) println("Left dest is LEFTOF base (advance left)") left = advance(left) setDest(base, getSrc(left)) } else { val lpsRel = relativeTo(base, getSrc(getPrev(left))) if (!(lpsRel == RIGHTOF || (lpsRel == ON && ldRel == ON && distance(getSrc(base), getDest(base)) < distance(getSrc(base), getDest(left))))) { // left still needs to be moved if (ldRel == RIGHTOF) { if (debug) println(s"Left previous source is not RIGHTOF base and left dest is RIGHTOF base (reverse left)") left = reverse(left) setDest(base, getSrc(left)) } else { if (debug) println(s"Left dest is ON base (advance left)") left = advance(left) setDest(base, getSrc(left)) } } else { // left is acceptable, try to adjust right val rpsRel = relativeTo(base, getSrc(getPrev(right))) if (rpsRel == LEFTOF) { if (debug) println(s"Right previous source is LEFTOF base (reverse right)") right = reverse(right) setSrc(base, getSrc(right)) } else { val rdRel = relativeTo(base, getDest(right)) if (!(rdRel == RIGHTOF || (rdRel == ON && rpsRel == ON && distance(getDest(base), getSrc(base)) < distance(getDest(base), getDest(right))))) { if (debug) println(s"Right dest is not RIGHTOF base, or right dest and prev src are ON base") right = advance(right) setSrc(base, getSrc(right)) } else { continue = false } } } } } setNext(base, left) setNext(getFlip(base), right) setNext(getPrev(left), getFlip(base)) setNext(getPrev(right), base) if (debug) println(s"Found base: ${getSrc(base)} -> ${getDest(base)}") base } // A function to make code readable. The `e` parameter will refer to // either the left or right candidate edges for extending the stitch. If // the candidate is not right of the base edge, then it cannot participate // in a triangle with `b`, and that candidate will be considered invalid. @inline final def valid(e: Int, b: Int) = isCCW(getDest(e), getDest(b), getSrc(b)) /** * Stiches two non-intersecting Delaunay triangulations, given as half edges * on the outside boundary of each constituent triangulation. */ def merge(left: Int, isLeftLinear: Boolean, right: Int, isRightLinear: Boolean, triangles: TriangleMap, debug: Boolean = false): (Int, Boolean) = { var base = insertBase(left, isLeftLinear, right, isRightLinear, debug) // If linear joins to linear, check that the current state // isn't already done (linear result) if(isLeftLinear && isRightLinear) { val b0 = getSrc(base) val b1 = getDest(base) val l = getDest(getNext(base)) val r = getDest(getNext(getFlip(base))) if (isCollinear(b0, b1, l) && isCollinear(b0, b1, r)) { return (advance(getFlip(base)), true) } } val allEs = collection.mutable.Set.empty[Line] var continue = true while(continue) { if (debug) { println(s"Base = [${getSrc(base)} -> ${getDest(base)}]") } var lcand = rotCCWSrc(getFlip(base)) var rcand = rotCWSrc(base) if (debug) { println(s"Initial LCAND = [${getSrc(lcand)} -> ${getDest(lcand)}]") println(s"Initial RCAND = [${getSrc(rcand)} -> ${getDest(rcand)}]") } // Find left side candidate edge for extending the fill triangulation if(valid(lcand, base)) { while( inCircle( getDest(base), getSrc(base), getDest(lcand), getDest(rotCCWSrc(lcand)) ) ) { val e = rotCCWSrc(lcand) if (debug) { println(s"Deleting LCAND") println(s"Advancing LCAND to [${getSrc(e)} -> ${getDest(e)}]") } triangles -= lcand setNext(rotCCWDest(lcand), getNext(lcand)) setNext(getPrev(lcand), getFlip(base)) killEdge(getFlip(lcand)) killEdge(lcand) lcand = e if (debug) { val c = circleCenter(getDest(base), getSrc(base), getDest(lcand))._2 val r = c.distance(getCoordinate(getDest(base))) println(s" ✘ Deleted LCAND [circle center = $c, radius = $r]") } } } // Find right side candidate edge for extending the fill triangulation if(valid(rcand, base)) { while( inCircle( getDest(base), getSrc(base), getDest(rcand), getDest(rotCWSrc(rcand)) ) ) { val e = rotCWSrc(rcand) if (debug) { println(s"Deleting RCAND") println(s"Advancing RCAND to [${getSrc(e)} -> ${getDest(e)}]") } triangles -= getFlip(rcand) setNext(getFlip(base), rotCWSrc(rcand)) setNext(rotCCWDest(rcand), getNext(rcand)) killEdge(getFlip(rcand)) killEdge(rcand) rcand = e if (debug) { val c = circleCenter(getDest(base), getSrc(base), getDest(rcand))._2 val r = c.distance(getCoordinate(getDest(base))) println(s" ✘ Deleted RCAND [circle center = $c, radius = $r]") } } } if( !valid(lcand, base) && !valid(rcand, base) ) { // no further Delaunay triangles to add continue = false } else { if (!valid(lcand, base) || (valid(rcand, base) && inCircle(getDest(lcand), getSrc(lcand), getSrc(rcand), getDest(rcand))) ) { // form new triangle from rcand and base val e = createHalfEdges(getDest(rcand), getDest(base)) setNext(getFlip(e), getNext(rcand)) setNext(e, getFlip(base)) setNext(rcand, e) setNext(getFlip(lcand), getFlip(e)) triangles += getFlip(base) if (debug) { val t = getFlip(base) println(s" ✔ Seleted RCAND, creating triangle ${(getSrc(t), getDest(t), getDest(getNext(t)))}") } base = e } else { // form new triangle from lcand and base val e = createHalfEdges(getSrc(base), getDest(lcand)) setNext(rotCCWDest(lcand), getFlip(e)) setNext(e, getFlip(lcand)) setNext(getFlip(e), rcand) setNext(getFlip(base), e) triangles += getFlip(base) if (debug) { val t = getFlip(base) println(s" ✔ Seleted LCAND, creating triangle ${(getSrc(t), getDest(t), getDest(getNext(t)))}") } base = e } } } (advance(getFlip(base)), false) } private def shouldAdvance(b: Int, e: Int) = { relativeTo(b, getDest(e)) match { case LEFTOF => true case RIGHTOF => relativeTo(b, getSrc(getPrev(e))) match { case LEFTOF => true case RIGHTOF => false case ON => true } case ON => relativeTo(b, getSrc(getPrev(e))) match { case RIGHTOF => false case LEFTOF => true case ON => distance(getSrc(b), getDest(b)) > distance(getSrc(b), getDest(e)) } } } def joinToVertex(bound: Int, isLinear: Boolean, vertex: Int, triangles: TriangleMap, debug: Boolean = false) = { var e = advanceIfNotCorner(bound) var base = createHalfEdges(vertex, getSrc(e)) while (shouldAdvance(base, e)) { e = advance(e) setDest(base, getSrc(e)) } setNext(getPrev(e), getFlip(base)) setNext(base, e) if (debug) println(s"Found base [$base]: [${getSrc(base)} ⇒ ${getDest(base)}], ${(getCoordinate(getSrc(base)), getCoordinate(getDest(base)))}") if (isLinear && relativeTo(base, getDest(e)) == ON) { (base, true) } else { var cand = rotCCWSrc(getFlip(base)) while(valid(cand, base)) { while(inCircle(getDest(base), getSrc(base), getDest(cand), getDest(rotCCWSrc(cand)))) { val hold = rotCCWSrc(cand) if (debug) println(s"Deleting [${getSrc(cand)} -> ${getDest(cand)}]") triangles -= cand setNext(rotCCWDest(cand), getNext(cand)) setNext(getPrev(cand), getFlip(base)) killEdge(getFlip(cand)) killEdge(cand) cand = hold } if (debug) println(s"Found candidate [$cand]: [${getSrc(cand)} ⇒ ${getDest(cand)}], ${(getCoordinate(getSrc(cand)), getCoordinate(getDest(cand)))}") val added = createHalfEdges(getSrc(base), getDest(cand)) if (debug) println(s"Adding [$added]: [${getSrc(added)} ⇒ ${getDest(added)}]") setNext(rotCCWDest(cand), getFlip(added)) setNext(added, getFlip(cand)) setNext(getFlip(added), getNext(getFlip(base))) setNext(getFlip(base), added) triangles += added if (debug) println(s"Added triangle ${(getSrc(added), getDest(added), getDest(getNext(added)))}") cand = rotCCWSrc(getFlip(added)) base = added } val `final` = advance(getFlip(base)) (`final`, false) } } }
mercycorps/TolaWorkflow
workflow/migrations/0045_auto_20190425_1109.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2019-04-25 18:09 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('workflow', '0044_auto_20190425_1030'), ] operations = [ migrations.AlterField( model_name='tolauser', name='user', field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='tola_user', to=settings.AUTH_USER_MODEL, verbose_name='User'), ), ]
andreimironenko/graphics-sdk
gfx_rel_es6.x/pds_aux_vtx_sizeof.h
/* Auto-generated file - don't edit. */ #define PDS_AUXILIARYVERTEX_SIZE (120UL)
alejo8591/unipiloto-am-4
modules/module_3/lab3/index.js
<reponame>alejo8591/unipiloto-am-4<gh_stars>10-100 /* Variables t elementos Booleanos */ var verdadero = true; var falso = false; /* Elementos de Comparación */ /* igualdad (==) */ console.log('Cuando es 1 == 1 es: ' + (1 == 1)); console.log('Cuando es "1" == 1 es: ' + ("1" == 1)); console.log('Cuando es 0 == false es: ' + (0 == false)); console.log('cuando es 1 == true es: ' + (1 == true)); console.log('Cuando es "" == 0' + ("" == 0)); // Convierte "" a 0 console.log('Cuando es 0 == ""' + (0 == "")); // Convierte "" a 0 console.log('CUando es " " == 0' + (0 == " ")); var x = {}; var y = x; console.log("La Comparación entre los objetos X y Y es: " + (x == y)); /* igualdad estricta (===) */ console.log('Cuando es "1" === 1 es: ' + ("1" === 1)); console.log('Cuando es "0" === 0 es: ' + ("0" === 0)); /* Comparación no estricta de no igual (!=) */ console.log('Cuando es "" != 0' + ("" != 0)); /* Comparación estricta de no igual (!==)*/ console.log('Cuando es "" !== 0' + ("" !== 0)); /* Flujos logicos */ console.log("----- flujos logicos -----"); // Operador del tipo and `&&` console.log( true && true); console.log(true && false); console.log(false && false); console.log(false && true); // Operador del tipo or `or` console.log( true || true); console.log(true || false); console.log(false || false); console.log(false || true);
jai-deepsource/carbonapi
expr/functions/cairo/png/graphutil.go
package png import ( "image/color" "strconv" "strings" ) func getBool(s string, def bool) bool { if s == "" { return def } switch s { case "True", "true", "1": return true case "False", "false", "0": return false } return def } func getString(s, def string) string { if s == "" { return def } return s } func getFloat64(s string, def float64) float64 { if s == "" { return def } n, err := strconv.ParseFloat(s, 64) if err != nil { return def } return n } func getInt(s string, def int) int { if s == "" { return def } n, err := strconv.ParseInt(s, 10, 32) if err != nil { return def } return int(n) } // For some reason, deepsource thinks this function is not used, even though it's actually used whenever Cairo is enabled. // skipcq: SCC-U1000 // lint:ignore U1000 - false-positive func string2RGBA(clr string) color.RGBA { if c, ok := colors[clr]; ok { return c } c, err := hexToRGBA(clr) if err != nil { return color.RGBA{0, 0, 0, 255} } return *c } // https://code.google.com/p/sadbox/source/browse/color/hex.go // hexToRGBA converts an Hex string to a RGB triple. func hexToRGBA(h string) (*color.RGBA, error) { var r, g, b uint8 if len(h) > 0 && h[0] == '#' { h = h[1:] } if len(h) == 3 { h = h[:1] + h[:1] + h[1:2] + h[1:2] + h[2:] + h[2:] } alpha := byte(255) if len(h) == 6 { if rgb, err := strconv.ParseUint(h, 16, 32); err == nil { r = uint8(rgb >> 16) g = uint8(rgb >> 8) b = uint8(rgb) } else { return nil, err } } if len(h) == 8 { if rgb, err := strconv.ParseUint(h, 16, 32); err == nil { r = uint8(rgb >> 24) g = uint8(rgb >> 16) b = uint8(rgb >> 8) alpha = uint8(rgb) } else { return nil, err } } return &color.RGBA{r, g, b, alpha}, nil } var colors = map[string]color.RGBA{ // Graphite default colors "black": {0x00, 0x00, 0x00, 0xff}, "white": {0xff, 0xff, 0xff, 0xff}, // blue is intentionally specified in that way (not really blue ;) ) to behave like graphite-web 1.1 "blue": {0x64, 0x64, 0xff, 0xff}, // green and darkgreen intentionally swapped. You can redefined that in config "green": {0x00, 0xc8, 0x00, 0xff}, // red and darkred intentionally swapped. You can redefined that in config "red": {0xc8, 0x00, 0x32, 0xff}, "yellow": {0xff, 0xff, 0x00, 0xff}, "orange": {0xff, 0xa5, 0x00, 0xff}, "purple": {0xc8, 0x64, 0xff, 0xff}, "brown": {0x96, 0x64, 0x32, 0xff}, "cyan": {0x00, 0xff, 0xff, 0xff}, "aqua": {0x00, 0x96, 0x96, 0xff}, "gray": {0xaf, 0xaf, 0xaf, 0xff}, "grey": {0xaf, 0xaf, 0xaf, 0xff}, "magenta": {0xff, 0x00, 0xff, 0xff}, "pink": {0xff, 0x64, 0x64, 0xff}, "gold": {0xc8, 0xc8, 0x00, 0xff}, "rose": {0xc8, 0x96, 0xc8, 0xff}, // darkblue is intentionally specified in that way to behave like graphite-web 1.1 "darkblue": {0x00, 0x00, 0xff, 0xff}, // green and darkgreen intentionally swapped. You can redefined that in config "darkgreen": {0x00, 0xff, 0x00, 0xff}, // red and darkred intentionally swapped. You can redefined that in config "darkred": {0xff, 0x00, 0x00, 0xff}, "darkgray": {0x6f, 0x6f, 0x6f, 0xff}, "darkgrey": {0x6f, 0x6f, 0x6f, 0xff}, // Custom colors "navy": {0x00, 0x00, 0x80, 0xff}, "mediumblue": {0x00, 0x00, 0xcd, 0xff}, "teal": {0x00, 0x80, 0x80, 0xff}, "darkcyan": {0x00, 0x8b, 0x8b, 0xff}, "deepskyblue": {0x00, 0xbf, 0xff, 0xff}, "darkturquoise": {0x00, 0xce, 0xd1, 0xff}, "mediumspringgreen": {0x00, 0xfa, 0x9a, 0xff}, "lime": {0x00, 0xff, 0x00, 0xff}, "springgreen": {0x00, 0xff, 0x7f, 0xff}, "midnightblue": {0x19, 0x19, 0x70, 0xff}, "dodgerblue": {0x1e, 0x90, 0xff, 0xff}, "lightseagreen": {0x20, 0xb2, 0xaa, 0xff}, "forestgreen": {0x22, 0x8b, 0x22, 0xff}, "seagreen": {0x2e, 0x8b, 0x57, 0xff}, "darkslategray": {0x2f, 0x4f, 0x4f, 0xff}, "limegreen": {0x32, 0xcd, 0x32, 0xff}, "mediumseagreen": {0x3c, 0xb3, 0x71, 0xff}, "turquoise": {0x40, 0xe0, 0xd0, 0xff}, "royalblue": {0x41, 0x69, 0xe1, 0xff}, "steelblue": {0x46, 0x82, 0xb4, 0xff}, "darkslateblue": {0x48, 0x3d, 0x8b, 0xff}, "mediumturquoise": {0x48, 0xd1, 0xcc, 0xff}, "indigo": {0x4b, 0x00, 0x82, 0xff}, "darkolivegreen": {0x55, 0x6b, 0x2f, 0xff}, "cadetblue": {0x5f, 0x9e, 0xa0, 0xff}, "cornflowerblue": {0x64, 0x95, 0xed, 0xff}, "mediumaquamarine": {0x66, 0xcd, 0xaa, 0xff}, "dimgray": {0x69, 0x69, 0x69, 0xff}, "slateblue": {0x6a, 0x5a, 0xcd, 0xff}, "olivedrab": {0x6b, 0x8e, 0x23, 0xff}, "slategray": {0x70, 0x80, 0x90, 0xff}, "lightslategray": {0x77, 0x88, 0x99, 0xff}, "mediumslateblue": {0x7b, 0x68, 0xee, 0xff}, "lawngreen": {0x7c, 0xfc, 0x00, 0xff}, "chartreuse": {0x7f, 0xff, 0x00, 0xff}, "aquamarine": {0x7f, 0xff, 0xd4, 0xff}, "lavender": {0xe6, 0xe6, 0xfa, 0xff}, "darksalmon": {0xe9, 0x96, 0x7a, 0xff}, "violet": {0xee, 0x82, 0xee, 0xff}, "palegoldenrod": {0xee, 0xe8, 0xaa, 0xff}, "lightcoral": {0xf0, 0x80, 0x80, 0xff}, "khaki": {0xf0, 0xe6, 0x8c, 0xff}, "aliceblue": {0xf0, 0xf8, 0xff, 0xff}, "honeydew": {0xf0, 0xff, 0xf0, 0xff}, "azure": {0xf0, 0xff, 0xff, 0xff}, "sandybrown": {0xf4, 0xa4, 0x60, 0xff}, "wheat": {0xf5, 0xde, 0xb3, 0xff}, "beige": {0xf5, 0xf5, 0xdc, 0xff}, "whitesmoke": {0xf5, 0xf5, 0xf5, 0xff}, "mintcream": {0xf5, 0xff, 0xfa, 0xff}, "ghostwhite": {0xf8, 0xf8, 0xff, 0xff}, "salmon": {0xfa, 0x80, 0x72, 0xff}, "antiquewhite": {0xfa, 0xeb, 0xd7, 0xff}, "linen": {0xfa, 0xf0, 0xe6, 0xff}, "lightgoldenrodyellow": {0xfa, 0xfa, 0xd2, 0xff}, "oldlace": {0xfd, 0xf5, 0xe6, 0xff}, "fuchsia": {0xff, 0x00, 0xff, 0xff}, "deeppink": {0xff, 0x14, 0x93, 0xff}, "orangered": {0xff, 0x45, 0x00, 0xff}, "tomato": {0xff, 0x63, 0x47, 0xff}, "hotpink": {0xff, 0x69, 0xb4, 0xff}, "coral": {0xff, 0x7f, 0x50, 0xff}, "darkorange": {0xff, 0x8c, 0x00, 0xff}, "lightsalmon": {0xff, 0xa0, 0x7a, 0xff}, "lightpink": {0xff, 0xb6, 0xc1, 0xff}, "peachpuff": {0xff, 0xda, 0xb9, 0xff}, "navajowhite": {0xff, 0xde, 0xad, 0xff}, "moccasin": {0xff, 0xe4, 0xb5, 0xff}, "bisque": {0xff, 0xe4, 0xc4, 0xff}, "mistyrose": {0xff, 0xe4, 0xe1, 0xff}, "blanchedalmond": {0xff, 0xeb, 0xcd, 0xff}, "papayawhip": {0xff, 0xef, 0xd5, 0xff}, "lavenderblush": {0xff, 0xf0, 0xf5, 0xff}, "seashell": {0xff, 0xf5, 0xee, 0xff}, "cornsilk": {0xff, 0xf8, 0xdc, 0xff}, "lemonchiffon": {0xff, 0xfa, 0xcd, 0xff}, "floralwhite": {0xff, 0xfa, 0xf0, 0xff}, "snow": {0xff, 0xfa, 0xfa, 0xff}, "lightyellow": {0xff, 0xff, 0xe0, 0xff}, "ivory": {0xff, 0xff, 0xf0, 0xff}, "graphiteblue": {0x64, 0x64, 0xff, 0xff}, } func SetColor(name, rgba string) error { color, err := hexToRGBA(rgba) if err != nil { return err } name = strings.ToLower(name) colors[name] = *color return nil }
slemjet/problems_and_solutions
questions_leetcode/medium/src/main/java/us/slemjet/leetcode/medium/tasks_451_500/FourSumII.java
<filename>questions_leetcode/medium/src/main/java/us/slemjet/leetcode/medium/tasks_451_500/FourSumII.java package us.slemjet.leetcode.medium.tasks_451_500; import java.util.HashMap; /** * 454. 4Sum II */ public class FourSumII { /** * Runtime: 14.22% * Memory Usage: 5.10% */ public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { int sum = 0; HashMap<Integer, Integer> complementsSum34Count = new HashMap<>(); for (int num3 : nums3) { for (int num4 : nums4) { int sum34 = num3 + num4; if (!complementsSum34Count.containsKey(-sum34)) complementsSum34Count.put(-sum34, 0); complementsSum34Count.put(-sum34, complementsSum34Count.get(-sum34) + 1); } } for (int num1 : nums1) { for (int num2 : nums2) { int sum12 = num1 + num2; if (complementsSum34Count.containsKey(sum12)) sum += complementsSum34Count.get(sum12); } } return sum; } /** * Time limit exceeded */ public int fourSumCount2(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { int sum = 0; HashMap<Integer, Integer> complementsNums4Count = new HashMap<>(); for (int num4 : nums4) { if (!complementsNums4Count.containsKey(-num4)) complementsNums4Count.put(-num4, 0); complementsNums4Count.put(-num4, complementsNums4Count.get(-num4) + 1); } for (int num1 : nums1) { for (int num2 : nums2) { for (int num3 : nums3) { int sum3 = num1 + num2 + num3; if (complementsNums4Count.containsKey(sum3)) { sum += complementsNums4Count.get(sum3); } } } } return sum; } /** * Time limit exceeded */ public int fourSumCountBrute(int[] nums1, int[] nums2, int[] nums3, int[] nums4) { int sum = 0; for (int num1 : nums1) { for (int num2 : nums2) { for (int num3 : nums3) { for (int num4 : nums4) { if (num1 + num2 + num3 + num4 == 0) sum++; } } } } return sum; } }
bingchunjin/1806_SDK
uboot/arch/arc/include/asm/sections.h
/* * Copyright (C) 2013-2014 Synopsys, Inc. All rights reserved. * * SPDX-License-Identifier: GPL-2.0+ */ #ifndef __ASM_ARC_SECTIONS_H #define __ASM_ARC_SECTIONS_H #include <asm-generic/sections.h> extern ulong __text_end; extern ulong __ivt_start; extern ulong __ivt_end; extern ulong __image_copy_start; #endif /* __ASM_ARC_SECTIONS_H */
RichardBarry/core-v-freertos
target/core-v-mcu/include/system_core_v_mcu_metal.h
/* * Copyright 2020 ETH Zurich * * 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. * * SPDX-License-Identifier: Apache-2.0 * Author: <NAME> (<EMAIL>) */ #ifndef __SYSTEM_CORE_V_MCU_METAL_H #define __SYSTEM_CORE_V_MCU_METAL_H #include <stdint.h> #include <stdbool.h> #include "FreeRTOSConfig.h" /* PULPissimo defs */ #define PULPISSIMO #define ARCHI_FPGA_FREQUENCY 5000000 #define ARCHI_REF_CLOCK_LOG2 15 #define ARCHI_REF_CLOCK (1 << ARCHI_REF_CLOCK_LOG2) /* hardware modules */ #define ARCHI_NUM_TIMER 1 #define ARCHI_NUM_FLL 2 /* TODO: clean up those macros */ #define ARCHI_FPGA_FREQUENCY 5000000 #define ARCHI_REF_CLOCK_LOG2 15 #define ARCHI_REF_CLOCK (1 << ARCHI_REF_CLOCK_LOG2) #define ARCHI_NB_FLL 2 #define RT_FREQ_NB_DOMAIN 2 #define __RT_FLL_CL 2 #define __RT_FLL_PERIPH 1 #define __RT_FLL_FC 0 #define __RT_FREQ_DOMAIN_FC 0 #define __RT_FREQ_DOMAIN_CL 2 #define __RT_FREQ_DOMAIN_PERIPH 1 #define RT_FREQ_NB_DOMAIN 2 extern volatile uint32_t system_core_clock; void system_init(void); void system_core_clock_update(void); #endif /* __SYSTEM_CORE_V_MCU_METAL_H */
DrFaust92/terraformer
vendor/github.com/aws/aws-sdk-go-v2/service/cloudfront/api_op_UpdateFieldLevelEncryptionProfile.go
<reponame>DrFaust92/terraformer // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package cloudfront import ( "context" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/internal/awsutil" "github.com/aws/aws-sdk-go-v2/private/protocol" ) type UpdateFieldLevelEncryptionProfileInput struct { _ struct{} `type:"structure" payload:"FieldLevelEncryptionProfileConfig"` // Request to update a field-level encryption profile. // // FieldLevelEncryptionProfileConfig is a required field FieldLevelEncryptionProfileConfig *FieldLevelEncryptionProfileConfig `locationName:"FieldLevelEncryptionProfileConfig" type:"structure" required:"true" xmlURI:"http://cloudfront.amazonaws.com/doc/2019-03-26/"` // The ID of the field-level encryption profile request. // // Id is a required field Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` // The value of the ETag header that you received when retrieving the profile // identity to update. For example: E2QWRUHAPOMQZL. IfMatch *string `location:"header" locationName:"If-Match" type:"string"` } // String returns the string representation func (s UpdateFieldLevelEncryptionProfileInput) String() string { return awsutil.Prettify(s) } // Validate inspects the fields of the type to determine if they are valid. func (s *UpdateFieldLevelEncryptionProfileInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "UpdateFieldLevelEncryptionProfileInput"} if s.FieldLevelEncryptionProfileConfig == nil { invalidParams.Add(aws.NewErrParamRequired("FieldLevelEncryptionProfileConfig")) } if s.Id == nil { invalidParams.Add(aws.NewErrParamRequired("Id")) } if s.FieldLevelEncryptionProfileConfig != nil { if err := s.FieldLevelEncryptionProfileConfig.Validate(); err != nil { invalidParams.AddNested("FieldLevelEncryptionProfileConfig", err.(aws.ErrInvalidParams)) } } if invalidParams.Len() > 0 { return invalidParams } return nil } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UpdateFieldLevelEncryptionProfileInput) MarshalFields(e protocol.FieldEncoder) error { if s.IfMatch != nil { v := *s.IfMatch metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "If-Match", protocol.StringValue(v), metadata) } if s.Id != nil { v := *s.Id metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "Id", protocol.StringValue(v), metadata) } if s.FieldLevelEncryptionProfileConfig != nil { v := s.FieldLevelEncryptionProfileConfig metadata := protocol.Metadata{XMLNamespaceURI: "http://cloudfront.amazonaws.com/doc/2019-03-26/"} e.SetFields(protocol.PayloadTarget, "FieldLevelEncryptionProfileConfig", v, metadata) } return nil } type UpdateFieldLevelEncryptionProfileOutput struct { _ struct{} `type:"structure" payload:"FieldLevelEncryptionProfile"` // The result of the field-level encryption profile request. ETag *string `location:"header" locationName:"ETag" type:"string"` // Return the results of updating the profile. FieldLevelEncryptionProfile *FieldLevelEncryptionProfile `type:"structure"` } // String returns the string representation func (s UpdateFieldLevelEncryptionProfileOutput) String() string { return awsutil.Prettify(s) } // MarshalFields encodes the AWS API shape using the passed in protocol encoder. func (s UpdateFieldLevelEncryptionProfileOutput) MarshalFields(e protocol.FieldEncoder) error { if s.ETag != nil { v := *s.ETag metadata := protocol.Metadata{} e.SetValue(protocol.HeaderTarget, "ETag", protocol.StringValue(v), metadata) } if s.FieldLevelEncryptionProfile != nil { v := s.FieldLevelEncryptionProfile metadata := protocol.Metadata{} e.SetFields(protocol.PayloadTarget, "FieldLevelEncryptionProfile", v, metadata) } return nil } const opUpdateFieldLevelEncryptionProfile = "UpdateFieldLevelEncryptionProfile2019_03_26" // UpdateFieldLevelEncryptionProfileRequest returns a request value for making API operation for // Amazon CloudFront. // // Update a field-level encryption profile. // // // Example sending a request using UpdateFieldLevelEncryptionProfileRequest. // req := client.UpdateFieldLevelEncryptionProfileRequest(params) // resp, err := req.Send(context.TODO()) // if err == nil { // fmt.Println(resp) // } // // Please also see https://docs.aws.amazon.com/goto/WebAPI/cloudfront-2019-03-26/UpdateFieldLevelEncryptionProfile func (c *Client) UpdateFieldLevelEncryptionProfileRequest(input *UpdateFieldLevelEncryptionProfileInput) UpdateFieldLevelEncryptionProfileRequest { op := &aws.Operation{ Name: opUpdateFieldLevelEncryptionProfile, HTTPMethod: "PUT", HTTPPath: "/2019-03-26/field-level-encryption-profile/{Id}/config", } if input == nil { input = &UpdateFieldLevelEncryptionProfileInput{} } req := c.newRequest(op, input, &UpdateFieldLevelEncryptionProfileOutput{}) return UpdateFieldLevelEncryptionProfileRequest{Request: req, Input: input, Copy: c.UpdateFieldLevelEncryptionProfileRequest} } // UpdateFieldLevelEncryptionProfileRequest is the request type for the // UpdateFieldLevelEncryptionProfile API operation. type UpdateFieldLevelEncryptionProfileRequest struct { *aws.Request Input *UpdateFieldLevelEncryptionProfileInput Copy func(*UpdateFieldLevelEncryptionProfileInput) UpdateFieldLevelEncryptionProfileRequest } // Send marshals and sends the UpdateFieldLevelEncryptionProfile API request. func (r UpdateFieldLevelEncryptionProfileRequest) Send(ctx context.Context) (*UpdateFieldLevelEncryptionProfileResponse, error) { r.Request.SetContext(ctx) err := r.Request.Send() if err != nil { return nil, err } resp := &UpdateFieldLevelEncryptionProfileResponse{ UpdateFieldLevelEncryptionProfileOutput: r.Request.Data.(*UpdateFieldLevelEncryptionProfileOutput), response: &aws.Response{Request: r.Request}, } return resp, nil } // UpdateFieldLevelEncryptionProfileResponse is the response type for the // UpdateFieldLevelEncryptionProfile API operation. type UpdateFieldLevelEncryptionProfileResponse struct { *UpdateFieldLevelEncryptionProfileOutput response *aws.Response } // SDKResponseMetdata returns the response metadata for the // UpdateFieldLevelEncryptionProfile request. func (r *UpdateFieldLevelEncryptionProfileResponse) SDKResponseMetdata() *aws.Response { return r.response }
dhis2/d2-import-export-app
src/components/Inputs/ObjectType.js
<filename>src/components/Inputs/ObjectType.js<gh_stars>0 import i18n from '@dhis2/d2-i18n' import { SingleSelectFieldFF } from '@dhis2/ui' import React from 'react' import { StyledField } from '../index.js' const objectTypeOptions = [ { value: 'dataSets', label: i18n.t('Data sets') }, { value: 'programs', label: i18n.t('Programs') }, { value: 'categoryCombos', label: i18n.t('Category combination') }, { value: 'dashboards', label: i18n.t('Dashboard') }, { value: 'dataElementGroups', label: i18n.t('Data element groups') }, { value: 'optionSets', label: i18n.t('Option sets') }, ] const defaultObjectTypeOption = objectTypeOptions[0].value const NAME = 'objectType' const LABEL = i18n.t('Object type') const DATATEST = 'input-object-type' const ObjectType = () => ( <div style={{ maxWidth: '480px' }}> <StyledField component={SingleSelectFieldFF} name={NAME} label={LABEL} options={objectTypeOptions} dataTest={DATATEST} filled initialFocus /> </div> ) export { ObjectType, defaultObjectTypeOption }
tedteng/test-infra
pkg/testmachinery/testflow/flow.go
// Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file. // // 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 testflow import ( argov1 "github.com/argoproj/argo/v2/pkg/apis/workflow/v1alpha1" corev1 "k8s.io/api/core/v1" tmv1beta1 "github.com/gardener/test-infra/pkg/apis/testmachinery/v1beta1" "github.com/gardener/test-infra/pkg/testmachinery" "github.com/gardener/test-infra/pkg/testmachinery/config" "github.com/gardener/test-infra/pkg/testmachinery/locations" "github.com/gardener/test-infra/pkg/testmachinery/locations/location" "github.com/gardener/test-infra/pkg/testmachinery/testflow/node" ) // NewFlow takes a testflow and the global config, and generates the DAG. // It generates an internal DAG representation and creates the corresponding argo DAG and templates. func NewFlow(flowID FlowIdentifier, root *node.Node, tf tmv1beta1.TestFlow, loc locations.Locations, globalConfig []*config.Element) (*Flow, error) { steps, testdefinitions, usedLocations, err := preprocessTestflow(flowID, root, tf, loc, globalConfig) if err != nil { return nil, err } flow := &Flow{ ID: flowID, Root: root, steps: steps, globalConfig: globalConfig, testdefinitions: testdefinitions, usedLocations: usedLocations, } flow.testdefinitions[root.TestDefinition] = nil // Go through all steps and create the initial DAG CreateInitialDAG(steps, root) // Reorder the dag so that tests with serial behavior run in serial within their sub DAG. ReorderChildrenOfNodes(node.NewSet(root)) // Determine kubeconfigs namespaces // which means to determine what kubeconfig artifact should be mounted to a specific node if err := ApplyOutputScope(steps); err != nil { return nil, err } ApplyConfigScope(steps) // Determine real serial steps SetSerialNodes(root) return flow, nil } // GetTemplates returns all TestDefinitions templates and the DAG of the testrun func (f *Flow) GetTemplates() ([]argov1.Template, error) { var templates []argov1.Template for td := range f.testdefinitions { newTemplate, err := td.GetTemplate() if err != nil { return nil, err } templates = append(templates, *newTemplate) } return templates, nil } // GetVolumes returns all volumes of local TestDefLocations and // used configuration with a reference to a secret or configuration. func (f *Flow) GetVolumes() []corev1.Volume { var volumes []corev1.Volume for loc := range f.usedLocations { if loc.Type() == tmv1beta1.LocationTypeLocal { local := loc.(*location.LocalLocation) volumes = append(volumes, local.GetVolume()) } } volumeSet := make(map[string]bool) for _, vol := range f.Root.TestDefinition.Volumes { if _, ok := volumeSet[vol.Name]; !ok { volumes = append(volumes, vol) volumeSet[vol.Name] = true } } for n := range f.Iterate() { for _, vol := range n.TestDefinition.Volumes { if _, ok := volumeSet[vol.Name]; !ok { volumes = append(volumes, vol) volumeSet[vol.Name] = true } } } return volumes } // Iterate iterates over the flow and returns their nodes. func (f *Flow) Iterate() <-chan *node.Node { c := make(chan *node.Node) go func() { c <- f.Root for _, step := range f.steps { for n := range step.Nodes.Iterate() { c <- n } } close(c) }() return c } func (f *Flow) GetDAGTemplate(phase testmachinery.Phase) *argov1.DAGTemplate { dag := &argov1.DAGTemplate{} for n := range f.Iterate() { dag.Tasks = append(dag.Tasks, n.Task(phase)...) } return dag } // GetStatuses returns the status of all nodes of the current flow. func (f *Flow) GetStatuses() []*tmv1beta1.StepStatus { status := make([]*tmv1beta1.StepStatus, 0) for n := range f.Iterate() { status = append(status, n.Status()) } // remove root element from status as this is the tm prepare step return status[1:] }
bayramcicek/py-repo
java-rep/java009/J_dog.java
package java009; /** * created by cicek on 03.11.2018 23:00 */ public class J_dog extends J_cat { // public void makeSound(){ // System.out.printf("Dooooog!!!\n"); //// super.makeSound(); // } }
pilif0/open-desert
src/main/java/net/pilif0/open_desert/ecs/ComponentFieldException.java
<gh_stars>0 package net.pilif0.open_desert.ecs; /** * Exception for when a there is problem with a component field when instantiating the component. * * @author <NAME> * @version 1.0 */ public class ComponentFieldException extends RuntimeException { public ComponentFieldException(String message) { super(message); } public ComponentFieldException(String message, Throwable cause) { super(message, cause); } }
alonmm/VCSamples
VC2010Samples/MFC/controls/localize/localctl.cpp
// localctl.cpp : Implementation of the CLocalizeCtrl OLE control class. // // This is a part of the Microsoft Foundation Classes C++ library. // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #include "localize.h" #include "localctl.h" #include "localppg.h" #ifdef _WIN32 #include <winnt.h> #else #include <olenls.h> #endif #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif IMPLEMENT_DYNCREATE(CLocalizeCtrl, COleControl) ///////////////////////////////////////////////////////////////////////////// // Message map BEGIN_MESSAGE_MAP(CLocalizeCtrl, COleControl) //{{AFX_MSG_MAP(CLocalizeCtrl) ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_CANCELMODE() //}}AFX_MSG_MAP ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // Dispatch map BEGIN_DISPATCH_MAP(CLocalizeCtrl, COleControl) //{{AFX_DISPATCH_MAP(CLocalizeCtrl) DISP_PROPERTY_NOTIFY(CLocalizeCtrl, "Invert", m_invert, OnInvertChanged, VT_BOOL) DISP_STOCKPROP_CAPTION() //}}AFX_DISPATCH_MAP DISP_FUNCTION_ID(CLocalizeCtrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VTS_NONE) END_DISPATCH_MAP() ///////////////////////////////////////////////////////////////////////////// // Event map BEGIN_EVENT_MAP(CLocalizeCtrl, COleControl) //{{AFX_EVENT_MAP(CLocalizeCtrl) EVENT_CUSTOM_ID("Click", DISPID_CLICK, FireClick, VTS_NONE) //}}AFX_EVENT_MAP END_EVENT_MAP() ///////////////////////////////////////////////////////////////////////////// // Property pages // TODO: Add more property pages as needed. Remember to increase the count! BEGIN_PROPPAGEIDS(CLocalizeCtrl, 1) PROPPAGEID(CLocalizePropPage::guid) END_PROPPAGEIDS(CLocalizeCtrl) ///////////////////////////////////////////////////////////////////////////// // Initialize class factory and guid IMPLEMENT_OLECREATE_EX(CLocalizeCtrl, "LOCALIZE.LocalizeCtrl.1", 0x879d6fe0, 0x5470, 0x101b, 0xb5, 0x7b, 0x0, 0x60, 0x8c, 0xc9, 0x6a, 0xfa) ///////////////////////////////////////////////////////////////////////////// // Type library ID and version IMPLEMENT_OLETYPELIB(CLocalizeCtrl, _tlid, _wVerMajor, _wVerMinor) ///////////////////////////////////////////////////////////////////////////// // Interface IDs const IID BASED_CODE IID_DLocalize = { 0x35e3e52, 0x6745, 0x101b, { 0xb5, 0x7b, 0x0, 0x60, 0x8c, 0xc9, 0x6a, 0xfa } }; const IID BASED_CODE IID_DLocalizeEvents = { 0x35e3e53, 0x6745, 0x101b, { 0xb5, 0x7b, 0x0, 0x60, 0x8c, 0xc9, 0x6a, 0xfa } }; ///////////////////////////////////////////////////////////////////////////// // Control type information static const DWORD BASED_CODE _dwLocalizeOleMisc = OLEMISC_ACTIVATEWHENVISIBLE | OLEMISC_SETCLIENTSITEFIRST | OLEMISC_INSIDEOUT | OLEMISC_CANTLINKINSIDE | OLEMISC_RECOMPOSEONRESIZE; IMPLEMENT_OLECTLTYPE(CLocalizeCtrl, IDS_LOCALIZE, _dwLocalizeOleMisc) ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::CLocalizeCtrlFactory::UpdateRegistry - // Adds or removes system registry entries for CLocalizeCtrl BOOL CLocalizeCtrl::CLocalizeCtrlFactory::UpdateRegistry(BOOL bRegister) { if (bRegister) return AfxOleRegisterControlClass( AfxGetInstanceHandle(), m_clsid, m_lpszProgID, IDS_LOCALIZE, IDB_LOCALIZE, FALSE, // Not insertable _dwLocalizeOleMisc, _tlid, _wVerMajor, _wVerMinor); else return AfxOleUnregisterClass(m_clsid, m_lpszProgID); } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::CLocalizeCtrl - Constructor CLocalizeCtrl::CLocalizeCtrl() { InitializeIIDs(&IID_DLocalize, &IID_DLocalizeEvents); // Initialize inverted flag m_inverted = FALSE; } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::~CLocalizeCtrl - Destructor CLocalizeCtrl::~CLocalizeCtrl() { } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::OnDraw - Drawing function void CLocalizeCtrl::OnDraw( CDC* pdc, const CRect& rcBounds, const CRect&) { CFont *pOldFont; TEXTMETRIC tm; // Load localized caption as Caption property const CString& strCaption = InternalGetText(); // Draw caption pOldFont = SelectStockFont(pdc); pdc->SetTextAlign(TA_CENTER | TA_TOP); GetStockTextMetrics(&tm); pdc->ExtTextOut((rcBounds.left + rcBounds.right) / 2, (rcBounds.top + rcBounds.bottom - tm.tmHeight) / 2, ETO_CLIPPED | ETO_OPAQUE, rcBounds, strCaption, strCaption.GetLength(), NULL); pdc->SelectObject(pOldFont); } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::DoPropExchange - Persistence support void CLocalizeCtrl::DoPropExchange(CPropExchange* pPX) { ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor)); COleControl::DoPropExchange(pPX); PX_Bool(pPX, _T("Invert"), m_invert, TRUE); if (pPX->IsLoading()) { CFontHolder& stockFont = InternalGetFont(); stockFont.InitializeFont(); } } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::OnResetState - Reset control to default state void CLocalizeCtrl::OnResetState() { COleControl::OnResetState(); // Resets defaults found in DoPropExchange LoadCaption(); } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::AboutBox - Display a localized "About" box to the user void CLocalizeCtrl::AboutBox() { BOOL bError = FALSE; // Load resource module HINSTANCE hResHandle = GetResourceHandle(AmbientLocaleID()); if (!hResHandle) bError = TRUE; if (!bError) { // Load dialog resource from resource module HINSTANCE hResPrev = AfxGetResourceHandle(); AfxSetResourceHandle(hResHandle); // Execute dialog CDialog dlgAbout(IDD_ABOUTBOX_LOCALIZE); dlgAbout.DoModal(); AfxSetResourceHandle(hResPrev); FreeLibrary(hResHandle); } else { // Execute dialog, using resource in control module CDialog dlgAbout(IDD_ABOUTBOX_LOCALIZE); dlgAbout.DoModal(); } } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::OnInvertChanged sets the modified flag of the control void CLocalizeCtrl::OnInvertChanged() { SetModifiedFlag(); } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::OnLButtonDown inverts the control if the Invert property // is TRUE void CLocalizeCtrl::OnLButtonDown(UINT nFlags, CPoint point) { CDC* pdc; CRect cRect; // If Invert property is set to TRUE if (m_invert) { // Invert the control pdc = GetDC(); GetClientRect(&cRect); pdc->InvertRect(&cRect); ReleaseDC(pdc); // Capture the mouse SetCapture(); // Set inverted flag m_inverted = TRUE; } COleControl::OnLButtonDown(nFlags, point); } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::OnLButtonUp fires the Click event. First releases the // mouse capture and invalidates the control, if the control was inverted // and the mouse was captured in OnLButtonDown. void CLocalizeCtrl::OnLButtonUp(UINT nFlags, CPoint point) { // If inverted flag is set if (m_inverted) { // Release the mouse ReleaseCapture(); // Invalidate to redraw (without inversion) InvalidateControl(); // Reset inverted flag m_inverted = FALSE; } COleControl::OnLButtonUp(nFlags, point); // Fire click event FireClick(); } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::OnCancelMode invalidates the control if the control was // inverted in OnLButtonDown. void CLocalizeCtrl::OnCancelMode() { // If inverted flag is set if (m_inverted) { // Invalidate to redraw (without inversion) InvalidateControl(); // Reset inverted flag m_inverted = FALSE; } // Default processing will release the mouse, if captured COleControl::OnCancelMode(); } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::OnAmbientPropertyChange - Reload locale-specific caption // and invalidate if the ambient LocaleID has changed. void CLocalizeCtrl::OnAmbientPropertyChange(DISPID dispid) { if (dispid == DISPID_AMBIENT_LOCALEID) { LoadCaption(); InvalidateControl(); } } ///////////////////////////////////////////////////////////////////////////// // CLocalizeCtrl::LoadCaption - Load the locale-specific caption of the // control. void CLocalizeCtrl::LoadCaption() { CString caption; BOOL bError = FALSE; // Get the handle of the resource module HINSTANCE hResHandle = GetResourceHandle(AmbientLocaleID()); if (!hResHandle) bError = TRUE; if (!bError) { // Load caption from resource module HINSTANCE hResPrev = AfxGetResourceHandle(); AfxSetResourceHandle(hResHandle); caption.LoadString(IDS_CAPTION); AfxSetResourceHandle(hResPrev); FreeLibrary(hResHandle); } else // Load caption from control module resource caption.LoadString(IDS_CAPTION); // Set caption property SetText(caption); } ///////////////////////////////////////////////////////////////////////////// // CLocalizePropPage::GetResourceHandle - Load module which contains // locale-specific resources HINSTANCE CLocalizeCtrl::GetResourceHandle(LCID lcid) { LPCTSTR lpszResModule = NULL; HINSTANCE hResHandle = NULL; // Use lcid to determine module that contains resources LANGID langID = LANGIDFROMLCID(lcid); unsigned short priLangID = (unsigned short) PRIMARYLANGID(langID); switch (priLangID) { case LANG_ENGLISH: break; case LANG_FRENCH: #ifdef _WIN32 lpszResModule = (LPCTSTR)_T("lresfr32.dll"); #else lpszResModule = (LPCTSTR)_T("locresfr.dll"); #endif break; case LANG_GERMAN: #ifdef _WIN32 lpszResModule = (LPCTSTR)_T("lresde32.dll"); #else lpszResModule = (LPCTSTR)_T("locresde.dll"); #endif break; case 0: default: break; } // Load resource module if (lpszResModule != NULL) hResHandle = LoadLibrary(lpszResModule); #ifndef _WIN32 if (hResHandle <= HINSTANCE_ERROR) hResHandle = NULL; #endif return hResHandle; }
spacemonkeydelivers/riscv_security_contest_project
tests/c/libc_sec/ns_malloc/ns_malloc.c
<reponame>spacemonkeydelivers/riscv_security_contest_project<gh_stars>1-10 #include <soc/traps.h> #include <stdlib.h> #include <stdio.h> void secure_monitor(int n, void* context) { (void)context; if (n == RISCV_INT_SM_PANIC) { printf("security panic detected! Test Failure!\n"); exit(EXIT_FAILURE); } } int main () { register_int_handler(RISCV_INT_SM_PANIC, &secure_monitor); unsigned char* ptr = (unsigned char*)malloc(64); if (ptr) { for (int i = 0; i < 64; ++i) { ptr[i] = i; } ptr[65] = 0; // no security, no boom :( return EXIT_SUCCESS; } return EXIT_FAILURE; }
rolfyone/discovery
src/main/java/org/ethereum/beacon/discovery/message/handler/TalkReqHandler.java
<filename>src/main/java/org/ethereum/beacon/discovery/message/handler/TalkReqHandler.java /* * SPDX-License-Identifier: Apache-2.0 */ package org.ethereum.beacon.discovery.message.handler; import java.util.concurrent.CompletableFuture; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.tuweni.bytes.Bytes; import org.ethereum.beacon.discovery.TalkHandler; import org.ethereum.beacon.discovery.message.TalkReqMessage; import org.ethereum.beacon.discovery.message.TalkRespMessage; import org.ethereum.beacon.discovery.schema.NodeRecord; import org.ethereum.beacon.discovery.schema.NodeSession; public class TalkReqHandler implements MessageHandler<TalkReqMessage> { private static final Logger logger = LogManager.getLogger(); private final TalkHandler appTalkHandler; public TalkReqHandler(TalkHandler appTalkHandler) { this.appTalkHandler = appTalkHandler; } @Override public void handle(TalkReqMessage message, NodeSession session) { final NodeRecord srcNode = session.getNodeRecord().orElseThrow(); CompletableFuture<Bytes> response = appTalkHandler.talk(srcNode, message.getProtocol(), message.getRequest()); response .thenAccept( respBytes -> { TalkRespMessage respMessage = new TalkRespMessage(message.getRequestId(), respBytes); session.sendOutgoingOrdinary(respMessage); }) .exceptionally( err -> { logger.debug("Application TalkHandler completed with error", err); return null; }); } }
deepsec-inc/deepchain
core/ledger/util/txvalidationflags_test.go
/* Copyright IBM Corp. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package util import ( "testing" "deepchain/protos/peer" "github.com/stretchr/testify/assert" ) func TestTransactionValidationFlags(t *testing.T) { txFlags := NewTxValidationFlagsSetValue(10, peer.TxValidationCode_VALID) assert.Equal(t, 10, len(txFlags)) txFlags.SetFlag(0, peer.TxValidationCode_VALID) assert.Equal(t, peer.TxValidationCode_VALID, txFlags.Flag(0)) assert.Equal(t, true, txFlags.IsValid(0)) txFlags.SetFlag(1, peer.TxValidationCode_MVCC_READ_CONFLICT) assert.Equal(t, true, txFlags.IsInvalid(1)) }
bmresearch/ccex
ftx/models/websocket/operations.go
<reponame>bmresearch/ccex package websocket type ( // BaseOperation is the base of the message, all common attributes. BaseOperation struct { Op string `json:"op"` } // AuthenticationMessage holds the authentication-relevant information. AuthenticationMessage struct { Key string `json:"key"` Signature string `json:"sign"` Timestamp string `json:"time"` } // LoginMessage is used to authenticate with the websocket server. LoginMessage struct { BaseOperation AuthenticationMessage `json:"args"` } // SubscribeMessage is used to request a subscription to a channel. SubscribeMessage struct { BaseOperation Channel string `json:"channel"` Market string `json:"market"` } )
ggcaponetto/nunuStudio
source/editor/gui/tab/scene/controls/EditorControls.js
"use strict"; /** * A editor controls objects is used to control the camera inside of the editor. * * @class EditorControls * @extends {THREE.Group} */ function EditorControls() { THREE.Group.call(this); /** * Camera object attached to this controls. * * @property camera * @type {Object3D} */ this.camera = null; } EditorControls.prototype = Object.create(THREE.Group.prototype); /** * Attach a camera to this controls object. * * @method attach * @param {Camera} camera */ EditorControls.prototype.attach = function(camera) { while(this.children.length > 0) { this.remove(this.children[0]); } this.add(camera); this.camera = camera; this.updateControls(); }; /** * Reset the controls to its original position. * * @method reset */ EditorControls.prototype.reset = function(){}; /** * Focus camera on a object. * * @method focusObject * @param {THREE.Object3D} object Object to point camera at. */ EditorControls.prototype.focusObject = function(object){}; /** * Set controls orientation, using orientation code form OrientationCube * * @method setOrientation */ EditorControls.prototype.setOrientation = function(orientation){}; /** * Update the orbit controls position, the keyboard movement should be optional. * * @method update * @param {Mouse} mouse * @param {Keyboard} keyboard * @param {Number} delta Time passed after from the last update. */ EditorControls.prototype.update = function(mouse, keyboard, delta){}; /** * Update controls position and rotation. * * Should be called if some of its properties are changed manually. * * @method updateControls */ EditorControls.prototype.updateControls = function(){};
imxiangpeng/webrtc
modules/remote_bitrate_estimator/tools/bwe_rtp_play.cc
<filename>modules/remote_bitrate_estimator/tools/bwe_rtp_play.cc /* * Copyright (c) 2014 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <stdio.h> #include <memory> #include "webrtc/base/format_macros.h" #include "webrtc/modules/remote_bitrate_estimator/include/remote_bitrate_estimator.h" #include "webrtc/modules/remote_bitrate_estimator/tools/bwe_rtp.h" #include "webrtc/modules/rtp_rtcp/include/rtp_header_parser.h" #include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h" #include "webrtc/test/rtp_file_reader.h" class Observer : public webrtc::RemoteBitrateObserver { public: explicit Observer(webrtc::Clock* clock) : clock_(clock) {} // Called when a receive channel group has a new bitrate estimate for the // incoming streams. virtual void OnReceiveBitrateChanged(const std::vector<uint32_t>& ssrcs, uint32_t bitrate) { printf("[%u] Num SSRCs: %d, bitrate: %u\n", static_cast<uint32_t>(clock_->TimeInMilliseconds()), static_cast<int>(ssrcs.size()), bitrate); } virtual ~Observer() {} private: webrtc::Clock* clock_; }; int main(int argc, char** argv) { webrtc::test::RtpFileReader* reader; webrtc::RemoteBitrateEstimator* estimator; webrtc::RtpHeaderParser* parser; std::string estimator_used; webrtc::SimulatedClock clock(0); Observer observer(&clock); if (!ParseArgsAndSetupEstimator(argc, argv, &clock, &observer, &reader, &parser, &estimator, &estimator_used)) { return -1; } std::unique_ptr<webrtc::test::RtpFileReader> rtp_reader(reader); std::unique_ptr<webrtc::RtpHeaderParser> rtp_parser(parser); std::unique_ptr<webrtc::RemoteBitrateEstimator> rbe(estimator); // Process the file. int packet_counter = 0; int64_t next_rtp_time_ms = 0; int64_t first_rtp_time_ms = -1; int abs_send_time_count = 0; int ts_offset_count = 0; webrtc::test::RtpPacket packet; if (!rtp_reader->NextPacket(&packet)) { printf("No RTP packet found\n"); return 0; } first_rtp_time_ms = packet.time_ms; packet.time_ms = packet.time_ms - first_rtp_time_ms; while (true) { if (next_rtp_time_ms <= clock.TimeInMilliseconds()) { if (!parser->IsRtcp(packet.data, packet.length)) { webrtc::RTPHeader header; parser->Parse(packet.data, packet.length, &header); if (header.extension.hasAbsoluteSendTime) ++abs_send_time_count; if (header.extension.hasTransmissionTimeOffset) ++ts_offset_count; size_t packet_length = packet.length; // Some RTP dumps only include the header, in which case packet.length // is equal to the header length. In those cases packet.original_length // usually contains the original packet length. if (packet.original_length > 0) { packet_length = packet.original_length; } rbe->IncomingPacket(clock.TimeInMilliseconds(), packet_length - header.headerLength, header); ++packet_counter; } if (!rtp_reader->NextPacket(&packet)) { break; } packet.time_ms = packet.time_ms - first_rtp_time_ms; next_rtp_time_ms = packet.time_ms; } int64_t time_until_process_ms = rbe->TimeUntilNextProcess(); if (time_until_process_ms <= 0) { rbe->Process(); } int64_t time_until_next_event = std::min(rbe->TimeUntilNextProcess(), next_rtp_time_ms - clock.TimeInMilliseconds()); clock.AdvanceTimeMilliseconds(std::max<int64_t>(time_until_next_event, 0)); } printf("Parsed %d packets\nTime passed: %" PRId64 " ms\n", packet_counter, clock.TimeInMilliseconds()); printf("Estimator used: %s\n", estimator_used.c_str()); printf("Packets with absolute send time: %d\n", abs_send_time_count); printf("Packets with timestamp offset: %d\n", ts_offset_count); printf("Packets with no extension: %d\n", packet_counter - ts_offset_count - abs_send_time_count); return 0; }
solidnerd/terraform-provider-acsengine
internal/operations/client.go
package operations import ( "context" "fmt" "path" "github.com/Azure/acs-engine/pkg/acsengine" "github.com/Azure/acs-engine/pkg/api" "github.com/Azure/acs-engine/pkg/armhelpers" "github.com/Azure/acs-engine/pkg/helpers" "github.com/Azure/acs-engine/pkg/i18n" "github.com/Azure/terraform-provider-acsengine/internal/resource" "github.com/leonelquinteros/gotext" log "github.com/sirupsen/logrus" ) // ACSEngineClient contains fields needed for acs-engine cluster operations type ACSEngineClient struct { AuthArgs ResourceGroupName string Location string Cluster *api.ContainerService Client armhelpers.ACSEngineClient DeploymentDirectory string APIVersion string APIModelPath string // Do I really need this and DeploymentDirectory? Locale *gotext.Locale NameSuffix string Logger *log.Entry } // NewACSEngineClient returns a new acs-engine cluster client func NewACSEngineClient(secret string) *ACSEngineClient { authArgs := NewAuthArgs(secret) return &ACSEngineClient{ AuthArgs: *authArgs, } } // AddACSEngineClientAuthArgs adds auth args and sets up client func (c *ACSEngineClient) AddACSEngineClientAuthArgs(cluster *api.ContainerService, azureID string) error { var err error if err = c.AddAuthArgs(cluster, azureID); err != nil { return fmt.Errorf("failed to add auth args: %+v", err) } if c.Client, err = c.GetClient(); err != nil { return fmt.Errorf("failed to get client: %+v", err) } if _, err = c.Client.EnsureResourceGroup(context.Background(), c.ResourceGroupName, c.Location, nil); err != nil { return fmt.Errorf("failed to get client: %+v", err) } return nil } // SetACSEngineClient sets all necessary client fields for cluster func (c *ACSEngineClient) SetACSEngineClient(cluster *api.ContainerService, azureID string) error { var err error id, err := resource.ParseAzureResourceID(azureID) if err != nil { return fmt.Errorf("error parsing resource ID: %+v", err) } c.ResourceGroupName = id.ResourceGroup c.DeploymentDirectory = path.Join("_output", cluster.Properties.MasterProfile.DNSPrefix) c.Location = cluster.Location if c.Locale, err = i18n.LoadTranslations(); err != nil { return fmt.Errorf("error loading translation files: %+v", err) } if err = c.AddACSEngineClientAuthArgs(cluster, azureID); err != nil { return fmt.Errorf("failed to add ACSEngineClient auth args: %+v", err) } c.Cluster = cluster if c.Cluster.Location != c.Location { return fmt.Errorf("location does not match api model location") // this should probably never happen? } c.NameSuffix = acsengine.GenerateClusterID(c.Cluster.Properties) return nil } // Validate validates general parameters needed for acs-engine cluster operations func (c *ACSEngineClient) Validate() error { var err error c.Locale, err = i18n.LoadTranslations() if err != nil { return fmt.Errorf("error loading translation files: %s", err.Error()) } if c.ResourceGroupName == "" { return fmt.Errorf("Resource group must be specified") } if c.Location == "" { return fmt.Errorf("Location must be specified") } c.Location = helpers.NormalizeAzureRegion(c.Location) if c.DeploymentDirectory == "" { return fmt.Errorf("Deployment directory must be specified") } return nil }
zhaobobin/metuAdmin
src/pages/ContentManage/OssList.js
<reponame>zhaobobin/metuAdmin import React from 'react'; export default class OssList extends React.Component { render() { return <div>OssList</div>; } }
AsPJT/CrafterraProterozoic
include/Crafterra/Basic/Resource.hpp
/*########################################################################################## Crafterra Library 🌏 [Planning and Production] 2017-2022 Kasugaccho 2018-2022 As Project [Contact Us] <EMAIL> https://github.com/AsPJT/Crafterra [License] Distributed under the CC0 1.0. https://creativecommons.org/publicdomain/zero/1.0/ ##########################################################################################*/ #ifndef INCLUDED_CRAFTERRA_LIBRARY_CRAFTERRA_BASIC_RESOURCE_HPP #define INCLUDED_CRAFTERRA_LIBRARY_CRAFTERRA_BASIC_RESOURCE_HPP #include <AsLib2/DataType/PrimitiveDataType.hpp> namespace As { class Font; class Music; class MapChipImage; class CharacterChipImage; } namespace Crafterra { class Resource { // 各種素材のポインタ private: ::As::Font* font = nullptr; // フォント ::As::Music* music = nullptr; // 音楽 ::As::MapChipImage* map_chip = nullptr; // マップチップ ::As::MapChipImage* character_chip = nullptr; // キャラチップ public: void setFont(::As::Font& font_) { this->font = &font_; } ::As::Font& getFont() { return *(this->font); } void setMusic(::As::Music& music_) { this->music = &music_; } ::As::Music& getMusic() { return *(this->music); } void setMapChip(::As::MapChipImage& map_chip_) { this->map_chip = &map_chip_; } ::As::MapChipImage& getMapChip() { return *(this->map_chip); } void setCharacterChip(::As::MapChipImage& character_chip_) { this->character_chip = &character_chip_; } ::As::MapChipImage& getCharacterChip() { return *(this->character_chip); } private: As::IndexUint window_width = 0; As::IndexUint window_height = 0; public: void setWindowWidth(const ::As::IndexUint window_width_) { this->window_width = window_width_; } void setWindowHeight(const ::As::IndexUint window_height_) { this->window_height = window_height_; } ::As::IndexUint getWindowWidth() const { return this->window_width; } ::As::IndexUint getWindowHeight() const { return this->window_height; } }; } #endif //Included Crafterra Library
khurtado/WMCore
src/python/WMCore/WorkQueue/Policy/Start/__init__.py
<filename>src/python/WMCore/WorkQueue/Policy/Start/__init__.py #!/usr/bin/env python """ WorkQueue Start Policy """ from copy import deepcopy from WMCore.WMFactory import WMFactory startFac = WMFactory(__name__, __name__) def startPolicy(name, startMap, rucioObj, logger=None): """Load a start policy""" # Take splitting policy from workload & load specific policy for this queue # Workload may also directly specify specific splitter implementation if name in startMap: # take mapping from queue policyName = startMap[name]['name'] else: # workload directly specifies splitting algo policyName = name try: args = deepcopy(startMap[name]['args']) except IndexError: args = {} args['rucioObject'] = rucioObj args['logger'] = logger return startFac.loadObject(policyName, args, storeInCache=False, ) __all__ = []
cbednarski/ifs-python
ifs/source/consul-template.py
<gh_stars>1-10 version = '0.14.0' version_cmd = 'consul-template -v' depends = ['unzip'] download_url = 'https://releases.hashicorp.com/consul-template/VERSION/consul-template_VERSION_linux_amd64.zip' install_script = """ unzip -o consul-template_VERSION_linux_amd64.zip mv -f consul-template /usr/local/bin/consul-template """
amnesic/cartodb
lib/tasks/relocator/rdbms.rb
# encoding: utf-8 module CartoDB module Relocator class RDBMS def initialize(connection) @connection = connection end #initialize def rename_user(existing_username, new_username) connection.run(" ALTER USER #{existing_username} RENAME TO #{new_username} ") end #rename_user def create_user(username, password) connection.run(" CREATE USER #{username} PASSWORD '#{password}' ") end #create_user def set_password(username, password) connection.run(" ALTER USER #{username} PASSWORD #{password} ") end #set_password def create_database(database_name, owner) connection.run(" CREATE DATABASE #{database_name} WITH TEMPLATE = template_postgis OWNER = #{owner} ENCODING = 'UTF8' CONNECTION LIMIT=-1 ") end #create_database private attr_accessor :connection end # RDBMS end # Relocator end # CartoDB
chef/azure-sdk-for-ruby
management/azure_mgmt_logic/lib/2018-07-01-preview/generated/azure_mgmt_logic/models/x12acknowledgement_settings.rb
<gh_stars>0 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Logic::Mgmt::V2018_07_01_preview module Models # # The X12 agreement acknowledgement settings. # class X12AcknowledgementSettings include MsRestAzure # @return [Boolean] The value indicating whether technical # acknowledgement is needed. attr_accessor :need_technical_acknowledgement # @return [Boolean] The value indicating whether to batch the technical # acknowledgements. attr_accessor :batch_technical_acknowledgements # @return [Boolean] The value indicating whether functional # acknowledgement is needed. attr_accessor :need_functional_acknowledgement # @return [String] The functional acknowledgement version. attr_accessor :functional_acknowledgement_version # @return [Boolean] The value indicating whether to batch functional # acknowledgements. attr_accessor :batch_functional_acknowledgements # @return [Boolean] The value indicating whether implementation # acknowledgement is needed. attr_accessor :need_implementation_acknowledgement # @return [String] The implementation acknowledgement version. attr_accessor :implementation_acknowledgement_version # @return [Boolean] The value indicating whether to batch implementation # acknowledgements. attr_accessor :batch_implementation_acknowledgements # @return [Boolean] The value indicating whether a loop is needed for # valid messages. attr_accessor :need_loop_for_valid_messages # @return [Boolean] The value indicating whether to send synchronous # acknowledgement. attr_accessor :send_synchronous_acknowledgement # @return [String] The acknowledgement control number prefix. attr_accessor :acknowledgement_control_number_prefix # @return [String] The acknowledgement control number suffix. attr_accessor :acknowledgement_control_number_suffix # @return [Integer] The acknowledgement control number lower bound. attr_accessor :acknowledgement_control_number_lower_bound # @return [Integer] The acknowledgement control number upper bound. attr_accessor :acknowledgement_control_number_upper_bound # @return [Boolean] The value indicating whether to rollover # acknowledgement control number. attr_accessor :rollover_acknowledgement_control_number # # Mapper for X12AcknowledgementSettings class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'X12AcknowledgementSettings', type: { name: 'Composite', class_name: 'X12AcknowledgementSettings', model_properties: { need_technical_acknowledgement: { client_side_validation: true, required: true, serialized_name: 'needTechnicalAcknowledgement', type: { name: 'Boolean' } }, batch_technical_acknowledgements: { client_side_validation: true, required: true, serialized_name: 'batchTechnicalAcknowledgements', type: { name: 'Boolean' } }, need_functional_acknowledgement: { client_side_validation: true, required: true, serialized_name: 'needFunctionalAcknowledgement', type: { name: 'Boolean' } }, functional_acknowledgement_version: { client_side_validation: true, required: false, serialized_name: 'functionalAcknowledgementVersion', type: { name: 'String' } }, batch_functional_acknowledgements: { client_side_validation: true, required: true, serialized_name: 'batchFunctionalAcknowledgements', type: { name: 'Boolean' } }, need_implementation_acknowledgement: { client_side_validation: true, required: true, serialized_name: 'needImplementationAcknowledgement', type: { name: 'Boolean' } }, implementation_acknowledgement_version: { client_side_validation: true, required: false, serialized_name: 'implementationAcknowledgementVersion', type: { name: 'String' } }, batch_implementation_acknowledgements: { client_side_validation: true, required: true, serialized_name: 'batchImplementationAcknowledgements', type: { name: 'Boolean' } }, need_loop_for_valid_messages: { client_side_validation: true, required: true, serialized_name: 'needLoopForValidMessages', type: { name: 'Boolean' } }, send_synchronous_acknowledgement: { client_side_validation: true, required: true, serialized_name: 'sendSynchronousAcknowledgement', type: { name: 'Boolean' } }, acknowledgement_control_number_prefix: { client_side_validation: true, required: false, serialized_name: 'acknowledgementControlNumberPrefix', type: { name: 'String' } }, acknowledgement_control_number_suffix: { client_side_validation: true, required: false, serialized_name: 'acknowledgementControlNumberSuffix', type: { name: 'String' } }, acknowledgement_control_number_lower_bound: { client_side_validation: true, required: true, serialized_name: 'acknowledgementControlNumberLowerBound', type: { name: 'Number' } }, acknowledgement_control_number_upper_bound: { client_side_validation: true, required: true, serialized_name: 'acknowledgementControlNumberUpperBound', type: { name: 'Number' } }, rollover_acknowledgement_control_number: { client_side_validation: true, required: true, serialized_name: 'rolloverAcknowledgementControlNumber', type: { name: 'Boolean' } } } } } end end end end
foxsake/infuzion-sgp
kernel/modules/drivers/char/brcm/fuse_ril/CAPI2_CIB/modem/capi/public/sms_proc.h
<filename>kernel/modules/drivers/char/brcm/fuse_ril/CAPI2_CIB/modem/capi/public/sms_proc.h /**************************************************************************** * * Copyright (c) 2007-2008 Broadcom Corporation * * Unless you and Broadcom execute a separate written software license * agreement governing use of this software, this software is licensed to you * under the terms of the GNU General Public License version 2, available * at http://www.gnu.org/licenses/old-licenses/gpl-2.0.html (the "GPL"). * * Notwithstanding the above, under no circumstances may you combine this * software in any way with any other Broadcom software provided under a license * other than the GPL, without Broadcom's express prior written consent. * ****************************************************************************/ /** * * @file sms_proc.h * * @brief This file defines some process interface for local SMS API. * ****************************************************************************/ #ifndef _SMS_PROC_H_ #define _SMS_PROC_H_ #ifndef _WIN32 #ifndef max #define max(x,y) ((x) > (y) ? (x) : (y)) #endif #endif #define CB_DATA_PER_BLOCK_SZ 22 ///< CB Data size from 2nd ~ 4th block #define FILL_BYTE 0x2B ///< CB Fill BYTE typedef enum { CBMID_CACHE_NOT_READY, CBMID_CACHE_READY, CBMID_NOT_EXIST } CBMidsDataStatus_t; /** * @addtogroup SMSAPIGroup * @{ */ //************************************************************************************** /** Initialize short message service module. **/ void SMS_APIInit(void); //------------------------------------------------- // Function Prototype //------------------------------------------------- /** @} */ // default setting API SmsTxParam_t* SMS_GetDefaultTxParamPtr( void ); SmsRxSettings_t* SMS_GetDefRxSettings(void); smsBearerDb_t* SMS_GetBearerDbPtr(void); SmsPrefProfile_t* SMS_GetSmsPrefProfilePtr( void ); void SMS_APIInitWithFS(void); // storage API void SMS_BufferInit ( void ); //void SMS_SimInit ( void ); SmsStorageWaitState_t SMS_GetStorageWaitState(void); void SMS_SetSMSAccessStorage(SmsStorage_t storageType); SmsStorage_t SMS_GetSMSAccessStorage(void); SmsMesgStatus_t SMS_GetNonSimSmsStoredState (SmsStorage_t storageType, UInt16 index); Boolean SMS_IsMeStorageOverFlow (void); Boolean SMS_IsSimStorageOverFlow (void); void SMS_resetCachedDataReady(void); void SMS_SetLastCmssSlotIndex(UInt16 index); void SMS_SmsBufferStatus (SmsStorage_t storageType, UInt16 *NbFree, UInt16 *NbUsed ); void SMS_StoreSmsInBuffer (UInt8 clientId, SmsStorage_t storageType, void *sms, UInt16 size, UInt16 recNum, SIMSMSMesgStatus_t smsState, UInt8 tp_pid); void SMS_GetSmsFromBuffer (UInt8 clientId, SmsStorage_t storageType, UInt16 index); void SMS_RmvSmsFromBuffer (UInt8 clientId, SmsStorage_t storageType, UInt16 index ); void SMS_SimSmsChangeStatusReq(UInt8 clientId, SmsStorage_t storageType, UInt16 index, SIMSMSMesgStatus_t status); // SMS utilities UInt8 SMS_DecTime(SmsVpf_t VPf, SmsTime_t* Dst, Sms_340Time_t* Src); UInt16 SMS_CodTime(SmsVpf_t *VPf, UInt8 Fo, Sms_340Time_t *Dst, SmsTime_t *Src); void SMS_GetUserDataPtr (SmsTpdu_t *DstSms, UInt8 SrcUdl, UInt8 * SrcTpUd, UInt8 Udhi, Boolean Compression, SmsAlphabet_t Alphabet); UInt8 SMS_FoToMnsmsVpf(UInt8 Fo); UInt8 SMS_MnsmsVpfToVpf (UInt8 MnsmsVpf); UInt8 SMS_ConvertSmsDeliverToStorageType(UInt8 * Dst, T_MN_TP_DELIVER_IND *DeliverInd); UInt8 SMS_ConvertSmsSubmitToStorageType(UInt8 * Dst,T_MN_TP_SUBMIT_REQ *SubmitReq); UInt8 SMS_ConvertSmsSRToStorageType(UInt8 * Dst, T_MN_TP_STATUS_REPORT_IND *StatusReportInd); // SMS processing void SMS_HandleSmsStatusRptInd(InterTaskMsg_t* inMsg); void SMS_HandleSmsDeliverInd(InterTaskMsg_t* inMsg); Result_t SMS_SubmitSmsPduReq(ClientInfo_t* inClientInfoPtr, UInt8 length, UInt8* inSmsPdu, Sms_411Addr_t* sca); Result_t SMS_SubmitSmsReq(ClientInfo_t* inClientInfoPtr, UInt8* inNum, UInt8* inSMS, SmsTxParam_t* params, UInt8* sca); Boolean SMS_CheckSmsLength(UInt8 udl, SmsAlphabet_t msgAlphabet); // SMS Command Result_t SMS_SendSmsCommandFromTextMsg(ClientInfo_t* inClientInfoPtr, SmsCommand_t smsCmd, UInt8* inNum, UInt8* inCmdTxt, Sms_411Addr_t* inSca); Result_t SMS_SendSmsCommandFromPduMsg(ClientInfo_t* inClientInfoPtr, UInt8 length, UInt8* inSmsPduCmd); /** * @addtogroup SMSAPIGroup * @{ */ /** API function for MMI to move a SMS from ME to SIM @param clientID (in) client ID @param size (in) msg PDU size @param *Sms (in) msg data @param smsState (in) msg status **/ void SMS_WriteSmsPduToSim(UInt8 clientID, UInt16 size, void* Sms, SIMSMSMesgStatus_t smsState); /** @} */ void SMS_HandleSendMesgToStorage(InterTaskMsg_t* inMsg); UInt16 SMS_FindNextMsg(SmsStorage_t storeType, SmsMesgStatus_t msgBox, UInt16 lastIndex); Boolean SMS_FormatSmsForClient(SmsSimMsg_t *smsMsg, SIM_SMS_DATA_t *sms_data, SrType_t sr_type); Boolean SMS_GetSimCachedDataReadyStatus(void); void SMS_GetVoiceMailInfo(SmsVoicemailInd_t *vm_ind); Boolean SMS_IsVoiceMailIndEnabled(void); void SMS_SetVoiceMailIndFlag(Boolean enabled); Boolean SMS_IsVoiceMailFowarded(void); void SMS_SetVoiceMailForwardedFlag(Boolean forwarded); CBMidsDataStatus_t GetCBMidsDataReadyStatus(void); SMS_CB_MSG_IDS_t* SMS_GetCBMIdb(void); MS_T_MN_CB_LANGUAGES* SMS_GetCbLanguageDb(void); void SMS_ReadCBMIReq(void); Result_t SMS_UpdateCBMIReq(UInt8* pCBMI, UInt8 cbmiLen); Result_t SMS_RemoveCBMIReq(UInt8* newCBMI); void SMS_StartAutoCBReq(UInt16 msgId); void SMS_StopAutoCBReq(void); Boolean SMS_IsCBMsgIdStarted(UInt16 msgId); void SMS_HandleStartCBReq(void); void SMS_HandleWriteCBMIReq(void); Result_t SMS_StartCBReq(UInt8* chnlIDs, UInt8* codings); Result_t SMS_StopCBReq(void); void MNSMS_SuspendCBFilteringReq(Boolean suspend_filering); Result_t SMS_AddCBLangReq(UInt8 newLang); Result_t SMS_RemoveCBLangReq(UInt8* newLang); void SMS_ResetCbLanguageDb(void); void SMS_HandleSimSmsTpMrRsp(InterTaskMsg_t* inMsg); void SMS_HandleSmsSubmitRsp(InterTaskMsg_t* inMsg); void SMS_HandleMemAvailRsp(InterTaskMsg_t* inMsg); void SMS_HandleSmsRetryReq(ClientInfo_t* inClientInfoPtr); void SMS_HandleSmsDeleteResp(InterTaskMsg_t *inMsg); void SMS_HandleMeSmsDeleteInd(InterTaskMsg_t *inMsg); void SMS_HandleSmsReadResp(InterTaskMsg_t *inMsg); void SMS_HandleSimSmsStatusUpdateRsp(InterTaskMsg_t* inMsg); void SMS_HandleSimSmsMemAvailInd(Boolean mem_avail); void SMS_HandleIncomingSmsStoredRes(InterTaskMsg_t* inMsg); void SMS_HandleSmsWriteResp(InterTaskMsg_t* inMsg); void SMS_HandleSimSmsDataResp(InterTaskMsg_t* inMsg); void SMS_HandleSmsSendFromSlot(InterTaskMsg_t* inMsg); void SMS_HandleSimEfileDataResp(InterTaskMsg_t* inMsg); void SMS_HandleSimScaUpdResp(void); void SMS_HandleCBDataInd(InterTaskMsg_t* inMsg); void SMS_HandleCBStartStopRsp(InterTaskMsg_t* inMsg); UInt8 SMS_GetCBMIRecLength(void); Boolean SMS_IsMemAvailRspPending(void); void SMS_SetPendingflagForMemAvailRsp(Boolean flag); // SATK SMS control void SMS_HandleMOSMS_ControlRsp(InterTaskMsg_t* inMsg); void SMS_HandleMsgWaitingIndReadRsp(InterTaskMsg_t *inMsg); void SMS_HandleSmsCommandRsp(InterTaskMsg_t* inMsg); // transaction management prototype UInt8 SMS_GetClientIDFromTransaction(SmsTransactionType_t smsTrans, ClientInfo_t* inClientInfoPtr); void SMS_ResetTransactionClientID(UInt8 clientID); SmsTransactionType_t SMS_GetTransactionFromDialogId(UInt32 dialogId, SmsMesgStatus_t* category, SmsStorage_t* storageType, ClientInfo_t* inClientInfoPtr); SmsTransactionType_t SMS_GetTransactionFromClientID(UInt8 clientID, SmsMesgStatus_t* category, SmsStorage_t* storageType, ClientInfo_t* inClientInfoPtr); SMS_BEARER_PREFERENCE_t SMS_GetSMSPrefBearer(void); void SMS_SetSMSPrefBearer(SMS_BEARER_PREFERENCE_t inPref); void SMS_SetAckTestCase(Boolean flag); void SMS_HandleSmsSubmitVccTimeOutRsp(InterTaskMsg_t* inMsg); #endif // _SMS_PROC_H_
zhenkunhe/Developer-Tutorial
C++/06_Dl/UniqueAndStaticVar/libunique/inc/UniqueVariable.hpp
<filename>C++/06_Dl/UniqueAndStaticVar/libunique/inc/UniqueVariable.hpp /** * @file UniqueVariable.hpp * @author alex * @date 2017年2月24日 * @version 1.0 * * @brief <brief> * * @section DESCRIPTION * * Your description * */ #ifndef _UNIQUEVARIABLE_HPP_ #define _UNIQUEVARIABLE_HPP_ #include <iostream> using namespace std; class UniqueVariable { public: UniqueVariable(){} ~UniqueVariable(){} void PrintStaticInGlobal(); void PrintStaticInMember(); void PrintStaticInLocal(); void PrintUniqueVarible(); static int m_count; }; inline void UniqueVariable::PrintUniqueVarible() { static int uniqueVariable; cout << "UNIQUE uniqueVarible:" << ++uniqueVariable << endl; } #endif /* _UNIQUEVARIABLE_HPP_ */
dandycheung/jmonet
src/main/java/com/defano/jmonet/model/PaintToolType.java
<reponame>dandycheung/jmonet package com.defano.jmonet.model; import com.defano.jmonet.tools.*; import com.defano.jmonet.tools.base.Tool; /** * An enumeration of paint tools provided by this library. */ public enum PaintToolType { ARROW(ArrowTool.class), PENCIL(PencilTool.class), RECTANGLE(RectangleTool.class), ROUND_RECTANGLE(RoundRectangleTool.class), OVAL(OvalTool.class), PAINTBRUSH(PaintbrushTool.class), ERASER(EraserTool.class), LINE(LineTool.class), POLYGON(PolygonTool.class), SHAPE(ShapeTool.class), FREEFORM(FreeformShapeTool.class), SELECTION(MarqueeTool.class), LASSO(LassoTool.class), TEXT(TextTool.class), FILL(FillTool.class), AIRBRUSH(AirbrushTool.class), CURVE(CurveTool.class), SLANT(SlantTool.class), ROTATE(RotateTool.class), SCALE(ScaleTool.class), MAGNIFIER(MagnifierTool.class), PROJECTION(ProjectionTool.class), PERSPECTIVE(PerspectiveTool.class), RUBBERSHEET(RubberSheetTool.class); private final Class<? extends Tool> toolClass; PaintToolType(Class<? extends Tool> clazz) { this.toolClass = clazz; } public Class<? extends Tool> getToolClass() { return toolClass; } /** * Determines if the given tool type draws closed-path "shapes" (i.e., elements which can be * filled with paint. * * @return True if the tool draws shapes; false otherwise. */ public boolean isShapeTool() { return this == RECTANGLE || this == ROUND_RECTANGLE || this == OVAL || this == POLYGON || this == SHAPE || this == FREEFORM; } }
cyroxx/meine-stadt-transparent
mainapp/models/body.py
from django.conf import settings from django.db import models from django.urls import reverse from .helper import DefaultFields, ShortableNameFields from .legislative_term import LegislativeTerm from .location import Location class Body(DefaultFields, ShortableNameFields): center = models.ForeignKey( Location, null=True, blank=True, related_name="body_center", on_delete=models.CASCADE, ) outline = models.ForeignKey( Location, null=True, blank=True, related_name="body_outline", on_delete=models.CASCADE, ) # There might be e.g. a newer body that didn't exist in the older terms, so # bodies and terms are mapped explicitly legislative_terms = models.ManyToManyField(LegislativeTerm, blank=True) # Normally 8 digits (Stadt/Gemeinde), can be 5 digits for Landkreise ags = models.CharField(max_length=8, null=True, blank=True) def __str__(self): return f"{self.short_name} ({self.ags})" def get_default_link(self): if settings.SITE_DEFAULT_BODY == self.id: return reverse("index") else: return reverse("body", args=[self.id]) def is_default_body(self) -> bool: return settings.SITE_DEFAULT_BODY == self.id
player1537-forks/spack
var/spack/repos/builtin/packages/cxxtest/package.py
<filename>var/spack/repos/builtin/packages/cxxtest/package.py # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Cxxtest(Package): """C++ unit test system.""" homepage = "https://cxxtest.com/" url = "https://sourceforge.net/projects/cxxtest/files/cxxtest/4.4/cxxtest-4.4.tar.gz/download" version('4.4', sha256='1c154fef91c65dbf1cd4519af7ade70a61d85a923b6e0c0b007dc7f4895cf7d8') def install(self, spec, prefix): install_tree(self.stage.source_path, prefix)
Ars2014/ulang
builtins/pow.go
package builtins import ( "math" "github.com/Ars2014/ulang/object" "github.com/Ars2014/ulang/typing" ) func pow(x, y int64) int64 { p := int64(1) for y > 0 { if y&1 != 0 { p *= x } y >>= 1 x *= x } return p } func Pow(args ...object.Object) object.Object { if err := typing.Check( "pow", args, typing.ExactArgs(2), ); err != nil { return newError(err.Error()) } switch { case args[0].Type() == object.IntegerType && args[1].Type() == object.IntegerType: x := args[0].(*object.Integer) y := args[1].(*object.Integer) value := pow(x.Value, y.Value) return &object.Integer{Value: value} case args[0].Type() == object.FloatType && args[1].Type() == object.FloatType: x := args[0].(*object.Float) y := args[1].(*object.Float) value := math.Pow(x.Value, y.Value) return &object.Float{Value: value} case args[0].Type() == object.IntegerType && args[1].Type() == object.FloatType: x := args[0].(*object.Integer) y := args[1].(*object.Float) value := math.Pow(float64(x.Value), y.Value) return &object.Float{Value: value} case args[0].Type() == object.FloatType && args[1].Type() == object.IntegerType: x := args[0].(*object.Float) y := args[1].(*object.Integer) value := math.Pow(x.Value, float64(y.Value)) return &object.Float{Value: value} default: return newError("pow() takes only 'float' or 'int' as parameters") } }
prodkt/carbon-platform
.lintstagedrc.js
<reponame>prodkt/carbon-platform<gh_stars>0 /* * Copyright IBM Corp. 2021, 2022 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ module.exports = { '**/*.(js|jsx|ts|tsx)': ['prettier --write', 'eslint --fix'], '**/*.scss': ['prettier --write', 'stylelint --fix'], '!(*sass).md': ['prettier --write'] }
mdg/snapl
src/server_message.h
<reponame>mdg/snapl #ifndef SNAPL_SERVER_MESSAGE_H #define SNAPL_SERVER_MESSAGE_H /** * Copyright 2008 <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. */ #include "snapl/message.h" #include <memory> namespace snapl { class connection_i; class response_c; /** * The server message class for passing requests & responses to and from * the protocols. */ class server_message_c { public: /** * Construct the server message from a line of text and a connection. */ server_message_c( const std::string &request, connection_i * ); /** * Destroy the server_message. */ virtual ~server_message_c(); /** * Get the request type from this message. */ const std::string & request_type() const { return m_request.argv(0); } /** * Get the request object from this message. */ const message_c & request() const { return m_request; } /** * Get the const message for this server message response. */ const message_c & response() const { return m_response; } /** * Get the non-const message for this server message response. */ message_c & response() { return m_response; } /** * Set response for writing back to the client */ void set_response( const response_c & ); /** * Get the port of this server_message */ short port() const; /** * Get the connection from which this message came. */ connection_i & connection() { return *m_connection; } /** * Release the connection from this message. */ connection_i * release_connection(); private: const message_c m_request; message_c m_response; connection_i *m_connection; }; } // namespace #endif
candrews/gradle
subprojects/publish/src/main/java/org/gradle/api/publish/PublishingExtension.java
<gh_stars>1-10 /* * Copyright 2012 the original author or 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 org.gradle.api.publish; import org.gradle.api.Action; import org.gradle.api.artifacts.dsl.RepositoryHandler; /** * The configuration of how to “publish” the different components of a project. * * @since 1.3 */ public interface PublishingExtension { /** * The name of this extension when installed by the {@link org.gradle.api.publish.plugins.PublishingPlugin} ({@value}). */ String NAME = "publishing"; /** * The container of possible repositories to publish to. * <p> * See {@link #repositories(org.gradle.api.Action)} for more information. * * @return The container of possible repositories to publish to. */ RepositoryHandler getRepositories(); /** * Configures the container of possible repositories to publish to. * * <pre class='autoTested'> * plugins { * id 'publishing' * } * * publishing { * repositories { * // Create an ivy publication destination named “releases” * ivy { * name "releases" * url "http://my.org/ivy-repos/releases" * } * } * } * </pre> * * The {@code repositories} block is backed by a {@link RepositoryHandler}, which is the same DSL as that that is used for declaring repositories to consume dependencies from. However, * certain types of repositories that can be created by the repository handler are not valid for publishing, such as {@link org.gradle.api.artifacts.dsl.RepositoryHandler#mavenCentral()}. * <p> * At this time, only repositories created by the {@code ivy()} factory method have any effect. Please see {@link org.gradle.api.publish.ivy.IvyPublication} * for information on how this can be used for publishing to Ivy repositories. * * @param configure The action to configure the container of repositories with. */ void repositories(Action<? super RepositoryHandler> configure); /** * The publications of the project. * <p> * See {@link #publications(org.gradle.api.Action)} for more information. * * @return The publications of this project. */ PublicationContainer getPublications(); /** * Configures the publications of this project. * <p> * The publications container defines the outgoing publications of the project. That is, the consumable representations of things produced * by building the project. An example of a publication would be an Ivy Module (i.e. {@code ivy.xml} and artifacts), or * Maven Project (i.e. {@code pom.xml} and artifacts). * <p> * Actual publication implementations and the ability to create them are provided by different plugins. The “publishing” plugin itself does not provide any publication types. * For example, given that the 'maven-publish' plugin provides a {@link org.gradle.api.publish.maven.MavenPublication} type, you can create a publication like: * <pre class='autoTested'> * plugins { * id 'maven-publish' * } * * publishing { * publications { * myPublicationName(MavenPublication) { * // Configure the publication here * } * } * } * </pre> * <p> * Please see {@link org.gradle.api.publish.ivy.IvyPublication} and {@link org.gradle.api.publish.maven.MavenPublication} for more information on publishing in these specific formats. * * @param configure The action or closure to configure the publications with. */ void publications(Action<? super PublicationContainer> configure); }
npocmaka/Windows-Server-2003
shell/osshell/ep/freecell/game.c
/**************************************************************************** Game.c June 91, JimH initial code Oct 91, JimH port to Win32 Routines for playing the game are here and in game2.c ****************************************************************************/ #include "freecell.h" #include "freecons.h" #include <assert.h> #include <memory.h> /**************************************************************************** SetFromLoc User clicks to select card to transfer FROM. ****************************************************************************/ VOID SetFromLoc(HWND hWnd, UINT x, UINT y) { HDC hDC; UINT col, pos; wFromCol = EMPTY; // assume we didn't find a card wFromPos = EMPTY; cUndo = 0; EnableMenuItem(GetMenu(hWnd), IDM_UNDO, MF_GRAYED); if (Point2Card(x, y, &col, &pos)) { if (col == TOPROW) { if (card[TOPROW][pos] == EMPTY || pos > 3) return; } else { pos = FindLastPos(col); if (pos == EMPTY) // empty column return; } } else return; wFromCol = col; // ok, we have a card wFromPos = pos; wMouseMode = TO; hDC = GetDC(hWnd); DrawCard(hDC, col, pos, card[col][pos], HILITE); if (col == TOPROW && pos < 4) DrawKing(hDC, LEFT, TRUE); ReleaseDC(hWnd, hDC); } /**************************************************************************** ProcessMoveRequest After user has selected a FROM card with SetFromLoc() above, he then chooses a TO location with the mouse which this function processes. Note that the layout of the cards (the card array) is copied into an array called shadow. This is so queued move requests can be determined before we commit to moving the cards. ****************************************************************************/ VOID ProcessMoveRequest(HWND hWnd, UINT x, UINT y) { UINT tcol, tpos; // location to move selected card TO UINT freecells; // number of free cells unoccupied UINT trans; // number of cards requested transfer requires UINT maxtrans; // MaxTransfer() number INT i; // index TCHAR buffer[160]; // extra buffer needed for MessageBox assert(wFromCol != EMPTY); /* Make copy of card[][] in shadow[][] */ memcpy(&(shadow[0][0]), &(card[0][0]), sizeof(card)); Point2Card(x, y, &tcol, &tpos); // determine requested TO loc. if (tcol >= MAXCOL) // if illegal move selected... { tpos = wFromPos; // cancel it. tcol = wFromCol; } if (tcol == TOPROW) // if moving to top row { if (tpos > 7) // illegal move... { tpos = wFromPos; // so cancel it. tcol = wFromCol; } } else // if moving to a column... { tpos = FindLastPos(tcol); // find end of column if (tpos == EMPTY) // if column is empty... tpos = 0; // move to top of column. } /* if moving between non-empty columns */ if (wFromCol != TOPROW && tcol != TOPROW && card[tcol][0] != EMPTY) { freecells = 0; // count free freecells for (i = 0; i < 4; i++) if (card[TOPROW][i] == EMPTY) freecells++; trans = NumberToTransfer(wFromCol, tcol); // how many required? DEBUGMSG(TEXT("trans is %u "), trans); DEBUGMSG(TEXT("and MaxTransfer() is %u\r\n"), MaxTransfer()); if (trans > 0) // legal move? { maxtrans = MaxTransfer(); if (trans <= maxtrans) // enough free cells? { MultiMove(wFromCol, tcol); } else if (bMessages) { LoadString(hInst, IDS_APPNAME, smallbuf, SMALL); LoadString(hInst, IDS_TOOFEWFREE, buffer, sizeof(buffer)/sizeof(TCHAR)); wsprintf(bigbuf, buffer, trans, maxtrans); MessageBeep(MB_ICONINFORMATION); MessageBox(hWnd, bigbuf, smallbuf, MB_ICONINFORMATION); /* illegal move, so deselect that card */ QueueTransfer(wFromCol, wFromPos, wFromCol, wFromPos); } else return; } else { if (bMessages) { LoadString(hInst, IDS_APPNAME, smallbuf, SMALL); LoadString(hInst, IDS_ILLEGAL, bigbuf, BIG); MessageBeep(MB_ICONINFORMATION); MessageBox(hWnd, bigbuf, smallbuf, MB_ICONINFORMATION); // deselect QueueTransfer(wFromCol, wFromPos, wFromCol, wFromPos); } else return; } } else // else move involves TOPROW or move to empty column { bMoveCol = 0; if (IsValidMove(hWnd, tcol, tpos)) { if (bMoveCol) // user selected move column? MoveCol(wFromCol, tcol); else QueueTransfer(wFromCol, wFromPos, tcol, tpos); } else { if (bMessages && (bMoveCol != -1)) // user did not select Cancel { LoadString(hInst, IDS_APPNAME, smallbuf, SMALL); LoadString(hInst, IDS_ILLEGAL, bigbuf, BIG); MessageBeep(MB_ICONINFORMATION); MessageBox(hWnd, bigbuf, smallbuf, MB_ICONINFORMATION); // deselect QueueTransfer(wFromCol, wFromPos, wFromCol, wFromPos); } else if (bMoveCol == -1) // user selected cancel { // deselect QueueTransfer(wFromCol, wFromPos, wFromCol, wFromPos); } else return; } } Cleanup(); // queue transfers of unneeded cards MoveCards(hWnd); // start transferring queued cards wMouseMode = FROM; // next mouse click chooses FROM card } /**************************************************************************** ProcessDoubleClick Double clicking on card in a column moves it to the first free cell found. After finding the free cell, this routine is identical to ProcessMoveRequest. ****************************************************************************/ BOOL ProcessDoubleClick(HWND hWnd) { UINT freecell = EMPTY; // assume none found INT i; // counter for (i = 3; i >= 0; i--) // look for free cell; if (card[TOPROW][i] == EMPTY) freecell = (UINT) i; if (freecell == EMPTY) // if none found return FALSE; memcpy(&(shadow[0][0]), &(card[0][0]), sizeof(card)); wFromPos = FindLastPos(wFromCol); QueueTransfer(wFromCol, wFromPos, TOPROW, freecell); Cleanup(); MoveCards(hWnd); wMouseMode = FROM; return TRUE; } /**************************************************************************** IsValidMove This function determines if moving from wFromCol,wFromPos to tcol,tpos is valid. It can assume wFromCol and tcol are not both non-empty columns. In other words, except for moves to empty columns, it is concerned with moving only one card. If the move is to an empty column, the user can select if he wants to move one card or as much of the column as possible. ****************************************************************************/ BOOL IsValidMove(HWND hWnd, UINT tcol, UINT tpos) { CARD fcard, tcard; // card values (0 to 51) UINT trans; // num cards required for transfer UINT freecells; // num of unoccupied free cells UINT pos; DEBUGMSG(TEXT("IVM: tpos is %d\r\n"), tpos); assert (tpos < MAXPOS); bMoveCol = FALSE; // assume FALSE /* allow cancel move from top row. */ if (wFromCol == TOPROW && tcol == TOPROW && wFromPos == tpos) return TRUE; fcard = card[wFromCol][wFromPos]; tcard = card[tcol][tpos]; /* transfer to empty column */ if ((wFromCol != TOPROW) && (tcol != TOPROW) && (card[tcol][0] == EMPTY)) { trans = NumberToTransfer(wFromCol, tcol); // how many required? freecells = 0; for (pos = 0; pos < 4; pos++) // count free cells if (card[TOPROW][pos] == EMPTY) freecells++; if (freecells == 0 && trans > 1) // no freecells anyway trans = 1; if (trans == 0) // if no valid move return FALSE; else if (trans == 1) // if only 1 card can move return TRUE; /* If multiple cards can move, user must disambiguate request. */ bMoveCol = (BOOL) DialogBox(hInst, TEXT("MoveCol"), hWnd, MoveColDlg); if (bMoveCol == -1) // CANCEL chosen return FALSE; return TRUE; } if (tcol == TOPROW) { if (tpos < 4) // free cells { if (tcard == EMPTY) return TRUE; else return FALSE; } else // home cells { if (VALUE(fcard) == ACE && tcard == EMPTY) // ace on new pile return TRUE; else if (SUIT(fcard) == SUIT(tcard)) // same suit { if (VALUE(fcard) == (VALUE(tcard) + 1)) // next card return TRUE; else return FALSE; } return FALSE; } } else // tcol is not TOPROW { if (card[tcol][0] == EMPTY) // top of empty column always ok return TRUE; return FitsUnder(fcard, tcard); } } /**************************************************************************** Cleanup This function checks if exposed cards (cards in home cells or bottoms of columns) are no longer needed (Useless.) When it finds cards it doesn't need, it queues them for transfer. It keeps looking until an entire pass finds no new useless cards. ****************************************************************************/ VOID Cleanup() { UINT col, pos; UINT i; // counter CARD c; BOOL bMore = TRUE; // assume we need another pass while (bMore) { bMore = FALSE; for (pos = 0; pos < 4; pos++) // do TOPROW first { c = card[TOPROW][pos]; if (Useless(c)) // if card is discardable { bMore = TRUE; // need another pass /* If this is the first card of this suit, we need to determine which home cell it can use. */ if (homesuit[SUIT(c)] == EMPTY) { i = 4; while (card[TOPROW][i] != EMPTY) i++; homesuit[SUIT(c)] = i; } QueueTransfer(TOPROW, pos, TOPROW, homesuit[SUIT(c)]); } } for (col = 1; col <= 8; col++) // do columns next { pos = FindLastPos(col); if (pos != EMPTY) { c = card[col][pos]; if (Useless(c)) { bMore = TRUE; if (homesuit[SUIT(c)] == EMPTY) { i = 4; while (card[TOPROW][i] != EMPTY) i++; homesuit[SUIT(c)] = i; } QueueTransfer(col, pos, TOPROW, homesuit[SUIT(c)]); } } } } } /**************************************************************************** Useless returns TRUE if a card can be safely discarded (no existing cards could possibly play on it.) Note that the lines identified with // *** are required in the 32 bit version since EMPTY == 0xFFFF is not longer equal to -1 as was the case in 16 bit ****************************************************************************/ BOOL Useless(CARD c) { CARD limit; // top home card of this suit if (c == EMPTY) return FALSE; // no card to discard if (bCheating == CHEAT_WIN) return TRUE; if (VALUE(c) == ACE) return TRUE; // ACEs can always be cleaned up else if (VALUE(c) == DEUCE) // DEUCEs need only check if ACE is up { if (home[SUIT(c)] == ACE) return TRUE; else return FALSE; } else // else check both cards that can play on it { limit = VALUE(c) - 1; if (home[SUIT(c)] != limit) // is this the next card? return FALSE; if (COLOUR(c) == RED) { if (home[CLUB] == EMPTY || home[SPADE] == EMPTY) // *** return FALSE; else return (home[CLUB] >= limit && home[SPADE] >= limit); } else { if (home[DIAMOND] == EMPTY || home[HEART] == EMPTY) // *** return FALSE; else return (home[DIAMOND] >= limit && home[HEART] >= limit); } } }
tobiasweibel/codacy-eslint
src/main/resources/docs/tests/no-nested-ternary.js
//#Patterns: no-nested-ternary //#Info: no-nested-ternary var foo = bar ? baz : qux === quxx ? bing : bam; //#Info: no-nested-ternary var thing = foo ? bar : baz === qux ? quxx : foobar; if (foo) { thing = bar; } else if (baz === qux) { thing = quxx; } else { thing = foobar; }
oikomi/FishRPC
core/src/main/java/org/miaohong/fishrpc/core/rpc/register/Register.java
package org.miaohong.fishrpc.core.rpc.register; import org.miaohong.fishrpc.core.annotation.Spi; import org.miaohong.fishrpc.core.rpc.base.Destroyable; import org.miaohong.fishrpc.core.rpc.client.ConsumerConfig; import org.miaohong.fishrpc.core.rpc.service.config.ServiceConfig; @Spi public interface Register extends Destroyable { void start(RegisterRole registerRole); void register(final ServiceConfig config); void unRegister(final ServiceConfig config); void subscribe(final ConsumerConfig config); void unSubscribe(); }
sgrif/crates.io
app/models/user.js
<reponame>sgrif/crates.io import DS from 'ember-data'; export default DS.Model.extend({ email: DS.attr('string'), name: DS.attr('string'), login: DS.attr('string'), api_token: DS.attr('string'), avatar: DS.attr('string'), url: DS.attr('string'), });
easylogic/editor
src/editor-layouts/common/body-panel/render-view/draw-panels/DragAreaView.js
<reponame>easylogic/editor import { POINTERSTART, IF, SUBSCRIBE } from "el/sapa/Event"; import { Length } from "el/editor/unit/Length"; import { KEY_CODE } from "el/editor/types/key"; import { END, MOVE } from "el/editor/types/event"; import { EditorElement } from "el/editor/ui/common/EditorElement"; import './DragAreaView.scss'; import { vec3 } from "gl-matrix"; export default class DragAreaView extends EditorElement { initState() { return { mode: 'selection', x: Length.z(), y: Length.z(), width: Length.px(10000), height: Length.px(10000), cachedCurrentElement: {}, html: '', } } template() { return /*html*/` <div class="elf--drag-area-view" ref="$dragAreaView"></div> ` } checkSelectionArea(e) { const mousePoint = this.$viewport.getWorldPosition(e); // select된 객체에 포지션이 있으면 움직일 수 있도록 한다. if (this.$selection.hasPoint(mousePoint)) { return true; } } /** * 레이어를 움직이기 위한 이벤트 실행 여부 체크 * * @param {PointerEvent} e */ checkEditMode(e) { // hand tool 이 on 되어 있으면 드래그 하지 않는다. if (this.$config.get('set.tool.hand')) { return false; } // space 키가 눌러져있을 때는 실행하지 않는다. const code = this.$shortcuts.getGeneratedKeyCode(KEY_CODE.space); if (this.$keyboardManager.check(code)) { return false; } // selection 영역에 속할 때 const mousePoint = this.$viewport.getWorldPosition(e); this.inSelection = false; if (this.$selection.hasPoint(mousePoint)) { this.inSelection = true; // 선택한 영역이 artboard 이고, 하위 레이어가 있다면 움직이지 않는다. if (this.$selection.current.is('artboard')) { if (this.$selection.current.hasChildren()) { // drag 모드로 변신 this.$config.set('set.dragarea.mode', true); this.$config.set('set.move.mode', false); return true; } else { // 움직임 this.$config.set('set.dragarea.mode', false); this.$config.set('set.move.mode', true); return true; } } else { // 움직임 this.$config.set('set.dragarea.mode', false); this.$config.set('set.move.mode', true); return true; } } this.mouseOverItem = this.$selection.filteredLayers[0]; if (this.mouseOverItem) { // move 모드로 변신 this.$config.set('set.dragarea.mode', false); this.$config.set('set.move.mode', true); } else { // drag 모드로 변신 this.$config.set('set.dragarea.mode', true); this.$config.set('set.move.mode', false); } return true; } [POINTERSTART('$dragAreaView') + IF('checkEditMode') + MOVE('movePointer') + END('moveEndPointer')](e) { if (this.$config.get('set.dragarea.mode')) { this.emit('startDragAreaView'); } else if (this.$config.get('set.move.mode')) { // 움직임 처리 this.initMousePoint = this.$viewport.getWorldPosition(); this.mouseOverItem = this.$selection.filteredLayers[0]; // mouse point 기준으로 item 찾기 구현 필요 // shift key 를 누른 상태로 선택 안되어 있는 객체나, 선택 되어 있는 객체를 체크 해야함 // alt(option) + pointerstart 시점에 Layer 카피하기 if (e.altKey) { if (this.$selection.isEmpty === false && this.$selection.hasPoint(this.initMousePoint)) { // 선택된 모든 객체 카피하기 this.$selection.selectAfterCopy(); this.trigger('refreshAllCanvas') this.emit('refreshLayerTreeView') // this.selectCurrent(...this.$selection.items) this.initializeDragSelection(); this.emit('history.refreshSelection'); } } else { // mouse over item 이 있을 때 if (this.mouseOverItem) { const id = this.mouseOverItem.id; // shift key 는 selection 을 토글한다. if (e.shiftKey) { this.$selection.toggleById(id); } else { // 선택이 안되어 있으면 선택 if (this.$selection.check({ id }) === false) { const current = this.$model.get(id); if (current && current.is('artboard') && current.hasChildren()) { // NOOP // artboard 인데 자식이 있으면 선택을 하지 않는다. } else { this.$selection.selectByGroup(id); } } } } this.initializeDragSelection(); this.emit('history.refreshSelection'); } } } initializeDragSelection() { this.$selection.reselect(); this.$snapManager.clear(); this.emit('refreshSelectionTool', true); } movePointer(dx, dy) { if (this.$config.get('set.dragarea.mode')) { this.emit('moveDragAreaView'); } else if (this.$config.get('set.move.mode')) { // 움직임 처리 // layout item 은 움직이지 않고 layout 이 좌표를 그리도록 한다. if (this.$selection.isLayoutItem) { return; } const targetMousePoint = this.$viewport.getWorldPosition(); const newDist = vec3.floor([], vec3.subtract([], targetMousePoint, this.initMousePoint)); this.moveTo(newDist); // 최종 위치에서 ArtBoard 변경하기 if (this.$selection.changeArtBoard()) { this.initMousePoint = targetMousePoint; this.$selection.reselect(); this.$snapManager.clear(); this.emit('refreshAllCanvas') // ArtBoard 변경 이후에 LayerTreeView 업데이트 this.emit('refreshLayerTreeView') } this.emit('setAttributeForMulti', this.$selection.pack('x', 'y')); this.emit('refreshSelectionTool', true); } } moveTo(distVector) { distVector = vec3.floor([], distVector); ////// snap 체크 하기 const snap = this.$snapManager.check(this.$selection.cachedRectVerties.map(v => { return vec3.add([], v, distVector) }), 3); // dist 거리 계산 const localDist = vec3.add([], snap, distVector); const result = {} this.$selection.cachedItemMatrices.forEach(it => { // newVerties 에 실제 움직인 좌표로 넣고 const newVerties = it.verties.map(v => { return vec3.add([], v, localDist) }) // 첫번째 좌표 it.rectVerties[0] 과 // 마지막 좌표 newVerties[0] 를 // parentMatrixInverse 기준으로 다시 원복하고 거리를 잰다 // 그게 실제적인 distance 이다. const newDist = vec3.subtract( [], vec3.transformMat4([], newVerties[0], it.parentMatrixInverse), vec3.transformMat4([], it.verties[0], it.parentMatrixInverse) ) result[it.id] = { x: Length.px(it.x + newDist[0]).round(1000), // 1px 단위로 위치 설정 y: Length.px(it.y + newDist[1]).round(1000), } }); this.$selection.reset(result); } [SUBSCRIBE('selectionToolView.moveTo')](newDist) { this.moveTo(newDist); this.emit('refreshSelectionTool', true); } moveEndPointer() { if (this.$config.get('set.dragarea.mode')) { this.emit('endDragAreaView'); } else if (this.$config.get('set.move.mode')) { const targetMousePoint = this.$viewport.getWorldPosition(); const newDist = vec3.floor([], vec3.subtract([], targetMousePoint, this.initMousePoint)); if (newDist < 1) { if (this.$selection.current.isSVG()) { this.emit('open.editor'); this.emit('removeGuideLine'); return; } } else { this.$selection.reselect(); this.$snapManager.clear(); // this.emit('removeGuideLine'); this.command( 'setAttributeForMulti', "move item", this.$selection.pack('x', 'y') ); } this.emit('refreshSelectionTool', true); } this.$config.set('set.dragarea.mode', false) this.$config.set('set.move.mode', false) } }
saketrule/smellycat-with-vc
myrepo/app/src/main/java/org/liberty/android/fantastischmemo/modules/AppModules.java
<reponame>saketrule/smellycat-with-vc<gh_stars>1-10 package org.liberty.android.fantastischmemo.modules; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import org.greenrobot.eventbus.EventBus; import org.liberty.android.fantastischmemo.common.AMApplication; import org.liberty.android.fantastischmemo.converter.CSVExporter; import org.liberty.android.fantastischmemo.converter.CSVImporter; import org.liberty.android.fantastischmemo.converter.Converter; import org.liberty.android.fantastischmemo.converter.Mnemosyne2CardsExporter; import org.liberty.android.fantastischmemo.converter.Mnemosyne2CardsImporter; import org.liberty.android.fantastischmemo.converter.MnemosyneXMLExporter; import org.liberty.android.fantastischmemo.converter.MnemosyneXMLImporter; import org.liberty.android.fantastischmemo.converter.QATxtExporter; import org.liberty.android.fantastischmemo.converter.QATxtImporter; import org.liberty.android.fantastischmemo.converter.Supermemo2008XMLImporter; import org.liberty.android.fantastischmemo.converter.SupermemoXMLImporter; import org.liberty.android.fantastischmemo.converter.TabTxtExporter; import org.liberty.android.fantastischmemo.converter.TabTxtImporter; import org.liberty.android.fantastischmemo.converter.ZipExporter; import org.liberty.android.fantastischmemo.converter.ZipImporter; import org.liberty.android.fantastischmemo.scheduler.DefaultScheduler; import org.liberty.android.fantastischmemo.scheduler.Scheduler; import org.liberty.android.fantastischmemo.utils.AMFileUtil; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import dagger.Module; import dagger.Provides; import dagger.multibindings.ClassKey; import dagger.multibindings.IntoMap; import okhttp3.OkHttpClient; @Module public class AppModules { private AMApplication application; public AppModules(AMApplication app) { this.application = app; } @Provides @PerApplication AMApplication providesApplication() { return application; } @Provides @PerApplication @ForApplication Context providesContext() { return application; } @Provides @PerApplication Scheduler providesScheduler(DefaultScheduler scheduler) { return scheduler; } @Provides @PerApplication ExecutorService provideExecutorService() { return Executors.newFixedThreadPool(4); } @Provides @PerApplication SharedPreferences providesSharedPreferences() { return PreferenceManager.getDefaultSharedPreferences(application); } @Provides @PerApplication OkHttpClient providesOkHttpClient() { return new OkHttpClient(); } @Provides @PerApplication EventBus providesEventBus() { return new EventBus(); } @Provides @PerApplication @IntoMap @ClassKey(CSVExporter.class) Converter providesCSVExporter() { return new CSVExporter(); } @Provides @PerApplication @IntoMap @ClassKey(CSVImporter.class) Converter providesCSVImporter(AMFileUtil amFileUtil) { return new CSVImporter(amFileUtil); } @Provides @PerApplication @IntoMap @ClassKey(Mnemosyne2CardsExporter.class) Converter providesMnemosyne2CardsExporter(AMFileUtil amFileUtil) { return new Mnemosyne2CardsExporter(amFileUtil); } @Provides @PerApplication @IntoMap @ClassKey(Mnemosyne2CardsImporter.class) Converter providesMnemosyne2CardsImporter(AMFileUtil amFileUtil) { return new Mnemosyne2CardsImporter(amFileUtil); } @Provides @PerApplication @IntoMap @ClassKey(MnemosyneXMLExporter.class) Converter providesMnemosyneXMLExporter() { return new MnemosyneXMLExporter(); } @Provides @PerApplication @IntoMap @ClassKey(MnemosyneXMLImporter.class) Converter providesMnemosyneXMLImporter(AMFileUtil amFileUtil) { return new MnemosyneXMLImporter(amFileUtil); } @Provides @PerApplication @IntoMap @ClassKey(QATxtExporter.class) Converter providesQATxtExporter() { return new QATxtExporter(); } @Provides @PerApplication @IntoMap @ClassKey(QATxtImporter.class) Converter providesQATxtImporter(AMFileUtil amFileUtil) { return new QATxtImporter(amFileUtil); } @Provides @PerApplication @IntoMap @ClassKey(Supermemo2008XMLImporter.class) Converter providesSupermemo2008XMLImporter() { return new Supermemo2008XMLImporter(); } @Provides @PerApplication @IntoMap @ClassKey(SupermemoXMLImporter.class) Converter providesSupermemoXMLImporter(AMFileUtil amFileUtil) { return new SupermemoXMLImporter(amFileUtil); } @Provides @PerApplication @IntoMap @ClassKey(TabTxtExporter.class) Converter providesTabTxtExporter() { return new TabTxtExporter(); } @Provides @PerApplication @IntoMap @ClassKey(TabTxtImporter.class) Converter providesTabTxtImporter(AMFileUtil amFileUtil) { return new TabTxtImporter(amFileUtil); } @Provides @PerApplication @IntoMap @ClassKey(ZipExporter.class) Converter providesZipExporter() { return new ZipExporter(); } @Provides @PerApplication @IntoMap @ClassKey(ZipImporter.class) Converter providesZipImporter() { return new ZipImporter(); } }
josepfo/lamassu-server
new-lamassu-admin/src/pages/Customers/CustomerData.styles.js
<reponame>josepfo/lamassu-server import { offColor } from 'src/styling/variables' export default { header: { display: 'flex', flexDirection: 'row', marginBottom: 15 }, title: { marginTop: 7, marginRight: 24 }, editIcon: { marginTop: 5 }, cardIcon: { marginTop: 7 }, viewIcons: { marginRight: 12 }, wrapper: { display: 'block', overflow: 'hidden', whiteSpace: 'nowrap' }, separator: { color: offColor, margin: [[8, 0, 8, 150]], position: 'relative', display: 'inline-block', '&:before, &:after': { content: '""', position: 'absolute', background: offColor, top: '50%', width: 1000, height: 1 }, '&:before': { right: '100%', marginRight: 15 }, '&:after': { left: '100%', marginLeft: 15 } } }
MartinGeisse/public
name.martingeisse.slave-services/src/main/java/name/martingeisse/slave_services/application/Initializer.java
<reponame>MartinGeisse/public /** * Copyright (c) 2012 <NAME> * * This file is distributed under the terms of the MIT license. */ package name.martingeisse.slave_services.application; import java.util.EnumSet; import java.util.Locale; import javax.servlet.DispatcherType; import javax.servlet.Filter; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import name.martingeisse.api.handler.DefaultMasterHandler; import name.martingeisse.api.handler.misc.NotFoundHandler; import name.martingeisse.api.request.ApiRequestCycle; import name.martingeisse.api.servlet.ApiConfiguration; import name.martingeisse.api.servlet.ApiServletFilter; import name.martingeisse.common.javascript.JavascriptAssembler; import name.martingeisse.common.security.SecurityUtil; import name.martingeisse.database.EntityConnectionServletFilter; import name.martingeisse.jetty.AntiJsessionidUrlFilter; import name.martingeisse.jetty.FlushFilter; import name.martingeisse.jetty.GlobalServletContext; import name.martingeisse.jetty.NoFlushOrCloseFilter; import name.martingeisse.slave_services.application.security.SlaveServicesSecurityProvider; import name.martingeisse.slave_services.application.wicket.SlaveServicesWicketApplication; import name.martingeisse.slave_services.common.api.ApiRootHandler; import name.martingeisse.sql.EntityConnectionManager; import name.martingeisse.sql.MysqlDatabaseDescriptor; import org.apache.commons.lang3.StringUtils; import org.apache.wicket.protocol.http.WicketFilter; import org.eclipse.jetty.server.HttpConfiguration; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.SecureRequestCustomizer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.server.SslConnectionFactory; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlets.IncludableGzipFilter; import org.eclipse.jetty.util.ssl.SslContextFactory; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import com.hazelcast.core.Hazelcast; /** * This class initializes various parts of the system through a single * static method. Before that method is called, however, the {@link Configuration} * must be initialized. */ public class Initializer { /** * Content-Types to compress on-the-fly with GZIP. */ private static final String[] gzipContentTypes = { "text/html", "text/plain", "text/xml", "text/css", "text/javascript", "application/xhtml+xml", "application/javascript", "application/x-javascript", "image/svg+xml" }; /** * Prevent instantiation. */ private Initializer() { } /** * Initializes the base system. */ public static void initializeBase() { // TODO set default locale DateTimeZone.setDefault(DateTimeZone.UTC); Constants.timeZone = DateTimeZone.forID("Europe/Berlin"); Constants.internalDateFormatter = JavascriptAssembler.defaultDateFormatter = DateTimeFormat.forPattern("YYYY-MM-dd").withZone(Constants.timeZone); Constants.internalDateTimeFormatter = JavascriptAssembler.defaultDateTimeFormatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss").withZone(Constants.timeZone); Constants.loggingDateFormatter = DateTimeFormat.forPattern("dd.MM.YYYY").withZone(Constants.timeZone); Constants.loggingDateTimeFormatter = DateTimeFormat.forPattern("dd.MM.YYYY HH:mm:ss").withZone(Constants.timeZone); Constants.uiDateFormatter = Constants.loggingDateFormatter; Constants.uiDateTimeFormatter = Constants.loggingDateTimeFormatter; SecurityUtil.initialize(new SlaveServicesSecurityProvider()); } /** * Initializes the SQL DB connection. */ public static void initializeSqlDatabase() { final MysqlDatabaseDescriptor database = new MysqlDatabaseDescriptor(); database.setDisplayName("main database"); database.setUrl(Configuration.databaseUrl.getMandatoryValue()); database.setUsername(Configuration.databaseUsername.getMandatoryValue()); database.setPassword(Configuration.databasePassword.getMandatoryValue()); database.setDefaultTimeZone(Constants.timeZone); database.initialize(); EntityConnectionManager.initializeDatabaseDescriptors(database); SlaveServicesSqldb.database = database; } /** * Initializes the Hazelcast cluster connection. */ public static void initializeHazelcast() { SlaveServicesHazelcast.instance = Hazelcast.newHazelcastInstance(); } /** * Launches the web user interface. */ public static void initializeWeb() { final EnumSet<DispatcherType> allDispatcherTypes = EnumSet.allOf(DispatcherType.class); // create and configure a servlet context final ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); context.getSessionHandler().getSessionManager().setMaxInactiveInterval(30 * 60); context.setInitParameter("org.eclipse.jetty.servlet.SessionIdPathParameterName", "none"); // make the servlet context globally available context.addEventListener(new GlobalServletContext()); // prevent JSESSIONID from appearing context.addFilter(AntiJsessionidUrlFilter.class, "/*", allDispatcherTypes); // log timing info for all requests // addGlobalFilter(context, new TimingFilter()); // make sure all responses get flushed addGlobalFilter(context, new FlushFilter()); // add GZIP filter final FilterHolder gzipFilterHolder = new FilterHolder(new IncludableGzipFilter()); gzipFilterHolder.setInitParameter("mimeTypes", StringUtils.join(gzipContentTypes, ',')); context.addFilter(gzipFilterHolder, "/*", EnumSet.allOf(DispatcherType.class)); // add sidekicks and helper filters addGlobalFilter(context, new EntityConnectionServletFilter()); // add API filter { ApiRequestCycle.setUseSessions(false); DefaultMasterHandler masterHandler = new DefaultMasterHandler(); masterHandler.setApplicationRequestHandler(new ApiRootHandler()); masterHandler.getInterceptHandlers().put("/favicon.ico", new NotFoundHandler(false)); ApiConfiguration configuration = new ApiConfiguration(); configuration.setMasterRequestHandler(masterHandler); configuration.getLocalizationConfiguration().setGlobalFallback(Locale.US); ApiConfiguration.setInstance(configuration); } addGlobalFilter(context, new ApiServletFilter() { @Override protected boolean isApiRequest(ServletRequest request) { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest)request; return httpRequest.getHeader("host").startsWith("api."); } else { return false; } } }); // for Wicket, prevent flushing or closing the response addGlobalFilter(context, new NoFlushOrCloseFilter()); // add the Wicket filter final Filter wicketFilter = new WicketFilter(); final FilterHolder wicketFilterHolder = new FilterHolder(wicketFilter); wicketFilterHolder.setInitParameter(WicketFilter.FILTER_MAPPING_PARAM, "/*"); wicketFilterHolder.setInitParameter("applicationClassName", SlaveServicesWicketApplication.class.getCanonicalName()); // wicketFilterHolder.setInitParameter("configuration", "deployment"); context.addFilter(wicketFilterHolder, "/*", allDispatcherTypes); // a default servlet is needed, otherwise the filters cannot catch the request context.addServlet(DefaultServlet.class, "/*"); // build SSL configuration SslContextFactory sslContextFactory = new SslContextFactory("/Users/martin/.keystore"); sslContextFactory.setKeyStorePassword("<PASSWORD>"); // build the server object final Server server = new Server(); // build HTTP(S) configurations HttpConfiguration httpConfiguration = new HttpConfiguration(); httpConfiguration.setSecurePort(8443); HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration); httpsConfiguration.addCustomizer(new SecureRequestCustomizer()); // build connection factories HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(httpConfiguration); HttpConnectionFactory httpsConnectionFactory = new HttpConnectionFactory(httpsConfiguration); SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslContextFactory, "http/1.1"); // build connectors and add them to the server ServerConnector httpConnector = new ServerConnector(server, httpConnectionFactory); httpConnector.setPort(8080); server.addConnector(httpConnector); ServerConnector httpsConnector = new ServerConnector(server, sslConnectionFactory, httpsConnectionFactory); httpsConnector.setPort(8443); server.addConnector(httpsConnector); // start the server server.setHandler(context); try { server.start(); server.join(); } catch (final Exception e) { throw new RuntimeException(e); } } /** * */ private static void addGlobalFilter(final ServletContextHandler context, final Filter filter) { final FilterHolder filterHolder = new FilterHolder(filter); context.addFilter(filterHolder, "/*", EnumSet.allOf(DispatcherType.class)); } }
mupraj10/c2
server/db/models/pet.spec.js
<filename>server/db/models/pet.spec.js const {expect} = require('chai') const db = require('../index') const Pet = db.model('pet') describe('Pet model', () => { beforeEach(() => { return db.sync({force: true}) }) })
skdx/peragraph
src/com/peralex/utilities/ui/graphs/constellationGraph/SquareLayout.java
<filename>src/com/peralex/utilities/ui/graphs/constellationGraph/SquareLayout.java package com.peralex.utilities.ui.graphs.constellationGraph; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Insets; import java.awt.LayoutManager2; /** * A Layout manager that sizes it's component to be square, and in the centre of it's parent. * * This is useful for the constellation graph because a constellation graph needs to be square. * * @author Andre */ public class SquareLayout implements LayoutManager2 { private Component comp; /** * Creates a new instance of SquareLayout */ public SquareLayout() { } /** * Required by LayoutManager. */ public void addLayoutComponent(String name, Component _comp) { if (this.comp!=null) throw new IllegalStateException("there can be one and only component in a SquareLayout"); this.comp = _comp; } /** * Required by LayoutManager. */ public void removeLayoutComponent(Component _comp) { if (this.comp==_comp) this.comp = null; } /** * Required by LayoutManager. */ public Dimension preferredLayoutSize(Container parent) { return new Dimension(0, 0); } /** * Required by LayoutManager. */ public Dimension minimumLayoutSize(Container parent) { return new Dimension(0, 0); } /** * Required by LayoutManager. * This is called when the panel is first displayed, * and every time its size changes. * Note: You CAN'T assume preferredLayoutSize or * minimumLayoutSize will be called -- in the case * of applets, at least, they probably won't be. */ public void layoutContainer(Container oParent) { final Insets oInsets = oParent.getInsets(); final int iMaxWidth = oParent.getWidth() - (oInsets.left + oInsets.right); final int iMaxHeight = oParent.getHeight() - (oInsets.top + oInsets.bottom); final int iWidth, iHeight; if (iMaxWidth >= iMaxHeight) { iWidth = iMaxHeight; iHeight = iMaxHeight; } else { iWidth = iMaxWidth; iHeight = iMaxWidth; } final int iXPos = ((iMaxWidth - iWidth) / 2) + oInsets.left; final int iYPos = ((iMaxHeight - iHeight) / 2) + oInsets.top; oParent.getComponent(0).setBounds(iXPos, iYPos, iWidth, iHeight); } /** * Required by LayoutManager2. */ public void addLayoutComponent(Component _comp, Object constraints) { if (this.comp!=null) throw new IllegalStateException("there can be one and only component in a SquareLayout"); this.comp = _comp; } /** * Required by LayoutManager2. */ public float getLayoutAlignmentX(Container target) { return 0.5f; } /** * Required by LayoutManager2. */ public float getLayoutAlignmentY(Container target) { return 0.5f; } /** * Required by LayoutManager2. */ public void invalidateLayout(Container target) { } /** * Required by LayoutManager2. */ public Dimension maximumLayoutSize(Container target) { return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE); } }
kagwicharles/Seniorproject-ui
node_modules/@iconify/icons-ic/baseline-no-drinks.js
var data = { "body": "<path d=\"M5.83 3H21v2l-6.2 6.97L9.83 7h6.74l1.78-2H7.83l-2-2zm13.95 19.61L18 20.83V21H6v-2h5v-5l-1.37-1.54l-8.24-8.24L2.8 2.81L3 3l18.19 18.19l-1.41 1.42zM16.17 19L13 15.83V19h3.17z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; exports.__esModule = true; exports.default = data;
DennyGD/JavaSciptBasics
ArraysMethods/scripts/makePerson.js
/* Write a function for creating people. Each person must have firstname, lastname, age and gender (true is female, false is male) Generate an array with ten people with different names, ages and genders */ var clones = [], cloneName = 'John', initialAge = 20, isFemale; for (var i = 1; i <= 10; i += 1 ) { isFemale = generateRandomBool(); clones.push(createPerson(cloneName, i.toString(), initialAge + i, isFemale)); } console.log('MAKE PERSON'); console.log('Clones:'); clones.forEach(function(clone){console.log(clone.toString())}); function createPerson(firstName, lastName, age, gender){ if (!firstName || !lastName || isNaN(age) || (typeof gender !== 'boolean')) { return 'Invalid arguments.'; } return { firstName: firstName, lastName: lastName, age: age, gender: gender === true ? 'female' : 'male', toString: function(){return 'name: ' + this.firstName + this.lastName + '; age: ' + this.age + '; gender: ' + this.gender} } } function generateRandomBool(){ return Boolean(Math.floor(Math.random() * 2)); }
DTenore/skulpt
src/lib/urllib2.py
<filename>src/lib/urllib2.py import _sk_fail; _sk_fail._("urllib2")
laurentperrinet/homebrew-cask
Casks/lyn.rb
<gh_stars>0 class Lyn < Cask url 'http://www.lynapp.com/downloads/Lyn-1.3.4.dmg' homepage 'http://www.lynapp.com/' version '1.3.4' sha1 '9d9e3dae26f6236bb930ee0b92eb96e46ea74a7c' link 'Lyn.app' end
andy176631/skb-java-interfaces
src/main/java/de/vandermeer/skb/interfaces/transformers/textformat/String_To_RightPadded.java
<gh_stars>1-10 /* Copyright 2016 <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. */ package de.vandermeer.skb.interfaces.transformers.textformat; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.text.StrBuilder; import de.vandermeer.skb.interfaces.transformers.IsTransformer; /** * Converts a string to a right-padded string of given length. * If the given string length is less than the required length, padding characters will be added to the right. * The returned string will be of the required length, blank strings will have only padding characters. * * The method can be further customized by * - Setting an inner white space character - replace all white spaces in the text with that character * * The default length is {@link #DEFAULT_LENGTH}. * The default padding character is {@link #DEFAULT_PADDING_CHARACTER}. * The default inner white space character is {@link #DEFAULT_INNER_WHITESPACE_CHARACTER}. * * The actual return object is of type {@link StrBuilder} to minimize the creation of lots of strings for more complex transformations. * An implementation can chose to provide a builder to append the padded string to as well. * * @author <NAME> &lt;<EMAIL>&gt; * @version v0.0.2 build 170502 (02-May-17) for Java 1.8 * @since v0.0.1 */ public interface String_To_RightPadded extends IsTransformer<String, StrBuilder> { /** The default width, set to 80. */ static int DEFAULT_LENGTH = 80; /** Default padding character, set to ' '. */ static char DEFAULT_PADDING_CHARACTER = ' '; /** Default white space replacement character, set to ' '. */ static char DEFAULT_INNER_WHITESPACE_CHARACTER = ' '; /** * Returns the required length for the conversion. * @return length, default is {@link #DEFAULT_LENGTH} */ default int getLength(){ return DEFAULT_LENGTH; } /** * Returns the white space replacement character. * @return white space replacement character, default is {@link #DEFAULT_INNER_WHITESPACE_CHARACTER} */ default Character getInnerWsChar(){ return DEFAULT_INNER_WHITESPACE_CHARACTER; } /** * Returns the padding character for the conversion. * @return padding character, cannot be null, default is {@link #DEFAULT_PADDING_CHARACTER} */ default Character getPaddingChar(){ return DEFAULT_PADDING_CHARACTER; } /** * Returns a builder to append the padded string to, rather than creating a new builder. * @return builder, can be null, if not null the padding string will be appended to it */ default StrBuilder getBuilderForAppend(){ return null; } @Override default StrBuilder transform(String s) { IsTransformer.super.transform(s); StrBuilder ret = (this.getBuilderForAppend()==null)?new StrBuilder(this.getLength()):this.getBuilderForAppend(); String right = (s==null)?"":s; right = right.replace(' ', this.getInnerWsChar()); ret.appendFixedWidthPadLeft(right, this.getLength(), this.getPaddingChar()); return ret; } /** * Creates a transformer that converts a string to a right-padded string of given length. * @param length the required length (must be &gt;0) * @param paddingChar the padding character, default is used if null * @param innerWsChar inner white space replacement character * @param builder an optional builder to append the padded string to, used if set, ignored if null * @return new transformer * @see String_To_RightPadded interface description for how the converter works * @throws NullPointerException if an argument was unexpectedly null * @throws IllegalArgumentException if an argument was illegal */ static String_To_RightPadded create(int length, Character paddingChar, Character innerWsChar, StrBuilder builder){ Validate.validState(length>0, "cannot work with lenght of less than 1"); return new String_To_RightPadded() { @Override public int getLength(){ return length; } @Override public Character getInnerWsChar() { return (innerWsChar==null)?String_To_RightPadded.super.getInnerWsChar():innerWsChar; } @Override public Character getPaddingChar(){ return (paddingChar==null)?String_To_RightPadded.super.getPaddingChar():paddingChar; } @Override public StrBuilder getBuilderForAppend(){ return builder; } }; } /** * Returns right-padded string of given length using the default padding character. * @param s input string * @param length the required length (must be &gt;0) * @return right-padded string * @see String_To_RightPadded interface description for how the conversion works * @throws NullPointerException if an argument was unexpectedly null * @throws IllegalArgumentException if an argument was illegal */ static StrBuilder convert(String s, int length){ return String_To_RightPadded.create(length, null, null, null).transform(s); } /** * Returns right-padded string of given length. * @param s input string * @param length the required length (must be &gt;0) * @param builder an optional builder to append the padded string to, used if set, ignored if null * @return right-padded string * @see String_To_RightPadded interface description for how the conversion works * @throws NullPointerException if an argument was unexpectedly null * @throws IllegalArgumentException if an argument was illegal */ static StrBuilder convert(String s, int length, StrBuilder builder){ return String_To_RightPadded.create(length, null, null, builder).transform(s); } /** * Returns right-padded string of given length. * @param s input string * @param length the required length (must be &gt;0) * @param paddingChar the padding character, default is used if null * @return right-padded string * @see String_To_RightPadded interface description for how the conversion works * @throws NullPointerException if an argument was unexpectedly null * @throws IllegalArgumentException if an argument was illegal */ static StrBuilder convert(String s, int length, Character paddingChar){ return String_To_RightPadded.create(length, paddingChar, null, null).transform(s); } /** * Returns right-padded string of given length. * @param s input string * @param length the required length (must be &gt;0) * @param paddingChar the padding character, default is used if null * @param innerWsChar inner white space replacement character, default is used if null * @return right-padded string * @see String_To_RightPadded interface description for how the conversion works * @throws NullPointerException if an argument was unexpectedly null * @throws IllegalArgumentException if an argument was illegal */ static StrBuilder convert(String s, int length, Character paddingChar, Character innerWsChar){ return String_To_RightPadded.create(length, paddingChar, innerWsChar, null).transform(s); } /** * Returns right-padded string of given length. * @param s input string * @param length the required length (must be &gt;0) * @param paddingChar the padding character, default is used if null * @param builder an optional builder to append the padded string to, used if set, ignored if null * @return right-padded string * @see String_To_RightPadded interface description for how the conversion works * @throws NullPointerException if an argument was unexpectedly null * @throws IllegalArgumentException if an argument was illegal */ static StrBuilder convert(String s, int length, Character paddingChar, StrBuilder builder){ return String_To_RightPadded.create(length, paddingChar, null, builder).transform(s); } /** * Returns right-padded string of given length. * @param s input string * @param length the required length (must be &gt;0) * @param paddingChar the padding character, default is used if null * @param innerWsChar inner white space replacement character, default is used if null * @param builder an optional builder to append the padded string to, used if set, ignored if null * @return right-padded string * @see String_To_RightPadded interface description for how the conversion works * @throws NullPointerException if an argument was unexpectedly null * @throws IllegalArgumentException if an argument was illegal */ static StrBuilder convert(String s, int length, Character paddingChar, Character innerWsChar, StrBuilder builder){ return String_To_RightPadded.create(length, paddingChar, innerWsChar, builder).transform(s); } }
MdUsmanAnsari/College-Management-System
src/com/usman/utilities/Utilities.java
package com.usman.utilities; import com.usman.database.Database; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.paint.ImagePattern; import javafx.scene.shape.Shape; import javafx.stage.FileChooser; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import java.io.*; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; public class Utilities { private static int imageSize; private static final String FILE_NAME = "userData.json"; public static int getImageSize() { return imageSize; } public static Image binaryToImage(InputStream inputStream) throws IOException { try { OutputStream outputStream = new FileOutputStream(new File("UserPic.jpg")); byte[] content = new byte[1024]; int size = 0; imageSize=0; while ((size = inputStream.read(content)) != -1) { imageSize += size; outputStream.write(content, 0, size); } outputStream.close(); inputStream.close(); return new Image("file:UserPic.jpg"); }catch (Exception e){ return null; } } public static InputStream imageToBinary(Image image) { try { return (InputStream)new FileInputStream(image.impl_getUrl().replace("file:/","")); }catch (Exception e){ try { return (InputStream)new FileInputStream(image.impl_getUrl().replace("file:","")); } catch (FileNotFoundException ex) { ex.printStackTrace(); return null; } } } public static String getDate(LocalDate localDate){ return localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); } public static LocalDate getDate(String date){ int year = Integer.parseInt(date.substring(0,4)); int month = Integer.parseInt(date.substring(5,7)); int dayOfMonth = Integer.parseInt(date.substring(8,10)); return LocalDate.of(year,month,dayOfMonth); } public static void focusEvent(TextField textField){ textField.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue){ if (textField.getWidth()==100) Animation.searchBtnAnimation(textField,-300); }else{ Animation.searchBtnAnimation(textField,textField.getWidth()-100); } } }); } public static File browserPicture(){ FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("JPG File","*.jpg")); return fileChooser.showOpenDialog(null); } public static Image setPicture(File file, Shape shape){ Image image = null; if (file !=null && file.length() <= 5000000) { image = new Image(file.toURI().toString()); shape.setFill(new ImagePattern(image)); } return image; } // Get Name Of User from UsersTable public static String getNameOfPerson(String tableName, String email){ String emailFieldCorrect =email ; if (tableName.equalsIgnoreCase("StudentTable")) emailFieldCorrect = "EmailId"; else if (tableName.equalsIgnoreCase("TeacherTable")) emailFieldCorrect = "Email"; final String QUERY = "SELECT Name FROM "+tableName+" WHERE " + emailFieldCorrect + " = ? "; PreparedStatement ps; String name = null; Connection conn = Database.connection(); try { ps = conn.prepareStatement(QUERY); ps.setString(1,email); ResultSet rs = ps.executeQuery(); if (rs.next()) name = rs.getString(1); rs.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } return name; } private static void createFile() throws IOException { File file = new File(FILE_NAME); if (!file.exists()){ file.createNewFile(); } } // Save theme in json file public static void saveTheme(String themeName) throws Exception { String[] user = readDataInJsonFile(); writeDataInJsonFile(user[0], user[1], themeName); } // read theme public static String getTheme() throws Exception { Object obj = new JSONParser().parse(new FileReader(FILE_NAME)); // typecasting obj to JSONObject JSONObject jo = (JSONObject) obj; return (String) jo.get("theme"); } // Save data in JSON file public static void writeDataInJsonFile(String email, String password) throws IOException { createFile(); JSONObject jsonObject = new JSONObject(); jsonObject.put("email", email); jsonObject.put("password", password); PrintWriter pw = new PrintWriter(FILE_NAME); pw.write(jsonObject.toJSONString()); pw.flush(); pw.close(); } public static void writeDataInJsonFile(String email, String password, String theme) throws IOException { createFile(); JSONObject jsonObject = new JSONObject(); jsonObject.put("email", email); jsonObject.put("password", password); jsonObject.put("theme", theme); PrintWriter pw = new PrintWriter(FILE_NAME); pw.write(jsonObject.toJSONString()); pw.flush(); pw.close(); } public static String[] readDataInJsonFile() throws Exception { Object obj = new JSONParser().parse(new FileReader(FILE_NAME)); // typecasting obj to JSONObject JSONObject jo = (JSONObject) obj; // getting email and password String email = (String) jo.get("email"); String password = (String) jo.get("password"); String[] user = new String[2]; user[0] = email; user[1] = password; return user; } public static String todayDate(){ Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); return formatter.format(date); } public static String getIPAddress(){ InetAddress ipAddress = null; try{ ipAddress= InetAddress.getLocalHost(); }catch (UnknownHostException exception){ return "null"; } return ipAddress.getHostAddress(); } public static Date getAgoDate(int daysAgo){ Calendar c = Calendar.getInstance(); c.add(Calendar.DAY_OF_MONTH, daysAgo); return c.getTime(); } public static int getCountSpecificData(String tableName) throws SQLException { int count = 0; String COUNT_QUERY ="SELECT COUNT (*) FROM "+tableName; PreparedStatement ps = Database.connection().prepareStatement(COUNT_QUERY); count = ps.executeQuery().getInt(1); Database.close(ps); return count; } public static int getCountSpecificData(String tableName,String conditionField,String conditionValue,String secondCondition,String secondValue) throws SQLException { int count = 0; String COUNT_QUERY ="SELECT COUNT (*) FROM "+tableName+" WHERE "+conditionField+" = ? AND "+secondCondition+" = ?"; PreparedStatement ps = Database.connection().prepareStatement(COUNT_QUERY); ps.setString(1,conditionValue); ps.setString(2,secondValue); count = ps.executeQuery().getInt(1); Database.close(ps); return count; } public static int getCountSpecificData(String tableName,String conditionField,String conditionValue) throws SQLException { int count = 0; String COUNT_QUERY ="SELECT COUNT (*) FROM "+ tableName +" WHERE "+ conditionField +" = ?"; PreparedStatement ps = Database.connection().prepareStatement(COUNT_QUERY); ps.setString(1,conditionValue); count = ps.executeQuery().getInt(1); Database.close(ps); return count; } }
opengauss-mirror/Yat
openGaussBase/testcase/GUC/ERRORLOG/Opengauss_Function_Guc_ErrorLog_Case0003.py
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v2 for more details. """ """ Case Type : GUC_ErrorLog Case Name : 设置参数log_destination的值为syslog,查看日志文件 Description : 1.设置参数log_destination的值为syslog:gs_guc reload -N all -I all -c "log_destination='csvlog'",查看参数设置结果:show log_destination; 2.执行重启数据库操作:gs_om - t stop && gs_om -t start 5.查看是否在 $gaussdb_log/$username/pg_log/下生成.scv的log日志 Expect : 1.参数设置成功,返回值为csvlog 2.重启数据库完成 3.在 $gaussdb_log/$username/pg_log/下生成.scv的log日志 History : """ import os import unittest from yat.test import Node from yat.test import macro from testcase.utils.Common import Common from testcase.utils.CommonSH import CommonSH from testcase.utils.Constant import Constant from testcase.utils.Logger import Logger class Errorlog(unittest.TestCase): def setUp(self): self.logger = Logger() self.logger.info('==Opengauss_Function_Guc_ErrorLog_Case0003 start==') self.userNode = Node('PrimaryDbUser') self.primaryRoot = Node('PrimaryRoot') self.DB_ENV_PATH = macro.DB_ENV_PATH self.sh_primy = CommonSH('PrimaryDbUser') self.common = Common() self.constant = Constant() self.log_path = os.path.join(macro.DB_INSTANCE_PATH, 'wftest') def test_errorlog(self): self.logger.info('-------查看log_directory默认路径------') global path_return check_path_cmd = 'show log_directory;' check_path_msg = self.sh_primy.execut_db_sql(check_path_cmd) self.logger.info(check_path_msg) path_return = check_path_msg.splitlines()[2].strip() self.logger.info(path_return) self.assertTrue(path_return.find(macro.PG_LOG_PATH) > -1) self.logger.info('-------配置log_directory合法路径------') execute_cmd4 = f'source {self.DB_ENV_PATH};' \ f'gs_guc reload -D {macro.DB_INSTANCE_PATH} -c ' \ f'"log_directory=\'{self.log_path}\'"' execute_msg4 = self.userNode.sh(execute_cmd4).result() self.logger.info(execute_msg4) self.logger.info('----查看日志路径----') sql_execute = f'show log_directory;' msg_log = self.sh_primy.execut_db_sql(sql_execute) self.logger.info(msg_log) self.common.equal_sql_mdg(msg_log, 'log_directory', self.log_path, '(1 row)', flag='1') self.logger.info('--------------查看log_destination默认值----------') sql_cmd0 = 'show log_destination;' msg0 = self.sh_primy.execut_db_sql(sql_cmd0) self.logger.info(msg0) self.common.equal_sql_mdg(msg0, 'log_destination', 'stderr', '(1 row)', flag='1') self.logger.info('---------设置参数log_destination的值为syslog-----') msg1 = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, f'log_destination=\'csvlog\'') self.logger.info(msg1) self.logger.info('-------查看log_destination修改后的值为csvlog-------') sql_cmd2 = 'show log_destination;' msg2 = self.sh_primy.execut_db_sql(sql_cmd2) self.logger.info(msg2) self.common.equal_sql_mdg(msg2, 'log_destination', 'csvlog', '(1 row)', flag='1') self.logger.info('-------重启数据库生成日志文件-------') excute_cmd3 = f'source {self.DB_ENV_PATH};' \ f'gs_om -t stop && gs_om -t start' msg3 = self.userNode.sh(excute_cmd3).result() self.logger.info(msg3) self.logger.info('-------查看是否生成日志文件-------') excute_cmd5 = f'ls -l {self.log_path} |grep "csv" |wc -l' msg5 = self.primaryRoot.sh(excute_cmd5).result() self.logger.info(msg5) self.assertTrue(int(msg5) >= 1) def tearDown(self): self.logger.info('-------恢复配置,清理环境-------') msg1 = self.sh_primy.execute_gsguc('reload', self.constant.GSGUC_SUCCESS_MSG, 'log_destination=\'stderr\'') self.logger.info(msg1) self.logger.info('-------查看log_destination是否恢复为stderr-------') sql_cmd2 = 'show log_destination;' msg2 = self.sh_primy.execut_db_sql(sql_cmd2) self.logger.info(msg2) self.common.equal_sql_mdg(msg2, 'log_destination', 'stderr', '(1 row)', flag='1') self.logger.info('-------恢复log_directory路径,清理环境-------') recover_cmd = f'source {self.DB_ENV_PATH};' \ f'gs_guc reload -D {macro.DB_INSTANCE_PATH} -c ' \ f'"log_directory=\'{path_return}\'";' recover_msg = self.userNode.sh(recover_cmd).result() self.logger.info(recover_msg) self.logger.info('-------查看配置是否恢复-------') check_path_cmd = 'show log_directory;' check_path_msg = self.sh_primy.execut_db_sql(check_path_cmd) self.logger.info(check_path_msg) self.assertTrue(macro.PG_LOG_PATH in path_return) self.logger.info('-------删除生成的日志文件-------') rm_log_file = self.log_path + "/*csv" execute_cmd3 = f'rm -rf {rm_log_file}' msg3 = self.primaryRoot.sh(execute_cmd3).result() self.logger.info(msg3) self.logger.info('-------检查日志文件被删除-------') excute_cmd4 = f'ls -l {self.log_path} |grep "csv" |wc -l' msg4 = self.primaryRoot.sh(excute_cmd4).result() self.logger.info(msg4) self.assertTrue(int(msg4) == 0) self.logger.info('--Opengauss_Function_Guc_ErrorLog_Case0003 finish--')
spurious/safecode-mirror
lib/Utility/BreakConstantStrings.cpp
<filename>lib/Utility/BreakConstantStrings.cpp //===- BreakConstantStrings.cpp - Make global string constants non-constant - // // // The SAFECode Compiler // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass removes the constant attribute from all global strings. This is // done so that the native system linker does not link the strings into the // same global string. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "break-conststrings" #include "llvm/ADT/Statistic.h" #include "llvm/IR/Constants.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Support/InstIterator.h" #include "safecode/BreakConstantStrings.h" #include <iostream> #include <map> #include <utility> namespace llvm { // Identifier variable for the pass char BreakConstantStrings::ID = 0; // Statistics STATISTIC (GVChanges, "Number of Strings Made Non-Constant"); // Register the pass static RegisterPass<BreakConstantStrings> P ("break-conststrings", "Make strings non-constant"); // // Method: runOnModule() // // Description: // Entry point for this LLVM pass. // // Return value: // true - The module was modified. // false - The module was not modified. // bool BreakConstantStrings::runOnModule (Module & M) { bool modified = false; const Type * Int8Type = IntegerType::getInt8Ty(getGlobalContext()); // // Scan through all the global variables in the module. Mark a variable as // non-constant if: // o) The variable is constant // o) The variable is an array of characters (Int8Ty). // o) The variable is not in a special section (e.g. debug info section). // This ensures that we don't mess up debug information or other special // strings within the code. // Module::global_iterator i,e; for (i = M.global_begin(), e = M.global_end(); i != e; ++i) { GlobalVariable * GV = i; // // All global variables are pointer types. Find the type of what the // global variable pointer is pointing at. // if (GV->isConstant() && (!GV->hasSection())) { const PointerType * PT = dyn_cast<PointerType>(GV->getType()); if (const ArrayType * AT = dyn_cast<ArrayType>(PT->getElementType())) { if (AT->getElementType() == Int8Type) { modified = true; ++GVChanges; GV->setConstant (false); } } } } return modified; } }
DwayneJengSage/BridgePF
test/org/sagebionetworks/bridge/dynamodb/DynamoReportDataDaoTest.java
package org.sagebionetworks.bridge.dynamodb; import static org.junit.Assert.assertEquals; import static org.sagebionetworks.bridge.TestConstants.TEST_STUDY; import java.util.Set; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.sagebionetworks.bridge.TestUtils; import org.sagebionetworks.bridge.models.DateRangeResourceList; import org.sagebionetworks.bridge.models.ForwardCursorPagedResourceList; import org.sagebionetworks.bridge.models.reports.ReportData; import org.sagebionetworks.bridge.models.reports.ReportDataKey; import org.sagebionetworks.bridge.models.reports.ReportType; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Sets; @ContextConfiguration("classpath:test-context.xml") @RunWith(SpringJUnit4ClassRunner.class) public class DynamoReportDataDaoTest { private static final LocalDate END_DATE = LocalDate.parse("2016-03-31"); private static final LocalDate START_DATE = LocalDate.parse("2016-03-29"); @Autowired DynamoReportDataDao dao; private String reportId; private ReportDataKey reportDataKey; private ReportDataKey differentReportDataKey; @Before public void before() { reportId = TestUtils.randomName(DynamoReportDataDaoTest.class); reportDataKey = new ReportDataKey.Builder().withReportType(ReportType.STUDY).withIdentifier(reportId) .withStudyIdentifier(TEST_STUDY).build(); } @After public void after() { if (reportDataKey != null) { dao.deleteReportData(reportDataKey); } if (differentReportDataKey != null) { dao.deleteReportData(differentReportDataKey);; } } @Test public void canCrud() { String reportId = TestUtils.randomName(DynamoReportDataDaoTest.class); differentReportDataKey = new ReportDataKey.Builder().withReportType(ReportType.STUDY).withIdentifier(reportId) .withStudyIdentifier(TEST_STUDY).build(); // A report clearly outside the date range ReportData report0 = createReport(LocalDate.parse("2016-02-14"), "g", "h"); // Two reports that are in the date range, with the right key, that should be returned. ReportData report1 = createReport(LocalDate.parse("2016-03-30"), "a", "b"); ReportData report2 = createReport(LocalDate.parse("2016-03-31"), "c", "d"); // And this is in the date range, but has a different key. ReportData report3 = createReport(LocalDate.parse("2016-03-30"), "e", "f"); report3.setKey(differentReportDataKey.getKeyString()); // These are not in date order. They should come back in date order. dao.saveReportData(report3); dao.saveReportData(report2); dao.saveReportData(report1); dao.saveReportData(report0); DateRangeResourceList<? extends ReportData> results = dao.getReportData( reportDataKey, START_DATE, END_DATE); assertResourceList(results, 2); assertReportDataEqual(report1, results.getItems().get(0)); assertReportDataEqual(report2, results.getItems().get(1)); dao.deleteReportData(reportDataKey); results = dao.getReportData(reportDataKey, START_DATE, END_DATE); assertResourceList(results, 0); } @Test public void canRetrievePagedRecordsWithDateTime() throws Exception { String dateString = "2017-02-%02dT04:00:00.000Z"; for (int i=2; i <= 19; i++) { DateTime dateTime = DateTime.parse(String.format(dateString, i)); ReportData report = createReport(dateTime, "a", "b"); dao.saveReportData(report); } DateTime startTime = DateTime.parse("2017-02-02T04:00:00.000Z"); DateTime endTime = DateTime.parse("2017-02-19T04:00:00.000Z"); Set<String> keys = Sets.newHashSet(); ForwardCursorPagedResourceList<ReportData> paged = dao.getReportDataV4(reportDataKey, startTime, endTime, null, 5); for (ReportData data : paged.getItems()) { keys.add(data.getDate()); } assertEquals(5, keys.size()); assertEquals("2017-02-02T04:00:00.000Z", paged.getItems().get(0).getDate()); paged = dao.getReportDataV4(reportDataKey, startTime, endTime, paged.getNextPageOffsetKey(), 5); for (ReportData data : paged.getItems()) { keys.add(data.getDate()); } assertEquals(10, keys.size()); paged = dao.getReportDataV4(reportDataKey, startTime, endTime, paged.getNextPageOffsetKey(), 5); for (ReportData data : paged.getItems()) { keys.add(data.getDate()); } assertEquals(15, keys.size()); paged = dao.getReportDataV4(reportDataKey, startTime, endTime, paged.getNextPageOffsetKey(), 5); for (ReportData data : paged.getItems()) { keys.add(data.getDate()); } assertEquals(18, keys.size()); keys.clear(); // Now, while we have these records, let's change the timezone and verify that works. startTime = DateTime.parse("2017-02-02T04:00:00.000-07:00"); endTime = DateTime.parse("2017-02-19T04:00:00.000-07:00"); // Should be missing the last record paged = dao.getReportDataV4(reportDataKey, startTime, endTime, null, 100); for (ReportData data : paged.getItems()) { keys.add(data.getDate()); } assertEquals(17, keys.size()); assertEquals("2017-02-02T21:00:00.000-07:00", paged.getItems().get(0).getDate()); // We can use the other API to get these records, it's implicitly UTC because what else could it be LocalDate startDate = LocalDate.parse("2017-02-02"); LocalDate endDate = LocalDate.parse("2017-02-19"); DateRangeResourceList<? extends ReportData> anotherPage = dao.getReportData(reportDataKey, startDate, endDate); // It's 17 because "2017-02-19" comes before "2017-02-19T04:00:00.000Z" alphabetically (moral: don't mix the two types) assertEquals(17, anotherPage.getItems().size()); } @Test public void canDeleteSingleStudyRecords() { ReportData report1 = createReport(LocalDate.parse("2016-03-30"), "a", "b"); ReportData report2 = createReport(LocalDate.parse("2016-03-31"), "c", "d"); dao.saveReportData(report1); dao.saveReportData(report2); assertEquals(2, dao.getReportData(reportDataKey, START_DATE, END_DATE).getItems().size()); dao.deleteReportDataRecord(reportDataKey, "2016-03-30"); assertEquals(1, dao.getReportData(reportDataKey, START_DATE, END_DATE).getItems().size()); dao.deleteReportDataRecord(reportDataKey, "2016-03-31"); assertEquals(0, dao.getReportData(reportDataKey, START_DATE, END_DATE).getItems().size()); } private ReportData createReport(LocalDate date, String fieldValue1, String fieldValue2) { ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put("field1", fieldValue1); node.put("field2", fieldValue2); ReportData report = ReportData.create(); report.setKey(reportDataKey.getKeyString()); report.setData(node); report.setLocalDate(date); return report; } private ReportData createReport(DateTime date, String fieldValue1, String fieldValue2) { ObjectNode node = JsonNodeFactory.instance.objectNode(); node.put("field1", fieldValue1); node.put("field2", fieldValue2); ReportData report = ReportData.create(); report.setKey(reportDataKey.getKeyString()); report.setData(node); report.setDateTime(date); return report; } private void assertReportDataEqual(ReportData original, ReportData retrieved) { assertEquals(original.getDate(), retrieved.getDate()); assertEquals(reportDataKey.getKeyString(), retrieved.getKey()); assertEquals(original.getData().get("field1").asText(), retrieved.getData().get("field1").asText()); assertEquals(original.getData().get("field2").asText(), retrieved.getData().get("field2").asText()); } private void assertResourceList(DateRangeResourceList<? extends ReportData> results, int recordNumber) { assertEquals(recordNumber, results.getItems().size()); assertEquals(START_DATE, results.getRequestParams().get("startDate")); assertEquals(END_DATE, results.getRequestParams().get("endDate")); } }
mcdeoliveira/NC
NCGB/Compile/src/OBSOLETE2009/SortPattern.hpp
<reponame>mcdeoliveira/NC // (c) <NAME> 1999 // SortPattern.hpp #ifndef INCLUDED_SORTPATTERN_H #define INCLUDED_SORTPATTERN_H #include "SortPattern.hpp" #pragma warning(disable:4786) #include "Choice.hpp" #ifdef HAS_INCLUDE_NO_DOTS #include <map> #else #include <map.h> #endif #include "GroebnerRule.hpp" #include "RuleDisplayPart.hpp" #ifdef HAS_INCLUDE_NO_DOTS #include <list> #else #include <list.h> #endif class BuildOutput; #include "vcpp.hpp" void SortPattern(const list<GroebnerRule> & L,BuildOutput & build,list<RuleDisplayPart> & result); #endif
viktor-silakov/syngrisi
lib/getElementsByPixPositionsFromDump.js
const getElementsByPositionFromDump = function getElementsByPositionFromDump(x, y, dump, offset = 1) { return new Promise(function (resolve, reject) { try { // check if position is gets into dumped elements rects boundaries let data = dump .filter(function (item) { return (x >= item.left) && (x <= item.right) && (y >= item.top) && (y <= item.bottom); }) .sort((a, b) => (a.domPath.length) < (b.domPath.length) ? 1 : -1); if (data.length < 1) { return resolve(null); } const pos = data[0]; return resolve({ tag: pos.tag, id: pos.id, x: pos.x, y: pos.y, width: pos.width, height: pos.height, domPath: pos.domPath, request: `${x}, ${y}` }); } catch (e) { return reject(e); } }); }; const getAllElementsByPositionFromDump = function getAllElementsByPositionFromDump(dump, positions) { return new Promise(function (resolve, reject) { try { let executionTimer = process.hrtime(); console.log(`Start parse elements from dump based on diff`); let promResults = []; for (const position of positions) { const el = getElementsByPositionFromDump(position.x, position.y, dump); promResults.push(el); } console.log(`Promises formed, time: ${process.hrtime(executionTimer) .toString()}`); let dumpResults = {}; Promise.all(promResults) .then((values) => { console.log(`Promises resolved, time: ${process.hrtime(executionTimer) .toString()}`); for (el of values) { // to make dump unique if (el !== null) { const key = `${el.tag}_${el.id}_${el.x}_${el.y}_${el.width}_${el.height}_${el.domPath.toString()}`; dumpResults[key] = el; } } console.log(`End parse elements from dump based on diff, time: '${process.hrtime(executionTimer) .toString()}'`); return resolve(Object.values(dumpResults) .map(x => x)); }); } catch (e) { reject(e); } }); }; module.exports = { getElementsByPositionFromDump: getElementsByPositionFromDump, getAllElementsByPositionFromDump: getAllElementsByPositionFromDump, };
lpea/cppinclude
src/reporter/impl/most_impact_reporter/rp_most_impact_reporter_detail.hpp
<reponame>lpea/cppinclude<gh_stars>100-1000 #pragma once #include "reporter/impl/tools/rp_file_with_count.hpp" //------------------------------------------------------------------------------ namespace model_includes { class IncludeLocation; class File; } //------------------------------------------------------------------------------ namespace reporter { //------------------------------------------------------------------------------ class MostImpactReporterDetail { public: using CountType = FileWithCount::CountType; MostImpactReporterDetail( const model_includes::File & _file, CountType _includedByCount, const model_includes::IncludeLocation & _includeLocation ); public: const model_includes::File & getFile() const; FileWithCount::CountType getIncludedByCount() const; const model_includes::IncludeLocation & getIncludeLocation() const; const FileWithCount & getFileInfo() const; private: const FileWithCount m_fileInfo; const model_includes::IncludeLocation & m_includeLocation; }; //------------------------------------------------------------------------------ }
filosunam/oceanic-exchanges
api/routers/admin/pages/detail.js
const moment = require('moment'); const Route = require('lib/router/route'); const { Page } = require('models'); module.exports = new Route({ method: 'get', path: '/:id', handler: async function(ctx) { const { id: _id } = ctx.params; const page = await Page.findOne({ _id }); ctx.assert(page, 404, 'Page not found'); ctx.body = { data: page.toAdmin(), }; }, });
LorranSutter/URI-Online-Judge
Mathematics/1197.py
while True: try: v, t = tuple(map(int,input().split())) print(v*t*2) except: break
nageshwarrao19/BUILD
BUILD_Auth/client/login/index.js
'use strict'; module.exports = angular.module('account.login', []) .config(function ($stateProvider) { $stateProvider.state('login', { url: '/login', templateUrl: './resources/norman-auth-client/login/login.html', controller: 'LoginCtrl' }); }) .controller('LoginCtrl', require('./login.controller'));
thedavisproject/davis-shared
test/protocolTest.js
const {expect} = require('chai'); const protocol = require('../src/protocol'); describe('Protocols', function(){ it('should properly register protocol', function(){ const proto = protocol({ foo: ['data'] }); proto('type1', { foo: function(dataIgnored){ return 'bar'; } }); const dataObj = { __type: ['type1'] }; expect(proto.foo(dataObj)).to.equal('bar'); }); it('should properly register protocol with multiple methods', function(){ const proto = protocol({ foo: ['data'], bar: ['x', 'data'] }); proto('type1', { foo: function(dataIgnored){ return 'bar'; }, bar: function(x, data){ return x + data.val; } }); const dataObj = { __type: ['type1'], val: 3 }; expect(proto.foo(dataObj)).to.equal('bar'); expect(proto.bar(7, dataObj)).to.equal(10); }); it('should choose the right implementation', function(){ const proto = protocol({ foo: ['data'] }); proto('type1', { foo: function(dataIgnored){ return 'bar'; } }); proto('type2', { foo: function(dataIgnored){ return 'baz'; } }); const dataObj1 = { __type: ['type1'] }; const dataObj2 = { __type: ['type2'] }; expect(proto.foo(dataObj1)).to.equal('bar'); expect(proto.foo(dataObj2)).to.equal('baz'); }); it('should choose the first type implementation', function(){ const proto = protocol({ foo: ['data'] }); proto('type1', { foo: function(dataIgnored){ return 'bar'; } }); proto('type2', { foo: function(dataIgnored){ return 'baz'; } }); const dataObj1 = { __type: ['type2', 'type1'] }; expect(proto.foo(dataObj1)).to.equal('baz'); }); it('should fall back to implementations for types later in the list', function(){ const proto = protocol({ foo: ['data'] }); proto('type1', { foo: function(dataIgnored){ return 'bar'; } }); const dataObj1 = { __type: ['type2', 'type1'] }; expect(proto.foo(dataObj1)).to.equal('bar'); }); it('should throw exception for no implementation found', function(){ const proto = protocol({ foo: ['data'] }); proto('type1', { foo: function(dataIgnored){ return 'bar'; } }); const dataObj1 = { __type: ['typea', 'typeb'] }; expect(() => proto.foo(dataObj1)).to.throw('No implementation found for method: foo'); }); it('should throw registration exception for method not implemented', function(){ const proto = protocol({ foo: ['data'] }); expect(() =>proto('type1', { bar: function(dataIgnored){ return 'bar'; } })).to.throw('Error registering protocol implementation. Method not implemented: foo'); }); it('should throw registration exception for method not implemented with correct number of parameters', function(){ const proto = protocol({ foo: ['param1', 'data'] }); expect(() =>proto('type1', { foo: function(dataIgnored){ return 'bar'; } })).to.throw('Error registering protocol implementation. Method not implemented with proper number of parameters: foo. Expected: (param1, data) Found: (dataIgnored)'); }); });
soul2zimate/galleon-plugins
galleon-plugins/src/main/java/org/wildfly/galleon/plugin/JandexIndexer.java
/* * Copyright 2016-2018 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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 org.wildfly.galleon.plugin; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.jboss.galleon.MessageWriter; import org.jboss.jandex.Index; import org.jboss.jandex.IndexWriter; import org.jboss.jandex.Indexer; /** * @author <NAME> */ class JandexIndexer { public static void createIndex(File jarFile, OutputStream target, MessageWriter log) throws IOException { ZipOutputStream zo; Indexer indexer = new Indexer(); JarFile jar = new JarFile(jarFile); zo = new ZipOutputStream(target); try { Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().endsWith(".class")) { try { final InputStream stream = jar.getInputStream(entry); try { indexer.index(stream); } finally { safeClose(stream, log); } } catch (Exception e) { String message = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); log.error("Could not index " + entry.getName() + ": " + message, e); } } } zo.putNextEntry(new ZipEntry("META-INF/jandex.idx")); IndexWriter writer = new IndexWriter(zo); Index index = indexer.complete(); writer.write(index); } finally { safeClose(zo, log); safeClose(jar, log); safeClose(target, log); } } private static void safeClose(Closeable closeable, MessageWriter log) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { log.error("Failed to close", e); } } } }
incubos/icfpcontest2021
src/main/java/icfpc2021/actions/MoveVertexToGridAction.java
<reponame>incubos/icfpcontest2021<filename>src/main/java/icfpc2021/actions/MoveVertexToGridAction.java package icfpc2021.actions; import icfpc2021.model.Figure; import icfpc2021.model.Vertex; import icfpc2021.viz.State; import org.jetbrains.annotations.NotNull; import java.awt.geom.AffineTransform; import java.util.ArrayList; import java.util.List; public class MoveVertexToGridAction implements Action { private final int v; private final Vertex gridVertex; public MoveVertexToGridAction(int v, int x, int y) { this.v = v; this.gridVertex = new Vertex(x, y); } public MoveVertexToGridAction(int v, Vertex gridVertex) { this.v = v; this.gridVertex = gridVertex; } @Override public Figure apply(State state, Figure figure) { return doApply(figure); } @NotNull public Figure doApply(Figure figure) { List<Vertex> vertices = new ArrayList<>(figure.vertices); vertices.set(v, gridVertex); return new Figure(vertices, figure.edges); } @Override public String toString() { return "MoveVertexToGrid " + v + ": " + gridVertex.x + "," + gridVertex.y; } }
turnonline/ecosystem-admin-widgets
src/main/java/biz/turnonline/ecosystem/widget/shared/rest/payment/Bill.java
<filename>src/main/java/biz/turnonline/ecosystem/widget/shared/rest/payment/Bill.java /* * Copyright (c) 2020 TurnOnline.biz s.r.o. All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package biz.turnonline.ecosystem.widget.shared.rest.payment; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; /** * The bill or invoice document settled by associated transaction. */ public class Bill { @JsonProperty( "receipt" ) private Long receipt; @JsonProperty( "invoice" ) private Long invoice; @JsonProperty( "order" ) private Long order; /** * The receipt identification **/ @JsonProperty( "receipt" ) public Long getReceipt() { return receipt; } public void setReceipt( Long receipt ) { this.receipt = receipt; } public Bill invoiceId( Long invoiceId ) { this.invoice = invoiceId; return this; } /** * The invoice identification, unique only for specified order. **/ @JsonProperty( "invoice" ) public Long getInvoice() { return invoice; } public void setInvoice( Long invoice ) { this.invoice = invoice; } public Bill orderId( Long orderId ) { this.order = orderId; return this; } /** * The unique identification of the order associated with the settled invoice. **/ @JsonProperty( "order" ) public Long getOrder() { return order; } public void setOrder( Long order ) { this.order = order; } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } Bill bill = ( Bill ) o; return Objects.equals( this.receipt, bill.receipt ) && Objects.equals( this.invoice, bill.invoice ) && Objects.equals( this.order, bill.order ); } @Override public int hashCode() { return Objects.hash( invoice, order ); } @Override public String toString() { return "class Bill {\n" + " receipt: " + toIndentedString( receipt ) + "\n" + " invoice: " + toIndentedString( invoice ) + "\n" + " order: " + toIndentedString( order ) + "\n" + "}"; } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString( Object o ) { if ( o == null ) { return "null"; } return o.toString().replace( "\n", "\n " ); } }
liuzhen21/core
pkg/mapper/expression/expression_test.go
<filename>pkg/mapper/expression/expression_test.go package expression import ( "context" "testing" "github.com/stretchr/testify/assert" "github.com/tkeel-io/tdtl" ) func Test_Expression(t *testing.T) { exprIns, err := NewExpr("device234.properties.temp2", nil) assert.Nil(t, err) t.Log(exprIns.Sources()) res, err := exprIns.Eval(context.Background(), map[string]tdtl.Node{"device234.properties.temp2": tdtl.NewInt64(89)}) t.Log(map[string]tdtl.Node{"device234.properties.temp2": tdtl.NewInt64(89)}) assert.Nil(t, err) t.Log(res.String()) }
aschmach/client-mimis
src/components/story/Story.js
<gh_stars>0 import React from "react" import Box from "./box/Box" import Text from "./text/Text" import Profile from "./profile/Profile" import Newsletter from "./newsletter/Newsletter" import { infoBox } from "./infoBox" import { infoText } from "./infoText" import "./story.css" export const Intro = () => ( <> <Box props={infoBox["opening"]} /> <div className="smallDivider" /> <NewsletterBox /> <Box props={infoBox["vision"]} /> <Seperator /> <Box props={infoBox["editor"]} /> <Seperator /> <Box props={infoBox["people"]} /> <div className="smallDivider" /> <NewsletterBox /> </> ) export const Algorithm = () => ( <> <Title title={"THE GLOBAL EDITOR"} /> <Text text={infoText["algorithm"]} /> <NewsletterBox /> </> ) export const Team = () => ( <> <Title title={"EDITORIAL BOARD"} /> <Text text={infoText["team"]} /> <Profile /> <NewsletterBox /> </> ) export const Vision = props => ( <> <Title title={"OUR VISION"} /> <Text text={infoText["vision"]} /> <NewsletterBox /> </> ) export const Legal = props => ( <> <Title title={"LEGAL MATTERS"} /> <Text text={infoText["legal"]} /> <NewsletterBox /> </> ) const Title = ({ title }) => ( <> <div className="title">{title}</div> </> ) const NewsletterBox = () => ( <> <Title title={"STAY IN TOUCH"} /> <div className="smallDivider" /> <Newsletter /> <div className="bigDivider" /> </> ) const Seperator = () => ( <> <div className="smallDivider" /> <div className="blueLine" /> <div className="smallDivider" /> </> )
iMokhles/MyTheosHeaders
include/UIKit/UIGestureInfo.h
/** * This header is generated by class-dump-z 0.1-11o. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. */ #import "UIKit-Structs.h" #import <Foundation/NSObject.h> @class UIGestureAnimation, UIScrollAnimation; @interface UIGestureInfo : NSObject { id delegate; int enabledGestures; int rotationState; int zoomState; int panState; CGPoint startGestureInner; CGPoint startGestureOuter; CGPoint startScrollPoint; CGPoint endScrollPoint; CGSize visibleSize; CGRect centerRect; UIGestureAnimation* rotationAnimation; float rotationDegrees; float recentRotationDegrees; float minDegrees; float maxDegrees; float startDegrees; float endDegrees; UIGestureAnimation* zoomAnimation; int zoomRubberBandHysteresisCount; float zoomScale; float startScale; float endScale; float unadjustedScale; float zoomMultiplier; float minScale; float maxScale; CGPoint zoomFailureWindowPoint; float zoomFailureDuration; float zoomFailureStartScale; float zoomAnimationProgress; UIScrollAnimation* scrollAnimation; struct { unsigned pushedRunLoop : 1; unsigned isRotatingRight : 1; unsigned isZoomRubberBandEnabled : 1; unsigned zoomsFromCurrentToMinOrMax : 1; unsigned updatesScroller : 1; unsigned isAnimatingZoomFailure : 1; } flags; } -(id)init; -(void)dealloc; @end
viewdy/phantomjs
src/qt/qtwebkit/Source/WebCore/platform/network/blackberry/ResourceRequestBlackBerry.cpp
/* * Copyright (C) 2009, 2010, 2011 Research In Motion Limited. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "ResourceRequest.h" #include "BlobRegistryImpl.h" #include "CookieManager.h" #include <network/NetworkRequest.h> #include <wtf/HashMap.h> #include <wtf/text/CString.h> using BlackBerry::Platform::NetworkRequest; namespace WebCore { unsigned initializeMaximumHTTPConnectionCountPerHost() { return 10000; } static inline NetworkRequest::CachePolicy platformCachePolicyForRequest(const ResourceRequest& request) { switch (request.cachePolicy()) { case WebCore::UseProtocolCachePolicy: return NetworkRequest::UseProtocolCachePolicy; case WebCore::ReloadIgnoringCacheData: return NetworkRequest::ReloadIgnoringCacheData; case WebCore::ReturnCacheDataElseLoad: return NetworkRequest::ReturnCacheDataElseLoad; case WebCore::ReturnCacheDataDontLoad: return NetworkRequest::ReturnCacheDataDontLoad; default: return NetworkRequest::UseProtocolCachePolicy; } } static inline NetworkRequest::TargetType platformTargetTypeForRequest(const ResourceRequest& request) { if (request.isXMLHTTPRequest()) return NetworkRequest::TargetIsXMLHTTPRequest; if (request.forceDownload()) return NetworkRequest::TargetIsDownload; switch (request.targetType()) { case ResourceRequest::TargetIsMainFrame: return NetworkRequest::TargetIsMainFrame; case ResourceRequest::TargetIsSubframe: return NetworkRequest::TargetIsSubframe; case ResourceRequest::TargetIsSubresource: return NetworkRequest::TargetIsSubresource; case ResourceRequest::TargetIsStyleSheet: return NetworkRequest::TargetIsStyleSheet; case ResourceRequest::TargetIsScript: return NetworkRequest::TargetIsScript; case ResourceRequest::TargetIsFontResource: return NetworkRequest::TargetIsFontResource; case ResourceRequest::TargetIsImage: return NetworkRequest::TargetIsImage; case ResourceRequest::TargetIsObject: return NetworkRequest::TargetIsObject; case ResourceRequest::TargetIsMedia: return NetworkRequest::TargetIsMedia; case ResourceRequest::TargetIsWorker: return NetworkRequest::TargetIsWorker; case ResourceRequest::TargetIsSharedWorker: return NetworkRequest::TargetIsSharedWorker; // FIXME: this need to be updated to the right value, but // we need to coordinate with AIR api change. case ResourceRequest::TargetIsFavicon: return NetworkRequest::TargetIsImage; case ResourceRequest::TargetIsPrefetch: return NetworkRequest::TargetIsSubresource; case ResourceRequest::TargetIsXHR: return NetworkRequest::TargetIsSubresource; case ResourceRequest::TargetIsTextTrack: return NetworkRequest::TargetIsSubresource; case ResourceRequest::TargetIsUnspecified: return NetworkRequest::TargetIsSubresource; default: ASSERT_NOT_REACHED(); return NetworkRequest::TargetIsUnknown; } } typedef HashMap<String, ResourceRequest::TargetType> MimeTypeResourceRequestTypeMap; static const MimeTypeResourceRequestTypeMap& mimeTypeRequestTypeMap() { static MimeTypeResourceRequestTypeMap* map = 0; if (!map) { map = new MimeTypeResourceRequestTypeMap; if (map) { // The list here should match extensionMap[] in MIMETypeRegistryBlackBerry.cpp map->add(String("text/css"), ResourceRequest::TargetIsStyleSheet); map->add(String("application/x-javascript"), ResourceRequest::TargetIsScript); map->add(String("image/bmp"), ResourceRequest::TargetIsImage); map->add(String("image/gif"), ResourceRequest::TargetIsImage); map->add(String("image/x-icon"), ResourceRequest::TargetIsImage); map->add(String("image/jpeg"), ResourceRequest::TargetIsImage); map->add(String("image/png"), ResourceRequest::TargetIsImage); map->add(String("image/x-portable-bitmap"), ResourceRequest::TargetIsImage); map->add(String("image/x-portable-graymap"), ResourceRequest::TargetIsImage); map->add(String("image/x-portable-pixmap"), ResourceRequest::TargetIsImage); map->add(String("image/svg+xml"), ResourceRequest::TargetIsImage); map->add(String("image/tiff"), ResourceRequest::TargetIsImage); map->add(String("image/x-xbitmap"), ResourceRequest::TargetIsImage); map->add(String("image/x-xpm"), ResourceRequest::TargetIsImage); } } return *map; } ResourceRequest::TargetType ResourceRequest::targetTypeFromMimeType(const String& mimeType) { const MimeTypeResourceRequestTypeMap& map = mimeTypeRequestTypeMap(); MimeTypeResourceRequestTypeMap::const_iterator iter = map.find(mimeType); if (iter == map.end()) return ResourceRequest::TargetIsUnspecified; return iter->value; } void ResourceRequest::initializePlatformRequest(NetworkRequest& platformRequest, bool cookiesEnabled, bool isInitial, bool rereadCookies) const { // If this is the initial load, skip the request body and headers. if (isInitial) platformRequest.setRequestInitial(timeoutInterval()); else { platformRequest.setRequestUrl(url().string(), httpMethod(), platformCachePolicyForRequest(*this), platformTargetTypeForRequest(*this), timeoutInterval()); platformRequest.setConditional(isConditional()); platformRequest.setSuggestedSaveName(suggestedSaveName()); if (httpBody() && !httpBody()->isEmpty()) { RefPtr<FormData> formData = httpBody(); #if ENABLE(BLOB) formData = formData->resolveBlobReferences(); #endif const Vector<FormDataElement>& elements = formData->elements(); // Use setData for simple forms because it is slightly more efficient. if (elements.size() == 1 && elements[0].m_type == FormDataElement::data) platformRequest.setData(elements[0].m_data.data(), elements[0].m_data.size()); else { for (unsigned i = 0; i < elements.size(); ++i) { const FormDataElement& element = elements[i]; if (element.m_type == FormDataElement::data) platformRequest.addMultipartData(element.m_data.data(), element.m_data.size()); else if (element.m_type == FormDataElement::encodedFile) platformRequest.addMultipartFilename(element.m_filename.characters(), element.m_filename.length()); else ASSERT_NOT_REACHED(); // Blobs should be resolved at this point. } } } // When ResourceRequest is reused by CacheResourceLoader, page refreshing or redirection, its cookies may be dirtied. We won't use these cookies any more. bool cookieHeaderMayBeDirty = rereadCookies || cachePolicy() == WebCore::ReloadIgnoringCacheData || cachePolicy() == WebCore::ReturnCacheDataElseLoad; for (HTTPHeaderMap::const_iterator it = httpHeaderFields().begin(); it != httpHeaderFields().end(); ++it) { String key = it->key; String value = it->value; if (!key.isEmpty()) { if (equalIgnoringCase(key, "Cookie")) { // We won't use the old cookies of resourceRequest for new location because these cookies may be changed by redirection. if (cookieHeaderMayBeDirty) continue; // We need to check the encoding and encode the cookie's value using latin1 or utf8 to support unicode data. if (!value.containsOnlyLatin1()) { platformRequest.addHeader("Cookie", value.utf8().data()); continue; } } platformRequest.addHeader(key, value); } } // If request's cookies may be dirty, they must be set again. // If there aren't cookies in the header list, we need trying to add cookies. if (cookiesEnabled && (cookieHeaderMayBeDirty || !httpHeaderFields().contains("Cookie")) && !url().isNull()) { // Prepare a cookie header if there are cookies related to this url. String cookiePairs = cookieManager().getCookie(url(), WithHttpOnlyCookies); if (!cookiePairs.isEmpty()) platformRequest.addHeader("Cookie", cookiePairs.containsOnlyLatin1() ? cookiePairs.latin1().data() : cookiePairs.utf8().data()); } if (!httpHeaderFields().contains("Accept-Language")) platformRequest.addAcceptLanguageHeader(); } } PassOwnPtr<CrossThreadResourceRequestData> ResourceRequest::doPlatformCopyData(PassOwnPtr<CrossThreadResourceRequestData> data) const { data->m_token = m_token; data->m_anchorText = m_anchorText; data->m_overrideContentType = m_overrideContentType; data->m_suggestedSaveName = m_suggestedSaveName; data->m_isXMLHTTPRequest = m_isXMLHTTPRequest; data->m_mustHandleInternally = m_mustHandleInternally; data->m_forceDownload = m_forceDownload; data->m_targetType = m_targetType; return data; } void ResourceRequest::doPlatformAdopt(PassOwnPtr<CrossThreadResourceRequestData> data) { m_token = data->m_token; m_anchorText = data->m_anchorText; m_overrideContentType = data->m_overrideContentType; m_suggestedSaveName = data->m_suggestedSaveName; m_isXMLHTTPRequest = data->m_isXMLHTTPRequest; m_mustHandleInternally = data->m_mustHandleInternally; m_forceDownload = data->m_forceDownload; m_targetType = data->m_targetType; } void ResourceRequest::clearHTTPContentLength() { updateResourceRequest(); m_httpHeaderFields.remove("Content-Length"); if (url().protocolIsInHTTPFamily()) m_platformRequestUpdated = false; } void ResourceRequest::clearHTTPContentType() { updateResourceRequest(); m_httpHeaderFields.remove("Content-Type"); if (url().protocolIsInHTTPFamily()) m_platformRequestUpdated = false; } } // namespace WebCore
lizzie2008/rapid4you
rapid-api/rapid-api-domain/src/main/java/tech/lancelot/mapstruct/blog/CategoryMapper.java
<gh_stars>10-100 package tech.lancelot.mapstruct.blog; import org.mapstruct.Mapper; import org.mapstruct.ReportingPolicy; import tech.lancelot.domain.blog.Article; import tech.lancelot.domain.blog.Category; import tech.lancelot.dto.blog.ArticleDto; import tech.lancelot.dto.blog.CategoryDto; import tech.lancelot.mapstruct.sys.BaseMapper; import tech.lancelot.mapstruct.sys.MenuMapper; /** * @author lancelot */ @Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE) public interface CategoryMapper extends BaseMapper<CategoryDto, Category> { }
tyazid/RTSP-Java-UrlConnection
project/src/com/net/rtsp/content/text/parameters/ResponseContent.java
package com.net.rtsp.content.text.parameters; public class ResponseContent extends com.net.rtsp.content.ResponseContent { protected ResponseContent(byte[] content ) { super(content, com.net.rtsp.content.text.parameters.ContentHandler.CONTENT_TYPE); } }
gnilrets/amylase
app/models/gooddata_project.rb
class GooddataProject < ActiveRecord::Base nilify_blanks PID_REGEX = /[0-9a-z]{32}/ belongs_to :client validates_presence_of :name validates_uniqueness_of :name validates_format_of :project_uid, with: PID_REGEX, message: "Gooddata project ids are 32 characters long and consist of only numbers and lowercase letters" end
morewings/react-calendar-toolk
src/lib/features/modal/index.js
<reponame>morewings/react-calendar-toolk export {initialState} from './ModalReducer'; export {useModalContext} from './context'; export {default as useModalActions} from './actionCreators'; export {default as withModalProvider} from './withModalProvider';
JakePrim/Flutter-House
Engineering/modular/es-modules/04-import/module.js
<gh_stars>1-10 var name = 'foo'; var age = 100 export {name,age}; export default 'default export';
rpl/ember-inspector
app/controllers/record-item.js
import Ember from "ember"; var COLOR_MAP = { red: '#ff2717', blue: '#174fff', green: '#006400' }; export default Ember.ObjectController.extend({ needs: ['records'], modelTypeColumns: Ember.computed.alias('controllers.records.columns'), // TODO: Color record based on `color` property. style: function() { if (!Ember.isEmpty(this.get('color'))) { var color = COLOR_MAP[this.get('color')]; if (color) { return 'color:' + color + ';'; } } return ''; }.property('color'), columns: function() { var self = this; return this.get('modelTypeColumns').map(function(col) { return { name: col.name, value: self.get('columnValues.' + col.name) }; }); }.property('modelTypeColumns.@each', 'model.columnValues') });
t-lawan/berlin
src/components/forms/press-form.js
<filename>src/components/forms/press-form.js<gh_stars>0 import React from "react" import { connect } from "react-redux" import { PressFormError, PressFormWrapper, PressFormInput, } from "./press-form.styles" import { FormButton, FormLabel } from "../modal/modal.styles" import { getCurrentLanguageString, createPath } from "../../utility/helper" import validator from "validator" import { navigate } from 'gatsby'; import axios from 'axios' class PressForm extends React.Component { language constructor(props) { super(props) this.state = { email: "", name: "", media_affliation: "", hasSubmitted: false, hasTouched: false, hasErrors: false, errors: { name: "", email: "", media_affliation: "", }, } } handleSubmit = async event => { event.preventDefault(); this.sendPostRequest().then(() => { this.setState({ hasSubmitted: true, }) }) navigate(createPath(this.language, 'press-images')) } sendPostRequest = async () => { const url = "https://admin11.berlinbiennale.de/wp-json/contact-form-7/v1/contact-forms/444/feedback" let formData = new FormData(); formData.set('address-email', this.state.email); formData.set('full-name', this.state.name); formData.set('media-outlet', this.state.media_affliation); formData.set('honeypot-179', "") formData.set('_wpcf7', 444); formData.set('_wpcf7_version', "5.1.4"); formData.set('_wpcf7_locale', "en_US"); formData.set('_wpcf7_unit_tag', "wpcf7-f444-o1"); formData.set('_wpcf7_container_post', "0"); axios({ method: 'post', url: url, data: formData, headers: {'Content-Type': 'multipart/form-data' } }).then((response) => { console.log('Response', response) }).catch((e) => { console.log('Error', e) }) // await axios.post(url, data) } clearState = () => { this.setState({ email: "", name: "", media_affliation: "", }) } handleInputChange = event => { if (!this.state.hasTouched) { this.setState({ hasTouched: true }) } const target = event.target const value = target.type === "checkbox" ? target.checked : target.value const name = target.name let errors = this.state.errors switch (name) { case "name": // errors.name = // value.length < 3 // ? formText[this.language].errors.name // : "" break case "email": errors.email = !validator.isEmail(value) ? formText[this.language].errors.email : "" break case "media_affliation": // errors.media_affliation = // value.length < 3 // ? formText[this.language].errors.media_affliation // : "" break default: break } let errorList = Object.values(errors); errorList = errorList.filter((item) => { return item.length !== 0; }); const hasErrors = errorList.length > 0 ? true : false; this.setState( { hasErrors: hasErrors, errors, [name]: value, } ) } render() { this.language = getCurrentLanguageString(this.props.languages) return ( <PressFormWrapper> <form onSubmit={this.handleSubmit.bind(this)}> <FormLabel> <p> {formText[this.language].name}</p> <PressFormInput type="text" name="name" onChange={this.handleInputChange.bind(this)} /> </FormLabel> <FormLabel> <p> {formText[this.language].email}</p> <PressFormInput type="email" name="email" onChange={this.handleInputChange.bind(this)} required /> <PressFormError hidden={this.state.errors.email === ""}> {this.state.errors.email} </PressFormError> </FormLabel> <FormLabel> <p> {formText[this.language].media_affliation}</p> <PressFormInput type="text" name="media_affliation" onChange={this.handleInputChange.bind(this)} /> </FormLabel> <FormButton disabled={this.state.hasErrors || !this.state.hasTouched}> {formText[this.language].button} </FormButton> </form> </PressFormWrapper> ) } } const formText = { EN: { email: "E-mail", name: "First and last name", media_affliation: "Media affiliation", button: "Submit", thank_you: "Thank you for your subscription. We have sent you an e-mail with a confirmation link.", errors : { name: 'This field requires at least 3 characters', email: 'Valid e-mail address required', media_affliation: 'This field requires at least 3 characters' } }, DE: { email: "E-Mail", name: "Vor- und Nachname", media_affliation: "Medium", thank_you: "Thank you for your subscription. We have sent you an e-mail with a confirmation link.", button: "Senden", errors : { name: 'This field requires at least 3 characters', email: 'Gültige E-Mail-Adresse erforderlich', media_affliation: 'This field requires at least 3 characters' } }, } const mapStateToProps = state => { return { languages: state.languages, } } export default connect( mapStateToProps, null )(PressForm)
Alelak/Camelus
src/com/devsolutions/camelus/managers/ClientManager.java
<filename>src/com/devsolutions/camelus/managers/ClientManager.java package com.devsolutions.camelus.managers; import java.util.Collections; import java.util.List; import org.apache.ibatis.exceptions.PersistenceException; import org.apache.ibatis.session.SqlSession; import com.devsolutions.camelus.auditing.Audit; import com.devsolutions.camelus.auditing.AuditTypes; import com.devsolutions.camelus.auditing.AuditUtils; import com.devsolutions.camelus.entities.Client; import com.devsolutions.camelus.mappers.ClientMapper; import com.devsolutions.camelus.services.DBConnection; import com.devsolutions.camelus.services.Session; import com.devsolutions.camelus.utils.FXUtils; public class ClientManager { public static List<Client> getAll() { SqlSession session = DBConnection.getSqlSessionFactory().openSession(); List<Client> clients = Collections.emptyList(); try { clients = session.getMapper(ClientMapper.class).getAll(); } catch (PersistenceException e) { FXUtils.openDBErrorDialog(); } finally { session.close(); } return clients; } public static List<Client> getByVendorId(int associated_vendor) { SqlSession session = DBConnection.getSqlSessionFactory().openSession(); List<Client> clients = Collections.emptyList(); try { clients = session.getMapper(ClientMapper.class).getByVendorId( associated_vendor); } catch (PersistenceException e) { FXUtils.openDBErrorDialog(); } finally { session.close(); } return clients; } public static Client getById(long id) { SqlSession session = DBConnection.getSqlSessionFactory().openSession(); Client client = null; try { client = session.getMapper(ClientMapper.class).getById(id); } catch (PersistenceException e) { FXUtils.openDBErrorDialog(); } finally { session.close(); } return client; } public static Client getByEntrepriseAndClientName(String enterprise_name, String contact_name) { SqlSession session = DBConnection.getSqlSessionFactory().openSession(); Client client = null; try { client = session .getMapper(ClientMapper.class) .getByEntrepriseAndClientName(enterprise_name, contact_name); } catch (PersistenceException e) { FXUtils.openDBErrorDialog(); } finally { session.close(); } return client; } public static void update(Client client) { SqlSession session = DBConnection.getSqlSessionFactory().openSession(); session.getMapper(ClientMapper.class).update(client); try { session.commit(); } catch (PersistenceException e) { FXUtils.openDBErrorDialog(); } finally { session.close(); } if (Session.vendor != null) { AuditUtils.getAuditingService().setAudit( new Audit(Session.vendor.getLogin(), AuditTypes.UPDATE, "à modifier un client id : " + client.getId())); } else { AuditUtils.getAuditingService().setAudit( new Audit(Session.admin.getLogin(), AuditTypes.UPDATE, "à modifier un client id : " + client.getId())); } AuditUtils.getAuditingService().start(); } public static void add(Client client) { SqlSession session = DBConnection.getSqlSessionFactory().openSession(); session.getMapper(ClientMapper.class).add(client); try { session.commit(); } catch (PersistenceException e) { FXUtils.openDBErrorDialog(); } finally { session.close(); } if (Session.vendor != null) { AuditUtils.getAuditingService().setAudit( new Audit(Session.vendor.getLogin(), AuditTypes.INSERT, "à ajouter un client id : " + client.getId())); } else { AuditUtils.getAuditingService().setAudit( new Audit(Session.admin.getLogin(), AuditTypes.INSERT, "à ajouter un client id : " + client.getId())); } AuditUtils.getAuditingService().start(); } public static void delete(long id) { SqlSession session = DBConnection.getSqlSessionFactory().openSession(); session.getMapper(ClientMapper.class).delete(id); try { session.commit(); } catch (PersistenceException e) { FXUtils.openDBErrorDialog(); } finally { session.close(); } if (Session.vendor != null) { AuditUtils.getAuditingService().setAudit( new Audit(Session.vendor.getLogin(), AuditTypes.DELETE, "à supprimer un client id : " + id)); } else { AuditUtils.getAuditingService().setAudit( new Audit(Session.admin.getLogin(), AuditTypes.DELETE, "à supprimer un client id : " + id)); } AuditUtils.getAuditingService().start(); } }
kshedden/dstream
dstream/doc.go
// Package dstream provides facilities for manipulating streams of // typed, multivariate data. A Dstream is a data container that holds // a rectangular array of data in which the columns are variables and // the rows are cases or observations. The dstream framework // facilitates processing data of this type in a streaming manner, // with a focus on feeding the data into statistical modeling tools. // // The data held by a Dstream are retrieved as chunks of contiguous // rows. Within each chunk, the data are stored column-wise. A // Dstream visits its chunks in order. When processing a Dstream, // call Next to advance to the next chunk, then call Get or GetPos to // retrieve the data for one column. // // Most operations on Dstreams take the form of a transformation d = // f(d), where d is a Dstream. Many transformations are defined in // the package, and it is easy to add new transformations. // Transformations can be composed to produce complex transformations // from simple components. Examples of transformations are Mutate // (modify a column in-place) and DropCols (drop one or more columns // from the Dstream). package dstream
senti-iot/waterworks-backend
api/events/event.js
<reponame>senti-iot/waterworks-backend const express = require('express') const router = express.Router() const sentiEventService = require('../../lib/eventService') let eService = null router.all('/v3/events*', async (req, res, next) => { eService = new sentiEventService() console.log() next() }) router.get('/v3/events/get-user-uuid/:deviceUUID', async (req, res) => { let deviceUUID = req.params.deviceUUID if (eService && deviceUUID) { let resp = await eService.getUserUUID(deviceUUID) return res.status(200).json(resp) } else { return res.status(500).json({"Error": "eService or DeviceUUID is null"}) } }) module.exports = router
lechium/iPhoneOS_12.1.1_Headers
System/Library/PrivateFrameworks/HomeUI.framework/HUPersonalRequestsEditorTableViewController.h
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:49:39 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/HomeUI.framework/HomeUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <HomeUI/HUItemTableViewController.h> #import <libobjc.A.dylib/HUPersonalRequestsDevicesModuleControllerDelegate.h> @class HUPersonalRequestsEditorItemManager, HUPersonalRequestsDevicesModuleController, NSString; @interface HUPersonalRequestsEditorTableViewController : HUItemTableViewController <HUPersonalRequestsDevicesModuleControllerDelegate> { HUPersonalRequestsEditorItemManager* _prEditorItemManager; HUPersonalRequestsDevicesModuleController* _prDevicesModuleController; } @property (nonatomic,retain) HUPersonalRequestsEditorItemManager * prEditorItemManager; //@synthesize prEditorItemManager=_prEditorItemManager - In the implementation block @property (nonatomic,readonly) HUPersonalRequestsDevicesModuleController * prDevicesModuleController; //@synthesize prDevicesModuleController=_prDevicesModuleController - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; -(void)updateCell:(id)arg1 forItem:(id)arg2 indexPath:(id)arg3 animated:(BOOL)arg4 ; -(Class)cellClassForItem:(id)arg1 indexPath:(id)arg2 ; -(id)initWithUserItem:(id)arg1 sourceMediaProfileContainer:(id)arg2 ; -(HUPersonalRequestsDevicesModuleController *)prDevicesModuleController; -(HUPersonalRequestsEditorItemManager *)prEditorItemManager; -(void)setupCell:(id)arg1 forItem:(id)arg2 indexPath:(id)arg3 ; -(void)devicesModuleController:(id)arg1 presentViewController:(id)arg2 ; -(id)initWithUserItem:(id)arg1 ; -(BOOL)automaticallyUpdatesViewControllerTitle; -(id)itemModuleControllers; -(void)setPrEditorItemManager:(HUPersonalRequestsEditorItemManager *)arg1 ; -(void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2 ; @end
ValKhv/BGX
MOBILAPP/BGX-App/BGX/ios/Pods/Headers/Private/GoogleUtilities/GULNetworkMessageCode.h
<filename>MOBILAPP/BGX-App/BGX/ios/Pods/Headers/Private/GoogleUtilities/GULNetworkMessageCode.h link ../../../GoogleUtilities/GoogleUtilities/Network/Private/GULNetworkMessageCode.h
alphagov/vitruvius
vitruvius.markdown/src/test/java/uk/gov/prototype/vitruvius/parser/domain/RepositoryInformationBuilderTest.java
<reponame>alphagov/vitruvius package uk.gov.prototype.vitruvius.parser.domain; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.fest.assertions.api.Assertions.assertThat; public class RepositoryInformationBuilderTest { private static final String TEST_LINK = "link.link.com"; private static final String TEST_COLLABORATING_PROJECT_NAME = "Test Service"; private static final String TEST_API_URI = "https://api.github.com/repos/owner/service"; private static final String TEST_NON_API_URI = "https://github.com/owner/service"; private static final String TEST_META_STATUS = "Draft"; private static final String TEST_META_DESCRIPTION = "Very brief description of this service."; private static final String TEST_META_AUTHOR = "<NAME> <<EMAIL>>"; private static final String TEST_META_LAST_UPDATED = "22/08/2014"; private static final String TEST_META_VERSION = "0.1"; public static final String TEST_META_STRING = "{\"status\":\"" + TEST_META_STATUS + "\"," + "\"description\":\"" + TEST_META_DESCRIPTION + "\"," + "\"author\":\"" + TEST_META_AUTHOR + "\"," + "\"lastUpdated\":\"" + TEST_META_LAST_UPDATED + "\"," + "\"version\":\"" + TEST_META_VERSION + "\"," + "\"department\":\"" + "department" + "\"," + "\"tags\":" + "[\"test\",\"test\"]" + "," + "\"type\":\"" + "Service" + "\"" + "}"; private static final String TEST_COLLABORATING_PROJECT_DESCRIPTION = "Used for looking people up"; private static final String TEST_COLLABORATING_PROJECT_LINK = "link for the web"; private static final String TEST_COLLABORATING_PROJECT_STRING = "{\"name\":\"" + TEST_COLLABORATING_PROJECT_NAME + "\"," + "\"description\":\"" + TEST_COLLABORATING_PROJECT_DESCRIPTION + "\"," + "\"link\":\"" + TEST_COLLABORATING_PROJECT_LINK + "\"" + "}"; private RepositoryInformationBuilder repositoryInformationBuilder; @Before public void setup() { repositoryInformationBuilder = new RepositoryInformationBuilder(); repositoryInformationBuilder.repoUri(TEST_API_URI); } @Test public void testTransformAndAddMeta() throws Exception { repositoryInformationBuilder.parseAndAddMeta(TEST_META_STRING); RepositoryInformation repositoryInformation = repositoryInformationBuilder.build(); assertThat(repositoryInformation).isNotNull(); Meta meta = repositoryInformation.getMeta(); assertThat(meta).isNotNull(); assertThat(meta.getStatus()).isEqualTo(TEST_META_STATUS); assertThat(meta.getDescription()).isEqualTo(TEST_META_DESCRIPTION); assertThat(meta.getAuthor()).isEqualTo(TEST_META_AUTHOR); assertThat(meta.getLastUpdated()).isEqualTo(TEST_META_LAST_UPDATED); assertThat(meta.getVersion()).isEqualTo(TEST_META_VERSION); assertThat(meta.getDepartment()).isEqualTo("department"); List<String> tags = new ArrayList<>(); tags.add("test"); tags.add("test"); assertThat(meta.getTags()).isEqualTo(tags); assertThat(meta.getType()).isEqualTo("Service"); } @Test public void testParseAndAddService() throws Exception { repositoryInformationBuilder.parseAndAddService(TEST_COLLABORATING_PROJECT_STRING); RepositoryInformation repositoryInformation = repositoryInformationBuilder.build(); assertThat(repositoryInformation).isNotNull(); List<CollaboratingProject> services = repositoryInformation.getServices(); assertThat(services).isNotNull(); assertThat(services.size()).isEqualTo(1); CollaboratingProject collaboratingProject = services.get(0); assertThat(collaboratingProject.getName()).isEqualTo(TEST_COLLABORATING_PROJECT_NAME); assertThat(collaboratingProject.getDescription()).isEqualTo(TEST_COLLABORATING_PROJECT_DESCRIPTION); assertThat(collaboratingProject.getLink()).isEqualTo(TEST_COLLABORATING_PROJECT_LINK); } @Test public void testParseAndAddTwoServices() throws Exception { repositoryInformationBuilder.parseAndAddService(TEST_COLLABORATING_PROJECT_STRING); repositoryInformationBuilder.parseAndAddService(TEST_COLLABORATING_PROJECT_STRING); RepositoryInformation repositoryInformation = repositoryInformationBuilder.build(); assertThat(repositoryInformation).isNotNull(); List<CollaboratingProject> services = repositoryInformation.getServices(); assertThat(services).isNotNull(); assertThat(services.size()).isEqualTo(2); assertThat(repositoryInformation.getComponents()).isEmpty(); } @Test public void testParseAndAddTwoComponents() throws Exception { repositoryInformationBuilder.parseAndAddComponent(TEST_COLLABORATING_PROJECT_STRING); repositoryInformationBuilder.parseAndAddComponent(TEST_COLLABORATING_PROJECT_STRING); RepositoryInformation repositoryInformation = repositoryInformationBuilder.build(); assertThat(repositoryInformation).isNotNull(); List<CollaboratingProject> services = repositoryInformation.getServices(); assertThat(services).isEmpty(); List<CollaboratingProject> components = repositoryInformation.getComponents(); assertThat(components).isNotEmpty(); assertThat(components.size()).isEqualTo(2); } @Test public void testRepoUri() throws Exception { RepositoryInformation repositoryInformation = repositoryInformationBuilder.build(); assertThat(repositoryInformation.getRepoUri()).isEqualTo(TEST_API_URI); } @Test public void testRepoUriForNonGitHubUri() throws Exception { repositoryInformationBuilder.repoUri(TEST_NON_API_URI); RepositoryInformation repositoryInformation = repositoryInformationBuilder.build(); assertThat(repositoryInformation.getRepoUri()).isEqualTo(TEST_API_URI); } @Test public void testServiceName() throws Exception { repositoryInformationBuilder.serviceName(TEST_COLLABORATING_PROJECT_NAME); RepositoryInformation repositoryInformation = repositoryInformationBuilder.build(); assertThat(repositoryInformation.getServiceName()).isEqualTo(TEST_COLLABORATING_PROJECT_NAME); } @Test public void testLink() throws Exception { repositoryInformationBuilder.link(TEST_LINK); RepositoryInformation repositoryInformation = repositoryInformationBuilder.build(); assertThat(repositoryInformation.getLink()).isEqualTo(TEST_LINK); } }
jungomi/iterfn
test/index.test.js
import test from 'ava'; import iter from '../src'; test('iter returns a correct iterator for iterables and generators', t => { function* gen() { yield 1; yield 5; } const array = [1, 5]; const genIter = iter(gen); const arrayIter = iter(array); t.is(typeof genIter.next, 'function'); t.is(genIter.next().value, 1); t.is(genIter.next().value, 5); t.true(genIter.next().done); t.is(typeof arrayIter.next, 'function'); t.is(arrayIter.next().value, 1); t.is(arrayIter.next().value, 5); t.true(arrayIter.next().done); }); test('iter makes an iterator also iterable', t => { const iterObj = { index: 0, next() { if (this.index >= 3) { return { done: true }; } this.index += 1; return { value: this.index, done: false }; } }; const iterator = iter(iterObj); t.is(typeof iterator[Symbol.iterator], 'function'); t.is(iterator.next().value, 1); t.is(iterator.next().value, 2); t.is(iterator.next().value, 3); t.true(iterator.next().done); }); test('iter throws when not passing an iterator', t => { const obj = {}; const num = 2; const func = () => {}; t.throws(() => iter(obj), TypeError); t.throws(() => iter(num), TypeError); t.throws(() => iter(func), TypeError); }); test('iterators can be chained', t => { const chainedIter = iter([1, 2]) .map(x => x * 3) .chain([9, 10]) .filter(x => x % 2 === 0); t.is(typeof chainedIter.next, 'function'); t.is(chainedIter.next().value, 6); t.is(chainedIter.next().value, 10); t.true(chainedIter.next().done); }); test('iterators end when calling a consumer', t => { const result = iter([1, 2]) .map(x => x * 3) .chain([9, 10]) .filter(x => x % 2 === 0) .collect(); t.deepEqual(result, [6, 10]); });
citrix-openstack-build/trove
trove/instance/tasks.py
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Common instance status code used across Trove API. """ class InstanceTask(object): """ Stores the different kind of tasks being performed by an instance. """ #TODO(tim.simpson): Figure out someway to migrate this to the TaskManager # once that revs up. _lookup = {} def __init__(self, code, action, db_text, is_error=False): self._code = int(code) self._action = action self._db_text = db_text self._is_error = is_error InstanceTask._lookup[self._code] = self @property def action(self): return self._action @property def code(self): return self._code @property def db_text(self): return self._db_text @property def is_error(self): return self._is_error def __eq__(self, other): if not isinstance(other, InstanceTask): return False return self._db_text == other._db_text @classmethod def from_code(cls, code): if code not in cls._lookup: return None return cls._lookup[code] def __str__(self): return "(%d %s %s)" % (self._code, self._action, self._db_text) class InstanceTasks(object): NONE = InstanceTask(0x01, 'NONE', 'No tasks for the instance.') DELETING = InstanceTask(0x02, 'DELETING', 'Deleting the instance.') REBOOTING = InstanceTask(0x03, 'REBOOTING', 'Rebooting the instance.') RESIZING = InstanceTask(0x04, 'RESIZING', 'Resizing the instance.') BUILDING = InstanceTask(0x05, 'BUILDING', 'The instance is building.') MIGRATING = InstanceTask(0x06, 'MIGRATING', 'Migrating the instance.') BUILDING_ERROR_DNS = InstanceTask(0x50, 'BUILDING', 'Build error: DNS.', is_error=True) BUILDING_ERROR_SERVER = InstanceTask(0x51, 'BUILDING', 'Build error: Server.', is_error=True) BUILDING_ERROR_VOLUME = InstanceTask(0x52, 'BUILDING', 'Build error: Volume.', is_error=True) # Dissuade further additions at run-time. InstanceTask.__init__ = None
JonoMacC/fast-tracks
src/Components/Playlist/TrackItem.js
<filename>src/Components/Playlist/TrackItem.js<gh_stars>0 import { useContext } from "react"; import { motion } from "framer-motion"; import { AppDispatch } from "../../contexts/AppContext"; import { Player } from "../Player/Player"; import { Icon } from "../Icons"; import "./TrackItem.css"; export const TrackItem = ({ track, isRemoval }) => { const dispatch = useContext(AppDispatch); const add = () => { dispatch({ type: "ADD_TRACK", payload: track }); }; const remove = () => { dispatch({ type: "REMOVE_PLAYLIST_TRACK", payload: track }); }; // console.log("TrackItem render", Date.now()); return ( <motion.li layout transition={{ duration: 0.07, layoutY: { duration: 0.07 } }} key={track.id} className="TrackItem" initial={{ opacity: 0, x: -375 }} animate={{ opacity: 1, x: 0, transition: { duration: 0.07, ease: "easeOut" }, }} exit={{ opacity: 0, x: -375, transition: { duration: 0.1, ease: "easeIn" }, }} > <div className="TrackPlayerContainer"> <Player track={track} miniPlayer={true} /> </div> <div className="TrackInformation"> <h2>{track.name}</h2> <p> {track.artist} | {track.album} </p> </div> <button className="TapItem" onClick={isRemoval ? remove : add} aria-label={isRemoval ? "Remove Track" : "Add Track"} > <Icon name={isRemoval ? "remove" : "add"} color="var(--text-secondary)" size="24px" /> </button> </motion.li> ); };
Ron423c/chromium
components/sync/engine/sync_engine.h
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SYNC_ENGINE_SYNC_ENGINE_H_ #define COMPONENTS_SYNC_ENGINE_SYNC_ENGINE_H_ #include <map> #include <memory> #include <string> #include <vector> #include "base/callback.h" #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "components/signin/public/identity_manager/account_info.h" #include "components/sync/base/extensions_activity.h" #include "components/sync/base/model_type.h" #include "components/sync/base/weak_handle.h" #include "components/sync/engine/configure_reason.h" #include "components/sync/engine/cycle/sync_cycle_snapshot.h" #include "components/sync/engine/model_type_configurer.h" #include "components/sync/engine/shutdown_reason.h" #include "components/sync/engine/sync_credentials.h" #include "components/sync/engine/sync_encryption_handler.h" #include "components/sync/engine/sync_manager_factory.h" #include "google_apis/gaia/core_account_id.h" #include "url/gurl.h" namespace syncer { class EngineComponentsFactory; class HttpPostProviderFactory; class JsEventHandler; class SyncEngineHost; struct SyncStatus; // The interface into the sync engine, which is the part of sync that performs // communication between model types and the sync server. In prod the engine // will always live on the sync thread and the object implementing this // interface will handle crossing threads if necessary. class SyncEngine : public ModelTypeConfigurer { public: using AllNodesCallback = base::OnceCallback<void(ModelType, std::unique_ptr<base::ListValue>)>; using HttpPostProviderFactoryGetter = base::OnceCallback<std::unique_ptr<HttpPostProviderFactory>()>; // Utility struct for holding initialization options. struct InitParams { InitParams(); InitParams(InitParams&& other); ~InitParams(); SyncEngineHost* host = nullptr; std::unique_ptr<SyncEncryptionHandler::Observer> encryption_observer_proxy; scoped_refptr<ExtensionsActivity> extensions_activity; WeakHandle<JsEventHandler> event_handler; GURL service_url; SyncEngine::HttpPostProviderFactoryGetter http_factory_getter; CoreAccountInfo authenticated_account_info; std::string invalidator_client_id; std::unique_ptr<SyncManagerFactory> sync_manager_factory; bool enable_local_sync_backend = false; base::FilePath local_sync_backend_folder; std::unique_ptr<EngineComponentsFactory> engine_components_factory; private: DISALLOW_COPY_AND_ASSIGN(InitParams); }; SyncEngine(); ~SyncEngine() override; // Kicks off asynchronous initialization. Optionally deletes sync data during // init in order to make sure we're starting fresh. // // |saved_nigori_state| is optional nigori state to restore from a previous // engine instance. May be null. virtual void Initialize(InitParams params) = 0; // Returns whether the asynchronous initialization process has finished. virtual bool IsInitialized() const = 0; // Inform the engine to trigger a sync cycle for |types|. virtual void TriggerRefresh(const ModelTypeSet& types) = 0; // Updates the engine's SyncCredentials. The credentials must be fully // specified (account ID, email, and sync token). To invalidate the // credentials, use InvalidateCredentials() instead. virtual void UpdateCredentials(const SyncCredentials& credentials) = 0; // Invalidates the SyncCredentials. virtual void InvalidateCredentials() = 0; // Transport metadata getters. virtual std::string GetCacheGuid() const = 0; virtual std::string GetBirthday() const = 0; virtual base::Time GetLastSyncedTimeForDebugging() const = 0; // Switches sync engine into configuration mode. In this mode only initial // data for newly enabled types is downloaded from server. No local changes // are committed to server. virtual void StartConfiguration() = 0; // This starts the sync engine running a Syncer object to communicate with // sync servers. Until this is called, no changes will leave or enter this // browser from the cloud / sync servers. virtual void StartSyncingWithServer() = 0; // Asynchronously set a new passphrase for encryption. Note that it is an // error to call SetEncryptionPassphrase under the following circumstances: // - An explicit passphrase has already been set // - We have pending keys. virtual void SetEncryptionPassphrase(const std::string& passphrase) = 0; // Use the provided passphrase to asynchronously attempt decryption. If new // encrypted keys arrive during the asynchronous call, OnPassphraseRequired // may be triggered at a later time. It is an error to call this when there // are no pending keys. virtual void SetDecryptionPassphrase(const std::string& passphrase) = 0; // Legacy bootstrap tokens stored in preferences. // TODO(crbug.com/1010397): Delete this API together with the preferences. virtual void SetEncryptionBootstrapToken(const std::string& token) = 0; virtual void SetKeystoreEncryptionBootstrapToken( const std::string& token) = 0; // Analogous to SetDecryptionPassphrase but specifically for // TRUSTED_VAULT_PASSPHRASE: it provides new decryption keys that could // allow decrypting pending Nigori keys. Notifies observers of the result of // the operation via OnTrustedVaultKeyAccepted if the provided keys // successfully decrypted pending keys. |done_cb| is invoked at the very end. virtual void AddTrustedVaultDecryptionKeys( const std::vector<std::vector<uint8_t>>& keys, base::OnceClosure done_cb) = 0; // Kick off shutdown procedure. Attempts to cut short any long-lived or // blocking sync thread tasks so that the shutdown on sync thread task that // we're about to post won't have to wait very long. virtual void StopSyncingForShutdown() = 0; // See the implementation and Core::DoShutdown for details. // Must be called *after* StopSyncingForShutdown. virtual void Shutdown(ShutdownReason reason) = 0; // Returns current detailed status information. virtual const SyncStatus& GetDetailedStatus() const = 0; // Determines if the underlying sync engine has made any local changes to // items that have not yet been synced with the server. // ONLY CALL THIS IF OnInitializationComplete was called! virtual void HasUnsyncedItemsForTest( base::OnceCallback<void(bool)> cb) const = 0; // Requests that the backend forward to the fronent any protocol events in // its buffer and begin forwarding automatically from now on. Repeated calls // to this function may result in the same events being emitted several // times. virtual void RequestBufferedProtocolEventsAndEnableForwarding() = 0; // Disables protocol event forwarding. virtual void DisableProtocolEventForwarding() = 0; // Notify the syncer that the cookie jar has changed. // See SyncManager::OnCookieJarChanged. virtual void OnCookieJarChanged(bool account_mismatch, base::OnceClosure callback) = 0; // Enables/Disables invalidations for session sync related datatypes. virtual void SetInvalidationsForSessionsEnabled(bool enabled) = 0; // Returns a ListValue representing Nigori node. virtual void GetNigoriNodeForDebugging(AllNodesCallback callback) = 0; private: DISALLOW_COPY_AND_ASSIGN(SyncEngine); }; } // namespace syncer #endif // COMPONENTS_SYNC_ENGINE_SYNC_ENGINE_H_
vanditbhatt/learn
src/templates/Challenges/project/Tool-Panel.js
<reponame>vanditbhatt/learn<filename>src/templates/Challenges/project/Tool-Panel.js import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { Button } from 'react-bootstrap'; import { openModal } from '../redux'; const mapStateToProps = () => ({}); const mapDispatchToProps = dispatch => bindActionCreators( { openHelpModal: () => openModal('help') }, dispatch ); const propTypes = { guideUrl: PropTypes.string, openHelpModal: PropTypes.func.isRequired }; export class ToolPanel extends PureComponent { render() { const { guideUrl, openHelpModal } = this.props; return ( <div className='tool-panel-group project-tool-panel'> {guideUrl && ( <Button block={true} bsStyle='primary' className='btn-primary-invert' href={guideUrl} target='_blank' > Get a hint </Button> )} <Button block={true} bsStyle='primary' className='btn-primary-invert' onClick={openHelpModal} > Ask for help </Button> </div> ); } } ToolPanel.displayName = 'ProjectToolPanel'; ToolPanel.propTypes = propTypes; export default connect(mapStateToProps, mapDispatchToProps)(ToolPanel); /** * * <Fragment> <ProjectForm isFrontEnd={isFrontEnd} openModal={openCompletionModal} /> <ButtonSpacer /> {guideUrl && ( <Fragment> <Button block={true} bsStyle='primary' className='btn-primary-ghost btn-big' href={guideUrl} target='_blank' > Get a hint </Button> <ButtonSpacer /> </Fragment> )} <Button block={true} bsStyle='primary' className='btn-primary-ghost btn-big' onClick={openHelpModal} > Ask for help on the forum </Button> <ButtonSpacer /> </Fragment> */
pustovitDmytro/semantic-release-telegram
src/success.js
import { VERIFICATION_MISSED } from './Error'; import Telegram, { Telegraph } from './telegram'; import { getVariables } from './utils'; export default async function success(pluginConfig, { logger, nextRelease, options, branch }) { if (!this.verified) throw new VERIFICATION_MISSED('success'); const { chats, botID, botToken, templates, assets } = this.verified; const telegram = new Telegram(botID, botToken, chats); const variables = getVariables({ verified: this.verified, nextRelease, options, branch }); const telegraphConfig = this.verified['telegra.ph']; if (telegraphConfig) { const config = telegraphConfig; const telegraph = new Telegraph(config.token); const telegraphVariables = await telegraph.send(config.title, config.content, variables); Object.assign(variables, telegraphVariables); } await telegram.send(templates.success, variables, { files: assets, telegraph: telegraphConfig }); logger.log('Notifications have been sent successfully'); }
primus305/nst-server
src/main/java/nst/projekat/service/impl/SpeakerServiceImpl.java
package nst.projekat.service.impl; import nst.projekat.domain.*; import nst.projekat.dto.SpeakerDTO; import nst.projekat.mapper.SpeakerMapper; import nst.projekat.mapper.UserMapper; import nst.projekat.repository.AgendaSessionRepository; import nst.projekat.repository.SpeakerRepository; import nst.projekat.service.SpeakerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.Set; @Service public class SpeakerServiceImpl implements SpeakerService { @Autowired private SpeakerRepository speakerRepository; @Autowired private AgendaSessionRepository agendaSessionRepository; @Autowired private PasswordEncoder passwordEncoder; @Override public List<SpeakerDTO> findAll() { return SpeakerMapper.INSTANCE.toSpeakerDTOs(speakerRepository.findAll()); } @Override public SpeakerDTO save(SpeakerDTO speakerDTO) { Speaker speaker = SpeakerMapper.INSTANCE.speakerDTOToSpeaker(speakerDTO); speaker.setPassword(passwordEncoder.encode(speakerDTO.getPassword())); return SpeakerMapper.INSTANCE.speakerToSpeakerDTO(speakerRepository.save(speaker)); } @Override public List<SpeakerDTO> findAllNotOnSession(Long sessionID, Long agendaID) { List<Speaker> speakers = speakerRepository.findAll(); Optional<AgendaSession> session = agendaSessionRepository.findById(new AgendaSessionPK(sessionID, agendaID)); if (session.isPresent()) { session.get().getSpeakers().forEach(speaker -> { speakers.removeIf(speaker1 -> speaker1.getSpeakerID().equals(speaker.getSpeakerID())); }); } return SpeakerMapper.INSTANCE.toSpeakerDTOs(speakers); } }
LuisJIVillalva/lippia-core
core/src/main/java/com/crowdar/bdd/cukes/TestNGParallelRunner.java
<gh_stars>1-10 package com.crowdar.bdd.cukes; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import cucumber.api.testng.CucumberFeatureWrapper; import cucumber.api.testng.PickleEventWrapper; import cucumber.api.testng.TestNGCucumberRunner; public class TestNGParallelRunner { private TestNGCucumberRunner testNGCucumberRunner; public TestNGParallelRunner() { } @BeforeClass( alwaysRun = true ) public void setUpClass() throws Exception { this.testNGCucumberRunner = new TestNGCucumberRunner(this.getClass()); } @Test( groups = {"cucumber"}, description = "Runs Cucumber Scenarios", dataProvider = "scenarios" ) public void runScenario(PickleEventWrapper pickleWrapper, CucumberFeatureWrapper featureWrapper) throws Throwable { this.testNGCucumberRunner.runScenario(pickleWrapper.getPickleEvent()); } @DataProvider(parallel = true) public Object[][] scenarios() { return this.testNGCucumberRunner == null ? new Object[0][0] : this.testNGCucumberRunner.provideScenarios(); } @AfterClass( alwaysRun = true ) public void tearDownClass() throws Exception { if (this.testNGCucumberRunner != null) { this.testNGCucumberRunner.finish(); } } }
hejfelix/slinky-wrappers
semantic-ui/src/main/scala/com/lambdaminute/slinkywrappers/semanticui/GridRow.scala
package com.lambdaminute.slinkywrappers.semanticui import slinky.core.ExternalComponent import slinky.core.annotations.react import scala.scalajs.js import scala.scalajs.js.UndefOr @react object GridRow extends ExternalComponent { case class Props( as:UndefOr[String] = js.undefined, centered:UndefOr[Boolean] = js.undefined, className:UndefOr[String] = js.undefined, color:UndefOr[Color] = js.undefined, columns:UndefOr[Number] = js.undefined, divided:UndefOr[Boolean] = js.undefined, only:UndefOr[String] = js.undefined, reversed:UndefOr[String] = js.undefined, stretched:UndefOr[Boolean] = js.undefined ) override val component = SemanticUiReact.Grid.Row }
wh00sh/Tanda-DAPP
node_modules/mdi-material-ui/AutoFix.js
<gh_stars>0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _createIcon = _interopRequireDefault(require("./util/createIcon")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _default = (0, _createIcon["default"])('M7.5,5.6L5,7L6.4,4.5L5,2L7.5,3.4L10,2L8.6,4.5L10,7L7.5,5.6M19.5,15.4L22,14L20.6,16.5L22,19L19.5,17.6L17,19L18.4,16.5L17,14L19.5,15.4M22,2L20.6,4.5L22,7L19.5,5.6L17,7L18.4,4.5L17,2L19.5,3.4L22,2M13.34,12.78L15.78,10.34L13.66,8.22L11.22,10.66L13.34,12.78M14.37,7.29L16.71,9.63C17.1,10 17.1,10.65 16.71,11.04L5.04,22.71C4.65,23.1 4,23.1 3.63,22.71L1.29,20.37C0.9,20 0.9,19.35 1.29,18.96L12.96,7.29C13.35,6.9 14,6.9 14.37,7.29Z'); exports["default"] = _default;
byteshiva/es6-tuts
functionalprogramming/day26/funcday26/index.js
<filename>functionalprogramming/day26/funcday26/index.js<gh_stars>1-10 const R = require('ramda'); R.call(R.add, 1, 2); //=> 3 var indentN = R.pipe(R.repeat(' '), R.join(''), R.replace(/^(?!$)/gm)); var format = R.converge(R.call, [ R.pipe(R.prop('indent'), indentN), R.prop('value') ]); const formatFn = format({indent: 2, value: 'foo\nbar\nbaz\n'}); //=> ' foo\n bar\n baz\n' console.log(formatFn);
wuyueandrew/GraphScope
research/query_service/ir/compiler/src/main/java/com/alibaba/graphscope/gremlin/transform/alias/AliasArg.java
/* * Copyright 2020 Alibaba Group Holding Limited. * * 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.alibaba.graphscope.gremlin.transform.alias; public class AliasArg { public static String GROUP_KEYS = "~keys"; public static String GROUP_VALUES = "~values"; public static String DEFAULT = "~alias"; // the prefix is composed of the type and the tag // there are 4 kinds of alias prefix, {keys, values, default, tag} private String tag; private AliasPrefixType type; // stepIdx_subTraversalIdx is as suffix // stepIdx is used to differentiate multiple select(..) in a gremlin query // subTraversalIdx is used to differentiate multiple apply from a same operator private int stepIdx; private int subTraversalIdx; private AliasArg() { this.tag = ""; this.type = AliasPrefixType.DEFAULT; this.stepIdx = 0; this.subTraversalIdx = 0; } public AliasArg(AliasPrefixType type) { super(); this.type = type; } public AliasArg(AliasPrefixType type, int stepIdx) { this(type); this.stepIdx = stepIdx; } public AliasArg(AliasPrefixType type, int stepIdx, int subTraversalIdx) { this(type, stepIdx); this.subTraversalIdx = subTraversalIdx; } public AliasArg(AliasPrefixType type, String tag) { super(); if (tag.isEmpty()) { this.type = AliasPrefixType.DEFAULT; } else { this.tag = tag; this.type = type; } } public AliasArg(AliasPrefixType type, String tag, int stepIdx) { this(type, tag); this.stepIdx = stepIdx; } public AliasArg(AliasPrefixType type, String tag, int stepIdx, int subTraversalIdx) { this(type, tag, stepIdx); this.subTraversalIdx = subTraversalIdx; } public String getPrefix() { switch (type) { case PROJECT_TAG: return this.tag; case GROUP_KEYS: return GROUP_KEYS; case GROUP_VALUES: return GROUP_VALUES; case DEFAULT: default: return DEFAULT; } } public int getStepIdx() { return stepIdx; } public int getSubTraversalIdx() { return subTraversalIdx; } }
matsubara0507/semantic
test/fixtures/java/corpus/Char.B.java
class Point { Char dinosaur() { Char B = 'B'; if (x) B; } }
mikaelho/youey
youey/util/color.py
<filename>youey/util/color.py<gh_stars>1-10 #coding: utf-8 from youey.util.webcolors import * from youey.util.prop import * class Color(list): def __init__(self, *args, alpha=None): value = False if len(args) == 0: value = [0, 0, 0, 1] elif len(args) == 1: arg = args[0] if type(arg) is Color: value = arg.copy() elif type(arg) in (int, float): value = (arg,)*3 elif type(arg) in (tuple, list): value = list(args[0]) elif type(arg) is str: if arg == 'transparent': value = [0, 0, 0, 0] elif arg.startswith('rgb'): segments = arg[:-1].split('(') value = [float(c) for c in segments[1].split(',')] else: rgb = html5_parse_legacy_color(arg) value = [rgb.red, rgb.green, rgb.blue] elif len(args) in [3,4]: value = args if len(value) == 3: value = list(value) value.append(alpha if alpha is not None else 1.0) elif alpha is not None: value[3] = alpha if not all((component <= 1.0) for component in value): for i in range(3): value[i] /= 255.0 super().__init__(value) @prop def r(self, *args, base_prop): if args: self[0] = args[0] else: return self[0] @prop def g(self, *args, base_prop): if args: self[1] = args[0] else: return self[1] @prop def b(self, *args, base_prop): if args: self[2] = args[0] else: return self[2] @prop def a(self, *args, base_prop): if args: self[3] = args[0] else: return self[3] red = r green = g blue = b alpha = a @prop def ints(self, *args, base_prop): if args: self.css = args[0] else: return (int(self.r*255), int(self.g*255), int(self.b*255), self.a) @prop def css(self, *args, base_prop): if args: c = Color(args[0]) self.r = c.r self.g = c.g self.b = c.b self.a = c.a else: return f'rgba({",".join([str(segment) for segment in self.ints])})' @prop def name(self, *args, base_prop): if args: self.css = args[0] else: try: value = rgb_to_name(tuple(self.ints[:3])) except ValueError: value = None return value @prop def hex(self, *args, base_prop): if args: self.css = args[0] else: try: value = rgb_to_hex(tuple(self.ints[:3])) except ValueError: value = None return value @prop def transparent(self, *args, base_prop): if args: self.alpha = 0.0 if args[0] else 1.0 else: return self.alpha == 0 def contrast_color(self, low_brightness_color='black', high_brightness_color='white'): r,g,b,a = self return Color(low_brightness_color) if ((r * 255 * 299 + g * 255 * 587 + b * 255 * 114) / 1000) > 150 else Color(high_brightness_color) def to_css_color(color, alpha=None): if type(color) is Color: return color.css if type(color) is str: return color if type(color) == tuple and len(color) >= 3: if alpha is None: alpha = color[3] if len(color) == 4 else 1.0 if all((component <= 1.0) for component in color): color_rgb = [int(component*255) for component in color[:3]] color_rgb.append(color[3] if len(color) == 4 else 1.0) color = tuple(color_rgb) return f'rgba{str(color)}' def from_css_color(css_color_str): segments = css_color_str[:-1].split('(') components = [float(c) for c in segments[1].split(',')] if len(components) == 3: components.append(1.0) return components
quasi-robotics/easy_manipulation_deployment
easy_manipulation_deployment/workcell_builder/workcell_builder/include/yaml_parser/collision_parser.h
// Copyright 2020 Advanced Remanufacturing and Technology Centre // Copyright 2020 ROS-Industrial Consortium Asia Pacific Team // // 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. #ifndef YAML_PARSER__COLLISION_PARSER_H_ #define YAML_PARSER__COLLISION_PARSER_H_ #include "yaml-cpp/yaml.h" #include "attributes/collision.h" #include "yaml_parser/geometry_parser.h" #include "yaml_parser/material_parser.h" #include "yaml_parser/origin_parser.h" struct CollisionParser { static void generate_collision(YAML::Emitter *** out, Collision collision) { // ***out<<YAML::BeginMap; *** out << YAML::Key << "collision"; *** out << YAML::Value; *** out << YAML::BeginMap; *** out << YAML::Key << "name"; *** out << YAML::Value << collision.name; GeometryParser::generate_geometry(&out, collision.geometry); if (collision.origin.is_origin) { OriginParser::generate_origin(&out, collision.origin); } *** out << YAML::EndMap; } }; #endif // YAML_PARSER__COLLISION_PARSER_H_