content
stringlengths
10
4.9M
def save_dataframe_as_CSV(dataframe,csv_filepath): csv_header= ['Speaker', 'Time_Stamp', 'Transcript', 'Turn-Taking Facilitation', 'Metacognitive Modeling Questions', 'Behavior Management Questions', 'Teacher Open-Ended S/Q', 'Teacher Close-Ended S/Q', 'Student Open-Ended S/Q', 'Student Close-Ended S/Q', 'Student Close-Ended Response', 'Student Open-Ended Response', 'Student Explanation + Evidence', 'Whole class discussion', 'Lecture', 'Small group + Instructor', 'Individual Work', 'Pair Work', 'Other'] df_utt_types=["Utt_Turn_Taking","Metacognitive_Modelling","Utt_Behavior","Utt_Teacher_OpenQ","Utt_Teacher_CloseQ","Utt_Student_OpenQ","Utt_Student_CloseQ","Utt_Student_CloseR","Utt_Student_OpenR","Utt_Student_ExpEvi"] df_part_types=["Part_Discussion","Part_Lecture","Part_Small_Group","Part_Individual","Part_Pairs","Part_Other"] with open(csv_filepath,"w+",encoding = 'utf-8') as output_csvfile: writer=csv.writer(output_csvfile,delimiter=",") writer.writerow(csv_header) speaker_index=dataframe.columns.get_loc("Speaker") speakers=dataframe.iloc[:,speaker_index].values timestamp_index=dataframe.columns.get_loc("Time_Stamp") timestamps=dataframe.iloc[:,timestamp_index].values utterance_index=dataframe.columns.get_loc("Utterance_String") utterances=dataframe.iloc[:,utterance_index].values predictions=[] for utt_type in df_utt_types: u_type_index=dataframe.columns.get_loc(utt_type) values=dataframe.iloc[:,u_type_index].values values=["1" if x else " " for x in values] predictions.append(values) participation_types=[] for part_type in df_part_types: p_type_index=dataframe.columns.get_loc(part_type) values=dataframe.iloc[:,p_type_index].values values=["1" if x else " " for x in values] participation_types.append(values) for i, speaker in enumerate(speakers): if timestamps[i]=="":speaker="" row=[speaker,timestamps[i],utterances[i]] for u_type in predictions: row.append(u_type[i]) for p_type in participation_types: row.append(p_type[i]) writer.writerow(row) print("File created:"+csv_filepath)
def create_ocp_node_label_line_item(self, report_period, report, node=None, node_labels=None): table_name = OCP_REPORT_TABLE_MAP["node_label_line_item"] data = self.create_columns_for_table(table_name) data["report_period_id"] = report_period.id data["report_id"] = report.id if node: data["node"] = node with OCPReportDBAccessor(self.schema) as accessor: return accessor.create_db_object(table_name, data)
package spec // NewEmptySERVICE - return an empty SERVICE, all fields are initialized func NewEmptySERVICE() SERVICE { return SERVICE{ Name: "", Description: "", Documentation: "", Executable: "", Args: []string{}, WorkingDirectory: "", Environment: map[string]string{}, DependsOn: []ServiceType{}, DependsOnOverrideByOS: map[OsType][]ServiceType{}, DependsOnOverrideByInit: map[InitType][]ServiceType{}, Start: StartConfig{}, Logging: LoggingConfig{ StdOut: LoggingConfigOut{ Disabled: true, }, StdErr: LoggingConfigOut{ Disabled: true, }, }, Credentials: CredentialsConfig{}, } } // KnownOsTypes - var KnownOsTypes = []OsType{ OsFreeBSD, OsLinux, OsMacOS, OsWindows, OsOpenBSD, OsNetBSD, } // KnownInitTypes - var KnownInitTypes = []InitType{ InitRC_D, InitSystemd, InitSystemV, InitUpstart, InitUknown, } // KnownServiceTypes - var KnownServiceTypes = []ServiceType{ ServiceNetwork, ServiceBluetooth, } // ServiceMappings - var ServiceMappings = map[InitType]map[ServiceType]string{ // based on /etc/rc.d/* and /usr/local/etc/rc.d/* InitRC_D: { ServiceNetwork: "NETWORKING", ServiceBluetooth: "bluetooth", }, // based on /etc/systemd/system/* and /usr/lib/systemd/system/* InitSystemd: { ServiceNetwork: "network.target", ServiceBluetooth: "bluetooth.target", }, }
<reponame>Bob-King/WifiTrafficAnalyzer<gh_stars>1-10 package org.mars.kjli.analyzer; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; class ProbeRequestReader implements Closeable { public ProbeRequestReader(InputStream is) { mBufferedReader = new BufferedReader(new InputStreamReader(is)); } public ProbeRequestRecord readProbeRequestRecord() throws IOException { final String line = mBufferedReader.readLine(); if (line == null) { return null; } Matcher matcher = PROBE_REQUEST_RECORD_LINE_PATTERN.matcher(line); if (!matcher.find()) { return null; } ProbeRequestRecord record = new ProbeRequestRecord(); record.ra = Long.valueOf(Utils.macAddress2Long(matcher.group(1))); record.ta = Long.valueOf(Utils.macAddress2Long(matcher.group(2))); record.tsf = Long.valueOf(matcher.group(3)); record.seq = Integer.valueOf(matcher.group(4)); record.rssi = Byte.valueOf(matcher.group(5)); return record; } private final BufferedReader mBufferedReader; private static final Pattern PROBE_REQUEST_RECORD_LINE_PATTERN = Pattern .compile("ra=((?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2})" + " ta=((?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2})" + " tsf=([1-9][0-9]*|0)" + " seq=([1-9][0-9]*|0)" + " rssi=(-[1-9][0-9]*)"); @Override public void close() throws IOException { mBufferedReader.close(); } }
/** * Launches an activity that allows user to select a device to use */ public void selectDevice() { Intent serverIntent = new Intent(this, DeviceListActivity.class); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE); }
/** * Method to init the Options Dialog * * @return */ public TagInputDialog build() { tagInputDialog.hint = Utils.assign(tagInputDialog.hint, tagInputDialog.activity.getString(R.string.add_text_here_text)); tagInputDialog.message = Utils.assign(tagInputDialog.message, Constant.EMPTY_STRING); tagInputDialog.errorMessage = Utils.assign(tagInputDialog.errorMessage, tagInputDialog.activity.getString(R.string.field_cannot_be_left_blank)); tagInputDialog.positiveButton = Utils.assign(tagInputDialog.positiveButton, tagInputDialog.activity.getString(R.string.ok_text)); tagInputDialog.negativeButton = Utils.assign(tagInputDialog.negativeButton, tagInputDialog.activity.getString(R.string.cancel_text)); return tagInputDialog.init(); }
Ultra-Microelectrode Voltammetric Measurement of the Hydrodynamic Radii and Shear Plane of Micellar Particles for Sodium Dodecyl Sulfate in Aqueous NaCl Solutions Abstract Ultra-microelectrode voltammetric measurements have been performed on sodium dodecyl sulfate (SDS) in the aqueous NaCl solutions at 298.2 ± 0.1 K. The hydrodynamic radii (Rh0) of micellar particles are calculated. The results suggest that Rh0 decrease initially due to collapse of the shear plane toward the micelle hard-sphere surface, and then Rh0 increase gradually due to electrolyte-induced linear spherical expansion of the micellar particles. Based on it, the location of micellar shear plane, the relationship between the shear plane and Debye–Hückel length, and the associated ζ-potential are also estimated. It is found that the relationship between the shear plane and Debye–Hückel length is linear, and, in different NaCl concentrations, the shear plane is almost located at a constant shear potential of 77 ± 10 mV, close to the hard-sphere surface of SDS micelle particles.
/** * Constants for Simbs. */ public final class Constants { /** Application version */ public static final String APP_VERSION = "1.3.3"; /** Name of {@code ResourceBundle} file */ public static final String I18N_PATH = "i18n/simbs"; // ******************* // ** SQL connection // ******************* // ********************* // ** HyperSQL(HSQLDB) // ********************* public static final String HYPER_DRIVER = "org.hsqldb.jdbcDriver"; public static final String HYPER_PROTOCOL = "jdbc:hsqldb:hsql://"; public static final String HYPER_HOST = "localhost"; public static final int HYPER_PORT = -1; public static final String HYPER_DATABASE = "bookdb"; // ******************** // ** PostgreSQL // ******************** public static final String POSTGRE_DRIVER = "org.postgresql.Driver"; public static final String POSTGRE_PROTOCOL = "jdbc:postgresql://"; public static final String POSTGRE_HOST = "localhost"; public static final int POSTGRE_PORT = 5432; public static final String POSTGRE_DATABASE = "bookdb"; private static final java.util.List<Profile> DataProfiles = new java.util.ArrayList<>(); static { ResourceBundle rb = ResourceBundle.getBundle(Constants.I18N_PATH); DataProfiles.add(new Profile(0, rb.getString("Dialog.Login.DataSource.HyperSQL"), HYPER_DRIVER, HYPER_PROTOCOL, HYPER_HOST, HYPER_PORT, HYPER_DATABASE, null, null)); DataProfiles.add(new Profile(1, rb.getString("Dialog.Login.DataSource.PostgreSQL"), POSTGRE_DRIVER, POSTGRE_PROTOCOL, POSTGRE_HOST, POSTGRE_PORT, POSTGRE_DATABASE, null, null)); } public static java.util.List<Profile> getDatabaseProfiles() { return DataProfiles; } public static Profile getDatabaseProfile(int id) { return DataProfiles.get(id); } /** User home of SIMBS */ public static final String SIMBS_HOME = String.format("%s/.simbs", System.getProperty("user.home")); // ************************ // ** Date and time format // ************************ public static final String DATE_FORMAT = "yyyy-M-d"; public static final String TIME_FORMAT = "H:m:s"; public static final String DATE_TIME_FORMAT = DATE_FORMAT+" "+TIME_FORMAT; /** Max rows in result table */ public static final int MAX_ROW_COUNT = 8; /** Days limit for customer borrow book */ public static final int MAX_LENT_DAYS = 100; /** Number of increased days when increasing level */ public static final int DAYS_OF_LEVEL = 20; /** Number of book for customer can borrow each time */ public static final int DEFAULT_LENT_LIMIT = 10; /** Default rental price of book */ public static final BigDecimal DEFAULT_RENTAL_PRICE = new BigDecimal("0.2"); /** For overdue period of price when returning books */ public static final BigDecimal OVERDUE_PERIOD_RATE = new BigDecimal(2); /** The money for upgrade limits */ public static final BigDecimal PRICE_OF_INCREASE_LIMIT = new BigDecimal(100); /** The money for upgrade level */ public static final BigDecimal PRICE_OF_INCREASE_LEVEL = new BigDecimal(150); // *********************** // ** SIMBS commands // *********************** public static final String REGISTER_BOOK = "register-book"; public static final String REGISTER_CUSTOMER = "register-customer"; public static final String EXIT_APP = "exit-app"; public static final String STORE_PROPERTIES = "store-prop"; public static final String VIEW_BILL = "view-bill"; /* Update TablePane in main Frame if the pane is shown */ public static final String UPDATE_BOOK_TABLE = "update-book"; public static final String UPDATE_CUSTOMER_TABLE = "update-customer"; public static final String UPDATE_BILL_TABLE = "update-bill"; public static final String EDIT_VIEW = "edit-view"; public static final String EDIT_MODIFY = "edit-modify"; public static final String EDIT_DELETE = "edit-delete"; public static final String SET_PROMOTE = "set-promote"; public static final String VIEW_BOOK = "view-book"; public static final String VIEW_CUSTOMER = "view-customer"; public static final String VIEW_INVENTORY = "view-inventory"; public static final String VIEW_HOME = "view-navigate"; public static final String VIEW_PROMOTION = "view-promotion"; public static final String STORE_BOOK = "store-book"; public static final String SELL_BOOK = "sell-book"; public static final String LEND_BOOK = "lend-book"; public static final String RETURN_BOOK = "return-book"; public static final String HELP_ABOUT = "help-about"; }
def handle_starttag(self, tag, attrs): self.log.debug( u'Encountered a start tag: {0} {1}'.format(tag, attrs) ) if tag in self.sanitizelist: self.level += 1 return if self.isNotPurify or tag in self.whitelist_keys: attrs = self.__attrs_str(tag, attrs) attrs = ' ' + attrs if attrs else '' tmpl = u'<%s%s />' if tag in self.unclosedTags and self.isStrictHtml else u'<%s%s>' self.data.append( tmpl % (tag, attrs,) )
<reponame>Paruck/ElE<gh_stars>1-10 #include "ElEScene.h" #include "ElE.h" ElEScene::ElEScene() { } ElEScene::~ElEScene() { this->SceneEnd(); } void ElEScene::Start() { } void ElEScene::Update() { } void ElEScene::Draw() { switch(ElE::getGraphicsRenderer()) { #ifdef RASPBERRY_COMPILE case ElEGraphicsComponents::OpenGLes20Rasp: break; #endif // RASPBERRY_COMPILE } } void ElEScene::SceneEnd() { }
Buy Photo Redevelopment of Concord Plaza, a large office complex off Silverside Road in Brandywine Hundred is in the planning stages. (Photo: SUCHAT PEDERSON/THE NEWS JOURNAL)Buy Photo Stores and hundreds of apartments are proposed to be added to Brandywine Hundred's Concord Plaza office complex, one of the largest commercial parks in the state. Wilmington developer Buccini/Pollin Group wants to build about 300 luxury apartments situated over restaurants, cafes and stores as well as a new office building at the complex located near Silverside Road and U.S. 202, said Larry Tarabicos, an attorney for the developer. Plans will be filed with New Castle County in the coming weeks, according to Mike Hare, senior vice president at Buccini/Pollin, who declined further comment on the property. The privately held developer, which has numerous projects in Delaware and elsewhere, has scheduled a meeting to unveil its plans to the public at 7 p.m. on Dec. 7 at the Talleyville Fire Company, 3919 Concord Pike. The 45-acre Concord Plaza has about 500,000 square feet of office space in 20 two-story, brick buildings. The developer will propose demolishing eight of the structures to make way for six luxury apartment buildings. Three will be four-stories tall and contain only housing. The other three will be five stories, with the ground floors home to about 40,000 square feet of retail space. "There will be high-end-type restaurants mixed with shops and a cafe," Tarabicos said, noting plans are still conceptual. Construction of a four-story "signature" office building also is part of the plan, Tarabicos said. The proposal will not require a rezoning. The project is in one of the busiest corridors in the county. Some residents of the Longwood neighborhood near Shipley and Silverside roads adjacent to the the site on Thursday said traffic will be a concern with new apartments and a more bustling office park. "Getting out on Silverside, the traffic can be bad at the standard times in the morning and afternoon," said Steven Jones, who has lived in Longwood for 25 years. "I guess this will add some traffic to our small part of the world. We'll wait and see. It could be hectic. I'd probably vote no If I had a vote." Others were concerned about any noise generated from a change in the office park's scenery. "They have been a perfect neighbor," said Mary Jo Gebensleb, whose backyard borders the complex. "The offices are old. They have been there a long time. It's quiet. People will probably get mad things are changing, but I don't think the traffic is that bad." About 370,000 square feet of existing office space will not be changed by the revamp. The office complex currently houses the U.S. Postal Service, a branch of Wilmington University, a daycare center, several medical service providers and smaller office tenants. The buildings are underutilized and at least a few sit vacant, said Pete Davisson, a principal with Jackson Cross Partners, a commercial real estate brokerage firm. Buy Photo Redevelopment of Concord Plaza, a large office complex off Silverside Road in Brandywine Hundred is in the planning stages. (Photo: SUCHAT PEDERSON/THE NEWS JOURNAL) The park was the first of its type in Delaware when it was built for DuPont Co. workers in the late 1960s, Davisson said. It was especially attractive given its location in the most developed part of the county with close access to major roadways, Davisson said. "This property was a great property when it was built. At that time, it was the best thing going," Davisson said. "It's just (corporate office) industry has gotten much more sophisticated." AstraZeneca was the park's last marquee tenant. The pharmaceutical giant consolidated its workforce elsewhere in the county between 2000 and 2005. Buccini/Pollin acquired the property around the same time. The park's redevelopment reflects a larger trend of unused office space being repurposed into stores or housing. "It happens in mid- and high-rise office buildings in the city and it happens in these suburban parks. I don't know that you have seen a lot of that here yet. We are coming out of what was the worst five or six years in the history of commercial real estate," Davisson said "This year has been a very good year for the industry. Wilmington hasn't done quite as well as other markets, but everyone is tying hard and, frankly, Buccini is trying harder than anyone." Since the company's formation in 1993, Buccini/Pollin has developed more than 6 million square feet of office and retail space in Mid-Atlantic and Northeast region. The firm owns more than $4 billion in assets, and office space holdings in Delaware include Wilmington's 500 Delaware Ave., The Nemours Building at 1007 Orange St. and the I.M. Pei Building at 105 N. Market St. The firm also owns the 450,000-square-foot Iron Hill Corporate Center near Newark and the 300,000-square-foot Foulkstone Plaza off Foulk Road, as well as four hotels throughout New Castle County. The development firm is part of a dozen developments in Wilmington in the central business district and on the Riverfront. The company has about 150 apartments along North Market Street downtown set to come online by the end of the year. Tarabicos said it is too soon to put a timeline on construction for the Concord Plaza project and it is unclear if the company will seek any state aid for the redevelopment. Financial details were not released. New Castle County Councilman Bob Weiner said the redevelopment of the office park and the development of the neighboring 111 acres of the now-shuttered Brandywine Country Club could be "transformational" for the area. In the coming months, developer Louis Capano III, whose father owns the country club property, is expected to propose building houses on the property. A public hearing about that proposal is scheduled for Dec. 10, but a location for the meeting hasn't been finalized. Buy Photo Redevelopment of Concord Plaza, a large office complex off Silverside Road in Brandywine Hundred is in the planning stages. (Photo: SUCHAT PEDERSON/THE NEWS JOURNAL) "We as a community will be engaged in the public hearing process to assure that the future of these two sites are consistent with community character and respectful of our traffic capacity and architecturally enhance our community," Weiner said. Contact Xerxes Wilson at (302) 324-2787 or xwilson@delawareonline.com. Follow @Ber_Xerxes on Twitter. Read or Share this story: http://delonline.us/1MllQTi
import math def solve(): x, y, p, q = map(int, input().split()) l, r = 0, 10**10 inf = 10**10 while l < r: mid = (l + r) // 2 mp, mq = mid * p, mid * q # print(f"l = {l}, r = {r}, mid = {mid}, mp = {mp}, mq = {mq}") if mp >= x and mq >= y and mp - x <= mq - y: r = mid else: l = mid + 1 print(l * q - y if l != inf else -1) if __name__ == "__main__": t = 1 t = int(input()) for _ in range(t): solve()
/* * Board.h * * Created on: 07.02.2020 * Author: LK */ #ifndef TMC_BOARDS_BOARD_H_ #define TMC_BOARDS_BOARD_H_ #include "Definitions.h" #include "tmc/helpers/API_Header.h" #ifndef TMC_CFLAGS //////////////////////////////////////////////////////////////////////////////// // User defines #define TMC_AXES_COUNT 3 #define TMC_BOARD_COUNT TMC_AXES_COUNT #define BOARD_0 ID_TMC5160 #define BOARD_1 ID_TMC5160 #define BOARD_2 ID_TMC5160 //////////////////////////////////////////////////////////////////////////////// #endif typedef enum { DRIVER_DISABLE, DRIVER_ENABLE, DRIVER_USE_GLOBAL_ENABLE } DriverState; typedef enum { TMC_ERROR_TYPE = 0x04, TMC_ERROR_ADDRESS = 0x04, TMC_ERROR_NOT_DONE = 0x20 } TMC_Error; typedef struct tmc_board_t { void *type; uint16_t id; uint8_t axis; uint8_t alive; uint32_t errors; uint32_t VMMax; uint32_t VMMin; unsigned char numberOfMotors; ConfigurationTypeDef config; uint32_t (*left) (uint8_t motor, int32_t velocity); // move left with velocity <velocity> uint32_t (*right) (uint8_t motor, int32_t velocity); // move right with velocity <velocity> uint32_t (*rotate) (uint8_t motor, int32_t velocity); // move right with velocity <velocity> uint32_t (*stop) (uint8_t motor); // stop motor uint32_t (*moveTo) (uint8_t motor, int32_t position); // move to position <position> uint32_t (*moveBy) (uint8_t motor, int32_t *ticks); // move by <ticks>, changes ticks to absolute target uint32_t (*moveProfile) (uint8_t motor, int32_t position); // move profile <position> uint32_t (*SAP) (uint8_t type, uint8_t motor, int32_t value); // set axis parameter -> TMCL conformance uint32_t (*GAP) (uint8_t type, uint8_t motor, int32_t *value); // get axis parameter -> TMCL conformance uint32_t (*STAP) (uint8_t type, uint8_t motor, int32_t value); // store axis parameter -> TMCL conformance uint32_t (*RSAP) (uint8_t type, uint8_t motor, int32_t value); // restore axis parameter -> TMCL conformance void (*readRegister) (uint8_t motor, uint8_t address, int32_t *value); // Motor needed since some chips utilize it as a switch between low and high values void (*writeRegister) (uint8_t motor, uint8_t address, int32_t value); // Motor needed since some chips utilize it as a switch between low and high values uint32_t (*getMeasuredSpeed) (uint8_t motor, int32_t *value); uint32_t (*userFunction) (uint8_t type, uint8_t motor, int32_t *value); void (*periodicJob) (uint32_t tick); void (*deInit) (void); void (*checkErrors) (uint32_t tick); void (*enableDriver) (DriverState state); uint8_t (*cover) (uint8_t data, uint8_t lastTransfer); void (*fullCover) (uint8_t *data, size_t length); uint32_t (*getMin) (uint8_t type, uint8_t motor, int32_t *value); uint32_t (*getMax) (uint8_t type, uint8_t motor, int32_t *value); DriverState driverState; } TMC_Board; TMC_Board board[TMC_BOARD_COUNT]; void Boards_init(void); void Board_init(TMC_Board *board); void board_setDummyFunctions(TMC_Board *board); #endif /* TMC_BOARDS_BOARD_H_ */
package com.zakrywilson.astro.tle; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.Calendar; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicReference; /** * A thread-safe epoch utility class for handling conversions between the TLE epoch (year + * fractional Julian day) and the millisecond epoch from January 1, 1970 00:00:00. It also provides * functionality for formatting a millisecond epoch to the TLE format <code>yyddd.dddddddd</code>. * * @author <NAME> */ final class EpochUtils { /** * UTC timezone. */ private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("UTC"); /** * Number of milliseconds in one day. */ private static final double MILLIS_IN_A_DAY = 86400000.0; /** * Decimal formatter used to format the decimal values of the Julian epoch day. */ private static final AtomicReference<DecimalFormat> DECIMAL_FORMAT_ATOMIC_REFERENCE = new AtomicReference<>(new DecimalFormat(".00000000")); static { DECIMAL_FORMAT_ATOMIC_REFERENCE.get().setRoundingMode(RoundingMode.HALF_UP); } /** * Private constructor since this is a static utility class. */ private EpochUtils() {} /** * Converts a TLE epoch year and fractional Julian day into a millisecond epoch from January 1, * 1970 00:00:00. * * @param year the year to be converted * @param julianDay the fractional Julian day to be converted * @return the millisecond epoch */ static long toMillisecondEpoch(int year, double julianDay) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); // Set year calendar.set(Calendar.YEAR, year); // Set day int wholeDay = (int) julianDay; calendar.set(Calendar.DAY_OF_YEAR, wholeDay); // Set millisecond double dayFraction = julianDay - (double) wholeDay; BigDecimal ms = new BigDecimal(dayFraction * MILLIS_IN_A_DAY); int millisecond = ms.setScale(0, RoundingMode.HALF_UP).intValueExact(); calendar.set(Calendar.MILLISECOND, millisecond); return calendar.getTimeInMillis(); } /** * Formats a TLE with the millisecond from January 1, 1970 00:00:00. * * @param epochMillisecond the epoch millisecond to be formatted * @return the formatted epoch */ static String formatForTLE(long epochMillisecond) { // Get the year and day Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); calendar.setTimeInMillis(epochMillisecond); int year = calendar.get(Calendar.YEAR); int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); int twoDigitYear = year % 100; // Reset the calendar to contain only milliseconds accounted for by year and day of year calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.DAY_OF_YEAR, dayOfYear); // Get the fractional part of the day by subtracting out the year and day of year long remainingMilliseconds = epochMillisecond - calendar.getTimeInMillis(); double fractionalDay = remainingMilliseconds / MILLIS_IN_A_DAY; // Format year and day for TLE epoch field String decimal = DECIMAL_FORMAT_ATOMIC_REFERENCE.get().format(fractionalDay); return String.format("%02d%3d%-8s", twoDigitYear, dayOfYear, decimal); } /** * Extracts the epoch year from the epoch millisecond. * * @param epochMillisecond the number of milliseconds since January 1, 1970 00:00:00 * @return the year */ static int getEpochYear(long epochMillisecond) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); calendar.setTimeInMillis(epochMillisecond); return calendar.get(Calendar.YEAR); } /** * Extracts the fractional Julian day from the epoch millisecond. * * @param epochMillisecond the number of milliseconds since January 1, 1970 00:00:00 * @return the fractional Julian day */ static double getEpochJulianDay(long epochMillisecond) { // Get the year and day Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); calendar.setTimeInMillis(epochMillisecond); int year = calendar.get(Calendar.YEAR); int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); // Get a calendar that contains milliseconds accounted for by the year and day of year calendar.clear(); calendar.setTimeZone(UTC_TIME_ZONE); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.DAY_OF_YEAR, dayOfYear); // Get the fractional part of the day by subtracting out the year and day of year long remainingMilliseconds = epochMillisecond - calendar.getTimeInMillis(); double fractionalDay = remainingMilliseconds / MILLIS_IN_A_DAY; // Format year and day for TLE epoch field return (double) dayOfYear + fractionalDay; } }
// Adds handlers to a map field. static void add_handlers_for_mapfield(upb_handlers* h, const upb_fielddef* fielddef, size_t offset) { const upb_msgdef* map_msgdef = upb_fielddef_msgsubdef(fielddef); map_handlerdata_t* hd = new_map_handlerdata(fielddef, map_msgdef); upb_handlerattr attr = UPB_HANDLERATTR_INIT; upb_handlers_addcleanup(h, hd, free); attr.handler_data = hd; upb_handlers_setstartsubmsg(h, fielddef, startmapentry_handler, &attr); }
from django.shortcuts import render from django.db import connection from django.shortcuts import render,redirect from django.http import HttpResponse from helpers.format import format_query from helpers.format import executeSQL from helpers.navbar import which_nav from helpers.email import send_email # Create your views here. def department_list(request): logged_in = request.session.get('logged_in') utype = request.session.get('usertype') if logged_in: navname = "logged_navbar.html" else: navname = "navbar.html" sql = f"SELECT * FROM Department" departments = executeSQL(sql, ['DeptID', 'DeptName', 'NumberOfEmployees', 'Budget', 'Location']) return render(request, 'department/department_list.html', {"departments":departments, "titles": list(departments[0].keys()), "nav": navname})
<reponame>cdslabamotong/StenierSolver<gh_stars>0 import math import numpy def mst_instance(current_node): cost = numpy.zeros([len(current_node), len(current_node)]) for i in range(len(current_node)): for j in range(i,len(current_node)): temp = (current_node[j][0] -current_node[i][0])*(current_node[j][0] -current_node[i][0]) + (current_node[j][1] -current_node[i][1]) * (current_node[j][1] -current_node[i][1]) cost[i][j] = math.sqrt(temp) cost[j][i] = cost[i][j] sum = 0 result = Prim(cost, 0, sum) return result def Prim (V, vertex, sum): length = len(V); lowcost = numpy.zeros([length]) U = numpy.zeros([length]) for i in range(length): lowcost[i] = V[vertex, i] U[i] = vertex lowcost[vertex] = -1; for i in range(1,length): k = 0 min = 65535 for j in range(length): if((lowcost[j] > 0) & (lowcost[j] < min)): min = lowcost[j] k = j lowcost[k] = -1 sum = sum + min for j in range(length): if((V[k, j] != 0) & ((lowcost[j] == 0 )| (V[k, j] < lowcost[j]))): lowcost[j] = V[k, j] U[j] = k return sum
red_str_list=[] blue_str_list=[] blue_cnt=int(input()) for _ in range(blue_cnt): red_str_list.append(input()) red_cnt=int(input()) for _ in range(red_cnt): blue_str_list.append(input()) ans=0 dic = dict() for i in red_str_list: if (i in dic.keys()): dic[i]+=1 else: dic[i]=1 for i in blue_str_list: if (i in dic.keys()): if dic[i]>0: dic[i]-=1 print(max(dic.values()))
The intelligence report of the Philippine National Police (PNP) indicating 17-year-old Kian Lloyd delos Santos was a drug runner could be wrong, President Rodrigo Duterte said Monday night. “Those are just information gathered by the police and the military. It is an internal thing. Hindi mo masabi na, ‘itong intel na ito.’ Maya-maya mali iyan (You just can’t say, ‘this intel,’ later on it could be wrong),” Duterte told reporters in Malacañang. ADVERTISEMENT Delos Santos was shot dead on the night of August 16, by the police in a drug operation in Caloocan City. Northern Police District Chief Superintendent Roberto Fajardo has said that Delos Santos was a newly identified drug suspect based on latest intelligence reports. But Duterte said police’s intelligence report has “no probative value” in court. “So, if there is no probative value, how can you use it in court and to the people,” he said. The chief executive in the same meeting with reporters assured the public that the police officers behind the killing Delos Santos would go to jail if proven guilty. READ: Duterte vows to punish cops in Kian killing if proven guilty “Should the investigation point to liabilities, my warning to all is there will be a prosecution and they have to go to jail. That I can assure you,” he said. “If it is really rubout, they (police) have to answer for it. They have to go to jail,” he added. The President said he would not visit the wake of Delos Santos, saying: “It is pregnant with so many presupositions.” ADVERTISEMENT He added that people might interpret his visit to the wake as a chance for him to apologize to the Delos Santos family and as confirmation of the truth of the accusations against the police. JPV RELATED VIDEO Read Next LATEST STORIES MOST READ
n = int(input()) A, B = list(), list() check = set() for i in range(n): a, b = map(int,input().split()) A.append(a);B.append(b) check.add(a) check = sorted(check) val = dict() for x in check: val[x] = list() for i in range(n): val[A[i]].append(B[i]) main_lst = list() for x in check: val[x].sort() itr, ans = 0, 0 for x in check: if itr == 0: prev = max(val[x]) itr += 1 else: if prev > min(val[x]): prev = x else: prev = max(val[x]) print(prev)
How Window Tinting Works- A Beginners Guide in Details You don't need to be a Mafia don or Hollywood star just in order to do a window-tinting job on your … [Continuous Reading--->] 12 Best Air Compressor for Painting Cars to Look This Year (2019)! A serious job requires serious tools. If you intend to paint some cars and you want the paint job … [Continuous Reading--->] How to Install Subwoofer in a Truck – Step by Step Process A truck sound subwoofer is a piece of a truck's sound framework that gives the low bass frequencies … [Continuous Reading--->] Top 10 Best Brake Bleeder Kits in 2019 (Vacuum, Pressure and Electric) Bubbles and air pockets can lead to under performance of your brake or sometimes your brakes even … [Continuous Reading--->] Best Shocks and Struts for Smooth Ride to Look at This Year (2019)! Maintaining your vehicle surely requires you to invest lots of time and effort in it. And, as one of … [Continuous Reading--->] The Difference between Brad and Finish Nailer – Which is The Best? A nailer is a popular power tool which is used to drive nails into wood or different kinds of … [Continuous Reading--->] What Is The Best Air Purifier 2019 – Complete Guide Oxygen is an important part of our daily life and fresh air is a free gift from the Almighty because … [Continuous Reading--->] 11 Best Truck Bed Bike Rack Review to Look at This Year (2019)! As we all know, biking is one of the best sports to do in order to stay in good shape, both … [Continuous Reading--->] Top 10 Best sander for cars to look at This Year (2019)! If auto body work is your professional job then an electric sander is out of the question. However, … [Continuous Reading--->] How to Remove Scratches From Cars and SUVs : Step by Step Guide Among all the damages that are being faced with a car, scratches are one of the most common ones. … [Continuous Reading--->] Are leather car seats better than fabric? The difference between them We can all agree on one thing, the seat comfort in your car is absolutely important! Just think of … [Continuous Reading--->] Best Dash Covers : Top Interior Dashboard Cover Review & Buyer Guide We all have at least one person in our life who has always claimed that dash covers are old … [Continuous Reading--->] Best RV Stabilizer 2019 – Top 10 Travel trailer & 5th wheel stabilizer review If you ever went on a camping trip in your RV, then you must know that uneven ground in a RV park or … [Continuous Reading--->] Best Head Gasket Sealers in 2019 – Top-Rated Gasket Sealer for Cars Do you have a car that may be old or new? If yes, then you’re in for different challenges. Your car … [Continuous Reading--->] How to Protect Your Car from Scratching and Damage In Details Everyone loves and wants the car to look shiny like a new penny. But as a matter of fact, when your … [Continuous Reading--->] Home Remedies for Detoxification | Body Cleanse Home Remedies Home Remedies for Detoxification your body. Typical cleanses that harness the natural processes of … [Continuous Reading--->] 15 DIY Home Remedies for Unwanted Hair Removal Naturally DIY Home Remedies for Unwanted Hair Removal Naturally. Hirsute denotes the growth of rough, dark … [Continuous Reading--->] How to Use Air Compressor to Fill Tire – Step by Step Guide A lovely sunny day and you want to take a long drive along the countryside in this beautiful … [Continuous Reading--->] How to use an Air Compressor and The Steps for Maintaining It Most power tools these days use air compressor to power themselves. An air compressor can be of … [Continuous Reading--->] Air Compressor Safety Guide and How to Maintain an Air Compressor Air compressors are units that are required to power air tools. These tools, also called pneumatic … [Continuous Reading--->] How to Use Nail Gun for Fencing – Step by Step Guide You might have a misconception that fencing is a very tough task to perform. Well, what you are … [Continuous Reading--->] How to Use Head Gasket Sealer – Step by Step Guide Head gasket sealers are like a revolution to us. Whether it’s about preventing leakage of the engine … [Continuous Reading--->] How to Use Nail Gun for Trim – Step by Step Guide Many are familiar with the term nail gun and also with its usage and befits. But, the proper usage … [Continuous Reading--->] How to Change Your Headlight Bulbs – Step by Step Guide If you have a car then you know very well the importance of car headlight. If one or both headlights … [Continuous Reading--->] 15 Home Remedies for Blackheads | Fast Home Remedies Home Remedies for Blackheads. Aesthetics are an extremely important section of the modern day … [Continuous Reading--->] Home Remedies for Weight Loss | How to Lose Weight Healthily Home Remedies for Weight Loss | How to Lose Weight Healthily. Obesity raises the risk of several … [Continuous Reading--->]
<filename>src/com/model/Users.java package com.model; public class Users { private String username; private String password; private String usersname; private String branch; private String privilege; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsersname() { return usersname; } public void setUsersname(String usersname) { this.usersname = usersname; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public String getPrivilege() { return privilege; } public void setPrivilege(String privilege) { this.privilege = privilege; } public Users(String username, String password, String usersname, String branch, String privilege) { this.username = username; this.password = password; this.usersname = usersname; this.branch = branch; this.privilege = privilege; } public Users() { } @Override public String toString() { return "Users{" + "username=" + username + ", password=" + password + ", usersname=" + usersname + ", branch=" + branch + ", privilege=" + privilege + '}'; } }
// InitGenesis will run module initialization using the genesis state //nolint:gocritic,gocyclo func InitGenesis(ctx sdk.Context, k keeper.Keeper, state GenesisState) { accountKeeper := k.AccountKeeper() coinKeeper := k.CoinKeeper() amount := sdk.NewInt(5000) coins := sdk.Coins{sdk.Coin{ Denom: ModuleName, Amount: amount, }} setServiceAccount(ctx, accountKeeper, coinKeeper, state.KeyService.Address, state.KeyService.PubKey, coins) setServiceAccount(ctx, accountKeeper, coinKeeper, state.BonusService.Address, state.BonusService.PubKey, coins) setServiceAccount(ctx, accountKeeper, coinKeeper, state.ClaimService.Address, state.ClaimService.PubKey, coins) if err := k.SetServiceAddress(ctx, state.KeyService.Address); err != nil { panic(err) } if err := k.SetBonusServiceAddress(ctx, state.BonusService.Address); err != nil { panic(err) } if err := k.SetClaimServiceAddress(ctx, state.ClaimService.Address); err != nil { panic(err) } for i := range state.Attendees { a := &state.Attendees[i] account := accountKeeper.GetAccount(ctx, a.GetAddress()) if account == nil { account = accountKeeper.NewAccountWithAddress(ctx, a.GetAddress()) _, e := coinKeeper.AddCoins(ctx, account.GetAddress(), coins) if e != nil { panic(e) } } _ = account.SetPubKey(a.PubKey) accountKeeper.SetAccount(ctx, account) k.SetAttendee(ctx, a) } for i := range state.Scans { k.SetScan(ctx, &state.Scans[i]) } for i := range state.Prizes { k.SetPrize(ctx, &state.Prizes[i]) } }
def circular_mean(data, weights=None, degrees=True, axis=0, exponential_weights=True): if degrees: data = np.radians(data, dtype=np.float32) sin = np.sin(data) cos = np.cos(data) if weights is None: sin = np.nanmean(sin, axis=axis) cos = np.nanmean(cos, axis=axis) else: if exponential_weights: weights = np.exp(weights) if weights.shape != data.shape: msg = ('The shape of weights {} does not match the shape of the ' 'data {} to which it is to be applied!' .format(weights.shape, data.shape)) logger.error(msg) raise RuntimeError(msg) n_weights = np.expand_dims(np.nansum(weights, axis=axis), axis) sin = np.nansum(sin * weights, axis=axis) / n_weights cos = np.nansum(cos * weights, axis=axis) / n_weights mean = np.arctan2(sin, cos) if degrees: mean = np.degrees(mean) mask = mean < 0 if isinstance(mask, np.ndarray): mean[mask] += 360 elif mask: mean += 360 return mean
// Function object for sorting vector of features and associated region ID's based on distance from a given point class DistanceAtIndexIsGreater { public: typedef std::pair< LocationRegistration::feature_sptr_type, LocationRegistration::SegmentedImageType::PixelType > FeatureIDPair; DistanceAtIndexIsGreater( itk::Point< double, 3 > const & ReferencePoint ) : m_ReferencePoint( ReferencePoint ) {} bool operator()( FeatureIDPair const & i, FeatureIDPair const & j ) { vnl_vector< double > distancei = i.first->location_ - m_ReferencePoint.GetVnlVector(); vnl_vector< double > distancej = j.first->location_ - m_ReferencePoint.GetVnlVector(); return distancei.magnitude() < distancej.magnitude(); } private: itk::Point< double, 3 > const & m_ReferencePoint; }
package faqs import ( "time" ) type FaqDocument struct { Id int64 `json:"id"` UniqHash string `json:"uniq_hash"` Question string `json:"question"` Answer string `json:"answer"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` } type FaqDocuments []FaqDocument func NewDocFromFaq(faq *Faq) *FaqDocument { return &FaqDocument{ Id: faq.Id, UniqHash: faq.UniqHash, Question: faq.Question, Answer: faq.Answer, CreatedAt: faq.CreatedAt, UpdatedAt: faq.UpdatedAt, } }
// Encontrar todos los switches de acceso public List<DatapathId> accessSwitches(SwitchPort[] ap) { List<DatapathId> switches = new ArrayList<DatapathId>(); for (DatapathId switchId : switchService.getAllSwitchDpids()) { IOFSwitch sw = switchService.getSwitch(switchId); for (OFPortDesc port : sw.getPorts()) { OFPort portId = port.getPortNo(); if (switchId.equals(ap[0].getSwitchDPID()) && (portId.getShortPortNumber() == ap[0].getPort() .getShortPortNumber())) { continue; } if (topologyManager.isAttachmentPointPort(switchId, port.getPortNo())) { switches.add(sw.getId()); break; } } } return switches; }
//------------------------------------------------------------- // Procedure: getEntryCount // Note: Return the number of entries contained in given partition unsigned int PartitionRecord::getEntryCount(unsigned int ix) const { if(ix < m_partition_entry_cnt.size()) return(m_partition_entry_cnt[ix]); return(0); }
PORTLAND, Maine — Houlton’s municipal electric utility on Tuesday received final approval to disconnect from the northern Maine power grid and connect directly with Canadian lines. Houlton Water Co. is in the final stages of securing a $5.4 million loan to fund about 11 miles of new power lines connecting it directly to the electric grid maintained by New Brunswick Power, which it expects to complete by the end of 2019. The Maine Public Utilities Commission on Tuesday gave final approval to the terms of the loan and a 10-year service agreement with the Canadian utility, which Houlton Water said would save the average residential customer about $54 in the first year after becoming a direct transmission customer of the New Brunswick system. The company argued during the case that the rest of the grid stands to benefit, too, but Emera Maine said losing Houlton Water as a transmission customer will raise its costs and increase the average customer’s annual bill by about $13.21 in the first year. Regulators found the eventual impacts on rates for both utilities are “not trivial” but that rate impacts alone were not enough to approve or deny the proposal. Houlton Water serves approximately 5,000 customers in Houlton and the surrounding communities of New Limerick, Linneus, Hodgdon and Ludlow. Houlton Water argued its departure would let its customers avoid paying for expected costly upgrades on Emera’s northern Maine system and also remove the need for Emera to make upgrades to serve load to Houlton.” “With HWC leaving the Emera Maine transmission system, there will be additional benefits to the customers remaining on the northern Maine transmission system,” the company said in a prepared statement. “Those include additional transfer capability between Emera Maine and [New Brunswick Power] and avoided costs from transmission upgrades that would otherwise be necessary if HWC remained a customer of Emera.” Regulators ultimately decided those avoided costs made the difference in finding the deal in the public interest, in a ruling issued in December. They estimated that losing Houlton Water as a customer would remove Emera’s need to spend up to $20 million to upgrade transmission infrastructure serving Houlton, which it wrote is “nearing the end of its useful life.” Instead, the utility estimates it will contribute at least $5.4 million to construction of a power line 1.5-mile line from its current system to the Canadian border at Woodstock, where it would connect with a new 9.3-mile New Brunswick Power line. The avoided upgrade costs to Emera’s system, they wrote, ” tips the balance” in favor of the proposal. The state’s consumer advocate opposed the deal, arguing that the company didn’t prove the arrangement would have a public benefit, including for the rest of Emera’s customers. The Office of the Public Advocate and Emera argued Houlton water overstated projected savings. The company countered that Emera’s estimates of the costs to its customers were based on ” flawed analysis.” With their approval, regulators in December wrote they remained concerned that terms with New Brunswick Power were not clearly for more than one year. The company on Jan. 27 filed updated agreement terms, effective Feb. 1, that specify the deal will end Jan. 31, 2027. PUC members said Tuesday the updated terms satisfied those concerns. They also gave clearance for the company to hold proceeds from its loan in a Key Bank account, because lender Machias Savings does not allow depositors to hold Canadian currency.
A Geometric Hamilton-Jacobi Theory for Classical Field Theories In this paper we extend the geometric formalism of the Hamilton-Jacobi theory for hamiltonian mechanics to the case of classical field theories in the framework of multisymplectic geometry and Ehresmann connections. Introduction The standard formulation of the Hamilton-Jacobi problem is to find a function S(t, q A ) (called the principal function) such that If we put S(t, q A ) = W (q A ) − tE, where E is a constant, then W satisfies H(q A , ∂W ∂q A ) = E; (1.2) W is called the characteristic function. There are some recent attempts to extend this theory for classical field theories in the framework of the so-called multisymplectic formalism . For a classical field theory the hamiltonian is a function H = H(x µ , y i , p µ i ), where (x µ ) are coordinates in the space-time, (y i ) represent the field coordinates, and (p µ i ) are the conjugate momenta. In this context, the Hamilton-Jacobi equation is ∂S µ ∂x µ + H(x ν , y i , where S µ = S µ (x ν , y j ). In this paper we introduce a geometric version for the Hamilton-Jacobi theory based in two facts: (1) the recent geometric description for Hamiltonian mechanics developed in (see for the case of nonholonomic mechanics); (2) the multisymplectic formalism for classical field theories in terms of Ehresmann connections . We shall also adopt the convention that a repeated index implies summation over the range of the index. A geometric Hamilton-Jacobi theory for Hamiltonian mechanics First of all, we give a geometric version of the standard Hamilton-Jacobi theory which will be useful in the sequel. Let Q be the configuration manifold, and T * Q its cotangent bundle equipped with the canonical symplectic form Let H : T * Q −→ R a hamiltonian function and X H the corresponding hamiltonian vector field: The integral curves of X H , (q A (t), p A (t)), satisfy the Hamilton equations: To go further in this analysis, define a vector field on Q: X λ H = T π Q • X H • λ as we can see in the following diagram: (i)' If σ : I → Q is an integral curve of X λ H , then λ•σ is an integral curve of X H ; (i)" X H and X λ H are λ-related, i.e. T λ(X λ H ) = X H • λ so that the above theorem can be stated as follows: Theorem 2.2 (Hamilton-Jacobi Theorem). Let λ be a closed 1-form on Q. Then, the following conditions are equivalent: 3. The multisymplectic formalism 3.1. Multisymplectic bundles. The configuration manifold in Mechanics is substituted by a fibred manifold We can choose fibred coordinates (x µ , y i ) such that We will use the following useful notations: Denote by V π = ker T π the vertical bundle of π, that is, their elements are the tangent vectors to E which are π-vertical. Denote by Π : Λ n E −→ E the vector bundle of n-forms on E. The total space Λ n E is equipped with a canonical n-form Θ: is called the canonical multisymplectic form on Λ n E. Denote by Λ n r E the bundle of r-semibasic n-forms on E, say Λ n r E = {α ∈ Λ n E | i v 1 ∧···∧vr α = 0, whenever v 1 , . . . , v r are π-vertical} Since Λ n r E is a submanifold of Λ n E it is equipped with a multisymplectic form Ω r , which is just the restriction of Ω. Two bundles of semibasic forms play an special role: Λ n 1 E and Λ n 2 E. The elements of these spaces have the following local expressions: we can obtain the quotient vector space denoted by J 1 π * which completes the following exact sequence of vector bundles: We denote by π 1,0 : J 1 π * −→ E and π 1 : J 1 π * −→ M the induced fibrations. Ehresmann Connections in the fibration A connection (in the sense of Ehresmann) in π 1 is a horizontal subbundle H which is complementary to V π 1 ; namely, where V π 1 = ker T π 1 is the vertical bundle of π 1 . Thus, we have: (i) there exists a (unique) horizontal lift of every tangent vector to M; (ii) in fibred coordinates (x µ , y i , p µ i ) on J 1 π * , then where H µ is the horizontal lift of ∂ ∂x µ . (iii) there is a horizontal projector h : T J * π −→ H. Hamiltonian sections. Consider a hamiltonian section where Ω 2 is the multisymplectic form on Λ n 2 E. The field equations can be written as follows: where h denotes the horizontal projection of an Ehresmann connection in the fibred manifold π 1 : J 1 π * −→ M. The local expressions of Ω 2 and Ω h are: 3.4. The field equations. Next, we go back to the Equation (3.1). The horizontal subspaces are locally spanned by the local vector fields where Γ i µ and (Γ µ ) ν j are the Christoffel components of the connection. Assume that τ is an integral section of h; this means that τ : M −→ J 1 π * is a local section of the canonical projection π 1 : If τ (x µ ) = (x µ , τ i (x), τ µ i (x)) then the above conditions becomes ∂τ i ∂x µ = The Hamilton-Jacobi theory Let λ be a 2-semibasic n-form on E; in local coordinates we have Alternatively, we can see it as a section λ : E −→ Λ n 2 E, and then we have λ(x µ , y i ) = (x µ , y i , λ 0 (x, y), λ µ i (x, y)) . A direct computation shows that Therefore, dλ = 0 if and only if Using λ and h we construct an induced connection in the fibred manifold π : E −→ M by defining its horizontal projector as follows: where ǫ(X) ∈ T (µ•λ)(e) (J 1 π * ) is an arbitrary tangent vector which projects onto X. From the above definition we immediately proves that (i)h is a well-defined connection in the fibration π : E −→ M. (ii) The corresponding horizontal subspaces are locally spanned bỹ The following theorem is the main result of this paper. Before to begin with the proof, let us consider some preliminary results. We have Notice that h • µ • λ is again a 2-semibasic n-form on E. A direct computation shows that Therefore, we have the following result. Proof of the Theorem (i) ⇒ (ii) It should be remarked the meaning of (i). Assume that is an integral section ofh; then (i) states that in the above conditions, is a solution of the Hamilton equations, that is, Sinceh is a flat connection, we may consider an integral section σ of h. Suppose that σ(x µ ) = (x µ , σ i (x)). Then, we have that Assume that λ = dS, where S is a 1-semibasic (n − 1)-form, say An alternative geometric approach of the Hamilton-Jacobi theory for Classical Field Theories in a multisymplectic setting was discussed in . Time-dependent mechanics A hamiltonian time-dependent mechanical system corresponds to a classical field theory when the base is M = R. We have the following identification Λ 1 2 E = T * E and we have local coordinates (t, y i , p 0 , p i ) and (t, y i , p i ) on T * E and J 1 π * , respectively. The hamiltonian section is given by and therefore we obtain If we denote by η = dt the different pull-backs of dt to the fibred manifolds over M, we have the following result. The pair (Ω h , dt) is a cosymplectic structure on E, that is, Ω h and dt are closed forms and dt ∧ Ω n h = dt ∧ Ω h ∧ · · · ∧ Ω h is a volume form, where dimE = 2n + 1. The Reeb vector field R h of the structure (Ω h , dt) satisfies i R h Ω h = 0 , i R h dt = 1. The integral curves of R h are just the solutions of the Hamilton equations for H. The relation with the multisymplectic approach is the following: or, equivalently, A closed 1-form λ on E is locally represented by λ = λ 0 dt + λ i dy i . Using λ we obtain a vector field on E: such that the induced connection is h = (R h ) λ ⊗ dt Therefore, we have the following result.
/** * @author Adam Gibson */ public class ReshapeTests extends BaseNd4jTest { public ReshapeTests() { } public ReshapeTests(String name) { super(name); } public ReshapeTests(String name, Nd4jBackend backend) { super(name, backend); } public ReshapeTests(Nd4jBackend backend) { super(backend); } @Test public void testThreeTwoTwoTwo() { INDArray threeTwoTwo = Nd4j.linspace(1,12,12).reshape(3,2,2); INDArray sliceZero = Nd4j.create(new double[][]{{1, 7}, {4, 10}}); INDArray sliceOne = Nd4j.create(new double[][]{{2,8},{5,11}}); INDArray sliceTwo = Nd4j.create(new double[][]{{3,9},{6,12}}); INDArray[] assertions = new INDArray[] { sliceZero,sliceOne,sliceTwo }; for(int i = 0; i < threeTwoTwo.slices(); i++) { INDArray sliceI = threeTwoTwo.slice(i); assertEquals(assertions[i],sliceI); } INDArray linspaced = Nd4j.linspace(1,4,4).reshape(2,2); INDArray[] assertionsTwo = new INDArray[] { Nd4j.create(new double[]{1,3}),Nd4j.create(new double[]{2,4}) }; for(int i = 0; i < assertionsTwo.length; i++) assertEquals(linspaced.slice(i),assertionsTwo[i]); } @Test public void testColumnVectorReshape() { double delta = 1e-1; INDArray arr = Nd4j.create(1,3); INDArray reshaped = arr.reshape('f',3,1); assertArrayEquals(new int[]{3,1},reshaped.shape()); assertEquals(0.0, reshaped.getDouble(1),delta); assertEquals(0.0,reshaped.getDouble(2),delta); assumeNotNull(reshaped.toString()); } @Override public char ordering() { return 'f'; } }
<reponame>hjc851/SourceCodePlagiarismDetectionDataset public class Layouts { public synchronized void increaseForestall() { this.barred++; } public int barred = 0; public synchronized int driveSecurity() { return identification; } public synchronized int takeAbortAppendage() { return allocateTreat; } public synchronized int driveStem() { return barred; } public int identification = 0; public int allocateTreat = 0; public synchronized void reloadCounteract() { this.barred = 0; } public Layouts(int picture, int receiveNegotiations, int anti) { this.identification = picture; this.allocateTreat = receiveNegotiations; this.barred = anti; } }
def secs_for_next(cron_format: str, tz: tzinfo = None) -> float: now_ts = time.time() now = datetime.now(tz) if tz else now_ts cron_it = croniter(cron_format, start_time=now) return cron_it.get_next(float) - now_ts
The influence of the number of graphene layers on the atomic resolution images obtained from aberration-corrected high resolution transmission electron microscopy Image patterns formed by low voltage aberration-corrected high resolution transmission electron microscopy (HRTEM) of few layer graphene provide insight into the number of layers present. For odd numbers of graphene layers (three layers or more) and even numbers of graphene layers, distinctly different image patterns are produced. A sheet with step edges of between zero, one, two and three layers of graphene is fabricated using in situ electron beam sputtering at 80 kV and atomic resolution images are obtained. A correlation between the theoretically generated image simulations and the real HRTEM images is found and this enables us to distinguish between monolayer, bilayer, and trilayer graphene using image pattern recognition.
// Query the capabilities of a device int playerc_device_hascapability(playerc_device_t *device, uint32_t type, uint32_t subtype) { player_capabilities_req_t capreq; capreq.type = type; capreq.subtype = subtype; return playerc_client_request(device->client, device, PLAYER_CAPABILTIES_REQ, &capreq, NULL) >= 0 ? 1 : 0; }
def _CRsweep(A, B, Findex, Cindex, nu, thetacr, method): n = A.shape[0] z = np.zeros((n,)) e = deepcopy(B[:, 0]) e[Cindex] = 0.0 enorm = norm(e) rhok = 1 it = 0 while True: if method not in ('habituated', 'concurrent'): raise NotImplementedError('method not recognized: need habituated ' 'or concurrent') if method == 'habituated': gauss_seidel(A, e, z, iterations=1) e[Cindex] = 0.0 elif method == 'concurrent': gauss_seidel_indexed(A, e, z, indices=Findex, iterations=1) enorm_old = enorm enorm = norm(e) rhok_old = rhok rhok = enorm / enorm_old it += 1 if rhok < 0.1 * thetacr: break if ((abs(rhok - rhok_old) / rhok) < 0.1) and (it >= nu): break return rhok, e
a = input().split() b = int(a[0]) c = int(a[1]) def f(x,y): if x*y == 0 or x*y == 1: return 0 elif x < 3 and y < 3: return 1 elif x > 2: return 1 + f(x-2,y+1) else: return 1 + f(x+1,y-2) print(f(b,c))
//-------------------------------------------------------- // Constructor // Grab references to ATC and thermostat data //-------------------------------------------------------- ThermostatIntegratorFlux::ThermostatIntegratorFlux(AtomicRegulator * thermostat, int lambdaMaxIterations, const string & regulatorPrefix) : ThermostatGlcFs(thermostat,lambdaMaxIterations,regulatorPrefix), heatSource_(atc_->atomic_source(TEMPERATURE)) { lambdaSolver_ = new ThermostatSolverFlux(thermostat, lambdaMaxIterations, regulatorPrefix); }
A domain free of the zeros of the partial theta function We prove that for $q\in (0,1)$, the partial theta function $\theta (q,x):=\sum _{j=0}^{\infty}q^{j(j+1)/2}x^j$ has no zeros in the closed domain $\{ \{ |x|\leq 3\} \cap \{${\rm Re}$x\leq 0\} \cap \{ |${\rm Im}$x|\leq 3/\sqrt{2}\} \} \subset \mathbb{C}$ and no real zeros $\geq -5$. Introduction The present paper deals with analytic properties of the partial theta function It owes its name to the resemblance between the function θ(q 2 , x/q) = ∞ j=0 q j 2 x j and the Jacobi theta function Θ(q, x) := ∞ j=−∞ q j 2 x j ; "partial" refers to the fact that summation in the case of θ takes place only from 0 to ∞. We consider the situation when the variable x and the parameter q are real, more precisely, when (q, x) ∈ (0, 1) × R. This function has been studied also for (q, x) ∈ (−1, 0) × R and (q, x) ∈ D 1 × C; here D 1 stands for the open unit disk. For any fixed non-zero value of the parameter q (|q| < 1), the function θ(q, .) is an entire function in x of order 0. The partial theta function finds various applications -from Ramanujan type q-series ( ) to the theory of (mock) modular forms ( ), from asymptotic analysis ( ) to statistical physics and combinatorics ( ). How θ can be applied to problems dealing with asymptotics and modularity of partial and false theta functions and their relationship to representation theory and conformal field theory is made clear in and . The place which this function finds in Ramanujan's lost notebook is explained in and . Its Padé approximants are studied in . A recent interest in the partial theta function is connected with the study of sectionhyperbolic polynomials, i. e. real polynomials with positive coefficients, with all roots real negative and all whose finite sections (i.e. truncations) have also this property, see , and ; the cited papers use results of Hardy, Petrovitch and Hutchinson (see , and ). Various analytic properties of the partial theta function are proved in - and other papers of the author. The analytic properties of θ known up to now, in particular, the behaviour of its zeros, are discussed in the next section. One of them is the fact that for any q ∈ (0, 1), all complex conjugate pairs of zeros of θ(q, .) remain within the domain {Rex ∈ (−5792.7, 0), |Imx| < 132} ∪ {|x| < 18} . For q ∈ (−1, 0), this is true for the domain {|Rex| < 364.2, |Imx| < 132}, see and . In this sense the complex conjugate zeros of θ never go too far from the origin. It is also true that they never enter into the unit disk, see (but this property is false if q and x are complex, see the next section). In the present paper we exhibit a convex domain which contains the left unit half-disk, which is more than 7 times larger than the latter and which is free of zeros of θ for any q ∈ (0, 1): Theorem 1. For any fixed q ∈ (0, 1), the partial theta function has no zeros in the domain When only the real zeros of θ are dealt with, one can improve the above theorem: Proposition 2. For any q ∈ (0, 1) fixed, the function θ(q, .) has no real zeros ≥ −5. Before giving comments on these results in the next section we explain the structure of the paper. Section 3 reminds certain analytic properties of θ. Proposition 2 is proved in Section 4. In Section 5 we prove some lemmas which are used to prove Theorem 1; their proofs can be skipped at first reading. Section 6 contains a plan of the proof of Theorem 1. The proofs of the proposition and lemmas formulated in Section 6 can be found in Section 7. One can make the following observations with regard to Theorem 1 and Proposition 1: (1) It is not clear whether Theorem 1 should hold true for the whole of the left half-disk of radius 3, because |θ(0.71, e 0.5188451144πi )| = 0.0141 . . ., i. e. one obtains a very small value of |θ| for a point of the arc C 1 . This might mean that a zero of θ crosses the arc C 1 for q close to 0.71. (2) The difficulty to prove results as the ones of Theorem 1 and Proposition 2 resides in the fact that the rate of convergence of the series of θ decreases as q tends to 1 − , and for q = 1, one obtains as limit of θ the rational (not entire) function 1/(1 − x). It is true that the series of θ converges to the function 1/(1 − x) (which has no zeros at all) on a domain larger than the unit disk and containing the domain D, see . Yet one disposes of no concrete estimations about this convergence, so one cannot deduce from it the absence of zeros of θ in the domain D for all q ∈ (0, 1). We explain by examples why analogs of the property of the zeros of θ to avoid the domain D cannot be found in cases other than q ∈ (0, 1), x ≤ 0: (i) If q is complex, then some of the zeros of θ can be of modulus < 1. Indeed, for q = ρe 3πi/4 , where ρ ∈ (0, 1) is close to 1, the function θ has a zero close to 0.33 . . . + 0.44 . . . i whose modulus is 0.56 . . . < 1. Similar examples can be given for any q of the form ρe kπi/ℓ , k, ℓ ∈ Z * , see . It is true however that θ has no zeros for |x| ≤ 1/2|q|, see Proposition 7 in . (ii) If q ∈ (0, 1), the function θ has no positive zeros, but θ(0.98, .) is likely to have a zero close to 1.209 . . . + 0.511 . . . i (i. e. of modulus 1.312 . . .), see . Conjecture: As q → 1 − , one can find complex zeros of θ(q, .) as close to 1 as possible. One can check numerically that for q close to 0.726475, θ has a complex conjugate couple of zeros close to ±2.9083 . . . i (which by the way corroborates the idea that the statement of Theorem 1 cannot be extended to the whole of the left half-disk of radius 3). Thus a convex domain free of zeros of θ should belong to the rectangle {Rex ∈ (0, 1), |Imx| < 2.9083 . . .}. (iii) For q ∈ (−1, 0), it is true that the leftmost of the positive zeros of θ tends to 1 + as q tends to −1 + , see part (2) of Theorem 3 in . The function θ(−0.96, .) is supposed to have a couple of conjugate zeros close to the zeros z ± := 0.824 . . . ± 1.226 . . . i (of modulus 1.478 . . .) of its truncation θ • 100 (−0.96, .); when truncating, the first two skipped terms are of modulus 6.57 . . . × 10 −75 and 1.51 . . . × 10 −76 . As q → −1 + , the limit of θ equals (1 − x)/(1 + x 2 ). One can suppose that the zeros, which equal z ± for q = −0.96, tend to ±i as q → −1 + . One knows that for q ∈ (−1, 0), complex zeros do not cross the imaginary axis, see Theorem 8 in . Hence these zeros of θ should remain in the right half-plane and close to ±i. This means that it is hard to imagine a convex domain in the right half-plane much larger than the right unit half-disk and free of zeros of θ. As for the left half-plane, the truncation θ • 100 (−0.96, .) of θ(−0.96, .) has conjugate zeros 0.769 . . . ± 1.255 . . . i (of modulus 1.473 . . .) about which, as about z ± above, one can suggest that they tend to ±i as q → −1 + . This could make one think that if one wants to find a domain in the left half-plane containing the left unit half-disk and free of zeros of θ, then in this domain the modulus of the imaginary part should not be larger than 1. On the other hand θ(−0.7, .) has a zero close to w 0 := −2.69998 . . . so the width of the desired domain should be < |w 0 |. Known properties of the partial theta function In this section we remind first that the Jacobi theta function satisfies the Jacobi triple product from which we deduce the equalities It is clear that Notation 4. (1) When treating the function G we often change the variable x to X := 1/x. To distinguish the truncations of the function θ in the variable x from the ones in the variable t (see Notation 3) we write θ = θ • k + θ • * , where θ • k := k j=0 q j(j+1)/2 x j and θ • * := ∞ j=k+1 q j(j+1)/2 x j , i. e. we use the superscript "bullet" when in the variable x (no index k is added to θ • * ). No superscript is used for the truncations of θ(q, −t + wi) and of G. (2) We set Remark 5. In the proofs we use the convergence of the series (1) when the parameter q belongs to an interval of the form , a ∈ (0, 1). When we need to deal with intervals of the form , we use the equalities (3) in which the modulus of the term Θ * tends to 0 as q tends to 1 − while the series of G converges uniformly for |x| ∈ . There exists an increasing and tending to 1 − sequence of spectral valuesq j of q such that θ(q j , .) has a multiple (more exactly double) real zero, see . The 6-digit truncations of the first 6 spectral values are: When q passes fromq − j toq + j , the rightmost two of the real zeros of θ coalesce and then form a complex conjugate pair. All other real zeros of θ remain negative and distinct, see Theorem 1 in , the function θ is the product of a real polynomial of degree 2j without real zeros and a function of the class L − PI. See the details in . Spectral values exist also for q ∈ (−1, 0), see . The existence of spectral values for complex values of q is proved in , see Proposition 8 therein. Using the above notation and (4) one can write To prove the latter inequality one has to observe that the numbers q m corresponding to factors |K(q m )| from the set Σ (1/3. (see the equalities and inequalities (5) and (4)) and one concludes that ℓ 3 ≤ m 3 + 6. The factors |K(q m )| which have not been mentioned up to now are all of modulus < 1; the corresponding numbers q m belong to the intervals (0, d ′ ) and (t ′′ , u ′′ ). Thus ∞ m=1 |K(q m )| < 2 6 . At the same time This shows that |Θ * (q, −5)| < 10 −4 < 4/25 < | − G(q, −5)| from which the proposition follows. For q fixed, these quantities are decreasing in ϕ, because such is cos ϕ. Set cos ϕ := − √ 2/2, |x| := 3. The displayed formulas show that from which one deduces the last two claims of the lemma. In the proofs we need some properties of the functions M := |(1 + qx)(1 + q/x)| and M 0 := (1 − q)M . We remind that we set x = −t + wi, t ∈ , w = 3/ √ 2. Proof. It suffices to prove the claims of the lemma about the function M . One checks directly for the square of M that One verifies straightforwardly that The discriminant of the trinomial 36(qt) 2 − 149qt + 198 is negative, so this trinomial is positivevalued. For the remaining terms of P , for t ∈ (hence t 2 ≤ 9/2), one obtains −18qt 3 + 198q 2 + 36t 2 ≥ −81qt + 198q 2 + 36t 2 which is again a trinomial with negative discriminant. Thus P > 0 and M 2 − M 2 | t=0 ≤ 0 with equality only for t = 0 which proves the first claim of the lemma. To prove its second statement we consider the difference The polynomial V 2 q 2 +V 1 q+V 0 has no crfitical points for (q, t) ∈ × , there is exactly one such pair. From now on we assume that q ∈ will be subdivided in two cases: We use the fact that |θ • 4 | ≥ max(|Re(θ • 4 )|, |Im(θ • 4 )|) =: µ. Neither of the functions G R and G I has a critical point with q ∈ I 0 , so G R (resp. G I ) attains its maximal and its minimal value when one of the following conditions takes place: t = 0, t = 3, q = 0 or q = 0.5.
def randbool(n=8): return randint(0, n*n-1) % n == 0
<filename>backend/core/src/main/java/com/github/thiagogarbazza/training/springangular/core/cliente/impl/ClienteRepositoryCustom.java<gh_stars>0 package com.github.thiagogarbazza.training.springangular.core.cliente.impl; import com.github.thiagogarbazza.training.springangular.core.cliente.Cliente; import java.util.Collection; interface ClienteRepositoryCustom { Collection<Cliente> pesquisar(); }
Pep Guardiola says Manchester City are unlikely to be spending big in the January transfer window and would be happy to complete the season with the present squad. “I’m happy with what we have, I have confidence in the players,” the City manager said. “I’m not saying we won’t do anything in the window, you never know what might happen in a week or two, but at the moment we have no plans for a major signing. We can work with what we have and if we finish the season with these players that will be good.” City travel to Hull City on Boxing Day, something of a novelty for a manager used to winter breaks. “This will be my first time playing through Christmas, I haven’t been able to sleep,” Guardiola joked. “Now we have put a couple of wins together we need to try and keep the run going, though of course all the other teams in the Premier League will feel the same. This is an important stage of the season.” Leicester are struggling but Manchester City wrote the book on bad title defences | Jonathan Wilson Read more City are seven points behind Chelsea, with the manager envious of the leaders’ consistency. “There is no secret about why they are so far ahead,” he said. “If you win 11 games in a row, take 33 points from 33, that is what will happen,” he said. “They take their chances, in the right moment they are there. When they played us we did not allow them too many chances, but they took them all and won. Our problem has been not creating enough chances. We have been dominating games but have had difficulty making openings and scoring goals.” Bottom-of-the-table Hull represent a different challenge. Guardiola has been talking to some of his players about what to expect at the KC Stadium, but the coach has seen enough of lower table sides to imagine he will be in for a tough game. “What I have learned in my short time in England is that the gap between the clubs in the top half of the table and those at the bottom is not all that great. We will have to be prepared. I am not expecting an easy game.” Fernandinho is back from suspension for the visit to the east coast, Sergio Agüero completes the last match of his ban, and Pablo Zabaleta will have a late fitness test.
import * as Vector2D from "./vector-2d"; export interface ControlLine { readonly length: number; readonly angle: number; } export interface VertexProperty { readonly point: Vector2D.Unit; readonly controlLine: ControlLine; } export interface PathSegment { readonly controlPoint1: Vector2D.Unit; readonly controlPoint2: Vector2D.Unit; readonly targetPoint: Vector2D.Unit; } export interface Curve { readonly startPoint: Vector2D.Unit; readonly paths: readonly PathSegment[]; } export const createCurve = ( vertexPropertyList: readonly VertexProperty[] ): Curve => { const paths: PathSegment[] = []; const len = vertexPropertyList.length; let previousVertex = vertexPropertyList[0]; let previousControlLine = previousVertex.controlLine; for (let i = 1; i < len; i += 1) { const currentVertex = vertexPropertyList[i]; const currentControlLine = currentVertex.controlLine; paths.push({ controlPoint1: Vector2D.addPolar( previousVertex.point, 0.5 * previousControlLine.length, previousControlLine.angle ), controlPoint2: Vector2D.subtractPolar( currentVertex.point, 0.5 * currentControlLine.length, currentControlLine.angle ), targetPoint: currentVertex.point, }); previousVertex = currentVertex; previousControlLine = currentControlLine; } return { startPoint: vertexPropertyList[0].point, paths, }; };
def restart_workers_signal_callback(sender, instance, field_name, **kwargs): if settings.DEBUG: return prev = getattr(instance, "_original_{}".format(field_name)) curr = getattr(instance, "{}".format(field_name)) if field_name == "evaluation_script": instance._original_evaluation_script = curr elif field_name == "test_annotation": instance._original_test_annotation = curr if prev != curr: challenge = None if field_name == "test_annotation": challenge = instance.challenge else: challenge = instance response = restart_workers([challenge]) count, failures = response["count"], response["failures"] logger.info( "The worker service for challenge {} was restarted, as {} was changed.".format( challenge.pk, field_name ) ) if count != 1: logger.warning( "Worker(s) for challenge {} couldn't restart! Error: {}".format( challenge.id, failures[0]["message"] ) ) else: challenge_url = "https://{}/web/challenges/challenge-page/{}".format( settings.HOSTNAME, challenge.id ) challenge_manage_url = "https://{}/web/challenges/challenge-page/{}/manage".format( settings.HOSTNAME, challenge.id ) if field_name == "test_annotation": file_updated = "Test Annotation" elif field_name == "evaluation_script": file_updated = "Evaluation script" template_data = { "CHALLENGE_NAME": challenge.title, "CHALLENGE_MANAGE_URL": challenge_manage_url, "CHALLENGE_URL": challenge_url, "FILE_UPDATED": file_updated, } if challenge.image: template_data["CHALLENGE_IMAGE_URL"] = challenge.image.url template_id = settings.SENDGRID_SETTINGS.get("TEMPLATES").get( "WORKER_RESTART_EMAIL" ) emails = challenge.creator.get_all_challenge_host_email() for email in emails: send_email( sender=settings.CLOUDCV_TEAM_EMAIL, recipient=email, template_id=template_id, template_data=template_data, )
<reponame>0xen/EnteeZ #pragma once #include <EnteeZ/EntityManager.hpp> #include <EnteeZ\TemplatePair.hpp> #include <typeindex> #include <map> #include <vector> namespace enteez { class EnteeZ { public: // Create a instance of EnteeZ (Entity Component Manager) EnteeZ(); // Handle destruction of the object ~EnteeZ(); // Get the local instance of the entity manager // Entity manager is used to create and destroy entity instances EntityManager& GetEntityManager(); template<typename T, typename V> // Links internaly a object to what base classes it inherits from, EG: // class PlayerMovment : public Movment -> RegisterBase<PlayerMovment, Movment>(); void RegisterBase(); template<typename T, typename A, typename B, typename... bases> // Links internaly a object to what base classes it inherits from, EG: // class PlayerMovment : public Movment, public KeyboardHandler -> RegisterBase<PlayerMovment, Movment, KeyboardHandler>(); void RegisterBase(); // Allow entity manager access to our private members friend class EntityManager; private: template<typename T> // Get component index using x index storage map unsigned int GetIndex(std::map<std::type_index, unsigned int>& map); // Stores objects that are inherited from a component std::map<std::type_index, unsigned int> m_base_indexs; // Used to store the top level component std::map<std::type_index, unsigned int> m_component_indexs; // Stores What classes a component inherits std::map<unsigned int, std::vector<unsigned int>> m_component_bases; // Stores all the casting information required to cast void* to base class whilest retaining the top level inheritance std::map<unsigned int, std::map<unsigned int, TemplateBase*>> m_component_base_templates; // Local instance of the entity manager EntityManager m_entity_manager; }; template<typename T, typename V> // Links internaly a object to what base classes it inherits from, EG: // class PlayerMovment : public Movment -> RegisterBase<PlayerMovment, Movment>(); inline void EnteeZ::RegisterBase() { unsigned int component_index = GetIndex<T>(m_component_indexs); unsigned int base_index = GetIndex<V>(m_base_indexs); m_component_base_templates[component_index][base_index] = new TemplatePair<T, V>(); auto it = std::find(m_component_bases[base_index].begin(), m_component_bases[base_index].end(), component_index); if (it == m_component_bases[base_index].end()) { m_component_bases[base_index].push_back(component_index); } } template<typename T, typename A, typename B, typename... bases> // Links internaly a object to what base classes it inherits from, EG: // class PlayerMovment : public Movment, public KeyboardHandler -> RegisterBase<PlayerMovment, Movment, KeyboardHandler>(); inline void EnteeZ::RegisterBase() { // Extract the first component that is inherited and store it RegisterBase<T, A>(); // Call itself if there are 2+ base classes left or add if 1 left (as 'bases' will be 0 and we will be calling <T, B>) RegisterBase<T, B, bases...>(); } template<typename T> // Get component index using x index storage map inline unsigned int EnteeZ::GetIndex(std::map<std::type_index, unsigned int>& map) { auto found = map.find(std::type_index(typeid(T))); // If the component was not found if (found == map.end()) { // Add component to the map map[(std::type_index)std::type_index(typeid(T))] = (unsigned int)map.size(); return (unsigned int)map.size() - 1; } // Return the component index return found->second; } }
<gh_stars>10-100 package xyz.belvi.permissiondialog.Rationale; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import java.util.ArrayList; import xyz.belvi.permissiondialog.Permission.SmoothPermission; import static xyz.belvi.permissiondialog.Rationale.RationaleDialog.SMOOTH_PERMISSIONS; /** * Created by zone2 on 1/20/17. */ public class Rationale implements RationaleBuilder.PermissionBuild, RationaleBuilder.PermissionInit { private RationaleDialogBuilder permissionDialogBuilder; private Rationale(Activity activity) { permissionDialogBuilder = new RationaleDialogBuilder(activity); } private Rationale(Fragment fragment) { permissionDialogBuilder = new RationaleDialogBuilder(fragment); } /** * launching with a an activity * @param activity - activity to return response via onActivityResult */ public static RationaleBuilder.PermissionInit withActivity(Activity activity) { return new Rationale(activity); } /** * launching with a fragment * @param fragment - fragment to return response via onActivityResult */ public static RationaleBuilder.PermissionInit withFragment(Fragment fragment) { return new Rationale(fragment); } /** * add of permissions to run Rationale on * @param smoothPermission - list of permission * @return PermissionInit */ @Override public RationaleBuilder.PermissionInit addSmoothPermission(SmoothPermission... smoothPermission) { permissionDialogBuilder.addSmoothPermission(smoothPermission); return this; } /** * add of permissions to run Rationale on * @param smoothPermission - arraylist of permission * @return PermissionInit */ @Override public RationaleBuilder.PermissionInit addSmoothPermission(ArrayList<SmoothPermission> smoothPermission) { permissionDialogBuilder.addSmoothPermission(smoothPermission); return this; } /** * set request code to mark response from Rationale * @param requestCode - request code to to start Rationale and return via onActivityResult * @return PermissionInit */ @Override public RationaleBuilder.PermissionInit requestCode(int requestCode) { permissionDialogBuilder.requestCode(requestCode); return this; } /** * style the Rationale Dialog with @styleRes * @param styleRes - styleRes id * @return PermissionBuild */ @Override public RationaleBuilder.PermissionBuild includeStyle(int styleRes) { permissionDialogBuilder.includeStyle(styleRes); return this; } /** * set list of permissions to run Rationale on * @param smoothPermission - list of permissions * @return PermissionInit */ @Override public RationaleBuilder.PermissionInit setPermission(SmoothPermission... smoothPermission) { permissionDialogBuilder.setSmoothPermission(smoothPermission); return this; } /** * set list of permissions to run Rationale on * @param smoothPermission - arraylist of permissions * @return PermissionInit */ @Override public RationaleBuilder.PermissionInit setPermission(ArrayList<SmoothPermission> smoothPermission) { permissionDialogBuilder.setSmoothPermission(smoothPermission); return this; } /** * * @param buildAnyway - true if the Rationale should show permissions that not not been permanently denied. */ @Override public void build(boolean buildAnyway) { permissionDialogBuilder.build(buildAnyway); } public static Bundle bundleResponse(ArrayList<SmoothPermission> smoothPermissions, boolean userDecline) { Bundle bundle = new Bundle(); bundle.putParcelable(SMOOTH_PERMISSIONS, new RationaleResponse(smoothPermissions, smoothPermissions.size() > 0 && !userDecline, userDecline)); return bundle; } public static boolean isResultFromRationale(int requestCode, int expectedCode) { return requestCode == expectedCode; } public static boolean permissionResolved(Intent intent) { return intent.getIntExtra(RationaleBase.RESULT_TYPE, -1) == RationaleDialog.PERMISSION_RESOLVE; } public static boolean noAction(Intent intent) { return intent.getIntExtra(RationaleBase.RESULT_TYPE, -1) == RationaleDialog.NO_ACTION; } public static RationaleResponse getRationaleResponse(Intent intent) { if (permissionResolved(intent) || noAction(intent)) { RationaleResponse rationaleResponse = getResponse(intent); if (rationaleResponse != null) return rationaleResponse; } return null; } private static RationaleResponse getResponse(Intent intent) { Bundle bundle = intent.getBundleExtra(RationaleBase.RESULT_DATA); if (bundle != null) { RationaleResponse rationaleResponse = bundle.getParcelable(SMOOTH_PERMISSIONS); return rationaleResponse; } return null; } }
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_LINALG_FUNCTIONS_GENERAL_SQRTM_HPP_INCLUDED #define NT2_LINALG_FUNCTIONS_GENERAL_SQRTM_HPP_INCLUDED #include <nt2/linalg/functions/sqrtm.hpp> #include <nt2/core/container/table/table.hpp> #include <nt2/include/functions/tofloat.hpp> #include <nt2/include/functions/sqrt.hpp> #include <nt2/include/functions/diag_of.hpp> #include <nt2/include/functions/from_diag.hpp> #include <nt2/include/functions/isdiagonal.hpp> #include <nt2/include/functions/schur.hpp> #include <nt2/include/functions/mtimes.hpp> #include <nt2/include/functions/globalsum.hpp> #include <nt2/include/functions/zeros.hpp> #include <nt2/include/functions/eye.hpp> #include <nt2/include/functions/length.hpp> #include <nt2/include/functions/transpose.hpp> #include <nt2/include/functions/conj.hpp> #include <nt2/include/functions/real.hpp> #include <nt2/include/functions/colvect.hpp> #include <nt2/include/functions/cast.hpp> #include <complex> namespace nt2{ namespace ext { BOOST_DISPATCH_IMPLEMENT ( sqrtm_, tag::cpu_ , (A0) , ((ast_<A0, nt2::container::domain>)) ) { typedef typename A0::value_type value_type; typedef typename A0::index_type index_type; typedef table<value_type, index_type> result_type; NT2_FUNCTOR_CALL(1) { return doit(a0, typename meta::is_complex<value_type>::type()); } private : result_type doit(const A0 & a0, boost::mpl::false_ const &) const { typedef typename std::complex<value_type> cmplx_type; typedef nt2::table<cmplx_type, nt2::_2D> ctab_t; size_t n = length(a0); ctab_t q, t, r; tie(q, t) = schur(a0, nt2::cmplx_); compute(n, t, r); ctab_t x = nt2::mtimes( nt2::mtimes(q, r), nt2::trans(nt2::conj(q))); return nt2::real(x); //bool nzeig = any(diag_of(t)(_))(1); // if nzeig // warning(message('sqrtm:SingularMatrix')) // end } result_type doit(const A0 & a0, boost::mpl::true_ const &) const { typedef nt2::table<value_type, nt2::_2D> tab_t; size_t n = length(a0); tab_t q, t, r; tie(q, t) = schur(a0, nt2::cmplx_); compute(n, t, r); return nt2::mtimes( nt2::mtimes(q, r), nt2::trans(nt2::conj(q))); //bool nzeig = any(diag_of(t)(_))(1); // if nzeig // warning(message('sqrtm:SingularMatrix')) // end } template < class S > void compute(const size_t & n, const S& t, S& r) const { typedef typename S::value_type v_type; if (nt2::isdiagonal(t)) { r = nt2::from_diag(nt2::sqrt(nt2::diag_of(t))); } else { // Compute upper triangular square root R of T, a column at a time. r = nt2::zeros(n, n, meta::as_<v_type>()); for (size_t j=1; j <= n; ++j) { r(j,j) = nt2::sqrt(t(j,j)); for (size_t i=j-1; i >= 1; --i) { //itab_ k = _(i+1, j-1); v_type s = nt2::globalsum(nt2::multiplies(colvect(r(i,_(i+1, j-1))), colvect(r(_(i+1, j-1),j)))); // value_type s = nt2::mtimes(r(i,_(i+1, j-1)), r(_(i+1, j-1),j)); r(i,j) = (t(i,j) - s)/(r(i,i) + r(j,j)); } } } } }; BOOST_DISPATCH_IMPLEMENT ( sqrtm_, tag::cpu_ , (A0) , (scalar_<fundamental_<A0> >) ) { typedef A0 result_type; NT2_FUNCTOR_CALL(1) { return nt2::sqrt(a0); } }; } } #endif
The NFLPA has released its latest cap figures for the 2017 offseason, and the Eagles have a little less money than expected According to the NFLPA, the Eagles will carry over $7.9 million in cap space from 2016 into 2017, which is slightly less than the $8.25 million they were projected to carry over. Any money not spent in the 2016 season is allowed to be moved over to the 2017 payroll, giving teams more money and cap space. Here is a complete look at the Eagles' cap situation, and how the $7.9 million in carry over in cap space from 2016 will impact 2017. Projected Cap: Somewhere between $170 to $166 million. For this article, we will use $168 million. Roll Over: According to the NFLPA, the Eagles are set to roll over $7.9 million in cap space from the 2016 season to the 2017 offseason. Dead Money: The Eagles have $6.8 million in dead money on their books -- $5.5 million from Sam Bradford, and $904,000 from Eric Rowe. 10 steps to a perfect Eagles' offseason Contracts: The Eagles currently have $158 million in committed contracts for the 2017 season. They can release players to lower that number, but as of now, they enter the offseason with $158 million committed to next season. Cap Space: Using $168 million as the NFL cap, the Eagles have around $12 million in cap space ($168 million cap - $158 million in contracts - $6.8 million in dead money + $7.9 million in carry over) Rookies: The Eagles will have to budget around $5 million for their 2017 rookie class, which comes out of the $12 million cap space. That brings the Eagles down to $7 million. Free Agents: The following players are set to become free agents: LB Stephen Tulloch, CB Nolan Carroll, OL Stefen Wisniewski, DE Bryan Braman, DL Bennie Logan, LB Najee Goode, S Jaylen Watkins, RB Kenjon Barner, TE Trey Burton Biggest Cap Hits: The top five cap hits for next season are OT Jason Peters ($11.2 million), OT Lane Johnson ($10 million), DE Fletcher Cox ($9.4 million), DE Vinny Curry ($9 million) and DE Connor Barwin ($8.3 million) Possible Cap Casualties: Jason Peters: Cutting Peters would save $9.2 million, leave $2 million in dead cap Connor Barwin: Cutting Barwin would save $7.75 million, leave $600,000 in dead cap Ryan Mathews: Cutting Mathews would save $4 million, leave $1 million in dead cap Leodis McKelvin: Cutting McKelvin would save $3 million, leave $200,000 in dead cap Darren Sproles: Cutting Sproles would save $4 million, leave $0 in dead cap Realistic space: If the Eagles do move on from Barwin, Mathews, McKelvin and Sproles, the team would add an additional $18.75 million in cap space. Outside of Sproles, the team could move on from those players even if there wasn't cap incentives. It is also very possible the team could re-do the deals of Peters to lower his cap hit. If you add the possible money gained by releasing players, plus the $7 million they already have, the Eagles could go into the 2017 offseason with around $25 million in cap space. THE NO-HUDDLE SHOW: Are we still all-in on Carson Wentz? Eliot Shorr-Parks may be reached at eshorrpa@njadvancemedia.com. Follow him on Twitter @EliotShorrParks. Find NJ.com Eagles on Facebook.
/** * Adds <i>append</i> to <i>string</i> if <i>string</i> does not end with <i>append</i>. * @param string * @param append * @return */ @NotNull public static String appendIfNotPresent(@NotNull final String string, @NotNull final String append) { Objects.requireNonNull(string, "Provided string is null"); Objects.requireNonNull(append, "Append string is null"); if (string.endsWith(append)) { return string; } else { return string + append; } }
<reponame>sasigume/manoikura interface PostJsonData { slug: string; modified_gmt: string; // パース時にnullになる acf: { fetch_on_build?: boolean | null; }; } export type { PostJsonData };
HOST-PATHOGEN INTERACTION IN INFECTIONS DUE TO STAPHYLOCOCCUS AUREUS. STAPHYLOCOCCUS AUREUS VIRULENCE FACTORS. Staphylococcus aureus (S. aureus) is a major cause of hospital-acquired (HA-SA) and community-acquired (CA-SA) infections worldwide. It is isolated from many human body sites, from animals and from foods, from the environment. Pathogenesis is caused by many virulence factors and antibiotic resistance. The host immune system tries to keep under control this pathogen, but many virulence factors produced by this under the regulatory systems control attack the immune system. The epidemiology of S. aureus is in permanent dynamic and is changing quickly. Therefore, it is necessary to monitor infections, to find new effective molecules and vaccines against this pathogen. In order to reduce this problem which affects public health as a whole, the search for new therapeutic alternatives must be associated with policies to control antibiotic use. Community-acquired and hospital-acquired infections epidemiological surveillance guided by scientific studies should be constant habits among health professionals and hospitals.
<reponame>surgelt/sptingboot-cloud-st package com.ggj.encrypt.modules.base.controller; import java.util.Date; import com.ggj.encrypt.common.exception.BizException; import com.ggj.encrypt.common.utils.DateUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; /** * @author:gaoguangjin * @Description: * @Email:<EMAIL> * @Date 2016/4/25 13:54 */ @RestController @RequestMapping("/test") @Slf4j public class RestTemplateController extends BaseController{ @RequestMapping("{sign}/{id}") public String restTemplateClient(@PathVariable("sign") String sign,@PathVariable("id") String id) { return sign+id; } @RequestMapping("/exception/{type}") public String testException(@PathVariable("type")int type) throws Exception { if(type==1) { throw new Exception("异常"); }else{ throw new BizException("111","测试BizException"); } } // public static void main(String[] args) { // // String date= DateUtils.formatDate(new Date((System.currentTimeMillis())),"yyyy-MM-dd HH:mm:ss"); // String date= DateUtils.formatDate(new Date(1425860757000l),"yyyy-MM-dd HH:mm:ss"); // System.out.println(date); // } }
import { TestBed } from '@angular/core/testing'; import { TodosApi } from './todos.api'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { mockTodo, mockAllTodos } from '../mocks/todos.mock'; import { environment } from 'src/environments/environment'; describe('TodosApi', () => { let service: TodosApi; let httpTestingController: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ providers: [TodosApi], imports: [HttpClientTestingModule] }); }); beforeEach(() => { service = TestBed.inject(TodosApi); httpTestingController = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTestingController.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); describe('#list', () => { it('returned Observable should match the right data', () => { const searchQuery = 'search'; service.list(searchQuery) .subscribe(todos => { expect(todos[0].title).toEqual(mockAllTodos[0].title); expect(todos[1].title).toEqual(mockAllTodos[1].title); }); const req = httpTestingController .expectOne(`${environment.apiBaseUrl}/todos?search=${searchQuery}`); expect(req.request.method).toEqual('GET'); req.flush(mockAllTodos); }); }); describe('#create', async () => { it('returned Observable should match the right data', () => { service.create(mockTodo) .subscribe(todo => { expect(todo.title).toEqual(mockTodo.title); }); const req = httpTestingController.expectOne(`${environment.apiBaseUrl}/todos`); expect(req.request.method).toEqual('POST'); req.flush(mockTodo); }); }); describe('#remove', async () => { it('returned Observable should match the right data', () => { service.remove(mockTodo.id) .subscribe(todo => { expect(todo).toEqual(mockTodo); }); const req = httpTestingController.expectOne(`${environment.apiBaseUrl}/todos/${mockTodo.id}`); expect(req.request.method).toEqual('DELETE'); req.flush(mockTodo); }); }); describe('#toggleCompleted', async () => { it('returned Observable should match the right data', () => { service.toggleCompleted(mockTodo.id, true) .subscribe(todo => { expect(todo.id).toEqual(mockTodo.id); expect(todo.isCompleted).toEqual(true); }); const req = httpTestingController.expectOne(`${environment.apiBaseUrl}/todos/${mockTodo.id}`); expect(req.request.method).toEqual('PUT'); req.flush({ ...mockTodo, isCompleted: true}); }); }); });
/** * @author Andrea Schweer schweer@waikato.ac.nz for the LCoNZ Institutional Research Repositories */ public class SolrStorageService { private static final DateFormat ISO_DATE_FORMAT; static { ISO_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); ISO_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } private static final SolrServer solr; static { String solrUrl = "http://localhost:8080/solr/altmetrics"; solr = new HttpSolrServer(solrUrl); } public static final int COMMIT_DELAY = 500; public static void addOrUpdate(ProviderMetrics providerMetrics) throws StorageException { try { SolrInputDocument solrDoc = toSolrDoc(providerMetrics); if (solrDoc != null) { solr.add(solrDoc, COMMIT_DELAY); } } catch (IOException | SolrServerException e) { throw new StorageException("Problem saving metrics", e); } } public static ProviderMetrics findByHandleAndProvider(String handle, String provider) throws StorageException { NamedList<String> queryParams = new NamedList<>(); queryParams.add("q", String.format("handle:%s AND provider:%s", wildcardOrEscape(handle), wildcardOrEscape(provider))); queryParams.add("sort", "last-updated DESC"); queryParams.add("rows", "1"); try { QueryResponse response = solr.query(SolrParams.toSolrParams(queryParams)); SolrDocumentList results = response.getResults(); for (SolrDocument result : results) { ProviderMetrics metrics = fromSolrDoc(result); if (metrics != null) { return metrics; // return first non-null result } } return null; } catch (SolrServerException e) { throw new StorageException("Could not do query", e); } } static SolrInputDocument toSolrDoc(ProviderMetrics metrics) { if (metrics == null) { return null; } SolrInputDocument doc = new SolrInputDocument(); doc.setField("provider", metrics.getProvider()); doc.setField("handle", metrics.getHandle()); doc.setField("last-updated", metrics.getLastUpdated()); doc.setField("id", metrics.getProvider() + "-" + metrics.getHandle()); for (String key : metrics.getMetrics().keySet()) { Object value = metrics.getMetrics().get(key); if (value instanceof Integer) { doc.setField(key + "_i_metric", value); } else { doc.setField(key + "_s_metric", Objects.toString(value, "")); } } return doc; } static ProviderMetrics fromSolrDoc(SolrDocument doc) { if (doc == null) { return null; } ProviderMetrics metrics = new ProviderMetrics(); metrics.setProvider(Objects.toString(doc.getFieldValue("provider"), "")); metrics.setHandle(Objects.toString(doc.getFieldValue("handle"), "")); try { metrics.setLastUpdated((Date) doc.getFieldValue("last-updated")); } catch (ClassCastException e) { // ignore } Collection<String> fieldNames = doc.getFieldNames(); for (String fieldName : fieldNames) { if (fieldName.endsWith("_i_metric")) { String key = StringUtils.removeEnd(fieldName, "_i_metric"); Integer value; try { value = (Integer) doc.getFieldValue(fieldName); metrics.putMetric(key, value); } catch (ClassCastException e) { // ignore } } else if (fieldName.endsWith("_s_metric")) { String key = StringUtils.removeEnd(fieldName, "_s_metric"); Object value = doc.getFieldValue(fieldName); metrics.putMetric(key, Objects.toString(value, "")); } } return metrics; } public static void deleteLastUpdatedBefore(Date cutOff) throws StorageException { if (cutOff == null || cutOff.before(new Date())) { throw new StorageException("Cut-off needs to be non-null date in the past, is " + cutOff); } try { solr.deleteByQuery(String.format("last-updated:[* TO %s]", ISO_DATE_FORMAT.format(cutOff))); } catch (SolrServerException | IOException e) { throw new StorageException("Could not delete older than cut-off", e); } } public static void deleteByHandleAndProvider(String handle, String provider) throws StorageException { handle = wildcardOrEscape(handle); provider = wildcardOrEscape(provider); try { solr.deleteByQuery(String.format("handle:%s AND provider:%s", handle, provider), COMMIT_DELAY); } catch (SolrServerException | IOException e) { throw new StorageException("Could not delete by handle/provider", e); } } private static String wildcardOrEscape(String string) { if (StringUtils.isBlank(string)) { string = "*"; } else { string = ClientUtils.escapeQueryChars(string); } return string; } }
// CreateUser creates a new org based on seed data in the POST body func (srv Instance) CreateUser(w http.ResponseWriter, r *http.Request) { ctx := r.Context() defer srv.ST.L.Sync() sugar := srv.ST.L.Sugar() authLevel, ok := ctx.Value(authLevelCtxKey).(int) if !ok { panic("auth missing") } if authLevel == AuthUser { http.Error(w, "auth inadequate", http.StatusForbidden) return } body, err := io.ReadAll(r.Body) if err != nil { sugar.Debugw("read body", "reqid", middleware.GetReqID(ctx), "err", err) http.Error(w, "internal error", http.StatusInternalServerError) return } var m CreateUserMsg err = json.Unmarshal(body, &m) if err != nil { http.Error(w, "malformed user create", http.StatusBadRequest) return } derived, err := security.DerivePassword(m.Password, srv.ST.Argon2Cfg) if err != nil { sugar.Debugw("derive password", "reqid", middleware.GetReqID(ctx), "err", err) http.Error(w, "internal error", http.StatusInternalServerError) return } if m.Org == srv.ST.RootOrg { http.Error(w, "malformed user args", http.StatusForbidden) return } u, err := user.New(m.DisplayName, m.Email, m.Org, derived) if err != nil { http.Error(w, "malformed user args", http.StatusBadRequest) return } if authLevel == AuthOrg { session, ok := ctx.Value(sessionCtxKey).(Session) if !ok { panic("session missing") } if session.Org.ID != m.Org { http.Error(w, "not a member of requested org", http.StatusForbidden) return } } err = u.Insert(ctx, srv.ST.Master, srv.ST.Key) if err != nil { if err == models.ErrConflict { http.Error(w, "duplicate user args", http.StatusConflict) return } sugar.Debugw("insert user", "reqid", middleware.GetReqID(ctx), "err", err) http.Error(w, "internal error", http.StatusInternalServerError) return } w.Header().Set("location", UserRoute+"/"+u.ID) w.WriteHeader(http.StatusCreated) }
MOD = 10 ** 9 + 7 MAXN = 10 ** 5 + 123 MAXK = 22 fact = [1] inv = [1] s = [[ 0 for i in range(MAXK)] for j in range(MAXK)] s[0][0] = 1 for n in range(1, MAXK): for k in range(1, n + 1): s[n][k] = (s[n - 1][k - 1] + k * s[n - 1][k]) % MOD for i in range(1, MAXN): fact.append(fact[-1] * i % MOD) inv.append(pow(fact[-1], MOD - 2, MOD)) for _ in range(int(input())): n, k = map(int, input().split()) ans = 0 for parts in range(1, min(n, k) + 1): mult = s[k][parts] cur = fact[n] * inv[n - parts] * mult ans = (ans + cur) % MOD print(ans)
/** * retourne la distance en micro-seconde de l'obstacle a droite * (retourne 0 si aucun obstacle n'a ete detecte) * @return la distance en micro-seconde */ int detecteDroite() { int counter = 0; while (!(PINA & (1 << PA2))) { } while ((PINA & (1 << PA2)) != 0) { counter++; _delay_us(DELAI); if (counter > 3600) { return 0; } } return counter; }
def load_github_owners(neo4j_session: neo4j.Session, update_tag: int, repo_owners: List[Dict]) -> None: for owner in repo_owners: ingest_owner_template = Template(""" MERGE (user:$account_type{id: {Id}}) ON CREATE SET user.firstseen = timestamp() SET user.username = {UserName}, user.lastupdated = {UpdateTag} WITH user MATCH (repo:GitHubRepository{id: {RepoId}}) MERGE (user)<-[r:OWNER]-(repo) ON CREATE SET r.firstseen = timestamp() SET r.lastupdated = {UpdateTag}""") account_type = {'User': "GitHubUser", 'Organization': "GitHubOrganization"} neo4j_session.run( ingest_owner_template.safe_substitute(account_type=account_type[owner['type']]), Id=owner['owner_id'], UserName=owner['owner'], RepoId=owner['repo_id'], UpdateTag=update_tag, )
// IsSubscriptionActivated checks if the subscription is active or not. func IsSubscriptionActivated(sub *kymaeventingv1alpha1.Subscription) bool { eventActivatedCondition := kymaeventingv1alpha1.SubscriptionCondition{Type: kymaeventingv1alpha1.EventsActivated, Status: kymaeventingv1alpha1.ConditionTrue} knSubReadyCondition := kymaeventingv1alpha1.SubscriptionCondition{Type: kymaeventingv1alpha1.SubscriptionReady, Status: kymaeventingv1alpha1.ConditionTrue} return sub.HasCondition(eventActivatedCondition) && sub.HasCondition(knSubReadyCondition) }
// ----------------------------------------------------------------------------------- // lossflag - return true if loss calculation required // metrics - given input(s), target(s) & model output for the batch, calculate metrics // ----------------------------------------------------------------------------------- static bool lossflag(const Metrics& m) { for(auto k:m) if(k==Metric::loss || k==Metric::batchloss) return true; return false; }
/* * 码云 Open API * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * API version: 5.3.2 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) */ package gitee import ( "context" "fmt" "io/ioutil" "net/http" "net/url" "strings" "github.com/antihax/optional" ) // Linger please var ( _ context.Context ) type IssuesApiService service /* IssuesApiService 删除Issue某条评论 删除Issue某条评论 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param repo 仓库路径(path) * @param id 评论的ID * @param optional nil or *DeleteV5ReposOwnerRepoIssuesCommentsIdOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 */ type DeleteV5ReposOwnerRepoIssuesCommentsIdOpts struct { AccessToken optional.String } func (a *IssuesApiService) DeleteV5ReposOwnerRepoIssuesCommentsId(ctx context.Context, owner string, repo string, id int32, localVarOptionals *DeleteV5ReposOwnerRepoIssuesCommentsIdOpts) (*http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Delete") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/{repo}/issues/comments/{id}" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarPath = strings.Replace(localVarPath, "{"+"repo"+"}", fmt.Sprintf("%v", repo), -1) localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarHttpResponse, err } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } return localVarHttpResponse, newErr } return localVarHttpResponse, nil } /* IssuesApiService 获取某个企业的所有Issues 获取某个企业的所有Issues * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param enterprise 企业的路径(path/login) * @param optional nil or *GetV5EnterprisesEnterpriseIssuesOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "State" (optional.String) - Issue的状态: open(开启的), progressing(进行中), closed(关闭的), rejected(拒绝的)。 默认: open * @param "Labels" (optional.String) - 用逗号分开的标签。如: bug,performance * @param "Sort" (optional.String) - 排序依据: 创建时间(created),更新时间(updated_at)。默认: created_at * @param "Direction" (optional.String) - 排序方式: 升序(asc),降序(desc)。默认: desc * @param "Since" (optional.String) - 起始的更新时间,要求时间格式为 ISO 8601 * @param "Page" (optional.Int32) - 当前的页码 * @param "PerPage" (optional.Int32) - 每页的数量,最大为 100 * @param "Schedule" (optional.String) - 计划开始日期,格式:20181006T173008+80-20181007T173008+80(区间),或者 -20181007T173008+80(小于20181007T173008+80),或者 20181006T173008+80-(大于20181006T173008+80),要求时间格式为20181006T173008+80 * @param "Deadline" (optional.String) - 计划截止日期,格式同上 * @param "CreatedAt" (optional.String) - 任务创建时间,格式同上 * @param "FinishedAt" (optional.String) - 任务完成时间,即任务最后一次转为已完成状态的时间点。格式同上 * @param "Milestone" (optional.String) - 根据里程碑标题。none为没里程碑的,*为所有带里程碑的 * @param "Assignee" (optional.String) - 用户的username。 none为没指派者, *为所有带有指派者的 * @param "Creator" (optional.String) - 创建Issues的用户username * @param "Program" (optional.String) - 所属项目名称。none为没所属有项目的,*为所有带所属项目的 @return []Issue */ type GetV5EnterprisesEnterpriseIssuesOpts struct { AccessToken optional.String State optional.String Labels optional.String Sort optional.String Direction optional.String Since optional.String Page optional.Int32 PerPage optional.Int32 Schedule optional.String Deadline optional.String CreatedAt optional.String FinishedAt optional.String Milestone optional.String Assignee optional.String Creator optional.String Program optional.String } func (a *IssuesApiService) GetV5EnterprisesEnterpriseIssues(ctx context.Context, enterprise string, localVarOptionals *GetV5EnterprisesEnterpriseIssuesOpts) ([]Issue, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []Issue ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/enterprises/{enterprise}/issues" localVarPath = strings.Replace(localVarPath, "{"+"enterprise"+"}", fmt.Sprintf("%v", enterprise), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.State.IsSet() { localVarQueryParams.Add("state", parameterToString(localVarOptionals.State.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Labels.IsSet() { localVarQueryParams.Add("labels", parameterToString(localVarOptionals.Labels.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sort.IsSet() { localVarQueryParams.Add("sort", parameterToString(localVarOptionals.Sort.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Direction.IsSet() { localVarQueryParams.Add("direction", parameterToString(localVarOptionals.Direction.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Since.IsSet() { localVarQueryParams.Add("since", parameterToString(localVarOptionals.Since.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Page.IsSet() { localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PerPage.IsSet() { localVarQueryParams.Add("per_page", parameterToString(localVarOptionals.PerPage.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Schedule.IsSet() { localVarQueryParams.Add("schedule", parameterToString(localVarOptionals.Schedule.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Deadline.IsSet() { localVarQueryParams.Add("deadline", parameterToString(localVarOptionals.Deadline.Value(), "")) } if localVarOptionals != nil && localVarOptionals.CreatedAt.IsSet() { localVarQueryParams.Add("created_at", parameterToString(localVarOptionals.CreatedAt.Value(), "")) } if localVarOptionals != nil && localVarOptionals.FinishedAt.IsSet() { localVarQueryParams.Add("finished_at", parameterToString(localVarOptionals.FinishedAt.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Milestone.IsSet() { localVarQueryParams.Add("milestone", parameterToString(localVarOptionals.Milestone.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Assignee.IsSet() { localVarQueryParams.Add("assignee", parameterToString(localVarOptionals.Assignee.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Creator.IsSet() { localVarQueryParams.Add("creator", parameterToString(localVarOptionals.Creator.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Program.IsSet() { localVarQueryParams.Add("program", parameterToString(localVarOptionals.Program.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []Issue err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 获取企业的某个Issue 获取企业的某个Issue * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param enterprise 企业的路径(path/login) * @param number Issue 编号(区分大小写,无需添加 # 号) * @param optional nil or *GetV5EnterprisesEnterpriseIssuesNumberOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 @return Issue */ type GetV5EnterprisesEnterpriseIssuesNumberOpts struct { AccessToken optional.String } func (a *IssuesApiService) GetV5EnterprisesEnterpriseIssuesNumber(ctx context.Context, enterprise string, number string, localVarOptionals *GetV5EnterprisesEnterpriseIssuesNumberOpts) (Issue, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue Issue ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/enterprises/{enterprise}/issues/{number}" localVarPath = strings.Replace(localVarPath, "{"+"enterprise"+"}", fmt.Sprintf("%v", enterprise), -1) localVarPath = strings.Replace(localVarPath, "{"+"number"+"}", fmt.Sprintf("%v", number), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v Issue err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 获取企业某个Issue所有评论 获取企业某个Issue所有评论 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param enterprise 企业的路径(path/login) * @param number Issue 编号(区分大小写,无需添加 # 号) * @param optional nil or *GetV5EnterprisesEnterpriseIssuesNumberCommentsOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "Page" (optional.Int32) - 当前的页码 * @param "PerPage" (optional.Int32) - 每页的数量,最大为 100 @return []Note */ type GetV5EnterprisesEnterpriseIssuesNumberCommentsOpts struct { AccessToken optional.String Page optional.Int32 PerPage optional.Int32 } func (a *IssuesApiService) GetV5EnterprisesEnterpriseIssuesNumberComments(ctx context.Context, enterprise string, number string, localVarOptionals *GetV5EnterprisesEnterpriseIssuesNumberCommentsOpts) ([]Note, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []Note ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/enterprises/{enterprise}/issues/{number}/comments" localVarPath = strings.Replace(localVarPath, "{"+"enterprise"+"}", fmt.Sprintf("%v", enterprise), -1) localVarPath = strings.Replace(localVarPath, "{"+"number"+"}", fmt.Sprintf("%v", number), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Page.IsSet() { localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PerPage.IsSet() { localVarQueryParams.Add("per_page", parameterToString(localVarOptionals.PerPage.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []Note err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 获取企业某个Issue所有标签 获取企业某个Issue所有标签 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param enterprise 企业的路径(path/login) * @param number Issue 编号(区分大小写,无需添加 # 号) * @param optional nil or *GetV5EnterprisesEnterpriseIssuesNumberLabelsOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "Page" (optional.Int32) - 当前的页码 * @param "PerPage" (optional.Int32) - 每页的数量,最大为 100 @return []Label */ type GetV5EnterprisesEnterpriseIssuesNumberLabelsOpts struct { AccessToken optional.String Page optional.Int32 PerPage optional.Int32 } func (a *IssuesApiService) GetV5EnterprisesEnterpriseIssuesNumberLabels(ctx context.Context, enterprise string, number string, localVarOptionals *GetV5EnterprisesEnterpriseIssuesNumberLabelsOpts) ([]Label, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []Label ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/enterprises/{enterprise}/issues/{number}/labels" localVarPath = strings.Replace(localVarPath, "{"+"enterprise"+"}", fmt.Sprintf("%v", enterprise), -1) localVarPath = strings.Replace(localVarPath, "{"+"number"+"}", fmt.Sprintf("%v", number), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Page.IsSet() { localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PerPage.IsSet() { localVarQueryParams.Add("per_page", parameterToString(localVarOptionals.PerPage.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []Label err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 获取当前授权用户的所有Issues 获取当前授权用户的所有Issues * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param optional nil or *GetV5IssuesOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "Filter" (optional.String) - 筛选参数: 授权用户负责的(assigned),授权用户创建的(created),包含前两者的(all)。默认: assigned * @param "State" (optional.String) - Issue的状态: open(开启的), progressing(进行中), closed(关闭的), rejected(拒绝的)。 默认: open * @param "Labels" (optional.String) - 用逗号分开的标签。如: bug,performance * @param "Sort" (optional.String) - 排序依据: 创建时间(created),更新时间(updated_at)。默认: created_at * @param "Direction" (optional.String) - 排序方式: 升序(asc),降序(desc)。默认: desc * @param "Since" (optional.String) - 起始的更新时间,要求时间格式为 ISO 8601 * @param "Page" (optional.Int32) - 当前的页码 * @param "PerPage" (optional.Int32) - 每页的数量,最大为 100 * @param "Schedule" (optional.String) - 计划开始日期,格式:20181006T173008+80-20181007T173008+80(区间),或者 -20181007T173008+80(小于20181007T173008+80),或者 20181006T173008+80-(大于20181006T173008+80),要求时间格式为20181006T173008+80 * @param "Deadline" (optional.String) - 计划截止日期,格式同上 * @param "CreatedAt" (optional.String) - 任务创建时间,格式同上 * @param "FinishedAt" (optional.String) - 任务完成时间,即任务最后一次转为已完成状态的时间点。格式同上 @return []Issue */ type GetV5IssuesOpts struct { AccessToken optional.String Filter optional.String State optional.String Labels optional.String Sort optional.String Direction optional.String Since optional.String Page optional.Int32 PerPage optional.Int32 Schedule optional.String Deadline optional.String CreatedAt optional.String FinishedAt optional.String } func (a *IssuesApiService) GetV5Issues(ctx context.Context, localVarOptionals *GetV5IssuesOpts) ([]Issue, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []Issue ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/issues" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Filter.IsSet() { localVarQueryParams.Add("filter", parameterToString(localVarOptionals.Filter.Value(), "")) } if localVarOptionals != nil && localVarOptionals.State.IsSet() { localVarQueryParams.Add("state", parameterToString(localVarOptionals.State.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Labels.IsSet() { localVarQueryParams.Add("labels", parameterToString(localVarOptionals.Labels.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sort.IsSet() { localVarQueryParams.Add("sort", parameterToString(localVarOptionals.Sort.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Direction.IsSet() { localVarQueryParams.Add("direction", parameterToString(localVarOptionals.Direction.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Since.IsSet() { localVarQueryParams.Add("since", parameterToString(localVarOptionals.Since.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Page.IsSet() { localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PerPage.IsSet() { localVarQueryParams.Add("per_page", parameterToString(localVarOptionals.PerPage.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Schedule.IsSet() { localVarQueryParams.Add("schedule", parameterToString(localVarOptionals.Schedule.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Deadline.IsSet() { localVarQueryParams.Add("deadline", parameterToString(localVarOptionals.Deadline.Value(), "")) } if localVarOptionals != nil && localVarOptionals.CreatedAt.IsSet() { localVarQueryParams.Add("created_at", parameterToString(localVarOptionals.CreatedAt.Value(), "")) } if localVarOptionals != nil && localVarOptionals.FinishedAt.IsSet() { localVarQueryParams.Add("finished_at", parameterToString(localVarOptionals.FinishedAt.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []Issue err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 获取当前用户某个组织的Issues 获取当前用户某个组织的Issues * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param org 组织的路径(path/login) * @param optional nil or *GetV5OrgsOrgIssuesOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "Filter" (optional.String) - 筛选参数: 授权用户负责的(assigned),授权用户创建的(created),包含前两者的(all)。默认: assigned * @param "State" (optional.String) - Issue的状态: open(开启的), progressing(进行中), closed(关闭的), rejected(拒绝的)。 默认: open * @param "Labels" (optional.String) - 用逗号分开的标签。如: bug,performance * @param "Sort" (optional.String) - 排序依据: 创建时间(created),更新时间(updated_at)。默认: created_at * @param "Direction" (optional.String) - 排序方式: 升序(asc),降序(desc)。默认: desc * @param "Since" (optional.String) - 起始的更新时间,要求时间格式为 ISO 8601 * @param "Page" (optional.Int32) - 当前的页码 * @param "PerPage" (optional.Int32) - 每页的数量,最大为 100 * @param "Schedule" (optional.String) - 计划开始日期,格式:20181006T173008+80-20181007T173008+80(区间),或者 -20181007T173008+80(小于20181007T173008+80),或者 20181006T173008+80-(大于20181006T173008+80),要求时间格式为20181006T173008+80 * @param "Deadline" (optional.String) - 计划截止日期,格式同上 * @param "CreatedAt" (optional.String) - 任务创建时间,格式同上 * @param "FinishedAt" (optional.String) - 任务完成时间,即任务最后一次转为已完成状态的时间点。格式同上 @return []Issue */ type GetV5OrgsOrgIssuesOpts struct { AccessToken optional.String Filter optional.String State optional.String Labels optional.String Sort optional.String Direction optional.String Since optional.String Page optional.Int32 PerPage optional.Int32 Schedule optional.String Deadline optional.String CreatedAt optional.String FinishedAt optional.String } func (a *IssuesApiService) GetV5OrgsOrgIssues(ctx context.Context, org string, localVarOptionals *GetV5OrgsOrgIssuesOpts) ([]Issue, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []Issue ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/orgs/{org}/issues" localVarPath = strings.Replace(localVarPath, "{"+"org"+"}", fmt.Sprintf("%v", org), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Filter.IsSet() { localVarQueryParams.Add("filter", parameterToString(localVarOptionals.Filter.Value(), "")) } if localVarOptionals != nil && localVarOptionals.State.IsSet() { localVarQueryParams.Add("state", parameterToString(localVarOptionals.State.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Labels.IsSet() { localVarQueryParams.Add("labels", parameterToString(localVarOptionals.Labels.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sort.IsSet() { localVarQueryParams.Add("sort", parameterToString(localVarOptionals.Sort.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Direction.IsSet() { localVarQueryParams.Add("direction", parameterToString(localVarOptionals.Direction.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Since.IsSet() { localVarQueryParams.Add("since", parameterToString(localVarOptionals.Since.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Page.IsSet() { localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PerPage.IsSet() { localVarQueryParams.Add("per_page", parameterToString(localVarOptionals.PerPage.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Schedule.IsSet() { localVarQueryParams.Add("schedule", parameterToString(localVarOptionals.Schedule.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Deadline.IsSet() { localVarQueryParams.Add("deadline", parameterToString(localVarOptionals.Deadline.Value(), "")) } if localVarOptionals != nil && localVarOptionals.CreatedAt.IsSet() { localVarQueryParams.Add("created_at", parameterToString(localVarOptionals.CreatedAt.Value(), "")) } if localVarOptionals != nil && localVarOptionals.FinishedAt.IsSet() { localVarQueryParams.Add("finished_at", parameterToString(localVarOptionals.FinishedAt.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []Issue err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 获取某个Issue下的操作日志 获取某个Issue下的操作日志 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param number Issue 编号(区分大小写,无需添加 # 号) * @param optional nil or *GetV5ReposOwnerIssuesNumberOperateLogsOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "Repo" (optional.String) - 仓库路径(path) * @param "Sort" (optional.String) - 按递增(asc)或递减(desc)排序,默认:递减 @return []OperateLog */ type GetV5ReposOwnerIssuesNumberOperateLogsOpts struct { AccessToken optional.String Repo optional.String Sort optional.String } func (a *IssuesApiService) GetV5ReposOwnerIssuesNumberOperateLogs(ctx context.Context, owner string, number string, localVarOptionals *GetV5ReposOwnerIssuesNumberOperateLogsOpts) ([]OperateLog, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []OperateLog ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/issues/{number}/operate_logs" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarPath = strings.Replace(localVarPath, "{"+"number"+"}", fmt.Sprintf("%v", number), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Repo.IsSet() { localVarQueryParams.Add("repo", parameterToString(localVarOptionals.Repo.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sort.IsSet() { localVarQueryParams.Add("sort", parameterToString(localVarOptionals.Sort.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []OperateLog err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 仓库的所有Issues 仓库的所有Issues * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param repo 仓库路径(path) * @param optional nil or *GetV5ReposOwnerRepoIssuesOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "State" (optional.String) - Issue的状态: open(开启的), progressing(进行中), closed(关闭的), rejected(拒绝的)。 默认: open * @param "Labels" (optional.String) - 用逗号分开的标签。如: bug,performance * @param "Sort" (optional.String) - 排序依据: 创建时间(created),更新时间(updated_at)。默认: created_at * @param "Direction" (optional.String) - 排序方式: 升序(asc),降序(desc)。默认: desc * @param "Since" (optional.String) - 起始的更新时间,要求时间格式为 ISO 8601 * @param "Page" (optional.Int32) - 当前的页码 * @param "PerPage" (optional.Int32) - 每页的数量,最大为 100 * @param "Schedule" (optional.String) - 计划开始日期,格式:20181006T173008+80-20181007T173008+80(区间),或者 -20181007T173008+80(小于20181007T173008+80),或者 20181006T173008+80-(大于20181006T173008+80),要求时间格式为20181006T173008+80 * @param "Deadline" (optional.String) - 计划截止日期,格式同上 * @param "CreatedAt" (optional.String) - 任务创建时间,格式同上 * @param "FinishedAt" (optional.String) - 任务完成时间,即任务最后一次转为已完成状态的时间点。格式同上 * @param "Milestone" (optional.String) - 根据里程碑标题。none为没里程碑的,*为所有带里程碑的 * @param "Assignee" (optional.String) - 用户的username。 none为没指派者, *为所有带有指派者的 * @param "Creator" (optional.String) - 创建Issues的用户username * @param "Program" (optional.String) - 所属项目名称。none为没有所属项目,*为所有带所属项目的 @return []Issue */ type GetV5ReposOwnerRepoIssuesOpts struct { AccessToken optional.String State optional.String Labels optional.String Sort optional.String Direction optional.String Since optional.String Page optional.Int32 PerPage optional.Int32 Schedule optional.String Deadline optional.String CreatedAt optional.String FinishedAt optional.String Milestone optional.String Assignee optional.String Creator optional.String Program optional.String } func (a *IssuesApiService) GetV5ReposOwnerRepoIssues(ctx context.Context, owner string, repo string, localVarOptionals *GetV5ReposOwnerRepoIssuesOpts) ([]Issue, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []Issue ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/{repo}/issues" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarPath = strings.Replace(localVarPath, "{"+"repo"+"}", fmt.Sprintf("%v", repo), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.State.IsSet() { localVarQueryParams.Add("state", parameterToString(localVarOptionals.State.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Labels.IsSet() { localVarQueryParams.Add("labels", parameterToString(localVarOptionals.Labels.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sort.IsSet() { localVarQueryParams.Add("sort", parameterToString(localVarOptionals.Sort.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Direction.IsSet() { localVarQueryParams.Add("direction", parameterToString(localVarOptionals.Direction.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Since.IsSet() { localVarQueryParams.Add("since", parameterToString(localVarOptionals.Since.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Page.IsSet() { localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PerPage.IsSet() { localVarQueryParams.Add("per_page", parameterToString(localVarOptionals.PerPage.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Schedule.IsSet() { localVarQueryParams.Add("schedule", parameterToString(localVarOptionals.Schedule.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Deadline.IsSet() { localVarQueryParams.Add("deadline", parameterToString(localVarOptionals.Deadline.Value(), "")) } if localVarOptionals != nil && localVarOptionals.CreatedAt.IsSet() { localVarQueryParams.Add("created_at", parameterToString(localVarOptionals.CreatedAt.Value(), "")) } if localVarOptionals != nil && localVarOptionals.FinishedAt.IsSet() { localVarQueryParams.Add("finished_at", parameterToString(localVarOptionals.FinishedAt.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Milestone.IsSet() { localVarQueryParams.Add("milestone", parameterToString(localVarOptionals.Milestone.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Assignee.IsSet() { localVarQueryParams.Add("assignee", parameterToString(localVarOptionals.Assignee.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Creator.IsSet() { localVarQueryParams.Add("creator", parameterToString(localVarOptionals.Creator.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Program.IsSet() { localVarQueryParams.Add("program", parameterToString(localVarOptionals.Program.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []Issue err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 获取仓库所有Issue的评论 获取仓库所有Issue的评论 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param repo 仓库路径(path) * @param optional nil or *GetV5ReposOwnerRepoIssuesCommentsOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "Sort" (optional.String) - Either created or updated. Default: created * @param "Direction" (optional.String) - Either asc or desc. Ignored without the sort parameter. * @param "Since" (optional.String) - Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ * @param "Page" (optional.Int32) - 当前的页码 * @param "PerPage" (optional.Int32) - 每页的数量,最大为 100 @return Note */ type GetV5ReposOwnerRepoIssuesCommentsOpts struct { AccessToken optional.String Sort optional.String Direction optional.String Since optional.String Page optional.Int32 PerPage optional.Int32 } func (a *IssuesApiService) GetV5ReposOwnerRepoIssuesComments(ctx context.Context, owner string, repo string, localVarOptionals *GetV5ReposOwnerRepoIssuesCommentsOpts) (Note, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue Note ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/{repo}/issues/comments" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarPath = strings.Replace(localVarPath, "{"+"repo"+"}", fmt.Sprintf("%v", repo), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sort.IsSet() { localVarQueryParams.Add("sort", parameterToString(localVarOptionals.Sort.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Direction.IsSet() { localVarQueryParams.Add("direction", parameterToString(localVarOptionals.Direction.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Since.IsSet() { localVarQueryParams.Add("since", parameterToString(localVarOptionals.Since.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Page.IsSet() { localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PerPage.IsSet() { localVarQueryParams.Add("per_page", parameterToString(localVarOptionals.PerPage.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v Note err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 获取仓库Issue某条评论 获取仓库Issue某条评论 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param repo 仓库路径(path) * @param id 评论的ID * @param optional nil or *GetV5ReposOwnerRepoIssuesCommentsIdOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 @return Note */ type GetV5ReposOwnerRepoIssuesCommentsIdOpts struct { AccessToken optional.String } func (a *IssuesApiService) GetV5ReposOwnerRepoIssuesCommentsId(ctx context.Context, owner string, repo string, id int32, localVarOptionals *GetV5ReposOwnerRepoIssuesCommentsIdOpts) (Note, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue Note ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/{repo}/issues/comments/{id}" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarPath = strings.Replace(localVarPath, "{"+"repo"+"}", fmt.Sprintf("%v", repo), -1) localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v Note err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 仓库的某个Issue 仓库的某个Issue * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param repo 仓库路径(path) * @param number Issue 编号(区分大小写,无需添加 # 号) * @param optional nil or *GetV5ReposOwnerRepoIssuesNumberOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 @return Issue */ type GetV5ReposOwnerRepoIssuesNumberOpts struct { AccessToken optional.String } func (a *IssuesApiService) GetV5ReposOwnerRepoIssuesNumber(ctx context.Context, owner string, repo string, number string, localVarOptionals *GetV5ReposOwnerRepoIssuesNumberOpts) (Issue, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue Issue ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/{repo}/issues/{number}" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarPath = strings.Replace(localVarPath, "{"+"repo"+"}", fmt.Sprintf("%v", repo), -1) localVarPath = strings.Replace(localVarPath, "{"+"number"+"}", fmt.Sprintf("%v", number), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v Issue err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 获取仓库某个Issue所有的评论 获取仓库某个Issue所有的评论 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param repo 仓库路径(path) * @param number Issue 编号(区分大小写,无需添加 # 号) * @param optional nil or *GetV5ReposOwnerRepoIssuesNumberCommentsOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "Since" (optional.String) - Only comments updated at or after this time are returned. This is a timestamp in ISO 8601 format: YYYY-MM-DDTHH:MM:SSZ * @param "Page" (optional.Int32) - 当前的页码 * @param "PerPage" (optional.Int32) - 每页的数量,最大为 100 @return Note */ type GetV5ReposOwnerRepoIssuesNumberCommentsOpts struct { AccessToken optional.String Since optional.String Page optional.Int32 PerPage optional.Int32 } func (a *IssuesApiService) GetV5ReposOwnerRepoIssuesNumberComments(ctx context.Context, owner string, repo string, number string, localVarOptionals *GetV5ReposOwnerRepoIssuesNumberCommentsOpts) (Note, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue Note ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/{repo}/issues/{number}/comments" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarPath = strings.Replace(localVarPath, "{"+"repo"+"}", fmt.Sprintf("%v", repo), -1) localVarPath = strings.Replace(localVarPath, "{"+"number"+"}", fmt.Sprintf("%v", number), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Since.IsSet() { localVarQueryParams.Add("since", parameterToString(localVarOptionals.Since.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Page.IsSet() { localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PerPage.IsSet() { localVarQueryParams.Add("per_page", parameterToString(localVarOptionals.PerPage.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v Note err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 获取授权用户的所有Issues 获取授权用户的所有Issues * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param optional nil or *GetV5UserIssuesOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "Filter" (optional.String) - 筛选参数: 授权用户负责的(assigned),授权用户创建的(created),包含前两者的(all)。默认: assigned * @param "State" (optional.String) - Issue的状态: open(开启的), progressing(进行中), closed(关闭的), rejected(拒绝的)。 默认: open * @param "Labels" (optional.String) - 用逗号分开的标签。如: bug,performance * @param "Sort" (optional.String) - 排序依据: 创建时间(created),更新时间(updated_at)。默认: created_at * @param "Direction" (optional.String) - 排序方式: 升序(asc),降序(desc)。默认: desc * @param "Since" (optional.String) - 起始的更新时间,要求时间格式为 ISO 8601 * @param "Page" (optional.Int32) - 当前的页码 * @param "PerPage" (optional.Int32) - 每页的数量,最大为 100 * @param "Schedule" (optional.String) - 计划开始日期,格式:20181006T173008+80-20181007T173008+80(区间),或者 -20181007T173008+80(小于20181007T173008+80),或者 20181006T173008+80-(大于20181006T173008+80),要求时间格式为20181006T173008+80 * @param "Deadline" (optional.String) - 计划截止日期,格式同上 * @param "CreatedAt" (optional.String) - 任务创建时间,格式同上 * @param "FinishedAt" (optional.String) - 任务完成时间,即任务最后一次转为已完成状态的时间点。格式同上 @return []Issue */ type GetV5UserIssuesOpts struct { AccessToken optional.String Filter optional.String State optional.String Labels optional.String Sort optional.String Direction optional.String Since optional.String Page optional.Int32 PerPage optional.Int32 Schedule optional.String Deadline optional.String CreatedAt optional.String FinishedAt optional.String } func (a *IssuesApiService) GetV5UserIssues(ctx context.Context, localVarOptionals *GetV5UserIssuesOpts) ([]Issue, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Get") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue []Issue ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/user/issues" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarQueryParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Filter.IsSet() { localVarQueryParams.Add("filter", parameterToString(localVarOptionals.Filter.Value(), "")) } if localVarOptionals != nil && localVarOptionals.State.IsSet() { localVarQueryParams.Add("state", parameterToString(localVarOptionals.State.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Labels.IsSet() { localVarQueryParams.Add("labels", parameterToString(localVarOptionals.Labels.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Sort.IsSet() { localVarQueryParams.Add("sort", parameterToString(localVarOptionals.Sort.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Direction.IsSet() { localVarQueryParams.Add("direction", parameterToString(localVarOptionals.Direction.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Since.IsSet() { localVarQueryParams.Add("since", parameterToString(localVarOptionals.Since.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Page.IsSet() { localVarQueryParams.Add("page", parameterToString(localVarOptionals.Page.Value(), "")) } if localVarOptionals != nil && localVarOptionals.PerPage.IsSet() { localVarQueryParams.Add("per_page", parameterToString(localVarOptionals.PerPage.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Schedule.IsSet() { localVarQueryParams.Add("schedule", parameterToString(localVarOptionals.Schedule.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Deadline.IsSet() { localVarQueryParams.Add("deadline", parameterToString(localVarOptionals.Deadline.Value(), "")) } if localVarOptionals != nil && localVarOptionals.CreatedAt.IsSet() { localVarQueryParams.Add("created_at", parameterToString(localVarOptionals.CreatedAt.Value(), "")) } if localVarOptionals != nil && localVarOptionals.FinishedAt.IsSet() { localVarQueryParams.Add("finished_at", parameterToString(localVarOptionals.FinishedAt.Value(), "")) } // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v []Issue err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 更新Issue 更新Issue * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param number Issue 编号(区分大小写,无需添加 # 号) * @param body 可选。Issue 内容 @return Issue */ func (a *IssuesApiService) PatchV5ReposOwnerIssuesNumber(ctx context.Context, owner string, number string, body IssueUpdateParam) (Issue, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Patch") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue Issue ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/issues/{number}" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarPath = strings.Replace(localVarPath, "{"+"number"+"}", fmt.Sprintf("%v", number), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v Issue err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 更新Issue某条评论 更新Issue某条评论 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param repo 仓库路径(path) * @param id 评论的ID * @param body The contents of the comment. * @param optional nil or *PatchV5ReposOwnerRepoIssuesCommentsIdOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 @return Note */ type PatchV5ReposOwnerRepoIssuesCommentsIdOpts struct { AccessToken optional.String } func (a *IssuesApiService) PatchV5ReposOwnerRepoIssuesCommentsId(ctx context.Context, owner string, repo string, id int32, body string, localVarOptionals *PatchV5ReposOwnerRepoIssuesCommentsIdOpts) (Note, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Patch") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue Note ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/{repo}/issues/comments/{id}" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarPath = strings.Replace(localVarPath, "{"+"repo"+"}", fmt.Sprintf("%v", repo), -1) localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarFormParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } localVarFormParams.Add("body", parameterToString(body, "")) r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 200 { var v Note err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 创建Issue 创建Issue * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param title Issue标题 * @param optional nil or *PostV5ReposOwnerIssuesOpts - Optional Parameters: * @param "AccessToken" (optional.String) - 用户授权码 * @param "Repo" (optional.String) - 仓库路径(path) * @param "IssueType" (optional.String) - 企业自定义任务类型,非企业默认任务类型为“任务” * @param "Body" (optional.String) - Issue描述 * @param "Assignee" (optional.String) - Issue负责人的username * @param "Milestone" (optional.Int32) - 里程碑序号 * @param "Labels" (optional.String) - 用逗号分开的标签,名称要求长度在 2-20 之间且非特殊字符。如: bug,performance * @param "Program" (optional.String) - 项目ID @return Issue */ type PostV5ReposOwnerIssuesOpts struct { AccessToken optional.String Repo optional.String IssueType optional.String Body optional.String Assignee optional.String Milestone optional.Int32 Labels optional.String Program optional.String } func (a *IssuesApiService) PostV5ReposOwnerIssues(ctx context.Context, owner string, title string, localVarOptionals *PostV5ReposOwnerIssuesOpts) (Issue, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue Issue ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/issues" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } if localVarOptionals != nil && localVarOptionals.AccessToken.IsSet() { localVarFormParams.Add("access_token", parameterToString(localVarOptionals.AccessToken.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Repo.IsSet() { localVarFormParams.Add("repo", parameterToString(localVarOptionals.Repo.Value(), "")) } localVarFormParams.Add("title", parameterToString(title, "")) if localVarOptionals != nil && localVarOptionals.IssueType.IsSet() { localVarFormParams.Add("issue_type", parameterToString(localVarOptionals.IssueType.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Body.IsSet() { localVarFormParams.Add("body", parameterToString(localVarOptionals.Body.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Assignee.IsSet() { localVarFormParams.Add("assignee", parameterToString(localVarOptionals.Assignee.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Milestone.IsSet() { localVarFormParams.Add("milestone", parameterToString(localVarOptionals.Milestone.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Labels.IsSet() { localVarFormParams.Add("labels", parameterToString(localVarOptionals.Labels.Value(), "")) } if localVarOptionals != nil && localVarOptionals.Program.IsSet() { localVarFormParams.Add("program", parameterToString(localVarOptionals.Program.Value(), "")) } r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 201 { var v Issue err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil } /* IssuesApiService 创建某个Issue评论 创建某个Issue评论 * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param owner 仓库所属空间地址(企业、组织或个人的地址path) * @param repo 仓库路径(path) * @param number Issue 编号(区分大小写,无需添加 # 号) * @param body Issue comment内容 @return Note */ func (a *IssuesApiService) PostV5ReposOwnerRepoIssuesNumberComments(ctx context.Context, owner string, repo string, number string, body IssueCommentPostParam) (Note, *http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFileName string localVarFileBytes []byte localVarReturnValue Note ) // create path and map variables localVarPath := a.client.cfg.BasePath + "/v5/repos/{owner}/{repo}/issues/{number}/comments" localVarPath = strings.Replace(localVarPath, "{"+"owner"+"}", fmt.Sprintf("%v", owner), -1) localVarPath = strings.Replace(localVarPath, "{"+"repo"+"}", fmt.Sprintf("%v", repo), -1) localVarPath = strings.Replace(localVarPath, "{"+"number"+"}", fmt.Sprintf("%v", number), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header localVarHttpContentTypes := []string{"application/json", "multipart/form-data"} // set Content-Type header localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) if localVarHttpContentType != "" { localVarHeaderParams["Content-Type"] = localVarHttpContentType } // to determine the Accept header localVarHttpHeaderAccepts := []string{"application/json"} // set Accept header localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } // body params localVarPostBody = &body r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHttpResponse, err := a.client.callAPI(r) if err != nil || localVarHttpResponse == nil { return localVarReturnValue, localVarHttpResponse, err } localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) localVarHttpResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHttpResponse, err } if localVarHttpResponse.StatusCode < 300 { // If we succeed, return the data, otherwise pass on to decode error. err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err == nil { return localVarReturnValue, localVarHttpResponse, err } } if localVarHttpResponse.StatusCode >= 300 { newErr := GenericSwaggerError{ body: localVarBody, error: localVarHttpResponse.Status, } if localVarHttpResponse.StatusCode == 201 { var v Note err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) if err != nil { newErr.error = err.Error() return localVarReturnValue, localVarHttpResponse, newErr } newErr.model = v return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, newErr } return localVarReturnValue, localVarHttpResponse, nil }
/** * When a model is registered, the following steps have to be executed in order: * <ol> * <li>Registration of model metadata (mappable fields et. al.)</li> * <li>Addition of the model to the model registry for lookup</li> * <li>Refresh the resource to model adapter factory to include the model</li> * </ol> */ private void verifyResourceModelIsRegistered() { InOrder inOrder = Mockito.inOrder(this.resourceModelMetaDataRegistrar, this.modelRegistry, this.resourceToModelAdapterUpdater); inOrder.verify(this.resourceModelMetaDataRegistrar).register(isA(OsgiModelSource.class)); inOrder.verify(this.modelRegistry).add(eq(this.modelResourceTypes), isA(OsgiModelSource.class)); inOrder.verify(this.resourceToModelAdapterUpdater).refresh(); }
<gh_stars>1-10 package reformism import ( "bytes" "strings" "testing" "text/template" ) type testCase struct { template string argument interface{} expectedResult string hasError bool } var testCases = []testCase{ { template: ` {{define "foo"}} {{if $args := . | require "arg1" | require "arg2" "int" | args }} {{with .Origin }} {{.Bar}} {{$args.arg1}} {{ end }} {{ end }} {{ end }} {{template "foo" . | arg "arg1" "test" | arg "arg2" 42}} `, argument: map[string]string{ "Bar": "bar", }, expectedResult: "bartest", hasError: false, }, { template: ` {{define "foo"}} {{if $args := . | require "arg1" | require "arg2" "string" | args }} {{with .Origin }} {{.Bar}} {{$args.arg1}} {{ end }} {{ end }} {{ end }} {{template "foo" . | arg "arg1" "test" | arg "arg2" 42}} `, argument: map[string]string{ "Bar": "bar", }, expectedResult: "bartest", hasError: true, }, { template: ` {{ $x := slice 1 2 3 }} {{ range $y := $x }} {{$y}}, {{end}} `, argument: map[string]string{}, expectedResult: "1,2,3,", hasError: false, }, { template: ` {{ $m := map "foo" 1 | map "bar" 2 }} {{ range $k, $v := $m }} {{$k}}:{{$v}}, {{end}}`, argument: map[string]string{}, expectedResult: "bar:2,foo:1,", hasError: false, }, { template: ` {{ $r1 := rng 5 }} {{ range $e := $r1 }} {{$e}}, {{end}}`, argument: map[string]string{}, expectedResult: "0,1,2,3,4,", hasError: false, }, { template: ` {{ $r2 := rng 1 4 }} {{ range $e := $r2 }} {{$e}}, {{end}}`, argument: map[string]string{}, expectedResult: "1,2,3,", hasError: false, }, { template: ` {{ $r3 := rng 10 1 -3}} {{ range $e := $r3 }} {{$e}}, {{end}}`, argument: map[string]string{}, expectedResult: "10,7,4,", hasError: false, }, { template: ` {{ $r4 := rng 3 }} {{ $r4_1 := $r4 | append 3 4 }} {{ range $e := $r4_1 }} {{$e}}, {{end}}`, argument: map[string]string{}, expectedResult: "0,1,2,3,4,", hasError: false, }, { template: ` {{ . | split "," | join ";" }}`, argument: "1,2,3", expectedResult: "1;2;3", hasError: false, }, } func removeWhite(s string) string { toRemove := []string{ "\n", " ", "\t", } for _, r := range toRemove { s = strings.Replace(s, r, "", -1) } return s } func runTestCase(t *testing.T, tc testCase) { temp := template.Must( template.New("test_template").Funcs( FuncsText, ).Parse(tc.template)) buf := new(bytes.Buffer) err := temp.Execute(buf, tc.argument) if (err != nil) != tc.hasError { t.Errorf("haserror status unexpected. Expected %v, actual error %v", tc.hasError, err) } if !tc.hasError && removeWhite(buf.String()) != removeWhite(tc.expectedResult) { t.Errorf("Unexpected result. Expected: %s, Actual: %s", tc.expectedResult, buf.String()) } } func TestAll(t *testing.T) { for _, tc := range testCases { runTestCase(t, tc) } }
export const groupEntries = (rawPerformanceData: PerformanceEntry[][]): PerformanceEntry[][] => { const runs = rawPerformanceData; const combined = runs[0].reduce((result, pEntry) => { const sameEntries = runs.reduce((acc, v) => { const same = v.find((x) => x.entryType === pEntry.entryType && x.name === pEntry.name); same && acc.push(same); return acc; }, []); result.push(sameEntries); return result; }, [] as PerformanceEntry[][]); return combined; };
// newRaftTimerRand creates a raftTimer with randomized duration. func newRaftTimerRand(durationMin int64, durationMax int64) *raftTimer { return &raftTimer{ durationMin: durationMin, durationMax: durationMax, random: rand.New(rand.NewSource(time.Now().UnixNano())), timer: nil, } }
A campaign has been launched to stop UKIP leader Nigel Farage being elected as MP for Thanet South. Thanet Stand Up To UKIP is a group that claims to be supported by trade unions, local people, Labour and the Green Party as well as gay rights and disabled activists. The campaign has been launched even though UKIP has not officially announced Mr Farage is standing in the county. UKIP leader Nigel Farage has his eyes on a Kent seat Campaign co-ordinator Bunny La Roche said: "Local UKIP activists have said Farage is on the shortlist and that means he's bound to be chosen to run for Thanet South. "We are dismayed - he is part of the establishment, a hard-right Tory. He tries to present himself as the man of the people, he's not. He will only look after the interests of his class - the rich and powerful." Ms La Roche added she believes Mr Farage "has nothing to offer people of Thanet, except hatred, racism and bigotry". Thanet Stand Up To UKIP is asking people to use their vote to "stop Farage". Thanet Stand Up To UKIP campaign co-ordinator Bunny La Roche It plans a campaign of "meetings, producing publications, protests, and cultural events to get our message across south Thanet until Election Day in 2015". However, Tong Flaig from the Big News Margate blog said: "No doubt should Nigel Farage stand for election in Thanet he will of course be haunted by a ragbag of work-shy socialist 'workers' and 'activists' whose behaviour will range from borish to thuggish. "To be bullied by self-righteous lefties every bit as obnoxious as any imaginary neo-Nazis is clearly going to colour UKIP's campaign." Mr Farage is almost certain to stand in Thanet South in the general election - despite efforts to keep it under wraps. The local UKIP association had been expected to identify who was on its shortlist last week, but that was put on hold at the 11th and the association said it was now planning to release the details on the day the selection meeting takes place at the end of August. Stories you might have missed One in four Kent families struggle to make ends meet Uncle accused of saw attack on niece at home Shotgun text earns jealous lover another year in jail Heads up! Giraffe spotted on motorway in Kent
def clearOptionsMenu(self): return self._rpc("clearOptionsMenu")
# -*- coding: utf-8 -*- """ Created on Thu Dec 19 22:37:09 2019 @author: lucifer """ n=int(input()) if n%500==0: print(1000*int(n/500)) else: s=int(n/500) x=1000*s+int((n-(s*500))/5)*5 print(x)
/** * @Title c.c.k.util * @Copyright: Copyright 2019 * @Description: java <br/> * @Created on 2019/7/6 chenck */ public class ProduceUtil { public static final String GET_SERVER(){ return "http://PRODUCE-SERVICE"; } }
package navmeshv2 import ( "github.com/ferdoran/go-sro-agent-server/navmesh" ) type RtNavmeshInstObj struct { RtNavmeshInstBase Region Region WorldID int } func (inst *RtNavmeshInstObj) Read(reader *navmesh.Loader) { // TODO Implement panic("implement me") } //func NewRtNavmeshInstObj(mesh RtNavmesh) *RtNavmeshInstObj { // // TODO fill all fields? // return &RtNavmeshInstObj{ // RtNavmeshInstBase: RtNavmeshInstBase{ // Mesh: mesh, // Object: nil, // ID: 0, // Position: nil, // Rotation: nil, // Scale: nil, // LocalToWorld: nil, // WorldToLocal: nil, // }, // Region: nil, // WorldID: 0, // } //}
/** * Created by socheatkhauv on 6/26/17. */ public class CenterBuilder implements Serializable { private String id; private boolean hasId; public CenterBuilder withId(String id) { this.id = id; this.hasId = true; return this; } private String officeId; private boolean hasOfficeId; public CenterBuilder withOfficeId(String officeId) { this.officeId = officeId; this.hasOfficeId = true; return this; } private String externalId; private boolean hasExternalId; public CenterBuilder withExternalId(String externalId) { this.externalId = externalId; this.hasExternalId = true; return this; } private String name; private boolean hasName; public CenterBuilder withName(String name) { this.name = name; this.hasName = true; return this; } private boolean active; private boolean hasActive; public CenterBuilder withActive(boolean active) { this.active = active; this.hasActive = true; return this; } private Date activationDate; private boolean hasActivationDate; public CenterBuilder withActivationDate(Date activationDate) { this.activationDate = activationDate; this.hasActivationDate = true; return this; } private Date submittedOnDate; private boolean hasSubmittedOnDate; public CenterBuilder withSubmittedOnDate(Date submittedOnDate) { this.submittedOnDate = submittedOnDate; this.hasSubmittedOnDate = true; return this; } private List<String> groupMembers = Lists.newArrayList(); private boolean hasGroupMembers; public CenterBuilder withGroupMember(String clientMember) { this.groupMembers.add(clientMember); this.hasGroupMembers = true; return this; } private String dateFormat = "yyyy-MM-dd"; private boolean hasDateFormat = true; public CenterBuilder withDateFormat(String dateFormat) { this.dateFormat = dateFormat; this.hasDateFormat = true; return this; } private String locale = "en"; private boolean hasLocale = true; public CenterBuilder withLocale(String locale) { this.locale = locale; this.hasLocale = true; return this; } private String staffId; private boolean hasStaffId; public CenterBuilder withStaffId(String staffId) { this.staffId = staffId; this.hasStaffId = true; return this; } public JsonNode build() { JsonNode object = new com.angkorteam.fintech.dto.JsonNode(new JSONObject()); if (this.hasStaffId) { object.getObject().put("staffId", this.staffId); } if (this.hasGroupMembers) { object.getObject().put("groupMembers", this.groupMembers); } if (this.hasOfficeId) { object.getObject().put("officeId", this.officeId); } if (this.hasId) { object.getObject().put("id", this.id); } if (this.hasName) { object.getObject().put("name", this.name); } if (this.hasExternalId) { object.getObject().put("externalId", this.externalId); } if (this.hasDateFormat) { object.getObject().put("dateFormat", this.dateFormat); } if (this.hasLocale) { object.getObject().put("locale", this.locale); } if (this.hasActive) { object.getObject().put("active", this.active); } if (this.hasActivationDate) { if (this.activationDate == null) { object.getObject().put("activationDate", (String) null); } else { object.getObject().put("activationDate", DateFormatUtils.format(this.activationDate, this.dateFormat)); } } if (this.hasSubmittedOnDate) { if (this.submittedOnDate == null) { object.getObject().put("submittedOnDate", (String) null); } else { object.getObject().put("submittedOnDate", DateFormatUtils.format(this.submittedOnDate, this.dateFormat)); } } return object; } }
/** * Switches the plot background color between black and white. * */ void QHistogram::switchBackground() { QPen *pen = new QPen(Qt::white); if(canvasBackground() == Qt::white) { setCanvasBackground(Qt::black); p_zoomer->setRubberBandPen(*pen); p_zoomer->setTrackerPen(*pen); } else { setCanvasBackground(Qt::white); pen->setColor(Qt::black); p_zoomer->setRubberBandPen(*pen); p_zoomer->setTrackerPen(*pen); } replot(); }
/** * Journalist risk * @author Fabian Prasser */ public static class JournalistRisk extends RiskSummary { /** * Creates a new instance * @param rA * @param rB * @param rC */ protected JournalistRisk(double rA, double rB, double rC) { super(rA, rB, rC); } }
package study.daydayup.wolf.bigdata.datav.biz.dal.dao; import study.daydayup.wolf.bigdata.datav.biz.dal.dataobject.DailyRepayDO; public interface DailyRepayDAO { int deleteById(Long id); int insert(DailyRepayDO record); int insertSelective(DailyRepayDO record); DailyRepayDO selectById(Long id); int updateByIdSelective(DailyRepayDO record); int updateById(DailyRepayDO record); }
May 6, 2017 By Bruce Anderson & David Coletto In recent years, much of the political upheaval that has been seen in democracies including the UK and the US appears to have to do with the impacts of globalization and technology on the economic confidence of people. We decided to explore how Canadians perceive these topics. Here’s what we found. THE ROLE OF TECHNOLOGY The large majority believe that technological change has been good for the world (89%) and almost as many (76%) think it has been good for their own economic well-being. Most people (62%) also believe continued technological change is inevitable, “whether we like it or not”. The broad consensus that technological change has been good for the world crosses party lines, generations, and self-defined class status. Where some differences are apparent is when it comes to the personal benefits of technological change: baby boomers, NDP voters, and self-described working/lower class Canadians are less sure of the upside, but majorities in every case are of the view that the impact has been positive for them personally. THE ROLE OF GLOBALIZATION A two-thirds majority (68%) of Canadians believe that globalization has “helped raise the standard of living for many poor people around the world”. At the same time, almost half (43%) feel “globalization has been harmful to the economic well-being of a fair number of people in affluent countries”. On a personal level, one in three (32%) believe that “globalization has been bad for my own economic well-being.” Majorities among all generations, supporters of all parties and all classes believe globalization has helped the poor around the world, but New Democrats, baby boomers and those who consider themselves working/lower class are less convinced that this has happened. These differences are more muted when it comes to the number of people who say they have been hurt by the impact of globalization. THE FUTURE OF THE ECONOMY We asked whether people thought a variety of factors were likely to be more helpful or harmful to Canada’s future economic prospects. We found: • There is close to anonymity that technological advances and the Internet, in particular, are positive forces for the future of Canada’s economy. • Three out of four people (73%) think “globalization including trade agreements” will have a positive influence on Canada’s future. • Opinion is more uncertain and almost evenly split on the impact of immigration and “artificial intelligence and automation.” There are some important differences by class and partisanship. On artificial intelligence/ automation, the majority of those in the upper/upper middle class say this will be a positive force, while the majority of those who self-describe as working or lower class take the opposite view. A small majority (55%) of Liberals see it as a positive, while a small majority (55%) of New Democrats see it as a negative. On immigration, Conservatives see it as a negative, Liberals as a positive, and New Democrats are evenly split. Class based and age differences are also evident. On globalization, differences are much more muted. Lots of supporters of all major parties see a positive effect, as do all generations and different self-described classes. A complex relationship exists between these various points of confidence or apprehension. We’ll explore these relationships in more detail in an upcoming release about globalism and nationalism, however, some of the highlights that we see are as follows: • People who are pessimistic about Canada’s economic future are twice as likely to see immigration as a threat, compared to those who are optimistic. • An 18% segment of the adult population are fearful about the impact of technological advances, artificial intelligence, the Internet, globalization, and immigration. • A separate 28% segment are worried about artificial intelligence/automation and immigration but don’t show the same level of apprehension about other technological advances, or globalization. UPSHOT According to Bruce Anderson: “Canadian attitudes are different from those which have given rise to nationalist economic politics in the US and elsewhere. While opinion is somewhat divided on the upside of immigration, Canadians are fairly united when it comes to seeing the value of globalization and trade arrangements with other countries. The question of technology is becoming more complex or nuanced. On the whole, Canadians see big upsides to the technological revolution that has transformed world economies. However, there is already a fair bit of anxiety about the dislocation that may occur as a result of artificial intelligence and automation. The numbers signal some potential for these issues to become class-based and partisan in nature, but so far, the differences are more modest than they appear to be in other countries, where the debate about globalism and nationalism is front and centre, and already highly charged. Based on these patterns, it’s reasonable to expect that in Canada the policy pressures from the left will be about cushioning impacts of dislocation and creating new employment opportunities, while from the right they will include pressure on immigration.” According to David Coletto: “Although we find a broad consensus among Canadians for the value of technological advancement and globalization to Canada’s economic future, it doesn’t mean these attitudes are static. It wasn’t that long ago that Republicans in the United States were more likely to favour trade and international engagement. Today, their views have shifted markedly as political leaders such as Donald Trump and other Republicans have railed against globalism and trade. In Canada, the audience for these arguments is smaller but not politically insignificant. A growing opinion gap between those in different classes or educational groups suggests Canada is not immune to the forces of nationalism and anti-globalism. Managing these attitudes requires both political leadership that refuses to play upon these fears and economic and social policies that produce what some term “inclusive growth”. In a future release, we will explore in more depth the prevalence of globalist and nationalist attitudes in Canada and profile the size and make up of these two points of view that are shaping the economic and political life of countries across the developed world.” METHODOLOGY Our survey was conducted online with 1,500 Canadians aged 18 and over from April 21 to 24, 2017. A random sample of panelists was invited to complete the survey from a large representative panel of over 500,000 Canadians. The Marketing Research and Intelligence Association policy limits statements about margins of sampling error for most online surveys. The margin of error for a comparable probability-based random sample of 1,500 is +/- 2.6%, 19 times out of 20. The data were weighted according to census data to ensure that the sample matched Canada’s population according to age, gender, educational attainment, and region. Totals may not add up to 100 due to rounding. ABACUS DATA INC. We offer global research capacity with a strong focus on customer service, attention to detail and value-added insight. Our team combines the experience of our Chairman Bruce Anderson, one of Canada’s leading research executives for two decades, with the energy, creativity and research expertise of CEO David Coletto, Ph.D.
// Repeats a given character to a given amount public static void repeat(int num, String str){ for (int i = 0; i <= num; i++) { System.out.print(str); } System.out.println("\n"); }
/** * Abstract class for sheet containing information about the origins of an SPDX document * Specific versions implemented as subclasses * @author Gary O'Neall * */ public abstract class DocumentInfoSheet extends AbstractSheet { static final int SPREADSHEET_VERSION_COL = 0; static final int DATA_ROW_NUM = 1; protected String version; public DocumentInfoSheet(Workbook workbook, String sheetName, String version, IModelStore modelStore, ModelCopyManager copyManager) throws SpreadsheetException { super(workbook, sheetName, modelStore, null, copyManager); // Need to add or create the document from information in the spreadsheet this.documentUri = this.getNamespace(); if (Objects.isNull(this.documentUri)) { throw new SpreadsheetException("Missing document URI in the document sheet"); } Objects.requireNonNull(version, "Missing version"); Objects.requireNonNull(modelStore, "Missing required model store"); this.version = version; } /** * @param wb Workbook * @param sheetName Sheet name * @param documentUri Document URI */ public static void create(Workbook wb, String sheetName, String documentUri) { //NOTE: this must be updated to the latest version DocumentInfoSheetV2d0.create(wb, sheetName, documentUri); } /** * Open an existing worksheet * @param workbook * @param originSheetName * @param version Spreadsheet version * @param modelStore model store for the SPDX document * @param copyManager * @return * @throws SpreadsheetException */ public static DocumentInfoSheet openVersion(Workbook workbook, String originSheetName, String version, IModelStore modelStore, ModelCopyManager copyManager) throws SpreadsheetException { return new DocumentInfoSheetV2d0(workbook, originSheetName, version, modelStore, copyManager); } protected Row getDataRow() { return getDataRow(0); } protected Row getDataRow(int rowIndex) { while (firstRowNum + DATA_ROW_NUM + rowIndex > lastRowNum) { addRow(); } Row dataRow = sheet.getRow(firstRowNum + DATA_ROW_NUM + rowIndex); if (dataRow == null) { dataRow = sheet.createRow(firstRowNum + DATA_ROW_NUM + rowIndex); } return dataRow; } protected Cell getOrCreateDataCell(int colNum) { Cell cell = getDataRow().getCell(colNum); if (cell == null) { cell = getDataRow().createCell(colNum); //cell.setCellType(CellType.NUMERIC); } return cell; } protected void setDataCellStringValue(int colNum, String value) { getOrCreateDataCell(colNum).setCellValue(value); } protected void setDataCellDateValue(int colNum, Date value) { Cell cell = getOrCreateDataCell(colNum); cell.setCellValue(value); cell.setCellStyle(dateStyle); } protected Date getDataCellDateValue(int colNum) { Cell cell = getDataRow().getCell(colNum); if (cell == null) { return null; } else { return cell.getDateCellValue(); } } protected String getDataCellStringValue(int colNum) { Cell cell = getDataRow().getCell(colNum); if (cell == null) { return null; } else { if (cell.getCellType() == CellType.NUMERIC) { return Double.toString(cell.getNumericCellValue()); } else { return cell.getStringCellValue(); } } } /** * @param spdxVersion */ public abstract void setSPDXVersion(String spdxVersion); /** * @param createdBys */ public abstract void setCreatedBy(Collection<String> createdBys); /** * @param id */ public abstract void setDataLicense(String licenseId); /** * @param comments */ public abstract void setAuthorComments(String comments); /** * @param parse */ public abstract void setCreated(Date createdDate); /** * @return */ public abstract Date getCreated(); /** * @return */ public abstract List<String> getCreatedBy(); /** * @return */ public abstract String getAuthorComments(); /** * @return */ public abstract String getSPDXVersion(); /** * @return */ public abstract String getDataLicense(); /** * @return */ public abstract String getDocumentComment(); /** * @param docComment */ public abstract void setDocumentComment(String docComment); /** * @return */ public abstract String getLicenseListVersion(); /** * @param licenseVersion */ public abstract void setLicenseListVersion(String licenseVersion); /** * @return */ public abstract String getNamespace(); /** * Add all origin information from the document * @param doc * @throws SpreadsheetException */ public abstract void addDocument(SpdxDocument doc) throws SpreadsheetException; /** * @return SPDX Identifier for the document */ public abstract String getSpdxId(); /** * Set the SPDX identified for the document * @param id */ public abstract void setSpdxId(String id); /** * @return Document name */ public abstract String getDocumentName(); /** * Set the document name * @param documentName */ public abstract void setDocumentName(String documentName); /** * @return SPDX ID's for content described by this SPDX document */ public abstract Collection<String> getDocumentContents(); /** * Set the SPDX ID's for content described by this SPDX document * @param contents */ public abstract void setDocumentDescribes(Collection<String> contents); /** * @return External document refs * @throws SpreadsheetException */ public abstract Collection<ExternalDocumentRef> getExternalDocumentRefs() throws SpreadsheetException; /** * Set the external document refs * @param externalDocumentRefs * @throws SpreadsheetException */ public abstract void setExternalDocumentRefs(Collection<ExternalDocumentRef> externalDocumentRefs) throws SpreadsheetException; }
/** * Allows to control zones in a grouped manner. */ class GroupUI : public GUI, public PathBuilder { private: std::map<std::string, uiGroupItem*> fLabelZoneMap; void insertMap(std::string label, FAUSTFLOAT* zone) { if (!MapUI::endsWith(label, "/gate") && !MapUI::endsWith(label, "/freq") && !MapUI::endsWith(label, "/key") && !MapUI::endsWith(label, "/gain") && !MapUI::endsWith(label, "/vel") && !MapUI::endsWith(label, "/velocity")) { if (fLabelZoneMap.find(label) != fLabelZoneMap.end()) { fLabelZoneMap[label]->addZone(zone); } else { fLabelZoneMap[label] = new uiGroupItem(this, zone); } } } uiCallbackItem* fPanic; public: GroupUI(FAUSTFLOAT* zone, uiCallback cb, void* arg) { fPanic = new uiCallbackItem(this, zone, cb, arg); } virtual ~GroupUI() { } void openTabBox(const char* label) { pushLabel(label); } void openHorizontalBox(const char* label) { pushLabel(label); } void openVerticalBox(const char* label) { pushLabel(label); } void closeBox() { popLabel(); } void addButton(const char* label, FAUSTFLOAT* zone) { insertMap(buildPath(label), zone); } void addCheckButton(const char* label, FAUSTFLOAT* zone) { insertMap(buildPath(label), zone); } void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step) { insertMap(buildPath(label), zone); } void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step) { insertMap(buildPath(label), zone); } void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step) { insertMap(buildPath(label), zone); } void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT fmin, FAUSTFLOAT fmax) { insertMap(buildPath(label), zone); } void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT fmin, FAUSTFLOAT fmax) { insertMap(buildPath(label), zone); } }
#ifndef SVDSENSITIVITY_HH #define SVDSENSITIVITY_HH #include <Eigen/Dense> #include <array> #include <MeshFEM/EnergyDensities/Tensor.hh> // 2x2 case only for now, also can be sped up. struct SVDSensitivity { using M2d = Eigen::Matrix2d; using V2d = Eigen::Vector2d; SVDSensitivity() { } template<typename Derived> SVDSensitivity(const Eigen::MatrixBase<Derived> &A) { setMatrix(A); } template<typename Derived> void setMatrix(const Eigen::MatrixBase<Derived> &A) { static_assert((Derived::RowsAtCompileTime == 2) && (Derived::ColsAtCompileTime == 2), "Only 2x2 supported for now"); Eigen::JacobiSVD<M2d> svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV); m_U = svd.matrixU(); m_V = svd.matrixV(); m_Sigma = svd.singularValues(); // Cache first derivatives (needed for computing second derivatives) m_dSigma[0] = m_U.col(0) * m_V.col(0).transpose(); m_dSigma[1] = m_U.col(1) * m_V.col(1).transpose(); const double sigmaSqDiff = m_Sigma[0] * m_Sigma[0] - m_Sigma[1] * m_Sigma[1]; if (std::abs(sigmaSqDiff) < 1e-15) { m_degenerate = true; m_invSigmaSqDiff = 0.0; } else { m_degenerate = false; m_invSigmaSqDiff = 1.0 / sigmaSqDiff; } m_y = m_invSigmaSqDiff * (m_Sigma[1] * m_U.col(0) * m_V.col(1).transpose() + m_Sigma[0] * m_U.col(1) * m_V.col(0).transpose()); m_du0[0] = m_y * m_U(0, 1); m_du0[1] = m_y * m_U(1, 1); m_du1[0] = -m_y * m_U(0, 0); m_du1[1] = -m_y * m_U(1, 0); m_z = m_invSigmaSqDiff * (m_Sigma[0] * m_U.col(0) * m_V.col(1).transpose() + m_Sigma[1] * m_U.col(1) * m_V.col(0).transpose()); m_dv0[0] = m_z * m_V(0, 1); m_dv0[1] = m_z * m_V(1, 1); m_dv1[0] = -m_z * m_V(0, 0); m_dv1[1] = -m_z * m_V(1, 0); } // Access SVD const M2d & U() const { return m_U; } const M2d & V() const { return m_V; } const V2d &Sigma() const { return m_Sigma; } auto u(size_t i) const { return m_U.col(i); } auto v(size_t i) const { return m_V.col(i); } double sigma(size_t i) const { return m_Sigma[i]; } //////////////////////////////////////////////////////////////////////////// // First derivative expressions //////////////////////////////////////////////////////////////////////////// M2d dsigma(size_t i) const { return m_dSigma.at(i); } M2d du0 (size_t i) const { return m_du0 .at(i); } M2d du1 (size_t i) const { return m_du1 .at(i); } M2d dv0 (size_t i) const { return m_dv0 .at(i); } M2d dv1 (size_t i) const { return m_dv1 .at(i); } template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d dSigma(const M2d_ &dA) const { return V2d(doubleContract(m_dSigma[0], dA), doubleContract(m_dSigma[1], dA)); } template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d du0 (const M2d_ &dA) const { return V2d(doubleContract(m_du0 [0], dA), doubleContract(m_du0 [1], dA)); } template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d du1 (const M2d_ &dA) const { return V2d(doubleContract(m_du1 [0], dA), doubleContract(m_du1 [1], dA)); } template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d dv0 (const M2d_ &dA) const { return V2d(doubleContract(m_dv0 [0], dA), doubleContract(m_dv0 [1], dA)); } template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d dv1 (const M2d_ &dA) const { return V2d(doubleContract(m_dv1 [0], dA), doubleContract(m_dv1 [1], dA)); } template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> double dsigma(size_t i, const M2d_ &dA) const { return doubleContract(m_dSigma[i], dA); } //////////////////////////////////////////////////////////////////////////// // Second derivative expressions //////////////////////////////////////////////////////////////////////////// // Note, to avoid using high order tensors, we only provide the contraction of the // singular value/vector Hessians with perturbation matrices. // Second derivative of singular values with respect to variables inducing // perturbations dA_1 and dA_2, respectively. template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d d2Sigma(const M2d_ &dA_1, const M2d_ &dA_2) const { return V2d(du0(dA_2).dot((dA_1 * m_V.col(0)).matrix()) + m_U.col(0).dot((dA_1 * dv0(dA_2)).matrix()), du1(dA_2).dot((dA_1 * m_V.col(1)).matrix()) + m_U.col(1).dot((dA_1 * dv1(dA_2)).matrix())); } template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> double d2sigma(size_t i, const M2d_ &dA_1, const M2d_ &dA_2) const { if (i == 0) return du0(dA_2).dot((dA_1 * m_V.col(0)).matrix()) + m_U.col(0).dot((dA_1 * dv0(dA_2)).matrix()); if (i == 1) return du1(dA_2).dot((dA_1 * m_V.col(1)).matrix()) + m_U.col(1).dot((dA_1 * dv1(dA_2)).matrix()); throw std::runtime_error("Index out of bounds"); } // Second derivative of first left singular vector with respect to variables inducing // perturbations dA_1 and dA_2, respectively. template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d d2u0(const M2d_ &dA_1, const M2d_ &dA_2) const { M2d Ut_dA1_V = m_U.transpose() * (dA_1 * m_V); V2d d_sigma_d2 = dSigma(dA_2); const double y1 = doubleContract(m_y, dA_1); const double y2 = doubleContract(m_y, dA_2); const double z2 = doubleContract(m_z, dA_2); const double dy1_d2 = m_invSigmaSqDiff * (d_sigma_d2[1] * (2 * m_Sigma[1] * y1 + Ut_dA1_V(0, 1)) + d_sigma_d2[0] * (Ut_dA1_V(1, 0) - 2 * m_Sigma[0] * y1) + Ut_dA1_V(1, 1) * (m_Sigma[1] * y2 + m_Sigma[0] * z2) - Ut_dA1_V(0, 0) * (m_Sigma[0] * y2 + m_Sigma[1] * z2)); return dy1_d2 * m_U.col(1) - y1 * y2 * m_U.col(0); } // Second derivative of second right singular vector with respect to variables inducing // perturbations dA_1 and dA_2, respectively. // -d z_1 / d2 v0 - z_1 z_2 v1 // Note: "z" is the same as "y" with sigma_0 and sigma_1 swapped (apart from the m_invSigmaSqDiff factor). template<typename M2d_, EnableIfMatrixOfSize<M2d_, 2, 2, int> = 0> V2d d2v1(const M2d_ &dA_1, const M2d_ &dA_2) const { M2d Ut_dA1_V = m_U.transpose() * (dA_1 * m_V); V2d d_sigma_d2 = dSigma(dA_2); const double z1 = doubleContract(m_z, dA_1); const double z2 = doubleContract(m_z, dA_2); const double y2 = doubleContract(m_y, dA_2); const double dz1_d2 = m_invSigmaSqDiff * (d_sigma_d2[0] * (Ut_dA1_V(0, 1) - 2 * m_Sigma[0] * z1) + d_sigma_d2[1] * (Ut_dA1_V(1, 0) + 2 * m_Sigma[1] * z1) + Ut_dA1_V(1, 1) * (m_Sigma[0] * y2 + m_Sigma[1] * z2) - Ut_dA1_V(0, 0) * (m_Sigma[1] * y2 + m_Sigma[0] * z2)); return -dz1_d2 * m_V.col(0) - z1 * z2 * m_V.col(1); } EIGEN_MAKE_ALIGNED_OPERATOR_NEW private: M2d m_U, m_V, m_y, m_z; V2d m_Sigma; bool m_degenerate; double m_invSigmaSqDiff; std::array<M2d, 2> m_dSigma; std::array<M2d, 2> m_du0, m_du1, m_dv0, m_dv1; }; #endif /* end of include guard: SVDSENSITIVITY_HH */
// BWString.cpp // A simple smart string class // (c) 1995-2018 <NAME> <http://bw.org/> // version as of 2018-10-12 #include "BWString.h" // MARK: - constructors/destructors BWString::BWString( ) { reset(); } BWString::BWString( const char * s ) { copy_str(s); } BWString::BWString( const BWString & old ) { copy_str(old); } BWString::~BWString() { reset(); } // move constructor BWString::BWString( BWString && other ) noexcept { reset(); _str = other._str; _str_len = other._str_len; other._str = nullptr; other._str_len = 0; other.reset(); } // MARK: - private methods void BWString::_reset_split_array() const { if (_split_count) { // dtor the elements in the array while(_split_count) { _split_array[--_split_count].reset(); } _split_array.reset(); _split_count = 0; } } void BWString::_append_split_array(const BWString & s) const { if (_split_count >= _bwstring_max_split) return; if (!_split_count) { _split_array.reset(new _bwsp[_bwstring_max_split + 1]); } _split_array[_split_count] = std::make_shared<BWString>(s); ++ _split_count; } // MARK: - public methods const char * BWString::alloc_str( size_t sz ) { if (_str) reset(); _str_len = (sz > _bwstring_max_len) ? _bwstring_max_len : sz; _str = new char[_str_len + 1](); // new char[]() fills with 0 return _str; } void BWString::reset() { _reset_split_array(); if(_str) { delete [] _str; _str = nullptr; _str_len = 0; } } void BWString::swap(BWString & other) { std::swap(_str, other._str); std::swap(_str_len, other._str_len); } const char * BWString::c_str() const { return _str; } const char * BWString::copy_str( const char * s) { if(s) { size_t len = strnlen(s, _bwstring_max_len); alloc_str(len); strncpy((char *)_str, s, len); _str_len = len; } return _str; } // MARK: - operators // copy-and-swap assignment BWString & BWString::operator = ( BWString other ) { swap(other); return *this; } BWString & BWString::operator += ( const char * rhs ) { if(rhs) { size_t newlen = _str_len + strnlen(rhs, _bwstring_max_len); if (newlen > _bwstring_max_len) newlen = _bwstring_max_len; size_t rhslen = newlen - _str_len; if(rhslen < 1) return *this; char * buf = new char[newlen + 1](); if(_str && _str_len) memcpy(buf, _str, _str_len); memcpy(buf + _str_len, rhs, rhslen); copy_str(buf); delete [] buf; } return *this; } BWString & BWString::operator += ( const BWString & rhs ) { operator+=(rhs.c_str()); return *this; } const char BWString::operator[] ( const int index ) const { if(index < 0) return 0; if(index >= (int) _str_len) return 0; else return _str[index]; } // MARK: - comparison operators bool BWString::operator == ( const BWString & rhs ) const { if( std::strncmp(this->c_str(), rhs.c_str(), _bwstring_max_len) == 0 ) return true; else return false; } bool BWString::operator != ( const BWString & rhs ) const { if( std::strncmp(this->c_str(), rhs.c_str(), _bwstring_max_len) != 0 ) return true; else return false; } bool BWString::operator > ( const BWString & rhs ) const { if( std::strncmp(this->c_str(), rhs.c_str(), _bwstring_max_len) > 0 ) return true; else return false; } bool BWString::operator < ( const BWString & rhs ) const { if( std::strncmp(this->c_str(), rhs.c_str(), _bwstring_max_len) < 0 ) return true; else return false; } bool BWString::operator >= ( const BWString & rhs ) const { if( std::strncmp(this->c_str(), rhs.c_str(), _bwstring_max_len) >= 0 ) return true; else return false; } bool BWString::operator <= ( const BWString & rhs ) const { if( std::strncmp(this->c_str(), rhs.c_str(), _bwstring_max_len) <= 0 ) return true; else return false; } // MARK: - conversion operators BWString::operator const char * () const { return c_str(); } // MARK: - Utility methods bool BWString::have_value() const { if(_str) return true; else return false; } // string format BWString & BWString::format( const char * format , ... ) { char * buffer; va_list args; va_start(args, format); vasprintf(&buffer, format, args); copy_str(buffer); free(buffer); // vasprintf uses malloc return *this; } // trim leading and trailing spaces BWString & BWString::trim() { const static char * whitespace = "\x20\x1b\t\r\n\v\b\f\a"; if(!have_value()) return *this; // make sure we have a string size_t begin = 0; size_t end = length() - 1; for (begin = 0; begin <= end; ++begin) { if (strchr(whitespace, _str[begin]) == nullptr) { break; } } for ( ; end > begin; --end) { if (strchr(whitespace, _str[end]) == nullptr) { break; } else { _str[end] = '\0'; } } if (begin) { for (size_t i = 0; _str[i]; ++i) { _str[i] = _str[begin++]; } } _str_len = strlen(_str); return *this; } BWString BWString::lower() const { BWString rs = *this; for (size_t i = 0; rs._str[i]; ++i) { rs._str[i] = tolower(rs._str[i]); } return rs; } BWString BWString::upper() const { BWString rs = *this; for (size_t i = 0; rs._str[i]; ++i) { rs._str[i] = toupper(rs._str[i]); } return rs; } const char & BWString::back() const { return _str[length() - 1]; } const char & BWString::front() const { return _str[0]; } // MARK: - find and replace methods long int BWString::char_find( const char & match ) const { for (size_t i = 0; _str[i]; ++i) { if(_str[i] == match) return i; } return -1; } const BWString & BWString::char_repl( const char & match, const char & repl ) { for (size_t i = 0; _str[i]; ++i) { if(_str[i] == match) _str[i] = repl; } return *this; } BWString BWString::substr( size_t start, size_t length ) { BWString rs; char * buf; if ((length + 1) > _bwstring_max_len || (start + length) > _bwstring_max_len) return rs; if (length > _str_len - start) return rs; if (!_str) return rs; buf = new char[length + 1](); memcpy(buf, _str + start, length); rs = buf; delete [] buf; return rs; } long BWString::find( const BWString & match ) const { char * pos = strstr(_str, match.c_str()); if(pos) return (long) ( pos - _str ); else return -1; } const BWString BWString::replace( const BWString & match, const BWString & repl ) { BWString rs; long f1 = find(match); if (f1 >= 0) { size_t pos1 = (size_t) f1; size_t pos2 = pos1 + match.length(); BWString s1 = pos1 > 0 ? substr(0, pos1) : ""; BWString s2 = substr(pos2, length() - pos2); rs = s1 + repl + s2; } return rs; } // MARK: - split methods // non-destructive split const BWString::split_ptr & BWString::split( const char match ) const { const char match_s[2] = { match, 0 }; return split(match_s, -1); } const BWString::split_ptr & BWString::split( const char * match ) const { return split(match, -1); } const BWString::split_ptr & BWString::split( const char * match, int max_split ) const { _reset_split_array(); if (length() < 1) return _split_array; if (max_split < 0) max_split = _bwstring_max_split; size_t match_len = strnlen(match, _bwstring_max_len); if(match_len >= _bwstring_max_len) return _split_array; char * mi; // match index char * pstr = _str; // string pointer while (( mi = strstr(pstr, match)) && --max_split ) { if(mi != pstr) { size_t lhsz = mi - pstr; char * cslhs = new char[lhsz + 1](); memcpy(cslhs, pstr, lhsz); _append_split_array(cslhs); delete [] cslhs; pstr += lhsz; } pstr += match_len; } if (*pstr != '\0') { _append_split_array(pstr); } return _split_array; } // zero-based index of _split_array const BWString & BWString::split_item( size_t index ) const { if(_split_count > index) return *_split_array[index]; else return *this; } // MARK: - non-member operator overloads BWString operator + ( const BWString & lhs, const BWString & rhs ) { BWString rs = lhs; rs += rhs; return rs; } #ifdef _MSC_VER // MARK: - MS missing standard-ish functions int vasprintf(char ** ret, const char * format, va_list ap) { int len; char *buffer; len = _vscprintf(format, ap) + 1; buffer = (char *) malloc(len * sizeof(char)); if (!buffer) return 0; vsprintf_s(buffer, len, format, ap); *ret = buffer; return len -1; } #endif // _MSC_VER
Exploring reasons for variation in urinary catheterisation prevalence in care homes: a qualitative study. Only 35% of the hospital inpatients who were prescribed opioid analgesia experienced adequate pain control. Poor pain relief was significantly associated with the presence of side effects, higher pain intensity, prescription of regular opioids without as-needed doses and lower received opioid doses. Young and middle-aged patients were significantly more likely to report side effects than older patients. Pain intensity did not vary across age groups. Older patients were prescribed and administered lower doses of opioids than middle-aged patients.
import { BoxGeometry, Mesh, MeshPhongMaterial } from "three"; export default class Blade { private _mesh: Mesh = new Mesh(); constructor(colors: any) { const geom = new BoxGeometry(1,100,20,1,1,1); const mat = new MeshPhongMaterial({ color: colors.brownDark, flatShading: true }); const blade = new Mesh(geom, mat); blade.position.set(8,0,0); blade.castShadow = true; blade.receiveShadow = true; this.mesh = blade; } get mesh () { return this._mesh; } set mesh(set: Mesh) { this._mesh = set; } }
#include <cstdio> int main() { int two_gram[27][27] = {}; int n; char str[128]; scanf("%d %s", &n, str); n--; for(int i = 0; i < n; ++i) two_gram[str[i] - 'A'][str[i + 1] - 'A']++; int a, b; a = b = 0; for(int i = 0; i < 27; ++i) for(int j = 0; j < 27; ++j) if(two_gram[i][j] > two_gram[a][b]) { a = i; b = j; } printf("%c%c\n", a + 'A', b + 'A'); return 0; }
// draw the third kind of combined pillar void Pillar::drawPillarCombined3() { Hat* hat = new Hat(2, "C:/Users/41713/Desktop/Academic/Year4_Autumn/computer_graphics/project/texture/stoneWall3.bmp"); hat->size(0.2f); GLUquadricObj* objCylinder1 = gluNewQuadric(); gluQuadricTexture(objCylinder1, GLU_TRUE); gluQuadricDrawStyle(objCylinder1, GLU_FILL); glBindTexture(GL_TEXTURE_2D, texID); glPushMatrix(); glScalef(0.4f, 4.0f, 0.4f); drawPillarPrism(); glPopMatrix(); glPushMatrix(); glTranslatef(0.0f, 4.0f, 0.0f); glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); gluCylinder(objCylinder1, 0.4f, 0.7f, 0.1f, 8.0f, 32.0f); glPopMatrix(); glPushMatrix(); glTranslatef(0.0f, 4.1f, 0.0f); glRotatef(-90.0f, 1.0f, 0.0f, 0.0f); gluCylinder(objCylinder1, 0.7f, 0.0f, 0.0f, 8.0f, 32.0f); glPopMatrix(); glPushMatrix(); glTranslatef(0.0f, 5.0f, 0.0f); hat->Display(); glPopMatrix(); }
<reponame>secona/todo-list import { RequestHandler } from 'express'; import todoService from '../services/todo.service'; const todoController: Record< 'all' | 'new' | 'getById' | 'updateById' | 'deleteById', RequestHandler > = { all: (req, res, next) => { todoService .getAllUserTodos(req.user!) .then(todo => res.status(200).json({ success: true, data: { todo }, }) ) .catch(next); }, new: (req, res, next) => { todoService .newTodo(req.user!, req.body) .then(todo => { res.status(201).json({ success: true, data: { todo }, }); }) .catch(next); }, getById: (req, res) => { res.status(200).json({ data: { todo: req.todo }, }); }, updateById: (req, res, next) => { todoService .updateTodo(req.todo!, req.body) .then(todo => res.status(200).json({ success: true, message: `updated todo with id "${todo?._id}"`, data: { todo }, }) ) .catch(next); }, deleteById: (req, res, next) => { const { todoId } = req.params; todoService .deleteTodo(req.todo!) .then(() => res.status(200).json({ success: true, message: `deleted todo with id "${todoId}"`, data: { todo: null }, }) ) .catch(next); }, }; export default todoController;
/* ### * IP: GHIDRA * * 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 docking.widgets.table; import javax.swing.JTable; import javax.swing.table.*; /** * A utility class for JTables used in Ghidra. */ public class TableUtils { /** * Attempts to sort the given table based upon the given column index. If the {@link TableModel} * of the given table is not a {@link SortedTableModel}, then this method will do nothing. * <p> * If the given column index is not sortable, then this method will not change the state of * the model. Otherwise, the sorted model will be sorted on the given column index. The * results of calling this method depend upon the current sorted state of the given column: * <ol> * <li>if the column is not yet the sorted column, then the column is made the sorted * column, if sortable, <b>and any other sorted columns will be made unsorted</b>, or</li> * <li>if the column is the sorted column and the direction will simply be toggled.</li> * </ol> * * @param table The table whose model shall be sorted. * @param columnIndex The column index upon which to sort. */ public static void columnSelected(JTable table, int columnIndex) { SortedTableModel sortedModel = getSortedTableModel(table); if (sortedModel == null) { return; } int modelColumnIndex = getColumnModelIndex(table, columnIndex); if (modelColumnIndex < 0) { return; } if (!sortedModel.isSortable(modelColumnIndex)) { return; } TableSortState columnSortStates = sortedModel.getTableSortState(); TableSortStateEditor editor = new TableSortStateEditor(columnSortStates); if (editor.isColumnSorted(modelColumnIndex)) { editor.flipColumnSortDirection(modelColumnIndex); } else { editor.clear(); editor.addSortedColumn(modelColumnIndex); } sortedModel.setTableSortState(editor.createTableSortState()); repaintTableHeader(table); } /** * Attempts to sort the given table based upon the given column index. If the {@link TableModel} * of the given table is not a {@link SortedTableModel}, then this method will do nothing. * <p> * If the given column index is not sortable, then this method will not change the state of * the model. The results of calling this method depend upon the current sorted state * of the given column: * <ol> * <li>if the column is not yet sorted, then the column is made sorted, if sortable, * <b>and any other sorted columns will not be changed</b>, or</li> * <li>if the column is sorted, then: * <ol> * <li>if there are other sorted columns, this column will no longer be sorted</li> * <li>if there are no other sorted columns, then no action will be taken</li> * </ol> * </li> * </ol> * * @param table The table whose model shall be sorted. * @param columnIndex The column index upon which to sort. */ public static void columnAlternativelySelected(JTable table, int columnIndex) { SortedTableModel sortedModel = getSortedTableModel(table); if (sortedModel == null) { return; } int modelColumnIndex = getColumnModelIndex(table, columnIndex); if (modelColumnIndex < 0) { return; } if (!sortedModel.isSortable(modelColumnIndex)) { return; } TableSortState columnSortStates = sortedModel.getTableSortState(); TableSortStateEditor editor = new TableSortStateEditor(columnSortStates); if (editor.isColumnSorted(modelColumnIndex)) { /* Note: this code allows us to disable the 'unsorting' of a table via the UI // remove it. If there is only one, don't remove the last one if (editor.getSortedColumnCount() == 1) { Toolkit.getDefaultToolkit().beep(); return; } */ editor.removeSortedColumn(modelColumnIndex); } else { editor.addSortedColumn(modelColumnIndex); } sortedModel.setTableSortState(editor.createTableSortState()); repaintTableHeader(table); } private static SortedTableModel getSortedTableModel(JTable table) { TableModel model = table.getModel(); if (!(model instanceof SortedTableModel)) { return null; } return (SortedTableModel) model; } private static int getColumnModelIndex(JTable table, int columnIndex) { TableColumnModel columnModel = table.getColumnModel(); return columnModel.getColumn(columnIndex).getModelIndex(); } private static void repaintTableHeader(JTable table) { // force an update on the headers so they display the new sorting order JTableHeader tableHeader = table.getTableHeader(); if (tableHeader != null) { tableHeader.paintImmediately(tableHeader.getBounds()); } } }
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * fdmon-epoll tests * * Copyright (c) 2020 Red Hat, Inc. */ #include "qemu/osdep.h" #include "block/aio.h" #include "qapi/error.h" #include "qemu/main-loop.h" static AioContext *ctx; static void dummy_fd_handler(EventNotifier *notifier) { event_notifier_test_and_clear(notifier); } static void add_event_notifiers(EventNotifier *notifiers, size_t n) { for (size_t i = 0; i < n; i++) { event_notifier_init(&notifiers[i], false); aio_set_event_notifier(ctx, &notifiers[i], false, dummy_fd_handler, NULL); } } static void remove_event_notifiers(EventNotifier *notifiers, size_t n) { for (size_t i = 0; i < n; i++) { aio_set_event_notifier(ctx, &notifiers[i], false, NULL, NULL); event_notifier_cleanup(&notifiers[i]); } } /* Check that fd handlers work when external clients are disabled */ static void test_external_disabled(void) { EventNotifier notifiers[100]; /* fdmon-epoll is only enabled when many fd handlers are registered */ add_event_notifiers(notifiers, G_N_ELEMENTS(notifiers)); event_notifier_set(&notifiers[0]); assert(aio_poll(ctx, true)); aio_disable_external(ctx); event_notifier_set(&notifiers[0]); assert(aio_poll(ctx, true)); aio_enable_external(ctx); remove_event_notifiers(notifiers, G_N_ELEMENTS(notifiers)); } int main(int argc, char **argv) { /* * This code relies on the fact that fdmon-io_uring disables itself when * the glib main loop is in use. The main loop uses fdmon-poll and upgrades * to fdmon-epoll when the number of fds exceeds a threshold. */ qemu_init_main_loop(&error_fatal); ctx = qemu_get_aio_context(); while (g_main_context_iteration(NULL, false)) { /* Do nothing */ } g_test_init(&argc, &argv, NULL); g_test_add_func("/fdmon-epoll/external-disabled", test_external_disabled); return g_test_run(); }
import GroupToGroupTable from './GroupToGroupTable'; import { REDIS } from '@schoolbell-e/backend.servers'; /** * npm run test -- src/shared/tables/GroupToGroupTable.spec.ts */ describe('GroupToGroupTable test', () => { const parent_id = `0:1`; const child_id1 = `0:2`; const child_id2 = `0:3`; let gtg_id_1: string, gtg_id_2: string; beforeAll(async () => { await GroupToGroupTable.truncate(); }); afterAll(()=>{ REDIS.client.quit(); }) it('insert()', async () => { gtg_id_1 = await GroupToGroupTable.insert({ parent_id, child_id: child_id1, }); gtg_id_2 = await GroupToGroupTable.insert({ parent_id, child_id: child_id2, }); expect(gtg_id_1 !== null).toBeTruthy(); expect(gtg_id_2 !== null).toBeTruthy(); }); it('get()', async () => { var list = await GroupToGroupTable.get({ gtg_id: gtg_id_1 }); expect(list.length === 1).toBeTruthy(); var list = await GroupToGroupTable.get({ child_id: child_id1 }); expect(list.length === 1).toBeTruthy(); var list = await GroupToGroupTable.get({ child_id: child_id2 }); expect(list.length === 1).toBeTruthy(); var list = await GroupToGroupTable.get({ parent_id }); expect(list.length === 2).toBeTruthy(); }); it('delete()', async () => { var affectedRow = await GroupToGroupTable.delete({ child_id: child_id1 }); expect(affectedRow === 1).toBeTruthy(); var affectedRow = await GroupToGroupTable.delete({ parent_id }); expect(affectedRow === 1).toBeTruthy(); }); });
import { Injectable, OnDestroy } from '@angular/core'; import { ServerService, ServerState } from './server.service'; import { U128, U64, U256 } from './util.service'; import { marker } from '@biesbjerg/ngx-translate-extract-marker'; import { Subject } from 'rxjs'; import { environment } from '../../environments/environment'; @Injectable({ providedIn: 'root' }) export class FaucetService implements OnDestroy { private globalState: GlobalState = new GlobalState(); private accounts: {[account:string]: AccountInfo} = {}; private SERVICE = 'bsc_faucet'; private timerSync: any = null; private timerUpdateClaimable: any = null; private bindSubject = new Subject<{error: boolean; info?:string}>(); public bindResult$ = this.bindSubject.asObservable(); private claimSubject = new Subject<{error: boolean; info?:string, amount?:U128}>(); public claimResult$ = this.claimSubject.asObservable(); constructor( private server: ServerService ) { this.server.state$.subscribe(state => this.processServerState(state)); this.server.message$.subscribe(message => this.processMessage(message)); this.timerSync = setInterval(() => this.ongoingSync(), 1000); this.timerUpdateClaimable = setInterval(() => this.updateClaimable(), 1000); } ngOnDestroy() { if (this.timerSync) { clearInterval(this.timerSync); this.timerSync = null; console.log('FaucetService destroyed.') } if (this.timerUpdateClaimable) { clearInterval(this.timerUpdateClaimable); this.timerUpdateClaimable = null; } } addAccount(address: string) { if (!address) return; address = address.toLowerCase(); if (this.accounts[address]) { return; } const account = new AccountInfo(); this.accounts[address] = account; } bind(account: string, recipient: string, timestamp: string, signature: string) { const message: any = { action: 'bind', service: this.SERVICE, account: account, to: recipient, timestamp: timestamp, signature: signature, request_id: account }; this.server.send(message); } waitingTime(address: string): number { address = address.toLowerCase(); if (!this.accounts[address] || !this.accounts[address].synced) { return 0; } const day = 86400; const now = this.server.getTimestamp(); const last = this.accounts[address].last_claim.toNumber() if (now > last + day) { return 0; } if (last > now) return day; return last + day - now; } synced(address: string): boolean { address = address.toLowerCase(); if (!this.accounts[address]) return false; return this.accounts[address].synced; } boundAccount(address: string): string { address = address.toLowerCase(); if (!this.accounts[address]) return ''; if (address.startsWith('rai_')) { return this.accounts[address].account; } else if (address.startsWith('0x')) { return this.accounts[address].to; } else { return ''; } } claim(account: string, amount: U128) { const message: any = { action: 'claim', service: this.SERVICE, account: account, amount: amount.toDec(), }; this.server.send(message); } claimable(): U128 { if (!this.globalState.faucetInfo.synced) return new U128(0); return this.globalState.faucetInfo.claimable; } maxClaimable(address: string): U128 { address = address.toLowerCase(); if (!this.accounts[address]) return new U128(0); return this.accounts[address].claimable; } historyItems(): HistoryItem[] { return this.globalState.history.items; } historySynced(): boolean { return this.globalState.history.synced; } moreHistory(): boolean { return this.globalState.history.more; } loadMoreHisotry() { const history = this.globalState.history; history.count += 10; while (history.count < history.items.length) { history.count += 10; } this.syncHistory(); } private processServerState(state: ServerState) { if (state === ServerState.CONNECTED) { this.ongoingSync(true); } else { } } private ongoingSync(force?: boolean) { if (this.server.getState() !== ServerState.CONNECTED) return; const now = window.performance.now(); for (let address in this.accounts) { let info = this.accounts[address]; if (info.nextSyncAt > now && !force) continue; this.subscribeAccountInfo(address); this.syncAccountInfo(address); if (info.synced && info.subscribed) { info.nextSyncAt = now + 150000 + Math.random() * 300 * 1000; } else { info.nextSyncAt = now + 1500; } } if (force || this.globalState.nextSyncAt <= now) { this.subscribeGlobalState(); this.syncFaucetInfo(); this.syncHistory(); if (this.globalState.subscribed && this.globalState.faucetInfo.synced && this.globalState.history.synced) { this.globalState.nextSyncAt = now + 150000 + Math.random() * 300 * 1000; } else { this.globalState.nextSyncAt = now + 1500; } } } private syncAccountInfo(address: string) { const message: any = { action: 'account_info', service: this.SERVICE, account: address, request_id: address }; this.server.send(message); } private subscribeAccountInfo(address: string) { let filterKey = ''; if (address.startsWith('rai_')) { filterKey = 'rai_account'; } else if (address.startsWith('0x')) { filterKey = 'bsc_account'; } else { return; } const message: any = { action: 'service_subscribe', service: this.SERVICE, filters: [{key:filterKey, value:address}], request_id: `account:${address}` }; this.server.send(message); } private syncFaucetInfo() { const message: any = { action: 'faucet_info', service: this.SERVICE, }; this.server.send(message); } private syncHistory(append: boolean = false) { let request_id = ''; const history = this.globalState.history; let count = history.count; let index = -1; if (append) { request_id = 'append'; if (history.items.length >= history.count) return; count = history.count - history.items.length; if (history.items.length) { index = history.items[history.items.length - 1].index - 1; } } const message: any = { action: 'history', service: this.SERVICE, count: count, request_id: request_id }; if (index >= 0) { message['index'] = index; } this.server.send(message); } private subscribeGlobalState() { const message: any = { action: 'service_subscribe', service: this.SERVICE, filters: [{key:'global_state', value:'all'}], request_id: 'global_state:all' }; this.server.send(message); } private processMessage(message: any) { if (!message.service || message.service !== this.SERVICE) return; if (message.ack) { switch (message.ack) { case 'service_subscribe': this.processServiceSubscribe(message); break; case 'history': this.processHistoryAck(message); break; case 'faucet_info': this.processFaucetInfo(message); break; case 'account_info': this.processAccountInfo(message); break; case 'bind': this.processBindAck(message); break; case 'claim': this.processClaimAck(message); break; default: break; } } else if (message.notify) { switch (message.notify) { case 'history': this.processHistoryNotify(message); break; case 'faucet_info': this.processFaucetInfo(message); break; case 'account_info': this.processAccountInfo(message); break; default: break; } } } private processServiceSubscribe(message: any) { if (!message.request_id) { console.log('processServiceSubscribeAck: request_id missing'); return; } const id = message.request_id; if (id.startsWith('account:')) { const address = id.substring(8); const info = this.accounts[address]; if (!info) return; if (message.error) { info.subscribed = false; info.nextSyncAt = 0; } else { info.subscribed = true; } } else if (id.startsWith('global_state:')) { if (message.error) { this.globalState.subscribed = false; this.globalState.nextSyncAt = 0; } else { this.globalState.subscribed = true; } } } private processHistoryAck(message: any) { if (message.error) { console.log(`processHistoryAck: error=${message.error}`); return; } const append = message.request_id === 'append'; const history = this.globalState.history; if (!append) { history.items = []; history.synced = true; history.more = message.more === 'true'; } for (let i of message.items) { const item = new HistoryItem(); const error = item.fromJson(i); if (error) continue; this.addHistoryItem(history.items, item); } } private addHistoryItem(history: HistoryItem[], item: HistoryItem) { const length = history.length; if (length === 0 || (history[length - 1].index - 1) === item.index) { history.push(item); return; } let i = 0; for (; i < length; ++i) { if (history[i].index === item.index) { history[i] = item; return; } else if (history[i].index < item.index) { break; } } if (i >= length) { history.push(item); } else { history.splice(i, 0, item); } } private processFaucetInfo(message: any) { if (message.error) { console.log(`processFaucetInfo: error=${message.error}`); return; } let info = this.globalState.faucetInfo; const error = info.fromJson(message); if (error) { info.synced = false; this.globalState.nextSyncAt = 0; return; } info.synced = true; this.updateClaimable(); } private processAccountInfo(message: any) { if (message.error) { console.log(`processAccountInfo: error=${message.error}`); return; } const accounts = this.accounts; const keys = ['request_id', 'account', 'to']; for (let key of keys) { if (message[key]) { const address = message[key]; if (accounts[address]) { const error = accounts[address].fromJson(message); if (error) { accounts[address].synced = false; accounts[address].nextSyncAt = 0; } else { if (key === 'request_id') { accounts[address].synced = true; } } } } } } private processBindAck(message: any) { if (message.error) { this.bindSubject.next({error:true, info:message.error}); } else { this.bindSubject.next({error:false}); } } private processClaimAck(message: any) { if (message.error) { this.claimSubject.next({error:true, info:message.error}); } else { const amount = new U128(message.amount); this.claimSubject.next({error:false, amount:amount}); } } private processHistoryNotify(message: any) { const item = new HistoryItem(); const error = item.fromJson(message); if (error) return; this.addHistoryItem(this.globalState.history.items, item); } private updateClaimable() { let info = this.globalState.faucetInfo; if (!info.synced) return; const now = new U64(this.server.getTimestamp()); const amount = this.rewardAmount(info.unpooled, info.timestamp, now); const income = info.income.plus(amount); if (income.gt(info.payout)) { info.claimable = income.minus(info.payout); } else { info.claimable = new U128(0); } } private rewardRate(timestamp: U64): U128 { const epoch = new U64(environment.epoch_timestamp); const rates = [ 7800, 4600, 3200, 2500, 1500, 1500, 1200, 1200, 620, 620, 620, 620, 270, 270, 270, 270 ]; const unit = new U128(1000); const quarter = new U64(7776000); const maxQuarters = 16; if (timestamp.lt(epoch)) return new U128(0); if (timestamp.gte(epoch.plus(quarter.mul(maxQuarters)))) { return unit.mul(140); } const index = timestamp.minus(epoch).idiv(quarter).toNumber(); return unit.mul(rates[index]); } private rewardAmount(balance: U128, begin: U64, end: U64): U128 { const epoch = new U64(environment.epoch_timestamp); const day = 86400; const rai = U128.RAI(); if (begin.gt(end) || begin.lt(epoch)) { return new U128(0); } const balanceSafe = new U256(balance); const rate = this.rewardRate(end); const duration = end.minus(begin); const amount = balanceSafe.mul(rate).mul(duration).idiv(day).idiv(rai); return new U128(amount, 10, false); } }// FaucetService class AccountInfo { account: string = ''; to: string = ''; claimable: U128 = new U128(0); last_claim: U64 = new U64(0); subscribed: boolean = false; synced: boolean = false; nextSyncAt: number = 0; fromJson(json: any): boolean { try { this.account = json.account; this.to = json.to; this.claimable = new U128(json.claimable); this.last_claim = new U64(json.last_claim); return false; } catch (e) { console.log(`AccountInfo.fromJson: failed to parse json=${json}`); return true; } } } class FaucetInfo { timestamp: U64 = new U64(0); unpooled: U128 = new U128(0); income: U128 = new U128(0); payout: U128 = new U128(0); claimable:U128 = new U128(0); synced: boolean = false; fromJson(json: any): boolean { try { this.timestamp = new U64(json.timestamp); this.unpooled = new U128(json.unpooled); this.income = new U128(json.income); this.payout = new U128(json.payout); return false; } catch (e) { console.log(`FaucetInfo.fromJson: failed to parse json=${json}`); return true; } } } export class HistoryItem { index: number = 0; height: U64 = new U64(0); hash: U256 = new U256(0); amount: U128 = new U128(0); to: string = ''; timestamp:number = 0; fromJson(json: any): boolean { try { this.index = +json.index; this.height = new U64(json.height); this.hash = new U256(json.hash, 16); this.amount = new U128(json.amount); this.to = json.to; this.timestamp = +json.timestamp; return false; } catch (e) { console.log(`HistoryItem.fromJson: failed to parse json=${json}`); return true; } } } class History { items: HistoryItem[] = []; count: number = 10; more: boolean = false; synced: boolean = false; } class GlobalState { faucetInfo: FaucetInfo = new FaucetInfo(); history: History = new History(); subscribed: boolean = false; nextSyncAt: number = 0; } marker('signature is outdated'); marker('invalid timestamp'); marker('invalid signature'); marker('server error, failed to get infomation from BSC chain'); marker('your BSC account should hold some BNB, BEP20 RAI or liquidity before binding'); marker('binding'); marker('the account has not been bound to any BSC account yet'); marker('invalid claim amount'); marker('please be patient, you can claim only once in 24 hours'); marker('not enough balance');
import { Component, OnInit, OnDestroy, ChangeDetectorRef, Input } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import {FeedListService} from "../FeedCardService/FeedListService"; import {FeedKind} from "./FeedKind"; import {ListViewDialogService} from "../ListViewDialog/ListViewDialogService"; import {FeedEvent} from "../FeedCardService/FeedEvent"; import {FeedEventType} from "../FeedCardService/FeedEventType"; import {ListModel} from "../Models/ListModel"; import {ListItemModel} from "../Models/ListItemModel"; @Component({ selector: 'feed-card', template: ` <div class="card"> <form class="new-message" [formGroup]="editForm" novalidate> <div *ngIf="showAddListInput" class="input-group"> <input formControlName="listNameInput" type="text" class="form-control" placeholder="Название нового списка…" /> <span class="input-group-addon"> <a *ngIf="!editForm.invalid" href="" data-toggle="tooltip" data-placement="bottom" title="Создать новый" (click)="addNew($event)"> <span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true" > </span> </a> <span *ngIf="editForm.invalid" class="glyphicon glyphicon-th-list" aria-hidden="true" title="Введите название для списка"> </span> </span> </div> <div *ngIf="!showAddListInput" class="empty-lists"> <em *ngIf="this.lists.length===0"> Нет списков для отображения </em> </div> </form> <ul id="feed" class="feed list-unstyled"> <list-view *ngFor="let list of lists" [list]="list" [showShare]="true"></list-view> <list-button *ngIf="hasMoreRows" [title]="'Показать еще'" (buttonClick)="nextFeedClick()"></list-button> </ul> </div> <list-view-dialog></list-view-dialog> ` }) export class FeedCardComponent implements OnInit, OnDestroy { lists: Array<ListModel> = []; @Input() showAddListInput:boolean; editForm: FormGroup; hasMoreRows: boolean; private feedKind: FeedKind; private lastListId:string; private userName:string; private listAddedSubject:any; private listUpdatedSubject: any; private listsCleanedSubject: any; private listRemovedSubject: any; private listItemsSwappedSubject: any; private listsFetchedSubject:any; constructor(private formBuilder: FormBuilder, private feedService: FeedListService, private dialogService: ListViewDialogService,private ref: ChangeDetectorRef) { this.editForm = formBuilder.group({ "listNameInput": ["", [Validators.required, Validators.maxLength(100)]] }); this.hasMoreRows = false; this.lastListId = null; this.userName = null; this.feedKind = FeedKind.Unknown; } ngOnInit(): void { this.listsCleanedSubject = this.feedService.listFeed.filter((e: FeedEvent) => e.eventType === FeedEventType.ListsCleaned).subscribe(e => { this.lists.length = 0; }); this.listsFetchedSubject = this.feedService.listFeed.filter((e: FeedEvent) => e.eventType === FeedEventType.ListsFetched) .map((e: FeedEvent) => e.targetItem).subscribe(data => { for (var i = 0; i < data.lists.length; i++) { ListModel.sortItems(data.lists[i]); this.lists.push(data.lists[i]); } this.hasMoreRows = data.hasMore; this.lastListId = data.lastListId; this.userName = data.userName; this.feedKind = <FeedKind>data.feedKind; if (data.selectedListId) { let list: ListModel = this.findList(data.selectedListId); if (list != null) { this.dialogService.showDialog(list, null); } } }); this.listAddedSubject = this.feedService.listFeed.filter((e: FeedEvent) => e.eventType === FeedEventType.ListAdded) .map((e: FeedEvent) => e.targetItem).subscribe(list => { ListModel.sortItems(list); this.lists.splice(0, 0, list); }); this.listUpdatedSubject = this.feedService.listFeed.filter((e: FeedEvent) => e.eventType === FeedEventType.ListUpdated) .map((e: FeedEvent) => e.targetItem).subscribe((list: ListModel) => { let index: number = this.findIndexInList(list.id); if (index >= 0) { this.lists[index] = list; } }); this.listRemovedSubject = this.feedService.listFeed.filter((e: FeedEvent) => e.eventType === FeedEventType.ListRemoved) .map((e: FeedEvent) => e.targetId).subscribe((id: string) => { let index: number = this.findIndexInList(id); if (index >= 0) { this.lists.splice(index, 1); } }); this.listItemsSwappedSubject = this.feedService.listFeed.filter((e: FeedEvent) => e.eventType === FeedEventType.ListItemsSwapped) .map((e: FeedEvent) => e.targetItem).subscribe((item: any) => { this.swapItems(item.itemId, item.afterItemId, item.targetListId, item.copiedItem, item.copy); }); } ngOnDestroy(): void { this.listsCleanedSubject.unsubscribe(); this.listUpdatedSubject.unsubscribe(); this.listAddedSubject.unsubscribe(); this.listRemovedSubject.unsubscribe(); this.listItemsSwappedSubject.unsubscribe(); this.listsFetchedSubject.unsubscribe(); } nextFeedClick() { if (this.feedKind===FeedKind.Feed) { this.feedService.userFeed(this.lastListId); } else if(this.feedKind === FeedKind.UserLists) { this.feedService.fetchUserList(this.userName, this.lastListId); } } private findIndexInList(id: string):number { return this.lists.findIndex(el => el.id === id); } private findList(id: string): ListModel { let index = this.lists.findIndex(el => el.id === id); if (index>=0) { return this.lists[index]; } return null; } private findListByItemId(id: string): ListModel { for (var i = 0; i < this.lists.length; i++) { if (ListModel.findIndexInList(this.lists[i],id)>=0) { return this.lists[i]; } } return null; } addNew(event: Event) { event.preventDefault(); this.feedService.addNewList(this.editForm.controls["listNameInput"].value); this.editForm.controls["listNameInput"].setValue(""); } private swapItems(itemId: string, afterItemId: string, targetListId: string, copiedItem: ListItemModel, copy: boolean) { if (copy && (copiedItem==null || copiedItem===undefined)) { return; } let toList = this.findList(targetListId); let fromList: ListModel; if (toList != null) { let item = ListModel.findItemInList(toList, itemId); if (item==null) { fromList = this.findListByItemId(itemId); if (fromList!=null) { item = ListModel.findItemInList(fromList,itemId); } } if (item == null) { return; } if (copy) { ListModel.addItemAfterItemId(toList,afterItemId,copiedItem); } else { ListModel.addItemAfterItemId(toList, afterItemId, item); ListModel.positionByIndex(toList); if (fromList!=null) { ListModel.removeItemInList(fromList, item.id); ListModel.positionByIndex(fromList); } } this.ref.detectChanges(); } } }
Cook County voter registration deadline is Tuesday hello The deadline to register to vote in the upcoming consolidated election April 7 is Tuesday, the office of Cook County Clerk David Orr said Monday. "The many offices up for election throughout the Cook County suburbs impact residents' lives every day," Orr said in a news release. "The first step to make sure you have a say in how your town or school district is governed is to make sure you're registered to vote. Especially if you have recently moved, you need to confirm you are registered at your new address." Suburban Cook County voters can verify their registration status by using the "Your Voter Information" tool at cookcountyclerk.com or at m.cookcountyclerk.com if using a smartphone or tablet. By entering their information, a voter can learn if they are registered, where to vote on April 7, and which candidates will appear on their ballot. Voter registration applications for suburban Cook County residents can be found at cookcountyclerk.com/registertovote. Chicago residents should visit chicagoelections.com for more information. Any resident wishing to register in person can do so by visiting the clerk's downtown office, 69 W. Washington St., Fifth floor, Chicago, their municipal or township office, or one of the Clerk's five suburban offices, including 2121 Euclid Ave., Room 238, Rolling Meadows. In order to register, applicants must have two pieces of identification, including one containing a current address. Neither needs to be a photo ID. To qualify to vote, a resident must be a United States citizen, at least 18 years old by Election Day and a resident of his or her precinct for at least 30 days prior to the election. Voters who have recently moved must re-register at their current address prior to the deadline. Early Voting will be held March 23 -- April 4. Mail ballot applications are now being accepted.
/** * Perform syntax highlighting on the document. This implementation only performs syntax highlighting on the current * visible text in the view port of the text pane, and detects if the text has been changed before performing the * syntax highlighting. * * @throws BadLocationException */ private void performSyntaxHighlighting(boolean force) throws BadLocationException { if (getLength() == 0 && !force) { return; } JViewport viewport = textPane.getViewport(); Point startPoint = viewport.getViewPosition(); Dimension size = viewport.getExtentSize(); Point endPoint = new Point(startPoint.x + size.width, startPoint.y + size.height); int startOffset = textPane.viewToModel(startPoint); int endOffset = textPane.viewToModel(endPoint); if (!force && startOffset == lastSyntaxHighlightStartOffset && endOffset == lastSyntaxHighlightEndOffset) { return; } lastSyntaxHighlightStartOffset = startOffset; lastSyntaxHighlightEndOffset = endOffset; setCharacterAttributes(startOffset, endOffset - startOffset, normalAttrSet, true); int startLine = getElementIndex(startOffset); int endLine = getElementIndex(endOffset); for (int line = startLine; line <= endLine; line++) { processChangedLine(line); } }
import * as React from 'react'; import { Button } from '@fluentui/react-northstar'; const ButtonExampleOverflow = () => <Button content="See how this very long text shows up in the button" />; export default ButtonExampleOverflow;
def _iterparse_nested_xml(xml_file, tags, fields, **ignored_kwd): fconvert = { tag: { fname: _fieldconverter( fconf['newname'] if isinstance(fconf, dict) else fname, fconf['func'] if isinstance(fconf, dict) else fconf ) for fname, fconf in tagfields.items() } for tag, tagfields in fields.items() } iterparser = ET.iterparse( source=xml_file, events=('start', 'end'), tag=[tags], recover=True, encoding='utf-8' ) container_tags = set(tags[:-1]) container_fields = dict() for event, elem in iterparser: if event == 'start': if elem.tag in container_tags: for fname, fconf in fconvert[elem.tag].items(): try: container_fields[fconf.newname] = fconf.convert( elem.get(fname) ) except TypeError as exc: warnings.warn( "Could not read/convert field {}[{}]: '{}'".format( elem.tag, fname, str(exc) ) ) else: fconf = fconvert[elem.tag] res = { fconf[key].newname: fconf[key].convert(val) for key, val in elem.attrib.items() } res.update(container_fields) yield res del res else: elem.clear()
<filename>src/data-type.ts export type INT8 = number; export type INT16 = number; export type INT32 = number; export type INT64 = number; export type UINT8 = number; export type UINT16 = number; export type UINT32 = number; export type UINT64 = number; export enum SIZE { INT8 = 1, INT16 = 2, INT32 = 4, INT64 = 8, UINT8 = 1, UINT16 = 2, UINT32 = 4, UINT64 = 8, }
<reponame>nix-community/go-nix<gh_stars>1-10 // Package nixpath parses and renders Nix store paths. package nixpath import ( "fmt" "path" "regexp" "github.com/nix-community/go-nix/pkg/nixbase32" ) const ( StoreDir = "/nix/store" PathHashSize = 20 ) var ( NameRe = regexp.MustCompile(`[a-zA-Z0-9+\-_?=][.a-zA-Z0-9+\-_?=]*`) PathRe = regexp.MustCompile(fmt.Sprintf( `^%v/([0-9a-z]{%d})-(%v)$`, regexp.QuoteMeta(StoreDir), nixbase32.EncodedLen(PathHashSize), NameRe, )) ) // NixPath represents a nix store path. type NixPath struct { Name string Digest []byte } func (n *NixPath) String() string { return path.Join(StoreDir, fmt.Sprintf("%v-%v", nixbase32.EncodeToString(n.Digest), n.Name)) } // FromString parses a path string into a nix path, // verifying it's syntactically valid // It returns an error if it fails to parse. func FromString(s string) (*NixPath, error) { m := PathRe.FindStringSubmatch(s) if m == nil { return nil, fmt.Errorf("unable to parse path %v", s) } digest, err := nixbase32.DecodeString(m[1]) if err != nil { return nil, fmt.Errorf("unable to decode hash: %v", err) } return &NixPath{ Name: m[2], Digest: digest, }, nil }
//===-- IntelJITEventsWrapper.h - Intel JIT Events API Wrapper --*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines a wrapper for the Intel JIT Events API. It allows for the // implementation of the jitprofiling library to be swapped with an alternative // implementation (for testing). To include this file, you must have the // jitprofiling.h header available; it is available in Intel(R) VTune(TM) // Amplifier XE 2011. // //===----------------------------------------------------------------------===// #ifndef INTEL_JIT_EVENTS_WRAPPER_H #define INTEL_JIT_EVENTS_WRAPPER_H #include "jitprofiling.h" namespace llvm { typedef enum { LoadBinaryModule, LoadBinarySection, UnloadBinaryModule, UnloadBinarySection } IttEventType; class IntelJITEventsWrapper { // Function pointer types for testing implementation of Intel jitprofiling // library typedef int (*NotifyEventPtr)(iJIT_JVM_EVENT, void*); typedef int (*IttnotifyInfoPtr)(IttEventType, const char *, unsigned int); typedef void (*RegisterCallbackExPtr)(void *, iJIT_ModeChangedEx ); typedef iJIT_IsProfilingActiveFlags (*IsProfilingActivePtr)(void); typedef void (*FinalizeThreadPtr)(void); typedef void (*FinalizeProcessPtr)(void); typedef unsigned int (*GetNewMethodIDPtr)(void); NotifyEventPtr NotifyEventFunc; IttnotifyInfoPtr IttnotifyInfoFunc; RegisterCallbackExPtr RegisterCallbackExFunc; IsProfilingActivePtr IsProfilingActiveFunc; GetNewMethodIDPtr GetNewMethodIDFunc; public: bool isAmplifierRunning() { return iJIT_IsProfilingActive() == iJIT_SAMPLING_ON; } IntelJITEventsWrapper() : NotifyEventFunc(::iJIT_NotifyEvent), IttnotifyInfoFunc(0), RegisterCallbackExFunc(::iJIT_RegisterCallbackEx), IsProfilingActiveFunc(::iJIT_IsProfilingActive), GetNewMethodIDFunc(::iJIT_GetNewMethodID) {} IntelJITEventsWrapper(NotifyEventPtr NotifyEventImpl, IttnotifyInfoPtr IttnotifyInfoImpl, RegisterCallbackExPtr RegisterCallbackExImpl, IsProfilingActivePtr IsProfilingActiveImpl, FinalizeThreadPtr FinalizeThreadImpl, FinalizeProcessPtr FinalizeProcessImpl, GetNewMethodIDPtr GetNewMethodIDImpl) : NotifyEventFunc(NotifyEventImpl), IttnotifyInfoFunc(IttnotifyInfoImpl), RegisterCallbackExFunc(RegisterCallbackExImpl), IsProfilingActiveFunc(IsProfilingActiveImpl), GetNewMethodIDFunc(GetNewMethodIDImpl) {} // Sends an event announcing that a function has been emitted // return values are event-specific. See Intel documentation for details. int iJIT_NotifyEvent(iJIT_JVM_EVENT EventType, void *EventSpecificData) { if (!NotifyEventFunc) return -1; return NotifyEventFunc(EventType, EventSpecificData); } int iJitIttNotifyInfo(IttEventType EventType, const char *Name, unsigned int Size) { if (!IttnotifyInfoFunc) return -1; return IttnotifyInfoFunc(EventType, Name, Size); } // Registers a callback function to receive notice of profiling state changes void iJIT_RegisterCallbackEx(void *UserData, iJIT_ModeChangedEx NewModeCallBackFuncEx) { if (RegisterCallbackExFunc) RegisterCallbackExFunc(UserData, NewModeCallBackFuncEx); } // Returns the current profiler mode iJIT_IsProfilingActiveFlags iJIT_IsProfilingActive(void) { if (!IsProfilingActiveFunc) return iJIT_NOTHING_RUNNING; return IsProfilingActiveFunc(); } // Generates a locally unique method ID for use in code registration unsigned int iJIT_GetNewMethodID(void) { if (!GetNewMethodIDFunc) return -1; return GetNewMethodIDFunc(); } }; } //namespace llvm #endif //INTEL_JIT_EVENTS_WRAPPER_H
def update_exons(exons, UTRs): exon_bt = pbt.BedTool(''.join(e.line for e in exons), from_string=True) UTR_bt = pbt.BedTool(''.join(e.line for e in UTRs), from_string=True) update = exon_bt.subtract(UTR_bt).saveas() for f in str(update).strip().split('\n'): line = reformat_bedtool_GTF(f) yield GTFEntry(*str(line).strip().split('\t'), str(line))
/** * Issue a verbose message to the command line. * @param message The messages to be printed to the command line. */ public static void verbose(String... message) { if (Verbose.getInstance().isVerbose()) { String output = Arrays.stream(message).collect(Collectors.joining()); System.out.println(output); } }
## Copyright 2022 The IREE Authors # # Licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception """Defines Tensorflow models.""" import string from e2e_test_framework import unique_ids from e2e_test_framework.definitions import common_definitions import e2e_test_framework.models.utils as model_utils TF_MODELS_MANUAL_ROOT_DIR = ( "https://storage.googleapis.com/iree-model-artifacts/tensorflow/manual" ) MINILM_L12_H384_UNCASED_INT32_SEQLEN128 = common_definitions.Model( id=unique_ids.MODEL_MINILM_L12_H384_UNCASED_INT32_SEQLEN128, name="MiniLML12H384Uncased", tags=["int32", "seqlen128"], source_type=common_definitions.ModelSourceType.EXPORTED_STABLEHLO_MLIR, # Converted from https://huggingface.co/microsoft/MiniLM-L12-H384-uncased/commit/44acabbec0ef496f6dbc93adadea57f376b7c0ec source_url=f"{TF_MODELS_MANUAL_ROOT_DIR}/MiniLML12H384Uncased_2023-05-07.timestamp_1683504734.mlirbc", entry_function="predict", input_types=["1x128xi32", "1x128xi32", "1x128xi32"], ) BERT_FOR_MASKED_LM_FP32_SEQLEN512 = common_definitions.Model( id=unique_ids.MODEL_BERT_FOR_MASKED_LM_FP32_SEQLEN512_TF, name="BertForMaskedLMTF", tags=["fp32", "seqlen512", "tensorflow"], source_type=common_definitions.ModelSourceType.EXPORTED_STABLEHLO_MLIR, # Converted from https://huggingface.co/transformers/v3.0.2/model_doc/bert.html#tfbertformaskedlm source_url=f"{TF_MODELS_MANUAL_ROOT_DIR}/BertForMaskedLMTF_2023-05-07.timestamp_1683504734.mlirbc", entry_function="forward", input_types=["1x512xi32", "1x512xi32"], ) EFFICIENTNET_V2_S_FP32 = common_definitions.Model( id=unique_ids.MODEL_EFFICIENTNET_V2_S_FP32_TF, name="EfficientNetV2STF", tags=["fp32", "cnn", "tensorflow"], source_type=common_definitions.ModelSourceType.EXPORTED_STABLEHLO_MLIR, # Converted from https://github.com/keras-team/keras/blob/v2.10.0/keras/applications/efficientnet_v2.py source_url=f"{TF_MODELS_MANUAL_ROOT_DIR}/EfficientNetV2STF_2023-05-07.timestamp_1683504734.mlirbc", entry_function="forward", input_types=["1x384x384x3xf32"], ) # This is the model used in the MLPerf Inference Suite. BERT_LARGE_TF_FP32_SEQLEN384 = common_definitions.Model( id=unique_ids.MODEL_BERT_LARGE_TF_FP32_SEQLEN384, name="BertLargeTF", tags=["fp32", "seqlen384", "tensorflow", "bert-variant", "batch-1"], source_type=common_definitions.ModelSourceType.EXPORTED_STABLEHLO_MLIR, # Derived from https://github.com/mlcommons/inference/tree/master/language/bert # Instructions on how to regenerate the model: https://gist.github.com/mariecwhite/e61ccebd979d98d097946ac7725bcc29 source_url=f"{TF_MODELS_MANUAL_ROOT_DIR}/BertLargeTF_2023-05-07.timestamp_1683504734.mlirbc", entry_function="serving_default", input_types=["1x384xi32", "1x384xi32", "1x384xi32"], ) TF_MODELS_ROOT_DIR = "https://storage.googleapis.com/iree-model-artifacts/tensorflow/tf_models_2.13.0rc2_1688540251" ID_FORMAT = string.Template("${model_id}-batch-${batch_size}") NAME_FORMAT = string.Template("${name}Batch${batch_size}") SOURCE_URL_FORMAT = string.Template( TF_MODELS_ROOT_DIR + "/${directory}_BATCH${batch_size}/stablehlo.mlirbc" ) # Derived from https://huggingface.co/docs/transformers/model_doc/bert#transformers.TFBertModel. BERT_LARGE_384_FP32_TF_BATCHES = model_utils.generate_batch_models( id_template=model_utils.partial_template_substitute( ID_FORMAT, model_id=unique_ids.MODEL_BERT_LARGE_384_FP32_TF ), name_template=model_utils.partial_template_substitute( NAME_FORMAT, name="BertLargeTF" ), tags=["fp32", "seqlen384", "tensorflow", "bert-variant"], source_type=common_definitions.ModelSourceType.EXPORTED_STABLEHLO_MLIR, source_url_template=model_utils.partial_template_substitute( SOURCE_URL_FORMAT, directory="BERT_LARGE_FP32_TF_384XI32" ), entry_function="forward", input_type_templates=[ string.Template("${batch_size}x384xi32"), string.Template("${batch_size}x384xi32"), ], batch_sizes=[1, 16, 24, 32, 48, 64, 512, 1024, 1280], ) # Converted from https://www.tensorflow.org/api_docs/python/tf/keras/applications/resnet50/ResNet50 RESNET50_3X224X224_FP32_TF_BATCHES = model_utils.generate_batch_models( id_template=model_utils.partial_template_substitute( ID_FORMAT, model_id=unique_ids.MODEL_RESNET50_3X224X224_FP32_TF ), name_template=model_utils.partial_template_substitute( NAME_FORMAT, name="Resnet50TF" ), tags=["fp32", "cnn"], source_type=common_definitions.ModelSourceType.EXPORTED_STABLEHLO_MLIR, source_url_template=model_utils.partial_template_substitute( SOURCE_URL_FORMAT, directory="RESNET50_FP32_TF_224X224X3XF32" ), entry_function="forward", input_type_templates=[string.Template("${batch_size}x3x224x224xf32")], batch_sizes=[1, 8, 64, 128, 256, 2048], ) # Derived from https://huggingface.co/transformers/v3.0.2/model_doc/t5.html#tft5model. T5_LARGE_512_FP32_TF_BATCHES = model_utils.generate_batch_models( id_template=model_utils.partial_template_substitute( ID_FORMAT, model_id=unique_ids.MODEL_T5_LARGE_512_FP32_TF ), name_template=model_utils.partial_template_substitute( NAME_FORMAT, name="T5LargeTF" ), tags=["fp32", "seqlen512", "tensorflow"], source_type=common_definitions.ModelSourceType.EXPORTED_STABLEHLO_MLIR, source_url_template=model_utils.partial_template_substitute( SOURCE_URL_FORMAT, directory="T5_LARGE_FP32_TF_512XI32" ), entry_function="forward", input_type_templates=[ string.Template("${batch_size}x512xi32"), string.Template("${batch_size}x512xi32"), ], batch_sizes=[1, 16, 24, 32, 48, 64, 512], )