code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/** * * ThingBench - Things and Devices Simulator * * http://github.com/frapu78/thingbench * * @author Frank Puhlmann * */ package thingbench; import java.util.HashMap; import net.frapu.code.visualization.ProcessNode; /** * This class provides an operation on a thing. * * @author fpu */ public abstract class ThingOperation { private ProcessNode thingNode; private String operationName; public ThingOperation(ProcessNode thingNode, String operationName) { this.thingNode = thingNode; this.operationName = operationName; } public ProcessNode getThingNode() { return thingNode; } public String getOperationName() { return operationName; } /** * This class executes the Operation. Each operation has a set of properties * of the type <String, String> as input and output. What the operation * does with it remains to the operation. * @param properties * @return * @throws thingbench.ThingExecutionException */ public abstract HashMap<String, String> execute(HashMap<String, String> properties) throws ThingExecutionException; }
frapu78/thingbench
src/thingbench/ThingOperation.java
Java
apache-2.0
1,167
// Code generated by msgraph.go/gen DO NOT EDIT. package msgraph import "context" // type WorkbookFunctionsTanRequestBuilder struct{ BaseRequestBuilder } // Tan action undocumented func (b *WorkbookFunctionsRequestBuilder) Tan(reqObj *WorkbookFunctionsTanRequestParameter) *WorkbookFunctionsTanRequestBuilder { bb := &WorkbookFunctionsTanRequestBuilder{BaseRequestBuilder: b.BaseRequestBuilder} bb.BaseRequestBuilder.baseURL += "/tan" bb.BaseRequestBuilder.requestObject = reqObj return bb } // type WorkbookFunctionsTanRequest struct{ BaseRequest } // func (b *WorkbookFunctionsTanRequestBuilder) Request() *WorkbookFunctionsTanRequest { return &WorkbookFunctionsTanRequest{ BaseRequest: BaseRequest{baseURL: b.baseURL, client: b.client, requestObject: b.requestObject}, } } // func (r *WorkbookFunctionsTanRequest) Post(ctx context.Context) (resObj *WorkbookFunctionResult, err error) { err = r.JSONRequest(ctx, "POST", "", r.requestObject, &resObj) return }
42wim/matterbridge
vendor/github.com/yaegashi/msgraph.go/beta/RequestWorkbookFunctionsTan.go
GO
apache-2.0
978
import optparse import pickle #converts urls to wiki_id parser = optparse.OptionParser() parser.add_option('-i','--input', dest = 'input_file', help = 'input_file') parser.add_option('-o','--output', dest = 'output_file', help = 'output_file') (options, args) = parser.parse_args() if options.input_file is None: options.input_file = raw_input('Enter input file:') if options.output_file is None: options.output_file = raw_input('Enter output file:') input_file = options.input_file output_file = options.output_file #define the dictionary url:wiki_id wiki_from_url_dict = {} with open('../../datasets/dbpedia/page_ids_en_2016.ttl','r') as f: for line in f: line = line.split(' ') if line[0] == '#': continue url = line[0] wiki_id_list = line[2].split('\"') wiki_id = wiki_id_list[1] print(url, wiki_id) wiki_from_url_dict[url] = int(wiki_id) output_file_write = open(output_file,'w') #iterate through the page links and turn urls into wiki_ids max_wiki_id = max(wiki_from_url_dict.values()) + 1 local_id = {} count = 0 with open(input_file) as page_links: for line in page_links: line = line.split(' ') if line[0] == '#': continue url_1 = line[0] url_2 = line[2] #if wiki_id not found, assign an id = max_wiki_id and increment max_wiki_id try: wiki_id1 = wiki_from_url_dict[url_1] #first entity has wiki_id try: wiki_id2 = wiki_from_url_dict[url_2] #first and second entities have wiki_ids except (KeyError, IndexError): #first entity has wiki_id, second entity doesn't try: #check if a local id has already been assigned wiki_id2 = local_id[url_2] except (KeyError, IndexError): wiki_id2 = max_wiki_id local_id[url_2] = wiki_id2 max_wiki_id +=1 except (KeyError, IndexError): #first entity doesn't have wiki_id try: wiki_id1 = local_id[url_1] except (KeyError, IndexError): wiki_id1 = max_wiki_id local_id[url_1] = wiki_id1 max_wiki_id += 1 try: #first entity doesn't have wiki_id, second entity has it wiki_id2 = wiki_from_url_dict[url_2] except (KeyError, IndexError): #neither first nor second entity have wiki_ids try: #check if a local id has already been assigned wiki_id2 = local_id[url_2] except (KeyError, IndexError): wiki_id2 = max_wiki_id local_id[url_2] = wiki_id2 max_wiki_id +=1 output_file_write.write('%d %d\n' %(wiki_id1,wiki_id2)) print count count += 1 output_file_write.close() pickle.dump(local_id,open('../../datasets/dbpedia/local_id_to_url_full_mapping_based.p','wb'))
MultimediaSemantics/entity2vec
scripts/old/page_links_to_edge_list_wiki.py
Python
apache-2.0
3,039
/* * #%L * fujion * %% * Copyright (C) 2021 Fujion Framework * %% * 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. * * #L% */ package org.fujion.highcharts; import org.fujion.ancillary.OptionMap; import org.fujion.ancillary.Options; import org.fujion.annotation.Option; import java.util.ArrayList; import java.util.List; /** * Base class for all plot types. * <p> * PlotOptions is a wrapper for config objects for each series type. The config objects for each * series can also be overridden for each series item as given in the series array. Configuration * options for the series are given in three levels. Options for all series in a chart are given in * the plotOptions.series object. Then options for all series of a specific type are given in the * plotOptions of that type, for example plotOptions.line. Next, options for one single series are * given in the series array. */ public abstract class PlotOptions extends Options { /** * The text identifier of the plot type. */ @Option(ignore = true) protected String type; /** * Allow this series' points to be selected by clicking on the markers, bars or pie slices. * Defaults to false. */ @Option public Boolean allowPointSelect; /** * Enable or disable the initial animation when a series is displayed. Since version 2.1, the * animation can be set as a configuration object. Please note that this option only applies to * the initial animation of the series itself. For other animations, see #chart.animation and * the animation parameter under the API methods. */ @Option public final AnimationOptions animation = new AnimationOptions(); /** * For some series, there is a limit that shuts down initial animation by default when the total * number of points in the chart is too high. For example, for a column chart and its * derivatives, animation doesn't run if there is more than 250 points totally. To disable this * cap, set animationLimit to Infinity. */ @Option public Integer animationLimit; /** * Set the point threshold for when a series should enter boost mode. Setting it to e.g. 2000 * will cause the series to enter boost mode when there are 2000 or more points in the series. * To disable boosting on the series, set the boostThreshold to 0. Setting it to 1 will force * boosting. Requires modules/boost.js. */ @Option public Integer boostThreshold; /** * A CSS class name to apply to the series' graphical elements. */ @Option public String className; /** * The main color or the series. In line type series it applies to the line and the point * markers unless otherwise specified. In bar type series it applies to the bars unless a color * is specified per point. The default value is pulled from the options.colors array. */ @Option public String color; /** * Styled mode only. A specific color index to use for the series, so its graphic * representations are given the class name highcharts-color-{n}. Defaults to undefined. */ @Option public Integer colorIndex; /** * When using automatic point colors pulled from the options.colors collection, this option * determines whether the chart should receive one color per series or one color per point. * Defaults to false. */ @Option public Boolean colorByPoint; /** * A series specific or series type specific color set to apply instead of the global colors * when colorByPoint is true. */ @Option public List<String> colors = new ArrayList<>(); /** * Polar charts only. Whether to connect the ends of a line series plot across the extremes. * Defaults to true. */ @Option public Boolean connectEnds; /** * Whether to connect a graph line across null points. Defaults to false. */ @Option public Boolean connectNulls; /** * When the series contains less points than the crop threshold, all points are drawn, event if * the points fall outside the visible plot area at the current zoom. The advantage of drawing * all points (including markers and columns), is that animation is performed on updates. On the * other hand, when the series contains more points than the crop threshold, the series data is * cropped to only contain points that fall within the plot area. The advantage of cropping away * invisible points is to increase performance on large series. . Defaults to 300. */ @Option public Double cropThreshold; /** * You can set the cursor to "pointer" if you have click events attached to the series, to * signal to the user that the points and lines can be clicked. Defaults to ''. */ @Option public String cursor; /** * A name for the dash style to use for the graph. Applies only to series type having a graph, * like line, spline, area and scatter in case it has a lineWidth. The value for the dashStyle * include: * <ul> * <li>Solid</li> * <li>ShortDash</li> * <li>ShortDot</li> * <li>ShortDashDot</li> * <li>ShortDashDotDot</li> * <li>Dot</li> * <li>Dash</li> * <li>LongDash</li> * <li>DashDot</li> * <li>LongDashDot</li> * <li>LongDashDotDot</li> * </ul> * Defaults to null. */ @Option public DashStyle dashStyle; /** * Options for data labels. * * @see DataLabelOptions */ @Option public final DataLabelOptions dataLabels = new DataLabelOptions(); /** * Requires the Accessibility module. A description of the series to add to the screen reader * information about the series. Defaults to undefined. */ @Option public String description; /** * Enable or disable the mouse tracking for a specific series. This includes point tooltips and * click events on graphs and points. For large datasets it improves performance. Defaults to * true. */ @Option public Boolean enableMouseTracking; /** * Requires the Accessibility module. By default, series are exposed to screen readers as * regions. By enabling this option, the series element itself will be exposed in the same way * as the data points. This is useful if the series is not used as a grouping entity in the * chart, but you still want to attach a description to the series. Defaults to undefined. */ @Option public Boolean exposeElementToA11y; /** * Determines whether the series should look for the nearest point in both dimensions or just * the x-dimension when hovering the series. Defaults to 'xy' for scatter series and 'x' for * most other series. If the data has duplicate x-values, it is recommended to set this to 'xy' * to allow hovering over all points. Applies only to series types using nearest neighbor search * (not direct hover) for tooltip. Defaults to x. */ @Option public String findNearestPointBy; /** * Whether to use the Y extremes of the total chart width or only the zoomed area when zooming * in on parts of the X axis. By default, the Y axis adjusts to the min and max of the visible * data. Cartesian series only. Defaults to false. */ @Option public Boolean getExtremesFromAll; /** * An id for the series. Defaults to null. */ @Option public String id; /** * An array specifying which option maps to which key in the data point array. This makes it * convenient to work with unstructured data arrays from different sources. Defaults to * undefined. */ @Option public final List<String> keys = new ArrayList<>(); /** * Text labels for the plot bands. */ @Option public final PlotLabelOptions label = new PlotLabelOptions(); /** * The line cap used for line ends and line joins on the graph. Defaults to round. */ @Option public String linecap; /** * Pixel with of the graph line. Defaults to 2. */ @Option public Integer lineWidth; /** * The id of another series to link to. Additionally, the value can be ":previous" to link to * the previous series. When two series are linked, only the first one appears in the legend. * Toggling the visibility of this also toggles the linked series. */ @Option public String linkedTo; /** * Options for point markers. * * @see MarkerOptions */ @Option public final MarkerOptions marker = new MarkerOptions(); /** * The color for the parts of the graph or points that are below the threshold. Defaults to * null. */ @Option public String negativeColor; /** * If no x values are given for the points in a series, pointInterval defines the interval of * the x values. For example, if a series contains one value every decade starting from year 0, * set pointInterval to 10. Defaults to 1. */ @Option public Double pointInterval; /** * On datetime series, this allows for setting the pointInterval to irregular time units, day, * month and year. A day is usually the same as 24 hours, but pointIntervalUnit also takes the * DST crossover into consideration when dealing with local time. Combine this option with * pointInterval to draw weeks, quarters, 6 months, 10 years etc. Please note that this options * applies to the series data, not the interval of the axis ticks, which is independent. * Defaults to undefined. */ @Option public String pointIntervalUnit; /** * Possible values: null, "on", "between". In a column chart, when pointPlacement is "on", the * point will not create any padding of the X axis. In a polar column chart this means that the * first column points directly north. If the pointPlacement is "between", the columns will be * laid out between ticks. This is useful for example for visualising an amount between two * points in time or in a certain sector of a polar chart. Defaults to null in cartesian charts, * "between" in polar charts. */ @Option public String pointPlacement; /** * If no x values are given for the points in a series, pointStart defines on what value to * start. For example, if a series contains one yearly value starting from 1945, set pointStart * to 1945. Defaults to 0. */ @Option public Double pointStart; /** * Whether to select the series initially. If showCheckbox is true, the checkbox next to the * series name will be checked for a selected series. Defaults to false. */ @Option public Boolean selected; /** * Boolean value whether to apply a drop shadow to the graph line. Optionally can be a * ShadowOptions object. Defaults to true. * * @see ShadowOptions */ @Option public Object shadow; /** * If true, a checkbox is displayed next to the legend item to allow selecting the series. The * state of the checkbox is determined by the selected option. Defaults to false. */ @Option public Boolean showCheckbox; /** * Whether to display this particular series or series type in the legend. Defaults to true. */ @Option public Boolean showInLegend; /** * If set to True, the accessibility module will skip past the points in this series for * keyboard navigation. Defaults to undefined. */ @Option public Boolean skipKeyboardNavigation; /** * When this is true, the series will not cause the Y axis to cross the zero plane (or threshold * option) unless the data actually crosses the plane. For example, if softThreshold is false, a * series of 0, 1, 2, 3 will make the Y axis show negative values according to the minPadding * option. If softThreshold is true, the Y axis starts at 0. Defaults to true. */ @Option public Boolean softThreshold; /** * Whether to stack the values of each series on top of each other. Possible values are null to * disable, "normal" to stack by value or "percent". Defaults to null. */ @Option public String stacking; /** * Whether to apply steps to the line. Possible values are left, center and right. Defaults to * undefined. */ @Option public AlignHorizontal step; /** * Sticky tracking of mouse events. When true, the mouseOut event on a series isn't triggered * until the mouse moves over another series, or out of the plot area. When false, the mouseOut * event on a series is triggered when the mouse leaves the area around the series' graph or * markers. This also implies the tooltip. When stickyTracking is false and tooltip.shared is * false, the tooltip will be hidden when moving the mouse between series. Defaults to true. */ @Option public Boolean stickyTracking; /** * The threshold, also called zero level or base level. For line type series this is only used * in conjunction with negativeColor. Defaults to 0. */ @Option public Double threshold; /** * A configuration object for the tooltip rendering of each single series. */ @Option public final TooltipOptions tooltip = new TooltipOptions(); /** * When a series contains a data array that is longer than this, only one dimensional arrays of * numbers, or two dimensional arrays with x and y values are allowed. Also, only the first * point is tested, and the rest are assumed to be the same format. This saves expensive data * checking and indexing in long series. Defaults to 1000. */ @Option public Integer turboThreshold; /** * Set the initial visibility of the series. Defaults to true. */ @Option public Boolean visible; /** * Defines the axis on which the zones are applied. Defaults to y. */ @Option public String zoneAxis; /** * An array defining zones within a series. Zones can be applied to the X axis, Y axis or Z axis * for bubbles, according to the zoneAxis option. In styled mode, the color zones are styled * with the .highcharts-zone-{n} class, or custom classed from the className option. */ @Option public final List<Zone> zones = new ArrayList<>(); /** * If type is not null, place options under a submap indexed by the type id. */ @Override public OptionMap toMap() { OptionMap map = super.toMap(); if (type != null) { OptionMap newMap = new OptionMap(); newMap.put(type, map); map = newMap; } return map; } }
fujion/fujion-framework
fujion-highcharts/src/main/java/org/fujion/highcharts/PlotOptions.java
Java
apache-2.0
15,646
describe('app.components.SaveProfileModal', function() { beforeEach(function () { module('app.components', 'ui.bootstrap', 'gettext'); }); describe('service', function () { var callbackObject; var saveSpy; var doNotSaveSpy; var cancelSpy; beforeEach(function () { bard.inject('SaveProfileModal', '$rootScope', '$document'); callbackObject = { save: function () {}, doNotSave: function () {}, cancel: function () {}, } saveSpy = sinon.spy(callbackObject, "save"); doNotSaveSpy = sinon.spy(callbackObject, "doNotSave"); cancelSpy = sinon.spy(callbackObject, "cancel"); }); xit('should show the modal', function () { var modal = SaveProfileModal.showModal(callbackObject.save, callbackObject.doNotSave, callbackObject.cancel); $rootScope.$digest(); var saveDialog = $document.find('.save-profile-modal'); expect(saveDialog.length).to.eq(1); var saveButton = $document.find('.save-profile-modal .btn.btn-primary'); expect(saveButton.length).to.eq(1); eventFire(saveButton[0], 'click'); $rootScope.$digest(); expect(saveSpy).to.have.been.called; var closeButtons = $document.find('.save-profile-modal .btn.btn-default'); expect(closeButtons.length).to.eq(2); eventFire(closeButtons[0], 'click'); $rootScope.$digest(); expect(cancelSpy).to.have.been.called; eventFire(closeButtons[1], 'click'); $rootScope.$digest(); expect(doNotSaveSpy).to.have.been.called; }); }); });
dtaylor113/manageiq-ui-self_service
tests/profiles/save-profile-modal-service.spec.js
JavaScript
apache-2.0
1,584
package grok.core; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; @AutoValue public abstract class Image { @JsonCreator public static Image of(@JsonProperty("id") String id, @JsonProperty("title") String title, @JsonProperty("url") String url) { return builder().id(id) .title(title) .url(url) .build(); } public static Builder builder() { return new AutoValue_Image.Builder(); } Image() {} @JsonProperty public abstract String id(); @JsonProperty public abstract String title(); @JsonProperty public abstract String url(); @AutoValue.Builder public abstract static class Builder { Builder() {} public abstract Builder id(String value); @JsonProperty public abstract Builder title(String value); @JsonProperty public abstract Builder url(String value); public abstract Image build(); } }
achaphiv/grok-core
grok-core-api/src/main/java/grok/core/Image.java
Java
apache-2.0
1,076
package com.mgaetan89.showsrage.fragment; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; @RunWith(Parameterized.class) public class ShowsFragment_OnQueryTextChangeTest { @Parameterized.Parameter(0) public String newText; private ShowsFragment fragment; @Before public void before() { this.fragment = spy(new ShowsFragment()); } @Test public void onQueryTextChange() { try { assertTrue(this.fragment.onQueryTextChange(this.newText)); } catch (NullPointerException exception) { // LocalBroadcastManager.getInstance(Context) returns null in tests } verify(this.fragment).sendFilterMessage(); } @After public void after() { this.fragment = null; } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {null}, {""}, {" "}, {"Search Query"}, }); } }
phaseburn/ShowsRage
app/src/test/java/com/mgaetan89/showsrage/fragment/ShowsFragment_OnQueryTextChangeTest.java
Java
apache-2.0
1,137
# frozen_string_literal: true class CreateSnapshotAttributeValues < ActiveRecord::Migration[4.2] def change create_table :snapshot_attribute_values do |t| t.integer :snapshot_id, null: false t.integer :attribute_value_id, null: false t.timestamps null: false end end end
ausaccessfed/validator-service
db/migrate/20160508233712_create_snapshot_attribute_values.rb
Ruby
apache-2.0
302
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "condor_config.h" #include "condor_state.h" #include "condor_api.h" #include "status_types.h" #include "totals.h" #include "get_daemon_name.h" #include "daemon.h" #include "dc_collector.h" #include "extArray.h" #include "sig_install.h" #include "string_list.h" #include "condor_string.h" // for strnewp() #include "match_prefix.h" // is_arg_colon_prefix #include "print_wrapped_text.h" #include "error_utils.h" #include "condor_distribution.h" #include "condor_version.h" #include <vector> #include <sstream> #include <iostream> using std::vector; using std::string; using std::stringstream; struct SortSpec { string arg; string keyAttr; string keyExprAttr; ExprTree* expr; ExprTree* exprLT; ExprTree* exprEQ; SortSpec(): arg(), keyAttr(), keyExprAttr(), expr(NULL), exprLT(NULL), exprEQ(NULL) {} ~SortSpec() { if (NULL != expr) delete expr; if (NULL != exprLT) delete exprLT; if (NULL != exprEQ) delete exprEQ; } SortSpec(const SortSpec& src): expr(NULL), exprLT(NULL), exprEQ(NULL) { *this = src; } SortSpec& operator=(const SortSpec& src) { if (this == &src) return *this; arg = src.arg; keyAttr = src.keyAttr; keyExprAttr = src.keyExprAttr; if (NULL != expr) delete expr; expr = src.expr->Copy(); if (NULL != exprLT) delete exprLT; exprLT = src.exprLT->Copy(); if (NULL != exprEQ) delete exprEQ; exprEQ = src.exprEQ->Copy(); return *this; } }; // global variables AttrListPrintMask pm; printmask_headerfooter_t pmHeadFoot = STD_HEADFOOT; List<const char> pm_head; // The list of headings for the mask entries std::vector<GroupByKeyInfo> group_by_keys; // TJ 8.1.5 for future use, ignored for now. bool explicit_format = false; bool using_print_format = false; // hack for now so we can get standard totals when using -print-format bool disable_user_print_files = false; // allow command line to defeat use of default user print files. const char *DEFAULT= "<default>"; DCCollector* pool = NULL; AdTypes type = (AdTypes) -1; ppOption ppStyle = PP_NOTSET; ppOption ppTotalStyle = PP_NOTSET; // used when setting PP_CUSTOM to keep track of how to do totals. int wantOnlyTotals = 0; int summarySize = -1; bool expert = false; bool wide_display = false; // when true, don't truncate field data bool invalid_fields_empty = false; // when true, print "" instead of "[?]" for missing data Mode mode = MODE_NOTSET; const char * mode_constraint = NULL; // constraint set by mode int diagnose = 0; char* direct = NULL; char* statistics = NULL; char* genericType = NULL; CondorQuery *query; char buffer[1024]; char *myName; vector<SortSpec> sortSpecs; bool noSort = false; // set to true to disable sorting entirely bool javaMode = false; bool vmMode = false; bool absentMode = false; char *target = NULL; const char * ads_file = NULL; // read classads from this file instead of querying them from the collector ClassAd *targetAd = NULL; ArgList projList; // Attributes that we want the server to send us // instantiate templates // function declarations void usage (); void firstPass (int, char *[]); void secondPass (int, char *[]); void prettyPrint(ClassAdList &, TrackTotals *); int matchPrefix(const char *, const char *, int min_len); int lessThanFunc(AttrList*,AttrList*,void*); int customLessThanFunc(AttrList*,AttrList*,void*); static bool read_classad_file(const char *filename, ClassAdList &classads, const char * constr); extern "C" int SetSyscalls (int) {return 0;} extern void setPPstyle (ppOption, int, const char *); extern void setType (const char *, int, const char *); extern void setMode (Mode, int, const char *); int main (int argc, char *argv[]) { #if !defined(WIN32) install_sig_handler(SIGPIPE, (SIG_HANDLER)SIG_IGN ); #endif // initialize to read from config file myDistro->Init( argc, argv ); myName = argv[0]; config(); dprintf_config_tool_on_error(0); // The arguments take two passes to process --- the first pass // figures out the mode, after which we can instantiate the required // query object. We add implied constraints from the command line in // the second pass. firstPass (argc, argv); // if the mode has not been set, it is STARTD_NORMAL if (mode == MODE_NOTSET) { setMode (MODE_STARTD_NORMAL, 0, DEFAULT); } // instantiate query object if (!(query = new CondorQuery (type))) { dprintf_WriteOnErrorBuffer(stderr, true); fprintf (stderr, "Error: Out of memory\n"); exit (1); } // if a first-pass setMode set a mode_constraint, apply it now to the query object if (mode_constraint && ! explicit_format) { query->addANDConstraint(mode_constraint); } // set pretty print style implied by the type of entity being queried // but do it with default priority, so that explicitly requested options // can override it switch (type) { #ifdef HAVE_EXT_POSTGRESQL case QUILL_AD: setPPstyle(PP_QUILL_NORMAL, 0, DEFAULT); break; #endif /* HAVE_EXT_POSTGRESQL */ case DEFRAG_AD: setPPstyle(PP_GENERIC_NORMAL, 0, DEFAULT); break; case STARTD_AD: setPPstyle(PP_STARTD_NORMAL, 0, DEFAULT); break; case SCHEDD_AD: setPPstyle(PP_SCHEDD_NORMAL, 0, DEFAULT); break; case MASTER_AD: setPPstyle(PP_MASTER_NORMAL, 0, DEFAULT); break; case CKPT_SRVR_AD: setPPstyle(PP_CKPT_SRVR_NORMAL, 0, DEFAULT); break; case COLLECTOR_AD: setPPstyle(PP_COLLECTOR_NORMAL, 0, DEFAULT); break; case STORAGE_AD: setPPstyle(PP_STORAGE_NORMAL, 0, DEFAULT); break; case NEGOTIATOR_AD: setPPstyle(PP_NEGOTIATOR_NORMAL, 0, DEFAULT); break; case GRID_AD: setPPstyle(PP_GRID_NORMAL, 0, DEFAULT); break; case GENERIC_AD: setPPstyle(PP_GENERIC, 0, DEFAULT); break; case ANY_AD: setPPstyle(PP_ANY_NORMAL, 0, DEFAULT); break; default: setPPstyle(PP_VERBOSE, 0, DEFAULT); } // set the constraints implied by the mode switch (mode) { #ifdef HAVE_EXT_POSTGRESQL case MODE_QUILL_NORMAL: #endif /* HAVE_EXT_POSTGRESQL */ case MODE_DEFRAG_NORMAL: case MODE_STARTD_NORMAL: case MODE_MASTER_NORMAL: case MODE_CKPT_SRVR_NORMAL: case MODE_SCHEDD_NORMAL: case MODE_SCHEDD_SUBMITTORS: case MODE_COLLECTOR_NORMAL: case MODE_NEGOTIATOR_NORMAL: case MODE_STORAGE_NORMAL: case MODE_GENERIC_NORMAL: case MODE_ANY_NORMAL: case MODE_GRID_NORMAL: case MODE_HAD_NORMAL: break; case MODE_OTHER: // tell the query object what the type we're querying is query->setGenericQueryType(genericType); free(genericType); genericType = NULL; break; case MODE_STARTD_AVAIL: // For now, -avail shows you machines avail to anyone. sprintf (buffer, "%s == \"%s\"", ATTR_STATE, state_to_string(unclaimed_state)); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addORConstraint (buffer); break; case MODE_STARTD_RUN: sprintf (buffer, "%s == \"%s\"", ATTR_STATE, state_to_string(claimed_state)); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addORConstraint (buffer); break; case MODE_STARTD_COD: sprintf (buffer, "%s > 0", ATTR_NUM_COD_CLAIMS ); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addORConstraint (buffer); break; default: break; } if(javaMode) { sprintf( buffer, "%s == TRUE", ATTR_HAS_JAVA ); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addANDConstraint (buffer); projList.AppendArg(ATTR_HAS_JAVA); projList.AppendArg(ATTR_JAVA_MFLOPS); projList.AppendArg(ATTR_JAVA_VENDOR); projList.AppendArg(ATTR_JAVA_VERSION); } if(absentMode) { sprintf( buffer, "%s == TRUE", ATTR_ABSENT ); if (diagnose) { printf( "Adding constraint %s\n", buffer ); } query->addANDConstraint( buffer ); projList.AppendArg( ATTR_ABSENT ); projList.AppendArg( ATTR_LAST_HEARD_FROM ); projList.AppendArg( ATTR_CLASSAD_LIFETIME ); } if(vmMode) { sprintf( buffer, "%s == TRUE", ATTR_HAS_VM); if (diagnose) { printf ("Adding constraint [%s]\n", buffer); } query->addANDConstraint (buffer); projList.AppendArg(ATTR_VM_TYPE); projList.AppendArg(ATTR_VM_MEMORY); projList.AppendArg(ATTR_VM_NETWORKING); projList.AppendArg(ATTR_VM_NETWORKING_TYPES); projList.AppendArg(ATTR_VM_HARDWARE_VT); projList.AppendArg(ATTR_VM_AVAIL_NUM); projList.AppendArg(ATTR_VM_ALL_GUEST_MACS); projList.AppendArg(ATTR_VM_ALL_GUEST_IPS); projList.AppendArg(ATTR_VM_GUEST_MAC); projList.AppendArg(ATTR_VM_GUEST_IP); } // second pass: add regular parameters and constraints if (diagnose) { printf ("----------\n"); } secondPass (argc, argv); // initialize the totals object if (ppStyle == PP_CUSTOM && using_print_format) { if (pmHeadFoot & HF_NOSUMMARY) ppTotalStyle = PP_CUSTOM; } else { ppTotalStyle = ppStyle; } TrackTotals totals(ppTotalStyle); // fetch the query QueryResult q; if ((mode == MODE_STARTD_NORMAL) && (ppStyle == PP_STARTD_NORMAL)) { projList.AppendArg("Name"); projList.AppendArg("Machine"); projList.AppendArg("Opsys"); projList.AppendArg("Arch"); projList.AppendArg("State"); projList.AppendArg("Activity"); projList.AppendArg("LoadAvg"); projList.AppendArg("Memory"); projList.AppendArg("ActvtyTime"); projList.AppendArg("MyCurrentTime"); projList.AppendArg("EnteredCurrentActivity"); } else if( ppStyle == PP_VERBOSE ) { // Remove everything from the projection list if we're displaying // the "long form" of the ads. projList.Clear(); } if( projList.Count() > 0 ) { char **attr_list = projList.GetStringArray(); query->setDesiredAttrs(attr_list); deleteStringArray(attr_list); } // if diagnose was requested, just print the query ad if (diagnose) { ClassAd queryAd; // print diagnostic information about inferred internal state setMode ((Mode) 0, 0, NULL); setType (NULL, 0, NULL); setPPstyle ((ppOption) 0, 0, DEFAULT); printf ("----------\n"); q = query->getQueryAd (queryAd); fPrintAd (stdout, queryAd); printf ("----------\n"); fprintf (stderr, "Result of making query ad was: %d\n", q); exit (1); } // Address (host:port) is taken from requested pool, if given. char* addr = (NULL != pool) ? pool->addr() : NULL; Daemon* requested_daemon = pool; // If we're in "direct" mode, then we attempt to locate the daemon // associated with the requested subsystem (here encoded by value of mode) // In this case the host:port of pool (if given) denotes which // pool is being consulted if( direct ) { Daemon *d = NULL; switch( mode ) { case MODE_MASTER_NORMAL: d = new Daemon( DT_MASTER, direct, addr ); break; case MODE_STARTD_NORMAL: case MODE_STARTD_AVAIL: case MODE_STARTD_RUN: case MODE_STARTD_COD: d = new Daemon( DT_STARTD, direct, addr ); break; #ifdef HAVE_EXT_POSTGRESQL case MODE_QUILL_NORMAL: d = new Daemon( DT_QUILL, direct, addr ); break; #endif /* HAVE_EXT_POSTGRESQL */ case MODE_SCHEDD_NORMAL: case MODE_SCHEDD_SUBMITTORS: d = new Daemon( DT_SCHEDD, direct, addr ); break; case MODE_NEGOTIATOR_NORMAL: d = new Daemon( DT_NEGOTIATOR, direct, addr ); break; case MODE_CKPT_SRVR_NORMAL: case MODE_COLLECTOR_NORMAL: case MODE_LICENSE_NORMAL: case MODE_STORAGE_NORMAL: case MODE_GENERIC_NORMAL: case MODE_ANY_NORMAL: case MODE_OTHER: case MODE_GRID_NORMAL: case MODE_HAD_NORMAL: // These have to go to the collector, anyway. break; default: fprintf( stderr, "Error: Illegal mode %d\n", mode ); exit( 1 ); break; } // Here is where we actually override 'addr', if we can obtain // address of the requested daemon/subsys. If it can't be // located, then fail with error msg. // 'd' will be null (unset) if mode is one of above that must go to // collector (MODE_ANY_NORMAL, MODE_COLLECTOR_NORMAL, etc) if (NULL != d) { if( d->locate() ) { addr = d->addr(); requested_daemon = d; } else { const char* id = d->idStr(); if (NULL == id) id = d->name(); dprintf_WriteOnErrorBuffer(stderr, true); if (NULL == id) id = "daemon"; fprintf(stderr, "Error: Failed to locate %s\n", id); fprintf(stderr, "%s\n", d->error()); exit( 1 ); } } } ClassAdList result; CondorError errstack; if (NULL != ads_file) { MyString req; // query requirements q = query->getRequirements(req); const char * constraint = req.empty() ? NULL : req.c_str(); if (read_classad_file(ads_file, result, constraint)) { q = Q_OK; } } else if (NULL != addr) { // this case executes if pool was provided, or if in "direct" mode with // subsystem that corresponds to a daemon (above). // Here 'addr' represents either the host:port of requested pool, or // alternatively the host:port of daemon associated with requested subsystem (direct mode) q = query->fetchAds (result, addr, &errstack); } else { // otherwise obtain list of collectors and submit query that way CollectorList * collectors = CollectorList::create(); q = collectors->query (*query, result, &errstack); delete collectors; } // if any error was encountered during the query, report it and exit if (Q_OK != q) { dprintf_WriteOnErrorBuffer(stderr, true); // we can always provide these messages: fprintf( stderr, "Error: %s\n", getStrQueryResult(q) ); fprintf( stderr, "%s\n", errstack.getFullText(true).c_str() ); if ((NULL != requested_daemon) && ((Q_NO_COLLECTOR_HOST == q) || (requested_daemon->type() == DT_COLLECTOR))) { // Specific long message if connection to collector failed. const char* fullhost = requested_daemon->fullHostname(); if (NULL == fullhost) fullhost = "<unknown_host>"; const char* daddr = requested_daemon->addr(); if (NULL == daddr) daddr = "<unknown>"; char info[1000]; sprintf(info, "%s (%s)", fullhost, daddr); printNoCollectorContact( stderr, info, !expert ); } else if ((NULL != requested_daemon) && (Q_COMMUNICATION_ERROR == q)) { // more helpful message for failure to connect to some daemon/subsys const char* id = requested_daemon->idStr(); if (NULL == id) id = requested_daemon->name(); if (NULL == id) id = "daemon"; const char* daddr = requested_daemon->addr(); if (NULL == daddr) daddr = "<unknown>"; fprintf(stderr, "Error: Failed to contact %s at %s\n", id, daddr); } // fail exit (1); } if (noSort) { // do nothing } else if (sortSpecs.empty()) { // default classad sorting result.Sort((SortFunctionType)lessThanFunc); } else { // User requested custom sorting expressions: // insert attributes related to custom sorting result.Open(); while (ClassAd* ad = result.Next()) { for (vector<SortSpec>::iterator ss(sortSpecs.begin()); ss != sortSpecs.end(); ++ss) { ss->expr->SetParentScope(ad); classad::Value v; ss->expr->Evaluate(v); stringstream vs; // This will properly render all supported value types, // including undefined and error, although current semantic // pre-filters classads where sort expressions are undef/err: vs << ((v.IsStringValue())?"\"":"") << v << ((v.IsStringValue())?"\"":""); ad->AssignExpr(ss->keyAttr.c_str(), vs.str().c_str()); // Save the full expr in case user wants to examine on output: ad->AssignExpr(ss->keyExprAttr.c_str(), ss->arg.c_str()); } } result.Open(); result.Sort((SortFunctionType)customLessThanFunc); } // output result prettyPrint (result, &totals); delete query; return 0; } const CustomFormatFnTable * getCondorStatusPrintFormats(); int set_status_print_mask_from_stream ( const char * streamid, bool is_filename, const char ** pconstraint) { std::string where_expr; std::string messages; StringList attrs; SimpleInputStream * pstream = NULL; *pconstraint = NULL; FILE *file = NULL; if (MATCH == strcmp("-", streamid)) { pstream = new SimpleFileInputStream(stdin, false); } else if (is_filename) { file = safe_fopen_wrapper_follow(streamid, "r"); if (file == NULL) { fprintf(stderr, "Can't open select file: %s\n", streamid); return -1; } pstream = new SimpleFileInputStream(file, true); } else { pstream = new StringLiteralInputStream(streamid); } ASSERT(pstream); int err = SetAttrListPrintMaskFromStream( *pstream, *getCondorStatusPrintFormats(), pm, pmHeadFoot, group_by_keys, where_expr, attrs, messages); delete pstream; pstream = NULL; if ( ! err) { if ( ! where_expr.empty()) { *pconstraint = pm.store(where_expr.c_str()); //if ( ! validate_constraint(*pconstraint)) { // formatstr_cat(messages, "WHERE expression is not valid: %s\n", *pconstraint); //} } // convert projection list into the format that condor status likes. because programmers. attrs.rewind(); const char * attr; while ((attr = attrs.next())) { projList.AppendArg(attr); } } if ( ! messages.empty()) { fprintf(stderr, "%s", messages.c_str()); } return err; } static bool read_classad_file(const char *filename, ClassAdList &classads, const char * constr) { bool success = false; FILE* file = safe_fopen_wrapper_follow(filename, "r"); if (file == NULL) { fprintf(stderr, "Can't open file of job ads: %s\n", filename); return false; } else { CondorClassAdFileParseHelper parse_helper("\n"); for (;;) { ClassAd* classad = new ClassAd(); int error; bool is_eof; int cAttrs = classad->InsertFromFile(file, is_eof, error, &parse_helper); bool include_classad = cAttrs > 0 && error >= 0; if (include_classad && constr) { classad::Value val; if (classad->EvaluateExpr(constr,val)) { if ( ! val.IsBooleanValueEquiv(include_classad)) { include_classad = false; } } } if (include_classad) { classads.Insert(classad); } else { delete classad; } if (is_eof) { success = true; break; } if (error < 0) { success = false; break; } } fclose(file); } return success; } void usage () { fprintf (stderr,"Usage: %s [help-opt] [query-opt] [display-opt] " "[custom-opts ...] [name ...]\n" " where [help-opt] is one of\n" "\t-help\t\t\tPrint this screen and exit\n" "\t-version\t\tPrint HTCondor version and exit\n" "\t-diagnose\t\tPrint out query ad without performing query\n" " and [query-opt] is one of\n" "\t-absent\t\t\tPrint information about absent resources\n" "\t-avail\t\t\tPrint information about available resources\n" "\t-ckptsrvr\t\tDisplay checkpoint server attributes\n" "\t-claimed\t\tPrint information about claimed resources\n" "\t-cod\t\t\tDisplay Computing On Demand (COD) jobs\n" "\t-collector\t\tDisplay collector daemon attributes\n" "\t-debug\t\t\tDisplay debugging info to console\n" "\t-defrag\t\t\tDisplay status of defrag daemon\n" "\t-direct <host>\t\tGet attributes directly from the given daemon\n" "\t-java\t\t\tDisplay Java-capable hosts\n" "\t-vm\t\t\tDisplay VM-capable hosts\n" "\t-license\t\tDisplay attributes of licenses\n" "\t-master\t\t\tDisplay daemon master attributes\n" "\t-pool <name>\t\tGet information from collector <name>\n" "\t-ads <file>\t\tGet information from <file>\n" "\t-grid\t\t\tDisplay grid resources\n" "\t-run\t\t\tSame as -claimed [deprecated]\n" #ifdef HAVE_EXT_POSTGRESQL "\t-quill\t\t\tDisplay attributes of quills\n" #endif /* HAVE_EXT_POSTGRESQL */ "\t-schedd\t\t\tDisplay attributes of schedds\n" "\t-server\t\t\tDisplay important attributes of resources\n" "\t-startd\t\t\tDisplay resource attributes\n" "\t-generic\t\tDisplay attributes of 'generic' ads\n" "\t-subsystem <type>\tDisplay classads of the given type\n" "\t-negotiator\t\tDisplay negotiator attributes\n" "\t-storage\t\tDisplay network storage resources\n" "\t-any\t\t\tDisplay any resources\n" "\t-state\t\t\tDisplay state of resources\n" "\t-submitters\t\tDisplay information about request submitters\n" // "\t-statistics <set>:<n>\tDisplay statistics for <set> at level <n>\n" // "\t\t\t\tsee STATISTICS_TO_PUBLISH for valid <set> and level values\n" // "\t-world\t\t\tDisplay all pools reporting to UW collector\n" " and [display-opt] is one of\n" "\t-long\t\t\tDisplay entire classads\n" "\t-sort <expr>\t\tSort entries by expressions. 'no' disables sorting\n" "\t-total\t\t\tDisplay totals only\n" "\t-verbose\t\tSame as -long\n" "\t-wide\t\t\tdon't truncate data to fit in 80 columns.\n" "\t-xml\t\t\tDisplay entire classads, but in XML\n" "\t-attributes X,Y,...\tAttributes to show in -xml or -long \n" "\t-expert\t\t\tDisplay shorter error messages\n" " and [custom-opts ...] are one or more of\n" "\t-constraint <const>\tAdd constraint on classads\n" "\t-format <fmt> <attr>\tRegister display format and attribute\n" "\t-autoformat:[V,ntlh] <attr> [attr2 [attr3 ...]]\t Print attr(s) with automatic formatting\n" "\t\tV\tUse %%V formatting\n" "\t\t,\tComma separated (default is space separated)\n" "\t\tt\tTab separated\n" "\t\tn\tNewline after each attribute\n" "\t\tl\tLabel each value\n" "\t\th\tHeadings\n" "\t-target filename\tIf -format or -af is used, the option target classad\n", myName); } void firstPass (int argc, char *argv[]) { int had_pool_error = 0; int had_direct_error = 0; int had_statistics_error = 0; //bool explicit_mode = false; const char * pcolon = NULL; // Process arguments: there are dependencies between them // o -l/v and -serv are mutually exclusive // o -sub, -avail and -run are mutually exclusive // o -pool and -entity may be used at most once // o since -c can be processed only after the query has been instantiated, // constraints are added on the second pass for (int i = 1; i < argc; i++) { if (matchPrefix (argv[i], "-avail", 3)) { setMode (MODE_STARTD_AVAIL, i, argv[i]); } else if (matchPrefix (argv[i], "-pool", 2)) { if( pool ) { delete pool; had_pool_error = 1; } i++; if( ! argv[i] ) { fprintf( stderr, "%s: -pool requires a hostname as an argument.\n", myName ); if (!expert) { printf("\n"); print_wrapped_text("Extra Info: The hostname should be the central " "manager of the Condor pool you wish to work with.", stderr); printf("\n"); } fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } pool = new DCCollector( argv[i] ); if( !pool->addr() ) { dprintf_WriteOnErrorBuffer(stderr, true); fprintf( stderr, "Error: %s\n", pool->error() ); if (!expert) { printf("\n"); print_wrapped_text("Extra Info: You specified a hostname for a pool " "(the -pool argument). That should be the Internet " "host name for the central manager of the pool, " "but it does not seem to " "be a valid hostname. (The DNS lookup failed.)", stderr); } exit( 1 ); } } else if (is_dash_arg_prefix (argv[i], "ads", 2)) { if( !argv[i+1] ) { fprintf( stderr, "%s: -ads requires a filename argument\n", myName ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } i += 1; ads_file = argv[i]; } else if (matchPrefix (argv[i], "-format", 2)) { setPPstyle (PP_CUSTOM, i, argv[i]); if( !argv[i+1] || !argv[i+2] ) { fprintf( stderr, "%s: -format requires two other arguments\n", myName ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } i += 2; explicit_format = true; } else if (*argv[i] == '-' && (is_arg_colon_prefix(argv[i]+1, "autoformat", &pcolon, 5) || is_arg_colon_prefix(argv[i]+1, "af", &pcolon, 2)) ) { // make sure we have at least one more argument if ( !argv[i+1] || *(argv[i+1]) == '-') { fprintf( stderr, "Error: Argument %s requires " "at last one attribute parameter\n", argv[i] ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } explicit_format = true; setPPstyle (PP_CUSTOM, i, argv[i]); while (argv[i+1] && *(argv[i+1]) != '-') { ++i; } // if autoformat list ends in a '-' without any characters after it, just eat the arg and keep going. if (i+1 < argc && '-' == (argv[i+1])[0] && 0 == (argv[i+1])[1]) { ++i; } } else if (is_dash_arg_colon_prefix(argv[i], "print-format", &pcolon, 2)) { if ( (i+1 >= argc) || (*(argv[i+1]) == '-' && (argv[i+1])[1] != 0)) { fprintf( stderr, "Error: Argument -print-format requires a filename argument\n"); exit( 1 ); } explicit_format = true; ++i; // eat the next argument. // we can't fully parse the print format argument until the second pass, so we are done for now. } else if (matchPrefix (argv[i], "-wide", 3)) { wide_display = true; // when true, don't truncate field data //invalid_fields_empty = true; } else if (matchPrefix (argv[i], "-target", 5)) { if( !argv[i+1] ) { fprintf( stderr, "%s: -target requires one additional argument\n", myName ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } i += 1; target = argv[i]; FILE *targetFile = safe_fopen_wrapper_follow(target, "r"); int iseof, iserror, empty; targetAd = new ClassAd(targetFile, "\n\n", iseof, iserror, empty); fclose(targetFile); } else if (matchPrefix (argv[i], "-constraint", 4)) { // can add constraints on second pass only i++; if( ! argv[i] ) { fprintf( stderr, "%s: -constraint requires another argument\n", myName ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } } else if (matchPrefix (argv[i], "-direct", 4)) { if( direct ) { free( direct ); had_direct_error = 1; } i++; if( ! argv[i] ) { fprintf( stderr, "%s: -direct requires another argument\n", myName ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } direct = strdup( argv[i] ); } else if (matchPrefix (argv[i], "-diagnose", 4)) { diagnose = 1; } else if (matchPrefix (argv[i], "-debug", 3)) { // dprintf to console dprintf_set_tool_debug("TOOL", 0); } else if (matchPrefix (argv[i], "-defrag", 4)) { setMode (MODE_DEFRAG_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-help", 2)) { usage (); exit (0); } else if (matchPrefix (argv[i], "-long", 2) || matchPrefix (argv[i],"-verbose", 3)) { setPPstyle (PP_VERBOSE, i, argv[i]); } else if (matchPrefix (argv[i],"-xml", 2)){ setPPstyle (PP_XML, i, argv[i]); } else if (matchPrefix (argv[i],"-attributes", 3)){ if( !argv[i+1] ) { fprintf( stderr, "%s: -attributes requires one additional argument\n", myName ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } i++; } else if (matchPrefix (argv[i], "-run", 2) || matchPrefix(argv[i], "-claimed", 3)) { setMode (MODE_STARTD_RUN, i, argv[i]); } else if( matchPrefix (argv[i], "-cod", 4) ) { setMode (MODE_STARTD_COD, i, argv[i]); } else if (matchPrefix (argv[i], "-java", 2)) { /*explicit_mode =*/ javaMode = true; } else if (matchPrefix (argv[i], "-absent", 3)) { /*explicit_mode =*/ absentMode = true; } else if (matchPrefix (argv[i], "-vm", 3)) { /*explicit_mode =*/ vmMode = true; } else if (matchPrefix (argv[i], "-server", 3)) { setPPstyle (PP_STARTD_SERVER, i, argv[i]); } else if (matchPrefix (argv[i], "-state", 5)) { setPPstyle (PP_STARTD_STATE, i, argv[i]); } else if (matchPrefix (argv[i], "-statistics", 6)) { if( statistics ) { free( statistics ); had_statistics_error = 1; } i++; if( ! argv[i] ) { fprintf( stderr, "%s: -statistics requires another argument\n", myName ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } statistics = strdup( argv[i] ); } else if (matchPrefix (argv[i], "-startd", 5)) { setMode (MODE_STARTD_NORMAL,i, argv[i]); } else if (matchPrefix (argv[i], "-schedd", 3)) { setMode (MODE_SCHEDD_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-grid", 2)) { setMode (MODE_GRID_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-subsystem", 5)) { i++; if( !argv[i] ) { fprintf( stderr, "%s: -subsystem requires another argument\n", myName ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } if (matchPrefix (argv[i], "schedd", 6)) { setMode (MODE_SCHEDD_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "startd", 6)) { setMode (MODE_STARTD_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "quill", 5)) { setMode (MODE_QUILL_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "negotiator", 10)) { setMode (MODE_NEGOTIATOR_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "master", 6)) { setMode (MODE_MASTER_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "collector", 9)) { setMode (MODE_COLLECTOR_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "generic", 7)) { setMode (MODE_GENERIC_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "had", 3)) { setMode (MODE_HAD_NORMAL, i, argv[i]); } else if (*argv[i] == '-') { fprintf(stderr, "%s: -subsystem requires another argument\n", myName); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit(1); } else { genericType = strdup(argv[i]); setMode (MODE_OTHER, i, argv[i]); } } else #ifdef HAVE_EXT_POSTGRESQL if (matchPrefix (argv[i], "-quill", 2)) { setMode (MODE_QUILL_NORMAL, i, argv[i]); } else #endif /* HAVE_EXT_POSTGRESQL */ if (matchPrefix (argv[i], "-license", 3)) { setMode (MODE_LICENSE_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-storage", 4)) { setMode (MODE_STORAGE_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-negotiator", 2)) { setMode (MODE_NEGOTIATOR_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-generic", 3)) { setMode (MODE_GENERIC_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-any", 3)) { setMode (MODE_ANY_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-sort", 3)) { i++; if( ! argv[i] ) { fprintf( stderr, "%s: -sort requires another argument\n", myName ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } if (MATCH == strcasecmp(argv[i], "false") || MATCH == strcasecmp(argv[i], "0") || MATCH == strcasecmp(argv[i], "no") || MATCH == strcasecmp(argv[i], "none")) { noSort = true; continue; } int jsort = sortSpecs.size(); SortSpec ss; ExprTree* sortExpr = NULL; if (ParseClassAdRvalExpr(argv[i], sortExpr)) { fprintf(stderr, "Error: Parse error of: %s\n", argv[i]); exit(1); } ss.expr = sortExpr; ss.arg = argv[i]; formatstr(ss.keyAttr, "CondorStatusSortKey%d", jsort); formatstr(ss.keyExprAttr, "CondorStatusSortKeyExpr%d", jsort); string exprString; formatstr(exprString, "MY.%s < TARGET.%s", ss.keyAttr.c_str(), ss.keyAttr.c_str()); if (ParseClassAdRvalExpr(exprString.c_str(), sortExpr)) { fprintf(stderr, "Error: Parse error of: %s\n", exprString.c_str()); exit(1); } ss.exprLT = sortExpr; formatstr(exprString, "MY.%s == TARGET.%s", ss.keyAttr.c_str(), ss.keyAttr.c_str()); if (ParseClassAdRvalExpr(exprString.c_str(), sortExpr)) { fprintf(stderr, "Error: Parse error of: %s\n", exprString.c_str()); exit(1); } ss.exprEQ = sortExpr; sortSpecs.push_back(ss); // the silent constraint TARGET.%s =!= UNDEFINED is added // as a customAND constraint on the second pass } else if (matchPrefix (argv[i], "-submitters", 5)) { setMode (MODE_SCHEDD_SUBMITTORS, i, argv[i]); } else if (matchPrefix (argv[i], "-master", 2)) { setMode (MODE_MASTER_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-collector", 4)) { setMode (MODE_COLLECTOR_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-world", 2)) { setMode (MODE_COLLECTOR_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-ckptsrvr", 3)) { setMode (MODE_CKPT_SRVR_NORMAL, i, argv[i]); } else if (matchPrefix (argv[i], "-total", 2)) { wantOnlyTotals = 1; explicit_format = true; } else if (matchPrefix(argv[i], "-expert", 2)) { expert = true; } else if (matchPrefix(argv[i], "-version", 4)) { printf( "%s\n%s\n", CondorVersion(), CondorPlatform() ); exit(0); } else if (*argv[i] == '-') { fprintf (stderr, "Error: Unknown option %s\n", argv[i]); usage (); exit (1); } } if( had_pool_error ) { fprintf( stderr, "Warning: Multiple -pool arguments given, using \"%s\"\n", pool->name() ); } if( had_direct_error ) { fprintf( stderr, "Warning: Multiple -direct arguments given, using \"%s\"\n", direct ); } if( had_statistics_error ) { fprintf( stderr, "Warning: Multiple -statistics arguments given, using \"%s\"\n", statistics ); } } void secondPass (int argc, char *argv[]) { const char * pcolon = NULL; char *daemonname; for (int i = 1; i < argc; i++) { // omit parameters which qualify switches if( matchPrefix(argv[i],"-pool", 2) || matchPrefix(argv[i],"-direct", 4) ) { i++; continue; } if( matchPrefix(argv[i],"-subsystem", 5) ) { i++; continue; } if (matchPrefix (argv[i], "-format", 2)) { pm.registerFormat (argv[i+1], argv[i+2]); StringList attributes; ClassAd ad; if(!ad.GetExprReferences(argv[i+2],attributes,attributes)){ fprintf( stderr, "Error: Parse error of: %s\n", argv[i+2]); exit(1); } attributes.rewind(); char const *s; while( (s=attributes.next()) ) { projList.AppendArg(s); } if (diagnose) { printf ("Arg %d --- register format [%s] for [%s]\n", i, argv[i+1], argv[i+2]); } i += 2; continue; } if (*argv[i] == '-' && (is_arg_colon_prefix(argv[i]+1, "autoformat", &pcolon, 5) || is_arg_colon_prefix(argv[i]+1, "af", &pcolon, 2)) ) { // make sure we have at least one more argument if ( !argv[i+1] || *(argv[i+1]) == '-') { fprintf( stderr, "Error: Argument %s requires " "at last one attribute parameter\n", argv[i] ); fprintf( stderr, "Use \"%s -help\" for details\n", myName ); exit( 1 ); } bool flabel = false; bool fCapV = false; bool fheadings = false; const char * pcolpre = " "; const char * pcolsux = NULL; if (pcolon) { ++pcolon; while (*pcolon) { switch (*pcolon) { case ',': pcolsux = ","; break; case 'n': pcolsux = "\n"; break; case 't': pcolpre = "\t"; break; case 'l': flabel = true; break; case 'V': fCapV = true; break; case 'h': fheadings = true; break; } ++pcolon; } } pm.SetAutoSep(NULL, pcolpre, pcolsux, "\n"); while (argv[i+1] && *(argv[i+1]) != '-') { ++i; ClassAd ad; StringList attributes; if(!ad.GetExprReferences(argv[i],attributes,attributes)){ fprintf( stderr, "Error: Parse error of: %s\n", argv[i]); exit(1); } attributes.rewind(); char const *s; while ((s = attributes.next())) { projList.AppendArg(s); } MyString lbl = ""; int wid = 0; int opts = FormatOptionNoTruncate; if (fheadings || pm_head.Length() > 0) { const char * hd = fheadings ? argv[i] : "(expr)"; wid = 0 - (int)strlen(hd); opts = FormatOptionAutoWidth | FormatOptionNoTruncate; pm_head.Append(hd); } else if (flabel) { lbl.formatstr("%s = ", argv[i]); wid = 0; opts = 0; } lbl += fCapV ? "%V" : "%v"; if (diagnose) { printf ("Arg %d --- register format [%s] width=%d, opt=0x%x for [%s]\n", i, lbl.Value(), wid, opts, argv[i]); } pm.registerFormat(lbl.Value(), wid, opts, argv[i]); } // if autoformat list ends in a '-' without any characters after it, just eat the arg and keep going. if (i+1 < argc && '-' == (argv[i+1])[0] && 0 == (argv[i+1])[1]) { ++i; } continue; } if (is_dash_arg_colon_prefix(argv[i], "print-format", &pcolon, 2)) { if ( (i+1 >= argc) || (*(argv[i+1]) == '-' && (argv[i+1])[1] != 0)) { fprintf( stderr, "Error: Argument -print-format requires a filename argument\n"); exit( 1 ); } // hack allow -pr ! to disable use of user-default print format files. if (MATCH == strcmp(argv[i+1], "!")) { ++i; disable_user_print_files = true; continue; } ppTotalStyle = ppStyle; setPPstyle (PP_CUSTOM, i, argv[i]); ++i; // skip to the next argument. if (set_status_print_mask_from_stream(argv[i], true, &mode_constraint) < 0) { fprintf(stderr, "Error: invalid select file %s\n", argv[i]); exit (1); } if (mode_constraint) { query->addANDConstraint(mode_constraint); } using_print_format = true; // so we can hack totals. continue; } if (matchPrefix (argv[i], "-target", 5)) { i++; continue; } if (is_dash_arg_prefix(argv[i], "ads", 2)) { ++i; continue; } if( matchPrefix(argv[i], "-sort", 3) ) { i++; if ( ! noSort) { sprintf( buffer, "%s =!= UNDEFINED", argv[i] ); query->addANDConstraint( buffer ); } continue; } if (matchPrefix (argv[i], "-statistics", 6)) { i += 2; sprintf(buffer,"STATISTICS_TO_PUBLISH = \"%s\"", statistics); if (diagnose) { printf ("[%s]\n", buffer); } query->addExtraAttribute(buffer); continue; } if (matchPrefix (argv[i], "-attributes", 3) ) { // parse attributes to be selected and split them along "," StringList more_attrs(argv[i+1],","); char const *s; more_attrs.rewind(); while( (s=more_attrs.next()) ) { projList.AppendArg(s); } i++; continue; } // figure out what the other parameters should do if (*argv[i] != '-') { // display extra information for diagnosis if (diagnose) { printf ("Arg %d (%s) --- adding constraint", i, argv[i]); } if( !(daemonname = get_daemon_name(argv[i])) ) { if ( (mode==MODE_SCHEDD_SUBMITTORS) && strchr(argv[i],'@') ) { // For a submittor query, it is possible that the // hostname is really a UID_DOMAIN. And there is // no requirement that UID_DOMAIN actually have // an inverse lookup in DNS... so if get_daemon_name() // fails with a fully qualified submittor lookup, just // use what we are given and do not flag an error. daemonname = strnewp(argv[i]); } else { dprintf_WriteOnErrorBuffer(stderr, true); fprintf( stderr, "%s: unknown host %s\n", argv[0], get_host_part(argv[i]) ); exit(1); } } switch (mode) { case MODE_DEFRAG_NORMAL: case MODE_STARTD_NORMAL: case MODE_STARTD_COD: #ifdef HAVE_EXT_POSTGRESQL case MODE_QUILL_NORMAL: #endif /* HAVE_EXT_POSTGRESQL */ case MODE_SCHEDD_NORMAL: case MODE_SCHEDD_SUBMITTORS: case MODE_MASTER_NORMAL: case MODE_COLLECTOR_NORMAL: case MODE_CKPT_SRVR_NORMAL: case MODE_NEGOTIATOR_NORMAL: case MODE_STORAGE_NORMAL: case MODE_ANY_NORMAL: case MODE_GENERIC_NORMAL: case MODE_STARTD_AVAIL: case MODE_OTHER: case MODE_GRID_NORMAL: case MODE_HAD_NORMAL: sprintf(buffer,"(%s==\"%s\") || (%s==\"%s\")", ATTR_NAME, daemonname, ATTR_MACHINE, daemonname ); if (diagnose) { printf ("[%s]\n", buffer); } query->addORConstraint (buffer); break; case MODE_STARTD_RUN: sprintf (buffer,"%s == \"%s\"",ATTR_REMOTE_USER,argv[i]); if (diagnose) { printf ("[%s]\n", buffer); } query->addORConstraint (buffer); break; default: fprintf(stderr,"Error: Don't know how to process %s\n",argv[i]); } delete [] daemonname; daemonname = NULL; } else if (matchPrefix (argv[i], "-constraint", 4)) { if (diagnose) { printf ("[%s]\n", argv[i+1]); } query->addANDConstraint (argv[i+1]); i++; } } } int matchPrefix (const char *s1, const char *s2, int min_len) { int lenS1 = strlen (s1); int lenS2 = strlen (s2); int len = (lenS1 < lenS2) ? lenS1 : lenS2; if(len < min_len) { return 0; } return (strncmp (s1, s2, len) == 0); } int lessThanFunc(AttrList *ad1, AttrList *ad2, void *) { MyString buf1; MyString buf2; int val; if( !ad1->LookupString(ATTR_OPSYS, buf1) || !ad2->LookupString(ATTR_OPSYS, buf2) ) { buf1 = ""; buf2 = ""; } val = strcmp( buf1.Value(), buf2.Value() ); if( val ) { return (val < 0); } if( !ad1->LookupString(ATTR_ARCH, buf1) || !ad2->LookupString(ATTR_ARCH, buf2) ) { buf1 = ""; buf2 = ""; } val = strcmp( buf1.Value(), buf2.Value() ); if( val ) { return (val < 0); } if( !ad1->LookupString(ATTR_MACHINE, buf1) || !ad2->LookupString(ATTR_MACHINE, buf2) ) { buf1 = ""; buf2 = ""; } val = strcmp( buf1.Value(), buf2.Value() ); if( val ) { return (val < 0); } if (!ad1->LookupString(ATTR_NAME, buf1) || !ad2->LookupString(ATTR_NAME, buf2)) return 0; return ( strcmp( buf1.Value(), buf2.Value() ) < 0 ); } int customLessThanFunc( AttrList *ad1, AttrList *ad2, void *) { classad::Value lt_result; bool val; for (unsigned i = 0; i < sortSpecs.size(); ++i) { if (EvalExprTree(sortSpecs[i].exprLT, ad1, ad2, lt_result) && lt_result.IsBooleanValue(val) ) { if( val ) { return 1; } else { if (EvalExprTree( sortSpecs[i].exprEQ, ad1, ad2, lt_result ) && ( !lt_result.IsBooleanValue(val) || !val )){ return 0; } } } else { return 0; } } return 0; }
zhangzhehust/htcondor
src/condor_status.V6/status.cpp
C++
apache-2.0
43,130
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entities; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Maarten De Weerdt */ @Entity @Table(name = "Product") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p") , @NamedQuery(name = "Product.findById", query = "SELECT p FROM Product p WHERE p.id = :id") , @NamedQuery(name = "Product.findByPrijs", query = "SELECT p FROM Product p WHERE p.prijs = :prijs") , @NamedQuery(name = "Product.findByCategorie", query = "SELECT p FROM Product p WHERE p.categorieNaam = :categorieNaam") }) public class Product implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "ID") private Integer id; @Basic(optional = false) @NotNull @Lob @Size(min = 1, max = 65535) @Column(name = "Naam") private String naam; @Basic(optional = false) @NotNull @Lob @Size(min = 1, max = 65535) @Column(name = "Omschrijving") private String omschrijving; @Basic(optional = false) @NotNull @Column(name = "Prijs") private double prijs; @Basic(optional = false) @NotNull @Lob @Size(min = 1, max = 65535) @Column(name = "Afbeelding") private String afbeelding; @Lob @Size(max = 65535) @Column(name = "Informatie") private String informatie; @JoinColumn(name = "CategorieNaam", referencedColumnName = "CategorieNaam") @ManyToOne(optional = false) private Categorie categorieNaam; public Product() { } public Product(Integer id) { this.id = id; } public Product(Integer id, String naam, String omschrijving, double prijs, String afbeelding) { this.id = id; this.naam = naam; this.omschrijving = omschrijving; this.prijs = prijs; this.afbeelding = afbeelding; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNaam() { return naam; } public void setNaam(String naam) { this.naam = naam; } public String getOmschrijving() { return omschrijving; } public void setOmschrijving(String omschrijving) { this.omschrijving = omschrijving; } public double getPrijs() { return prijs; } public void setPrijs(double prijs) { this.prijs = prijs; } public String getAfbeelding() { return afbeelding; } public void setAfbeelding(String afbeelding) { this.afbeelding = afbeelding; } public String getInformatie() { return informatie; } public void setInformatie(String informatie) { this.informatie = informatie; } public Categorie getCategorieNaam() { return categorieNaam; } public void setCategorieNaam(Categorie categorieNaam) { this.categorieNaam = categorieNaam; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Product)) { return false; } Product other = (Product) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "entities.Product[ id=" + id + " ]"; } }
MaartenDeWeerdt/TomEnJerry
TomEnJerry-ejb/src/java/entities/Product.java
Java
apache-2.0
4,620
/* * Copyright (C) 2018 The Dagger 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 dagger.internal.codegen.validation; import static com.google.auto.common.MoreTypes.asDeclared; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.in; import static com.google.common.collect.Collections2.transform; import static com.google.common.collect.Iterables.getOnlyElement; import static dagger.internal.codegen.base.ComponentAnnotation.rootComponentAnnotation; import static dagger.internal.codegen.base.DiagnosticFormatting.stripCommonTypePrefixes; import static dagger.internal.codegen.base.Formatter.INDENT; import static dagger.internal.codegen.base.Scopes.getReadableSource; import static dagger.internal.codegen.base.Scopes.scopesOf; import static dagger.internal.codegen.base.Scopes.singletonScope; import static dagger.internal.codegen.base.Util.reentrantComputeIfAbsent; import static dagger.internal.codegen.extension.DaggerStreams.toImmutableSet; import static dagger.internal.codegen.extension.DaggerStreams.toImmutableSetMultimap; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import static javax.tools.Diagnostic.Kind.ERROR; import com.google.auto.common.MoreElements; import com.google.auto.common.MoreTypes; import com.google.common.base.Equivalence.Wrapper; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.collect.Multimaps; import com.google.common.collect.Sets; import dagger.internal.codegen.binding.ComponentCreatorDescriptor; import dagger.internal.codegen.binding.ComponentDescriptor; import dagger.internal.codegen.binding.ComponentRequirement; import dagger.internal.codegen.binding.ComponentRequirement.NullPolicy; import dagger.internal.codegen.binding.ContributionBinding; import dagger.internal.codegen.binding.ErrorMessages; import dagger.internal.codegen.binding.ErrorMessages.ComponentCreatorMessages; import dagger.internal.codegen.binding.MethodSignatureFormatter; import dagger.internal.codegen.binding.ModuleDescriptor; import dagger.internal.codegen.compileroption.CompilerOptions; import dagger.internal.codegen.compileroption.ValidationType; import dagger.internal.codegen.langmodel.DaggerElements; import dagger.internal.codegen.langmodel.DaggerTypes; import dagger.model.Scope; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.StringJoiner; import javax.inject.Inject; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic; /** * Reports errors in the component hierarchy. * * <ul> * <li>Validates scope hierarchy of component dependencies and subcomponents. * <li>Reports errors if there are component dependency cycles. * <li>Reports errors if any abstract modules have non-abstract instance binding methods. * <li>Validates component creator types. * </ul> */ // TODO(dpb): Combine with ComponentHierarchyValidator. public final class ComponentDescriptorValidator { private final DaggerElements elements; private final DaggerTypes types; private final CompilerOptions compilerOptions; private final MethodSignatureFormatter methodSignatureFormatter; private final ComponentHierarchyValidator componentHierarchyValidator; @Inject ComponentDescriptorValidator( DaggerElements elements, DaggerTypes types, CompilerOptions compilerOptions, MethodSignatureFormatter methodSignatureFormatter, ComponentHierarchyValidator componentHierarchyValidator) { this.elements = elements; this.types = types; this.compilerOptions = compilerOptions; this.methodSignatureFormatter = methodSignatureFormatter; this.componentHierarchyValidator = componentHierarchyValidator; } public ValidationReport<TypeElement> validate(ComponentDescriptor component) { ComponentValidation validation = new ComponentValidation(component); validation.visitComponent(component); validation.report(component).addSubreport(componentHierarchyValidator.validate(component)); return validation.buildReport(); } private final class ComponentValidation { final ComponentDescriptor rootComponent; final Map<ComponentDescriptor, ValidationReport.Builder<TypeElement>> reports = new LinkedHashMap<>(); ComponentValidation(ComponentDescriptor rootComponent) { this.rootComponent = checkNotNull(rootComponent); } /** Returns a report that contains all validation messages found during traversal. */ ValidationReport<TypeElement> buildReport() { ValidationReport.Builder<TypeElement> report = ValidationReport.about(rootComponent.typeElement()); reports.values().forEach(subreport -> report.addSubreport(subreport.build())); return report.build(); } /** Returns the report builder for a (sub)component. */ private ValidationReport.Builder<TypeElement> report(ComponentDescriptor component) { return reentrantComputeIfAbsent( reports, component, descriptor -> ValidationReport.about(descriptor.typeElement())); } private void reportComponentItem( Diagnostic.Kind kind, ComponentDescriptor component, String message) { report(component) .addItem(message, kind, component.typeElement(), component.annotation().annotation()); } private void reportComponentError(ComponentDescriptor component, String error) { reportComponentItem(ERROR, component, error); } void visitComponent(ComponentDescriptor component) { validateDependencyScopes(component); validateComponentDependencyHierarchy(component); validateModules(component); validateCreators(component); component.childComponents().forEach(this::visitComponent); } /** Validates that component dependencies do not form a cycle. */ private void validateComponentDependencyHierarchy(ComponentDescriptor component) { validateComponentDependencyHierarchy(component, component.typeElement(), new ArrayDeque<>()); } /** Recursive method to validate that component dependencies do not form a cycle. */ private void validateComponentDependencyHierarchy( ComponentDescriptor component, TypeElement dependency, Deque<TypeElement> dependencyStack) { if (dependencyStack.contains(dependency)) { // Current component has already appeared in the component chain. StringBuilder message = new StringBuilder(); message.append(component.typeElement().getQualifiedName()); message.append(" contains a cycle in its component dependencies:\n"); dependencyStack.push(dependency); appendIndentedComponentsList(message, dependencyStack); dependencyStack.pop(); reportComponentItem( compilerOptions.scopeCycleValidationType().diagnosticKind().get(), component, message.toString()); } else { rootComponentAnnotation(dependency) .ifPresent( componentAnnotation -> { dependencyStack.push(dependency); for (TypeElement nextDependency : componentAnnotation.dependencies()) { validateComponentDependencyHierarchy( component, nextDependency, dependencyStack); } dependencyStack.pop(); }); } } /** * Validates that among the dependencies are at most one scoped dependency, that there are no * cycles within the scoping chain, and that singleton components have no scoped dependencies. */ private void validateDependencyScopes(ComponentDescriptor component) { ImmutableSet<Scope> scopes = component.scopes(); ImmutableSet<TypeElement> scopedDependencies = scopedTypesIn( component .dependencies() .stream() .map(ComponentRequirement::typeElement) .collect(toImmutableSet())); if (!scopes.isEmpty()) { Scope singletonScope = singletonScope(elements); // Dagger 1.x scope compatibility requires this be suppress-able. if (compilerOptions.scopeCycleValidationType().diagnosticKind().isPresent() && scopes.contains(singletonScope)) { // Singleton is a special-case representing the longest lifetime, and therefore // @Singleton components may not depend on scoped components if (!scopedDependencies.isEmpty()) { StringBuilder message = new StringBuilder( "This @Singleton component cannot depend on scoped components:\n"); appendIndentedComponentsList(message, scopedDependencies); reportComponentItem( compilerOptions.scopeCycleValidationType().diagnosticKind().get(), component, message.toString()); } } else if (scopedDependencies.size() > 1) { // Scoped components may depend on at most one scoped component. StringBuilder message = new StringBuilder(); for (Scope scope : scopes) { message.append(getReadableSource(scope)).append(' '); } message .append(component.typeElement().getQualifiedName()) .append(" depends on more than one scoped component:\n"); appendIndentedComponentsList(message, scopedDependencies); reportComponentError(component, message.toString()); } else { // Dagger 1.x scope compatibility requires this be suppress-able. if (!compilerOptions.scopeCycleValidationType().equals(ValidationType.NONE)) { validateDependencyScopeHierarchy( component, component.typeElement(), new ArrayDeque<>(), new ArrayDeque<>()); } } } else { // Scopeless components may not depend on scoped components. if (!scopedDependencies.isEmpty()) { StringBuilder message = new StringBuilder(component.typeElement().getQualifiedName()) .append(" (unscoped) cannot depend on scoped components:\n"); appendIndentedComponentsList(message, scopedDependencies); reportComponentError(component, message.toString()); } } } private void validateModules(ComponentDescriptor component) { for (ModuleDescriptor module : component.modules()) { if (module.moduleElement().getModifiers().contains(Modifier.ABSTRACT)) { for (ContributionBinding binding : module.bindings()) { if (binding.requiresModuleInstance()) { report(component).addError(abstractModuleHasInstanceBindingMethodsError(module)); break; } } } } } private String abstractModuleHasInstanceBindingMethodsError(ModuleDescriptor module) { String methodAnnotations; switch (module.kind()) { case MODULE: methodAnnotations = "@Provides"; break; case PRODUCER_MODULE: methodAnnotations = "@Provides or @Produces"; break; default: throw new AssertionError(module.kind()); } return String.format( "%s is abstract and has instance %s methods. Consider making the methods static or " + "including a non-abstract subclass of the module instead.", module.moduleElement(), methodAnnotations); } private void validateCreators(ComponentDescriptor component) { if (!component.creatorDescriptor().isPresent()) { // If no builder, nothing to validate. return; } ComponentCreatorDescriptor creator = component.creatorDescriptor().get(); ComponentCreatorMessages messages = ErrorMessages.creatorMessagesFor(creator.annotation()); // Requirements for modules and dependencies that the creator can set Set<ComponentRequirement> creatorModuleAndDependencyRequirements = creator.moduleAndDependencyRequirements(); // Modules and dependencies the component requires Set<ComponentRequirement> componentModuleAndDependencyRequirements = component.dependenciesAndConcreteModules(); // Requirements that the creator can set that don't match any requirements that the component // actually has. Set<ComponentRequirement> inapplicableRequirementsOnCreator = Sets.difference( creatorModuleAndDependencyRequirements, componentModuleAndDependencyRequirements); DeclaredType container = asDeclared(creator.typeElement().asType()); if (!inapplicableRequirementsOnCreator.isEmpty()) { Collection<Element> excessElements = Multimaps.filterKeys( creator.unvalidatedRequirementElements(), in(inapplicableRequirementsOnCreator)) .values(); String formatted = excessElements.stream() .map(element -> formatElement(element, container)) .collect(joining(", ", "[", "]")); report(component) .addError(String.format(messages.extraSetters(), formatted), creator.typeElement()); } // Component requirements that the creator must be able to set Set<ComponentRequirement> mustBePassed = Sets.filter( componentModuleAndDependencyRequirements, input -> input.nullPolicy(elements, types).equals(NullPolicy.THROW)); // Component requirements that the creator must be able to set, but can't Set<ComponentRequirement> missingRequirements = Sets.difference(mustBePassed, creatorModuleAndDependencyRequirements); if (!missingRequirements.isEmpty()) { report(component) .addError( String.format( messages.missingSetters(), missingRequirements.stream().map(ComponentRequirement::type).collect(toList())), creator.typeElement()); } // Validate that declared creator requirements (modules, dependencies) have unique types. ImmutableSetMultimap<Wrapper<TypeMirror>, Element> declaredRequirementsByType = Multimaps.filterKeys( creator.unvalidatedRequirementElements(), creatorModuleAndDependencyRequirements::contains) .entries().stream() .collect( toImmutableSetMultimap(entry -> entry.getKey().wrappedType(), Entry::getValue)); declaredRequirementsByType .asMap() .forEach( (typeWrapper, elementsForType) -> { if (elementsForType.size() > 1) { TypeMirror type = typeWrapper.get(); // TODO(cgdecker): Attach this error message to the factory method rather than // the component type if the elements are factory method parameters AND the // factory method is defined by the factory type itself and not by a supertype. report(component) .addError( String.format( messages.multipleSettersForModuleOrDependencyType(), type, transform( elementsForType, element -> formatElement(element, container))), creator.typeElement()); } }); // TODO(cgdecker): Duplicate binding validation should handle the case of multiple elements // that set the same bound-instance Key, but validating that here would make it fail faster // for subcomponents. } private String formatElement(Element element, DeclaredType container) { // TODO(cgdecker): Extract some or all of this to another class? // But note that it does different formatting for parameters than // DaggerElements.elementToString(Element). switch (element.getKind()) { case METHOD: return methodSignatureFormatter.format( MoreElements.asExecutable(element), Optional.of(container)); case PARAMETER: return formatParameter(MoreElements.asVariable(element), container); default: // This method shouldn't be called with any other type of element. throw new AssertionError(); } } private String formatParameter(VariableElement parameter, DeclaredType container) { // TODO(cgdecker): Possibly leave the type (and annotations?) off of the parameters here and // just use their names, since the type will be redundant in the context of the error message. StringJoiner joiner = new StringJoiner(" "); parameter.getAnnotationMirrors().stream().map(Object::toString).forEach(joiner::add); TypeMirror parameterType = resolveParameterType(parameter, container); return joiner .add(stripCommonTypePrefixes(parameterType.toString())) .add(parameter.getSimpleName()) .toString(); } private TypeMirror resolveParameterType(VariableElement parameter, DeclaredType container) { ExecutableElement method = MoreElements.asExecutable(parameter.getEnclosingElement()); int parameterIndex = method.getParameters().indexOf(parameter); ExecutableType methodType = MoreTypes.asExecutable(types.asMemberOf(container, method)); return methodType.getParameterTypes().get(parameterIndex); } /** * Validates that scopes do not participate in a scoping cycle - that is to say, scoped * components are in a hierarchical relationship terminating with Singleton. * * <p>As a side-effect, this means scoped components cannot have a dependency cycle between * themselves, since a component's presence within its own dependency path implies a cyclical * relationship between scopes. However, cycles in component dependencies are explicitly checked * in {@link #validateComponentDependencyHierarchy(ComponentDescriptor)}. */ private void validateDependencyScopeHierarchy( ComponentDescriptor component, TypeElement dependency, Deque<ImmutableSet<Scope>> scopeStack, Deque<TypeElement> scopedDependencyStack) { ImmutableSet<Scope> scopes = scopesOf(dependency); if (stackOverlaps(scopeStack, scopes)) { scopedDependencyStack.push(dependency); // Current scope has already appeared in the component chain. StringBuilder message = new StringBuilder(); message.append(component.typeElement().getQualifiedName()); message.append(" depends on scoped components in a non-hierarchical scope ordering:\n"); appendIndentedComponentsList(message, scopedDependencyStack); if (compilerOptions.scopeCycleValidationType().diagnosticKind().isPresent()) { reportComponentItem( compilerOptions.scopeCycleValidationType().diagnosticKind().get(), component, message.toString()); } scopedDependencyStack.pop(); } else { // TODO(beder): transitively check scopes of production components too. rootComponentAnnotation(dependency) .filter(componentAnnotation -> !componentAnnotation.isProduction()) .ifPresent( componentAnnotation -> { ImmutableSet<TypeElement> scopedDependencies = scopedTypesIn(componentAnnotation.dependencies()); if (scopedDependencies.size() == 1) { // empty can be ignored (base-case), and > 1 is a separately-reported error. scopeStack.push(scopes); scopedDependencyStack.push(dependency); validateDependencyScopeHierarchy( component, getOnlyElement(scopedDependencies), scopeStack, scopedDependencyStack); scopedDependencyStack.pop(); scopeStack.pop(); } }); // else: we skip component dependencies which are not components } } private <T> boolean stackOverlaps(Deque<ImmutableSet<T>> stack, ImmutableSet<T> set) { for (ImmutableSet<T> entry : stack) { if (!Sets.intersection(entry, set).isEmpty()) { return true; } } return false; } /** Appends and formats a list of indented component types (with their scope annotations). */ private void appendIndentedComponentsList(StringBuilder message, Iterable<TypeElement> types) { for (TypeElement scopedComponent : types) { message.append(INDENT); for (Scope scope : scopesOf(scopedComponent)) { message.append(getReadableSource(scope)).append(' '); } message .append(stripCommonTypePrefixes(scopedComponent.getQualifiedName().toString())) .append('\n'); } } /** * Returns a set of type elements containing only those found in the input set that have a * scoping annotation. */ private ImmutableSet<TypeElement> scopedTypesIn(Collection<TypeElement> types) { return types.stream().filter(type -> !scopesOf(type).isEmpty()).collect(toImmutableSet()); } } }
cgruber/dagger
java/dagger/internal/codegen/validation/ComponentDescriptorValidator.java
Java
apache-2.0
22,500
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace ungarc0r { static class Program { /// <summary> /// Der Haupteinstiegspunkt für die Anwendung. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
manuth/ungarc0r
GameArchiver/Program.cs
C#
apache-2.0
511
import errno import os import pwd import shutil import sys from jinja2 import Environment, FileSystemLoader class TutorialEnv: LOCAL_MACHINE = ("Local Machine Condor Pool", "submit-host") USC_HPCC_CLUSTER = ("USC HPCC Cluster", "usc-hpcc") OSG_FROM_ISI = ("OSG from ISI submit node", "osg") XSEDE_BOSCO = ("XSEDE, with Bosco", "xsede-bosco") BLUEWATERS_GLITE = ("Bluewaters, with Glite", "bw-glite") TACC_WRANGLER = ("TACC Wrangler with Glite", "wrangler-glite") OLCF_TITAN = ("OLCF TITAN with Glite", "titan-glite") OLCF_SUMMIT_KUBERNETES_BOSCO = ( "OLCF Summit from Kubernetes using BOSCO", "summit-kub-bosco", ) class TutorialExample: PROCESS = ("Process", "process") PIPELINE = ("Pipeline", "pipeline") SPLIT = ("Split", "split") MERGE = ("Merge", "merge") EPA = ("EPA (requires R)", "r-epa") DIAMOND = ("Diamond", "diamond") CONTAINER = ("Population Modeling using Containers", "population") MPI = ("MPI Hello World", "mpi-hw") def choice(question, options, default): "Ask the user to choose from a short list of named options" while True: sys.stdout.write("{} ({}) [{}]: ".format(question, "/".join(options), default)) answer = sys.stdin.readline().strip() if len(answer) == 0: return default for opt in options: if answer == opt: return answer def yesno(question, default="y"): "Ask the user a yes/no question" while True: sys.stdout.write("{} (y/n) [{}]: ".format(question, default)) answer = sys.stdin.readline().strip().lower() if len(answer) == 0: answer = default if answer == "y": return True elif answer == "n": return False def query(question, default=None): "Ask the user a question and return the response" while True: if default: sys.stdout.write("{} [{}]: ".format(question, default)) else: sys.stdout.write("%s: " % question) answer = sys.stdin.readline().strip().replace(" ", "_") if answer == "": if default: return default else: return answer def optionlist(question, options, default=0): "Ask the user to choose from a list of options" for i, option in enumerate(options): print("%d: %s" % (i + 1, option[0])) while True: sys.stdout.write("%s (1-%d) [%d]: " % (question, len(options), default + 1)) answer = sys.stdin.readline().strip() if len(answer) == 0: return options[default][1] try: optno = int(answer) if optno > 0 and optno <= len(options): return options[optno - 1][1] except Exception: pass class Workflow: def __init__(self, workflowdir, sharedir): self.jinja = Environment(loader=FileSystemLoader(sharedir), trim_blocks=True) self.name = os.path.basename(workflowdir) self.workflowdir = workflowdir self.sharedir = sharedir self.properties = {} self.home = os.environ["HOME"] self.user = pwd.getpwuid(os.getuid())[0] self.tutorial = None self.generate_tutorial = False self.tutorial_setup = None self.compute_queue = "default" self.project = "MYPROJ123" sysname, _, _, _, machine = os.uname() if sysname == "Darwin": self.os = "MACOSX" else: # Probably Linux self.os = sysname.upper() self.arch = machine def copy_template(self, template, dest, mode=0o644): "Copy template to dest in workflowdir with mode" path = os.path.join(self.workflowdir, dest) t = self.jinja.get_template(template) t.stream(**self.__dict__).dump(path) os.chmod(path, mode) def copy_dir(self, src, dest): # self.mkdir(dest) if not src.startswith("/"): src = os.path.join(self.sharedir, src) try: dest = os.path.join(self.workflowdir, dest) shutil.copytree(src, dest) except OSError as exc: # python >2.5 if exc.errno == errno.ENOTDIR: shutil.copy(src, dest) else: raise def mkdir(self, path): "Make relative directory in workflowdir" path = os.path.join(self.workflowdir, path) if not os.path.exists(path): os.makedirs(path) def configure(self): # The tutorial is a special case if yesno("Do you want to generate a tutorial workflow?", "n"): self.config = "tutorial" self.daxgen = "tutorial" self.generate_tutorial = True # determine the environment to setup tutorial for self.tutorial_setup = optionlist( "What environment is tutorial to be setup for?", [ TutorialEnv.LOCAL_MACHINE, TutorialEnv.USC_HPCC_CLUSTER, TutorialEnv.OSG_FROM_ISI, TutorialEnv.XSEDE_BOSCO, TutorialEnv.BLUEWATERS_GLITE, TutorialEnv.TACC_WRANGLER, TutorialEnv.OLCF_TITAN, TutorialEnv.OLCF_SUMMIT_KUBERNETES_BOSCO, ], ) # figure out what example options to provide examples = [ TutorialExample.PROCESS, TutorialExample.PIPELINE, TutorialExample.SPLIT, TutorialExample.MERGE, TutorialExample.EPA, TutorialExample.CONTAINER, ] if self.tutorial_setup != "osg": examples.append(TutorialExample.DIAMOND) if self.tutorial_setup in [ "bw-glite", "wrangler-glite", "titan-glite", "summit-kub-bosco", ]: examples.append(TutorialExample.MPI) self.project = query( "What project your jobs should run under. For example on TACC there are like : TG-DDM160003 ?" ) self.tutorial = optionlist("What tutorial workflow do you want?", examples) self.setup_tutorial() return # Determine which DAX generator API to use self.daxgen = choice( "What DAX generator API do you want to use?", ["python", "perl", "java", "r"], "python", ) # Determine what kind of site catalog we need to generate self.config = optionlist( "What does your computing infrastructure look like?", [ ("Local Machine Condor Pool", "condorpool"), ("Remote Cluster using Globus GRAM", "globus"), ("Remote Cluster using CREAMCE", "creamce"), ("Local PBS Cluster with Glite", "glite"), ("Remote PBS Cluster with BOSCO and SSH", "bosco"), ], ) # Find out some information about the site self.sitename = query("What do you want to call your compute site?", "compute") self.os = choice( "What OS does your compute site have?", ["LINUX", "MACOSX"], self.os ) self.arch = choice( "What architecture does your compute site have?", ["x86_64", "x86"], self.arch, ) def setup_tutorial(self): """ Set up tutorial for pre-defined computing environments :return: """ if self.tutorial_setup is None: self.tutorial_setup = "submit-host" if self.tutorial_setup == "submit-host": self.sitename = "condorpool" elif self.tutorial_setup == "usc-hpcc": self.sitename = "usc-hpcc" self.config = "glite" self.compute_queue = "quick" # for running the whole workflow as mpi job self.properties["pegasus.job.aggregator"] = "mpiexec" elif self.tutorial_setup == "osg": self.sitename = "osg" self.os = "linux" if not yesno("Do you want to use Condor file transfers", "y"): self.staging_site = "isi_workflow" elif self.tutorial_setup == "xsede-bosco": self.sitename = "condorpool" elif self.tutorial_setup == "bw-glite": self.sitename = "bluewaters" self.config = "glite" self.compute_queue = "normal" elif self.tutorial_setup == "wrangler-glite": self.sitename = "wrangler" self.config = "glite" self.compute_queue = "normal" elif self.tutorial_setup == "titan-glite": self.sitename = "titan" self.config = "glite" self.compute_queue = "titan" elif self.tutorial_setup == "summit-kub-bosco": self.sitename = "summit" self.config = "bosco" self.compute_queue = "batch" return def generate(self): os.makedirs(self.workflowdir) if self.tutorial != "population": self.mkdir("input") self.mkdir("output") if self.generate_tutorial: self.copy_template("%s/tc.txt" % self.tutorial, "tc.txt") if self.tutorial == "r-epa": self.copy_template("%s/daxgen.R" % self.tutorial, "daxgen.R") elif self.tutorial != "mpi-hw": self.copy_template("%s/daxgen.py" % self.tutorial, "daxgen.py") if self.tutorial == "diamond": # Executables used by the diamond workflow self.mkdir("bin") self.copy_template( "diamond/transformation.py", "bin/preprocess", mode=0o755 ) self.copy_template( "diamond/transformation.py", "bin/findrange", mode=0o755 ) self.copy_template( "diamond/transformation.py", "bin/analyze", mode=0o755 ) # Diamond input file self.copy_template("diamond/f.a", "input/f.a") elif self.tutorial == "split": # Split workflow input file self.mkdir("bin") self.copy_template("split/pegasus.html", "input/pegasus.html") elif self.tutorial == "r-epa": # Executables used by the R-EPA workflow self.mkdir("bin") self.copy_template( "r-epa/epa-wrapper.sh", "bin/epa-wrapper.sh", mode=0o755 ) self.copy_template("r-epa/setupvar.R", "bin/setupvar.R", mode=0o755) self.copy_template( "r-epa/weighted.average.R", "bin/weighted.average.R", mode=0o755 ) self.copy_template( "r-epa/cumulative.percentiles.R", "bin/cumulative.percentiles.R", mode=0o755, ) elif self.tutorial == "population": self.copy_template("%s/Dockerfile" % self.tutorial, "Dockerfile") self.copy_template("%s/Singularity" % self.tutorial, "Singularity") self.copy_template( "%s/tc.txt.containers" % self.tutorial, "tc.txt.containers" ) self.copy_dir("%s/scripts" % self.tutorial, "scripts") self.copy_dir("%s/data" % self.tutorial, "input") # copy the mpi wrapper, c code and mpi elif self.tutorial == "mpi-hw": # copy the mpi wrapper, c code and mpi example # Executables used by the mpi-hw workflow self.mkdir("bin") self.copy_template( "%s/pegasus-mpi-hw.c" % self.tutorial, "pegasus-mpi-hw.c" ) self.copy_template("%s/Makefile" % self.tutorial, "Makefile") self.copy_template("%s/daxgen.py.template" % self.tutorial, "daxgen.py") self.copy_template( "%s/mpi-hello-world-wrapper" % self.tutorial, "bin/mpi-hello-world-wrapper", mode=0o755, ) self.copy_template("split/pegasus.html", "input/f.in") else: self.copy_template("tc.txt", "tc.txt") if self.daxgen == "python": self.copy_template("daxgen/daxgen.py", "daxgen.py") elif self.daxgen == "perl": self.copy_template("daxgen/daxgen.pl", "daxgen.pl") elif self.daxgen == "java": self.copy_template("daxgen/DAXGen.java", "DAXGen.java") elif self.daxgen == "r": self.copy_template("daxgen/daxgen.R", "daxgen.R") else: assert False self.copy_template("sites.xml", "sites.xml") self.copy_template("plan_dax.sh", "plan_dax.sh", mode=0o755) self.copy_template("plan_cluster_dax.sh", "plan_cluster_dax.sh", mode=0o755) self.copy_template("generate_dax.sh", "generate_dax.sh", mode=0o755) self.copy_template("README.md", "README.md") self.copy_template("rc.txt", "rc.txt") self.copy_template("pegasus.properties", "pegasus.properties") if self.tutorial == "diamond": if self.tutorial_setup == "wrangler-glite": self.copy_template( "pmc-wrapper.wrangler", "bin/pmc-wrapper", mode=0o755 ) elif self.tutorial_setup == "titan-glite": self.copy_template("pmc-wrapper.titan", "bin/pmc-wrapper", mode=0o755) elif self.tutorial_setup == "wrangler-glite": self.copy_template( "pmc-wrapper.wrangler", "bin/pmc-wrapper", mode=0o755 ) elif self.tutorial_setup == "summit-kub-bosco": self.copy_template("pmc-wrapper.summit", "bin/pmc-wrapper", mode=0o755) if self.generate_tutorial: sys.stdout.write( "Pegasus Tutorial setup for example workflow - %s for execution on %s in directory %s\n" % (self.tutorial, self.tutorial_setup, self.workflowdir) ) def usage(): print("Usage: %s WORKFLOW_DIR" % sys.argv[0]) def main(pegasus_share_dir): if len(sys.argv) != 2: usage() exit(1) if "-h" in sys.argv: usage() exit(1) workflowdir = sys.argv[1] if os.path.exists(workflowdir): print("ERROR: WORKFLOW_DIR '%s' already exists" % workflowdir) exit(1) workflowdir = os.path.abspath(workflowdir) sharedir = os.path.join(pegasus_share_dir, "init") w = Workflow(workflowdir, sharedir) w.configure() w.generate()
pegasus-isi/pegasus
packages/pegasus-python/src/Pegasus/init-old.py
Python
apache-2.0
14,973
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V10.Resources; namespace Google.Ads.GoogleAds.V10.Services { public partial class BiddingDataExclusionOperation { /// <summary> /// <see cref="gagvr::BiddingDataExclusionName"/>-typed view over the <see cref="Remove"/> resource name /// property. /// </summary> public gagvr::BiddingDataExclusionName RemoveAsBiddingDataExclusionName { get => string.IsNullOrEmpty(Remove) ? null : gagvr::BiddingDataExclusionName.Parse(Remove, allowUnparsed: true); set => Remove = value?.ToString() ?? ""; } } public partial class MutateBiddingDataExclusionsResult { /// <summary> /// <see cref="gagvr::BiddingDataExclusionName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> public gagvr::BiddingDataExclusionName ResourceNameAsBiddingDataExclusionName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::BiddingDataExclusionName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
googleads/google-ads-dotnet
src/V10/Services/BiddingDataExclusionServiceResourceNames.g.cs
C#
apache-2.0
1,806
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.route53.model.transform; import java.util.ArrayList; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.route53.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * GetHealthCheckLastFailureReasonResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetHealthCheckLastFailureReasonResultStaxUnmarshaller implements Unmarshaller<GetHealthCheckLastFailureReasonResult, StaxUnmarshallerContext> { public GetHealthCheckLastFailureReasonResult unmarshall(StaxUnmarshallerContext context) throws Exception { GetHealthCheckLastFailureReasonResult getHealthCheckLastFailureReasonResult = new GetHealthCheckLastFailureReasonResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return getHealthCheckLastFailureReasonResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("HealthCheckObservations", targetDepth)) { getHealthCheckLastFailureReasonResult.withHealthCheckObservations(new ArrayList<HealthCheckObservation>()); continue; } if (context.testExpression("HealthCheckObservations/HealthCheckObservation", targetDepth)) { getHealthCheckLastFailureReasonResult.withHealthCheckObservations(HealthCheckObservationStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return getHealthCheckLastFailureReasonResult; } } } } private static GetHealthCheckLastFailureReasonResultStaxUnmarshaller instance; public static GetHealthCheckLastFailureReasonResultStaxUnmarshaller getInstance() { if (instance == null) instance = new GetHealthCheckLastFailureReasonResultStaxUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-route53/src/main/java/com/amazonaws/services/route53/model/transform/GetHealthCheckLastFailureReasonResultStaxUnmarshaller.java
Java
apache-2.0
3,038
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.cache.store.jdbc; import java.nio.ByteBuffer; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.cache.Cache; import javax.cache.CacheException; import javax.cache.integration.CacheLoaderException; import javax.cache.integration.CacheWriterException; import javax.sql.DataSource; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.IgniteException; import org.apache.ignite.IgniteLogger; import org.apache.ignite.cache.CacheTypeFieldMetadata; import org.apache.ignite.cache.CacheTypeMetadata; import org.apache.ignite.cache.store.CacheStore; import org.apache.ignite.cache.store.CacheStoreSession; import org.apache.ignite.cache.store.jdbc.dialect.BasicJdbcDialect; import org.apache.ignite.cache.store.jdbc.dialect.DB2Dialect; import org.apache.ignite.cache.store.jdbc.dialect.H2Dialect; import org.apache.ignite.cache.store.jdbc.dialect.JdbcDialect; import org.apache.ignite.cache.store.jdbc.dialect.MySQLDialect; import org.apache.ignite.cache.store.jdbc.dialect.OracleDialect; import org.apache.ignite.cache.store.jdbc.dialect.SQLServerDialect; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.internal.util.tostring.GridToStringExclude; import org.apache.ignite.internal.util.typedef.C1; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgniteBiInClosure; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.lifecycle.LifecycleAware; import org.apache.ignite.resources.CacheStoreSessionResource; import org.apache.ignite.resources.IgniteInstanceResource; import org.apache.ignite.resources.LoggerResource; import org.apache.ignite.transactions.Transaction; import org.jetbrains.annotations.Nullable; import static java.sql.Statement.EXECUTE_FAILED; import static java.sql.Statement.SUCCESS_NO_INFO; /** * Implementation of {@link CacheStore} backed by JDBC. * <p> * Store works with database via SQL dialect. Ignite ships with dialects for most popular databases: * <ul> * <li>{@link DB2Dialect} - dialect for IBM DB2 database.</li> * <li>{@link OracleDialect} - dialect for Oracle database.</li> * <li>{@link SQLServerDialect} - dialect for Microsoft SQL Server database.</li> * <li>{@link MySQLDialect} - dialect for Oracle MySQL database.</li> * <li>{@link H2Dialect} - dialect for H2 database.</li> * <li>{@link BasicJdbcDialect} - dialect for any database via plain JDBC.</li> * </ul> * <p> * <h2 class="header">Configuration</h2> * <ul> * <li>Data source (see {@link #setDataSource(DataSource)}</li> * <li>Dialect (see {@link #setDialect(JdbcDialect)}</li> * <li>Maximum batch size for writeAll and deleteAll operations. (see {@link #setBatchSize(int)})</li> * <li>Max workers thread count. These threads are responsible for load cache. (see {@link #setMaximumPoolSize(int)})</li> * <li>Parallel load cache minimum threshold. (see {@link #setParallelLoadCacheMinimumThreshold(int)})</li> * </ul> * <h2 class="header">Java Example</h2> * <pre name="code" class="java"> * ... * CacheConfiguration ccfg = new CacheConfiguration&lt;&gt;(); * * // Configure cache store. * ccfg.setCacheStoreFactory(new FactoryBuilder.SingletonFactory(ConfigurationSnippet.store())); * ccfg.setReadThrough(true); * ccfg.setWriteThrough(true); * * // Configure cache types metadata. * ccfg.setTypeMetadata(ConfigurationSnippet.typeMetadata()); * * cfg.setCacheConfiguration(ccfg); * ... * </pre> */ public abstract class CacheAbstractJdbcStore<K, V> implements CacheStore<K, V>, LifecycleAware { /** Max attempt write count. */ protected static final int MAX_ATTEMPT_WRITE_COUNT = 2; /** Default batch size for put and remove operations. */ protected static final int DFLT_BATCH_SIZE = 512; /** Default batch size for put and remove operations. */ protected static final int DFLT_PARALLEL_LOAD_CACHE_MINIMUM_THRESHOLD = 512; /** Connection attribute property name. */ protected static final String ATTR_CONN_PROP = "JDBC_STORE_CONNECTION"; /** Empty column value. */ protected static final Object[] EMPTY_COLUMN_VALUE = new Object[] { null }; /** Auto-injected store session. */ @CacheStoreSessionResource private CacheStoreSession ses; /** Auto injected ignite instance. */ @IgniteInstanceResource private Ignite ignite; /** Auto-injected logger instance. */ @LoggerResource protected IgniteLogger log; /** Lock for metadata cache. */ @GridToStringExclude private final Lock cacheMappingsLock = new ReentrantLock(); /** Data source. */ protected DataSource dataSrc; /** Cache with entry mapping description. (cache name, (key id, mapping description)). */ protected volatile Map<String, Map<Object, EntryMapping>> cacheMappings = Collections.emptyMap(); /** Database dialect. */ protected JdbcDialect dialect; /** Max workers thread count. These threads are responsible for load cache. */ private int maxPoolSz = Runtime.getRuntime().availableProcessors(); /** Maximum batch size for writeAll and deleteAll operations. */ private int batchSz = DFLT_BATCH_SIZE; /** Parallel load cache minimum threshold. If {@code 0} then load sequentially. */ private int parallelLoadCacheMinThreshold = DFLT_PARALLEL_LOAD_CACHE_MINIMUM_THRESHOLD; /** * Get field value from object for use as query parameter. * * @param cacheName Cache name. * @param typeName Type name. * @param fieldName Field name. * @param obj Cache object. * @return Field value from object. * @throws CacheException in case of error. */ @Nullable protected abstract Object extractParameter(@Nullable String cacheName, String typeName, String fieldName, Object obj) throws CacheException; /** * Construct object from query result. * * @param <R> Type of result object. * @param cacheName Cache name. * @param typeName Type name. * @param fields Fields descriptors. * @param loadColIdxs Select query columns index. * @param rs ResultSet. * @return Constructed object. * @throws CacheLoaderException If failed to construct cache object. */ protected abstract <R> R buildObject(@Nullable String cacheName, String typeName, Collection<CacheTypeFieldMetadata> fields, Map<String, Integer> loadColIdxs, ResultSet rs) throws CacheLoaderException; /** * Extract key type id from key object. * * @param key Key object. * @return Key type id. * @throws CacheException If failed to get type key id from object. */ protected abstract Object keyTypeId(Object key) throws CacheException; /** * Extract key type id from key class name. * * @param type String description of key type. * @return Key type id. * @throws CacheException If failed to get type key id from object. */ protected abstract Object keyTypeId(String type) throws CacheException; /** * Prepare internal store specific builders for provided types metadata. * * @param cacheName Cache name to prepare builders for. * @param types Collection of types. * @throws CacheException If failed to prepare internal builders for types. */ protected abstract void prepareBuilders(@Nullable String cacheName, Collection<CacheTypeMetadata> types) throws CacheException; /** * Perform dialect resolution. * * @return The resolved dialect. * @throws CacheException Indicates problems accessing the metadata. */ protected JdbcDialect resolveDialect() throws CacheException { Connection conn = null; String dbProductName = null; try { conn = openConnection(false); dbProductName = conn.getMetaData().getDatabaseProductName(); } catch (SQLException e) { throw new CacheException("Failed access to metadata for detect database dialect.", e); } finally { U.closeQuiet(conn); } if ("H2".equals(dbProductName)) return new H2Dialect(); if ("MySQL".equals(dbProductName)) return new MySQLDialect(); if (dbProductName.startsWith("Microsoft SQL Server")) return new SQLServerDialect(); if ("Oracle".equals(dbProductName)) return new OracleDialect(); if (dbProductName.startsWith("DB2/")) return new DB2Dialect(); U.warn(log, "Failed to resolve dialect (BasicJdbcDialect will be used): " + dbProductName); return new BasicJdbcDialect(); } /** {@inheritDoc} */ @Override public void start() throws IgniteException { if (dataSrc == null) throw new IgniteException("Failed to initialize cache store (data source is not provided)."); if (dialect == null) { dialect = resolveDialect(); if (log.isDebugEnabled() && dialect.getClass() != BasicJdbcDialect.class) log.debug("Resolved database dialect: " + U.getSimpleName(dialect.getClass())); } } /** {@inheritDoc} */ @Override public void stop() throws IgniteException { // No-op. } /** * Gets connection from a pool. * * @param autocommit {@code true} If connection should use autocommit mode. * @return Pooled connection. * @throws SQLException In case of error. */ protected Connection openConnection(boolean autocommit) throws SQLException { Connection conn = dataSrc.getConnection(); conn.setAutoCommit(autocommit); return conn; } /** * @return Connection. * @throws SQLException In case of error. */ protected Connection connection() throws SQLException { CacheStoreSession ses = session(); if (ses.transaction() != null) { Map<String, Connection> prop = ses.properties(); Connection conn = prop.get(ATTR_CONN_PROP); if (conn == null) { conn = openConnection(false); // Store connection in session to used it for other operations in the same session. prop.put(ATTR_CONN_PROP, conn); } return conn; } // Transaction can be null in case of simple load operation. else return openConnection(true); } /** * Closes connection. * * @param conn Connection to close. */ protected void closeConnection(@Nullable Connection conn) { CacheStoreSession ses = session(); // Close connection right away if there is no transaction. if (ses.transaction() == null) U.closeQuiet(conn); } /** * Closes allocated resources depending on transaction status. * * @param conn Allocated connection. * @param st Created statement, */ protected void end(@Nullable Connection conn, @Nullable Statement st) { U.closeQuiet(st); closeConnection(conn); } /** {@inheritDoc} */ @Override public void sessionEnd(boolean commit) throws CacheWriterException { CacheStoreSession ses = session(); Transaction tx = ses.transaction(); if (tx != null) { Map<String, Connection> sesProps = ses.properties(); Connection conn = sesProps.get(ATTR_CONN_PROP); if (conn != null) { sesProps.remove(ATTR_CONN_PROP); try { if (commit) conn.commit(); else conn.rollback(); } catch (SQLException e) { throw new CacheWriterException( "Failed to end transaction [xid=" + tx.xid() + ", commit=" + commit + ']', e); } finally { U.closeQuiet(conn); } } if (log.isDebugEnabled()) log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']'); } } /** * Retrieves the value of the designated column in the current row of this <code>ResultSet</code> object and * will convert to the requested Java data type. * * @param rs Result set. * @param colIdx Column index in result set. * @param type Class representing the Java data type to convert the designated column to. * @return Value in column. * @throws SQLException If a database access error occurs or this method is called. */ protected Object getColumnValue(ResultSet rs, int colIdx, Class<?> type) throws SQLException { Object val = rs.getObject(colIdx); if (val == null) return null; if (type == int.class) return rs.getInt(colIdx); if (type == long.class) return rs.getLong(colIdx); if (type == double.class) return rs.getDouble(colIdx); if (type == boolean.class || type == Boolean.class) return rs.getBoolean(colIdx); if (type == byte.class) return rs.getByte(colIdx); if (type == short.class) return rs.getShort(colIdx); if (type == float.class) return rs.getFloat(colIdx); if (type == Integer.class || type == Long.class || type == Double.class || type == Byte.class || type == Short.class || type == Float.class) { Number num = (Number)val; if (type == Integer.class) return num.intValue(); else if (type == Long.class) return num.longValue(); else if (type == Double.class) return num.doubleValue(); else if (type == Byte.class) return num.byteValue(); else if (type == Short.class) return num.shortValue(); else if (type == Float.class) return num.floatValue(); } if (type == UUID.class) { if (val instanceof UUID) return val; if (val instanceof byte[]) { ByteBuffer bb = ByteBuffer.wrap((byte[])val); long most = bb.getLong(); long least = bb.getLong(); return new UUID(most, least); } if (val instanceof String) return UUID.fromString((String)val); } return val; } /** * Construct load cache from range. * * @param em Type mapping description. * @param clo Closure that will be applied to loaded values. * @param lowerBound Lower bound for range. * @param upperBound Upper bound for range. * @return Callable for pool submit. */ private Callable<Void> loadCacheRange(final EntryMapping em, final IgniteBiInClosure<K, V> clo, @Nullable final Object[] lowerBound, @Nullable final Object[] upperBound) { return new Callable<Void>() { @Override public Void call() throws Exception { Connection conn = null; PreparedStatement stmt = null; try { conn = openConnection(true); stmt = conn.prepareStatement(lowerBound == null && upperBound == null ? em.loadCacheQry : em.loadCacheRangeQuery(lowerBound != null, upperBound != null)); int ix = 1; if (lowerBound != null) for (int i = lowerBound.length; i > 0; i--) for (int j = 0; j < i; j++) stmt.setObject(ix++, lowerBound[j]); if (upperBound != null) for (int i = upperBound.length; i > 0; i--) for (int j = 0; j < i; j++) stmt.setObject(ix++, upperBound[j]); ResultSet rs = stmt.executeQuery(); while (rs.next()) { K key = buildObject(em.cacheName, em.keyType(), em.keyColumns(), em.loadColIdxs, rs); V val = buildObject(em.cacheName, em.valueType(), em.valueColumns(), em.loadColIdxs, rs); clo.apply(key, val); } } catch (SQLException e) { throw new IgniteCheckedException("Failed to load cache", e); } finally { U.closeQuiet(stmt); U.closeQuiet(conn); } return null; } }; } /** * Construct load cache in one select. * * @param m Type mapping description. * @param clo Closure for loaded values. * @return Callable for pool submit. */ private Callable<Void> loadCacheFull(EntryMapping m, IgniteBiInClosure<K, V> clo) { return loadCacheRange(m, clo, null, null); } /** * Object is a simple type. * * @param cls Class. * @return {@code True} if object is a simple type. */ protected static boolean simpleType(Class<?> cls) { return (Number.class.isAssignableFrom(cls) || String.class.isAssignableFrom(cls) || java.util.Date.class.isAssignableFrom(cls) || Boolean.class.isAssignableFrom(cls) || UUID.class.isAssignableFrom(cls)); } /** * @param cacheName Cache name to check mapping for. * @param clsName Class name. * @param fields Fields descriptors. * @throws CacheException If failed to check type metadata. */ private static void checkMapping(@Nullable String cacheName, String clsName, Collection<CacheTypeFieldMetadata> fields) throws CacheException { try { Class<?> cls = Class.forName(clsName); if (simpleType(cls)) { if (fields.size() != 1) throw new CacheException("More than one field for simple type [cache name=" + cacheName + ", type=" + clsName + " ]"); CacheTypeFieldMetadata field = F.first(fields); if (field.getDatabaseName() == null) throw new CacheException("Missing database name in mapping description [cache name=" + cacheName + ", type=" + clsName + " ]"); field.setJavaType(cls); } else for (CacheTypeFieldMetadata field : fields) { if (field.getDatabaseName() == null) throw new CacheException("Missing database name in mapping description [cache name=" + cacheName + ", type=" + clsName + " ]"); if (field.getJavaName() == null) throw new CacheException("Missing field name in mapping description [cache name=" + cacheName + ", type=" + clsName + " ]"); if (field.getJavaType() == null) throw new CacheException("Missing field type in mapping description [cache name=" + cacheName + ", type=" + clsName + " ]"); } } catch (ClassNotFoundException e) { throw new CacheException("Failed to find class: " + clsName, e); } } /** * @param cacheName Cache name to check mappings for. * @return Type mappings for specified cache name. * @throws CacheException If failed to initialize cache mappings. */ private Map<Object, EntryMapping> cacheMappings(@Nullable String cacheName) throws CacheException { Map<Object, EntryMapping> entryMappings = cacheMappings.get(cacheName); if (entryMappings != null) return entryMappings; cacheMappingsLock.lock(); try { entryMappings = cacheMappings.get(cacheName); if (entryMappings != null) return entryMappings; CacheConfiguration ccfg = ignite().cache(cacheName).getConfiguration(CacheConfiguration.class); Collection<CacheTypeMetadata> types = ccfg.getTypeMetadata(); entryMappings = U.newHashMap(types.size()); for (CacheTypeMetadata type : types) { Object keyTypeId = keyTypeId(type.getKeyType()); if (entryMappings.containsKey(keyTypeId)) throw new CacheException("Key type must be unique in type metadata [cache name=" + cacheName + ", key type=" + type.getKeyType() + "]"); checkMapping(cacheName, type.getKeyType(), type.getKeyFields()); checkMapping(cacheName, type.getValueType(), type.getValueFields()); entryMappings.put(keyTypeId(type.getKeyType()), new EntryMapping(cacheName, dialect, type)); } Map<String, Map<Object, EntryMapping>> mappings = new HashMap<>(cacheMappings); mappings.put(cacheName, entryMappings); prepareBuilders(cacheName, types); cacheMappings = mappings; return entryMappings; } finally { cacheMappingsLock.unlock(); } } /** * @param cacheName Cache name. * @param keyTypeId Key type id. * @param key Key object. * @return Entry mapping. * @throws CacheException If mapping for key was not found. */ private EntryMapping entryMapping(String cacheName, Object keyTypeId, Object key) throws CacheException { EntryMapping em = cacheMappings(cacheName).get(keyTypeId); if (em == null) { String maskedCacheName = U.maskName(cacheName); throw new CacheException("Failed to find mapping description [key=" + key + ", cache=" + maskedCacheName + "]. Please configure CacheTypeMetadata to associate '" + maskedCacheName + "' with JdbcPojoStore."); } return em; } /** {@inheritDoc} */ @Override public void loadCache(final IgniteBiInClosure<K, V> clo, @Nullable Object... args) throws CacheLoaderException { ExecutorService pool = null; String cacheName = session().cacheName(); try { pool = Executors.newFixedThreadPool(maxPoolSz); Collection<Future<?>> futs = new ArrayList<>(); if (args != null && args.length > 0) { if (args.length % 2 != 0) throw new CacheLoaderException("Expected even number of arguments, but found: " + args.length); if (log.isDebugEnabled()) log.debug("Start loading entries from db using user queries from arguments"); for (int i = 0; i < args.length; i += 2) { String keyType = args[i].toString(); String selQry = args[i + 1].toString(); EntryMapping em = entryMapping(cacheName, keyTypeId(keyType), keyType); futs.add(pool.submit(new LoadCacheCustomQueryWorker<>(em, selQry, clo))); } } else { Collection<EntryMapping> entryMappings = cacheMappings(session().cacheName()).values(); for (EntryMapping em : entryMappings) { if (parallelLoadCacheMinThreshold > 0) { log.debug("Multithread loading entries from db [cache name=" + cacheName + ", key type=" + em.keyType() + " ]"); Connection conn = null; try { conn = connection(); PreparedStatement stmt = conn.prepareStatement(em.loadCacheSelRangeQry); stmt.setInt(1, parallelLoadCacheMinThreshold); ResultSet rs = stmt.executeQuery(); if (rs.next()) { int keyCnt = em.keyCols.size(); Object[] upperBound = new Object[keyCnt]; for (int i = 0; i < keyCnt; i++) upperBound[i] = rs.getObject(i + 1); futs.add(pool.submit(loadCacheRange(em, clo, null, upperBound))); while (rs.next()) { Object[] lowerBound = upperBound; upperBound = new Object[keyCnt]; for (int i = 0; i < keyCnt; i++) upperBound[i] = rs.getObject(i + 1); futs.add(pool.submit(loadCacheRange(em, clo, lowerBound, upperBound))); } futs.add(pool.submit(loadCacheRange(em, clo, upperBound, null))); } else futs.add(pool.submit(loadCacheFull(em, clo))); } catch (SQLException ignored) { futs.add(pool.submit(loadCacheFull(em, clo))); } finally { U.closeQuiet(conn); } } else { if (log.isDebugEnabled()) log.debug("Single thread loading entries from db [cache name=" + cacheName + ", key type=" + em.keyType() + " ]"); futs.add(pool.submit(loadCacheFull(em, clo))); } } } for (Future<?> fut : futs) U.get(fut); if (log.isDebugEnabled()) log.debug("Cache loaded from db: " + cacheName); } catch (IgniteCheckedException e) { throw new CacheLoaderException("Failed to load cache: " + cacheName, e.getCause()); } finally { U.shutdownNow(getClass(), pool, log); } } /** {@inheritDoc} */ @Nullable @Override public V load(K key) throws CacheLoaderException { assert key != null; EntryMapping em = entryMapping(session().cacheName(), keyTypeId(key), key); if (log.isDebugEnabled()) log.debug("Load value from db [table= " + em.fullTableName() + ", key=" + key + "]"); Connection conn = null; PreparedStatement stmt = null; try { conn = connection(); stmt = conn.prepareStatement(em.loadQrySingle); fillKeyParameters(stmt, em, key); ResultSet rs = stmt.executeQuery(); if (rs.next()) return buildObject(em.cacheName, em.valueType(), em.valueColumns(), em.loadColIdxs, rs); } catch (SQLException e) { throw new CacheLoaderException("Failed to load object [table=" + em.fullTableName() + ", key=" + key + "]", e); } finally { end(conn, stmt); } return null; } /** {@inheritDoc} */ @Override public Map<K, V> loadAll(Iterable<? extends K> keys) throws CacheLoaderException { assert keys != null; Connection conn = null; try { conn = connection(); String cacheName = session().cacheName(); Map<Object, LoadWorker<K, V>> workers = U.newHashMap(cacheMappings(cacheName).size()); Map<K, V> res = new HashMap<>(); for (K key : keys) { Object keyTypeId = keyTypeId(key); EntryMapping em = entryMapping(cacheName, keyTypeId, key); LoadWorker<K, V> worker = workers.get(keyTypeId); if (worker == null) workers.put(keyTypeId, worker = new LoadWorker<>(conn, em)); worker.keys.add(key); if (worker.keys.size() == em.maxKeysPerStmt) res.putAll(workers.remove(keyTypeId).call()); } for (LoadWorker<K, V> worker : workers.values()) res.putAll(worker.call()); return res; } catch (Exception e) { throw new CacheWriterException("Failed to load entries from database", e); } finally { closeConnection(conn); } } /** * @param insStmt Insert statement. * @param updStmt Update statement. * @param em Entry mapping. * @param entry Cache entry. * @throws CacheWriterException If failed to update record in database. */ private void writeUpsert(PreparedStatement insStmt, PreparedStatement updStmt, EntryMapping em, Cache.Entry<? extends K, ? extends V> entry) throws CacheWriterException { try { CacheWriterException we = null; for (int attempt = 0; attempt < MAX_ATTEMPT_WRITE_COUNT; attempt++) { int paramIdx = fillValueParameters(updStmt, 1, em, entry.getValue()); fillKeyParameters(updStmt, paramIdx, em, entry.getKey()); if (updStmt.executeUpdate() == 0) { paramIdx = fillKeyParameters(insStmt, em, entry.getKey()); fillValueParameters(insStmt, paramIdx, em, entry.getValue()); try { insStmt.executeUpdate(); if (attempt > 0) U.warn(log, "Entry was inserted in database on second try [table=" + em.fullTableName() + ", entry=" + entry + "]"); } catch (SQLException e) { String sqlState = e.getSQLState(); SQLException nested = e.getNextException(); while (sqlState == null && nested != null) { sqlState = nested.getSQLState(); nested = nested.getNextException(); } // The error with code 23505 or 23000 is thrown when trying to insert a row that // would violate a unique index or primary key. if ("23505".equals(sqlState) || "23000".equals(sqlState)) { if (we == null) we = new CacheWriterException("Failed insert entry in database, violate a unique" + " index or primary key [table=" + em.fullTableName() + ", entry=" + entry + "]"); we.addSuppressed(e); U.warn(log, "Failed insert entry in database, violate a unique index or primary key" + " [table=" + em.fullTableName() + ", entry=" + entry + "]"); continue; } throw new CacheWriterException("Failed insert entry in database [table=" + em.fullTableName() + ", entry=" + entry, e); } } if (attempt > 0) U.warn(log, "Entry was updated in database on second try [table=" + em.fullTableName() + ", entry=" + entry + "]"); return; } throw we; } catch (SQLException e) { throw new CacheWriterException("Failed update entry in database [table=" + em.fullTableName() + ", entry=" + entry + "]", e); } } /** {@inheritDoc} */ @Override public void write(Cache.Entry<? extends K, ? extends V> entry) throws CacheWriterException { assert entry != null; K key = entry.getKey(); EntryMapping em = entryMapping(session().cacheName(), keyTypeId(key), key); if (log.isDebugEnabled()) log.debug("Start write entry to database [table=" + em.fullTableName() + ", entry=" + entry + "]"); Connection conn = null; try { conn = connection(); if (dialect.hasMerge()) { PreparedStatement stmt = null; try { stmt = conn.prepareStatement(em.mergeQry); int i = fillKeyParameters(stmt, em, key); fillValueParameters(stmt, i, em, entry.getValue()); int updCnt = stmt.executeUpdate(); if (updCnt != 1) U.warn(log, "Unexpected number of updated entries [table=" + em.fullTableName() + ", entry=" + entry + "expected=1, actual=" + updCnt + "]"); } finally { U.closeQuiet(stmt); } } else { PreparedStatement insStmt = null; PreparedStatement updStmt = null; try { insStmt = conn.prepareStatement(em.insQry); updStmt = conn.prepareStatement(em.updQry); writeUpsert(insStmt, updStmt, em, entry); } finally { U.closeQuiet(insStmt); U.closeQuiet(updStmt); } } } catch (SQLException e) { throw new CacheWriterException("Failed to write entry to database [table=" + em.fullTableName() + ", entry=" + entry + "]", e); } finally { closeConnection(conn); } } /** {@inheritDoc} */ @Override public void writeAll(final Collection<Cache.Entry<? extends K, ? extends V>> entries) throws CacheWriterException { assert entries != null; Connection conn = null; try { conn = connection(); String cacheName = session().cacheName(); Object currKeyTypeId = null; if (dialect.hasMerge()) { PreparedStatement mergeStmt = null; try { EntryMapping em = null; LazyValue<Object[]> lazyEntries = new LazyValue<Object[]>() { @Override public Object[] create() { return entries.toArray(); } }; int fromIdx = 0, prepared = 0; for (Cache.Entry<? extends K, ? extends V> entry : entries) { K key = entry.getKey(); Object keyTypeId = keyTypeId(key); em = entryMapping(cacheName, keyTypeId, key); if (currKeyTypeId == null || !currKeyTypeId.equals(keyTypeId)) { if (mergeStmt != null) { if (log.isDebugEnabled()) log.debug("Write entries to db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, mergeStmt, "writeAll", fromIdx, prepared, lazyEntries); U.closeQuiet(mergeStmt); } mergeStmt = conn.prepareStatement(em.mergeQry); currKeyTypeId = keyTypeId; fromIdx += prepared; prepared = 0; } int i = fillKeyParameters(mergeStmt, em, key); fillValueParameters(mergeStmt, i, em, entry.getValue()); mergeStmt.addBatch(); if (++prepared % batchSz == 0) { if (log.isDebugEnabled()) log.debug("Write entries to db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, mergeStmt, "writeAll", fromIdx, prepared, lazyEntries); fromIdx += prepared; prepared = 0; } } if (mergeStmt != null && prepared % batchSz != 0) { if (log.isDebugEnabled()) log.debug("Write entries to db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, mergeStmt, "writeAll", fromIdx, prepared, lazyEntries); } } finally { U.closeQuiet(mergeStmt); } } else { log.debug("Write entries to db one by one using update and insert statements [cache name=" + cacheName + ", count=" + entries.size() + "]"); PreparedStatement insStmt = null; PreparedStatement updStmt = null; try { for (Cache.Entry<? extends K, ? extends V> entry : entries) { K key = entry.getKey(); Object keyTypeId = keyTypeId(key); EntryMapping em = entryMapping(cacheName, keyTypeId, key); if (currKeyTypeId == null || !currKeyTypeId.equals(keyTypeId)) { U.closeQuiet(insStmt); insStmt = conn.prepareStatement(em.insQry); U.closeQuiet(updStmt); updStmt = conn.prepareStatement(em.updQry); currKeyTypeId = keyTypeId; } writeUpsert(insStmt, updStmt, em, entry); } } finally { U.closeQuiet(insStmt); U.closeQuiet(updStmt); } } } catch (SQLException e) { throw new CacheWriterException("Failed to write entries in database", e); } finally { closeConnection(conn); } } /** {@inheritDoc} */ @Override public void delete(Object key) throws CacheWriterException { assert key != null; EntryMapping em = entryMapping(session().cacheName(), keyTypeId(key), key); if (log.isDebugEnabled()) log.debug("Remove value from db [table=" + em.fullTableName() + ", key=" + key + "]"); Connection conn = null; PreparedStatement stmt = null; try { conn = connection(); stmt = conn.prepareStatement(em.remQry); fillKeyParameters(stmt, em, key); int delCnt = stmt.executeUpdate(); if (delCnt != 1) U.warn(log, "Unexpected number of deleted entries [table=" + em.fullTableName() + ", key=" + key + ", expected=1, actual=" + delCnt + "]"); } catch (SQLException e) { throw new CacheWriterException("Failed to remove value from database [table=" + em.fullTableName() + ", key=" + key + "]", e); } finally { end(conn, stmt); } } /** * @param em Entry mapping. * @param stmt Statement. * @param desc Statement description for error message. * @param fromIdx Objects in batch start from index. * @param prepared Expected objects in batch. * @param lazyObjs All objects used in batch statement as array. * @throws SQLException If failed to execute batch statement. */ private void executeBatch(EntryMapping em, Statement stmt, String desc, int fromIdx, int prepared, LazyValue<Object[]> lazyObjs) throws SQLException { try { int[] rowCounts = stmt.executeBatch(); int numOfRowCnt = rowCounts.length; if (numOfRowCnt != prepared) U.warn(log, "Unexpected number of updated rows [table=" + em.fullTableName() + ", expected=" + prepared + ", actual=" + numOfRowCnt + "]"); for (int i = 0; i < numOfRowCnt; i++) { int cnt = rowCounts[i]; if (cnt != 1 && cnt != SUCCESS_NO_INFO) { Object[] objs = lazyObjs.value(); U.warn(log, "Batch " + desc + " returned unexpected updated row count [table=" + em.fullTableName() + ", entry=" + objs[fromIdx + i] + ", expected=1, actual=" + cnt + "]"); } } } catch (BatchUpdateException be) { int[] rowCounts = be.getUpdateCounts(); for (int i = 0; i < rowCounts.length; i++) { if (rowCounts[i] == EXECUTE_FAILED) { Object[] objs = lazyObjs.value(); U.warn(log, "Batch " + desc + " failed on execution [table=" + em.fullTableName() + ", entry=" + objs[fromIdx + i] + "]"); } } throw be; } } /** {@inheritDoc} */ @Override public void deleteAll(final Collection<?> keys) throws CacheWriterException { assert keys != null; Connection conn = null; try { conn = connection(); LazyValue<Object[]> lazyKeys = new LazyValue<Object[]>() { @Override public Object[] create() { return keys.toArray(); } }; String cacheName = session().cacheName(); Object currKeyTypeId = null; EntryMapping em = null; PreparedStatement delStmt = null; int fromIdx = 0, prepared = 0; for (Object key : keys) { Object keyTypeId = keyTypeId(key); em = entryMapping(cacheName, keyTypeId, key); if (delStmt == null) { delStmt = conn.prepareStatement(em.remQry); currKeyTypeId = keyTypeId; } if (!currKeyTypeId.equals(keyTypeId)) { if (log.isDebugEnabled()) log.debug("Delete entries from db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, delStmt, "deleteAll", fromIdx, prepared, lazyKeys); fromIdx += prepared; prepared = 0; currKeyTypeId = keyTypeId; } fillKeyParameters(delStmt, em, key); delStmt.addBatch(); if (++prepared % batchSz == 0) { if (log.isDebugEnabled()) log.debug("Delete entries from db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, delStmt, "deleteAll", fromIdx, prepared, lazyKeys); fromIdx += prepared; prepared = 0; } } if (delStmt != null && prepared % batchSz != 0) { if (log.isDebugEnabled()) log.debug("Delete entries from db [cache name=" + cacheName + ", key type=" + em.keyType() + ", count=" + prepared + "]"); executeBatch(em, delStmt, "deleteAll", fromIdx, prepared, lazyKeys); } } catch (SQLException e) { throw new CacheWriterException("Failed to remove values from database", e); } finally { closeConnection(conn); } } /** * Sets the value of the designated parameter using the given object. * * @param stmt Prepare statement. * @param i Index for parameters. * @param field Field descriptor. * @param fieldVal Field value. * @throws CacheException If failed to set statement parameter. */ protected void fillParameter(PreparedStatement stmt, int i, CacheTypeFieldMetadata field, @Nullable Object fieldVal) throws CacheException { try { if (fieldVal != null) { if (field.getJavaType() == UUID.class) { switch (field.getDatabaseType()) { case Types.BINARY: fieldVal = U.uuidToBytes((UUID)fieldVal); break; case Types.CHAR: case Types.VARCHAR: fieldVal = fieldVal.toString(); break; } } stmt.setObject(i, fieldVal); } else stmt.setNull(i, field.getDatabaseType()); } catch (SQLException e) { throw new CacheException("Failed to set statement parameter name: " + field.getDatabaseName(), e); } } /** * @param stmt Prepare statement. * @param idx Start index for parameters. * @param em Entry mapping. * @param key Key object. * @return Next index for parameters. * @throws CacheException If failed to set statement parameters. */ protected int fillKeyParameters(PreparedStatement stmt, int idx, EntryMapping em, Object key) throws CacheException { for (CacheTypeFieldMetadata field : em.keyColumns()) { Object fieldVal = extractParameter(em.cacheName, em.keyType(), field.getJavaName(), key); fillParameter(stmt, idx++, field, fieldVal); } return idx; } /** * @param stmt Prepare statement. * @param m Type mapping description. * @param key Key object. * @return Next index for parameters. * @throws CacheException If failed to set statement parameters. */ protected int fillKeyParameters(PreparedStatement stmt, EntryMapping m, Object key) throws CacheException { return fillKeyParameters(stmt, 1, m, key); } /** * @param stmt Prepare statement. * @param idx Start index for parameters. * @param em Type mapping description. * @param val Value object. * @return Next index for parameters. * @throws CacheException If failed to set statement parameters. */ protected int fillValueParameters(PreparedStatement stmt, int idx, EntryMapping em, Object val) throws CacheWriterException { for (CacheTypeFieldMetadata field : em.uniqValFields) { Object fieldVal = extractParameter(em.cacheName, em.valueType(), field.getJavaName(), val); fillParameter(stmt, idx++, field, fieldVal); } return idx; } /** * @return Data source. */ public DataSource getDataSource() { return dataSrc; } /** * @param dataSrc Data source. */ public void setDataSource(DataSource dataSrc) { this.dataSrc = dataSrc; } /** * Get database dialect. * * @return Database dialect. */ public JdbcDialect getDialect() { return dialect; } /** * Set database dialect. * * @param dialect Database dialect. */ public void setDialect(JdbcDialect dialect) { this.dialect = dialect; } /** * Get Max workers thread count. These threads are responsible for execute query. * * @return Max workers thread count. */ public int getMaximumPoolSize() { return maxPoolSz; } /** * Set Max workers thread count. These threads are responsible for execute query. * * @param maxPoolSz Max workers thread count. */ public void setMaximumPoolSize(int maxPoolSz) { this.maxPoolSz = maxPoolSz; } /** * Get maximum batch size for delete and delete operations. * * @return Maximum batch size. */ public int getBatchSize() { return batchSz; } /** * Set maximum batch size for write and delete operations. * * @param batchSz Maximum batch size. */ public void setBatchSize(int batchSz) { this.batchSz = batchSz; } /** * Parallel load cache minimum row count threshold. * * @return If {@code 0} then load sequentially. */ public int getParallelLoadCacheMinimumThreshold() { return parallelLoadCacheMinThreshold; } /** * Parallel load cache minimum row count threshold. * * @param parallelLoadCacheMinThreshold Minimum row count threshold. If {@code 0} then load sequentially. */ public void setParallelLoadCacheMinimumThreshold(int parallelLoadCacheMinThreshold) { this.parallelLoadCacheMinThreshold = parallelLoadCacheMinThreshold; } /** * @return Ignite instance. */ protected Ignite ignite() { return ignite; } /** * @return Store session. */ protected CacheStoreSession session() { return ses; } /** * Entry mapping description. */ protected static class EntryMapping { /** Cache name. */ private final String cacheName; /** Database dialect. */ private final JdbcDialect dialect; /** Select border for range queries. */ private final String loadCacheSelRangeQry; /** Select all items query. */ private final String loadCacheQry; /** Select item query. */ private final String loadQrySingle; /** Select items query. */ private final String loadQry; /** Merge item(s) query. */ private final String mergeQry; /** Update item query. */ private final String insQry; /** Update item query. */ private final String updQry; /** Remove item(s) query. */ private final String remQry; /** Max key count for load query per statement. */ private final int maxKeysPerStmt; /** Database key columns. */ private final Collection<String> keyCols; /** Database unique value columns. */ private final Collection<String> cols; /** Select query columns index. */ private final Map<String, Integer> loadColIdxs; /** Unique value fields. */ private final Collection<CacheTypeFieldMetadata> uniqValFields; /** Type metadata. */ private final CacheTypeMetadata typeMeta; /** Full table name. */ private final String fullTblName; /** * @param cacheName Cache name. * @param dialect JDBC dialect. * @param typeMeta Type metadata. */ public EntryMapping(@Nullable String cacheName, JdbcDialect dialect, CacheTypeMetadata typeMeta) { this.cacheName = cacheName; this.dialect = dialect; this.typeMeta = typeMeta; Collection<CacheTypeFieldMetadata> keyFields = typeMeta.getKeyFields(); Collection<CacheTypeFieldMetadata> valFields = typeMeta.getValueFields(); keyCols = databaseColumns(keyFields); uniqValFields = F.view(valFields, new IgnitePredicate<CacheTypeFieldMetadata>() { @Override public boolean apply(CacheTypeFieldMetadata col) { return !keyCols.contains(col.getDatabaseName()); } }); String schema = typeMeta.getDatabaseSchema(); String tblName = typeMeta.getDatabaseTable(); fullTblName = F.isEmpty(schema) ? tblName : schema + "." + tblName; Collection<String> uniqValCols = databaseColumns(uniqValFields); cols = F.concat(false, keyCols, uniqValCols); loadColIdxs = U.newHashMap(cols.size()); int idx = 1; for (String col : cols) loadColIdxs.put(col, idx++); loadCacheQry = dialect.loadCacheQuery(fullTblName, cols); loadCacheSelRangeQry = dialect.loadCacheSelectRangeQuery(fullTblName, keyCols); loadQrySingle = dialect.loadQuery(fullTblName, keyCols, cols, 1); maxKeysPerStmt = dialect.getMaxParameterCount() / keyCols.size(); loadQry = dialect.loadQuery(fullTblName, keyCols, cols, maxKeysPerStmt); insQry = dialect.insertQuery(fullTblName, keyCols, uniqValCols); updQry = dialect.updateQuery(fullTblName, keyCols, uniqValCols); mergeQry = dialect.mergeQuery(fullTblName, keyCols, uniqValCols); remQry = dialect.removeQuery(fullTblName, keyCols); } /** * Extract database column names from {@link CacheTypeFieldMetadata}. * * @param dsc collection of {@link CacheTypeFieldMetadata}. * @return Collection with database column names. */ private static Collection<String> databaseColumns(Collection<CacheTypeFieldMetadata> dsc) { return F.transform(dsc, new C1<CacheTypeFieldMetadata, String>() { /** {@inheritDoc} */ @Override public String apply(CacheTypeFieldMetadata col) { return col.getDatabaseName(); } }); } /** * Construct query for select values with key count less or equal {@code maxKeysPerStmt} * * @param keyCnt Key count. * @return Load query statement text. */ protected String loadQuery(int keyCnt) { assert keyCnt <= maxKeysPerStmt; if (keyCnt == maxKeysPerStmt) return loadQry; if (keyCnt == 1) return loadQrySingle; return dialect.loadQuery(fullTblName, keyCols, cols, keyCnt); } /** * Construct query for select values in range. * * @param appendLowerBound Need add lower bound for range. * @param appendUpperBound Need add upper bound for range. * @return Query with range. */ protected String loadCacheRangeQuery(boolean appendLowerBound, boolean appendUpperBound) { return dialect.loadCacheRangeQuery(fullTblName, keyCols, cols, appendLowerBound, appendUpperBound); } /** * @return Key type. */ protected String keyType() { return typeMeta.getKeyType(); } /** * @return Value type. */ protected String valueType() { return typeMeta.getValueType(); } /** * Gets key columns. * * @return Key columns. */ protected Collection<CacheTypeFieldMetadata> keyColumns() { return typeMeta.getKeyFields(); } /** * Gets value columns. * * @return Value columns. */ protected Collection<CacheTypeFieldMetadata> valueColumns() { return typeMeta.getValueFields(); } /** * Get full table name. * * @return &lt;schema&gt;.&lt;table name&gt */ protected String fullTableName() { return fullTblName; } } /** * Worker for load cache using custom user query. * * @param <K1> Key type. * @param <V1> Value type. */ private class LoadCacheCustomQueryWorker<K1, V1> implements Callable<Void> { /** Entry mapping description. */ private final EntryMapping em; /** User query. */ private final String qry; /** Closure for loaded values. */ private final IgniteBiInClosure<K1, V1> clo; /** * @param em Entry mapping description. * @param qry User query. * @param clo Closure for loaded values. */ private LoadCacheCustomQueryWorker(EntryMapping em, String qry, IgniteBiInClosure<K1, V1> clo) { this.em = em; this.qry = qry; this.clo = clo; } /** {@inheritDoc} */ @Override public Void call() throws Exception { if (log.isDebugEnabled()) log.debug("Load cache using custom query [cache name= " + em.cacheName + ", key type=" + em.keyType() + ", query=" + qry + "]"); Connection conn = null; PreparedStatement stmt = null; try { conn = openConnection(true); stmt = conn.prepareStatement(qry); ResultSet rs = stmt.executeQuery(); ResultSetMetaData meta = rs.getMetaData(); Map<String, Integer> colIdxs = U.newHashMap(meta.getColumnCount()); for (int i = 1; i <= meta.getColumnCount(); i++) colIdxs.put(meta.getColumnLabel(i), i); while (rs.next()) { K1 key = buildObject(em.cacheName, em.keyType(), em.keyColumns(), colIdxs, rs); V1 val = buildObject(em.cacheName, em.valueType(), em.valueColumns(), colIdxs, rs); clo.apply(key, val); } return null; } catch (SQLException e) { throw new CacheLoaderException("Failed to execute custom query for load cache", e); } finally { U.closeQuiet(stmt); U.closeQuiet(conn); } } } /** * Lazy initialization of value. * * @param <T> Cached object type */ private abstract static class LazyValue<T> { /** Cached value. */ private T val; /** * @return Construct value. */ protected abstract T create(); /** * @return Value. */ public T value() { if (val == null) val = create(); return val; } } /** * Worker for load by keys. * * @param <K1> Key type. * @param <V1> Value type. */ private class LoadWorker<K1, V1> implements Callable<Map<K1, V1>> { /** Connection. */ private final Connection conn; /** Keys for load. */ private final Collection<K1> keys; /** Entry mapping description. */ private final EntryMapping em; /** * @param conn Connection. * @param em Entry mapping description. */ private LoadWorker(Connection conn, EntryMapping em) { this.conn = conn; this.em = em; keys = new ArrayList<>(em.maxKeysPerStmt); } /** {@inheritDoc} */ @Override public Map<K1, V1> call() throws Exception { if (log.isDebugEnabled()) log.debug("Load values from db [table= " + em.fullTableName() + ", key count=" + keys.size() + "]"); PreparedStatement stmt = null; try { stmt = conn.prepareStatement(em.loadQuery(keys.size())); int idx = 1; for (Object key : keys) for (CacheTypeFieldMetadata field : em.keyColumns()) { Object fieldVal = extractParameter(em.cacheName, em.keyType(), field.getJavaName(), key); fillParameter(stmt, idx++, field, fieldVal); } ResultSet rs = stmt.executeQuery(); Map<K1, V1> entries = U.newHashMap(keys.size()); while (rs.next()) { K1 key = buildObject(em.cacheName, em.keyType(), em.keyColumns(), em.loadColIdxs, rs); V1 val = buildObject(em.cacheName, em.valueType(), em.valueColumns(), em.loadColIdxs, rs); entries.put(key, val); } return entries; } finally { U.closeQuiet(stmt); } } } }
vsisko/incubator-ignite
modules/core/src/main/java/org/apache/ignite/cache/store/jdbc/CacheAbstractJdbcStore.java
Java
apache-2.0
62,015
connection = ActiveRecord::Base.connection puts 'adding govt data' %w[states districts zip_codes districts_zip_codes legislators].each do |table| puts "loading #{table}" connection.execute(IO.read("db/seed_data/#{table}.sql")) end %w[states districts zip_codes legislators].each do |table| puts "updating table IDs for #{table}" result = connection.execute("SELECT id FROM #{table} ORDER BY id DESC LIMIT 1") connection.execute( "ALTER SEQUENCE #{table}_id_seq RESTART WITH #{result.first['id'].to_i + 1}" ) end
MayOneUS/mayday-2.0-backend
db/seeds.rb
Ruby
apache-2.0
532
<?php /** * Activity * * PHP version 5 * * @category Class * @package ultracart\v2 * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ /** * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * Swagger Codegen version: 2.4.15-SNAPSHOT */ /** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ namespace ultracart\v2\models; use \ArrayAccess; use \ultracart\v2\ObjectSerializer; /** * Activity Class Doc Comment * * @category Class * @package ultracart\v2 * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class Activity implements ModelInterface, ArrayAccess { const DISCRIMINATOR = null; /** * The original name of the model. * * @var string */ protected static $swaggerModelName = 'Activity'; /** * Array of property to type mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerTypes = [ 'action' => 'string', 'metric' => 'string', 'subject' => 'string', 'ts' => 'int', 'type' => 'string', 'uuid' => 'string' ]; /** * Array of property to format mappings. Used for (de)serialization * * @var string[] */ protected static $swaggerFormats = [ 'action' => null, 'metric' => null, 'subject' => null, 'ts' => 'int64', 'type' => null, 'uuid' => null ]; /** * Array of property to type mappings. Used for (de)serialization * * @return array */ public static function swaggerTypes() { return self::$swaggerTypes; } /** * Array of property to format mappings. Used for (de)serialization * * @return array */ public static function swaggerFormats() { return self::$swaggerFormats; } /** * Array of attributes where the key is the local name, * and the value is the original name * * @var string[] */ protected static $attributeMap = [ 'action' => 'action', 'metric' => 'metric', 'subject' => 'subject', 'ts' => 'ts', 'type' => 'type', 'uuid' => 'uuid' ]; /** * Array of attributes to setter functions (for deserialization of responses) * * @var string[] */ protected static $setters = [ 'action' => 'setAction', 'metric' => 'setMetric', 'subject' => 'setSubject', 'ts' => 'setTs', 'type' => 'setType', 'uuid' => 'setUuid' ]; /** * Array of attributes to getter functions (for serialization of requests) * * @var string[] */ protected static $getters = [ 'action' => 'getAction', 'metric' => 'getMetric', 'subject' => 'getSubject', 'ts' => 'getTs', 'type' => 'getType', 'uuid' => 'getUuid' ]; /** * Array of attributes where the key is the local name, * and the value is the original name * * @return array */ public static function attributeMap() { return self::$attributeMap; } /** * Array of attributes to setter functions (for deserialization of responses) * * @return array */ public static function setters() { return self::$setters; } /** * Array of attributes to getter functions (for serialization of requests) * * @return array */ public static function getters() { return self::$getters; } /** * The original name of the model. * * @return string */ public function getModelName() { return self::$swaggerModelName; } /** * Associative array for storing property values * * @var mixed[] */ protected $container = []; /** * Constructor * * @param mixed[] $data Associated array of property values * initializing the model */ public function __construct(array $data = null) { $this->container['action'] = isset($data['action']) ? $data['action'] : null; $this->container['metric'] = isset($data['metric']) ? $data['metric'] : null; $this->container['subject'] = isset($data['subject']) ? $data['subject'] : null; $this->container['ts'] = isset($data['ts']) ? $data['ts'] : null; $this->container['type'] = isset($data['type']) ? $data['type'] : null; $this->container['uuid'] = isset($data['uuid']) ? $data['uuid'] : null; } /** * Show all the invalid properties with reasons. * * @return array invalid properties with reasons */ public function listInvalidProperties() { $invalidProperties = []; return $invalidProperties; } /** * Validate all the properties in the model * return true if all passed * * @return bool True if all properties are valid */ public function valid() { return count($this->listInvalidProperties()) === 0; } /** * Gets action * * @return string */ public function getAction() { return $this->container['action']; } /** * Sets action * * @param string $action action * * @return $this */ public function setAction($action) { $this->container['action'] = $action; return $this; } /** * Gets metric * * @return string */ public function getMetric() { return $this->container['metric']; } /** * Sets metric * * @param string $metric metric * * @return $this */ public function setMetric($metric) { $this->container['metric'] = $metric; return $this; } /** * Gets subject * * @return string */ public function getSubject() { return $this->container['subject']; } /** * Sets subject * * @param string $subject subject * * @return $this */ public function setSubject($subject) { $this->container['subject'] = $subject; return $this; } /** * Gets ts * * @return int */ public function getTs() { return $this->container['ts']; } /** * Sets ts * * @param int $ts ts * * @return $this */ public function setTs($ts) { $this->container['ts'] = $ts; return $this; } /** * Gets type * * @return string */ public function getType() { return $this->container['type']; } /** * Sets type * * @param string $type type * * @return $this */ public function setType($type) { $this->container['type'] = $type; return $this; } /** * Gets uuid * * @return string */ public function getUuid() { return $this->container['uuid']; } /** * Sets uuid * * @param string $uuid uuid * * @return $this */ public function setUuid($uuid) { $this->container['uuid'] = $uuid; return $this; } /** * Returns true if offset exists. False otherwise. * * @param integer $offset Offset * * @return boolean */ public function offsetExists($offset) { return isset($this->container[$offset]); } /** * Gets offset. * * @param integer $offset Offset * * @return mixed */ public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } /** * Sets value based on offset. * * @param integer $offset Offset * @param mixed $value Value to be set * * @return void */ public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } /** * Unsets offset. * * @param integer $offset Offset * * @return void */ public function offsetUnset($offset) { unset($this->container[$offset]); } /** * Gets the string presentation of the object * * @return string */ public function __toString() { if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print return json_encode( ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT ); } return json_encode(ObjectSerializer::sanitizeForSerialization($this)); } }
UltraCart/rest_api_v2_sdk_php
lib/models/Activity.php
PHP
apache-2.0
9,144
using System; using System.Linq.Expressions; namespace storagecore.EntityFrameworkCore.Query { public class Filter<TEntity> { public Filter(Expression<Func<TEntity, bool>> expression) { Expression = expression; } public Expression<Func<TEntity, bool>> Expression { get; private set; } public void AddExpression(Expression<Func<TEntity, bool>> newExpression) { if (newExpression == null) throw new ArgumentNullException(nameof(newExpression), $"{nameof(newExpression)} is null."); if (Expression == null) Expression = newExpression; var parameter = System.Linq.Expressions.Expression.Parameter(typeof(TEntity)); var leftVisitor = new ReplaceExpressionVisitor(newExpression.Parameters[0], parameter); var left = leftVisitor.Visit(newExpression.Body); var rightVisitor = new ReplaceExpressionVisitor(Expression.Parameters[0], parameter); var right = rightVisitor.Visit(Expression.Body); Expression = System.Linq.Expressions.Expression.Lambda<Func<TEntity, bool>>(System.Linq.Expressions.Expression.AndAlso(left, right), parameter); } } }
FlorinskiyDI/coremanage
coremanage/storagecore.EntityFrameworkCore/Query/Filter.cs
C#
apache-2.0
1,222
package de.jungblut.math.squashing; import de.jungblut.math.DoubleMatrix; import de.jungblut.math.MathUtils; /** * Logistic error function implementation. * * @author thomas.jungblut * */ public final class LogisticErrorFunction implements ErrorFunction { @Override public double calculateError(DoubleMatrix y, DoubleMatrix hypothesis) { return (y.multiply(-1d) .multiplyElementWise(MathUtils.logMatrix(hypothesis)).subtract((y .subtractBy(1.0d)).multiplyElementWise(MathUtils.logMatrix(hypothesis .subtractBy(1d))))).sum(); } }
sourcewarehouse/thomasjungblut
src/de/jungblut/math/squashing/LogisticErrorFunction.java
Java
apache-2.0
574
""" Django settings for sparta project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ')mg$xo^v*2mmwidr0ak6%9&!@e18v8t#7@+vd+wqg8kydb48k7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'sparta.urls' WSGI_APPLICATION = 'sparta.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER':'root', 'NAME':'fordjango', 'PASSWORD':'123456', 'HOST':'localhost', 'PORT':'' } } # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) STATIC_ROOT = os.path.join('/home/dexter/weaponx/Django/sparta/sparta/static') STATIC_URL = '/assets/' STATICFILES_DIRS = ( '/home/dexter/weaponx/Django/sparta/sparta/assets', ) TEMPLATE_DIRS=('/home/dexter/weaponx/Django/sparta/sparta/template',)
sureshprasanna70/the-spartan-blog
sparta/settings.py
Python
apache-2.0
2,223
namespace CJia.PIVAS.App.UI { partial class BatchIllfieldLabelCollectReport { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Detail = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrIllfield = new DevExpress.XtraReports.UI.XRTableCell(); this.xrBatchZ = new DevExpress.XtraReports.UI.XRTableCell(); this.xrBatch1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrBatch2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrBatch3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrBatch4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrBatch5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrBatch6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrBatchB = new DevExpress.XtraReports.UI.XRTableCell(); this.xrBatchW = new DevExpress.XtraReports.UI.XRTableCell(); this.xrBatchL = new DevExpress.XtraReports.UI.XRTableCell(); this.xrAllBatch = new DevExpress.XtraReports.UI.XRTableCell(); this.TopMargin = new DevExpress.XtraReports.UI.TopMarginBand(); this.BottomMargin = new DevExpress.XtraReports.UI.BottomMarginBand(); this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xlZX = new DevExpress.XtraReports.UI.XRLabel(); this.xlZXDate = new DevExpress.XtraReports.UI.XRLabel(); this.xlKDDate = new DevExpress.XtraReports.UI.XRLabel(); this.xlKD1 = new DevExpress.XtraReports.UI.XRLabel(); this.xrDY1 = new DevExpress.XtraReports.UI.XRLabel(); this.xlDYstart = new DevExpress.XtraReports.UI.XRLabel(); this.xrDY2 = new DevExpress.XtraReports.UI.XRLabel(); this.xlDYEnd = new DevExpress.XtraReports.UI.XRLabel(); this.xrRepertHeader = new DevExpress.XtraReports.UI.XRLabel(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.xrLabel8 = new DevExpress.XtraReports.UI.XRLabel(); this.xrPrintBy = new DevExpress.XtraReports.UI.XRLabel(); this.lblPrintDate = new DevExpress.XtraReports.UI.XRLabel(); this.xrLabel6 = new DevExpress.XtraReports.UI.XRLabel(); this.xrPageInfo1 = new DevExpress.XtraReports.UI.XRPageInfo(); this.xr = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTable3 = new DevExpress.XtraReports.UI.XRTable(); this.GroupHeader1 = new DevExpress.XtraReports.UI.GroupHeaderBand(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // Detail // this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); this.Detail.HeightF = 25.95833F; this.Detail.Name = "Detail"; this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.Detail.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft; // // xrTable1 // this.xrTable1.LocationFloat = new DevExpress.Utils.PointFloat(16.49996F, 0F); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1}); this.xrTable1.SizeF = new System.Drawing.SizeF(823.5001F, 25F); // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrIllfield, this.xrBatchZ, this.xrBatch1, this.xrBatch2, this.xrBatch3, this.xrBatch4, this.xrBatch5, this.xrBatch6, this.xrBatchB, this.xrBatchW, this.xrBatchL, this.xrAllBatch}); this.xrTableRow1.Name = "xrTableRow1"; this.xrTableRow1.Weight = 1D; // // xrIllfield // this.xrIllfield.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrIllfield.Name = "xrIllfield"; this.xrIllfield.StylePriority.UseBorders = false; this.xrIllfield.StylePriority.UseTextAlignment = false; this.xrIllfield.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrIllfield.Weight = 0.56262541342602934D; // // xrBatchZ // this.xrBatchZ.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrBatchZ.Name = "xrBatchZ"; this.xrBatchZ.StylePriority.UseBorders = false; this.xrBatchZ.StylePriority.UseTextAlignment = false; this.xrBatchZ.Text = "xrBatchZ"; this.xrBatchZ.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrBatchZ.Weight = 0.21932980514517925D; // // xrBatch1 // this.xrBatch1.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrBatch1.Name = "xrBatch1"; this.xrBatch1.StylePriority.UseBorders = false; this.xrBatch1.StylePriority.UseTextAlignment = false; this.xrBatch1.Text = "xrBatch1"; this.xrBatch1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrBatch1.Weight = 0.21932980955029355D; // // xrBatch2 // this.xrBatch2.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrBatch2.Name = "xrBatch2"; this.xrBatch2.StylePriority.UseBorders = false; this.xrBatch2.StylePriority.UseTextAlignment = false; this.xrBatch2.Text = "xrBatch2"; this.xrBatch2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrBatch2.Weight = 0.21932981924775033D; // // xrBatch3 // this.xrBatch3.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrBatch3.Name = "xrBatch3"; this.xrBatch3.Padding = new DevExpress.XtraPrinting.PaddingInfo(5, 0, 0, 0, 100F); this.xrBatch3.StylePriority.UseBorders = false; this.xrBatch3.StylePriority.UsePadding = false; this.xrBatch3.StylePriority.UseTextAlignment = false; this.xrBatch3.Text = "xrBatch3"; this.xrBatch3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrBatch3.Weight = 0.21932982002991075D; // // xrBatch4 // this.xrBatch4.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrBatch4.Name = "xrBatch4"; this.xrBatch4.StylePriority.UseBorders = false; this.xrBatch4.StylePriority.UseTextAlignment = false; this.xrBatch4.Text = "xrBatch4"; this.xrBatch4.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrBatch4.Weight = 0.21932980591515972D; // // xrBatch5 // this.xrBatch5.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrBatch5.Name = "xrBatch5"; this.xrBatch5.StylePriority.UseBorders = false; this.xrBatch5.StylePriority.UseTextAlignment = false; this.xrBatch5.Text = "xrBatch5"; this.xrBatch5.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrBatch5.Weight = 0.21932981354501713D; // // xrBatch6 // this.xrBatch6.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrBatch6.Name = "xrBatch6"; this.xrBatch6.StylePriority.UseBorders = false; this.xrBatch6.StylePriority.UseTextAlignment = false; this.xrBatch6.Text = "xrBatch6"; this.xrBatch6.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrBatch6.Weight = 0.21932980797892387D; // // xrBatchB // this.xrBatchB.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrBatchB.Name = "xrBatchB"; this.xrBatchB.StylePriority.UseBorders = false; this.xrBatchB.StylePriority.UseTextAlignment = false; this.xrBatchB.Text = "xrBatchB"; this.xrBatchB.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrBatchB.Weight = 0.2193298025618684D; // // xrBatchW // this.xrBatchW.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrBatchW.Name = "xrBatchW"; this.xrBatchW.StylePriority.UseBorders = false; this.xrBatchW.StylePriority.UseTextAlignment = false; this.xrBatchW.Text = "xrBatchW"; this.xrBatchW.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrBatchW.Weight = 0.21932980514517925D; // // xrBatchL // this.xrBatchL.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrBatchL.Name = "xrBatchL"; this.xrBatchL.StylePriority.UseBorders = false; this.xrBatchL.StylePriority.UseTextAlignment = false; this.xrBatchL.Text = "xrBatchL"; this.xrBatchL.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrBatchL.Weight = 0.21932980436755359D; // // xrAllBatch // this.xrAllBatch.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrAllBatch.Name = "xrAllBatch"; this.xrAllBatch.StylePriority.UseBorders = false; this.xrAllBatch.StylePriority.UseTextAlignment = false; this.xrAllBatch.Text = "xrAllBatch"; this.xrAllBatch.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrAllBatch.Weight = 0.25437855038829715D; // // TopMargin // this.TopMargin.HeightF = 42F; this.TopMargin.Name = "TopMargin"; this.TopMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.TopMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft; // // BottomMargin // this.BottomMargin.HeightF = 34.24994F; this.BottomMargin.Name = "BottomMargin"; this.BottomMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.BottomMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xlZX, this.xlZXDate, this.xlKDDate, this.xlKD1, this.xrDY1, this.xlDYstart, this.xrDY2, this.xlDYEnd, this.xrRepertHeader}); this.ReportHeader.HeightF = 111.1667F; this.ReportHeader.Name = "ReportHeader"; // // xlZX // this.xlZX.Font = new System.Drawing.Font("Times New Roman", 9.75F); this.xlZX.LocationFloat = new DevExpress.Utils.PointFloat(633.5764F, 78.16674F); this.xlZX.Name = "xlZX"; this.xlZX.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xlZX.SizeF = new System.Drawing.SizeF(82.59384F, 23.00001F); this.xlZX.StylePriority.UseFont = false; this.xlZX.StylePriority.UseTextAlignment = false; this.xlZX.Text = "执行日期:"; this.xlZX.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xlZX.Visible = false; // // xlZXDate // this.xlZXDate.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold); this.xlZXDate.LocationFloat = new DevExpress.Utils.PointFloat(716.1702F, 78.16674F); this.xlZXDate.Name = "xlZXDate"; this.xlZXDate.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xlZXDate.SizeF = new System.Drawing.SizeF(108.3733F, 23.00002F); this.xlZXDate.StylePriority.UseFont = false; this.xlZXDate.StylePriority.UseTextAlignment = false; this.xlZXDate.Text = "2222/22/22"; this.xlZXDate.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xlZXDate.Visible = false; // // xlKDDate // this.xlKDDate.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold); this.xlKDDate.LocationFloat = new DevExpress.Utils.PointFloat(525.2031F, 78.16674F); this.xlKDDate.Name = "xlKDDate"; this.xlKDDate.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xlKDDate.SizeF = new System.Drawing.SizeF(108.3733F, 23.00002F); this.xlKDDate.StylePriority.UseFont = false; this.xlKDDate.StylePriority.UseTextAlignment = false; this.xlKDDate.Text = "2222/22/22"; this.xlKDDate.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xlKDDate.Visible = false; // // xlKD1 // this.xlKD1.Font = new System.Drawing.Font("Times New Roman", 9.75F); this.xlKD1.LocationFloat = new DevExpress.Utils.PointFloat(442.6093F, 78.16674F); this.xlKD1.Name = "xlKD1"; this.xlKD1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xlKD1.SizeF = new System.Drawing.SizeF(82.59384F, 23.00001F); this.xlKD1.StylePriority.UseFont = false; this.xlKD1.StylePriority.UseTextAlignment = false; this.xlKD1.Text = "开单日期:"; this.xlKD1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xlKD1.Visible = false; // // xrDY1 // this.xrDY1.Font = new System.Drawing.Font("Times New Roman", 9.75F); this.xrDY1.LocationFloat = new DevExpress.Utils.PointFloat(18.99999F, 78.16671F); this.xrDY1.Name = "xrDY1"; this.xrDY1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrDY1.SizeF = new System.Drawing.SizeF(82.59384F, 23.00001F); this.xrDY1.StylePriority.UseFont = false; this.xrDY1.StylePriority.UseTextAlignment = false; this.xrDY1.Text = "打印时间:"; this.xrDY1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrDY1.Visible = false; // // xlDYstart // this.xlDYstart.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold); this.xlDYstart.LocationFloat = new DevExpress.Utils.PointFloat(101.5938F, 78.16671F); this.xlDYstart.Name = "xlDYstart"; this.xlDYstart.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xlDYstart.SizeF = new System.Drawing.SizeF(156.8757F, 23.00002F); this.xlDYstart.StylePriority.UseFont = false; this.xlDYstart.StylePriority.UseTextAlignment = false; this.xlDYstart.Text = "2222/22/22 22:33:33"; this.xlDYstart.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xlDYstart.Visible = false; // // xrDY2 // this.xrDY2.Font = new System.Drawing.Font("Times New Roman", 9.75F); this.xrDY2.LocationFloat = new DevExpress.Utils.PointFloat(258.4695F, 78.16671F); this.xrDY2.Name = "xrDY2"; this.xrDY2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrDY2.SizeF = new System.Drawing.SizeF(27.2641F, 23.00001F); this.xrDY2.StylePriority.UseFont = false; this.xrDY2.StylePriority.UseTextAlignment = false; this.xrDY2.Text = "~"; this.xrDY2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrDY2.Visible = false; // // xlDYEnd // this.xlDYEnd.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold); this.xlDYEnd.LocationFloat = new DevExpress.Utils.PointFloat(285.7336F, 78.16671F); this.xlDYEnd.Name = "xlDYEnd"; this.xlDYEnd.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xlDYEnd.SizeF = new System.Drawing.SizeF(156.8757F, 22.99998F); this.xlDYEnd.StylePriority.UseFont = false; this.xlDYEnd.StylePriority.UseTextAlignment = false; this.xlDYEnd.Text = "2222/22/22 22:33:33"; this.xlDYEnd.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xlDYEnd.Visible = false; // // xrRepertHeader // this.xrRepertHeader.Font = new System.Drawing.Font("Times New Roman", 24F, System.Drawing.FontStyle.Bold); this.xrRepertHeader.LocationFloat = new DevExpress.Utils.PointFloat(16.5F, 10.00001F); this.xrRepertHeader.Name = "xrRepertHeader"; this.xrRepertHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrRepertHeader.SizeF = new System.Drawing.SizeF(823.4999F, 45.91666F); this.xrRepertHeader.StylePriority.UseFont = false; this.xrRepertHeader.StylePriority.UseTextAlignment = false; this.xrRepertHeader.Text = "瓶贴汇总"; this.xrRepertHeader.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; // // ReportFooter // this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLabel8, this.xrPrintBy, this.lblPrintDate, this.xrLabel6, this.xrPageInfo1}); this.ReportFooter.HeightF = 60.66672F; this.ReportFooter.Name = "ReportFooter"; // // xrLabel8 // this.xrLabel8.Font = new System.Drawing.Font("Times New Roman", 9F); this.xrLabel8.LocationFloat = new DevExpress.Utils.PointFloat(18.99999F, 10.00001F); this.xrLabel8.Multiline = true; this.xrLabel8.Name = "xrLabel8"; this.xrLabel8.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel8.SizeF = new System.Drawing.SizeF(67.70834F, 23F); this.xrLabel8.StylePriority.UseFont = false; this.xrLabel8.StylePriority.UseTextAlignment = false; this.xrLabel8.Text = "打印人:\r\n"; this.xrLabel8.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft; // // xrPrintBy // this.xrPrintBy.Font = new System.Drawing.Font("Times New Roman", 9F); this.xrPrintBy.LocationFloat = new DevExpress.Utils.PointFloat(86.70836F, 10.00001F); this.xrPrintBy.Name = "xrPrintBy"; this.xrPrintBy.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrPrintBy.SizeF = new System.Drawing.SizeF(134.375F, 22.99999F); this.xrPrintBy.StylePriority.UseFont = false; this.xrPrintBy.StylePriority.UseTextAlignment = false; this.xrPrintBy.Text = "xrPrintBy"; this.xrPrintBy.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft; // // lblPrintDate // this.lblPrintDate.Font = new System.Drawing.Font("Times New Roman", 9.75F); this.lblPrintDate.LocationFloat = new DevExpress.Utils.PointFloat(699.4152F, 10.00001F); this.lblPrintDate.Name = "lblPrintDate"; this.lblPrintDate.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.lblPrintDate.SizeF = new System.Drawing.SizeF(145.4509F, 23.00002F); this.lblPrintDate.StylePriority.UseFont = false; this.lblPrintDate.StylePriority.UseTextAlignment = false; this.lblPrintDate.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleLeft; // // xrLabel6 // this.xrLabel6.Font = new System.Drawing.Font("Times New Roman", 9.75F); this.xrLabel6.LocationFloat = new DevExpress.Utils.PointFloat(602.238F, 10.00001F); this.xrLabel6.Name = "xrLabel6"; this.xrLabel6.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel6.SizeF = new System.Drawing.SizeF(97.17715F, 23.00001F); this.xrLabel6.StylePriority.UseFont = false; this.xrLabel6.StylePriority.UseTextAlignment = false; this.xrLabel6.Text = "打印时间:"; this.xrLabel6.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleRight; // // xrPageInfo1 // this.xrPageInfo1.LocationFloat = new DevExpress.Utils.PointFloat(770.4121F, 33.00002F); this.xrPageInfo1.Name = "xrPageInfo1"; this.xrPageInfo1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrPageInfo1.SizeF = new System.Drawing.SizeF(50F, 23F); // // xr // this.xr.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xr.Name = "xr"; this.xr.Padding = new DevExpress.XtraPrinting.PaddingInfo(5, 0, 0, 0, 100F); this.xr.StylePriority.UseBorders = false; this.xr.StylePriority.UsePadding = false; this.xr.StylePriority.UseTextAlignment = false; this.xr.Text = "第2批"; this.xr.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xr.Weight = 0.21635782812123941D; // // xrTableCell3 // this.xrTableCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell3.Name = "xrTableCell3"; this.xrTableCell3.StylePriority.UseBorders = false; this.xrTableCell3.StylePriority.UseTextAlignment = false; this.xrTableCell3.Text = "第1批"; this.xrTableCell3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrTableCell3.Weight = 0.21635782165233986D; // // xrTableCell2 // this.xrTableCell2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell2.Name = "xrTableCell2"; this.xrTableCell2.StylePriority.UseBorders = false; this.xrTableCell2.StylePriority.UseTextAlignment = false; this.xrTableCell2.Text = "早上批"; this.xrTableCell2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrTableCell2.Weight = 0.21635782739762832D; // // xrTableCell4 // this.xrTableCell4.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.StylePriority.UseBorders = false; this.xrTableCell4.StylePriority.UseTextAlignment = false; this.xrTableCell4.Text = "病区\\批次"; this.xrTableCell4.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrTableCell4.Weight = 0.55500149632994178D; // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell4, this.xrTableCell2, this.xrTableCell3, this.xr, this.xrTableCell1, this.xrTableCell8, this.xrTableCell9, this.xrTableCell10, this.xrTableCell11, this.xrTableCell5, this.xrTableCell6, this.xrTableCell7}); this.xrTableRow3.Name = "xrTableRow3"; this.xrTableRow3.Weight = 1D; // // xrTableCell1 // this.xrTableCell1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell1.Name = "xrTableCell1"; this.xrTableCell1.StylePriority.UseBorders = false; this.xrTableCell1.StylePriority.UseTextAlignment = false; this.xrTableCell1.Text = "第3批"; this.xrTableCell1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrTableCell1.Weight = 0.21635793591515309D; // // xrTableCell8 // this.xrTableCell8.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseBorders = false; this.xrTableCell8.Text = "第4批"; this.xrTableCell8.Weight = 0.21635784117031898D; // // xrTableCell9 // this.xrTableCell9.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.StylePriority.UseBorders = false; this.xrTableCell9.Text = "第5批"; this.xrTableCell9.Weight = 0.21635794209431053D; // // xrTableCell10 // this.xrTableCell10.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.StylePriority.UseBorders = false; this.xrTableCell10.Text = "第6批"; this.xrTableCell10.Weight = 0.21635761118606367D; // // xrTableCell11 // this.xrTableCell11.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell11.Name = "xrTableCell11"; this.xrTableCell11.StylePriority.UseBorders = false; this.xrTableCell11.Text = "打包"; this.xrTableCell11.Weight = 0.21635761118606367D; // // xrTableCell5 // this.xrTableCell5.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell5.Name = "xrTableCell5"; this.xrTableCell5.StylePriority.UseBorders = false; this.xrTableCell5.StylePriority.UseTextAlignment = false; this.xrTableCell5.Text = "打包2"; this.xrTableCell5.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrTableCell5.Weight = 0.2163580562136298D; // // xrTableCell6 // this.xrTableCell6.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell6.Name = "xrTableCell6"; this.xrTableCell6.StylePriority.UseBorders = false; this.xrTableCell6.StylePriority.UseTextAlignment = false; this.xrTableCell6.Text = "临时"; this.xrTableCell6.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrTableCell6.Weight = 0.21635783261726718D; // // xrTableCell7 // this.xrTableCell7.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.StylePriority.UseBorders = false; this.xrTableCell7.StylePriority.UseTextAlignment = false; this.xrTableCell7.Text = "全部批次"; this.xrTableCell7.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; this.xrTableCell7.Weight = 0.25093144098893139D; // // xrTable3 // this.xrTable3.LocationFloat = new DevExpress.Utils.PointFloat(16.5F, 0F); this.xrTable3.Name = "xrTable3"; this.xrTable3.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow3}); this.xrTable3.SizeF = new System.Drawing.SizeF(823.5F, 25F); this.xrTable3.StylePriority.UseTextAlignment = false; this.xrTable3.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; // // GroupHeader1 // this.GroupHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable3}); this.GroupHeader1.HeightF = 25F; this.GroupHeader1.Name = "GroupHeader1"; // // BatchIllfieldLabelCollectReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.ReportHeader, this.ReportFooter, this.BottomMargin, this.Detail, this.TopMargin, this.GroupHeader1}); this.Margins = new System.Drawing.Printing.Margins(0, 0, 42, 34); this.Version = "12.1"; ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailBand Detail; private DevExpress.XtraReports.UI.TopMarginBand TopMargin; private DevExpress.XtraReports.UI.BottomMarginBand BottomMargin; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private DevExpress.XtraReports.UI.XRLabel lblPrintDate; private DevExpress.XtraReports.UI.XRLabel xrLabel6; private DevExpress.XtraReports.UI.XRLabel xrRepertHeader; private DevExpress.XtraReports.UI.XRPageInfo xrPageInfo1; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrIllfield; private DevExpress.XtraReports.UI.XRTableCell xrBatch1; private DevExpress.XtraReports.UI.XRTableCell xrBatch2; private DevExpress.XtraReports.UI.XRTableCell xrBatch3; private DevExpress.XtraReports.UI.XRLabel xrLabel8; private DevExpress.XtraReports.UI.XRLabel xrPrintBy; private DevExpress.XtraReports.UI.XRTableCell xr; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTable xrTable3; private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeader1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrBatch4; private DevExpress.XtraReports.UI.XRTableCell xrBatch5; private DevExpress.XtraReports.UI.XRTableCell xrBatch6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrAllBatch; private DevExpress.XtraReports.UI.XRTableCell xrBatchZ; private DevExpress.XtraReports.UI.XRTableCell xrBatchB; private DevExpress.XtraReports.UI.XRTableCell xrBatchL; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRLabel xrDY1; private DevExpress.XtraReports.UI.XRLabel xlDYstart; private DevExpress.XtraReports.UI.XRLabel xrDY2; private DevExpress.XtraReports.UI.XRLabel xlDYEnd; private DevExpress.XtraReports.UI.XRLabel xlKDDate; private DevExpress.XtraReports.UI.XRLabel xlKD1; private DevExpress.XtraReports.UI.XRTableCell xrBatchW; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRLabel xlZX; private DevExpress.XtraReports.UI.XRLabel xlZXDate; } }
leborety/CJia
CJia.PIVAS.JiuJiang/CJia.PIVAS.App/UI/BatchIllfieldLabelCollectReport.designer.cs
C#
apache-2.0
37,992
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2016 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ package ti.modules.titanium.geolocation; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import org.appcelerator.kroll.KrollDict; import org.appcelerator.kroll.KrollFunction; import org.appcelerator.kroll.KrollModule; import org.appcelerator.kroll.KrollProxy; import org.appcelerator.kroll.KrollRuntime; import org.appcelerator.kroll.annotations.Kroll; import org.appcelerator.kroll.common.Log; import org.appcelerator.titanium.TiApplication; import org.appcelerator.titanium.TiBaseActivity; import org.appcelerator.titanium.TiC; import org.appcelerator.titanium.analytics.TiAnalyticsEventFactory; import org.appcelerator.titanium.util.TiConvert; import ti.modules.titanium.geolocation.TiLocation.GeocodeResponseHandler; import ti.modules.titanium.geolocation.android.AndroidModule; import ti.modules.titanium.geolocation.android.LocationProviderProxy; import ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener; import ti.modules.titanium.geolocation.android.LocationRuleProxy; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Build; import android.os.Handler; import android.os.Message; /** * GeolocationModule exposes all common methods and properties relating to geolocation behavior * associated with Ti.Geolocation to the Titanium developer. Only cross platform API points should * be exposed through this class as Android-only API points or types should be put in a Android module * under this module. * * The GeolocationModule provides management for 3 different location behavior modes (detailed * descriptions will follow below): * <ul> * <li>legacy - existing behavior found in Titanium Mobile 1.7 and 1.8. <b>DEPRECATED</b></li> * <li>simple - replacement for the old legacy mode that allows for better parity across platforms</li> * <li>manual - Android-specific mode that exposes full control over the providers and rules</li> * </ul> * * <p> * <b>Legacy location mode</b>:<br> * This mode operates on receiving location updates from a single active provider at a time. Settings * used to pick and register a provider with the OS are pulled from the PROPERTY_ACCURACY, PROPERTY_FREQUENCY * and PROPERTY_PREFERRED_PROVIDER properties on the module. * <p> * The valid accuracy properties for this location mode are ACCURACY_BEST, ACCURACY_NEAREST_TEN_METERS, * ACCURACY_HUNDRED_METERS, ACCURACY_KILOMETER and ACCURACY_THREE_KILOMETERS. The accuracy property is a * double value that will be used by the OS as a way to determine how many meters should change in location * before a new update is sent. Accuracy properties other than this will either be ignored or change the * current location behavior mode. The frequency property is a double value that is used by the OS to determine * how much time in milliseconds should pass before a new update is sent. * <p> * The OS uses some fuzzy logic to determine the update frequency and these values are treated as no more than * suggestions. For example: setting the frequency to 0 milliseconds and the accuracy to 10 meters may not * result in a update being sent as fast as possible which is what frequency of 0 ms indicates. This is due to * the OS not sending updates till the accuracy property is satisfied. If the desired behavior is to get updates * purely based on time then the suggested mechanism would be to set the accuracy to 0 meters and then set the * frequency to the desired update interval in milliseconds. * * <p> * <b>Simple location mode</b>:<br> * This mode operates on receiving location updates from multiple sources. The simple mode has two states - high * accuracy and low accuracy. The difference in these two modes is that low accuracy has the passive and network * providers registered by default where the high accuracy state enables the gps provider in addition to the passive * and network providers. The simple mode utilizes location rules for filtering location updates to try and fall back * gracefully (when in high accuracy state) to the network and passive providers if a gps update has not been received * recently. * <p> * No specific controls for time or distance (better terminology in line with native Android docs but these * are called frequency and accuracy in legacy mode) are exposed to the Titanium developer as the details of this mode * are supposed to be driven by Appcelerator based on our observations. If greater control on the part of the Titanium * developer is needed then the manual behavior mode can and should be used. * * <p> * <b>Manual location mode</b>:<br> * This mode puts full control over providers and rules in the hands of the Titanium developer. The developer will be * responsible for registering location providers, setting time and distance settings per provider and defining the rule * set if any rules are desired. * <p> * In this mode, the developer would create a Ti.Geolocation.Android.LocationProvider object for each provider they want * to use and add this to the list of manual providers via addLocationProvider(LocationProviderProxy). In order to set * rules, the developer will have to create a Ti.Geolocation.Android.LocationRule object per rule and then add those * rules via addLocationRule(LocationRuleProxy). These rules will be applied to any location updates that come from the * registered providers. Further information on the LocationProvider and LocationRule objects can be found by looking at * those specific classes. * * <p> * <b>General location behavior</b>:<br> * The GeolocationModule is capable of switching modes at any time and keeping settings per mode separated. Changing modes * is done by updating the Ti.Geolocation.accuracy property. Based on the new value of the accuracy property, the * legacy or simple modes may be enabled (and the previous mode may be turned off). Enabling or disabling the manual mode * is done by setting the AndroidModule.manualMode (Ti.Geolocation.Android.manualMode) value. NOTE: updating the location * rules will not update the mode. Simply setting the Ti.Geolocation.accuracy property will not enable the legacy/simple * modes if you are currently in the manual mode - you must disable the manual mode before the simple/legacy modes are used * <p> * In regards to actually "turning on" the providers by registering them with the OS - this is triggered by the presence of * "location" event listeners on the GeolocationModule. When the first listener is added, providers start being registered * with the OS. When there are no listeners then all the providers are de-registered. Changes made to location providers or * accuracy, frequency properties or even changing modes are respected and kept but don't actually get applied on the OS until * the listener count is greater than 0. */ // TODO deprecate the frequency and preferredProvider property @Kroll.module(propertyAccessors={ TiC.PROPERTY_ACCURACY, TiC.PROPERTY_FREQUENCY, TiC.PROPERTY_PREFERRED_PROVIDER }) public class GeolocationModule extends KrollModule implements Handler.Callback, LocationProviderListener { // TODO move these to the AndroidModule namespace since they will only be used when creating // manual location providers @Kroll.constant @Deprecated public static final String PROVIDER_PASSIVE = LocationManager.PASSIVE_PROVIDER; @Kroll.constant @Deprecated public static final String PROVIDER_NETWORK = LocationManager.NETWORK_PROVIDER; @Kroll.constant @Deprecated public static final String PROVIDER_GPS = LocationManager.GPS_PROVIDER; @Kroll.constant public static final int ACCURACY_LOW = 0; @Kroll.constant public static final int ACCURACY_HIGH = 1; @Kroll.constant @Deprecated public static final int ACCURACY_BEST = 2; @Kroll.constant @Deprecated public static final int ACCURACY_NEAREST_TEN_METERS = 3; @Kroll.constant @Deprecated public static final int ACCURACY_HUNDRED_METERS = 4; @Kroll.constant @Deprecated public static final int ACCURACY_KILOMETER = 5; @Kroll.constant @Deprecated public static final int ACCURACY_THREE_KILOMETERS = 6; public TiLocation tiLocation; public AndroidModule androidModule; public int numLocationListeners = 0; public HashMap<String, LocationProviderProxy> simpleLocationProviders = new HashMap<String, LocationProviderProxy>(); @Deprecated public HashMap<String, LocationProviderProxy> legacyLocationProviders = new HashMap<String, LocationProviderProxy>(); public boolean legacyModeActive = true; protected static final int MSG_ENABLE_LOCATION_PROVIDERS = KrollModule.MSG_LAST_ID + 100; protected static final int MSG_LAST_ID = MSG_ENABLE_LOCATION_PROVIDERS; private static final String TAG = "GeolocationModule"; private static final double SIMPLE_LOCATION_PASSIVE_DISTANCE = 0.0; private static final double SIMPLE_LOCATION_PASSIVE_TIME = 0; private static final double SIMPLE_LOCATION_NETWORK_DISTANCE = 10.0; private static final double SIMPLE_LOCATION_NETWORK_TIME = 10000; private static final double SIMPLE_LOCATION_GPS_DISTANCE = 3.0; private static final double SIMPLE_LOCATION_GPS_TIME = 3000; private static final double SIMPLE_LOCATION_NETWORK_DISTANCE_RULE = 200; private static final double SIMPLE_LOCATION_NETWORK_MIN_AGE_RULE = 60000; private static final double SIMPLE_LOCATION_GPS_MIN_AGE_RULE = 30000; private TiCompass tiCompass; private boolean compassListenersRegistered = false; private boolean sentAnalytics = false; private ArrayList<LocationRuleProxy> simpleLocationRules = new ArrayList<LocationRuleProxy>(); private LocationRuleProxy simpleLocationGpsRule; private LocationRuleProxy simpleLocationNetworkRule; private int simpleLocationAccuracyProperty = ACCURACY_LOW; private Location currentLocation; //currentLocation is conditionally updated. lastLocation is unconditionally updated //since currentLocation determines when to send out updates, and lastLocation is passive private Location lastLocation; @Deprecated private HashMap<Integer, Double> legacyLocationAccuracyMap = new HashMap<Integer, Double>(); @Deprecated private int legacyLocationAccuracyProperty = ACCURACY_NEAREST_TEN_METERS; @Deprecated private double legacyLocationFrequency = 5000; @Deprecated private String legacyLocationPreferredProvider = PROVIDER_NETWORK; /** * Constructor */ public GeolocationModule() { super("geolocation"); tiLocation = new TiLocation(); tiCompass = new TiCompass(this, tiLocation); // initialize the legacy location accuracy map legacyLocationAccuracyMap.put(ACCURACY_BEST, 0.0); // this needs to be 0.0 to work for only time based updates legacyLocationAccuracyMap.put(ACCURACY_NEAREST_TEN_METERS, 10.0); legacyLocationAccuracyMap.put(ACCURACY_HUNDRED_METERS, 100.0); legacyLocationAccuracyMap.put(ACCURACY_KILOMETER, 1000.0); legacyLocationAccuracyMap.put(ACCURACY_THREE_KILOMETERS, 3000.0); legacyLocationProviders.put(PROVIDER_NETWORK, new LocationProviderProxy(PROVIDER_NETWORK, 10.0f, legacyLocationFrequency, this)); simpleLocationProviders.put(PROVIDER_NETWORK, new LocationProviderProxy(PROVIDER_NETWORK, SIMPLE_LOCATION_NETWORK_DISTANCE, SIMPLE_LOCATION_NETWORK_TIME, this)); simpleLocationProviders.put(PROVIDER_PASSIVE, new LocationProviderProxy(PROVIDER_PASSIVE, SIMPLE_LOCATION_PASSIVE_DISTANCE, SIMPLE_LOCATION_PASSIVE_TIME, this)); // create these now but we don't want to include these in the rule set unless the simple GPS provider is enabled simpleLocationGpsRule = new LocationRuleProxy(PROVIDER_GPS, null, SIMPLE_LOCATION_GPS_MIN_AGE_RULE, null); simpleLocationNetworkRule = new LocationRuleProxy(PROVIDER_NETWORK, SIMPLE_LOCATION_NETWORK_DISTANCE_RULE, SIMPLE_LOCATION_NETWORK_MIN_AGE_RULE, null); } /** * @see org.appcelerator.kroll.KrollProxy#handleMessage(android.os.Message) */ @Override public boolean handleMessage(Message message) { switch (message.what) { case MSG_ENABLE_LOCATION_PROVIDERS: { Object locationProviders = message.obj; doEnableLocationProviders((HashMap<String, LocationProviderProxy>) locationProviders); return true; } } return super.handleMessage(message); } private void doAnalytics(Location location) { if (!sentAnalytics) { tiLocation.doAnalytics(location); sentAnalytics = true; } } /** * Called by a registered location provider when a location update is received * * @param location location update that was received * * @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onLocationChanged(android.location.Location) */ public void onLocationChanged(Location location) { lastLocation = location; if (shouldUseUpdate(location)) { fireEvent(TiC.EVENT_LOCATION, buildLocationEvent(location, tiLocation.locationManager.getProvider(location.getProvider()))); currentLocation = location; doAnalytics(location); } } /** * Called by a registered location provider when its state changes * * @param providerName name of the provider whose state has changed * @param state new state of the provider * * @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onProviderStateChanged(java.lang.String, int) */ public void onProviderStateChanged(String providerName, int state) { String message = providerName; // TODO this is trash. deprecate the existing mechanism of bundling status updates with the // location event and create a new "locationState" (or whatever) event. for the time being, // this solution kills my soul slightly less than the previous one switch (state) { case LocationProviderProxy.STATE_DISABLED: message += " is disabled"; Log.i(TAG, message, Log.DEBUG_MODE); fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message)); break; case LocationProviderProxy.STATE_ENABLED: message += " is enabled"; Log.d(TAG, message, Log.DEBUG_MODE); break; case LocationProviderProxy.STATE_OUT_OF_SERVICE: message += " is out of service"; Log.d(TAG, message, Log.DEBUG_MODE); fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message)); break; case LocationProviderProxy.STATE_UNAVAILABLE: message += " is unavailable"; Log.d(TAG, message, Log.DEBUG_MODE); fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message)); break; case LocationProviderProxy.STATE_AVAILABLE: message += " is available"; Log.d(TAG, message, Log.DEBUG_MODE); break; case LocationProviderProxy.STATE_UNKNOWN: message += " is in a unknown state [" + state + "]"; Log.d(TAG, message, Log.DEBUG_MODE); fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message)); break; default: message += " is in a unknown state [" + state + "]"; Log.d(TAG, message, Log.DEBUG_MODE); fireEvent(TiC.EVENT_LOCATION, buildLocationErrorEvent(state, message)); break; } } /** * Called when the location provider has had one of it's properties updated and thus needs to be re-registered with the OS * * @param locationProvider the location provider that needs to be re-registered * * @see ti.modules.titanium.geolocation.android.LocationProviderProxy.LocationProviderListener#onProviderUpdated(ti.modules.titanium.geolocation.android.LocationProviderProxy) */ public void onProviderUpdated(LocationProviderProxy locationProvider) { if (getManualMode() && (numLocationListeners > 0)) { tiLocation.locationManager.removeUpdates(locationProvider); registerLocationProvider(locationProvider); } } /** * @see org.appcelerator.kroll.KrollModule#propertyChanged(java.lang.String, java.lang.Object, java.lang.Object, org.appcelerator.kroll.KrollProxy) */ @Override public void propertyChanged(String key, Object oldValue, Object newValue, KrollProxy proxy) { if (key.equals(TiC.PROPERTY_ACCURACY)) { // accuracy property is what triggers a shift between simple and legacy modes. the // android only manual mode is indicated by the AndroidModule.manualMode value which // has no impact on the legacyModeActive flag. IE: when determining the current mode, // both flags must be checked propertyChangedAccuracy(newValue); } else if (key.equals(TiC.PROPERTY_FREQUENCY)) { propertyChangedFrequency(newValue); } else if (key.equals(TiC.PROPERTY_PREFERRED_PROVIDER)) { propertyChangedPreferredProvider(newValue); } } /** * Handles property change for Ti.Geolocation.accuracy * * @param newValue new accuracy value */ private void propertyChangedAccuracy(Object newValue) { // is legacy mode enabled (registered with OS, not just selected via the accuracy property) boolean legacyModeEnabled = false; if (legacyModeActive && (!getManualMode()) && (numLocationListeners > 0)) { legacyModeEnabled = true; } // is simple mode enabled (registered with OS, not just selected via the accuracy property) boolean simpleModeEnabled = false; if (!legacyModeActive && !(getManualMode()) && (numLocationListeners > 0)) { simpleModeEnabled = true; } int accuracyProperty = TiConvert.toInt(newValue); // is this a legacy accuracy property? Double accuracyLookupResult = legacyLocationAccuracyMap.get(accuracyProperty); if (accuracyLookupResult != null) { // has the value changed from the last known good value? if (accuracyProperty != legacyLocationAccuracyProperty) { legacyLocationAccuracyProperty = accuracyProperty; for (String providerKey : legacyLocationProviders.keySet()) { LocationProviderProxy locationProvider = legacyLocationProviders.get(providerKey); locationProvider.setProperty(TiC.PROPERTY_MIN_UPDATE_DISTANCE, accuracyLookupResult); } if (legacyModeEnabled) { enableLocationProviders(legacyLocationProviders); } } if (simpleModeEnabled) { enableLocationProviders(legacyLocationProviders); } legacyModeActive = true; // is this a simple accuracy property? } else if ((accuracyProperty == ACCURACY_HIGH) || (accuracyProperty == ACCURACY_LOW)) { // has the value changed from the last known good value? if (accuracyProperty != simpleLocationAccuracyProperty) { simpleLocationAccuracyProperty = accuracyProperty; LocationProviderProxy gpsProvider = simpleLocationProviders.get(PROVIDER_GPS); if ((accuracyProperty == ACCURACY_HIGH) && (gpsProvider == null)) { gpsProvider = new LocationProviderProxy(PROVIDER_GPS, SIMPLE_LOCATION_GPS_DISTANCE, SIMPLE_LOCATION_GPS_TIME, this); simpleLocationProviders.put(PROVIDER_GPS, gpsProvider); simpleLocationRules.add(simpleLocationNetworkRule); simpleLocationRules.add(simpleLocationGpsRule); if (simpleModeEnabled) { registerLocationProvider(gpsProvider); } } else if ((accuracyProperty == ACCURACY_LOW) && (gpsProvider != null)) { simpleLocationProviders.remove(PROVIDER_GPS); simpleLocationRules.remove(simpleLocationNetworkRule); simpleLocationRules.remove(simpleLocationGpsRule); if (simpleModeEnabled) { tiLocation.locationManager.removeUpdates(gpsProvider); } } } if (legacyModeEnabled) { enableLocationProviders(simpleLocationProviders); } legacyModeActive = false; } } /** * Handles property change for Ti.Geolocation.frequency * * @param newValue new frequency value */ private void propertyChangedFrequency(Object newValue) { // is legacy mode enabled (registered with OS, not just selected via the accuracy property) boolean legacyModeEnabled = false; if (legacyModeActive && !getManualMode() && (numLocationListeners > 0)) { legacyModeEnabled = true; } double frequencyProperty = TiConvert.toDouble(newValue) * 1000; if (frequencyProperty != legacyLocationFrequency) { legacyLocationFrequency = frequencyProperty; Iterator<String> iterator = legacyLocationProviders.keySet().iterator(); while(iterator.hasNext()) { LocationProviderProxy locationProvider = legacyLocationProviders.get(iterator.next()); locationProvider.setProperty(TiC.PROPERTY_MIN_UPDATE_TIME, legacyLocationFrequency); } if (legacyModeEnabled) { enableLocationProviders(legacyLocationProviders); } } } /** * Handles property change for Ti.Geolocation.preferredProvider * * @param newValue new preferredProvider value */ private void propertyChangedPreferredProvider(Object newValue) { // is legacy mode enabled (registered with OS, not just selected via the accuracy property) boolean legacyModeEnabled = false; if (legacyModeActive && !getManualMode() && (numLocationListeners > 0)) { legacyModeEnabled = true; } String preferredProviderProperty = TiConvert.toString(newValue); if (!(preferredProviderProperty.equals(PROVIDER_NETWORK)) && (!(preferredProviderProperty.equals(PROVIDER_GPS)))) { return; } if (!(preferredProviderProperty.equals(legacyLocationPreferredProvider))) { LocationProviderProxy oldProvider = legacyLocationProviders.get(legacyLocationPreferredProvider); LocationProviderProxy newProvider = legacyLocationProviders.get(preferredProviderProperty); if (oldProvider != null) { legacyLocationProviders.remove(legacyLocationPreferredProvider); if (legacyModeEnabled) { tiLocation.locationManager.removeUpdates(oldProvider); } } if (newProvider == null) { newProvider = new LocationProviderProxy(preferredProviderProperty, legacyLocationAccuracyMap.get(legacyLocationAccuracyProperty), legacyLocationFrequency, this); legacyLocationProviders.put(preferredProviderProperty, newProvider); if (legacyModeEnabled) { registerLocationProvider(newProvider); } } legacyLocationPreferredProvider = preferredProviderProperty; } } /** * @see org.appcelerator.kroll.KrollProxy#eventListenerAdded(java.lang.String, int, org.appcelerator.kroll.KrollProxy) */ @Override protected void eventListenerAdded(String event, int count, KrollProxy proxy) { if (TiC.EVENT_HEADING.equals(event)) { if (!compassListenersRegistered) { tiCompass.registerListener(); compassListenersRegistered = true; } } else if (TiC.EVENT_LOCATION.equals(event)) { numLocationListeners++; if (numLocationListeners == 1) { HashMap<String, LocationProviderProxy> locationProviders = legacyLocationProviders; if (getManualMode()) { locationProviders = androidModule.manualLocationProviders; } else if (!legacyModeActive) { locationProviders = simpleLocationProviders; } enableLocationProviders(locationProviders); // fire off an initial location fix if one is available if (!hasLocationPermissions()) { Log.e(TAG, "Location permissions missing"); return; } lastLocation = tiLocation.getLastKnownLocation(); if (lastLocation != null) { fireEvent(TiC.EVENT_LOCATION, buildLocationEvent(lastLocation, tiLocation.locationManager.getProvider(lastLocation.getProvider()))); doAnalytics(lastLocation); } } } super.eventListenerAdded(event, count, proxy); } /** * @see org.appcelerator.kroll.KrollProxy#eventListenerRemoved(java.lang.String, int, org.appcelerator.kroll.KrollProxy) */ @Override protected void eventListenerRemoved(String event, int count, KrollProxy proxy) { if (TiC.EVENT_HEADING.equals(event)) { if (compassListenersRegistered) { tiCompass.unregisterListener(); compassListenersRegistered = false; } } else if (TiC.EVENT_LOCATION.equals(event)) { numLocationListeners--; if (numLocationListeners == 0) { disableLocationProviders(); } } super.eventListenerRemoved(event, count, proxy); } /** * Checks if the device has a compass sensor * * @return <code>true</code> if the device has a compass, <code>false</code> if not */ @Kroll.method @Kroll.getProperty public boolean getHasCompass() { return tiCompass.getHasCompass(); } /** * Retrieves the current compass heading and returns it to the specified Javascript function * * @param listener Javascript function that will be invoked with the compass heading */ @Kroll.method public void getCurrentHeading(final KrollFunction listener) { tiCompass.getCurrentHeading(listener); } /** * Retrieves the last obtained location and returns it as JSON. * * @return String representing the last geolocation event */ @Kroll.method @Kroll.getProperty public String getLastGeolocation() { return TiAnalyticsEventFactory.locationToJSONString(lastLocation); } /** * Checks if the Android manual location behavior mode is currently enabled * * @return <code>true</code> if currently in manual mode, <code> * false</code> if the Android module has not been registered * yet with the OS or manual mode is not enabled */ private boolean getManualMode() { if (androidModule == null) { return false; } else { return androidModule.manualMode; } } @Kroll.method public boolean hasLocationPermissions() { if (Build.VERSION.SDK_INT < 23) { return true; } Activity currentActivity = TiApplication.getInstance().getCurrentActivity(); if (currentActivity.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { return true; } return false; } @Kroll.method public void requestLocationPermissions(@Kroll.argument(optional=true) Object type, @Kroll.argument(optional=true) KrollFunction permissionCallback) { if (hasLocationPermissions()) { return; } KrollFunction permissionCB; if (type instanceof KrollFunction && permissionCallback == null) { permissionCB = (KrollFunction) type; } else { permissionCB = permissionCallback; } TiBaseActivity.registerPermissionRequestCallback(TiC.PERMISSION_CODE_LOCATION, permissionCB, getKrollObject()); Activity currentActivity = TiApplication.getInstance().getCurrentActivity(); currentActivity.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, TiC.PERMISSION_CODE_LOCATION); } /** * Registers the specified location provider with the OS. Once the provider is registered, the OS * will begin to provider location updates as they are available * * @param locationProvider location provider to be registered */ public void registerLocationProvider(LocationProviderProxy locationProvider) { if (!hasLocationPermissions()) { Log.e(TAG, "Location permissions missing", Log.DEBUG_MODE); return; } String provider = TiConvert.toString(locationProvider.getProperty(TiC.PROPERTY_NAME)); try { tiLocation.locationManager.requestLocationUpdates( provider, (long) locationProvider.getMinUpdateTime(), (float) locationProvider.getMinUpdateDistance(), locationProvider); } catch (IllegalArgumentException e) { Log.e(TAG, "Unable to register [" + provider + "], provider is null"); } catch (SecurityException e) { Log.e(TAG, "Unable to register [" + provider + "], permission denied"); } } /** * Wrapper to ensure task executes on the runtime thread * * @param locationProviders list of location providers to enable by registering * the providers with the OS */ public void enableLocationProviders(HashMap<String, LocationProviderProxy> locationProviders) { if (KrollRuntime.getInstance().isRuntimeThread()) { doEnableLocationProviders(locationProviders); } else { Message message = getRuntimeHandler().obtainMessage(MSG_ENABLE_LOCATION_PROVIDERS, locationProviders); message.sendToTarget(); } } /** * Enables the specified location behavior mode by registering the associated * providers with the OS. Even if the specified mode is currently active, the * current mode will be disabled by de-registering all the associated providers * for that mode with the OS and then registering * them again. This can be useful in cases where the properties for all the * providers have been updated and they need to be re-registered in order for the * change to take effect. Modification of the list of providers for any mode * should occur on the runtime thread in order to make sure threading issues are * avoiding * * @param locationProviders */ private void doEnableLocationProviders(HashMap<String, LocationProviderProxy> locationProviders) { if (numLocationListeners > 0) { disableLocationProviders(); Iterator<String> iterator = locationProviders.keySet().iterator(); while(iterator.hasNext()) { LocationProviderProxy locationProvider = locationProviders.get(iterator.next()); registerLocationProvider(locationProvider); } } } /** * Disables the current mode by de-registering all the associated providers * for that mode with the OS. Providers are just de-registered with the OS, * not removed from the list of providers we associate with the behavior mode. */ private void disableLocationProviders() { for (LocationProviderProxy locationProvider : legacyLocationProviders.values()) { tiLocation.locationManager.removeUpdates(locationProvider); } for (LocationProviderProxy locationProvider : simpleLocationProviders.values()) { tiLocation.locationManager.removeUpdates(locationProvider); } if (androidModule != null) { for (LocationProviderProxy locationProvider : androidModule.manualLocationProviders.values()) { tiLocation.locationManager.removeUpdates(locationProvider); } } } /** * Checks if the device has a valid location service present. The passive location service * is not counted. * * @return <code>true</code> if a valid location service is available on the device, * <code>false</code> if not */ @Kroll.getProperty @Kroll.method public boolean getLocationServicesEnabled() { return tiLocation.getLocationServicesEnabled(); } /** * Retrieves the last known location and returns it to the specified Javascript function * * @param callback Javascript function that will be invoked with the last known location */ @Kroll.method public void getCurrentPosition(KrollFunction callback) { if (!hasLocationPermissions()) { Log.e(TAG, "Location permissions missing"); return; } if (callback != null) { Location latestKnownLocation = tiLocation.getLastKnownLocation(); if (latestKnownLocation != null) { callback.call(this.getKrollObject(), new Object[] { buildLocationEvent(latestKnownLocation, tiLocation.locationManager.getProvider(latestKnownLocation.getProvider())) }); } else { Log.e(TAG, "Unable to get current position, location is null"); callback.call(this.getKrollObject(), new Object[] { buildLocationErrorEvent(TiLocation.ERR_POSITION_UNAVAILABLE, "location is currently unavailable.") }); } } } /** * Converts the specified address to coordinates and returns the value to the specified * Javascript function * * @param address address to be converted * @param callback Javascript function that will be invoked with the coordinates * for the specified address if available */ @Kroll.method public void forwardGeocoder(String address, KrollFunction callback) { tiLocation.forwardGeocode(address, createGeocodeResponseHandler(callback)); } /** * Converts the specified latitude and longitude to a human readable address and returns * the value to the specified Javascript function * * @param latitude latitude to be used in looking up the associated address * @param longitude longitude to be used in looking up the associated address * @param callback Javascript function that will be invoked with the address * for the specified latitude and longitude if available */ @Kroll.method public void reverseGeocoder(double latitude, double longitude, KrollFunction callback) { tiLocation.reverseGeocode(latitude, longitude, createGeocodeResponseHandler(callback)); } /** * Convenience method for creating a response handler that is used when doing a * geocode lookup. * * @param callback Javascript function that the response handler will invoke * once the geocode response is ready * @return the geocode response handler */ private GeocodeResponseHandler createGeocodeResponseHandler(final KrollFunction callback) { final GeolocationModule geolocationModule = this; return new GeocodeResponseHandler() { @Override public void handleGeocodeResponse(KrollDict geocodeResponse) { geocodeResponse.put(TiC.EVENT_PROPERTY_SOURCE, geolocationModule); callback.call(getKrollObject(), new Object[] { geocodeResponse }); } }; } /** * Called to determine if the specified location is "better" than the current location. * This is determined by comparing the new location to the current location according * to the location rules (if any are set) for the current behavior mode. If no rules * are set for the current behavior mode, the new location is always accepted. * * @param newLocation location to evaluate * @return <code>true</code> if the location has been deemed better than * the current location based on the existing rules set for the * current behavior mode, <code>false</code> if not */ private boolean shouldUseUpdate(Location newLocation) { boolean passed = false; if (getManualMode()) { if (androidModule.manualLocationRules.size() > 0) { for(LocationRuleProxy rule : androidModule.manualLocationRules) { if (rule.check(currentLocation, newLocation)) { passed = true; break; } } } else { passed = true; // no rules set, always accept } } else if (!legacyModeActive) { for(LocationRuleProxy rule : simpleLocationRules) { if (rule.check(currentLocation, newLocation)) { passed = true; break; } } // TODO remove this block when legacy mode is removed } else { // the legacy mode will fall here, don't filter the results passed = true; } return passed; } /** * Convenience method used to package a location from a location provider into a * consumable form for the Titanium developer before it is fire back to Javascript. * * @param location location that needs to be packaged into consumable form * @param locationProvider location provider that provided the location update * @return map of property names and values that contain information * pulled from the specified location */ private KrollDict buildLocationEvent(Location location, LocationProvider locationProvider) { KrollDict coordinates = new KrollDict(); coordinates.put(TiC.PROPERTY_LATITUDE, location.getLatitude()); coordinates.put(TiC.PROPERTY_LONGITUDE, location.getLongitude()); coordinates.put(TiC.PROPERTY_ALTITUDE, location.getAltitude()); coordinates.put(TiC.PROPERTY_ACCURACY, location.getAccuracy()); coordinates.put(TiC.PROPERTY_ALTITUDE_ACCURACY, null); // Not provided coordinates.put(TiC.PROPERTY_HEADING, location.getBearing()); coordinates.put(TiC.PROPERTY_SPEED, location.getSpeed()); coordinates.put(TiC.PROPERTY_TIMESTAMP, location.getTime()); KrollDict event = new KrollDict(); event.putCodeAndMessage(TiC.ERROR_CODE_NO_ERROR, null); event.put(TiC.PROPERTY_COORDS, coordinates); if (locationProvider != null) { KrollDict provider = new KrollDict(); provider.put(TiC.PROPERTY_NAME, locationProvider.getName()); provider.put(TiC.PROPERTY_ACCURACY, locationProvider.getAccuracy()); provider.put(TiC.PROPERTY_POWER, locationProvider.getPowerRequirement()); event.put(TiC.PROPERTY_PROVIDER, provider); } return event; } /** * Convenience method used to package a error into a consumable form * for the Titanium developer before it is fired back to Javascript. * * @param code Error code identifying the error * @param msg Error message describing the event * @return map of property names and values that contain information * regarding the error */ private KrollDict buildLocationErrorEvent(int code, String msg) { KrollDict d = new KrollDict(3); d.putCodeAndMessage(code, msg); return d; } @Override public String getApiName() { return "Ti.Geolocation"; } @Override public void onDestroy(Activity activity) { //clean up event listeners if (compassListenersRegistered) { tiCompass.unregisterListener(); compassListenersRegistered = false; } disableLocationProviders(); super.onDestroy(activity); } }
ashcoding/titanium_mobile
android/modules/geolocation/src/java/ti/modules/titanium/geolocation/GeolocationModule.java
Java
apache-2.0
36,967
package repomodel import ( "github.com/kopia/kopia/repo/content" "github.com/kopia/kopia/repo/manifest" ) // RepositorySession models the behavior of a single session in an repository. type RepositorySession struct { OpenRepo *OpenRepository WrittenContents ContentSet WrittenManifests ManifestSet } // WriteContent adds the provided content ID to the model. func (s *RepositorySession) WriteContent(cid content.ID) { s.WrittenContents.Add(cid) } // WriteManifest adds the provided manifest ID to the model. func (s *RepositorySession) WriteManifest(mid manifest.ID) { s.WrittenManifests.Add(mid) } // Refresh refreshes the set of committed contents and manifest from repositor. func (s *RepositorySession) Refresh() { s.OpenRepo.Refresh() } // Flush flushes the changes written in this RepositorySession and makes them available // to other RepositoryData model. func (s *RepositorySession) Flush(wc *ContentSet, wm *ManifestSet) { s.OpenRepo.mu.Lock() defer s.OpenRepo.mu.Unlock() // data flushed is visible to other sessions in the same open repository. s.OpenRepo.Contents.Add(wc.ids...) s.OpenRepo.Manifests.Add(wm.ids...) // data flushed is visible to other sessions in other open repositories. s.OpenRepo.RepoData.Contents.Add(wc.ids...) s.OpenRepo.RepoData.Manifests.Add(wm.ids...) s.WrittenContents.RemoveAll(wc.ids...) s.WrittenManifests.RemoveAll(wm.ids...) }
kopia/kopia
tests/repository_stress_test/repomodel/repository_session_model.go
GO
apache-2.0
1,400
using EPiServer.Core; namespace EPiServer.SocialAlloy.Web.Social.Models { /// <summary> /// The LikeButtonBlockViewModel class represents the model that will be used to /// provide data to the Like button block frontend view. /// </summary> public class LikeButtonBlockViewModel { /// <summary> /// Parameterless constructor /// </summary> public LikeButtonBlockViewModel() { } /// <summary> /// Gets or sets the current page link. /// </summary> public PageReference PageLink { get; set; } /// <summary> /// Gets or sets the total number of Liked ratings found for the current page. /// </summary> public long TotalCount { get; set; } /// <summary> /// Gets or sets the existing Liked rating, if any, submitted by current user for the current page. /// </summary> public int? CurrentRating { get; set; } } }
episerver/SocialAlloy
src/EPiServer.SocialAlloy.Web/Social/Models/Ratings/LikeButtonBlockViewModel.cs
C#
apache-2.0
987
package org.xmlcml.ami.visitor; import java.io.File; import java.util.List; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.xmlcml.ami.util.AMIUtil; import org.xmlcml.ami.visitable.VisitableInput; /** manages the output. * * Decides whether to create files or directories. May map the structure onto the input structure. * * @author pm286 * */ public class VisitorOutput { private static final Logger LOG = Logger.getLogger(VisitorOutput.class); private static final String DEFAULT_OUTPUT_LOCATION = "target/"; private static final String DEFAULT_BASENAME = "dummy"; private static final String DEFAULT_OUTPUT_SUFFIX = ".xml"; private String outputLocation; // private VisitableInput visitableInput; private List<VisitableInput> visitableInputList; private String extension; private boolean isDirectory; private File outputDirectory; /** reads outputLocation and ducktypes the type (File, Directory, etc.). * * @param outputLocation */ public VisitorOutput(String outputLocation) { setDefaults(); this.outputLocation = outputLocation; generateOutputDirectoryName(); } /** this creates a default outputLocation * */ public VisitorOutput() { setDefaults(); } private void setDefaults() { outputLocation = DEFAULT_OUTPUT_LOCATION; extension = DEFAULT_OUTPUT_SUFFIX; outputDirectory = new File(DEFAULT_OUTPUT_LOCATION); } /** not yet used * * @param visitableInput */ public void setVisitableInputList(List<VisitableInput> visitableInputList) { this.visitableInputList = visitableInputList; } private void generateOutputDirectoryName() { if (outputLocation.startsWith(AMIUtil.HTTP)) { throw new RuntimeException("Cannot output to URL: "+outputLocation); } if (outputLocation.startsWith(AMIUtil.DOI)) { throw new RuntimeException("Cannot output to DOI: "+outputLocation); } if (outputLocation == null) { LOG.info("No explicit output location"); } else { outputLocation = FilenameUtils.normalize(new File(outputLocation).getAbsolutePath()); extension = FilenameUtils.getExtension(outputLocation); isDirectory = AMIUtil.endsWithSeparator(outputLocation) || extension == null || extension.equals(""); outputDirectory = new File(outputLocation); } } protected String getOutputLocation() { return outputLocation; } protected String getExtension() { return extension; } protected boolean isDirectory() { return isDirectory; } public File getOutputDirectoryFile() { if (outputDirectory != null) { LOG.trace("outputDirectory: "+outputDirectory); if (outputDirectory.exists() && !outputDirectory.isDirectory()) { LOG.info("existing file is not a directory: "+outputDirectory); } else { ifNotEndsWithSlashUseParentAsOutputDirectory(); outputDirectory.mkdirs(); String baseName = (visitableInputList == null || visitableInputList.size() == 0) ? DEFAULT_BASENAME : visitableInputList.get(0).getBaseName(); LOG.trace("basename "+baseName); outputDirectory = new File(outputDirectory, baseName+"."+extension); } } else { throw new RuntimeException("Null output directory"); } return outputDirectory; } private void ifNotEndsWithSlashUseParentAsOutputDirectory() { if (!outputDirectory.toString().endsWith("/")) { File parent = outputDirectory.getParentFile(); outputDirectory = (parent == null) ? outputDirectory : parent; } } public void setExtension(String extension) { this.extension = extension; } }
tarrow/ami
src/main/java/org/xmlcml/ami/visitor/VisitorOutput.java
Java
apache-2.0
3,654
/* Copyright 2006 Jerry Huxtable Copyright 2009 Martin Davis Copyright 2012 Antoine Gourlay 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.jproj; import java.text.DecimalFormat; /** * Stores a the coordinates for a position * defined relative to some {@link CoordinateReferenceSystem}. * The coordinate is defined via X, Y, and optional Z ordinates. * Provides utility methods for comparing the ordinates of two positions and * for creating positions from Strings/storing positions as strings. * <p> * The primary use of this class is to represent coordinate * values which are to be transformed * by a {@link CoordinateTransform}. */ public class ProjCoordinate { private static final String DECIMAL_FORMAT_PATTERN = "0.0###############"; // a DecimalFormat is not ThreadSafe, hence the ThreadLocal variable. private static final ThreadLocal<DecimalFormat> DECIMAL_FORMAT = new ThreadLocal<DecimalFormat>() { @Override protected DecimalFormat initialValue() { return new DecimalFormat(DECIMAL_FORMAT_PATTERN); } }; /** * The X ordinate for this point. * <p> * Note: This member variable * can be accessed directly. In the future this direct access should * be replaced with getter and setter methods. This will require * refactoring of the Proj4J code base. */ public double x; /** * The Y ordinate for this point. * <p> * Note: This member variable * can be accessed directly. In the future this direct access should * be replaced with getter and setter methods. This will require * refactoring of the Proj4J code base. */ public double y; /** * The Z ordinate for this point. * If this variable has the value <tt>Double.NaN</tt> * then this coordinate does not have a Z value. * <p> * Note: This member variable * can be accessed directly. In the future this direct access should * be replaced with getter and setter methods. This will require * refactoring of the Proj4J code base. */ public double z; /** * Creates a ProjCoordinate with default ordinate values. * */ public ProjCoordinate() { this(0.0, 0.0); } /** * Creates a ProjCoordinate with values copied from the given coordinate object. * @param pt a ProjCoordinate to copy */ public ProjCoordinate(ProjCoordinate pt) { this(pt.x, pt.y, pt.z); } /** * Creates a ProjCoordinate using the provided double parameters. * The first double parameter is the x ordinate (or easting), * the second double parameter is the y ordinate (or northing), * and the third double parameter is the z ordinate (elevation or height). * * Valid values should be passed for all three (3) double parameters. If * you want to create a horizontal-only point without a valid Z value, use * the constructor defined in this class that only accepts two (2) double * parameters. * * @param argX * @param argY * @param argZ * @see #ProjCoordinate(double argX, double argY) */ public ProjCoordinate(double argX, double argY, double argZ) { this.x = argX; this.y = argY; this.z = argZ; } /** * Creates a ProjCoordinate using the provided double parameters. * The first double parameter is the x ordinate (or easting), * the second double parameter is the y ordinate (or northing). * This constructor is used to create a "2D" point, so the Z ordinate * is automatically set to Double.NaN. * @param argX * @param argY */ public ProjCoordinate(double argX, double argY) { this.x = argX; this.y = argY; this.z = Double.NaN; } /** * Create a ProjCoordinate by parsing a String in the same format as returned * by the toString method defined by this class. * * @param argToParse the string to parse */ public ProjCoordinate(String argToParse) { // Make sure the String starts with "ProjCoordinate: ". if (!argToParse.startsWith("ProjCoordinate: ")) { throw new IllegalArgumentException("The input string was not in the proper format."); } // 15 characters should cut out "ProjCoordinate: ". String chomped = argToParse.substring(16); // Get rid of the starting and ending square brackets. String withoutFrontBracket = chomped.substring(1); // Calc the position of the last bracket. int length = withoutFrontBracket.length(); int positionOfCharBeforeLast = length - 2; String withoutBackBracket = withoutFrontBracket.substring(0, positionOfCharBeforeLast); // We should be left with just the ordinate values as strings, // separated by spaces. Split them into an array of Strings. String[] parts = withoutBackBracket.split(" "); // Get number of elements in Array. There should be two (2) elements // or three (3) elements. // If we don't have an array with two (2) or three (3) elements, // then we need to throw an exception. if (parts.length != 2 && parts.length != 3) { throw new IllegalArgumentException("The input string was not in the proper format."); } // Convert strings to doubles. this.x = "NaN".equals(parts[0]) ? Double.NaN : Double.parseDouble(parts[0]); this.y = "NaN".equals(parts[1]) ? Double.NaN : Double.parseDouble(parts[1]); // You might not always have a Z ordinate. If you do, set it. if (parts.length == 3) { this.z = "NaN".equals(parts[2]) ? Double.NaN : Double.parseDouble(parts[2]); } else { this.z = Double.NaN; } } /** * Sets the value of this coordinate to * be equal to the given coordinate's ordinates. * * @param p the coordinate to copy */ public void setValue(ProjCoordinate p) { this.x = p.x; this.y = p.y; this.z = p.z; } /** * Returns a boolean indicating if the X ordinate value of the * ProjCoordinate provided as an ordinate is equal to the X ordinate * value of this ProjCoordinate. Because we are working with floating * point numbers the ordinates are considered equal if the difference * between them is less than the specified tolerance. * @param argToCompare * @param argTolerance * @return */ public boolean areXOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) { // Subtract the x ordinate values and then see if the difference // between them is less than the specified tolerance. If the difference // is less, return true. return argToCompare.x - this.x <= argTolerance; } /** * Returns a boolean indicating if the Y ordinate value of the * ProjCoordinate provided as an ordinate is equal to the Y ordinate * value of this ProjCoordinate. Because we are working with floating * point numbers the ordinates are considered equal if the difference * between them is less than the specified tolerance. * @param argToCompare * @param argTolerance * @return */ public boolean areYOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) { // Subtract the y ordinate values and then see if the difference // between them is less than the specified tolerance. If the difference // is less, return true. return argToCompare.y - this.y <= argTolerance; } /** * Returns a boolean indicating if the Z ordinate value of the * ProjCoordinate provided as an ordinate is equal to the Z ordinate * value of this ProjCoordinate. Because we are working with floating * point numbers the ordinates are considered equal if the difference * between them is less than the specified tolerance. * * If both Z ordinate values are Double.NaN this method will return * true. If one Z ordinate value is a valid double value and one is * Double.Nan, this method will return false. * @param argToCompare * @param argTolerance * @return */ public boolean areZOrdinatesEqual(ProjCoordinate argToCompare, double argTolerance) { // We have to handle Double.NaN values here, because not every // ProjCoordinate will have a valid Z Value. if (Double.isNaN(z)) { return Double.isNaN(argToCompare.z); // if true, both the z ordinate values are Double.Nan. // else, We've got one z ordinate with a valid value and one with // a Double.NaN value. } // We have a valid z ordinate value in this ProjCoordinate object. else { if (Double.isNaN(argToCompare.z)) { // We've got one z ordinate with a valid value and one with // a Double.NaN value. Return false. return false; } // If we get to this point in the method execution, we have to // z ordinates with valid values, and we need to do a regular // comparison. This is done in the remainder of the method. } // Subtract the z ordinate values and then see if the difference // between them is less than the specified tolerance. If the difference // is less, return true. return argToCompare.z - this.z <= argTolerance; } /** * Returns a string representing the ProjPoint in the format: * <tt>ProjCoordinate[X Y Z]</tt>. * <p> * Example: * <pre> * ProjCoordinate[6241.11 5218.25 12.3] * </pre> */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("ProjCoordinate["); if (Double.isNaN(x)) { builder.append("NaN"); } else { builder.append(x); } builder.append(" "); if (Double.isNaN(x)) { builder.append("NaN"); } else { builder.append(y); } builder.append(" "); if (Double.isNaN(x)) { builder.append("NaN"); } else { builder.append(z); } builder.append("]"); return builder.toString(); } /** * Returns a string representing the ProjPoint in the format: * <tt>[X Y]</tt> * or <tt>[X, Y, Z]</tt>. * Z is not displayed if it is NaN. * <p> * Example: * <pre> * [6241.11, 5218.25, 12.3] * </pre> * @return */ public String toShortString() { StringBuilder builder = new StringBuilder(); builder.append("["); if (Double.isNaN(x)) { builder.append("NaN"); } else { builder.append(DECIMAL_FORMAT.get().format(x)); } builder.append(", "); if (Double.isNaN(y)) { builder.append("NaN"); } else { builder.append(DECIMAL_FORMAT.get().format(y)); } if (!Double.isNaN(z)) { builder.append(", "); builder.append(this.z); } builder.append("]"); return builder.toString(); } public boolean hasValidZOrdinate() { return !Double.isNaN(z); } /** * Indicates if this ProjCoordinate has valid X ordinate and Y ordinate * values. Values are considered invalid if they are Double.NaN or * positive/negative infinity. * @return */ public boolean hasValidXandYOrdinates() { return !Double.isNaN(x) && !Double.isInfinite(x) && !Double.isNaN(y) && !Double.isInfinite(y); } }
ebocher/jproj
src/main/java/org/jproj/ProjCoordinate.java
Java
apache-2.0
14,438
package interviews; public class Yahoo { } Run Length Encoding for byte array Input byte array [10, 10, 10, 255, 255, 0, 10] ==> output byte array [3, 10, 2, 255, 1, 0, 1, 10] Class ByteArrayEncodeDecode { public byte[] encodeByteArray(byte[] input) { int n = input.length; if (n == 0) return new byte[]; Arraylist<Byte> out = Arraylist<Byte>(); byte prevByte = input[0]; byte prevCount = 1; for (int i = 1; i < n; i++) { if(prevByte == input[i] && prevCount != 255){ // prevCount++; } else { out.add(prevCount); out.add(prevByte); prevByte = input[i]; prevCount = 1; } } out.add(prevCount); out.add(prevByte); return out.toArray(); } public static void main() { } } // [] ==> [] // [1] ==> [1, 1] // [1, 1, 1, 2, 2, 3] ==> [3, 1, 2, 2, 1, 3] // [1 ... 300.....1] ==> [255, 1, 45, 1]
rezaur86/Coding-competitions
Java/interviews/Yahoo.java
Java
apache-2.0
1,011
/*******************************************************************\ Module: Type Naming for C Author: Daniel Kroening, kroening@cs.cmu.edu \*******************************************************************/ #include <ctype.h> #include <i2string.h> #include <std_types.h> #include "type2name.h" /*******************************************************************\ Function: type2name Inputs: Outputs: Purpose: \*******************************************************************/ std::string type2name(const typet &type) { std::string result; if(type.id()=="") throw "Empty type encountered."; else if(type.id()=="empty") result+="V"; else if(type.id()=="signedbv") result+="S" + type.width().as_string(); else if(type.id()=="unsignedbv") result+="U" + type.width().as_string(); else if(type.is_bool()) result+="B"; else if(type.id()=="integer") result+="I"; else if(type.id()=="real") result+="R"; else if(type.id()=="complex") result+="C"; else if(type.id()=="float") result+="F"; else if(type.id()=="floatbv") result+="F" + type.width().as_string(); else if(type.id()=="fixed") result+="X"; else if(type.id()=="fixedbv") result+="X" + type.width().as_string(); else if(type.id()=="natural") result+="N"; else if(type.id()=="pointer") result+="*"; else if(type.id()=="reference") result+="&"; else if(type.is_code()) { const code_typet &t = to_code_type(type); const code_typet::argumentst arguments = t.arguments(); result+="P("; for (code_typet::argumentst::const_iterator it = arguments.begin(); it!=arguments.end(); it++) { result+=type2name(it->type()); result+="'" + it->get_identifier().as_string() + "'|"; } result.resize(result.size()-1); result+=")"; } else if(type.is_array()) { const array_typet &t = to_array_type(type); result+="ARR" + t.size().value().as_string(); } else if(type.id()=="incomplete_array") { result+="ARR?"; } else if(type.id()=="symbol") { result+="SYM#" + type.identifier().as_string() + "#"; } else if(type.id()=="struct" || type.id()=="union") { if(type.id()=="struct") result +="ST"; if(type.id()=="union") result +="UN"; const struct_typet &t = to_struct_type(type); const struct_typet::componentst &components = t.components(); result+="["; for(struct_typet::componentst::const_iterator it = components.begin(); it!=components.end(); it++) { result+=type2name(it->type()); result+="'" + it->name().as_string() + "'|"; } result.resize(result.size()-1); result+="]"; } else if(type.id()=="incomplete_struct") result +="ST?"; else if(type.id()=="incomplete_union") result +="UN?"; else if(type.id()=="c_enum") result +="EN" + type.width().as_string(); else if(type.id()=="incomplete_c_enum") result +="EN?"; else if(type.id()=="c_bitfield") { result+="BF" + type.size().as_string(); } else { throw (std::string("Unknown type '") + type.id().as_string() + "' encountered."); } if(type.has_subtype()) { result+="{"; result+=type2name(type.subtype()); result+="}"; } if(type.has_subtypes()) { result+="$"; forall_subtypes(it, type) { result+=type2name(*it); result+="|"; } result.resize(result.size()-1); result+="$"; } return result; }
ssvlab/esbmc-gpu
ansi-c/type2name.cpp
C++
apache-2.0
3,566
using System; namespace ProSecuritiesTrading.MOEX.FIX.Base.Field { public class PartyID { public const int Tag = 448; public static readonly byte[] TagBytes; static PartyID() { TagBytes = new byte[3]; TagBytes[0] = 52; TagBytes[1] = 52; TagBytes[2] = 56; } } }
AlexeyLA0509/PSTTrader
src/ProSecuritiesTrading.MOEX.FIX/Base/Field/PartyID.cs
C#
apache-2.0
366
/* * Copyright 2013-2017 Grzegorz Ligas <ligasgr@gmail.com> and other contributors * (see the CONTRIBUTORS 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. */ // This is a generated file. Not intended for manual editing. package org.intellij.xquery.psi; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.psi.PsiElement; public interface XQueryContextItemDecl extends XQueryPsiElement { @Nullable XQueryItemType getItemType(); @Nullable XQuerySeparator getSeparator(); @Nullable XQueryVarDefaultValue getVarDefaultValue(); @Nullable XQueryVarValue getVarValue(); }
ligasgr/intellij-xquery
gen/org/intellij/xquery/psi/XQueryContextItemDecl.java
Java
apache-2.0
1,132
/* * Copyright (c) 2008-2016 Computer Network Information Center (CNIC), Chinese Academy of Sciences. * * This file is part of Duckling project. * * 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 net.duckling.vmt.domain; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import org.apache.log4j.Logger; public class HttpGet { private static final Logger LOG=Logger.getLogger(HttpGet.class); private String path; private String encode="UTF-8"; public HttpGet(String url,String encode){ this.path=url; this.encode=encode; } public HttpGet(String url){ this.path=url; } public String connect(){ URL url = null; try { url = new URL(path); } catch (MalformedURLException e) { LOG.error(e.getMessage()+",can't touch this url="+path, e); return null; } try (InputStream ins = url.openConnection().getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(ins, encode));) { String line; StringBuffer sb = new StringBuffer(); while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } catch (IOException e) { LOG.error(e.getMessage(), e); return null; } } }
duckling-falcon/vmt
src/main/java/net/duckling/vmt/domain/HttpGet.java
Java
apache-2.0
1,845
/* * Copyright 2011 Jon S Akhtar (Sylvanaar) * * 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.sylvanaar.idea.Lua.lang.psi.impl.symbols; import com.intellij.lang.ASTNode; import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaParameter; import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaSymbol; import com.sylvanaar.idea.Lua.lang.psi.symbols.LuaUpvalueIdentifier; /** * Created by IntelliJ IDEA. * User: Jon S Akhtar * Date: 1/26/11 * Time: 9:23 PM */ public class LuaUpvalueIdentifierImpl extends LuaLocalIdentifierImpl implements LuaUpvalueIdentifier { public LuaUpvalueIdentifierImpl(ASTNode node) { super(node); } @Override public boolean isSameKind(LuaSymbol symbol) { return symbol instanceof LuaLocalDeclarationImpl || symbol instanceof LuaParameter; } @Override public String toString() { return "Upvalue: " + getText(); } }
consulo/consulo-lua
src/main/java/com/sylvanaar/idea/Lua/lang/psi/impl/symbols/LuaUpvalueIdentifierImpl.java
Java
apache-2.0
1,415
<?php namespace ContainerFelbUiK; use Symfony\Component\DependencyInjection\Argument\RewindableGenerator; use Symfony\Component\DependencyInjection\Exception\RuntimeException; /** * @internal This class has been auto-generated by the Symfony Dependency Injection Component. */ class getForm_TypeExtension_Form_ValidatorService extends App_KernelDevDebugContainer { /** * Gets the private 'form.type_extension.form.validator' shared service. * * @return \Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension */ public static function do($container, $lazyLoad = true) { include_once \dirname(__DIR__, 4).'/vendor/symfony/form/FormTypeExtensionInterface.php'; include_once \dirname(__DIR__, 4).'/vendor/symfony/form/AbstractTypeExtension.php'; include_once \dirname(__DIR__, 4).'/vendor/symfony/form/Extension/Validator/Type/BaseValidatorExtension.php'; include_once \dirname(__DIR__, 4).'/vendor/symfony/form/Extension/Validator/Type/FormTypeValidatorExtension.php'; return $container->privates['form.type_extension.form.validator'] = new \Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension(($container->services['validator'] ?? $container->getValidatorService())); } }
cloudfoundry/php-buildpack
fixtures/symfony_5_local_deps/var/cache/dev/ContainerFelbUiK/getForm_TypeExtension_Form_ValidatorService.php
PHP
apache-2.0
1,296
package com.tle.configmanager; import com.dytech.gui.ComponentHelper; import com.thoughtworks.xstream.XStream; import com.tle.common.Check; import java.awt.Container; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JSeparator; import net.miginfocom.swing.MigLayout; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.io.FileUtils; // Author: Andrew Gibb @SuppressWarnings({"serial", "nls"}) public class ConfigLauncherGUI extends JFrame implements ActionListener { public static final String MANDATORY_CONFIG = "mandatory-config.properties"; public static final String OPTIONAL_CONFIG = "optional-config.properties"; public static final String HIBERNATE_CONFIG = "hibernate.properties"; public static final String LOGGING_CONFIG = "learningedge-log4j.properties"; public static final String IMAGEMAGICK_CONFIG = "plugins/com.tle.core.imagemagick/config.properties.unresolved"; public static final String HIKARI_CONFIG = "hikari.properties"; private final String TITLE = "TLE Configuration Manager"; private final String PATH = "./configs/"; private final String ORACLE = "oracle"; private final String POSTGRESQL = "postgresql"; private final String MSSQL = "ms sql"; private final String source; private final String destination; private JLabel lblConfig; private JComboBox<ConfigProfile> cmbConfigs; private JButton btnNew, btnEdit, btnApply, btnDelete; private JSeparator sep; private List<ConfigProfile> configs; public ConfigLauncherGUI(String source, String destination) { setTitle(TITLE); setupGUI(); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); this.source = source; this.destination = destination; // Set a minimum width...leave the height to the pack... setMinimumSize(new Dimension(300, 0)); pack(); ComponentHelper.centreOnScreen(this); // Updated combo box containing profiles updateConfigs(); } // Sets up the GUI for managing/loading the configuration profiles private void setupGUI() { Container contents = getContentPane(); contents.setLayout(new MigLayout("wrap 3", "[grow][grow][grow]")); configs = new ArrayList<ConfigProfile>(); lblConfig = new JLabel("Configurations: "); cmbConfigs = new JComboBox<ConfigProfile>(); btnNew = new JButton("New"); btnNew.addActionListener(this); btnApply = new JButton("Apply Configuration"); btnApply.addActionListener(this); btnEdit = new JButton("Edit"); btnEdit.addActionListener(this); sep = new JSeparator(); btnDelete = new JButton("Delete"); btnDelete.addActionListener(this); contents.add(lblConfig, "growx, spanx 3"); contents.add(cmbConfigs, "growx, spanx 3"); contents.add(btnNew, "growx, center"); contents.add(btnEdit, "growx, center"); contents.add(btnDelete, "growx, center"); contents.add(sep, "growx, spanx 3"); contents.add(btnApply, "center, growx, spanx 3"); } // Updates the available configuration profiles public void updateConfigs() { File srcDir = new File(PATH); File[] configFiles = srcDir.listFiles(); Reader rdr; cmbConfigs.removeAllItems(); configs.clear(); if (configFiles != null) { for (File f : configFiles) { if (f.isFile()) { XStream xstream = new XStream(); try { rdr = new BufferedReader(new FileReader(f)); ConfigProfile prof = (ConfigProfile) xstream.fromXML(rdr); configs.add(prof); rdr.close(); } catch (IOException e) { throw new RuntimeException(e); } } } Collections.sort( configs, new Comparator<ConfigProfile>() { @Override public int compare(ConfigProfile o1, ConfigProfile o2) { return o1.getProfName().compareToIgnoreCase(o2.getProfName()); } }); for (ConfigProfile prof : configs) { cmbConfigs.addItem(prof); } } if (configs.isEmpty()) { btnEdit.setEnabled(false); btnApply.setEnabled(false); btnDelete.setEnabled(false); } else { btnEdit.setEnabled(true); btnApply.setEnabled(true); btnDelete.setEnabled(true); } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnNew) { addProfile(); } else if (e.getSource() == btnEdit) { editProfile(); } else if (e.getSource() == btnDelete) { deleteProfile(); } else if (e.getSource() == btnApply) { try { loadProfile(); } catch (Exception ex) { JOptionPane.showMessageDialog( null, "Error loading configuration: \n" + ex.getMessage(), "Load Failed", JOptionPane.ERROR_MESSAGE); } } } // Adds a new profile which is either a clone of an existing profile or is // blank private void addProfile() { ConfigEditorGUI confEd = null; if (configs != null && cmbConfigs.getSelectedItem() != null) { ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem(); int result = JOptionPane.showConfirmDialog( null, "Do you want to clone the currently selected configuration?: " + selectedProf.getProfName(), "Clone Confirmation", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { confEd = new ConfigEditorGUI(selectedProf, "copy"); } else { confEd = new ConfigEditorGUI(); } } else { confEd = new ConfigEditorGUI(); } confEd.setModal(true); confEd.setVisible(true); if (confEd.getResult() == ConfigEditorGUI.RESULT_SAVE) { updateConfigs(); } } // Edits and existing profile private void editProfile() { int index = cmbConfigs.getSelectedIndex(); ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem(); ConfigEditorGUI confEd = new ConfigEditorGUI(selectedProf); confEd.setModal(true); confEd.setVisible(true); if (confEd.getResult() == ConfigEditorGUI.RESULT_SAVE) { updateConfigs(); cmbConfigs.setSelectedIndex(index); } } // Deletes a configuration profile private void deleteProfile() { ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem(); File toDel = new File(PATH + selectedProf.getProfName() + ".xml"); int result = JOptionPane.showConfirmDialog( null, "Are you sure you want to delete this configuration?: " + selectedProf.getProfName(), "Delete Confirmation", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { boolean success = toDel.delete(); if (!success) { JOptionPane.showMessageDialog( null, "Unable to delete configuration: " + selectedProf.getProfName(), "Delete Failed", JOptionPane.ERROR_MESSAGE); } } updateConfigs(); } // Loads a profile (SUPER HACKISH) private void loadProfile() throws FileNotFoundException, IOException, ConfigurationException { ConfigProfile selectedProf = (ConfigProfile) cmbConfigs.getSelectedItem(); File srcDir = new File(source); // Remove Current Configuration Files File destDir = new File(destination); FileUtils.deleteDirectory(destDir); // Create Destination destDir.mkdir(); // Copy Required Files (Database Specific) boolean oracleSelected = selectedProf.getDbtype().equalsIgnoreCase(ORACLE); if (oracleSelected) { org.apache.commons.io.FileUtils.copyFile( new File(srcDir + "/hibernate.properties.oracle"), new File(destDir + "/hibernate.properties")); } else if (selectedProf.getDbtype().equalsIgnoreCase(POSTGRESQL)) { FileUtils.copyFile( new File(srcDir + "/hibernate.properties.postgresql"), new File(destDir + "/hibernate.properties")); } else if (selectedProf.getDbtype().equalsIgnoreCase(MSSQL)) { FileUtils.copyFile( new File(srcDir + "/hibernate.properties.sqlserver"), new File(destDir + "/hibernate.properties")); } // Mandatory / Optional / Logging FileUtils.copyFile( new File(srcDir + "/mandatory-config.properties"), new File(destDir + "/mandatory-config.properties")); FileUtils.copyFile( new File(srcDir + "/optional-config.properties"), new File(destDir + "/optional-config.properties")); // Copy custom development logging file FileUtils.copyFile( new File("./learningedge-log4j.properties"), new File(destDir + "/learningedge-log4j.properties")); // Other Miscellaneous Files FileUtils.copyFile( new File(srcDir + "/en-stopWords.txt"), new File(destDir + "/en-stopWords.txt")); FileUtils.copyFile( new File(srcDir + "/" + HIKARI_CONFIG), new File(destDir + "/" + HIKARI_CONFIG)); // Plugins Folder FileUtils.copyDirectoryToDirectory(new File(srcDir + "/plugins"), destDir); // Edit Hibernate Properties String hibProp = readFile(destination + "/" + HIBERNATE_CONFIG); hibProp = hibProp.replace("${datasource/host}", selectedProf.getHost()); hibProp = hibProp.replace("${datasource/port}", selectedProf.getPort()); hibProp = hibProp.replace("${datasource/database}", selectedProf.getDatabase()); hibProp = hibProp.replace("${datasource/username}", selectedProf.getUsername()); hibProp = hibProp.replace("${datasource/password}", selectedProf.getPassword()); hibProp = hibProp.replace( "${datasource/schema}", oracleSelected ? "hibernate.default_schema = " + selectedProf.getUsername() : ""); writeFile(destination + "/hibernate.properties", hibProp); // Edit Mandatory Properties PropertyEditor mandProps = new PropertyEditor(); mandProps.load(new File(destination + "/" + MANDATORY_CONFIG)); String http = selectedProf.getHttp(); String portFromUrl = selectedProf.getAdminurl().split(":")[1]; mandProps.setProperty( "http.port", !Check.isEmpty(http) ? http : !Check.isEmpty(portFromUrl) ? portFromUrl : "80"); String https = selectedProf.getHttps(); if (!Check.isEmpty(https)) { mandProps.setProperty("https.port", https); } String ajp = selectedProf.getAjp(); if (!Check.isEmpty(https)) { mandProps.setProperty("ajp.port", ajp); } mandProps.setProperty("filestore.root", selectedProf.getFilestore()); mandProps.setProperty("java.home", selectedProf.getJavahome()); mandProps.setProperty("admin.url", selectedProf.getAdminurl()); mandProps.setProperty("freetext.index.location", selectedProf.getFreetext()); mandProps.setProperty("freetext.stopwords.file", selectedProf.getStopwords()); String reporting = selectedProf.getReporting(); if (!Check.isEmpty(reporting)) { mandProps.setProperty("reporting.workspace.location", reporting); } mandProps.setProperty("plugins.location", selectedProf.getPlugins()); mandProps.save(new File(destination + "/" + MANDATORY_CONFIG)); // Edit Optional Properties String optProp = readFile(destination + "/" + OPTIONAL_CONFIG); if (selectedProf.isDevinst()) { optProp = optProp.replace( "#conversionService.disableConversion = false", "conversionService.disableConversion = true"); optProp = optProp.replace( "conversionService.conversionServicePath = ${install.path#t\\/}/conversion/conversion-service.jar", "#conversionService.conversionServicePath ="); optProp = optProp.replace("#pluginPathResolver.wrappedClass", "pluginPathResolver.wrappedClass"); } else { optProp = optProp.replace( "${install.path#t\\/}/conversion/conversion-service.jar", selectedProf.getConversion()); } writeFile(destination + "/optional-config.properties", optProp); // Edit ImageMagik Properties (MORE HAX...) File imgmgk = new File(destination + "/" + IMAGEMAGICK_CONFIG); PropertyEditor magickProps = new PropertyEditor(); magickProps.load(imgmgk); magickProps.setProperty("imageMagick.path", selectedProf.getImagemagick()); magickProps.save(new File((destination + "/" + IMAGEMAGICK_CONFIG).replace(".unresolved", ""))); imgmgk.delete(); JOptionPane.showMessageDialog( null, "The configuration: " + selectedProf.getProfName() + " has been successfully loaded.", "Load Success", JOptionPane.INFORMATION_MESSAGE); } // Reads a file into a string private String readFile(String path) throws IOException { StringBuilder contents = new StringBuilder(); BufferedReader br = new BufferedReader(new FileReader(path)); String line = null; while ((line = br.readLine()) != null) { contents.append(line); contents.append(System.getProperty("line.separator")); } br.close(); return contents.toString(); } // Writes a file from String private void writeFile(String path, String contents) throws IOException { BufferedWriter output = null; output = new BufferedWriter(new FileWriter(new File(path))); output.write(contents); output.close(); } }
equella/Equella
Source/Tools/ConfigManager/src/com/tle/configmanager/ConfigLauncherGUI.java
Java
apache-2.0
13,989
<?php final class DrydockLeaseViewController extends DrydockLeaseController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $lease = id(new DrydockLeaseQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->needUnconsumedCommands(true) ->executeOne(); if (!$lease) { return new Aphront404Response(); } $lease_uri = $this->getApplicationURI('lease/'.$lease->getID().'/'); $title = pht('Lease %d', $lease->getID()); $header = id(new PHUIHeaderView()) ->setHeader($title); if ($lease->isReleasing()) { $header->setStatus('fa-exclamation-triangle', 'red', pht('Releasing')); } $actions = $this->buildActionListView($lease); $properties = $this->buildPropertyListView($lease, $actions); $pager = new PHUIPagerView(); $pager->setURI(new PhutilURI($lease_uri), 'offset'); $pager->setOffset($request->getInt('offset')); $logs = id(new DrydockLogQuery()) ->setViewer($viewer) ->withLeaseIDs(array($lease->getID())) ->executeWithOffsetPager($pager); $log_table = id(new DrydockLogListView()) ->setUser($viewer) ->setLogs($logs) ->render(); $log_table->appendChild($pager); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb($title, $lease_uri); $locks = $this->buildLocksTab($lease->getPHID()); $commands = $this->buildCommandsTab($lease->getPHID()); $object_box = id(new PHUIObjectBoxView()) ->setHeader($header) ->addPropertyList($properties, pht('Properties')) ->addPropertyList($locks, pht('Slot Locks')) ->addPropertyList($commands, pht('Commands')); $log_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Lease Logs')) ->setTable($log_table); return $this->buildApplicationPage( array( $crumbs, $object_box, $log_box, ), array( 'title' => $title, )); } private function buildActionListView(DrydockLease $lease) { $viewer = $this->getViewer(); $view = id(new PhabricatorActionListView()) ->setUser($viewer) ->setObjectURI($this->getRequest()->getRequestURI()) ->setObject($lease); $id = $lease->getID(); $can_release = $lease->canRelease(); if ($lease->isReleasing()) { $can_release = false; } $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $lease, PhabricatorPolicyCapability::CAN_EDIT); $view->addAction( id(new PhabricatorActionView()) ->setName(pht('Release Lease')) ->setIcon('fa-times') ->setHref($this->getApplicationURI("/lease/{$id}/release/")) ->setWorkflow(true) ->setDisabled(!$can_release || !$can_edit)); return $view; } private function buildPropertyListView( DrydockLease $lease, PhabricatorActionListView $actions) { $viewer = $this->getViewer(); $view = new PHUIPropertyListView(); $view->setActionList($actions); $view->addProperty( pht('Status'), DrydockLeaseStatus::getNameForStatus($lease->getStatus())); $view->addProperty( pht('Resource Type'), $lease->getResourceType()); $owner_phid = $lease->getOwnerPHID(); if ($owner_phid) { $owner_display = $viewer->renderHandle($owner_phid); } else { $owner_display = phutil_tag('em', array(), pht('No Owner')); } $view->addProperty(pht('Owner'), $owner_display); $resource_phid = $lease->getResourcePHID(); if ($resource_phid) { $resource_display = $viewer->renderHandle($resource_phid); } else { $resource_display = phutil_tag('em', array(), pht('No Resource')); } $view->addProperty(pht('Resource'), $resource_display); $until = $lease->getUntil(); if ($until) { $until_display = phabricator_datetime($until, $viewer); } else { $until_display = phutil_tag('em', array(), pht('Never')); } $view->addProperty(pht('Expires'), $until_display); $attributes = $lease->getAttributes(); if ($attributes) { $view->addSectionHeader( pht('Attributes'), 'fa-list-ul'); foreach ($attributes as $key => $value) { $view->addProperty($key, $value); } } return $view; } }
librewiki/phabricator
src/applications/drydock/controller/DrydockLeaseViewController.php
PHP
apache-2.0
4,366
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Text; namespace Microsoft.Web.Utility.PInvoke.Fusion { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")] internal interface IAssemblyName { [PreserveSig()] int SetProperty( int PropertyId, IntPtr pvProperty, int cbProperty); [PreserveSig()] int GetProperty( int PropertyId, IntPtr pvProperty, ref int pcbProperty); [PreserveSig()] int Finalize(); [PreserveSig()] int GetDisplayName( StringBuilder pDisplayName, ref int pccDisplayName, int displayFlags); [PreserveSig()] int Reserved(ref Guid guid, Object obj1, Object obj2, String string1, Int64 llFlags, IntPtr pvReserved, int cbReserved, out IntPtr ppv); [PreserveSig()] int GetName( ref int pccBuffer, StringBuilder pwzName); [PreserveSig()] int GetVersion( out int versionHi, out int versionLow); [PreserveSig()] int IsEqual( IAssemblyName pAsmName, int cmpFlags); [PreserveSig()] int Clone(out IAssemblyName pAsmName); }// IAssemblyName [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae")] internal interface IAssemblyCache { [PreserveSig()] int UninstallAssembly( int flags, [MarshalAs(UnmanagedType.LPWStr)] string assemblyName, IntPtr refData, out int disposition); [PreserveSig()] int QueryAssemblyInfo( int flags, [MarshalAs(UnmanagedType.LPWStr)] string assemblyName, ref AssemblyInfo assemblyInfo); [PreserveSig()] int Reserved( int flags, IntPtr pvReserved, out object ppAsmItem, [MarshalAs(UnmanagedType.LPWStr)] string assemblyName); [PreserveSig()] int Reserved(out object ppAsmScavenger); [PreserveSig()] int InstallAssembly( int flags, [MarshalAs(UnmanagedType.LPWStr)] string assemblyFilePath, IntPtr refData); }// IAssemblyCache [StructLayout(LayoutKind.Sequential)] internal struct AssemblyInfo { public int cbAssemblyInfo; // size of this structure for future expansion public int assemblyFlags; public long assemblySizeInKB; [MarshalAs(UnmanagedType.LPWStr)] public string currentAssemblyPath; public int cchBuf; // size of path buf. } [Flags] internal enum AssemblyCacheFlags { GAC = 2, } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")] internal interface IAssemblyEnum { [PreserveSig()] int GetNextAssembly( IntPtr pvReserved, out IAssemblyName ppName, int flags); [PreserveSig()] int Reset(); [PreserveSig()] int Clone(out IAssemblyEnum ppEnum); } [Flags] internal enum AssemblyNameDisplayFlags { VERSION = 0x01, CULTURE = 0x02, PUBLIC_KEY_TOKEN = 0x04, PROCESSORARCHITECTURE = 0x20, RETARGETABLE = 0x80, // This enum might change in the future to include // more attributes. ALL = VERSION | CULTURE | PUBLIC_KEY_TOKEN | PROCESSORARCHITECTURE | RETARGETABLE } internal enum CreateAssemblyNameObjectFlags { CANOF_DEFAULT = 0, CANOF_PARSE_DISPLAY_NAME = 1, } internal static class NativeMethods { [DllImport("fusion.dll")] public static extern int CreateAssemblyCache( out IAssemblyCache ppAsmCache, int reserved); [DllImport("fusion.dll")] public static extern int CreateAssemblyEnum( out IAssemblyEnum ppEnum, IntPtr pUnkReserved, IAssemblyName pName, AssemblyCacheFlags flags, IntPtr pvReserved); [DllImport("fusion.dll")] public static extern int CreateAssemblyNameObject( out IAssemblyName ppAssemblyNameObj, [MarshalAs(UnmanagedType.LPWStr)] String szAssemblyName, CreateAssemblyNameObjectFlags flags, IntPtr pvReserved); } }
aspnet/AspNetCore
src/Installers/Windows/AspNetCoreModule-Setup/IIS-Setup/IIS-Common/Managed/NativeMethods/Fusion.cs
C#
apache-2.0
4,421
package com.krealid.starter.adapters; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.krealid.starter.R; import butterknife.ButterKnife; /** * Created by Maxime on 26/08/2015. */ public class ActuExpendedAdapter extends RecyclerView.Adapter<ActuExpendedAdapter.ViewHolder> { private String text; private Context context; private View view; public ActuExpendedAdapter(String text, Context context){ this.text = text; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { view = LayoutInflater .from(parent.getContext()) .inflate(R.layout.actu_text, parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { String iframeLink; if(this.text.contains("<iframe")){ String iframeStart = "<iframe src=\""; String iframeEnd = "\" width="; int indexToStartIframe = this.text.indexOf(iframeStart); int indexToEndIframe = (this.text.substring(indexToStartIframe)).indexOf(iframeEnd); String iframeHeight = "height=\""; int indexToStartHeightIframe= this.text.indexOf(iframeHeight); String iframeHeightValue = this.text.substring(indexToStartHeightIframe + iframeHeight.length(), this.text.indexOf('"', indexToStartHeightIframe + iframeHeight.length())); iframeLink = this.text.substring(indexToStartIframe + iframeStart.length(), indexToStartIframe + indexToEndIframe); String articleText = this.text.substring(0, indexToStartIframe); holder.text.loadData("<font style=\"text-align:justify;text-justify:inter-word;\">" + articleText + "</font>", "text/html; charset=UTF-8", null); final RelativeLayout layout = new RelativeLayout(this.context); RelativeLayout.LayoutParams lprams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.MATCH_PARENT); layout.setLayoutParams(lprams); WebView web1 = new WebView(this.context); web1.setWebChromeClient(new WebChromeClient()); web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); web1.getSettings().setJavaScriptEnabled(true); web1.getSettings().setPluginState(WebSettings.PluginState.ON); web1.loadUrl(iframeLink); web1.setId(R.id.myWebView); int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Integer.parseInt(iframeHeightValue), this.context.getResources().getDisplayMetrics()); final RelativeLayout.LayoutParams webViewParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, height); layout.addView(web1, webViewParams); holder.articleContainer.addView(layout); } else { holder.text.loadData("<font style=\"text-align:justify;text-justify:inter-word;\">" + this.text + "</font>", "text/html; charset=UTF-8", null); } } @Override public int getItemCount() { return 1; } public void stopVideo(){ ViewHolder holder = new ViewHolder(view); WebView mWebView = (WebView) holder.articleContainer.findViewById(R.id.myWebView); if(mWebView != null) mWebView.loadUrl("about:blank"); } public static class ViewHolder extends RecyclerView.ViewHolder { public WebView text; public LinearLayout articleContainer; public ViewHolder(View itemView) { super(itemView); text = ButterKnife.findById(itemView, R.id.articleContent); articleContainer = ButterKnife.findById(itemView, R.id.article_container); } } }
max02100/paroisse
ParseStarterProject/src/main/java/com/krealid/starter/adapters/ActuExpendedAdapter.java
Java
apache-2.0
4,384
// // PBObjcWrapper.h // AppBootstrap // // Created by Yaming on 10/31/14. // Copyright (c) 2014 whosbean.com. All rights reserved. // #import <Foundation/Foundation.h> #ifdef __cplusplus #import <google/protobuf/message.h> #endif @protocol PBObjcWrapper <NSObject> -(instancetype) initWithProtocolData:(NSData*) data; #ifdef __cplusplus -(instancetype) initWithProtocolObj:(google::protobuf::Message *)pbobj; #endif -(NSData*) getProtocolData; -(NSMutableDictionary*) asDict; @end
yamingd/AppBootstrap-iOS
AppBootstrap/Protobuf/PBObjcWrapper.hh
C++
apache-2.0
493
package storage import ( "io/ioutil" "log" "os" "path/filepath" "testing" ) func TestSetBinlogPosition(t *testing.T) { dir, err := ioutil.TempDir("", "example") if err != nil { log.Fatal(err) } defer os.RemoveAll(dir) file := filepath.Join(dir, "temp.db") store := &BoltDBStore{} store.Open(file) store.SetBinlogPosition(&BinlogInformation{File: "binlog001.log", Position: 1234567890}) binlogInfo, err := store.GetBinlogPosition() if err != nil || binlogInfo.File != "binlog001.log" || binlogInfo.Position != 1234567890 { t.Error("failed") } }
simongui/fastlane
storage/boltdb_store_test.go
GO
apache-2.0
568
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBigPicture.h" #include "SkData.h" #include "SkDrawable.h" #include "SkLayerInfo.h" #include "SkPictureRecorder.h" #include "SkPictureUtils.h" #include "SkRecord.h" #include "SkRecordDraw.h" #include "SkRecordOpts.h" #include "SkRecorder.h" #include "SkTypes.h" SkPictureRecorder::SkPictureRecorder() { fActivelyRecording = false; fRecorder.reset(new SkRecorder(nullptr, SkRect::MakeWH(0, 0), &fMiniRecorder)); } SkPictureRecorder::~SkPictureRecorder() {} SkCanvas* SkPictureRecorder::beginRecording(const SkRect& cullRect, SkBBHFactory* bbhFactory /* = nullptr */, uint32_t recordFlags /* = 0 */) { fCullRect = cullRect; fFlags = recordFlags; if (bbhFactory) { fBBH.reset((*bbhFactory)(cullRect)); SkASSERT(fBBH.get()); } if (!fRecord) { fRecord.reset(new SkRecord); } SkRecorder::DrawPictureMode dpm = (recordFlags & kPlaybackDrawPicture_RecordFlag) ? SkRecorder::Playback_DrawPictureMode : SkRecorder::Record_DrawPictureMode; fRecorder->reset(fRecord.get(), cullRect, dpm, &fMiniRecorder); fActivelyRecording = true; return this->getRecordingCanvas(); } SkCanvas* SkPictureRecorder::getRecordingCanvas() { return fActivelyRecording ? fRecorder.get() : nullptr; } sk_sp<SkPicture> SkPictureRecorder::finishRecordingAsPicture() { fActivelyRecording = false; fRecorder->restoreToCount(1); // If we were missing any restores, add them now. if (fRecord->count() == 0) { return fMiniRecorder.detachAsPicture(fCullRect); } // TODO: delay as much of this work until just before first playback? SkRecordOptimize(fRecord); SkAutoTUnref<SkLayerInfo> saveLayerData; if (fBBH && (fFlags & kComputeSaveLayerInfo_RecordFlag)) { saveLayerData.reset(new SkLayerInfo); } SkDrawableList* drawableList = fRecorder->getDrawableList(); SkBigPicture::SnapshotArray* pictList = drawableList ? drawableList->newDrawableSnapshot() : nullptr; if (fBBH.get()) { SkAutoTMalloc<SkRect> bounds(fRecord->count()); if (saveLayerData) { SkRecordComputeLayers(fCullRect, *fRecord, bounds, pictList, saveLayerData); } else { SkRecordFillBounds(fCullRect, *fRecord, bounds); } fBBH->insert(bounds, fRecord->count()); // Now that we've calculated content bounds, we can update fCullRect, often trimming it. // TODO: get updated fCullRect from bounds instead of forcing the BBH to return it? SkRect bbhBound = fBBH->getRootBound(); SkASSERT((bbhBound.isEmpty() || fCullRect.contains(bbhBound)) || (bbhBound.isEmpty() && fCullRect.isEmpty())); fCullRect = bbhBound; } size_t subPictureBytes = fRecorder->approxBytesUsedBySubPictures(); for (int i = 0; pictList && i < pictList->count(); i++) { subPictureBytes += SkPictureUtils::ApproximateBytesUsed(pictList->begin()[i]); } return sk_make_sp<SkBigPicture>(fCullRect, fRecord.release(), pictList, fBBH.release(), saveLayerData.release(), subPictureBytes); } sk_sp<SkPicture> SkPictureRecorder::finishRecordingAsPictureWithCull(const SkRect& cullRect) { fCullRect = cullRect; return this->finishRecordingAsPicture(); } void SkPictureRecorder::partialReplay(SkCanvas* canvas) const { if (nullptr == canvas) { return; } int drawableCount = 0; SkDrawable* const* drawables = nullptr; SkDrawableList* drawableList = fRecorder->getDrawableList(); if (drawableList) { drawableCount = drawableList->count(); drawables = drawableList->begin(); } SkRecordDraw(*fRecord, canvas, nullptr, drawables, drawableCount, nullptr/*bbh*/, nullptr/*callback*/); } /////////////////////////////////////////////////////////////////////////////////////////////////// class SkRecordedDrawable : public SkDrawable { SkAutoTUnref<SkRecord> fRecord; SkAutoTUnref<SkBBoxHierarchy> fBBH; SkAutoTDelete<SkDrawableList> fDrawableList; const SkRect fBounds; const bool fDoSaveLayerInfo; public: SkRecordedDrawable(SkRecord* record, SkBBoxHierarchy* bbh, SkDrawableList* drawableList, const SkRect& bounds, bool doSaveLayerInfo) : fRecord(SkRef(record)) , fBBH(SkSafeRef(bbh)) , fDrawableList(drawableList) // we take ownership , fBounds(bounds) , fDoSaveLayerInfo(doSaveLayerInfo) {} protected: SkRect onGetBounds() override { return fBounds; } void onDraw(SkCanvas* canvas) override { SkDrawable* const* drawables = nullptr; int drawableCount = 0; if (fDrawableList) { drawables = fDrawableList->begin(); drawableCount = fDrawableList->count(); } SkRecordDraw(*fRecord, canvas, nullptr, drawables, drawableCount, fBBH, nullptr/*callback*/); } SkPicture* onNewPictureSnapshot() override { SkBigPicture::SnapshotArray* pictList = nullptr; if (fDrawableList) { // TODO: should we plumb-down the BBHFactory and recordFlags from our host // PictureRecorder? pictList = fDrawableList->newDrawableSnapshot(); } SkAutoTUnref<SkLayerInfo> saveLayerData; if (fBBH && fDoSaveLayerInfo) { // TODO: can we avoid work by not allocating / filling these bounds? SkAutoTMalloc<SkRect> scratchBounds(fRecord->count()); saveLayerData.reset(new SkLayerInfo); SkRecordComputeLayers(fBounds, *fRecord, scratchBounds, pictList, saveLayerData); } size_t subPictureBytes = 0; for (int i = 0; pictList && i < pictList->count(); i++) { subPictureBytes += SkPictureUtils::ApproximateBytesUsed(pictList->begin()[i]); } // SkBigPicture will take ownership of a ref on both fRecord and fBBH. // We're not willing to give up our ownership, so we must ref them for SkPicture. return new SkBigPicture(fBounds, SkRef(fRecord.get()), pictList, SkSafeRef(fBBH.get()), saveLayerData.release(), subPictureBytes); } }; sk_sp<SkDrawable> SkPictureRecorder::finishRecordingAsDrawable() { fActivelyRecording = false; fRecorder->flushMiniRecorder(); fRecorder->restoreToCount(1); // If we were missing any restores, add them now. // TODO: delay as much of this work until just before first playback? SkRecordOptimize(fRecord); if (fBBH.get()) { SkAutoTMalloc<SkRect> bounds(fRecord->count()); SkRecordFillBounds(fCullRect, *fRecord, bounds); fBBH->insert(bounds, fRecord->count()); } sk_sp<SkDrawable> drawable = sk_make_sp<SkRecordedDrawable>(fRecord, fBBH, fRecorder->detachDrawableList(), fCullRect, SkToBool(fFlags & kComputeSaveLayerInfo_RecordFlag)); // release our refs now, so only the drawable will be the owner. fRecord.reset(nullptr); fBBH.reset(nullptr); return drawable; }
qrealka/skia-hc
src/core/SkPictureRecorder.cpp
C++
apache-2.0
7,381
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; namespace gov.va.medora.mdo.dao { public interface IEncounterDao { Appointment[] getAppointments(); Appointment[] getAppointments(string pid); Appointment[] getFutureAppointments(); Appointment[] getFutureAppointments(string pid); Appointment[] getAppointments(int pastDays, int futureDays); Appointment[] getAppointments(string pid, int pastDays, int futureDays); Appointment[] getMentalHealthAppointments(); string getAppointmentText(string apptId); string getAppointmentText(string pid, string apptId); Adt[] getInpatientMoves(string fromDate, string toDate); Adt[] getInpatientMovesByCheckinId(string checkinId); Adt[] getInpatientMoves(); Adt[] getInpatientMoves(string pid); Adt[] getInpatientMoves(string fromDate, string toDate, string iterLength); // Depreciate to lookupHospitalLocations HospitalLocation[] lookupLocations(string target, string direction); StringDictionary lookupHospitalLocations(string target); string getLocationId(string locationName); HospitalLocation[] getWards(); HospitalLocation[] getClinics(string target, string direction); InpatientStay[] getStaysForWard(string wardId); Drg[] getDRGRecords(); Visit[] getOutpatientVisits(); Visit[] getOutpatientVisits(string pid); Visit[] getVisits(string fromDate, string toDate); Visit[] getVisits(string pid, string fromDate, string toDate); Visit[] getVisitsForDay(string theDate); Visit[] getMentalHealthVisits(); InpatientStay[] getAdmissions(); InpatientStay[] getAdmissions(string pid); string getServiceConnectedCategory(string initialCategory, string locationIen, bool outpatient); string getOutpatientEncounterReport(string fromDate, string toDate, int nrpts); string getOutpatientEncounterReport(string pid, string fromDate, string toDate, int nrpts); string getAdmissionsReport(string fromDate, string toDate, int nrpts); string getAdmissionsReport(string pid, string fromDate, string toDate, int nrpts); string getExpandedAdtReport(string fromDate, string toDate, int nrpts); string getExpandedAdtReport(string pid, string fromDate, string toDate, int nrpts); string getDischargesReport(string fromDate, string toDate, int nrpts); string getDischargesReport(string pid, string fromDate, string toDate, int nrpts); string getTransfersReport(string fromDate, string toDate, int nrpts); string getTransfersReport(string pid, string fromDate, string toDate, int nrpts); string getFutureClinicVisitsReport(string fromDate, string toDate, int nrpts); string getFutureClinicVisitsReport(string pid, string fromDate, string toDate, int nrpts); string getPastClinicVisitsReport(string fromDate, string toDate, int nrpts); string getPastClinicVisitsReport(string pid, string fromDate, string toDate, int nrpts); string getTreatingSpecialtyReport(string fromDate, string toDate, int nrpts); string getTreatingSpecialtyReport(string pid, string fromDate, string toDate, int nrpts); string getCareTeamReport(); string getCareTeamReport(string pid); string getDischargeDiagnosisReport(string fromDate, string toDate, int nrpts); string getDischargeDiagnosisReport(string pid, string fromDate, string toDate, int nrpts); IcdReport[] getIcdProceduresReport(string fromDate, string toDate, int nrpts); IcdReport[] getIcdProceduresReport(string pid, string fromDate, string toDate, int nrpts); IcdReport[] getIcdSurgeryReport(string fromDate, string toDate, int nrpts); IcdReport[] getIcdSurgeryReport(string pid, string fromDate, string toDate, int nrpts); string getCompAndPenReport(string fromDate, string toDate, int nrpts); string getCompAndPenReport(string pid, string fromDate, string toDate, int nrpts); DictionaryHashList getSpecialties(); DictionaryHashList getTeams(); Adt[] getInpatientDischarges(string pid); InpatientStay[] getStayMovementsByDateRange(string fromDate, string toDate); InpatientStay getStayMovements(string checkinId); Site[] getSiteDivisions(string siteId); PatientCareTeam getPatientCareTeamMembers(string station); } }
VHAINNOVATIONS/RAPTOR
OtherComponents/MDWSvistalayer/MDWS Source/mdo/mdo/src/mdo/dao/IEncounterDao.cs
C#
apache-2.0
4,557
/* * Copyright (c) 2017 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. */ package org.webrtc; @JNINamespace("webrtc::jni") class VP8Decoder extends WrappedNativeVideoDecoder { @Override long createNativeDecoder() { return nativeCreateDecoder(); } static native long nativeCreateDecoder(); }
wangcy6/storm_app
frame/c++/webrtc-master/sdk/android/src/java/org/webrtc/VP8Decoder.java
Java
apache-2.0
645
/* * Copyright (C) 2013 The Android Open Source Project * * 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.android.inputmethod.keyboard.internal; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.os.Message; import android.util.SparseArray; import android.view.View; import com.android.inputmethod.keyboard.PointerTracker; import com.android.inputmethod.keyboard.internal.GestureTrail.Params; import com.android.inputmethod.latin.CollectionUtils; import com.android.inputmethod.latin.StaticInnerHandlerWrapper; /** * Draw gesture trail preview graphics during gesture. */ public final class GestureTrailsPreview extends AbstractDrawingPreview { private final SparseArray<GestureTrail> mGestureTrails = CollectionUtils.newSparseArray(); private final Params mGestureTrailParams; private final Paint mGesturePaint; private int mOffscreenWidth; private int mOffscreenHeight; private int mOffscreenOffsetY; private Bitmap mOffscreenBuffer; private final Canvas mOffscreenCanvas = new Canvas(); private final Rect mOffscreenSrcRect = new Rect(); private final Rect mDirtyRect = new Rect(); private final Rect mGestureTrailBoundsRect = new Rect(); // per trail private final DrawingHandler mDrawingHandler; private static final class DrawingHandler extends StaticInnerHandlerWrapper<GestureTrailsPreview> { private static final int MSG_UPDATE_GESTURE_TRAIL = 0; private final Params mGestureTrailParams; public DrawingHandler(final GestureTrailsPreview outerInstance, final Params gestureTrailParams) { super(outerInstance); mGestureTrailParams = gestureTrailParams; } @Override public void handleMessage(final Message msg) { final GestureTrailsPreview preview = getOuterInstance(); if (preview == null) return; switch (msg.what) { case MSG_UPDATE_GESTURE_TRAIL: preview.getDrawingView().invalidate(); break; } } public void postUpdateGestureTrailPreview() { removeMessages(MSG_UPDATE_GESTURE_TRAIL); sendMessageDelayed(obtainMessage(MSG_UPDATE_GESTURE_TRAIL), mGestureTrailParams.mUpdateInterval); } } public GestureTrailsPreview(final View drawingView, final TypedArray mainKeyboardViewAttr) { super(drawingView); mGestureTrailParams = new Params(mainKeyboardViewAttr); mDrawingHandler = new DrawingHandler(this, mGestureTrailParams); final Paint gesturePaint = new Paint(); gesturePaint.setAntiAlias(true); gesturePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC)); mGesturePaint = gesturePaint; } @Override public void setKeyboardGeometry(final int[] originCoords, final int width, final int height) { mOffscreenOffsetY = (int)( height * GestureStroke.EXTRA_GESTURE_TRAIL_AREA_ABOVE_KEYBOARD_RATIO); mOffscreenWidth = width; mOffscreenHeight = mOffscreenOffsetY + height; } @Override public void onDetachFromWindow() { freeOffscreenBuffer(); } private void freeOffscreenBuffer() { if (mOffscreenBuffer != null) { mOffscreenBuffer.recycle(); mOffscreenBuffer = null; } } private void mayAllocateOffscreenBuffer() { if (mOffscreenBuffer != null && mOffscreenBuffer.getWidth() == mOffscreenWidth && mOffscreenBuffer.getHeight() == mOffscreenHeight) { return; } freeOffscreenBuffer(); mOffscreenBuffer = Bitmap.createBitmap( mOffscreenWidth, mOffscreenHeight, Bitmap.Config.ARGB_8888); mOffscreenCanvas.setBitmap(mOffscreenBuffer); mOffscreenCanvas.translate(0, mOffscreenOffsetY); } private boolean drawGestureTrails(final Canvas offscreenCanvas, final Paint paint, final Rect dirtyRect) { // Clear previous dirty rectangle. if (!dirtyRect.isEmpty()) { paint.setColor(Color.TRANSPARENT); paint.setStyle(Paint.Style.FILL); offscreenCanvas.drawRect(dirtyRect, paint); } dirtyRect.setEmpty(); boolean needsUpdatingGestureTrail = false; // Draw gesture trails to offscreen buffer. synchronized (mGestureTrails) { // Trails count == fingers count that have ever been active. final int trailsCount = mGestureTrails.size(); for (int index = 0; index < trailsCount; index++) { final GestureTrail trail = mGestureTrails.valueAt(index); needsUpdatingGestureTrail |= trail.drawGestureTrail(offscreenCanvas, paint, mGestureTrailBoundsRect, mGestureTrailParams); // {@link #mGestureTrailBoundsRect} has bounding box of the trail. dirtyRect.union(mGestureTrailBoundsRect); } } return needsUpdatingGestureTrail; } /** * Draws the preview * @param canvas The canvas where the preview is drawn. */ @Override public void drawPreview(final Canvas canvas) { if (!isPreviewEnabled()) { return; } mayAllocateOffscreenBuffer(); // Draw gesture trails to offscreen buffer. final boolean needsUpdatingGestureTrail = drawGestureTrails( mOffscreenCanvas, mGesturePaint, mDirtyRect); if (needsUpdatingGestureTrail) { mDrawingHandler.postUpdateGestureTrailPreview(); } // Transfer offscreen buffer to screen. if (!mDirtyRect.isEmpty()) { mOffscreenSrcRect.set(mDirtyRect); mOffscreenSrcRect.offset(0, mOffscreenOffsetY); canvas.drawBitmap(mOffscreenBuffer, mOffscreenSrcRect, mDirtyRect, null); // Note: Defer clearing the dirty rectangle here because we will get cleared // rectangle on the canvas. } } /** * Set the position of the preview. * @param tracker The new location of the preview is based on the points in PointerTracker. */ @Override public void setPreviewPosition(final PointerTracker tracker) { if (!isPreviewEnabled()) { return; } GestureTrail trail; synchronized (mGestureTrails) { trail = mGestureTrails.get(tracker.mPointerId); if (trail == null) { trail = new GestureTrail(); mGestureTrails.put(tracker.mPointerId, trail); } } trail.addStroke(tracker.getGestureStrokeWithPreviewPoints(), tracker.getDownTime()); // TODO: Should narrow the invalidate region. getDrawingView().invalidate(); } }
slightfoot/android-kioskime
src/com/android/inputmethod/keyboard/internal/GestureTrailsPreview.java
Java
apache-2.0
7,627
using System.Collections.Generic; using Amazon.DynamoDBv2.Model; using AwsTools; using IndexBackend; namespace SlideshowCreator.AwsAccess { class DynamoDbInsert { public const int BATCH_SIZE = 25; public static Dictionary<string, List<WriteRequest>> GetBatchInserts<T>(List<T> pocoModels) where T : IModel, new() { var batchWrite = new Dictionary<string, List<WriteRequest>> { [new T().GetTable()] = new List<WriteRequest>() }; foreach (var pocoModel in pocoModels) { var dyamoDbModel = Conversion<T>.ConvertToDynamoDb(pocoModel); var putRequest = new PutRequest(dyamoDbModel); var writeRequest = new WriteRequest(putRequest); batchWrite[new T().GetTable()].Add(writeRequest); } return batchWrite; } } }
timg456789/SlideshowCreator
SlideshowCreator/SlideshowCreator/AwsAccess/DynamoDbInsert.cs
C#
apache-2.0
879
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.dialogflow.v3beta1.model; /** * Metadata for a ConversationDatasets.ImportConversationData operation. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudDialogflowV2ImportConversationDataOperationMetadata extends com.google.api.client.json.GenericJson { /** * The resource name of the imported conversation dataset. Format: * `projects//locations//conversationDatasets/` * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String conversationDataset; /** * Timestamp when import conversation data request was created. The time is measured on server * side. * The value may be {@code null}. */ @com.google.api.client.util.Key private String createTime; /** * Partial failures are failures that don't fail the whole long running operation, e.g. single * files that couldn't be read. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleRpcStatus> partialFailures; /** * The resource name of the imported conversation dataset. Format: * `projects//locations//conversationDatasets/` * @return value or {@code null} for none */ public java.lang.String getConversationDataset() { return conversationDataset; } /** * The resource name of the imported conversation dataset. Format: * `projects//locations//conversationDatasets/` * @param conversationDataset conversationDataset or {@code null} for none */ public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setConversationDataset(java.lang.String conversationDataset) { this.conversationDataset = conversationDataset; return this; } /** * Timestamp when import conversation data request was created. The time is measured on server * side. * @return value or {@code null} for none */ public String getCreateTime() { return createTime; } /** * Timestamp when import conversation data request was created. The time is measured on server * side. * @param createTime createTime or {@code null} for none */ public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setCreateTime(String createTime) { this.createTime = createTime; return this; } /** * Partial failures are failures that don't fail the whole long running operation, e.g. single * files that couldn't be read. * @return value or {@code null} for none */ public java.util.List<GoogleRpcStatus> getPartialFailures() { return partialFailures; } /** * Partial failures are failures that don't fail the whole long running operation, e.g. single * files that couldn't be read. * @param partialFailures partialFailures or {@code null} for none */ public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata setPartialFailures(java.util.List<GoogleRpcStatus> partialFailures) { this.partialFailures = partialFailures; return this; } @Override public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata set(String fieldName, Object value) { return (GoogleCloudDialogflowV2ImportConversationDataOperationMetadata) super.set(fieldName, value); } @Override public GoogleCloudDialogflowV2ImportConversationDataOperationMetadata clone() { return (GoogleCloudDialogflowV2ImportConversationDataOperationMetadata) super.clone(); } }
googleapis/google-api-java-client-services
clients/google-api-services-dialogflow/v3beta1/1.31.0/com/google/api/services/dialogflow/v3beta1/model/GoogleCloudDialogflowV2ImportConversationDataOperationMetadata.java
Java
apache-2.0
4,520
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using Windows.Web.Syndication; namespace DncShowcaseHub.DataModel { class FeedItemIterator { private SyndicationFeed feed; private int index; public FeedItemIterator() { this.feed = null; this.index = 0; } public void AttachFeed(SyndicationFeed feed) { this.feed = feed; this.index = 0; } public bool MoveNext() { if (feed != null && index < feed.Items.Count - 1) { index++; return true; } return false; } public void MovePrevious() { if (feed != null && index > 0) { index--; } } public bool HasElements() { return feed != null && feed.Items.Count > 0; } public string GetTitle() { // Nothing to return yet. if (!HasElements()) { return "(no title)"; } if (feed.Items[index].Title != null) { return WebUtility.HtmlDecode(feed.Items[index].Title.Text); } return "(no title)"; } public string GetContent() { // Nothing to return yet. if (!HasElements()) { return "(no value)"; } if ((feed.Items[index].Content != null) && (feed.Items[index].Content.Text != null)) { return feed.Items[index].Content.Text; } else if (feed.Items[index].Summary != null && !string.IsNullOrEmpty(feed.Items[index].Summary.Text)) { return feed.Items[index].Summary.Text; } return "(no value)"; } public string GetIndexDescription() { // Nothing to return yet. if (!HasElements()) { return "0 of 0"; } return String.Format("{0} of {1}", index + 1, feed.Items.Count); } public Uri GetEditUri() { // Nothing to return yet. if (!HasElements()) { return null; } return feed.Items[index].EditUri; } public SyndicationItem GetSyndicationItem() { // Nothing to return yet. if (!HasElements()) { return null; } return feed.Items[index]; } internal string GetAuthor() { if (feed.Items[index].Authors != null && feed.Items[index].Authors.Count > 0) { string authors = ""; foreach (var author in feed.Items[index].Authors) { authors += (author.NodeValue + ","); } return authors.TrimEnd(','); } return ""; } internal string GetUrlPath() { if (feed.Items[index].Links != null && feed.Items[index].Links.Count > 0) { return feed.Items[index].Links[0].Uri.AbsoluteUri; } return ""; } } }
dotnetcurry/winrt-81-hub-control
DncShowcaseHub/DncShowcaseHub/DataModel/FeedItemIterator.cs
C#
apache-2.0
3,497
<?php namespace db2eav\Classes; class Value extends ValueBase { public function __construct(){ } public function __destruct(){ } }
arhouati/DB2EAV
src/db2eav/Classes/Value.php
PHP
apache-2.0
156
package com.xiaochen.progressroundbutton; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.RectF; import android.graphics.Shader; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.animation.PathInterpolatorCompat; import android.util.AttributeSet; import android.widget.TextView; /** * Created by tanfujun on 15/9/4. */ public class AnimDownloadProgressButton extends TextView { private Context mContext; //背景画笔 private Paint mBackgroundPaint; //按钮文字画笔 private volatile Paint mTextPaint; //第一个点画笔 private Paint mDot1Paint; //第二个点画笔 private Paint mDot2Paint; //背景颜色 private int[] mBackgroundColor; private int[] mOriginBackgroundColor; //下载中后半部分后面背景颜色 private int mBackgroundSecondColor; //文字颜色 private int mTextColor; //覆盖后颜色 private int mTextCoverColor; //文字大小 private float mAboveTextSize = 50; private float mProgress = -1; private float mToProgress; private int mMaxProgress; private int mMinProgress; private float mProgressPercent; private float mButtonRadius; //两个点向右移动距离 private float mDot1transX; private float mDot2transX; private RectF mBackgroundBounds; private LinearGradient mFillBgGradient; private LinearGradient mProgressBgGradient; private LinearGradient mProgressTextGradient; //点运动动画 private AnimatorSet mDotAnimationSet; //下载平滑动画 private ValueAnimator mProgressAnimation; //记录当前文字 private CharSequence mCurrentText; //普通状态 public static final int NORMAL = 0; //下载中 public static final int DOWNLOADING = 1; //有点运动状态 public static final int INSTALLING = 2; private ButtonController mDefaultController; private ButtonController mCustomerController; private int mState; public AnimDownloadProgressButton(Context context) { this(context, null); } public AnimDownloadProgressButton(Context context, AttributeSet attrs) { super(context, attrs); if (!isInEditMode()) { mContext = context; initController(); initAttrs(context, attrs); init(); setupAnimations(); }else { initController(); } } private void initController() { mDefaultController = new DefaultButtonController(); } @Override protected void drawableStateChanged() { super.drawableStateChanged(); ButtonController buttonController = switchController(); if (buttonController.enablePress()) { if (mOriginBackgroundColor == null) { mOriginBackgroundColor = new int[2]; mOriginBackgroundColor[0] = mBackgroundColor[0]; mOriginBackgroundColor[1] = mBackgroundColor[1]; } if (this.isPressed()) { int pressColorleft = buttonController.getPressedColor(mBackgroundColor[0]); int pressColorright = buttonController.getPressedColor(mBackgroundColor[1]); if (buttonController.enableGradient()) { initGradientColor(pressColorleft, pressColorright); } else { initGradientColor(pressColorleft, pressColorleft); } } else { if (buttonController.enableGradient()) { initGradientColor(mOriginBackgroundColor[0], mOriginBackgroundColor[1]); } else { initGradientColor(mOriginBackgroundColor[0], mOriginBackgroundColor[0]); } } invalidate(); } } private void initAttrs(Context context, AttributeSet attrs) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AnimDownloadProgressButton); int bgColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_backgroud_color, Color.parseColor("#6699ff")); //初始化背景颜色数组 initGradientColor(bgColor, bgColor); mBackgroundSecondColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_backgroud_second_color, Color.LTGRAY); mButtonRadius = a.getFloat(R.styleable.AnimDownloadProgressButton_progressbtn_radius, getMeasuredHeight() / 2); mAboveTextSize = a.getFloat(R.styleable.AnimDownloadProgressButton_progressbtn_text_size, 50); mTextColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_text_color, bgColor); mTextCoverColor = a.getColor(R.styleable.AnimDownloadProgressButton_progressbtn_text_covercolor, Color.WHITE); boolean enableGradient = a.getBoolean(R.styleable.AnimDownloadProgressButton_progressbtn_enable_gradient, false); boolean enablePress = a.getBoolean(R.styleable.AnimDownloadProgressButton_progressbtn_enable_press, false); ((DefaultButtonController) mDefaultController).setEnableGradient(enableGradient).setEnablePress(enablePress); if (enableGradient){ initGradientColor(mDefaultController.getLighterColor(mBackgroundColor[0]),mBackgroundColor[0]); } a.recycle(); } private void init() { mMaxProgress = 100; mMinProgress = 0; mProgress = 0; //设置背景画笔 mBackgroundPaint = new Paint(); mBackgroundPaint.setAntiAlias(true); mBackgroundPaint.setStyle(Paint.Style.FILL); //设置文字画笔 mTextPaint = new Paint(); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(mAboveTextSize); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { //解决文字有时候画不出问题 setLayerType(LAYER_TYPE_SOFTWARE, mTextPaint); } //设置第一个点画笔 mDot1Paint = new Paint(); mDot1Paint.setAntiAlias(true); mDot1Paint.setTextSize(mAboveTextSize); //设置第二个点画笔 mDot2Paint = new Paint(); mDot2Paint.setAntiAlias(true); mDot2Paint.setTextSize(mAboveTextSize); //初始化状态设为NORMAL mState = NORMAL; invalidate(); } //初始化渐变色 private int[] initGradientColor(int leftColor, int rightColor) { mBackgroundColor = new int[2]; mBackgroundColor[0] = leftColor; mBackgroundColor[1] = rightColor; return mBackgroundColor; } private void setupAnimations() { //两个点向右移动动画 ValueAnimator dotMoveAnimation = ValueAnimator.ofFloat(0, 20); TimeInterpolator pathInterpolator = PathInterpolatorCompat.create(0.11f, 0f, 0.12f, 1f); dotMoveAnimation.setInterpolator(pathInterpolator); dotMoveAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float transX = (float) animation.getAnimatedValue(); mDot1transX = transX; mDot2transX = transX; invalidate(); } }); dotMoveAnimation.setDuration(1243); dotMoveAnimation.setRepeatMode(ValueAnimator.RESTART); dotMoveAnimation.setRepeatCount(ValueAnimator.INFINITE); //两个点渐显渐隐动画 final ValueAnimator dotAlphaAnim = ValueAnimator.ofInt(0, 1243).setDuration(1243); dotAlphaAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int time = (int) dotAlphaAnim.getAnimatedValue(); int dot1Alpha = calculateDot1AlphaByTime(time); int dot2Alpha = calculateDot2AlphaByTime(time); mDot1Paint.setColor(mTextCoverColor); mDot2Paint.setColor(mTextCoverColor); mDot1Paint.setAlpha(dot1Alpha); mDot2Paint.setAlpha(dot2Alpha); } }); dotAlphaAnim.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { mDot1Paint.setAlpha(0); mDot2Paint.setAlpha(0); } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); dotAlphaAnim.setRepeatMode(ValueAnimator.RESTART); dotAlphaAnim.setRepeatCount(ValueAnimator.INFINITE); //两个点的动画集合 mDotAnimationSet = new AnimatorSet(); mDotAnimationSet.playTogether(dotAlphaAnim, dotMoveAnimation); //ProgressBar的动画 mProgressAnimation = ValueAnimator.ofFloat(0, 1).setDuration(500); mProgressAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float timepercent = (float) animation.getAnimatedValue(); mProgress = ((mToProgress - mProgress) * timepercent + mProgress); invalidate(); } }); } //第一个点透明度计算函数 private int calculateDot2AlphaByTime(int time) { int alpha; if (0 <= time && time <= 83) { double DAlpha = 255.0 / 83.0 * time; alpha = (int) DAlpha; } else if (83 < time && time <= 1000) { alpha = 255; } else if (1000 < time && time <= 1083) { double DAlpha = -255.0 / 83.0 * (time - 1083); alpha = (int) DAlpha; } else if (1083 < time && time <= 1243) { alpha = 0; } else { alpha = 255; } return alpha; } //第二个点透明度计算函数 private int calculateDot1AlphaByTime(int time) { int alpha; if (0 <= time && time <= 160) { alpha = 0; } else if (160 < time && time <= 243) { double DAlpha = 255.0 / 83.0 * (time - 160); alpha = (int) DAlpha; } else if (243 < time && time <= 1160) { alpha = 255; } else if (1160 < time && time <= 1243) { double DAlpha = -255.0 / 83.0 * (time - 1243); alpha = (int) DAlpha; } else { alpha = 255; } return alpha; } private ValueAnimator createDotAlphaAnimation(int i, Paint mDot1Paint, int i1, int i2, int i3) { return new ValueAnimator(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (!isInEditMode()) { drawing(canvas); } } private void drawing(Canvas canvas) { drawBackground(canvas); drawTextAbove(canvas); } private void drawBackground(Canvas canvas) { mBackgroundBounds = new RectF(); if (mButtonRadius == 0) { mButtonRadius = getMeasuredHeight() / 2; } mBackgroundBounds.left = 2; mBackgroundBounds.top = 2; mBackgroundBounds.right = getMeasuredWidth() - 2; mBackgroundBounds.bottom = getMeasuredHeight() - 2; ButtonController buttonController = switchController(); //color switch (mState) { case NORMAL: if (buttonController.enableGradient()) { mFillBgGradient = new LinearGradient(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2, mBackgroundColor, null, Shader.TileMode.CLAMP); mBackgroundPaint.setShader(mFillBgGradient); } else { if (mBackgroundPaint.getShader() != null) { mBackgroundPaint.setShader(null); } mBackgroundPaint.setColor(mBackgroundColor[0]); } canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint); break; case DOWNLOADING: if (buttonController.enableGradient()) { mProgressPercent = mProgress / (mMaxProgress + 0f); int[] colorList = new int[]{mBackgroundColor[0], mBackgroundColor[1], mBackgroundSecondColor}; mProgressBgGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0, colorList, new float[]{0, mProgressPercent, mProgressPercent + 0.001f}, Shader.TileMode.CLAMP ); mBackgroundPaint.setShader(mProgressBgGradient); } else { mProgressPercent = mProgress / (mMaxProgress + 0f); mProgressBgGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0, new int[]{mBackgroundColor[0], mBackgroundSecondColor}, new float[]{mProgressPercent, mProgressPercent + 0.001f}, Shader.TileMode.CLAMP ); mBackgroundPaint.setColor(mBackgroundColor[0]); mBackgroundPaint.setShader(mProgressBgGradient); } canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint); break; case INSTALLING: if (buttonController.enableGradient()) { mFillBgGradient = new LinearGradient(0, getMeasuredHeight() / 2, getMeasuredWidth(), getMeasuredHeight() / 2, mBackgroundColor, null, Shader.TileMode.CLAMP); mBackgroundPaint.setShader(mFillBgGradient); } else { mBackgroundPaint.setShader(null); mBackgroundPaint.setColor(mBackgroundColor[0]); } canvas.drawRoundRect(mBackgroundBounds, mButtonRadius, mButtonRadius, mBackgroundPaint); break; } } private void drawTextAbove(Canvas canvas) { final float y = canvas.getHeight() / 2 - (mTextPaint.descent() / 2 + mTextPaint.ascent() / 2); if (mCurrentText == null) { mCurrentText = ""; } final float textWidth = mTextPaint.measureText(mCurrentText.toString()); //color switch (mState) { case NORMAL: mTextPaint.setShader(null); mTextPaint.setColor(mTextCoverColor); canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint); break; case DOWNLOADING: //进度条压过距离 float coverlength = getMeasuredWidth() * mProgressPercent; //开始渐变指示器 float indicator1 = getMeasuredWidth() / 2 - textWidth / 2; //结束渐变指示器 float indicator2 = getMeasuredWidth() / 2 + textWidth / 2; //文字变色部分的距离 float coverTextLength = textWidth / 2 - getMeasuredWidth() / 2 + coverlength; float textProgress = coverTextLength / textWidth; if (coverlength <= indicator1) { mTextPaint.setShader(null); mTextPaint.setColor(mTextColor); } else if (indicator1 < coverlength && coverlength <= indicator2) { mProgressTextGradient = new LinearGradient((getMeasuredWidth() - textWidth) / 2, 0, (getMeasuredWidth() + textWidth) / 2, 0, new int[]{mTextCoverColor, mTextColor}, new float[]{textProgress, textProgress + 0.001f}, Shader.TileMode.CLAMP); mTextPaint.setColor(mTextColor); mTextPaint.setShader(mProgressTextGradient); } else { mTextPaint.setShader(null); mTextPaint.setColor(mTextCoverColor); } canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint); break; case INSTALLING: mTextPaint.setColor(mTextCoverColor); canvas.drawText(mCurrentText.toString(), (getMeasuredWidth() - textWidth) / 2, y, mTextPaint); canvas.drawCircle((getMeasuredWidth() + textWidth) / 2 + 4 + mDot1transX, y, 4, mDot1Paint); canvas.drawCircle((getMeasuredWidth() + textWidth) / 2 + 24 + mDot2transX, y, 4, mDot2Paint); break; } } private ButtonController switchController() { if (mCustomerController != null) { return mCustomerController; } else { return mDefaultController; } } public int getState() { return mState; } public void setState(int state) { if (mState != state) {//状态确实有改变 this.mState = state; invalidate(); if (state == AnimDownloadProgressButton.INSTALLING) { //开启两个点动画 mDotAnimationSet.start(); } else if (state == NORMAL) { mDotAnimationSet.cancel(); } else if (state == DOWNLOADING) { mDotAnimationSet.cancel(); } } } /** * 设置按钮文字 */ public void setCurrentText(CharSequence charSequence) { mCurrentText = charSequence; invalidate(); } /** * 设置带下载进度的文字 */ @TargetApi(Build.VERSION_CODES.KITKAT) public void setProgressText(String text, float progress) { if (progress >= mMinProgress && progress < mMaxProgress) { mCurrentText = text + getResources().getString(R.string.downloaded, (int) progress); mToProgress = progress; if (mProgressAnimation.isRunning()) { mProgressAnimation.start(); } else { mProgressAnimation.start(); } } else if (progress < mMinProgress) { mProgress = 0; } else if (progress >= mMaxProgress) { mProgress = 100; mCurrentText = text + getResources().getString(R.string.downloaded, (int) mProgress); invalidate(); } } public float getProgress() { return mProgress; } public void setProgress(float progress) { this.mProgress = progress; } /** * Sometimes you should use the method to avoid memory leak */ public void removeAllAnim() { mDotAnimationSet.cancel(); mDotAnimationSet.removeAllListeners(); mProgressAnimation.cancel(); mProgressAnimation.removeAllListeners(); } public void setProgressBtnBackgroundColor(int color){ initGradientColor(color, color); } public void setProgressBtnBackgroundSecondColor(int color){ mBackgroundSecondColor = color; } public float getButtonRadius() { return mButtonRadius; } public void setButtonRadius(float buttonRadius) { mButtonRadius = buttonRadius; } public int getTextColor() { return mTextColor; } @Override public void setTextColor(int textColor) { mTextColor = textColor; } public int getTextCoverColor() { return mTextCoverColor; } public void setTextCoverColor(int textCoverColor) { mTextCoverColor = textCoverColor; } public int getMinProgress() { return mMinProgress; } public void setMinProgress(int minProgress) { mMinProgress = minProgress; } public int getMaxProgress() { return mMaxProgress; } public void setMaxProgress(int maxProgress) { mMaxProgress = maxProgress; } public void enabelDefaultPress(boolean enable) { if (mDefaultController != null) { ((DefaultButtonController) mDefaultController).setEnablePress(enable); } } public void enabelDefaultGradient(boolean enable) { if (mDefaultController != null) { ((DefaultButtonController) mDefaultController).setEnableGradient(enable); initGradientColor(mDefaultController.getLighterColor(mBackgroundColor[0]),mBackgroundColor[0]); } } @Override public void setTextSize(float size) { mAboveTextSize = size; mTextPaint.setTextSize(size); } @Override public float getTextSize() { return mAboveTextSize; } public AnimDownloadProgressButton setCustomerController(ButtonController customerController) { mCustomerController = customerController; return this; } @Override public void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); mState = ss.state; mProgress = ss.progress; mCurrentText = ss.currentText; } @Override public Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); return new SavedState(superState, (int) mProgress, mState, mCurrentText.toString()); } public static class SavedState extends BaseSavedState { private int progress; private int state; private String currentText; public SavedState(Parcelable parcel, int progress, int state, String currentText) { super(parcel); this.progress = progress; this.state = state; this.currentText = currentText; } private SavedState(Parcel in) { super(in); progress = in.readInt(); state = in.readInt(); currentText = in.readString(); } @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(progress); out.writeInt(state); out.writeString(currentText); } public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } }
Ernest-su/ProgressRoundButton
library/src/main/java/com/xiaochen/progressroundbutton/AnimDownloadProgressButton.java
Java
apache-2.0
23,449
###################################################################### # tc_divmod.rb # # Test case for the Bignum#divmod instance method. ###################################################################### require 'test/unit' class TC_Bignum_Divmod_InstanceMethod < Test::Unit::TestCase def setup @num_int = 9223372036854775808 @den_int = 8589934593 @num_flt = 9223372036854775808.0 @den_flt = 8589934593.0 end def test_divmod_basic assert_respond_to(@num_int, :divmod) assert_nothing_raised{ @num_int.divmod(@den_int) } assert_kind_of(Array, @num_int.divmod(@den_int)) end def test_divmod_integers assert_equal([1073741823, 7516192769.0], @num_int.divmod(@den_int)) assert_equal([0, 8589934593], @den_int.divmod(@num_int)) end def test_divmod_integer_and_float assert_equal([0.0, 8589934593.0], @den_flt.divmod(@num_int)) assert_equal([1073741823, 7516192769.0], @num_int.divmod(@den_flt)) end def test_divmod_floats assert_equal([1073741823, 7516192769.0], @num_flt.divmod(@den_flt)) assert_equal([0.0, 8589934593.0], @den_flt.divmod(@num_flt)) end def test_divmod_expected_errors assert_raises(ArgumentError){ @num_int.divmod } assert_raises(ZeroDivisionError){ @num_int.divmod(0) } assert_raises(TypeError){ @num_int.divmod(nil) } assert_raises(TypeError){ @num_int.divmod('test') } assert_raises(TypeError){ @num_int.divmod(true) } end def teardown @num_int = nil @den_int = nil @num_flt = nil @den_flt = nil end end
google-code/android-scripting
jruby/src/test/externals/ruby_test/test/core/Bignum/instance/tc_divmod.rb
Ruby
apache-2.0
1,607
/* * Copyright 2017 Crown Copyright * * 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 stroom.security.identity.authenticate; import stroom.security.identity.authenticate.api.AuthenticationService; import stroom.util.guice.RestResourcesBinder; import com.google.inject.AbstractModule; public final class AuthenticateModule extends AbstractModule { @Override protected void configure() { bind(AuthenticationService.class).to(AuthenticationServiceImpl.class); RestResourcesBinder.create(binder()) .bind(AuthenticationResourceImpl.class); } }
gchq/stroom
stroom-security/stroom-security-identity/src/main/java/stroom/security/identity/authenticate/AuthenticateModule.java
Java
apache-2.0
1,110
<?php namespace DCarbone\PHPFHIRGenerated\STU3\FHIRElement; /*! * This class was generated with the PHPFHIR library (https://github.com/dcarbone/php-fhir) using * class definitions from HL7 FHIR (https://www.hl7.org/fhir/) * * Class creation date: December 26th, 2019 15:43+0000 * * PHPFHIR Copyright: * * Copyright 2016-2019 Daniel Carbone (daniel.p.carbone@gmail.com) * * 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. * * * FHIR Copyright Notice: * * Copyright (c) 2011+, HL7, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of HL7 nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * * Generated on Wed, Apr 19, 2017 07:44+1000 for FHIR v3.0.1 * * Note: the schemas & schematrons do not contain all of the rules about what makes resources * valid. Implementers will still need to be familiar with the content of the specification and with * any profiles that apply to the resources in order to make a conformant implementation. * */ use DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList; use DCarbone\PHPFHIRGenerated\STU3\FHIRElement; use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRConstants; use DCarbone\PHPFHIRGenerated\STU3\PHPFHIRTypeInterface; /** * Different measurement principle supported by the device. * If the element is present, it must have either a \@value, an \@id, or extensions * * Class FHIRMeasmntPrinciple * @package \DCarbone\PHPFHIRGenerated\STU3\FHIRElement */ class FHIRMeasmntPrinciple extends FHIRElement { // name of FHIR type this class describes const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_MEASMNT_PRINCIPLE; const FIELD_VALUE = 'value'; /** @var string */ private $_xmlns = 'http://hl7.org/fhir'; /** * @var null|\DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList */ protected $value = null; /** * Validation map for fields in type MeasmntPrinciple * @var array */ private static $_validationRules = [ ]; /** * FHIRMeasmntPrinciple Constructor * @param null|array $data */ public function __construct($data = null) { if (null === $data || [] === $data) { return; } if (is_scalar($data)) { $this->setValue(new FHIRMeasmntPrincipleList($data)); return; } if (!is_array($data)) { throw new \InvalidArgumentException(sprintf( 'FHIRMeasmntPrinciple::_construct - $data expected to be null or array, %s seen', gettype($data) )); } parent::__construct($data); if (isset($data[self::FIELD_VALUE])) { $this->setValue($data[self::FIELD_VALUE]); } } /** * @return string */ public function _getFHIRTypeName() { return self::FHIR_TYPE_NAME; } /** * @return string */ public function _getFHIRXMLElementDefinition() { $xmlns = $this->_getFHIRXMLNamespace(); if (null !== $xmlns) { $xmlns = " xmlns=\"{$xmlns}\""; } return "<MeasmntPrinciple{$xmlns}></MeasmntPrinciple>"; } /** * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList */ public function getValue() { return $this->value; } /** * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRCodePrimitive\FHIRMeasmntPrincipleList $value * @return static */ public function setValue($value = null) { if (null === $value) { $this->value = null; return $this; } if ($value instanceof FHIRMeasmntPrincipleList) { $this->value = $value; return $this; } $this->value = new FHIRMeasmntPrincipleList($value); return $this; } /** * Returns the validation rules that this type's fields must comply with to be considered "valid" * The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]] * * @return array */ public function _getValidationRules() { return self::$_validationRules; } /** * Validates that this type conforms to the specifications set forth for it by FHIR. An empty array must be seen as * passing. * * @return array */ public function _getValidationErrors() { $errs = parent::_getValidationErrors(); $validationRules = $this->_getValidationRules(); if (null !== ($v = $this->getValue())) { if ([] !== ($fieldErrs = $v->_getValidationErrors())) { $errs[self::FIELD_VALUE] = $fieldErrs; } } if (isset($validationRules[self::FIELD_VALUE])) { $v = $this->getValue(); foreach($validationRules[self::FIELD_VALUE] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_MEASMNT_PRINCIPLE, self::FIELD_VALUE, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_VALUE])) { $errs[self::FIELD_VALUE] = []; } $errs[self::FIELD_VALUE][$rule] = $err; } } } if (isset($validationRules[self::FIELD_EXTENSION])) { $v = $this->getExtension(); foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_EXTENSION, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_EXTENSION])) { $errs[self::FIELD_EXTENSION] = []; } $errs[self::FIELD_EXTENSION][$rule] = $err; } } } if (isset($validationRules[self::FIELD_ID])) { $v = $this->getId(); foreach($validationRules[self::FIELD_ID] as $rule => $constraint) { $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_ID, $rule, $constraint, $v); if (null !== $err) { if (!isset($errs[self::FIELD_ID])) { $errs[self::FIELD_ID] = []; } $errs[self::FIELD_ID][$rule] = $err; } } } return $errs; } /** * @param \SimpleXMLElement|string|null $sxe * @param null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRMeasmntPrinciple $type * @param null|int $libxmlOpts * @return null|\DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRMeasmntPrinciple */ public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872) { if (null === $sxe) { return null; } if (is_string($sxe)) { libxml_use_internal_errors(true); $sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false); if ($sxe === false) { throw new \DomainException(sprintf('FHIRMeasmntPrinciple::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors())))); } libxml_use_internal_errors(false); } if (!($sxe instanceof \SimpleXMLElement)) { throw new \InvalidArgumentException(sprintf('FHIRMeasmntPrinciple::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe))); } if (null === $type) { $type = new FHIRMeasmntPrinciple; } elseif (!is_object($type) || !($type instanceof FHIRMeasmntPrinciple)) { throw new \RuntimeException(sprintf( 'FHIRMeasmntPrinciple::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\STU3\FHIRElement\FHIRMeasmntPrinciple or null, %s seen.', is_object($type) ? get_class($type) : gettype($type) )); } FHIRElement::xmlUnserialize($sxe, $type); $xmlNamespaces = $sxe->getDocNamespaces(false, false); if ([] !== $xmlNamespaces) { $ns = reset($xmlNamespaces); if (false !== $ns && '' !== $ns) { $type->_xmlns = $ns; } } $attributes = $sxe->attributes(); $children = $sxe->children(); if (isset($children->value)) { $type->setValue(FHIRMeasmntPrincipleList::xmlUnserialize($children->value)); } if (isset($attributes->value)) { $pt = $type->getValue(); if (null !== $pt) { $pt->setValue((string)$attributes->value); } else { $type->setValue((string)$attributes->value); } } return $type; } /** * @param null|\SimpleXMLElement $sxe * @param null|int $libxmlOpts * @return \SimpleXMLElement */ public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872) { if (null === $sxe) { $sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false); } parent::xmlSerialize($sxe); if (null !== ($v = $this->getValue())) { $sxe->addAttribute(self::FIELD_VALUE, (string)$v); } return $sxe; } /** * @return array */ public function jsonSerialize() { $a = parent::jsonSerialize(); if (null !== ($v = $this->getValue())) { $a[self::FIELD_VALUE] = $v; } return $a; } /** * @return string */ public function __toString() { return self::FHIR_TYPE_NAME; } }
dcarbone/php-fhir-generated
src/DCarbone/PHPFHIRGenerated/STU3/FHIRElement/FHIRMeasmntPrinciple.php
PHP
apache-2.0
11,892
using System; using System.Linq; using System.Linq.Expressions; using System.Reactive; using Xamarin.Forms; using RxObservable = System.Reactive.Linq.Observable; using System.Reactive.Linq; namespace RxApp.XamarinForms { public static class Bindings { public static IDisposable BindTo( this IObservable<NavigationStack> This, RxFormsApplication application, Func<INavigationViewModel,Page> createPage) { var navigationPage = application.MainPage; var popping = false; var stack = This .ObserveOnMainThread() .Scan(Tuple.Create(RxApp.NavigationStack.Empty, RxApp.NavigationStack.Empty), (acc, navStack) => Tuple.Create(acc.Item2, navStack)) .SelectMany(async x => { var previousNavStack = x.Item1; var currentNavStack = x.Item2; var currentPage = (navigationPage.CurrentPage as IReadOnlyViewFor); var navPageModel = (currentPage != null) ? (currentPage.ViewModel as INavigationViewModel) : null; var head = currentNavStack.FirstOrDefault(); if (currentNavStack.IsEmpty) { // Do nothing. Can only happen on Android. Android handles the stack being empty by // killing the activity. } else if (head == navPageModel) { // Do nothing, means the user clicked the back button which we cant intercept, // so we let forms pop the view, listen for the popping event, and then popped the view model. } else if (currentNavStack.Pop().Equals(previousNavStack)) { var view = createPage(head); await navigationPage.PushAsync(view, true); } else if (previousNavStack.Pop().Equals(currentNavStack)) { // Programmatic back button was clicked popping = true; await navigationPage.PopAsync(true); popping = false; } else if (previousNavStack.Up().Equals(currentNavStack)) { // Programmatic up button was clicked popping = true; await navigationPage.PopToRootAsync(true); popping = false; } return currentNavStack; }) .Publish(); return Disposable.Compose( stack.Where(x => x.IsEmpty).Subscribe(_ => application.SendDone()), // Handle the user clicking the back button RxObservable.FromEventPattern<NavigationEventArgs>(navigationPage, "Popped") .Where(_ => !popping) .Subscribe(e => { var vm = ((e.EventArgs.Page as IReadOnlyViewFor).ViewModel as INavigationViewModel); vm.Activate.Execute(); vm.Back.Execute(); vm.Deactivate.Execute(); }), stack.Connect() ); } public static IDisposable BindTo<T, TView>(this IObservable<T> This, TView target, Expression<Func<TView, T>> property) { return This.BindTo(target, property, Scheduler.MainThreadScheduler); } public static IDisposable BindTo(this IObservable<Unit> This, Action action) { return This.ObserveOnMainThread().Subscribe(_ => action()); } public static IDisposable BindTo<T>(this IObservable<T> This, Action<T> action) { return This.ObserveOnMainThread().Subscribe(action); } public static IDisposable Bind(this IRxCommand This, Button button) { return Disposable.Compose( This.CanExecute.ObserveOnMainThread().Subscribe(x => button.IsEnabled = x), RxObservable.FromEventPattern(button, "Clicked").InvokeCommand(This) ); } } }
bordoley/RxApp
RxApp.XamarinForms/Bindings.cs
C#
apache-2.0
4,570
/* * Copyright (c) 2012-2015 S-Core Co., Ltd. * * 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. */ require([ 'common', 'lodash', 'moment', 'async', 'text!resource/add_wsdlg.html', 'text!resource/remove_wsdlg.html' ], function (common, _, moment, async, addDlg, removeDlg) { 'use strict'; /* global webidaFs, webidaApp, webidaAuth, webidaHost: true */ var WORKSPACE_PATH = '.profile/workspace.json'; var WORKSPACE_INFO; //var _menuSettings = $('#menu-settings'); var _wsContents = $('.ws-body'); var _dimming = $('.dimming'); var _uniqId; function _dimmingOn() { _dimming.addClass('active'); } function _dimmingOff() { _dimming.removeClass('active'); } function _checkValidWSFile(cb) { webidaFs.readFile(WORKSPACE_PATH, function (err, data) { if (err) { cb('_checkValidWSFile() - readFile Error: ' + err); } else { var wsMeta = JSON.parse(data); var wsMetaCount = Object.keys(wsMeta).length; _getWSList(function (err, wslist) { if (err) { cb('_checkValidWSFile() - _getWSList Error: ' + err); } else { var wsCount = wslist.length; if (wsMetaCount === wsCount) { cb(null, true); } else { cb(null, false); } } }); } }); } function _launchIDE(domObj) { console.log($(domObj).attr('data-wsname')); var workspace = '?workspace=' + webidaFs.fsid + '/' + domObj.attr('data-wsname'); webidaApp.launchApp('devenv', true, workspace); } function _registerDefaultEvent() { // register dimming cancel event _dimming.on('click', function () { _dimming.removeClass('active'); var addWSDlg = $('.add_wsdlg'); var removeWSDlg = $('.remove_wsdlg'); if (addWSDlg) { addWSDlg.remove(); } if (removeWSDlg) { removeWSDlg.remove(); } }); $('#menu-logo').on('click', function () { webidaApp.launchApp('desktop', false, null); }); // register workspace event $('#menu-ws').on('click', function () { var wswrap = $('.ws-wrap'); var settingwrap = $('.settings-wrap'); if (wswrap.hasClass('acitve')) { settingwrap.removeClass('active'); } else { wswrap.addClass('active'); settingwrap.removeClass('active'); } }); // register setting event $('#menu-settings').on('click', function () { var wswrap = $('.ws-wrap'); var settingwrap = $('.settings-wrap'); if (settingwrap.hasClass('acitve')) { wswrap.removeClass('active'); } else { settingwrap.addClass('active'); wswrap.removeClass('active'); } }); // register logout event $('#menu-logout').on('click', function () { _setLogout(); }); // register workspace add event $('.ws-icon-add').on('click', function () { _addWSList(); }); } // WORKSPACE_PATH 파일이 있는지 없는지 여부 확인 후 없으면 생성. function _initialize() { _registerDefaultEvent(); webidaFs.exists(WORKSPACE_PATH, function (err, exist) { if (err) { console.log('_checkWSFile() - exists Error: ' + err); } if (!exist) { _setWorkspace(function (err) { if (err) { console.log(err); } _renderWSList(); }); } else { _checkValidWSFile(function (err, bool) { if (err) { console.log(err); } else { if (bool) { _renderWSList(); } else { console.log('workspace meta-info is invalid.'); _renderWSList(); } } }); } }); } // WORKSPACE 목록 생성 및 WORKSPACE_PATH에 정보 저장. function _setWorkspace(cb) { webidaFs.list('/', function (err, data) { if (err) { console.log('setWorkspace() - list Error: ' + err); cb(err); } else { var WSList = _.chain(data).filter(function (fileObj) { if (!fileObj.name.match(/^\./) && fileObj.isDirectory) { return true; } }).map(function (fileObj) { return '/' + fileObj.name; }).value(); webidaFs.stat(WSList, function (err, stats) { if (err) { console.log('setWorkspace() - stat Error: ' + err); cb(err); } else { var wsObj = {}; _.forEach(stats, function (fileObj) { fileObj.birth = ''; fileObj.desc = ''; wsObj[fileObj.name] = fileObj; }); webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(wsObj), function (err) { if (err) { console.log('setWorkspace() - writeFile Error: ' + err); cb(err); } else { cb(null, true); } }); } }); } }); } // 유니크 id 생성. function _genUniuqeId() { _uniqId = _.uniqueId(); return _uniqId; } // 로그아웃 function _setLogout() { webidaAuth.logout(function (err) { if (err) { alert('Failed to logout'); } else { location.href = '//' + webidaHost; } }); } function _getWSList(cb) { webidaFs.list('/', function (err, data) { if (err) { cb(err); } else { var WSList = _.chain(data).filter(function (fileObj) { if (!fileObj.name.match(/^\./) && fileObj.isDirectory) { return true; } }).map(function (fileObj) { return '/' + fileObj.name; }).value(); webidaFs.stat(WSList, function (err, stats) { if (err) { cb(err); } else { cb(null, stats); } }); } }); } // 프로젝트 목록 얻어오기 function _getPJListPath(WSPath, cb) { webidaFs.list(WSPath, function (err, pjList) { if (err) { cb(err); } else { var filteredPJList = _.chain(pjList).filter(function (file) { if (!file.name.match('.workspace') && file.isDirectory) { return true; } }).map(function (file) { return WSPath + '/' + file.name + '/.project/project.json'; }).value(); return cb(null, filteredPJList); } }); } // 프로젝트 목록 그리기 function _renderPJList(domObj) { var ws = domObj.attr('data-wspath'); var wsRow = domObj.parent(); if (wsRow.hasClass('ws-closed')) { wsRow.addClass('ws-opened'); wsRow.removeClass('ws-closed'); wsRow.after('<div class="pj-body" data-id="' + wsRow.attr('data-id') + '"></div>'); var proRow = wsRow.next(); _getPJListPath(ws, function (err, pjPathList) { if (err) { console.log('_renderPJList() - _getPJListPath Error: ' + err); } else { _.forEach(pjPathList, function (pjPath) { webidaFs.exists(pjPath, function (err, exist) { if (err) { console.log('_renderPJList() - exists Error: ' + err); } if (exist) { webidaFs.readFile(pjPath, function (err, data) { if (err) { console.log('_renderPJList() - read Error: ' + err); } else { var projInfo = JSON.parse(data); /* jshint maxlen : 200 */ var template = '<div class="pj-row"">' + '<div class="pj-content">' + '<div class="pj-item pj-arrow"></div>' + '<div class="pj-item pj-name">' + projInfo.name + '</div>' + '<div class="pj-item pj-ltime"></div>' + '<div class="pj-item pj-birth">' + moment(projInfo.created).fromNow() + '</div>' + '<div class="pj-item pj-desc">' + projInfo.description + '</div>' + '</div>' + '<div class="pj-content-icon">' + '</div>' + '</div>'; /* jshint maxlen:120 */ proRow.append(template); } }); } }); }); } }); } else { var projRow = wsRow.next(); if (projRow.hasClass('pj-body') && (projRow.attr('data-id') === wsRow.attr('data-id'))) { projRow.remove(); wsRow.removeClass('ws-opened'); wsRow.addClass('ws-closed'); } } } // 워크스페이스 목록 그리기 function _renderWSList() { if (_wsContents.children.length) { _wsContents.empty(); } webidaFs.readFile(WORKSPACE_PATH, function (err, data) { if (err) { console.log('_renderWSList() - readFile Error: ' + err); } else { var wsObj = JSON.parse(data); WORKSPACE_INFO = wsObj; _.forEach(wsObj, function (ws) { var id = _genUniuqeId(); var birth = ''; var desc = ''; if (ws.birth) { birth = moment(ws.birth).fromNow(); } if (ws.desc) { desc = ws.desc; } /* jshint maxlen : 200 */ var template = '<div class="ws-row ws-closed" data-id="' + id + '">' + '<div class="ws-content" data-wspath="' + ws.path + '">' + '<div class="ws-item ws-arrow"></div>' + '<div class="ws-item ws-name">' + ws.name + '</div>' + '<div class="ws-item ws-ltime">' + moment(ws.mtime).fromNow() + '</div>' + '<div class="ws-item ws-birth">' + birth + '</div>' + '<div class="ws-item ws-desc">' + desc + '</div>' + '</div>' + '<div class="ws-content-icon">' + '<div class="ws-launch">' + '<div class="ws-icon-launch" title="Launch IDE" data-wsname="' + ws.name + '"></div>' + '</div>' + '<div class="ws-delete">' + '<div class="ws-icon-delete" title="Delete Workspace" data-wsname="' + ws.name + '" data-id="' + id + '"></div>' + '</div>' + '</div>' + '</div>'; /* jshint maxlen : 120 */ _wsContents.append(template); }); // register get project event $('.ws-body .ws-content').on('click', function (evt) { var domObj = $(evt.target).parent(); _renderPJList(domObj); }); // register launch event $('.ws-icon-launch').on('click', function (evt) { var domObj = $(evt.target); _launchIDE(domObj); }); $('.ws-icon-delete').on('click', function (evt) { var domObj = $(evt.target); _removeWSList(domObj); }); } }); } function _addWSList() { _dimmingOn(); $('body').append(addDlg); // register dialog close event $('.adddlg_close').on('click', function () { $('.add_wsdlg').remove(); _dimmingOff(); }); // input에 포커스 $('#workspace_name').focus(); $('#workspace_name').on('keyup', function () { var wsname = this.value; if (wsname) { $('#adddlg_message').text(''); } }); // register create workspace event $('#adddlg_confirm').on('click', function (evt) { evt.preventDefault(); var wsname = $('#workspace_name').val(); var wsdesc = $('#workspace_desc').val(); var message = $('#adddlg_message'); if (!wsname) { message.text('Please enter workspace name.'); return; } _getWSList(function (err, wslist) { if (err) { console.log('_addWSList()' + err); } else { var isExist = _.find(wslist, { 'name' : wsname }); if (isExist) { message.text('\'' + wsname + '\' worskpace is already existed.'); return; } else { // create workspace var WS_META_PATH = wsname + '/.workspace'; var WS_META_FILE = WS_META_PATH + '/workspace.json'; async.waterfall([ function (next) { webidaFs.createDirectory(wsname, false, function (err) { if (err) { next('_addWSList() - 1st createDirectory Error:' + err); } else { next(); } }); }, function (next) { webidaFs.createDirectory(WS_META_PATH, false, function (err) { if (err) { next('_addWSList() - 2nd createDirectory Error:' + err); } else { next(); } }); }, function (next) { webidaFs.writeFile(WS_META_FILE, '', function (err) { if (err) { next('_addWSList() - 1st writeFile Error:' + err); } else { next(); } }); }, function (next) { webidaFs.stat([wsname], function (err, stats) { if (err) { next('_addWSList() - stat Error:' + err); } else { stats[0].birth = new Date().toJSON(); stats[0].desc = wsdesc; WORKSPACE_INFO[wsname] = stats[0]; next(); } }); }, function (next) { webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(WORKSPACE_INFO), function (err) { if (err) { next('_addWSList() - 2nd writeFile Error:' + err); } else { next(); } }); } ], function (err) { if (err) { console.log(err); } else { $('.add_wsdlg').remove(); _dimmingOff(); _renderWSList(); } }); } } }); }); } function _removeWSList(domObj) { _dimmingOn(); $('body').append(removeDlg); $('.removedlg_close').on('click', function () { $('.remove_wsdlg').remove(); _dimmingOff(); }); var deleteWSname = domObj.attr('data-wsname'); var msg = '<p>This action <strong style="color:#fff">CANNOT</strong> be undone. ' + 'This will delete the <span style="color:#fff; font-weight:bold;">' + deleteWSname + '</span> workspace and projects permanetly.</p>' + '<p>Please type in the name of the workspace to confirm.</p>'; $('.removedlg_warning_text').html(msg); // input에 포커스 $('#workspace_name').focus(); $('#workspace_name').on('keyup', function () { var wsname = this.value; if (wsname) { $('#removedlg_message').text(''); } }); $('#removedlg_confirm').on('click', function (evt) { evt.preventDefault(); var wsname = $('#workspace_name').val(); var message = $('#removedlg_message'); if (!wsname) { message.text('Please enter workspace name.'); return; } else if (wsname !== deleteWSname) { message.text('workspace name doesn\'t match.'); return; } if (WORKSPACE_INFO[deleteWSname]) { delete WORKSPACE_INFO[deleteWSname]; async.waterfall([ function (next) { webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(WORKSPACE_INFO), function (err) { if (err) { err('_removeWSList() - writeFile Error: ' + err); } else { next(); } }); }, function (next) { webidaFs.delete(deleteWSname, true, function (err) { if (err) { next('_removeWSList() - delete Error:' + err); } else { next(); } }); } ], function (err) { if (err) { console.log(err); } else { var id = domObj.attr('data-id'); var selectorWS = '.ws-row[data-id=' + id + ']'; var selectorProj = '.pj-body[data-id=' + id + ']'; $(selectorWS).remove(); if ($(selectorProj)) { $(selectorProj).remove(); } $('.remove_wsdlg').remove(); _dimmingOff(); } }); } }); } common.getFS(function (exist) { if (exist) { _initialize(); } else { location.href = '//' + webidaHost; } }); });
5hk/webida-client
apps/dashboard/src/js/main_bak.js
JavaScript
apache-2.0
22,004
package com.example.android.bluetoothlegatt.ble_service; /** * @author Sopheak Tuon * @created on 04-Oct-17 */ import java.util.Locale; public class CountryUtils { public static boolean getMonthAndDayFormate() { Locale locale = Locale.getDefault(); String lang = locale.getLanguage(); String contr = locale.getCountry(); if (lang == null || (!lang.equals("zh") && !lang.equals("ja") && !lang.equals("ko") && (!lang.equals("en") || contr == null || !contr.equals("US")))) { return false; } return true; } public static boolean getLanguageFormate() { String language = Locale.getDefault().getLanguage(); if (language == null || !language.equals("zh")) { return false; } return true; } }
SopheakTuon/Smart-Bracelet
Application/src/main/java/com/example/android/bluetoothlegatt/ble_service/CountryUtils.java
Java
apache-2.0
812
# coding=utf8 from django.views.generic import ListView, DetailView, CreateView from django.db.models import Q from django.http import JsonResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import render from pure_pagination.mixins import PaginationMixin from django.contrib.auth.mixins import LoginRequiredMixin from django.conf import settings from books.models import Publish, Author, Book from books.forms import PublishForm import json import logging logger = logging.getLogger('opsweb') class PublishListView(LoginRequiredMixin, PaginationMixin, ListView): ''' 动作:getlist, create ''' model = Publish template_name = "books/publish_list.html" context_object_name = "publish_list" paginate_by = 5 keyword = '' def get_queryset(self): queryset = super(PublishListView, self).get_queryset() self.keyword = self.request.GET.get('keyword', '').strip() if self.keyword: queryset = queryset.filter(Q(name__icontains=self.keyword) | Q(address__icontains=self.keyword) | Q(city__icontains=self.keyword)) return queryset def get_context_data(self, **kwargs): context = super(PublishListView, self).get_context_data(**kwargs) context['keyword'] = self.keyword return context def post(self, request): form = PublishForm(request.POST) if form.is_valid(): form.save() res = {'code': 0, 'result': '添加出版商成功'} else: # form.errors会把验证不通过的信息以对象的形式传到前端,前端直接渲染即可 res = {'code': 1, 'errmsg': form.errors} print form.errors return JsonResponse(res, safe=True) class PublishDetailView(LoginRequiredMixin, DetailView): ''' 动作:getone, update, delete ''' model = Publish template_name = "books/publish_detail.html" context_object_name = 'publish' next_url = '/books/publishlist/' def post(self, request, *args, **kwargs): pk = kwargs.get('pk') p = self.model.objects.get(pk=pk) form = PublishForm(request.POST, instance=p) if form.is_valid(): form.save() res = {"code": 0, "result": "更新出版商成功", 'next_url': self.next_url} else: res = {"code": 1, "errmsg": form.errors, 'next_url': self.next_url} return render(request, settings.JUMP_PAGE, res) # return HttpResponseRedirect(reverse('books:publish_detail',args=[pk])) def delete(self, request, *args, **kwargs): pk = kwargs.get('pk') # 通过出版社对象查所在该出版社的书籍,如果有关联书籍不可以删除,没有关联书籍可以删除 try: obj = self.model.objects.get(pk=pk) if not obj.book_set.all(): self.model.objects.filter(pk=pk).delete() res = {"code": 0, "result": "删除出版商成功"} else: res = {"code": 1, "errmsg": "该出版社有关联书籍,请联系管理员"} except: res = {"code": 1, "errmsg": "删除错误请联系管理员"} return JsonResponse(res, safe=True)
1032231418/python
lesson10/apps/books/publish/__init__.py
Python
apache-2.0
3,345
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.workmailmessageflow.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.workmailmessageflow.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * MessageRejectedException JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class MessageRejectedExceptionUnmarshaller extends EnhancedJsonErrorUnmarshaller { private MessageRejectedExceptionUnmarshaller() { super(com.amazonaws.services.workmailmessageflow.model.MessageRejectedException.class, "MessageRejected"); } @Override public com.amazonaws.services.workmailmessageflow.model.MessageRejectedException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception { com.amazonaws.services.workmailmessageflow.model.MessageRejectedException messageRejectedException = new com.amazonaws.services.workmailmessageflow.model.MessageRejectedException( null); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return messageRejectedException; } private static MessageRejectedExceptionUnmarshaller instance; public static MessageRejectedExceptionUnmarshaller getInstance() { if (instance == null) instance = new MessageRejectedExceptionUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-workmailmessageflow/src/main/java/com/amazonaws/services/workmailmessageflow/model/transform/MessageRejectedExceptionUnmarshaller.java
Java
apache-2.0
2,934
"use strict"; var router_1 = require('@angular/router'); var authorize_component_1 = require('./authorize/authorize-component'); var user_component_1 = require('./User/user-component'); var welcome_component_1 = require('./welcome-component'); exports.routes = [ { path: '', component: welcome_component_1.welcome }, { path: 'login', component: authorize_component_1.AuthorizeComponent }, { path: 'dashboard', component: user_component_1.UserComponent }, ]; exports.APP_ROUTER_PROVIDERS = [ router_1.provideRouter(exports.routes) ]; //# sourceMappingURL=app.route.js.map
devilsuraj/openiddict-samples
Samples/resource-owner-password-credential/Angualar2-Client-ROPC/app/app.route.js
JavaScript
apache-2.0
586
<?php namespace Home\Controller; class EmptyController extends HomeController{ public function _empty($action){ $resource = strtolower(CONTROLLER_NAME); $this->assign('type', $resource); if(in_array($resource, array('text', 'picture', 'music', 'video'))){ if(in_array($action, array('new', 'edit'))){ if('edit' == $action){ $id = intval(I('id')); if($post = M('post')->find($id)) $this->assign('post', $post); else $this->error('错误的记录'); } $this->display('Post/'.$resource); }else{ $this->error('错误的请求'); } }else{ switch (strtolower(CONTROLLER_NAME)) { case 'post': echo 'post';die; $Index = new IndexController(); $Index->detail(ACTION_NAME); break; case 'search': $Index = new IndexController(); $Index->search(); break; case 'feed': $type = I('get.type'); $this->feed($type); break; case 'mine': if(!is_login()) $this->error('尚未登录,请登录后再访问', "User/login"); $Index = new IndexController(); $Index->mine(); break; default: $Index = new IndexController(); if (is_numeric(CONTROLLER_NAME) && is_numeric(ACTION_NAME)) { $Index->archive(CONTROLLER_NAME,ACTION_NAME); }else{ $this->error('错误的请求'); } break; } } } }
cokeboL/freeblog
App/Home/Controller/EmptyController.class.php
PHP
apache-2.0
1,592
<?php /*------------------------------------------------------------------------ # TZ Portfolio Extension # ------------------------------------------------------------------------ # author DuongTVTemPlaza # copyright Copyright (C) 2012 templaza.com. All Rights Reserved. # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # Websites: http://www.templaza.com # Technical Support: Forum - http://templaza.com/Forum -------------------------------------------------------------------------*/ defined('_JEXEC') or die(); $item = $this -> item; $media = $this -> listMedia; $params = $this -> mediaParams; if($params -> get('portfolio_image_size','S')){ if(!empty($media[0] -> images)){ $src = JURI::root().str_replace('.'.JFile::getExt($media[0] -> images),'_'.$params -> get('portfolio_image_size','S') .'.'.JFile::getExt($media[0] -> images),$media[0] -> images); } } ?> <?php if($media):?> <?php if($media[0] -> type == 'image'):?> <?php $src2 = JURI::root().str_replace('.'.JFile::getExt($media[0] -> images), '_'.$params -> get('detail_article_image_size','XL') .'.'.JFile::getExt($media[0] -> images),$media[0] -> images); ?> <?php if($params -> get('show_image',1) == 1 AND !empty($media[0] -> images)):?> <a class="ib-image" href="<?php echo $item ->link;?>"> <img src="<?php echo $src;?>" data-largesrc="<?php echo$src2;?>" alt="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>" title="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>"/> <span><?php echo $item -> title;?></span> </a> <?php endif;?> <?php endif;?> <?php if($media[0] -> type == 'imagegallery'):?> <?php $srcGallery2 = JURI::root().str_replace('.'.JFile::getExt($media[0] -> images), '_'.$params -> get('detail_article_image_gallery_size','XL') .'.'.JFile::getExt($media[0] -> images),$media[0] -> images); ?> <?php if($params -> get('show_image_gallery',1) == 1 AND !empty($media[0] -> images)):?> <a class="ib-image" href="<?php echo $item ->link;?>"> <img src="<?php echo $src;?>" data-largesrc="<?php echo $srcGallery2;?>" alt="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>" title="<?php if(isset($media[0] -> imagetitle)) echo $media[0] -> imagetitle;?>"/> <span><?php echo $item -> title;?></span> </a> <?php endif;?> <?php endif;?> <?php if($media[0] -> type == 'video'): if($params -> get('show_video',1) == 1 AND !empty($media[0] -> thumb)): $srcVideo = str_replace('.'.JFile::getExt($media[0] -> thumb),'_' .$params -> get('portfolio_image_size','M') .'.'.JFile::getExt($media[0] -> thumb),$media[0] -> thumb); $srcVideo2 = JURI::root().str_replace('.'.JFile::getExt($media[0] -> thumb), '_'.$params -> get('detail_article_image_size','XL') .'.'.JFile::getExt($media[0] -> thumb),$media[0] -> thumb); ?> <a class="ib-image" href="<?php echo $item ->link;?>"> <img src="<?php echo $srcVideo;?>" data-largesrc="<?php echo $srcVideo2;?>" title="<?php echo $media[0] -> imagetitle;?>" alt="<?php echo $media[0] -> imagetitle;?>"/> <span><?php echo $item -> title;?></span> </a> <?php endif;?> <?php endif;?> <?php endif;?>
doomchocolate/dreame-mall
templates/tz_dreame/html/com_tz_portfolio/gallery/default_media.php
PHP
apache-2.0
4,020
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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. namespace Gallio.Model.Filters { internal class FilterToken { private readonly FilterTokenType type; private readonly string text; private readonly int position; internal FilterToken(FilterTokenType type, string text, int position) { this.type = type; this.text = text; this.position = position; } public FilterTokenType Type { get { return type; } } public string Text { get { return text; } } public int Position { get { return position; } } } }
citizenmatt/gallio
src/Gallio/Gallio/Model/Filters/FilterToken.cs
C#
apache-2.0
1,333
<?php /** * Unbind ... * * @phpstub * * @param resource $connection * @param string $trigger_name * * @return bool */ function cyrus_unbind($connection, $trigger_name) { }
schmittjoh/php-stubs
res/php/cyrus/functions/cyrus-unbind.php
PHP
apache-2.0
182
ngDefine( 'cockpit.plugin.statistics-plugin.controllers', function(module) { module .controller( 'processDefinitionCtrl', [ '$scope', 'DataFactory', 'Uri', function($scope, DataFactory, Uri) { $scope.options = { chart : { type : 'pieChart', height : 500, x : function(d) { return d.key; }, y : function(d) { return d.y; }, showLabels : true, transitionDuration : 500, labelThreshold : 0.01, tooltips : true, tooltipContent : function(key, y, e, graph) { if (key == "finished") { return '<h3>' + key + '</h3>' + '<p>count:<b>' + y + '</b><br/>' + 'average Duration:<b>' + (e.point.avg / 1000 / 60).toFixed(2) + ' min</b><br/>minimal Duration:<b>' + (e.point.min / 1000 / 60).toFixed(2) + ' min</b><br/>maximal Duration:<b>' + (e.point.max / 1000 / 60).toFixed(2) + ' min</b></p>' } else { return '<h3>' + key + '</h3>' + '<p>' + y + '</p>' } }, noData : "No Processes met the requirements", legend : { margin : { top : 5, right : 5, bottom : 5, left : 5 } } } }; DataFactory .getAllProcessInstanceCountsByState( $scope.processDefinition.key) .then( function() { var processDefinitionCounts = DataFactory.allProcessInstanceCountsByState[$scope.processDefinition.key]; var counts = []; counts .push({ "key" : "running", "y" : processDefinitionCounts[0].runningInstanceCount }); counts .push({ "key" : "failed", "y" : processDefinitionCounts[0].failedInstanceCount }); counts .push({ "key" : "finished", "y" : processDefinitionCounts[0].endedInstanceCount, "avg" : processDefinitionCounts[0].duration, "min" : processDefinitionCounts[0].minDuration, "max" : processDefinitionCounts[0].maxDuration }); $scope.statesOfDefinition = counts; }); } ]); });
nagyistoce/camunda-cockpit-plugin-statistics
src/main/resources/plugin-webapp/statistics-plugin/app/controllers/processDefinitionCtrl.js
JavaScript
apache-2.0
3,679
/* Copyright 2015 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. */ #include <math.h> #include "Mutex.h" #include "PathState.h" #include "Utils.h" /* calculate the cubic root of x using a table lookup followed by one * Newton-Raphson iteration. * Avg err ~= 0.195% * * Taken (and slightly modified) from Linux TCP Cubic implementation */ static uint32_t cubeRoot(uint64_t a) { uint32_t x, b, shift; uint64_t c; /* * cbrt(x) MSB values for x MSB values in [0..63]. * Precomputed then refined by hand - Willy Tarreau * * For x in [0..63], * v = cbrt(x << 18) - 1 * cbrt(x) = (v[x] + 10) >> 6 */ static const uint8_t v[] = { /* 0x00 */ 0, 54, 54, 54, 118, 118, 118, 118, /* 0x08 */ 123, 129, 134, 138, 143, 147, 151, 156, /* 0x10 */ 157, 161, 164, 168, 170, 173, 176, 179, /* 0x18 */ 181, 185, 187, 190, 192, 194, 197, 199, /* 0x20 */ 200, 202, 204, 206, 209, 211, 213, 215, /* 0x28 */ 217, 219, 221, 222, 224, 225, 227, 229, /* 0x30 */ 231, 232, 234, 236, 237, 239, 240, 242, /* 0x38 */ 244, 245, 246, 248, 250, 251, 252, 254, }; /* Probably not the fastest way but works without using asm */ b = 0; c = a; while (c >>= 1) b++; b++; if (b < 7) { /* a in [0..63] */ return ((uint32_t)v[(uint32_t)a] + 35) >> 6; } b = ((b * 84) >> 8) - 1; shift = (a >> (b * 3)); x = ((uint32_t)(((uint32_t)v[shift] + 10) << b)) >> 6; /* * Newton-Raphson iteration * 2 * x = ( 2 * x + a / x ) / 3 * k+1 k k */ x = 2 * x + (uint32_t)(a / ((uint64_t)x * (uint64_t)(x - 1))); x = ((x * 341) >> 10); return x; } PathState::PathState(int rtt, int mtu) : mPathIndex(-1), mMTU(mtu), mSRTT(rtt), mLastRTT(rtt), mSendWindow(2), mCongestionWindow(1), mWindow(1), mInFlight(0), mCurrentBurst(0), mInLoss(false), mTotalSent(0), mTotalAcked(0), mLastTotalAcked(0), mTotalLost(0), mAverageLossInterval(0) { mVAR = rtt >> VAR_SHIFT; mRTO = mSRTT + (mVAR << 2); mSRTT = 0; // initial RTT estimate used for RTO only memset(mLossBursts, 0, sizeof(mLossBursts)); Mutex mMutex; } PathState::~PathState() { } void PathState::setIndex(int index) { mPathIndex = index; } void PathState::setRemoteWindow(uint32_t sendWindow) { mSendWindow = sendWindow; DEBUG("send window set to %d\n", mSendWindow); } int PathState::timeUntilReady() { return 0; } int PathState::bandwidth() { if (mSRTT == 0) return 0; return mWindow * mMTU / mSRTT * 1000000; } int PathState::estimatedRTT() EXCLUDES(mMutex) { int ret; mMutex.Lock(); ret = mSRTT; mMutex.Unlock(); return ret; } int PathState::getRTO() EXCLUDES(mMutex) { int ret; mMutex.Lock(); ret = mRTO; mMutex.Unlock(); return ret; } int PathState::packetsInFlight() EXCLUDES(mMutex) { int ret; mMutex.Lock(); ret = mInFlight; mMutex.Unlock(); return ret; } double PathState::getLossRate() EXCLUDES(mMutex) { mMutex.Lock(); uint64_t currentInterval = mTotalAcked - mLastTotalAcked; if (currentInterval > mAverageLossInterval) { if (currentInterval > 2 * mAverageLossInterval) calculateLoss(ALI_HISTORY_DISCOUNTING); else calculateLoss(ALI_FROM_INTERVAL_0); } mMutex.Unlock(); if (mAverageLossInterval == 0) return 0.0; return 1.0 / mAverageLossInterval; } void PathState::addLoss(uint64_t packetNum) EXCLUDES(mMutex) { mTotalLost++; mMutex.Lock(); mInFlight--; mMutex.Unlock(); mCurrentBurst++; mInLoss = true; if (mCurrentBurst == SSP_MAX_LOSS_BURST) { mLossBursts[SSP_MAX_LOSS_BURST - 1]++; mCurrentBurst = 0; mInLoss = false; } } void PathState::addRTTSample(int rtt, uint64_t packetNum) EXCLUDES(mMutex) { mTotalAcked++; mMutex.Lock(); mInFlight--; DEBUG("path %d: receive ack: %d packets now in flight\n", mPathIndex, mInFlight); if (rtt > 0) { mLastRTT = rtt; if (mSRTT == 0) { mSRTT = rtt; mVAR = rtt >> 1; } else { int err = rtt - mSRTT; mSRTT += err >> ERR_SHIFT; err = err >= 0 ? err : -err; mVAR += (err - mVAR) >> VAR_SHIFT; } mRTO = mSRTT + (mVAR << 2); if (mRTO > SSP_MAX_RTO) mRTO = SSP_MAX_RTO; DEBUG("path %d: RTT sample %d us, sRTT = %d us, RTO = %d us\n", mPathIndex, rtt, mSRTT, mRTO); } if (mInLoss) { mLossBursts[mCurrentBurst]++; mCurrentBurst = 0; mInLoss = false; } mMutex.Unlock(); } void PathState::addRetransmit() EXCLUDES(mMutex) { mMutex.Lock(); mLossIntervals.push_front(mTotalAcked - mLastTotalAcked); if (mLossIntervals.size() > MAX_LOSS_INTERVALS) mLossIntervals.pop_back(); DEBUG("loss on path %d: new loss interval = %ld, %d/%d in flight\n", mPathIndex, mTotalAcked - mLastTotalAcked, mInFlight, mWindow); mLastTotalAcked = mTotalAcked; calculateLoss(ALI_FROM_INTERVAL_1); mMutex.Unlock(); } void PathState::handleSend(uint64_t packetNum) EXCLUDES(mMutex) { mMutex.Lock(); mInFlight++; mTotalSent++; DEBUG("path %d: send: %d/%d packets now in flight\n", mPathIndex, mInFlight, mWindow); mMutex.Unlock(); } void PathState::handleTimeout() EXCLUDES(mMutex) { mMutex.Lock(); mRTO = mRTO << 1; if (mRTO > SSP_MAX_RTO) mRTO = SSP_MAX_RTO; DEBUG("timeout: new rto = %d\n", mRTO); mMutex.Unlock(); } void PathState::handleDupAck() { } void PathState::calculateLoss(ALIType type) { if (mLossIntervals.empty()) return; uint64_t currentInterval = mTotalAcked - mLastTotalAcked; size_t i; list<uint64_t>::iterator it; size_t n = mLossIntervals.size(); double ws = 0.0; double w = 0.0; double d[MAX_LOSS_INTERVALS + 1]; double di = 2.0 * mAverageLossInterval / currentInterval; double wi; DEBUG("calculate average loss interval (%d), currentInterval = %ld\n", type, currentInterval); if (di < 0.5) di = 0.5; for (i = 0; i <= MAX_LOSS_INTERVALS; i++) d[i] = 1.0; switch (type) { case ALI_HISTORY_DISCOUNTING: for (i = 1; i < MAX_LOSS_INTERVALS; i++) d[i] = di; case ALI_FROM_INTERVAL_0: mLossIntervals.push_front(currentInterval); case ALI_FROM_INTERVAL_1: for (it = mLossIntervals.begin(), i = 1; it != mLossIntervals.end() && i < MAX_LOSS_INTERVALS; it++, i++) { if (i <= n / 2) { ws += d[i - 1] * (*it); w += d[i - 1]; } else { wi = 1 - (i - n / 2.0) / (n / 2.0 + 1); ws += d[i - 1] * wi * (*it); w += d[i - 1] * wi; } } break; default: break; } if (type != ALI_FROM_INTERVAL_1) mLossIntervals.pop_front(); mAverageLossInterval = ws / w; DEBUG("average loss interval = %ld\n", mAverageLossInterval); } bool PathState::isWindowBased() { return false; } int PathState::window() { return 0; } int PathState::profileLoss() { double p, q; int m = 0; for (int i = 1; i < SSP_MAX_LOSS_BURST; i++) m += mLossBursts[i]; p = (double)m / mTotalAcked; int mi1 = 0, mi2 = 0; for (int i = 2; i < SSP_MAX_LOSS_BURST; i++) mi2 += mLossBursts[i] * (i - 1); for (int i = 1; i < SSP_MAX_LOSS_BURST; i++) mi1 += mLossBursts[i] * i; q = 1 - (double)mi2 / mi1; printf("p = %f, q = %f\n", p, q); return 0; } // CBR CBRPathState::CBRPathState(int rtt, int mtu) : PathState(rtt, mtu), mSendInterval(SSP_SEND_INTERVAL) { memset(&mLastSendTime, 0, sizeof(mLastSendTime)); } int CBRPathState::timeUntilReady() { if (mLastSendTime.tv_sec == 0) return 0; struct timeval current; gettimeofday(&current, NULL); DEBUG("%ld us since last send\n", elapsedTime(&mLastSendTime, &current)); int time = mSendInterval - elapsedTime(&mLastSendTime, &current); if (time < 0) time = 0; return time; } int CBRPathState::bandwidth() { return mMTU / mSendInterval * 1000000; } void CBRPathState::handleSend(uint64_t packetNum) { PathState::handleSend(packetNum); gettimeofday(&mLastSendTime, NULL); } // PCC PCCPathState::PCCPathState(int rtt, int mtu) : CBRPathState(rtt, mtu), mLastSendInterval(SSP_SEND_INTERVAL), mMonitorRTT(0.0), mMonitorReceived(0), mMonitorLost(0), mMonitoring(false), mUtility(0.0), mCurrentTrial(0), mAdjustCount(0), mDirection(0), mState(PCC_START) { memset(&mMonitorStartTime, 0, sizeof(mMonitorStartTime)); memset(&mMonitorEndTime, 0, sizeof(mMonitorEndTime)); memset(mTrialResults, 0, sizeof(mTrialResults)); memset(mTrialIntervals, 0, sizeof(mTrialIntervals)); Mutex mMonitorMutex; } int PCCPathState::timeUntilReady() { int currentInterval = mSendInterval; if (mState == PCC_DECISION) mSendInterval = mTrialIntervals[mCurrentTrial]; int res = CBRPathState::timeUntilReady(); mSendInterval = currentInterval; return res; } void PCCPathState::handleSend(uint64_t packetNum) EXCLUDES(mMonitorMutex) { struct timeval t; gettimeofday(&t, NULL); CBRPathState::handleSend(packetNum); if (!mMonitoring) { DEBUG("%ld.%06ld: current state = %d, begin monitoring\n", t.tv_sec, t.tv_usec, mState); mMonitorStartTime = t; srand(t.tv_usec); double x = (double)rand() / RAND_MAX; // 0 ~ 1.0 x /= 2.0; // 0 ~ 0.5 x += 1.7; // 1.7 ~ 2.2 mMonitorDuration = x * mSRTT; if (mMonitorDuration < PCC_MIN_PACKETS * mSendInterval) mMonitorDuration = PCC_MIN_PACKETS * mSendInterval; mMonitorRTT = 0; mMonitorReceived = 0; mMonitorLost = 0; mMonitoring = true; } if (mMonitoring) { if (elapsedTime(&mMonitorStartTime, &t) < mMonitorDuration ) { mMonitorMutex.Lock(); mMonitoredPackets.insert(packetNum); mMonitorMutex.Unlock(); } } } void PCCPathState::addRTTSample(int rtt, uint64_t packetNum) EXCLUDES(mMonitorMutex) { PathState::addRTTSample(rtt, packetNum); if (mMonitoring) { bool found = false; mMonitorMutex.Lock(); found = mMonitoredPackets.find(packetNum) != mMonitoredPackets.end(); mMonitorMutex.Unlock(); if (found) { mMonitorReceived++; mMonitorRTT += rtt; DEBUG("current state = %d: got ack %ld\n", mState, packetNum); } } struct timeval t; gettimeofday(&t, NULL); if (elapsedTime(&mMonitorStartTime, &t) >= mMonitorDuration + mSRTT) handleMonitorEnd(); } void PCCPathState::addLoss(uint64_t packetNum) { PathState::addLoss(packetNum); struct timeval t; gettimeofday(&t, NULL); if (elapsedTime(&mMonitorStartTime, &t) >= mMonitorDuration + mSRTT) handleMonitorEnd(); } void PCCPathState::handleMonitorEnd() EXCLUDES(mMonitorMutex) { if (!mMonitoring) return; mMonitorMutex.Lock(); gettimeofday(&mMonitorEndTime, NULL); DEBUG("%ld.%06ld: monitor end\n", mMonitorEndTime.tv_sec, mMonitorEndTime.tv_usec); long monitorTime = elapsedTime(&mMonitorStartTime, &mMonitorEndTime); if (mMonitorReceived == 0) { mMonitorRTT = SSP_MAX_RTO; } else { mMonitorRTT /= mMonitorReceived; } DEBUG("%lu packets sent during this interval, %lu received\n", mMonitoredPackets.size(), mMonitorReceived); mMonitorLost = mMonitoredPackets.size() - mMonitorReceived; double u = utility(mMonitorReceived, mMonitorLost, monitorTime / 1000000.0, mMonitorRTT); DEBUG("utility %f\n", u); if (mState == PCC_DECISION) { DEBUG("decision phase, trial %d\n", mCurrentTrial); mTrialResults[mCurrentTrial++] = u; if (mCurrentTrial == PCC_TRIALS) { int direction = 0; for (int i = 0; i < PCC_TRIALS - 1; i += 2) { if (mTrialIntervals[i] < mSendInterval) { // i: shorter period, i + 1: longer period if (mTrialResults[i] > mTrialResults[i + 1]) direction--; else if (mTrialResults[i] < mTrialResults[i + 1]) direction++; } else { // i: longer period, i + 1: shorter period if (mTrialResults[i] > mTrialResults[i + 1]) direction++; else if (mTrialResults[i] < mTrialResults[i + 1]) direction--; } } if (direction == 0) { DEBUG("inconclusive, do over with larger deltas\n"); mAdjustCount++; if (mAdjustCount > PCC_MAX_ADJUST_COUNT) mAdjustCount = PCC_MAX_ADJUST_COUNT; startDecision(); } else { mDirection = direction / 2; // direction = +-2, mDirection = +-1 mState = PCC_ADJUST; mLastSendInterval = mSendInterval; mSendInterval += mSendInterval * mDirection * mAdjustCount * PCC_ADJUST_RATE; DEBUG("switched to adjust phase, direction = %d with %d us period\n", mDirection, mSendInterval); } } } else if (mState == PCC_ADJUST) { if (u >= mUtility) { mAdjustCount++; if (mAdjustCount > PCC_MAX_ADJUST_COUNT) mAdjustCount = PCC_MAX_ADJUST_COUNT; mLastSendInterval = mSendInterval; mSendInterval += mSendInterval * mDirection * mAdjustCount * PCC_ADJUST_RATE; DEBUG("utility increased, keep going in direction %d with %d us period\n", mDirection, mSendInterval); } else { mSendInterval = mLastSendInterval; mAdjustCount = 1; DEBUG("utility decreased, drop back to decision phase with %d us period\n", mSendInterval); startDecision(); } mUtility = u; } else if (mState == PCC_START) { if (u >= mUtility) { mLastSendInterval = mSendInterval; mSendInterval /= 2; DEBUG("utility increased, double speed: %d us period\n", mSendInterval); } else { mSendInterval = mLastSendInterval; mAdjustCount = 1; DEBUG("utility decreased, drop down to decision phase with %d us period\n", mSendInterval); startDecision(); } mUtility = u; } if (mSendInterval > SSP_MAX_SEND_INTERVAL) mSendInterval = SSP_MAX_SEND_INTERVAL; mMonitoredPackets.clear(); mMonitoring = false; if (mMonitorReceived == 0) mSendInterval *= 2; mMonitorMutex.Unlock(); } void PCCPathState::startDecision() { srand(time(NULL)); for (int i = 0; i < PCC_TRIALS - 1; i += 2) { int delta = (rand() % 2) * 2 - 1; delta *= mAdjustCount * PCC_ADJUST_RATE * mSendInterval; mTrialIntervals[i] = mSendInterval + delta; mTrialIntervals[i + 1] = mSendInterval - delta; } mCurrentTrial = 0; mState = PCC_DECISION; } double PCCPathState::utility(int received, int lost, double time, double rtt) { DEBUG("%d %d %f %f\n", received, lost, time, rtt); //utility = ((t-l)/time*(1-1/(1+exp(-100*(l/t-0.05))))-1*l/time); //utility = ((t-l)/time*(1-1/(1+exp(-100*(l/t-0.05))))* (1-1/(1+exp(-10*(1-previous_rtt/rtt)))) -1*l/time)/rtt*1000; return received / time * (1 - 1 / (1 + exp(-100 * (lost / (received + lost) - 0.05)))) - lost / time; } // TCP Reno RenoPathState::RenoPathState(int rtt, int mtu) : PathState(rtt, mtu), mState(TCP_STATE_START), mThreshold(-1), mDupAckCount(0), mAckCount(0) { } int RenoPathState::timeUntilReady() { if (mInFlight < mWindow) { DEBUG("path %d: room in window (%d/%d), send right away\n", mPathIndex, mInFlight, mWindow); return 0; } else { DEBUG("path %d: window full, wait about 1 RTT (%d us)\n", mPathIndex, mSRTT); return mSRTT ? mSRTT : mRTO; } } void RenoPathState::handleTimeout() { PathState::handleTimeout(); mState = TCP_STATE_TIMEOUT; mCongestionWindow = 1; DEBUG("path %d: timeout: congestion window set to 1\n", mPathIndex); } void RenoPathState::handleDupAck() { mDupAckCount++; if (mState > SSP_FR_THRESHOLD && mState == TCP_STATE_FAST_RETRANSMIT) { mCongestionWindow++; mWindow = mCongestionWindow > mSendWindow ? mSendWindow : mCongestionWindow; DEBUG("path %d: duplicate ack received: window set to %d (%d/%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow); } } void RenoPathState::addRTTSample(int rtt, uint64_t packetNum) { PathState::addRTTSample(rtt, packetNum); mDupAckCount = 0; mAckCount++; switch (mState) { case TCP_STATE_START: case TCP_STATE_TIMEOUT: DEBUG("path %d: slow start: %d -> %d\n", mPathIndex, mCongestionWindow, mCongestionWindow + 1); mCongestionWindow++; if (mCongestionWindow == mThreshold) { DEBUG("path %d: reached threshold: %d\n", mPathIndex, mThreshold); mState = TCP_STATE_NORMAL; } break; case TCP_STATE_FAST_RETRANSMIT: mState = TCP_STATE_NORMAL; mCongestionWindow = mThreshold; break; case TCP_STATE_NORMAL: if (mAckCount == mCongestionWindow) { DEBUG("path %d: congestion avoidance: %d -> %d\n", mPathIndex, mCongestionWindow, mCongestionWindow + 1); mAckCount = 0; mCongestionWindow++; } break; default: break; } mWindow = mCongestionWindow > mSendWindow ? mSendWindow : mCongestionWindow; DEBUG("path %d: ack received: window set to %d (%d/%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow); } void RenoPathState::addRetransmit() { PathState::addRetransmit(); mThreshold = mWindow >> 1; if (mThreshold < 2) mThreshold = 2; mAckCount = 0; if (mState != TCP_STATE_TIMEOUT && mState != TCP_STATE_FAST_RETRANSMIT) { mState = TCP_STATE_FAST_RETRANSMIT; mCongestionWindow = mThreshold + 3; } mWindow = mCongestionWindow > mSendWindow ? mSendWindow : mCongestionWindow; DEBUG("path %d: packet loss: window set to %d (%d/%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow); } bool RenoPathState::isWindowBased() { return true; } int RenoPathState::window() { return mWindow; } // TCP CUBIC CUBICPathState::CUBICPathState(int rtt, int mtu) : PathState(rtt, mtu), mThreshold(-1), mTimeout(false) { reset(); } int CUBICPathState::timeUntilReady() EXCLUDES(mMutex) { mMutex.Lock(); if (mInFlight < mWindow) { DEBUG("path %d: room in window (%d/%d), send right away\n", mPathIndex, mInFlight, mWindow); mMutex.Unlock(); return 0; } else { DEBUG("path %d: window full (%d/%d), wait about 1 RTT (%d us)\n", mPathIndex, mInFlight, mWindow, mSRTT); mMutex.Unlock(); return mSRTT ? mSRTT : mRTO; } } void CUBICPathState::addRTTSample(int rtt, uint64_t packetNum) { PathState::addRTTSample(rtt, packetNum); if (rtt == 0) return; mTimeout = false; if (mMinDelay == 0 || mMinDelay > rtt) mMinDelay = rtt; mAckCount++; int thresh = mThreshold > 0 ? mThreshold : CUBIC_SSTHRESH; if (mCongestionWindow < thresh) { mCongestionWindow++; DEBUG("path %d: slow start, increase to %d\n", mPathIndex, mCongestionWindow); } else { update(); DEBUG("path %d: congestion avoidance (%d/%d)\n", mPathIndex, mWindowCount, mCount); if (mWindowCount > mCount) { mCongestionWindow++; DEBUG("path %d: increase window to %d\n", mPathIndex, mCongestionWindow); mWindowCount = 0; } else { mWindowCount++; } } mWindow = mCongestionWindow < mSendWindow ? mCongestionWindow : mSendWindow; DEBUG("path %d: ack received: window set to %d (%d|%d)\n", mPathIndex, mWindow, mCongestionWindow, mSendWindow); } void CUBICPathState::addRetransmit() EXCLUDES(mMutex) { PathState::addRetransmit(); mEpochStart = 0; if (mCongestionWindow < mMaxWindow) mMaxWindow = mCongestionWindow * (2 - BETA) / 2; else mMaxWindow = mCongestionWindow; mCongestionWindow *= (1 - BETA); if (mCongestionWindow < 1) mCongestionWindow = 1; mThreshold = mCongestionWindow; if (mTimeout) mCongestionWindow = 1; mMutex.Lock(); mWindow = mCongestionWindow < mSendWindow ? mCongestionWindow : mSendWindow; mMutex.Unlock(); DEBUG("path %d: packet loss: window set to %d (last max window %d)\n", mPathIndex, mWindow, mMaxWindow); } void CUBICPathState::handleSend(uint64_t packetNum) { PathState::handleSend(packetNum); } void CUBICPathState::handleTimeout() { PathState::handleTimeout(); mTimeout = true; mThreshold = (1 - BETA) * mCongestionWindow; reset(); DEBUG("path %d: timeout: congestion window dropped to 1\n", mPathIndex); } void CUBICPathState::reset() { mWindowCount = 0; mAckCount = 0; mMinDelay = 0; mMaxWindow = 0; mTCPWindow = 0; mOrigin = 0; mCount = 0; mK = 0; mEpochStart = 0; } void CUBICPathState::doTCPFriendly() { mTCPWindow += 3 * BETA / (2 - BETA) * mAckCount / mCongestionWindow; mAckCount = 0; if (mTCPWindow > mCongestionWindow) { if (mCount > mCongestionWindow / (mTCPWindow - mCongestionWindow)) mCount = mCongestionWindow / (mTCPWindow - mCongestionWindow); } } void CUBICPathState::update() { time_t timestamp = time(NULL); if (mEpochStart == 0) { mEpochStart = timestamp; if (mCongestionWindow < mMaxWindow) { mK = cubeRoot((mMaxWindow - mCongestionWindow) / C); mOrigin = mMaxWindow; } else { mK = 0; mOrigin = mCongestionWindow; } mAckCount = 1; mTCPWindow = mCongestionWindow; } int t = timestamp + mMinDelay / 1000000 - mEpochStart; int x = t - mK; int target = mOrigin + C * x * x * x; if (target > mCongestionWindow) mCount = mCongestionWindow / (target - mCongestionWindow); else mCount = 100 * mCongestionWindow; doTCPFriendly(); } bool CUBICPathState::isWindowBased() { return true; } int CUBICPathState::window() { return mWindow; }
dmpiergiacomo/scion
c/ssp/PathState.cpp
C++
apache-2.0
23,627
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { UserData } from './user-data'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/observable/of'; @Injectable() export class ConferenceData { data: any; constructor(public http: Http, public user: UserData) { } load(): any { if (this.data) { return Observable.of(this.data); } else { return this.http.get('assets/data/data.json') .map(this.processData, this); } } processData(data: any) { // just some good 'ol JS fun with objects and arrays // build up the data by linking employees to sessions this.data = data.json(); this.data.tracks = []; // loop through each day in the schedule this.data.schedule.forEach((day: any) => { // loop through each timeline group in the day day.groups.forEach((group: any) => { // loop through each session in the timeline group group.sessions.forEach((session: any) => { session.employees = []; if (session.employeeNames) { session.employeeNames.forEach((employeeName: any) => { let employee = this.data.employees.find((s: any) => s.name === employeeName); if (employee) { session.employees.push(employee); employee.sessions = employee.sessions || []; employee.sessions.push(session); } }); } if (session.tracks) { session.tracks.forEach((track: any) => { if (this.data.tracks.indexOf(track) < 0) { this.data.tracks.push(track); } }); } }); }); }); return this.data; } getTimeline(dayIndex: number, queryText = '', excludeTracks: any[] = [], segment = 'all') { return this.load().map((data: any) => { let day = data.schedule[dayIndex]; day.shownSessions = 0; queryText = queryText.toLowerCase().replace(/,|\.|-/g, ' '); let queryWords = queryText.split(' ').filter(w => !!w.trim().length); day.groups.forEach((group: any) => { group.hide = true; group.sessions.forEach((session: any) => { // check if this session should show or not this.filterSession(session, queryWords, excludeTracks, segment); if (!session.hide) { // if this session is not hidden then this group should show group.hide = false; day.shownSessions++; } }); }); return day; }); } filterSession(session: any, queryWords: string[], excludeTracks: any[], segment: string) { let matchesQueryText = false; if (queryWords.length) { // of any query word is in the session name than it passes the query test queryWords.forEach((queryWord: string) => { if (session.name.toLowerCase().indexOf(queryWord) > -1) { matchesQueryText = true; } }); } else { // if there are no query words then this session passes the query test matchesQueryText = true; } // if any of the sessions tracks are not in the // exclude tracks then this session passes the track test let matchesTracks = false; session.tracks.forEach((trackName: string) => { if (excludeTracks.indexOf(trackName) === -1) { matchesTracks = true; } }); // if the segement is 'favorites', but session is not a user favorite // then this session does not pass the segment test let matchesSegment = false; if (segment === 'favorites') { if (this.user.hasFavorite(session.name)) { matchesSegment = true; } } else { matchesSegment = true; } // all tests must be true if it should not be hidden session.hide = !(matchesQueryText && matchesTracks && matchesSegment); } getEmployees() { return this.load().map((data: any) => { return data.employees.sort((a: any, b: any) => { let aName = a.name.split(' ').pop(); let bName = b.name.split(' ').pop(); return aName.localeCompare(bName); }); }); } getTracks() { return this.load().map((data: any) => { return data.tracks.sort(); }); } getMap() { return this.load().map((data: any) => { return data.map; }); } }
josephjohn136/logonfly
Ionic/src/providers/conference-data.ts
TypeScript
apache-2.0
4,422
/** * Red Hat Open Innovation Labs API * A generic model to support automation at all levels of the application and infrastructure lifecycle. * * OpenAPI spec version: 0.3.0-alpha * Contact: rhc-open-innovation-labs@redhat.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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. */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['ApiClient', 'model/Port'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient'), require('./Port')); } else { // Browser globals (root is window) if (!root.RedHatOpenInnovationLabsApi) { root.RedHatOpenInnovationLabsApi = {}; } root.RedHatOpenInnovationLabsApi.Service = factory(root.RedHatOpenInnovationLabsApi.ApiClient, root.RedHatOpenInnovationLabsApi.Port); } }(this, function(ApiClient, Port) { 'use strict'; /** * The Service model module. * @module model/Service * @version 0.3.0-alpha */ /** * Constructs a new <code>Service</code>. * @alias module:model/Service * @class */ var exports = function() { var _this = this; }; /** * Constructs a <code>Service</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/Service} obj Optional instance to populate. * @return {module:model/Service} The populated <code>Service</code> instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('ports')) { obj['ports'] = ApiClient.convertToType(data['ports'], [Port]); } } return obj; } /** * @member {Number} id */ exports.prototype['id'] = undefined; /** * @member {String} name */ exports.prototype['name'] = undefined; /** * @member {Array.<module:model/Port>} ports */ exports.prototype['ports'] = undefined; return exports; }));
priley86/labs-console
app/automation/model/Service.js
JavaScript
apache-2.0
3,193
using System; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using RElmah.Common.Model; using RElmah.Errors; using RElmah.Services.Nulls; namespace RElmah.Services.Inbox { public class SerializedErrorsInbox : IErrorsInbox { private readonly IErrorsBacklog _errorsBacklog; private readonly Subject<ErrorPayload> _errors; private readonly IObservable<ErrorPayload> _publishedErrors; public SerializedErrorsInbox() : this(NullErrorsBacklog.Instance) { } public SerializedErrorsInbox(IErrorsBacklog errorsBacklog) { _errorsBacklog = errorsBacklog; _errors = new Subject<ErrorPayload>(); _publishedErrors = _errors.Publish().RefCount(); } public Task Post(ErrorPayload payload) { return _errorsBacklog .Store(payload) .ContinueWith(_ => _errors.OnNext(payload)); } public IObservable<ErrorPayload> GetErrorsStream() { return _publishedErrors; } } }
wasphub/RElmah
relmah/src/RElmah/Services/Inbox/SerializedErrorsInbox.cs
C#
apache-2.0
1,105
/* Copyright 2020 Google LLC 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 https://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 "absl/container/flat_hash_map.h" #include "struct2tensor/kernels/parquet/parquet_reader.h" #include "struct2tensor/kernels/parquet/parquet_reader_util.h" #include "struct2tensor/kernels/vector_to_tensor.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/types.h" namespace struct2tensor { namespace parquet_dataset { class Dataset : public tensorflow::data::DatasetBase { public: explicit Dataset(tensorflow::OpKernelContext* ctx, const std::vector<std::string>& filenames, const std::vector<std::string>& value_paths, const tensorflow::DataTypeVector& value_dtypes, const std::vector<std::vector<int>>& segregated_path_indices, const tensorflow::int64 batch_size, const tensorflow::DataTypeVector& output_dtypes) : DatasetBase(tensorflow::data::DatasetContext(ctx)), filenames_(filenames), value_paths_(value_paths), value_dtypes_(value_dtypes), segregated_path_indices_(segregated_path_indices), batch_size_(batch_size), output_dtypes_(output_dtypes), output_shapes_([this]() { // The first output tensor is always the root size (number of messages // read) which is a scalar. Other output tensors are parent indices // so they are 1-D. std::vector<tensorflow::PartialTensorShape> shapes( output_dtypes_.size(), tensorflow::PartialTensorShape({-1})); shapes[0] = tensorflow::PartialTensorShape({}); return shapes; }()) {} std::unique_ptr<tensorflow::data::IteratorBase> MakeIteratorInternal( const std::string& prefix) const override { return absl::WrapUnique(new Iterator( {this, tensorflow::strings::StrCat(prefix, "::Parquet")}, filenames_, value_paths_, value_dtypes_, segregated_path_indices_, batch_size_)); } const tensorflow::DataTypeVector& output_dtypes() const override { return output_dtypes_; } const std::vector<tensorflow::PartialTensorShape>& output_shapes() const override { return output_shapes_; } std::string DebugString() const override { return "ParquetDatasetOp::Dataset"; } tensorflow::Status CheckExternalState() const { return tensorflow::Status::OK(); } protected: // TODO(andylou): Implement saving dataset state. tensorflow::Status AsGraphDefInternal( tensorflow::data::SerializationContext* ctx, DatasetGraphDefBuilder* b, tensorflow::Node** output) const override { return tensorflow::errors::Unimplemented( DebugString(), " does not support serialization."); } private: class Iterator : public tensorflow::data::DatasetIterator<Dataset> { public: explicit Iterator( const Params& params, const std::vector<std::string>& filenames, const std::vector<std::string>& value_paths, const tensorflow::DataTypeVector& value_dtypes, const std::vector<std::vector<int>>& segregated_path_indices, const tensorflow::int64 batch_size) : DatasetIterator<Dataset>(params), filenames_(filenames), value_paths_(value_paths), value_dtypes_(value_dtypes), segregated_path_indices_(segregated_path_indices), batch_size_(batch_size), current_file_index_(0) {} // For a deeper understanding of what tensors are returned in out_tensors, // see parquet_dataset_op.cc. tensorflow::Status GetNextInternal( tensorflow::data::IteratorContext* ctx, std::vector<tensorflow::Tensor>* out_tensors, bool* end_of_sequence) override { tensorflow::mutex_lock l(mu_); if (current_file_index_ >= filenames_.size()) { *end_of_sequence = true; return tensorflow::Status::OK(); } if (!parquet_reader_) { // Once a file is finished reading, this will create a ParquetReader // for the next file in file_names_. TF_RETURN_IF_ERROR( ValidateFileAndSchema(filenames_[current_file_index_])); TF_RETURN_IF_ERROR(ParquetReader::Create( filenames_[current_file_index_], value_paths_, value_dtypes_, batch_size_, &parquet_reader_)); } bool end_of_file = false; std::vector<ParquetReader::ParentIndicesAndValues> parent_indices_and_values; TF_RETURN_IF_ERROR(parquet_reader_->ReadMessages( ctx, &parent_indices_and_values, &end_of_file)); if (end_of_file) { ++current_file_index_; parquet_reader_.reset(); } // pushes the number of messages read as the first output tensor. tensorflow::Tensor root_tensor(ctx->allocator({}), tensorflow::DT_INT64, {}); if (parent_indices_and_values.size() != value_paths_.size()) { return tensorflow::errors::Internal(absl::StrCat( parent_indices_and_values.size(), " messages read, expected to read ", value_paths_.size())); } if (parent_indices_and_values[0].parent_indices.empty()) { return tensorflow::errors::Internal( absl::StrCat("0 messages read, expected to read ", batch_size_)); } root_tensor.flat<tensorflow::int64>()(0) = parent_indices_and_values[0].parent_indices[0].size(); out_tensors->push_back(std::move(root_tensor)); for (int column_index = 0; column_index < value_paths_.size(); ++column_index) { for (int path_index : segregated_path_indices_[column_index]) { tensorflow::Tensor res( ctx->allocator({}), tensorflow::DT_INT64, {static_cast<long long>(parent_indices_and_values[column_index] .parent_indices[path_index] .size())}); struct2tensor::VectorToTensor(parent_indices_and_values[column_index] .parent_indices[path_index], &res, /*produce_string_view=*/false); out_tensors->push_back(std::move(res)); } out_tensors->push_back( std::move(parent_indices_and_values[column_index].values)); } return tensorflow::Status::OK(); } protected: // TODO(b/139440495): Implement saving and restoring iterator state. tensorflow::Status SaveInternal( tensorflow::data::SerializationContext* ctx, tensorflow::data::IteratorStateWriter* writer) { return tensorflow::errors::Unimplemented( "Parquet Dataset Iterator does not support checkpointing."); } tensorflow::Status RestoreInternal( tensorflow::data::IteratorContext* ctx, tensorflow::data::IteratorStateReader* reader) { return tensorflow::errors::Unimplemented( "Parquet Dataset Iterator does not support checkpointing."); } private: // validates that the file exists and can be opened as a parquet file. // validates that the schema is the expected schema. tensorflow::Status ValidateFileAndSchema(const std::string& filename) { std::unique_ptr<parquet::ParquetFileReader> file_reader; tensorflow::Status s = OpenFileWithStatus(filename, &file_reader); absl::flat_hash_map<std::string, tensorflow::DataType> paths; std::shared_ptr<parquet::FileMetaData> file_metadata = file_reader->metadata(); for (int i = 0; i < file_metadata->num_columns(); ++i) { std::string path = file_metadata->schema()->Column(i)->path()->ToDotString(); switch (file_metadata->schema()->Column(i)->physical_type()) { case parquet::Type::INT32: paths[path] = tensorflow::DT_INT32; break; case parquet::Type::INT64: paths[path] = tensorflow::DT_INT64; break; case parquet::Type::FLOAT: paths[path] = tensorflow::DT_FLOAT; break; case parquet::Type::DOUBLE: paths[path] = tensorflow::DT_DOUBLE; break; case parquet::Type::BOOLEAN: paths[path] = tensorflow::DT_BOOL; break; case parquet::Type::BYTE_ARRAY: paths[path] = tensorflow::DT_STRING; break; default: return tensorflow::errors::Unimplemented(absl::StrCat( "This Parquet Data Type is unimplemented ", file_metadata->schema()->Column(i)->physical_type())); } } for (int i = 0; i < value_dtypes_.size(); ++i) { auto paths_iter = paths.find(value_paths_[i]); if (paths_iter == paths.end()) { return tensorflow::errors::InvalidArgument( absl::StrCat("path not found ", value_paths_[i])); } else if (paths_iter->second != value_dtypes_[i]) { return tensorflow::errors::InvalidArgument( absl::StrCat("This dtype is incorrect: ", value_dtypes_[i], ". dtype should be: ", paths_iter->second)); } } return s; } const std::vector<std::string>& filenames_; const std::vector<std::string>& value_paths_; const tensorflow::DataTypeVector& value_dtypes_; const std::vector<std::vector<int>>& segregated_path_indices_; const tensorflow::int64 batch_size_; int current_file_index_ ABSL_GUARDED_BY(mu_); std::unique_ptr<ParquetReader> parquet_reader_ ABSL_GUARDED_BY(mu_); tensorflow::mutex mu_; }; const std::vector<std::string> filenames_; const std::vector<std::string> value_paths_; const tensorflow::DataTypeVector value_dtypes_; // 2D vectore to tell us which parent_indices from the path we want. i.e. // [[0,1],[0]] means we want the 0th field and 1st field of the 0th path, and // the 0th field of the 1st path. const std::vector<std::vector<int>> segregated_path_indices_; const tensorflow::int64 batch_size_; const tensorflow::DataTypeVector output_dtypes_; const std::vector<tensorflow::PartialTensorShape> output_shapes_; }; class ParquetDatasetOp : public tensorflow::data::DatasetOpKernel { public: ParquetDatasetOp(tensorflow::OpKernelConstruction* ctx) : DatasetOpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("value_paths", &value_paths_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("value_dtypes", &value_dtypes_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("parent_index_paths", &parent_index_paths_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("path_index", &path_index_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("batch_size", &batch_size_)); } void MakeDataset(tensorflow::OpKernelContext* ctx, tensorflow::data::DatasetBase** output) override { const tensorflow::Tensor* filenames_tensor; OP_REQUIRES_OK(ctx, ctx->input("filenames", &filenames_tensor)); std::vector<std::string> filenames; filenames.reserve(filenames_tensor->NumElements()); for (int i = 0; i < filenames_tensor->NumElements(); ++i) { filenames.push_back(filenames_tensor->flat<tensorflow::tstring>()(i)); } tensorflow::DataTypeVector output_dtypes = tensorflow::DataTypeVector(); int column_counter = 0; std::string prev = parent_index_paths_[0]; output_dtypes.push_back(tensorflow::DT_INT64); for (int i = 1; i < parent_index_paths_.size(); ++i) { std::string curr = parent_index_paths_[i]; output_dtypes.push_back(tensorflow::DT_INT64); if (curr != prev) { output_dtypes.push_back(value_dtypes_[column_counter]); ++column_counter; prev = curr; } } output_dtypes.push_back(tensorflow::DT_INT64); output_dtypes.push_back(value_dtypes_[column_counter]); // This validates that parent_index_paths is aligned with value_paths, // so segregated_path_indices can correctly be constructed. for (int i = 0, j = 0; i < parent_index_paths_.size(); ++i) { while (parent_index_paths_[i] != value_paths_[j]) { ++j; if (j >= value_paths_.size()) { ctx->CtxFailure(tensorflow::errors::InvalidArgument( "parent_index_paths is not aligned with value_paths")); return; } } } std::vector<std::vector<int>> segregated_path_indices(value_paths_.size()); // This is used to transform path_index to a 2d vector, splitting it up // by clustering the same paths. for example: [0, 1, 2, 0, 1, 0, 1, 2, 3] // becomes: [[0, 1, 2], [0, 1], [0, 1, 2, 3]] for (int i = 0, j = 0; i < parent_index_paths_.size(); ++i) { if (parent_index_paths_[i] == value_paths_[j]) { segregated_path_indices[j].push_back(path_index_[i] + 1); } if (i < parent_index_paths_.size() - 1 && parent_index_paths_[i + 1] != parent_index_paths_[i]) { ++j; } } *output = new Dataset(ctx, filenames, value_paths_, value_dtypes_, segregated_path_indices, batch_size_, output_dtypes); } private: std::vector<std::string> value_paths_; tensorflow::DataTypeVector value_dtypes_; // Paths of parent indices that we want. For example: // ["DocId", "Name.Language.Code", "Name.Language.Code", "Name.Language.Code"] std::vector<std::string> parent_index_paths_; std::vector<int> path_index_; int batch_size_; }; // Register the kernel implementation for ParquetDataset. REGISTER_KERNEL_BUILDER(Name("ParquetDataset").Device(tensorflow::DEVICE_CPU), ParquetDatasetOp); } // namespace parquet_dataset } // namespace struct2tensor
google/struct2tensor
struct2tensor/kernels/parquet/parquet_dataset_kernel.cc
C++
apache-2.0
14,363
$(function () { var controller = new ScrollMagic.Controller({ globalSceneOptions: { triggerHook: 'onLeave', reverse: true } }); // $('.homepage .panel').each(function () { // var element = $(this); // console.log(element); // new ScrollMagic.Scene({triggerElement: element}) // .setPin(element) // .setClassToggle(element,'active') // .addTo(controller) // }) // var actual_positions = [0]; // var mid_points = []; // var all_scenes = []; // $('.services .panel').each(function (index) { // if($(this).hasClass('main')) { // new ScrollMagic.Scene({triggerElement: '.services .main'}) // .setPin('.services .main') // .setClassToggle('.services .main','active') // .addTo(controller) // } // else { // var element_id = $(this).attr('id'); // var element_id_with_hash = '#' + $(this).attr('id'); // var scene = new ScrollMagic.Scene({triggerElement: element_id_with_hash}) // .setPin(element_id_with_hash) // .setClassToggle(element_id_with_hash,'show-bottom-nav') // .addTo(controller) // all_scenes.push({ // id: element_id, // scene: scene // }); // actual_positions.push(Math.ceil(scene.triggerPosition())); // if(actual_positions.length > 1) { // mid_points.push((actual_positions[index] + actual_positions [index-1]) / 2) // } // } // }) // $('a[href*=#]:not([href=#])').click(function () { // var id = $(this).attr('href').replace('#',''); // if($(this).parent().parent().parent().hasClass('bottom-nav')) { // var index = $('.bottom-nav ul li a').index($(this)); // }else { // var index = $('ul.wrap li a').index($(this)); // } // if(id == 'down') { // setTimeout(function () { // $('.bottom-nav').addClass('fixed') // },1100) // } // else { // var targetted_scene = all_scenes[index]; // if(targetted_scene.id == id) { // $('html,body').animate({scrollTop: targetted_scene.scene.scrollOffset()},1000); // return false; // } // } // }) // var add_and_remove_active_class = function (index) { // $('.bottom-nav').addClass('fixed') // $('.bottom-nav ul li').removeClass('active'); // $('.bottom-nav ul li:nth-child(' + index + ')').children('a').parent().last().addClass('active'); // } // $(window).scroll(function () { // if ($(".show-bottom-nav")[0]){ // $('.bottom-nav').addClass('fixed') // }else{ // $('.bottom-nav').removeClass('fixed') // } // for(var index=0; index<mid_points.length; index++) { // var next_index = index+1; // var last_index = mid_points.length-1 // /* check between mid point ranges and set active class to the respective nav item. */ // if($(window).scrollTop() > mid_points[index] && $(window).scrollTop() < mid_points[next_index]) { // add_and_remove_active_class(next_index); // break; // /* if nothing matches and reaches to last index then set active active to last nav item. */ // }else if ($(window).scrollTop() > mid_points[last_index]) { // add_and_remove_active_class(mid_points.length); // /* remove from all if its rolled back to the top*/ // }else { // $('.bottom-nav ul li').removeClass('active'); // } // } // }); }); //change navigation color on scroll /* var offset_top_news_section = $('.color-light').offset().top; var offset_top_contact_section = $('.pattern').offset().top; console.log(offset_top_contact_section, offset_top_news_section); $(window).scroll(function (event) { var scroll = $(window).scrollTop(); console.log(scroll); if(scroll < offset_top_contact_section && scroll >= offset_top_news_section) { $('.homepage nav').addClass('change-color'); } else { $('.homepage nav').removeClass('change-color'); } }); */
shamroze/squarespace-gulp-scaffolding
sqs_template/scripts/parallax.js
JavaScript
apache-2.0
4,557
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with this * work for additional information regarding copyright ownership. The ASF * licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.jmeter.protocol.http.sampler; import java.io.IOException; import java.net.Socket; import javax.net.ssl.SSLSocket; import org.apache.http.HttpHost; import org.apache.http.conn.DnsResolver; import org.apache.http.conn.OperatedClientConnection; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.conn.DefaultClientConnection; import org.apache.http.impl.conn.DefaultClientConnectionOperator; import org.apache.jmeter.util.HostNameSetter; /** * Custom implementation of {@link DefaultClientConnectionOperator} to fix SNI Issue * @see "https://bz.apache.org/bugzilla/show_bug.cgi?id=57935" * @since 3.0 * TODO Remove it when full upgrade to 4.5.X is done and cleanup is made in the Socket Factory of JMeter that handles client certificates and Slow socket */ public class JMeterClientConnectionOperator extends DefaultClientConnectionOperator { /** * @param schemes * the scheme registry */ public JMeterClientConnectionOperator(final SchemeRegistry schemes) { super(schemes); } /** * @param schemes * the scheme registry * @param dnsResolver * the custom DNS lookup mechanism */ public JMeterClientConnectionOperator(final SchemeRegistry schemes, final DnsResolver dnsResolver) { super(schemes, dnsResolver); } @Override public OperatedClientConnection createConnection() { return new JMeterDefaultClientConnection(); } private static class JMeterDefaultClientConnection extends DefaultClientConnection { public JMeterDefaultClientConnection() { super(); } /* (non-Javadoc) * @see org.apache.http.impl.conn.DefaultClientConnection#opening(java.net.Socket, org.apache.http.HttpHost) */ @Override public void opening(Socket sock, HttpHost target) throws IOException { super.opening(sock, target); if(sock instanceof SSLSocket) { HostNameSetter.setServerNameIndication(target.getHostName(), (SSLSocket) sock); } } } }
ra0077/jmeter
src/protocol/http/org/apache/jmeter/protocol/http/sampler/JMeterClientConnectionOperator.java
Java
apache-2.0
3,341
angular.module('aac.controllers.main', []) /** * Main layout controller * @param $scope */ .controller('MainCtrl', function($scope, $rootScope, $location, Data, Utils) { $scope.go = function(v) { $location.path(v); } $scope.activeView = function(view) { return view == $rootScope.currentView ? 'active' : ''; }; $scope.signOut = function() { window.document.location = "./logout"; }; Data.getProfile().then(function(data) { data.fullname = data.name + ' ' + data.surname; $rootScope.user = data; }).catch(function(err) { Utils.showError(err); }); }) .controller('HomeController', function($scope, $rootScope, $location) { }) .controller('AccountsController', function($scope, $rootScope, $location, Data, Utils) { Data.getAccounts().then(function(data) { Data.getProviders().then(function(providers) { providers.sort(function(a,b) { if (data.accounts[a] && !data.accounts[b]) return -1; if (data.accounts[b] && !data.accounts[a]) return 1; return a.localeCompare(b); }); $scope.providers = providers; var accounts = {}; for (var p in data.accounts) { var amap = {}; for (var k in data.accounts[p]) { if (k === 'it.smartcommunitylab.aac.surname') amap['surname'] = data.accounts[p][k]; else if (k === 'it.smartcommunitylab.aac.givenname') amap['givenname'] = data.accounts[p][k]; else if (k === 'it.smartcommunitylab.aac.username') amap['username'] = data.accounts[p][k]; else amap[k] = data.accounts[p][k]; } accounts[p] = amap; } $scope.accounts = accounts; }).catch(function(err) { Utils.showError(err); }); }).catch(function(err) { Utils.showError(err); }); $scope.confirmDeleteAccount = function() { $('#deleteConfirm').modal({keyboard: false}); } $scope.deleteAccount = function() { $('#deleteConfirm').modal('hide'); Data.deleteAccount().then(function() { window.location.href = './logout'; }).catch(function(err) { Utils.showError(err); }); } }) .controller('ConnectionsController', function($scope, $rootScope, $location, Data, Utils) { Data.getConnections().then(function(connections) { $scope.connections = connections; }).catch(function(err) { Utils.showError(err); }); $scope.confirmDeleteApp = function(app) { $scope.clientId = app.clientId; $('#deleteConfirm').modal({keyboard: false}); } $scope.deleteApp = function() { $('#deleteConfirm').modal('hide'); Data.removeConnection($scope.clientId).then(function(connections) { $scope.connections = connections; Utils.showSuccess(); }).catch(function(err) { Utils.showError(err); }); } }) .controller('ProfileController', function($scope, $rootScope, $location, Data, Utils) { $scope.profile = Object.assign($rootScope.user); Data.getAccounts().then(function(data) { if (!data.accounts.internal) { $scope.password_required = true; } }).catch(function(err) { Utils.showError(err); }); $scope.cancel = function() { window.history.back(); } $scope.save = function() { if (!$scope.profile.name || !$scope.profile.surname || !$scope.profile.username || $scope.profile.password && $scope.profile.password != $scope.profile.password2) { return; } Data.saveAccount($scope.profile).then(function(data) { data.fullname = data.name + ' ' + data.surname; $rootScope.user = data; $scope.profile = Object.assign($rootScope.user); $scope.password_required = false; Utils.showSuccess(); }).catch(function(err) { Utils.showError(err); }); } Utils.initUI(); }) ;
smartcommunitylab/AAC
src/main/resources/public/js/account/main.js
JavaScript
apache-2.0
3,561
#!/bin/env python import itertools import collections def read_table(filename): with open(filename) as fp: header = next(fp).split() rows = [line.split()[1:] for line in fp if line.strip()] columns = zip(*rows) data = dict(zip(header, columns)) return data table = read_table("../../data/colldata.txt") pots = sorted(table) alphabet = "+-?" for num in range(2, len(table) + 1): for group in itertools.combinations(pots, num): patterns = zip(*[table[p] for p in group]) counts = collections.Counter(patterns) for poss in itertools.product(alphabet, repeat=num): print ', '.join(group) + ':', print ''.join(poss), counts[poss]
ketancmaheshwari/hello-goog
src/python/collectionsexample.py
Python
apache-2.0
718
package com.jota.patterns.singleton; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.jota.patterns.singleton.singleton.User; public class MainActivity extends AppCompatActivity { @BindView(R.id.user1) TextView user1Text; @BindView(R.id.user2) TextView user2Text; @BindView(R.id.user3) TextView user3Text; private User user, user1, user2, user3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); user = User.getInstance(); user.setToken("token"); user.setSocialNetwork("Facebook"); user1 = User.getInstance(); user2 = User.getInstance(); user3 = User.getInstance(); } private void showUsers() { user1Text.setText(user1.getSocialNetwork() + " - " + user1.getToken()); user2Text.setText(user2.getSocialNetwork() + " - " + user2.getToken()); user3Text.setText(user3.getSocialNetwork() + " - " + user3.getToken()); } @OnClick(R.id.change_social_button) public void changeSocial() { user.setSocialNetwork("Twitter"); showUsers(); } @OnClick(R.id.change_token_button) public void changeToken() { user.setToken("Token token"); showUsers(); } }
jotaramirez90/Android-DesignPatterns
singleton/src/main/java/com/jota/patterns/singleton/MainActivity.java
Java
apache-2.0
1,406
# This file is part of the MapProxy project. # Copyright (C) 2010 Omniscale <http://omniscale.de> # # 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. from __future__ import with_statement import operator import threading from mapproxy.grid import bbox_intersects, bbox_contains from mapproxy.util.py import cached_property from mapproxy.util.geom import ( require_geom_support, load_polygon_lines, transform_geometry, bbox_polygon, ) from mapproxy.srs import SRS import logging log_config = logging.getLogger('mapproxy.config.coverage') try: import shapely.geometry import shapely.prepared except ImportError: # missing Shapely is handled by require_geom_support pass def coverage(geom, srs): if isinstance(geom, (list, tuple)): return BBOXCoverage(geom, srs) else: return GeomCoverage(geom, srs) def load_limited_to(limited_to): require_geom_support() srs = SRS(limited_to['srs']) geom = limited_to['geometry'] if not hasattr(geom, 'type'): # not a Shapely geometry if isinstance(geom, (list, tuple)): geom = bbox_polygon(geom) else: polygons = load_polygon_lines(geom.split('\n')) if len(polygons) == 1: geom = polygons[0] else: geom = shapely.geometry.MultiPolygon(polygons) return GeomCoverage(geom, srs, clip=True) class MultiCoverage(object): clip = False """Aggregates multiple coverages""" def __init__(self, coverages): self.coverages = coverages self.bbox = self.extent.bbox @cached_property def extent(self): return reduce(operator.add, [c.extent for c in self.coverages]) def intersects(self, bbox, srs): return any(c.intersects(bbox, srs) for c in self.coverages) def contains(self, bbox, srs): return any(c.contains(bbox, srs) for c in self.coverages) def transform_to(self, srs): return MultiCoverage([c.transform_to(srs) for c in self.coverages]) def __eq__(self, other): if not isinstance(other, MultiCoverage): return NotImplemented if self.bbox != other.bbox: return False if len(self.coverages) != len(other.coverages): return False for a, b in zip(self.coverages, other.coverages): if a != b: return False return True def __ne__(self, other): if not isinstance(other, MultiCoverage): return NotImplemented return not self.__eq__(other) def __repr__(self): return '<MultiCoverage %r: %r>' % (self.extent.llbbox, self.coverages) class BBOXCoverage(object): clip = False def __init__(self, bbox, srs): self.bbox = bbox self.srs = srs self.geom = None @property def extent(self): from mapproxy.layer import MapExtent return MapExtent(self.bbox, self.srs) def _bbox_in_coverage_srs(self, bbox, srs): if srs != self.srs: bbox = srs.transform_bbox_to(self.srs, bbox) return bbox def intersects(self, bbox, srs): bbox = self._bbox_in_coverage_srs(bbox, srs) return bbox_intersects(self.bbox, bbox) def intersection(self, bbox, srs): bbox = self._bbox_in_coverage_srs(bbox, srs) intersection = ( max(self.bbox[0], bbox[0]), max(self.bbox[1], bbox[1]), min(self.bbox[2], bbox[2]), min(self.bbox[3], bbox[3]), ) if intersection[0] >= intersection[2] or intersection[1] >= intersection[3]: return None return BBOXCoverage(intersection, self.srs) def contains(self, bbox, srs): bbox = self._bbox_in_coverage_srs(bbox, srs) return bbox_contains(self.bbox, bbox) def transform_to(self, srs): if srs == self.srs: return self bbox = self.srs.transform_bbox_to(srs, self.bbox) return BBOXCoverage(bbox, srs) def __eq__(self, other): if not isinstance(other, BBOXCoverage): return NotImplemented if self.srs != other.srs: return False if self.bbox != other.bbox: return False return True def __ne__(self, other): if not isinstance(other, BBOXCoverage): return NotImplemented return not self.__eq__(other) def __repr__(self): return '<BBOXCoverage %r/%r>' % (self.extent.llbbox, self.bbox) class GeomCoverage(object): def __init__(self, geom, srs, clip=False): self.geom = geom self.bbox = geom.bounds self.srs = srs self.clip = clip self._prep_lock = threading.Lock() self._prepared_geom = None self._prepared_counter = 0 self._prepared_max = 10000 @property def extent(self): from mapproxy.layer import MapExtent return MapExtent(self.bbox, self.srs) @property def prepared_geom(self): # GEOS internal data structure for prepared geometries grows over time, # recreate to limit memory consumption if not self._prepared_geom or self._prepared_counter > self._prepared_max: self._prepared_geom = shapely.prepared.prep(self.geom) self._prepared_counter = 0 self._prepared_counter += 1 return self._prepared_geom def _geom_in_coverage_srs(self, geom, srs): if isinstance(geom, shapely.geometry.base.BaseGeometry): if srs != self.srs: geom = transform_geometry(srs, self.srs, geom) elif len(geom) == 2: if srs != self.srs: geom = srs.transform_to(self.srs, geom) geom = shapely.geometry.Point(geom) else: if srs != self.srs: geom = srs.transform_bbox_to(self.srs, geom) geom = bbox_polygon(geom) return geom def transform_to(self, srs): if srs == self.srs: return self geom = transform_geometry(self.srs, srs, self.geom) return GeomCoverage(geom, srs) def intersects(self, bbox, srs): bbox = self._geom_in_coverage_srs(bbox, srs) with self._prep_lock: return self.prepared_geom.intersects(bbox) def intersection(self, bbox, srs): bbox = self._geom_in_coverage_srs(bbox, srs) return GeomCoverage(self.geom.intersection(bbox), self.srs) def contains(self, bbox, srs): bbox = self._geom_in_coverage_srs(bbox, srs) with self._prep_lock: return self.prepared_geom.contains(bbox) def __eq__(self, other): if not isinstance(other, GeomCoverage): return NotImplemented if self.srs != other.srs: return False if self.bbox != other.bbox: return False if not self.geom.equals(other.geom): return False return True def __ne__(self, other): if not isinstance(other, GeomCoverage): return NotImplemented return not self.__eq__(other) def __repr__(self): return '<GeomCoverage %r: %r>' % (self.extent.llbbox, self.geom)
Anderson0026/mapproxy
mapproxy/util/coverage.py
Python
apache-2.0
7,709
jQuery(function($) { //smooth scroll $('.navbar-nav > li.anchor').click(function(event) { //event.preventDefault(); var target = $(this).find('>a').prop('hash'); $('#navbar .active').removeClass('active'); $(this).addClass('active'); $('html, body').animate({ scrollTop: $(target).offset().top }, 500); }); //scrollspy $('[data-spy="scroll"]').each(function () { var $spy = $(this).scrollspy('refresh') }); $(function() { $(".navbar-btn").click(function() { $("#options").toggle(); $(".navbar-btn .glyphicon").toggleClass("glyphicon-plus") .toggleClass("glyphicon-minus"); }); }); });
clinm/visu-regions-autonomes-france
js/main.js
JavaScript
apache-2.0
656
<?php namespace Academe\Instructions; use Academe\Contracts\Mapper\Executable; abstract class BaseExecutable implements Executable { }
AaronJan/Academe
src/Academe/Instructions/BaseExecutable.php
PHP
apache-2.0
147
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var STATIC_REG = /.*\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)$/; var VER_REG = /[\W][\d\w]+(?=\.\w+$)/; var _default = function _default(req, res, next) { var filePaths = req.url.split('/'); if (STATIC_REG.test(req.path) && filePaths[2] === 'prd') { filePaths.splice(2, 1); req.url = filePaths.join('/').replace(VER_REG, ''); } next(); }; exports["default"] = _default;
angrytoro/fetool
lib/server/middlewares/webpackStatic.js
JavaScript
apache-2.0
497
System.register([], function (exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; function toSnakeCase(camelCase) { if (!camelCase) { throw new Error("Please provide camelCase."); } return camelCase.replace(/([A-Z])/g, "-$1").toLowerCase(); } exports_1("toSnakeCase", toSnakeCase); return { setters: [], execute: function () { } }; }); //# sourceMappingURL=to.snake.case.js.map
roelvanlisdonk/dev
apps/sportersonline/www/libraries/am/common/text/to.snake.case.js
JavaScript
apache-2.0
497
package com.gotcreations.emojilibrary.controller; import android.animation.Animator; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import androidx.annotation.DrawableRes; import androidx.appcompat.widget.Toolbar; import android.text.Editable; import android.text.InputType; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.gotcreations.emojilibrary.R; import com.gotcreations.emojilibrary.model.layout.EmojiCompatActivity; import com.gotcreations.emojilibrary.model.layout.EmojiEditText; import com.gotcreations.emojilibrary.model.layout.AppPanelEventListener; import com.gotcreations.emojilibrary.model.layout.TelegramPanelView; import com.gotcreations.emojilibrary.util.AbstractAnimatorListener; import static android.view.View.GONE; import static android.view.View.getDefaultSize; /** * Created by edgar on 18/02/2016. */ public class TelegramPanel extends AppPanel{ private static final String TAG = "TelegramPanel"; public static final int EMPTY_MESSAGE = 0; public static final int EMPTY_MESSAGE_EMOJI_KEYBOARD = 1; public static final int EMPTY_MESSAGE_KEYBOARD = 2; public static final int PREPARED_MESSAGE = 3; public static final int PREPARED_MESSAGE_EMOJI_KEYBOARD = 4; public static final int PREPARED_MESSAGE_KEYBOARD = 5; public static final int AUDIO = 6; private Toolbar mBottomPanel; private TextView audioTime; private TelegramPanelView panelView; private int state; // CONSTRUCTOR public TelegramPanel(EmojiCompatActivity activity, AppPanelEventListener listener) { super(activity); this.mActivity = activity; init(); this.mEmojiKeyboard = new EmojiKeyboard(this.mActivity, this.mInput); this.mListener = listener; } public TelegramPanel(EmojiCompatActivity activity) { this(activity, null); } // INITIALIZATION @Override protected void initBottomPanel() { this.audioTime = (TextView) this.mActivity.findViewById(R.id.audio_time); this.mBottomPanel = (Toolbar) this.mActivity.findViewById(R.id.panel); this.panelView = (TelegramPanelView) this.mActivity.findViewById(R.id.panel_container).getParent(); this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); this.mBottomPanel.inflateMenu(R.menu.telegram_menu); this.mBottomPanel.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (state == AUDIO) { fireOnMicOffClicked(); showAudioPanel(false); } else if (TelegramPanel.this.isEmojiKeyboardVisible) { TelegramPanel.this.closeCurtain(); if (TelegramPanel.this.mInput.isSoftKeyboardVisible()) { TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard); TelegramPanel.this.mInput.hideSoftKeyboard(); } else { TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); TelegramPanel.this.mInput.showSoftKeyboard(); } } else { TelegramPanel.this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard); TelegramPanel.this.closeCurtain(); TelegramPanel.this.showEmojiKeyboard(0); } } }); this.mBottomPanel.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { if (item.getItemId() == R.id.action_attach) { fireOnAttachClicked(); } else if (item.getItemId() == R.id.action_mic) { switch (state) { case AUDIO: fireOnSendClicked(); showAudioPanel(false); break; default: if (TelegramPanel.this.mInput.getText().toString().equals("")) { showAudioPanel(true); } else { fireOnSendClicked(); } } } return Boolean.TRUE; } }); this.mCurtain = (LinearLayout) this.mActivity.findViewById(R.id.curtain); this.state = EMPTY_MESSAGE; } @Override protected void setInputConfig() { this.mInput = (EmojiEditText) this.mBottomPanel.findViewById(R.id.input); mInput.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); this.mInput.addOnSoftKeyboardListener(new EmojiEditText.OnSoftKeyboardListener() { @Override public void onSoftKeyboardDisplay() { if (!TelegramPanel.this.isEmojiKeyboardVisible) { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.schedule(new Runnable() { @Override public void run() { Handler mainHandler = new Handler(TelegramPanel.this.mActivity.getMainLooper()); Runnable myRunnable = new Runnable() { @Override public void run() { TelegramPanel.this.openCurtain(); TelegramPanel.this.showEmojiKeyboard(0); } }; mainHandler.post(myRunnable); } }, 150, TimeUnit.MILLISECONDS); } } @Override public void onSoftKeyboardHidden() { if (TelegramPanel.this.isEmojiKeyboardVisible) { TelegramPanel.this.closeCurtain(); TelegramPanel.this.hideEmojiKeyboard(200); } } }); this.mInput.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { showSendOptions(true); } @Override public void afterTextChanged(Editable s) { } }); audioTime.setTextColor(panelView.getAudioTextColor()); mInput.setTextColor(panelView.getTextColor()); mInput.setHint(panelView.getHintText()); mInput.setHintTextColor(panelView.getTextColorHint()); setIcon(R.id.action_attach, panelView.getAttachIconColor(), R.drawable.ic_attachment); setIcon(R.id.action_mic, panelView.getAudioIconColor(), R.drawable.ic_mic); } private void setIcon(int itemId, int color, @DrawableRes int drawableId) { Drawable icon = mActivity.getResources().getDrawable(drawableId); icon.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); setIcon(itemId, icon); } private void setIcon(int itemId, Drawable icon) { Menu menu = this.mBottomPanel.getMenu(); MenuItem mi = menu.findItem(itemId); mi.setIcon(icon); } @Override public void showAudioPanel(final boolean show) { if (show) { state = AUDIO; hideEmojiKeyboard(0); this.mInput.hideSoftKeyboard(); this.mInput.animate().alpha(0).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "Hide mInput"); mInput.setVisibility(GONE); } }).start(); this.audioTime.animate().alpha(1).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "show audioTime"); audioTime.setVisibility(View.VISIBLE); } }).start(); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(0).scaleY(0).setDuration(150).start(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() { @Override public void run() { setIcon(R.id.action_mic, panelView.getSendIconColor(), R.drawable.ic_send); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start(); } }).start(); } Drawable icCircle = mActivity.getResources().getDrawable(R.drawable.ic_circle); icCircle.setColorFilter(panelView.getAudioIconColor(), PorterDuff.Mode.SRC_ATOP); this.mBottomPanel.setNavigationIcon(icCircle); fireOnMicOnClicked(); } else { this.audioTime.animate().alpha(0).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "Hide audioInput"); audioTime.setVisibility(GONE); } }).start(); this.mInput.animate().alpha(1).setDuration(75).setListener(new AbstractAnimatorListener() { @Override public void onAnimationEnd(Animator animation) { Log.d(TAG, "Show mInput"); mInput.setVisibility(View.VISIBLE); } }).start(); showSendOptions(true); } } public void showSendOptions(boolean show) { final MenuItem micButton = TelegramPanel.this.mBottomPanel.getMenu().findItem(R.id.action_mic); if (isEmojiKeyboardVisible) { this.mBottomPanel.setNavigationIcon(R.drawable.ic_keyboard); } else { this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); } if (!this.mInput.getText().toString().equals("") && show) { if (state != PREPARED_MESSAGE && state != PREPARED_MESSAGE_EMOJI_KEYBOARD && state != PREPARED_MESSAGE_KEYBOARD) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(0).scaleY(0).setDuration(150).start(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() { @Override public void run() { setIcon(R.id.action_mic, panelView.getSendIconColor(), R.drawable.ic_send); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start(); } }).start(); } } state = PREPARED_MESSAGE; if (mInput.isSoftKeyboardVisible()) { state = PREPARED_MESSAGE_KEYBOARD; } else if (isEmojiKeyboardVisible) { state = PREPARED_MESSAGE_EMOJI_KEYBOARD; } } else { state = EMPTY_MESSAGE; if (mInput.isSoftKeyboardVisible()) { state = EMPTY_MESSAGE_KEYBOARD; } else if (isEmojiKeyboardVisible) { state = EMPTY_MESSAGE_EMOJI_KEYBOARD; } TelegramPanel.this.mBottomPanel.findViewById(R.id.action_attach).animate().scaleX(1).scaleY(1).setDuration(150).start(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(0).scaleY(0).setDuration(75).withEndAction(new Runnable() { @Override public void run() { setIcon(R.id.action_mic, panelView.getAudioIconColor(), R.drawable.ic_mic); TelegramPanel.this.mBottomPanel.findViewById(R.id.action_mic).animate().scaleX(1).scaleY(1).setDuration(75).start(); } }).start(); } } } public int getState() { return state; } public boolean isInState(int state) { return this.state == state; } public boolean isInAudioState() { return isInState(AUDIO); } public boolean isInMessageState() { return !isInAudioState(); } @Override public void hideEmojiKeyboard(int delay) { super.hideEmojiKeyboard(delay); this.mBottomPanel.setNavigationIcon(R.drawable.input_emoji); } public void setAudioTime(CharSequence time) { this.audioTime.setText(time); } }
ander7agar/emoji-keyboard
emoji-library/src/main/java/com/gotcreations/emojilibrary/controller/TelegramPanel.java
Java
apache-2.0
13,759
/** * Copyright Pravega 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 io.pravega.controller.server.eventProcessor.requesthandlers; import com.google.common.annotations.VisibleForTesting; import io.pravega.common.Timer; import io.pravega.common.concurrent.Futures; import io.pravega.common.tracing.TagLogger; import io.pravega.controller.eventProcessor.impl.SerializedRequestHandler; import io.pravega.controller.metrics.TransactionMetrics; import io.pravega.controller.server.ControllerService; import io.pravega.controller.store.stream.OperationContext; import io.pravega.controller.store.stream.StreamMetadataStore; import io.pravega.controller.store.stream.records.StreamSegmentRecord; import io.pravega.controller.task.Stream.StreamMetadataTasks; import io.pravega.shared.controller.event.AbortEvent; import java.util.UUID; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import org.slf4j.LoggerFactory; /** * This actor processes commit txn events. * It does the following 2 operations in order. * 1. Send abort txn message to active segments of the stream. * 2. Change txn state from aborting to aborted. */ public class AbortRequestHandler extends SerializedRequestHandler<AbortEvent> { private static final TagLogger log = new TagLogger(LoggerFactory.getLogger(AbortRequestHandler.class)); private final StreamMetadataStore streamMetadataStore; private final StreamMetadataTasks streamMetadataTasks; private final ScheduledExecutorService executor; private final BlockingQueue<AbortEvent> processedEvents; @VisibleForTesting public AbortRequestHandler(final StreamMetadataStore streamMetadataStore, final StreamMetadataTasks streamMetadataTasks, final ScheduledExecutorService executor, final BlockingQueue<AbortEvent> queue) { super(executor); this.streamMetadataStore = streamMetadataStore; this.streamMetadataTasks = streamMetadataTasks; this.executor = executor; this.processedEvents = queue; } public AbortRequestHandler(final StreamMetadataStore streamMetadataStore, final StreamMetadataTasks streamMetadataTasks, final ScheduledExecutorService executor) { super(executor); this.streamMetadataStore = streamMetadataStore; this.streamMetadataTasks = streamMetadataTasks; this.executor = executor; this.processedEvents = null; } @Override public CompletableFuture<Void> processEvent(AbortEvent event) { String scope = event.getScope(); String stream = event.getStream(); int epoch = event.getEpoch(); UUID txId = event.getTxid(); long requestId = event.getRequestId(); if (requestId == 0L) { requestId = ControllerService.nextRequestId(); } Timer timer = new Timer(); OperationContext context = streamMetadataStore.createStreamContext(scope, stream, requestId); log.info(requestId, "Aborting transaction {} on stream {}/{}", event.getTxid(), event.getScope(), event.getStream()); return Futures.toVoid(streamMetadataStore.getSegmentsInEpoch(event.getScope(), event.getStream(), epoch, context, executor) .thenApply(segments -> segments.stream().map(StreamSegmentRecord::segmentId) .collect(Collectors.toList())) .thenCompose(segments -> streamMetadataTasks.notifyTxnAbort(scope, stream, segments, txId, context.getRequestId())) .thenCompose(x -> streamMetadataStore.abortTransaction(scope, stream, txId, context, executor)) .whenComplete((result, error) -> { if (error != null) { log.warn(context.getRequestId(), "Failed aborting transaction {} on stream {}/{}", event.getTxid(), event.getScope(), event.getStream()); TransactionMetrics.getInstance().abortTransactionFailed(scope, stream); } else { log.info(context.getRequestId(), "Successfully aborted transaction {} on stream {}/{}", event.getTxid(), event.getScope(), event.getStream()); if (processedEvents != null) { processedEvents.offer(event); } TransactionMetrics.getInstance().abortTransaction(scope, stream, timer.getElapsed()); } })); } }
pravega/pravega
controller/src/main/java/io/pravega/controller/server/eventProcessor/requesthandlers/AbortRequestHandler.java
Java
apache-2.0
5,395
# Copyright (c) 2019 Infortrend Technology, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class InfortrendNASTestData(object): fake_share_id = ['5a0aa06e-1c57-4996-be46-b81e360e8866', # NFS 'aac4fe64-7a9c-472a-b156-9adbb50b4d29'] # CIFS fake_share_name = [fake_share_id[0].replace('-', ''), fake_share_id[1].replace('-', '')] fake_channel_ip = ['172.27.112.223', '172.27.113.209'] fake_service_status_data = ('(64175, 1234, 272, 0)\n\n' '{"cliCode": ' '[{"Return": "0x0000", "CLI": "Successful"}], ' '"returnCode": [], ' '"data": ' '[{"A": ' '{"NFS": ' '{"displayName": "NFS", ' '"state_time": "2017-05-04 14:19:53", ' '"enabled": true, ' '"cpu_rate": "0.0", ' '"mem_rate": "0.0", ' '"state": "exited", ' '"type": "share"}}}]}\n\n') fake_folder_status_data = ('(64175, 1234, 1017, 0)\n\n' '{"cliCode": ' '[{"Return": "0x0000", "CLI": "Successful"}], ' '"returnCode": [], ' '"data": ' '[{"utility": "1.00", ' '"used": "33886208", ' '"subshare": true, ' '"share": false, ' '"worm": "", ' '"free": "321931374592", ' '"fsType": "xfs", ' '"owner": "A", ' '"readOnly": false, ' '"modifyTime": "2017-04-27 16:16", ' '"directory": "/share-pool-01/LV-1", ' '"volumeId": "6541BAFB2E6C57B6", ' '"mounted": true, ' '"size": "321965260800"}, ' '{"utility": "1.00", ' '"used": "33779712", ' '"subshare": false, ' '"share": false, ' '"worm": "", ' '"free": "107287973888", ' '"fsType": "xfs", ' '"owner": "A", ' '"readOnly": false, ' '"modifyTime": "2017-04-27 15:45", ' '"directory": "/share-pool-02/LV-1", ' '"volumeId": "147A8FB67DA39914", ' '"mounted": true, ' '"size": "107321753600"}]}\n\n') fake_nfs_status_off = [{ 'A': { 'NFS': { 'displayName': 'NFS', 'state_time': '2017-05-04 14:19:53', 'enabled': False, 'cpu_rate': '0.0', 'mem_rate': '0.0', 'state': 'exited', 'type': 'share', } } }] fake_folder_status = [{ 'utility': '1.00', 'used': '33886208', 'subshare': True, 'share': False, 'worm': '', 'free': '321931374592', 'fsType': 'xfs', 'owner': 'A', 'readOnly': False, 'modifyTime': '2017-04-27 16:16', 'directory': '/share-pool-01/LV-1', 'volumeId': '6541BAFB2E6C57B6', 'mounted': True, 'size': '321965260800'}, { 'utility': '1.00', 'used': '33779712', 'subshare': False, 'share': False, 'worm': '', 'free': '107287973888', 'fsType': 'xfs', 'owner': 'A', 'readOnly': False, 'modifyTime': '2017-04-27 15:45', 'directory': '/share-pool-02/LV-1', 'volumeId': '147A8FB67DA39914', 'mounted': True, 'size': '107321753600', }] def fake_get_channel_status(self, ch1_status='UP'): return [{ 'datalink': 'mgmt0', 'status': 'UP', 'typeConfig': 'DHCP', 'IP': '172.27.112.125', 'MAC': '00:d0:23:00:15:a6', 'netmask': '255.255.240.0', 'type': 'dhcp', 'gateway': '172.27.127.254'}, { 'datalink': 'CH0', 'status': 'UP', 'typeConfig': 'DHCP', 'IP': self.fake_channel_ip[0], 'MAC': '00:d0:23:80:15:a6', 'netmask': '255.255.240.0', 'type': 'dhcp', 'gateway': '172.27.127.254'}, { 'datalink': 'CH1', 'status': ch1_status, 'typeConfig': 'DHCP', 'IP': self.fake_channel_ip[1], 'MAC': '00:d0:23:40:15:a6', 'netmask': '255.255.240.0', 'type': 'dhcp', 'gateway': '172.27.127.254'}, { 'datalink': 'CH2', 'status': 'DOWN', 'typeConfig': 'DHCP', 'IP': '', 'MAC': '00:d0:23:c0:15:a6', 'netmask': '', 'type': '', 'gateway': ''}, { 'datalink': 'CH3', 'status': 'DOWN', 'typeConfig': 'DHCP', 'IP': '', 'MAC': '00:d0:23:20:15:a6', 'netmask': '', 'type': '', 'gateway': '', }] fake_fquota_status = [{ 'quota': '21474836480', 'used': '0', 'name': 'test-folder', 'type': 'subfolder', 'id': '537178178'}, { 'quota': '32212254720', 'used': '0', 'name': fake_share_name[0], 'type': 'subfolder', 'id': '805306752'}, { 'quota': '53687091200', 'used': '21474836480', 'name': fake_share_name[1], 'type': 'subfolder', 'id': '69'}, { 'quota': '94091997184', 'used': '0', 'type': 'subfolder', 'id': '70', "name": 'test-folder-02' }] fake_fquota_status_with_no_settings = [] def fake_get_share_status_nfs(self, status=False): fake_share_status_nfs = [{ 'ftp': False, 'cifs': False, 'oss': False, 'sftp': False, 'nfs': status, 'directory': '/LV-1/share-pool-01/' + self.fake_share_name[0], 'exist': True, 'afp': False, 'webdav': False }] if status: fake_share_status_nfs[0]['nfs_detail'] = { 'hostList': [{ 'uid': '65534', 'insecure': 'insecure', 'squash': 'all', 'access': 'ro', 'host': '*', 'gid': '65534', 'mode': 'async', 'no_subtree_check': 'no_subtree_check', }] } return fake_share_status_nfs def fake_get_share_status_cifs(self, status=False): fake_share_status_cifs = [{ 'ftp': False, 'cifs': status, 'oss': False, 'sftp': False, 'nfs': False, 'directory': '/share-pool-01/LV-1/' + self.fake_share_name[1], 'exist': True, 'afp': False, 'webdav': False }] if status: fake_share_status_cifs[0]['cifs_detail'] = { 'available': True, 'encrypt': False, 'description': '', 'sharename': 'cifs-01', 'failover': '', 'AIO': True, 'priv': 'None', 'recycle_bin': False, 'ABE': True, } return fake_share_status_cifs fake_subfolder_data = [{ 'size': '6', 'index': '34', 'description': '', 'encryption': '', 'isEnd': False, 'share': False, 'volumeId': '6541BAFB2E6C57B6', 'quota': '', 'modifyTime': '2017-04-06 11:35', 'owner': 'A', 'path': '/share-pool-01/LV-1/UserHome', 'subshare': True, 'type': 'subfolder', 'empty': False, 'name': 'UserHome'}, { 'size': '6', 'index': '39', 'description': '', 'encryption': '', 'isEnd': False, 'share': False, 'volumeId': '6541BAFB2E6C57B6', 'quota': '21474836480', 'modifyTime': '2017-04-27 15:44', 'owner': 'A', 'path': '/share-pool-01/LV-1/test-folder', 'subshare': False, 'type': 'subfolder', 'empty': True, 'name': 'test-folder'}, { 'size': '6', 'index': '45', 'description': '', 'encryption': '', 'isEnd': False, 'share': True, 'volumeId': '6541BAFB2E6C57B6', 'quota': '32212254720', 'modifyTime': '2017-04-27 16:15', 'owner': 'A', 'path': '/share-pool-01/LV-1/' + fake_share_name[0], 'subshare': False, 'type': 'subfolder', 'empty': True, 'name': fake_share_name[0]}, { 'size': '6', 'index': '512', 'description': '', 'encryption': '', 'isEnd': True, 'share': True, 'volumeId': '6541BAFB2E6C57B6', 'quota': '53687091200', 'modifyTime': '2017-04-27 16:16', 'owner': 'A', 'path': '/share-pool-01/LV-1/' + fake_share_name[1], 'subshare': False, 'type': 'subfolder', 'empty': True, 'name': fake_share_name[1]}, { 'size': '6', 'index': '777', 'description': '', 'encryption': '', 'isEnd': False, 'share': False, 'volumeId': '6541BAFB2E6C57B6', 'quota': '94091997184', 'modifyTime': '2017-04-28 15:44', 'owner': 'A', 'path': '/share-pool-01/LV-1/test-folder-02', 'subshare': False, 'type': 'subfolder', 'empty': True, 'name': 'test-folder-02' }] fake_cifs_user_list = [{ 'Superuser': 'No', 'Group': 'users', 'Description': '', 'Quota': 'none', 'PWD Expiry Date': '2291-01-19', 'Home Directory': '/share-pool-01/LV-1/UserHome/user01', 'UID': '100001', 'Type': 'Local', 'Name': 'user01'}, { 'Superuser': 'No', 'Group': 'users', 'Description': '', 'Quota': 'none', 'PWD Expiry Date': '2017-08-07', 'Home Directory': '/share-pool-01/LV-1/UserHome/user02', 'UID': '100002', 'Type': 'Local', 'Name': 'user02' }] fake_share_status_nfs_with_rules = [{ 'ftp': False, 'cifs': False, 'oss': False, 'sftp': False, 'nfs': True, 'directory': '/share-pool-01/LV-1/' + fake_share_name[0], 'exist': True, 'nfs_detail': { 'hostList': [{ 'uid': '65534', 'insecure': 'insecure', 'squash': 'all', 'access': 'ro', 'host': '*', 'gid': '65534', 'mode': 'async', 'no_subtree_check': 'no_subtree_check'}, { 'uid': '65534', 'insecure': 'insecure', 'squash': 'all', 'access': 'rw', 'host': '172.27.1.1', 'gid': '65534', 'mode': 'async', 'no_subtree_check': 'no_subtree_check'}, { 'uid': '65534', 'insecure': 'insecure', 'squash': 'all', 'access': 'rw', 'host': '172.27.1.2', 'gid': '65534', 'mode': 'async', 'no_subtree_check': 'no_subtree_check'}] }, 'afp': False, 'webdav': False, }] fake_share_status_cifs_with_rules = [ { 'permission': { 'Read': True, 'Write': True, 'Execute': True}, 'type': 'user', 'id': '100001', 'name': 'user01' }, { 'permission': { 'Read': True, 'Write': False, 'Execute': True}, 'type': 'user', 'id': '100002', 'name': 'user02' }, { 'permission': { 'Read': True, 'Write': False, 'Execute': True}, 'type': 'group@', 'id': '100', 'name': 'users' }, { 'permission': { 'Read': True, 'Write': False, 'Execute': True}, 'type': 'other@', 'id': '', 'name': '' } ]
openstack/manila
manila/tests/share/drivers/infortrend/fake_infortrend_nas_data.py
Python
apache-2.0
13,722
import { createStore, applyMiddleware, compose } from 'redux' import logger from 'redux-logger' import thunkMiddleware from 'redux-thunk' import rootReducer from './reducers' const configureStore = () => { const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; return createStore(rootReducer, /* preloadedState, */ composeEnhancers( applyMiddleware(thunkMiddleware) // applyMiddleware(logger) )); } export default configureStore
AleksandrRogachev94/chat-vote-go-frontend
src/configureStore.js
JavaScript
apache-2.0
471
(function outer(modules, cache, entries){ /** * Global */ var global = (function(){ return this; })(); /** * Require `name`. * * @param {String} name * @param {Boolean} jumped * @api public */ function require(name, jumped){ if (cache[name]) return cache[name].exports; if (modules[name]) return call(name, require); throw new Error('cannot find module "' + name + '"'); } /** * Call module `id` and cache it. * * @param {Number} id * @param {Function} require * @return {Function} * @api private */ function call(id, require){ var m = cache[id] = { exports: {} }; var mod = modules[id]; var name = mod[2]; var fn = mod[0]; fn.call(m.exports, function(req){ var dep = modules[id][1][req]; return require(dep ? dep : req); }, m, m.exports, outer, modules, cache, entries); // expose as `name`. if (name) cache[name] = cache[id]; return cache[id].exports; } /** * Require all entries exposing them on global if needed. */ for (var id in entries) { if (entries[id]) { global[entries[id]] = require(id); } else { require(id); } } /** * Duo flag. */ require.duo = true; /** * Expose cache. */ require.cache = cache; /** * Expose modules */ require.modules = modules; /** * Return newest require. */ return require; })({ 1: [function(require, module, exports) { /** @jsx React.DOM */ React.renderComponent( React.DOM.h1(null, "Hello, world!"), document.getElementById('example') ); }, {}]}, {}, {"1":""})
wdamron/duo-jsx
test/exp_react.js
JavaScript
apache-2.0
1,625
/** * Copyright 2011-2021 Asakusa Framework 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. */ package com.asakusafw.directio.hive.serde; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.math.BigDecimal; import java.sql.Timestamp; import org.apache.hadoop.hive.common.type.HiveChar; import org.apache.hadoop.hive.common.type.HiveDecimal; import org.apache.hadoop.hive.common.type.HiveVarchar; import org.apache.hadoop.hive.serde2.io.HiveCharWritable; import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable; import org.apache.hadoop.hive.serde2.io.HiveVarcharWritable; import org.apache.hadoop.hive.serde2.io.TimestampWritable; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveCharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveVarcharObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector; import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector; import org.apache.hadoop.io.Text; import org.junit.Test; import com.asakusafw.runtime.value.Date; import com.asakusafw.runtime.value.DateOption; import com.asakusafw.runtime.value.DateTime; import com.asakusafw.runtime.value.DateTimeOption; import com.asakusafw.runtime.value.DecimalOption; import com.asakusafw.runtime.value.StringOption; /** * Test for {@link ValueSerdeFactory}. */ public class ValueSerdeFactoryTest { /** * constants. */ @Test public void constants() { for (ValueSerdeFactory serde : ValueSerdeFactory.values()) { serde.getDriver(serde.getInspector()); } } /** * char. */ @Test public void getChar() { ValueSerde serde = ValueSerdeFactory.getChar(10); HiveCharObjectInspector inspector = (HiveCharObjectInspector) serde.getInspector(); StringOption option = new StringOption("hello"); HiveChar value = new HiveChar("hello", 10); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveCharWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); StringOption copy = new StringOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * varchar. */ @Test public void getVarchar() { ValueSerde serde = ValueSerdeFactory.getVarchar(10); HiveVarcharObjectInspector inspector = (HiveVarcharObjectInspector) serde.getInspector(); StringOption option = new StringOption("hello"); HiveVarchar value = new HiveVarchar("hello", 10); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); // HiveVarchar cannot compare by equals assertThat(inspector.getPrimitiveJavaObject(option).compareTo(value), is(0)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveVarcharWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); StringOption copy = new StringOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * qualified decimal. */ @Test public void getDecimal() { ValueSerde serde = ValueSerdeFactory.getDecimal(10, 2); HiveDecimalObjectInspector inspector = (HiveDecimalObjectInspector) serde.getInspector(); DecimalOption option = new DecimalOption(new BigDecimal("123.45")); HiveDecimal value = HiveDecimal.create(new BigDecimal("123.45")); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new HiveDecimalWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DecimalOption copy = new DecimalOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * decimal by string. */ @Test public void decimal_by_string() { ValueSerde serde = StringValueSerdeFactory.DECIMAL; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DecimalOption option = new DecimalOption(new BigDecimal("123.45")); String value = "123.45"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DecimalOption copy = new DecimalOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date by string. */ @Test public void date_by_string() { ValueSerde serde = StringValueSerdeFactory.DATE; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateOption option = new DateOption(new Date(2014, 7, 1)); String value = "2014-07-01"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateOption copy = new DateOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date-time by string. */ @Test public void datetime_by_string() { ValueSerde serde = StringValueSerdeFactory.DATETIME; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateTimeOption option = new DateTimeOption(new DateTime(2014, 7, 1, 12, 5, 59)); String value = "2014-07-01 12:05:59"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateTimeOption copy = new DateTimeOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date-time by string. */ @Test public void datetime_by_string_w_zeros() { ValueSerde serde = StringValueSerdeFactory.DATETIME; StringObjectInspector inspector = (StringObjectInspector) serde.getInspector(); DateTimeOption option = new DateTimeOption(new DateTime(1, 1, 1, 0, 0, 0)); String value = "0001-01-01 00:00:00"; assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new Text(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateTimeOption copy = new DateTimeOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } /** * date by timestamp. */ @SuppressWarnings("deprecation") @Test public void date_by_timestamp() { ValueSerde serde = TimestampValueSerdeFactory.DATE; TimestampObjectInspector inspector = (TimestampObjectInspector) serde.getInspector(); DateOption option = new DateOption(new Date(2014, 7, 1)); Timestamp value = new Timestamp(2014 - 1900, 7 - 1, 1, 0, 0, 0, 0); assertThat(inspector.copyObject(option), is((Object) option)); assertThat(inspector.copyObject(option), is(not(sameInstance((Object) option)))); assertThat(inspector.copyObject(null), is(nullValue())); assertThat(inspector.getPrimitiveJavaObject(option), is(value)); assertThat(inspector.getPrimitiveJavaObject(null), is(nullValue())); assertThat(inspector.getPrimitiveWritableObject(option), is(new TimestampWritable(value))); assertThat(inspector.getPrimitiveWritableObject(null), is(nullValue())); ValueDriver driver = serde.getDriver(inspector); DateOption copy = new DateOption(); driver.set(copy, option); assertThat(copy, is(option)); driver.set(copy, null); assertThat(copy.isNull(), is(true)); } }
asakusafw/asakusafw
hive-project/core-v2/src/test/java/com/asakusafw/directio/hive/serde/ValueSerdeFactoryTest.java
Java
apache-2.0
11,792
/* * Copyright (C) 2017-2019 Dremio Corporation * * 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. */ declare module '*.less'; declare function la(textToLocalize: string): string;
dremio/dremio-oss
dac/ui/src/modules.d.ts
TypeScript
apache-2.0
689
/** * Copyright 2015 The AMP HTML Authors. 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. */ /** * @fileoverview Embeds an instagram photo. The data-shortcode attribute can be * easily copied from a normal instagram URL. Example: <code> <amp-instagram * data-shortcode="fBwFP" data-captioned data-default-framing alt="Fastest page * in the west." width="320" height="392" layout="responsive"> </amp-instagram> * </code> * * For responsive embedding the width and height can be left unchanged from the * example above and should produce the correct aspect ratio. amp-instagram will * attempt to resize on load based on the height reported by the embedded frame. * If captions are specified (data-captioned) then a resize will be requested * every time due to the fact that it's not possible to know the height of the * caption in advance. * * If captions are included it is stringly reccomended that an overflow element * is also included. See description of overflow in amp-iframe. * * If data-default-framing is present will apply the default instagram frame * style without changing the layout/size. */ import {CSS} from '../../../build/amp-instagram-0.1.css'; import {getData, listen} from '../../../src/event-helper'; import {isLayoutSizeDefined} from '../../../src/layout'; import {isObject} from '../../../src/types'; import {removeElement} from '../../../src/dom'; import {setStyles} from '../../../src/style'; import {startsWith} from '../../../src/string'; import {tryParseJson} from '../../../src/json'; import {user} from '../../../src/log'; class AmpInstagram extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private {?Element} */ this.iframe_ = null; /** @private {?string} */ this.shortcode_ = ''; /** @private {?Function} */ this.unlistenMessage_ = null; /** @private {string} */ this.captioned_ = ''; /** * @private {?Promise} * @visibleForTesting */ this.iframePromise_ = null; } /** * @param {boolean=} opt_onLayout * @override */ preconnectCallback(opt_onLayout) { // See // https://instagram.com/developer/embedding/?hl=en this.preconnect.url('https://www.instagram.com', opt_onLayout); // Host instagram used for image serving. While the host name is // funky this appears to be stable in the post-domain sharding era. this.preconnect.url('https://instagram.fsnc1-1.fna.fbcdn.net', opt_onLayout); } /** @override */ renderOutsideViewport() { return false; } /** @override */ buildCallback() { this.shortcode_ = user().assert( (this.element.getAttribute('data-shortcode') || this.element.getAttribute('shortcode')), 'The data-shortcode attribute is required for <amp-instagram> %s', this.element); this.captioned_ = this.element.hasAttribute('data-captioned') ? 'captioned/' : ''; } /** @override */ createPlaceholderCallback() { const placeholder = this.win.document.createElement('div'); placeholder.setAttribute('placeholder', ''); const image = this.win.document.createElement('amp-img'); image.setAttribute('noprerender', ''); // This will redirect to the image URL. By experimentation this is // always the same URL that is actually used inside of the embed. image.setAttribute('src', 'https://www.instagram.com/p/' + encodeURIComponent(this.shortcode_) + '/media/?size=l'); image.setAttribute('layout', 'fill'); image.setAttribute('referrerpolicy', 'origin'); this.propagateAttributes(['alt'], image); /* * Add instagram default styling */ if (this.element.hasAttribute('data-default-framing')) { this.element.classList.add('amp-instagram-default-framing'); } // This makes the non-iframe image appear in the exact same spot // where it will be inside of the iframe. setStyles(image, { 'top': '0 px', 'bottom': '0 px', 'left': '0 px', 'right': '0 px', }); placeholder.appendChild(image); return placeholder; } /** @override */ isLayoutSupported(layout) { return isLayoutSizeDefined(layout); } /** @override */ layoutCallback() { const iframe = this.element.ownerDocument.createElement('iframe'); this.iframe_ = iframe; this.unlistenMessage_ = listen( this.win, 'message', this.handleInstagramMessages_.bind(this) ); iframe.setAttribute('scrolling', 'no'); iframe.setAttribute('frameborder', '0'); iframe.setAttribute('allowtransparency', 'true'); //Add title to the iframe for better accessibility. iframe.setAttribute('title', 'Instagram: ' + this.element.getAttribute('alt')); iframe.src = 'https://www.instagram.com/p/' + encodeURIComponent(this.shortcode_) + '/embed/' + this.captioned_ + '?cr=1&v=7'; this.applyFillContent(iframe); this.element.appendChild(iframe); setStyles(iframe, { 'opacity': 0, }); return this.iframePromise_ = this.loadPromise(iframe).then(() => { this.getVsync().mutate(() => { setStyles(iframe, { 'opacity': 1, }); }); }); } /** * @param {!Event} event * @private */ handleInstagramMessages_(event) { if (event.origin != 'https://www.instagram.com' || event.source != this.iframe_.contentWindow) { return; } const eventData = getData(event); if (!eventData || !(isObject(eventData) || startsWith(/** @type {string} */ (eventData), '{'))) { return; // Doesn't look like JSON. } const data = isObject(eventData) ? eventData : tryParseJson(eventData); if (data === undefined) { return; // We only process valid JSON. } if (data['type'] == 'MEASURE' && data['details']) { const height = data['details']['height']; this.getVsync().measure(() => { if (this.iframe_ && this.iframe_./*OK*/offsetHeight !== height) { this./*OK*/changeHeight(height); } }); } } /** @override */ unlayoutOnPause() { return true; } /** @override */ unlayoutCallback() { if (this.iframe_) { removeElement(this.iframe_); this.iframe_ = null; this.iframePromise_ = null; } if (this.unlistenMessage_) { this.unlistenMessage_(); } return true; // Call layoutCallback again. } } AMP.extension('amp-instagram', '0.1', AMP => { AMP.registerElement('amp-instagram', AmpInstagram, CSS); });
aghassemi/amphtml
extensions/amp-instagram/0.1/amp-instagram.js
JavaScript
apache-2.0
7,111
import arez.Arez; import arez.ArezContext; import arez.Component; import arez.Disposable; import arez.ObservableValue; import arez.SafeProcedure; import arez.component.DisposeNotifier; import arez.component.Identifiable; import arez.component.internal.ComponentKernel; import java.text.ParseException; import javax.annotation.Generated; import javax.annotation.Nonnull; import org.realityforge.braincheck.Guards; @Generated("arez.processor.ArezProcessor") final class Arez_ObservableWithSpecificExceptionModel extends ObservableWithSpecificExceptionModel implements Disposable, Identifiable<Integer>, DisposeNotifier { private static volatile int $$arezi$$_nextId; private final ComponentKernel $$arezi$$_kernel; @Nonnull private final ObservableValue<Long> $$arez$$_time; Arez_ObservableWithSpecificExceptionModel() { super(); final ArezContext $$arezv$$_context = Arez.context(); final int $$arezv$$_id = ++$$arezi$$_nextId; final String $$arezv$$_name = Arez.areNamesEnabled() ? "ObservableWithSpecificExceptionModel." + $$arezv$$_id : null; final Component $$arezv$$_component = Arez.areNativeComponentsEnabled() ? $$arezv$$_context.component( "ObservableWithSpecificExceptionModel", $$arezv$$_id, $$arezv$$_name, this::$$arezi$$_nativeComponentPreDispose ) : null; this.$$arezi$$_kernel = new ComponentKernel( Arez.areZonesEnabled() ? $$arezv$$_context : null, Arez.areNamesEnabled() ? $$arezv$$_name : null, $$arezv$$_id, Arez.areNativeComponentsEnabled() ? $$arezv$$_component : null, null, Arez.areNativeComponentsEnabled() ? null : this::$$arezi$$_dispose, null, true, false, false ); this.$$arez$$_time = $$arezv$$_context.observable( Arez.areNativeComponentsEnabled() ? $$arezv$$_component : null, Arez.areNamesEnabled() ? $$arezv$$_name + ".time" : null, Arez.arePropertyIntrospectorsEnabled() ? () -> super.getTime() : null, Arez.arePropertyIntrospectorsEnabled() ? v -> super.setTime( v ) : null ); this.$$arezi$$_kernel.componentConstructed(); this.$$arezi$$_kernel.componentReady(); } private int $$arezi$$_id() { return this.$$arezi$$_kernel.getId(); } @Override @Nonnull public Integer getArezId() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'getArezId' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'getArezId' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } return $$arezi$$_id(); } private void $$arezi$$_nativeComponentPreDispose() { this.$$arezi$$_kernel.notifyOnDisposeListeners(); } @Override public void addOnDisposeListener(@Nonnull final Object key, @Nonnull final SafeProcedure action) { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'addOnDisposeListener' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } this.$$arezi$$_kernel.addOnDisposeListener( key, action ); } @Override public void removeOnDisposeListener(@Nonnull final Object key) { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'removeOnDisposeListener' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'removeOnDisposeListener' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } this.$$arezi$$_kernel.removeOnDisposeListener( key ); } @Override public boolean isDisposed() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'isDisposed' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'isDisposed' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } return this.$$arezi$$_kernel.isDisposed(); } @Override public void dispose() { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenInitialized(), () -> "Method named 'dispose' invoked on uninitialized component of type 'ObservableWithSpecificExceptionModel'" ); } if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.hasBeenConstructed(), () -> "Method named 'dispose' invoked on un-constructed component named '" + ( null == this.$$arezi$$_kernel ? "?" : this.$$arezi$$_kernel.getName() ) + "'" ); } this.$$arezi$$_kernel.dispose(); } private void $$arezi$$_dispose() { this.$$arez$$_time.dispose(); } @Override public long getTime() throws ParseException { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.isActive(), () -> "Method named 'getTime' invoked on " + this.$$arezi$$_kernel.describeState() + " component named '" + this.$$arezi$$_kernel.getName() + "'" ); } this.$$arez$$_time.reportObserved(); return super.getTime(); } @Override public void setTime(final long time) throws ParseException { if ( Arez.shouldCheckApiInvariants() ) { Guards.apiInvariant( () -> null != this.$$arezi$$_kernel && this.$$arezi$$_kernel.isActive(), () -> "Method named 'setTime' invoked on " + this.$$arezi$$_kernel.describeState() + " component named '" + this.$$arezi$$_kernel.getName() + "'" ); } this.$$arez$$_time.preReportChanged(); final long $$arezv$$_currentValue = super.getTime(); if ( time != $$arezv$$_currentValue ) { super.setTime( time ); this.$$arez$$_time.reportChanged(); } } @Override public String toString() { if ( Arez.areNamesEnabled() ) { return "ArezComponent[" + this.$$arezi$$_kernel.getName() + "]"; } else { return super.toString(); } } }
realityforge/arez
processor/src/test/fixtures/expected/Arez_ObservableWithSpecificExceptionModel.java
Java
apache-2.0
6,870
namespace RoslynPad.Roslyn.Snippets { public sealed class SnippetInfo { public string Shortcut { get; } public string Title { get; } public string Description { get; } public SnippetInfo(string shortcut, string title, string description) { Shortcut = shortcut; Title = title; Description = description; } } }
aelij/roslynpad
src/RoslynPad.Roslyn/Snippets/SnippetInfo.cs
C#
apache-2.0
407
/** * Licensing arrangement (from website FAQ): * * The software is completely free for any purpose, unless notes at the * head of the program text indicates otherwise (which is rare). In any * case, the notes about licensing are never more restrictive than the * BSD License. * */ package com.novartis.pcs.ontology.service.mapper; /* Porter stemmer in Java. The original paper is in Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14, no. 3, pp 130-137, See also http://www.tartarus.org/~martin/PorterStemmer/index.html Bug 1 (reported by Gonzalo Parra 16/10/99) fixed as marked below. Tthe words 'aed', 'eed', 'oed' leave k at 'a' for step 3, and b[k-1] is then out outside the bounds of b. Similarly, Bug 2 (reported by Steve Dyrdahl 22/2/00) fixed as marked below. 'ion' by itself leaves j = -1 in the test for 'ion' in step 5, and b[j] is then outside the bounds of b. Release 3. [ This version is derived from Release 3, modified by Brian Goetz to optimize for fewer object creations. ] */ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * * Stemmer, implementing the Porter Stemming Algorithm * * The Stemmer class transforms a word into its root form. The input * word can be provided a character at time (by calling add()), or at once * by calling one of the various stem(something) methods. */ class PorterStemmer { private char[] b; private int i, /* offset into b */ j, k, k0; private boolean dirty = false; private static final int INC = 50; /* unit of size whereby b is increased */ private static final int EXTRA = 1; public PorterStemmer() { b = new char[INC]; i = 0; } /** * reset() resets the stemmer so it can stem another word. If you invoke * the stemmer by calling add(char) and then stem(), you must call reset() * before starting another word. */ public void reset() { i = 0; dirty = false; } /** * Add a character to the word being stemmed. When you are finished * adding characters, you can call stem(void) to process the word. */ public void add(char ch) { if (b.length <= i + EXTRA) { char[] new_b = new char[b.length+INC]; System.arraycopy(b, 0, new_b, 0, b.length); b = new_b; } b[i++] = ch; } /** * After a word has been stemmed, it can be retrieved by toString(), * or a reference to the internal buffer can be retrieved by getResultBuffer * and getResultLength (which is generally more efficient.) */ @Override public String toString() { return new String(b,0,i); } /** * Returns the length of the word resulting from the stemming process. */ public int getResultLength() { return i; } /** * Returns a reference to a character buffer containing the results of * the stemming process. You also need to consult getResultLength() * to determine the length of the result. */ public char[] getResultBuffer() { return b; } /* cons(i) is true <=> b[i] is a consonant. */ private final boolean cons(int i) { switch (b[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': return false; case 'y': return (i==k0) ? true : !cons(i-1); default: return true; } } /* m() measures the number of consonant sequences between k0 and j. if c is a consonant sequence and v a vowel sequence, and <..> indicates arbitrary presence, <c><v> gives 0 <c>vc<v> gives 1 <c>vcvc<v> gives 2 <c>vcvcvc<v> gives 3 .... */ private final int m() { int n = 0; int i = k0; while(true) { if (i > j) return n; if (! cons(i)) break; i++; } i++; while(true) { while(true) { if (i > j) return n; if (cons(i)) break; i++; } i++; n++; while(true) { if (i > j) return n; if (! cons(i)) break; i++; } i++; } } /* vowelinstem() is true <=> k0,...j contains a vowel */ private final boolean vowelinstem() { int i; for (i = k0; i <= j; i++) if (! cons(i)) return true; return false; } /* doublec(j) is true <=> j,(j-1) contain a double consonant. */ private final boolean doublec(int j) { if (j < k0+1) return false; if (b[j] != b[j-1]) return false; return cons(j); } /* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant and also if the second c is not w,x or y. this is used when trying to restore an e at the end of a short word. e.g. cav(e), lov(e), hop(e), crim(e), but snow, box, tray. */ private final boolean cvc(int i) { if (i < k0+2 || !cons(i) || cons(i-1) || !cons(i-2)) return false; else { int ch = b[i]; if (ch == 'w' || ch == 'x' || ch == 'y') return false; } return true; } private final boolean ends(String s) { int l = s.length(); int o = k-l+1; if (o < k0) return false; for (int i = 0; i < l; i++) if (b[o+i] != s.charAt(i)) return false; j = k-l; return true; } /* setto(s) sets (j+1),...k to the characters in the string s, readjusting k. */ void setto(String s) { int l = s.length(); int o = j+1; for (int i = 0; i < l; i++) b[o+i] = s.charAt(i); k = j+l; dirty = true; } /* r(s) is used further down. */ void r(String s) { if (m() > 0) setto(s); } /* step1() gets rid of plurals and -ed or -ing. e.g. caresses -> caress ponies -> poni ties -> ti caress -> caress cats -> cat feed -> feed agreed -> agree disabled -> disable matting -> mat mating -> mate meeting -> meet milling -> mill messing -> mess meetings -> meet */ private final void step1() { if (b[k] == 's') { if (ends("sses")) k -= 2; else if (ends("ies")) setto("i"); else if (b[k-1] != 's') k--; } if (ends("eed")) { if (m() > 0) k--; } else if ((ends("ed") || ends("ing")) && vowelinstem()) { k = j; if (ends("at")) setto("ate"); else if (ends("bl")) setto("ble"); else if (ends("iz")) setto("ize"); else if (doublec(k)) { int ch = b[k--]; if (ch == 'l' || ch == 's' || ch == 'z') k++; } else if (m() == 1 && cvc(k)) setto("e"); } } /* step2() turns terminal y to i when there is another vowel in the stem. */ private final void step2() { if (ends("y") && vowelinstem()) { b[k] = 'i'; dirty = true; } } /* step3() maps double suffices to single ones. so -ization ( = -ize plus -ation) maps to -ize etc. note that the string before the suffix must give m() > 0. */ private final void step3() { if (k == k0) return; /* For Bug 1 */ switch (b[k-1]) { case 'a': if (ends("ational")) { r("ate"); break; } if (ends("tional")) { r("tion"); break; } break; case 'c': if (ends("enci")) { r("ence"); break; } if (ends("anci")) { r("ance"); break; } break; case 'e': if (ends("izer")) { r("ize"); break; } break; case 'l': if (ends("bli")) { r("ble"); break; } if (ends("alli")) { r("al"); break; } if (ends("entli")) { r("ent"); break; } if (ends("eli")) { r("e"); break; } if (ends("ousli")) { r("ous"); break; } break; case 'o': if (ends("ization")) { r("ize"); break; } if (ends("ation")) { r("ate"); break; } if (ends("ator")) { r("ate"); break; } break; case 's': if (ends("alism")) { r("al"); break; } if (ends("iveness")) { r("ive"); break; } if (ends("fulness")) { r("ful"); break; } if (ends("ousness")) { r("ous"); break; } break; case 't': if (ends("aliti")) { r("al"); break; } if (ends("iviti")) { r("ive"); break; } if (ends("biliti")) { r("ble"); break; } break; case 'g': if (ends("logi")) { r("log"); break; } } } /* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */ private final void step4() { switch (b[k]) { case 'e': if (ends("icate")) { r("ic"); break; } if (ends("ative")) { r(""); break; } if (ends("alize")) { r("al"); break; } break; case 'i': if (ends("iciti")) { r("ic"); break; } break; case 'l': if (ends("ical")) { r("ic"); break; } if (ends("ful")) { r(""); break; } break; case 's': if (ends("ness")) { r(""); break; } break; } } /* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */ private final void step5() { if (k == k0) return; /* for Bug 1 */ switch (b[k-1]) { case 'a': if (ends("al")) break; return; case 'c': if (ends("ance")) break; if (ends("ence")) break; return; case 'e': if (ends("er")) break; return; case 'i': if (ends("ic")) break; return; case 'l': if (ends("able")) break; if (ends("ible")) break; return; case 'n': if (ends("ant")) break; if (ends("ement")) break; if (ends("ment")) break; /* element etc. not stripped before the m */ if (ends("ent")) break; return; case 'o': if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break; /* j >= 0 fixes Bug 2 */ if (ends("ou")) break; return; /* takes care of -ous */ case 's': if (ends("ism")) break; return; case 't': if (ends("ate")) break; if (ends("iti")) break; return; case 'u': if (ends("ous")) break; return; case 'v': if (ends("ive")) break; return; case 'z': if (ends("ize")) break; return; default: return; } if (m() > 1) k = j; } /* step6() removes a final -e if m() > 1. */ private final void step6() { j = k; if (b[k] == 'e') { int a = m(); if (a > 1 || a == 1 && !cvc(k-1)) k--; } if (b[k] == 'l' && doublec(k) && m() > 1) k--; } /** * Stem a word provided as a String. Returns the result as a String. */ public String stem(String s) { if (stem(s.toCharArray(), s.length())) return toString(); else return s; } /** Stem a word contained in a char[]. Returns true if the stemming process * resulted in a word different from the input. You can retrieve the * result with getResultLength()/getResultBuffer() or toString(). */ public boolean stem(char[] word) { return stem(word, word.length); } /** Stem a word contained in a portion of a char[] array. Returns * true if the stemming process resulted in a word different from * the input. You can retrieve the result with * getResultLength()/getResultBuffer() or toString(). */ public boolean stem(char[] wordBuffer, int offset, int wordLen) { reset(); if (b.length < wordLen) { char[] new_b = new char[wordLen + EXTRA]; b = new_b; } System.arraycopy(wordBuffer, offset, b, 0, wordLen); i = wordLen; return stem(0); } /** Stem a word contained in a leading portion of a char[] array. * Returns true if the stemming process resulted in a word different * from the input. You can retrieve the result with * getResultLength()/getResultBuffer() or toString(). */ public boolean stem(char[] word, int wordLen) { return stem(word, 0, wordLen); } /** Stem the word placed into the Stemmer buffer through calls to add(). * Returns true if the stemming process resulted in a word different * from the input. You can retrieve the result with * getResultLength()/getResultBuffer() or toString(). */ public boolean stem() { return stem(0); } public boolean stem(int i0) { k = i - 1; k0 = i0; if (k > k0+1) { step1(); step2(); step3(); step4(); step5(); step6(); } // Also, a word is considered dirty if we lopped off letters // Thanks to Ifigenia Vairelles for pointing this out. if (i != k+1) dirty = true; i = k+1; return dirty; } /** Test program for demonstrating the Stemmer. It reads a file and * stems each word, writing the result to standard out. * Usage: Stemmer file-name */ public static void main(String[] args) { PorterStemmer s = new PorterStemmer(); for (int i = 0; i < args.length; i++) { try { InputStream in = new FileInputStream(args[i]); byte[] buffer = new byte[1024]; int bufferLen, offset, ch; bufferLen = in.read(buffer); offset = 0; s.reset(); while(true) { if (offset < bufferLen) ch = buffer[offset++]; else { bufferLen = in.read(buffer); offset = 0; if (bufferLen < 0) ch = -1; else ch = buffer[offset++]; } if (Character.isLetter((char) ch)) { s.add(Character.toLowerCase((char) ch)); } else { s.stem(); System.out.print(s.toString()); s.reset(); if (ch < 0) break; else { System.out.print((char) ch); } } } in.close(); } catch (IOException e) { System.out.println("error reading " + args[i]); } } } }
Novartis/ontobrowser
src/main/java/com/novartis/pcs/ontology/service/mapper/PorterStemmer.java
Java
apache-2.0
13,830
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # 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. # # Generated code. DO NOT EDIT! # # Snippet for GetTagKey # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-resourcemanager # [START cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async] from google.cloud import resourcemanager_v3 async def sample_get_tag_key(): # Create a client client = resourcemanager_v3.TagKeysAsyncClient() # Initialize request argument(s) request = resourcemanager_v3.GetTagKeyRequest( name="name_value", ) # Make the request response = await client.get_tag_key(request=request) # Handle the response print(response) # [END cloudresourcemanager_v3_generated_TagKeys_GetTagKey_async]
googleapis/python-resource-manager
samples/generated_samples/cloudresourcemanager_v3_generated_tag_keys_get_tag_key_async.py
Python
apache-2.0
1,477
<?php /** * @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com) */ namespace Magento\Sales\Model\Grid; class CollectionUpdater implements \Magento\Framework\View\Layout\Argument\UpdaterInterface { /** * @var \Magento\Framework\Registry */ protected $registryManager; /** * @param \Magento\Framework\Registry $registryManager */ public function __construct(\Magento\Framework\Registry $registryManager) { $this->registryManager = $registryManager; } /** * Update grid collection according to chosen order * * @param \Magento\Sales\Model\Resource\Transaction\Grid\Collection $argument * @return \Magento\Sales\Model\Resource\Transaction\Grid\Collection */ public function update($argument) { $order = $this->registryManager->registry('current_order'); if ($order) { $argument->setOrderFilter($order->getId()); } $argument->addOrderInformation(['increment_id']); return $argument; } }
webadvancedservicescom/magento
app/code/Magento/Sales/Model/Grid/CollectionUpdater.php
PHP
apache-2.0
1,062
// Copyright (C) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package resolve import ( "context" "fmt" "github.com/google/gapid/core/data/id" "github.com/google/gapid/core/log" "github.com/google/gapid/gapis/api" "github.com/google/gapid/gapis/api/sync" "github.com/google/gapid/gapis/capture" "github.com/google/gapid/gapis/database" "github.com/google/gapid/gapis/resolve/initialcmds" "github.com/google/gapid/gapis/service/path" ) // ResolvedResources contains all of the resolved resources for a // particular point in the trace. type ResolvedResources struct { resourceMap api.ResourceMap resources map[id.ID]api.Resource resourceData map[id.ID]interface{} } // Resolve builds a ResolvedResources object for all of the resources // at the path r.After func (r *AllResourceDataResolvable) Resolve(ctx context.Context) (interface{}, error) { ctx = SetupContext(ctx, r.After.Capture, r.Config) resources, err := buildResources(ctx, r.After) if err != nil { return nil, err } return resources, nil } func buildResources(ctx context.Context, p *path.Command) (*ResolvedResources, error) { cmdIdx := p.Indices[0] capture, err := capture.Resolve(ctx) if err != nil { return nil, err } allCmds, err := Cmds(ctx, p.Capture) if err != nil { return nil, err } s, err := SyncData(ctx, p.Capture) if err != nil { return nil, err } cmds, err := sync.MutationCmdsFor(ctx, p.Capture, s, allCmds, api.CmdID(cmdIdx), p.Indices[1:], false) if err != nil { return nil, err } initialCmds, ranges, err := initialcmds.InitialCommands(ctx, p.Capture) if err != nil { return nil, err } state := capture.NewUninitializedState(ctx).ReserveMemory(ranges) var currentCmdIndex uint64 var currentCmdResourceCount int idMap := api.ResourceMap{} resources := make(map[id.ID]api.Resource) state.OnResourceCreated = func(r api.Resource) { currentCmdResourceCount++ i := genResourceID(currentCmdIndex, currentCmdResourceCount) idMap[r] = i resources[i] = r } api.ForeachCmd(ctx, initialCmds, func(ctx context.Context, id api.CmdID, cmd api.Cmd) error { if err := cmd.Mutate(ctx, id, state, nil, nil); err != nil { log.W(ctx, "Get resources at %v: Initial cmd [%v]%v - %v", p.Indices, id, cmd, err) } return nil }) err = api.ForeachCmd(ctx, cmds, func(ctx context.Context, id api.CmdID, cmd api.Cmd) error { currentCmdResourceCount = 0 currentCmdIndex = uint64(id) cmd.Mutate(ctx, id, state, nil, nil) return nil }) if err != nil { return nil, err } resourceData := make(map[id.ID]interface{}) for k, v := range resources { res, err := v.ResourceData(ctx, state) if err != nil { resourceData[k] = err } else { resourceData[k] = res } } return &ResolvedResources{idMap, resources, resourceData}, nil } // ResourceData resolves the data of the specified resource at the specified // point in the capture. func ResourceData(ctx context.Context, p *path.ResourceData, r *path.ResolveConfig) (interface{}, error) { obj, err := database.Build(ctx, &ResourceDataResolvable{Path: p, Config: r}) if err != nil { return nil, err } return obj, nil } // Resolve implements the database.Resolver interface. func (r *ResourceDataResolvable) Resolve(ctx context.Context) (interface{}, error) { resources, err := database.Build(ctx, &AllResourceDataResolvable{After: r.Path.After, Config: r.Config}) if err != nil { return nil, err } res, ok := resources.(*ResolvedResources) if !ok { return nil, fmt.Errorf("Cannot resolve resources at command: %v", r.Path.After) } id := r.Path.ID.ID() if val, ok := res.resourceData[id]; ok { if err, isErr := val.(error); isErr { return nil, err } return val, nil } return nil, fmt.Errorf("Cannot find resource with id: %v", id) }
Qining/gapid
gapis/resolve/resource_data.go
GO
apache-2.0
4,307
<style type="text/css"> .placeholder { display: none; } </style> <div class="contentRight"> <div class="sanpham" style=" height: 100%; margin-top: 0"> <div class="row" style="margin: 5px"> <div class="page-header"> <h2><?php echo lang('form_checkout'); ?></h2> </div> <?php if (validation_errors()): ?> <div class="alert alert-error"> <a class="close" data-dismiss="alert">×</a> <?php echo validation_errors(); ?> </div> <?php endif; ?> <script type="text/javascript"> $(document).ready(function () { //if we support placeholder text, remove all the labels if (!supports_placeholder()) { $('.placeholder').show(); } <?php // Restore previous selection, if we are on a validation page reload $zone_id = set_value('zone_id'); echo "\$('#zone_id').val($zone_id);\n"; ?> }); function supports_placeholder() { return 'placeholder' in document.createElement('input'); } </script> <script type="text/javascript"> $(document).ready(function () { $('#country_id').change(function () { populate_zone_menu(); }); }); // context is ship or bill function populate_zone_menu(value) { $.post('<?php echo site_url('locations/get_zone_menu');?>', {id: $('#country_id').val()}, function (data) { $('#zone_id').html(data); }); } </script> <?php /* Only show this javascript if the user is logged in */ ?> <?php if ($this->Customer_model->is_logged_in(false, false)) : ?> <script type="text/javascript"> <?php $add_list = array(); foreach($customer_addresses as $row) { // build a new array $add_list[$row['id']] = $row['field_data']; } $add_list = json_encode($add_list); echo "eval(addresses=$add_list);"; ?> function populate_address(address_id) { if (address_id == '') { return; } // - populate the fields $.each(addresses[address_id], function (key, value) { $('.address[name=' + key + ']').val(value); // repopulate the zone menu and set the right value if we change the country if (key == 'zone_id') { zone_id = value; } }); // repopulate the zone list, set the right value, then copy all to billing $.post('<?php echo site_url('locations/get_zone_menu');?>', {id: $('#country_id').val()}, function (data) { $('#zone_id').html(data); $('#zone_id').val(zone_id); }); } </script> <?php endif; ?> <?php $countries = $this->Location_model->get_countries_menu(); if (!empty($customer[$address_form_prefix . '_address']['country_id'])) { $zone_menu = $this->Location_model->get_zones_menu($customer[$address_form_prefix . '_address']['country_id']); } else { $zone_menu = array('' => '') + $this->Location_model->get_zones_menu(array_shift(array_keys($countries))); } //form elements $company = array('placeholder' => lang('address_company'), 'class' => 'address span8', 'name' => 'company', 'value' => set_value('company', @$customer[$address_form_prefix . '_address']['company'])); $address1 = array('placeholder' => lang('address1'), 'class' => 'address span8', 'name' => 'address1', 'value' => set_value('address1', @$customer[$address_form_prefix . '_address']['address1'])); $address2 = array('placeholder' => lang('address2'), 'class' => 'address span8', 'name' => 'address2', 'value' => set_value('address2', @$customer[$address_form_prefix . '_address']['address2'])); $first = array('placeholder' => lang('address_firstname'), 'class' => 'address span4', 'name' => 'firstname', 'value' => set_value('firstname', @$customer[$address_form_prefix . '_address']['firstname'])); $last = array('placeholder' => lang('address_lastname'), 'class' => 'address span4', 'name' => 'lastname', 'value' => set_value('lastname', @$customer[$address_form_prefix . '_address']['lastname'])); $email = array('placeholder' => lang('address_email'), 'class' => 'address span4', 'name' => 'email', 'value' => set_value('email', @$customer[$address_form_prefix . '_address']['email'])); $phone = array('placeholder' => lang('address_phone'), 'class' => 'address span4', 'name' => 'phone', 'value' => set_value('phone', @$customer[$address_form_prefix . '_address']['phone'])); $city = array('placeholder' => lang('address_city'), 'class' => 'address span3', 'name' => 'city', 'value' => set_value('city', @$customer[$address_form_prefix . '_address']['city'])); $zip = array('placeholder' => lang('address_zip'), 'maxlength' => '10', 'class' => 'address span2', 'name' => 'zip', 'value' => set_value('zip', @$customer[$address_form_prefix . '_address']['zip'])); ?> <?php //post to the correct place. echo ($address_form_prefix == 'bill') ? form_open('checkout/step_1', 'style = "padding-left: 60px;"') : form_open('checkout/shipping_address', 'style = "padding-left: 60px;"');?> <div class="row"> <?php // Address form ?> <div class="span8"> <div class="row"> <div class="span4"> <h2 style="margin:0px;"> <?php echo ($address_form_prefix == 'bill') ? lang('address') : lang('shipping_address'); ?> </h2> </div> <div class="span4"> <?php if ($this->Customer_model->is_logged_in(false, false)) : ?> <button class="btn btn-inverse pull-right" onclick="$('#address_manager').modal().modal('show');" type="button"><i class="icon-envelope icon-white"></i> <?php echo lang('choose_address'); ?> </button> <?php endif; ?> </div> </div> <div class="row"> <div class="span8"> <label class="placeholder"><?php echo lang('address_company'); ?></label> <?php echo form_input($company); ?> </div> </div> <div class="row"> <div class="span4"> <label class="placeholder"><?php echo lang('address_firstname'); ?><b class="r"> *</b></label> <?php echo form_input($first); ?> </div> <div class="span4"> <label class="placeholder"><?php echo lang('address_lastname'); ?><b class="r"> *</b></label> <?php echo form_input($last); ?> </div> </div> <div class="row"> <div class="span4"> <label class="placeholder"><?php echo lang('address_email'); ?><b class="r"> *</b></label> <?php echo form_input($email); ?> </div> <div class="span4"> <label class="placeholder"><?php echo lang('address_phone'); ?><b class="r"> *</b></label> <?php echo form_input($phone); ?> </div> </div> <div class="row"> <div class="span8"> <label class="placeholder"><?php echo lang('address_country'); ?><b class="r"> *</b></label> <?php echo form_dropdown('country_id', $countries, @$customer[$address_form_prefix . '_address']['country_id'], 'id="country_id" class="address span8"'); ?> </div> </div> <div class="row"> <div class="span8"> <label class="placeholder"><?php echo lang('address1'); ?><b class="r"> *</b></label> <?php echo form_input($address1); ?> </div> </div> <div class="row"> <div class="span8"> <label class="placeholder"><?php echo lang('address2'); ?></label> <?php echo form_input($address2); ?> </div> </div> <div class="row"> <div class="span3"> <label class="placeholder"><?php echo lang('address_city'); ?><b class="r"> *</b></label> <?php echo form_input($city); ?> </div> <div class="span3"> <label class="placeholder"><?php echo lang('address_state'); ?><b class="r"> *</b></label> <?php echo form_dropdown('zone_id', $zone_menu, @$customer[$address_form_prefix . '_address']['zone_id'], 'id="zone_id" class="address span3" ');?> </div> <div class="span2"> <label class="placeholder"><?php echo lang('address_zip'); ?><b class="r"> *</b></label> <?php echo form_input($zip); ?> </div> </div> <?php if ($address_form_prefix == 'bill') : ?> <div class="row"> <div class="span3"> <label class="checkbox inline" for="use_shipping"> <?php echo form_checkbox(array('name' => 'use_shipping', 'value' => 'yes', 'id' => 'use_shipping', 'checked' => $use_shipping)) ?> <?php echo lang('ship_to_address') ?> </label> </div> </div> <?php endif ?> <div class="row"> <div class="span8"> <?php if ($address_form_prefix == 'ship') : ?> <input class="btn btn-block btn-large btn-secondary" type="button" value="<?php echo lang('form_previous'); ?>" onclick="window.location='<?php echo base_url('checkout/step_1') ?>'"/> <?php endif; ?> <input class="btn btn-block btn-large btn-primary" type="submit" value="<?php echo lang('form_continue'); ?>"/> </div> </div> </div> </div> </form> </div> </div> </div> <?php if ($this->Customer_model->is_logged_in(false, false)) : ?> <div class="modal hide" id="address_manager"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h3><?php echo lang('your_addresses'); ?></h3> </div> <div class="modal-body"> <p> <table class="table table-striped"> <?php $c = 1; foreach ($customer_addresses as $a):?> <tr> <td> <?php $b = $a['field_data']; echo nl2br(format_address($b)); ?> </td> <td style="width:100px;"><input type="button" class="btn btn-primary choose_address pull-right" onclick="populate_address(<?php echo $a['id']; ?>);" data-dismiss="modal" value="<?php echo lang('form_choose'); ?>"/></td> </tr> <?php endforeach; ?> </table> </p> </div> <div class="modal-footer"> <a href="#" class="btn" data-dismiss="modal">Close</a> </div> </div> <?php endif; ?>
CaoLP/tranhviet
Code/tranhviet/gocart/themes/default/views/checkout/address_form.php
PHP
apache-2.0
11,288
/* * Copyright 2014-2021 Sayi * * 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.deepoove.poi.xwpf; import java.util.List; import org.apache.poi.xwpf.usermodel.IRunBody; import org.apache.poi.xwpf.usermodel.XWPFFieldRun; import org.apache.poi.xwpf.usermodel.XWPFHyperlinkRun; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.xmlbeans.XmlObject; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField; public class ParagraphContext implements RunBodyContext { private XWPFParagraphWrapper paragraphWrapper; public ParagraphContext(XWPFParagraphWrapper paragraphWrapper) { this.paragraphWrapper = paragraphWrapper; } @Override public IRunBody getTarget() { return paragraphWrapper.getParagraph(); } @Override public List<XWPFRun> getRuns() { return paragraphWrapper.getParagraph().getRuns(); } @Override public void setAndUpdateRun(XWPFRun xwpfRun, XWPFRun sourceRun, int insertPostionCursor) { paragraphWrapper.setAndUpdateRun(xwpfRun, sourceRun, insertPostionCursor); } @Override public XWPFRun insertNewRun(XWPFRun xwpfRun, int insertPostionCursor) { if (xwpfRun instanceof XWPFHyperlinkRun) { return paragraphWrapper.insertNewHyperLinkRun(insertPostionCursor, ""); } else if (xwpfRun instanceof XWPFFieldRun) { return paragraphWrapper.insertNewField(insertPostionCursor); } else { return paragraphWrapper.insertNewRun(insertPostionCursor); } } @Override public XWPFRun createRun(XWPFRun xwpfRun, IRunBody p) { if (xwpfRun instanceof XWPFHyperlinkRun) { return new XWPFHyperlinkRun((CTHyperlink) ((XWPFHyperlinkRun) xwpfRun).getCTHyperlink().copy(), (CTR) ((XWPFHyperlinkRun) xwpfRun).getCTR().copy(), p); } else if (xwpfRun instanceof XWPFFieldRun) { return new XWPFFieldRun((CTSimpleField) ((XWPFFieldRun) xwpfRun).getCTField().copy(), (CTR) ((XWPFFieldRun) xwpfRun).getCTR().copy(), p); } else { return new XWPFRun((CTR) xwpfRun.getCTR().copy(), p); } } @Override public XWPFRun createRun(XmlObject object, IRunBody p) { if (object instanceof CTHyperlink) { return new XWPFHyperlinkRun((CTHyperlink) object, ((CTHyperlink) object).getRArray(0), p); } else if (object instanceof CTSimpleField) { return new XWPFFieldRun((CTSimpleField) object, ((CTSimpleField) object).getRArray(0), p); } else { return new XWPFRun((CTR) object, p); } } @Override public void removeRun(int pos) { paragraphWrapper.removeRun(pos); } }
Sayi/poi-tl
poi-tl/src/main/java/com/deepoove/poi/xwpf/ParagraphContext.java
Java
apache-2.0
3,416
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.portable; import org.apache.ignite.internal.portable.streams.*; import org.apache.ignite.internal.util.*; import org.apache.ignite.internal.util.typedef.internal.*; import sun.misc.*; import static org.apache.ignite.IgniteSystemProperties.*; /** * Thread-local memory allocator. */ public class PortableThreadLocalMemoryAllocator implements PortableMemoryAllocator { /** Memory allocator instance. */ public static final PortableThreadLocalMemoryAllocator THREAD_LOCAL_ALLOC = new PortableThreadLocalMemoryAllocator(); /** Holders. */ private static final ThreadLocal<ByteArrayHolder> holders = new ThreadLocal<>(); /** Unsafe instance. */ protected static final Unsafe UNSAFE = GridUnsafe.unsafe(); /** Array offset: byte. */ protected static final long BYTE_ARR_OFF = UNSAFE.arrayBaseOffset(byte[].class); /** * Ensures singleton. */ private PortableThreadLocalMemoryAllocator() { // No-op. } /** {@inheritDoc} */ @Override public byte[] allocate(int size) { ByteArrayHolder holder = holders.get(); if (holder == null) holders.set(holder = new ByteArrayHolder()); if (holder.acquired) return new byte[size]; holder.acquired = true; if (holder.data == null || size > holder.data.length) holder.data = new byte[size]; return holder.data; } /** {@inheritDoc} */ @Override public byte[] reallocate(byte[] data, int size) { ByteArrayHolder holder = holders.get(); assert holder != null; byte[] newData = new byte[size]; if (holder.data == data) holder.data = newData; UNSAFE.copyMemory(data, BYTE_ARR_OFF, newData, BYTE_ARR_OFF, data.length); return newData; } /** {@inheritDoc} */ @Override public void release(byte[] data, int maxMsgSize) { ByteArrayHolder holder = holders.get(); assert holder != null; if (holder.data != data) return; holder.maxMsgSize = maxMsgSize; holder.acquired = false; holder.shrink(); } /** {@inheritDoc} */ @Override public long allocateDirect(int size) { return 0; } /** {@inheritDoc} */ @Override public long reallocateDirect(long addr, int size) { return 0; } /** {@inheritDoc} */ @Override public void releaseDirect(long addr) { // No-op } /** * Checks whether a thread-local array is acquired or not. * The function is used by Unit tests. * * @return {@code true} if acquired {@code false} otherwise. */ public boolean isThreadLocalArrayAcquired() { ByteArrayHolder holder = holders.get(); return holder != null && holder.acquired; } /** * Thread-local byte array holder. */ private static class ByteArrayHolder { /** */ private static final Long CHECK_FREQ = Long.getLong(IGNITE_MARSHAL_BUFFERS_RECHECK, 10000); /** Data array */ private byte[] data; /** Max message size detected between checks. */ private int maxMsgSize; /** Last time array size is checked. */ private long lastCheck = U.currentTimeMillis(); /** Whether the holder is acquired or not. */ private boolean acquired; /** * Shrinks array size if needed. */ private void shrink() { long now = U.currentTimeMillis(); if (now - lastCheck >= CHECK_FREQ) { int halfSize = data.length >> 1; if (maxMsgSize < halfSize) data = new byte[halfSize]; lastCheck = now; } } } }
avinogradovgg/ignite
modules/core/src/main/java/org/apache/ignite/internal/portable/PortableThreadLocalMemoryAllocator.java
Java
apache-2.0
4,612
var addressBar = element(by.css("#addressBar")), url = 'http://www.example.com/base/ratingList.html#!/path?a=b#h'; it("should show fake browser info on load", function(){ expect(addressBar.getAttribute('value')).toBe(url); expect(element(by.binding('$location.protocol()')).getText()).toBe('http'); expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com'); expect(element(by.binding('$location.port()')).getText()).toBe('80'); expect(element(by.binding('$location.path()')).getText()).toBe('/path'); expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}'); expect(element(by.binding('$location.hash()')).getText()).toBe('h'); }); it("should change $location accordingly", function(){ var navigation = element.all(by.css("#navigation a")); navigation.get(0).click(); expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/ratingList.html#!/first?a=b"); expect(element(by.binding('$location.protocol()')).getText()).toBe('http'); expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com'); expect(element(by.binding('$location.port()')).getText()).toBe('80'); expect(element(by.binding('$location.path()')).getText()).toBe('/first'); expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}'); expect(element(by.binding('$location.hash()')).getText()).toBe(''); navigation.get(1).click(); expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/ratingList.html#!/sec/ond?flag#hash"); expect(element(by.binding('$location.protocol()')).getText()).toBe('http'); expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com'); expect(element(by.binding('$location.port()')).getText()).toBe('80'); expect(element(by.binding('$location.path()')).getText()).toBe('/sec/ond'); expect(element(by.binding('$location.search()')).getText()).toBe('{"flag":true}'); expect(element(by.binding('$location.hash()')).getText()).toBe('hash'); });
lvkklemo/shopApp
library/angular-1.4.9/docs/examples/example-location-hashbang-mode/protractor.js
JavaScript
apache-2.0
2,038
/* * Copyright 2006-2011 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.kew.xml.export; import org.kuali.rice.core.api.CoreApiServiceLocator; import org.kuali.rice.kew.export.KewExportDataSet; import org.kuali.rice.kim.api.group.Group; import org.kuali.rice.kim.api.group.GroupService; import org.kuali.rice.kim.api.identity.IdentityService; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.kuali.rice.test.BaselineTestCase; import java.util.List; import static org.junit.Assert.assertTrue; /** * This is a description of what this class does - jjhanso don't forget to fill this in. * * @author Kuali Rice Team (rice.collab@kuali.org) * */ @BaselineTestCase.BaselineMode(BaselineTestCase.Mode.NONE) public class GroupXmlExporterTest extends XmlExporterTestCase { /** * This overridden method ... * * @see org.kuali.rice.kew.xml.export.XmlExporterTestCase#assertExport() */ @Override protected void assertExport() throws Exception { IdentityService identityService = KimApiServiceLocator.getIdentityService(); GroupService groupService = KimApiServiceLocator.getGroupService(); List<? extends Group> oldGroups = groupService.getGroupsByPrincipalId( identityService.getPrincipalByPrincipalName("ewestfal").getPrincipalId()); KewExportDataSet dataSet = new KewExportDataSet(); dataSet.getGroups().addAll(oldGroups); byte[] xmlBytes = CoreApiServiceLocator.getXmlExporterService().export(dataSet.createExportDataSet()); assertTrue("XML should be non empty.", xmlBytes != null && xmlBytes.length > 0); StringBuffer output = new StringBuffer(); for (int i=0; i < xmlBytes.length; i++){ output.append((char)xmlBytes[i]); } System.out.print(output.toString()); // now clear the tables //ClearDatabaseLifecycle clearLifeCycle = new ClearDatabaseLifecycle(); //clearLifeCycle.getTablesToClear().add("EN_RULE_BASE_VAL_T"); //clearLifeCycle.getTablesToClear().add("EN_RULE_ATTRIB_T"); //clearLifeCycle.getTablesToClear().add("EN_RULE_TMPL_T"); //clearLifeCycle.getTablesToClear().add("EN_DOC_TYP_T"); //clearLifeCycle.start(); //new ClearCacheLifecycle().stop(); //KimImplServiceLocator.getGroupService(). // import the exported xml //loadXmlStream(new BufferedInputStream(new ByteArrayInputStream(xmlBytes))); /* List newRules = KEWServiceLocator.getRuleService().fetchAllRules(true); assertEquals("Should have same number of old and new Rules.", oldRules.size(), newRules.size()); for (Iterator iterator = oldRules.iterator(); iterator.hasNext();) { RuleBaseValues oldRule = (RuleBaseValues) iterator.next(); boolean foundRule = false; for (Iterator iterator2 = newRules.iterator(); iterator2.hasNext();) { RuleBaseValues newRule = (RuleBaseValues) iterator2.next(); if (oldRule.getDescription().equals(newRule.getDescription())) { assertRuleExport(oldRule, newRule); foundRule = true; } } assertTrue("Could not locate the new rule for description " + oldRule.getDescription(), foundRule); } */ } }
sbower/kuali-rice-1
it/kew/src/test/java/org/kuali/rice/kew/xml/export/GroupXmlExporterTest.java
Java
apache-2.0
4,009
/** * Copyright 2015 Smart Society Services B.V. * * 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 */ package com.alliander.osgp.core.infra.jms.protocol.in; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.jms.ConnectionFactory; import org.apache.activemq.command.ActiveMQQueue; import org.springframework.beans.factory.InitializingBean; import org.springframework.jms.core.JmsTemplate; import com.alliander.osgp.core.infra.jms.JmsTemplateSettings; import com.alliander.osgp.domain.core.entities.ProtocolInfo; public class ProtocolResponseMessageJmsTemplateFactory implements InitializingBean { private final ConnectionFactory connectionFactory; private final JmsTemplateSettings jmsTemplateSettings; private Map<String, JmsTemplate> jmsTemplateMap = new HashMap<>(); public ProtocolResponseMessageJmsTemplateFactory(final ConnectionFactory connectionFactory, final JmsTemplateSettings jmsTemplateSettings, final List<ProtocolInfo> protocolInfos) { this.connectionFactory = connectionFactory; this.jmsTemplateSettings = jmsTemplateSettings; for (final ProtocolInfo protocolInfo : protocolInfos) { this.jmsTemplateMap.put(protocolInfo.getKey(), this.createJmsTemplate(protocolInfo)); } } public JmsTemplate getJmsTemplate(final String key) { return this.jmsTemplateMap.get(key); } @Override public void afterPropertiesSet() { for (final JmsTemplate jmsTemplate : this.jmsTemplateMap.values()) { jmsTemplate.afterPropertiesSet(); } } private JmsTemplate createJmsTemplate(final ProtocolInfo protocolInfo) { final JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setDefaultDestination(new ActiveMQQueue(protocolInfo.getOutgoingProtocolResponsesQueue())); // Enable the use of deliveryMode, priority, and timeToLive jmsTemplate.setExplicitQosEnabled(this.jmsTemplateSettings.isExplicitQosEnabled()); jmsTemplate.setTimeToLive(this.jmsTemplateSettings.getTimeToLive()); jmsTemplate.setDeliveryPersistent(this.jmsTemplateSettings.isDeliveryPersistent()); jmsTemplate.setConnectionFactory(this.connectionFactory); return jmsTemplate; } }
wernerb/Platform
osgp-core/src/main/java/com/alliander/osgp/core/infra/jms/protocol/in/ProtocolResponseMessageJmsTemplateFactory.java
Java
apache-2.0
2,471
package com.codedpoetry.maven.dockerplugin.templates; import java.io.StringWriter; import java.util.Map; public interface TemplateRenderer { StringWriter renderTemplate(String templateUrl, Map context); }
fllaca/docker-maven-plugin
src/main/java/com/codedpoetry/maven/dockerplugin/templates/TemplateRenderer.java
Java
apache-2.0
209
package st.domain.quitanda.client.model.contract; /** * Created by Daniel Costa at 8/27/16. * Using user computer xdata */ public interface TypePayment { public int getDataBaseId(); }
danie555costa/Quitanda
app/src/main/java/st/domain/quitanda/client/model/contract/TypePayment.java
Java
apache-2.0
192