max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
373 |
/*
* #%L
* ACS AEM Commons Bundle
* %%
* Copyright (C) 2017 Adobe
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.adobe.acs.commons.mcp.form;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.lang.reflect.Field;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.apache.sling.testing.mock.sling.ResourceResolverType;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import io.wcm.testing.mock.aem.junit.AemContext;
@RunWith(MockitoJUnitRunner.class)
public class DatePickerComponentTest {
@Rule
public AemContext ctx = new AemContext(ResourceResolverType.JCR_MOCK);
private Field field;
@Mock
private FormField formField;
@Mock
private SlingScriptHelper slingScriptHelper;
@Before
public void setup() {
when(slingScriptHelper.getRequest()).thenReturn(ctx.request());
}
@Test
public void normalDateField() {
final DatePickerComponent dateComponent = new DatePickerComponent();
when(formField.name()).thenReturn("Start Date");
when(formField.description()).thenReturn("Select the start date.");
dateComponent.setup("startDate", field, formField, slingScriptHelper);
Resource resource = dateComponent.buildComponentResource();
ValueMap map = resource.getValueMap();
assertEquals("wrong component resource type.", "granite/ui/components/coral/foundation/form/datepicker",
resource.getResourceType());
assertEquals("wrong field label", "Start Date", map.get("fieldLabel"));
assertEquals("wrong field description", "Select the start date.", map.get("fieldDescription"));
}
@Test
public void dateTimeField() {
final DatePickerComponent dateComponent = new DatePickerComponent();
String[] opts = new String[1];
opts[0] = DatePickerComponent.TYPE_OPT_DATETIME;
when(formField.options()).thenReturn(opts);
when(formField.name()).thenReturn("Start Date");
when(formField.description()).thenReturn("Select the start date.");
dateComponent.setup("startDate", field, formField, slingScriptHelper);
Resource resource = dateComponent.buildComponentResource();
ValueMap map = resource.getValueMap();
assertEquals("wrong component type.", DatePickerComponent.TYPE_OPT_DATETIME,
map.get(DatePickerComponent.TYPE));
}
@Test
public void timeField() {
final DatePickerComponent dateComponent = new DatePickerComponent();
String[] opts = new String[1];
opts[0] = DatePickerComponent.TYPE_OPT_TIME;
when(formField.options()).thenReturn(opts);
when(formField.name()).thenReturn("Start Date");
when(formField.description()).thenReturn("Select the start date.");
dateComponent.setup("startDate", field, formField, slingScriptHelper);
Resource resource = dateComponent.buildComponentResource();
ValueMap map = resource.getValueMap();
assertEquals("wrong component type.", DatePickerComponent.TYPE_OPT_TIME,
map.get(DatePickerComponent.TYPE));
}
}
| 1,369 |
1,561 |
<reponame>victorhu3/webots<filename>src/ode/ode/src/ode_MT/heuristics/heuristicsManager.h
#ifndef _ODE_MT_HEURISTICMANAGER_H_
#define _ODE_MT_HEURISTICMANAGER_H_
#include "heuristic.h"
//template<typename T> class dxHeuristic;
class HeuristicAlertCallback
{
public:
virtual void alertCallback(dxHeuristic<int>* _heuristic) = 0;
};
class dxHeuristicsManager : public HeuristicAlertCallback
{
private:
int userThreadCount;
int recommendedThreadCount;
int frameCount;
int frameCounter;
int syncInterval;
int mBestClusterCount;
float mBestGridSize;
class dxClusterManager* clusterManager;
class dxThreadManager* threadManager;
class dxHeuristic<int>* objectCountHeuristic;
class dxHeuristic<int>* clusterCountHeuristic;
class dxHeuristic<int>* clusterCheckHeuristic;
void alertFunc();
void alertCallback(dxHeuristic<int>* _heuristic);
void resetVariables();
public:
dxHeuristicsManager(int _numThreads, int _syncInterval, class dxClusterManager* _clusterManager, class dxThreadManager* _threadManager);
~dxHeuristicsManager();
void reset();
void simLoop(struct dxWorld* _world, struct dxSpace* _space);
};
#endif
| 503 |
965 |
<gh_stars>100-1000
// Declare an array of integers
CAtlArray<int> iMyArray;
int element;
// Add ten elements to the array
for (int i = 0; i < 10; i++)
{
iMyArray.Add(i);
}
// Use GetAt and SetAt to modify
// every element in the array
for (size_t i = 0; i < iMyArray.GetCount(); i++)
{
element = iMyArray.GetAt(i);
element *= 10;
iMyArray.SetAt(i, element);
}
| 185 |
631 |
<gh_stars>100-1000
/*
* Copyright 2018 <NAME>. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.meituan.dorado.config.service.spring;
import com.meituan.dorado.HelloService;
import com.meituan.dorado.MockUtil;
import org.junit.Assert;
import org.junit.Test;
public class SpringBeanTest {
@Test
public void testSpringBean() throws Exception {
ReferenceBean referenceBean = MockUtil.getReferenceBean();
try {
referenceBean.afterPropertiesSet();
} catch (Exception e) {
Assert.fail();
}
Assert.assertNotNull(referenceBean.getObject());
Assert.assertTrue(referenceBean.getObjectType() == HelloService.class);
Assert.assertTrue(referenceBean.isSingleton());
ServiceBean serviceBean = MockUtil.getServerBean();
try {
serviceBean.afterPropertiesSet();
} catch (Exception e) {
Assert.fail();
}
}
}
| 533 |
1,056 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.welcome.content;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.ParserConfigurationException;
import org.netbeans.modules.welcome.content.RSSFeed.ErrorCatcher;
import org.netbeans.modules.welcome.content.RSSFeed.FeedHandler;
import org.netbeans.modules.welcome.content.RSSFeed.FeedItem;
import org.openide.util.NbPreferences;
import org.openide.xml.XMLUtil;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Combines two RSS feeds into one.
*
* @author <NAME>
*/
public class CombinationRSSFeed extends RSSFeed {
private String url1;
private String url2;
private int maxItemCount;
/** Creates a new instance of CombinationRSSFeed */
public CombinationRSSFeed( String url1, String url2, boolean showProxyButton, int maxItemCount ) {
super( showProxyButton );
this.maxItemCount = maxItemCount;
this.url1 = url1;
this.url2 = url2;
}
@Override
protected List<FeedItem> buildItemList() throws SAXException, ParserConfigurationException, IOException {
XMLReader reader = XMLUtil.createXMLReader( false, true );
FeedHandler handler = new FeedHandler( getMaxItemCount() );
reader.setContentHandler( handler );
reader.setEntityResolver( new RSSEntityResolver() );
reader.setErrorHandler( new ErrorCatcher() );
reader.parse( findInputSource(new URL(url1)) );
ArrayList<FeedItem> res = new ArrayList<FeedItem>( 2*getMaxItemCount() );
res.addAll( handler.getItemList() );
handler = new FeedHandler( getMaxItemCount() );
reader.setContentHandler( handler );
reader.parse( findInputSource(new URL(url2)) );
res.addAll( handler.getItemList() );
List<FeedItem> items = sortNodes( res );
if( items.size() > getMaxItemCount() ) {
items = items.subList( 0, getMaxItemCount() );
}
return items;
}
private ArrayList<FeedItem> sortNodes( ArrayList<FeedItem> res ) {
Collections.sort( res, new DateFeedItemComparator() );
return res;
}
@Override
protected void clearCache() {
try {
NbPreferences.forModule( RSSFeed.class ).remove( url2path( new URL(url1))) ;
NbPreferences.forModule( RSSFeed.class ).remove( url2path( new URL(url2))) ;
} catch( MalformedURLException mE ) {
//ignore
}
}
@Override
protected int getMaxItemCount() {
return this.maxItemCount;
}
private static class DateFeedItemComparator implements Comparator<FeedItem> {
private static DateFormat dateFormat = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH ); // NOI18N
private static DateFormat dateFormatLong = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH ); // NOI18N
private static DateFormat dateFormatShort = new SimpleDateFormat( "EEE, dd MMM yyyy", Locale.ENGLISH ); // NOI18N
public int compare(FeedItem item1, FeedItem item2) {
Date date1 = extractDate( item1 );
Date date2 = extractDate( item2 );
if( null == date1 && null == date2 )
return 0;
else if( null == date1 )
return 1;
else if( null == date2 )
return -1;
if( date1.after( date2 ) ) {
return -1;
} else if( date1.before( date2 ) ) {
return 1;
}
return 0;
}
private Date extractDate( FeedItem item ) {
try {
if( null != item.dateTime )
return dateFormat.parse( item.dateTime );
} catch( ParseException pE ) {
try {
return dateFormatShort.parse( item.dateTime );
} catch( ParseException otherPE ) {
try {
return dateFormatLong.parse( item.dateTime );
} catch( ParseException e ) {
//ignore
}
}
}
return null;
}
}
}
| 2,136 |
1,178 |
<gh_stars>1000+
/*
* Copyright 2020 Makani Technologies LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include "avionics/common/cvt_avionics_messages.h"
#include "avionics/common/imu_output.h"
#include "avionics/fc/firmware/config_params.h"
#include "avionics/fc/firmware/fpv_pitot_control.h"
#include "avionics/fc/firmware/monitor.h"
#include "avionics/fc/firmware/output.h"
#include "avionics/fc/firmware/selftest.h"
#include "avionics/firmware/cpu/clock.h"
#include "avionics/firmware/cpu/i2c.h"
#include "avionics/firmware/cpu/mibspi.h"
#include "avionics/firmware/cpu/vim.h"
#include "avionics/firmware/drivers/adis16488.h"
#include "avionics/firmware/drivers/bcm53101.h"
#include "avionics/firmware/drivers/ext_watchdog.h"
#include "avionics/firmware/drivers/faa_light.h"
#include "avionics/firmware/drivers/hsc.h"
#include "avionics/firmware/drivers/led.h"
#include "avionics/firmware/drivers/q7_watchdog.h"
#include "avionics/firmware/gps/gps_interface.h"
#include "avionics/firmware/identity/identity.h"
#include "avionics/firmware/network/net.h"
#include "avionics/firmware/network/net_diag.h"
#include "avionics/firmware/network/net_mon.h"
#include "avionics/firmware/network/net_send.h"
#include "avionics/firmware/network/switch_config.h"
#include "avionics/firmware/output/slow_status.h"
#include "avionics/network/aio_node.h"
#include "avionics/network/message_stats.h"
#include "common/macros.h"
// Reserve time at the end of each iteration to prevent processes from
// overrunning the maximum processing time. All trivial polling functions
// called at the end ScheduleLoop() should take less than this amount of time.
#define GUARD_TIME_US 50
// Define maximum loop processing time.
#define LOOP_PROCESSING_TIME_US (1000000 / ADIS16488_SYNC_FREQ_HZ)
// Define message rate decimations of loop iteration rate.
#define SLOW_STATUS_MESSAGE_DECIMATION \
(ADIS16488_SYNC_FREQ_HZ / SLOW_STATUS_FREQUENCY_HZ)
#define SERIAL_DEBUG_DECIMATION \
(ADIS16488_SYNC_FREQ_HZ / SERIAL_DEBUG_FREQUENCY_HZ)
#define GPS_SOLUTION_DECIMATION \
(ADIS16488_SYNC_FREQ_HZ / NOV_ATEL_SOLUTION_FREQUENCY_HZ)
#define GPS_OBSERVATIONS_DECIMATION \
(ADIS16488_SYNC_FREQ_HZ / NOV_ATEL_OBSERVATIONS_FREQUENCY_HZ)
#define GPS_SATELLITES_DECIMATION \
(ADIS16488_SYNC_FREQ_HZ / GPS_SATELLITES_FREQUENCY_HZ)
#define GPS_TIME_DECIMATION (ADIS16488_SYNC_FREQ_HZ / GPS_TIME_FREQUENCY_HZ)
#define FAA_LIGHT_TIME_DECIMATION \
(ADIS16488_SYNC_FREQ_HZ / FAA_LIGHT_STATUS_FREQUENCY_HZ)
// Define the amount of time before selecting a new RTCM source.
#define GPS_RTCM_OBS_TIMEOUT_US 5000000 // Observables.
#define GPS_RTCM_AUX_TIMEOUT_US 5000000 // Auxiliary information.
// Septentrio's support indicates that the AsteRx-m receiver has limited
// processing capabilities and will not be able to track all satellites
// with a 10 Hz RTCM rate and 10 Hz PVT rate.
#define SEPTENTRIO_RTCM_MIN_PERIOD_US 500000
typedef bool (*const CvtGetFunction)(AioNode source, void *message,
uint16_t *seq_num, int64_t *timestamp);
static int64_t g_rtcm_obs_timestamp = INT32_MIN;
static int64_t g_rtcm1006_timestamp = INT32_MIN;
static int64_t g_rtcm1033_timestamp = INT32_MIN;
static int64_t g_rtcm1230_timestamp = INT32_MIN;
static int64_t g_rtcm_timestamp = INT32_MIN;
static int32_t g_rtcm_obs_source_index = -1;
static int32_t g_rtcm1006_source_index = -1;
static int32_t g_rtcm1033_source_index = -1;
static int32_t g_rtcm1230_source_index = -1;
static int32_t g_rtcm_source_index = -1;
static AioNode g_current_node;
static FlightComputerSensorMessage g_sensor_message;
static void HandleGpsRtcm(CvtGetFunction cvt_get, int32_t timeout,
int32_t max_length, const int16_t *length,
const uint8_t *data, void *message,
int32_t *last_source_index, int64_t *last_timestamp) {
// List RTCM sources according to descending priority.
const AioNode sources[] = {kAioNodeGpsBaseStation, kAioNodeCsA, kAioNodeCsB};
for (int32_t i = 0; i < ARRAYSIZE(sources); ++i) {
int64_t timestamp;
if (cvt_get(sources[i], message, NULL, ×tamp) && 0 < *length &&
*length <= max_length &&
(timestamp - *last_timestamp > timeout || i <= *last_source_index)) {
// Rate limit corrections to Septentrio receiver.
if (kFcConfigParams->gps_receiver != kGpsReceiverTypeSeptentrio ||
timestamp - *last_timestamp > SEPTENTRIO_RTCM_MIN_PERIOD_US) {
// Select new source.
*last_timestamp = timestamp;
*last_source_index = i;
// Forward differential GPS corrections to wing receiver.
GpsInsertRtcm(&kGpsConfigRover, kFcConfigParams->gps_receiver, *length,
data);
}
}
}
}
static void PollGpsRtcmMessages(void) {
// Declare static to prevent stack overflow.
static union {
GpsRtcm1006Message rtcm1006;
GpsRtcm1033Message rtcm1033;
GpsRtcm1230Message rtcm1230;
GpsRtcm1072Message rtcm1072;
GpsRtcm1074Message rtcm1074;
GpsRtcm1082Message rtcm1082;
GpsRtcm1084Message rtcm1084;
GpsRtcmMessage rtcm;
} u;
#define HANDLE_GPS_RTCM(cvt_get, timeout, message, source_index, timestamp) \
HandleGpsRtcm((CvtGetFunction)(cvt_get), (timeout), \
ARRAYSIZE((message)->data), &(message)->length, \
(message)->data, (message), (source_index), (timestamp))
// Observables.
HANDLE_GPS_RTCM(CvtGetGpsRtcm1072Message, GPS_RTCM_OBS_TIMEOUT_US,
&u.rtcm1072, &g_rtcm_obs_source_index, &g_rtcm_obs_timestamp);
HANDLE_GPS_RTCM(CvtGetGpsRtcm1074Message, GPS_RTCM_OBS_TIMEOUT_US,
&u.rtcm1074, &g_rtcm_obs_source_index, &g_rtcm_obs_timestamp);
HANDLE_GPS_RTCM(CvtGetGpsRtcm1082Message, GPS_RTCM_OBS_TIMEOUT_US,
&u.rtcm1082, &g_rtcm_obs_source_index, &g_rtcm_obs_timestamp);
HANDLE_GPS_RTCM(CvtGetGpsRtcm1084Message, GPS_RTCM_OBS_TIMEOUT_US,
&u.rtcm1084, &g_rtcm_obs_source_index, &g_rtcm_obs_timestamp);
// Auxiliary information.
HANDLE_GPS_RTCM(CvtGetGpsRtcm1006Message, GPS_RTCM_AUX_TIMEOUT_US,
&u.rtcm1006, &g_rtcm1006_source_index, &g_rtcm1006_timestamp);
HANDLE_GPS_RTCM(CvtGetGpsRtcm1033Message, GPS_RTCM_AUX_TIMEOUT_US,
&u.rtcm1033, &g_rtcm1033_source_index, &g_rtcm1033_timestamp);
HANDLE_GPS_RTCM(CvtGetGpsRtcm1230Message, GPS_RTCM_AUX_TIMEOUT_US,
&u.rtcm1230, &g_rtcm1230_source_index, &g_rtcm1230_timestamp);
// Catch all.
HANDLE_GPS_RTCM(CvtGetGpsRtcmMessage, GPS_RTCM_OBS_TIMEOUT_US, &u.rtcm,
&g_rtcm_source_index, &g_rtcm_timestamp);
#undef HANDLE_GPS_RTCM
}
static void PollExtWatchdog(void) { ExtWatchdogPoll(); }
static void PollFaaLight(void) {
if (IsLightNode(g_current_node)) {
FaaLightPoll();
}
}
static void PollSwitch(void) { Bcm53101Poll(GetSwitchConfig()); }
static void PollGps(void) {
int64_t now = ClockGetUs();
if (GpsDevicePollPps(&kGps)) {
FcOutputPps(now);
GpsUpdatePpsTimestamp(now);
}
GpsPoll(&kGpsConfigRover, kFcConfigParams->gps_receiver, now);
}
static HscDevice PollPitot(HscDevice pitot, int64_t now) {
HscDevice pitot_next = (pitot + 1) % kNumHscDevices;
HscData data;
if (HscRead(&data)) {
FcOutputPitot(pitot, &kFcConfigParams->pitot, &data, &g_sensor_message,
now);
}
HscTrigger(pitot_next);
return pitot_next;
}
static void ScheduleLoop(void) {
// Current pitot tube device.
HscDevice pitot = 0;
// Define iteration counters for loop decimation.
int32_t sensor_message_count = 0;
int32_t slow_status_message_count = 0;
int32_t faa_light_status_message_count = 0;
int32_t imu_count = 0;
int32_t serial_debug_count = SERIAL_DEBUG_DECIMATION / 4;
int32_t gps_solution_count = 0;
int32_t gps_observations_count = GPS_OBSERVATIONS_DECIMATION / 2;
int32_t gps_satellites_count = 0;
int32_t gps_time_count = 0;
// GpsSolutionMessage and GpsObservationsMessage should be out of phase.
assert(GPS_SOLUTION_DECIMATION == GPS_OBSERVATIONS_DECIMATION);
assert(gps_solution_count == 0 &&
gps_observations_count == GPS_OBSERVATIONS_DECIMATION / 2);
// Poll trivial processes.
void (*const poll_fn[])(void) = {
FcMonPoll, NetDiagPoll, NetMonPoll, NetPoll,
PollExtWatchdog, PollFaaLight, PollGps, PollGpsRtcmMessages,
PollSwitch, Q7WatchdogFcPoll, FpvPitotControlPoll,
};
// Loop forever.
for (;;) {
// Align schedule with the ePWM output that synchronizes the IMU. The ePWM
// frequency is 2400 Hz, so we have <416 us to process everything.
Adis16488WaitForSyncPulse();
int64_t now = ClockGetUs();
int64_t start_time = now;
// Use LEDs for loop timing measurements.
LedOn(true, true);
// At this time, the MibSPI should have an IMU transfer in progress for
// the current synchronization pulse. If we trigger a pitot tube transfer
// now, the MibSPI handle this request immediately after the IMU transfer
// completes.
pitot = PollPitot(pitot, now);
// Sample the IMU output from the previous synchronization pulse.
Adis16488OutputData imu_output;
bool imu_cs_update = false;
if (Adis16488PollOutputData(now, &imu_output)) {
imu_cs_update = ImuOutputData(&imu_output, &g_sensor_message, now);
++imu_count;
}
// Output sensor warnings.
ImuOutputUpdateFailure(!Adis16488IsReady(), &g_sensor_message);
FcOutputGpsFailure(!GpsIsReady(kFcConfigParams->gps_receiver),
&g_sensor_message);
// Send FlightComputerImuMessage.
if (imu_count >= IMU_OUTPUT_DECIMATION) {
imu_count = 0;
now = ClockGetUs();
ImuOutputSendImuMessage(kFcConfigParams->imu.fir_coefs, now);
}
// Send FlightComputerSensorMessage. Synchronize to c/s update.
++sensor_message_count;
if (imu_cs_update || sensor_message_count >= CONING_SCULLING_DECIMATION) {
sensor_message_count = 0;
now = ClockGetUs();
ImuOutputUpdateSensorMessage(&g_sensor_message, now);
FcOutputUpdateSensorMessage(&g_sensor_message, now);
NetSendAioFlightComputerSensorMessage(&g_sensor_message);
}
// Send SerialDebugMessage.
++serial_debug_count;
if (serial_debug_count >= SERIAL_DEBUG_DECIMATION) {
serial_debug_count = 0;
GpsSendSerialDebugMessage();
}
// Send Hemisphere/NovAtel/SeptentrioSolutionMessage.
++gps_solution_count;
if (gps_solution_count >= GPS_SOLUTION_DECIMATION) {
gps_solution_count = 0;
now = ClockGetUs();
GpsSendSolutionMessage(kFcConfigParams->gps_receiver, now);
}
// Send Hemisphere/NovAtel/SeptentrioObservationsMessage.
++gps_observations_count;
if (gps_observations_count >= GPS_OBSERVATIONS_DECIMATION) {
gps_observations_count = 0;
now = ClockGetUs();
GpsSendObservationsMessage(kFcConfigParams->gps_receiver, now);
}
// Send GpsSatellitesMessage.
++gps_satellites_count;
if (gps_satellites_count >= GPS_SATELLITES_DECIMATION) {
gps_satellites_count = 0;
now = ClockGetUs();
GpsSendSatellitesMessage(now);
}
// Send GpsTimeMessage.
++gps_time_count;
if (gps_time_count >= GPS_TIME_DECIMATION) {
gps_time_count = 0;
now = ClockGetUs();
GpsSendTimeMessage(now);
}
// Send FaaLightStatusMessage.
if (IsLightNode(g_current_node)) {
++faa_light_status_message_count;
if (faa_light_status_message_count >= FAA_LIGHT_TIME_DECIMATION) {
faa_light_status_message_count = 0;
FaaLightSendStatusMessage();
}
}
// Send SlowStatusMessage.
++slow_status_message_count;
if (slow_status_message_count >= SLOW_STATUS_MESSAGE_DECIMATION) {
slow_status_message_count = 0;
now = ClockGetUs();
OutputSendSlowStatusMessage(now);
}
// Poll all trivial processes once.
for (int32_t i = 0; i < ARRAYSIZE(poll_fn); ++i) {
poll_fn[i]();
}
// Complete required processing.
LedOff(true, false);
// Poll trivial processes until end time.
now = ClockGetUs();
int64_t end_time = start_time + LOOP_PROCESSING_TIME_US - GUARD_TIME_US;
for (int32_t cycle = 0; now < end_time; ++cycle) {
cycle %= ARRAYSIZE(poll_fn);
poll_fn[cycle]();
now = ClockGetUs();
}
}
}
int main(void) {
// Initialize watchdog.
ExtWatchdogInit();
Q7WatchdogFcInit();
// Initialize TMS570 hardware.
MibSPIInit(1, kSpiPinmuxAll); // For access switch.
MibSPIInit(3, kSpiPinmuxAll); // For IMU, pitot.
I2cInit(400000); // For voltage and temperature monitoring.
g_current_node = AppConfigGetAioNode();
if (IsLightNode(g_current_node)) {
FaaLightInit(); // Initialize FAA lights.
}
// Initialize network.
SwitchConfigInit();
Bcm53101Init(true);
NetInit(g_current_node);
// Perform self test as soon as possible and immediately after NetInit()
// such that we validate parameters before calling dependent code.
SelfTest();
NetMonInit(GetSwitchConfig()->info);
NetDiagInit(GetSwitchConfig()->info);
// Initialize IMU.
Adis16488Init();
// Initialize pitot.
HscInit();
// Initialize GPS.
GpsInit();
// Initialize flight computer output.
FcOutputInit(&g_sensor_message);
// Initialize IMU output.
ImuOutputInit(&g_sensor_message);
// FPV power control.
FpvPitotControlInit(&g_sensor_message);
// Initialize LEDs for timing measurements.
LedInit();
// Initialize flight computer monitors.
FcMonInit(&g_sensor_message.fc_mon, &g_sensor_message.aio_mon);
// Initialize slow status message.
OutputInitSlowStatusMessage();
// Enable interrupts for SCI driver.
VimEnableIrq();
// Run!
ScheduleLoop();
return 0;
}
| 6,242 |
460 |
#include "../../tools/assistant/lib/qhelpsearchresultwidget.h"
| 23 |
348 |
{"nom":"Rouvenac","circ":"3ème circonscription","dpt":"Aude","inscrits":178,"abs":100,"votants":78,"blancs":13,"nuls":4,"exp":61,"res":[{"nuance":"REM","nom":"<NAME>","voix":40},{"nuance":"SOC","nom":"<NAME>","voix":21}]}
| 90 |
333 |
<filename>Utils/MultiGather.py
# Copyright 2017 <NAME>. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==============================================================================
import tensorflow as tf
def gather(tensors, indices):
with tf.name_scope("multiGather"):
res = []
for a in tensors:
res.append(tf.gather_nd(a, indices))
return res
def gatherTopK(t, k, others=[], sorted=False):
res=[]
with tf.name_scope("gather_top_k"):
isMoreThanK = tf.shape(t)[-1]>k
values, indices = tf.cond(isMoreThanK, lambda: tuple(tf.nn.top_k(t, k=k, sorted=sorted)), lambda: (t, tf.zeros((0,1), tf.int32)))
indices = tf.reshape(indices, [-1,1])
res.append(values)
for o in others:
res.append(tf.cond(isMoreThanK, lambda: tf.gather_nd(o, indices), lambda: o))
return res
| 498 |
1,481 |
<gh_stars>1000+
package apoc.result;
import java.util.List;
/**
* Created by alberto.delazzari on 04/07/17.
*/
public class ConstraintRelationshipInfo {
public final String name;
public final String type;
public final List<String> properties;
public final String status;
public ConstraintRelationshipInfo(String name, String type, List<String> properties, String status) {
this.name = name;
this.type = type;
this.properties = properties;
this.status = status;
}
}
| 186 |
319 |
/*
* IXWebSocketHandshake.h
* Author: <NAME>
* Copyright (c) 2019 Machine Zone, Inc. All rights reserved.
*/
#pragma once
#include "IXCancellationRequest.h"
#include "IXSocket.h"
#include "IXWebSocketHttpHeaders.h"
#include "IXWebSocketInitResult.h"
#include "IXWebSocketPerMessageDeflate.h"
#include "IXWebSocketPerMessageDeflateOptions.h"
#include <atomic>
#include <chrono>
#include <memory>
#include <string>
namespace ix
{
class WebSocketHandshake
{
public:
WebSocketHandshake(std::atomic<bool>& requestInitCancellation,
std::unique_ptr<Socket>& _socket,
WebSocketPerMessageDeflatePtr& perMessageDeflate,
WebSocketPerMessageDeflateOptions& perMessageDeflateOptions,
std::atomic<bool>& enablePerMessageDeflate);
WebSocketInitResult clientHandshake(const std::string& url,
const WebSocketHttpHeaders& extraHeaders,
const std::string& host,
const std::string& path,
int port,
int timeoutSecs);
WebSocketInitResult serverHandshake(int timeoutSecs, bool enablePerMessageDeflate);
private:
std::string genRandomString(const int len);
// Parse HTTP headers
WebSocketInitResult sendErrorResponse(int code, const std::string& reason);
bool insensitiveStringCompare(const std::string& a, const std::string& b);
std::atomic<bool>& _requestInitCancellation;
std::unique_ptr<Socket>& _socket;
WebSocketPerMessageDeflatePtr& _perMessageDeflate;
WebSocketPerMessageDeflateOptions& _perMessageDeflateOptions;
std::atomic<bool>& _enablePerMessageDeflate;
};
} // namespace ix
| 879 |
305 |
<gh_stars>100-1000
#include <isl/map.h>
#include <isl/union_map.h>
#undef EL
#define EL isl_basic_map
#include <isl_list_templ.h>
#undef EL_BASE
#define EL_BASE basic_map
#include <isl_list_templ.c>
#undef EL
#define EL isl_map
#include <isl_list_templ.h>
#undef EL_BASE
#define EL_BASE map
#include <isl_list_templ.c>
#undef EL
#define EL isl_union_map
#include <isl_list_templ.h>
#undef EL_BASE
#define EL_BASE union_map
#include <isl_list_templ.c>
| 216 |
1,046 |
<filename>pynes/analyzer.py
# -*- coding: utf-8 -*-
from re import match
import re
from io import StringIO, BytesIO
class UnknownToken(Exception):
''' Unknown token error when trying to tokenize a single line '''
def __init__(self, line, column, line_code):
self.line_code = line_code
self.line = line
self.column = column
super(UnknownToken, self).__init__(self.message)
@property
def message(self):
msg = 'Unknown token @({line},{column}): {0}'
return msg.format(self.line_code.rstrip(), **vars(self))
def code_line_generator(code):
''' A generator for lines from a file/string, keeping the \n at end '''
if isinstance(code, unicode):
stream = StringIO(code)
elif isinstance(code, str):
stream = BytesIO(code)
else:
stream = code # Should be a file input stream, already
while True:
line = stream.readline()
if line:
yield line
else: # Line is empty (without \n) at EOF
break
def analyse(code, token_types):
for line, line_code in enumerate(code_line_generator(code), 1):
column = 1
while column <= len(line_code):
remaining_line_code = line_code[column - 1:]
for ttype in token_types:
m = match(ttype['regex'], remaining_line_code, re.S)
if m:
value = m.group(0)
if ttype['store']:
yield dict(
type=ttype['type'],
value=value,
line=line,
column=column
)
column += len(value)
break
else:
raise UnknownToken(line, column, line_code)
| 918 |
2,177 |
<reponame>roipoussiere/requests
"""
oauthlib.oauth2.draft_25
~~~~~~~~~~~~~~
This module is an implementation of various logic needed
for signing and checking OAuth 2.0 draft 25 requests.
"""
from tokens import prepare_bearer_uri, prepare_bearer_headers
from tokens import prepare_bearer_body, prepare_mac_header
from parameters import prepare_grant_uri, prepare_token_request
from parameters import parse_authorization_code_response
from parameters import parse_implicit_response, parse_token_response
AUTH_HEADER = u'auth_header'
URI_QUERY = u'query'
BODY = u'body'
class Client(object):
def __init__(self, client_id,
default_redirect_uri=None,
token_type=None,
access_token=None,
refresh_token=None):
"""Initialize a client with commonly used attributes."""
self.client_id = client_id
self.default_redirect_uri = default_redirect_uri
self.token_type = token_type
self.access_token = access_token
self.refresh_token = refresh_token
self.token_types = {
u'bearer': self._add_bearer_token,
u'mac': self._add_mac_token
}
def add_token(self, uri, http_method=u'GET', body=None, headers=None,
token_placement=AUTH_HEADER):
"""Add token to the request uri, body or authorization header.
The access token type provides the client with the information
required to successfully utilize the access token to make a protected
resource request (along with type-specific attributes). The client
MUST NOT use an access token if it does not understand the token
type.
For example, the "bearer" token type defined in
[I-D.ietf-oauth-v2-bearer] is utilized by simply including the access
token string in the request:
GET /resource/1 HTTP/1.1
Host: example.com
Authorization: Bearer mF_9.B5f-4.1JqM
while the "mac" token type defined in [I-D.ietf-oauth-v2-http-mac] is
utilized by issuing a MAC key together with the access token which is
used to sign certain components of the HTTP requests:
GET /resource/1 HTTP/1.1
Host: example.com
Authorization: MAC id="h480djs93hd8",
nonce="274312:dj83hs9s",
mac="kDZvddkndxvhGRXZhvuDjEWhGeE="
.. _`I-D.ietf-oauth-v2-bearer`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#ref-I-D.ietf-oauth-v2-bearer
.. _`I-D.ietf-oauth-v2-http-mac`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#ref-I-D.ietf-oauth-v2-http-mac
"""
return self.token_types[self.token_type](uri, http_method, body,
headers, token_placement)
def prepare_refresh_body(self, body=u'', refresh_token=None, scope=None):
"""Prepare an access token request, using a refresh token.
If the authorization server issued a refresh token to the client, the
client makes a refresh request to the token endpoint by adding the
following parameters using the "application/x-www-form-urlencoded"
format in the HTTP request entity-body:
grant_type
REQUIRED. Value MUST be set to "refresh_token".
refresh_token
REQUIRED. The refresh token issued to the client.
scope
OPTIONAL. The scope of the access request as described by
Section 3.3. The requested scope MUST NOT include any scope
not originally granted by the resource owner, and if omitted is
treated as equal to the scope originally granted by the
resource owner.
"""
refresh_token = refresh_token or self.refresh_token
return prepare_token_request(u'refresh_token', body=body, scope=scope,
refresh_token=refresh_token)
def _add_bearer_token(self, uri, http_method=u'GET', body=None,
headers=None, token_placement=AUTH_HEADER):
"""Add a bearer token to the request uri, body or authorization header."""
if token_placement == AUTH_HEADER:
headers = prepare_bearer_headers(self.token, headers)
if token_placement == URI_QUERY:
uri = prepare_bearer_uri(self.token, uri)
if token_placement == BODY:
body = prepare_bearer_body(self.token, body)
return uri, headers, body
def _add_mac_token(self, uri, http_method=u'GET', body=None,
headers=None, token_placement=AUTH_HEADER):
"""Add a MAC token to the request authorization header."""
headers = prepare_mac_header(self.token, uri, self.key, http_method,
headers=headers, body=body, ext=self.ext,
hash_algorithm=self.hash_algorithm)
return uri, headers, body
def _populate_attributes(self, response):
"""Add commonly used values such as access_token to self."""
if u'access_token' in response:
self.access_token = response.get(u'access_token')
if u'refresh_token' in response:
self.refresh_token = response.get(u'refresh_token')
if u'token_type' in response:
self.token_type = response.get(u'token_type')
if u'expires_in' in response:
self.expires_in = response.get(u'expires_in')
if u'code' in response:
self.code = response.get(u'code')
def prepare_request_uri(self, *args, **kwargs):
"""Abstract method used to create request URIs."""
raise NotImplementedError("Must be implemented by inheriting classes.")
def prepare_request_body(self, *args, **kwargs):
"""Abstract method used to create request bodies."""
raise NotImplementedError("Must be implemented by inheriting classes.")
def parse_request_uri_response(self, *args, **kwargs):
"""Abstract method used to parse redirection responses."""
def parse_request_body_response(self, *args, **kwargs):
"""Abstract method used to parse JSON responses."""
class WebApplicationClient(Client):
"""A client utilizing the authorization code grant workflow.
A web application is a confidential client running on a web
server. Resource owners access the client via an HTML user
interface rendered in a user-agent on the device used by the
resource owner. The client credentials as well as any access
token issued to the client are stored on the web server and are
not exposed to or accessible by the resource owner.
The authorization code grant type is used to obtain both access
tokens and refresh tokens and is optimized for confidential clients.
As a redirection-based flow, the client must be capable of
interacting with the resource owner's user-agent (typically a web
browser) and capable of receiving incoming requests (via redirection)
from the authorization server.
"""
def prepare_request_uri(self, uri, redirect_uri=None, scope=None,
state=None, **kwargs):
"""Prepare the authorization code request URI
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format as defined by
[`W3C.REC-html401-19991224`_]:
response_type
REQUIRED. Value MUST be set to "code".
client_id
REQUIRED. The client identifier as described in `Section 2.2`_.
redirect_uri
OPTIONAL. As described in `Section 3.1.2`_.
scope
OPTIONAL. The scope of the access request as described by
`Section 3.3`_.
state
RECOMMENDED. An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent back
to the client. The parameter SHOULD be used for preventing
cross-site request forgery as described in `Section 10.12`_.
.. _`W3C.REC-html401-19991224`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#ref-W3C.REC-html401-19991224
.. _`Section 2.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-2.2
.. _`Section 3.1.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.1.2
.. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3
.. _`Section 10.12`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-10.12
"""
redirect_uri = redirect_uri or self.default_redirect_uri
return prepare_grant_uri(uri, self.client_id, u'code',
redirect_uri=redirect_uri, scope=scope, state=state, **kwargs)
def prepare_request_body(self, code, body=u'', redirect_uri=None, **kwargs):
"""Prepare the access token request body.
The client makes a request to the token endpoint by adding the
following parameters using the "application/x-www-form-urlencoded"
format in the HTTP request entity-body:
grant_type
REQUIRED. Value MUST be set to "authorization_code".
code
REQUIRED. The authorization code received from the
authorization server.
redirect_uri
REQUIRED, if the "redirect_uri" parameter was included in the
authorization request as described in Section 4.1.1, and their
values MUST be identical.
.. _`Section 4.1.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-4.1.1
"""
redirect_uri = redirect_uri or self.default_redirect_uri
code = code or self.code
return prepare_token_request(u'authorization_code', code=code, body=body,
redirect_uri=redirect_uri, **kwargs)
def parse_request_uri_response(self, uri, state=None):
"""Parse the URI query for code and state.
If the resource owner grants the access request, the authorization
server issues an authorization code and delivers it to the client by
adding the following parameters to the query component of the
redirection URI using the "application/x-www-form-urlencoded" format:
code
REQUIRED. The authorization code generated by the
authorization server. The authorization code MUST expire
shortly after it is issued to mitigate the risk of leaks. A
maximum authorization code lifetime of 10 minutes is
RECOMMENDED. The client MUST NOT use the authorization code
more than once. If an authorization code is used more than
once, the authorization server MUST deny the request and SHOULD
revoke (when possible) all tokens previously issued based on
that authorization code. The authorization code is bound to
the client identifier and redirection URI.
state
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
"""
response = parse_authorization_code_response(uri, state=state)
self._populate_attributes(response)
return response
def parse_request_body_response(self, body, scope=None):
"""Parse the JSON response body.
If the access token request is valid and authorized, the
authorization server issues an access token and optional refresh
token as described in `Section 5.1`_. If the request client
authentication failed or is invalid, the authorization server returns
an error response as described in `Section 5.2`_.
.. `Section 5.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.1
.. `Section 5.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.2
"""
response = parse_token_response(body, scope=scope)
self._populate_attributes(response)
return response
class UserAgentClient(Client):
"""A public client utilizing the implicit code grant workflow.
A user-agent-based application is a public client in which the
client code is downloaded from a web server and executes within a
user-agent (e.g. web browser) on the device used by the resource
owner. Protocol data and credentials are easily accessible (and
often visible) to the resource owner. Since such applications
reside within the user-agent, they can make seamless use of the
user-agent capabilities when requesting authorization.
The implicit grant type is used to obtain access tokens (it does not
support the issuance of refresh tokens) and is optimized for public
clients known to operate a particular redirection URI. These clients
are typically implemented in a browser using a scripting language
such as JavaScript.
As a redirection-based flow, the client must be capable of
interacting with the resource owner's user-agent (typically a web
browser) and capable of receiving incoming requests (via redirection)
from the authorization server.
Unlike the authorization code grant type in which the client makes
separate requests for authorization and access token, the client
receives the access token as the result of the authorization request.
The implicit grant type does not include client authentication, and
relies on the presence of the resource owner and the registration of
the redirection URI. Because the access token is encoded into the
redirection URI, it may be exposed to the resource owner and other
applications residing on the same device.
"""
def prepare_request_uri(self, uri, redirect_uri=None, scope=None,
state=None, **kwargs):
"""Prepare the implicit grant request URI.
The client constructs the request URI by adding the following
parameters to the query component of the authorization endpoint URI
using the "application/x-www-form-urlencoded" format:
response_type
REQUIRED. Value MUST be set to "token".
client_id
REQUIRED. The client identifier as described in Section 2.2.
redirect_uri
OPTIONAL. As described in Section 3.1.2.
scope
OPTIONAL. The scope of the access request as described by
Section 3.3.
state
RECOMMENDED. An opaque value used by the client to maintain
state between the request and callback. The authorization
server includes this value when redirecting the user-agent back
to the client. The parameter SHOULD be used for preventing
cross-site request forgery as described in Section 10.12.
"""
redirect_uri = redirect_uri or self.default_redirect_uri
return prepare_grant_uri(uri, self.client_id, u'token',
redirect_uri=redirect_uri, state=state, scope=scope, **kwargs)
def parse_request_uri_response(self, uri, state=None, scope=None):
"""Parse the response URI fragment.
If the resource owner grants the access request, the authorization
server issues an access token and delivers it to the client by adding
the following parameters to the fragment component of the redirection
URI using the "application/x-www-form-urlencoded" format:
access_token
REQUIRED. The access token issued by the authorization server.
token_type
REQUIRED. The type of the token issued as described in
`Section 7.1`_. Value is case insensitive.
expires_in
RECOMMENDED. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
If omitted, the authorization server SHOULD provide the
expiration time via other means or document the default value.
scope
OPTIONAL, if identical to the scope requested by the client,
otherwise REQUIRED. The scope of the access token as described
by `Section 3.3`_.
state
REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the
client.
.. _`Section 7.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-7.1
.. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3
"""
response = parse_implicit_response(uri, state=state, scope=scope)
self._populate_attributes(response)
return response
class NativeApplicationClient(Client):
"""A public client utilizing the client credentials grant workflow.
A native application is a public client installed and executed on
the device used by the resource owner. Protocol data and
credentials are accessible to the resource owner. It is assumed
that any client authentication credentials included in the
application can be extracted. On the other hand, dynamically
issued credentials such as access tokens or refresh tokens can
receive an acceptable level of protection. At a minimum, these
credentials are protected from hostile servers with which the
application may interact with. On some platforms these
credentials might be protected from other applications residing on
the same device.
The client can request an access token using only its client
credentials (or other supported means of authentication) when the
client is requesting access to the protected resources under its
control, or those of another resource owner which has been previously
arranged with the authorization server (the method of which is beyond
the scope of this specification).
The client credentials grant type MUST only be used by confidential
clients.
Since the client authentication is used as the authorization grant,
no additional authorization request is needed.
"""
def prepare_request_body(self, body=u'', scope=None, **kwargs):
"""Add the client credentials to the request body.
The client makes a request to the token endpoint by adding the
following parameters using the "application/x-www-form-urlencoded"
format in the HTTP request entity-body:
grant_type
REQUIRED. Value MUST be set to "client_credentials".
scope
OPTIONAL. The scope of the access request as described by
`Section 3.3`_.
.. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3
"""
return prepare_token_request(u'client_credentials', body=body,
scope=scope, **kwargs)
def parse_request_body_response(self, body, scope=None):
"""Parse the JSON response body.
If the access token request is valid and authorized, the
authorization server issues an access token as described in
`Section 5.1`_. A refresh token SHOULD NOT be included. If the request
failed client authentication or is invalid, the authorization server
returns an error response as described in `Section 5.2`_.
.. `Section 5.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.1
.. `Section 5.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.2
"""
response = parse_token_response(body, scope=scope)
self._populate_attributes(response)
return response
class PasswordCredentialsClient(Client):
"""A public client using the resource owner password and username directly.
The resource owner password credentials grant type is suitable in
cases where the resource owner has a trust relationship with the
client, such as the device operating system or a highly privileged
application. The authorization server should take special care when
enabling this grant type, and only allow it when other flows are not
viable.
The grant type is suitable for clients capable of obtaining the
resource owner's credentials (username and password, typically using
an interactive form). It is also used to migrate existing clients
using direct authentication schemes such as HTTP Basic or Digest
authentication to OAuth by converting the stored credentials to an
access token.
The method through which the client obtains the resource owner
credentials is beyond the scope of this specification. The client
MUST discard the credentials once an access token has been obtained.
"""
def prepare_request_body(self, username, password, body=u'', scope=None,
**kwargs):
"""Add the resource owner password and username to the request body.
The client makes a request to the token endpoint by adding the
following parameters using the "application/x-www-form-urlencoded"
format in the HTTP request entity-body:
grant_type
REQUIRED. Value MUST be set to "password".
username
REQUIRED. The resource owner username.
password
REQUIRED. The resource owner password.
scope
OPTIONAL. The scope of the access request as described by
`Section 3.3`_.
.. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3
"""
return prepare_token_request(u'password', body=body, username=username,
password=password, scope=scope, **kwargs)
def parse_request_body_response(self, body, scope=None):
"""Parse the JSON response body.
If the access token request is valid and authorized, the
authorization server issues an access token and optional refresh
token as described in `Section 5.1`_. If the request failed client
authentication or is invalid, the authorization server returns an
error response as described in `Section 5.2`_.
.. `Section 5.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.1
.. `Section 5.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.2
"""
response = parse_token_response(body, scope=scope)
self._populate_attributes(response)
return response
class Server(object):
pass
| 8,466 |
360 |
<filename>src/common/interfaces/libpq/jdbc/client_logic_jni/org_postgresql_jdbc_ClientLogicImpl.cpp
/*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* org_postgresql_jdbc_ClientLogicImpl.cpp
*
* IDENTIFICATION
* src/common/interfaces/libpq/jdbc/client_logic_jni/org_postgresql_jdbc_ClientLogicImpl.cpp
*
* -------------------------------------------------------------------------
*/
#include "client_logic_jni.h"
#include "org_postgresql_jdbc_ClientLogicImpl.h"
#include <jni.h>
#include <stdio.h>
#include "libpq-fe.h"
#include "jni_logger.h"
#include "jni_string_convertor.h"
#include "jni_util.h"
#include "jni_logger.h"
#include "client_logic_data_fetcher/data_fetcher_manager.h"
#define DELETE_ARRAY(ptr) \
if (ptr != NULL) { \
delete[] ptr; \
ptr = NULL; \
}
/*
* Placeholder for few usefull methods in JNI pluming
*/
struct JniResult {
JniResult(JNIEnv *env, int array_length) : m_env(env), m_array_length(array_length) {}
/* *
* Initializes the array to return
* @return false on any failure or true on success
*/
bool init()
{
if (m_env == NULL) {
return false; /* Should never happen */
}
object_class = m_env->FindClass("java/lang/Object");
if (object_class == NULL) {
return false; /* Should never happen */
}
array = m_env->NewObjectArray(m_array_length, object_class, NULL);
if (array == NULL) {
return false; /* Should never happen */
}
return true;
}
/* *
* Set the array to return error
* @param status
*/
void set_error_return(DriverError *status) const
{
if (status == NULL) {
return;
}
set_error(m_env, object_class, array, status->get_error_code(),
status->get_error_message() ? status->get_error_message() : "");
}
/* *
* sets to return OK success
*/
void set_no_error_retrun() const
{
set_no_error(m_env, object_class, array);
}
/*
* Convert java string to utf8 char * using JNIStringConvertor and handles errors if any
* @param string_convertor string converter pointer
* @param java_str the java string to convert
* @param status
* @param failure_message message to put in log for failures
* @return true for success and false for failures
*/
bool convert_string(JNIStringConvertor *string_convertor, jstring java_str, DriverError *status,
const char *failure_message) const
{
if (string_convertor == NULL || java_str == NULL || status == NULL) {
return false;
}
string_convertor->convert(m_env, java_str);
if (string_convertor->c_str == NULL) {
status->set_error(JNI_SYSTEM_ERROR_CODES::STRING_CREATION_FAILED);
set_error_return(status);
JNI_LOG_ERROR("string conversion failed :%s", failure_message ? failure_message : "");
return false;
}
return true;
}
bool from_handle(long handle, ClientLogicJNI **client_logic, DriverError *status, const char *failure_message) const
{
if (!ClientLogicJNI::from_handle(handle, client_logic, status) || *client_logic == NULL) {
JNI_LOG_ERROR("From handle failed: %ld, on: %s", (long)handle, failure_message ? failure_message : "");
set_error_return(status);
return false;
}
return true;
}
JNIEnv *m_env;
int m_array_length;
jobjectArray array = NULL;
jclass object_class = NULL;
};
/* *
* Links the client logic object with its libpq conn to the Java PgConnection Instance
* @param env pointer to JVM
* @param jdbc_cl_impl pointer back to the Java client logic impl instance
* @return java array
* [0][0] - int status code - zero for success
* [0][1] - string status description
* [1] - long - instance handle to be re-used in future calls by the same connection
*/
JNIEXPORT jobjectArray JNICALL Java_org_postgresql_jdbc_ClientLogicImpl_linkClientLogicImpl(JNIEnv *env,
jobject jdbc_cl_impl, jstring database_name_java)
{
JniResult result(env, 2);
if (!result.init()) {
return result.array; /* Should never happen */
}
if (env == NULL || jdbc_cl_impl == NULL) {
return result.array; /* Should never happen */
}
DriverError status(0, "");
// Link the client logic object
ClientLogicJNI *client_logic_jni = NULL;
client_logic_jni = new (std::nothrow) ClientLogicJNI();
if (client_logic_jni == NULL) {
status.set_error(UNEXPECTED_ERROR);
JNI_LOG_ERROR("linkClientLogicImpl failed");
} else {
DriverError status(0, "");
JNIStringConvertor database_name;
database_name.convert(env, database_name_java);
if (!client_logic_jni->link_client_logic(env, jdbc_cl_impl, database_name.c_str, &status)) {
delete client_logic_jni;
client_logic_jni = NULL;
result.set_error_return(&status);
} else {
// Successful Connection
result.set_no_error_retrun();
jlong handle = (jlong)(intptr_t)client_logic_jni;
place_jlong_in_target_array(env, handle, 1, result.array);
}
}
return result.array;
}
JNIEXPORT jobjectArray JNICALL Java_org_postgresql_jdbc_ClientLogicImpl_setKmsInfoImpl(JNIEnv *env, jobject,
jlong handle, jstring key_java, jstring value_java)
{
JNIStringConvertor key;
JNIStringConvertor value;
JniResult result(env, 1);
if (!result.init()) {
return result.array; /* Should never happen */
}
DriverError status(0, "");
ClientLogicJNI *client_logic_jni = NULL;
if (!result.from_handle((long)handle, &client_logic_jni, &status, "setKmsInfoImpl")) {
return result.array;
}
if (!result.convert_string(&key, key_java, &status, "setKmsInfo dump kms info")) {
return result.array;
}
if (!result.convert_string(&value, value_java, &status, "setKmsInfo dump kms info")) {
return result.array;
}
if (client_logic_jni->set_kms_info(key.c_str, value.c_str)) {
result.set_no_error_retrun();
} else {
status.set_error(INVALID_INPUT_PARAMETER, get_cmkem_errmsg(CMKEM_CHECK_INPUT_AUTH_ERR));
result.set_error_return(&status);
}
return result.array;
}
/*
* Runs the pre query, to replace client logic field values with binary format before sending the query to the database
* server
* @param env pointer to jvm
* @param
* @param handle pointer to ClientLogicJNI instance
* @param original_query_java the query with potentially client logic values in user format
* @return java array
* [0][0] - int status code - zero for success
* [0][1] - string status description
* [1] - String - The modified query
*/
JNIEXPORT jobjectArray JNICALL Java_org_postgresql_jdbc_ClientLogicImpl_runQueryPreProcessImpl(JNIEnv *env,
jobject jdbc_cl_impl, jlong handle, jstring original_query_java)
{
JniResult result(env, 2);
if (!result.init()) {
return result.array; /* Should never happen */
}
if (env == NULL || original_query_java == NULL) {
return result.array; /* Should never happen */
}
DriverError status(0, "");
ClientLogicJNI *client_logic = NULL;
if (!result.from_handle((long)handle, &client_logic, &status, "runQueryPreProcess")) {
JNI_LOG_ERROR("no handle? %s", env->GetStringUTFChars(original_query_java, NULL));
return result.array;
}
JNIStringConvertor original_query;
original_query.convert(env, original_query_java);
if (original_query.c_str == NULL) {
status.set_error(JNI_SYSTEM_ERROR_CODES::STRING_CREATION_FAILED);
result.set_error_return(&status);
JNI_LOG_ERROR("Java_org_postgresql_jdbc_ClientLogicImpl_runQueryPreProcessImpl error code:%d text:'%s'",
status.get_error_code(), status.get_error_message() ? status.get_error_message() : "");
return result.array;
}
const char *original_query_dup = client_logic->get_new_query(original_query.c_str);
if (original_query_dup == NULL) {
status.set_error(JNI_SYSTEM_ERROR_CODES::STRING_CREATION_FAILED);
result.set_error_return(&status);
JNI_LOG_ERROR("Java_org_postgresql_jdbc_ClientLogicImpl_runQueryPreProcessImpl error code:%d text:'%s'",
status.get_error_code(), status.get_error_message() ? status.get_error_message() : "");
result.set_error_return(&status);
return result.array;
}
client_logic->set_jni_env_and_cl_impl(env, jdbc_cl_impl);
if (!client_logic->run_pre_query(original_query_dup, &status)) {
JNI_LOG_ERROR(
"Java_org_postgresql_jdbc_ClientLogicImpl_runQueryPreProcessImpl failed: %ld, error code: %d error: '%s'",
(long)handle, status.get_error_code(), status.get_error_message() ? status.get_error_message() : "");
result.set_error_return(&status);
return result.array;
}
result.set_no_error_retrun();
place_string_in_array(env, client_logic->get_pre_query_result(), 1, result.array);
client_logic->clean_stmnt();
return result.array;
}
/*
* Runs post process on the backend, to free the client logic state machine when a query is done
* @param env pointer to jvm
* @param
* @param handle pointer to ClientLogicJNI instance
* @return java array
* [0][0] - int status code - zero for success
* [0][1] - string status description
*/
JNIEXPORT jobjectArray JNICALL Java_org_postgresql_jdbc_ClientLogicImpl_runQueryPostProcessImpl(JNIEnv *env,
jobject jdbc_cl_impl, jlong handle)
{
JniResult result(env, 1);
if (!result.init()) {
return result.array; /* Should never happen */
}
DriverError status(0, "");
ClientLogicJNI *client_logic = NULL;
if (!result.from_handle((long)handle, &client_logic, &status, "runQueryPostProcess")) {
return result.array;
}
client_logic->set_jni_env_and_cl_impl(env, jdbc_cl_impl);
if (JNI_TRUE == env->IsSameObject(jdbc_cl_impl, NULL)) {
fprintf(stderr, "Client encryption run_post_query failed jobject %p was invalid\n", jdbc_cl_impl);
}
if (!client_logic->run_post_query(&status)) {
JNI_LOG_ERROR("run_post_query failed: %ld, error code: %d error: '%s'", (long)handle, status.get_error_code(),
status.get_error_message() ? status.get_error_message() : "");
result.set_error_return(&status);
return result.array;
}
result.set_no_error_retrun();
return result.array;
}
/*
* Replace client logic field value with user input - used when receiving data in a resultset
* @param env pointer to jvm
* @param
* @param handle pointer to ClientLogicJNI instance
* @param data_to_process_java the data in binary format (hexa)
* @param data_type the oid (modid) of the original field type
* @return java array with the format below:
* [0][0] - int status code - zero for success
* [0][1] - string status description
* [1] - String - The data in user format
*/
JNIEXPORT jobjectArray JNICALL Java_org_postgresql_jdbc_ClientLogicImpl_runClientLogicImpl(JNIEnv *env,
jobject jdbc_cl_impl, jlong handle, jstring data_to_process_java, jint data_type)
{
JniResult result(env, 2);
if (!result.init()) {
return result.array; /* Should never happen */
}
if (env == NULL || data_to_process_java == NULL) {
return result.array;
}
DriverError status(0, "");
JNIStringConvertor data_to_process;
if (!result.convert_string(&data_to_process, data_to_process_java, &status, "runClientLogicImpl")) {
return result.array;
}
ClientLogicJNI *client_logic = NULL;
if (!result.from_handle((long)handle, &client_logic, &status, "runClientLogicImpl")) {
return result.array;
}
client_logic->set_jni_env_and_cl_impl(env, jdbc_cl_impl);
unsigned char *proccessed_data = NULL;
size_t length_output;
if (!client_logic->deprocess_value(data_to_process.c_str, data_type, &proccessed_data, length_output, &status)) {
libpq_free(proccessed_data);
JNI_LOG_ERROR("Java_org_postgresql_jdbc_ClientLogicImpl_runClientLogicImpl failed:error code: %d error: '%s'",
status.get_error_code(), status.get_error_message() ? status.get_error_message() : "");
result.set_error_return(&status);
return result.array;
}
result.set_no_error_retrun();
place_ustring_in_array(env, proccessed_data, 1, result.array);
libpq_free(proccessed_data);
return result.array;
}
/* *
* [0][0] - int status code - zero for success
* [0][1] - string status description
* [1] - int 0 not client logic 1 - is client logic
* [2] - String - The data in user format
*/
JNIEXPORT jobjectArray JNICALL Java_org_postgresql_jdbc_ClientLogicImpl_runClientLogic4RecordImpl(JNIEnv *env, jobject,
jlong handle, jstring data_to_process_java, jint mod_data_type, jint data_type, jstring column_label_java)
{
JniResult result(env, ARRAY_SIZE + 1);
if (!result.init()) {
return result.array; /* Should never happen */
}
if (env == NULL || data_to_process_java == NULL) {
return result.array;
}
DriverError status(0, "");
JNIStringConvertor data_to_process;
if (!result.convert_string(&data_to_process, data_to_process_java, &status, "runClientLogic4RecordImpl")) {
return result.array;
}
JNIStringConvertor column_label;
if (!result.convert_string(&column_label, column_label_java, &status, "runClientLogic4RecordImpl")) {
return result.array;
}
ClientLogicJNI *client_logic = NULL;
if (!result.from_handle((long)handle, &client_logic, &status, "runClientLogic4RecordImpl")) {
return result.array;
}
bool is_client_logic = false;
unsigned char *proccessed_data = NULL;
size_t length_output;
if (!client_logic->process_record_data(data_to_process.c_str, NULL, data_type, column_label.c_str, &proccessed_data,
&is_client_logic, length_output, &status)) {
libpq_free(proccessed_data);
JNI_LOG_ERROR("Java_org_postgresql_jdbc_ClientLogicImpl_runClientLogicImpl failed:error code: %d error: '%s'",
status.get_error_code(), status.get_error_message() ? status.get_error_message() : "");
result.set_error_return(&status);
return result.array;
}
result.set_no_error_retrun();
if (is_client_logic) {
place_int_in_target_array(env, 1, 1, result.array);
} else {
place_int_in_target_array(env, 0, 1, result.array);
}
if (proccessed_data != NULL) {
place_ustring_in_array(env, proccessed_data, 2, result.array);
libpq_free(proccessed_data);
}
return result.array;
}
/*
* Run prepare statement
* @param env pointer to jvm
* @param
* @param handle pointer to ClientLogicJNI instance
* @param query_java
* @param statement_name
* @param parameter_count
* @return Object in the following format:
* [0][0][0] - error code - 0 for none
* [0][1] - error text - if none, empty string
* [1] - modified query
*/
JNIEXPORT jobjectArray JNICALL Java_org_postgresql_jdbc_ClientLogicImpl_prepareQueryImpl(JNIEnv *env,
jobject jdbc_cl_impl, jlong handle, jstring query_java, jstring statement_name_java, jint parameter_count)
{
JniResult result(env, 2);
if (!result.init()) {
return result.array;
}
if (env == NULL || statement_name_java == NULL || query_java == NULL) {
return result.array;
}
DriverError status(0, "");
ClientLogicJNI *client_logic = NULL;
if (!result.from_handle((long)handle, &client_logic, &status, "prepareQuery")) {
return result.array;
}
JNIStringConvertor original_query;
original_query.convert(env, query_java);
if (original_query.c_str == NULL) {
status.set_error(JNI_SYSTEM_ERROR_CODES::STRING_CREATION_FAILED);
result.set_error_return(&status);
JNI_LOG_ERROR("prepareQuery failed getting the query string error code:%d text:'%s'", status.get_error_code(),
status.get_error_message() ? status.get_error_message() : "");
return result.array;
}
JNIStringConvertor statement_name;
if (!result.convert_string(&statement_name, statement_name_java, &status, "prepareQuery")) {
return result.array;
}
client_logic->set_jni_env_and_cl_impl(env, jdbc_cl_impl);
if (!client_logic->preare_statement(original_query.c_str, statement_name.c_str, parameter_count, &status)) {
JNI_LOG_ERROR("preare_statement call failed: %ld, error code: %d error: '%s'", (long)handle,
status.get_error_code(), status.get_error_message() ? status.get_error_message() : "");
result.set_error_return(&status);
return result.array;
}
if (client_logic->get_statement_data() == NULL) {
status.set_error(STATEMENT_DATA_EMPTY);
JNI_LOG_ERROR("preare_statement get_statement_data call failed: %ld, error code: %d error: '%s'", (long)handle,
status.get_error_code(), status.get_error_message() ? status.get_error_message() : "");
result.set_error_return(&status);
return result.array;
}
result.set_no_error_retrun();
place_string_in_array(env, client_logic->get_statement_data()->params.adjusted_query, 1, result.array);
return result.array;
}
/*
* Replaces parameters in prepare statement values before sending to execution
* @param[in] env JVM environment
* @param[in]
* @param[in] handle pointer to ClientLogicJNI instance
* @param[in] statement_name_java statement name
* @param[in] parameters_java list of parameters in form of Java array of strings
* @param[in] parameter_count number of parameters
* @return Object in the following format:
* [0][0] - error code - 0 for none
* [0][1][0] - error text - if none, empty string
* [1][0 ... parameter_count - 1] - array with the parameters value, if the parameter is not being replace a NULL apears
* otherwise the replaced value
*/
JNIEXPORT jobjectArray JNICALL Java_org_postgresql_jdbc_ClientLogicImpl_replaceStatementParamsImpl(JNIEnv *env,
jobject jdbc_cl_impl, jlong handle, jstring statement_name_java, jobjectArray parameters_java)
{
JniResult result(env, 2);
if (!result.init()) {
return result.array;
}
if (env == NULL || statement_name_java == NULL || parameters_java == NULL) {
return result.array;
}
DriverError status(0, "");
JNIStringConvertor statement_name;
if (!result.convert_string(&statement_name, statement_name_java, &status,
"replaceStatementParams statement_name_java")) {
return result.array;
}
ClientLogicJNI *client_logic = NULL;
if (!result.from_handle((long)handle, &client_logic, &status, "replaceStatementParams")) {
return result.array;
}
int parameter_count = env->GetArrayLength(parameters_java);
bool convert_failure = false;
const char **param_values = NULL;
param_values = new (std::nothrow) const char *[(size_t)parameter_count];
if (param_values == NULL) {
status.set_error(JNI_SYSTEM_ERROR_CODES::UNEXPECTED_ERROR);
result.set_error_return(&status);
JNI_LOG_ERROR("out of memory");
return result.array;
}
JNIStringConvertor *string_convertors = NULL;
string_convertors = new (std::nothrow) JNIStringConvertor[(size_t)parameter_count];
if (string_convertors == NULL) {
delete[] param_values;
status.set_error(JNI_SYSTEM_ERROR_CODES::UNEXPECTED_ERROR);
result.set_error_return(&status);
JNI_LOG_ERROR("out of memory");
return result.array;
}
for (int i = 0; i < parameter_count && !convert_failure; ++i) {
jstring value = (jstring)env->GetObjectArrayElement(parameters_java, i);
string_convertors[i].convert(env, value);
if (string_convertors[i].c_str == NULL) {
status.set_error(JNI_SYSTEM_ERROR_CODES::STRING_CREATION_FAILED);
result.set_error_return(&status);
JNI_LOG_ERROR("replaceStatementParams failed getting the parameter at index %d", i);
convert_failure = true;
} else {
param_values[i] = string_convertors[i].c_str;
}
}
if (convert_failure) {
delete[] param_values;
delete[] string_convertors;
return result.array;
}
client_logic->set_jni_env_and_cl_impl(env, jdbc_cl_impl);
if (!client_logic->replace_statement_params(statement_name.c_str, param_values, parameter_count, &status)) {
JNI_LOG_ERROR("replace_statement_params failed: %ld, error code: %d error: '%s'", (long)handle,
status.get_error_code(), status.get_error_message() ? status.get_error_message() : "");
result.set_error_return(&status);
delete[] param_values;
delete[] string_convertors;
return result.array;
}
/* After parameters values replaces, place the new values on the target array */
jobjectArray parameters_array = env->NewObjectArray(parameter_count, result.object_class, NULL);
const StatementData *stmnt_data = client_logic->get_statement_data();
for (int i = 0; i < parameter_count && !convert_failure; ++i) {
if (strcmp(stmnt_data->params.adjusted_param_values[i], param_values[i]) != 0) {
place_string_in_array(env, stmnt_data->params.adjusted_param_values[i], i, parameters_array);
}
}
env->SetObjectArrayElement(result.array, 1, parameters_array);
delete[] param_values;
delete[] string_convertors;
client_logic->clean_stmnt();
result.set_no_error_retrun();
return result.array;
}
/*
* replace client logic values in error message coming from the server
* For example, when inserting a duplicate unique value,
* it will change the client logic value of \x... back to the user input
* @param env java environment
* @param
* @param handle client logic instance handle
* @param original_message_java the message received from the server and need to be converted
* @return Object in the following format:
* [0][0] - error code - 0 for none
* [0][1][0] - error text - if none, empty string
* [1] - converted message - if empty then the message has not changed
*/
JNIEXPORT jobjectArray JNICALL Java_org_postgresql_jdbc_ClientLogicImpl_replaceErrorMessageImpl(JNIEnv *env,
jobject jdbc_cl_impl, jlong handle, jstring original_message_java)
{
JniResult result(env, 2);
if (!result.init()) {
return result.array;
}
if (env == NULL || original_message_java == NULL) {
return result.array;
}
DriverError status(0, "");
// Find the client logic instance:
ClientLogicJNI *client_logic = NULL;
if (!result.from_handle((long)handle, &client_logic, &status, "replaceErrorMessage")) {
return result.array;
}
JNIStringConvertor original_message;
if (!result.convert_string(&original_message, original_message_java, &status, "replaceErrorMessage")) {
return result.array;
}
client_logic->set_jni_env_and_cl_impl(env, jdbc_cl_impl);
char *converted_message = NULL;
bool retval = client_logic->replace_message(original_message.c_str, &converted_message, &status);
if (!retval) {
// returning false due to an error
if (converted_message != NULL) {
free(converted_message);
converted_message = NULL;
}
if (status.get_error_code() != 0) {
JNI_LOG_ERROR("replaceErrorMessage failed: %ld, error code: %d error: '%s'", (long)handle,
status.get_error_code(), status.get_error_message() ? status.get_error_message() : "");
result.set_error_return(&status);
return result.array;
}
// returning false may be due to not finding anything to replace and then the string is empty
result.set_no_error_retrun();
place_string_in_array(env, "", 1, result.array);
return result.array;
}
result.set_no_error_retrun();
if (converted_message == NULL) {
/* Should not happen, but just in case */
place_string_in_array(env, "", 1, result.array);
} else {
place_string_in_array(env, converted_message, 1, result.array);
free(converted_message);
converted_message = NULL;
}
return result.array;
}
/*
* Class: org_postgresql_jdbc_ClientLogicImpl
* Method: destroy
* Signature: (J)V
*/
JNIEXPORT void JNICALL Java_org_postgresql_jdbc_ClientLogicImpl_destroy(JNIEnv *env, jobject, jlong handle)
{
JNI_LOG_DEBUG("About to destroy handle: %ld", (long)handle);
ClientLogicJNI *client_logic = NULL;
DriverError status(0, "");
if (!ClientLogicJNI::from_handle(handle, &client_logic, &status) || client_logic == NULL) {
JNI_LOG_DEBUG("Destroy failed: %ld, error code: %d error: '%s'", (long)handle, status.get_error_code(),
status.get_error_message() ? status.get_error_message() : "");
return;
} else {
delete client_logic;
client_logic = NULL;
JNI_LOG_DEBUG("Handle destroyed: %ld", (long)handle);
}
return;
}
| 10,292 |
6,036 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
namespace onnxruntime {
//
// Selection helpers
//
// Struct to serialize the node indexes in an ORT format model.
// Use EmptyNodeIndex for nullptr entries in the vectors for missing optional inputs
struct NodesToOptimizeIndexes {
std::vector<NodeIndex> nodes;
int num_inputs;
int num_outputs;
bool variadic_input;
bool variadic_output;
int num_variadic_inputs;
int num_variadic_outputs;
};
// Group of nodes that will be optimized. The group will either be merged into the target node, or a new node
// will be created to replace the entire group, including the target node.
//
// Accessors are provided for input/target/output nodes.
// A single variadic input OR output (not both - but no inferencing operator requires that) is currently supported.
//
// We don't support multiple nodes being connected to a single output of the target node, as the group of nodes
// will be removed post-optimization. As such, it's not possible to remove two nodes consuming a single output value
// as those nodes outputs would also need to be accounted for, and it's not possible to replace a single output
// from the target node with multiple outputs from downstream nodes.
class NodesToOptimize {
public:
enum class NodeType {
kInput, // node providing input to target node
kTarget, // target node
kOutput // node consuming output from target node
};
struct NodeLocation {
NodeType type; // is this a node providing input to the target, or consuming output from it
int index;
};
// nodes to assemble. num_inputs and num_outputs default to the size of input_nodes and output_nodes.
// specify num_input_defs/num_output_defs if the last input/output is variadic
NodesToOptimize(const std::vector<Node*>& input_nodes,
Node& target_node,
const std::vector<Node*>& output_nodes,
int num_input_defs = -1, int num_output_defs = -1);
// construct from saved NodeIndex values. IsValid() will return false if one or more nodes were missing.
// Use EmptyNodeIndex for nullptr entries in the vectors for missing optional inputs
NodesToOptimize(Graph& graph, const NodesToOptimizeIndexes& node_indexes);
static constexpr NodeIndex EmptyNodeIndex = std::numeric_limits<NodeIndex>::max();
NodesToOptimizeIndexes ToIndexes() const;
// number of inputs and outputs that the target node has, as defined by the operator schema.
// for each input/output, the node connected to that is stored
// optional non-variadic inputs/outputs that are missing will have a nullptr entry for the node.
//
// if the target node has a variadic input/output, the nodes providing those will always begin at the last entry
// in the input/output nodes (i.e. at num_inputs - 1 or num_outputs - 1).
//
// e.g if there are 3 inputs (same applies to outputs)
// if there is a variadic input:
// if zero variadic values: num_inputs=3, last input is nullptr
// if one variadic value: num_inputs=3, last input is the single variadic input
// if multiple variadic values: num_inputs=3, total inputs = num_inputs + (NumVariadicInputs() - 1)
const int num_inputs;
const int num_outputs;
bool HasVariadicInput() const { return variadic_input_; }
bool HasVariadicOutput() const { return variadic_output_; }
int NumVariadicInputs() const { return num_variadic_inputs_; }
int NumVariadicOutputs() const { return num_variadic_outputs_; }
bool IsValid() const { return !nodes_.empty(); }
// fetch an input.
// valid indexes are 0 to num_inputs - 1 if no variadic inputs.
// if there are variadic inputs, valid indexes are 0 to num_inputs + num_extra_variadic_inputs - 1
// e.g. 3 inputs. last is variadic with 3 values. num_inputs=3 num_extra_variadic_inputs=2 for a total of 5 inputs.
Node* Input(int idx, bool required = true) const {
return GetNode(idx, required);
}
// inputs filtered by index. includes all variadic.
std::vector<Node*> Inputs(const std::vector<int>& indexes, bool required = true) const;
Node& Target() const {
return *GetNode(NumInputEntries() + 0, /*required*/ true);
}
Node* Output(int idx, bool required = true) const {
return GetNode(NumInputEntries() + 1 + idx, required);
}
// outputs filtered by index. includes all variadic.
std::vector<Node*> Outputs(const std::vector<int>& indexes, bool required = true) const;
// Get the Node or Nodes (if variadic) at a specific index.
std::vector<Node*> GetNodesAtLocation(const NodeLocation& location, bool required = true) const;
const std::vector<Node*>& AllNodes() const { return nodes_; }
ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(NodesToOptimize);
private:
Node* GetNode(int index, bool required) const {
Node* node = nullptr;
ORT_ENFORCE(static_cast<size_t>(index) < nodes_.size() &&
((node = nodes_[index]) != nullptr || !required));
return node;
}
// if the last input in num_inputs is for the variadic input, the variadic input could have zero or more values
// so we need to special case the zero and count that as one. same for outputs
int NumInputEntries() const { return variadic_input_ ? num_inputs + std::max(1, num_variadic_inputs_) - 1
: num_inputs; }
int NumOutputEntries() const { return variadic_output_ ? num_outputs + std::max(1, num_variadic_outputs_) - 1
: num_outputs; }
bool variadic_input_{false}; // is last input variadic
bool variadic_output_{false};
int num_variadic_inputs_{0}; // how many values does the variadic input have. can be zero or more.
int num_variadic_outputs_{0};
std::vector<Node*> nodes_;
};
// Helper to build a NodesToOptimize instance
// Use in selector to incrementally add pieces
struct NodesToOptimizeBuilder {
std::vector<Node*> input_nodes;
Node* target_node{nullptr};
std::vector<Node*> output_nodes;
int num_input_defs{-1};
int num_output_defs{-1};
std::unique_ptr<NodesToOptimize> Build() {
ORT_ENFORCE(target_node != nullptr, "A target node must be set.");
return std::make_unique<NodesToOptimize>(input_nodes, *target_node, output_nodes, num_input_defs, num_output_defs);
}
};
//
// Action helpers
//
enum class ArgType { kInput,
kOutput };
// struct to define the location of an input or output definition for a Node
struct InOutDefSlot {
ArgType in_out;
int idx; // idx of -1 means 'all' if a source, or 'end' if appending to a target
};
// Helper to define moving a value from one node to another
struct ValueMoveInfo {
// simple 1:1 copy
ValueMoveInfo(InOutDefSlot src_slot_in, InOutDefSlot dest_slot_in)
: src_slot(src_slot_in), dest_slot(dest_slot_in) {}
// copy all from source to destination
ValueMoveInfo(ArgType src_slot_type, ArgType dest_slot_type, bool is_optional = false)
: src_slot{src_slot_type, -1},
dest_slot{dest_slot_type, -1},
copy_all{true},
append{true},
optional{is_optional} {
}
// append single value (may be variadic) from source to destination
ValueMoveInfo(InOutDefSlot src_slot_in, ArgType dest_slot_type, bool is_optional = false)
: src_slot(src_slot_in),
dest_slot{dest_slot_type, -1},
copy_all{false},
append{true},
optional{is_optional} {}
InOutDefSlot src_slot;
InOutDefSlot dest_slot;
bool copy_all{false}; // ignore src_slot.idx and copy all values
bool append{false}; // ignore dest_slot.idx and append to existing values
bool optional{false}; // optional copy that can be skipped if source node is missing
private:
ValueMoveInfo() = default;
};
// info to move a value between a source node in the selected_nodes and the target/replacement node.
struct NodeAndMoveInfo {
NodesToOptimize::NodeLocation src_node;
ValueMoveInfo value_move_info;
};
// helpers for moving inputs/outputs and their edges between nodes
Status MoveInputOutput(Graph& graph, const NodesToOptimize& selected_nodes, Node& dest,
const std::vector<NodeAndMoveInfo>& moves);
Status MoveInputOutput(Graph& graph, Node& src, Node& dest, const ValueMoveInfo& move_info);
//
// Helpers to make the 'move' configuration more easily read
//
// move specific input/output to slot on target/replacement node
inline NodeAndMoveInfo MoveToSlot(const NodesToOptimize::NodeLocation& src_node,
ArgType src_direction, int src_slot,
ArgType dest_direction, int dest_slot) {
return NodeAndMoveInfo{src_node,
ValueMoveInfo{
InOutDefSlot{src_direction, src_slot}, // move from this slot
InOutDefSlot{dest_direction, dest_slot}}}; // to this one
}
// move specific input/output and append to target/replacement node
inline NodeAndMoveInfo MoveAndAppend(const NodesToOptimize::NodeLocation& src_node,
ArgType src_direction, int src_slot,
ArgType dest_direction,
bool optional = false) {
return NodeAndMoveInfo{src_node, ValueMoveInfo{
InOutDefSlot{src_direction, src_slot}, // move from this slot
dest_direction, optional}}; // append here
}
// move all inputs/outputs from the source node to the target/replacement node
inline NodeAndMoveInfo MoveAll(const NodesToOptimize::NodeLocation& src_node,
ArgType arg_type, // moving inputs or outputs
bool optional = false) {
return NodeAndMoveInfo{src_node, ValueMoveInfo{arg_type, arg_type, optional}};
}
} // namespace onnxruntime
| 3,553 |
6,457 |
<reponame>chadbramwell/librealsense
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2020 Intel Corporation. All Rights Reserved.
#pragma once
#include "RsDevice.hh"
#include <liveMedia.hh>
#ifndef _ON_DEMAND_SERVER_MEDIA_SUBSESSION_HH
#include "OnDemandServerMediaSubsession.hh"
#endif
#include "RsSource.hh"
class RsServerMediaSubsession : public OnDemandServerMediaSubsession
{
public:
static RsServerMediaSubsession* createNew(UsageEnvironment& t_env, rs2::video_stream_profile& t_videoStreamProfile, std::shared_ptr<RsDevice> rsDevice);
rs2::frame_queue& getFrameQueue();
rs2::video_stream_profile getStreamProfile();
protected:
RsServerMediaSubsession(UsageEnvironment& t_env, rs2::video_stream_profile& t_video_stream_profile, std::shared_ptr<RsDevice> device);
virtual ~RsServerMediaSubsession();
virtual FramedSource* createNewStreamSource(unsigned t_clientSessionId, unsigned& t_estBitrate);
virtual RTPSink* createNewRTPSink(Groupsock* t_rtpGroupsock, unsigned char t_rtpPayloadTypeIfDynamic, FramedSource* t_inputSource);
private:
rs2::video_stream_profile m_videoStreamProfile;
rs2::frame_queue m_frameQueue;
std::shared_ptr<RsDevice> m_rsDevice;
};
| 417 |
4,124 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jstorm.example.unittests.utils;
import java.util.Map;
/**
* @author binyang.dby on 2016/7/8.
*
* This interface is used for check if a unit test should pass after running. The abstract classes which
* implements this interface (like JStormUnitTestMetricValidator etc.) is recommended.
*/
public interface JStormUnitTestValidator
{
/**
* Validate is pass a unit test or not. Use assert in the body of this method since the return
* value of it doesn't determine the test result of the unit test, it is just passed to the
* return value of JStormUnitTestRunner.submitTopology()
*
* @param config the config which is passed in JStormUnitTestRunner.submitTopology()
* @return the return value will be pass to the return value of JStormUnitTestRunner.submitTopology()
*/
public boolean validate(Map config);
}
| 447 |
1,056 |
<reponame>timfel/netbeans
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.java.editor.fold;
import com.sun.source.tree.AssignmentTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreePath;
import org.netbeans.api.java.source.support.ErrorAwareTreePathScanner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.prefs.Preferences;
import java.util.regex.Pattern;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.editor.fold.FoldUtilities;
import org.netbeans.api.editor.mimelookup.MimeRegistration;
import org.netbeans.api.editor.mimelookup.MimeRegistrations;
import org.netbeans.api.java.classpath.ClassPath;
import org.netbeans.api.java.source.CompilationController;
import org.netbeans.api.java.source.CompilationInfo;
import org.netbeans.api.java.source.JavaParserResultTask;
import org.netbeans.api.java.source.JavaSource;
import org.netbeans.modules.parsing.spi.Parser;
import org.netbeans.modules.parsing.spi.ParserResultTask;
import org.netbeans.modules.parsing.spi.Scheduler;
import org.netbeans.modules.parsing.spi.SchedulerEvent;
import org.netbeans.modules.parsing.spi.TaskFactory;
import org.netbeans.modules.parsing.spi.TaskIndexingMode;
import org.netbeans.spi.editor.fold.FoldInfo;
import org.netbeans.spi.editor.fold.FoldManagerFactory;
import org.openide.filesystems.FileObject;
/**
*
* @author sdedic
*/
@MimeRegistrations({
@MimeRegistration(mimeType = "text/x-java", service = TaskFactory.class),
@MimeRegistration(mimeType = "text/x-java", service = FoldManagerFactory.class, position = 1400),
})
public class ResourceStringFoldProvider extends ParsingFoldSupport{
private List<MessagePattern> messages = new ArrayList<>();
public ResourceStringFoldProvider() {
messages.add(
new MessagePattern(
Pattern.compile("^" + Pattern.quote("java.util.ResourceBundle") + "$"),
Pattern.compile("^getString$"), MessagePattern.BUNDLE_FROM_INSTANCE, 0));
messages.add(
new MessagePattern(
Pattern.compile("^" + Pattern.quote("org.openide.util.NbBundle") + "$"),
Pattern.compile("^getMessage$"), 0, 1));
messages.add(
new MessagePattern(
Pattern.compile("^" + Pattern.quote("java.util.ResourceBundle") + "$"),
Pattern.compile("^getBundle$"), 0, MessagePattern.GET_BUNDLE_CALL));
messages.add(
new MessagePattern(
Pattern.compile("^" + Pattern.quote("org.openide.util.NbBundle") + "$"),
Pattern.compile("^getBundle$"), 0, MessagePattern.GET_BUNDLE_CALL));
messages.add(
new MessagePattern(
Pattern.compile("\\.[^.]+(Bundle|Messages)$"),
Pattern.compile("^(getMessage|getString)"), MessagePattern.BUNDLE_FROM_CLASS, 0));
// total wildcards
messages.add(
new MessagePattern(
Pattern.compile("\\.Bundle$"),
Pattern.compile(".*"), MessagePattern.BUNDLE_FROM_CLASS, MessagePattern.KEY_FROM_METHODNAME));
}
@Override
protected FoldProcessor createTask(FileObject f) {
return new Proc(f);
}
private final class Proc extends FoldProcessor implements ChangeListener {
ResourceStringLoader loader;
public Proc(FileObject f) {
super(f, "text/x-java");
}
@Override
protected boolean processResult(Parser.Result result) {
CompilationInfo info = CompilationInfo.get(result);
if (info == null) {
return false;
}
CompilationController ctrl = CompilationController.get(result);
if (ctrl != null) {
try {
ctrl.toPhase(JavaSource.Phase.RESOLVED);
} catch (IOException ex) {
return false;
}
}
if (loader == null) {
loader = new ResourceStringLoader(this);
}
V v = new V(info, getFile(), this);
v.setDescriptions(messages);
v.scan(info.getCompilationUnit(), null);
return true;
}
@Override
public void stateChanged(ChangeEvent e) {
performRefresh();
}
}
@Override
protected ParserResultTask createParserTask(FileObject file, FoldProcessor processor) {
final ParserResultTask wrapped = super.createParserTask(file, processor);
return new JavaParserResultTask(JavaSource.Phase.RESOLVED, TaskIndexingMode.ALLOWED_DURING_SCAN) {
@Override
public void run(Parser.Result result, SchedulerEvent event) {
wrapped.run(result, event);
}
@Override
public int getPriority() {
return wrapped.getPriority();
}
@Override
public Class<? extends Scheduler> getSchedulerClass() {
return wrapped.getSchedulerClass();
}
@Override
public void cancel() {
wrapped.cancel();
}
};
}
private static class V extends ErrorAwareTreePathScanner<Void, Void> {
private final FileObject anchor;
private final Proc proc;
private final CompilationInfo info;
private MessagePattern messageMethod;
private Map<Element, String> variableBundles = new HashMap<>();
private TypeMirror resourceBundleType;
private String exprBundleName;
private TreePath methodOwnerPath;
private String methodName;
/**
* Recognized method calls will be inspected for possible resource bundle folding
*/
private List<MessagePattern> descriptions = new ArrayList<>();
public V(CompilationInfo info, FileObject anchor, Proc proc) {
this.proc = proc;
this.info = info;
this.anchor = anchor;
Element el = info.getElements().getTypeElement("java.util.ResourceBundle"); // NO18N
if (el != null) {
resourceBundleType = el.asType();
}
}
public void setDescriptions(List<MessagePattern> descs) {
this.descriptions = descs;
}
private boolean isCancelled() {
return proc.isCancelled();
}
private void defineFold(String bundle, String key, Tree expr) {
final ClassPath cp = ClassPath.getClassPath(anchor, ClassPath.SOURCE);
FileObject bundleFile = cp != null ? cp.findResource(bundle + ".properties") : null;
SourcePositions spos = info.getTrees().getSourcePositions();
int start = (int)spos.getStartPosition(info.getCompilationUnit(), expr);
int end = (int)spos.getEndPosition(info.getCompilationUnit(), expr);
if (start == -1 || end == -1) {
return;
}
if (bundleFile == null) {
return;
}
String message = proc.loader.getMessage(bundleFile, key);
if (message == null) {
return;
}
int newline = message.indexOf('\n');
if (newline >= 0) {
message = message.substring(0, newline);
}
message = message.replaceAll("\\.\\.\\.", "\u2026");
FoldInfo info = FoldInfo.range(start, end, JavaFoldTypeProvider.BUNDLE_STRING).
withDescription(message).
attach(new ResourceStringFoldInfo(bundle, key));
proc.addFold(info, -1);
}
@Override
public Void scan(Tree tree, Void p) {
if (isCancelled()) {
return null;
}
super.scan(tree, p);
return p;
}
@Override
public Void visitMemberSelect(MemberSelectTree node, Void p) {
Void d = super.visitMemberSelect(node, p);
Element el = info.getTrees().getElement(getCurrentPath());
messageMethod = null;
if (el == null || el.getKind() != ElementKind.METHOD) {
return d;
}
ExecutableElement ee = (ExecutableElement)el;
String sn = ee.getSimpleName().toString();
for (MessagePattern desc : descriptions) {
if (!desc.getMethodNamePattern().matcher(sn).matches()) {
continue;
}
// check the defining type
el = ee.getEnclosingElement();
if (el == null || !(el.getKind().isClass() || el.getKind().isInterface())) {
continue;
}
TypeElement tel = (TypeElement)el;
if (!desc.getOwnerTypePattern().matcher(tel.getQualifiedName().toString()).matches()) {
continue;
}
messageMethod = desc;
methodName = sn;
methodOwnerPath = new TreePath(getCurrentPath(), node.getExpression());
break;
}
return d;
}
@Override
public Void visitVariable(VariableTree node, Void p) {
scan(node.getInitializer(), null);
if (exprBundleName == null) {
return null;
}
TypeMirror tm = info.getTrees().getTypeMirror(getCurrentPath());
if (resourceBundleType == null || !info.getTypes().isAssignable(tm, resourceBundleType)) {
return null;
}
Element dest = info.getTrees().getElement(getCurrentPath());
if (dest != null && (dest.getKind() == ElementKind.LOCAL_VARIABLE || dest.getKind() == ElementKind.FIELD)) {
variableBundles.put(dest, exprBundleName);
}
return null;
}
@Override
public Void visitAssignment(AssignmentTree node, Void p) {
exprBundleName = null;
Void d = super.visitAssignment(node, p);
if (exprBundleName != null) {
Element dest = info.getTrees().getElement(getCurrentPath());
if (dest != null && (dest.getKind() == ElementKind.LOCAL_VARIABLE || dest.getKind() == ElementKind.FIELD)) {
variableBundles.put(dest, exprBundleName);
}
}
return d;
}
private void processGetBundleCall(MethodInvocationTree node) {
TypeMirror tm = info.getTrees().getTypeMirror(getCurrentPath());
if (resourceBundleType == null ||tm == null || tm.getKind() != TypeKind.DECLARED) {
return;
}
if (!info.getTypes().isAssignable(tm, resourceBundleType)) {
return;
}
// OK, get the parameter said to describe the bundle name
exprBundleName = getBundleName(node, messageMethod.getBundleParam(), messageMethod.getBundleFile());
}
private String getBundleName(MethodInvocationTree n, int index, String bfn) {
if (n.getArguments().size() <= index) {
return null;
}
ExpressionTree t = n.getArguments().get(index);
// recognize just string literals + .class references
if (t.getKind() == Tree.Kind.STRING_LITERAL) {
Object o = ((LiteralTree)t).getValue();
return o == null ? null : o.toString();
} else if (t.getKind() == Tree.Kind.MEMBER_SELECT) {
MemberSelectTree mst = (MemberSelectTree)t;
if (!mst.getIdentifier().contentEquals("class")) {
return null;
}
return bundleFileFromClass(new TreePath(getCurrentPath(), mst.getExpression()), bfn);
}
return null;
}
private String bundleFileFromClass(TreePath classTreePath, String bfn) {
TypeMirror tm = info.getTrees().getTypeMirror(classTreePath);
if (tm.getKind() != TypeKind.DECLARED) {
return null;
}
Element clazz = ((DeclaredType)tm).asElement();
while ((clazz instanceof TypeElement)) {
clazz = ((TypeElement)clazz).getEnclosingElement();
}
if (clazz.getKind() == ElementKind.PACKAGE) {
PackageElement pack = ((PackageElement)clazz);
if (pack.isUnnamed()) {
return null;
}
return pack.getQualifiedName().toString().replaceAll("\\.", "/") + "/" + bfn;
}
return null;
}
@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void p) {
messageMethod = null;
exprBundleName = null;
Void d = scan(node.getMethodSelect(), p);
try {
if (messageMethod == null) {
return d;
}
String bundleFile = null;
if (messageMethod.getKeyParam() == MessagePattern.GET_BUNDLE_CALL) {
processGetBundleCall(node);
} else {
int bp = messageMethod.getBundleParam();
if (bp == MessagePattern.BUNDLE_FROM_CLASS) {
TypeMirror tm = info.getTrees().getTypeMirror(methodOwnerPath);
if (tm != null && tm.getKind() == TypeKind.DECLARED) {
bundleFile = bundleFileFromClass(methodOwnerPath, messageMethod.getBundleFile());
}
} else if (bp == MessagePattern.BUNDLE_FROM_INSTANCE) {
// simplification: assume the selector expression is a variable
Element el = info.getTrees().getElement(methodOwnerPath);
if (el != null && (el.getKind() == ElementKind.LOCAL_VARIABLE || el.getKind() == ElementKind.FIELD)) {
bundleFile = variableBundles.get(el);
} else {
bundleFile = exprBundleName;
}
} else if (bp >= 0 && bp < node.getArguments().size()) {
bundleFile = getBundleName(node, bp, messageMethod.getBundleFile());
}
}
if (bundleFile == null) {
return d;
}
int keyIndex = messageMethod.getKeyParam();
if (node.getArguments().size() <= keyIndex) {
return d;
}
String keyVal;
if (keyIndex == MessagePattern.KEY_FROM_METHODNAME) {
keyVal = this.methodName;
} else {
ExpressionTree keyArg = node.getArguments().get(keyIndex);
if (keyArg.getKind() != Tree.Kind.STRING_LITERAL) {
return d;
}
Object o = ((LiteralTree)keyArg).getValue();
if (o == null) {
return d;
}
keyVal = o.toString();
}
defineFold(bundleFile, keyVal, node);
} finally {
String expr = exprBundleName;
scan(node.getArguments(), p);
this.exprBundleName = expr;
}
// simplification, accept only String literals
return d;
}
}
}
| 8,540 |
1,262 |
/*
*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.metacat.common.type;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
/**
* Type util class.
*
* @author zhenl
*/
public final class TypeUtils {
private TypeUtils() {
}
/**
* parameterizedTypeName.
*
* @param baseType baseType
* @param argumentNames args
* @return type signature
*/
public static TypeSignature parameterizedTypeSignature(
final TypeEnum baseType,
final TypeSignature... argumentNames
) {
return new TypeSignature(baseType, ImmutableList.copyOf(argumentNames), ImmutableList.of());
}
/**
* Check if the collection is null or empty.
*
* @param collection collection
* @return boolean
*/
public static boolean isNullOrEmpty(final Collection<?> collection) {
return collection == null || collection.isEmpty();
}
/**
* CheckType.
*
* @param value value
* @param target type
* @param name name
* @param <A> A
* @param <B> B
* @return B
*/
public static <A, B extends A> B checkType(final A value, final Class<B> target, final String name) {
Preconditions.checkNotNull(value, "%s is null", name);
Preconditions.checkArgument(target.isInstance(value),
"%s must be of type %s, not %s",
name,
target.getName(),
value.getClass().getName());
return target.cast(value);
}
}
| 815 |
363 |
<filename>src/com/wenshuo/agent/transformer/AgentLogClassFileTransformer.java<gh_stars>100-1000
package com.wenshuo.agent.transformer;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.Collections;
import java.util.Set;
import java.util.regex.Pattern;
import com.wenshuo.agent.javassist.CannotCompileException;
import com.wenshuo.agent.javassist.ClassPool;
import com.wenshuo.agent.javassist.CtClass;
import com.wenshuo.agent.javassist.CtMethod;
import com.wenshuo.agent.javassist.LoaderClassPath;
import com.wenshuo.agent.javassist.Modifier;
import com.wenshuo.agent.javassist.NotFoundException;
import com.wenshuo.agent.ConfigUtils;
import com.wenshuo.agent.PojoDetector;
/**
* AgentLogClassFileTransformer 类增强,增加agent日志
*
* @author dingjsh
* @time 2015-7-24上午09:53:44
*/
public class AgentLogClassFileTransformer implements ClassFileTransformer {
private static final String LOG_UTILS = "com.wenshuo.agent.log.ExecuteLogUtils";
private static final String AGENT_PACKAGE_NAME = "com.wenshuo.agent";
/*
* (non-Javadoc)
*
* @see
* java.lang.instrument.ClassFileTransformer#transform(java.lang.ClassLoader
* , java.lang.String, java.lang.Class, java.security.ProtectionDomain,
* byte[])
*/
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
ProtectionDomain protectionDomain, byte[] classfileBuffer) {
byte[] byteCode = classfileBuffer;
className = className.replace('/', '.');
if (!isNeedLogExecuteInfo(className)) {
return byteCode;
}
if (null == loader) {
loader = Thread.currentThread().getContextClassLoader();
}
byteCode = aopLog(loader, className, byteCode);
return byteCode;
}
private byte[] aopLog(ClassLoader loader, String className, byte[] byteCode) {
try {
ClassPool cp = ClassPool.getDefault();
CtClass cc;
try {
cc = cp.get(className);
} catch (NotFoundException e) {
cp.insertClassPath(new LoaderClassPath(loader));
cc = cp.get(className);
}
byteCode = aopLog(cc, className, byteCode);
} catch (Exception ex) {
System.err.println(ex);
}
return byteCode;
}
private byte[] aopLog(CtClass cc, String className, byte[] byteCode) throws CannotCompileException, IOException {
if (null == cc) {
return byteCode;
}
if (!cc.isInterface()) {
CtMethod[] methods = cc.getDeclaredMethods();
if (null != methods && methods.length > 0) {
boolean isOpenPojoMonitor = ConfigUtils.isOpenPojoMonitor();
Set<String> getSetMethods = Collections.emptySet();
if (!isOpenPojoMonitor) {
getSetMethods = PojoDetector.getPojoMethodNames(methods);
}
for (CtMethod m : methods) {
if (isOpenPojoMonitor || !getSetMethods.contains(m.getName())) {
aopLog(className, m);
}
}
byteCode = cc.toBytecode();
}
}
cc.detach();
return byteCode;
}
private void aopLog(String className, CtMethod m) throws CannotCompileException {
if (null == m || m.isEmpty()) {
return;
}
boolean isMethodStatic = Modifier.isStatic(m.getModifiers());
String aopClassName = isMethodStatic ? "\"" + className + "\"" : "this.getClass().getName()";
final String timeMethodStr
= ConfigUtils.isUsingNanoTime() ? "java.lang.System.nanoTime()" : "java.lang.System.currentTimeMillis()";
// 避免变量名重复
m.addLocalVariable("dingjsh_javaagent_elapsedTime", CtClass.longType);
m.insertBefore("dingjsh_javaagent_elapsedTime = " + timeMethodStr + ";");
m.insertAfter("dingjsh_javaagent_elapsedTime = " + timeMethodStr + " - dingjsh_javaagent_elapsedTime;");
m.insertAfter(LOG_UTILS + ".log(" + aopClassName + ",\"" + m.getName()
+ "\",(long)dingjsh_javaagent_elapsedTime" + ");");
}
/**
* 是否需要记录执行信息
*
* @param className 类名
* @return 是否需要记录执行信息
* @author dingjsh
* @time 2015-7-27下午06:11:02
*/
private boolean isNeedLogExecuteInfo(String className) {
// do not transform the agent class,prevent deadlock
if (className.startsWith(AGENT_PACKAGE_NAME)) {
return false;
}
Set<String> includes = ConfigUtils.getIncludePackages();
if (null == includes || includes.isEmpty()) {
return false;
}
boolean isNeeded = false;
// include package
for (String packageName : includes) {
if (className.startsWith(packageName)) {
isNeeded = true;
break;
}
}
// exclude package
if (isNeeded) {
Set<String> excludes = ConfigUtils.getExcludePackages();
if (null != excludes && !excludes.isEmpty()) {
for (String packageName : excludes) {
if (className.startsWith(packageName)) {
isNeeded = false;
break;
}
}
}
}
if (isNeeded) {
Set<String> excludeClassRegexs = ConfigUtils.getExcludeClassRegexs();
if (null != excludeClassRegexs && !excludeClassRegexs.isEmpty()) {
for (String regex : excludeClassRegexs) {
isNeeded = !Pattern.matches(regex, className);
if (!isNeeded) {
break;
}
}
}
}
return isNeeded;
}
}
| 2,883 |
739 |
<gh_stars>100-1000
{
"name": "<NAME>",
"img": "https://github.com/Dhrunit.png",
"email":"",
"links": {
"website": "http://dhrunitportfolio.surge.sh/",
"linkedin": "https://www.linkedin.com/in/dhrunitprajapati/",
"github": "https://github.com/Dhrunit/"
},
"jobTitle": "Student",
"location": {
"city": "Ahmedabad",
"state": "Gujarat",
"country": "India"
}
}
| 206 |
852 |
from builtins import range
__author__="Aurelija"
__date__ ="$Jul 12, 2010 10:08:20 AM$"
import re
#fileList is list of files paths or could be a tuple of (path, [fileLines])
def finds(fileList, regularExpression, exceptRegEx = []):
info = []
lines = []
for i in range(len(fileList)):
if type(fileList[0]).__name__ != 'tuple':
file = fileList[i]
lines = find(fileList[i], regularExpression, exceptRegEx)
else:
file = fileList[i][0]
lines = find(fileList[i][1], regularExpression, exceptRegEx)
if lines:
info.append((file, lines))
return info
#file is the file path or the list of file lines
#exceptRegEx is the list of regular expressions that says to skip line if one of these regEx matches
def find(file, regularExpression, exceptRegEx = []):
lines = []
if type(file).__name__ != 'list':
fileLines = open(file).readlines()
else: fileLines = file
for i in range(len(fileLines)):
matchException = False
if re.search(regularExpression, fileLines[i]) != None:
for regEx in exceptRegEx:
if re.search(regEx, fileLines[i]) != None:
matchException = True
break
if not matchException:
lines.append(i+1)
return lines
| 611 |
1,558 |
<reponame>Microsoft/WindowsTemplateStudio
{
"author": "Microsoft",
"name": "Settings",
"description": "La page des paramètres est la page où nous vous recommandons de saisir les paramètres de configuration de votre application.",
"identity": "ts.WPF.Page.Settings"
}
| 91 |
793 |
// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify -fopenmp -ferror-limit 100 -o - %s
// RUN: %clang_cc1 -triple x86_64-apple-macos10.7.0 -verify -fopenmp-simd -ferror-limit 100 -o - %s
int main(int argc, char **argv) {
int i;
#pragma omp nowait target enter data map(to: i) // expected-error {{expected an OpenMP directive}}
#pragma omp target nowait enter data map(to: i) // expected-warning {{extra tokens at the end of '#pragma omp target' are ignored}}
#pragma omp target enter nowait data map(to: i) // expected-error {{expected an OpenMP directive}}
#pragma omp target enter data nowait() map(to: i) // expected-warning {{extra tokens at the end of '#pragma omp target enter data' are ignored}} expected-error {{expected at least one 'map' clause for '#pragma omp target enter data'}}
#pragma omp target enter data map(to: i) nowait( // expected-warning {{extra tokens at the end of '#pragma omp target enter data' are ignored}}
#pragma omp target enter data map(to: i) nowait (argc)) // expected-warning {{extra tokens at the end of '#pragma omp target enter data' are ignored}}
#pragma omp target enter data map(to: i) nowait device (-10u)
#pragma omp target enter data map(to: i) nowait (3.14) device (-10u) // expected-warning {{extra tokens at the end of '#pragma omp target enter data' are ignored}}
#pragma omp target enter data map(to: i) nowait nowait // expected-error {{directive '#pragma omp target enter data' cannot contain more than one 'nowait' clause}}
#pragma omp target enter data nowait map(to: i) nowait // expected-error {{directive '#pragma omp target enter data' cannot contain more than one 'nowait' clause}}
return 0;
}
| 564 |
535 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef __LPS33HW_PRIV_H__
#define __LPS33HW_PRIV_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Max time to wait for interrupt */
#define LPS33HW_MAX_INT_WAIT (4 * OS_TICKS_PER_SEC)
enum lps33hw_registers {
LPS33HW_INTERRUPT_CFG = 0x0b,
LPS33HW_THS_P = 0x0c,
LPS33HW_IF_CTRL = 0x0e,
LPS33HW_WHO_AM_I = 0x0f,
LPS33HW_CTRL_REG1 = 0x10,
LPS33HW_CTRL_REG2 = 0x11,
LPS33HW_CTRL_REG3 = 0x12,
LPS33HW_FIFO_CTRL = 0x14,
LPS33HW_REF_P = 0x15,
LPS33HW_RPDS = 0x18,
LPS33HW_RES_CONF = 0x1a,
LPS33HW_INT_SOURCE = 0x25,
LPS33HW_FIFO_STATUS = 0x26,
LPS33HW_STATUS = 0x27,
LPS33HW_PRESS_OUT = 0x28,
LPS33HW_TEMP_OUT = 0x2b,
LPS33HW_LPFP_RES = 0x33
};
enum lps33hw_fifo_mode {
LPS33HW_FIFO_BYPASS = 0x00,
LPS33HW_FIFO_CONTINUOUS = 0x02,
};
/* registers */
struct lps33hw_register_value {
uint8_t reg;
uint8_t pos;
uint8_t mask;
};
#define LPS33HW_INT_LOW_BIT (0x01)
#define LPS33HW_INT_HIGH_BIT (0x01)
#define LPS33HW_REGISTER_VALUE(r, n, p, m) \
static const struct lps33hw_register_value n = {.reg = r, .pos = p, .mask = m}
LPS33HW_REGISTER_VALUE(LPS33HW_INTERRUPT_CFG, LPS33HW_INTERRUPT_CFG_AUTORIFP, 7, 0x80);
LPS33HW_REGISTER_VALUE(LPS33HW_INTERRUPT_CFG, LPS33HW_INTERRUPT_CFG_RESET_ARP, 6, 0x40);
LPS33HW_REGISTER_VALUE(LPS33HW_INTERRUPT_CFG, LPS33HW_INTERRUPT_CFG_AUTOZERO, 5, 0x20);
LPS33HW_REGISTER_VALUE(LPS33HW_INTERRUPT_CFG, LPS33HW_INTERRUPT_CFG_RESET_AZ, 4, 0x10);
LPS33HW_REGISTER_VALUE(LPS33HW_INTERRUPT_CFG, LPS33HW_INTERRUPT_CFG_DIFF_EN, 3, 0x08);
LPS33HW_REGISTER_VALUE(LPS33HW_INTERRUPT_CFG, LPS33HW_INTERRUPT_CFG_LIR, 2, 0x04);
LPS33HW_REGISTER_VALUE(LPS33HW_INTERRUPT_CFG, LPS33HW_INTERRUPT_CFG_PLE, 1, 0x02);
LPS33HW_REGISTER_VALUE(LPS33HW_INTERRUPT_CFG, LPS33HW_INTERRUPT_CFG_PHE, 0, 0x01);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG1, LPS33HW_CTRL_REG1_ODR, 4, 0x70);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG1, LPS33HW_CTRL_REG1_EN_LPFP, 3, 0x08);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG1, LPS33HW_CTRL_REG1_LPFP_CFG, 2, 0x04);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG1, LPS33HW_CTRL_REG1_BDU, 1, 0x02);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG1, LPS33HW_CTRL_REG1_SIM, 0, 0x01);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG2, LPS33HW_CTRL_REG2_BOOT, 7, 0x80);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG2, LPS33HW_CTRL_REG2_FIFO_EN, 6, 0x40);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG2, LPS33HW_CTRL_REG2_STOP_ON_FTH, 5, 0x20);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG2, LPS33HW_CTRL_REG2_IF_ADD_INC, 4, 0x10);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG2, LPS33HW_CTRL_REG2_I2C_DIS, 3, 0x08);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG2, LPS33HW_CTRL_REG2_SWRESET, 2, 0x04);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG2, LPS33HW_CTRL_REG2_ONE_SHOT, 0, 0x01);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG3, LPS33HW_CTRL_REG3_INT_H_L, 7, 0x80);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG3, LPS33HW_CTRL_REG3_PP_OD, 6, 0x40);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG3, LPS33HW_CTRL_REG3_F_FSS5, 5, 0x20);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG3, LPS33HW_CTRL_REG3_F_FTH, 4, 0x10);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG3, LPS33HW_CTRL_REG3_F_OVR, 3, 0x08);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG3, LPS33HW_CTRL_REG3_DRDY, 2, 0x04);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG3, LPS33HW_CTRL_REG3_FIFO_WTM, 4, 0x10);
LPS33HW_REGISTER_VALUE(LPS33HW_CTRL_REG3, LPS33HW_CTRL_REG3_INT_S, 0, 0x03);
LPS33HW_REGISTER_VALUE(LPS33HW_FIFO_CTRL, LPS33HW_FIFO_CTRL_MODE, 5, 0xe0);
LPS33HW_REGISTER_VALUE(LPS33HW_FIFO_CTRL, LPS33HW_FIFO_WTM_THR, 0, 0x1f);
LPS33HW_REGISTER_VALUE(LPS33HW_FIFO_STATUS, LPS33HW_FIFO_FSS, 0, 0x3f);
LPS33HW_REGISTER_VALUE(LPS33HW_RES_CONF, LPS33HW_CTRL_RES_CONF_LC_EN, 0, 0x01);
LPS33HW_REGISTER_VALUE(LPS33HW_INT_SOURCE, LPS33HW_INT_SOURCE_BOOT_STATUS, 7, 0x80);
LPS33HW_REGISTER_VALUE(LPS33HW_INT_SOURCE, LPS33HW_INT_SOURCE_IA, 2, 0x04);
LPS33HW_REGISTER_VALUE(LPS33HW_INT_SOURCE, LPS33HW_INT_SOURCE_PL, 1, 0x02);
LPS33HW_REGISTER_VALUE(LPS33HW_INT_SOURCE, LPS33HW_INT_SOURCE_PH, 0, 0x01);
LPS33HW_REGISTER_VALUE(LPS33HW_STATUS, LPS33HW_STATUS_T_OR, 5, 0x20);
LPS33HW_REGISTER_VALUE(LPS33HW_STATUS, LPS33HW_STATUS_P_OR, 5, 0x10);
LPS33HW_REGISTER_VALUE(LPS33HW_STATUS, LPS33HW_STATUS_T_DA, 5, 0x02);
LPS33HW_REGISTER_VALUE(LPS33HW_STATUS, LPS33HW_STATUS_P_DA, 5, 0x01);
#define LPS33HW_WHO_AM_I_VAL (0xb1)
#ifdef __cplusplus
}
#endif
#endif /* __LPS33HW_PRIV_H__ */
| 2,743 |
834 |
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
* * This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include "fboss/agent/hw/sai/api/LoggingUtil.h"
#include "fboss/agent/hw/sai/store/SaiObject.h"
#include "fboss/agent/hw/sai/store/SaiObjectWithCounters.h"
#include <fmt/format.h>
#include <fmt/ranges.h>
namespace fmt {
template <typename SaiObjectTraits>
struct formatter<facebook::fboss::SaiObject<SaiObjectTraits>> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(
const facebook::fboss::SaiObject<SaiObjectTraits>& saiObject,
FormatContext& ctx) {
return format_to(
ctx.out(), "{}: {}", saiObject.adapterKey(), saiObject.attributes());
}
};
template <typename SaiObjectTraits>
struct formatter<facebook::fboss::SaiObjectWithCounters<SaiObjectTraits>> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(
const facebook::fboss::SaiObjectWithCounters<SaiObjectTraits>& saiObject,
FormatContext& ctx) {
return format_to(
ctx.out(), "{}: {}", saiObject.adapterKey(), saiObject.attributes());
}
};
} // namespace fmt
| 549 |
582 |
/*
Bulllord Game Engine
Copyright (C) 2010-2017 Trix
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../headers/network.h"
#include "../headers/util.h"
#include "../headers/system.h"
#include "internal/list.h"
#include "internal/array.h"
#include "internal/internal.h"
#include "../externals/fastlz/fastlz.h"
#ifdef EMSCRIPTEN
# include <emscripten/fetch.h>
#endif
#pragma pack(1)
typedef struct _NetMsg {
BLU32 nID;
BLVoid* pBuf;
BLU32 nLength;
BLEnum eNetType;
}_BLNetMsg;
typedef struct _HttpJob {
BLBool bOver;
BLSocket sSocket;
BLThread* pThread;
_BLNetMsg* pMsg;
}_BLHttpJob;
typedef struct _HttpSect {
BLAnsi* pHost;
BLAnsi* pPath;
BLAnsi* pRemoteName;
BLAnsi* pLocalName;
BLU16 nPort;
BLU32 nStart;
BLU32 nEnd;
BLU32 nState;
}_BLHttpSect;
#pragma pack()
typedef struct _NetworkMember {
BLAnsi aHostTCP[64];
BLU16 nPortTCP;
BLAnsi aHostUDP[64];
BLU16 nPortUDP;
BLAnsi aHostHTTP[64];
BLU16 nPortHTTP;
BLList* pCriList;
BLList* pNorList;
BLList* pRevList;
BLList* pHttpJobArray;
BLArray* pDownList;
BLArray* pLocalList;
BLU32 nFinish[64];
BLThread* pConnThread;
BLThread* pSendThread;
BLThread* pRecvThread;
BLThread* pDownMain;
BLU32 _PrCurDownHash;
volatile BLU32 nCurDownTotal;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
volatile LONG nCurDownSize;
#elif defined(BL_PLATFORM_OSX) || defined(BL_PLATFORM_IOS)
volatile atomic_int nCurDownSize;
#elif defined(BL_PLATFORM_LINUX)
volatile int32_t nCurDownSize;
#else
volatile int32_t nCurDownSize;
#endif
BLBool bClientIpv6;
BLBool bTcpServerIpv6;
BLBool bUdpServerIpv6;
BLBool bHttpServerIpv6;
BLBool bConnected;
BLSocket sTcpSocket;
BLSocket sUdpSocket;
}_BLNetworkMember;
static _BLNetworkMember* _PrNetworkMem = NULL;
static BLVoid
_FillAddr(const BLAnsi* _Host, BLU16 _Port, struct sockaddr_in* _Out, struct sockaddr_in6* _Out6, BLEnum _Type)
{
if (_Out6 && !_Out)
{
if (!_PrNetworkMem->bTcpServerIpv6 && _Type == BL_NT_TCP)
{
struct addrinfo _hints;
struct addrinfo* _res;
memset(&_hints, 0, sizeof(_hints));
_hints.ai_family = PF_UNSPEC;
_hints.ai_socktype = SOCK_STREAM;
#if defined(WIN32)
_hints.ai_flags = AI_NUMERICHOST;
#else
_hints.ai_flags = AI_ADDRCONFIG | AI_V4MAPPED;
#endif
BLS32 _rlt = getaddrinfo("ipv4only.arpa", NULL, &_hints, &_res);
if (_rlt == 0)
{
for (struct addrinfo* _temp = _res; _temp; _temp = _temp->ai_next)
{
if(_temp->ai_family == AF_INET6)
{
memcpy(_Out6, (struct sockaddr_in6*)_temp->ai_addr, sizeof(struct sockaddr_in6));
#if defined(WIN32)
unsigned long _ipv4;
inet_pton(AF_INET, _Host, (void*)&_ipv4);
memcpy(_Out6->sin6_addr.s6_addr + 12, &_ipv4, sizeof(unsigned long));
#else
in_addr_t _ipv4 = inet_addr(_Host);
memcpy(_Out6->sin6_addr.s6_addr + 12, &_ipv4, sizeof(in_addr_t));
#endif
_Out6->sin6_port = htons(_Port);
break;
}
}
}
freeaddrinfo(_res);
}
else if (_PrNetworkMem->bTcpServerIpv6 && _Type == BL_NT_TCP)
{
_Out6->sin6_family = PF_INET6;
inet_pton(PF_INET6, _Host, (BLVoid*)&_Out6->sin6_addr);
_Out6->sin6_port = htons(_Port);
}
else if (!_PrNetworkMem->bUdpServerIpv6 && _Type == BL_NT_UDP)
{
struct addrinfo _hints;
struct addrinfo* _res;
memset(&_hints, 0, sizeof(_hints));
_hints.ai_family = PF_UNSPEC;
_hints.ai_socktype = SOCK_DGRAM;
#if defined(WIN32)
_hints.ai_flags = AI_NUMERICHOST;
#else
_hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG;
#endif
BLS32 _rlt = getaddrinfo("ipv4only.arpa", NULL, &_hints, &_res);
if (_rlt == 0)
{
for (struct addrinfo* _temp = _res; _temp; _temp = _temp->ai_next)
{
if(_temp->ai_family == AF_INET6)
{
memcpy(_Out6, (struct sockaddr_in6*)_temp->ai_addr, sizeof(struct sockaddr_in6));
#if defined(WIN32)
unsigned long _ipv4;
inet_pton(AF_INET, _Host, (void*)&_ipv4);
#else
in_addr_t _ipv4 = inet_addr(_Host);
memcpy(_Out6->sin6_addr.s6_addr + 12, &_ipv4, sizeof(in_addr_t));
#endif
_Out6->sin6_port = htons(_Port);
break;
}
}
}
freeaddrinfo(_res);
}
else if (_PrNetworkMem->bUdpServerIpv6 && _Type == BL_NT_UDP)
{
_Out6->sin6_family = PF_INET6;
inet_pton(PF_INET6, _Host, (BLVoid*)&_Out6->sin6_addr);
_Out6->sin6_port = htons(_Port);
}
else if (!_PrNetworkMem->bHttpServerIpv6 && _Type == BL_NT_HTTP)
{
struct addrinfo _hints;
struct addrinfo* _res;
memset(&_hints, 0, sizeof(_hints));
_hints.ai_family = PF_UNSPEC;
_hints.ai_socktype = SOCK_STREAM;
#if defined(WIN32)
_hints.ai_flags = AI_NUMERICHOST;
#else
_hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG;
#endif
BLS32 _rlt = getaddrinfo("ipv4only.arpa", NULL, &_hints, &_res);
if (_rlt == 0)
{
for (struct addrinfo* _temp = _res; _temp; _temp = _temp->ai_next)
{
if(_temp->ai_family == AF_INET6)
{
memcpy(_Out6, (struct sockaddr_in6*)_temp->ai_addr, sizeof(struct sockaddr_in6));
#if defined(WIN32)
unsigned long _ipv4;
inet_pton(AF_INET, _Host, (void*)&_ipv4);
#else
in_addr_t _ipv4 = inet_addr(_Host);
memcpy(_Out6->sin6_addr.s6_addr + 12, &_ipv4, sizeof(in_addr_t));
#endif
_Out6->sin6_port = htons(_Port);
break;
}
}
}
freeaddrinfo(_res);
}
else if (_PrNetworkMem->bHttpServerIpv6 && _Type == BL_NT_HTTP)
{
_Out6->sin6_family = PF_INET6;
inet_pton(PF_INET6, _Host, (BLVoid*)&_Out6->sin6_addr);
_Out6->sin6_port = htons(_Port);
}
}
else if (!_Out6 && _Out)
{
if (!_PrNetworkMem->bTcpServerIpv6 && _Type == BL_NT_TCP)
{
inet_pton(PF_INET, _Host, (BLVoid*)&_Out->sin_addr);
_Out->sin_family = PF_INET;
_Out->sin_port = htons(_Port);
}
else if (_PrNetworkMem->bTcpServerIpv6 && _Type == BL_NT_TCP)
{
}
else if (!_PrNetworkMem->bUdpServerIpv6 && _Type == BL_NT_UDP)
{
inet_pton(PF_INET, _Host, (BLVoid*)&_Out->sin_addr);
_Out->sin_family = PF_INET;
_Out->sin_port = htons(_Port);
}
else if (_PrNetworkMem->bUdpServerIpv6 && _Type == BL_NT_UDP)
{
}
else if (!_PrNetworkMem->bHttpServerIpv6 && _Type == BL_NT_HTTP)
{
inet_pton(PF_INET, _Host, (BLVoid*)&_Out->sin_addr);
_Out->sin_family = PF_INET;
_Out->sin_port = htons(_Port);
}
else if (_PrNetworkMem->bHttpServerIpv6 && _Type == BL_NT_HTTP)
{
}
}
}
static BLS32
_GetError()
{
#ifdef BL_PLATFORM_WIN32
switch (WSAGetLastError())
{
case WSAEWOULDBLOCK:
case WSAENOBUFS:return 0xEA;
case WSAECONNABORTED:
case WSAECONNRESET:
case WSAETIMEDOUT:
case WSAENETRESET:
case WSAENOTCONN:return 0xDEAD;
default:return 0xDEAD;
}
#else
if ((errno == EAGAIN) || (errno == EINPROGRESS))
return 0xEA;
switch (errno)
{
case EINPROGRESS:
case EWOULDBLOCK:return 0xEA;
case ECONNABORTED:
case ECONNRESET:
case ETIMEDOUT:
case ENETRESET:
case ENOTCONN:return 0xDEAD;
default:return 0xDEAD;
}
#endif
}
static BLBool
_Select(BLSocket _Sok, BLBool _Recv)
{
struct timeval _time;
fd_set _selector;
FD_ZERO(&_selector);
FD_SET(_Sok, &_selector);
_time.tv_sec = 0;
_time.tv_usec = 150 * 1000;
if (_Recv)
return select(0, &_selector, 0, 0, &_time) >= 0;
else
return select(0, 0, &_selector, 0, &_time) >= 0;
}
static BLBool
_Send(BLSocket _Sock, _BLNetMsg* _Msg, const BLAnsi* _Header)
{
if (_Msg->eNetType == BL_NT_UDP)
{
}
else
{
BLS32 _nreturn = 0;
if (_Header)
{
BLS32 _sz = (BLS32)strlen(_Header);
while (_sz > 0)
{
_nreturn = (BLS32)send(_Sock, _Header, _sz, 0);
if (-1 == _nreturn)
{
if (_GetError() == 0xEA)
_Select(_Sock, FALSE);
else
return FALSE;
}
else
{
_Header += _nreturn;
_sz -= _nreturn;
}
}
}
BLAnsi* _header = (BLAnsi*)&_Msg->nLength;
BLS32 _headsz = sizeof(BLU32);
while (_headsz > 0)
{
_nreturn = (BLS32)send(_Sock, _header, _headsz, 0);
if (-1 == _nreturn)
{
if (_GetError() == 0xEA)
_Select(_Sock, FALSE);
else
return FALSE;
}
else
{
_header += _nreturn;
_headsz -= _nreturn;
}
}
_header = (BLAnsi*)&_Msg->nID;
_headsz = sizeof(BLU32);
while (_headsz > 0)
{
_nreturn = (BLS32)send(_Sock, _header, _headsz, 0);
if (-1 == _nreturn)
{
if (_GetError() == 0xEA)
_Select(_Sock, FALSE);
else
return FALSE;
}
else
{
_header += _nreturn;
_headsz -= _nreturn;
}
}
_headsz = _Msg->nLength;
BLU8* _data = (BLU8*)_Msg->pBuf;
while (_headsz > 0)
{
if (!_data)
break;
_nreturn = (BLS32)send(_Sock, (BLAnsi*)_data, _headsz, 0);
if (-1 == _nreturn)
{
if (_GetError() == 0xEA)
_Select(_Sock, FALSE);
else
return FALSE;
}
else
{
_data += _nreturn;
_headsz -= _nreturn;
}
}
}
return TRUE;
}
static BLAnsi*
_Recv(BLSocket _Sock, BLU32* _Msgsz)
{
BLU32 _tempsz = 0;
BLS32 _nresult = 0;
BLAnsi* _tempptr = NULL;
_tempsz = sizeof(BLU32);
_tempptr = (BLAnsi*)_Msgsz;
while (_tempsz > 0)
{
if (_Select(_Sock, TRUE))
{
_nresult = (BLS32)recv(_Sock, _tempptr, _tempsz, 0);
if (0 == _nresult)
return NULL;
if (-1 == _nresult)
return NULL;
else
{
_tempsz -= _nresult;
_tempptr += _nresult;
}
}
}
if (-1 != _nresult)
{
BLAnsi* _bufin = (BLAnsi*)malloc(*_Msgsz + *_Msgsz / 64 + 64);
_tempsz = sizeof(BLU32) + *_Msgsz;
_tempptr = _bufin;
while (_tempsz > 0)
{
if (_Select(_Sock, TRUE))
{
_nresult = (BLS32)recv(_Sock, _tempptr, _tempsz, 0);
if (0 == _nresult)
{
free(_bufin);
return NULL;
}
if (-1 == _nresult)
{
free(_bufin);
return NULL;
}
else
{
_tempsz -= _nresult;
_tempptr += _nresult;
}
}
}
return _bufin;
}
return NULL;
}
#if defined(BL_PLATFORM_WEB)
static BLVoid
_OnWGetLoaded(BLU32 _Dummy, BLVoid* _User, BLVoid* _Data, BLU32 _DataSz)
{
const BLAnsi* _url = (const BLAnsi*)blArrayFrontElement(_PrNetworkMem->pDownList);
const BLAnsi* _local = (const BLAnsi*)blArrayFrontElement(_PrNetworkMem->pLocalList);
for (BLU32 _idx = 0; _idx < 64; ++_idx)
{
if (_PrNetworkMem->nFinish[_idx] == 0)
{
_PrNetworkMem->nFinish[_idx] = _PrNetworkMem->_PrCurDownHash;
break;
}
}
FILE* _fp = fopen(_local, "wb");
fwrite(_Data, _DataSz, 1, _fp);
fclose(_fp);
free(_url);
free(_local);
blArrayPopFront(_PrNetworkMem->pDownList);
blArrayPopFront(_PrNetworkMem->pLocalList);
if (_PrNetworkMem->pDownList->nSize)
blNetDownload();
else
{
EM_ASM(FS.syncfs(false, function(err) {}););
}
}
static BLVoid
_OnWGetError(BLU32 _Dummy, BLVoid* _User, BLS32 _Error, const BLAnsi* _Stats)
{
if (_PrNetworkMem->pDownList->nSize)
{
const BLAnsi* _url = (const BLAnsi*)blArrayFrontElement(_PrNetworkMem->pDownList);
const BLAnsi* _local = (const BLAnsi*)blArrayFrontElement(_PrNetworkMem->pLocalList);
free(_url);
free(_local);
blArrayPopFront(_PrNetworkMem->pDownList);
blArrayPopFront(_PrNetworkMem->pLocalList);
if (_PrNetworkMem->pDownList->nSize)
blNetDownload();
}
}
static BLVoid
_OnWGetProg(BLU32 _Dummy, BLVoid* _User, BLS32 _Down, BLS32 _Total)
{
_PrNetworkMem->nCurDownSize = _Down;
_PrNetworkMem->nCurDownTotal = _Total;
}
static BLVoid
_OnWebSocketError(BLS32 _Fd, BLS32 _Err, const BLAnsi* _Msg, BLVoid* _UserData)
{
if (_PrNetworkMem->sTcpSocket == _Fd)
_PrNetworkMem->bConnected = FALSE;
}
static BLVoid
_OnWebSocketMsg(BLS32 _Fd, BLVoid* _UserData)
{
BLAnsi* _bufin = NULL;
BLU32 _msgsz = 0;
_bufin = _Recv(_PrNetworkMem->sTcpSocket, &_msgsz);
if (_bufin)
{
BLU32 _osz = *(BLU32*)_bufin;
if (_osz == _msgsz)
{
BLAnsi* _rp = _bufin + sizeof(unsigned int);
BLU32 _packsz = 0;
while (_rp < _bufin + sizeof(unsigned int) + _msgsz)
{
BLU32* _rc = (BLU32*)_rp;
_BLNetMsg* _ele = (_BLNetMsg*)malloc(sizeof(_BLNetMsg));
_ele->nID = *_rc;
_rc++;
_packsz = _ele->nLength = *_rc;
_rc++;
_ele->pBuf = malloc(_ele->nLength);
memcpy(_ele->pBuf, (BLU8*)_rc, _ele->nLength);
blMutexLock(_PrNetworkMem->pRevList->pMutex);
blListPushBack(_PrNetworkMem->pRevList, _ele);
blMutexUnlock(_PrNetworkMem->pRevList->pMutex);
_rp += _packsz;
}
}
else
{
BLU8* _buflzo = (BLU8*)malloc(_osz);
BLU32 _sz = fastlz_decompress((BLU8*)_bufin + sizeof(unsigned int), _msgsz, _buflzo, _osz);
if (_sz)
{
BLAnsi* _rp = (BLAnsi*)_buflzo;
BLU32 _packsz = 0;
while (_rp < (BLAnsi*)_buflzo + _osz)
{
BLU32* _rc = (BLU32*)_rp;
_BLNetMsg* _ele = (_BLNetMsg*)malloc(sizeof(_BLNetMsg));
_ele->nID = *_rc;
_rc++;
_packsz = _ele->nLength = *_rc;
_rc++;
_ele->pBuf = malloc(_ele->nLength);
memcpy(_ele->pBuf, (BLU8*)_rc, _ele->nLength);
blMutexLock(_PrNetworkMem->pRevList->pMutex);
blListPushBack(_PrNetworkMem->pRevList, _ele);
blMutexUnlock(_PrNetworkMem->pRevList->pMutex);
_rp += _packsz;
}
free(_buflzo);
}
}
free(_bufin);
}
}
#else
static BLU32
_HttpDownloadRequest(BLSocket _Sock, const BLAnsi* _Host, const BLAnsi* _Addr, const BLAnsi* _Filename, BLU32 _Pos, BLU32 _End, BLAnsi _Redirect[1024])
{
BLBool _responsed = FALSE, _endresponse = FALSE;
BLU32 _responsesz = 0, _k, _idx = 0, _sz, _nreturn;
BLAnsi _filesz[32] = { 0 };
BLAnsi* _tmp;
BLAnsi* _temp = (BLAnsi*)malloc(512 * sizeof(BLAnsi));
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
if (_End == 0xFFFFFFFF)
sprintf_s(_temp, 512, "HEAD %s%s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)\r\n\r\n", _Addr, _Filename, _Host);
else
sprintf_s(_temp, 512, "GET %s%s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)\r\nConnection: close\r\nRange: bytes=%lu-%lu\r\n\r\n", _Addr, _Filename, _Host, (unsigned long)_Pos, (unsigned long)_End);
#elif defined(BL_PLATFORM_LINUX) || defined(BL_PLATFORM_ANDROID) || defined(BL_PLATFORM_WEB)
if (_End == 0xFFFFFFFF)
sprintf(_temp, "HEAD %s%s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)\r\n\r\n", _Addr, _Filename, _Host);
else
sprintf(_temp, "GET %s%s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)\r\nConnection: close\r\nRange: bytes=%zu-%zu\r\n\r\n", _Addr, _Filename, _Host, _Pos, _End);
#else
if (_End == 0xFFFFFFFF)
sprintf(_temp, "HEAD %s%s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)\r\n\r\n", _Addr, _Filename, _Host);
else
sprintf(_temp, "GET %s%s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)\r\nConnection: close\r\nRange: bytes=%zu-%zu\r\n\r\n", _Addr, _Filename, _Host, (unsigned long)_Pos, (unsigned long)_End);
#endif
_sz = (BLU32)strlen(_temp);
_tmp = _temp;
while (_sz > 0)
{
_nreturn = (BLS32)send(_Sock, _tmp, _sz, 0);
if (0xFFFFFFFF == _nreturn)
{
if (_GetError() == 0xEA)
_Select(_Sock, FALSE);
else
{
free(_temp);
return -1;
}
}
else
{
_tmp += _nreturn;
_sz -= _nreturn;
}
}
memset(_temp, 0, 512 * sizeof(BLAnsi));
if (!_responsed)
{
BLAnsi _c = 0;
while (!_endresponse && _idx < 513)
{
if (!_GbSystemRunning)
return -1;
if (0 == recv(_Sock, &_c, 1, 0))
{
free(_temp);
return -1;
}
_temp[_idx++] = _c;
if (_idx >= 4)
{
if (_temp[_idx - 4] == '\r' && _temp[_idx - 3] == '\n' && _temp[_idx - 2] == '\r' && _temp[_idx - 1] == '\n')
_endresponse = TRUE;
}
}
if (_idx > 512)
{
_responsed = FALSE;
}
else
{
_temp[_idx] = 0;
_responsesz = _idx;
_responsed = TRUE;
}
}
if (!_responsesz)
{
free(_temp);
return -1;
}
if (_temp[9] == '4' && _temp[10] == '0' && _temp[11] == '4')
{
free(_temp);
return -1;
}
if (_temp[9] == '3' && _temp[10] == '0' && _temp[11] == '2')
{
for (_idx = 0; _idx < strlen(_temp); ++_idx)
{
if (_temp[_idx] == 'h')
{
if (0 == strncmp(_temp + _idx, "http", 4))
{
if (_Redirect)
{
for (BLU32 _i = 0; ; ++_i)
{
if (_temp[_idx] == '\r' && _temp[1 + _idx] == '\n')
break;
_Redirect[_i] = _temp[_idx];
++_idx;
}
free(_temp);
return 0;
}
else
{
free(_temp);
return -1;
}
}
}
}
}
for (_idx = 0; _idx < strlen(_temp); ++_idx)
{
if (_temp[_idx] == 'C')
{
if (0 == strncmp(_temp + _idx, "Content-Length", 14))
{
break;
}
}
}
_idx += 14;
_k = _idx;
for (; _idx <strlen(_temp); ++_idx)
{
if (_idx >= 512)
{
free(_temp);
return -1;
}
if (_temp[_idx] == '\r' && _temp[1 + _idx] == '\n')
break;
}
if ((BLS32)_idx - (BLS32)_k - 1 > 0)
{
strncpy(_filesz, _temp + _k + 1, _idx - _k - 1);
free(_temp);
return (BLU32)atoll(_filesz);
}
else
{
free(_temp);
return -1;
}
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
static DWORD __stdcall
_DownloadWorkerThreadFunc(BLVoid* _Userdata)
#else
static BLVoid*
_DownloadWorkerThreadFunc(BLVoid* _Userdata)
#endif
{
struct sockaddr_in _sin;
struct sockaddr_in6 _sin6;
struct addrinfo _hint, *_servaddr, *_iter;
_BLHttpSect* _sect = (_BLHttpSect*)_Userdata;
BLSocket _httpsok;
BLU32 _filesz, _sectsz, _len, _sumlen;
BLBool _fileexist;
BLAnsi* _buffer = (BLAnsi*)malloc(8192 * sizeof(BLAnsi));
BLS32 _nodelay = 1, _reuse = 1;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
HANDLE _fp;
#else
FILE* _fp;
#endif
reconnect:
_httpsok = socket(_PrNetworkMem->bClientIpv6 ? PF_INET6 : PF_INET, SOCK_STREAM, 0);
memset(&_hint, 0, sizeof(_hint));
_hint.ai_family = PF_UNSPEC;
_hint.ai_socktype = SOCK_STREAM;
if (getaddrinfo(_sect->pHost, "http", &_hint, &_servaddr))
goto failed;
if (_PrNetworkMem->bClientIpv6)
{
for (_iter = _servaddr; _iter != NULL; _iter = _iter->ai_next)
{
if (_iter->ai_family == AF_INET6)
_sin6 = *(struct sockaddr_in6*)_iter->ai_addr;
}
}
else
_sin = *(struct sockaddr_in*)_servaddr->ai_addr;
freeaddrinfo(_servaddr);
if (!_PrNetworkMem->bClientIpv6)
{
_sin.sin_port = htons(_sect->nPort);
if (connect(_httpsok, (struct sockaddr*)&_sin, sizeof(_sin)) < 0)
{
if (0xEA == _GetError())
{
for (BLU32 _n = 0; _n < 64; ++_n)
{
if (_Select(_httpsok, FALSE))
goto success;
}
}
goto failed;
}
}
else
{
_sin6.sin6_port = htons(_sect->nPort);
if (connect(_httpsok, (struct sockaddr*)&_sin6, sizeof(_sin6)) < 0)
{
if (0xEA == _GetError())
{
for (BLU32 _n = 0; _n < 64; ++_n)
{
if (_Select(_httpsok, FALSE))
goto success;
}
}
goto failed;
}
}
_nodelay = 1;
_reuse = 1;
setsockopt(_httpsok, IPPROTO_TCP, TCP_NODELAY, (BLAnsi*)&_nodelay, sizeof(_nodelay));
setsockopt(_httpsok, SOL_SOCKET, SO_REUSEADDR, (BLAnsi*)&_reuse, sizeof(_reuse));
struct linger _lin;
_lin.l_linger = 0;
_lin.l_onoff = 1;
setsockopt(_httpsok, SOL_SOCKET, SO_LINGER, (BLAnsi*)&_lin, sizeof(_lin));
_filesz = 0;
_sectsz = (_sect->nEnd) - (_sect->nStart);
_fileexist = FALSE;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
#ifdef WINAPI_FAMILY
WCHAR _wfilename[260] = { 0 };
MultiByteToWideChar(CP_UTF8, 0, _sect->pLocalName, -1, _wfilename, sizeof(_wfilename));
_fp = CreateFile2(_wfilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
#else
_fp = CreateFileA(_sect->pLocalName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
#else
_fp = fopen(_sect->pLocalName, "rb");
#endif
if (FILE_INVALID_INTERNAL(_fp))
{
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
LARGE_INTEGER _li;
GetFileSizeEx(_fp, &_li);
_filesz = _li.LowPart;
CloseHandle(_fp);
#else
fseek(_fp, 0, SEEK_END);
_filesz = (BLU32)ftell(_fp);
fseek(_fp, 0, SEEK_SET);
fclose(_fp);
#endif
_fileexist = TRUE;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
InterlockedExchangeAdd(&_PrNetworkMem->nCurDownSize, (LONG)_filesz);
#elif defined(BL_PLATFORM_OSX) || defined(BL_PLATFORM_IOS)
atomic_fetch_add(&_PrNetworkMem->nCurDownSize, _filesz);
#elif defined(BL_PLATFORM_LINUX)
__sync_fetch_and_add(&_PrNetworkMem->nCurDownSize, _filesz);
#elif defined(BL_PLATFORM_ANDROID)
{
int32_t _prev, _tmp, _status;
__asm__ __volatile__("dmb" : : : "memory");
do {
__asm__ __volatile__("ldrex %0, [%4]\n"
"add %1, %0, %5\n"
"strex %2, %1, [%4]"
: "=&r" (_prev), "=&r" (_tmp),
"=&r" (_status), "+m" (*&_PrNetworkMem->nCurDownSize)
: "r" (&_PrNetworkMem->nCurDownSize), "Ir" (_filesz)
: "cc");
} while (__builtin_expect(_status != 0, 0));
}
#elif defined(BL_PLATFORM_WEB)
__sync_fetch_and_add(&_PrNetworkMem->nCurDownSize, _filesz);
#else
#error unsupport platform
#endif
}
if (_sectsz == _filesz)
goto success;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
#ifdef WINAPI_FAMILY
if (_fileexist)
_fp = CreateFile2(_wfilename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
else
_fp = CreateFile2(_wfilename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, CREATE_ALWAYS, NULL);
#else
if (_fileexist)
_fp = CreateFileA(_sect->pLocalName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
else
_fp = CreateFileA(_sect->pLocalName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
#else
if (_fileexist)
_fp = fopen(_sect->pLocalName, "r+b");
else
_fp = fopen(_sect->pLocalName, "w+b");
#endif
_HttpDownloadRequest(_httpsok, _sect->pHost, _sect->pPath, _sect->pRemoteName, _sect->nStart + _filesz, _sect->nEnd, NULL);
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
LARGE_INTEGER _li;
GetFileSizeEx(_fp, &_li);
assert(_li.LowPart == _filesz);
_li.LowPart = _li.HighPart = 0;
SetFilePointerEx(_fp, _li, NULL, FILE_END);
#else
fseek(_fp, 0, SEEK_END);
assert((BLU32)ftell(_fp) == _filesz);
#endif
_sumlen = 0;
memset(_buffer, 0, 8192 * sizeof(BLAnsi));
while (1)
{
if (!_GbSystemRunning)
{
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
CloseHandle(_fp);
#else
fclose(_fp);
#endif
goto failed;
}
if (_sumlen >= _sectsz - _filesz)
break;
memset(_buffer, 0, 8192 * sizeof(BLAnsi));
_len = (BLU32)recv(_httpsok, _buffer, 8192 * sizeof(BLAnsi), 0);
if (0xFFFFFFFF == _len)
{
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
CloseHandle(_fp);
#else
fclose(_fp);
#endif
goto failed;
}
if (_len == 0)
{
blYield();
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
CloseHandle(_fp);
closesocket(_httpsok);
#else
fclose(_fp);
close(_httpsok);
#endif
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
InterlockedExchangeAdd(&_PrNetworkMem->nCurDownSize, -(LONG)(_filesz));
#elif defined(BL_PLATFORM_OSX) || defined(BL_PLATFORM_IOS)
atomic_fetch_sub(&_PrNetworkMem->nCurDownSize, _filesz);
#elif defined(BL_PLATFORM_LINUX)
__sync_fetch_and_sub(&_PrNetworkMem->nCurDownSize, _filesz);
#elif defined(BL_PLATFORM_ANDROID)
{
int32_t _prev, _tmp, _status;
__asm__ __volatile__("dmb" : : : "memory");
do {
__asm__ __volatile__("ldrex %0, [%4]\n"
"add %1, %0, %5\n"
"strex %2, %1, [%4]"
: "=&r" (_prev), "=&r" (_tmp),
"=&r" (_status), "+m" (*&_PrNetworkMem->nCurDownSize)
: "r" (&_PrNetworkMem->nCurDownSize), "Ir" (-_filesz)
: "cc");
} while (__builtin_expect(_status != 0, 0));
}
#elif defined(BL_PLATFORM_WEB)
__sync_fetch_and_sub(&_PrNetworkMem->nCurDownSize, _filesz);
#else
#error unsupport platform
#endif
goto reconnect;
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
if (_filesz + _sumlen + _len >= _sectsz)
WriteFile(_fp, _buffer, _sectsz - _filesz - _sumlen, NULL, NULL);
else
WriteFile(_fp, _buffer, _len, NULL, NULL);
FlushFileBuffers(_fp);
#else
if (_filesz + _sumlen + _len >= _sectsz)
fwrite(_buffer, _sectsz - _filesz - _sumlen, 1, _fp);
else
fwrite(_buffer, _len, 1, _fp);
fflush(_fp);
#endif
_sumlen += _len;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
InterlockedExchangeAdd(&_PrNetworkMem->nCurDownSize, (LONG)_len);
#elif defined(BL_PLATFORM_OSX) || defined(BL_PLATFORM_IOS)
atomic_fetch_add(&_PrNetworkMem->nCurDownSize, _len);
#elif defined(BL_PLATFORM_LINUX)
__sync_fetch_and_add(&_PrNetworkMem->nCurDownSize, _len);
#elif defined(BL_PLATFORM_ANDROID)
{
int32_t _prev, _tmp, _status;
__asm__ __volatile__("dmb" : : : "memory");
do {
__asm__ __volatile__("ldrex %0, [%4]\n"
"add %1, %0, %5\n"
"strex %2, %1, [%4]"
: "=&r" (_prev), "=&r" (_tmp),
"=&r" (_status), "+m" (*&_PrNetworkMem->nCurDownSize)
: "r" (&_PrNetworkMem->nCurDownSize), "Ir" (_len)
: "cc");
} while (__builtin_expect(_status != 0, 0));
}
#elif defined(BL_PLATFORM_WEB)
__sync_fetch_and_add(&_PrNetworkMem->nCurDownSize, _len);
#else
#error unsupport platform
#endif
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
CloseHandle(_fp);
#else
fclose(_fp);
#endif
success:
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
closesocket(_httpsok);
#else
close(_httpsok);
#endif
_sect->nState = -1;
free(_buffer);
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
return 0xdead;
#else
return (BLVoid*)0xdead;
#endif
failed:
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
closesocket(_httpsok);
#else
close(_httpsok);
#endif
_sect->nState = 1;
free(_buffer);
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
return 0xdead;
#else
return (BLVoid*)0xdead;
#endif
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
static DWORD __stdcall
_NetDownMainThread(BLVoid* _Userdata)
#else
static BLVoid*
_NetDownMainThread(BLVoid* _Userdata)
#endif
{
while (_PrNetworkMem->pDownList->nSize > 0)
{
blMutexLock(_PrNetworkMem->pDownList->pMutex);
blMutexLock(_PrNetworkMem->pLocalList->pMutex);
BLU16 _port = 80;
BLS32 _idx = 0;
BLU32 _n = 0, _filesz;
struct sockaddr_in _sin;
struct sockaddr_in6 _sin6;
BLAnsi _host[1024] = { 0 };
BLAnsi _path[1024] = { 0 };
BLAnsi _file[1024] = { 0 };
BLAnsi _writefile[260] = { 0 };
BLAnsi _redirect[1024] = { 0 };
BLSocket _httpsok = INVALID_SOCKET_INTERNAL;
BLS32 _nodelay = 1, _reuse = 1;
BLU32 _sectsz;
redirect:
_port = 80;
_idx = 0;
_n = 0;
memset(_host, 0, sizeof(_host));
memset(_path, 0, sizeof(_path));
memset(_file, 0, sizeof(_file));
memset(_writefile, 0, sizeof(_writefile));
const BLAnsi* _url = (const BLAnsi*)blArrayFrontElement(_PrNetworkMem->pDownList);
const BLAnsi* _localfile = (const BLAnsi*)blArrayFrontElement(_PrNetworkMem->pLocalList);
if (strncmp(_url, "http://", 7) != 0)
goto failed;
for (_idx = 7; _idx < (BLS32)strlen(_url) - 7; ++_idx)
{
if (_url[_idx] == '/')
break;
else
_host[_idx - 7] = _url[_idx];
}
for (_idx = 0; _idx < (BLS32)strlen(_host); ++_idx)
{
if (_host[_idx] == ':')
{
_port = atoi(_host + _idx + 1);
_host[_idx] = 0;
break;
}
}
for (_idx = (BLS32)strlen(_url) - 1; _idx >= 0; --_idx)
{
if (_url[_idx] == '/')
break;
}
strncpy(_path, _url, _idx + 1);
strncpy(_file, _url + _idx + 1, strlen(_url) - _idx - 1);
strcpy(_writefile, _localfile);
strcat(_writefile, _file);
_httpsok = socket(_PrNetworkMem->bClientIpv6 ? PF_INET6 : PF_INET, SOCK_STREAM, 0);
if (_PrNetworkMem->bClientIpv6)
_FillAddr(_host, _port, NULL, &_sin6, BL_NT_HTTP);
else
_FillAddr(_host, _port, &_sin, NULL, BL_NT_HTTP);
if (!_PrNetworkMem->bClientIpv6)
{
if (connect(_httpsok, (struct sockaddr*)&_sin, sizeof(_sin)) < 0)
{
if (0xEA == _GetError())
{
for (_n = 0; _n < 64; ++_n)
{
if (_Select(_httpsok, FALSE))
goto success;
}
}
goto failed;
}
}
else
{
if (connect(_httpsok, (struct sockaddr*)&_sin6, sizeof(_sin6)) < 0)
{
if (0xEA == _GetError())
{
for (_n = 0; _n < 64; ++_n)
{
if (_Select(_httpsok, FALSE))
goto success;
}
}
goto failed;
}
}
_nodelay = 1;
_reuse = 1;
setsockopt(_httpsok, IPPROTO_TCP, TCP_NODELAY, (BLAnsi*)&_nodelay, sizeof(_nodelay));
setsockopt(_httpsok, SOL_SOCKET, SO_REUSEADDR, (BLAnsi*)&_reuse, sizeof(_reuse));
struct linger _lin;
_lin.l_linger = 0;
_lin.l_onoff = 1;
setsockopt(_httpsok, SOL_SOCKET, SO_LINGER, (BLAnsi*)&_lin, sizeof(_lin));
success:
_filesz = _HttpDownloadRequest(_httpsok, _host, _path, _file, 0, -1, _redirect);
if ((BLU32)-1 == _filesz)
goto failed;
else if (0 == _filesz)
{
BLAnsi* _retmp = (BLAnsi*)blArrayFrontElement(_PrNetworkMem->pDownList);
free(_retmp);
blArrayPopFront(_PrNetworkMem->pDownList);
_retmp = (BLAnsi*)malloc(strlen(_redirect) + 1);
strcpy(_retmp, _redirect);
blArrayPushFront(_PrNetworkMem->pDownList, _retmp);
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
closesocket(_httpsok);
#else
close(_httpsok);
#endif
goto redirect;
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
closesocket(_httpsok);
#else
close(_httpsok);
#endif
_httpsok = 0;
_BLHttpSect _sects[3];
_sectsz = _filesz / 3;
for (_idx = 0; _idx < 3; ++_idx)
{
_sects[_idx].pHost = (BLAnsi*)malloc(strlen(_host) + 1);
strcpy(_sects[_idx].pHost, _host);
_sects[_idx].pHost[strlen(_host)] = 0;
_sects[_idx].nPort = _port;
_sects[_idx].pPath = (BLAnsi*)malloc(strlen(_path) + 1);
strcpy(_sects[_idx].pPath, _path);
_sects[_idx].pPath[strlen(_path)] = 0;
_sects[_idx].pRemoteName = (BLAnsi*)malloc(strlen(_file) + 1);
strcpy(_sects[_idx].pRemoteName, _file);
_sects[_idx].pRemoteName[strlen(_file)] = 0;
_sects[_idx].pLocalName = (BLAnsi*)malloc(strlen(_localfile) + strlen(_file) + 3);
sprintf(_sects[_idx].pLocalName, "%s%s_%d", _localfile, _file, _idx);
if (_idx < 2)
{
_sects[_idx].nStart = _idx * _sectsz;
_sects[_idx].nEnd = (_idx + 1) * _sectsz;
}
else
{
_sects[_idx].nStart = _idx * _sectsz;
_sects[_idx].nEnd = _filesz;
}
_sects[_idx].nState = 0;
}
_PrNetworkMem->nCurDownTotal = _filesz;
_PrNetworkMem->nCurDownSize = 0;
_PrNetworkMem->_PrCurDownHash = blHashString((const BLUtf8*)_url);
BLThread* _workthread[3];
for (_idx = 0; _idx < 3; ++_idx)
{
_workthread[_idx] = blGenThread(_DownloadWorkerThreadFunc, NULL, &_sects[_idx]);
blThreadRun(_workthread[_idx]);
}
while (TRUE)
{
if (_sects[0].nState == 0xFFFFFFFF && _sects[1].nState == 0xFFFFFFFF && _sects[2].nState == 0xFFFFFFFF)
{
blDeleteThread(_workthread[0]);
blDeleteThread(_workthread[1]);
blDeleteThread(_workthread[2]);
break;
}
else if (_sects[0].nState == 1 || _sects[1].nState == 1 || _sects[2].nState == 1)
{
blDeleteThread(_workthread[0]);
blDeleteThread(_workthread[1]);
blDeleteThread(_workthread[2]);
for (_idx = 0; _idx < 3; ++_idx)
{
free(_sects[_idx].pHost);
free(_sects[_idx].pPath);
free(_sects[_idx].pRemoteName);
free(_sects[_idx].pLocalName);
}
goto failed;
}
else
blYield();
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
HANDLE _fp, _fpread;
#ifdef WINAPI_FAMILY
WCHAR _wfilename[260] = { 0 };
MultiByteToWideChar(CP_UTF8, 0, _writefile, -1, _wfilename, sizeof(_wfilename));
_fp = CreateFile2(_wfilename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, CREATE_ALWAYS, NULL);
#else
_fp = CreateFileA(_writefile, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
for (_idx = 0; _idx < 3; ++_idx)
{
BLU32 _pos = _sects[_idx].nStart;
LARGE_INTEGER _li;
_li.HighPart = 0;
_li.LowPart = _pos;
SetFilePointerEx(_fp, _li, NULL, FILE_BEGIN);
#ifdef WINAPI_FAMILY
memset(_wfilename, 0, sizeof(_wfilename));
MultiByteToWideChar(CP_UTF8, 0, _sects[_idx].pLocalName, -1, _wfilename, sizeof(_wfilename));
_fpread = CreateFile2(_wfilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
#else
_fpread = CreateFileA(_sects[_idx].pLocalName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
BLU8 _c;
do
{
ReadFile(_fpread, &_c, sizeof(BLU8), NULL, NULL);
WriteFile(_fp, &_c, sizeof(BLU8), NULL, NULL);
_pos++;
if (_pos == _sects[_idx].nEnd)
break;
} while (1);
CloseHandle(_fpread);
}
LARGE_INTEGER _li;
GetFileSizeEx(_fp, &_li);
if (_li.LowPart != _PrNetworkMem->nCurDownTotal)
DeleteFileA(_writefile);
else
{
for (_idx = 0; _idx < 3; ++_idx)
DeleteFileA(_sects[_idx].pLocalName);
}
CloseHandle(_fp);
#else
FILE* _fp, *_fpread;
_fp = fopen(_writefile, "wb");
for (_idx = 0; _idx < 3; ++_idx)
{
BLU32 _pos = _sects[_idx].nStart;
fseek(_fp, _pos, SEEK_SET);
_fpread = fopen(_sects[_idx].pLocalName, "rb");
BLS32 _c;
while ((_c = fgetc(_fpread)) != EOF)
{
fputc(_c, _fp);
_pos++;
if (_pos == _sects[_idx].nEnd)
break;
}
fclose(_fpread);
}
if ((BLU32)ftell(_fp) != _PrNetworkMem->nCurDownTotal)
remove(_writefile);
else
{
for (_idx = 0; _idx < 3; ++_idx)
remove(_sects[_idx].pLocalName);
}
fclose(_fp);
#endif
for (_idx = 0; _idx < 3; ++_idx)
{
free(_sects[_idx].pHost);
free(_sects[_idx].pPath);
free(_sects[_idx].pRemoteName);
free(_sects[_idx].pLocalName);
}
failed:
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
if (_httpsok != INVALID_SOCKET_INTERNAL)
closesocket(_httpsok);
#else
if (_httpsok != INVALID_SOCKET_INTERNAL)
close(_httpsok);
#endif
BLAnsi _filetmp[260] = { 0 };
for (_idx = (BLS32)strlen((const BLAnsi*)blArrayFrontElement(_PrNetworkMem->pDownList)) - 1; _idx >= 0; --_idx)
{
if (((BLAnsi*)blArrayFrontElement(_PrNetworkMem->pDownList))[_idx] == '/')
{
strcpy(_filetmp, (BLAnsi*)blArrayFrontElement(_PrNetworkMem->pDownList) + _idx + 1);
break;
}
}
BLAnsi _pathtmp[260] = { 0 };
strcpy(_pathtmp, (BLAnsi*)blArrayFrontElement(_PrNetworkMem->pLocalList));
strcat(_pathtmp, _filetmp);
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
WIN32_FILE_ATTRIBUTE_DATA _wfad;
if (GetFileAttributesExA(_pathtmp, GetFileExInfoStandard, &_wfad))
#else
if (access(_pathtmp, 0) != -1)
#endif
{
for (_idx = 0; _idx < 64; ++_idx)
{
if (_PrNetworkMem->nFinish[_idx] == 0)
{
_PrNetworkMem->nFinish[_idx] = _PrNetworkMem->_PrCurDownHash;
break;
}
}
}
BLAnsi* _tmp;
_tmp = (BLAnsi*)blArrayFrontElement(_PrNetworkMem->pDownList);
free(_tmp);
blArrayPopFront(_PrNetworkMem->pDownList);
_tmp = (BLAnsi*)blArrayFrontElement(_PrNetworkMem->pLocalList);
free(_tmp);
blArrayPopFront(_PrNetworkMem->pLocalList);
blMutexUnlock(_PrNetworkMem->pLocalList->pMutex);
blMutexUnlock(_PrNetworkMem->pDownList->pMutex);
_PrNetworkMem->nCurDownTotal = 0;
_PrNetworkMem->nCurDownSize = 0;
}
_PrNetworkMem->_PrCurDownHash = -1;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
return 0xdead;
#else
return (BLVoid*)0xdead;
#endif
}
#endif
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
static DWORD __stdcall
_NetSocketSendThreadFunc(BLVoid* _Userdata)
#else
static BLVoid*
_NetSocketSendThreadFunc(BLVoid* _Userdata)
#endif
{
while (!_PrNetworkMem->pSendThread)
blYield();
do
{
if (_PrNetworkMem->bConnected)
{
while (_PrNetworkMem->pCriList->nSize)
{
blMutexLock(_PrNetworkMem->pCriList->pMutex);
_BLNetMsg* _msg = (_BLNetMsg*)blListFrontElement(_PrNetworkMem->pCriList);
if (!_Send((_msg->eNetType == BL_NT_UDP) ? _PrNetworkMem->sUdpSocket : _PrNetworkMem->sTcpSocket, _msg, NULL))
_PrNetworkMem->bConnected = FALSE;
blListPopFront(_PrNetworkMem->pCriList);
free(_msg);
blMutexUnlock(_PrNetworkMem->pCriList->pMutex);
}
if (_PrNetworkMem->pNorList->nSize)
{
blMutexLock(_PrNetworkMem->pNorList->pMutex);
_BLNetMsg* _msg = (_BLNetMsg*)blListFrontElement(_PrNetworkMem->pNorList);
if (!_Send((_msg->eNetType == BL_NT_UDP) ? _PrNetworkMem->sUdpSocket : _PrNetworkMem->sTcpSocket, _msg, NULL))
_PrNetworkMem->bConnected = FALSE;
blListPopFront(_PrNetworkMem->pNorList);
free(_msg);
blMutexUnlock(_PrNetworkMem->pNorList->pMutex);
}
}
blYield();
} while (_PrNetworkMem->pSendThread->bRunning);
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
return 0xDEAD;
#else
return (BLVoid*)0xDEAD;
#endif
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
static DWORD __stdcall
_NetSocketRecvThreadFunc(BLVoid* _Userdata)
#else
static BLVoid*
_NetSocketRecvThreadFunc(BLVoid* _Userdata)
#endif
{
while (!_PrNetworkMem->pRecvThread)
blYield();
do
{
BLAnsi* _bufin = NULL;
BLU32 _msgsz = 0;
_bufin = _Recv(_PrNetworkMem->sTcpSocket, &_msgsz);
if (_bufin)
{
BLU8* _buflzo = (BLU8*)alloca(_msgsz * 4);
BLU32 _sz = fastlz_decompress((BLU8*)_bufin, _msgsz, _buflzo, _msgsz * 4);
if (_sz)
{
BLAnsi* _rp = (BLAnsi*)_buflzo;
while (_rp < (BLAnsi*)_buflzo + _sz)
{
BLU32* _rc = (BLU32*)_rp;
_BLNetMsg* _ele = (_BLNetMsg*)malloc(sizeof(_BLNetMsg));
_ele->nID = *_rc;
_rc++;
_ele->nLength = *_rc;
_rc++;
_ele->pBuf = malloc(_ele->nLength);
memcpy(_ele->pBuf, (BLU8*)_rc, _ele->nLength);
blMutexLock(_PrNetworkMem->pRevList->pMutex);
blListPushBack(_PrNetworkMem->pRevList, _ele);
blMutexUnlock(_PrNetworkMem->pRevList->pMutex);
_rp += _ele->nLength + 2 * sizeof(BLU32);
}
}
free(_bufin);
}
else
_PrNetworkMem->bConnected = FALSE;
blYield();
} while (_PrNetworkMem->pRecvThread->bRunning);
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
return 0xdead;
#else
return (BLVoid*)0xdead;
#endif
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
static DWORD __stdcall
_NetSocketConnThreadFunc(BLVoid* _Userdata)
#else
static BLVoid*
_NetSocketConnThreadFunc(BLVoid* _Userdata)
#endif
{
BLU32 _n;
if (_PrNetworkMem->bClientIpv6)
{
blYield();
struct sockaddr_in6 _address;
_FillAddr(_Userdata ? _PrNetworkMem->aHostUDP : _PrNetworkMem->aHostTCP, _Userdata ? _PrNetworkMem->nPortUDP : _PrNetworkMem->nPortTCP, NULL, &_address, _Userdata ? BL_NT_UDP : BL_NT_TCP);
if (connect(_Userdata ? _PrNetworkMem->sUdpSocket : _PrNetworkMem->sTcpSocket, (struct sockaddr*)(&_address), sizeof(_address)) < 0)
{
if (0xEA == _GetError())
{
for (_n = 0; _n < 64; ++_n)
{
if (_Select(_Userdata ? _PrNetworkMem->sUdpSocket : _PrNetworkMem->sTcpSocket, FALSE))
goto beginthread;
}
}
goto end;
}
}
else
{
blYield();
struct sockaddr_in _address;
_FillAddr(_Userdata ? _PrNetworkMem->aHostUDP : _PrNetworkMem->aHostTCP, _Userdata ? _PrNetworkMem->nPortUDP : _PrNetworkMem->nPortTCP, &_address, NULL, _Userdata ? BL_NT_UDP : BL_NT_TCP);
if (connect(_Userdata ? _PrNetworkMem->sUdpSocket : _PrNetworkMem->sTcpSocket, (struct sockaddr*)&(_address), sizeof(_address)) < 0)
{
if (0xEA == _GetError())
{
for (_n = 0; _n < 64; ++_n)
{
if (_Select(_Userdata ? _PrNetworkMem->sUdpSocket : _PrNetworkMem->sTcpSocket, FALSE))
goto beginthread;
}
}
goto end;
}
}
beginthread:
#if defined(BL_PLATFORM_WEB)
_PrNetworkMem->pSendThread = (BLVoid*)0xFFFFFFFF;
_PrNetworkMem->pRecvThread = (BLVoid*)0xFFFFFFFF;
#else
_PrNetworkMem->pSendThread = blGenThread(_NetSocketSendThreadFunc, NULL, NULL);
_PrNetworkMem->pRecvThread = blGenThread(_NetSocketRecvThreadFunc, NULL, NULL);
blThreadRun(_PrNetworkMem->pSendThread);
blThreadRun(_PrNetworkMem->pRecvThread);
#endif
_PrNetworkMem->bConnected = TRUE;
end:
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
return 0xdead;
#else
return (BLVoid*)0xdead;
#endif
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
static DWORD __stdcall
_NetHTTPWorkThreadFunc(BLVoid* _Userdata)
#else
static BLVoid*
_NetHTTPWorkThreadFunc(BLVoid* _Userdata)
#endif
{
blMutexWait(_PrNetworkMem->pHttpJobArray->pMutex);
BLU32 _n;
BLAnsi _httpheader[1024];
BLAnsi* _bufin = NULL;
_BLHttpJob* _job = (_BLHttpJob*)_Userdata;
_BLNetMsg* _msg = _job->pMsg;
BLU32 _msgsz = 0;
if (_PrNetworkMem->bClientIpv6)
{
struct sockaddr_in6 _address;
blYield();
_FillAddr(_PrNetworkMem->aHostHTTP, _PrNetworkMem->nPortHTTP, NULL, &_address, BL_NT_HTTP);
if (connect(((_BLHttpJob*)_Userdata)->sSocket, (struct sockaddr*)&(_address), sizeof(_address)) < 0)
{
if (0xEA == _GetError())
{
for (_n = 0; _n < 64; ++_n)
{
if (_Select(((_BLHttpJob*)_Userdata)->sSocket, FALSE))
goto beginwork;
}
}
free(((_BLHttpJob*)_Userdata)->pMsg);
goto end;
}
}
else
{
struct sockaddr_in _address;
blYield();
_FillAddr(_PrNetworkMem->aHostHTTP, _PrNetworkMem->nPortHTTP, &_address, NULL, BL_NT_HTTP);
if (connect(((_BLHttpJob*)_Userdata)->sSocket, (struct sockaddr*)&(_address), sizeof(_address)) < 0)
{
if (0xEA == _GetError())
{
for (_n = 0; _n < 64; ++_n)
{
if (_Select(((_BLHttpJob*)_Userdata)->sSocket, FALSE))
goto beginwork;
}
}
free(((_BLHttpJob*)_Userdata)->pMsg);
goto end;
}
}
beginwork:
sprintf(_httpheader, "POST / HTTP/1.1\r\nHost: %s:%d\r\nAccept: */*\r\nConnection: close\r\nContent-Length: %zu\r\n\r\n", _PrNetworkMem->aHostHTTP, _PrNetworkMem->nPortHTTP, _msg->nLength + 2 * sizeof(BLU32));
_Send(((_BLHttpJob*)_Userdata)->sSocket, _msg, _httpheader);
blYield();
#if !defined(BL_PLATFORM_WEB)
_bufin = _Recv(((_BLHttpJob*)_Userdata)->sSocket, &_msgsz);
if (_bufin)
{
BLU8* _buflzo = (BLU8*)alloca(_msgsz * 4);
BLU32 _sz = fastlz_decompress((BLU8*)_bufin, _msgsz, _buflzo, _msgsz * 4);
if (_sz)
{
BLAnsi* _rp = (BLAnsi*)_buflzo;
while (_rp < (BLAnsi*)_buflzo + _sz)
{
BLU32* _rc = (BLU32*)_rp;
_BLNetMsg* _ele = (_BLNetMsg*)malloc(sizeof(_BLNetMsg));
_ele->nID = *_rc;
_rc++;
_ele->nLength = *_rc;
_rc++;
_ele->pBuf = malloc(_ele->nLength);
memcpy(_ele->pBuf, (BLU8*)_rc, _ele->nLength);
blMutexLock(_PrNetworkMem->pRevList->pMutex);
blListPushBack(_PrNetworkMem->pRevList, _ele);
blMutexUnlock(_PrNetworkMem->pRevList->pMutex);
_rp += _ele->nLength + 2 * sizeof(BLU32);
}
}
free(_bufin);
}
#endif
end:
((_BLHttpJob*)_Userdata)->bOver = TRUE;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
return 0xdead;
#else
return (BLVoid*)0xdead;
#endif
}
BLVoid
_NetworkInit()
{
_PrNetworkMem = (_BLNetworkMember*)malloc(sizeof(_BLNetworkMember));
memset(_PrNetworkMem->aHostTCP, 0, sizeof(_PrNetworkMem->aHostTCP));
_PrNetworkMem->nPortTCP = 0;
memset(_PrNetworkMem->aHostUDP, 0, sizeof(_PrNetworkMem->aHostUDP));
_PrNetworkMem->nPortUDP = 0;
memset(_PrNetworkMem->aHostHTTP, 0, sizeof(_PrNetworkMem->aHostHTTP));
_PrNetworkMem->nPortHTTP = 0;
_PrNetworkMem->pCriList = NULL;
_PrNetworkMem->pNorList = NULL;
_PrNetworkMem->pRevList = NULL;
_PrNetworkMem->pHttpJobArray = NULL;
_PrNetworkMem->pDownList = NULL;
_PrNetworkMem->pLocalList = NULL;
memset(_PrNetworkMem->nFinish, 0, sizeof(_PrNetworkMem->nFinish));
_PrNetworkMem->pConnThread = NULL;
_PrNetworkMem->pSendThread = NULL;
_PrNetworkMem->pRecvThread = NULL;
_PrNetworkMem->pDownMain = NULL;
_PrNetworkMem->_PrCurDownHash = -1;
_PrNetworkMem->nCurDownTotal = 0;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
_PrNetworkMem->nCurDownSize = 0;
#elif defined(BL_PLATFORM_OSX) || defined(BL_PLATFORM_IOS)
_PrNetworkMem->nCurDownSize = 0;
#elif defined(BL_PLATFORM_LINUX)
_PrNetworkMem->nCurDownSize = 0;
#else
_PrNetworkMem->nCurDownSize = 0;
#endif
_PrNetworkMem->bClientIpv6 = FALSE;
_PrNetworkMem->bTcpServerIpv6 = FALSE;
_PrNetworkMem->bUdpServerIpv6 = FALSE;
_PrNetworkMem->bHttpServerIpv6 = FALSE;
_PrNetworkMem->bConnected = FALSE;
_PrNetworkMem->sTcpSocket = INVALID_SOCKET_INTERNAL;
_PrNetworkMem->sUdpSocket = INVALID_SOCKET_INTERNAL;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
WSADATA ws;
WSAStartup(MAKEWORD(2, 2), &ws);
#endif
_PrNetworkMem->pCriList = blGenList(TRUE);
_PrNetworkMem->pNorList = blGenList(TRUE);
_PrNetworkMem->pRevList = blGenList(TRUE);
_PrNetworkMem->pHttpJobArray = blGenList(TRUE);
_PrNetworkMem->pDownList = blGenArray(TRUE);
_PrNetworkMem->pLocalList = blGenArray(TRUE);
struct addrinfo* _result = NULL;
struct addrinfo* _curr;
BLS32 _ret = getaddrinfo("www.bing.com", NULL, NULL, &_result);
if (_ret == 0)
{
for (_curr = _result; _curr != NULL; _curr = _curr->ai_next)
{
switch (_curr->ai_family)
{
case AF_INET6:
_PrNetworkMem->bClientIpv6 = TRUE;
break;
default:
break;
}
}
}
freeaddrinfo(_result);
#if defined(BL_PLATFORM_WEB)
emscripten_set_socket_message_callback(NULL, _OnWebSocketMsg);
emscripten_set_socket_error_callback(NULL, _OnWebSocketError);
#endif
blDebugOutput("Network initialize successfully");
}
BLVoid
_NetworkDestroy()
{
if (_PrNetworkMem->pConnThread)
{
blDeleteThread(_PrNetworkMem->pConnThread);
_PrNetworkMem->pConnThread = NULL;
}
if (_PrNetworkMem->pSendThread)
{
blDeleteThread(_PrNetworkMem->pSendThread);
_PrNetworkMem->pSendThread = NULL;
}
if (_PrNetworkMem->pRecvThread)
{
blDeleteThread(_PrNetworkMem->pRecvThread);
_PrNetworkMem->pRecvThread = NULL;
}
if (_PrNetworkMem->pDownMain)
{
blDeleteThread(_PrNetworkMem->pDownMain);
_PrNetworkMem->pDownMain = NULL;
}
{
FOREACH_LIST(_BLNetMsg*, _citer, _PrNetworkMem->pCriList)
{
free(_citer->pBuf);
free(_citer);
}
}
{
FOREACH_LIST(_BLNetMsg*, _niter, _PrNetworkMem->pNorList)
{
free(_niter->pBuf);
free(_niter);
}
}
{
FOREACH_LIST(_BLNetMsg*, _riter, _PrNetworkMem->pRevList)
{
free(_riter->pBuf);
free(_riter);
}
}
{
FOREACH_ARRAY(BLAnsi*, _riter, _PrNetworkMem->pDownList)
{
free(_riter);
}
}
{
FOREACH_ARRAY(BLAnsi*, _riter, _PrNetworkMem->pLocalList)
{
free(_riter);
}
}
blDeleteList(_PrNetworkMem->pCriList);
blDeleteList(_PrNetworkMem->pNorList);
blDeleteList(_PrNetworkMem->pRevList);
blDeleteArray(_PrNetworkMem->pDownList);
blDeleteArray(_PrNetworkMem->pLocalList);
if (_PrNetworkMem->sTcpSocket != INVALID_SOCKET_INTERNAL)
{
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
shutdown(_PrNetworkMem->sTcpSocket, SD_SEND);
closesocket(_PrNetworkMem->sTcpSocket);
_PrNetworkMem->sTcpSocket = INVALID_SOCKET_INTERNAL;
#else
shutdown(_PrNetworkMem->sTcpSocket, SHUT_WR);
close(_PrNetworkMem->sTcpSocket);
_PrNetworkMem->sTcpSocket = INVALID_SOCKET_INTERNAL;
#endif
}
if (_PrNetworkMem->sUdpSocket != INVALID_SOCKET_INTERNAL)
{
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
shutdown(_PrNetworkMem->sUdpSocket, SD_SEND);
closesocket(_PrNetworkMem->sUdpSocket);
_PrNetworkMem->sUdpSocket = INVALID_SOCKET_INTERNAL;
#else
shutdown(_PrNetworkMem->sUdpSocket, SHUT_WR);
close(_PrNetworkMem->sUdpSocket);
_PrNetworkMem->sUdpSocket = INVALID_SOCKET_INTERNAL;
#endif
}
FOREACH_LIST(_BLHttpJob*, _iter, _PrNetworkMem->pHttpJobArray)
{
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
shutdown(_iter->sSocket, SD_SEND);
closesocket(_iter->sSocket);
#else
shutdown(_iter->sSocket, SHUT_WR);
close(_iter->sSocket);
#endif
blDeleteThread(_iter->pThread);
}
if (_PrNetworkMem->pHttpJobArray)
{
blDeleteList(_PrNetworkMem->pHttpJobArray);
_PrNetworkMem->pHttpJobArray = NULL;
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
WSACleanup();
#endif
blDebugOutput("Network shutdown");
free(_PrNetworkMem);
}
BLVoid
_NetworkStep(BLU32 _Delta)
{
if (_PrNetworkMem->pSendThread && _PrNetworkMem->pRecvThread)
{
if (_PrNetworkMem->pConnThread)
{
blDeleteThread(_PrNetworkMem->pConnThread);
_PrNetworkMem->pConnThread = NULL;
blSysInvokeEvent(BL_ET_NET, 0xFFFFFFFF, 0xFFFFFFFF, NULL, INVALID_GUID);
}
if (!_PrNetworkMem->bConnected)
{
blDeleteThread(_PrNetworkMem->pSendThread);
_PrNetworkMem->pSendThread = NULL;
blDeleteThread(_PrNetworkMem->pRecvThread);
_PrNetworkMem->pRecvThread = NULL;
blSysInvokeEvent(BL_ET_NET, 0, 0, NULL, INVALID_GUID);
}
blMutexLock(_PrNetworkMem->pRevList->pMutex);
{
FOREACH_LIST(_BLNetMsg*, _iter, _PrNetworkMem->pRevList)
{
BLVoid* _buf = malloc(_iter->nLength);
memcpy(_buf, _iter->pBuf, _iter->nLength);
blSysInvokeEvent(BL_ET_NET, _iter->nID, _iter->nLength, _buf, INVALID_GUID);
free(_iter->pBuf);
free(_iter);
}
}
blClearList(_PrNetworkMem->pRevList);
blMutexUnlock(_PrNetworkMem->pRevList->pMutex);
}
blMutexLock(_PrNetworkMem->pRevList->pMutex);
{
FOREACH_LIST(_BLNetMsg*, _iter, _PrNetworkMem->pRevList)
{
BLVoid* _buf = malloc(_iter->nLength);
memcpy(_buf, _iter->pBuf, _iter->nLength);
blSysInvokeEvent(BL_ET_NET, _iter->nID, _iter->nLength, _buf, INVALID_GUID);
free(_iter->pBuf);
free(_iter);
}
}
blClearList(_PrNetworkMem->pRevList);
blMutexUnlock(_PrNetworkMem->pRevList->pMutex);
blMutexLock(_PrNetworkMem->pHttpJobArray->pMutex);
{
FOREACH_LIST(_BLHttpJob*, _iter, _PrNetworkMem->pHttpJobArray)
{
if (_iter->bOver)
{
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
shutdown(_iter->sSocket, SD_SEND);
closesocket(_iter->sSocket);
#else
shutdown(_iter->sSocket, SHUT_WR);
close(_iter->sSocket);
#endif
blDeleteThread(_iter->pThread);
blListErase(_PrNetworkMem->pHttpJobArray, _iterator_iter);
}
}
}
blMutexUnlock(_PrNetworkMem->pHttpJobArray->pMutex);
#if defined(BL_PLATFORM_WEB)
if (_PrNetworkMem->bConnected)
{
while (_PrNetworkMem->pCriList->nSize)
{
blMutexLock(_PrNetworkMem->pCriList->pMutex);
_BLNetMsg* _msg = (_BLNetMsg*)blListFrontElement(_PrNetworkMem->pCriList);
if (!_Send((_msg->eNetType == BL_NT_UDP) ? _PrNetworkMem->sUdpSocket : _PrNetworkMem->sTcpSocket, _msg, NULL))
_PrNetworkMem->bConnected = FALSE;
blListPopFront(_PrNetworkMem->pCriList);
free(_msg);
blMutexUnlock(_PrNetworkMem->pCriList->pMutex);
}
if (_PrNetworkMem->pNorList->nSize)
{
blMutexLock(_PrNetworkMem->pNorList->pMutex);
_BLNetMsg* _msg = (_BLNetMsg*)blListFrontElement(_PrNetworkMem->pNorList);
if (!_Send((_msg->eNetType == BL_NT_UDP) ? _PrNetworkMem->sUdpSocket : _PrNetworkMem->sTcpSocket, _msg, NULL))
_PrNetworkMem->bConnected = FALSE;
blListPopFront(_PrNetworkMem->pNorList);
free(_msg);
blMutexUnlock(_PrNetworkMem->pNorList->pMutex);
}
}
#endif
}
BLVoid
blNetConnect(IN BLAnsi* _Host, IN BLU16 _Port, IN BLEnum _Type)
{
if (_Type == BL_NT_UDP)
{
struct addrinfo _hints;
memset(&_hints, 0, sizeof(_hints));
_hints.ai_family = PF_UNSPEC;
_hints.ai_socktype = SOCK_DGRAM;
#if defined(WIN32)
_hints.ai_flags = AI_NUMERICHOST;
#else
_hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG;
#endif
struct addrinfo* _answer;
getaddrinfo(_Host, NULL, &_hints, &_answer);
for (struct addrinfo* _curr = _answer; _curr != NULL; _curr = _curr->ai_next)
{
switch (_curr->ai_family)
{
case AF_UNSPEC:
break;
case AF_INET:
break;
case AF_INET6:
_PrNetworkMem->bUdpServerIpv6 = TRUE;
break;
}
}
freeaddrinfo(_answer);
memset(_PrNetworkMem->aHostUDP, 0, sizeof(_PrNetworkMem->aHostUDP));
strcpy(_PrNetworkMem->aHostUDP, _Host);
_PrNetworkMem->nPortUDP = _Port;
_PrNetworkMem->sUdpSocket = socket(_PrNetworkMem->bClientIpv6 ? PF_INET6 : PF_INET, SOCK_DGRAM, IPPROTO_UDP);
}
else if (_Type == BL_NT_TCP)
{
struct addrinfo _hints;
memset(&_hints, 0, sizeof(_hints));
_hints.ai_family = PF_UNSPEC;
_hints.ai_socktype = SOCK_STREAM;
#if defined(WIN32)
_hints.ai_flags = AI_NUMERICHOST;
#else
_hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG;
#endif
struct addrinfo* _answer;
getaddrinfo(_Host, NULL, &_hints, &_answer);
for (struct addrinfo* _curr = _answer; _curr != NULL; _curr = _curr->ai_next)
{
switch (_curr->ai_family)
{
case AF_UNSPEC:
break;
case AF_INET:
break;
case AF_INET6:
_PrNetworkMem->bTcpServerIpv6 = TRUE;
break;
}
}
freeaddrinfo(_answer);
memset(_PrNetworkMem->aHostTCP, 0, sizeof(_PrNetworkMem->aHostTCP));
strcpy(_PrNetworkMem->aHostTCP, _Host);
_PrNetworkMem->nPortTCP = _Port;
BLS32 _nodelay = 1, _reuse = 1;
struct linger _lin;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
u_long _nonblocking = 1;
#endif
_PrNetworkMem->sTcpSocket = socket(_PrNetworkMem->bClientIpv6 ? PF_INET6 : PF_INET, SOCK_STREAM, IPPROTO_TCP);
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
ioctlsocket(_PrNetworkMem->sTcpSocket, FIONBIO, &_nonblocking);
#else
fcntl(_PrNetworkMem->sTcpSocket, F_SETFL, fcntl(_PrNetworkMem->sTcpSocket, F_GETFL) | O_NONBLOCK);
#endif
setsockopt(_PrNetworkMem->sTcpSocket, IPPROTO_TCP, TCP_NODELAY, (BLAnsi*)&_nodelay, sizeof(_nodelay));
setsockopt(_PrNetworkMem->sTcpSocket, SOL_SOCKET, SO_REUSEADDR, (BLAnsi*)&_reuse, sizeof(_reuse));
_lin.l_linger = 0;
_lin.l_onoff = 1;
setsockopt(_PrNetworkMem->sTcpSocket, SOL_SOCKET, SO_LINGER, (BLAnsi*)&_lin, sizeof(_lin));
#if defined(BL_PLATFORM_WEB)
_PrNetworkMem->pConnThread = (BLVoid*)0xFFFFFFFF;
_NetSocketConnThreadFunc(NULL);
#else
_PrNetworkMem->pConnThread = blGenThread(_NetSocketConnThreadFunc, NULL, NULL);
blThreadRun(_PrNetworkMem->pConnThread);
#endif
}
else
{
struct addrinfo _hints;
memset(&_hints, 0, sizeof(_hints));
_hints.ai_family = PF_UNSPEC;
_hints.ai_socktype = SOCK_STREAM;
#if defined(WIN32)
_hints.ai_flags = AI_NUMERICHOST;
#else
_hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG;
#endif
struct addrinfo* _answer;
getaddrinfo(_Host, NULL, &_hints, &_answer);
for (struct addrinfo* _curr = _answer; _curr != NULL; _curr = _curr->ai_next)
{
switch (_curr->ai_family)
{
case AF_UNSPEC:
break;
case AF_INET:
break;
case AF_INET6:
_PrNetworkMem->bHttpServerIpv6 = TRUE;
break;
}
}
freeaddrinfo(_answer);
memset(_PrNetworkMem->aHostHTTP, 0, sizeof(_PrNetworkMem->aHostHTTP));
strcpy(_PrNetworkMem->aHostHTTP, _Host);
_PrNetworkMem->nPortHTTP = _Port;
}
}
BLVoid
blNetDisconnect()
{
{
FOREACH_LIST(_BLNetMsg*, _citer, _PrNetworkMem->pCriList)
{
free(_citer->pBuf);
free(_citer);
}
}
{
FOREACH_LIST(_BLNetMsg*, _niter, _PrNetworkMem->pNorList)
{
free(_niter->pBuf);
free(_niter);
}
}
{
FOREACH_LIST(_BLNetMsg*, _riter, _PrNetworkMem->pRevList)
{
free(_riter->pBuf);
free(_riter);
}
}
if (_PrNetworkMem->pSendThread)
{
blDeleteThread(_PrNetworkMem->pSendThread);
_PrNetworkMem->pSendThread = NULL;
}
if (_PrNetworkMem->pRecvThread)
{
blDeleteThread(_PrNetworkMem->pRecvThread);
_PrNetworkMem->pRecvThread = NULL;
}
if (_PrNetworkMem->pConnThread)
{
blDeleteThread(_PrNetworkMem->pConnThread);
_PrNetworkMem->pConnThread = NULL;
}
if (_PrNetworkMem->sTcpSocket != INVALID_SOCKET_INTERNAL)
{
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
shutdown(_PrNetworkMem->sTcpSocket, SD_SEND);
closesocket(_PrNetworkMem->sTcpSocket);
_PrNetworkMem->sTcpSocket = INVALID_SOCKET_INTERNAL;
#else
shutdown(_PrNetworkMem->sTcpSocket, SHUT_WR);
close(_PrNetworkMem->sTcpSocket);
_PrNetworkMem->sTcpSocket = INVALID_SOCKET_INTERNAL;
#endif
}
if (_PrNetworkMem->sUdpSocket != INVALID_SOCKET_INTERNAL)
{
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
shutdown(_PrNetworkMem->sUdpSocket, SD_SEND);
closesocket(_PrNetworkMem->sUdpSocket);
_PrNetworkMem->sUdpSocket = INVALID_SOCKET_INTERNAL;
#else
shutdown(_PrNetworkMem->sUdpSocket, SHUT_WR);
close(_PrNetworkMem->sUdpSocket);
_PrNetworkMem->sUdpSocket = INVALID_SOCKET_INTERNAL;
#endif
}
}
BLVoid
blNetSendMsg(IN BLU32 _ID, IN BLAnsi* _JsonData, IN BLBool _Critical, IN BLBool _Overwrite, IN BLEnum _Nettype)
{
_BLNetMsg* _msg = (_BLNetMsg*)malloc(sizeof(_BLNetMsg));
_msg->nID = _ID;
_msg->eNetType = _Nettype;
_msg->nLength = (BLU32)strlen(_JsonData);
BLU8* _stream;
BLU32 _sz;
_stream = (BLU8*)alloca(((_msg->nLength + (BLU32)(_msg->nLength * 0.06)) > 66) ? (_msg->nLength + (BLU32)(_msg->nLength * 0.06)) : 66);
_sz = fastlz_compress(_JsonData, _msg->nLength, _stream);
_msg->pBuf = malloc(_sz);
memcpy(_msg->pBuf, _stream, _sz);
_msg->nLength = _sz;
if (_Critical || _Nettype == BL_NT_HTTP)
{
if (_Overwrite && _Nettype != BL_NT_HTTP)
{
blMutexLock(_PrNetworkMem->pCriList->pMutex);
{
FOREACH_LIST(_BLNetMsg*, _citer, _PrNetworkMem->pCriList)
{
if (_citer->nID == _msg->nID)
{
free(_citer->pBuf);
free(_citer);
blListErase(_PrNetworkMem->pCriList, _iterator_citer);
break;
}
}
}
blMutexUnlock(_PrNetworkMem->pCriList->pMutex);
}
if (_Nettype != BL_NT_HTTP)
blListPushBack(_PrNetworkMem->pCriList, _msg);
}
else
{
if (_Overwrite)
{
blMutexLock(_PrNetworkMem->pNorList->pMutex);
{
FOREACH_LIST(_BLNetMsg*, _niter, _PrNetworkMem->pNorList)
{
if (_niter->nID == _msg->nID)
{
free(_niter->pBuf);
free(_niter);
blListErase(_PrNetworkMem->pNorList, _iterator_niter);
break;
}
}
}
blMutexUnlock(_PrNetworkMem->pNorList->pMutex);
}
blListPushBack(_PrNetworkMem->pNorList, _msg);
}
if (_Nettype == BL_NT_HTTP)
{
BLS32 _nodelay = 1, _reuse = 1;
struct linger _lin;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
u_long _nonblocking = 1;
#endif
_BLHttpJob* _job = (_BLHttpJob*)malloc(sizeof(_BLHttpJob));
_job->sSocket = socket(_PrNetworkMem->bClientIpv6 ? PF_INET6 : PF_INET, SOCK_STREAM, IPPROTO_TCP);
_job->bOver = FALSE;
_job->pMsg = _msg;
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
ioctlsocket(_job->sSocket, FIONBIO, &_nonblocking);
#else
fcntl(_job->sSocket, F_SETFL, fcntl(_job->sSocket, F_GETFL) | O_NONBLOCK);
#endif
setsockopt(_job->sSocket, IPPROTO_TCP, TCP_NODELAY, (BLAnsi*)&_nodelay, sizeof(_nodelay));
setsockopt(_job->sSocket, SOL_SOCKET, SO_REUSEADDR, (BLAnsi*)&_reuse, sizeof(_reuse));
_lin.l_linger = 0;
_lin.l_onoff = 1;
setsockopt(_job->sSocket, SOL_SOCKET, SO_LINGER, (BLAnsi*)&_lin, sizeof(_lin));
blMutexLock(_PrNetworkMem->pCriList->pMutex);
blListPushBack(_PrNetworkMem->pHttpJobArray, _job);
blMutexUnlock(_PrNetworkMem->pCriList->pMutex);
#if defined(BL_PLATFORM_WEB)
_NetHTTPWorkThreadFunc(_job);
#else
_job->pThread = blGenThread(_NetHTTPWorkThreadFunc, NULL, _job);
blThreadRun(_job->pThread);
#endif
}
}
BLBool
blNetHTTPRequest(IN BLAnsi* _Url, IN BLAnsi* _Param, IN BLBool _Get, OUT BLAnsi _Response[1025])
{
if (strlen(_Url) >= 1024)
return FALSE;
if (strncmp(_Url, "http://", 7) != 0)
return FALSE;
BLBool _chunked;
BLBool _responsed = FALSE, _endresponse = FALSE;
BLS32 _idx = 0;
BLU32 _port = 80, _nreturn, _sz, _responsesz = 0;
struct sockaddr_in _sin;
struct sockaddr_in6 _sin6;
struct addrinfo _hint, *_servaddr, *_iter;
BLAnsi _host[1024] = { 0 };
BLAnsi* _tmp;
BLSocket _sok = socket(_PrNetworkMem->bClientIpv6 ? PF_INET6 : PF_INET, SOCK_STREAM, 0);
memset(&_hint, 0, sizeof(_hint));
_hint.ai_family = PF_UNSPEC;
_hint.ai_socktype = SOCK_STREAM;
for (_idx = 7; _idx < (BLS32)strlen(_Url) - 7; ++_idx)
{
if (_Url[_idx] == '/')
break;
else
_host[_idx - 7] = _Url[_idx];
}
for (_idx = 0; _idx < (BLS32)strlen(_Url); ++_idx)
{
if (_host[_idx] == ':')
{
_port = atoi(_host + _idx + 1);
_host[_idx] = 0;
break;
}
}
for (_idx = (BLS32)strlen(_Url) - 1; _idx >= 0; --_idx)
{
if (_Url[_idx] == '/')
break;
}
if (getaddrinfo(_host, "http", &_hint, &_servaddr))
return FALSE;
if (_PrNetworkMem->bClientIpv6)
{
for (_iter = _servaddr; _iter != NULL; _iter = _iter->ai_next)
{
if (_iter->ai_family == PF_INET6)
_sin6 = *(struct sockaddr_in6*)_iter->ai_addr;
}
}
else
_sin = *(struct sockaddr_in*)_servaddr->ai_addr;
freeaddrinfo(_servaddr);
if (!_PrNetworkMem->bClientIpv6)
{
_sin.sin_port = htons(_port);
if (connect(_sok, (struct sockaddr*)&_sin, sizeof(_sin)) < 0)
{
if (0xEA == _GetError())
{
for (_idx = 0; _idx < 64; ++_idx)
{
if (_Select(_sok, FALSE))
goto success;
}
}
goto failed;
}
}
else
{
_sin6.sin6_port = htons(_port);
if (connect(_sok, (struct sockaddr*)&_sin6, sizeof(_sin6)) < 0)
{
if (0xEA == _GetError())
{
for (_idx = 0; _idx < 64; ++_idx)
{
if (_Select(_sok, FALSE))
goto success;
}
}
goto failed;
}
}
success:
memset(_Response, 0, 1025 * sizeof(BLAnsi));
if (_Get)
sprintf(_Response, "GET %s?%s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", _Url, _Param, _host);
else
sprintf(_Response, "POST %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: %zu\r\n\r\n%s", _Url, _host, strlen(_Url), _Param);
_sz = (BLU32)strlen(_Response);
_tmp = _Response;
while (_sz > 0)
{
_nreturn = (BLS32)send(_sok, _tmp, _sz, 0);
if (0xFFFFFFFF == _nreturn)
{
if (_GetError() == 0xEA)
_Select(_sok, FALSE);
else
goto failed;
}
else
{
_tmp += _nreturn;
_sz -= _nreturn;
}
}
memset(_Response, 0, sizeof(BLAnsi) * 1025);
_idx = 0;
if (!_responsed)
{
BLAnsi _c = 0;
while (!_endresponse && _idx < 1025)
{
if (!_GbSystemRunning)
goto failed;
if (_Select(_sok, TRUE))
{
if (0 == recv(_sok, &_c, 1, 0))
goto failed;
_Response[_idx++] = _c;
if (_idx >= 4)
{
if (_Response[_idx - 4] == '\r' && _Response[_idx - 3] == '\n' && _Response[_idx - 2] == '\r' && _Response[_idx - 1] == '\n')
_endresponse = TRUE;
}
}
}
_Response[_idx] = 0;
_responsesz = _idx;
_responsed = TRUE;
}
if (!_responsed)
goto failed;
if (!_responsesz)
goto failed;
if (_Response[9] != '2' || _Response[10] != '0' || _Response[11] != '0')
goto failed;
_responsesz = -1;
_chunked = TRUE;
for (_idx = 0; _idx < (BLS32)strlen(_Response); ++_idx)
{
if (_Response[_idx] == 'C')
{
if (0 == strncmp(_Response + _idx, "Content-Length", 14))
{
_chunked = FALSE;
break;
}
}
}
if (!_chunked)
{
_idx += 14;
BLAnsi _filesz[32];
BLS32 _k = _idx;
for (; _idx < (BLS32)strlen(_Response); ++_idx)
{
if (_idx >= 1024)
goto failed;
if (_Response[_idx] == '\r' && _Response[1 + _idx] == '\n')
break;
}
if ((BLS32)_idx - (BLS32)_k - 1 > 0)
{
strncpy(_filesz, _Response + _k + 1, _idx - _k - 1);
_responsesz = atoi(_filesz);
}
else
goto failed;
}
if (!_chunked && _responsesz >= 1024)
goto failed;
memset(_Response, 0, sizeof(BLAnsi) * 1025);
if (!_chunked)
{
_idx = 0;
BLAnsi _c = 0;
while (_idx < (BLS32)_responsesz)
{
if (!_GbSystemRunning)
goto failed;
if (_Select(_sok, TRUE))
{
if (0 == recv(_sok, &_c, 1, 0))
break;
_Response[_idx++] = _c;
}
}
_Response[_idx] = 0;
}
else
{
BLAnsi _c = 0;
BLAnsi _nbtmp[32] = { 0 };
BLS32 _chunksz;
_idx = 0;
while (1)
{
if (!_GbSystemRunning)
goto failed;
if (_Select(_sok, TRUE))
{
if (0 == recv(_sok, &_c, 1, 0))
break;
if (_c == '\n')
break;
else if (_c == '\r')
continue;
else
_nbtmp[_idx++] = _c;
}
}
_chunksz = atoi(_nbtmp);
_idx = 0;
while (_idx < (BLS32)_chunksz)
{
if (!_GbSystemRunning)
goto failed;
if (_Select(_sok, TRUE))
{
if (0 == recv(_sok, &_c, 1, 0))
break;
_Response[_idx++] = _c;
}
}
_Response[_idx] = 0;
}
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
if (_sok)
closesocket(_sok);
#else
if (_sok)
close(_sok);
#endif
return TRUE;
failed:
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
if (_sok)
closesocket(_sok);
#else
if (_sok)
close(_sok);
#endif
return FALSE;
}
BLBool
blNetAddDownloadList(IN BLAnsi* _Host, IN BLAnsi* _Localpath, OUT BLU32* _Taskid)
{
if (_PrNetworkMem->pDownList->nSize >= 64)
return FALSE;
*_Taskid = -1;
BLU32 _idx;
BLU32 _sz = (BLU32)strlen(_Host);
BLAnsi* _remoteurl = (BLAnsi*)malloc(_sz + 1);
strcpy(_remoteurl, _Host);
_remoteurl[_sz] = 0;
_sz = (BLU32)strlen(_Localpath);
BLAnsi* _localpath = (BLAnsi*)malloc(260);
memset(_localpath, 0, sizeof(BLAnsi) * 260);
strcpy(_localpath, blSysUserFolderDir());
strcat(_localpath, _Localpath);
FOREACH_ARRAY(BLAnsi*, _iter, _PrNetworkMem->pDownList)
{
if (strcmp(_iter, _Host) == 0)
{
free(_remoteurl);
free(_localpath);
return FALSE;
}
}
for (_idx = 0; _idx < strlen(_localpath); ++_idx)
{
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
if (_localpath[_idx] == '/')
{
BLAnsi _tmppath[256] = { 0 };
strncpy(_tmppath, _localpath, _idx);
CreateDirectoryA(_tmppath, NULL);
}
#else
if (_localpath[_idx] == '/')
{
BLAnsi _tmppath[256] = { 0 };
strncpy(_tmppath, _localpath, _idx);
mkdir(_tmppath, 0755);
}
#endif
}
for (_idx = (BLS32)strlen(_Host) - 1; _idx >= 1; --_idx)
{
if (_Host[_idx] == '/')
break;
}
BLAnsi _tmp[260] = { 0 };
strcpy(_tmp, _localpath);
strncat(_tmp + strlen(_tmp), _Host + _idx + 1, strlen(_Host) - _idx - 1);
#if defined(BL_PLATFORM_WIN32) || defined(BL_PLATFORM_UWP)
#ifdef WINAPI_FAMILY
WCHAR _wfilename[260] = { 0 };
MultiByteToWideChar(CP_UTF8, 0, _tmp, -1, _wfilename, sizeof(_wfilename));
HANDLE _fp = CreateFile2(_wfilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
#else
HANDLE _fp = CreateFileA(_tmp, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
if (FILE_INVALID_INTERNAL(_fp))
{
LARGE_INTEGER _li;
GetFileSizeEx(_fp, &_li);
BLU32 _filesz = _li.LowPart;
CloseHandle(_fp);
BLU32 _shouldsz = 0;
BLU32 _tmplen = (BLU32)strlen(_tmp);
_tmp[_tmplen] = '_';
_tmp[_tmplen + 1] = '1';
#ifdef WINAPI_FAMILY
memset(_wfilename, 0, sizeof(_wfilename));
MultiByteToWideChar(CP_UTF8, 0, _tmp, -1, _wfilename, sizeof(_wfilename));
_fp = CreateFile2(_wfilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
#else
_fp = CreateFileA(_tmp, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
if (FILE_INVALID_INTERNAL(_fp))
{
GetFileSizeEx(_fp, &_li);
_shouldsz += _li.LowPart;
CloseHandle(_fp);
}
_tmp[_tmplen + 1] = '2';
#ifdef WINAPI_FAMILY
memset(_wfilename, 0, sizeof(_wfilename));
MultiByteToWideChar(CP_UTF8, 0, _tmp, -1, _wfilename, sizeof(_wfilename));
_fp = CreateFile2(_wfilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
#else
_fp = CreateFileA(_tmp, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
if (_fp)
{
GetFileSizeEx(_fp, &_li);
_shouldsz += _li.LowPart;
CloseHandle(_fp);
}
_tmp[_tmplen + 1] = '3';
#ifdef WINAPI_FAMILY
memset(_wfilename, 0, sizeof(_wfilename));
MultiByteToWideChar(CP_UTF8, 0, _tmp, -1, _wfilename, sizeof(_wfilename));
_fp = CreateFile2(_wfilename, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, NULL);
#else
_fp = CreateFileA(_tmp, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
#endif
if (_fp)
{
GetFileSizeEx(_fp, &_li);
_shouldsz += _li.LowPart;
CloseHandle(_fp);
}
if ((_shouldsz == _filesz) || _filesz)
{
_tmp[_tmplen + 1] = '1';
DeleteFileA(_tmp);
_tmp[_tmplen + 1] = '2';
DeleteFileA(_tmp);
_tmp[_tmplen + 1] = '3';
DeleteFileA(_tmp);
free(_remoteurl);
free(_localpath);
return FALSE;
}
else
{
_tmp[_tmplen] = 0;
_tmp[_tmplen + 1] = 0;
DeleteFileA(_tmp);
}
}
#elif defined(BL_PLATFORM_LINUX) || defined(BL_PLATFORM_ANDROID) || defined(BL_PLATFORM_OSX) || defined(BL_PLATFORM_IOS)
FILE* _fp = fopen(_tmp, "rb");
if (FILE_INVALID_INTERNAL(_fp))
{
fseek(_fp, 0, SEEK_END);
BLU32 _filesz = (BLU32)ftell(_fp);
fclose(_fp);
BLU32 _shouldsz = 0;
BLU32 _tmplen = (BLU32)strlen(_tmp);
_tmp[_tmplen] = '_';
_tmp[_tmplen + 1] = '1';
_fp = fopen(_tmp, "rb");
if (_fp)
{
fseek(_fp, 0, SEEK_END);
_shouldsz += ftell(_fp);
fclose(_fp);
}
_tmp[_tmplen + 1] = '2';
_fp = fopen(_tmp, "rb");
if (_fp)
{
fseek(_fp, 0, SEEK_END);
_shouldsz += ftell(_fp);
fclose(_fp);
}
_tmp[_tmplen + 1] = '3';
_fp = fopen(_tmp, "rb");
if (_fp)
{
fseek(_fp, 0, SEEK_END);
_shouldsz += ftell(_fp);
fclose(_fp);
}
if ((_shouldsz == _filesz) || _filesz)
{
_tmp[_tmplen + 1] = '1';
remove(_tmp);
_tmp[_tmplen + 1] = '2';
remove(_tmp);
_tmp[_tmplen + 1] = '3';
remove(_tmp);
free(_remoteurl);
free(_localpath);
return FALSE;
}
else
{
_tmp[_tmplen] = 0;
_tmp[_tmplen + 1] = 0;
remove(_tmp);
}
}
#endif
blArrayPushBack(_PrNetworkMem->pDownList, _remoteurl);
blArrayPushBack(_PrNetworkMem->pLocalList, _localpath);
*_Taskid = blHashString((const BLUtf8*)_Host);
return TRUE;
}
BLVoid
blNetDownload()
{
#if defined(BL_PLATFORM_WEB)
const BLAnsi* _url = (const BLAnsi*)blArrayFrontElement(_PrNetworkMem->pDownList);
const BLAnsi* _local = (const BLAnsi*)blArrayFrontElement(_PrNetworkMem->pLocalList);
_PrNetworkMem->_PrCurDownHash = blHashString((const BLUtf8*)_url);
_PrNetworkMem->nCurDownSize = 0;
_PrNetworkMem->nCurDownTotal = 0;
emscripten_async_wget2_data(_url, "GET", NULL, NULL, 1, _OnWGetLoaded, _OnWGetError, _OnWGetProg);
#else
_PrNetworkMem->pDownMain = blGenThread(_NetDownMainThread, NULL, NULL);
blThreadRun(_PrNetworkMem->pDownMain);
#endif
}
BLVoid
blNetDownloadProgressQuery(OUT BLU32* _Curtask, OUT BLU32* _Progress, OUT BLU32 _Finish[64])
{
*_Curtask = _PrNetworkMem->_PrCurDownHash;
*_Progress = _PrNetworkMem->nCurDownSize * 100 / _PrNetworkMem->nCurDownTotal;
for (BLU32 _idx = 0; _idx < 64; ++_idx)
_Finish[_idx] = _PrNetworkMem->nFinish[_idx];
}
| 38,070 |
347 |
package org.ovirt.engine.core.dal.dbbroker;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import org.ovirt.engine.core.utils.crypt.EngineEncryptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DbFacadeUtils {
private static final Logger log = LoggerFactory.getLogger(DbFacadeUtils.class);
public static Date fromDate(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
return new Date(timestamp.getTime());
}
public static Object asSingleResult(List<?> list) {
return list.isEmpty() ? null : list.get(0);
}
public static String encryptPassword(String password) {
try {
return EngineEncryptionUtils.encrypt(password);
} catch (Exception e) {
throw new SecurityException(e);
}
}
public static String decryptPassword(String password) {
try {
return EngineEncryptionUtils.decrypt(password);
} catch (Exception e) {
log.debug("Failed to decrypt password", e);
return password;
}
}
}
| 465 |
807 |
<filename>src/main/java/dev/jbang/Main.java
package dev.jbang;
import java.util.ArrayList;
import java.util.List;
import dev.jbang.cli.JBang;
import picocli.CommandLine;
public class Main {
public static void main(String... args) {
CommandLine cli = JBang.getCommandLine();
args = handleDefaultRun(cli.getCommandSpec(), args);
int exitcode = cli.execute(args);
System.exit(exitcode);
}
private static String[] handleDefaultRun(CommandLine.Model.CommandSpec spec, String[] args) {
List<String> leadingOpts = new ArrayList<>();
List<String> remainingArgs = new ArrayList<>();
boolean foundParam = false;
for (String arg : args) {
if (!arg.startsWith("-") || arg.equals("-") || arg.equals("--")) {
foundParam = true;
}
if (foundParam) {
remainingArgs.add(arg);
} else {
leadingOpts.add(arg);
}
}
// Check if we have a parameter and it's not the same as any of the subcommand
// names
if (!remainingArgs.isEmpty() && !spec.subcommands().containsKey(remainingArgs.get(0))) {
List<String> result = new ArrayList<>();
result.add("run");
result.addAll(leadingOpts);
result.addAll(remainingArgs);
args = result.toArray(args);
}
return args;
}
}
| 459 |
678 |
<filename>iOSOpenDev/frameworks/AppStoreUI.framework/Headers/ASApplicationInfoListingViewItem.h<gh_stars>100-1000
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/AppStoreUI.framework/AppStoreUI
*/
#import <AppStoreUI/XXUnknownSuperclass.h>
#import <AppStoreUI/AppStoreUI-Structs.h>
@class UIImage, NSString, NSArray;
@interface ASApplicationInfoListingViewItem : XXUnknownSuperclass {
UIImage *_image; // 4 = 0x4
CGSize _imageSize; // 8 = 0x8
NSString *_label; // 16 = 0x10
CGSize _labelSize; // 20 = 0x14
NSArray *_values; // 28 = 0x1c
float _valueHeight; // 32 = 0x20
float _valueWidth; // 36 = 0x24
unsigned _isCompact : 1; // 40 = 0x28
unsigned _wrapsIfNecessary : 1; // 40 = 0x28
}
@property(assign, nonatomic) float valueWidth; // G=0xefe5; S=0xee19; @synthesize=_valueWidth
@property(retain, nonatomic) NSArray *values; // G=0xefd5; S=0xedc5; @synthesize=_values
@property(assign, nonatomic) BOOL wrapsIfNecessary; // G=0xef31; S=0xee39;
@property(readonly, assign, nonatomic) int type; // G=0xeec9;
@property(readonly, assign, nonatomic) BOOL shouldCompact; // G=0xee85;
@property(readonly, assign, nonatomic) CGSize labelSize; // G=0xefb9; @synthesize=_labelSize
@property(retain, nonatomic) NSString *label; // G=0xefa9; S=0xed21; @synthesize=_label
@property(assign, nonatomic) CGSize imageSize; // G=0xef79; S=0xef95; @synthesize=_imageSize
@property(retain, nonatomic) UIImage *image; // G=0xef45; S=0xef55; @synthesize=_image
@property(readonly, assign, nonatomic) float height; // G=0xea25;
@property(assign, nonatomic, getter=isCompact) BOOL compact; // G=0xed0d; S=0xee61;
@property(readonly, assign, nonatomic) NSString *combinedValues; // G=0xe9f1;
// declared property getter: - (float)valueWidth; // 0xefe5
// declared property getter: - (id)values; // 0xefd5
// declared property getter: - (CGSize)labelSize; // 0xefb9
// declared property getter: - (id)label; // 0xefa9
// declared property setter: - (void)setImageSize:(CGSize)size; // 0xef95
// declared property getter: - (CGSize)imageSize; // 0xef79
// declared property setter: - (void)setImage:(id)image; // 0xef55
// declared property getter: - (id)image; // 0xef45
// declared property getter: - (BOOL)wrapsIfNecessary; // 0xef31
// declared property getter: - (int)type; // 0xeec9
// declared property getter: - (BOOL)shouldCompact; // 0xee85
// declared property setter: - (void)setCompact:(BOOL)compact; // 0xee61
// declared property setter: - (void)setWrapsIfNecessary:(BOOL)necessary; // 0xee39
// declared property setter: - (void)setValueWidth:(float)width; // 0xee19
// declared property setter: - (void)setValues:(id)values; // 0xedc5
// declared property setter: - (void)setLabel:(id)label; // 0xed21
// declared property getter: - (BOOL)isCompact; // 0xed0d
// declared property getter: - (float)height; // 0xea25
// declared property getter: - (id)combinedValues; // 0xe9f1
- (void)dealloc; // 0xe965
- (id)initWithLabel:(id)label values:(id)values; // 0xe91d
@end
| 1,183 |
1,256 |
#include <all_far.h>
#pragma hdrstop
#include "Int.h"
//--------------------------------------------------------------------------------
BOOL Connection::SetType(int type)
{
switch(type)
{
case TYPE_A:
return setascii();
case TYPE_I:
return setbinary();
case TYPE_E:
return setebcdic();
}
return FALSE;
}
void Connection::reset()
{
struct fd_set mask;
int nfnd;
do
{
FD_ZERO(&mask);
FD_SET(cin, &mask); /*!*/
nfnd = empty(&mask,0);
if(nfnd < 0)
{
Log(("!reset"));
code = -1;
lostpeer();
}
else if(nfnd)
getreply(0);
}
while(nfnd > 0);
}
void Connection::AbortAllRequest(int BrkFlag)
{
if(BrkFlag)
brk_flag = TRUE;
else
{
scClose(data_peer,-1);
scClose(cmd_peer,-1);
}
}
int Connection::empty(struct fd_set *mask, int sec)
{
struct timeval t;
t.tv_sec = (long) sec;
t.tv_usec = 0;
return select(FD_SETSIZE,mask,NULL,NULL,&t);
}
//--------------------------------------------------------------------------------
/*VARARGS1*/
int Connection::command(const char *fmt, ...)
{
PROC(("Connection::command", "%s", fmt));
va_list ap;
int r;
String buffer;
if(!cout)
{
Log(("!control connection for command [%s]",fmt));
code = -1;
return (0);
}
va_start(ap, fmt);
buffer.vprintf(fmt, ap);
va_end(ap);
buffer.cat("\r\n");
if(!fputsSocket(buffer.c_str(), cout))
{
Log(("!puts"));
lostpeer();
code = -1;
return RPL_ERROR;
}
cpend = 1;
r = getreply(StrCmp(fmt,Opt.cmdQuit) == 0);
Log(("reply rc=%d",r));
#if 0/*?*/
while(r != RPL_ERROR &&
!brk_flag &&
((StrCmp(fmt,Opt.cmdPwd)==0 && (reply_string.Chr('\"') == -1) ||
!isdigit(reply_string[0]) ||
!isdigit(reply_string[1]) ||
!isdigit(reply_string[2]) ||
!isspace(reply_string[3]))))
{
r = getreply(FALSE);
}
#endif
Log(("rc=%d",r));
return r;
}
//--------------------------------------------------------------------------------
int Connection::getreply(BOOL expecteof, DWORD tm)
{
int c, n, dig;
int originalcode = 0,
continuation = 0,
pflag = 0;
char *pt = pasv;
if(cin == INVALID_SOCKET)
{
Log(("gr: inv socket"));
code = 421;
return RPL_ERROR;
}
for(;;)
{
dig = n = code = 0;
reply_string = "";
//Read line
while((c=fgetcSocket(cin,tm)) != '\n')
{
if(c == RPL_TIMEOUT)
{
return RPL_TIMEOUT;
}
if(!c)
{
Log(("gr conn closed"));
lostpeer();
code = 421;
return RPL_ERROR;
}
if(!dig)
{
// handle telnet commands
if(c == ffIAC)
{
switch(c = fgetcSocket(cin))
{
case ffWILL:
case ffWONT:
c = fgetcSocket(cin);
fprintfSocket(cout, "%c%c%c",ffIAC,ffDONT,c);
break;
case ffDO:
case ffDONT:
c = fgetcSocket(cin);
fprintfSocket(cout, "%c%c%c",ffIAC,ffWONT,c);
break;
default:
break;
}
continue;
}
if(!c || c == ffEOF)
{
Log(("gr EOF: c: %d (%d)",c,expecteof));
if(expecteof)
{
code = 221;
return RPL_OK;
}
lostpeer();
code = 421;
return RPL_TRANSIENT;
}
}
dig++;
if(dig < 4 && isdigit(c))
code = code * 10 + (c - '0');
if(!pflag && code == 227)
pflag = 1;
if(dig > 4 && pflag == 1 && isdigit(c))
pflag = 2;
if(pflag == 2)
{
if(c != '\r' && c != ')')
*pt++ = c;
else
{
*pt = '\0';
pflag = 3;
}
}
if(dig == 4 && c == '-')
{
if(continuation)
code = 0;
continuation++;
}
if(n == 0)
n = c;
reply_string.Add((char)c);
}
AddCmdLine(NULL);
if(continuation && code != originalcode)
{
//Log(( "Continue: Cont: %d Code: %d Orig: %d", continuation,code,originalcode ));
if(originalcode == 0)
originalcode = code;
continue;
}
if(n != '1')
cpend = 0;
if(code == 421 || originalcode == 421)
{
//Log(( "Code=%d, Orig=%d -> lostpeer",code,originalcode ));
lostpeer();
}
//Log(( "rc = %d", (n - '0') ));
return (n - '0');
}
}
//--------------------------------------------------------------------------------
void Connection::pswitch(int flag)
{
struct comvars *ip, *op;
if(flag)
{
if(proxy) return;
ip = &tmpstruct;
op = &proxstruct;
proxy++;
}
else
{
if(!proxy) return;
ip = &proxstruct;
op = &tmpstruct;
proxy = 0;
}
ip->connect = connected;
connected = op->connect;
if(hostname)
{
StrCpy(ip->name, hostname, ARRAYSIZE(ip->name) - 1);
ip->name[strlen(ip->name)] = '\0';
}
else
ip->name[0] = 0;
StrCpy(hostname,op->name,ARRAYSIZE(hostname));
ip->hctl = hisctladdr;
hisctladdr = op->hctl;
ip->mctl = myctladdr;
myctladdr = op->mctl;
ip->in = cin; // What the hell am I looking at...?
cin = op->in;
ip->out = cout; // Same again...
cout = op->out;
ip->tpe = type;
type = op->tpe;
if(!type)
type = TYPE_A;
ip->cpnd = cpend;
cpend = op->cpnd;
ip->sunqe = sunique;
sunique = op->sunqe;
ip->runqe = runique;
runique = op->runqe;
}
//--------------------------------------------------------------------------------
void Connection::proxtrans(char *cmd, char *local, char *remote)
{
int tmptype, oldtype = 0, secndflag = 0, nfnd;
char *cmd2;
struct fd_set mask;
if(StrCmp(cmd,Opt.cmdRetr) != 0)
cmd2 = Opt.cmdRetr;
else
cmd2 = runique ? Opt.cmdPutUniq : Opt.cmdStor;
if(command(Opt.cmdPasv) != RPL_COMPLETE)
{
ConnectMessage(MProxyNoThird,NULL,-MOk);
return;
}
tmptype = type;
pswitch(0);
if(!connected)
{
ConnectMessage(MNotConnected,NULL,-MOk);
pswitch(1);
code = -1;
return;
}
if(type != tmptype)
{
oldtype = type;
SetType(tmptype);
}
if(command("%s %s",Opt.cmdPort,pasv) != RPL_COMPLETE)
{
SetType(oldtype);
pswitch(1);
return;
}
if(command("%s %s", cmd, remote) != RPL_PRELIM)
{
SetType(oldtype);
pswitch(1);
return;
}
pswitch(1);
secndflag++;
if(command("%s %s", cmd2, local) != RPL_PRELIM)
goto abort;
getreply(0);
pswitch(0);
getreply(0);
SetType(oldtype);
pswitch(1);
return;
abort:
if(StrCmp(cmd,Opt.cmdRetr) != 0 && !proxy)
pswitch(1);
else if(StrCmp(cmd,Opt.cmdRetr) == 0 && proxy)
pswitch(0);
if(!cpend && !secndflag) /* only here if cmd = "STOR" (proxy=1) */
{
if(command("%s %s", cmd2, local) != RPL_PRELIM)
{
pswitch(0);
SetType(oldtype);
if(cpend)
{
char msg[2];
fprintfSocket(cout,"%c%c",ffIAC,ffIP);
*msg = ffIAC;
*(msg+1) = ffDM;
if(nb_send(&cout,msg,2,MSG_OOB) != RPL_COMPLETE)
{
Log(("!send [%s:%d]",__FILE__ , __LINE__));
}
fprintfSocket(cout,"ABOR\r\n");
FD_ZERO(&mask);
FD_SET(cin, &mask); /*!*/ // Chris: Need to correct this
if((nfnd = empty(&mask,10)) <= 0)
{
Log(("abort"));
lostpeer();
}
if(getreply(0) != RPL_ERROR)
getreply(0);
else
{
lostpeer();
return;
}
}
}
pswitch(1);
return;
}
if(cpend)
{
char msg[2];
fprintfSocket(cout,"%c%c",ffIAC,ffIP);
*msg = ffIAC;
*(msg+1) = ffDM;
if(nb_send(&cout,msg,2,MSG_OOB) != RPL_COMPLETE)
{
Log(("!send [%s:%d]",__FILE__ , __LINE__));
}
fprintfSocket(cout,"ABOR\r\n");
FD_ZERO(&mask);
/*!*/
FD_SET(cin, &mask); // Chris: Need to correct this...
if((nfnd = empty(&mask,10)) <= 0)
{
if(nfnd < 0)
{
Log(("abort"));
}
lostpeer();
}
if(getreply(0) != RPL_ERROR)
getreply(0);
else
{
lostpeer();
return;
}
}
pswitch(!proxy);
if(!cpend && !secndflag) /* only if cmd = "RETR" (proxy=1) */
{
if(command("%s %s", cmd2, local) != RPL_PRELIM)
{
pswitch(0);
SetType(oldtype);
if(cpend)
{
char msg[2];
fprintfSocket(cout,"%c%c",ffIAC,ffIP);
*msg = ffIAC;
*(msg+1) = ffDM;
if(nb_send(&cout,msg,2,MSG_OOB) != RPL_COMPLETE)
{
Log(("!send [%s:%d]",__FILE__ , __LINE__));
}
fprintfSocket(cout,"ABOR\r\n");
FD_ZERO(&mask);
/*!*/
FD_SET(cin, &mask); // Chris:
if((nfnd = empty(&mask,10)) <= 0)
{
if(nfnd < 0)
{
Log(("abort"));
}
lostpeer();
}
if(getreply(0) != RPL_ERROR)
getreply(0);
else
{
lostpeer();
return;
}
}
pswitch(1);
return;
}
}
if(cpend)
{
char msg[2];
fprintfSocket(cout,"%c%c",ffIAC,ffIP);
*msg = ffIAC;
*(msg+1) = ffDM;
if(nb_send(&cout,msg,2,MSG_OOB) != RPL_COMPLETE)
{
Log(("!send [%s:%d]",__FILE__ , __LINE__));
}
fprintfSocket(cout,"ABOR\r\n");
FD_ZERO(&mask);
/*!*/
FD_SET(cin, &mask);
if((nfnd = empty(&mask,10)) <= 0)
{
if(nfnd < 0)
{
Log(("abort"));
}
lostpeer();
}
if(getreply(0) != RPL_ERROR)
getreply(0);
else
{
lostpeer();
return;
}
}
pswitch(!proxy);
if(cpend)
{
FD_ZERO(&mask);
/*!*/
FD_SET(cin, &mask); // Chris:
if((nfnd = empty(&mask,10)) <= 0)
{
if(nfnd < 0)
{
Log(("abort"));
}
lostpeer();
}
if(getreply(0) != RPL_ERROR)
getreply(0);
else
{
lostpeer();
return;
}
}
if(proxy)
pswitch(0);
SetType(oldtype);
pswitch(1);
}
| 4,680 |
735 |
<filename>xstream/src/test/com/thoughtworks/xstream/mapper/FieldAliasingMapperTest.java
/*
* Copyright (C) 2005 <NAME>.
* Copyright (C) 2006, 2007 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 09. April 2005 by <NAME>
*/
package com.thoughtworks.xstream.mapper;
import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.acceptance.objects.Software;
public class FieldAliasingMapperTest extends AbstractAcceptanceTest {
public void testAllowsIndividualFieldsToBeAliased() {
Software in = new Software("ms", "word");
xstream.alias("software", Software.class);
xstream.aliasField("CUSTOM-VENDOR", Software.class, "vendor");
xstream.aliasField("CUSTOM-NAME", Software.class, "name");
String expectedXml = "" +
"<software>\n" +
" <CUSTOM-VENDOR>ms</CUSTOM-VENDOR>\n" +
" <CUSTOM-NAME>word</CUSTOM-NAME>\n" +
"</software>";
assertBothWays(in, expectedXml);
}
}
| 459 |
303 |
<reponame>ofZach/landlinesApp<gh_stars>100-1000
{"id":5244,"line-1":"Free State","line-2":"South Africa","attribution":"©2015 CNES / Astrium, DigitalGlobe","url":"https://www.google.com/maps/@-29.152911,24.681602,17z/data=!3m1!1e3"}
| 96 |
310 |
{
"name": "SP-202 Dr. Sample",
"description": "An audio sampler.",
"url": "http://www.vintagesynth.com/roland/sp202.php"
}
| 53 |
356 |
/*
* Copyright (C) 2014 University of South Florida (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onebusaway.android.report.connection;
import android.os.AsyncTask;
import edu.usf.cutr.open311client.Open311;
import edu.usf.cutr.open311client.models.ServiceDescription;
import edu.usf.cutr.open311client.models.ServiceDescriptionRequest;
/**
* Async task for getting service description of the given Open311 service
*
* @author <NAME>
*/
public class ServiceDescriptionTask extends AsyncTask<Void, Integer, ServiceDescription> {
private ServiceDescriptionRequest mServiceDescriptionRequest;
private Open311 mOpen311;
private Callback callback;
public interface Callback {
/**
* Called when the Open311 ServiceDescriptionTask is complete
*
* @param serviceDescription contains the detailed information of the given service
*/
void onServiceDescriptionTaskCompleted(ServiceDescription serviceDescription);
}
public ServiceDescriptionTask(ServiceDescriptionRequest serviceDescriptionRequest,
Open311 open311, Callback callback) {
this.callback = callback;
this.mServiceDescriptionRequest = serviceDescriptionRequest;
this.mOpen311 = open311;
}
@Override
protected ServiceDescription doInBackground(Void... params) {
return mOpen311.getServiceDescription(mServiceDescriptionRequest);
}
@Override
protected void onPostExecute(ServiceDescription serviceDescription) {
callback.onServiceDescriptionTaskCompleted(serviceDescription);
}
}
| 648 |
15,947 |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Manages all plugins."""
import importlib
import importlib.machinery
import importlib.util
import inspect
import logging
import os
import sys
import types
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Type
try:
import importlib_metadata
except ImportError:
from importlib import metadata as importlib_metadata
from airflow import settings
from airflow.utils.entry_points import entry_points_with_dist
from airflow.utils.file import find_path_from_directory
from airflow.utils.module_loading import as_importable_string
if TYPE_CHECKING:
from airflow.hooks.base import BaseHook
from airflow.timetables.base import Timetable
log = logging.getLogger(__name__)
import_errors: Dict[str, str] = {}
plugins = None # type: Optional[List[AirflowPlugin]]
# Plugin components to integrate as modules
registered_hooks: Optional[List['BaseHook']] = None
macros_modules: Optional[List[Any]] = None
executors_modules: Optional[List[Any]] = None
# Plugin components to integrate directly
admin_views: Optional[List[Any]] = None
flask_blueprints: Optional[List[Any]] = None
menu_links: Optional[List[Any]] = None
flask_appbuilder_views: Optional[List[Any]] = None
flask_appbuilder_menu_links: Optional[List[Any]] = None
global_operator_extra_links: Optional[List[Any]] = None
operator_extra_links: Optional[List[Any]] = None
registered_operator_link_classes: Optional[Dict[str, Type]] = None
timetable_classes: Optional[Dict[str, Type["Timetable"]]] = None
"""Mapping of class names to class of OperatorLinks registered by plugins.
Used by the DAG serialization code to only allow specific classes to be created
during deserialization
"""
PLUGINS_ATTRIBUTES_TO_DUMP = {
"hooks",
"executors",
"macros",
"flask_blueprints",
"appbuilder_views",
"appbuilder_menu_items",
"global_operator_extra_links",
"operator_extra_links",
"source",
}
class AirflowPluginSource:
"""Class used to define an AirflowPluginSource."""
def __str__(self):
raise NotImplementedError
def __html__(self):
raise NotImplementedError
class PluginsDirectorySource(AirflowPluginSource):
"""Class used to define Plugins loaded from Plugins Directory."""
def __init__(self, path):
self.path = os.path.relpath(path, settings.PLUGINS_FOLDER)
def __str__(self):
return f"$PLUGINS_FOLDER/{self.path}"
def __html__(self):
return f"<em>$PLUGINS_FOLDER/</em>{self.path}"
class EntryPointSource(AirflowPluginSource):
"""Class used to define Plugins loaded from entrypoint."""
def __init__(self, entrypoint: importlib_metadata.EntryPoint, dist: importlib_metadata.Distribution):
self.dist = dist.metadata['name']
self.version = dist.version
self.entrypoint = str(entrypoint)
def __str__(self):
return f"{self.dist}=={self.version}: {self.entrypoint}"
def __html__(self):
return f"<em>{self.dist}=={self.version}:</em> {self.entrypoint}"
class AirflowPluginException(Exception):
"""Exception when loading plugin."""
class AirflowPlugin:
"""Class used to define AirflowPlugin."""
name: Optional[str] = None
source: Optional[AirflowPluginSource] = None
hooks: List[Any] = []
executors: List[Any] = []
macros: List[Any] = []
admin_views: List[Any] = []
flask_blueprints: List[Any] = []
menu_links: List[Any] = []
appbuilder_views: List[Any] = []
appbuilder_menu_items: List[Any] = []
# A list of global operator extra links that can redirect users to
# external systems. These extra links will be available on the
# task page in the form of buttons.
#
# Note: the global operator extra link can be overridden at each
# operator level.
global_operator_extra_links: List[Any] = []
# A list of operator extra links to override or add operator links
# to existing Airflow Operators.
# These extra links will be available on the task page in form of
# buttons.
operator_extra_links: List[Any] = []
# A list of timetable classes that can be used for DAG scheduling.
timetables: List[Type["Timetable"]] = []
@classmethod
def validate(cls):
"""Validates that plugin has a name."""
if not cls.name:
raise AirflowPluginException("Your plugin needs a name.")
@classmethod
def on_load(cls, *args, **kwargs):
"""
Executed when the plugin is loaded.
This method is only called once during runtime.
:param args: If future arguments are passed in on call.
:param kwargs: If future arguments are passed in on call.
"""
def is_valid_plugin(plugin_obj):
"""
Check whether a potential object is a subclass of
the AirflowPlugin class.
:param plugin_obj: potential subclass of AirflowPlugin
:return: Whether or not the obj is a valid subclass of
AirflowPlugin
"""
global plugins
if (
inspect.isclass(plugin_obj)
and issubclass(plugin_obj, AirflowPlugin)
and (plugin_obj is not AirflowPlugin)
):
plugin_obj.validate()
return plugin_obj not in plugins
return False
def register_plugin(plugin_instance):
"""
Start plugin load and register it after success initialization
:param plugin_instance: subclass of AirflowPlugin
"""
global plugins
plugin_instance.on_load()
plugins.append(plugin_instance)
def load_entrypoint_plugins():
"""
Load and register plugins AirflowPlugin subclasses from the entrypoints.
The entry_point group should be 'airflow.plugins'.
"""
global import_errors
log.debug("Loading plugins from entrypoints")
for entry_point, dist in entry_points_with_dist('airflow.plugins'):
log.debug('Importing entry_point plugin %s', entry_point.name)
try:
plugin_class = entry_point.load()
if not is_valid_plugin(plugin_class):
continue
plugin_instance = plugin_class()
plugin_instance.source = EntryPointSource(entry_point, dist)
register_plugin(plugin_instance)
except Exception as e:
log.exception("Failed to import plugin %s", entry_point.name)
import_errors[entry_point.module] = str(e)
def load_plugins_from_plugin_directory():
"""Load and register Airflow Plugins from plugins directory"""
global import_errors
log.debug("Loading plugins from directory: %s", settings.PLUGINS_FOLDER)
for file_path in find_path_from_directory(settings.PLUGINS_FOLDER, ".airflowignore"):
if not os.path.isfile(file_path):
continue
mod_name, file_ext = os.path.splitext(os.path.split(file_path)[-1])
if file_ext != '.py':
continue
try:
loader = importlib.machinery.SourceFileLoader(mod_name, file_path)
spec = importlib.util.spec_from_loader(mod_name, loader)
mod = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = mod
loader.exec_module(mod)
log.debug('Importing plugin module %s', file_path)
for mod_attr_value in (m for m in mod.__dict__.values() if is_valid_plugin(m)):
plugin_instance = mod_attr_value()
plugin_instance.source = PluginsDirectorySource(file_path)
register_plugin(plugin_instance)
except Exception as e:
log.exception('Failed to import plugin %s', file_path)
import_errors[file_path] = str(e)
def make_module(name: str, objects: List[Any]):
"""Creates new module."""
if not objects:
return None
log.debug('Creating module %s', name)
name = name.lower()
module = types.ModuleType(name)
module._name = name.split('.')[-1] # type: ignore
module._objects = objects # type: ignore
module.__dict__.update((o.__name__, o) for o in objects)
return module
def ensure_plugins_loaded():
"""
Load plugins from plugins directory and entrypoints.
Plugins are only loaded if they have not been previously loaded.
"""
from airflow.stats import Stats
global plugins, registered_hooks
if plugins is not None:
log.debug("Plugins are already loaded. Skipping.")
return
if not settings.PLUGINS_FOLDER:
raise ValueError("Plugins folder is not set")
log.debug("Loading plugins")
with Stats.timer() as timer:
plugins = []
registered_hooks = []
load_plugins_from_plugin_directory()
load_entrypoint_plugins()
# We don't do anything with these for now, but we want to keep track of
# them so we can integrate them in to the UI's Connection screens
for plugin in plugins:
registered_hooks.extend(plugin.hooks)
num_loaded = len(plugins)
if num_loaded > 0:
log.debug("Loading %d plugin(s) took %.2f seconds", num_loaded, timer.duration)
def initialize_web_ui_plugins():
"""Collect extension points for WEB UI"""
global plugins
global flask_blueprints
global flask_appbuilder_views
global flask_appbuilder_menu_links
if (
flask_blueprints is not None
and flask_appbuilder_views is not None
and flask_appbuilder_menu_links is not None
):
return
ensure_plugins_loaded()
if plugins is None:
raise AirflowPluginException("Can't load plugins.")
log.debug("Initialize Web UI plugin")
flask_blueprints = []
flask_appbuilder_views = []
flask_appbuilder_menu_links = []
for plugin in plugins:
flask_appbuilder_views.extend(plugin.appbuilder_views)
flask_appbuilder_menu_links.extend(plugin.appbuilder_menu_items)
flask_blueprints.extend([{'name': plugin.name, 'blueprint': bp} for bp in plugin.flask_blueprints])
if (plugin.admin_views and not plugin.appbuilder_views) or (
plugin.menu_links and not plugin.appbuilder_menu_items
):
log.warning(
"Plugin \'%s\' may not be compatible with the current Airflow version. "
"Please contact the author of the plugin.",
plugin.name,
)
def initialize_extra_operators_links_plugins():
"""Creates modules for loaded extension from extra operators links plugins"""
global global_operator_extra_links
global operator_extra_links
global registered_operator_link_classes
if (
global_operator_extra_links is not None
and operator_extra_links is not None
and registered_operator_link_classes is not None
):
return
ensure_plugins_loaded()
if plugins is None:
raise AirflowPluginException("Can't load plugins.")
log.debug("Initialize extra operators links plugins")
global_operator_extra_links = []
operator_extra_links = []
registered_operator_link_classes = {}
for plugin in plugins:
global_operator_extra_links.extend(plugin.global_operator_extra_links)
operator_extra_links.extend(list(plugin.operator_extra_links))
registered_operator_link_classes.update(
{
f"{link.__class__.__module__}.{link.__class__.__name__}": link.__class__
for link in plugin.operator_extra_links
}
)
def initialize_timetables_plugins():
"""Collect timetable classes registered by plugins."""
global timetable_classes
if timetable_classes is not None:
return
ensure_plugins_loaded()
if plugins is None:
raise AirflowPluginException("Can't load plugins.")
log.debug("Initialize extra timetables plugins")
timetable_classes = {
as_importable_string(timetable_class): timetable_class
for plugin in plugins
for timetable_class in plugin.timetables
}
def integrate_executor_plugins() -> None:
"""Integrate executor plugins to the context."""
global plugins
global executors_modules
if executors_modules is not None:
return
ensure_plugins_loaded()
if plugins is None:
raise AirflowPluginException("Can't load plugins.")
log.debug("Integrate executor plugins")
executors_modules = []
for plugin in plugins:
if plugin.name is None:
raise AirflowPluginException("Invalid plugin name")
plugin_name: str = plugin.name
executors_module = make_module('airflow.executors.' + plugin_name, plugin.executors)
if executors_module:
executors_modules.append(executors_module)
sys.modules[executors_module.__name__] = executors_module
def integrate_macros_plugins() -> None:
"""Integrates macro plugins."""
global plugins
global macros_modules
from airflow import macros
if macros_modules is not None:
return
ensure_plugins_loaded()
if plugins is None:
raise AirflowPluginException("Can't load plugins.")
log.debug("Integrate DAG plugins")
macros_modules = []
for plugin in plugins:
if plugin.name is None:
raise AirflowPluginException("Invalid plugin name")
macros_module = make_module(f'airflow.macros.{plugin.name}', plugin.macros)
if macros_module:
macros_modules.append(macros_module)
sys.modules[macros_module.__name__] = macros_module
# Register the newly created module on airflow.macros such that it
# can be accessed when rendering templates.
setattr(macros, plugin.name, macros_module)
def get_plugin_info(attrs_to_dump: Optional[List[str]] = None) -> List[Dict[str, Any]]:
"""
Dump plugins attributes
:param attrs_to_dump: A list of plugin attributes to dump
:type attrs_to_dump: List
"""
ensure_plugins_loaded()
integrate_executor_plugins()
integrate_macros_plugins()
initialize_web_ui_plugins()
initialize_extra_operators_links_plugins()
if not attrs_to_dump:
attrs_to_dump = PLUGINS_ATTRIBUTES_TO_DUMP
plugins_info = []
if plugins:
for plugin in plugins:
info = {"name": plugin.name}
info.update({n: getattr(plugin, n) for n in attrs_to_dump})
plugins_info.append(info)
return plugins_info
| 5,522 |
410 |
<filename>Source/TestBase/CUDA.h
#ifndef _CUDA_H_INCLUDED_
#define _CUDA_H_INCLUDED_
/*
====================================================================================================
CUDA
====================================================================================================
*/
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_runtime_api.h>
class MyCuda {
public:
static bool Init();
static void Shutdown();
static int driverVersion;
static int runtimeVersion;
static cudaDeviceProp deviceProp[2];
};
#define _CheckCudaError() CheckCudaError(__FILE__, __LINE__)
void CheckCudaError(const char *file, const int line);
#include "cuda_kernels.cuh"
#endif // _CUDA_H_INCLUDED_
| 229 |
1,602 |
<filename>third-party/gmp/gmp-src/mini-gmp/tests/t-mpq_muldiv.c<gh_stars>1000+
/*
Copyright 2012, 2013, 2018 Free Software Foundation, Inc.
This file is part of the GNU MP Library test suite.
The GNU MP Library test suite is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
The GNU MP Library test suite is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with
the GNU MP Library test suite. If not, see https://www.gnu.org/licenses/. */
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "testutils.h"
#include "../mini-mpq.h"
#define MAXBITS 300
#define COUNT 10000
static void
_mpq_set_zz (mpq_t q, mpz_t n, mpz_t d)
{
if (mpz_fits_ulong_p (d) && mpz_fits_slong_p (n))
{
mpq_set_si (q, mpz_get_si (n), mpz_get_ui (d));
}
else if (mpz_fits_ulong_p (d) && mpz_fits_ulong_p (n))
{
mpq_set_ui (q, mpz_get_ui (n), mpz_get_ui (d));
}
else
{
mpq_set_num (q, n);
mpq_set_den (q, d);
}
mpq_canonicalize (q);
}
void
testmain (int argc, char **argv)
{
unsigned i;
mpz_t an, bn, rn, ad, bd, rd;
mpq_t aq, bq, refq, resq;
mpz_init (an);
mpz_init (bn);
mpz_init (rn);
mpz_init (ad);
mpz_init (bd);
mpz_init (rd);
mpq_init (aq);
mpq_init (bq);
mpq_init (refq);
mpq_init (resq);
for (i = 0; i < COUNT; i++)
{
mini_random_op3 (OP_MUL, MAXBITS, an, bn, rn);
do {
mini_random_op3 (OP_MUL, MAXBITS, ad, bd, rd);
} while (mpz_sgn (rd) == 0);
_mpq_set_zz (aq, an, ad);
_mpq_set_zz (bq, bn, bd);
_mpq_set_zz (refq, rn, rd);
mpq_mul (resq, aq, bq);
if (!mpq_equal (resq, refq))
{
fprintf (stderr, "mpq_mul failed [%i]:\n", i);
dump ("an", an);
dump ("ad", ad);
dump ("bn", bn);
dump ("bd", bd);
dump ("refn", rn);
dump ("refd", rd);
dump ("resn", mpq_numref (resq));
dump ("resd", mpq_denref (resq));
abort ();
}
if (mpq_sgn (refq) != 0)
{
mpq_set_ui (resq, ~6, 8);
mpq_inv (aq, aq);
mpq_div (resq, aq, bq);
mpq_inv (resq, resq);
if (!mpq_equal (resq, refq))
{
fprintf (stderr, "mpq_div failed [%i]:\n", i);
dump ("an", an);
dump ("ad", ad);
dump ("bn", bn);
dump ("bd", bd);
dump ("refn", rn);
dump ("refd", rd);
dump ("resn", mpq_numref (resq));
dump ("resd", mpq_denref (resq));
abort ();
}
mpq_swap (bq, aq);
mpq_div (resq, aq, bq);
if (!mpq_equal (resq, refq))
{
fprintf (stderr, "mpq_swap failed [%i]:\n", i);
dump ("an", an);
dump ("ad", ad);
dump ("bn", bn);
dump ("bd", bd);
dump ("refn", rn);
dump ("refd", rd);
dump ("resn", mpq_numref (resq));
dump ("resd", mpq_denref (resq));
abort ();
}
}
mpq_set (resq, aq);
mpq_neg (bq, aq);
mpq_abs (refq, aq);
if (mpq_equal (refq, resq))
mpq_add (resq, refq, bq);
else
mpq_add (resq, refq, resq);
mpq_set_ui (refq, 0, 1);
if (!mpq_equal (resq, refq))
{
fprintf (stderr, "mpq_abs failed [%i]:\n", i);
dump ("an", an);
dump ("ad", ad);
dump ("resn", mpq_numref (resq));
dump ("resd", mpq_denref (resq));
abort ();
}
mpq_mul (resq, aq, aq);
mpq_mul (refq, aq, bq); /* now bq = - aq */
mpq_neg (refq, refq);
if (!mpq_equal (resq, refq))
{
fprintf (stderr, "mpq_mul(sqr) failed [%i]:\n", i);
dump ("an", an);
dump ("ad", ad);
dump ("bn", bn);
dump ("bd", bd);
dump ("refn", rn);
dump ("refd", rd);
dump ("resn", mpq_numref (resq));
dump ("resd", mpq_denref (resq));
abort ();
}
}
mpz_clear (an);
mpz_clear (bn);
mpz_clear (rn);
mpz_clear (ad);
mpz_clear (bd);
mpz_clear (rd);
mpq_clear (aq);
mpq_clear (bq);
mpq_clear (refq);
mpq_clear (resq);
}
| 2,114 |
61,676 |
import unittest
from unittest import mock
from django.core.exceptions import ValidationError
class TestValidationError(unittest.TestCase):
def test_messages_concatenates_error_dict_values(self):
message_dict = {}
exception = ValidationError(message_dict)
self.assertEqual(sorted(exception.messages), [])
message_dict['field1'] = ['E1', 'E2']
exception = ValidationError(message_dict)
self.assertEqual(sorted(exception.messages), ['E1', 'E2'])
message_dict['field2'] = ['E3', 'E4']
exception = ValidationError(message_dict)
self.assertEqual(sorted(exception.messages), ['E1', 'E2', 'E3', 'E4'])
def test_eq(self):
error1 = ValidationError('message')
error2 = ValidationError('message', code='my_code1')
error3 = ValidationError('message', code='my_code2')
error4 = ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code1',
params={'parm1': 'val1', 'parm2': 'val2'},
)
error5 = ValidationError({'field1': 'message', 'field2': 'other'})
error6 = ValidationError({'field1': 'message'})
error7 = ValidationError([
ValidationError({'field1': 'field error', 'field2': 'other'}),
'message',
])
self.assertEqual(error1, ValidationError('message'))
self.assertNotEqual(error1, ValidationError('message2'))
self.assertNotEqual(error1, error2)
self.assertNotEqual(error1, error4)
self.assertNotEqual(error1, error5)
self.assertNotEqual(error1, error6)
self.assertNotEqual(error1, error7)
self.assertEqual(error1, mock.ANY)
self.assertEqual(error2, ValidationError('message', code='my_code1'))
self.assertNotEqual(error2, ValidationError('other', code='my_code1'))
self.assertNotEqual(error2, error3)
self.assertNotEqual(error2, error4)
self.assertNotEqual(error2, error5)
self.assertNotEqual(error2, error6)
self.assertNotEqual(error2, error7)
self.assertEqual(error4, ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code1',
params={'parm1': 'val1', 'parm2': 'val2'},
))
self.assertNotEqual(error4, ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code2',
params={'parm1': 'val1', 'parm2': 'val2'},
))
self.assertNotEqual(error4, ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code1',
params={'parm2': 'val2'},
))
self.assertNotEqual(error4, ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code1',
params={'parm2': 'val1', 'parm1': 'val2'},
))
self.assertNotEqual(error4, ValidationError(
'error val1 val2',
code='my_code1',
))
# params ordering is ignored.
self.assertEqual(error4, ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code1',
params={'parm2': 'val2', 'parm1': 'val1'},
))
self.assertEqual(
error5,
ValidationError({'field1': 'message', 'field2': 'other'}),
)
self.assertNotEqual(
error5,
ValidationError({'field1': 'message', 'field2': 'other2'}),
)
self.assertNotEqual(
error5,
ValidationError({'field1': 'message', 'field3': 'other'}),
)
self.assertNotEqual(error5, error6)
# fields ordering is ignored.
self.assertEqual(
error5,
ValidationError({'field2': 'other', 'field1': 'message'}),
)
self.assertNotEqual(error7, ValidationError(error7.error_list[1:]))
self.assertNotEqual(
ValidationError(['message']),
ValidationError([ValidationError('message', code='my_code')]),
)
# messages ordering is ignored.
self.assertEqual(
error7,
ValidationError(list(reversed(error7.error_list))),
)
self.assertNotEqual(error4, ValidationError([error4]))
self.assertNotEqual(ValidationError([error4]), error4)
self.assertNotEqual(error4, ValidationError({'field1': error4}))
self.assertNotEqual(ValidationError({'field1': error4}), error4)
def test_eq_nested(self):
error_dict = {
'field1': ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code',
params={'parm1': 'val1', 'parm2': 'val2'},
),
'field2': 'other',
}
error = ValidationError(error_dict)
self.assertEqual(error, ValidationError(dict(error_dict)))
self.assertEqual(error, ValidationError({
'field1': ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code',
params={'parm2': 'val2', 'parm1': 'val1'},
),
'field2': 'other',
}))
self.assertNotEqual(error, ValidationError(
{**error_dict, 'field2': 'message'},
))
self.assertNotEqual(error, ValidationError({
'field1': ValidationError(
'error %(parm1)s val2',
code='my_code',
params={'parm1': 'val1'},
),
'field2': 'other',
}))
def test_hash(self):
error1 = ValidationError('message')
error2 = ValidationError('message', code='my_code1')
error3 = ValidationError('message', code='my_code2')
error4 = ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code1',
params={'parm1': 'val1', 'parm2': 'val2'},
)
error5 = ValidationError({'field1': 'message', 'field2': 'other'})
error6 = ValidationError({'field1': 'message'})
error7 = ValidationError([
ValidationError({'field1': 'field error', 'field2': 'other'}),
'message',
])
self.assertEqual(hash(error1), hash(ValidationError('message')))
self.assertNotEqual(hash(error1), hash(ValidationError('message2')))
self.assertNotEqual(hash(error1), hash(error2))
self.assertNotEqual(hash(error1), hash(error4))
self.assertNotEqual(hash(error1), hash(error5))
self.assertNotEqual(hash(error1), hash(error6))
self.assertNotEqual(hash(error1), hash(error7))
self.assertEqual(
hash(error2),
hash(ValidationError('message', code='my_code1')),
)
self.assertNotEqual(
hash(error2),
hash(ValidationError('other', code='my_code1')),
)
self.assertNotEqual(hash(error2), hash(error3))
self.assertNotEqual(hash(error2), hash(error4))
self.assertNotEqual(hash(error2), hash(error5))
self.assertNotEqual(hash(error2), hash(error6))
self.assertNotEqual(hash(error2), hash(error7))
self.assertEqual(hash(error4), hash(ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code1',
params={'parm1': 'val1', 'parm2': 'val2'},
)))
self.assertNotEqual(hash(error4), hash(ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code2',
params={'parm1': 'val1', 'parm2': 'val2'},
)))
self.assertNotEqual(hash(error4), hash(ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code1',
params={'parm2': 'val2'},
)))
self.assertNotEqual(hash(error4), hash(ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code1',
params={'parm2': 'val1', 'parm1': 'val2'},
)))
self.assertNotEqual(hash(error4), hash(ValidationError(
'error val1 val2',
code='my_code1',
)))
# params ordering is ignored.
self.assertEqual(hash(error4), hash(ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code1',
params={'parm2': 'val2', 'parm1': 'val1'},
)))
self.assertEqual(
hash(error5),
hash(ValidationError({'field1': 'message', 'field2': 'other'})),
)
self.assertNotEqual(
hash(error5),
hash(ValidationError({'field1': 'message', 'field2': 'other2'})),
)
self.assertNotEqual(
hash(error5),
hash(ValidationError({'field1': 'message', 'field3': 'other'})),
)
self.assertNotEqual(error5, error6)
# fields ordering is ignored.
self.assertEqual(
hash(error5),
hash(ValidationError({'field2': 'other', 'field1': 'message'})),
)
self.assertNotEqual(
hash(error7),
hash(ValidationError(error7.error_list[1:])),
)
self.assertNotEqual(
hash(ValidationError(['message'])),
hash(ValidationError([ValidationError('message', code='my_code')])),
)
# messages ordering is ignored.
self.assertEqual(
hash(error7),
hash(ValidationError(list(reversed(error7.error_list)))),
)
self.assertNotEqual(hash(error4), hash(ValidationError([error4])))
self.assertNotEqual(hash(ValidationError([error4])), hash(error4))
self.assertNotEqual(
hash(error4),
hash(ValidationError({'field1': error4})),
)
def test_hash_nested(self):
error_dict = {
'field1': ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code',
params={'parm2': 'val2', 'parm1': 'val1'},
),
'field2': 'other',
}
error = ValidationError(error_dict)
self.assertEqual(hash(error), hash(ValidationError(dict(error_dict))))
self.assertEqual(hash(error), hash(ValidationError({
'field1': ValidationError(
'error %(parm1)s %(parm2)s',
code='my_code',
params={'parm1': 'val1', 'parm2': 'val2'},
),
'field2': 'other',
})))
self.assertNotEqual(hash(error), hash(ValidationError(
{**error_dict, 'field2': 'message'},
)))
self.assertNotEqual(hash(error), hash(ValidationError({
'field1': ValidationError(
'error %(parm1)s val2',
code='my_code',
params={'parm1': 'val1'},
),
'field2': 'other',
})))
| 5,523 |
679 |
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#include "svx/EnhancedCustomShape2d.hxx"
#include <rtl/ustring.hxx>
#include <tools/fract.hxx>
// Makes parser a static resource,
// we're synchronized externally.
// But watch out, the parser might have
// state not visible to this code!
#define BOOST_SPIRIT_SINGLE_GRAMMAR_INSTANCE
#if defined(VERBOSE) && defined(DBG_UTIL)
#include <typeinfo>
#define BOOST_SPIRIT_DEBUG
#endif
#include <boost/spirit/include/classic_core.hpp>
#if (OSL_DEBUG_LEVEL > 0)
#include <iostream>
#endif
#include <functional>
#include <algorithm>
#include <stack>
#include <math.h> // fabs, sqrt, sin, cos, tan, atan, atan2
using namespace EnhancedCustomShape;
using namespace com::sun::star;
using namespace com::sun::star::drawing;
void EnhancedCustomShape::FillEquationParameter( const EnhancedCustomShapeParameter& rSource, const sal_Int32 nDestPara, EnhancedCustomShapeEquation& rDest )
{
sal_Int32 nValue = 0;
if ( rSource.Value.getValueTypeClass() == uno::TypeClass_DOUBLE )
{
double fValue;
if ( rSource.Value >>= fValue )
nValue = (sal_Int32)fValue;
}
else
rSource.Value >>= nValue;
switch( rSource.Type )
{
case com::sun::star::drawing::EnhancedCustomShapeParameterType::EQUATION :
{
if ( nValue & 0x40000000 )
{
nValue ^= 0x40000000;
rDest.nOperation |= 0x20000000 << nDestPara; // the bit is indicating that this value has to be adjusted later
}
nValue |= 0x400;
}
break;
case com::sun::star::drawing::EnhancedCustomShapeParameterType::ADJUSTMENT : nValue += DFF_Prop_adjustValue; break;
case com::sun::star::drawing::EnhancedCustomShapeParameterType::BOTTOM : nValue = DFF_Prop_geoBottom; break;
case com::sun::star::drawing::EnhancedCustomShapeParameterType::RIGHT : nValue = DFF_Prop_geoRight; break;
case com::sun::star::drawing::EnhancedCustomShapeParameterType::TOP : nValue = DFF_Prop_geoTop; break;
case com::sun::star::drawing::EnhancedCustomShapeParameterType::LEFT : nValue = DFF_Prop_geoLeft; break;
}
if ( rSource.Type != com::sun::star::drawing::EnhancedCustomShapeParameterType::NORMAL )
rDest.nOperation |= ( 0x2000 << nDestPara );
rDest.nPara[ nDestPara ] = nValue;
}
ExpressionNode::~ExpressionNode()
{}
namespace
{
//////////////////////
//////////////////////
// EXPRESSION NODES
//////////////////////
//////////////////////
class ConstantValueExpression : public ExpressionNode
{
double maValue;
public:
ConstantValueExpression( double rValue ) :
maValue( rValue )
{
}
virtual double operator()() const
{
return maValue;
}
virtual bool isConstant() const
{
return true;
}
virtual ExpressionFunct getType() const
{
return FUNC_CONST;
}
virtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* /* pOptionalArg */, sal_uInt32 /* nFlags */ )
{
EnhancedCustomShapeParameter aRet;
Fraction aFract( maValue );
if ( aFract.GetDenominator() == 1 )
{
aRet.Type = EnhancedCustomShapeParameterType::NORMAL;
aRet.Value <<= (sal_Int32)aFract.GetNumerator();
}
else
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation = 1;
aEquation.nPara[ 0 ] = 1;
aEquation.nPara[ 1 ] = (sal_Int16)aFract.GetNumerator();
aEquation.nPara[ 2 ] = (sal_Int16)aFract.GetDenominator();
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
return aRet;
}
};
class AdjustmentExpression : public ExpressionNode
{
sal_Int32 mnIndex;
const EnhancedCustomShape2d& mrCustoShape;
public:
AdjustmentExpression( const EnhancedCustomShape2d& rCustoShape, sal_Int32 nIndex )
: mnIndex ( nIndex )
, mrCustoShape( rCustoShape )
{
}
virtual double operator()() const
{
return mrCustoShape.GetAdjustValueAsDouble( mnIndex );
}
virtual bool isConstant() const
{
return false;
}
virtual ExpressionFunct getType() const
{
return ENUM_FUNC_ADJUSTMENT;
}
virtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& /*rEquations*/, ExpressionNode* /*pOptionalArg*/, sal_uInt32 /*nFlags*/ )
{
EnhancedCustomShapeParameter aRet;
aRet.Type = EnhancedCustomShapeParameterType::ADJUSTMENT;
aRet.Value <<= mnIndex;
return aRet;
}
};
class EquationExpression : public ExpressionNode
{
sal_Int32 mnIndex;
const EnhancedCustomShape2d& mrCustoShape;
public:
EquationExpression( const EnhancedCustomShape2d& rCustoShape, sal_Int32 nIndex )
: mnIndex ( nIndex )
, mrCustoShape( rCustoShape )
{
}
virtual double operator()() const
{
return mrCustoShape.GetEquationValueAsDouble( mnIndex );
}
virtual bool isConstant() const
{
return false;
}
virtual ExpressionFunct getType() const
{
return ENUM_FUNC_EQUATION;
}
virtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& /*rEquations*/, ExpressionNode* /*pOptionalArg*/, sal_uInt32 /*nFlags*/ )
{
EnhancedCustomShapeParameter aRet;
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= mnIndex | 0x40000000; // the bit is indicating that this equation needs to be adjusted later
return aRet;
}
};
class EnumValueExpression : public ExpressionNode
{
const ExpressionFunct meFunct;
const EnhancedCustomShape2d& mrCustoShape;
public:
EnumValueExpression( const EnhancedCustomShape2d& rCustoShape, const ExpressionFunct eFunct )
: meFunct ( eFunct )
, mrCustoShape ( rCustoShape )
{
}
static double getValue( const EnhancedCustomShape2d& rCustoShape, const ExpressionFunct eFunc )
{
EnhancedCustomShape2d::EnumFunc eF;
switch( eFunc )
{
case ENUM_FUNC_PI : eF = EnhancedCustomShape2d::ENUM_FUNC_PI; break;
case ENUM_FUNC_LEFT : eF = EnhancedCustomShape2d::ENUM_FUNC_LEFT; break;
case ENUM_FUNC_TOP : eF = EnhancedCustomShape2d::ENUM_FUNC_TOP; break;
case ENUM_FUNC_RIGHT : eF = EnhancedCustomShape2d::ENUM_FUNC_RIGHT; break;
case ENUM_FUNC_BOTTOM : eF = EnhancedCustomShape2d::ENUM_FUNC_BOTTOM; break;
case ENUM_FUNC_XSTRETCH : eF = EnhancedCustomShape2d::ENUM_FUNC_XSTRETCH; break;
case ENUM_FUNC_YSTRETCH : eF = EnhancedCustomShape2d::ENUM_FUNC_YSTRETCH; break;
case ENUM_FUNC_HASSTROKE : eF = EnhancedCustomShape2d::ENUM_FUNC_HASSTROKE; break;
case ENUM_FUNC_HASFILL : eF = EnhancedCustomShape2d::ENUM_FUNC_HASFILL; break;
case ENUM_FUNC_WIDTH : eF = EnhancedCustomShape2d::ENUM_FUNC_WIDTH; break;
case ENUM_FUNC_HEIGHT : eF = EnhancedCustomShape2d::ENUM_FUNC_HEIGHT; break;
case ENUM_FUNC_LOGWIDTH : eF = EnhancedCustomShape2d::ENUM_FUNC_LOGWIDTH; break;
case ENUM_FUNC_LOGHEIGHT : eF = EnhancedCustomShape2d::ENUM_FUNC_LOGHEIGHT; break;
default :
return 0.0;
}
return rCustoShape.GetEnumFunc( eF );
}
virtual double operator()() const
{
return getValue( mrCustoShape, meFunct );
}
virtual bool isConstant() const
{
return false;
}
virtual ExpressionFunct getType() const
{
return meFunct;
}
virtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* /*pOptionalArg*/, sal_uInt32 nFlags )
{
EnhancedCustomShapeParameter aRet;
sal_Int32 nDummy = 1;
aRet.Value <<= nDummy;
switch( meFunct )
{
case ENUM_FUNC_WIDTH : // TODO: do not use this as constant value
case ENUM_FUNC_HEIGHT :
case ENUM_FUNC_LOGWIDTH :
case ENUM_FUNC_LOGHEIGHT :
case ENUM_FUNC_PI :
{
ConstantValueExpression aConstantValue( getValue( mrCustoShape, meFunct ) );
aRet = aConstantValue.fillNode( rEquations, NULL, nFlags );
}
break;
case ENUM_FUNC_LEFT : aRet.Type = EnhancedCustomShapeParameterType::LEFT; break;
case ENUM_FUNC_TOP : aRet.Type = EnhancedCustomShapeParameterType::TOP; break;
case ENUM_FUNC_RIGHT : aRet.Type = EnhancedCustomShapeParameterType::RIGHT; break;
case ENUM_FUNC_BOTTOM : aRet.Type = EnhancedCustomShapeParameterType::BOTTOM; break;
// not implemented so far
case ENUM_FUNC_XSTRETCH :
case ENUM_FUNC_YSTRETCH :
case ENUM_FUNC_HASSTROKE :
case ENUM_FUNC_HASFILL : aRet.Type = EnhancedCustomShapeParameterType::NORMAL; break;
default:
break;
}
return aRet;
}
};
/** ExpressionNode implementation for unary
function over one ExpressionNode
*/
class UnaryFunctionExpression : public ExpressionNode
{
const ExpressionFunct meFunct;
ExpressionNodeSharedPtr mpArg;
public:
UnaryFunctionExpression( const ExpressionFunct eFunct, const ExpressionNodeSharedPtr& rArg ) :
meFunct( eFunct ),
mpArg( rArg )
{
}
static double getValue( const ExpressionFunct eFunct, const ExpressionNodeSharedPtr& rArg )
{
double fRet = 0;
switch( eFunct )
{
case UNARY_FUNC_ABS : fRet = fabs( (*rArg)() ); break;
case UNARY_FUNC_SQRT: fRet = sqrt( (*rArg)() ); break;
case UNARY_FUNC_SIN : fRet = sin( (*rArg)() ); break;
case UNARY_FUNC_COS : fRet = cos( (*rArg)() ); break;
case UNARY_FUNC_TAN : fRet = tan( (*rArg)() ); break;
case UNARY_FUNC_ATAN: fRet = atan( (*rArg)() ); break;
case UNARY_FUNC_NEG : fRet = ::std::negate<double>()( (*rArg)() ); break;
default:
break;
}
return fRet;
}
virtual double operator()() const
{
return getValue( meFunct, mpArg );
}
virtual bool isConstant() const
{
return mpArg->isConstant();
}
virtual ExpressionFunct getType() const
{
return meFunct;
}
virtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* pOptionalArg, sal_uInt32 nFlags )
{
EnhancedCustomShapeParameter aRet;
switch( meFunct )
{
case UNARY_FUNC_ABS :
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 3;
FillEquationParameter( mpArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
case UNARY_FUNC_SQRT:
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 13;
FillEquationParameter( mpArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
case UNARY_FUNC_SIN :
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 9;
if ( pOptionalArg )
FillEquationParameter( pOptionalArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
else
aEquation.nPara[ 0 ] = 1;
EnhancedCustomShapeParameter aSource( mpArg->fillNode( rEquations, NULL, nFlags | EXPRESSION_FLAG_SUMANGLE_MODE ) );
if ( aSource.Type == EnhancedCustomShapeParameterType::NORMAL )
{ // sumangle needed :-(
EnhancedCustomShapeEquation _aEquation;
_aEquation.nOperation |= 0xe; // sumangle
FillEquationParameter( aSource, 1, _aEquation );
aSource.Type = EnhancedCustomShapeParameterType::EQUATION;
aSource.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( _aEquation );
}
FillEquationParameter( aSource, 1, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
case UNARY_FUNC_COS :
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 10;
if ( pOptionalArg )
FillEquationParameter( pOptionalArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
else
aEquation.nPara[ 0 ] = 1;
EnhancedCustomShapeParameter aSource( mpArg->fillNode( rEquations, NULL, nFlags | EXPRESSION_FLAG_SUMANGLE_MODE ) );
if ( aSource.Type == EnhancedCustomShapeParameterType::NORMAL )
{ // sumangle needed :-(
EnhancedCustomShapeEquation aTmpEquation;
aTmpEquation.nOperation |= 0xe; // sumangle
FillEquationParameter( aSource, 1, aTmpEquation );
aSource.Type = EnhancedCustomShapeParameterType::EQUATION;
aSource.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aTmpEquation );
}
FillEquationParameter( aSource, 1, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
case UNARY_FUNC_TAN :
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 16;
if ( pOptionalArg )
FillEquationParameter( pOptionalArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
else
aEquation.nPara[ 0 ] = 1;
EnhancedCustomShapeParameter aSource( mpArg->fillNode( rEquations, NULL, nFlags | EXPRESSION_FLAG_SUMANGLE_MODE ) );
if ( aSource.Type == EnhancedCustomShapeParameterType::NORMAL )
{ // sumangle needed :-(
EnhancedCustomShapeEquation aTmpEquation;
aTmpEquation.nOperation |= 0xe; // sumangle
FillEquationParameter( aSource, 1, aTmpEquation );
aSource.Type = EnhancedCustomShapeParameterType::EQUATION;
aSource.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aTmpEquation );
}
FillEquationParameter( aSource, 1, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
case UNARY_FUNC_ATAN:
{
// TODO:
aRet.Type = EnhancedCustomShapeParameterType::NORMAL;
}
break;
case UNARY_FUNC_NEG:
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 1;
aEquation.nPara[ 1 ] = -1;
aEquation.nPara[ 2 ] = 1;
FillEquationParameter( mpArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
default:
break;
}
return aRet;
}
};
/** ExpressionNode implementation for unary
function over two ExpressionNodes
*/
class BinaryFunctionExpression : public ExpressionNode
{
const ExpressionFunct meFunct;
ExpressionNodeSharedPtr mpFirstArg;
ExpressionNodeSharedPtr mpSecondArg;
public:
BinaryFunctionExpression( const ExpressionFunct eFunct, const ExpressionNodeSharedPtr& rFirstArg, const ExpressionNodeSharedPtr& rSecondArg ) :
meFunct( eFunct ),
mpFirstArg( rFirstArg ),
mpSecondArg( rSecondArg )
{
}
static double getValue( const ExpressionFunct eFunct, const ExpressionNodeSharedPtr& rFirstArg, const ExpressionNodeSharedPtr& rSecondArg )
{
double fRet = 0;
switch( eFunct )
{
case BINARY_FUNC_PLUS : fRet = (*rFirstArg)() + (*rSecondArg)(); break;
case BINARY_FUNC_MINUS: fRet = (*rFirstArg)() - (*rSecondArg)(); break;
case BINARY_FUNC_MUL : fRet = (*rFirstArg)() * (*rSecondArg)(); break;
case BINARY_FUNC_DIV : fRet = (*rFirstArg)() / (*rSecondArg)(); break;
case BINARY_FUNC_MIN : fRet = ::std::min( (*rFirstArg)(), (*rSecondArg)() ); break;
case BINARY_FUNC_MAX : fRet = ::std::max( (*rFirstArg)(), (*rSecondArg)() ); break;
case BINARY_FUNC_ATAN2: fRet = atan2( (*rFirstArg)(), (*rSecondArg)() ); break;
default:
break;
}
return fRet;
}
virtual double operator()() const
{
return getValue( meFunct, mpFirstArg, mpSecondArg );
}
virtual bool isConstant() const
{
return mpFirstArg->isConstant() && mpSecondArg->isConstant();
}
virtual ExpressionFunct getType() const
{
return meFunct;
}
virtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* /*pOptionalArg*/, sal_uInt32 nFlags )
{
EnhancedCustomShapeParameter aRet;
switch( meFunct )
{
case BINARY_FUNC_PLUS :
{
if ( nFlags & EXPRESSION_FLAG_SUMANGLE_MODE )
{
if ( mpFirstArg->getType() == ENUM_FUNC_ADJUSTMENT )
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 0xe; // sumangle
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
else if ( mpSecondArg->getType() == ENUM_FUNC_ADJUSTMENT )
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 0xe; // sumangle
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
else
{
EnhancedCustomShapeEquation aSumangle1;
aSumangle1.nOperation |= 0xe; // sumangle
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags &~EXPRESSION_FLAG_SUMANGLE_MODE ), 1, aSumangle1 );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aSumangle1 );
EnhancedCustomShapeEquation aSumangle2;
aSumangle2.nOperation |= 0xe; // sumangle
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags &~EXPRESSION_FLAG_SUMANGLE_MODE ), 1, aSumangle2 );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aSumangle2 );
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 0;
aEquation.nPara[ 0 ] = ( rEquations.size() - 2 ) | 0x400;
aEquation.nPara[ 1 ] = ( rEquations.size() - 1 ) | 0x400;
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
}
else
{
sal_Bool bFirstIsEmpty = mpFirstArg->isConstant() && ( (*mpFirstArg)() == 0 );
sal_Bool bSecondIsEmpty = mpSecondArg->isConstant() && ( (*mpSecondArg)() == 0 );
if ( bFirstIsEmpty )
aRet = mpSecondArg->fillNode( rEquations, NULL, nFlags );
else if ( bSecondIsEmpty )
aRet = mpFirstArg->fillNode( rEquations, NULL, nFlags );
else
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 0;
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
}
}
break;
case BINARY_FUNC_MINUS:
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 0;
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 2, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
case BINARY_FUNC_MUL :
{
// in the dest. format the cos function is using integer as result :-(
// so we can't use the generic algorithm
if ( ( mpFirstArg->getType() == UNARY_FUNC_SIN ) || ( mpFirstArg->getType() == UNARY_FUNC_COS ) || ( mpFirstArg->getType() == UNARY_FUNC_TAN ) )
aRet = mpFirstArg->fillNode( rEquations, mpSecondArg.get(), nFlags );
else if ( ( mpSecondArg->getType() == UNARY_FUNC_SIN ) || ( mpSecondArg->getType() == UNARY_FUNC_COS ) || ( mpSecondArg->getType() == UNARY_FUNC_TAN ) )
aRet = mpSecondArg->fillNode( rEquations, mpFirstArg.get(), nFlags );
else
{
if ( mpFirstArg->isConstant() && (*mpFirstArg)() == 1 )
aRet = mpSecondArg->fillNode( rEquations, NULL, nFlags );
else if ( mpSecondArg->isConstant() && (*mpSecondArg)() == 1 )
aRet = mpFirstArg->fillNode( rEquations, NULL, nFlags );
else if ( ( mpFirstArg->getType() == BINARY_FUNC_DIV ) // don't care of (pi/180)
&& ( ((BinaryFunctionExpression*)((BinaryFunctionExpression*)mpFirstArg.get())->mpFirstArg.get())->getType() == ENUM_FUNC_PI )
&& ( ((BinaryFunctionExpression*)((BinaryFunctionExpression*)mpFirstArg.get())->mpSecondArg.get())->getType() == FUNC_CONST ) )
{
aRet = mpSecondArg->fillNode( rEquations, NULL, nFlags );
}
else if ( ( mpSecondArg->getType() == BINARY_FUNC_DIV ) // don't care of (pi/180)
&& ( ((BinaryFunctionExpression*)((BinaryFunctionExpression*)mpSecondArg.get())->mpFirstArg.get())->getType() == ENUM_FUNC_PI )
&& ( ((BinaryFunctionExpression*)((BinaryFunctionExpression*)mpSecondArg.get())->mpSecondArg.get())->getType() == FUNC_CONST ) )
{
aRet = mpFirstArg->fillNode( rEquations, NULL, nFlags );
}
else
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 1;
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );
aEquation.nPara[ 2 ] = 1;
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
}
}
break;
case BINARY_FUNC_DIV :
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 1;
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
aEquation.nPara[ 1 ] = 1;
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 2, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
case BINARY_FUNC_MIN :
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 4;
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
case BINARY_FUNC_MAX :
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 5;
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
case BINARY_FUNC_ATAN2:
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 8;
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
rEquations.push_back( aEquation );
}
break;
default:
break;
}
return aRet;
}
};
class IfExpression : public ExpressionNode
{
ExpressionNodeSharedPtr mpFirstArg;
ExpressionNodeSharedPtr mpSecondArg;
ExpressionNodeSharedPtr mpThirdArg;
public:
IfExpression( const ExpressionNodeSharedPtr& rFirstArg,
const ExpressionNodeSharedPtr& rSecondArg,
const ExpressionNodeSharedPtr& rThirdArg ) :
mpFirstArg( rFirstArg ),
mpSecondArg( rSecondArg ),
mpThirdArg( rThirdArg )
{
}
virtual bool isConstant() const
{
return
mpFirstArg->isConstant() &&
mpSecondArg->isConstant() &&
mpThirdArg->isConstant();
}
virtual double operator()() const
{
return (*mpFirstArg)() > 0 ? (*mpSecondArg)() : (*mpThirdArg)();
}
virtual ExpressionFunct getType() const
{
return TERNARY_FUNC_IF;
}
virtual EnhancedCustomShapeParameter fillNode( std::vector< EnhancedCustomShapeEquation >& rEquations, ExpressionNode* /*pOptionalArg*/, sal_uInt32 nFlags )
{
EnhancedCustomShapeParameter aRet;
aRet.Type = EnhancedCustomShapeParameterType::EQUATION;
aRet.Value <<= (sal_Int32)rEquations.size();
{
EnhancedCustomShapeEquation aEquation;
aEquation.nOperation |= 6;
FillEquationParameter( mpFirstArg->fillNode( rEquations, NULL, nFlags ), 0, aEquation );
FillEquationParameter( mpSecondArg->fillNode( rEquations, NULL, nFlags ), 1, aEquation );
FillEquationParameter( mpThirdArg->fillNode( rEquations, NULL, nFlags ), 2, aEquation );
rEquations.push_back( aEquation );
}
return aRet;
}
};
////////////////////////
////////////////////////
// FUNCTION PARSER
////////////////////////
////////////////////////
typedef const sal_Char* StringIteratorT;
struct ParserContext
{
typedef ::std::stack< ExpressionNodeSharedPtr > OperandStack;
// stores a stack of not-yet-evaluated operands. This is used
// by the operators (i.e. '+', '*', 'sin' etc.) to pop their
// arguments from. If all arguments to an operator are constant,
// the operator pushes a precalculated result on the stack, and
// a composite ExpressionNode otherwise.
OperandStack maOperandStack;
const EnhancedCustomShape2d* mpCustoShape;
};
typedef ::boost::shared_ptr< ParserContext > ParserContextSharedPtr;
/** Generate apriori constant value
*/
class ConstantFunctor
{
const double mnValue;
ParserContextSharedPtr mpContext;
public:
ConstantFunctor( double rValue, const ParserContextSharedPtr& rContext ) :
mnValue( rValue ),
mpContext( rContext )
{
}
void operator()( StringIteratorT /*rFirst*/, StringIteratorT /*rSecond*/ ) const
{
mpContext->maOperandStack.push( ExpressionNodeSharedPtr( new ConstantValueExpression( mnValue ) ) );
}
};
/** Generate parse-dependent-but-then-constant value
*/
class DoubleConstantFunctor
{
ParserContextSharedPtr mpContext;
public:
DoubleConstantFunctor( const ParserContextSharedPtr& rContext ) :
mpContext( rContext )
{
}
void operator()( double n ) const
{
mpContext->maOperandStack.push( ExpressionNodeSharedPtr( new ConstantValueExpression( n ) ) );
}
};
class EnumFunctor
{
const ExpressionFunct meFunct;
double mnValue;
ParserContextSharedPtr mpContext;
public:
EnumFunctor( const ExpressionFunct eFunct, const ParserContextSharedPtr& rContext )
: meFunct( eFunct )
, mnValue( 0 )
, mpContext( rContext )
{
}
void operator()( StringIteratorT rFirst, StringIteratorT rSecond ) const
{
/*double nVal = mnValue;*/
switch( meFunct )
{
case ENUM_FUNC_ADJUSTMENT :
{
rtl::OUString aVal( rFirst + 1, rSecond - rFirst, RTL_TEXTENCODING_UTF8 );
mpContext->maOperandStack.push( ExpressionNodeSharedPtr( new AdjustmentExpression( *mpContext->mpCustoShape, aVal.toInt32() ) ) );
}
break;
case ENUM_FUNC_EQUATION :
{
rtl::OUString aVal( rFirst + 1, rSecond - rFirst, RTL_TEXTENCODING_UTF8 );
mpContext->maOperandStack.push( ExpressionNodeSharedPtr( new EquationExpression( *mpContext->mpCustoShape, aVal.toInt32() ) ) );
}
break;
default:
mpContext->maOperandStack.push( ExpressionNodeSharedPtr( new EnumValueExpression( *mpContext->mpCustoShape, meFunct ) ) );
}
}
};
class UnaryFunctionFunctor
{
const ExpressionFunct meFunct;
ParserContextSharedPtr mpContext;
public :
UnaryFunctionFunctor( const ExpressionFunct eFunct, const ParserContextSharedPtr& rContext ) :
meFunct( eFunct ),
mpContext( rContext )
{
}
void operator()( StringIteratorT, StringIteratorT ) const
{
ParserContext::OperandStack& rNodeStack( mpContext->maOperandStack );
if( rNodeStack.size() < 1 )
throw ParseError( "Not enough arguments for unary operator" );
// retrieve arguments
ExpressionNodeSharedPtr pArg( rNodeStack.top() );
rNodeStack.pop();
if( pArg->isConstant() ) // check for constness
rNodeStack.push( ExpressionNodeSharedPtr( new ConstantValueExpression( UnaryFunctionExpression::getValue( meFunct, pArg ) ) ) );
else // push complex node, that calcs the value on demand
rNodeStack.push( ExpressionNodeSharedPtr( new UnaryFunctionExpression( meFunct, pArg ) ) );
}
};
/** Implements a binary function over two ExpressionNodes
@tpl Generator
Generator functor, to generate an ExpressionNode of
appropriate type
*/
class BinaryFunctionFunctor
{
const ExpressionFunct meFunct;
ParserContextSharedPtr mpContext;
public:
BinaryFunctionFunctor( const ExpressionFunct eFunct, const ParserContextSharedPtr& rContext ) :
meFunct( eFunct ),
mpContext( rContext )
{
}
void operator()( StringIteratorT, StringIteratorT ) const
{
ParserContext::OperandStack& rNodeStack( mpContext->maOperandStack );
if( rNodeStack.size() < 2 )
throw ParseError( "Not enough arguments for binary operator" );
// retrieve arguments
ExpressionNodeSharedPtr pSecondArg( rNodeStack.top() );
rNodeStack.pop();
ExpressionNodeSharedPtr pFirstArg( rNodeStack.top() );
rNodeStack.pop();
// create combined ExpressionNode
ExpressionNodeSharedPtr pNode = ExpressionNodeSharedPtr( new BinaryFunctionExpression( meFunct, pFirstArg, pSecondArg ) );
// check for constness
if( pFirstArg->isConstant() && pSecondArg->isConstant() ) // call the operator() at pNode, store result in constant value ExpressionNode.
rNodeStack.push( ExpressionNodeSharedPtr( new ConstantValueExpression( (*pNode)() ) ) );
else // push complex node, that calcs the value on demand
rNodeStack.push( pNode );
}
};
class IfFunctor
{
ParserContextSharedPtr mpContext;
public :
IfFunctor( const ParserContextSharedPtr& rContext ) :
mpContext( rContext )
{
}
void operator()( StringIteratorT, StringIteratorT ) const
{
ParserContext::OperandStack& rNodeStack( mpContext->maOperandStack );
if( rNodeStack.size() < 3 )
throw ParseError( "Not enough arguments for ternary operator" );
// retrieve arguments
ExpressionNodeSharedPtr pThirdArg( rNodeStack.top() );
rNodeStack.pop();
ExpressionNodeSharedPtr pSecondArg( rNodeStack.top() );
rNodeStack.pop();
ExpressionNodeSharedPtr pFirstArg( rNodeStack.top() );
rNodeStack.pop();
// create combined ExpressionNode
ExpressionNodeSharedPtr pNode( new IfExpression( pFirstArg, pSecondArg, pThirdArg ) );
// check for constness
if( pFirstArg->isConstant() && pSecondArg->isConstant() && pThirdArg->isConstant() )
rNodeStack.push( ExpressionNodeSharedPtr( new ConstantValueExpression( (*pNode)() ) ) ); // call the operator() at pNode, store result in constant value ExpressionNode.
else
rNodeStack.push( pNode ); // push complex node, that calcs the value on demand
}
};
// Workaround for MSVC compiler anomaly (stack trashing)
//
// The default ureal_parser_policies implementation of parse_exp
// triggers a really weird error in MSVC7 (Version 13.00.9466), in
// that the real_parser_impl::parse_main() call of parse_exp()
// overwrites the frame pointer _on the stack_ (EBP of the calling
// function gets overwritten while lying on the stack).
//
// For the time being, our parser thus can only read the 1.0E10
// notation, not the 1.0e10 one.
//
// TODO(F1): Also handle the 1.0e10 case here.
template< typename T > struct custom_real_parser_policies : public ::boost::spirit::ureal_parser_policies<T>
{
template< typename ScannerT >
static typename ::boost::spirit::parser_result< ::boost::spirit::chlit<>, ScannerT >::type
parse_exp(ScannerT& scan)
{
// as_lower_d somehow breaks MSVC7
return ::boost::spirit::ch_p('E').parse(scan);
}
};
/* This class implements the following grammar (more or
less literally written down below, only slightly
obfuscated by the parser actions):
identifier = '$'|'pi'|'e'|'X'|'Y'|'Width'|'Height'
function = 'abs'|'sqrt'|'sin'|'cos'|'tan'|'atan'|'acos'|'asin'|'exp'|'log'
basic_expression =
number |
identifier |
function '(' additive_expression ')' |
'(' additive_expression ')'
unary_expression =
'-' basic_expression |
basic_expression
multiplicative_expression =
unary_expression ( ( '*' unary_expression )* |
( '/' unary_expression )* )
additive_expression =
multiplicative_expression ( ( '+' multiplicative_expression )* |
( '-' multiplicative_expression )* )
*/
class ExpressionGrammar : public ::boost::spirit::grammar< ExpressionGrammar >
{
public:
/** Create an arithmetic expression grammar
@param rParserContext
Contains context info for the parser
*/
ExpressionGrammar( const ParserContextSharedPtr& rParserContext ) :
mpParserContext( rParserContext )
{
}
template< typename ScannerT > class definition
{
public:
// grammar definition
definition( const ExpressionGrammar& self )
{
using ::boost::spirit::str_p;
using ::boost::spirit::range_p;
using ::boost::spirit::lexeme_d;
using ::boost::spirit::real_parser;
using ::boost::spirit::chseq_p;
identifier =
str_p( "pi" )[ EnumFunctor(ENUM_FUNC_PI, self.getContext() ) ]
| str_p( "left" )[ EnumFunctor(ENUM_FUNC_LEFT, self.getContext() ) ]
| str_p( "top" )[ EnumFunctor(ENUM_FUNC_TOP, self.getContext() ) ]
| str_p( "right" )[ EnumFunctor(ENUM_FUNC_RIGHT, self.getContext() ) ]
| str_p( "bottom" )[ EnumFunctor(ENUM_FUNC_BOTTOM, self.getContext() ) ]
| str_p( "xstretch" )[ EnumFunctor(ENUM_FUNC_XSTRETCH, self.getContext() ) ]
| str_p( "ystretch" )[ EnumFunctor(ENUM_FUNC_YSTRETCH, self.getContext() ) ]
| str_p( "hasstroke" )[ EnumFunctor(ENUM_FUNC_HASSTROKE, self.getContext() ) ]
| str_p( "hasfill" )[ EnumFunctor(ENUM_FUNC_HASFILL, self.getContext() ) ]
| str_p( "width" )[ EnumFunctor(ENUM_FUNC_WIDTH, self.getContext() ) ]
| str_p( "height" )[ EnumFunctor(ENUM_FUNC_HEIGHT, self.getContext() ) ]
| str_p( "logwidth" )[ EnumFunctor(ENUM_FUNC_LOGWIDTH, self.getContext() ) ]
| str_p( "logheight" )[ EnumFunctor(ENUM_FUNC_LOGHEIGHT, self.getContext() ) ]
;
unaryFunction =
(str_p( "abs" ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_ABS, self.getContext()) ]
| (str_p( "sqrt" ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_SQRT, self.getContext()) ]
| (str_p( "sin" ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_SIN, self.getContext()) ]
| (str_p( "cos" ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_COS, self.getContext()) ]
| (str_p( "tan" ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_TAN, self.getContext()) ]
| (str_p( "atan" ) >> '(' >> additiveExpression >> ')' )[ UnaryFunctionFunctor( UNARY_FUNC_ATAN, self.getContext()) ]
;
binaryFunction =
(str_p( "min" ) >> '(' >> additiveExpression >> ',' >> additiveExpression >> ')' )[ BinaryFunctionFunctor( BINARY_FUNC_MIN, self.getContext()) ]
| (str_p( "max" ) >> '(' >> additiveExpression >> ',' >> additiveExpression >> ')' )[ BinaryFunctionFunctor( BINARY_FUNC_MAX, self.getContext()) ]
| (str_p( "atan2") >> '(' >> additiveExpression >> ',' >> additiveExpression >> ')' )[ BinaryFunctionFunctor( BINARY_FUNC_ATAN2,self.getContext()) ]
;
ternaryFunction =
(str_p( "if" ) >> '(' >> additiveExpression >> ',' >> additiveExpression >> ',' >> additiveExpression >> ')' )[ IfFunctor( self.getContext() ) ]
;
funcRef_decl =
lexeme_d[ +( range_p('a','z') | range_p('A','Z') | range_p('0','9') ) ];
functionReference =
(str_p( "?" ) >> funcRef_decl )[ EnumFunctor( ENUM_FUNC_EQUATION, self.getContext() ) ];
modRef_decl =
lexeme_d[ +( range_p('0','9') ) ];
modifierReference =
(str_p( "$" ) >> modRef_decl )[ EnumFunctor( ENUM_FUNC_ADJUSTMENT, self.getContext() ) ];
basicExpression =
real_parser<double, custom_real_parser_policies<double> >()[ DoubleConstantFunctor(self.getContext()) ]
| identifier
| functionReference
| modifierReference
| unaryFunction
| binaryFunction
| ternaryFunction
| '(' >> additiveExpression >> ')'
;
unaryExpression =
('-' >> basicExpression)[ UnaryFunctionFunctor( UNARY_FUNC_NEG, self.getContext()) ]
| basicExpression
;
multiplicativeExpression =
unaryExpression
>> *( ('*' >> unaryExpression)[ BinaryFunctionFunctor( BINARY_FUNC_MUL, self.getContext()) ]
| ('/' >> unaryExpression)[ BinaryFunctionFunctor( BINARY_FUNC_DIV, self.getContext()) ]
)
;
additiveExpression =
multiplicativeExpression
>> *( ('+' >> multiplicativeExpression)[ BinaryFunctionFunctor( BINARY_FUNC_PLUS, self.getContext()) ]
| ('-' >> multiplicativeExpression)[ BinaryFunctionFunctor( BINARY_FUNC_MINUS, self.getContext()) ]
)
;
BOOST_SPIRIT_DEBUG_RULE(additiveExpression);
BOOST_SPIRIT_DEBUG_RULE(multiplicativeExpression);
BOOST_SPIRIT_DEBUG_RULE(unaryExpression);
BOOST_SPIRIT_DEBUG_RULE(basicExpression);
BOOST_SPIRIT_DEBUG_RULE(unaryFunction);
BOOST_SPIRIT_DEBUG_RULE(binaryFunction);
BOOST_SPIRIT_DEBUG_RULE(ternaryFunction);
BOOST_SPIRIT_DEBUG_RULE(identifier);
}
const ::boost::spirit::rule< ScannerT >& start() const
{
return additiveExpression;
}
private:
// the constituents of the Spirit arithmetic expression grammar.
// For the sake of readability, without 'ma' prefix.
::boost::spirit::rule< ScannerT > additiveExpression;
::boost::spirit::rule< ScannerT > multiplicativeExpression;
::boost::spirit::rule< ScannerT > unaryExpression;
::boost::spirit::rule< ScannerT > basicExpression;
::boost::spirit::rule< ScannerT > unaryFunction;
::boost::spirit::rule< ScannerT > binaryFunction;
::boost::spirit::rule< ScannerT > ternaryFunction;
::boost::spirit::rule< ScannerT > funcRef_decl;
::boost::spirit::rule< ScannerT > functionReference;
::boost::spirit::rule< ScannerT > modRef_decl;
::boost::spirit::rule< ScannerT > modifierReference;
::boost::spirit::rule< ScannerT > identifier;
};
const ParserContextSharedPtr& getContext() const
{
return mpParserContext;
}
private:
ParserContextSharedPtr mpParserContext; // might get modified during parsing
};
#ifdef BOOST_SPIRIT_SINGLE_GRAMMAR_INSTANCE
const ParserContextSharedPtr& getParserContext()
{
static ParserContextSharedPtr lcl_parserContext( new ParserContext() );
// clear node stack (since we reuse the static object, that's
// the whole point here)
while( !lcl_parserContext->maOperandStack.empty() )
lcl_parserContext->maOperandStack.pop();
return lcl_parserContext;
}
#endif
}
namespace EnhancedCustomShape {
ExpressionNodeSharedPtr FunctionParser::parseFunction( const ::rtl::OUString& rFunction, const EnhancedCustomShape2d& rCustoShape )
{
// TODO(Q1): Check if a combination of the RTL_UNICODETOTEXT_FLAGS_*
// gives better conversion robustness here (we might want to map space
// etc. to ASCII space here)
const ::rtl::OString& rAsciiFunction(
rtl::OUStringToOString( rFunction, RTL_TEXTENCODING_ASCII_US ) );
StringIteratorT aStart( rAsciiFunction.getStr() );
StringIteratorT aEnd( rAsciiFunction.getStr()+rAsciiFunction.getLength() );
ParserContextSharedPtr pContext;
#ifdef BOOST_SPIRIT_SINGLE_GRAMMAR_INSTANCE
// static parser context, because the actual
// Spirit parser is also a static object
pContext = getParserContext();
#else
pContext.reset( new ParserContext() );
#endif
pContext->mpCustoShape = &rCustoShape;
ExpressionGrammar aExpressionGrammer( pContext );
const ::boost::spirit::parse_info<StringIteratorT> aParseInfo(
::boost::spirit::parse( aStart,
aEnd,
aExpressionGrammer >> ::boost::spirit::end_p,
::boost::spirit::space_p ) );
OSL_DEBUG_ONLY(::std::cout.flush()); // needed to keep stdout and cout in sync
// input fully congested by the parser?
if( !aParseInfo.full )
throw ParseError( "EnhancedCustomShapeFunctionParser::parseFunction(): string not fully parseable" );
// parser's state stack now must contain exactly _one_ ExpressionNode,
// which represents our formula.
if( pContext->maOperandStack.size() != 1 )
throw ParseError( "EnhancedCustomShapeFunctionParser::parseFunction(): incomplete or empty expression" );
return pContext->maOperandStack.top();
}
}
| 17,627 |
369 |
// Copyright (c) 2017-2021, Mudita <NAME>.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include <endpoints/Context.hpp>
#include <endpoints/backup/BackupHelper.hpp>
#include <endpoints/JsonKeyNames.hpp>
#include <endpoints/message/Sender.hpp>
#include <service-desktop/DesktopMessages.hpp>
#include <service-desktop/ServiceDesktop.hpp>
#include <json11.hpp>
#include <purefs/filesystem_paths.hpp>
#include <filesystem>
namespace sdesktop::endpoints
{
using sender::putToSendQueue;
auto BackupHelper::processGet(Context &context) -> ProcessResult
{
return checkState(context);
}
auto BackupHelper::processPost(Context &context) -> ProcessResult
{
return executeRequest(context);
}
auto BackupHelper::executeRequest(Context &context) -> ProcessResult
{
auto ownerServicePtr = static_cast<ServiceDesktop *>(owner);
if (ownerServicePtr->getBackupRestoreStatus().state == BackupRestore::OperationState::Running) {
LOG_DEBUG("Backup already running");
// a backup is already running, don't start a second task
context.setResponseStatus(http::Code::NotAcceptable);
}
else {
LOG_DEBUG("Starting backup");
// initialize new backup information
ownerServicePtr->prepareBackupData();
// start the backup process in the background
ownerServicePtr->bus.sendUnicast(std::make_shared<sdesktop::BackupMessage>(),
service::name::service_desktop);
// return new generated backup info
context.setResponseBody(ownerServicePtr->getBackupRestoreStatus());
}
putToSendQueue(context.createSimpleResponse());
return {sent::yes, std::nullopt};
}
auto BackupHelper::checkState(Context &context) -> ProcessResult
{
auto ownerServicePtr = static_cast<ServiceDesktop *>(owner);
if (context.getBody()[json::taskId].is_string()) {
if (ownerServicePtr->getBackupRestoreStatus().taskId == context.getBody()[json::taskId].string_value()) {
if (ownerServicePtr->getBackupRestoreStatus().state == BackupRestore::OperationState::Finished) {
context.setResponseStatus(http::Code::SeeOther);
}
else {
context.setResponseStatus(http::Code::OK);
}
context.setResponseBody(ownerServicePtr->getBackupRestoreStatus());
}
else {
context.setResponseStatus(http::Code::NotFound);
}
}
else {
LOG_DEBUG("Backup task not found");
context.setResponseStatus(http::Code::BadRequest);
}
LOG_DEBUG("Responding");
putToSendQueue(context.createSimpleResponse());
return {sent::yes, std::nullopt};
}
} // namespace sdesktop::endpoints
| 1,237 |
10,225 |
package io.quarkus.config;
import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.inject.Inject;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import io.quarkus.test.QuarkusUnitTest;
import io.smallrye.config.ConfigMapping;
public class StaticInitConfigMappingTest {
@RegisterExtension
static final QuarkusUnitTest TEST = new QuarkusUnitTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClass(StaticInitConfigSource.class)
.addAsServiceProvider("org.eclipse.microprofile.config.spi.ConfigSource",
StaticInitConfigSource.class.getName()));
// This does not come from the static init Config, but it is registered in both static and runtime.
// If it doesn't fail, it means that the static mapping was done correctly.
@Inject
StaticInitConfigMapping mapping;
@Test
void staticInitMapping() {
assertEquals("1234", mapping.myProp());
}
@ConfigMapping(prefix = "config.static.init")
public interface StaticInitConfigMapping {
String myProp();
}
}
| 489 |
841 |
/*
* Tencent is pleased to support the open source community by making Pebble available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
*/
#ifndef SRC_COMMON_UNCOPYABLE_H
#define SRC_COMMON_UNCOPYABLE_H
#pragma once
namespace pebble {
class Uncopyable {
protected:
Uncopyable() {}
~Uncopyable() {}
private:
Uncopyable(const Uncopyable&);
const Uncopyable& operator=(const Uncopyable&);
}; // class Uncopyable
#define DECLARE_UNCOPYABLE(Class) \
private: \
Class(const Class&); \
const Class& operator=(const Class&);
} // namespace common
#endif // SRC_COMMON_BASE_UNCOPYABLE_H
| 353 |
3,084 |
#pragma once
class WpdBaseDriver :
public IUnknown
{
public:
WpdBaseDriver();
virtual ~WpdBaseDriver();
HRESULT Initialize();
VOID Uninitialize();
HRESULT DispatchWpdMessage(_In_ IPortableDeviceValues* pParams,
_In_ IPortableDeviceValues* pResults);
private:
HRESULT OnGetObjectIDsFromPersistentUniqueIDs(_In_ IPortableDeviceValues* pParams,
_In_ IPortableDeviceValues* pResults);
HRESULT OnSaveClientInfo(_In_ IPortableDeviceValues* pParams,
_In_ IPortableDeviceValues* pResults);
public: // IUnknown
ULONG __stdcall AddRef();
_At_(this, __drv_freesMem(Mem))
ULONG __stdcall Release();
HRESULT __stdcall QueryInterface(REFIID riid, void** ppv);
public:
WpdObjectEnumerator m_ObjectEnum;
WpdObjectManagement m_ObjectManagement;
WpdObjectProperties m_ObjectProperties;
WpdObjectResources m_ObjectResources;
WpdObjectPropertiesBulk m_ObjectPropertiesBulk;
WpdCapabilities m_Capabilities;
WpdService m_Service;
private:
FakeDevice m_Device;
ULONG m_cRef;
};
| 637 |
1,554 |
/*
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the Apache License.
* See the accompanying LICENSE file for terms.
*/
package com.yahoo.dba.perf.myperf.common;
/**
* Information about the columns from the a query retiurn results
* @author xrao
*
*/
public class ColumnDescriptor implements java.io.Serializable{
private static final long serialVersionUID = 6923318258330634209L;
private java.util.List<ColumnInfo> columns ;
public ColumnDescriptor()
{
columns = new java.util.ArrayList<ColumnInfo>();
}
public java.util.List<ColumnInfo> getColumns() {
return columns;
}
public void setColumns(java.util.List<ColumnInfo> columns) {
this.columns = columns;
}
public ColumnInfo getColumn(String colName)
{
for(int i=this.columns.size()-1;i>=0;i--)
{
if(colName.equalsIgnoreCase(this.columns.get(i).getName()))return this.columns.get(i);
}
return null;
}
public int getColumnIndex(String colName)
{
for(int i=this.columns.size()-1;i>=0;i--)
{
if(colName.equalsIgnoreCase(this.columns.get(i).getName()))return i;
}
return -1;
}
public void addColumn(String colName, boolean isNumber, int pos)
{
if(this.columns==null)this.columns = new java.util.ArrayList<ColumnInfo>();
ColumnInfo col = new ColumnInfo();
col.setName(colName);
col.setNumberType(isNumber);
col.setPosition(pos);
this.columns.add(col);
}
}
| 585 |
14,425 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.metrics2.AbstractMetric;
import org.apache.hadoop.metrics2.MetricsRecord;
import org.apache.hadoop.metrics2.impl.MetricsCollectorImpl;
import org.apache.hadoop.yarn.server.resourcemanager.MockNodes;
import org.apache.hadoop.yarn.server.resourcemanager.MockRM;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeAddedSchedulerEvent;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.event.NodeRemovedSchedulerEvent;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class TestSchedulingUpdate extends FairSchedulerTestBase {
@Override
public Configuration createConfiguration() {
Configuration conf = super.createConfiguration();
// Make the update loop to never finish to ensure zero update calls
conf.setInt(
FairSchedulerConfiguration.UPDATE_INTERVAL_MS,
Integer.MAX_VALUE);
return conf;
}
@Before
public void setup() {
conf = createConfiguration();
resourceManager = new MockRM(conf);
resourceManager.start();
scheduler = (FairScheduler) resourceManager.getResourceScheduler();
}
@After
public void teardown() {
if (resourceManager != null) {
resourceManager.stop();
resourceManager = null;
}
}
@Test (timeout = 3000)
public void testSchedulingUpdateOnNodeJoinLeave() throws InterruptedException {
verifyNoCalls();
// Add one node
String host = "127.0.0.1";
final int memory = 4096;
final int cores = 4;
RMNode node1 = MockNodes.newNodeInfo(
1, Resources.createResource(memory, cores), 1, host);
NodeAddedSchedulerEvent nodeEvent1 = new NodeAddedSchedulerEvent(node1);
scheduler.handle(nodeEvent1);
long expectedCalls = 1;
verifyExpectedCalls(expectedCalls, memory, cores);
// Remove the node
NodeRemovedSchedulerEvent nodeEvent2 = new NodeRemovedSchedulerEvent(node1);
scheduler.handle(nodeEvent2);
expectedCalls = 2;
verifyExpectedCalls(expectedCalls, 0, 0);
}
private void verifyExpectedCalls(long expectedCalls, int memory, int vcores)
throws InterruptedException {
boolean verified = false;
int count = 0;
while (count < 100) {
if (scheduler.fsOpDurations.hasUpdateThreadRunChanged()) {
break;
}
count++;
Thread.sleep(10);
}
assertTrue("Update Thread has not run based on its metrics",
scheduler.fsOpDurations.hasUpdateThreadRunChanged());
assertEquals("Root queue metrics memory does not have expected value",
memory, scheduler.getRootQueueMetrics().getAvailableMB());
assertEquals("Root queue metrics cpu does not have expected value",
vcores, scheduler.getRootQueueMetrics().getAvailableVirtualCores());
MetricsCollectorImpl collector = new MetricsCollectorImpl();
scheduler.fsOpDurations.getMetrics(collector, true);
MetricsRecord record = collector.getRecords().get(0);
for (AbstractMetric abstractMetric : record.metrics()) {
if (abstractMetric.name().contains("UpdateThreadRunNumOps")) {
assertEquals("Update Thread did not run expected number of times " +
"based on metric record count",
expectedCalls,
abstractMetric.value());
verified = true;
}
}
assertTrue("Did not find metric for UpdateThreadRunNumOps", verified);
}
private void verifyNoCalls() {
assertFalse("Update thread should not have executed",
scheduler.fsOpDurations.hasUpdateThreadRunChanged());
assertEquals("Scheduler queue memory should not have been updated",
0, scheduler.getRootQueueMetrics().getAvailableMB());
assertEquals("Scheduler queue cpu should not have been updated",
0,scheduler.getRootQueueMetrics().getAvailableVirtualCores());
}
}
| 1,633 |
852 |
import FWCore.ParameterSet.Config as cms
bfilter = cms.EDFilter("MCSingleParticleFilter",
MaxEta = cms.untracked.vdouble(20.0, 20.0),
MinEta = cms.untracked.vdouble(-20.0, -20.0),
MinPt = cms.untracked.vdouble(0.0, 0.0),
ParticleID = cms.untracked.vint32(5, -5)
)
jpsifilter = cms.EDFilter("PythiaFilter",
Status = cms.untracked.int32(2),
MaxEta = cms.untracked.double(20.0),
MinEta = cms.untracked.double(-20.0),
MinPt = cms.untracked.double(0.0),
ParticleID = cms.untracked.int32(443)
)
mumufilter = cms.EDFilter("MCParticlePairFilter",
Status = cms.untracked.vint32(1, 1),
MinPt = cms.untracked.vdouble(2.0, 2.0),
MaxEta = cms.untracked.vdouble(2.5, 2.5),
MinEta = cms.untracked.vdouble(-2.5, -2.5),
ParticleCharge = cms.untracked.int32(-1),
MaxInvMass = cms.untracked.double(4.0),
MinInvMass = cms.untracked.double(2.0),
ParticleID1 = cms.untracked.vint32(13),
ParticleID2 = cms.untracked.vint32(13)
)
| 486 |
4,551 |
package org.robolectric.shadows;
import static android.os.Build.VERSION_CODES.R;
import static com.google.common.truth.Truth.assertThat;
import android.content.pm.SuspendDialogInfo;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
/** Tests for {@link ShadowSuspendDialogInfo} */
@RunWith(AndroidJUnit4.class)
@Config(minSdk = R)
public class ShadowSuspendDialogInfoTest {
@Test
public void getNeutralActionButton_notSet_shouldReturnMoreDetails() {
SuspendDialogInfo dialogInfo = new SuspendDialogInfo.Builder().build();
ShadowSuspendDialogInfo shadowDialogInfo = Shadow.extract(dialogInfo);
assertThat(shadowDialogInfo.getNeutralButtonAction())
.isEqualTo(SuspendDialogInfo.BUTTON_ACTION_MORE_DETAILS);
}
@Test
public void getNeutralActionButton_setToUnsuspend_shouldReturnUnsuspend() {
SuspendDialogInfo dialogInfo =
new SuspendDialogInfo.Builder()
.setNeutralButtonAction(SuspendDialogInfo.BUTTON_ACTION_UNSUSPEND)
.build();
ShadowSuspendDialogInfo shadowDialogInfo = Shadow.extract(dialogInfo);
assertThat(shadowDialogInfo.getNeutralButtonAction())
.isEqualTo(SuspendDialogInfo.BUTTON_ACTION_UNSUSPEND);
}
}
| 478 |
14,668 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/payments/editor_view_controller.h"
#include <algorithm>
#include <map>
#include <memory>
#include <utility>
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/browser/ui/views/chrome_typography.h"
#include "chrome/browser/ui/views/payments/payment_request_dialog_view.h"
#include "chrome/browser/ui/views/payments/payment_request_dialog_view_ids.h"
#include "chrome/browser/ui/views/payments/payment_request_views_util.h"
#include "chrome/browser/ui/views/payments/validating_combobox.h"
#include "chrome/browser/ui/views/payments/validating_textfield.h"
#include "components/strings/grit/components_strings.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/combobox_model.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/border.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/button/md_text_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/styled_label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/box_layout_view.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/table_layout_view.h"
#include "ui/views/view.h"
namespace payments {
namespace {
class ErrorLabelView : public views::Label {
public:
METADATA_HEADER(ErrorLabelView);
ErrorLabelView(const std::u16string& error, autofill::ServerFieldType type)
: views::Label(error, CONTEXT_DIALOG_BODY_TEXT_SMALL) {
SetID(static_cast<int>(DialogViewID::ERROR_LABEL_OFFSET) + type);
SetMultiLine(true);
SetHorizontalAlignment(gfx::ALIGN_LEFT);
constexpr int kErrorLabelTopPadding = 6;
SetBorder(
views::CreateEmptyBorder(gfx::Insets(kErrorLabelTopPadding, 0, 0, 0)));
}
// views::Label:
void OnThemeChanged() override {
views::Label::OnThemeChanged();
SetEnabledColor(GetColorProvider()->GetColor(ui::kColorAlertHighSeverity));
}
};
BEGIN_METADATA(ErrorLabelView, views::Label)
END_METADATA
} // namespace
EditorViewController::EditorViewController(
base::WeakPtr<PaymentRequestSpec> spec,
base::WeakPtr<PaymentRequestState> state,
base::WeakPtr<PaymentRequestDialogView> dialog,
BackNavigationType back_navigation_type,
bool is_incognito)
: PaymentRequestSheetController(spec, state, dialog),
initial_focus_field_view_(nullptr),
back_navigation_type_(back_navigation_type),
is_incognito_(is_incognito) {}
EditorViewController::~EditorViewController() {}
void EditorViewController::DisplayErrorMessageForField(
autofill::ServerFieldType type,
const std::u16string& error_message) {
AddOrUpdateErrorMessageForField(type, error_message);
RelayoutPane();
}
// static
int EditorViewController::GetInputFieldViewId(autofill::ServerFieldType type) {
return static_cast<int>(DialogViewID::INPUT_FIELD_TYPE_OFFSET) +
static_cast<int>(type);
}
std::unique_ptr<views::View> EditorViewController::CreateHeaderView() {
return nullptr;
}
std::unique_ptr<views::View> EditorViewController::CreateCustomFieldView(
autofill::ServerFieldType type,
views::View** focusable_field,
bool* valid,
std::u16string* error_message) {
return nullptr;
}
std::unique_ptr<views::View> EditorViewController::CreateExtraViewForField(
autofill::ServerFieldType type) {
return nullptr;
}
bool EditorViewController::ValidateInputFields() {
for (const auto& field : text_fields()) {
if (!field.first->IsValid())
return false;
}
for (const auto& field : comboboxes()) {
if (!field.first->IsValid())
return false;
}
return true;
}
std::u16string EditorViewController::GetPrimaryButtonLabel() {
return l10n_util::GetStringUTF16(IDS_DONE);
}
PaymentRequestSheetController::ButtonCallback
EditorViewController::GetPrimaryButtonCallback() {
return base::BindRepeating(&EditorViewController::SaveButtonPressed,
base::Unretained(this));
}
int EditorViewController::GetPrimaryButtonId() {
return static_cast<int>(DialogViewID::EDITOR_SAVE_BUTTON);
}
bool EditorViewController::GetPrimaryButtonEnabled() {
return true;
}
bool EditorViewController::ShouldShowSecondaryButton() {
// Do not show the "Cancel Payment" button.
return false;
}
void EditorViewController::FillContentView(views::View* content_view) {
auto layout = std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical);
layout->set_main_axis_alignment(views::BoxLayout::MainAxisAlignment::kStart);
layout->set_cross_axis_alignment(
views::BoxLayout::CrossAxisAlignment::kStretch);
content_view->SetLayoutManager(std::move(layout));
// No insets. Child views below are responsible for their padding.
// An editor can optionally have a header view specific to it.
std::unique_ptr<views::View> header_view = CreateHeaderView();
if (header_view.get())
content_view->AddChildView(header_view.release());
// The heart of the editor dialog: all the input fields with their labels.
content_view->AddChildView(CreateEditorView().release());
}
void EditorViewController::UpdateEditorView() {
UpdateContentView();
UpdateFocus(GetFirstFocusedView());
dialog()->EditorViewUpdated();
}
views::View* EditorViewController::GetFirstFocusedView() {
if (initial_focus_field_view_)
return initial_focus_field_view_;
return PaymentRequestSheetController::GetFirstFocusedView();
}
std::unique_ptr<ValidatingCombobox>
EditorViewController::CreateComboboxForField(const EditorField& field,
std::u16string* error_message) {
std::unique_ptr<ValidationDelegate> delegate =
CreateValidationDelegate(field);
ValidationDelegate* delegate_ptr = delegate.get();
std::unique_ptr<ValidatingCombobox> combobox =
std::make_unique<ValidatingCombobox>(GetComboboxModelForType(field.type),
std::move(delegate));
combobox->SetAccessibleName(field.label);
std::u16string initial_value = GetInitialValueForType(field.type);
if (!initial_value.empty())
combobox->SelectValue(initial_value);
if (IsEditingExistingItem()) {
combobox->SetInvalid(
!delegate_ptr->IsValidCombobox(combobox.get(), error_message));
}
// Using autofill field type as a view ID.
combobox->SetID(GetInputFieldViewId(field.type));
combobox->SetCallback(
base::BindRepeating(&EditorViewController::OnPerformAction,
base::Unretained(this), combobox.get()));
comboboxes_.insert(std::make_pair(combobox.get(), field));
return combobox;
}
void EditorViewController::ContentsChanged(views::Textfield* sender,
const std::u16string& new_contents) {
ValidatingTextfield* sender_cast = static_cast<ValidatingTextfield*>(sender);
sender_cast->OnContentsChanged();
primary_button()->SetEnabled(ValidateInputFields());
}
void EditorViewController::OnPerformAction(ValidatingCombobox* sender) {
static_cast<ValidatingCombobox*>(sender)->OnContentsChanged();
primary_button()->SetEnabled(ValidateInputFields());
}
std::unique_ptr<views::View> EditorViewController::CreateEditorView() {
std::unique_ptr<views::View> editor_view = std::make_unique<views::View>();
text_fields_.clear();
comboboxes_.clear();
initial_focus_field_view_ = nullptr;
// All views have fixed size except the Field which stretches. The fixed
// padding at the end is computed so that Field views have a minimum of
// 176/272dp (short/long fields) as per spec.
// ___________________________________________________________________________
// |Label | 16dp pad | Field (flex) | 8dp pad | Extra View | Computed Padding|
// |______|__________|______________|_________|____________|_________________|
constexpr int kInputRowSpacing = 12;
editor_view->SetBorder(views::CreateEmptyBorder(
kInputRowSpacing, payments::kPaymentRequestRowHorizontalInsets, 0,
payments::kPaymentRequestRowHorizontalInsets));
editor_view->SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical, gfx::Insets(),
kInputRowSpacing));
views::View* first_field = nullptr;
for (const auto& field : GetFieldDefinitions()) {
bool valid = false;
views::View* focusable_field =
CreateInputField(editor_view.get(), field, &valid);
if (!first_field)
first_field = focusable_field;
if (!initial_focus_field_view_ && !valid)
initial_focus_field_view_ = focusable_field;
}
if (!initial_focus_field_view_)
initial_focus_field_view_ = first_field;
// Validate all fields and disable the primary (Done) button if necessary.
primary_button()->SetEnabled(ValidateInputFields());
// Adds the "* indicates a required field" label in "hint" grey text.
editor_view->AddChildView(CreateHintLabel(
l10n_util::GetStringUTF16(IDS_PAYMENTS_REQUIRED_FIELD_MESSAGE),
gfx::HorizontalAlignment::ALIGN_LEFT));
return editor_view;
}
// Each input field is a 4-quadrant grid.
// +----------------------------------------------------------+
// | Field Label | Input field (textfield/combobox) |
// |_______________________|__________________________________|
// | (empty) | Error label |
// +----------------------------------------------------------+
views::View* EditorViewController::CreateInputField(views::View* editor_view,
const EditorField& field,
bool* valid) {
constexpr int kShortFieldMinimumWidth = 176;
constexpr int kLabelWidth = 140;
constexpr int kLongFieldMinimumWidth = 272;
// This is the horizontal padding between the label and the field.
const int label_input_field_horizontal_padding =
ChromeLayoutProvider::Get()->GetDistanceMetric(
views::DISTANCE_RELATED_CONTROL_HORIZONTAL);
// The horizontal padding between the field and the extra view.
constexpr int kFieldExtraViewHorizontalPadding = 8;
auto* field_view =
editor_view->AddChildView(std::make_unique<views::TableLayoutView>());
// Label.
field_view->AddColumn(views::LayoutAlignment::kStart,
views::LayoutAlignment::kCenter,
views::TableLayout::kFixedSize,
views::TableLayout::ColumnSize::kFixed, kLabelWidth, 0);
field_view->AddPaddingColumn(views::TableLayout::kFixedSize,
label_input_field_horizontal_padding);
// Field.
field_view->AddColumn(views::LayoutAlignment::kStretch,
views::LayoutAlignment::kStretch, 1.0,
views::TableLayout::ColumnSize::kUsePreferred, 0, 0);
field_view->AddPaddingColumn(views::TableLayout::kFixedSize,
kFieldExtraViewHorizontalPadding);
int extra_view_width, padding, field_width;
if (field.length_hint == EditorField::LengthHint::HINT_SHORT) {
field_width = kShortFieldMinimumWidth;
extra_view_width =
ComputeWidestExtraViewWidth(EditorField::LengthHint::HINT_SHORT);
// The padding at the end is fixed, computed to make sure the short field
// maintains its minimum width.
} else {
field_width = kLongFieldMinimumWidth;
extra_view_width =
ComputeWidestExtraViewWidth(EditorField::LengthHint::HINT_LONG);
}
// The padding at the end is fixed, computed to make sure the long field
// maintains its minimum width.
padding = kDialogMinWidth - field_width - kLabelWidth -
(2 * kPaymentRequestRowHorizontalInsets) -
label_input_field_horizontal_padding -
kFieldExtraViewHorizontalPadding - extra_view_width;
// Extra view.
field_view->AddColumn(
views::LayoutAlignment::kStart, views::LayoutAlignment::kCenter,
views::TableLayout::kFixedSize, views::TableLayout::ColumnSize::kFixed,
extra_view_width, 0);
field_view->AddPaddingColumn(views::TableLayout::kFixedSize, padding);
field_view->AddRows(1, views::TableLayout::kFixedSize);
std::unique_ptr<views::Label> label = std::make_unique<views::Label>(
field.required ? field.label + u"*" : field.label);
label->SetMultiLine(true);
label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
field_view->AddChildView(std::move(label));
views::View* focusable_field = nullptr;
constexpr int kInputFieldHeight = 28;
std::u16string error_message;
switch (field.control_type) {
case EditorField::ControlType::TEXTFIELD:
case EditorField::ControlType::TEXTFIELD_NUMBER: {
std::unique_ptr<ValidationDelegate> validation_delegate =
CreateValidationDelegate(field);
ValidationDelegate* delegate_ptr = validation_delegate.get();
std::u16string initial_value = GetInitialValueForType(field.type);
auto text_field =
std::make_unique<ValidatingTextfield>(std::move(validation_delegate));
// Set the initial value and validity state.
text_field->SetText(initial_value);
text_field->SetAccessibleName(field.label);
*valid = IsEditingExistingItem() &&
delegate_ptr->IsValidTextfield(text_field.get(), &error_message);
if (IsEditingExistingItem())
text_field->SetInvalid(!(*valid));
if (field.control_type == EditorField::ControlType::TEXTFIELD_NUMBER)
text_field->SetTextInputType(ui::TextInputType::TEXT_INPUT_TYPE_NUMBER);
text_field->set_controller(this);
// Using autofill field type as a view ID (for testing).
text_field->SetID(GetInputFieldViewId(field.type));
text_fields_.insert(std::make_pair(text_field.get(), field));
focusable_field = field_view->AddChildView(std::move(text_field));
focusable_field->SetPreferredSize(
gfx::Size(field_width, kInputFieldHeight));
break;
}
case EditorField::ControlType::COMBOBOX: {
std::unique_ptr<ValidatingCombobox> combobox =
CreateComboboxForField(field, &error_message);
*valid = combobox->IsValid();
focusable_field = field_view->AddChildView(std::move(combobox));
focusable_field->SetPreferredSize(
gfx::Size(field_width, kInputFieldHeight));
break;
}
case EditorField::ControlType::CUSTOMFIELD: {
std::unique_ptr<views::View> custom_view = CreateCustomFieldView(
field.type, &focusable_field, valid, &error_message);
DCHECK(custom_view);
field_view->AddChildView(std::move(custom_view));
field_view->SetPreferredSize(gfx::Size(field_width, kInputFieldHeight));
break;
}
case EditorField::ControlType::READONLY_LABEL: {
std::unique_ptr<views::Label> readonly_label =
std::make_unique<views::Label>(GetInitialValueForType(field.type));
readonly_label->SetID(GetInputFieldViewId(field.type));
readonly_label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
field_view->AddChildView(std::move(readonly_label));
field_view->SetPreferredSize(gfx::Size(field_width, kInputFieldHeight));
break;
}
}
// If an extra view needs to go alongside the input field view, add it to the
// last column.
std::unique_ptr<views::View> extra_view = CreateExtraViewForField(field.type);
field_view->AddChildView(extra_view ? std::move(extra_view)
: std::make_unique<views::View>());
// Error view.
field_view->AddRows(1, views::TableLayout::kFixedSize);
// Skip the first label column.
field_view->AddChildView(std::make_unique<views::View>());
auto error_label_view = std::make_unique<views::View>();
error_label_view->SetLayoutManager(std::make_unique<views::FillLayout>());
error_labels_[field.type] = error_label_view.get();
if (IsEditingExistingItem() && !error_message.empty())
AddOrUpdateErrorMessageForField(field.type, error_message);
field_view->AddChildView(std::move(error_label_view));
return focusable_field;
}
int EditorViewController::ComputeWidestExtraViewWidth(
EditorField::LengthHint size) {
int widest_column_width = 0;
for (const auto& field : GetFieldDefinitions()) {
if (field.length_hint != size)
continue;
std::unique_ptr<views::View> extra_view =
CreateExtraViewForField(field.type);
if (!extra_view)
continue;
widest_column_width =
std::max(extra_view->GetPreferredSize().width(), widest_column_width);
}
return widest_column_width;
}
void EditorViewController::AddOrUpdateErrorMessageForField(
autofill::ServerFieldType type,
const std::u16string& error_message) {
const auto& label_view_it = error_labels_.find(type);
DCHECK(label_view_it != error_labels_.end());
if (error_message.empty()) {
label_view_it->second->RemoveAllChildViews();
} else {
if (label_view_it->second->children().empty()) {
// If there was no error label view, add it.
label_view_it->second->AddChildView(
std::make_unique<ErrorLabelView>(error_message, type));
} else {
// The error view is the only child, and has a Label as only child itself.
static_cast<views::Label*>(label_view_it->second->children().front())
->SetText(error_message);
}
}
}
void EditorViewController::SaveButtonPressed() {
if (!ValidateModelAndSave())
return;
if (back_navigation_type_ == BackNavigationType::kOneStep) {
dialog()->GoBack();
} else {
DCHECK_EQ(BackNavigationType::kPaymentSheet, back_navigation_type_);
dialog()->GoBackToPaymentSheet();
}
}
} // namespace payments
| 6,559 |
5,411 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/android/scoped_hardware_buffer_fence_sync.h"
#include <utility>
namespace base {
namespace android {
ScopedHardwareBufferFenceSync::ScopedHardwareBufferFenceSync(
ScopedHardwareBufferHandle handle,
ScopedFD fence_fd)
: handle_(std::move(handle)), fence_fd_(std::move(fence_fd)) {}
ScopedHardwareBufferFenceSync::~ScopedHardwareBufferFenceSync() = default;
ScopedHardwareBufferHandle ScopedHardwareBufferFenceSync::TakeBuffer() {
return std::move(handle_);
}
ScopedFD ScopedHardwareBufferFenceSync::TakeFence() {
return std::move(fence_fd_);
}
} // namespace android
} // namespace base
| 250 |
5,903 |
/*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2018 by <NAME> : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.pentaho.di.trans.steps.jsonoutput.analyzer;
import org.pentaho.di.core.annotations.LifecyclePlugin;
import org.pentaho.di.core.lifecycle.LifeEventHandler;
import org.pentaho.di.core.lifecycle.LifecycleException;
import org.pentaho.di.core.lifecycle.LifecycleListener;
import org.pentaho.metaverse.api.analyzer.kettle.step.ExternalResourceStepAnalyzer;
import org.pentaho.metaverse.api.analyzer.kettle.step.IStepExternalResourceConsumer;
import org.pentaho.platform.engine.core.system.PentahoSystem;
@LifecyclePlugin( id = "JsonOutputAnalyzerPlugin", name = "JsonOutputAnalyzerPlugin" )
public class JsonOutputAnalyzerPluginLifecycleListener implements LifecycleListener {
@Override
public void onStart( final LifeEventHandler lifeEventHandler ) throws LifecycleException {
// instantiate a new analyzer
final ExternalResourceStepAnalyzer analyzer = new JsonOutputAnalyzer();
// construct the external resource consumer for the files that it reads from
final IStepExternalResourceConsumer consumer = new JsonOutputExternalResourceConsumer();
analyzer.setExternalResourceConsumer( consumer );
// register the analyzer with PentahoSystem
PentahoSystem.registerObject( analyzer );
// register the consumer with PentahoSystem
PentahoSystem.registerObject( consumer );
}
@Override
public void onExit( LifeEventHandler lifeEventHandler ) throws LifecycleException {
}
}
| 597 |
389 |
/*
* Copyright 2014 <NAME>, Inc.
*/
package gw.internal.gosu.ir.transform.statement;
import gw.internal.gosu.ir.transform.ExpressionTransformer;
import gw.internal.gosu.ir.transform.TopLevelTransformationContext;
import gw.internal.gosu.parser.statements.NewStatement;
import gw.lang.ir.IRExpression;
import gw.lang.ir.IRStatement;
import gw.lang.ir.expression.IRNewExpression;
/**
*/
public class NewStatementTransformer extends AbstractStatementTransformer<NewStatement>
{
public static IRStatement compile( TopLevelTransformationContext cc, NewStatement stmt )
{
NewStatementTransformer compiler = new NewStatementTransformer( cc, stmt );
return compiler.compile();
}
private NewStatementTransformer( TopLevelTransformationContext cc, NewStatement stmt )
{
super( cc, stmt );
}
@Override
protected IRStatement compile_impl()
{
IRExpression expr = ExpressionTransformer.compile( _stmt().getNewExpression(), _cc() );
if(expr instanceof IRNewExpression)
{
return buildNewExpression( (IRNewExpression) expr );
}
return buildMethodCall( expr );
}
}
| 355 |
334 |
<reponame>NuAngel/PoS-DogeCoin_PUPS<filename>nxt/src/java/nxt/tools/BaseTargetTest.java<gh_stars>100-1000
/*
* Copyright © 2013-2016 The Nxt Core Developers.
* Copyright © 2016-2020 Jelurida IP B.V.
*
* See the LICENSE.txt file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with Jelurida B.V.,
* no part of the Nxt software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE.txt file.
*
* Removal or modification of this copyright notice is prohibited.
*
*/
package nxt.tools;
import nxt.Constants;
import nxt.util.Convert;
import nxt.util.Logger;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
public final class BaseTargetTest {
private static final long MIN_BASE_TARGET = Constants.INITIAL_BASE_TARGET * 9 / 10;
private static final long MAX_BASE_TARGET = Constants.isTestnet ? Constants.MAX_BASE_TARGET : Constants.INITIAL_BASE_TARGET * 50;
private static final int MIN_BLOCKTIME_LIMIT = 53;
private static final int MAX_BLOCKTIME_LIMIT = 67;
private static final int GAMMA = 64;
private static final int START_HEIGHT = 170000;
private static final boolean USE_EWMA = false;
private static final int EWMA_N = 8;
private static final int SMA_N = 3;
private static final int FREQUENCY = 2;
private static long calculateBaseTarget(long previousBaseTarget, long blocktimeEMA) {
long baseTarget;
if (blocktimeEMA > 60) {
baseTarget = (previousBaseTarget * Math.min(blocktimeEMA, MAX_BLOCKTIME_LIMIT)) / 60;
} else {
baseTarget = previousBaseTarget - previousBaseTarget * GAMMA * (60 - Math.max(blocktimeEMA, MIN_BLOCKTIME_LIMIT)) / 6000;
}
if (baseTarget < 0 || baseTarget > MAX_BASE_TARGET) {
baseTarget = MAX_BASE_TARGET;
}
if (baseTarget < MIN_BASE_TARGET) {
baseTarget = MIN_BASE_TARGET;
}
return baseTarget;
}
public static void main(String[] args) {
try {
BigInteger testCumulativeDifficulty = BigInteger.ZERO;
long testBaseTarget;
int testTimestamp;
BigInteger cumulativeDifficulty = BigInteger.ZERO;
long baseTarget;
int timestamp;
BigInteger previousCumulativeDifficulty = null;
long previousBaseTarget = 0;
int previousTimestamp = 0;
BigInteger previousTestCumulativeDifficulty = null;
long previousTestBaseTarget = 0;
int previousTestTimestamp = 0;
int height = START_HEIGHT;
if (args.length == 1) {
height = Integer.parseInt(args[0]);
}
long totalBlocktime = 0;
long totalTestBlocktime = 0;
long maxBlocktime = 0;
long minBlocktime = Integer.MAX_VALUE;
long maxTestBlocktime = 0;
long minTestBlocktime = Integer.MAX_VALUE;
double M = 0.0;
double S = 0.0;
double testM = 0.0;
double testS = 0.0;
long testBlocktimeEMA = 0;
List<Integer> testBlocktimes = new ArrayList<>();
int count = 0;
String dbLocation = Constants.isTestnet ? "nxt_test_db" : "nxt_db";
try (Connection con = DriverManager.getConnection("jdbc:h2:./" + dbLocation + "/nxt;DB_CLOSE_ON_EXIT=FALSE", "sa", "sa");
PreparedStatement selectBlocks = con.prepareStatement("SELECT * FROM block WHERE height > " + height + " ORDER BY db_id ASC");
ResultSet rs = selectBlocks.executeQuery()) {
while (rs.next()) {
cumulativeDifficulty = new BigInteger(rs.getBytes("cumulative_difficulty"));
baseTarget = rs.getLong("base_target");
timestamp = rs.getInt("timestamp");
height = rs.getInt("height");
if (previousCumulativeDifficulty == null) {
previousCumulativeDifficulty = cumulativeDifficulty;
previousBaseTarget = baseTarget;
previousTimestamp = timestamp;
previousTestCumulativeDifficulty = previousCumulativeDifficulty;
previousTestBaseTarget = previousBaseTarget;
previousTestTimestamp = previousTimestamp;
continue;
}
int testBlocktime = (int)((previousBaseTarget * (timestamp - previousTimestamp - 1)) / previousTestBaseTarget) + 1;
if (testBlocktimeEMA == 0) {
testBlocktimeEMA = testBlocktime;
} else {
testBlocktimeEMA = (testBlocktime + testBlocktimeEMA * (EWMA_N - 1)) / EWMA_N;
}
testTimestamp = previousTestTimestamp + testBlocktime;
testBlocktimes.add(testBlocktime);
if (testBlocktimes.size() > SMA_N) {
testBlocktimes.remove(0);
}
int testBlocktimeSMA = 0;
for (int t : testBlocktimes) {
testBlocktimeSMA += t;
}
testBlocktimeSMA = testBlocktimeSMA / testBlocktimes.size();
if (testBlocktimes.size() < SMA_N) {
testBaseTarget = baseTarget;
} else if ((height - 1) % FREQUENCY == 0) {
testBaseTarget = calculateBaseTarget(previousTestBaseTarget, USE_EWMA ? testBlocktimeEMA : testBlocktimeSMA);
} else {
testBaseTarget = previousTestBaseTarget;
}
testCumulativeDifficulty = previousTestCumulativeDifficulty.add(Convert.two64.divide(BigInteger.valueOf(testBaseTarget)));
int blocktime = timestamp - previousTimestamp;
if (blocktime > maxBlocktime) {
maxBlocktime = blocktime;
}
if (blocktime < minBlocktime) {
minBlocktime = blocktime;
}
if (testBlocktime > maxTestBlocktime) {
maxTestBlocktime = testBlocktime;
}
if (testBlocktime < minTestBlocktime) {
minTestBlocktime = testBlocktime;
}
totalBlocktime += blocktime;
totalTestBlocktime += testBlocktime;
count += 1;
double tmp = M;
M += (blocktime - tmp) / count;
S += (blocktime - tmp) * (blocktime - M);
tmp = testM;
testM += (testBlocktime - tmp) / count;
testS += (testBlocktime - tmp) * (testBlocktime - testM);
previousTestTimestamp = testTimestamp;
previousTestBaseTarget = testBaseTarget;
previousTestCumulativeDifficulty = testCumulativeDifficulty;
previousTimestamp = timestamp;
previousBaseTarget = baseTarget;
previousCumulativeDifficulty = cumulativeDifficulty;
}
}
Logger.logMessage("Cumulative difficulty " + cumulativeDifficulty.toString());
Logger.logMessage("Test cumulative difficulty " + testCumulativeDifficulty.toString());
Logger.logMessage("Cumulative difficulty difference " + (testCumulativeDifficulty.subtract(cumulativeDifficulty))
.multiply(BigInteger.valueOf(100)).divide(cumulativeDifficulty).toString());
Logger.logMessage("Max blocktime " + maxBlocktime);
Logger.logMessage("Max test blocktime " + maxTestBlocktime);
Logger.logMessage("Min blocktime " + minBlocktime);
Logger.logMessage("Min test blocktime " + minTestBlocktime);
Logger.logMessage("Average blocktime " + ((double)totalBlocktime) / count);
Logger.logMessage("Average test blocktime " + ((double)totalTestBlocktime) / count);
Logger.logMessage("Standard deviation of blocktime " + Math.sqrt(S / count));
Logger.logMessage("Standard deviation of test blocktime " + Math.sqrt(testS / count));
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 4,113 |
416 |
<reponame>Zi0P4tch0/sdks
//
// IdentityLookupUI.h
// IdentityLookupUI
//
// Copyright © 2018 Apple. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <IdentityLookupUI/ILClassificationUIExtensionContext.h>
#import <IdentityLookupUI/ILClassificationUIExtensionViewController.h>
| 107 |
4,320 |
/*
* Copyright (c) 2018, <NAME> <<EMAIL>>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.cache.util;
import java.util.HashMap;
import java.util.Map;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public enum ScriptVarType
{
INTEGER('i', "integer"),
BOOLEAN('1', "boolean"),
SEQ('A', "seq"),
COLOUR('C', "colour"),
/**
* Also known as {@code Widget}.
*/
COMPONENT('I', "component"),
IDKIT('K', "idkit"),
MIDI('M', "midi"),
SYNTH('P', "synth"),
STAT('S', "stat"),
COORDGRID('c', "coordgrid"),
GRAPHIC('d', "graphic"),
FONTMETRICS('f', "fontmetrics"),
ENUM('g', "enum"),
JINGLE('j', "jingle"),
/**
* Also known as {@code Object}.
*/
LOC('l', "loc"),
MODEL('m', "model"),
NPC('n', "npc"),
/**
* Also known as {@code Item}.
*/
OBJ('o', "obj"),
/**
* Another version of {@code OBJ}, but means that on Jagex's side they used the internal name for an item.
*/
NAMEDOBJ('O', "namedobj"),
STRING('s', "string"),
SPOTANIM('t', "spotanim"),
INV('v', "inv"),
TEXTURE('x', "texture"),
CHAR('z', "char"),
MAPSCENEICON('£', "mapsceneicon"),
MAPELEMENT('µ', "mapelement"),
HITMARK('×', "hitmark"),
STRUCT('J', "struct");
private static final Map<Character, ScriptVarType> keyToTypeMap = new HashMap<>();
static
{
for (ScriptVarType type : values())
{
keyToTypeMap.put(type.keyChar, type);
}
}
public static ScriptVarType forCharKey(char key)
{
return keyToTypeMap.get(key);
}
/**
* The character used when encoding or decoding types.
*/
private final char keyChar;
/**
* The full name of the var type.
*/
private final String fullName;
}
| 1,014 |
777 |
<gh_stars>100-1000
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/touch_selection_controller_test_api.h"
namespace ui {
TouchSelectionControllerTestApi::TouchSelectionControllerTestApi(
TouchSelectionController* controller)
: controller_(controller) {}
TouchSelectionControllerTestApi::~TouchSelectionControllerTestApi() {}
bool TouchSelectionControllerTestApi::GetStartVisible() const {
return controller_->GetStartVisible();
}
bool TouchSelectionControllerTestApi::GetEndVisible() const {
return controller_->GetEndVisible();
}
TouchHandleOrientation
TouchSelectionControllerTestApi::GetStartHandleOrientation() const {
if (controller_->active_status_ != TouchSelectionController::SELECTION_ACTIVE)
return TouchHandleOrientation::UNDEFINED;
return controller_->start_selection_handle_->orientation();
}
TouchHandleOrientation
TouchSelectionControllerTestApi::GetEndHandleOrientation() const {
if (controller_->active_status_ != TouchSelectionController::SELECTION_ACTIVE)
return TouchHandleOrientation::UNDEFINED;
return controller_->end_selection_handle_->orientation();
}
} // namespace ui
| 373 |
312 |
/*
* Copyright (C) 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.googlecode.android_scripting.facade;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import com.googlecode.android_scripting.Log;
import com.googlecode.android_scripting.jsonrpc.RpcReceiver;
import com.googlecode.android_scripting.rpc.Rpc;
import com.googlecode.android_scripting.rpc.RpcMinSdk;
import com.googlecode.android_scripting.rpc.RpcStartEvent;
import com.googlecode.android_scripting.rpc.RpcStopEvent;
import java.lang.reflect.Field;
/**
* Exposes Batterymanager API. Note that in order to use any of the batteryGet* functions, you need
* to batteryStartMonitoring, and then wait for a "battery" event. Sleeping for a second will
* usually work just as well.
*
* @author <NAME> (<EMAIL>)
* @author <NAME> (<EMAIL>)
*/
public class BatteryManagerFacade extends RpcReceiver {
private final Service mService;
private final EventFacade mEventFacade;
private final int mSdkVersion;
private BatteryStateListener mReceiver;
private volatile Bundle mBatteryData = null;
private volatile Integer mBatteryStatus = null;
private volatile Integer mBatteryHealth = null;
private volatile Integer mPlugType = null;
private volatile Boolean mBatteryPresent = null;
private volatile Integer mBatteryLevel = null;
private volatile Integer mBatteryMaxLevel = null;
private volatile Integer mBatteryVoltage = null;
private volatile Integer mBatteryTemperature = null;
private volatile String mBatteryTechnology = null;
public BatteryManagerFacade(FacadeManager manager) {
super(manager);
mService = manager.getService();
mSdkVersion = manager.getSdkLevel();
mEventFacade = manager.getReceiver(EventFacade.class);
mReceiver = null;
mBatteryData = null;
}
private class BatteryStateListener extends BroadcastReceiver {
private final EventFacade mmEventFacade;
private BatteryStateListener(EventFacade facade) {
mmEventFacade = facade;
}
@Override
public void onReceive(Context context, Intent intent) {
mBatteryStatus = intent.getIntExtra("status", 1);
mBatteryHealth = intent.getIntExtra("health", 1);
mPlugType = intent.getIntExtra("plugged", -1);
if (mSdkVersion >= 5) {
mBatteryPresent =
intent.getBooleanExtra(getBatteryManagerFieldValue("EXTRA_PRESENT"), false);
mBatteryLevel = intent.getIntExtra(getBatteryManagerFieldValue("EXTRA_LEVEL"), -1);
mBatteryMaxLevel = intent.getIntExtra(getBatteryManagerFieldValue("EXTRA_SCALE"), 0);
mBatteryVoltage = intent.getIntExtra(getBatteryManagerFieldValue("EXTRA_VOLTAGE"), -1);
mBatteryTemperature =
intent.getIntExtra(getBatteryManagerFieldValue("EXTRA_TEMPERATURE"), -1);
mBatteryTechnology = intent.getStringExtra(getBatteryManagerFieldValue("EXTRA_TECHNOLOGY"));
}
Bundle data = new Bundle();
data.putInt("status", mBatteryStatus);
data.putInt("health", mBatteryHealth);
data.putInt("plugged", mPlugType);
if (mSdkVersion >= 5) {
data.putBoolean("battery_present", mBatteryPresent);
if (mBatteryMaxLevel == null || mBatteryMaxLevel == 100 || mBatteryMaxLevel == 0) {
data.putInt("level", mBatteryLevel);
} else {
data.putInt("level", (int) (mBatteryLevel * 100.0 / mBatteryMaxLevel));
}
data.putInt("voltage", mBatteryVoltage);
data.putInt("temperature", mBatteryTemperature);
data.putString("technology", mBatteryTechnology);
}
mBatteryData = data;
mmEventFacade.postEvent("battery", mBatteryData.clone());
}
}
private String getBatteryManagerFieldValue(String name) {
try {
Field f = BatteryManager.class.getField(name);
return f.get(null).toString();
} catch (Exception e) {
Log.e(e);
}
return null;
}
@Rpc(description = "Returns the most recently recorded battery data.")
public Bundle readBatteryData() {
return mBatteryData;
}
/**
* throws "battery" events
*/
@Rpc(description = "Starts tracking battery state.")
@RpcStartEvent("battery")
public void batteryStartMonitoring() {
if (mReceiver == null) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
mReceiver = new BatteryStateListener(mEventFacade);
mService.registerReceiver(mReceiver, filter);
}
}
@Rpc(description = "Stops tracking battery state.")
@RpcStopEvent("battery")
public void batteryStopMonitoring() {
if (mReceiver != null) {
mService.unregisterReceiver(mReceiver);
mReceiver = null;
}
mBatteryData = null;
}
@Override
public void shutdown() {
batteryStopMonitoring();
}
@Rpc(description = "Returns the most recently received battery status data:" + "\n1 - unknown;"
+ "\n2 - charging;" + "\n3 - discharging;" + "\n4 - not charging;" + "\n5 - full;")
public Integer batteryGetStatus() {
return mBatteryStatus;
}
@Rpc(description = "Returns the most recently received battery health data:" + "\n1 - unknown;"
+ "\n2 - good;" + "\n3 - overheat;" + "\n4 - dead;" + "\n5 - over voltage;"
+ "\n6 - unspecified failure;")
public Integer batteryGetHealth() {
return mBatteryHealth;
}
/** Power source is an AC charger. */
public static final int BATTERY_PLUGGED_AC = 1;
/** Power source is a USB port. */
public static final int BATTERY_PLUGGED_USB = 2;
@Rpc(description = "Returns the most recently received plug type data:" + "\n-1 - unknown"
+ "\n0 - unplugged;" + "\n1 - power source is an AC charger"
+ "\n2 - power source is a USB port")
public Integer batteryGetPlugType() {
return mPlugType;
}
@Rpc(description = "Returns the most recently received battery presence data.")
@RpcMinSdk(5)
public Boolean batteryCheckPresent() {
return mBatteryPresent;
}
@Rpc(description = "Returns the most recently received battery level (percentage).")
@RpcMinSdk(5)
public Integer batteryGetLevel() {
if (mBatteryMaxLevel == null || mBatteryMaxLevel == 100 || mBatteryMaxLevel == 0) {
return mBatteryLevel;
} else {
return (int) (mBatteryLevel * 100.0 / mBatteryMaxLevel);
}
}
@Rpc(description = "Returns the most recently received battery voltage.")
@RpcMinSdk(5)
public Integer batteryGetVoltage() {
return mBatteryVoltage;
}
@Rpc(description = "Returns the most recently received battery temperature.")
@RpcMinSdk(5)
public Integer batteryGetTemperature() {
return mBatteryTemperature;
}
@Rpc(description = "Returns the most recently received battery technology data.")
@RpcMinSdk(5)
public String batteryGetTechnology() {
return mBatteryTechnology;
}
}
| 2,479 |
563 |
<filename>servers/zts/src/test/java/com/yahoo/athenz/zts/workload/impl/JDBCWorkloadRecordStoreConnectionTest.java
/*
* Copyright The Athenz Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.yahoo.athenz.zts.workload.impl;
import com.yahoo.athenz.common.server.db.PoolableDataSource;
import com.yahoo.athenz.common.server.workload.WorkloadRecord;
import org.mockito.ArgumentMatchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.sql.*;
import java.util.Date;
import java.util.List;
import static org.mockito.Mockito.times;
import static org.testng.Assert.*;
public class JDBCWorkloadRecordStoreConnectionTest {
@Mock private PoolableDataSource mockDataSrc;
@Mock private Statement mockStmt;
@Mock private PreparedStatement mockPrepStmt;
@Mock private Connection mockConn;
@Mock private ResultSet mockResultSet;
@BeforeMethod
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
Mockito.doReturn(mockConn).when(mockDataSrc).getConnection();
Mockito.doReturn(mockStmt).when(mockConn).createStatement();
Mockito.doReturn(mockResultSet).when(mockPrepStmt).executeQuery();
Mockito.doReturn(mockPrepStmt).when(mockConn).prepareStatement(ArgumentMatchers.isA(String.class));
Mockito.doReturn(true).when(mockStmt).execute(ArgumentMatchers.isA(String.class));
}
@Test
public void testGetWorkloadRecordsByIp() throws Exception {
Date now = new Date();
Mockito.when(mockResultSet.next()).thenReturn(true, false);
mockNonNullableColumns(now);
Mockito.doReturn("athenz.api").when(mockResultSet).getString(JDBCWorkloadRecordStoreConnection.DB_COLUMN_SERVICE);
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
List<WorkloadRecord> workloadRecordList = jdbcConn.getWorkloadRecordsByIp("10.0.0.1");
assertNotNull(workloadRecordList);
assertNonNullableColumns(now, workloadRecordList.get(0));
assertEquals(workloadRecordList.get(0).getService(), "athenz.api");
jdbcConn.close();
}
@Test
public void testGetWorkloadRecordsByIpException() throws Exception {
Mockito.when(mockResultSet.next()).thenThrow(new SQLException("sql error"));
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
try {
jdbcConn.getWorkloadRecordsByIp("10.0.0.1");
fail();
} catch (RuntimeException se) {
assertTrue(se.getMessage().contains("sql error"));
}
jdbcConn.close();
}
@Test
public void testGetWorkloadRecordsByIpTimeout() throws Exception {
Mockito.when(mockResultSet.next()).thenThrow(new SQLTimeoutException("sql timeout"));
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
jdbcConn.setOperationTimeout(2);
try {
jdbcConn.getWorkloadRecordsByIp("10.0.0.1");
fail();
} catch (RuntimeException se) {
assertTrue(se.getMessage().contains("timeout"));
}
jdbcConn.close();
}
@Test
public void testGetWorkloadRecordsByService() throws Exception {
Date now = new Date();
Mockito.when(mockResultSet.next()).thenReturn(true, false);
mockNonNullableColumns(now);
Mockito.doReturn("10.0.0.1").when(mockResultSet).getString(JDBCWorkloadRecordStoreConnection.DB_COLUMN_IP);
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
List<WorkloadRecord> workloadRecordList = jdbcConn.getWorkloadRecordsByService("athenz", "api");
assertNotNull(workloadRecordList);
assertNonNullableColumns(now, workloadRecordList.get(0));
assertEquals(workloadRecordList.get(0).getIp(), "10.0.0.1");
jdbcConn.close();
}
@Test
public void testGetWorkloadRecordsByServiceException() throws Exception {
Mockito.when(mockResultSet.next()).thenThrow(new SQLException("sql error"));
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
try {
jdbcConn.getWorkloadRecordsByService("athenz", "api");
fail();
} catch (RuntimeException se) {
assertTrue(se.getMessage().contains("sql error"));
}
jdbcConn.close();
}
@Test
public void testGetWorkloadRecordsByServiceTimeout() throws Exception {
Mockito.when(mockResultSet.next()).thenThrow(new SQLTimeoutException("sql timeout"));
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
try {
jdbcConn.getWorkloadRecordsByService("athenz", "api");
fail();
} catch (RuntimeException se) {
assertTrue(se.getMessage().contains("timeout"));
}
jdbcConn.close();
}
@Test
public void testInsertWorkloadRecord() throws Exception {
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
Date now = new Date();
WorkloadRecord workloadRecord = getRecordWithNonNullableColumns(now);
Mockito.doReturn(1).when(mockPrepStmt).executeUpdate();
boolean requestSuccess = jdbcConn.insertWorkloadRecord(workloadRecord);
assertTrue(requestSuccess);
Mockito.verify(mockPrepStmt, times(1)).setString(1, "athenz.api");
Mockito.verify(mockPrepStmt, times(1)).setString(2, "instance-id");
Mockito.verify(mockPrepStmt, times(1)).setString(3, "openstack");
Mockito.verify(mockPrepStmt, times(1)).setString(4, "10.0.0.1");
Mockito.verify(mockPrepStmt, times(1)).setString(5, "test-host1.yahoo.cloud");
Mockito.verify(mockPrepStmt, times(1)).setTimestamp(6, new java.sql.Timestamp(now.getTime()));
jdbcConn.close();
}
@Test
public void testInsertWorkloadRecordException() throws Exception {
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
Date now = new Date();
WorkloadRecord workloadRecord = getRecordWithNonNullableColumns(now);
Mockito.when(mockPrepStmt.executeUpdate()).thenThrow(new SQLException("sql error"));
try {
jdbcConn.insertWorkloadRecord(workloadRecord);
fail();
}catch (RuntimeException se) {
assertTrue(se.getMessage().contains("sql error"));
}
jdbcConn.close();
}
@Test
public void testUpdateWorkloadRecord() throws Exception {
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
Date now = new Date();
WorkloadRecord workloadRecord = getRecordWithNonNullableColumns(now);
Mockito.doReturn(1).when(mockPrepStmt).executeUpdate();
boolean requestSuccess = jdbcConn.updateWorkloadRecord(workloadRecord);
assertTrue(requestSuccess);
Mockito.verify(mockPrepStmt, times(1)).setString(1, "openstack");
Mockito.verify(mockPrepStmt, times(1)).setTimestamp(2, new java.sql.Timestamp(now.getTime()));
Mockito.verify(mockPrepStmt, times(1)).setString(3, "instance-id");
Mockito.verify(mockPrepStmt, times(1)).setString(4, "athenz.api");
Mockito.verify(mockPrepStmt, times(1)).setString(5, "10.0.0.1");
jdbcConn.close();
}
@Test
public void testUpdateWorkloadRecordException() throws Exception {
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
Date now = new Date();
WorkloadRecord workloadRecord = getRecordWithNonNullableColumns(now);
Mockito.when(mockPrepStmt.executeUpdate()).thenThrow(new SQLException("sql error"));
try {
jdbcConn.updateWorkloadRecord(workloadRecord);
fail();
}catch (RuntimeException se) {
assertTrue(se.getMessage().contains("sql error"));
}
jdbcConn.close();
}
@Test
public void closeTest() throws Exception {
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
Mockito.doThrow(new SQLException("connection close error")).when(mockConn).close();
try {
jdbcConn.close();
fail();
} catch (RuntimeException re) {
assertTrue(re.getMessage().contains("Internal Server Error"));
}
jdbcConn = new JDBCWorkloadRecordStoreConnection(null);
try {
jdbcConn.close();
} catch (RuntimeException ex) {
fail();
}
}
@Test
public void processInsertValueTest() throws Exception {
JDBCWorkloadRecordStoreConnection jdbcConn = new JDBCWorkloadRecordStoreConnection(mockConn);
assertEquals(jdbcConn.processInsertValue(" "), "");
assertEquals(jdbcConn.processInsertValue(" abc"), "abc");
assertEquals(jdbcConn.processInsertValue("xyz "), "xyz");
assertEquals(jdbcConn.processInsertValue(null), "");
}
private void mockNonNullableColumns(Date now) throws SQLException {
Timestamp tstamp = new Timestamp(now.getTime());
Mockito.doReturn("openstack").when(mockResultSet).getString(JDBCWorkloadRecordStoreConnection.DB_COLUMN_PROVIDER);
Mockito.doReturn("instance-id").when(mockResultSet).getString(JDBCWorkloadRecordStoreConnection.DB_COLUMN_INSTANCE_ID);
Mockito.doReturn(tstamp).when(mockResultSet).getTimestamp(JDBCWorkloadRecordStoreConnection.DB_COLUMN_CREATION_TIME);
Mockito.doReturn(tstamp).when(mockResultSet).getTimestamp(JDBCWorkloadRecordStoreConnection.DB_COLUMN_UPDATE_TIME);
}
private void assertNonNullableColumns(Date now, WorkloadRecord workloadRecord) {
assertNotNull(workloadRecord);
assertEquals(workloadRecord.getProvider(), "openstack");
assertEquals(workloadRecord.getInstanceId(), "instance-id");
assertEquals(workloadRecord.getCreationTime().getTime(), now.getTime());
assertEquals(workloadRecord.getUpdateTime().getTime(), now.getTime());
}
private WorkloadRecord getRecordWithNonNullableColumns(Date now) {
WorkloadRecord workloadRecord = new WorkloadRecord();
workloadRecord.setService("athenz.api");
workloadRecord.setProvider("openstack");
workloadRecord.setInstanceId("instance-id");
workloadRecord.setIp("10.0.0.1");
workloadRecord.setHostname("test-host1.yahoo.cloud");
workloadRecord.setCertExpiryTime(now);
workloadRecord.setCreationTime(now);
workloadRecord.setUpdateTime(now);
return workloadRecord;
}
}
| 4,491 |
1,779 |
/*
* Copyright (c) 2020 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.exadel.frs.core.trainservice.cache;
import com.exadel.frs.commonservice.entity.Embedding;
import com.exadel.frs.core.trainservice.service.EmbeddingService;
import com.exadel.frs.core.trainservice.service.NotificationSenderService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.function.Function;
import java.util.stream.Stream;
import static com.exadel.frs.core.trainservice.ItemsBuilder.makeEmbedding;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class EmbeddingCacheProviderTest {
private static final String API_KEY = "model_key";
@Mock
private EmbeddingService embeddingService;
@Mock
private NotificationSenderService notificationSenderService;
@InjectMocks
private EmbeddingCacheProvider embeddingCacheProvider;
@Test
void getOrLoad() {
var embeddings = new Embedding[]{
makeEmbedding("A", API_KEY),
makeEmbedding("B", API_KEY),
makeEmbedding("C", API_KEY)
};
when(embeddingService.doWithEmbeddingsStream(eq(API_KEY), any()))
.thenAnswer(invocation -> {
var function = (Function<Stream<Embedding>, ?>) invocation.getArgument(1);
return function.apply(Stream.of(embeddings));
});
var actual = embeddingCacheProvider.getOrLoad(API_KEY);
assertThat(actual, notNullValue());
assertThat(actual.getProjections(), notNullValue());
assertThat(actual.getProjections().size(), is(embeddings.length));
assertThat(actual.getEmbeddings(), notNullValue());
}
}
| 964 |
3,027 |
#ifndef _ORDER_EXPIRATION_ENTRY_H
#define _ORDER_EXPIRATION_ENTRY_H
#include <string>
#include <set>
#include <iterator>
#include <Python.h>
class OrderExpirationEntry {
std::string tradingPair;
std::string orderId;
double timestamp;
double expiration_timestamp;
public:
OrderExpirationEntry();
OrderExpirationEntry(std::string tradingPair, std::string orderId, double timestamp, double expiration_timestamp);
OrderExpirationEntry(const OrderExpirationEntry &other);
OrderExpirationEntry &operator=(const OrderExpirationEntry &other);
friend bool operator<(OrderExpirationEntry const &a, OrderExpirationEntry const &b);
std::string getTradingPair() const;
std::string getClientOrderID() const;
double getTimestamp() const;
double getExpirationTimestamp() const;
};
#endif
| 307 |
2,073 |
package org.pac4j.core.matching.checker;
import org.pac4j.core.client.Client;
import org.pac4j.core.client.IndirectClient;
import org.pac4j.core.context.HttpConstants;
import org.pac4j.core.context.session.SessionStore;
import org.pac4j.core.util.Pac4jConstants;
import org.pac4j.core.context.WebContext;
import org.pac4j.core.matching.matcher.*;
import org.pac4j.core.matching.matcher.csrf.CsrfTokenGeneratorMatcher;
import org.pac4j.core.matching.matcher.csrf.DefaultCsrfTokenGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import static org.pac4j.core.util.CommonHelper.*;
/**
* Default way to check the matchers (with default matchers).
*
* @author <NAME>
* @since 4.0.0
*/
public class DefaultMatchingChecker implements MatchingChecker {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMatchingChecker.class);
protected static final Matcher GET_MATCHER = new HttpMethodMatcher(HttpConstants.HTTP_METHOD.GET);
protected static final Matcher POST_MATCHER = new HttpMethodMatcher(HttpConstants.HTTP_METHOD.POST);
protected static final Matcher PUT_MATCHER = new HttpMethodMatcher(HttpConstants.HTTP_METHOD.PUT);
protected static final Matcher DELETE_MATCHER = new HttpMethodMatcher(HttpConstants.HTTP_METHOD.DELETE);
protected static final StrictTransportSecurityMatcher STRICT_TRANSPORT_MATCHER = new StrictTransportSecurityMatcher();
protected static final XContentTypeOptionsMatcher X_CONTENT_TYPE_OPTIONS_MATCHER = new XContentTypeOptionsMatcher();
protected static final XFrameOptionsMatcher X_FRAME_OPTIONS_MATCHER = new XFrameOptionsMatcher();
protected static final XSSProtectionMatcher XSS_PROTECTION_MATCHER = new XSSProtectionMatcher();
protected static final CacheControlMatcher CACHE_CONTROL_MATCHER = new CacheControlMatcher();
protected static final CsrfTokenGeneratorMatcher CSRF_TOKEN_MATCHER = new CsrfTokenGeneratorMatcher(new DefaultCsrfTokenGenerator());
static final List<Matcher> SECURITY_HEADERS_MATCHERS = Arrays.asList(CACHE_CONTROL_MATCHER, X_CONTENT_TYPE_OPTIONS_MATCHER,
STRICT_TRANSPORT_MATCHER, X_FRAME_OPTIONS_MATCHER, XSS_PROTECTION_MATCHER);
protected static final CorsMatcher CORS_MATCHER = new CorsMatcher();
static {
CORS_MATCHER.setAllowOrigin("*");
CORS_MATCHER.setAllowCredentials(true);
final Set<HttpConstants.HTTP_METHOD> methods = new HashSet<>();
methods.add(HttpConstants.HTTP_METHOD.GET);
methods.add(HttpConstants.HTTP_METHOD.PUT);
methods.add(HttpConstants.HTTP_METHOD.POST);
methods.add(HttpConstants.HTTP_METHOD.DELETE);
methods.add(HttpConstants.HTTP_METHOD.OPTIONS);
CORS_MATCHER.setAllowMethods(methods);
}
@Override
public boolean matches(final WebContext context, final SessionStore sessionStore, final String matchersValue,
final Map<String, Matcher> matchersMap, final List<Client> clients) {
final var matchers = computeMatchers(context, sessionStore, matchersValue, matchersMap, clients);
return matches(context, sessionStore, matchers);
}
protected List<Matcher> computeMatchers(final WebContext context, final SessionStore sessionStore, final String matchersValue,
final Map<String, Matcher> matchersMap, final List<Client> clients) {
final List<Matcher> matchers;
if (isBlank(matchersValue)) {
matchers = computeDefaultMatchers(context, sessionStore, clients);
} else {
if (matchersValue.trim().startsWith(Pac4jConstants.ADD_ELEMENT)) {
final var matcherNames = substringAfter(matchersValue, Pac4jConstants.ADD_ELEMENT);
matchers = computeDefaultMatchers(context, sessionStore, clients);
matchers.addAll(computeMatchersFromNames(matcherNames, matchersMap));
} else {
matchers = computeMatchersFromNames(matchersValue, matchersMap);
}
}
return matchers;
}
protected List<Matcher> computeDefaultMatchers(final WebContext context, final SessionStore sessionStore, final List<Client> clients) {
final List<Matcher> matchers = new ArrayList<>();
matchers.addAll(SECURITY_HEADERS_MATCHERS);
if (sessionStore.getSessionId(context, false).isPresent()) {
matchers.add(CSRF_TOKEN_MATCHER);
return matchers;
}
for (final var client : clients) {
if (client instanceof IndirectClient) {
matchers.add(CSRF_TOKEN_MATCHER);
return matchers;
}
}
return matchers;
}
protected List<Matcher> computeMatchersFromNames(final String matchersValue, final Map<String, Matcher> matchersMap) {
assertNotNull("matchersMap", matchersMap);
final List<Matcher> matchers = new ArrayList<>();
final var names = matchersValue.split(Pac4jConstants.ELEMENT_SEPARATOR);
final var nb = names.length;
for (var i = 0; i < nb; i++) {
final var name = names[i].trim();
if (!DefaultMatchers.NONE.equalsIgnoreCase(name)) {
final var results = retrieveMatchers(name, matchersMap);
// we must have matchers defined for this name
assertTrue(results != null && results.size() > 0,
"The matcher '" + name + "' must be defined in the security configuration");
matchers.addAll(results);
}
}
return matchers;
}
protected List<Matcher> retrieveMatchers(final String matcherName, final Map<String, Matcher> matchersMap) {
final List<Matcher> results = new ArrayList<>();
for (final var entry : matchersMap.entrySet()) {
if (areEqualsIgnoreCaseAndTrim(entry.getKey(), matcherName)) {
results.add(entry.getValue());
break;
}
}
if (results.size() == 0) {
if (DefaultMatchers.HSTS.equalsIgnoreCase(matcherName)) {
return Arrays.asList(STRICT_TRANSPORT_MATCHER);
} else if (DefaultMatchers.NOSNIFF.equalsIgnoreCase(matcherName)) {
return Arrays.asList(X_CONTENT_TYPE_OPTIONS_MATCHER);
} else if (DefaultMatchers.NOFRAME.equalsIgnoreCase(matcherName)) {
return Arrays.asList(X_FRAME_OPTIONS_MATCHER);
} else if (DefaultMatchers.XSSPROTECTION.equalsIgnoreCase(matcherName)) {
return Arrays.asList(XSS_PROTECTION_MATCHER);
} else if (DefaultMatchers.NOCACHE.equalsIgnoreCase(matcherName)) {
return Arrays.asList(CACHE_CONTROL_MATCHER);
} else if (DefaultMatchers.SECURITYHEADERS.equalsIgnoreCase(matcherName)) {
return SECURITY_HEADERS_MATCHERS;
} else if (DefaultMatchers.CSRF_TOKEN.equalsIgnoreCase(matcherName)) {
return Arrays.asList(CSRF_TOKEN_MATCHER);
} else if (DefaultMatchers.ALLOW_AJAX_REQUESTS.equalsIgnoreCase(matcherName)) {
return Arrays.asList(CORS_MATCHER);
} else if (DefaultMatchers.GET.equalsIgnoreCase(matcherName)) {
return Arrays.asList(GET_MATCHER);
} else if (DefaultMatchers.POST.equalsIgnoreCase(matcherName)) {
return Arrays.asList(POST_MATCHER);
} else if (DefaultMatchers.PUT.equalsIgnoreCase(matcherName)) {
return Arrays.asList(PUT_MATCHER);
} else if (DefaultMatchers.DELETE.equalsIgnoreCase(matcherName)) {
return Arrays.asList(DELETE_MATCHER);
}
}
return results;
}
protected boolean matches(final WebContext context, final SessionStore sessionStore, final List<Matcher> matchers) {
if (!matchers.isEmpty()) {
// check matching using matchers: all must be satisfied
for (final var matcher : matchers) {
final var matches = matcher.matches(context, sessionStore);
LOGGER.debug("Checking matcher: {} -> {}", matcher, matches);
if (!matches) {
return false;
}
}
}
return true;
}
}
| 3,521 |
358 |
from __future__ import print_function
# import matplotlib
# matplotlib.use('Agg')
import unittest
import numpy as np
from SimPEG.electromagnetics import resistivity as dc
from SimPEG.electromagnetics.static import utils
from SimPEG import maps, mkvc, data
from SimPEG.utils.io_utils import io_utils_electromagnetics as io_utils
import shutil
import os
class Test_DCIP_IO(unittest.TestCase):
def setUp(self):
self.survey_type = ["pole-pole", "dipole-pole", "pole-dipole", "dipole-dipole"]
self.topo = 10
self.num_rx_per_src = 4
self.station_spacing = 25
self.dir_path = "./dcip_io_tests"
os.mkdir(self.dir_path)
def test_dc2d(self):
data_type = "volt"
end_points = np.array([-100, 100])
# Create sources and data object
source_list = []
for stype in self.survey_type:
source_list = source_list + utils.generate_dcip_sources_line(
stype,
data_type,
"2D",
end_points,
self.topo,
self.num_rx_per_src,
self.station_spacing,
)
survey2D = dc.survey.Survey(source_list)
dobs = np.random.rand(survey2D.nD)
dunc = 1e-3 * np.ones(survey2D.nD)
data2D = data.Data(survey2D, dobs=dobs, standard_deviation=dunc)
io_utils.write_dcip2d_ubc(
self.dir_path + "/dc2d_general.txt",
data2D,
"volt",
"dobs",
"general",
comment_lines="GENERAL FORMAT",
)
io_utils.write_dcip2d_ubc(
self.dir_path + "/dc2d_surface.txt",
data2D,
"volt",
"dobs",
"surface",
comment_lines="SURFACE FORMAT",
)
# Read DCIP2D files
data_general = io_utils.read_dcip2d_ubc(
self.dir_path + "/dc2d_general.txt", "volt", "general"
)
data_surface = io_utils.read_dcip2d_ubc(
self.dir_path + "/dc2d_surface.txt", "volt", "surface"
)
# Compare
passed = np.all(
np.isclose(data2D.dobs, data_general.dobs)
& np.isclose(data2D.dobs, data_surface.dobs)
)
self.assertTrue(passed)
print("READ/WRITE METHODS FOR DC2D DATA PASSED!")
def test_ip2d(self):
data_type = "apparent_chargeability"
end_points = np.array([-100, 100])
# Create sources and data object
source_list = []
for stype in self.survey_type:
source_list = source_list + utils.generate_dcip_sources_line(
stype,
data_type,
"2D",
end_points,
self.topo,
self.num_rx_per_src,
self.station_spacing,
)
survey2D = dc.survey.Survey(source_list)
dobs = np.random.rand(survey2D.nD)
dunc = 1e-3 * np.ones(survey2D.nD)
data2D = data.Data(survey2D, dobs=dobs, standard_deviation=dunc)
# Write DCIP2D files
io_utils.write_dcip2d_ubc(
self.dir_path + "/ip2d_general.txt",
data2D,
"apparent_chargeability",
"dobs",
"general",
comment_lines="GENERAL FORMAT",
)
io_utils.write_dcip2d_ubc(
self.dir_path + "/ip2d_surface.txt",
data2D,
"apparent_chargeability",
"dobs",
"surface",
comment_lines="SURFACE FORMAT",
)
# Read DCIP2D files
data_general = io_utils.read_dcip2d_ubc(
self.dir_path + "/ip2d_general.txt", "apparent_chargeability", "general"
)
data_surface = io_utils.read_dcip2d_ubc(
self.dir_path + "/ip2d_surface.txt", "apparent_chargeability", "surface"
)
# Compare
passed = np.all(
np.isclose(data2D.dobs, data_general.dobs)
& np.isclose(data2D.dobs, data_surface.dobs)
)
self.assertTrue(passed)
print("READ/WRITE METHODS FOR IP2D DATA PASSED!")
def test_dcip3d(self):
# Survey parameters
data_type = "volt"
end_points = np.array([-100, 50, 100, -50])
# Create sources and data object
source_list = []
for stype in self.survey_type:
source_list = source_list + utils.generate_dcip_sources_line(
stype,
data_type,
"3D",
end_points,
self.topo,
self.num_rx_per_src,
self.station_spacing,
)
survey3D = dc.survey.Survey(source_list)
dobs = np.random.rand(survey3D.nD)
dunc = 1e-3 * np.ones(survey3D.nD)
data3D = data.Data(survey3D, dobs=dobs, standard_deviation=dunc)
# Write DCIP3D files
io_utils.write_dcipoctree_ubc(
self.dir_path + "/dcip3d_general.txt",
data3D,
"volt",
"dobs",
format_type="general",
comment_lines="GENERAL FORMAT",
)
io_utils.write_dcipoctree_ubc(
self.dir_path + "/dcip3d_surface.txt",
data3D,
"volt",
"dobs",
format_type="surface",
comment_lines="SURFACE FORMAT",
)
# Read DCIP3D files
data_general = io_utils.read_dcipoctree_ubc(
self.dir_path + "/dcip3d_general.txt", "volt"
)
data_surface = io_utils.read_dcipoctree_ubc(
self.dir_path + "/dcip3d_surface.txt", "volt"
)
# Compare
passed = np.all(
np.isclose(data3D.dobs, data_general.dobs)
& np.isclose(data3D.dobs, data_surface.dobs)
)
self.assertTrue(passed)
print("READ/WRITE METHODS FOR DCIP3D DATA PASSED!")
def tearDown(self):
# Clean up the working directory
shutil.rmtree("./dcip_io_tests")
if __name__ == "__main__":
unittest.main()
| 3,342 |
333 |
<reponame>coreyp1/graphlab
/*
* Copyright (c) 2009 <NAME> University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* For more about this software visit:
*
* http://www.graphlab.ml.cmu.edu
*
*/
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <graphlab.hpp>
//remove assigned options from arguments
std::string get_arg_str_without(int argc, char** argv,
std::vector<std::string> remove_opts) {
std::stringstream strm;
bool skip_next = false;
for (int i = 1; i < argc; ++i) {
bool skip = false;
for (size_t j = 0; j < remove_opts.size(); ++j) {
std::string with_equal = remove_opts[j] + "=";
if (strncmp(with_equal.c_str(), argv[i], with_equal.size()) == 0) {
skip = true;
} else if (strncmp(remove_opts[j].c_str(), argv[i], remove_opts[j].size())
== 0) {
skip = true;
skip_next = true;
}
}
if (skip == false && skip_next == false) {
strm << argv[i] << " ";
} else if (skip == false && skip_next == true) {
skip_next = false;
}
}
return strm.str();
}
bool call_graph_laplacian(const std::string& mpi_args,
const std::string& filename, const std::string& format,
const bool normalized_cut, const bool ratio_cut, const std::string& args) {
std::stringstream strm;
if(mpi_args.length() > 0)
strm << "mpiexec " << mpi_args << " ";
strm << "./graph_laplacian ";
strm << " --graph=" << filename;
strm << " --format=" << format;
// strm << " --normalized-cut=" << normalized_cut;
// strm << " --ratio-cut=" << ratio_cut;
strm << " " << args;
std::cout << "CALLING >" << strm.str() << std::endl;
int sys_ret = system(strm.str().c_str());
if (sys_ret != 0) {
std::cout << "system call fails" << std::endl;
return false;
}
return true;
}
void make_initial_vector_file(const std::string& filename, const size_t num_data){
std::ofstream ofs((filename + ".init").c_str());
for(size_t i=0;i<num_data;++i){
ofs << 0.1*((i+1)%10)/10.0 << "\n";
}
ofs.close();
}
bool call_svd(const std::string& mpi_args, const std::string& filename,
const std::string& svd_dir, const size_t num_clusters, const size_t rank,
const size_t num_data, const std::string& args) {
make_initial_vector_file(filename, num_data+1);
std::stringstream strm;
if(mpi_args.length() > 0)
strm << "mpiexec " << mpi_args << " ";
strm << svd_dir << "svd " + filename + ".glap";
strm << " --rows=" << num_data+1;
strm << " --cols=" << num_data;
strm << " --nsv=" << num_clusters;
strm << " --nv=" << rank;
strm << " --max_iter=4";
strm << " --quiet=1";
strm << " --save_vectors=1";
strm << " --ortho_repeats=3";
//strm << " --id=1";
//strm << " --prediction=" << filename + ".";
strm << " --prediction=" << filename;
strm << " --initial_vector=" << filename + ".init";
strm << " " << args;
std::cout << "CALLING >" << strm.str() << std::endl;
int sys_ret = system(strm.str().c_str());
if (sys_ret != 0) {
std::cout << "system call fails" << std::endl;
return false;
}
return true;
}
bool call_eigen_vector_normalization(const std::string& mpi_args,
const std::string& filename, const size_t num_clusters, const size_t rank,
const size_t num_data, const std::string& args) {
std::stringstream strm;
if(mpi_args.length() > 0)
strm << "mpiexec " << mpi_args << " ";
strm << "./eigen_vector_normalization";
strm << " --data=" << filename;
strm << " --clusters=" << num_clusters;
strm << " --rank=" << rank;
strm << " --data-num=" << num_data;
strm << " " << args;
std::cout << "CALLING >" << strm.str() << std::endl;
int sys_ret = system(strm.str().c_str());
if (sys_ret != 0) {
std::cout << "system call fails" << std::endl;
return false;
}
return true;
}
bool call_kmeans(const std::string& mpi_args, const std::string& filename,
const std::string& kmeans_dir, const size_t num_clusters,
const std::string& args) {
//call svd
std::stringstream strm;
if(mpi_args.length() > 0)
strm << "mpiexec " << mpi_args << " ";
strm << kmeans_dir << "kmeans ";
strm << " --data " << filename << ".compressed";
strm << " --clusters " << num_clusters;
strm << " --output-data " << filename << ".result";
strm << " --id=1";
strm << " " << args;
std::cout << "CALLING >" << strm.str() << std::endl;
int sys_ret = system(strm.str().c_str());
if (sys_ret != 0) {
std::cout << "system call fails" << std::endl;
return false;
}
return true;
}
//select good rank
int get_lanczos_rank(const size_t num_clusters, const size_t num_data) {
size_t rank = 1;
if (num_data < 1000) {
if (num_clusters + 10 <= num_data)
rank = num_clusters + 10;
else
rank = num_data;
} else if (num_data < 10000) {
rank = num_clusters + 25;
} else if (num_data < 100000) {
rank = num_clusters + 50;
} else if (num_data < 1000000) {
rank = num_clusters + 80;
} else {
rank = num_clusters + 100;
}
return rank;
// return num_clusters + 1;
}
int main(int argc, char** argv) {
std::cout << "Graph partitioning (normalized cut)\n\n";
std::string graph_dir;
std::string format = "adj";
std::string svd_dir = "../collaborative_filtering/";
std::string kmeans_dir = "../clustering/";
std::string mpi_args;
size_t num_partitions = 2;
bool normalized_cut = true;
bool ratio_cut = false;
size_t sv = 0;
//parse command line
graphlab::command_line_options clopts(
"Graph partitioning (normalized cut)");
clopts.attach_option("graph", graph_dir,
"The graph file. This is not optional. Vertex ids must start from 1 "
"and must not skip any numbers.");
clopts.attach_option("format", format,
"The graph file format. If \"weight\" is set, the program will read "
"the data file where each line holds [id1] [id2] [weight].");
clopts.attach_option("partitions", num_partitions,
"The number of partitions to create");
clopts.attach_option("svd-dir", svd_dir,
"Path to the directory of Graphlab svd");
clopts.attach_option("kmeans-dir", kmeans_dir,
"Path to the directory of Graphlab kmeans");
clopts.attach_option("mpi-args", mpi_args,
"If set, will execute mipexec with the given arguments. "
"For example, --mpi-args=\"-n [N machines] --hostfile [host file]\"");
clopts.attach_option("sv", sv,
"Number of vectors in each iteration in the Lanczos svd.");
// clopts.attach_option("normalized-cut", normalized_cut,
// "do normalized cut");
// clopts.attach_option("ratio-cut", ratio_cut,
// "do ratio cut");
if (!clopts.parse(argc, argv))
return EXIT_FAILURE;
if (graph_dir == "") {
std::cout << "--graph is not optional\n";
return EXIT_FAILURE;
}
// if(normalized_cut == true && ratio_cut == true){
// std::cout << "Both normalized-cut and ratio-cut are true. Ratio cut is selected.\n";
// normalized_cut = false;
// }else if(normalized_cut == false && ratio_cut == false){
// std::cout << "Both normalized-cut and ratio-cut are false. Ratio cut is selected.\n";
// ratio_cut = true;
// }
std::vector<std::string> remove_opts;
remove_opts.push_back("--graph");
remove_opts.push_back("--format");
remove_opts.push_back("--svd-dir");
remove_opts.push_back("--kmeans-dir");
remove_opts.push_back("--partitions");
remove_opts.push_back("--mpi-args");
remove_opts.push_back("--sv");
// remove_opts.push_back("--normalized-cut");
// remove_opts.push_back("--ratio-cut");
std::string other_args = get_arg_str_without(argc, argv, remove_opts);
//construct graph laplacian
if (call_graph_laplacian(mpi_args, graph_dir, format, normalized_cut,
ratio_cut, other_args) == false) {
return EXIT_FAILURE;
}
//eigen value decomposition
//read number of data
size_t num_data = 0;
const std::string datanum_filename = graph_dir + ".datanum";
std::ifstream ifs(datanum_filename.c_str());
if (!ifs) {
std::cout << "can't read number of data." << std::endl;
return false;
}
ifs >> num_data;
//determine the rank of Lanczos method
if(sv == 0){
sv = get_lanczos_rank(num_partitions, num_data);
}else{
if(sv < num_partitions)
sv = num_partitions;
}
if (call_svd(mpi_args, graph_dir, svd_dir, num_partitions, sv, num_data,
other_args) == false) {
return EXIT_FAILURE;
}
if (call_eigen_vector_normalization(mpi_args, graph_dir, num_partitions, sv,
num_data, other_args) == false) {
return EXIT_FAILURE;
}
//kmeans
if (call_kmeans(mpi_args, graph_dir, kmeans_dir, num_partitions, other_args)
== false) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 3,913 |
1,521 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2014-2017 <NAME>, 2017-2021 Ta4j Organization & respective
* authors (see AUTHORS)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.ta4j.core.indicators;
import org.ta4j.core.Bar;
import org.ta4j.core.BarSeries;
import org.ta4j.core.num.Num;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* Distance From Moving Average (close - MA)/MA
*
* @see <a href=
* "https://school.stockcharts.com/doku.php?id=technical_indicators:distance_from_ma">
* https://school.stockcharts.com/doku.php?id=technical_indicators:distance_from_ma
* </a>
*/
public class DistanceFromMAIndicator extends CachedIndicator<Num> {
private static final Set<Class> supportedMovingAverages = new HashSet<>(
Arrays.asList(EMAIndicator.class, DoubleEMAIndicator.class, TripleEMAIndicator.class, SMAIndicator.class,
WMAIndicator.class, ZLEMAIndicator.class, HMAIndicator.class, KAMAIndicator.class,
LWMAIndicator.class, AbstractEMAIndicator.class, MMAIndicator.class));
private final CachedIndicator movingAverage;
/**
*
* @param series the bar series {@link BarSeries}.
* @param movingAverage the moving average.
*/
public DistanceFromMAIndicator(BarSeries series, CachedIndicator movingAverage) {
super(series);
if (!(supportedMovingAverages.contains(movingAverage.getClass()))) {
throw new IllegalArgumentException(
"Passed indicator must be a moving average based indicator. " + movingAverage.toString());
}
this.movingAverage = movingAverage;
}
@Override
protected Num calculate(int index) {
Bar currentBar = getBarSeries().getBar(index);
Num closePrice = currentBar.getClosePrice();
Num maValue = (Num) movingAverage.getValue(index);
return (closePrice.minus(maValue)).dividedBy(maValue);
}
}
| 1,015 |
1,144 |
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via <EMAIL> or http://www.compiere.org/license.html *
*****************************************************************************/
/** Generated Model - DO NOT CHANGE */
package de.metas.document.refid.model;
import java.sql.ResultSet;
import java.util.Properties;
/** Generated Model for C_ReferenceNo
* @author Adempiere (generated)
*/
@SuppressWarnings("javadoc")
public class X_C_ReferenceNo extends org.compiere.model.PO implements I_C_ReferenceNo, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 162203464L;
/** Standard Constructor */
public X_C_ReferenceNo (Properties ctx, int C_ReferenceNo_ID, String trxName)
{
super (ctx, C_ReferenceNo_ID, trxName);
/** if (C_ReferenceNo_ID == 0)
{
setC_ReferenceNo_ID (0);
setC_ReferenceNo_Type_ID (0);
setReferenceNo (null);
} */
}
/** Load Constructor */
public X_C_ReferenceNo (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_ReferenceNo[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Reference No.
@param C_ReferenceNo_ID Reference No */
@Override
public void setC_ReferenceNo_ID (int C_ReferenceNo_ID)
{
if (C_ReferenceNo_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_ReferenceNo_ID, Integer.valueOf(C_ReferenceNo_ID));
}
/** Get Reference No.
@return Reference No */
@Override
public int getC_ReferenceNo_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.document.refid.model.I_C_ReferenceNo_Type getC_ReferenceNo_Type() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_ReferenceNo_Type_ID, de.metas.document.refid.model.I_C_ReferenceNo_Type.class);
}
@Override
public void setC_ReferenceNo_Type(de.metas.document.refid.model.I_C_ReferenceNo_Type C_ReferenceNo_Type)
{
set_ValueFromPO(COLUMNNAME_C_ReferenceNo_Type_ID, de.metas.document.refid.model.I_C_ReferenceNo_Type.class, C_ReferenceNo_Type);
}
/** Set Reference No Type.
@param C_ReferenceNo_Type_ID Reference No Type */
@Override
public void setC_ReferenceNo_Type_ID (int C_ReferenceNo_Type_ID)
{
if (C_ReferenceNo_Type_ID < 1)
set_Value (COLUMNNAME_C_ReferenceNo_Type_ID, null);
else
set_Value (COLUMNNAME_C_ReferenceNo_Type_ID, Integer.valueOf(C_ReferenceNo_Type_ID));
}
/** Get Reference No Type.
@return Reference No Type */
@Override
public int getC_ReferenceNo_Type_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_ReferenceNo_Type_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Manuell.
@param IsManual
Dies ist ein manueller Vorgang
*/
@Override
public void setIsManual (boolean IsManual)
{
set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual));
}
/** Get Manuell.
@return Dies ist ein manueller Vorgang
*/
@Override
public boolean isManual ()
{
Object oo = get_Value(COLUMNNAME_IsManual);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Referenznummer.
@param ReferenceNo
Ihre Kunden- oder Lieferantennummer beim Geschäftspartner
*/
@Override
public void setReferenceNo (java.lang.String ReferenceNo)
{
set_Value (COLUMNNAME_ReferenceNo, ReferenceNo);
}
/** Get Referenznummer.
@return Ihre Kunden- oder Lieferantennummer beim Geschäftspartner
*/
@Override
public java.lang.String getReferenceNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_ReferenceNo);
}
}
| 1,983 |
456 |
{"ast":null,"code":"import * as React from 'react';\nimport ThemeContext from \"./ThemeContext\";\nexport default function useTheme() {\n var theme = React.useContext(ThemeContext);\n return theme;\n}","map":{"version":3,"sources":["useTheme.tsx"],"names":["theme","React"],"mappings":"AAAA,OAAO,KAAP,KAAA,MAAA,OAAA;AACA,OAAA,YAAA;AAEA,eAAe,SAAA,QAAA,GAAoB;AACjC,MAAMA,KAAK,GAAGC,KAAK,CAALA,UAAAA,CAAd,YAAcA,CAAd;AAEA,SAAA,KAAA;AACD","sourcesContent":["import * as React from 'react';\nimport ThemeContext from './ThemeContext';\n\nexport default function useTheme() {\n const theme = React.useContext(ThemeContext);\n\n return theme;\n}\n"]},"metadata":{},"sourceType":"module"}
| 251 |
372 |
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* include/k5-json.h - JSON declarations */
/*
* Copyright (c) 2010 <NAME>
* (Royal Institute of Technology, Stockholm, Sweden).
* All rights reserved.
*
* Portions Copyright (c) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Copyright (C) 2012 by the Massachusetts Institute of Technology.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef K5_JSON_H
#define K5_JSON_H
#include <stddef.h>
#define K5_JSON_TID_NUMBER 0
#define K5_JSON_TID_NULL 1
#define K5_JSON_TID_BOOL 2
#define K5_JSON_TID_MEMORY 128
#define K5_JSON_TID_ARRAY 129
#define K5_JSON_TID_OBJECT 130
#define K5_JSON_TID_STRING 131
/*
* The k5_json_value C type can represent any kind of JSON value. It has no
* static type safety since it is represented using a void pointer, so be
* careful with it. Its type can be checked dynamically with k5_json_get_tid()
* and the above constants.
*/
typedef void *k5_json_value;
typedef unsigned int k5_json_tid;
k5_json_tid k5_json_get_tid(k5_json_value val);
/*
* k5_json_value objects are reference-counted. These functions increment and
* decrement the refcount, possibly freeing the value. k5_json_retain returns
* its argument and always succeeds. Both functions gracefully accept NULL.
*/
void *k5_json_retain(k5_json_value val);
void k5_json_release(k5_json_value val);
/*
* Unless otherwise specified, the following functions return NULL on error
* (generally only if out of memory) if they return a pointer type, or 0 on
* success and -1 on failure if they return int.
*/
/*
* Null
*/
typedef struct k5_json_null_st *k5_json_null;
k5_json_null k5_json_null_create(void);
/*
* Boolean
*/
typedef struct k5_json_bool_st *k5_json_bool;
k5_json_bool k5_json_bool_create(int truth);
int k5_json_bool_value(k5_json_bool bval);
/*
* Array
*/
typedef struct k5_json_array_st *k5_json_array;
k5_json_array k5_json_array_create(void);
size_t k5_json_array_length(k5_json_array array);
/* Both of these functions increment the reference count on val. */
int k5_json_array_add(k5_json_array array, k5_json_value val);
void k5_json_array_set(k5_json_array array, size_t idx, k5_json_value val);
/* Get an alias to the idx-th element of array, without incrementing the
* reference count. The caller must check idx against the array length. */
k5_json_value k5_json_array_get(k5_json_array array, size_t idx);
/*
* Object
*/
typedef struct k5_json_object_st *k5_json_object;
typedef void (*k5_json_object_iterator_fn)(void *arg, const char *key,
k5_json_value val);
k5_json_object k5_json_object_create(void);
void k5_json_object_iterate(k5_json_object obj,
k5_json_object_iterator_fn func, void *arg);
/* Return the number of mappings in an object. */
size_t k5_json_object_count(k5_json_object obj);
/* Store val into object at key, incrementing val's reference count. */
int k5_json_object_set(k5_json_object obj, const char *key, k5_json_value val);
/* Get an alias to the object's value for key, without incrementing the
* reference count. Returns NULL if there is no value for key. */
k5_json_value k5_json_object_get(k5_json_object obj, const char *key);
/*
* String
*/
typedef struct k5_json_string_st *k5_json_string;
k5_json_string k5_json_string_create(const char *string);
k5_json_string k5_json_string_create_len(const void *data, size_t len);
const char *k5_json_string_utf8(k5_json_string string);
/* Create a base64 string value from binary data. */
k5_json_string k5_json_string_create_base64(const void *data, size_t len);
/* Decode a base64 string. Returns NULL and *len_out == 0 if out of memory,
* NULL and *len == SIZE_MAX if string's contents aren't valid base64. */
void *k5_json_string_unbase64(k5_json_string string, size_t *len_out);
/*
* Number
*/
typedef struct k5_json_number_st *k5_json_number;
k5_json_number k5_json_number_create(long long number);
long long k5_json_number_value(k5_json_number number);
/*
* JSON encoding and decoding
*/
char *k5_json_encode(k5_json_value val);
k5_json_value k5_json_decode(const char *str);
#endif /* K5_JSON_H */
| 2,342 |
589 |
package rocks.inspectit.server.processor.impl;
import javax.persistence.EntityManager;
import rocks.inspectit.server.processor.AbstractCmrDataProcessor;
import rocks.inspectit.shared.all.communication.DefaultData;
import rocks.inspectit.shared.all.communication.data.SqlStatementData;
/**
* Processor that sets the correct exclusive time for {@link SqlStatementData} because it's always
* known.
*
* @author <NAME>
*
*/
public class SqlExclusiveTimeCmrProcessor extends AbstractCmrDataProcessor {
/**
* {@inheritDoc}
*/
@Override
protected void processData(DefaultData defaultData, EntityManager entityManager) {
SqlStatementData sqlStatementData = (SqlStatementData) defaultData;
sqlStatementData.setExclusiveCount(1L);
sqlStatementData.setExclusiveDuration(sqlStatementData.getDuration());
sqlStatementData.calculateExclusiveMax(sqlStatementData.getDuration());
sqlStatementData.calculateExclusiveMin(sqlStatementData.getDuration());
}
/**
* {@inheritDoc}
*/
@Override
public boolean canBeProcessed(DefaultData defaultData) {
return defaultData instanceof SqlStatementData;
}
}
| 338 |
307 |
/*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
#ifndef _FRED_XSTR_HASH_TABLE_HEADER_FILE
#define _FRED_XSTR_HASH_TABLE_HEADER_FILE
// -----------------------------------------------------------------------------------------------
// HASH DEFINES/VARS
//
// -----------------------------------------------------------------------------------------------
// HASH FUNCTIONS
//
// initialize the hash table
void fhash_init();
// set the hash table to be active for parsing
void fhash_activate();
// set the hash table to be inactive for parsing
void fhash_deactivate();
// if the hash table is active
int fhash_active();
// flush out the hash table, freeing up everything
void fhash_flush();
// add a string with the given id# to the hash table
void fhash_add_str(const char *str, int id);
// determine if the passed string exists in the table
// returns : -2 if the string doesn't exit, or >= -1 as the string id # otherwise
int fhash_string_exists(const char *str);
#endif
| 315 |
777 |
<reponame>google-ar/chromium
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CC_LAYERS_UI_RESOURCE_LAYER_IMPL_H_
#define CC_LAYERS_UI_RESOURCE_LAYER_IMPL_H_
#include <string>
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "cc/base/cc_export.h"
#include "cc/layers/layer_impl.h"
#include "cc/resources/resource_provider.h"
#include "cc/resources/ui_resource_client.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
namespace base {
class DictionaryValue;
}
namespace cc {
class CC_EXPORT UIResourceLayerImpl : public LayerImpl {
public:
static std::unique_ptr<UIResourceLayerImpl> Create(LayerTreeImpl* tree_impl,
int id) {
return base::WrapUnique(new UIResourceLayerImpl(tree_impl, id));
}
~UIResourceLayerImpl() override;
void SetUIResourceId(UIResourceId uid);
void SetImageBounds(const gfx::Size& image_bounds);
// Sets a UV transform to be used at draw time. Defaults to (0, 0) and (1, 1).
void SetUV(const gfx::PointF& top_left, const gfx::PointF& bottom_right);
// Sets an opacity value per vertex. It will be multiplied by the layer
// opacity value.
void SetVertexOpacity(const float vertex_opacity[4]);
std::unique_ptr<LayerImpl> CreateLayerImpl(LayerTreeImpl* tree_impl) override;
void PushPropertiesTo(LayerImpl* layer) override;
bool WillDraw(DrawMode draw_mode,
ResourceProvider* resource_provider) override;
void AppendQuads(RenderPass* render_pass,
AppendQuadsData* append_quads_data) override;
std::unique_ptr<base::DictionaryValue> LayerTreeAsJson() override;
protected:
UIResourceLayerImpl(LayerTreeImpl* tree_impl, int id);
// The size of the resource bitmap in pixels.
gfx::Size image_bounds_;
UIResourceId ui_resource_id_;
gfx::PointF uv_top_left_;
gfx::PointF uv_bottom_right_;
float vertex_opacity_[4];
private:
const char* LayerTypeAsString() const override;
DISALLOW_COPY_AND_ASSIGN(UIResourceLayerImpl);
};
} // namespace cc
#endif // CC_LAYERS_UI_RESOURCE_LAYER_IMPL_H_
| 850 |
1,319 |
<reponame>zhangyimi/Research<filename>ST_DM/KDD2021-MSTPAC/code/ST-PAC/utils/logger.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
"""
logger utilities.
"""
import time
import sys
import re
import os
import six
import numpy as np
import logging
import logging.handlers
"""
******functions for string processing******
"""
def pattern_match(pattern, line):
"""
Check whether a string is matched
Args:
pattern: mathing pattern
line : input string
Returns:
True/False
"""
if re.match(pattern, line):
return True
else:
return False
"""
******functions for parameter processing******
"""
def print_progress(task_name, percentage, style=0):
"""
Print progress bar
Args:
task_name: The name of the current task
percentage: Current progress
style: Progress bar form
"""
styles = ['#', '█']
mark = styles[style] * percentage
mark += ' ' * (100 - percentage)
status = '%d%%' % percentage if percentage < 100 else 'Finished'
sys.stdout.write('%+20s [%s] %s\r' % (task_name, mark, status))
sys.stdout.flush()
time.sleep(0.002)
def display_args(name, args):
"""
Print parameter information
Args:
name: logger instance name
args: Input parameter dictionary
"""
logger = logging.getLogger(name)
logger.info("The arguments passed by command line is :")
for k, v in sorted(v for v in vars(args).items()):
logger.info("{}:\t{}".format(k, v))
def import_class(module_path, module_name, class_name):
"""
Load class dynamically
Args:
module_path: The current path of the module
module_name: The module name
class_name: The name of class in the import module
Return:
Return the attribute value of the class object
"""
if module_path:
sys.path.append(module_path)
module = __import__(module_name)
return getattr(module, class_name)
def str2bool(v):
"""
String to Boolean
"""
# because argparse does not support to parse "true, False" as python
# boolean directly
return v.lower() in ("true", "t", "1")
class ArgumentGroup(object):
"""
Argument Class
"""
def __init__(self, parser, title, des):
self._group = parser.add_argument_group(title=title, description=des)
def add_arg(self, name, type, default, help, **kwargs):
"""
Add argument
"""
type = str2bool if type == bool else type
self._group.add_argument(
"--" + name,
default=default,
type=type,
help=help + ' Default: %(default)s.',
**kwargs)
def print_arguments(args):
"""
Print Arguments
"""
print('----------- Configuration Arguments -----------')
for arg, value in sorted(six.iteritems(vars(args))):
print('%s: %s' % (arg, value))
print('------------------------------------------------')
def init_log(
log_path,
level=logging.INFO,
when="D",
backup=7,
format="%(levelname)s: %(asctime)s - %(filename)s:%(lineno)d * %(message)s",
datefmt=None):
"""
init_log - initialize log module
Args:
log_path - Log file path prefix.
Log data will go to two files: log_path.log and log_path.log.wf
Any non-exist parent directories will be created automatically
level - msg above the level will be displayed
DEBUG < INFO < WARNING < ERROR < CRITICAL
the default value is logging.INFO
when - how to split the log file by time interval
'S' : Seconds
'M' : Minutes
'H' : Hours
'D' : Days
'W' : Week day
default value: 'D'
format - format of the log
default format:
%(levelname)s: %(asctime)s: %(filename)s:%(lineno)d * %(thread)d %(message)s
INFO: 12-09 18:02:42: log.py:40 * 139814749787872 HELLO WORLD
backup - how many backup file to keep
default value: 7
Raises:
OSError: fail to create log directories
IOError: fail to open log file
"""
formatter = logging.Formatter(format, datefmt)
logger = logging.getLogger()
logger.setLevel(level)
if len(logger.handlers) > 0:
logger.handlers = []
# console handler
console_handler = logging.StreamHandler(sys.stderr)
console_handler.setLevel(logging.INFO)
console_handler.setFormatter(logging.Formatter(
"%(levelname)s: %(asctime)s - %(filename)s:%(lineno)d * %(message)s", None))
logger.addHandler(console_handler)
dir = os.path.dirname(log_path)
if not os.path.isdir(dir):
os.makedirs(dir)
handler = logging.handlers.TimedRotatingFileHandler(
log_path + ".log", when=when, backupCount=backup)
handler.setLevel(level)
handler.setFormatter(formatter)
logger.addHandler(handler)
handler = logging.handlers.TimedRotatingFileHandler(
log_path + ".log.wf", when=when, backupCount=backup)
handler.setLevel(logging.WARNING)
handler.setFormatter(formatter)
logger.addHandler(handler)
def set_level(level):
"""
Reak-time set log level
"""
logger = logging.getLogger()
logger.setLevel(level)
logging.info('log level is set to : %d' % level)
def get_level():
"""
get Real-time log level
"""
logger = logging.getLogger()
return logger.level
| 2,609 |
2,900 |
<filename>src/test/java/com/fasterxml/jackson/databind/struct/TestPOJOAsArray.java
package com.fasterxml.jackson.databind.struct;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat.Shape;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
public class TestPOJOAsArray extends BaseMapTest
{
static class PojoAsArrayWrapper
{
@JsonFormat(shape=JsonFormat.Shape.ARRAY)
public PojoAsArray value;
public PojoAsArrayWrapper() { }
public PojoAsArrayWrapper(String name, int x, int y, boolean c) {
value = new PojoAsArray(name, x, y, c);
}
}
@JsonPropertyOrder(alphabetic=true)
static class NonAnnotatedXY {
public int x, y;
public NonAnnotatedXY() { }
public NonAnnotatedXY(int x0, int y0) {
x = x0;
y = y0;
}
}
// note: must be serialized/deserialized alphabetically; fields NOT declared in that order
@JsonPropertyOrder(alphabetic=true)
static class PojoAsArray
{
public int x, y;
public String name;
public boolean complete;
public PojoAsArray() { }
public PojoAsArray(String name, int x, int y, boolean c) {
this.name = name;
this.x = x;
this.y = y;
this.complete = c;
}
}
@JsonPropertyOrder(alphabetic=true)
@JsonFormat(shape=JsonFormat.Shape.ARRAY)
static class FlatPojo
{
public int x, y;
public String name;
public boolean complete;
public FlatPojo() { }
public FlatPojo(String name, int x, int y, boolean c) {
this.name = name;
this.x = x;
this.y = y;
this.complete = c;
}
}
static class ForceArraysIntrospector extends JacksonAnnotationIntrospector
{
private static final long serialVersionUID = 1L;
@Override
public JsonFormat.Value findFormat(Annotated a) {
return new JsonFormat.Value().withShape(JsonFormat.Shape.ARRAY);
}
}
static class A {
public B value = new B();
}
@JsonPropertyOrder(alphabetic=true)
static class B {
public int x = 1;
public int y = 2;
}
@JsonFormat(shape=Shape.ARRAY)
static class SingleBean {
public String name = "foo";
}
@JsonPropertyOrder(alphabetic=true)
@JsonFormat(shape=Shape.ARRAY)
static class TwoStringsBean {
public String bar = null;
public String foo = "bar";
}
@JsonFormat(shape=JsonFormat.Shape.ARRAY)
@JsonPropertyOrder(alphabetic=true)
static class AsArrayWithMap
{
public Map<Integer,Integer> attrs;
public AsArrayWithMap() { }
public AsArrayWithMap(int x, int y) {
attrs = new HashMap<Integer,Integer>();
attrs.put(x, y);
}
}
@JsonFormat(shape=JsonFormat.Shape.ARRAY)
static class CreatorWithIndex {
protected int _a, _b;
@JsonCreator
public CreatorWithIndex(@JsonProperty(index=0, value="a") int a,
@JsonProperty(index=1, value="b") int b) {
this._a = a;
this._b = b;
}
}
/*
/*****************************************************
/* Basic tests
/*****************************************************
*/
private final static ObjectMapper MAPPER = new ObjectMapper();
/**
* Test that verifies that property annotation works
*/
public void testReadSimplePropertyValue() throws Exception
{
String json = "{\"value\":[true,\"Foobar\",42,13]}";
PojoAsArrayWrapper p = MAPPER.readValue(json, PojoAsArrayWrapper.class);
assertNotNull(p.value);
assertTrue(p.value.complete);
assertEquals("Foobar", p.value.name);
assertEquals(42, p.value.x);
assertEquals(13, p.value.y);
}
/**
* Test that verifies that Class annotation works
*/
public void testReadSimpleRootValue() throws Exception
{
String json = "[false,\"Bubba\",1,2]";
FlatPojo p = MAPPER.readValue(json, FlatPojo.class);
assertFalse(p.complete);
assertEquals("Bubba", p.name);
assertEquals(1, p.x);
assertEquals(2, p.y);
}
/**
* Test that verifies that property annotation works
*/
public void testWriteSimplePropertyValue() throws Exception
{
String json = MAPPER.writeValueAsString(new PojoAsArrayWrapper("Foobar", 42, 13, true));
// will have wrapper POJO, then POJO-as-array..
assertEquals("{\"value\":[true,\"Foobar\",42,13]}", json);
}
/**
* Test that verifies that Class annotation works
*/
public void testWriteSimpleRootValue() throws Exception
{
String json = MAPPER.writeValueAsString(new FlatPojo("Bubba", 1, 2, false));
// will have wrapper POJO, then POJO-as-array..
assertEquals("[false,\"Bubba\",1,2]", json);
}
// [Issue#223]
public void testNullColumn() throws Exception
{
assertEquals("[null,\"bar\"]", MAPPER.writeValueAsString(new TwoStringsBean()));
}
/*
/*****************************************************
/* Compatibility with "single-elem as array" feature
/*****************************************************
*/
public void testSerializeAsArrayWithSingleProperty() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
String json = mapper.writeValueAsString(new SingleBean());
assertEquals("\"foo\"", json);
}
public void testBeanAsArrayUnwrapped() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
SingleBean result = mapper.readValue("[\"foobar\"]", SingleBean.class);
assertNotNull(result);
assertEquals("foobar", result.name);
}
/*
/*****************************************************
/* Round-trip tests
/*****************************************************
*/
public void testAnnotationOverride() throws Exception
{
// by default, POJOs become JSON Objects;
assertEquals("{\"value\":{\"x\":1,\"y\":2}}", MAPPER.writeValueAsString(new A()));
// but override should change it:
ObjectMapper mapper2 = new ObjectMapper();
mapper2.setAnnotationIntrospector(new ForceArraysIntrospector());
assertEquals("[[1,2]]", mapper2.writeValueAsString(new A()));
// and allow reading back, too
}
public void testWithMaps() throws Exception
{
AsArrayWithMap input = new AsArrayWithMap(1, 2);
String json = MAPPER.writeValueAsString(input);
AsArrayWithMap output = MAPPER.readValue(json, AsArrayWithMap.class);
assertNotNull(output);
assertNotNull(output.attrs);
assertEquals(1, output.attrs.size());
assertEquals(Integer.valueOf(2), output.attrs.get(1));
}
public void testSimpleWithIndex() throws Exception
{
// as POJO:
// CreatorWithIndex value = MAPPER.readValue(aposToQuotes("{'b':1,'a':2}"),
CreatorWithIndex value = MAPPER.readValue(a2q("[2,1]"),
CreatorWithIndex.class);
assertEquals(2, value._a);
assertEquals(1, value._b);
}
public void testWithConfigOverrides() throws Exception
{
ObjectMapper mapper = jsonMapperBuilder()
.withConfigOverride(NonAnnotatedXY.class,
o -> o.setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.ARRAY)))
.build();
final String json = mapper.writeValueAsString(new NonAnnotatedXY(2, 3));
assertEquals("[2,3]", json);
// also, read it back
NonAnnotatedXY result = mapper.readValue(json, NonAnnotatedXY.class);
assertNotNull(result);
assertEquals(3, result.y);
}
/*
/*****************************************************
/* Failure tests
/*****************************************************
*/
public void testUnknownExtraProp() throws Exception
{
String json = "{\"value\":[true,\"Foobar\",42,13, false]}";
try {
MAPPER.readValue(json, PojoAsArrayWrapper.class);
fail("should not pass with extra element");
} catch (MismatchedInputException e) {
verifyException(e, "Unexpected JSON values");
}
// but actually fine if skip-unknown set
PojoAsArrayWrapper v = MAPPER.readerFor(PojoAsArrayWrapper.class)
.without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.readValue(json);
assertNotNull(v);
// note: +1 for both so
assertEquals(v.value.x, 42);
assertEquals(v.value.y, 13);
assertTrue(v.value.complete);
assertEquals("Foobar", v.value.name);
}
}
| 3,923 |
435 |
<filename>pycon-lt-2014/videos/domantas-jackunas-openerp-ir-tryton.json
{
"description": "<NAME>\u016bnas: OpenERP ir Tryton",
"duration": 1882,
"recorded": "2014-05-10",
"speakers": [
"<NAME>\u016bnas"
],
"thumbnail_url": "https://i.ytimg.com/vi/QJBTSXezD_U/hqdefault.jpg",
"title": "OpenERP ir Tryton",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=QJBTSXezD_U"
}
]
}
| 209 |
310 |
"""
Copyright (c) 2021 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from collections import deque
from typing import List, Tuple
import torch
import numpy as np
def max_reduce_like(input_: torch.Tensor, ref_tensor_shape: List[int]) -> torch.Tensor:
numel = np.prod(ref_tensor_shape)
if numel == 1:
retval = input_.max()
for _ in ref_tensor_shape:
retval.unsqueeze_(-1)
return retval
tmp_max = input_
for dim_idx, dim in enumerate(ref_tensor_shape):
if dim == 1:
tmp_max, _ = torch.max(tmp_max, dim_idx, keepdim=True)
return tmp_max
def min_reduce_like(input_: torch.Tensor, ref_tensor_shape: List[int]):
numel = np.prod(ref_tensor_shape)
if numel == 1:
retval = input_.min()
for _ in ref_tensor_shape:
retval.unsqueeze_(-1)
return retval
tmp_min = input_
for dim_idx, dim in enumerate(ref_tensor_shape):
if dim == 1:
tmp_min, _ = torch.min(tmp_min, dim_idx, keepdim=True)
return tmp_min
def percentile_reduce_like(input_: torch.Tensor, ref_tensor_shape: List[int], q: float):
numel = np.prod(ref_tensor_shape)
if numel == 1:
return torch.from_numpy(np.array([np.percentile(input_.cpu().numpy(), q)])).to(dtype=torch.float)
tmp = input_
for dim_idx, dim in enumerate(ref_tensor_shape):
if dim == 1:
numpy_tmp = np.percentile(tmp.cpu().numpy(), q, axis=dim_idx, keepdims=True)
tmp = torch.from_numpy(numpy_tmp).to(dtype=torch.float)
return tmp
def get_channel_count_and_dim_idx(scale_shape: List[int]) -> Tuple[int, int]:
channel_dim_idx = 0
channel_count = 1
for dim_idx, dim in enumerate(scale_shape):
if dim != 1:
channel_dim_idx = dim_idx
channel_count = dim
return channel_count, channel_dim_idx
def expand_like(input_: torch.Tensor, scale_shape: List[int]) -> torch.Tensor:
retval = input_
count, idx = get_channel_count_and_dim_idx(scale_shape)
assert input_.numel() == count
assert len(input_.size()) == 1
for _ in range(0, idx):
retval = retval.unsqueeze(0)
for _ in range(idx + 1, len(scale_shape)):
retval = retval.unsqueeze(-1)
return retval
def split_into_channels(input_: np.ndarray, scale_shape: List[int]) -> List[np.ndarray]:
channel_count, channel_dim_idx = get_channel_count_and_dim_idx(scale_shape)
channel_first_tensor = np.moveaxis(input_, channel_dim_idx, 0)
if channel_count == 1:
return [channel_first_tensor]
ret_list = []
for i in range(channel_count):
ret_list.append(channel_first_tensor[i, ...])
return ret_list
def get_per_channel_history(raw_input_history: deque, scale_shape: List[int], discard_zeros=False) -> List:
channel_count, _ = get_channel_count_and_dim_idx(scale_shape)
per_channel_history = [None for i in range(channel_count)]
for _ in range(len(raw_input_history)):
entry = raw_input_history.popleft()
split = split_into_channels(entry, scale_shape)
for i in range(channel_count):
flat_channel_split = split[i].flatten()
if discard_zeros:
# For post-RELU quantizers exact zeros may prevail and lead to
# zero mean and MAD - discard them
flat_channel_split = flat_channel_split[flat_channel_split != 0]
if per_channel_history[i] is None:
per_channel_history[i] = flat_channel_split
else:
per_channel_history[i] = np.concatenate([per_channel_history[i], flat_channel_split])
raw_input_history.append(entry)
return per_channel_history
| 1,768 |
715 |
<gh_stars>100-1000
/*
Simple DirectMedia Layer
Copyright (C) 1997-2021 <NAME> <<EMAIL>>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
#if SDL_VIDEO_DRIVER_DIRECTFB
#include "SDL_DirectFB_video.h"
#include "SDL_DirectFB_mouse.h"
#include "SDL_DirectFB_modes.h"
#include "SDL_DirectFB_window.h"
#include "../SDL_sysvideo.h"
#include "../../events/SDL_mouse_c.h"
static SDL_Cursor *DirectFB_CreateDefaultCursor(void);
static SDL_Cursor *DirectFB_CreateCursor(SDL_Surface * surface,
int hot_x, int hot_y);
static int DirectFB_ShowCursor(SDL_Cursor * cursor);
static void DirectFB_FreeCursor(SDL_Cursor * cursor);
static void DirectFB_WarpMouse(SDL_Window * window, int x, int y);
static const char *arrow[] = {
/* pixels */
"X ",
"XX ",
"X.X ",
"X..X ",
"X...X ",
"X....X ",
"X.....X ",
"X......X ",
"X.......X ",
"X........X ",
"X.....XXXXX ",
"X..X..X ",
"X.X X..X ",
"XX X..X ",
"X X..X ",
" X..X ",
" X..X ",
" X..X ",
" XX ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
};
static SDL_Cursor *
DirectFB_CreateDefaultCursor(void)
{
SDL_VideoDevice *dev = SDL_GetVideoDevice();
SDL_DFB_DEVICEDATA(dev);
DFB_CursorData *curdata;
DFBSurfaceDescription dsc;
SDL_Cursor *cursor;
Uint32 *dest;
int pitch, i, j;
SDL_DFB_ALLOC_CLEAR( cursor, sizeof(*cursor));
SDL_DFB_ALLOC_CLEAR(curdata, sizeof(*curdata));
dsc.flags =
DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS;
dsc.caps = DSCAPS_VIDEOONLY;
dsc.width = 32;
dsc.height = 32;
dsc.pixelformat = DSPF_ARGB;
SDL_DFB_CHECKERR(devdata->dfb->CreateSurface(devdata->dfb, &dsc,
&curdata->surf));
curdata->hotx = 0;
curdata->hoty = 0;
cursor->driverdata = curdata;
SDL_DFB_CHECKERR(curdata->surf->Lock(curdata->surf, DSLF_WRITE,
(void *) &dest, &pitch));
/* Relies on the fact that this is only called with ARGB surface. */
for (i = 0; i < 32; i++)
{
for (j = 0; j < 32; j++)
{
switch (arrow[i][j])
{
case ' ': dest[j] = 0x00000000; break;
case '.': dest[j] = 0xffffffff; break;
case 'X': dest[j] = 0xff000000; break;
}
}
dest += (pitch >> 2);
}
curdata->surf->Unlock(curdata->surf);
return cursor;
error:
return NULL;
}
/* Create a cursor from a surface */
static SDL_Cursor *
DirectFB_CreateCursor(SDL_Surface * surface, int hot_x, int hot_y)
{
SDL_VideoDevice *dev = SDL_GetVideoDevice();
SDL_DFB_DEVICEDATA(dev);
DFB_CursorData *curdata;
DFBSurfaceDescription dsc;
SDL_Cursor *cursor;
Uint32 *dest;
Uint32 *p;
int pitch, i;
SDL_assert(surface->format->format == SDL_PIXELFORMAT_ARGB8888);
SDL_assert(surface->pitch == surface->w * 4);
SDL_DFB_ALLOC_CLEAR( cursor, sizeof(*cursor));
SDL_DFB_ALLOC_CLEAR(curdata, sizeof(*curdata));
dsc.flags =
DSDESC_WIDTH | DSDESC_HEIGHT | DSDESC_PIXELFORMAT | DSDESC_CAPS;
dsc.caps = DSCAPS_VIDEOONLY;
dsc.width = surface->w;
dsc.height = surface->h;
dsc.pixelformat = DSPF_ARGB;
SDL_DFB_CHECKERR(devdata->dfb->CreateSurface(devdata->dfb, &dsc,
&curdata->surf));
curdata->hotx = hot_x;
curdata->hoty = hot_y;
cursor->driverdata = curdata;
SDL_DFB_CHECKERR(curdata->surf->Lock(curdata->surf, DSLF_WRITE,
(void *) &dest, &pitch));
p = surface->pixels;
for (i = 0; i < surface->h; i++)
memcpy((char *) dest + i * pitch,
(char *) p + i * surface->pitch, 4 * surface->w);
curdata->surf->Unlock(curdata->surf);
return cursor;
error:
return NULL;
}
/* Show the specified cursor, or hide if cursor is NULL */
static int
DirectFB_ShowCursor(SDL_Cursor * cursor)
{
SDL_DFB_CURSORDATA(cursor);
SDL_Window *window;
window = SDL_GetFocusWindow();
if (!window)
return -1;
else {
SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
if (display) {
DFB_DisplayData *dispdata =
(DFB_DisplayData *) display->driverdata;
DFB_WindowData *windata = (DFB_WindowData *) window->driverdata;
if (cursor)
SDL_DFB_CHECKERR(windata->dfbwin->
SetCursorShape(windata->dfbwin,
curdata->surf, curdata->hotx,
curdata->hoty));
SDL_DFB_CHECKERR(dispdata->layer->
SetCooperativeLevel(dispdata->layer,
DLSCL_ADMINISTRATIVE));
SDL_DFB_CHECKERR(dispdata->layer->
SetCursorOpacity(dispdata->layer,
cursor ? 0xC0 : 0x00));
SDL_DFB_CHECKERR(dispdata->layer->
SetCooperativeLevel(dispdata->layer,
DLSCL_SHARED));
}
}
return 0;
error:
return -1;
}
/* Free a window manager cursor */
static void
DirectFB_FreeCursor(SDL_Cursor * cursor)
{
SDL_DFB_CURSORDATA(cursor);
SDL_DFB_RELEASE(curdata->surf);
SDL_DFB_FREE(cursor->driverdata);
SDL_DFB_FREE(cursor);
}
/* Warp the mouse to (x,y) */
static void
DirectFB_WarpMouse(SDL_Window * window, int x, int y)
{
SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata;
DFB_WindowData *windata = (DFB_WindowData *) window->driverdata;
int cx, cy;
SDL_DFB_CHECKERR(windata->dfbwin->GetPosition(windata->dfbwin, &cx, &cy));
SDL_DFB_CHECKERR(dispdata->layer->WarpCursor(dispdata->layer,
cx + x + windata->client.x,
cy + y + windata->client.y));
error:
return;
}
#if USE_MULTI_API
static void DirectFB_MoveCursor(SDL_Cursor * cursor);
static void DirectFB_WarpMouse(SDL_Mouse * mouse, SDL_Window * window,
int x, int y);
static void DirectFB_FreeMouse(SDL_Mouse * mouse);
static int id_mask;
static DFBEnumerationResult
EnumMice(DFBInputDeviceID device_id, DFBInputDeviceDescription desc,
void *callbackdata)
{
DFB_DeviceData *devdata = callbackdata;
if ((desc.type & DIDTF_MOUSE) && (device_id & id_mask)) {
SDL_Mouse mouse;
SDL_zero(mouse);
mouse.id = device_id;
mouse.CreateCursor = DirectFB_CreateCursor;
mouse.ShowCursor = DirectFB_ShowCursor;
mouse.MoveCursor = DirectFB_MoveCursor;
mouse.FreeCursor = DirectFB_FreeCursor;
mouse.WarpMouse = DirectFB_WarpMouse;
mouse.FreeMouse = DirectFB_FreeMouse;
mouse.cursor_shown = 1;
SDL_AddMouse(&mouse, desc.name, 0, 0, 1);
devdata->mouse_id[devdata->num_mice++] = device_id;
}
return DFENUM_OK;
}
void
DirectFB_InitMouse(_THIS)
{
SDL_DFB_DEVICEDATA(_this);
devdata->num_mice = 0;
if (devdata->use_linux_input) {
/* try non-core devices first */
id_mask = 0xF0;
devdata->dfb->EnumInputDevices(devdata->dfb, EnumMice, devdata);
if (devdata->num_mice == 0) {
/* try core devices */
id_mask = 0x0F;
devdata->dfb->EnumInputDevices(devdata->dfb, EnumMice, devdata);
}
}
if (devdata->num_mice == 0) {
SDL_Mouse mouse;
SDL_zero(mouse);
mouse.CreateCursor = DirectFB_CreateCursor;
mouse.ShowCursor = DirectFB_ShowCursor;
mouse.MoveCursor = DirectFB_MoveCursor;
mouse.FreeCursor = DirectFB_FreeCursor;
mouse.WarpMouse = DirectFB_WarpMouse;
mouse.FreeMouse = DirectFB_FreeMouse;
mouse.cursor_shown = 1;
SDL_AddMouse(&mouse, "Mouse", 0, 0, 1);
devdata->num_mice = 1;
}
}
void
DirectFB_QuitMouse(_THIS)
{
SDL_DFB_DEVICEDATA(_this);
if (devdata->use_linux_input) {
SDL_MouseQuit();
} else {
SDL_DelMouse(0);
}
}
/* This is called when a mouse motion event occurs */
static void
DirectFB_MoveCursor(SDL_Cursor * cursor)
{
}
/* Warp the mouse to (x,y) */
static void
DirectFB_WarpMouse(SDL_Mouse * mouse, SDL_Window * window, int x, int y)
{
SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
DFB_DisplayData *dispdata = (DFB_DisplayData *) display->driverdata;
DFB_WindowData *windata = (DFB_WindowData *) window->driverdata;
DFBResult ret;
int cx, cy;
SDL_DFB_CHECKERR(windata->dfbwin->GetPosition(windata->dfbwin, &cx, &cy));
SDL_DFB_CHECKERR(dispdata->layer->WarpCursor(dispdata->layer,
cx + x + windata->client.x,
cy + y + windata->client.y));
error:
return;
}
/* Free the mouse when it's time */
static void
DirectFB_FreeMouse(SDL_Mouse * mouse)
{
/* nothing yet */
}
#else /* USE_MULTI_API */
void
DirectFB_InitMouse(_THIS)
{
SDL_DFB_DEVICEDATA(_this);
SDL_Mouse *mouse = SDL_GetMouse();
mouse->CreateCursor = DirectFB_CreateCursor;
mouse->ShowCursor = DirectFB_ShowCursor;
mouse->WarpMouse = DirectFB_WarpMouse;
mouse->FreeCursor = DirectFB_FreeCursor;
SDL_SetDefaultCursor(DirectFB_CreateDefaultCursor());
devdata->num_mice = 1;
}
void
DirectFB_QuitMouse(_THIS)
{
}
#endif
#endif /* SDL_VIDEO_DRIVER_DIRECTFB */
/* vi: set ts=4 sw=4 expandtab: */
| 5,994 |
2,360 |
<filename>var/spack/repos/builtin/packages/ruby-xdg/package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class RubyXdg(RubyPackage):
"""Provides a Ruby implementation of the XDG Base Directory Specification.
"""
homepage = "https://www.alchemists.io/projects/xdg/"
url = "https://rubygems.org/downloads/xdg-2.2.5.gem"
# Source code can be found at https://github.com/bkuhlmann/xdg and
# https://github.com/rubyworks/xdg but I was unable to get it to build
# from source
version('2.2.5', sha256='f3a5f799363852695e457bb7379ac6c4e3e8cb3a51ce6b449ab47fbb1523b913', expand=False)
| 292 |
1,061 |
<gh_stars>1000+
/**
*
*/
package org.sword.wechat4j.event;
/**
* 微信消息类型,大小写对应微信接口,msgType的枚举值
* @author ChengNing
* @date 2014-12-4
*/
public enum MsgType {
event, //事件
text, //文本消息
image,
location,
link,
voice,
video,
shortvideo, //小视频消息
music,
news,
transfer_customer_service;//客服系统
}
| 221 |
14,668 |
<reponame>zealoussnow/chromium<filename>components/background_task_scheduler/android/java/src/org/chromium/components/background_task_scheduler/NativeBackgroundTaskDelegate.java
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.background_task_scheduler;
/**
* Delegate for {@link NativeBackgroundTask} that handles native initialization, and runs the task
* after Chrome is successfully started.
*/
public interface NativeBackgroundTaskDelegate {
/**
* Initializes native and runs the task.
* @param minimalBrowserMode Whether a minimal browser should be launched during the
* startup, without running remaining parts of the Chrome.
* @param onSuccess The runnable that represents the task to be run after loading
* native successfully.
* @param onFailure The runnable to be run in case the initialization fails.
*/
void initializeNativeAsync(boolean minimalBrowserMode, Runnable onSuccess, Runnable onFailure);
/** @return Helper class to report UMA stats. */
BackgroundTaskSchedulerExternalUma getUmaReporter();
}
| 355 |
852 |
<filename>FastSimulation/ShowerDevelopment/src/EMECALShowerParametrization.cc
#include "FastSimulation/ShowerDevelopment/interface/EMECALShowerParametrization.h"
| 51 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay
{"nom":"Boisney","circ":"2ème circonscription","dpt":"Eure","inscrits":266,"abs":146,"votants":120,"blancs":15,"nuls":0,"exp":105,"res":[{"nuance":"REM","nom":"<NAME>","voix":60},{"nuance":"FN","nom":"M. <NAME>","voix":45}]}
| 109 |
341 |
<gh_stars>100-1000
// Created by http://oleddisplay.squix.ch/ Consider a donation
// In case of problems make sure that you are using the font file with the correct version!
const uint8_t DSEG7_Classic_Regular_16Bitmaps[] PROGMEM = {
// Bitmap Data:
0x00, // ' '
0x00, // '!'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '"'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '#'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '$'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '%'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '&'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '''
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '('
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // ')'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '*'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '+'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // ','
0x7F,0x1F,0xC0, // '-'
0xD8, // '.'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '/'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x08,0x00,0x00,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x0B,0xFE, // '0'
0xAA,0xA0,0xAA,0xA0, // '1'
0xFF,0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x09,0xFC,0x7F,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x03,0xFE, // '2'
0xFF,0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x09,0xFC,0x7F,0x00,0x20,0x08,0x02,0x00,0x80,0x20,0x0B,0xFE, // '3'
0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x27,0xF1,0xFC,0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x20, // '4'
0xFF,0xA0,0x08,0x02,0x00,0x80,0x20,0x08,0x01,0xFC,0x7F,0x00,0x20,0x08,0x02,0x00,0x80,0x20,0x0B,0xFE, // '5'
0xFF,0xA0,0x08,0x02,0x00,0x80,0x20,0x08,0x01,0xFC,0x7F,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x0B,0xFE, // '6'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x08,0x00,0x00,0x00,0x20,0x08,0x02,0x00,0x80,0x20,0x08, // '7'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x09,0xFC,0x7F,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x0B,0xFE, // '8'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x09,0xFC,0x7F,0x00,0x20,0x08,0x02,0x00,0x80,0x20,0x0B,0xFE, // '9'
0xD0,0x00,0x06, // ':'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // ';'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '<'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '='
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '>'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '?'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '@'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x09,0xFC,0x7F,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x08, // 'A'
0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x07,0xF1,0xFC,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x2F,0xF8, // 'B'
0x7F,0x1F,0xC8,0x02,0x00,0x80,0x20,0x08,0x02,0x00,0xFF,0x80, // 'C'
0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x27,0xF1,0xFC,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x2F,0xF8, // 'D'
0xFF,0xA0,0x08,0x02,0x00,0x80,0x20,0x08,0x01,0xFC,0x7F,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x03,0xFE, // 'E'
0xFF,0xA0,0x08,0x02,0x00,0x80,0x20,0x08,0x01,0xFC,0x7F,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x00, // 'F'
0xFF,0xA0,0x08,0x02,0x00,0x80,0x20,0x08,0x00,0x00,0x00,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x0B,0xFE, // 'G'
0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x07,0xF1,0xFC,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x20, // 'H'
0x2A,0xA8, // 'I'
0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x00,0x00,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x2F,0xF8, // 'J'
0xFF,0xA0,0x08,0x02,0x00,0x80,0x20,0x08,0x01,0xFC,0x7F,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x08, // 'K'
0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x00,0x00,0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x0F,0xF8, // 'L'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x08,0x00,0x00,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x08, // 'M'
0x7F,0x1F,0xC8,0x0A,0x02,0x80,0xA0,0x28,0x0A,0x02, // 'N'
0x7F,0x1F,0xC8,0x0A,0x02,0x80,0xA0,0x28,0x0A,0x02,0xFF,0x80, // 'O'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x09,0xFC,0x7F,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x00, // 'P'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x09,0xFC,0x7F,0x00,0x20,0x08,0x02,0x00,0x80,0x20,0x08, // 'Q'
0x7F,0x1F,0xC8,0x02,0x00,0x80,0x20,0x08,0x02,0x00, // 'R'
0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x07,0xF1,0xFC,0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x2F,0xF8, // 'S'
0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x07,0xF1,0xFC,0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x0F,0xF8, // 'T'
0x00,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x0B,0xFE, // 'U'
0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x20,0x00,0x00,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x2F,0xF8, // 'V'
0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x27,0xF1,0xFC,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x2F,0xF8, // 'W'
0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x27,0xF1,0xFC,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x20, // 'X'
0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x27,0xF1,0xFC,0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x2F,0xF8, // 'Y'
0xFF,0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x00,0x00,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x03,0xFE, // 'Z'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '['
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '\'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // ']'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '^'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '_'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '`'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x09,0xFC,0x7F,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x08, // 'a'
0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x07,0xF1,0xFC,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x2F,0xF8, // 'b'
0x7F,0x1F,0xC8,0x02,0x00,0x80,0x20,0x08,0x02,0x00,0xFF,0x80, // 'c'
0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x27,0xF1,0xFC,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x2F,0xF8, // 'd'
0xFF,0xA0,0x08,0x02,0x00,0x80,0x20,0x08,0x01,0xFC,0x7F,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x03,0xFE, // 'e'
0xFF,0xA0,0x08,0x02,0x00,0x80,0x20,0x08,0x01,0xFC,0x7F,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x00, // 'f'
0xFF,0xA0,0x08,0x02,0x00,0x80,0x20,0x08,0x00,0x00,0x00,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x0B,0xFE, // 'g'
0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x07,0xF1,0xFC,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x20, // 'h'
0x2A,0xA8, // 'i'
0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x00,0x00,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x2F,0xF8, // 'j'
0xFF,0xA0,0x08,0x02,0x00,0x80,0x20,0x08,0x01,0xFC,0x7F,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x08, // 'k'
0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x00,0x00,0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x0F,0xF8, // 'l'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x08,0x00,0x00,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x08, // 'm'
0x7F,0x1F,0xC8,0x0A,0x02,0x80,0xA0,0x28,0x0A,0x02, // 'n'
0x7F,0x1F,0xC8,0x0A,0x02,0x80,0xA0,0x28,0x0A,0x02,0xFF,0x80, // 'o'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x09,0xFC,0x7F,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x00, // 'p'
0xFF,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x28,0x09,0xFC,0x7F,0x00,0x20,0x08,0x02,0x00,0x80,0x20,0x08, // 'q'
0x7F,0x1F,0xC8,0x02,0x00,0x80,0x20,0x08,0x02,0x00, // 'r'
0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x07,0xF1,0xFC,0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x2F,0xF8, // 's'
0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x07,0xF1,0xFC,0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x0F,0xF8, // 't'
0x00,0x20,0x28,0x0A,0x02,0x80,0xA0,0x28,0x0B,0xFE, // 'u'
0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x20,0x00,0x00,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x2F,0xF8, // 'v'
0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x27,0xF1,0xFC,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x2F,0xF8, // 'w'
0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x27,0xF1,0xFC,0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x20, // 'x'
0x80,0xA0,0x28,0x0A,0x02,0x80,0xA0,0x27,0xF1,0xFC,0x00,0x80,0x20,0x08,0x02,0x00,0x80,0x2F,0xF8, // 'y'
0xFF,0x80,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x00,0x00,0x20,0x08,0x02,0x00,0x80,0x20,0x08,0x03,0xFE, // 'z'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '{'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80, // '|'
0xFA,0x28,0xA2,0x8A,0x28,0xA2,0x8A,0x2F,0x80 // '}'
};
const GFXglyph DSEG7_Classic_Regular_16Glyphs[] PROGMEM = {
// bitmapOffset, width, height, xAdvance, xOffset, yOffset
{ 0, 1, 1, 4, 0, 0 }, // ' '
{ 1, 1, 1, 14, 0, 0 }, // '!'
{ 2, 6, 11, 7, 1, -11 }, // '"'
{ 11, 6, 11, 7, 1, -11 }, // '#'
{ 20, 6, 11, 7, 1, -11 }, // '$'
{ 29, 6, 11, 7, 1, -11 }, // '%'
{ 38, 6, 11, 7, 1, -11 }, // '&'
{ 47, 6, 11, 7, 1, -11 }, // '''
{ 56, 6, 11, 7, 1, -11 }, // '('
{ 65, 6, 11, 7, 1, -11 }, // ')'
{ 74, 6, 11, 7, 1, -11 }, // '*'
{ 83, 6, 11, 7, 1, -11 }, // '+'
{ 92, 6, 11, 7, 1, -11 }, // ','
{ 101, 10, 2, 14, 2, -9 }, // '-'
{ 104, 3, 2, 1, -1, -2 }, // '.'
{ 105, 6, 11, 7, 1, -11 }, // '/'
{ 114, 10, 16, 14, 2, -16 }, // '0'
{ 134, 2, 14, 14, 10, -15 }, // '1'
{ 138, 10, 16, 14, 2, -16 }, // '2'
{ 158, 10, 16, 14, 2, -16 }, // '3'
{ 178, 10, 14, 14, 2, -15 }, // '4'
{ 196, 10, 16, 14, 2, -16 }, // '5'
{ 216, 10, 16, 14, 2, -16 }, // '6'
{ 236, 10, 15, 14, 2, -16 }, // '7'
{ 255, 10, 16, 14, 2, -16 }, // '8'
{ 275, 10, 16, 14, 2, -16 }, // '9'
{ 295, 3, 8, 4, 1, -12 }, // ':'
{ 298, 6, 11, 7, 1, -11 }, // ';'
{ 307, 6, 11, 7, 1, -11 }, // '<'
{ 316, 6, 11, 7, 1, -11 }, // '='
{ 325, 6, 11, 7, 1, -11 }, // '>'
{ 334, 6, 11, 7, 1, -11 }, // '?'
{ 343, 6, 11, 7, 1, -11 }, // '@'
{ 352, 10, 15, 14, 2, -16 }, // 'A'
{ 371, 10, 15, 14, 2, -15 }, // 'B'
{ 390, 10, 9, 14, 2, -9 }, // 'C'
{ 402, 10, 15, 14, 2, -15 }, // 'D'
{ 421, 10, 16, 14, 2, -16 }, // 'E'
{ 441, 10, 15, 14, 2, -16 }, // 'F'
{ 460, 10, 16, 14, 2, -16 }, // 'G'
{ 480, 10, 14, 14, 2, -15 }, // 'H'
{ 498, 2, 7, 14, 10, -8 }, // 'I'
{ 500, 10, 15, 14, 2, -15 }, // 'J'
{ 519, 10, 15, 14, 2, -16 }, // 'K'
{ 538, 10, 15, 14, 2, -15 }, // 'L'
{ 557, 10, 15, 14, 2, -16 }, // 'M'
{ 576, 10, 8, 14, 2, -9 }, // 'N'
{ 586, 10, 9, 14, 2, -9 }, // 'O'
{ 598, 10, 15, 14, 2, -16 }, // 'P'
{ 617, 10, 15, 14, 2, -16 }, // 'Q'
{ 636, 10, 8, 14, 2, -9 }, // 'R'
{ 646, 10, 15, 14, 2, -15 }, // 'S'
{ 665, 10, 15, 14, 2, -15 }, // 'T'
{ 684, 10, 8, 14, 2, -8 }, // 'U'
{ 694, 10, 15, 14, 2, -15 }, // 'V'
{ 713, 10, 15, 14, 2, -15 }, // 'W'
{ 732, 10, 14, 14, 2, -15 }, // 'X'
{ 750, 10, 15, 14, 2, -15 }, // 'Y'
{ 769, 10, 16, 14, 2, -16 }, // 'Z'
{ 789, 6, 11, 7, 1, -11 }, // '['
{ 798, 6, 11, 7, 1, -11 }, // '\'
{ 807, 6, 11, 7, 1, -11 }, // ']'
{ 816, 6, 11, 7, 1, -11 }, // '^'
{ 825, 6, 11, 7, 1, -11 }, // '_'
{ 834, 6, 11, 7, 1, -11 }, // '`'
{ 843, 10, 15, 14, 2, -16 }, // 'a'
{ 862, 10, 15, 14, 2, -15 }, // 'b'
{ 881, 10, 9, 14, 2, -9 }, // 'c'
{ 893, 10, 15, 14, 2, -15 }, // 'd'
{ 912, 10, 16, 14, 2, -16 }, // 'e'
{ 932, 10, 15, 14, 2, -16 }, // 'f'
{ 951, 10, 16, 14, 2, -16 }, // 'g'
{ 971, 10, 14, 14, 2, -15 }, // 'h'
{ 989, 2, 7, 14, 10, -8 }, // 'i'
{ 991, 10, 15, 14, 2, -15 }, // 'j'
{ 1010, 10, 15, 14, 2, -16 }, // 'k'
{ 1029, 10, 15, 14, 2, -15 }, // 'l'
{ 1048, 10, 15, 14, 2, -16 }, // 'm'
{ 1067, 10, 8, 14, 2, -9 }, // 'n'
{ 1077, 10, 9, 14, 2, -9 }, // 'o'
{ 1089, 10, 15, 14, 2, -16 }, // 'p'
{ 1108, 10, 15, 14, 2, -16 }, // 'q'
{ 1127, 10, 8, 14, 2, -9 }, // 'r'
{ 1137, 10, 15, 14, 2, -15 }, // 's'
{ 1156, 10, 15, 14, 2, -15 }, // 't'
{ 1175, 10, 8, 14, 2, -8 }, // 'u'
{ 1185, 10, 15, 14, 2, -15 }, // 'v'
{ 1204, 10, 15, 14, 2, -15 }, // 'w'
{ 1223, 10, 14, 14, 2, -15 }, // 'x'
{ 1241, 10, 15, 14, 2, -15 }, // 'y'
{ 1260, 10, 16, 14, 2, -16 }, // 'z'
{ 1280, 6, 11, 7, 1, -11 }, // '{'
{ 1289, 6, 11, 7, 1, -11 }, // '|'
{ 1298, 6, 11, 7, 1, -11 } // '}'
};
const GFXfont DSEG7_Classic_Regular_16 PROGMEM = {
(uint8_t *)DSEG7_Classic_Regular_16Bitmaps,(GFXglyph *)DSEG7_Classic_Regular_16Glyphs,0x20, 0x7E, 18};
| 9,325 |
506 |
// https://codeforces.com/contest/1201/problem/B
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, x, m = 0;
ll s = 0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
m = max(m, x);
s += x;
}
cout << (s % 2 || m * 2 > s ? "NO\n" : "YES\n");
}
| 175 |
777 |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/cache_storage/cache_storage_index.h"
#include <list>
#include <utility>
#include "testing/gtest/include/gtest/gtest.h"
namespace content {
class CacheStorageIndexTest : public testing::Test {
public:
void SetUp() override {}
void TearDown() override {}
CacheStorageIndexTest() = default;
private:
DISALLOW_COPY_AND_ASSIGN(CacheStorageIndexTest);
};
TEST_F(CacheStorageIndexTest, TestDefaultConstructor) {
CacheStorageIndex index;
EXPECT_EQ(0u, index.num_entries());
EXPECT_TRUE(index.ordered_cache_metadata().empty());
EXPECT_EQ(0u, index.GetStorageSize());
}
TEST_F(CacheStorageIndexTest, TestSetCacheSize) {
CacheStorageIndex index;
index.Insert(CacheStorageIndex::CacheMetadata("foo", 12));
index.Insert(CacheStorageIndex::CacheMetadata("bar", 19));
index.Insert(CacheStorageIndex::CacheMetadata("baz", 1000));
EXPECT_EQ(3u, index.num_entries());
ASSERT_EQ(3u, index.ordered_cache_metadata().size());
EXPECT_EQ(1031, index.GetStorageSize());
EXPECT_TRUE(index.SetCacheSize("baz", 2000));
EXPECT_EQ(2031, index.GetStorageSize());
EXPECT_FALSE(index.SetCacheSize("baz", 2000));
EXPECT_EQ(2031, index.GetStorageSize());
EXPECT_EQ(2000, index.GetCacheSize("baz"));
EXPECT_EQ(CacheStorage::kSizeUnknown, index.GetCacheSize("<not-present>"));
}
TEST_F(CacheStorageIndexTest, TestDoomCache) {
CacheStorageIndex index;
index.Insert(CacheStorageIndex::CacheMetadata("foo", 12));
index.Insert(CacheStorageIndex::CacheMetadata("bar", 19));
index.Insert(CacheStorageIndex::CacheMetadata("baz", 1000));
EXPECT_EQ(3u, index.num_entries());
ASSERT_EQ(3u, index.ordered_cache_metadata().size());
EXPECT_EQ(1031, index.GetStorageSize());
index.DoomCache("bar");
EXPECT_EQ(2u, index.num_entries());
ASSERT_EQ(2u, index.ordered_cache_metadata().size());
EXPECT_EQ(1031 - 19, index.GetStorageSize());
index.RestoreDoomedCache();
EXPECT_EQ(3u, index.num_entries());
ASSERT_EQ(3u, index.ordered_cache_metadata().size());
auto it = index.ordered_cache_metadata().begin();
EXPECT_EQ("foo", (it++)->name);
EXPECT_EQ("bar", (it++)->name);
EXPECT_EQ("baz", (it++)->name);
EXPECT_EQ(1031, index.GetStorageSize());
index.DoomCache("foo");
EXPECT_EQ(2u, index.num_entries());
ASSERT_EQ(2u, index.ordered_cache_metadata().size());
EXPECT_EQ(1031 - 12, index.GetStorageSize());
index.FinalizeDoomedCache();
EXPECT_EQ(2u, index.num_entries());
ASSERT_EQ(2u, index.ordered_cache_metadata().size());
EXPECT_EQ(1031 - 12, index.GetStorageSize());
}
TEST_F(CacheStorageIndexTest, TestDelete) {
CacheStorageIndex index;
index.Insert(CacheStorageIndex::CacheMetadata("bar", 19));
index.Insert(CacheStorageIndex::CacheMetadata("foo", 12));
index.Insert(CacheStorageIndex::CacheMetadata("baz", 1000));
EXPECT_EQ(3u, index.num_entries());
ASSERT_EQ(3u, index.ordered_cache_metadata().size());
EXPECT_EQ(1031, index.GetStorageSize());
auto it = index.ordered_cache_metadata().begin();
EXPECT_EQ("bar", it->name);
EXPECT_EQ(19u, it->size);
it++;
EXPECT_EQ("foo", it->name);
EXPECT_EQ(12u, it->size);
it++;
EXPECT_EQ("baz", it->name);
EXPECT_EQ(1000u, it->size);
index.Delete("bar");
EXPECT_EQ(2u, index.num_entries());
ASSERT_EQ(2u, index.ordered_cache_metadata().size());
EXPECT_EQ(1012, index.GetStorageSize());
it = index.ordered_cache_metadata().begin();
EXPECT_EQ("foo", it->name);
EXPECT_EQ(12u, it->size);
it++;
EXPECT_EQ("baz", it->name);
EXPECT_EQ(1000u, it->size);
index.Delete("baz");
EXPECT_EQ(1u, index.num_entries());
ASSERT_EQ(1u, index.ordered_cache_metadata().size());
EXPECT_EQ(12, index.GetStorageSize());
it = index.ordered_cache_metadata().begin();
EXPECT_EQ("foo", it->name);
EXPECT_EQ(12u, it->size);
}
TEST_F(CacheStorageIndexTest, TestInsert) {
CacheStorageIndex index;
index.Insert(CacheStorageIndex::CacheMetadata("foo", 12));
index.Insert(CacheStorageIndex::CacheMetadata("bar", 19));
index.Insert(CacheStorageIndex::CacheMetadata("baz", 1000));
EXPECT_EQ(3u, index.num_entries());
ASSERT_EQ(3u, index.ordered_cache_metadata().size());
EXPECT_EQ(1031, index.GetStorageSize());
}
TEST_F(CacheStorageIndexTest, TestMoveOperator) {
CacheStorageIndex index;
index.Insert(CacheStorageIndex::CacheMetadata("foo", 12));
index.Insert(CacheStorageIndex::CacheMetadata("bar", 19));
index.Insert(CacheStorageIndex::CacheMetadata("baz", 1000));
CacheStorageIndex index2;
index2 = std::move(index);
EXPECT_EQ(3u, index2.num_entries());
EXPECT_EQ(3u, index2.ordered_cache_metadata().size());
ASSERT_EQ(1031, index2.GetStorageSize());
EXPECT_EQ(0u, index.num_entries());
EXPECT_TRUE(index.ordered_cache_metadata().empty());
EXPECT_EQ(0u, index.GetStorageSize());
auto it = index2.ordered_cache_metadata().begin();
EXPECT_EQ("foo", it->name);
EXPECT_EQ(12u, it->size);
it++;
EXPECT_EQ("bar", it->name);
EXPECT_EQ(19u, it->size);
it++;
EXPECT_EQ("baz", it->name);
EXPECT_EQ(1000u, it->size);
EXPECT_EQ(3u, index2.num_entries());
ASSERT_EQ(3u, index2.ordered_cache_metadata().size());
EXPECT_EQ(1031, index2.GetStorageSize());
}
} // namespace content
| 2,003 |
373 |
<reponame>linkingtd/UniAuth<filename>common/src/main/java/com/dianrong/common/uniauth/common/cons/AppConstants.java<gh_stars>100-1000
package com.dianrong.common.uniauth.common.cons;
/**
* Created by Arc on 26/1/16.
*/
public interface AppConstants {
// 0 = 启用
Byte ZERO_BYTE = (byte) 0;
// 1 = 禁用
Byte ONE_BYTE = (byte) 1;
// 类型0
Byte ZERO_TYPE = ZERO_BYTE;
// 类型1
Byte ONE_TYPE = ONE_BYTE;
// 0 = 启用
byte ZERO_BYTE_PRIMITIVE = (byte) 0;
// 1 = 禁用
byte ONE_BYTE_PRIMITIVE = (byte) 1;
// 0 = 启用
Byte SUCCESS = ZERO_BYTE;
// 1 = 禁用
Byte FAILURE = ONE_BYTE;
// 人性化设计
byte STATUS_ENABLED = ZERO_BYTE_PRIMITIVE;
byte STATUS_DISABLED = ONE_BYTE_PRIMITIVE;
String API_UUID = "api-uuid";
String NODE_TYPE_GROUP = "grp";
String NODE_TYPE_MEMBER_USER = "mUser";
String NODE_TYPE_OWNER_USER = "oUser";
// 组织关系的根组Code
String ORGANIZATION_ROOT = "ORGANIZATION_ROOT";
String GRP_ROOT = "GRP_ROOT";
String TECHOPS_SUPER_ADMIN_GRP = "GRP_TECHOPS_SUPER_ADMIN";
byte MAX_AUTH_FAIL_COUNT = 10;
int MAX_PASSWORD_VALID_MONTH = 3;
int DUPLICATE_PWD_VALID_MONTH = 8;
// this value can avoid the "data.query.result.number.exceed" exception when you need query as
// much as more.
Integer MAX_PAGE_SIZE_MINUS_ONE = 4999;
// if you don't pass pageSize parameter to the query api, it is the default value.
Integer MAX_PAGE_SIZE = 5000;
// if you don't pass pageNumber parameter to the query api, it is the default value.
Integer MIN_PAGE_NUMBER = 0;
String PERM_TYPE_DOMAIN = "DOMAIN";
String PERM_TYPE_URIPATTERN = "URI_PATTERN";
String PERM_TYPE_PRIVILEGE = "PRIVILEGE";
String PERM_TYPE_THIRD_ACCOUNT = "THIRD_ACCOUNT";
String DOMAIN_CODE_TECHOPS = "techops";
// ROLE_NORMAL
String ROLE_CODE_ROLE_NORMAL = "ROLE_NORMAL";
String UNKNOWN_STAFF_NO = "UNKNOWN_STAFF_NO";
/*** zk节点配置相关的常量定义. */
/**
* zk配置中的分隔符.
*/
String ZK_CFG_SPLIT = ".";
/**
* domain.
*/
String ZK_DOMAIN = "domains";
/**
* zk中domain节点的前缀.
*/
String ZK_DOMAIN_PREFIX = ZK_DOMAIN + ZK_CFG_SPLIT;
/**
* 域的登陆页属性.
*/
String ZK_DOMAIN_LOGIN_PAGE = "loginPage";
/**
* ticket 验证失败url.
**/
String ZK_DOMAIN_AUTH_FAIL_URL = "auth_fail_url";
/**
* 是否在主页显示登陆项.
*/
String ZK_DOMAIN_SHOW_IN_HOME_PAGE = "showInHomePage";
/**
* zk节点中,域的登出地址的节点后缀.
*/
String ZK_DOMAIN_LOGOUT_ADDRESS_NODE_SUFFIX = "logout_address";
/**
* 定义域的所属tenancy的code.
*/
String ZK_DOMAIN_TEANANCY_CODE = "tenancycode";
/**
* zk 配置的node name, st使用的次数.
*/
String ZK_NODE_NAME_ST_USED_TIMES = "cas.st_use_times";
/**
* zk 配置cas的短信和邮箱验证码的显示开关.
*/
String ZK_CAS_VERIFY_CODE_SHOW = "cas.verify_code.show";
String SERVICE_LOGIN_SUFFIX = "/login/cas";
String ROLE_ADMIN = "ROLE_ADMIN";
String ROLE_SUPER_ADMIN = "ROLE_SUPER_ADMIN";
String CROSS_RESOURCE_ORIGIN_HEADER = "Origin";
String AJAX_HEADER = "X-Requested-With";
String JQUERY_XMLHttpRequest_HEADER = "XMLHttpRequest";
String LOGIN_REDIRECT_URL = "LOGIN_REDIRECT_URL";
String NO_PRIVILEGE = "NO_PRIVILEGE";
String PERM_TYPE_DOMAIN_ID = "DOMAIN_ID";
String CFG_TYPE_TEXT = "TEXT";
String CFG_TYPE_FILE = "FILE";
String MAIL_PREFIX = "[TechOps]";
int GLOBAL_VAR_QUEUE_SIZE = 2048;
int AUDIT_INSERT_LIST_SIZE = 1024;
int AUDIT_INSERT_LIST_CACHE_SIZE = 40960;
int AUDIT_INSERT_EVERY_SECOND = 60;
int AUDIT_INSERT_EXP_LENGTH = 3072;
int AUDIT_INSET_PARAM_LENGTH = 256;
String HTTP_METHOD_ALL = "ALL";
// Cxf 传递的locale的key
@Deprecated
String CAS_CXF_HEADER_LOCALE_KEY = "cas.cxf.header.locale.key";
// 默认的租户code
String DEFAULT_TANANCY_CODE = "DIANRONG";
// 设置一个非租户相关的租户id
Long TENANCY_UNRELATED_TENANCY_ID = -1L;
// 配置项,指定是否强制监测租户信息
String CHECK_TENANCY_IDENTITY_FORCIBLY = "tenancyIdentity.check.switch";
// 配置项,指定是否开启uniauth-server的监控开关
String UNIAUTH_SERVER_API_CALL_SWITCH = "apicall.check.switch";
// 配置jwt的秘钥
String UNIAUTH_APICTL_JWT_SECKEY = "apicall.jwt.security.key";
// 配置techops的api访问密码
String UNIAUTH_APICTL_TECHOPS_PSWD = "<PASSWORD>";
// 配置项, 指定是否使用notification实现的通知发送
String UNIAUTH_NOTIFY_USE_NOTIFICATION = "notify.notification";
// uniauth_server使用的GlobalVarQueue是否采用旧的实现
String UNIAUTH_GLOBAL_VAR_QUEUE_USE_OLD_IMPL = "global.var.queue.old.impl";
// 2 hours
long DEFAULT_API_CALL_TOKEN_AVAILABLE_MILLiSECONDS = 1000L * 60L * 60L * 2L;
// 记录API访问超时的日志logger name
String UNIAUTH_API_CALL_TIME_OUT_LOGGER =
"com.dianrong.common.uniauth.api.call.socket.timeout.exception";
}
| 2,360 |
488 |
<reponame>IBKS-EZ/DotNetAnywhere<filename>libIGraph/Graphics.h
// Copyright (c) 2012 DotNetAnywhere
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#ifndef __GRAPHICS_H
#define __GRAPHICS_H
typedef struct tGraphics_ tGraphics;
#include "libIGraph.h"
#include "Image.h"
#include "Region.h"
#define TextRenderingHint_SystemDefault 0
#define TextRenderingHint_SingleBitPerPixelGridFit 1
#define TextRenderingHint_SingleBitPerPixel 2
#define TextRenderingHint_AntiAliasGridFit 3
#define TextRenderingHint_AntiAlias 4
#define TextRenderingHint_ClearTypeGridFit 5
#define PixelFormat_Alpha 262144
#define PixelFormat_Canonical 2097152
#define PixelFormat_DontCare 0
#define PixelFormat_Extended 1048576
#define PixelFormat_Format16bppArgb1555 397319
#define PixelFormat_Format16bppGrayScale 1052676
#define PixelFormat_Format16bppRgb555 135173
#define PixelFormat_Format16bppRgb565 135174
#define PixelFormat_Format1bppIndexed 196865
#define PixelFormat_Format24bppRgb 137224
#define PixelFormat_Format32bppArgb 2498570
#define PixelFormat_Format32bppPArgb 925707
#define PixelFormat_Format32bppRgb 139273
#define PixelFormat_Format48bppRgb 1060876
#define PixelFormat_Format4bppIndexed 197634
#define PixelFormat_Format64bppArgb 3424269
#define PixelFormat_Format64bppPArgb 1851406
#define PixelFormat_Format8bppIndexed 198659
#define PixelFormat_Gdi 131072
#define PixelFormat_Indexed 65536
#define PixelFormat_Max 15
#define PixelFormat_PAlpha 524288
#define PixelFormat_Undefined 0
struct tGraphics_ {
I32 xSize;
I32 ySize;
U32 pixelFormat;
U32 pixelFormatIndex;
void *pScan0;
I32 stride;
void* screenPtr; // Only set if this is a Graphics for the screen
tImage *pImage; // Only set if this is a Graphics for an Image
U32 memSize;
U32 textRenderingHint;
tRegion *pClip; // Null if no clipping region set
};
tGraphics* InitGraphics();
void DisposeGraphics_(tGraphics *pGraphics);
void TextRenderingHint_Set_(tGraphics *pGraphics, U32 textRenderingHint);
typedef void (*tClear)(tGraphics *pGraphics, U32 col);
extern tClear mClear_[FMT_NUM];
#define mClear(pGraphics, col) mClear_[pGraphics->pixelFormatIndex](pGraphics, col)
void DrawImageUnscaled_(tGraphics *pGraphics, tImage *pImage, I32 x, I32 y);
void Graphics_SetClip_(tGraphics *pGraphics, tRegion *pRegion);
void Graphics_CopyFromScreen_(tGraphics *pGraphics, I32 srcX, I32 srcY, I32 destX, I32 destY, I32 sizeX, I32 sizeY);
#endif
| 1,091 |
390 |
//
// RHUpstreamBuffer.h
// Example
//
// Created by zhuruhong on 2019/9/8.
// Copyright © 2019年 zhuruhong. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "RHChannelBufferProtocol.h"
//NS_ASSUME_NONNULL_BEGIN
/**
* 上行数据包缓存
*/
@interface RHUpstreamBuffer : NSObject <RHUpstreamBuffer>
/** 上行数据包缓存 */
@property (nonatomic, strong) NSMutableArray *packetBuffer;
/** 缓存数据包个数,默认为30 */
@property (nonatomic, assign) NSUInteger maxPacketSize;
@end
//NS_ASSUME_NONNULL_END
| 234 |
7,137 |
package io.onedev.server.web.page.admin.buildsetting.agent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.Component;
import org.apache.wicket.Session;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.feedback.FencedFeedbackPanel;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.cycle.RequestCycle;
import io.onedev.commons.bootstrap.Bootstrap;
import io.onedev.commons.utils.ExplicitException;
import io.onedev.server.OneDev;
import io.onedev.server.entitymanager.AgentManager;
import io.onedev.server.model.Agent;
import io.onedev.server.search.entity.EntityCriteria;
import io.onedev.server.search.entity.EntitySort;
import io.onedev.server.search.entity.OrEntityCriteria;
import io.onedev.server.search.entity.agent.AgentQuery;
import io.onedev.server.search.entity.agent.NameCriteria;
import io.onedev.server.security.SecurityUtils;
import io.onedev.server.web.WebConstants;
import io.onedev.server.web.behavior.AgentQueryBehavior;
import io.onedev.server.web.component.AgentStatusBadge;
import io.onedev.server.web.component.datatable.OneDataTable;
import io.onedev.server.web.component.datatable.selectioncolumn.SelectionColumn;
import io.onedev.server.web.component.floating.FloatingPanel;
import io.onedev.server.web.component.link.DropdownLink;
import io.onedev.server.web.component.menu.MenuItem;
import io.onedev.server.web.component.menu.MenuLink;
import io.onedev.server.web.component.modal.confirm.ConfirmModalPanel;
import io.onedev.server.web.component.orderedit.OrderEditPanel;
import io.onedev.server.web.component.savedquery.SavedQueriesClosed;
import io.onedev.server.web.component.savedquery.SavedQueriesOpened;
import io.onedev.server.web.component.svg.SpriteImage;
import io.onedev.server.web.util.LoadableDetachableDataProvider;
import io.onedev.server.web.util.PagingHistorySupport;
import io.onedev.server.web.util.QuerySaveSupport;
@SuppressWarnings("serial")
class AgentListPanel extends Panel {
private final IModel<String> queryStringModel;
private final IModel<AgentQuery> queryModel = new LoadableDetachableModel<AgentQuery>() {
@Override
protected AgentQuery load() {
String queryString = queryStringModel.getObject();
try {
return AgentQuery.parse(queryString, false);
} catch (ExplicitException e) {
error(e.getMessage());
return null;
} catch (Exception e) {
warn("Not a valid formal query, performing fuzzy query");
List<EntityCriteria<Agent>> criterias = new ArrayList<>();
criterias.add(new NameCriteria("*" + queryString + "*"));
return new AgentQuery(new OrEntityCriteria<Agent>(criterias));
}
}
};
private DataTable<Agent, Void> agentsTable;
private SelectionColumn<Agent, Void> selectionColumn;
private SortableDataProvider<Agent, Void> dataProvider;
private WebMarkupContainer body;
private Component saveQueryLink;
private TextField<String> queryInput;
private boolean querySubmitted = true;
public AgentListPanel(String id, IModel<String> queryModel) {
super(id);
this.queryStringModel = queryModel;
}
private AgentManager getAgentManager() {
return OneDev.getInstance(AgentManager.class);
}
@Override
protected void onDetach() {
queryStringModel.detach();
queryModel.detach();
super.onDetach();
}
@Nullable
protected PagingHistorySupport getPagingHistorySupport() {
return null;
}
@Nullable
protected QuerySaveSupport getQuerySaveSupport() {
return null;
}
private void doQuery(AjaxRequestTarget target) {
agentsTable.setCurrentPage(0);
target.add(body);
selectionColumn.getSelections().clear();
querySubmitted = true;
if (SecurityUtils.getUser() != null && getQuerySaveSupport() != null)
target.add(saveQueryLink);
}
@Override
protected void onInitialize() {
super.onInitialize();
add(new AjaxLink<Void>("showSavedQueries") {
@Override
public void onEvent(IEvent<?> event) {
super.onEvent(event);
if (event.getPayload() instanceof SavedQueriesClosed)
((SavedQueriesClosed) event.getPayload()).getHandler().add(this);
}
@Override
protected void onConfigure() {
super.onConfigure();
setVisible(getQuerySaveSupport() != null && !getQuerySaveSupport().isSavedQueriesVisible());
}
@Override
public void onClick(AjaxRequestTarget target) {
send(getPage(), Broadcast.BREADTH, new SavedQueriesOpened(target));
target.add(this);
}
}.setOutputMarkupPlaceholderTag(true));
add(saveQueryLink = new AjaxLink<Void>("saveQuery") {
@Override
protected void onConfigure() {
super.onConfigure();
setEnabled(querySubmitted && queryModel.getObject() != null);
setVisible(getQuerySaveSupport() != null);
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
configure();
if (!isEnabled())
tag.append("class", "disabled", " ");
if (!querySubmitted)
tag.put("title", "Query not submitted");
else if (queryModel.getObject() == null)
tag.put("title", "Can not save malformed query");
}
@Override
public void onClick(AjaxRequestTarget target) {
getQuerySaveSupport().onSaveQuery(target, queryModel.getObject().toString());
}
}.setOutputMarkupPlaceholderTag(true));
add(new DropdownLink("orderBy") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
List<String> orderFields = new ArrayList<>(Agent.ORDER_FIELDS.keySet());
return new OrderEditPanel(id, orderFields, new IModel<List<EntitySort>> () {
@Override
public void detach() {
}
@Override
public List<EntitySort> getObject() {
AgentQuery query = queryModel.getObject();
AgentListPanel.this.getFeedbackMessages().clear();
if (query != null)
return query.getSorts();
else
return new ArrayList<>();
}
@Override
public void setObject(List<EntitySort> object) {
AgentQuery query = queryModel.getObject();
AgentListPanel.this.getFeedbackMessages().clear();
if (query == null)
query = new AgentQuery();
query.getSorts().clear();
query.getSorts().addAll(object);
queryModel.setObject(query);
queryStringModel.setObject(query.toString());
AjaxRequestTarget target = RequestCycle.get().find(AjaxRequestTarget.class);
target.add(queryInput);
doQuery(target);
}
});
}
});
add(new DropdownLink("tokens") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
return new TokenListPanel(id);
}
});
add(new MenuLink("operations") {
@Override
protected List<MenuItem> getMenuItems(FloatingPanel dropdown) {
List<MenuItem> menuItems = new ArrayList<>();
menuItems.add(new MenuItem() {
@Override
public String getLabel() {
return "Pause Selected Agents";
}
@Override
public WebMarkupContainer newLink(String id) {
return new AjaxLink<Void>(id) {
@Override
public void onClick(AjaxRequestTarget target) {
dropdown.close();
Collection<Agent> agents = new ArrayList<>();
for (IModel<Agent> each: selectionColumn.getSelections())
agents.add(each.getObject());
OneDev.getInstance(AgentManager.class).pause(agents);
target.add(body);
selectionColumn.getSelections().clear();
Session.get().success("Paused selected agents");
}
@Override
protected void onConfigure() {
super.onConfigure();
setEnabled(!selectionColumn.getSelections().isEmpty());
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
configure();
if (!isEnabled()) {
tag.put("disabled", "disabled");
tag.put("title", "Please select agents to pause");
}
}
};
}
});
menuItems.add(new MenuItem() {
@Override
public String getLabel() {
return "Resume Selected Agents";
}
@Override
public WebMarkupContainer newLink(String id) {
return new AjaxLink<Void>(id) {
@Override
public void onClick(AjaxRequestTarget target) {
dropdown.close();
Collection<Agent> agents = new ArrayList<>();
for (IModel<Agent> each: selectionColumn.getSelections())
agents.add(each.getObject());
OneDev.getInstance(AgentManager.class).resume(agents);
target.add(body);
selectionColumn.getSelections().clear();
Session.get().success("Resumed selected agents");
}
@Override
protected void onConfigure() {
super.onConfigure();
setEnabled(!selectionColumn.getSelections().isEmpty());
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
configure();
if (!isEnabled()) {
tag.put("disabled", "disabled");
tag.put("title", "Please select agents to resume");
}
}
};
}
});
menuItems.add(new MenuItem() {
@Override
public String getLabel() {
return "Restart Selected Agents";
}
@Override
public WebMarkupContainer newLink(String id) {
return new AjaxLink<Void>(id) {
@Override
public void onClick(AjaxRequestTarget target) {
dropdown.close();
new ConfirmModalPanel(target) {
@Override
protected void onConfirm(AjaxRequestTarget target) {
Collection<Agent> agents = new ArrayList<>();
for (IModel<Agent> each: selectionColumn.getSelections())
agents.add(each.getObject());
OneDev.getInstance(AgentManager.class).restart(agents);
target.add(body);
selectionColumn.getSelections().clear();
Session.get().success("Restart command issued to selected agents");
}
@Override
protected String getConfirmMessage() {
return "Type <code>yes</code> below to restart selected agents";
}
@Override
protected String getConfirmInput() {
return "yes";
}
};
}
@Override
protected void onConfigure() {
super.onConfigure();
setEnabled(!selectionColumn.getSelections().isEmpty());
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
configure();
if (!isEnabled()) {
tag.put("disabled", "disabled");
tag.put("title", "Please select agents to restart");
}
}
};
}
});
menuItems.add(new MenuItem() {
@Override
public String getLabel() {
return "Remove Selected Agents";
}
@Override
public WebMarkupContainer newLink(String id) {
return new AjaxLink<Void>(id) {
@Override
public void onClick(AjaxRequestTarget target) {
dropdown.close();
new ConfirmModalPanel(target) {
@Override
protected void onConfirm(AjaxRequestTarget target) {
Collection<Agent> agents = new ArrayList<>();
for (IModel<Agent> each: selectionColumn.getSelections())
agents.add(each.getObject());
OneDev.getInstance(AgentManager.class).delete(agents);
selectionColumn.getSelections().clear();
target.add(body);
}
@Override
protected String getConfirmMessage() {
return "Type <code>yes</code> below to remove selected agents";
}
@Override
protected String getConfirmInput() {
return "yes";
}
};
}
@Override
protected void onConfigure() {
super.onConfigure();
setEnabled(!selectionColumn.getSelections().isEmpty());
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
configure();
if (!isEnabled()) {
tag.put("disabled", "disabled");
tag.put("title", "Please select agents to remove");
}
}
};
}
});
menuItems.add(new MenuItem() {
@Override
public String getLabel() {
return "Pause All Queried Agents";
}
@Override
public WebMarkupContainer newLink(String id) {
return new AjaxLink<Void>(id) {
@SuppressWarnings("unchecked")
@Override
public void onClick(AjaxRequestTarget target) {
dropdown.close();
new ConfirmModalPanel(target) {
@Override
protected void onConfirm(AjaxRequestTarget target) {
Collection<Agent> agents = new ArrayList<>();
for (Iterator<Agent> it = (Iterator<Agent>) dataProvider.iterator(0, agentsTable.getItemCount()); it.hasNext();) {
agents.add(it.next());
}
OneDev.getInstance(AgentManager.class).pause(agents);
selectionColumn.getSelections().clear();
target.add(body);
Session.get().success("Paused all queried agents");
}
@Override
protected String getConfirmMessage() {
return "Type <code>yes</code> below to pause all queried agents";
}
@Override
protected String getConfirmInput() {
return "yes";
}
};
}
@Override
protected void onConfigure() {
super.onConfigure();
setEnabled(agentsTable.getItemCount() != 0);
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
configure();
if (!isEnabled()) {
tag.put("disabled", "disabled");
tag.put("title", "No agents to pause");
}
}
};
}
});
menuItems.add(new MenuItem() {
@Override
public String getLabel() {
return "Resume All Queried Agents";
}
@Override
public WebMarkupContainer newLink(String id) {
return new AjaxLink<Void>(id) {
@SuppressWarnings("unchecked")
@Override
public void onClick(AjaxRequestTarget target) {
dropdown.close();
new ConfirmModalPanel(target) {
@Override
protected void onConfirm(AjaxRequestTarget target) {
Collection<Agent> agents = new ArrayList<>();
for (Iterator<Agent> it = (Iterator<Agent>) dataProvider.iterator(0, agentsTable.getItemCount()); it.hasNext();) {
agents.add(it.next());
}
OneDev.getInstance(AgentManager.class).resume(agents);
target.add(body);
selectionColumn.getSelections().clear();
Session.get().success("Resumed all queried agents");
}
@Override
protected String getConfirmMessage() {
return "Type <code>yes</code> below to resume all queried agents";
}
@Override
protected String getConfirmInput() {
return "yes";
}
};
}
@Override
protected void onConfigure() {
super.onConfigure();
setEnabled(agentsTable.getItemCount() != 0);
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
configure();
if (!isEnabled()) {
tag.put("disabled", "disabled");
tag.put("title", "No agents to resume");
}
}
};
}
});
menuItems.add(new MenuItem() {
@Override
public String getLabel() {
return "Restart All Queried Agents";
}
@Override
public WebMarkupContainer newLink(String id) {
return new AjaxLink<Void>(id) {
@SuppressWarnings("unchecked")
@Override
public void onClick(AjaxRequestTarget target) {
dropdown.close();
new ConfirmModalPanel(target) {
@Override
protected void onConfirm(AjaxRequestTarget target) {
Collection<Agent> agents = new ArrayList<>();
for (Iterator<Agent> it = (Iterator<Agent>) dataProvider.iterator(0, agentsTable.getItemCount()); it.hasNext();) {
agents.add(it.next());
}
OneDev.getInstance(AgentManager.class).restart(agents);
target.add(body);
selectionColumn.getSelections().clear();
Session.get().success("Restart command issued to all queried agents");
}
@Override
protected String getConfirmMessage() {
return "Type <code>yes</code> below to restart all queried agents";
}
@Override
protected String getConfirmInput() {
return "yes";
}
};
}
@Override
protected void onConfigure() {
super.onConfigure();
setEnabled(agentsTable.getItemCount() != 0);
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
configure();
if (!isEnabled()) {
tag.put("disabled", "disabled");
tag.put("title", "No agents to restart");
}
}
};
}
});
menuItems.add(new MenuItem() {
@Override
public String getLabel() {
return "Remove All Queried Agents";
}
@Override
public WebMarkupContainer newLink(String id) {
return new AjaxLink<Void>(id) {
@SuppressWarnings("unchecked")
@Override
public void onClick(AjaxRequestTarget target) {
dropdown.close();
new ConfirmModalPanel(target) {
@Override
protected void onConfirm(AjaxRequestTarget target) {
Collection<Agent> agents = new ArrayList<>();
for (Iterator<Agent> it = (Iterator<Agent>) dataProvider.iterator(0, agentsTable.getItemCount()); it.hasNext();) {
agents.add(it.next());
}
OneDev.getInstance(AgentManager.class).delete(agents);
target.add(body);
selectionColumn.getSelections().clear();
}
@Override
protected String getConfirmMessage() {
return "Type <code>yes</code> below to remove all queried agents";
}
@Override
protected String getConfirmInput() {
return "yes";
}
};
}
@Override
protected void onConfigure() {
super.onConfigure();
setEnabled(agentsTable.getItemCount() != 0);
}
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
configure();
if (!isEnabled()) {
tag.put("disabled", "disabled");
tag.put("title", "No agents to remove");
}
}
};
}
});
return menuItems;
}
});
queryInput = new TextField<String>("input", queryStringModel);
queryInput.setOutputMarkupId(true);
queryInput.add(new AgentQueryBehavior(false) {
@Override
protected void onInput(AjaxRequestTarget target, String inputContent) {
AgentListPanel.this.getFeedbackMessages().clear();
querySubmitted = StringUtils.trimToEmpty(queryStringModel.getObject())
.equals(StringUtils.trimToEmpty(inputContent));
target.add(saveQueryLink);
}
});
queryInput.add(new AjaxFormComponentUpdatingBehavior("clear") {
@Override
protected void onUpdate(AjaxRequestTarget target) {
doQuery(target);
}
});
Form<?> queryForm = new Form<Void>("query");
queryForm.add(queryInput);
queryForm.add(new AjaxButton("submit") {
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
super.onSubmit(target, form);
doQuery(target);
}
});
add(queryForm);
add(new DropdownLink("downloadAgent") {
@Override
protected Component newContent(String id, FloatingPanel dropdown) {
if (new File(Bootstrap.installDir, "agent").exists()) {
return new AgentDownloadPanel(id);
} else {
Label label = new Label(id, "Agent package not available");
label.add(AttributeAppender.append("class", "p-5"));
return label;
}
}
});
dataProvider = new LoadableDetachableDataProvider<Agent, Void>() {
@Override
public Iterator<? extends Agent> iterator(long first, long count) {
try {
return getAgentManager().query(queryModel.getObject(), (int)first, (int)count).iterator();
} catch (ExplicitException e) {
error(e.getMessage());
return new ArrayList<Agent>().iterator();
}
}
@Override
public long calcSize() {
AgentQuery query = queryModel.getObject();
if (query != null) {
try {
return getAgentManager().count(query.getCriteria());
} catch (ExplicitException e) {
error(e.getMessage());
}
}
return 0;
}
@Override
public IModel<Agent> model(Agent object) {
Long agentId = object.getId();
return new LoadableDetachableModel<Agent>() {
@Override
protected Agent load() {
return getAgentManager().load(agentId);
}
};
}
};
body = new WebMarkupContainer("body");
add(body.setOutputMarkupId(true));
body.add(new FencedFeedbackPanel("feedback", this));
List<IColumn<Agent, Void>> columns = new ArrayList<>();
columns.add(selectionColumn = new SelectionColumn<Agent, Void>());
columns.add(new AbstractColumn<Agent, Void>(Model.of("Name")) {
@Override
public void populateItem(Item<ICellPopulator<Agent>> cellItem, String componentId, IModel<Agent> rowModel) {
Fragment fragment = new Fragment(componentId, "agentLinkFrag", AgentListPanel.this);
Agent agent = rowModel.getObject();
Link<Void> link = new BookmarkablePageLink<Void>("link",
AgentOverviewPage.class, AgentOverviewPage.paramsOf(agent));
link.add(new SpriteImage("icon", agent.getOs().getIcon()));
link.add(new Label("label", agent.getName()));
fragment.add(link);
cellItem.add(fragment);
}
});
columns.add(new AbstractColumn<Agent, Void>(Model.of("IP Address")) {
@Override
public void populateItem(Item<ICellPopulator<Agent>> cellItem, String componentId, IModel<Agent> rowModel) {
Agent agent = rowModel.getObject();
cellItem.add(new Label(componentId, agent.getIpAddress()));
}
});
columns.add(new AbstractColumn<Agent, Void>(Model.of("CPU")) {
@Override
public void populateItem(Item<ICellPopulator<Agent>> cellItem, String componentId, IModel<Agent> rowModel) {
Agent agent = rowModel.getObject();
cellItem.add(new Label(componentId, agent.getCpu()));
}
@Override
public String getCssClass() {
return "d-none d-lg-table-cell";
}
@Override
public Component getHeader(String componentId) {
return new Fragment(componentId, "cpuHeaderFrag", AgentListPanel.this);
}
});
columns.add(new AbstractColumn<Agent, Void>(Model.of("Memory")) {
@Override
public void populateItem(Item<ICellPopulator<Agent>> cellItem, String componentId, IModel<Agent> rowModel) {
Agent agent = rowModel.getObject();
cellItem.add(new Label(componentId, agent.getMemory()));
}
@Override
public String getCssClass() {
return "d-none d-lg-table-cell";
}
@Override
public Component getHeader(String componentId) {
return new Fragment(componentId, "memoryHeaderFrag", AgentListPanel.this);
}
});
columns.add(new AbstractColumn<Agent, Void>(Model.of("Status")) {
@Override
public void populateItem(Item<ICellPopulator<Agent>> cellItem, String componentId, IModel<Agent> rowModel) {
cellItem.add(new AgentStatusBadge(componentId, rowModel));
}
});
body.add(agentsTable = new OneDataTable<Agent, Void>("agents", columns, dataProvider,
WebConstants.PAGE_SIZE, getPagingHistorySupport()));
setOutputMarkupId(true);
}
}
| 11,293 |
310 |
<gh_stars>100-1000
{
"name": "Mother-32",
"description": "A modular synth.",
"url": "https://www.moogmusic.com/products/semi-modular/mother-32"
}
| 61 |
335 |
<filename>C/Corporation_noun.json<gh_stars>100-1000
{
"word": "Corporation",
"definitions": [
"A large company or group of companies authorized to act as a single entity and recognized as such in law.",
"A group of people elected to govern a city, town, or borough.",
"A paunch."
],
"parts-of-speech": "Noun"
}
| 133 |
399 |
<gh_stars>100-1000
/*-
* #%L
* athena-elasticsearch
* %%
* Copyright (C) 2019 - 2020 Amazon Web Services
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.amazonaws.athena.connectors.elasticsearch;
import org.apache.arrow.vector.types.Types;
import org.apache.arrow.vector.types.pojo.Field;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* This class is used to test the ElasticsearchGlueTypeMapper class.
*/
@RunWith(MockitoJUnitRunner.class)
public class ElasticsearchGlueTypeMapperTest
{
private static final Logger logger = LoggerFactory.getLogger(ElasticsearchGlueTypeMapperTest.class);
@Test
public void getFieldTest()
{
logger.info("getFieldTest: enter");
ElasticsearchGlueTypeMapper glueTypeMapper = new ElasticsearchGlueTypeMapper();
Field field;
// Test scaling factor with decimal point.
field = glueTypeMapper.getField("myscaled", "SCALED_FLOAT(100.0)");
logger.info("Field: {}, metadata: {}", field, field.getMetadata());
assertEquals("Field's name is invalid: ", "myscaled", field.getName());
assertEquals("Field's type is invalid: ", Types.MinorType.BIGINT.getType(), field.getType());
assertEquals("Field's scaling factor is invalid: ",
"100.0", field.getMetadata().get("scaling_factor"));
// Test scaling factor w/o decimal point.
field = glueTypeMapper.getField("myscaled", "SCALED_FLOAT(100)");
logger.info("Field: {}, metadata: {}", field, field.getMetadata());
assertEquals("Field's name is invalid: ", "myscaled", field.getName());
assertEquals("Field's type is invalid: ", Types.MinorType.BIGINT.getType(), field.getType());
assertEquals("Field's scaling factor is invalid: ",
"100", field.getMetadata().get("scaling_factor"));
// Test an INT field
field = glueTypeMapper.getField("myscaled", "INT");
logger.info("Field: {}, metadata: {}", field, field.getMetadata());
assertEquals("Field's name is invalid: ", "myscaled", field.getName());
assertEquals("Field's type is invalid: ", Types.MinorType.INT.getType(), field.getType());
assertTrue("Fields metadata is invalid: ", field.getMetadata().isEmpty());
logger.info("getFieldTest: exit");
}
}
| 1,077 |
848 |
/*
* Copyright 2021 Xilinx Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
int main(int argc, char* argv[]) {
cv::Mat a(2, 2, CV_8UC1);
cv::Mat b(4, 4, CV_8UC1);
a return 0;
}
| 256 |
1,639 |
<reponame>bazzyadb/all-code
#include<bits/stdc++.h>
using namespace std;
const int N = 20;
long long dp[1 << N];
int n, a[N][N];
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int t; cin >> t;
while (t--) {
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) cin >> a[i][j];
}
memset(dp, 0, sizeof dp);
dp[(1 << n) - 1] = 1;
for (int mask = (1 << n) - 2; mask >= 0; mask--) {
int i = __builtin_popcount(mask);
for (int j = 0; j < n; j++) if (!(mask >> j & 1)) dp[mask] += dp[mask | 1 << j] * a[i][j];
}
cout << dp[0] << '\n'; // permanent of the matrix
}
return 0;
}
| 360 |
330 |
#!/usr/bin/env python
"""
Copyright (c) 2017, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Ryan Dellana nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import cv2
import tensorflow as tf
import pickle
from car_models import cnn_cccccfffff
import os
import cv2
import numpy as np
import time
def load_dataset(path, percent_testing=None):
assert percent_testing is None or (percent_testing >= 0.0 and percent_testing <= 1.0)
x, y, fnames = [], [], []
for i in os.walk(path):
(d, sub_dirs, files_) = i
fnames.extend(files_)
seq_fname = []
for fname in fnames:
seq = int(fname.split('_')[0])
seq_fname.append((seq, fname))
seq_fname.sort()
for (seq, fname) in seq_fname:
#img = cv2.imread(path+'/'+fname, 1) for black and white
img = cv2.imread(path+'/'+fname)
img = cv2.resize(img, (200, 150), interpolation=cv2.INTER_CUBIC)
#img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for black and white
img = img[35:,:,:]
#img = img[35:,:] for black and white
#img = np.reshape(img, (115, 200, 1)) for black and white
x.append(img)
_, timestamp, throttle, steering = fname.split('_')
timestamp, throttle, steering = long(timestamp), float(throttle), float(steering.split('.jpg')[0])
print('(seq, timestamp, throttle, steering):', seq, timestamp, throttle, steering)
y.append((steering, throttle))
train_x, train_y, test_x, test_y = [], [], [], []
if percent_testing is not None:
tst_strt = int(len(x)*(1.0-percent_testing))
train_x, train_y, test_x, test_y = x[:tst_strt], y[:tst_strt], x[tst_strt:], y[tst_strt:]
else:
train_x, train_y = x, y
return train_x, train_y, test_x, test_y
path = '/home/djtobias/Documents/Tensorflow/TrainingIMG'
train_x, train_y, test_x, test_y = load_dataset(path=path, percent_testing=0.20)
num_epochs = 100
batch_size = 100
# Drop items from dataset so that it's divisible by batch_size
train_x = train_x[0:-1*(len(train_x) % batch_size)]
train_y = train_y[0:-1*(len(train_y) % batch_size)]
test_x = test_x[0:-1*(len(test_x) % batch_size)]
test_y = test_y[0:-1*(len(test_y) % batch_size)]
print('len(test_x) =', len(test_x))
batches_per_epoch = int(len(train_x)/batch_size)
sess = tf.InteractiveSession()
model = cnn_cccccfffff()
train_step = tf.train.AdamOptimizer(1e-4).minimize(model.loss)
saver = tf.train.Saver()
sess.run(tf.initialize_all_variables())
for i in range(num_epochs):
for b in range(0, batches_per_epoch):
batch = [train_x[b*batch_size:b*batch_size+batch_size], train_y[b*batch_size:b*batch_size+batch_size]]
# --- normalize batch ---
batch_ = [[],[]]
for j in range(len(batch[0])):
batch_[0].append(batch[0][j].astype(dtype=np.float32)/255.0)
batch_[1].append(np.array([batch[1][j][0]], dtype=np.float32))
batch = batch_
# ------------------------
train_step.run(feed_dict={model.x:batch[0], model.y_:batch[1], model.keep_prob_fc1:0.8, model.keep_prob_fc2:0.8, model.keep_prob_fc3:0.8, model.keep_prob_fc4:0.8})
#train_error = model.loss.eval(feed_dict={model.x:batch[0], model.y_:batch[1],
# model.keep_prob_fc1:1.0, model.keep_prob_fc2:1.0,
# model.keep_prob_fc3:1.0, model.keep_prob_fc4:1.0})
#print("epoch %d, training entropy %g"%(i, train_error))
print('epoch', i, 'complete')
if i % 5 == 0:
test_error = 0.0
for b in range(0, len(test_x), batch_size):
batch = [test_x[b:b+batch_size], test_y[b:b+batch_size]]
# --- normalize batch ---
batch_ = [[],[]]
for j in range(len(batch[0])):
batch_[0].append(batch[0][j].astype(dtype=np.float32)/255.0)
batch_[1].append(np.array([batch[1][j][0]], dtype=np.float32))
batch = batch_
#print('batch =', len(batch[0]), len(batch[1]))
test_error_ = model.loss.eval(feed_dict={model.x:batch[0], model.y_:batch[1],
model.keep_prob_fc1:1.0, model.keep_prob_fc2:1.0,
model.keep_prob_fc3:1.0, model.keep_prob_fc4:1.0})
# -----------------------
test_error += test_error_
test_error /= len(test_x)/batch_size
test_accuracy = 1.0 - test_error
print("test accuracy %g"%test_accuracy)
filename = saver.save(sess, '/home/djtobias/Documents/Tensorflow/model.ckpt')
| 2,690 |
14,668 |
<filename>content/test/gpu/flake_suppressor/expectations.py
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module for interacting with expectation files."""
import base64
import collections
import os
import posixpath
import re
import six
# This script is Python 3-only, but some presubmit stuff still tries to parse
# it in Python 2, and this module does not exist in Python 2.
if six.PY3:
import urllib.request
import flake_suppressor
from flake_suppressor import tag_utils
from typ import expectations_parser
CHROMIUM_SRC_DIR = flake_suppressor.CHROMIUM_SRC_DIR
RELATIVE_EXPECTATION_FILE_DIRECTORY = os.path.join('content', 'test', 'gpu',
'gpu_tests',
'test_expectations')
ABSOLUTE_EXPECTATION_FILE_DIRECTORY = os.path.join(
CHROMIUM_SRC_DIR, RELATIVE_EXPECTATION_FILE_DIRECTORY)
# For most test suites reported to ResultDB, we can chop off "_integration_test"
# and get the name used for the expectation file. However, there are a few
# special cases, so map those there.
EXPECTATION_FILE_OVERRIDE = {
'info_collection_test': 'info_collection',
'trace': 'trace_test',
}
GITILES_URL = 'https://chromium.googlesource.com/chromium/src/+/refs/heads/main'
TEXT_FORMAT_ARG = '?format=TEXT'
TAG_GROUP_REGEX = re.compile(r'# tags: \[([^\]]*)\]', re.MULTILINE | re.DOTALL)
def IterateThroughResultsForUser(result_map, group_by_tags, include_all_tags):
"""Iterates over |result_map| for the user to provide input.
For each unique result, user will be able to decide whether to ignore it (do
nothing), mark as flaky (add RetryOnFailure expectation), or mark as failing
(add Failure expectation). If the latter two are chosen, they can also
associate a bug with the new expectation.
Args:
result_map: Aggregated query results from results.AggregateResults to
iterate over.
group_by_tags: A boolean denoting whether to attempt to group expectations
by tags or not. If True, expectations will be added after an existing
expectation whose tags are the largest subset of the produced tags. If
False, new expectations will be appended to the end of the file.
include_all_tags: A boolean denoting whether all tags should be used for
expectations or only the most specific ones.
"""
typ_tag_ordered_result_map = _ReorderMapByTypTags(result_map)
for suite, test_map in result_map.items():
for test, tag_map in test_map.items():
for typ_tags, build_url_list in tag_map.items():
print('')
print('Suite: %s' % suite)
print('Test: %s' % test)
print('Configuration:\n %s' % '\n '.join(typ_tags))
print('Failed builds:\n %s' % '\n '.join(build_url_list))
other_failures_for_test = FindFailuresInSameTest(
result_map, suite, test, typ_tags)
if other_failures_for_test:
print('Other failures in same test found on other configurations')
for (tags, failure_count) in other_failures_for_test:
print(' %d failures on %s' % (failure_count, ' '.join(tags)))
other_failures_for_config = FindFailuresInSameConfig(
typ_tag_ordered_result_map, suite, test, typ_tags)
if other_failures_for_config:
print('Other failures on same configuration found in other tests')
for (name, failure_count) in other_failures_for_config:
print(' %d failures in %s' % (failure_count, name))
expected_result, bug = PromptUserForExpectationAction()
if not expected_result:
continue
ModifyFileForResult(suite, test, typ_tags, bug, expected_result,
group_by_tags, include_all_tags)
def IterateThroughResultsWithThresholds(result_map, group_by_tags,
result_counts, ignore_threshold,
flaky_threshold, include_all_tags):
"""Iterates over |result_map| and generates expectations based off thresholds.
Args:
result_map: Aggregated query results from results.AggregateResults to
iterate over.
group_by_tags: A boolean denoting whether to attempt to group expectations
by tags or not. If True, expectations will be added after an existing
expectation whose tags are the largest subset of the produced tags. If
False, new expectations will be appended to the end of the file.
result_counts: A dict in the format output by queries.GetResultCounts.
ignore_threshold: A float containing the fraction of failed tests under
which failures will be ignored.
flaky_threshold: A float containing the fraction of failed tests under which
failures will be suppressed with RetryOnFailure and above which will be
suppressed with Failure.
include_all_tags: A boolean denoting whether all tags should be used for
expectations or only the most specific ones.
"""
assert isinstance(ignore_threshold, float)
assert isinstance(flaky_threshold, float)
for suite, test_map in result_map.items():
for test, tag_map in test_map.items():
for typ_tags, build_url_list in tag_map.items():
failure_count = len(build_url_list)
total_count = result_counts[typ_tags][test]
fraction = failure_count / total_count
if fraction < ignore_threshold:
continue
if fraction < flaky_threshold:
expected_result = 'RetryOnFailure'
else:
expected_result = 'Failure'
ModifyFileForResult(suite, test, typ_tags, '', expected_result,
group_by_tags, include_all_tags)
def FindFailuresInSameTest(result_map, target_suite, target_test,
target_typ_tags):
"""Finds all other failures that occurred in the given test.
Ignores the failures for the test on the same configuration.
Args:
result_map: Aggregated query results from results.AggregateResults.
target_suite: A string containing the test suite being checked.
target_test: A string containing the target test case being checked.
target_typ_tags: A list of strings containing the typ tags that the failure
took place on.
Returns:
A list of tuples (typ_tags, count). |typ_tags| is a list of strings
defining a configuration the specified test failed on. |count| is how many
times the test failed on that configuration.
"""
other_failures = []
target_typ_tags = tuple(target_typ_tags)
tag_map = result_map.get(target_suite, {}).get(target_test, {})
for typ_tags, build_url_list in tag_map.items():
if typ_tags == target_typ_tags:
continue
other_failures.append((typ_tags, len(build_url_list)))
return other_failures
def FindFailuresInSameConfig(typ_tag_ordered_result_map, target_suite,
target_test, target_typ_tags):
"""Finds all other failures that occurred on the given configuration.
Ignores the failures for the given test on the given configuration.
Args:
typ_tag_ordered_result_map: Aggregated query results from
results.AggregateResults that have been reordered using
_ReorderMapByTypTags.
target_suite: A string containing the test suite the original failure was
found in.
target_test: A string containing the test case the original failure was
found in.
target_typ_tags: A list of strings containing the typ tags defining the
configuration to find failures for.
Returns:
A list of tuples (full_name, count). |full_name| is a string containing a
test suite and test case concatenated together. |count| is how many times
|full_name| failed on the configuration specified by |target_typ_tags|.
"""
target_typ_tags = tuple(target_typ_tags)
other_failures = []
suite_map = typ_tag_ordered_result_map.get(target_typ_tags, {})
for suite, test_map in suite_map.items():
for test, build_url_list in test_map.items():
if suite == target_suite and test == target_test:
continue
full_name = '%s.%s' % (suite, test)
other_failures.append((full_name, len(build_url_list)))
return other_failures
def _ReorderMapByTypTags(result_map):
"""Rearranges|result_map| to use typ tags as the top level keys.
Args:
result_map: Aggregated query results from results.AggregateResults
Returns:
A dict containing the same contents as |result_map|, but in the following
format:
{
typ_tags (tuple of str): {
suite (str): {
test (str): build_url_list (list of str),
},
},
}
"""
reordered_map = {}
for suite, test_map in result_map.items():
for test, tag_map in test_map.items():
for typ_tags, build_url_list in tag_map.items():
reordered_map.setdefault(typ_tags,
{}).setdefault(suite,
{})[test] = build_url_list
return reordered_map
def PromptUserForExpectationAction():
"""Prompts the user on what to do to handle a failure.
Returns:
A tuple (expected_result, bug). |expected_result| is a string containing
the expected result to use for the expectation, e.g. RetryOnFailure. |bug|
is a string containing the bug to use for the expectation. If the user
chooses to ignore the failure, both will be None. Otherwise, both are
filled, although |bug| may be an empty string if no bug is provided.
"""
prompt = ('How should this failure be handled? (i)gnore/(r)etry on '
'failure/(f)ailure: ')
valid_inputs = ['f', 'i', 'r']
response = input(prompt).lower()
while response not in valid_inputs:
print('Invalid input, valid inputs are %s' % (', '.join(valid_inputs)))
response = input(prompt).lower()
if response == 'i':
return (None, None)
expected_result = 'RetryOnFailure' if response == 'r' else 'Failure'
prompt = ('What is the bug URL that should be associated with this '
'expectation? E.g. crbug.com/1234. ')
response = input(prompt)
return (expected_result, response)
def ModifyFileForResult(suite, test, typ_tags, bug, expected_result,
group_by_tags, include_all_tags):
"""Adds an expectation to the appropriate expectation file.
Args:
suite: A string containing the suite the failure occurred in.
test: A string containing the test case the failure occurred in.
typ_tags: A list of strings containing the typ tags the test produced.
bug: A string containing the bug to associate with the new expectation.
expected_result: A string containing the expected result to use for the new
expectation, e.g. RetryOnFailure.
group_by_tags: A boolean denoting whether to attempt to group expectations
by tags or not. If True, expectations will be added after an existing
expectation whose tags are the largest subset of the produced tags. If
False, new expectations will be appended to the end of the file.
include_all_tags: A boolean denoting whether all tags should be used for
expectations or only the most specific ones.
"""
expectation_file = GetExpectationFileForSuite(suite, typ_tags)
if not include_all_tags:
# Remove temporarily un-ignored tags, namely webgl-version-x tags, since
# those were necessary to find the correct file. However, we do not want
# to actually include them in the file since they are unused/ignored.
typ_tags = tag_utils.RemoveTemporarilyKeptIgnoredTags(typ_tags)
typ_tags = FilterToMostSpecificTypTags(typ_tags, expectation_file)
bug = '%s ' % bug if bug else bug
def AppendExpectationToEnd():
expectation_line = '%s[ %s ] %s [ %s ]\n' % (bug, ' '.join(typ_tags), test,
expected_result)
with open(expectation_file, 'a') as outfile:
outfile.write(expectation_line)
if group_by_tags:
insertion_line, best_matching_tags = FindBestInsertionLineForExpectation(
typ_tags, expectation_file)
if insertion_line == -1:
AppendExpectationToEnd()
else:
# If we've already filtered tags, then use those instead of the "best
# matching" ones.
tags_to_use = best_matching_tags
if not include_all_tags:
tags_to_use = typ_tags
# enumerate starts at 0 but line numbers start at 1.
insertion_line -= 1
tags_to_use = list(tags_to_use)
tags_to_use.sort()
expectation_line = '%s[ %s ] %s [ %s ]\n' % (bug, ' '.join(tags_to_use),
test, expected_result)
with open(expectation_file) as infile:
input_contents = infile.read()
output_contents = ''
for lineno, line in enumerate(input_contents.splitlines(True)):
output_contents += line
if lineno == insertion_line:
output_contents += expectation_line
with open(expectation_file, 'w') as outfile:
outfile.write(output_contents)
else:
AppendExpectationToEnd()
def FilterToMostSpecificTypTags(typ_tags, expectation_file):
"""Filters |typ_tags| to the most specific set.
Assumes that the tags in |expectation_file| are ordered from least specific
to most specific within each tag group.
Args:
typ_tags: A list of strings containing the typ tags the test produced.
expectation_file: A string containing a filepath pointing to the
expectation file to filter tags with.
Returns:
A list containing the contents of |typ_tags| with only the most specific
tag from each tag group remaining.
"""
with open(expectation_file) as infile:
contents = infile.read()
tag_groups = []
for match in TAG_GROUP_REGEX.findall(contents):
tag_groups.append(match.strip().replace('#', '').split())
num_matches = 0
tags_in_same_group = collections.defaultdict(list)
for tag in typ_tags:
for index, tag_group in enumerate(tag_groups):
if tag in tag_group:
tags_in_same_group[index].append(tag)
num_matches += 1
break
if num_matches != len(typ_tags):
all_tags = set()
for group in tag_groups:
all_tags |= set(group)
raise RuntimeError('Found tags not in expectation file: %s' %
' '.join(set(typ_tags) - all_tags))
filtered_tags = []
for index, tags in tags_in_same_group.items():
if len(tags) == 1:
filtered_tags.append(tags[0])
else:
tag_group = tag_groups[index]
best_index = -1
for t in tags:
i = tag_group.index(t)
if i > best_index:
best_index = i
filtered_tags.append(tag_group[best_index])
# Sort to keep order consistent with what we were given.
filtered_tags.sort()
return filtered_tags
def GetExpectationFileForSuite(suite, typ_tags):
"""Finds the correct expectation file for the given suite.
Args:
suite: A string containing the test suite to look for.
typ_tags: A list of strings containing typ tags that were produced by the
failing test.
Returns:
A string containing a filepath to the correct expectation file for |suite|
and |typ_tags|.
"""
truncated_suite = suite.replace('_integration_test', '')
if truncated_suite == 'webgl_conformance':
if 'webgl-version-2' in typ_tags:
truncated_suite = 'webgl2_conformance'
expectation_file = EXPECTATION_FILE_OVERRIDE.get(truncated_suite,
truncated_suite)
expectation_file += '_expectations.txt'
expectation_file = os.path.join(ABSOLUTE_EXPECTATION_FILE_DIRECTORY,
expectation_file)
return expectation_file
def FindBestInsertionLineForExpectation(typ_tags, expectation_file):
"""Finds the best place to insert an expectation when grouping by tags.
Args:
typ_tags: A list of strings containing typ tags that were produced by the
failing test.
expectation_file: A string containing a filepath to the expectation file to
use.
Returns:
A tuple (insertion_line, best_matching_tags). |insertion_line| is an int
specifying the line number to insert the expectation into.
|best_matching_tags| is a set containing the tags of an existing expectation
that was found to be the closest match. If no appropriate line is found,
|insertion_line| is -1 and |best_matching_tags| is empty.
"""
best_matching_tags = set()
best_insertion_line = -1
with open(expectation_file) as f:
content = f.read()
list_parser = expectations_parser.TaggedTestListParser(content)
for e in list_parser.expectations:
expectation_tags = e.tags
if not expectation_tags.issubset(typ_tags):
continue
if len(expectation_tags) > len(best_matching_tags):
best_matching_tags = expectation_tags
best_insertion_line = e.lineno
elif len(expectation_tags) == len(best_matching_tags):
if best_insertion_line < e.lineno:
best_insertion_line = e.lineno
return best_insertion_line, best_matching_tags
def GetExpectationFilesFromOrigin():
"""Gets expectation file contents from origin/main.
Returns:
A dict of expectation file name (str) -> expectation file contents (str)
that are available on origin/main.
"""
# Get the path to the expectation file directory in gitiles, i.e. the POSIX
# path relative to the Chromium src directory.
origin_dir = RELATIVE_EXPECTATION_FILE_DIRECTORY.replace(os.sep, '/')
origin_dir_url = posixpath.join(GITILES_URL, origin_dir) + TEXT_FORMAT_ARG
response = urllib.request.urlopen(origin_dir_url).read()
# Response is a base64 encoded, newline-separated list of files in the
# directory in the format: `mode file_type hash name`
files = []
decoded_text = base64.b64decode(response).decode('utf-8')
for line in decoded_text.splitlines():
files.append(line.split()[-1])
origin_file_contents = {}
for f in files:
origin_filepath = posixpath.join(origin_dir, f)
origin_filepath_url = posixpath.join(GITILES_URL,
origin_filepath) + TEXT_FORMAT_ARG
response = urllib.request.urlopen(origin_filepath_url).read()
decoded_text = base64.b64decode(response).decode('utf-8')
origin_file_contents[f] = decoded_text
return origin_file_contents
def GetExpectationFilesFromLocalCheckout():
"""Gets expectaiton file contents from the local checkout.
Returns:
A dict of expectation file name (str) -> expectation file contents (str)
that are available from the local checkout.
"""
local_file_contents = {}
for f in os.listdir(ABSOLUTE_EXPECTATION_FILE_DIRECTORY):
with open(os.path.join(ABSOLUTE_EXPECTATION_FILE_DIRECTORY, f)) as infile:
local_file_contents[f] = infile.read()
return local_file_contents
def AssertCheckoutIsUpToDate():
"""Confirms that the local checkout's expectations are up to date."""
origin_file_contents = GetExpectationFilesFromOrigin()
local_file_contents = GetExpectationFilesFromLocalCheckout()
if origin_file_contents != local_file_contents:
raise RuntimeError(
'Local Chromium checkout expectations are out of date. Please perform '
'a `git pull`.')
| 7,123 |
5,169 |
<reponame>Gantios/Specs
{
"name": "DAIMKit",
"version": "0.1.17",
"summary": "Important Message Model.",
"description": "Important Message Model Description.",
"homepage": "http://git.duia.org.cn/ios/ImportMessageModel.git",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"fuqiang": "<EMAIL>"
},
"source": {
"git": "http://git.duia.org.cn/ios/ImportMessageModel.git",
"branch": "dev",
"tag": "0.1.17"
},
"platforms": {
"ios": "8.0"
},
"ios": {
"frameworks": [
"UIKit",
"Foundation",
"Accelerate",
"CoreFoundation",
"CoreGraphics",
"CoreImage",
"QuartzCore",
"Security",
"SystemConfiguration"
],
"resources": "DAIMKit/**/*.{plist,html,xcdatamodeld,bundle,json,xib}",
"resource_bundles": {
"DAIMKit": [
"DAIMKit/Resource/DAIM.xcassets"
]
}
},
"source_files": "DAIMKit/**/*.{h,m}",
"user_target_xcconfig": {
"CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES": "YES"
},
"dependencies": {
"SDWebImage": [
"~>3.7"
],
"AFNetworking": [
],
"Reachability": [
],
"MJExtension": [
],
"YYModel": [
],
"OpenUDID": [
],
"UMengAnalytics": [
],
"SKBounceAnimation": [
],
"YYCategories": [
]
},
"static_framework": true,
"prefix_header_file": "DAIMKit/Supporting Files/DAIM_Prefix.pch"
}
| 695 |
420 |
package android.os;
import kotlin.NotImplementedError;
/**
* Power manager compat class
*/
public final class PowerManager {
public static final int ACQUIRE_CAUSES_WAKEUP = 268435456;
public static final String ACTION_DEVICE_IDLE_MODE_CHANGED = "android.os.action.DEVICE_IDLE_MODE_CHANGED";
public static final String ACTION_POWER_SAVE_MODE_CHANGED = "android.os.action.POWER_SAVE_MODE_CHANGED";
/** @deprecated */
@Deprecated
public static final int FULL_WAKE_LOCK = 26;
public static final int ON_AFTER_RELEASE = 536870912;
public static final int PARTIAL_WAKE_LOCK = 1;
public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 32;
public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1;
/** @deprecated */
@Deprecated
public static final int SCREEN_BRIGHT_WAKE_LOCK = 10;
/** @deprecated */
@Deprecated
public static final int SCREEN_DIM_WAKE_LOCK = 6;
public static final PowerManager INSTANCE = new PowerManager();
public PowerManager.WakeLock newWakeLock(int levelAndFlags, String tag) {
return new WakeLock();
}
public boolean isWakeLockLevelSupported(int level) {
return true;
}
/** @deprecated */
@Deprecated
public boolean isScreenOn() {
return true;
}
public boolean isInteractive() {
return true;
}
public void reboot(String reason) {
throw new NotImplementedError("This device cannot be rebooted!");
}
public boolean isPowerSaveMode() {
return false;
}
public boolean isDeviceIdleMode() {
return false;
}
public boolean isIgnoringBatteryOptimizations(String packageName) {
return true;
}
public boolean isSustainedPerformanceModeSupported() {
return true;
}
public final class WakeLock {
int count = 0;
public void setReferenceCounted(boolean value) {
count = -1;
}
public void acquire() {
if(count != -1 && count != -2)
count++;
}
public void acquire(long timeout) {
acquire();
}
public void release() {
if(count > 0 || count == -1)
count--;
}
public void release(int flags) {
release();
}
public boolean isHeld() {
return count > 0 || count == -1;
}
public void setWorkSource(WorkSource ws) {
//Do nothing
}
}
}
| 1,041 |
34,359 |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "WindowManager.h"
#include "MonarchFactory.h"
#include "CommandlineArgs.h"
#include "../inc/WindowingBehavior.h"
#include "FindTargetWindowArgs.h"
#include "ProposeCommandlineResult.h"
#include "WindowManager.g.cpp"
#include "../../types/inc/utils.hpp"
using namespace winrt;
using namespace winrt::Microsoft::Terminal;
using namespace winrt::Windows::Foundation;
using namespace ::Microsoft::Console;
namespace winrt::Microsoft::Terminal::Remoting::implementation
{
WindowManager::WindowManager()
{
_monarchWaitInterrupt.create();
// Register with COM as a server for the Monarch class
_registerAsMonarch();
// Instantiate an instance of the Monarch. This may or may not be in-proc!
auto foundMonarch = false;
while (!foundMonarch)
{
try
{
_createMonarchAndCallbacks();
// _createMonarchAndCallbacks will initialize _isKing
foundMonarch = true;
}
catch (...)
{
// If we fail to find the monarch,
// stay in this jail until we do.
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_ExceptionInCtor",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
}
}
}
WindowManager::~WindowManager()
{
// IMPORTANT! Tear down the registration as soon as we exit. If we're not a
// real peasant window (the monarch passed our commandline to someone else),
// then the monarch dies, we don't want our registration becoming the active
// monarch!
CoRevokeClassObject(_registrationHostClass);
_registrationHostClass = 0;
SignalClose();
_monarchWaitInterrupt.SetEvent();
// A thread is joinable once it's been started. Basically this just
// makes sure that the thread isn't just default-constructed.
if (_electionThread.joinable())
{
_electionThread.join();
}
}
void WindowManager::SignalClose()
{
if (_monarch)
{
try
{
_monarch.SignalClose(_peasant.GetID());
}
CATCH_LOG()
}
}
void WindowManager::_proposeToMonarch(const Remoting::CommandlineArgs& args,
std::optional<uint64_t>& givenID,
winrt::hstring& givenName)
{
// these two errors are Win32 errors, convert them to HRESULTS so we can actually compare below.
static constexpr auto RPC_SERVER_UNAVAILABLE_HR = HRESULT_FROM_WIN32(RPC_S_SERVER_UNAVAILABLE);
static constexpr auto RPC_CALL_FAILED_HR = HRESULT_FROM_WIN32(RPC_S_CALL_FAILED);
// The monarch may respond back "you should be a new
// window, with ID,name of (id, name)". Really the responses are:
// * You should not create a new window
// * Create a new window (but without a given ID or name). The
// Monarch will assign your ID/name later
// * Create a new window, and you'll have this ID or name
// - This is the case where the user provides `wt -w 1`, and
// there's no existing window 1
// You can emulate the monarch dying by: starting a terminal, sticking a
// breakpoint in
// TerminalApp!winrt::TerminalApp::implementation::AppLogic::_doFindTargetWindow,
// starting a defterm, and when that BP gets hit, kill the original
// monarch, and see what happens here.
auto proposedCommandline = false;
Remoting::ProposeCommandlineResult result{ nullptr };
while (!proposedCommandline)
{
try
{
// MSFT:38542548 _We believe_ that this is the source of the
// crash here. After we get the result, stash it's values into a
// local copy, so that we can check them later. If the Monarch
// dies between now and the inspection of
// `result.ShouldCreateWindow` below, we don't want to explode
// (since _proposeToMonarch is not try/caught).
auto outOfProcResult = _monarch.ProposeCommandline(args);
result = winrt::make<implementation::ProposeCommandlineResult>(outOfProcResult);
proposedCommandline = true;
}
catch (const winrt::hresult_error& e)
{
// We did not successfully ask the king what to do. They
// hopefully just died here. That's okay, let's just go ask the
// next in the line of succession. At the very worst, we'll find
// _us_, (likely last in the line).
//
// If the king returned some _other_ error here, than lets
// bubble that up because that's a real issue.
//
// I'm checking both these here. I had previously got a
// RPC_S_CALL_FAILED about here once.
if (e.code() == RPC_SERVER_UNAVAILABLE_HR || e.code() == RPC_CALL_FAILED_HR)
{
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_proposeToMonarch_kingDied",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
// We failed to ask the monarch. It must have died. Try and
// find the real monarch. Don't perform an election, that
// assumes we have a peasant, which we don't yet.
_createMonarchAndCallbacks();
// _createMonarchAndCallbacks will initialize _isKing
if (_isKing)
{
// We became the king. We don't need to ProposeCommandline to ourself, we're just
// going to do it.
//
// Return early, because there's nothing else for us to do here.
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_proposeToMonarch_becameKing",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
// In WindowManager::ProposeCommandline, had we been the
// king originally, we would have started by setting
// this to true. We became the monarch here, so set it
// here as well.
_shouldCreateWindow = true;
return;
}
// Here, we created the new monarch, it wasn't us, so we're
// gonna go through the while loop again and ask the new
// king.
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_proposeToMonarch_tryAgain",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
}
else
{
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_proposeToMonarch_unexpectedResultFromKing",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
LOG_CAUGHT_EXCEPTION();
throw;
}
}
catch (...)
{
// If the monarch (maybe us) failed for _any other reason_ than
// them dying. This IS quite unexpected. Let this bubble out.
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_proposeToMonarch_unexpectedExceptionFromKing",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
LOG_CAUGHT_EXCEPTION();
throw;
}
}
// Here, the monarch (not us) has replied to the message. Get the
// valuables out of the response:
_shouldCreateWindow = result.ShouldCreateWindow();
if (result.Id())
{
givenID = result.Id().Value();
}
givenName = result.WindowName();
// TraceLogging doesn't have a good solution for logging an
// optional. So we have to repeat the calls here:
if (givenID)
{
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_ProposeCommandline",
TraceLoggingBoolean(_shouldCreateWindow, "CreateWindow", "true iff we should create a new window"),
TraceLoggingUInt64(givenID.value(), "Id", "The ID we should assign our peasant"),
TraceLoggingWideString(givenName.c_str(), "Name", "The name we should assign this window"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
}
else
{
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_ProposeCommandline",
TraceLoggingBoolean(_shouldCreateWindow, "CreateWindow", "true iff we should create a new window"),
TraceLoggingPointer(nullptr, "Id", "No ID provided"),
TraceLoggingWideString(givenName.c_str(), "Name", "The name we should assign this window"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
}
}
void WindowManager::ProposeCommandline(const Remoting::CommandlineArgs& args)
{
// If we're the king, we _definitely_ want to process the arguments, we were
// launched with them!
//
// Otherwise, the King will tell us if we should make a new window
_shouldCreateWindow = _isKing;
std::optional<uint64_t> givenID;
winrt::hstring givenName{};
if (!_isKing)
{
_proposeToMonarch(args, givenID, givenName);
}
// During _proposeToMonarch, it's possible that we found that the king was dead, and we're the new king. Cool! Do this now.
if (_isKing)
{
// We're the monarch, we don't need to propose anything. We're just
// going to do it.
//
// However, we _do_ need to ask what our name should be. It's
// possible someone started the _first_ wt with something like `wt
// -w king` as the commandline - we want to make sure we set our
// name to "king".
//
// The FindTargetWindow event is the WindowManager's way of saying
// "I do not know how to figure out how to turn this list of args
// into a window ID/name. Whoever's listening to this event does, so
// I'll ask them". It's a convoluted way of hooking the
// WindowManager up to AppLogic without actually telling it anything
// about TerminalApp (or even WindowsTerminal)
auto findWindowArgs{ winrt::make_self<Remoting::implementation::FindTargetWindowArgs>(args) };
_raiseFindTargetWindowRequested(nullptr, *findWindowArgs);
const auto responseId = findWindowArgs->ResultTargetWindow();
if (responseId > 0)
{
givenID = ::base::saturated_cast<uint64_t>(responseId);
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_ProposeCommandline_AsMonarch",
TraceLoggingBoolean(_shouldCreateWindow, "CreateWindow", "true iff we should create a new window"),
TraceLoggingUInt64(givenID.value(), "Id", "The ID we should assign our peasant"),
TraceLoggingWideString(givenName.c_str(), "Name", "The name we should assign this window"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
}
else if (responseId == WindowingBehaviorUseName)
{
givenName = findWindowArgs->ResultTargetWindowName();
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_ProposeCommandline_AsMonarch",
TraceLoggingBoolean(_shouldCreateWindow, "CreateWindow", "true iff we should create a new window"),
TraceLoggingUInt64(0, "Id", "The ID we should assign our peasant"),
TraceLoggingWideString(givenName.c_str(), "Name", "The name we should assign this window"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
}
else
{
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_ProposeCommandline_AsMonarch",
TraceLoggingBoolean(_shouldCreateWindow, "CreateWindow", "true iff we should create a new window"),
TraceLoggingUInt64(0, "Id", "The ID we should assign our peasant"),
TraceLoggingWideString(L"", "Name", "The name we should assign this window"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
}
}
if (_shouldCreateWindow)
{
// If we should create a new window, then instantiate our Peasant
// instance, and tell that peasant to handle that commandline.
_createOurPeasant({ givenID }, givenName);
// Spawn a thread to wait on the monarch, and handle the election
if (!_isKing)
{
_createPeasantThread();
}
// This right here will just tell us to stash the args away for the
// future. The AppHost hasnt yet set up the callbacks, and the rest
// of the app hasn't started at all. We'll note them and come back
// later.
_peasant.ExecuteCommandline(args);
}
// Otherwise, we'll do _nothing_.
}
bool WindowManager::ShouldCreateWindow()
{
return _shouldCreateWindow;
}
void WindowManager::_registerAsMonarch()
{
winrt::check_hresult(CoRegisterClassObject(Monarch_clsid,
winrt::make<::MonarchFactory>().get(),
CLSCTX_LOCAL_SERVER,
REGCLS_MULTIPLEUSE,
&_registrationHostClass));
}
void WindowManager::_createMonarch()
{
// Heads up! This only works because we're using
// "metadata-based-marshalling" for our WinRT types. That means the OS is
// using the .winmd file we generate to figure out the proxy/stub
// definitions for our types automatically. This only works in the following
// cases:
//
// * If we're running unpackaged: the .winmd must be a sibling of the .exe
// * If we're running packaged: the .winmd must be in the package root
_monarch = create_instance<Remoting::IMonarch>(Monarch_clsid,
CLSCTX_LOCAL_SERVER);
}
// NOTE: This can throw! Callers include:
// - the constructor, who performs this in a loop until it successfully
// find a a monarch
// - the performElection method, which is called in the waitOnMonarch
// thread. All the calls in that thread are wrapped in try/catch's
// already.
// - _createOurPeasant, who might do this in a loop to establish us with the
// monarch.
void WindowManager::_createMonarchAndCallbacks()
{
_createMonarch();
if (_monarch == nullptr)
{
// See MSFT:38540483, GH#12774 for details.
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_NullMonarchTryAgain",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
// Here we're gonna just give it a quick second try.Probably not
// definitive, but might help.
_createMonarch();
}
if (_monarch == nullptr)
{
// See MSFT:38540483, GH#12774 for details.
if constexpr (Feature_IsolatedMonarchMode::IsEnabled())
{
// Fall back to having a in proc monarch. Were now isolated from
// other windows. This is a pretty torn state, but at least we
// didn't just explode.
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_NullMonarchIsolateMode",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
_monarch = winrt::make<winrt::Microsoft::Terminal::Remoting::implementation::Monarch>();
}
else
{
// The monarch is null. We're hoping that we can find another,
// hopefully us. We're gonna go back around the loop again and
// see what happens. If this is really an infinite loop (where
// the OS won't even give us back US as the monarch), then I
// suppose we'll find out soon enough.
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_NullMonarchTryAgain",
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
winrt::hresult_error(E_UNEXPECTED, L"Did not expect the Monarch to ever be null");
}
}
// We're pretty confident that we have a Monarch here.
// Save the result of checking if we're the king. We want to avoid
// unnecessary calls back and forth if we can.
_isKing = _areWeTheKing();
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_ConnectedToMonarch",
TraceLoggingUInt64(_monarch.GetPID(), "monarchPID", "The PID of the new Monarch"),
TraceLoggingBoolean(_isKing, "isKing", "true if we are the new monarch"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
if (_peasant)
{
if (const auto& lastActivated{ _peasant.GetLastActivatedArgs() })
{
// Inform the monarch of the time we were last activated
_monarch.HandleActivatePeasant(lastActivated);
}
}
if (!_isKing)
{
return;
}
// Here, we're the king!
//
// This is where you should do any additional setup that might need to be
// done when we become the king. This will be called both for the first
// window, and when the current monarch dies.
_monarch.WindowCreated({ get_weak(), &WindowManager::_WindowCreatedHandlers });
_monarch.WindowClosed({ get_weak(), &WindowManager::_WindowClosedHandlers });
_monarch.FindTargetWindowRequested({ this, &WindowManager::_raiseFindTargetWindowRequested });
_monarch.ShowNotificationIconRequested([this](auto&&, auto&&) { _ShowNotificationIconRequestedHandlers(*this, nullptr); });
_monarch.HideNotificationIconRequested([this](auto&&, auto&&) { _HideNotificationIconRequestedHandlers(*this, nullptr); });
_monarch.QuitAllRequested({ get_weak(), &WindowManager::_QuitAllRequestedHandlers });
_BecameMonarchHandlers(*this, nullptr);
}
bool WindowManager::_areWeTheKing()
{
const auto ourPID{ GetCurrentProcessId() };
const auto kingPID{ _monarch.GetPID() };
return (ourPID == kingPID);
}
Remoting::IPeasant WindowManager::_createOurPeasant(std::optional<uint64_t> givenID,
const winrt::hstring& givenName)
{
auto p = winrt::make_self<Remoting::implementation::Peasant>();
if (givenID)
{
p->AssignID(givenID.value());
}
// If the name wasn't specified, this will be an empty string.
p->WindowName(givenName);
_peasant = *p;
// Try to add us to the monarch. If that fails, try to find a monarch
// again, until we find one (we will eventually find us)
while (true)
{
try
{
_monarch.AddPeasant(_peasant);
break;
}
catch (...)
{
try
{
// Wrap this in it's own try/catch, because this can throw.
_createMonarchAndCallbacks();
}
catch (...)
{
}
}
}
_peasant.GetWindowLayoutRequested({ get_weak(), &WindowManager::_GetWindowLayoutRequestedHandlers });
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_CreateOurPeasant",
TraceLoggingUInt64(_peasant.GetID(), "peasantID", "The ID of our new peasant"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
// If the peasant asks us to quit we should not try to act in future elections.
_peasant.QuitRequested([weakThis{ get_weak() }](auto&&, auto&&) {
if (auto wm = weakThis.get())
{
wm->_monarchWaitInterrupt.SetEvent();
}
});
return _peasant;
}
// Method Description:
// - Attempt to connect to the monarch process. This might be us!
// - For the new monarch, add us to their list of peasants.
// Arguments:
// - <none>
// Return Value:
// - true iff we're the new monarch process.
// NOTE: This can throw!
bool WindowManager::_performElection()
{
_createMonarchAndCallbacks();
// Tell the new monarch who we are. We might be that monarch!
_monarch.AddPeasant(_peasant);
// This method is only called when a _new_ monarch is elected. So
// don't do anything here that needs to be done for all monarch
// windows. This should only be for work that's done when a window
// _becomes_ a monarch, after the death of the previous monarch.
return _isKing;
}
void WindowManager::_createPeasantThread()
{
// If we catch an exception trying to get at the monarch ever, we can
// set the _monarchWaitInterrupt, and use that to trigger a new
// election. Though, we wouldn't be able to retry the function that
// caused the exception in the first place...
_electionThread = std::thread([this] {
_waitOnMonarchThread();
});
}
void WindowManager::_waitOnMonarchThread()
{
// This is the array of HANDLEs that we're going to wait on in
// WaitForMultipleObjects below.
// * waits[0] will be the handle to the monarch process. It gets
// signalled when the process exits / dies.
// * waits[1] is the handle to our _monarchWaitInterrupt event. Another
// thread can use that to manually break this loop. We'll do that when
// we're getting torn down.
HANDLE waits[2];
waits[1] = _monarchWaitInterrupt.get();
const auto peasantID = _peasant.GetID(); // safe: _peasant is in-proc.
auto exitThreadRequested = false;
while (!exitThreadRequested)
{
// At any point in all this, the current monarch might die. If it
// does, we'll go straight to a new election, in the "jail"
// try/catch below. Worst case, eventually, we'll become the new
// monarch.
try
{
// This might fail to even ask the monarch for it's PID.
wil::unique_handle hMonarch{ OpenProcess(PROCESS_ALL_ACCESS,
FALSE,
static_cast<DWORD>(_monarch.GetPID())) };
// If we fail to open the monarch, then they don't exist
// anymore! Go straight to an election.
if (hMonarch.get() == nullptr)
{
const auto gle = GetLastError();
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_FailedToOpenMonarch",
TraceLoggingUInt64(peasantID, "peasantID", "Our peasant ID"),
TraceLoggingUInt64(gle, "lastError", "The result of GetLastError"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
exitThreadRequested = _performElection();
continue;
}
waits[0] = hMonarch.get();
auto waitResult = WaitForMultipleObjects(2, waits, FALSE, INFINITE);
switch (waitResult)
{
case WAIT_OBJECT_0 + 0: // waits[0] was signaled, the handle to the monarch process
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_MonarchDied",
TraceLoggingUInt64(peasantID, "peasantID", "Our peasant ID"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
// Connect to the new monarch, which might be us!
// If we become the monarch, then we'll return true and exit this thread.
exitThreadRequested = _performElection();
break;
case WAIT_OBJECT_0 + 1: // waits[1] was signaled, our manual interrupt
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_MonarchWaitInterrupted",
TraceLoggingUInt64(peasantID, "peasantID", "Our peasant ID"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
exitThreadRequested = true;
break;
case WAIT_TIMEOUT:
// This should be impossible.
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_MonarchWaitTimeout",
TraceLoggingUInt64(peasantID, "peasantID", "Our peasant ID"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
exitThreadRequested = true;
break;
default:
{
// Returning any other value is invalid. Just die.
const auto gle = GetLastError();
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_WaitFailed",
TraceLoggingUInt64(peasantID, "peasantID", "Our peasant ID"),
TraceLoggingUInt64(gle, "lastError", "The result of GetLastError"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
ExitProcess(0);
}
}
}
catch (...)
{
// Theoretically, if window[1] dies when we're trying to get
// it's PID we'll get here. If we just try to do the election
// once here, it's possible we might elect window[2], but have
// it die before we add ourselves as a peasant. That
// _performElection call will throw, and we wouldn't catch it
// here, and we'd die.
// Instead, we're going to have a resilient election process.
// We're going to keep trying an election, until one _doesn't_
// throw an exception. That might mean burning through all the
// other dying monarchs until we find us as the monarch. But if
// this process is alive, then there's _someone_ in the line of
// succession.
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_ExceptionInWaitThread",
TraceLoggingUInt64(peasantID, "peasantID", "Our peasant ID"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
auto foundNewMonarch = false;
while (!foundNewMonarch)
{
try
{
exitThreadRequested = _performElection();
// It doesn't matter if we're the monarch, or someone
// else is, but if we complete the election, then we've
// registered with a new one. We can escape this jail
// and re-enter society.
foundNewMonarch = true;
}
catch (...)
{
// If we fail to acknowledge the results of the election,
// stay in this jail until we do.
TraceLoggingWrite(g_hRemotingProvider,
"WindowManager_ExceptionInNestedWaitThread",
TraceLoggingUInt64(peasantID, "peasantID", "Our peasant ID"),
TraceLoggingLevel(WINEVENT_LEVEL_VERBOSE),
TraceLoggingKeyword(TIL_KEYWORD_TRACE));
}
}
}
}
}
Remoting::Peasant WindowManager::CurrentWindow()
{
return _peasant;
}
void WindowManager::_raiseFindTargetWindowRequested(const winrt::Windows::Foundation::IInspectable& sender,
const winrt::Microsoft::Terminal::Remoting::FindTargetWindowArgs& args)
{
_FindTargetWindowRequestedHandlers(sender, args);
}
bool WindowManager::IsMonarch()
{
return _isKing;
}
void WindowManager::SummonWindow(const Remoting::SummonWindowSelectionArgs& args)
{
// We should only ever get called when we are the monarch, because only
// the monarch ever registers for the global hotkey. So the monarch is
// the only window that will be calling this.
_monarch.SummonWindow(args);
}
void WindowManager::SummonAllWindows()
{
_monarch.SummonAllWindows();
}
Windows::Foundation::Collections::IVectorView<winrt::Microsoft::Terminal::Remoting::PeasantInfo> WindowManager::GetPeasantInfos()
{
// We should only get called when we're the monarch since the monarch
// is the only one that knows about all peasants.
return _monarch.GetPeasantInfos();
}
uint64_t WindowManager::GetNumberOfPeasants()
{
if (_monarch)
{
try
{
return _monarch.GetNumberOfPeasants();
}
CATCH_LOG()
}
return 0;
}
// Method Description:
// - Ask the monarch to show a notification icon.
// Arguments:
// - <none>
// Return Value:
// - <none>
winrt::fire_and_forget WindowManager::RequestShowNotificationIcon()
{
co_await winrt::resume_background();
_peasant.RequestShowNotificationIcon();
}
// Method Description:
// - Ask the monarch to hide its notification icon.
// Arguments:
// - <none>
// Return Value:
// - <none>
winrt::fire_and_forget WindowManager::RequestHideNotificationIcon()
{
auto strongThis{ get_strong() };
co_await winrt::resume_background();
_peasant.RequestHideNotificationIcon();
}
// Method Description:
// - Ask the monarch to quit all windows.
// Arguments:
// - <none>
// Return Value:
// - <none>
winrt::fire_and_forget WindowManager::RequestQuitAll()
{
auto strongThis{ get_strong() };
co_await winrt::resume_background();
_peasant.RequestQuitAll();
}
bool WindowManager::DoesQuakeWindowExist()
{
return _monarch.DoesQuakeWindowExist();
}
void WindowManager::UpdateActiveTabTitle(winrt::hstring title)
{
winrt::get_self<implementation::Peasant>(_peasant)->ActiveTabTitle(title);
}
Windows::Foundation::Collections::IVector<winrt::hstring> WindowManager::GetAllWindowLayouts()
{
if (_monarch)
{
try
{
return _monarch.GetAllWindowLayouts();
}
CATCH_LOG()
}
return nullptr;
}
}
| 18,113 |
841 |
/*
* Copyright (C) 2016 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#define LEAP_YEAR(x) ( ((x)%4) == 0 && ( ((x)%100) != 0 || ((x)%400) == 0 ) )
void XX_httplib_addenv( struct lh_ctx_t *ctx, struct cgi_environment *env, PRINTF_FORMAT_STRING(const char *fmt), ... ) PRINTF_ARGS(3, 4);
double XX_httplib_difftimespec( const struct timespec *ts_now, const struct timespec *ts_before );
void XX_httplib_gmt_time_string( char *buf, size_t buf_len, time_t *t );
int XX_httplib_inet_pton( int af, const char *src, void *dst, size_t dstlen );
int XX_httplib_lowercase( const char *s );
extern const int XX_httplib_days_per_month[];
| 539 |
1,408 |
/*
* Copyright (c) 2019-2020, ARM Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <assert.h>
#include <arch_helpers.h>
#include <drivers/delay_timer.h>
#include <lib/bakery_lock.h>
#include <brcm_mhu.h>
#include <platform_def.h>
#include "m0_ipc.h"
#define PLAT_MHU_INTR_REG AP_TO_SCP_MAILBOX1
/* SCP MHU secure channel registers */
#define SCP_INTR_S_STAT CRMU_IHOST_SW_PERSISTENT_REG11
#define SCP_INTR_S_SET CRMU_IHOST_SW_PERSISTENT_REG11
#define SCP_INTR_S_CLEAR CRMU_IHOST_SW_PERSISTENT_REG11
/* CPU MHU secure channel registers */
#define CPU_INTR_S_STAT CRMU_IHOST_SW_PERSISTENT_REG10
#define CPU_INTR_S_SET CRMU_IHOST_SW_PERSISTENT_REG10
#define CPU_INTR_S_CLEAR CRMU_IHOST_SW_PERSISTENT_REG10
static DEFINE_BAKERY_LOCK(bcm_lock);
/*
* Slot 31 is reserved because the MHU hardware uses this register bit to
* indicate a non-secure access attempt. The total number of available slots is
* therefore 31 [30:0].
*/
#define MHU_MAX_SLOT_ID 30
void mhu_secure_message_start(unsigned int slot_id)
{
int iter = 1000000;
assert(slot_id <= MHU_MAX_SLOT_ID);
bakery_lock_get(&bcm_lock);
/* Make sure any previous command has finished */
do {
if (!(mmio_read_32(PLAT_BRCM_MHU_BASE + CPU_INTR_S_STAT) &
(1 << slot_id)))
break;
udelay(1);
} while (--iter);
assert(iter != 0);
}
void mhu_secure_message_send(unsigned int slot_id)
{
uint32_t response, iter = 1000000;
assert(slot_id <= MHU_MAX_SLOT_ID);
assert(!(mmio_read_32(PLAT_BRCM_MHU_BASE + CPU_INTR_S_STAT) &
(1 << slot_id)));
/* Send command to SCP */
mmio_setbits_32(PLAT_BRCM_MHU_BASE + CPU_INTR_S_SET, 1 << slot_id);
mmio_write_32(CRMU_MAIL_BOX0, MCU_IPC_MCU_CMD_SCPI);
mmio_write_32(PLAT_BRCM_MHU_BASE + PLAT_MHU_INTR_REG, 0x1);
/* Wait until IPC transport acknowledges reception of SCP command */
do {
response = mmio_read_32(CRMU_MAIL_BOX0);
if ((response & ~MCU_IPC_CMD_REPLY_MASK) ==
(MCU_IPC_CMD_DONE_MASK | MCU_IPC_MCU_CMD_SCPI))
break;
udelay(1);
} while (--iter);
assert(iter != 0);
}
uint32_t mhu_secure_message_wait(void)
{
/* Wait for response from SCP */
uint32_t response, iter = 1000000;
do {
response = mmio_read_32(PLAT_BRCM_MHU_BASE + SCP_INTR_S_STAT);
if (!response)
break;
udelay(1);
} while (--iter);
assert(iter != 0);
return response;
}
void mhu_secure_message_end(unsigned int slot_id)
{
assert(slot_id <= MHU_MAX_SLOT_ID);
/*
* Clear any response we got by writing one in the relevant slot bit to
* the CLEAR register
*/
mmio_clrbits_32(PLAT_BRCM_MHU_BASE + SCP_INTR_S_CLEAR, 1 << slot_id);
bakery_lock_release(&bcm_lock);
}
void mhu_secure_init(void)
{
bakery_lock_init(&bcm_lock);
/*
* The STAT register resets to zero. Ensure it is in the expected state,
* as a stale or garbage value would make us think it's a message we've
* already sent.
*/
mmio_write_32(PLAT_BRCM_MHU_BASE + CPU_INTR_S_STAT, 0);
mmio_write_32(PLAT_BRCM_MHU_BASE + SCP_INTR_S_STAT, 0);
}
void plat_brcm_pwrc_setup(void)
{
mhu_secure_init();
}
| 1,353 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.