identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/zingson/eleme-openapi-java-sdk/blob/master/src/main/java/eleme/openapi/sdk/api/enumeration/product/OItemWeekEnum.java
Github Open Source
Open Source
MIT
2,018
eleme-openapi-java-sdk
zingson
Java
Code
52
218
package eleme.openapi.sdk.api.enumeration.product; public enum OItemWeekEnum { /** * 周一 */ MONDAY("MONDAY"), /** * 周二 */ TUESDAY("TUESDAY"), /** * 周三 */ WEDNESDAY("WEDNESDAY"), /** * 周四 */ THURSDAY("THURSDAY"), /** * 周五 */ FRIDAY("FRIDAY"), /** * 周六 */ SATURDAY("SATURDAY"), /** * 周日 */ SUNDAY("SUNDAY"); private String productDesc; OItemWeekEnum(String productDesc) { this.productDesc = productDesc; } }
36,373
https://github.com/hongjic/sgw/blob/master/sgw-core/src/main/java/sgw/core/service_channel/thrift/ThriftEncoder.java
Github Open Source
Open Source
MIT
2,018
sgw
hongjic
Java
Code
230
856
package sgw.core.service_channel.thrift; import io.netty.buffer.*; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import org.apache.thrift.TBase; import org.apache.thrift.TException; import org.apache.thrift.protocol.*; import org.apache.thrift.transport.TFramedTransport; import org.apache.thrift.transport.TTransport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sgw.core.service_channel.thrift.transport.ByteBufWriteTransport; public class ThriftEncoder extends MessageToByteEncoder<ThriftOrderedRequest> { private final Logger logger = LoggerFactory.getLogger(ThriftEncoder.class); private static final int INITIAL_BUFFER_SIZE = 128; private static final int MAX_BUFFER_SIZE = 1024*1024*1024; private final byte[] i32buf = new byte[4]; private ThriftChannelContext thriftChanCtx; public ThriftEncoder(ThriftChannelContext thriftChanCtx) { this.thriftChanCtx = thriftChanCtx; } @Override public void encode(ChannelHandlerContext ctx, ThriftOrderedRequest request, ByteBuf out) throws TException { long tChReqId = request.channelMessageId(); ThriftRequestContext treqCtx = thriftChanCtx.getRequestContext(tChReqId); logger.debug("Request {}: Message sent to thrift channel, start encoding thrift call...", treqCtx.getHttpGlRequestId()); writeFrameBuffer(out, request); writeSizeBuffer(out); } private void writeSizeBuffer(ByteBuf buf) { int frameSize = buf.readableBytes() - 4; TFramedTransport.encodeFrameSize(frameSize, i32buf); // this op doesn't change write/read index. buf.setBytes(0, i32buf); } private void writeFrameBuffer(ByteBuf buf, ThriftOrderedRequest request) throws TException { TBase args = request.getArgs(); TMessage message = new TMessage(request.getMethodName(), TMessageType.CALL, (int) request.channelMessageId()); String serviceName = request.getServiceName(); // Leave space to write frame size. Use the same buffer to avoid data copy. buf.setIndex(0, 4); // write frame buffer TTransport transport = new ByteBufWriteTransport(buf); TProtocol basicProtocol = new TCompactProtocol.Factory().getProtocol(transport); TProtocol protocol = new TMultiplexedProtocol(basicProtocol, serviceName); protocol.writeMessageBegin(message); args.write(protocol); protocol.writeMessageEnd(); } @Override protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, @SuppressWarnings("unused") ThriftOrderedRequest msg, boolean preferDirect) { if (preferDirect) { return ctx.alloc().ioBuffer(INITIAL_BUFFER_SIZE, MAX_BUFFER_SIZE); } else { return ctx.alloc().heapBuffer(INITIAL_BUFFER_SIZE, MAX_BUFFER_SIZE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
5,859
https://github.com/chaeyeunpark/Yavque/blob/master/include/yavque/Utilities/pauli_operators.hpp
Github Open Source
Open Source
Apache-2.0
null
Yavque
chaeyeunpark
C++
Code
27
142
#pragma once #include <Eigen/Dense> #include <Eigen/Sparse> #include "typedefs.hpp" namespace yavque { Eigen::SparseMatrix<double> pauli_x(); Eigen::SparseMatrix<cx_double> pauli_y(); Eigen::SparseMatrix<double> pauli_z(); Eigen::SparseMatrix<double> pauli_xx(); Eigen::SparseMatrix<double> pauli_yy(); Eigen::SparseMatrix<double> pauli_zz(); } // namespace yavque
15,661
https://github.com/mP1/j2cl-locale/blob/master/src/test/java/walkingkooka/j2cl/locale/TimeZoneCalendarTest.java
Github Open Source
Open Source
Apache-2.0
null
j2cl-locale
mP1
Java
Code
290
914
/* * Copyright 2019 Miroslav Pokorny (github.com/mP1) * * 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 walkingkooka.j2cl.locale; import org.junit.jupiter.api.Test; import walkingkooka.HashCodeEqualsDefinedTesting2; import walkingkooka.ToStringTesting; import walkingkooka.compare.ComparableTesting2; import walkingkooka.j2cl.java.io.string.StringDataInputDataOutput; import walkingkooka.reflect.ClassTesting2; import walkingkooka.reflect.JavaVisibility; import java.io.DataInput; import java.io.DataOutput; import java.io.EOFException; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; public final class TimeZoneCalendarTest implements ClassTesting2<TimeZoneCalendar>, HashCodeEqualsDefinedTesting2<TimeZoneCalendar>, ComparableTesting2<TimeZoneCalendar>, ToStringTesting<TimeZoneCalendar> { private final static int FIRST = 1; private final static int MINIMAL = 5; @Test public void testWriteAndReadRoundtrip() throws IOException { final StringBuilder data = new StringBuilder(); final DataOutput dataOutput = StringDataInputDataOutput.output(data::append); final TimeZoneCalendar calendar = TimeZoneCalendar.with(1 , 2); calendar.write(dataOutput); final DataInput dataInput = StringDataInputDataOutput.input(data.toString()); assertEquals(TimeZoneCalendar.read(dataInput), calendar); assertThrows(EOFException.class, () -> dataInput.readBoolean()); } @Test public void testCompareLess() { this.compareToAndCheckLess(TimeZoneCalendar.with(FIRST + 1, MINIMAL)); } @Test public void testCompareLess2() { this.compareToAndCheckLess(TimeZoneCalendar.with(FIRST, MINIMAL + 1)); } @Test public void testCompareSorted() { final TimeZoneCalendar a = TimeZoneCalendar.with(FIRST, MINIMAL); final TimeZoneCalendar b = TimeZoneCalendar.with(FIRST, MINIMAL + 1); final TimeZoneCalendar c = TimeZoneCalendar.with(FIRST, MINIMAL + 5); final TimeZoneCalendar d = TimeZoneCalendar.with(FIRST + 1, MINIMAL); this.compareToArraySortAndCheck(d, c, a, b, a, b, c, d); } @Test public void testToString() { this.toStringAndCheck(this.createComparable().toString(), "firstDayOfWeek=1 minimalDaysInFirstWeek=5"); } @Override public TimeZoneCalendar createComparable() { return TimeZoneCalendar.with(FIRST, MINIMAL); } @Override public Class<TimeZoneCalendar> type() { return TimeZoneCalendar.class; } @Override public JavaVisibility typeVisibility() { return JavaVisibility.PUBLIC; } }
18,717
https://github.com/zhangkn/iOS14Header/blob/master/usr/sbin/WirelessRadioManagerd/WRM_TerminusContext.h
Github Open Source
Open Source
MIT
2,020
iOS14Header
zhangkn
C
Code
379
1,520
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 Steve Nygard. // #import "WRM_Mobility_Context.h" @interface WRM_TerminusContext : WRM_Mobility_Context { _Bool _mTerminusIsRegistered; // 136 = 0x88 _Bool _mForceUpdateNeeded; // 137 = 0x89 _Bool _mClientSubscriptionValid; // 138 = 0x8a _Bool _mIsRetry; // 139 = 0x8b _Bool _mBtLinkRecommendationUpdateNeeded; // 140 = 0x8c _Bool _mCompanionWifiLinkRecommendationUpdateNeeded; // 141 = 0x8d _Bool _mDirectWifiLinkRecommendationUpdateNeeded; // 142 = 0x8e _Bool _mBtLinkIsRecommended; // 143 = 0x8f _Bool _mCompanionWifiLinkIsRecommended; // 144 = 0x90 _Bool _mDirectWifiLinkIsRecommended; // 145 = 0x91 _Bool _isGizmoNearbyOverBt; // 146 = 0x92 BOOL _nwType; // 147 = 0x93 int _mAppLinkPreference; // 148 = 0x94 int _mCurrentActiveLink; // 152 = 0x98 int _beaconPER; // 156 = 0x9c unsigned long long _btMovingAvgRSSI; // 160 = 0xa0 long long _wifiRSSI; // 168 = 0xa8 long long _wifiSNR; // 176 = 0xb0 long long _wifiCCA; // 184 = 0xb8 long long _lsmRecommendationBe; // 192 = 0xc0 long long _expectedThroughputVIBE; // 200 = 0xc8 long long _packetLifetimeVIBE; // 208 = 0xd0 long long _packetLossRateVIBE; // 216 = 0xd8 long long _btRetransmissionRateTx; // 224 = 0xe0 long long _btRetransmissionRateRx; // 232 = 0xe8 long long _btTech; // 240 = 0xf0 } @property(nonatomic) long long btTech; // @synthesize btTech=_btTech; @property(nonatomic) long long btRetransmissionRateRx; // @synthesize btRetransmissionRateRx=_btRetransmissionRateRx; @property(nonatomic) long long btRetransmissionRateTx; // @synthesize btRetransmissionRateTx=_btRetransmissionRateTx; @property(nonatomic) long long packetLossRateVIBE; // @synthesize packetLossRateVIBE=_packetLossRateVIBE; @property(nonatomic) long long packetLifetimeVIBE; // @synthesize packetLifetimeVIBE=_packetLifetimeVIBE; @property(nonatomic) long long expectedThroughputVIBE; // @synthesize expectedThroughputVIBE=_expectedThroughputVIBE; @property(nonatomic) long long lsmRecommendationBe; // @synthesize lsmRecommendationBe=_lsmRecommendationBe; @property(nonatomic) long long wifiCCA; // @synthesize wifiCCA=_wifiCCA; @property(nonatomic) BOOL nwType; // @synthesize nwType=_nwType; @property(nonatomic) int beaconPER; // @synthesize beaconPER=_beaconPER; @property(nonatomic) long long wifiSNR; // @synthesize wifiSNR=_wifiSNR; @property(nonatomic) long long wifiRSSI; // @synthesize wifiRSSI=_wifiRSSI; @property(nonatomic) unsigned long long btMovingAvgRSSI; // @synthesize btMovingAvgRSSI=_btMovingAvgRSSI; @property(nonatomic) _Bool isGizmoNearbyOverBt; // @synthesize isGizmoNearbyOverBt=_isGizmoNearbyOverBt; @property(nonatomic) _Bool mDirectWifiLinkIsRecommended; // @synthesize mDirectWifiLinkIsRecommended=_mDirectWifiLinkIsRecommended; @property(nonatomic) _Bool mCompanionWifiLinkIsRecommended; // @synthesize mCompanionWifiLinkIsRecommended=_mCompanionWifiLinkIsRecommended; @property(nonatomic) _Bool mBtLinkIsRecommended; // @synthesize mBtLinkIsRecommended=_mBtLinkIsRecommended; @property(nonatomic) _Bool mDirectWifiLinkRecommendationUpdateNeeded; // @synthesize mDirectWifiLinkRecommendationUpdateNeeded=_mDirectWifiLinkRecommendationUpdateNeeded; @property(nonatomic) _Bool mCompanionWifiLinkRecommendationUpdateNeeded; // @synthesize mCompanionWifiLinkRecommendationUpdateNeeded=_mCompanionWifiLinkRecommendationUpdateNeeded; @property(nonatomic) _Bool mBtLinkRecommendationUpdateNeeded; // @synthesize mBtLinkRecommendationUpdateNeeded=_mBtLinkRecommendationUpdateNeeded; @property(nonatomic) _Bool mIsRetry; // @synthesize mIsRetry=_mIsRetry; @property(nonatomic) _Bool mClientSubscriptionValid; // @synthesize mClientSubscriptionValid=_mClientSubscriptionValid; @property(nonatomic) _Bool mForceUpdateNeeded; // @synthesize mForceUpdateNeeded=_mForceUpdateNeeded; @property(nonatomic) _Bool mTerminusIsRegistered; // @synthesize mTerminusIsRegistered=_mTerminusIsRegistered; @property(nonatomic) int mCurrentActiveLink; // @synthesize mCurrentActiveLink=_mCurrentActiveLink; @property(nonatomic) int mAppLinkPreference; // @synthesize mAppLinkPreference=_mAppLinkPreference; - (void)dealloc; // IMP=0x00000001000685cc - (id)init; // IMP=0x00000001000682c8 @end
25,449
https://github.com/iAmMichelleDzvokora/GADS-practice-project/blob/master/src/app/app.routing.ts
Github Open Source
Open Source
MIT
null
GADS-practice-project
iAmMichelleDzvokora
TypeScript
Code
109
311
import { Routes, RouterModule } from '@angular/router'; import { ModuleWithProviders } from '@angular/core'; import { ResolveLocationService } from './shared/services/resolve-location.service'; import { CityCardResolver } from './city-card/city-card-resolver.service'; import { WeatherComponent } from './weather/weather.component'; import { ErrorComponent } from './error/error.component'; import { NotFoundComponent } from './not-found/not-found.component'; const APP_ROUTER: Routes = [ { path: '', component: WeatherComponent, resolve: { weather: ResolveLocationService }, }, { path: ':city', component: WeatherComponent, resolve: { weather: CityCardResolver }, }, { path: 'service/search', component: NotFoundComponent }, { path: '**', component: ErrorComponent, data: { title: '404 Not Found', message: 'You may be lost. Follow the breadcrumbs back <a href="/">home</a>.', }, }, ]; export const appRouting: ModuleWithProviders<RouterModule> = RouterModule.forRoot( APP_ROUTER );
35,670
https://github.com/ksenia-konyushkova/LAL/blob/master/Classes/dataset.py
Github Open Source
Open Source
Apache-2.0
2,022
LAL
ksenia-konyushkova
Python
Code
597
2,194
import numpy as np import scipy import scipy.io as sio from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import Imputer class Dataset: def __init__(self): # each dataset will have training and test data with labels self.trainData = np.array([[]]) self.trainLabels = np.array([[]]) self.testData = np.array([[]]) self.testLabels = np.array([[]]) def setStartState(self, nStart): ''' This functions initialises fields indicesKnown and indicesUnknown which contain the indices of labelled and unlabeled datapoints Input: nStart -- number of labelled datapoints (size of indicesKnown) ''' self.nStart = nStart # first get 1 positive and 1 negative point so that both classes are represented and initial classifer could be trained. cl1 = np.nonzero(self.trainLabels==1)[0] indices1 = np.random.permutation(cl1) self.indicesKnown = np.array([indices1[0]]); cl2 = np.nonzero(self.trainLabels==0)[0] indices2 = np.random.permutation(cl2) self.indicesKnown = np.concatenate(([self.indicesKnown, np.array([indices2[0]])])); # combine all the rest of the indices that have not been sampled yet indicesRestAll = np.concatenate(([indices1[1:], indices2[1:]])); # permute them indicesRestAll = np.random.permutation(indicesRestAll) # if we need more than 2 datapoints, select the rest nStart-2 at random if nStart>2: self.indicesKnown = np.concatenate(([self.indicesKnown, indicesRestAll[0:nStart-2]])); # the rest of the points will be unlabeled at the beginning self.indicesUnknown = indicesRestAll[nStart-2:] class DatasetCheckerboard2x2(Dataset): '''Loads XOR-like dataset of checkerboard shape of size 2x2. Origine of the dataset: generated by us. ''' def __init__(self): Dataset.__init__(self) filename = './data/checkerboard2x2_train.npz' dt = np.load(filename) self.trainData = dt['x'] self.trainLabels = dt['y'] scaler = preprocessing.StandardScaler().fit(self.trainData) self.trainData = scaler.transform(self.trainData) filename = './data/checkerboard2x2_test.npz' dt = np.load(filename) self.testData = dt['x'] self.testLabels = dt['y'] self.testData = scaler.transform(self.testData) class DatasetCheckerboard4x4(Dataset): '''Loads XOR-like dataset of checkerboard shape of size 4x4. Origine of the dataset: generated by us. ''' def __init__(self): Dataset.__init__(self) filename = './data/checkerboard4x4_train.npz' dt = np.load(filename) self.trainData = dt['x'] self.trainLabels = dt['y'] scaler = preprocessing.StandardScaler().fit(self.trainData) self.trainData = scaler.transform(self.trainData) filename = './data/checkerboard4x4_test.npz' dt = np.load(filename) self.testData = dt['x'] self.testLabels = dt['y'] self.testData = scaler.transform(self.testData) class DatasetRotatedCheckerboard2x2(Dataset): '''Loads XOR-like dataset of checkerboard shape of size 2x2 that is rotated by 45'. Origine of the dataset: generated by us. ''' def __init__(self): Dataset.__init__(self) filename = './data/rotated_checkerboard2x2_train.npz' dt = np.load(filename) self.trainData = dt['x'] self.trainLabels = dt['y'] scaler = preprocessing.StandardScaler().fit(self.trainData) self.trainData = scaler.transform(self.trainData) filename = './data/rotated_checkerboard2x2_test.npz' dt = np.load(filename) self.testData = dt['x'] self.testLabels = dt['y'] self.testData = scaler.transform(self.testData) class DatasetSimulatedUnbalanced(Dataset): '''Simple dataset with 2 Gaussian clouds is generated by this class. ''' def __init__(self, sizeTrain, n_dim): Dataset.__init__(self) cl1_prop = np.random.rand() # we want the proportion of class 1 to vary from 10% to 90% cl1_prop = (cl1_prop-0.5)*0.8+0.5 trainSize1 = int(sizeTrain*cl1_prop) trainSize2 = sizeTrain-trainSize1 # the test dataset will be 10 times bigger than the train dataset. testSize1 = trainSize1*10 testSize2 = trainSize2*10 # generate parameters (mean and covariance) of each cloud mean1 = scipy.random.rand(n_dim) cov1 = scipy.random.rand(n_dim,n_dim)-0.5 cov1 = np.dot(cov1,cov1.transpose()) mean2 = scipy.random.rand(n_dim) cov2 = scipy.random.rand(n_dim,n_dim)-0.5 cov2 = np.dot(cov2,cov2.transpose()) # generate train data trainX1 = np.random.multivariate_normal(mean1, cov1, trainSize1) trainY1 = np.ones((trainSize1,1)) trainX2 = np.random.multivariate_normal(mean2, cov2, trainSize2) trainY2 = np.zeros((trainSize2,1)) # the test data testX1 = np.random.multivariate_normal(mean1, cov1, testSize1) testY1 = np.ones((testSize1,1)) testX2 = np.random.multivariate_normal(mean2, cov2, testSize2) testY2 = np.zeros((testSize2,1)) # put the data from both clouds togetehr self.trainData = np.concatenate((trainX1, trainX2), axis=0) self.trainLabels = np.concatenate((trainY1, trainY2)) self.testData = np.concatenate((testX1, testX2), axis=0) self.testLabels = np.concatenate((testY1, testY2)) class DatasetStriatumMini(Dataset): '''Dataset from CVLab. https://cvlab.epfl.ch/data/em Features as in A. Lucchi, Y. Li, K. Smith, and P. Fua. Structured Image Segmentation Using Kernelized Features. ECCV, 2012''' def __init__(self): Dataset.__init__(self) filename = './data/striatum_train_features_mini.mat' dt = sio.loadmat(filename) self.trainData = dt['features'] filename = './data/striatum_train_labels_mini.mat' dt = sio.loadmat(filename) self.trainLabels = dt['labels'] self.trainLabels[self.trainLabels==-1] = 0 scaler = preprocessing.StandardScaler().fit(self.trainData) self.trainData = scaler.transform(self.trainData) filename = './data/striatum_test_features_mini.mat' dt = sio.loadmat(filename) self.testData = dt['features'] filename = './data/striatum_test_labels_mini.mat' dt = sio.loadmat(filename) self.testLabels = dt['labels'] self.testLabels[self.testLabels==-1] = 0 self.testData = scaler.transform(self.testData)
17,195
https://github.com/chenjianping99/onlineAffairs/blob/master/samples/src/com/guangzhou/gov/net/view/DialogManager.java
Github Open Source
Open Source
Apache-2.0
null
onlineAffairs
chenjianping99
Java
Code
44
158
package com.guangzhou.gov.net.view; import android.app.Dialog; import android.content.Context; /** * 方便添加dialog 不喜欢可以干掉 * * @ClassName: DialogManager * @author chenjianping * @date 2014-11-9 * */ public class DialogManager { public static Dialog getProgressMsgDialog(Context context, String msg) { Dialog dialog = new PrjProgressMsgDialog.Builder(context).setTextContent(msg).create(); dialog.setCanceledOnTouchOutside(false); return dialog; } }
28,745
https://github.com/yashdhume/Photoshop-Ultra-Light-2/blob/master/src/main/java/VIPLogin/Encrpt.java
Github Open Source
Open Source
MIT
2,022
Photoshop-Ultra-Light-2
yashdhume
Java
Code
57
141
package VIPLogin; //XOR encryption to so no password is stored passed through sockets public class Encrpt { private char[] key = "a_5$]-xU44qmLut;".toCharArray(); public Encrpt(){} public String encrypt(byte[] bufferIn, int total) { StringBuilder cipher = new StringBuilder(); for (int i = 0; i < total; i++) { cipher.append((char) (bufferIn[i] ^ key[i % key.length])); } return cipher.toString(); } }
12,468
https://github.com/cryptowilliam/goutil/blob/master/net/gmtu/check_linux.go
Github Open Source
Open Source
MIT
2,021
goutil
cryptowilliam
Go
Code
117
361
package gmtu import ( "net" "os/exec" "regexp" "strconv" "strings" ) func check(ip net.IP, size int) (bool, int, error) { for i := 0; i < 7; i++ { outByte, _ := exec.Command("ping", "-c", strconv.Itoa(NumberOfMessages), "-s", strconv.Itoa(size), "-M", "do", ip.String()).Output() outString := string(outByte) if strings.Contains(outString, "Message too long") { regex := regexp.MustCompile(`mtu=\d+`) inv := regex.FindString(outString) mtuString := strings.TrimPrefix(inv, "mtu=") if mtuString != "" { mtu, err := strconv.Atoi(mtuString) if err == nil { return false, mtu, nil } } return false, 0, nil } if strings.Contains(outString, " 0% packet loss") { return true, 0, nil } if strings.Contains(outString, " 100% packet loss") { return false, 0, nil } } return false, 0, gerrors.New("something went wrong with pinging") }
27,371
https://github.com/Suntx1994/cs203-assignment-3/blob/master/build/ALPHA/params/Tsunami.hh
Github Open Source
Open Source
BSD-3-Clause
null
cs203-assignment-3
Suntx1994
C++
Code
28
104
#ifndef __PARAMS__Tsunami__ #define __PARAMS__Tsunami__ class Tsunami; #include <cstddef> #include "params/System.hh" #include "params/Platform.hh" struct TsunamiParams : public PlatformParams { Tsunami * create(); System * system; }; #endif // __PARAMS__Tsunami__
40,517
https://github.com/mrnettek/VBScript/blob/master/VBScript2/List Virtual Server Security Information.vbs
Github Open Source
Open Source
MIT
2,020
VBScript
mrnettek
VBScript
Code
44
117
' Description: Lists security information for Virtual Server. On Error Resume Next Set objVS = CreateObject("VirtualServer.Application") Set objSecurity = objVS.Security Wscript.Echo "Group name: " & objSecurity.GroupName Wscript.Echo "Group SID: " & objSecurity.GroupSID Wscript.Echo "Owner name: " & objSecurity.OwnerName Wscript.Echo "Owner name: " & objSecurity.OwnerSID
10,927
https://github.com/LucasLazogue/ContadorUNO/blob/master/app/src/main/java/com/contadoruno/UnoScoreHelper/Estacion/Adapters/AdaptadorJugadoresAgregados.java
Github Open Source
Open Source
MIT
2,023
ContadorUNO
LucasLazogue
Java
Code
206
842
package com.contadoruno.UnoScoreHelper.Estacion.Adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.contadoruno.UnoScoreHelper.Logica.Interfaces.IJugadorController; import com.contadoruno.UnoScoreHelper.Logica.Singleton.Factory; import com.contadoruno.UnoScoreHelper.R; import java.util.Arrays; import java.util.List; public class AdaptadorJugadoresAgregados extends RecyclerView.Adapter<AdaptadorJugadoresAgregados.ViewHolder> { private int layout; private List<String> jugadores; private OnItemClickListener listener; public AdaptadorJugadoresAgregados(int layout, List<String> jugadores, OnItemClickListener listener) { this.jugadores = jugadores; this.layout = layout; this.listener = listener; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(this.layout, parent, false); AdaptadorJugadoresAgregados.ViewHolder vh = new ViewHolder(v); return vh; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { holder.bind(jugadores.get(position)); ImageView remove = holder.itemView.findViewById(R.id.removerAgregado); /*remove.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { jugadores.remove(position); notifyDataSetChanged(); } });*/ } @Override public int getItemCount() { return this.jugadores.size(); } public class ViewHolder extends RecyclerView.ViewHolder { private TextView nombre; private ImageView removerAgregado; public ViewHolder(@NonNull View itemView) { super(itemView); this.nombre = itemView.findViewById(R.id.nombreAdd); this.removerAgregado = itemView.findViewById(R.id.removerAgregado); } public void bind(final String nombre) { this.nombre.setText(nombre); removerAgregado.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listener.OnItemClickListener(nombre); } }); } } public interface OnItemClickListener { void OnItemClickListener(String nombre); } public void updateAdapter() { Factory f = Factory.getInstance(); IJugadorController jc = f.getIJugadorController(); String[] j = jc.getJugadores(); List<String> jgs = Arrays.asList(j); this.jugadores = jgs; notifyDataSetChanged(); } public List<String> getJugadores() { return jugadores; } }
31,894
https://github.com/rabby420/git-github/blob/master/app/src/main/java/com/codegama/Taskscheduler/activity/TaskAdapter.java
Github Open Source
Open Source
MIT
null
git-github
rabby420
Java
Code
523
2,617
package com.codegama.Taskscheduler.activity; import static android.content.Context.MODE_PRIVATE; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.codegama.Taskscheduler.R; import com.codegama.Taskscheduler.bottomSheetFragment.CreateTaskBottomSheetFragment; import com.codegama.Taskscheduler.database.DatabaseClient; import com.codegama.Taskscheduler.model.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import org.jetbrains.annotations.NotNull; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import butterknife.BindView; import butterknife.ButterKnife; public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskViewHolder> { //SharedPreferences sharedPreferences= getA.getPreferences("our_data",MODE_PRIVATE); private MainActivity context; //private history context5; private LayoutInflater inflater; private List<Task> taskList; public SimpleDateFormat dateFormat = new SimpleDateFormat("EE dd MMM yyyy", Locale.US); public SimpleDateFormat inputDateFormat = new SimpleDateFormat("dd-M-yyyy", Locale.US); Date date = null; String outputDateString = null; CreateTaskBottomSheetFragment.setRefreshListener setRefreshListener; FirebaseDatabase root; DatabaseReference Ttask; FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); public TaskAdapter(MainActivity context, List<Task> taskList, CreateTaskBottomSheetFragment.setRefreshListener setRefreshListener) { this.context = context; this.taskList = taskList; this.setRefreshListener = setRefreshListener; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @NonNull @Override public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) { View view = inflater.inflate(R.layout.item_task, viewGroup, false); return new TaskViewHolder(view); } @Override public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) { Task task = taskList.get(position); holder.title.setText(task.getTaskTitle()); holder.description.setText(task.getTaskDescrption()); holder.time.setText(task.getLastAlarm()); holder.status.setText(task.isComplete() ? "COMPLETED" : "UPCOMING"); holder.options.setOnClickListener(view -> showPopUpMenu(view, position)); try { date = inputDateFormat.parse(task.getDate()); outputDateString = dateFormat.format(date); String[] items1 = outputDateString.split(" "); String day = items1[0]; String dd = items1[1]; String month = items1[2]; holder.day.setText(day); holder.date.setText(dd); holder.month.setText(month); } catch (Exception e) { e.printStackTrace(); } } public void showPopUpMenu(View view, int position) { final Task task = taskList.get(position); PopupMenu popupMenu = new PopupMenu(context, view); popupMenu.getMenuInflater().inflate(R.menu.menu, popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(item -> { switch (item.getItemId()) { case R.id.menuDelete: SharedPreferences share=context.getSharedPreferences("quit",MODE_PRIVATE); SharedPreferences.Editor edit=share.edit(); SimpleDateFormat todays_date=new SimpleDateFormat("dd/MM/yyyy"); Date today=new Date(); String ajker_tarikh=todays_date.format(today); String s1=ajker_tarikh.substring(0,2); Integer date_int=Integer.parseInt(s1); String date_string=Integer.toString(date_int); String ans=share.getString(date_string,"0"); int j=Integer.parseInt(ans); j=j+1; ans=Integer.toString(j); edit.putString(date_string,ans); edit.commit(); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context, R.style.AppTheme_Dialog); alertDialogBuilder.setTitle(R.string.delete_confirmation).setMessage(R.string.sureToDelete). setPositiveButton(R.string.yes, (dialog, which) -> { deleteTaskFromId(task.getTaskId(), position); }) .setNegativeButton(R.string.no, (dialog, which) -> dialog.cancel()).show(); break; case R.id.menuUpdate: CreateTaskBottomSheetFragment createTaskBottomSheetFragment = new CreateTaskBottomSheetFragment(); createTaskBottomSheetFragment.setTaskId(task.getTaskId(), true, context, context); createTaskBottomSheetFragment.show(context.getSupportFragmentManager(), createTaskBottomSheetFragment.getTag()); break; case R.id.menuComplete: //start here SharedPreferences sharedPreferences=context.getSharedPreferences("our_data", MODE_PRIVATE); SharedPreferences.Editor editor=sharedPreferences.edit(); SimpleDateFormat currentDate = new SimpleDateFormat("dd/MM/yyyy"); Date todayDate = new Date(); String thisDate = currentDate.format(todayDate); String s=thisDate.substring(0,2); Integer s2int=Integer.parseInt(s); String s2string=Integer.toString(s2int); String result=sharedPreferences.getString(s2string,"0"); int i=Integer.parseInt(result); i=i+1; result=Integer.toString(i); editor.putString(s2string,result); editor.commit(); // Toast.makeText(context.getApplicationContext(),result,Toast.LENGTH_LONG).show(); // Toast.makeText(context.getApplicationContext(),date_to_string,Toast.LENGTH_LONG).show(); // Toast.makeText(context.getApplicationContext(),result,Toast.LENGTH_SHORT).show(); //end here AlertDialog.Builder completeAlertDialog = new AlertDialog.Builder(context, R.style.AppTheme_Dialog); completeAlertDialog.setTitle(R.string.confirmation).setMessage(R.string.sureToMarkAsComplete). setPositiveButton(R.string.yes, (dialog, which) -> showCompleteDialog(task.getTaskId(), position)) .setNegativeButton(R.string.no, (dialog, which) -> dialog.cancel()).show(); break; } return false; }); popupMenu.show(); } public void showCompleteDialog(int taskId, int position) { Dialog dialog = new Dialog(context, R.style.AppTheme); dialog.setContentView(R.layout.dialog_completed_theme); Button close = dialog.findViewById(R.id.closeButton); close.setOnClickListener(view -> { deleteTaskFromId(taskId, position); dialog.dismiss(); }); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); dialog.show(); } private void deleteTaskFromId(int taskId, int position) { class GetSavedTasks extends AsyncTask<Void, Void, List<Task>> { @Override protected List<Task> doInBackground(Void... voids) { DatabaseClient.getInstance(context) .getAppDatabase() .dataBaseAction() .deleteTaskFromId(taskId); return taskList; } @Override protected void onPostExecute(List<Task> tasks) { super.onPostExecute(tasks); removeAtPosition(position); setRefreshListener.refresh(); } } GetSavedTasks savedTasks = new GetSavedTasks(); savedTasks.execute(); } private void removeAtPosition(int position) { taskList.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position, taskList.size()); } @Override public int getItemCount() { return taskList.size(); } public class TaskViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.day) TextView day; @BindView(R.id.date) TextView date; @BindView(R.id.month) TextView month; @BindView(R.id.title) TextView title; @BindView(R.id.description) TextView description; @BindView(R.id.status) TextView status; @BindView(R.id.options) ImageView options; @BindView(R.id.time) TextView time; TaskViewHolder(@NonNull View view) { super(view); ButterKnife.bind(this, view); } } }
30,055
https://github.com/Stanek-K/EvilWithin/blob/master/src/main/java/expansioncontent/actions/CorruptAction.java
Github Open Source
Open Source
MIT
2,022
EvilWithin
Stanek-K
Java
Code
214
977
package expansioncontent.actions; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.core.Settings; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.localization.UIStrings; import expansioncontent.expansionContentMod; import java.util.Iterator; public class CorruptAction extends AbstractGameAction { public static final String[] TEXT; private static final UIStrings uiStrings; public static int numExhausted; static { uiStrings = CardCrawlGame.languagePack.getUIString("ExhaustAction"); TEXT = uiStrings.TEXT; } public boolean upgraded; private AbstractPlayer p; private boolean isRandom; private boolean anyNumber; private boolean canPickZero; public CorruptAction(int amount, boolean isRandom, boolean anyNumber, boolean canPickZero, boolean upgraded) { this.anyNumber = anyNumber; this.p = AbstractDungeon.player; this.canPickZero = canPickZero; this.isRandom = isRandom; this.amount = amount; this.duration = this.startDuration = Settings.ACTION_DUR_FAST; this.actionType = ActionType.EXHAUST; this.upgraded = upgraded; } public void update() { if (this.duration == this.startDuration) { if (this.p.hand.size() == 0) { this.isDone = true; return; } if (!this.anyNumber && this.p.hand.size() <= this.amount) { this.amount = this.p.hand.size(); numExhausted = this.amount; int i = this.p.hand.size(); for (int q = 0; q < i; ++q) { AbstractCard c = this.p.hand.getTopCard(); this.p.hand.moveToExhaustPile(c); AbstractDungeon.actionManager.addToBottom(new RandomCardWithTagAction(upgraded, expansionContentMod.STUDY, false, true)); } CardCrawlGame.dungeon.checkForPactAchievement(); return; } if (!this.isRandom) { numExhausted = this.amount; AbstractDungeon.handCardSelectScreen.open(TEXT[0], this.amount, this.anyNumber, this.canPickZero); this.tickDuration(); return; } for (int i = 0; i < this.amount; ++i) { this.p.hand.moveToExhaustPile(this.p.hand.getRandomCard(AbstractDungeon.cardRandomRng)); } CardCrawlGame.dungeon.checkForPactAchievement(); } if (!AbstractDungeon.handCardSelectScreen.wereCardsRetrieved) { for (AbstractCard c : AbstractDungeon.handCardSelectScreen.selectedCards.group) { this.p.hand.moveToExhaustPile(c); AbstractDungeon.actionManager.addToBottom(new RandomCardWithTagAction(upgraded, expansionContentMod.STUDY, false, true)); } CardCrawlGame.dungeon.checkForPactAchievement(); AbstractDungeon.handCardSelectScreen.wereCardsRetrieved = true; } this.tickDuration(); } }
28,639
https://github.com/petersjl/280-WebDev/blob/master/FollowAlongs/Node/SimpleServers/public/scripts/main.js
Github Open Source
Open Source
MIT
2,022
280-WebDev
petersjl
JavaScript
Code
62
188
var counter = 0; function main(){ console.log("Ready"); document.querySelector("#decButton").onclick = (event) => { console.log("Decrement button pressed") counter = counter - 1; updateView(); }; document.querySelector("#incButton").onclick = (event) => { console.log("Increment button pressed") counter = counter + 1; updateView(); }; document.querySelector("#resButton").onclick = (event) => { console.log("Reset button pressed") counter = 0; updateView(); }; } function updateView(){ document.querySelector("#counterText").innerHTML = "Counter = " + counter; } main();
7,856
https://github.com/MediaNetwork/media-on-demand-webapp/blob/master/client/src/app/state/ducks/project/reducers.js
Github Open Source
Open Source
MIT
null
media-on-demand-webapp
MediaNetwork
JavaScript
Code
311
892
import arrayToMap from 'state/helpers/array-to-map' import createReducer from 'state/helpers/create-reducer' import * as types from './types' const collaboratorsToMap = (arr, indexKey) => arr.reduce( (dict, element) => ({ ...dict, [ element.account[ indexKey ] ]: element }), {} ) export default createReducer({})({ [ types.FETCH_COMPLETED ]: (state, action) => { return action.payload.projects.reduce( (projects, project) => ({ ...projects, [ project.identifier ]: { ...project, collaborators: arrayToMap(project.collaborators, 'identifier'), } }), {} ) }, [ types.CREATE_COMPLETED ]: (state, action) => ({ ...state, [ action.payload.project.identifier ]: { ...action.payload.project, } }), [ types.REMOVE_COMPLETED ]: (state, action) => { const { identifier } = action.payload const { [ identifier ]: removedProject, ...projects } = state return projects }, [ types.GET_COMPLETED ]: (state, action) => ({ ...state, [ action.payload.project.identifier ]: { ...action.payload.project, collaborators: collaboratorsToMap(action.payload.project.collaborators, 'identifier') } }), [types.UPDATE_COMPLETED ]: (state, action) => ({ ...state, [ action.payload.project.identifier ]: { ...action.payload.project, collaborators: collaboratorsToMap(action.payload.project.collaborators, 'identifier') } }), [ types.INVITE_COLLABORATOR_COMPLETED ]: (state, action) => { const { collaborators, identifier } = action.payload const project = state[ identifier ] const newCollaborators = arrayToMap(collaborators, 'identifier') return { ...state, [ identifier ]: { ...project, collaborators: { ...state[ identifier ].collaborators, ...newCollaborators } } } }, [ types.DELETE_COLLABORATOR_COMPLETED ]: (state, action) => { const { identifier } = action.payload const project = state[ identifier ] const { collaborators } = project const { accountId } = action.payload const { [ accountId ]: accountIdtoDelete, ...newCollaborators } = collaborators return { ...state, [ identifier ]: { ...project, collaborators: newCollaborators } } }, [ types.MAKE_OWNER_COMPLETED ]: (state, action) => { const { identifier } = action.payload const { currentAccountId } = action.payload const { accountId } = action.payload const project = state[ identifier ] return { ...state, [ identifier ]: { ...project, collaborators: { ...state[ identifier ].collaborators, [ currentAccountId ]: { ...state[ identifier ].collaborators[ currentAccountId ], privilege: 'ADMIN', }, [ accountId ]: { ...state[ identifier ].collaborators[ accountId ], privilege: 'OWNER' } } }, } } })
49,562
https://github.com/elliotleee/Apollo-lab/blob/master/src/ApolloRescue/module/universal/ApolloWorld.java
Github Open Source
Open Source
BSD-3-Clause
null
Apollo-lab
elliotleee
Java
Code
5,260
19,213
package ApolloRescue.module.universal; import java.awt.*; import java.awt.geom.Rectangle2D; import java.util.*; import java.util.List; import ApolloRescue.ApolloConstants; import ApolloRescue.module.algorithm.convexhull.BorderEntities; import ApolloRescue.module.complex.component.*; import ApolloRescue.module.complex.firebrigade.FireBrigadeWorld; import ApolloRescue.module.universal.entities.BuildingModel; import ApolloRescue.module.universal.entities.Entrance; import ApolloRescue.module.universal.entities.Paths; import ApolloRescue.module.universal.entities.RoadModel; import ApolloRescue.module.universal.newsearch.graph.GraphModule; import ApolloRescue.module.universal.tools.comparator.EntityIDComparator; import adf.agent.communication.MessageManager; import adf.agent.communication.standard.bundle.MessageUtil; import adf.agent.communication.standard.bundle.information.MessageBuilding; import adf.agent.develop.DevelopData; import adf.agent.info.AgentInfo; import adf.agent.info.ScenarioInfo; import adf.agent.info.WorldInfo; import adf.agent.module.ModuleManager; import adf.agent.precompute.PrecomputeData; import adf.component.communication.CommunicationMessage; import adf.component.module.AbstractModule; import firesimulator.world.Wall; import javolution.util.FastMap; import javolution.util.FastSet; import rescuecore2.messages.Command; import rescuecore2.misc.Handy; import rescuecore2.misc.Pair; import rescuecore2.standard.components.StandardAgent; import rescuecore2.standard.entities.*; import rescuecore2.standard.messages.AKSpeak; import rescuecore2.worldmodel.EntityID; import rescuecore2.worldmodel.Property; import static rescuecore2.standard.entities.StandardEntityURN.AMBULANCE_TEAM; import static rescuecore2.standard.entities.StandardEntityURN.FIRE_BRIGADE; import static rescuecore2.standard.entities.StandardEntityURN.POLICE_FORCE; public class ApolloWorld extends AbstractModule { protected ScenarioInfo scenarioInfo; protected AgentInfo agentInfo; protected WorldInfo worldInfo; protected ModuleManager moduleManager; public boolean shouldPrecompute = false; private boolean precomputed = false; private boolean resumed = false; private boolean preparated = false; public int maxID = 0; public float rayRate = 0.0025f; private Set<EntityID> changes = new FastSet<EntityID>(); // protected List<IComponent> helpers = new ArrayList<>();//ljy: MRL中helper包中的类 IComponent的实现类 // helpers == components protected Human selfHuman; protected StandardAgent self; protected Building selfBuilding; protected int minX, minY, maxX, maxY; private int maxPower; protected int worldTotalArea; protected Long uniqueMapNumber; /** The last command */ private int lastCommand; // 记录多个周期一直在<身边的同类Agent,Agent--连续出现次数> protected Map<Human, Integer> sameAgentNear = new HashMap<Human, Integer>(); private int[] biggestGatherEvent; //<gatherNum, gatherTime> /** * 历史坐标 */ private List<Pair<Integer, Integer>> historyLocation; private int lastMassiveGatherTime; private Pair<Integer, Integer> lastMassiveGatherLocation; /** * 各周期内FB数量 */ private List<Integer> companions; private Map<EntityID, Integer> PFNearby; protected boolean CommunicationLess = false; protected boolean isCommunicationLow = false; protected boolean isCommunicationMedium = false; protected boolean isCommunicationHigh = false; public boolean isWaterRefillRateInHydrantSet; public boolean isWaterRefillRateInRefugeSet; protected boolean isMapHuge = false; protected boolean isMapMedium = false; protected boolean isMapSmall = false; protected Set<Road> roadsSeen; protected List<BuildingModel> apolloBuildings; protected Set<Building> buildingsSeen; protected Set<Civilian> civiliansSeen; protected Set<Blockade> blockadesSeen; protected Set<FireBrigade> fireBrigadesSeen = new HashSet<FireBrigade>(); protected Set<StandardEntity> roads; protected Set<RoadModel> apolloRoads; protected Map<EntityID, RoadModel> apolloRoadIdMap; protected Collection<StandardEntity> civilians; protected Set<StandardEntity> areas; protected Set<StandardEntity> humans; protected Set<StandardEntity> agents; protected Set<StandardEntity> platoonAgents; protected Set<StandardEntity> hydrants; protected Set<StandardEntity> gasStations; protected Map<EntityID, EntityID> entranceRoads = new FastMap<EntityID, EntityID>(); protected List<EntityID> unvisitedBuildings = new ArrayList<EntityID>(); protected Set<EntityID> visitedBuildings = new FastSet<EntityID>(); protected Set<EntityID> thisCycleEmptyBuildings = new FastSet<EntityID>(); protected Set<EntityID> emptyBuildings; protected Set<StandardEntity> buildings; protected Set<EntityID> borderBuildings; public BorderEntities borderFinder; protected Map<EntityID, BuildingModel> apolloBuildingIdMap; protected List<BuildingModel> shouldCheckInsideBuildings = new ArrayList<BuildingModel>(); protected PropertyComponent propertyComponent; protected Set<EntityID> burningBuildings; private Set<EntityID> allCivilians; private Set<EntityID> heardCivilians; protected int lastAfterShockTime = 0; protected int aftershockCount = 0; protected List<BuildingModel> buildingModels; protected Map<EntityID, BuildingModel> tempBuildingsMap; Map<String, Building> buildingXYMap = new FastMap<String, Building>(); protected Map<String, Road> roadXYMap; protected Set<EntityID> mapSideBuildings; // PF & FB fire zone protected Set<BuildingModel> estimatedBurningBuildings = new FastSet<BuildingModel>(); // FB & PF private Set<EntityID> possibleBurningBuildings; // IComponent protected List<IComponent> components = new ArrayList<>(); protected List<FireBrigade> fireBrigadeList = new ArrayList<FireBrigade>(); protected List<PoliceForce> policeForceList = new ArrayList<PoliceForce>(); protected List<AmbulanceTeam> ambulanceTeamList = new ArrayList<AmbulanceTeam>(); public List<EntityID> viewerEmptyBuildings = new ArrayList<EntityID>(); protected List<Civilian> civilianSeenInMap = new ArrayList<Civilian>(); //从一开始所有看见的! protected GraphModule graphModule; protected Paths paths; public ApolloWorld(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { super(ai, wi, si, moduleManager, developData); this.worldInfo = wi; this.agentInfo = ai; this.scenarioInfo = si; this.moduleManager = moduleManager; this.developData = developData; this.roadsSeen = new HashSet<>(); buildingsSeen = new HashSet<>(); civiliansSeen = new HashSet<>(); blockadesSeen = new HashSet<>(); apolloRoads = new HashSet<>(); burningBuildings = new HashSet<>(); apolloRoadIdMap = new HashMap<>(); emptyBuildings = new FastSet<EntityID>(); thisCycleEmptyBuildings = new HashSet<>(); civilians = new HashSet<>(); buildings = new HashSet<>(getBuildingsWithURN()); entranceRoads = new HashMap<>(); buildingXYMap = new HashMap<>(); apolloBuildingIdMap = new HashMap<>(); this.mapSideBuildings = new FastSet<EntityID>(); burningBuildings = new HashSet<>(); allCivilians = new HashSet<>(); buildings = new HashSet<>(getBuildingsWithURN()); roads = new HashSet<>(getRoadsWithURN()); areas = new HashSet<>(getAreasWithURN()); humans = new HashSet<>(getHumansWithURN()); agents = new HashSet<>(getAgentsWithURN()); platoonAgents = new HashSet<>(getPlatoonAgentsWithURN()); hydrants = new HashSet<>(getHydrantsWithURN()); gasStations = new HashSet<>(getGasStationsWithUrn()); graphModule = new GraphModule(ai, wi, si, moduleManager, developData); apolloRoadIdMap = new HashMap<>(); entranceRoads = new HashMap<>(); buildingXYMap = new HashMap<>(); roadXYMap = new HashMap<>(); possibleBurningBuildings = new HashSet<>(); heardCivilians = new HashSet<>(); createUniqueMapNumber(); components.add(new PropertyComponent(this)); components.add(new BuildingInfoComponent(this, scenarioInfo, agentInfo, worldInfo)); components.add(new RoadInfoComponent(this, ai, wi, si, moduleManager, developData)); components.add(new CivilianInfoComponent(this, si, ai, wi)); components.add(new VisibilityInfoComponent(this, si, ai, wi)); this.self = self; if (worldInfo.getEntity(agentInfo.getID()) instanceof Building) { selfBuilding = (Building) worldInfo.getEntity(agentInfo.getID()); // this.centre = (MrlCentre) self; } else { // this.platoonAgent = (MrlPlatoonAgent) self; selfHuman = (Human) worldInfo.getEntity(agentInfo.getID()); } propertyComponent = this.getComponent(PropertyComponent.class); calculateMapDimensions(); setMapInfo(); StandardEntity entity = worldInfo.getEntity(agentInfo.getID()); if (entity instanceof FireBrigade || entity instanceof PoliceForce || entity instanceof AmbulanceTeam) { // System.err.println("calling createApolloBuildings ......."); createBuildingsModel(); //createApolloBuildings(); } paths = new Paths(this, worldInfo, agentInfo, scenarioInfo); createApolloRoads(); borderBuildings = new HashSet<>(); borderFinder = new BorderEntities(this); // policeForceList = getPoliceForceList(); this.mapSideBuildings = new FastSet<EntityID>(); this.companions = new ArrayList<Integer>(); this.PFNearby = new HashMap<EntityID, Integer>(); this.biggestGatherEvent = new int[2]; this.historyLocation = new ArrayList<Pair<Integer, Integer>>(); //Jingyi Lu TODO: Check (暂时) // for (StandardEntity standardEntity : worldInfo.getEntitiesOfType( // StandardEntityURN.POLICE_FORCE, StandardEntityURN.FIRE_BRIGADE, // StandardEntityURN.AMBULANCE_TEAM)) { // if (standardEntity instanceof FireBrigade) { // fireBrigadeList.add((FireBrigade) standardEntity); // } else if (standardEntity instanceof PoliceForce) { // policeForceList.add((PoliceForce) standardEntity); // } else if (standardEntity instanceof AmbulanceTeam) { // ambulanceTeamList.add((AmbulanceTeam) standardEntity); // } // if (maxID < standardEntity.getID().getValue()) { // maxID = standardEntity.getID().getValue(); // } // } } @Override public AbstractModule calc() { return this; } /** * To update basic world info every cycle.</br> * <b>Note: </b>child agent override this method will update after component.</br> */ public synchronized static ApolloWorld load(AgentInfo agentInfo, WorldInfo worldInfo, ScenarioInfo scenarioInfo, ModuleManager moduleManager, DevelopData developData) { ApolloWorld world = null; try { // System.err.println(" getting ApolloWorldHelper ......."); if (agentInfo.me().getStandardURN() == FIRE_BRIGADE) { world = moduleManager.getModule("ApolloRescue.module.complex.firebrigade.FireBrigadeWorld", "ApolloRescue.module.complex.firebrigade.FireBrigadeWorld"); //world = new FireBrigadeWorld(agentInfo,worldInfo,scenarioInfo,moduleManager,developData); // System.out.println("FBWORLD"); } /* else if(agentInfo.me().getStandardURN() == POLICE_FORCE){ // Jingyi Lu world = moduleManager.getModule("ApolloRescue.extaction.clear.PoliceForceWorld", "ApolloRescue.module.universal.ApolloWorld"); } */ else { world = moduleManager.getModule("ApolloRescue.ApolloWorld", "ApolloRescue.module.universal.ApolloWorld"); //world = new ApolloWorld(agentInfo,worldInfo,scenarioInfo,moduleManager,developData); } } catch (Exception ex) { ex.printStackTrace(); world = null; } if (world == null) { // System.err.println(" creating ApolloWorldHelper ......."); if (worldInfo.getEntity(agentInfo.getID()) instanceof FireBrigade) { world = new FireBrigadeWorld(agentInfo, worldInfo, scenarioInfo, moduleManager, developData); } else { world = new ApolloWorld(agentInfo, worldInfo, scenarioInfo, moduleManager, developData); } } return world; } private void createApolloRoads() { apolloRoads = new HashSet<>(); apolloRoadIdMap = new HashMap<>(); for (StandardEntity rEntity : getRoads()) { Road road = (Road) rEntity; RoadModel apolloRoad = new RoadModel(agentInfo, worldInfo, scenarioInfo, moduleManager, road, this); apolloRoads.add(apolloRoad); apolloRoadIdMap.put(road.getID(), apolloRoad); String xy = road.getX() + "," + road.getY(); roadXYMap.put(xy, road); } // MrlPersonalData.VIEWER_DATA.setViewRoadsMap(self.getID(), mrlRoads); } private void createApolloBuildings() { tempBuildingsMap = new HashMap<>(); apolloBuildings = new ArrayList<>(); BuildingModel apolloBuilding; Building building; for (StandardEntity standardEntity : getBuildings()) { building = (Building) standardEntity; String xy = building.getX() + "," + building.getY(); buildingXYMap.put(xy, building); apolloBuilding = new BuildingModel(standardEntity, this, worldInfo, agentInfo); if ((standardEntity instanceof Refuge) || (standardEntity instanceof FireStation) || (standardEntity instanceof PoliceOffice) || (standardEntity instanceof AmbulanceCentre)) { //todo all of these buildings may be flammable.............. apolloBuilding.setFlammable(false); } apolloBuildings.add(apolloBuilding); tempBuildingsMap.put(standardEntity.getID(), apolloBuilding); apolloBuildingIdMap.put(building.getID(), apolloBuilding); // ina bejaye building helper umade. unvisitedBuildings.add(standardEntity.getID()); worldTotalArea += apolloBuilding.getSelfBuilding().getTotalArea(); } shouldCheckInsideBuildings.clear(); //related to FBLegacyStrategy and Zone operations if (getSelfHuman() instanceof FireBrigade) { apolloBuildings.parallelStream().forEach(b -> { Collection<StandardEntity> neighbour = worldInfo.getObjectsInRange(b.getSelfBuilding(), Wall.MAX_SAMPLE_DISTANCE); // Collection<StandardEntity> fireNeighbour = getObjectsInRange(b.getSelfBuilding(), Wall.MAX_FIRE_DISTANCE); List<EntityID> neighbourBuildings = new ArrayList<EntityID>(); for (StandardEntity entity : neighbour) { if (entity instanceof Building) { neighbourBuildings.add(entity.getID()); b.addApolloBuildingNeighbour(tempBuildingsMap.get(entity.getID())); } } b.setNeighbourIdBuildings(neighbourBuildings); }); // for (MrlBuilding b : mrlBuildings) { // Collection<StandardEntity> neighbour = worldInfo.getObjectsInRange(b.getSelfBuilding(), Wall.MAX_ SAMPLE_DISTANCE); //// Collection<StandardEntity> fireNeighbour = getObjectsInRange(b.getSelfBuilding(), Wall.MAX_FIRE_DISTANCE); // List<EntityID> neighbourBuildings = new ArrayList<EntityID>(); // for (StandardEntity entity : neighbour) { // if (entity instanceof Building) { // neighbourBuildings.add(entity.getID()); // b.addMrlBuildingNeighbour(tempBuildingsMap.get(entity.getID())); // } // } // b.setNeighbourIdBuildings(neighbourBuildings); // } } for (BuildingModel b : apolloBuildings) { //MTN if (b.getEntrances() != null) { building = b.getSelfBuilding(); List<Road> rEntrances = BuildingInfoComponent.getEntranceRoads(this, building); for (Road road : rEntrances) { entranceRoads.put(road.getID(), b.getID()); } /* boolean shouldCheck = true; // if (rEntrances != null) { // if (rEntrances.size() == 0) // shouldCheck = false; VisibilityInfoComponent visibilityHelper = getHelper(VisibilityInfoComponent.class); for (Road road : rEntrances) { boolean shouldCheckTemp = !visibilityHelper.isInsideVisible(new Point(road.getX(), road.getY()), new Point(building.getX(), building.getY()), building.getEdgeTo(road.getID()), scenarioInfo.getPerceptionLosMaxDistance()); if (!shouldCheckTemp) { shouldCheck = false; break; // } } } b.setShouldCheckInside(shouldCheck); if (shouldCheck) { shouldCheckInsideBuildings.add(b); } */ } // b.setNeighbourFireBuildings(fireNeighbours); // MrlPersonalData.VIEWER_DATA.setMrlBuildingsMap(b); } // MrlPersonalData.VIEWER_DATA.setViewerBuildingsMap(self.getID(), mrlBuildings); } public List<StandardEntity> getBuildingsInShape(Shape shape) { List<StandardEntity> result = new ArrayList<StandardEntity>(); for (StandardEntity next : getBuildings()) { Area area = (Area) next; if (shape.contains(area.getShape().getBounds2D())) result.add(next); } return result; } //与getBuildingsModel一样,重复。请使用本方法 public List<BuildingModel> getApolloBuildings() { return buildingModels; } public BuildingModel getBuildingsModel(EntityID id) { return apolloBuildingIdMap.get(id); } public Set<StandardEntity> getBuildings() { return buildings; } public <T extends StandardEntity> T getEntity(EntityID id, Class<T> c) { StandardEntity entity; entity = getEntity(id); if (c.isInstance(entity)) { T castedEntity; castedEntity = c.cast(entity); return castedEntity; } else { return null; } } public Set<BuildingModel> getEstimatedBurningBuildings() { return estimatedBurningBuildings; } /** * pf & fb */ protected void setEstimatedBurningBuildings() { estimatedBurningBuildings.clear(); for (BuildingModel buildingModel : getBuildingsModel()) { if (buildingModel.getEstimatedFieryness() >= 1 && buildingModel.getEstimatedFieryness() <= 3) { estimatedBurningBuildings.add(buildingModel); } } } public List<PoliceForce> getPoliceForceList() { return policeForceList; } public List<BuildingModel> getBuildingsModel() { return buildingModels; } public BuildingModel getBuildingModel(EntityID id) { return tempBuildingsMap.get(id); } public Map<EntityID, BuildingModel> getApolloBuildingIdMap() { return apolloBuildingIdMap; } public Set<Civilian> getCiviliansSeen() { return civiliansSeen; } private void createBuildingsModel() { tempBuildingsMap = new FastMap<EntityID, BuildingModel>(); buildingModels = new ArrayList<BuildingModel>(); BuildingModel buildingModel; Building building; for (StandardEntity standardEntity : getBuildings()) { building = (Building) standardEntity; String xy = building.getX() + "," + building.getY(); buildingXYMap.put(xy, building); buildingModel = new BuildingModel(standardEntity, this, worldInfo, agentInfo); if ((standardEntity instanceof Refuge) || (standardEntity instanceof FireStation) || (standardEntity instanceof PoliceOffice) || (standardEntity instanceof AmbulanceCentre)) { // todo buildingModel.setFlammable(false); } buildingModels.add(buildingModel); tempBuildingsMap.put(standardEntity.getID(), buildingModel); apolloBuildingIdMap.put(building.getID(), buildingModel); unvisitedBuildings.add(standardEntity.getID()); viewerEmptyBuildings.add(standardEntity.getID()); worldTotalArea += buildingModel.getSelfBuilding().getTotalArea(); } shouldCheckInsideBuildings.clear(); for (BuildingModel b : buildingModels) { Collection<StandardEntity> neighbour = worldInfo.getObjectsInRange(b.getSelfBuilding(), Wall.MAX_SAMPLE_DISTANCE); // Collection<StandardEntity> fireNeighbour = // getObjectsInRange(b.getSelfBuilding(), Wall.MAX_FIRE_DISTANCE); List<EntityID> neighbourBuildings = new ArrayList<EntityID>(); // List<EntityID> fireNeighbours = new ArrayList<EntityID>(); for (StandardEntity entity : neighbour) { if (entity instanceof Building) { neighbourBuildings.add(entity.getID()); b.addBuildingModelNeighbour(tempBuildingsMap.get(entity .getID())); } } b.setNeighbourIdBuildings(neighbourBuildings); // MTN if (b.getEntrances() != null) { building = b.getSelfBuilding(); List<Road> rEntrances = BuildingInfoComponent.getEntranceRoads( this, building); for (Road road : rEntrances) { entranceRoads.put(road.getID(), b.getID()); } /*boolean shouldCheck = true; // if (rEntrances != null) { // if (rEntrances.size() == 0) // shouldCheck = false; VisibilityComponent visibilityComponent = getComponent(VisibilityComponent.class); for (Road road : rEntrances) { boolean shouldCheckTemp = !visibilityComponent .isInsideVisible( new Point(road.getX(), road.getY()), new Point(building.getX(), building.getY()), building.getEdgeTo(road.getID()), viewDistance); if (!shouldCheckTemp) { shouldCheck = false; break; // } } }*/ /*b.setShouldCheckInside(shouldCheck); if (shouldCheck) { shouldCheckInsideBuildings.add(b); } */ } // // b.setNeighbourFireBuildings(fireNeighbours); } } /** * this method remove input building from {@code visitedBuildings}, add it in the {@code unvisitedBuilding} and prepare * message that should be send.<br/><br/> * use this must visit it to make sure whether it is empty. * * @param buildingID {@code EntityID} of building that visited! * @param sendMessage {@code boolean} to sent visited building message */ public void setBuildingVisited(EntityID buildingID, boolean sendMessage) { BuildingModel buildingModel = getBuildingModel(buildingID); /*if (commonAgent == null) { return; }*/ if (!buildingModel.isVisited()) { buildingModel.setVisited(); visitedBuildings.add(buildingID); unvisitedBuildings.remove(buildingID); } updateEmptyBuildingState(buildingModel, sendMessage); } private Collection<StandardEntity> getBuildingsWithURN() { return worldInfo.getEntitiesOfType( StandardEntityURN.BUILDING, StandardEntityURN.REFUGE, StandardEntityURN.AMBULANCE_CENTRE, StandardEntityURN.POLICE_OFFICE, StandardEntityURN.FIRE_STATION, StandardEntityURN.GAS_STATION); } private Collection<StandardEntity> getHydrantsWithURN() { return worldInfo.getEntitiesOfType(StandardEntityURN.HYDRANT); } /** * map size move time > 60 big; > 30 medium ; small */ private void setMapInfo() { double mapDimension = Math.hypot(getMapWidth(), getMapHeight()); double rate = mapDimension / ApolloConstants.MEAN_VELOCITY_OF_MOVING; if (rate > 60) { isMapHuge = true; } else if (rate > 30) { isMapMedium = true; } else { isMapSmall = true; } } private Collection<StandardEntity> getGasStationsWithUrn() { return worldInfo.getEntitiesOfType(StandardEntityURN.GAS_STATION); } private Collection<StandardEntity> getAreasWithURN() { return worldInfo.getEntitiesOfType( StandardEntityURN.BUILDING, StandardEntityURN.REFUGE, StandardEntityURN.ROAD, StandardEntityURN.AMBULANCE_CENTRE, StandardEntityURN.POLICE_OFFICE, StandardEntityURN.FIRE_STATION, StandardEntityURN.HYDRANT, StandardEntityURN.GAS_STATION); } private Collection<StandardEntity> getHumansWithURN() { return worldInfo.getEntitiesOfType( StandardEntityURN.CIVILIAN, FIRE_BRIGADE, StandardEntityURN.POLICE_FORCE, StandardEntityURN.AMBULANCE_TEAM); } private Collection<StandardEntity> getAgentsWithURN() { return worldInfo.getEntitiesOfType( FIRE_BRIGADE, StandardEntityURN.POLICE_FORCE, StandardEntityURN.AMBULANCE_TEAM, StandardEntityURN.FIRE_STATION, StandardEntityURN.POLICE_OFFICE, StandardEntityURN.AMBULANCE_CENTRE); } private Collection<StandardEntity> getPlatoonAgentsWithURN() { return worldInfo.getEntitiesOfType( FIRE_BRIGADE, StandardEntityURN.POLICE_FORCE, StandardEntityURN.AMBULANCE_TEAM); } public Collection<StandardEntity> getFireBrigades() { return worldInfo.getEntitiesOfType(FIRE_BRIGADE); } public Collection<StandardEntity> getAmbulanceTeams() { return worldInfo.getEntitiesOfType(AMBULANCE_TEAM); } public Collection<StandardEntity> getPoliceForces() { return worldInfo.getEntitiesOfType(POLICE_FORCE); } // // Jingyi Lu // public List<PoliceForce> getPoliceForceList() { // Collection<StandardEntity> standardPolices = getPoliceForces(); // for(StandardEntity standardEntity : standardPolices ){ // if(standardEntity instanceof PoliceForce){ // policeForceList.add((PoliceForce)standardEntity); // } // } // return policeForceList; // } public Collection<StandardEntity> getAreas() { return areas; } private Collection<StandardEntity> getRoadsWithURN() { return worldInfo.getEntitiesOfType(StandardEntityURN.ROAD, StandardEntityURN.HYDRANT); } public void updateEmptyBuildingState(BuildingModel buildingModel, boolean sendMessage) { if (!buildingModel.isVisited()) { return; } if (!emptyBuildings.contains(buildingModel.getID()) && buildingModel.getCivilians().isEmpty()) { if (sendMessage) { thisCycleEmptyBuildings.add(buildingModel.getID()); } emptyBuildings.add(buildingModel.getID()); } if (emptyBuildings.contains(buildingModel.getID()) && !buildingModel.getCivilians().isEmpty()) { emptyBuildings.remove(buildingModel.getID()); } } private void calculateMapDimensions() { this.minX = Integer.MAX_VALUE; this.maxX = Integer.MIN_VALUE; this.minY = Integer.MAX_VALUE; this.maxY = Integer.MIN_VALUE; Pair<Integer, Integer> pos; List<StandardEntity> invalidEntities = new ArrayList<>(); for (StandardEntity standardEntity : worldInfo.getAllEntities()) { pos = worldInfo.getLocation(standardEntity); if (pos.first() == Integer.MIN_VALUE || pos.first() == Integer.MAX_VALUE || pos.second() == Integer.MIN_VALUE || pos.second() == Integer.MAX_VALUE) { invalidEntities.add(standardEntity); continue; } if (pos.first() < this.minX) this.minX = pos.first(); if (pos.second() < this.minY) this.minY = pos.second(); if (pos.first() > this.maxX) this.maxX = pos.first(); if (pos.second() > this.maxY) this.maxY = pos.second(); } if (!invalidEntities.isEmpty()) { System.out.println("##### WARNING: There is some invalid entities ====> " + invalidEntities.size()); } } public Building getBuildingInPoint(int x, int y) { String xy = x + "," + y; return buildingXYMap.get(xy); } public List<EntityID> getUnvisitedBuildings() { return unvisitedBuildings; } public Set<EntityID> getVisitedBuildings() { return visitedBuildings; } public Set<EntityID> getThisCycleEmptyBuildings() { return thisCycleEmptyBuildings; } public List<EntityID> getViewerEmptyBuildings() { return viewerEmptyBuildings; } public int getWorldTotalArea() { return worldTotalArea; } public List<BuildingModel> getShouldCheckInsideBuildings() { return shouldCheckInsideBuildings; } /** * Map of entrance RoadID to BuildingID. */ public Map<EntityID, EntityID> getEntranceRoads() { return entranceRoads; } public boolean isEntrance(Road road) { return entranceRoads.containsKey(road.getID()); } public int getMinX() { return this.minX; } public int getMinY() { return this.minY; } public int getMaxX() { return this.maxX; } public int getMaxY() { return this.maxY; } public int getMapWidth() { return maxX - minX; } public int getMapHeight() { return maxY - minY; } public List<FireBrigade> getFireBrigadeList() { return fireBrigadeList; } public int getMaxPower() { return maxPower; } public Human getSelfHuman() { return selfHuman; } public void setMaxPower(int maxPower) { this.maxPower = maxPower; } public ScenarioInfo getScenarioInfo() { return scenarioInfo; } public void setScenarioInfo(ScenarioInfo scenarioInfo) { this.scenarioInfo = scenarioInfo; } public AgentInfo getAgentInfo() { return agentInfo; } public void setAgentInfo(AgentInfo agentInfo) { this.agentInfo = agentInfo; } public WorldInfo getWorldInfo() { return worldInfo; } public void setModuleManager(ModuleManager moduleManager) { this.moduleManager = moduleManager; } public ModuleManager getModuleManager() { return this.moduleManager; } public void setDevelopData(DevelopData developData) { this.developData = developData; } public DevelopData getDevelopData() { return this.developData; } public void setWorldInfo(WorldInfo worldInfo) { this.worldInfo = worldInfo; } /** * fire zone use.</br> * <b>Note: </b>fb & pf self world initial before.</br> * * @return */ public Set<EntityID> getMapSideBuildings() { return mapSideBuildings; } public StandardEntity getEntity(EntityID id) { return worldInfo.getEntity(id); } public Rectangle2D getBounds() { return worldInfo.getBounds(); } public Building getSelfBuilding() { return selfBuilding; } public StandardEntity getSelfPosition() { if (worldInfo.getEntity(agentInfo.getID()) instanceof Building) { return selfBuilding; } else { return agentInfo.getPositionArea(); } } public void setCommunicationLess(boolean CL) { this.CommunicationLess = CL; } public boolean isCommunicationLess() { return CommunicationLess; } public boolean isCommunicationLow() { return isCommunicationLow; } public void setCommunicationLow(boolean communicationLow) { isCommunicationLow = communicationLow; } public boolean isCommunicationMedium() { return isCommunicationMedium; } public void setCommunicationMedium(boolean communicationMedium) { isCommunicationMedium = communicationMedium; } public boolean isCommunicationHigh() { return isCommunicationHigh; } public void setCommunicationHigh(boolean communicationHigh) { isCommunicationHigh = communicationHigh; } private void createUniqueMapNumber() { long sum = 0; for (StandardEntity building : getBuildings()) { Building b = (Building) building; int[] ap = b.getApexList(); for (int anAp : ap) { if (Long.MAX_VALUE - sum <= anAp) { sum = 0; } sum += anAp; } } uniqueMapNumber = sum; // System.out.println("Unique Map Number=" + uniqueMapNumber); } public String getMapName() { return getUniqueMapNumber().toString(); } public Long getUniqueMapNumber() { return uniqueMapNumber; } @Override public ApolloWorld precompute(PrecomputeData precomputeData) { super.precompute(precomputeData); if (this.getCountPrecompute() >= 2) { return this; } if (precomputed) { return this; } precomputed = true; components.forEach(IComponent::init); shouldPrecompute = true; return this; } @Override public ApolloWorld resume(PrecomputeData precomputeData) { super.resume(precomputeData); if (this.getCountResume() >= 2) { return this; } if (resumed) { return this; } resumed = true; shouldPrecompute = false; components.forEach(IComponent::init); return this; } @Override public ApolloWorld preparate() { super.preparate(); if (this.getCountPreparate() >= 2) { return this; } if (preparated) { return this; } preparated = true; shouldPrecompute = false; components.forEach(IComponent::init); return this; } private int lastUpdateTime = -1; @Override public ApolloWorld updateInfo(MessageManager messageManager) { super.updateInfo(messageManager); if (this.getCountUpdateInfo() >= 2) { return this; } if (lastUpdateTime == agentInfo.getTime()) { return this; } lastUpdateTime = agentInfo.getTime(); reflectMessage(messageManager); roadsSeen.clear(); buildingsSeen.clear(); blockadesSeen.clear(); civiliansSeen.clear(); fireBrigadesSeen.clear(); civilians = worldInfo.getEntitiesOfType(StandardEntityURN.CIVILIAN); for (StandardEntity civEntity : civilians) { allCivilians.add(civEntity.getID()); } Collection<Command> heard = agentInfo.getHeard(); heardCivilians.clear(); if (heard != null) { for (Command next : heard) { if (next instanceof AKSpeak && ((AKSpeak) next).getChannel() == 0 && !next.getAgentID().equals(agentInfo.getID())) {// say messages AKSpeak speak = (AKSpeak) next; Collection<EntityID> platoonIDs = Handy.objectsToIDs(getAgents()); if (!platoonIDs.contains(speak.getAgentID())) {//Civilian message processCivilianCommand(speak); allCivilians.add(speak.getAgentID()); } } } } changes=agentInfo.getChanged().getChangedEntities(); for (EntityID changedId : worldInfo.getChanged().getChangedEntities()) { StandardEntity entity = worldInfo.getEntity(changedId); if (entity instanceof Civilian) { Civilian civilian = (Civilian) entity; civiliansSeen.add(civilian); } else if (entity instanceof Building) { Building building = (Building) entity; //Checking for AFTER SHOCK occurrence Property brokennessProperty = building.getProperty(StandardPropertyURN.BROKENNESS.toString()); if (brokennessProperty.isDefined()) { int newBrokennessValue = -1; for (Property p : worldInfo.getChanged().getChangedProperties(building.getID())) { if (p.getURN().endsWith(brokennessProperty.getURN())) { newBrokennessValue = (Integer) p.getValue(); } } if (building.getBrokenness() < newBrokennessValue) { //after shock is occurred if (propertyComponent.getPropertyTime(brokennessProperty) > getLastAfterShockTime()) { setAftershockProperties(agentInfo.getTime(), agentInfo.getTime()); } } } //Update seen building properties for (Property p : worldInfo.getChanged().getChangedProperties(building.getID())) { building.getProperty(p.getURN()).takeValue(p); propertyComponent.setPropertyTime(building.getProperty(p.getURN()), agentInfo.getTime()); } BuildingModel apolloBuilding = getBuildingsModel(building.getID()); if (agentInfo.me() instanceof FireBrigade) { if (building.isFierynessDefined() && building.isTemperatureDefined()) { apolloBuilding.setEnergy(building.getTemperature() * apolloBuilding.getCapacity()); apolloBuilding.updateValues(building); } } // if (getEntity(building.getID()) == null) { // addEntityImpl(building); propertyComponent.addEntityProperty(building, agentInfo.getTime()); // } //updating burning buildings set if (building.getFieryness() > 0 && building.getFieryness() < 4) { burningBuildings.add(building.getID()); } else { burningBuildings.remove(building.getID()); } buildingsSeen.add(building); apolloBuilding.setSensed(agentInfo.getTime()); if (building.isOnFire()) { apolloBuilding.setIgnitionTime(agentInfo.getTime()); } } else if (entity instanceof Road) { Road road = (Road) entity; roadsSeen.add(road); RoadModel apolloRoad = getApolloRoad(entity.getID()); if (apolloRoad.isNeedUpdate()) { apolloRoad.update(); } apolloRoad.setLastSeenTime(agentInfo.getTime()); apolloRoad.setSeen(true); // if (road.isBlockadesDefined()) { // for (EntityID blockadeId : road.getBlockades()) { // blockadesSeen.add((Blockade) worldInfo.getEntity(blockadeId)); // } // } }else if (entity instanceof FireBrigade) { FireBrigade fireBrigade = (FireBrigade) entity; // System.out.println(getTime()+" "+getSelf().getID() // +" agent: "+ fireBrigade.getID()); // if (!(selfHuman instanceof AmbulanceTeam) || // !fireBrigade.isBuriednessDefined() || fireBrigade.getHP() // == 0) { // for (Property p : changeSet.getChangedProperties(entityID)) { // fireBrigade.getProperty(p.getURN()).takeValue(p); // propertyComponent.setPropertyTime( // fireBrigade.getProperty(p.getURN()), time); // } // // } else { // // // // Property p = changeSet.getChangedProperty(entityID, // // fireBrigade.getPositionProperty().getURN()); // // fireBrigade.setPosition((EntityID) p.getValue()); // // propertyComponent.setPropertyTime(fireBrigade.getPositionProperty(), // // time); // // // // p = changeSet.getChangedProperty(entityID, // // fireBrigade.getBuriednessProperty().getURN()); // // fireBrigade.setBuriedness((Integer) p.getValue()); // // propertyComponent.setPropertyTime(fireBrigade.getBuriednessProperty(), // // time); // // // // } // // // if (getPlatoonAgent() != null) { // // getPlatoonAgent().markVisitedBuildings((Area) // // getEntity(fireBrigade.getPosition())); // // } // // if (Util.isOnBlockade(this, fireBrigade)) { // getComponent(HumanInfoComponent.class) // .setLockedByBlockade(fireBrigade.getID(), true); // } // // add agent seen //// if (!agentSeen.contains(fireBrigade)) { // agentSeen.add(fireBrigade); //// } fireBrigadesSeen.add(fireBrigade); }else if (entity instanceof Blockade) { blockadesSeen.add((Blockade) entity); } } components.forEach(IComponent::update); updateSameAgentNear(); if (agentInfo.getTime() - this.biggestGatherEvent[1] > 0 && (agentInfo.getTime() - this.biggestGatherEvent[1]) % 5 == 0) //更新历史位置 this.historyLocation.add(worldInfo.getLocation(agentInfo.getID())); return this; } public void processCivilianCommand(AKSpeak speak) { Civilian civilian = (Civilian) getEntity(speak.getAgentID()); if (civilian == null) { civilian = new Civilian(speak.getAgentID()); addNewCivilian(civilian); } if (!civilian.isPositionDefined()) { addHeardCivilian(civilian.getID()); } } public int getLastAfterShockTime() { return lastAfterShockTime; } public int getAftershockCount() { return aftershockCount; } public void setAftershockProperties(int lastAfterShockTime, int aftershockCount) { if (this.aftershockCount < aftershockCount) { this.aftershockCount = aftershockCount; if (selfHuman != null) { postAftershockAction(); } } } public void postAftershockAction() { this.printData("New aftershock occurred! Time: " + agentInfo.getTime() + " Total: " + this.getAftershockCount()); for (RoadModel apolloRoad : this.getApolloRoads()) { apolloRoad.getParent().undefineBlockades(); } } public int getTime() { return agentInfo.getTime(); } /** * All civilian defined in world model or their voice were heard. * * @return */ public Set<EntityID> getAllCivilians() { return allCivilians; } public Collection<StandardEntity> getObjectsInRange(int x, int y, int range) { int newRange = (int) (0.64 * range); return worldInfo.getObjectsInRange(x, y, newRange); } public int getMaxExtinguishDistance() { return scenarioInfo.getFireExtinguishMaxDistance(); } public Collection<StandardEntity> getObjectsInRange(EntityID entityID, int distance) { return worldInfo.getObjectsInRange(entityID, distance); } /** Get the distance between two entities. @param first The first entity. @param second The second entity. @return The distance between the two entities. A negative value indicates that one or both objects could not be located. */ public int getDistance(StandardEntity first, StandardEntity second) { // Pair<Integer, Integer> a = first.getLocation(this); Pair<Integer, Integer> a = worldInfo.getLocation(first); Pair<Integer, Integer> b = worldInfo.getLocation(second); if (a == null || b == null) { return -1; } return Util.distance(a, b); } public int getDistance(EntityID first, EntityID second) { return worldInfo.getDistance(first, second); } public Set<EntityID> getBorderBuildings() { return borderBuildings; } public Set<EntityID> getBuildingIDs() { Set<EntityID> buildingIDs = new HashSet<>(); Collection<StandardEntity> buildings = getBuildings(); for (StandardEntity entity : buildings) { buildingIDs.add(entity.getID()); } return buildingIDs; } public boolean isMapHuge() { return isMapHuge; } public boolean isMapMedium() { return isMapMedium; } public boolean isMapSmall() { return isMapSmall; } /** * include road & hydrant. * * @return {@code StandardEntity} collection */ public Collection<StandardEntity> getRoads() { return worldInfo.getEntitiesOfType(StandardEntityURN.ROAD, StandardEntityURN.HYDRANT); } public List<EntityID> getRoadsList() { List<EntityID> list = new ArrayList<EntityID>(); for (StandardEntity entity : getRoads()) { list.add(entity.getID()); } return list; } public RoadModel getRoadModel(EntityID roadID) { return apolloRoadIdMap.get(roadID); } public <T extends IComponent> T getComponent(Class<T> c) { // for (IComponent component : components) { // if (c.isInstance(component)) { //// return c.cast(component); // System.out.println("c.isInstance(component). component:" + component.getClass().getName()); // break; // } // } // if (c.isInstance(new RoadInfoComponent(this, agentInfo, worldInfo, scenarioInfo, moduleManager, developData))) { // //System.out.println("This is RoadInfoComponent"); // return c.cast(new RoadInfoComponent(this, agentInfo, worldInfo, scenarioInfo, moduleManager, developData)); // } else if (c.isInstance(new BuildingInfoComponent(this, scenarioInfo, agentInfo, worldInfo))) { // //System.out.println("This is BuildingInfoComponent"); // return c.cast(new BuildingInfoComponent(this, scenarioInfo, agentInfo, worldInfo)); // } else if (c.isInstance(new PropertyComponent(this))) { // return c.cast(new PropertyComponent(this)); // } else if (c.isInstance(new CivilianInfoComponent(this, scenarioInfo, agentInfo, worldInfo))) { // //System.out.println("This is CivilianInfoComponent"); // return c.cast(new CivilianInfoComponent(this, scenarioInfo, agentInfo, worldInfo)); // } /////////////////////////////////////// try { for (IComponent component : components) { if (c.isInstance(component)) { return c.cast(component); } } } catch (Exception e) { e.printStackTrace(); } throw new RuntimeException("Component not available for:" + c); } @SuppressWarnings("rawtypes") public StandardAgent getSelf() { return self; } public void printData(String s) { System.out.println("Time:" + agentInfo.getTime() + " Me:" + agentInfo.me() + " \t- " + s); } public void putEntrance(EntityID buildingId, Entrance entrance) { entranceRoads.put(entrance.getID(), buildingId); } public Set<StandardEntity> getAgents() { return agents; } public List<StandardEntity> getAreasInShape(Shape shape) { List<StandardEntity> result = new ArrayList<StandardEntity>(); for (StandardEntity next : getAreas()) { Area area = (Area) next; if (shape.contains(area.getShape().getBounds2D())) result.add(next); } return result; } public Set<Road> getRoadsSeen() { return roadsSeen; } public Set<Building> getBuildingsSeen() { return buildingsSeen; } public Set<Blockade> getBlockadesSeen() { return blockadesSeen; } public Paths getPaths() { return paths; } public GraphModule getGraphModule() { return graphModule; } public Set<RoadModel> getApolloRoads() { return apolloRoads; } public Map<EntityID, RoadModel> getApolloRoadIdMap() { return apolloRoadIdMap; } public RoadModel getApolloRoad(EntityID id) { return apolloRoadIdMap.get(id); } // public RoadInfoComponent getRoadInfoComponent(){ // return (new RoadInfoComponent(this, agentInfo, worldInfo, scenarioInfo, moduleManager, developData)); // } public Set<EntityID> getPossibleBurningBuildings() { return possibleBurningBuildings; } public void setPossibleBurningBuildings(Set<EntityID> possibleBurningBuildings) { this.possibleBurningBuildings = possibleBurningBuildings; } public void addNewCivilian(Civilian civilian) { // worldInfo.getRawWorld().addEntityImpl(civilian);//todo or should be worldInfo.addEntity(civilian); getComponent(PropertyComponent.class).addEntityProperty(civilian, getTime()); getComponent(CivilianInfoComponent.class).setInfoMap(civilian.getID()); } private void reflectMessage(MessageManager messageManager) { Set<EntityID> changedEntities = this.worldInfo.getChanged().getChangedEntities(); changedEntities.add(this.agentInfo.getID()); int time = this.agentInfo.getTime(); int receivedTime = -1; for (CommunicationMessage message : messageManager.getReceivedMessageList(MessageBuilding.class)) { MessageBuilding mb = (MessageBuilding) message; if (!changedEntities.contains(mb.getBuildingID())) { MessageUtil.reflectMessage(this.worldInfo, mb); if (mb.isRadio()) { receivedTime = time - 1; } else { receivedTime = time - 5; } if (agentInfo.me() instanceof FireBrigade) { processBurningBuilding(mb, receivedTime); } } // this.sentTimeMap.put(mb.getBuildingID(), time + this.sendingAvoidTimeReceived); } // for (CommunicationMessage message : messageManager.getReceivedMessageList(MessageFireBrigade.class)) { // MessageFireBrigade mb = (MessageFireBrigade) message; // MessageUtil.reflectMessage(this.worldInfo, mb); // // processWaterMessage(mb.getAction(), mb.getTargetID()); // } } private void processBurningBuilding(MessageBuilding burningBuildingMessage, int receivedTime) { Building building; building = (Building) this.getEntity(burningBuildingMessage.getBuildingID()); if (propertyComponent.getPropertyTime(building.getFierynessProperty()) < receivedTime) { // if (building.isFierynessDefined() && building.getFieryness() == 8 && burningBuilding.getFieryness() != 8) { // System.out.println("aaaa"); // } // if (building.getID().getValue() == 25393) { // world.printData("BurningBuilding\tSender=" + burningBuilding.getSender().getValue() + " Real Fire=" + (building.isFierynessDefined() ? building.getFieryness() : 0) + " message fire: " + burningBuilding.getFieryness()); // } building.setFieryness(burningBuildingMessage.getFieryness()); propertyComponent.setPropertyTime(building.getFierynessProperty(), receivedTime); building.setTemperature(burningBuildingMessage.getTemperature()); propertyComponent.setPropertyTime(building.getTemperatureProperty(), receivedTime); // if ((platoonAgent instanceof MrlFireBrigade)) { // MrlFireBrigadeWorld w = (MrlFireBrigadeWorld) world; BuildingModel mrlBuilding = this.getBuildingsModel(building.getID()); switch (building.getFieryness()) { case 0: mrlBuilding.setFuel(mrlBuilding.getInitialFuel()); break; case 1: if (mrlBuilding.getFuel() < mrlBuilding.getInitialFuel() * 0.66) { mrlBuilding.setFuel((float) (mrlBuilding.getInitialFuel() * 0.75)); } else if (mrlBuilding.getFuel() == mrlBuilding.getInitialFuel()) { mrlBuilding.setFuel((float) (mrlBuilding.getInitialFuel() * 0.90)); } break; case 2: if (mrlBuilding.getFuel() < mrlBuilding.getInitialFuel() * 0.33 || mrlBuilding.getFuel() > mrlBuilding.getInitialFuel() * 0.66) { mrlBuilding.setFuel((float) (mrlBuilding.getInitialFuel() * 0.50)); } break; case 3: if (mrlBuilding.getFuel() < mrlBuilding.getInitialFuel() * 0.01 || mrlBuilding.getFuel() > mrlBuilding.getInitialFuel() * 0.33) { mrlBuilding.setFuel((float) (mrlBuilding.getInitialFuel() * 0.15)); } break; case 4: case 5: case 6: case 7: mrlBuilding.setWasEverWatered(true); mrlBuilding.setEnergy(0); break; case 8: mrlBuilding.setFuel(0); break; } mrlBuilding.setEnergy(building.getTemperature() * mrlBuilding.getCapacity()); // world.printData("burningBuilding:" + building+" f:"+burningBuildingMessage.getFieriness()+" temp:"+burningBuildingMessage.getTemperature()); // } //updating burning buildings set if (building.getFieryness() > 0 && building.getFieryness() < 4) { this.getBurningBuildings().add(building.getID()); mrlBuilding.setIgnitionTime(this.getTime()); } else { this.getBurningBuildings().remove(building.getID()); } mrlBuilding.updateValues(building); } } public Set<EntityID> getBurningBuildings() { return burningBuildings; } /** * Gets heard civilians at current cycle;<br/> * <br/> * <b>Note: </b> At each cycle the list will be cleared * * @return EntityIDs of heard civilians */ public Set<EntityID> getHeardCivilians() { return heardCivilians; } /** * add civilian who speak of it was heard in current cycle! * * @param civID EntityID of civilian */ public void addHeardCivilian(EntityID civID) { // MrlPersonalData.VIEWER_DATA.setHeardPositions(civID, getSelfLocation()); if (!heardCivilians.contains(civID)) { heardCivilians.add(civID); } } public int getVoiceRange() { return scenarioInfo.getRawConfig().getIntValue(ApolloConstants.VOICE_RANGE_KEY); } public List<StandardEntity> getEntities(Set<EntityID> entityIDs) { List<StandardEntity> result = new ArrayList<StandardEntity>(); for (EntityID next : entityIDs) { result.add(getEntity(next)); } return result; } public List<StandardEntity> getEntities(List<EntityID> entityIDs) { List<StandardEntity> result = new ArrayList<StandardEntity>(); for (EntityID next : entityIDs) { result.add(getEntity(next)); } return result; } public int getViewDistance() { return scenarioInfo.getRawConfig().getIntValue(ApolloConstants.MAX_VIEW_DISTANCE_KEY); } /** * 判断是否能看见 需要视野内 & 小于视野距离 * * @param entity * @return */ public boolean canSee(StandardEntity entity) { boolean canSee; if (changes != null) { canSee = changes.contains(entity.getID()) && getDistance(getSelfPosition().getID(), entity.getID()) < getViewDistance(); } else { canSee = true; } return canSee; } public boolean inRange(StandardEntity entity){ return getDistance(getSelfPosition().getID(), entity.getID()) < getViewDistance(); } // Jingyi Lu public boolean isInSameArea(Human human) { if (human == null) { return false; } else { EntityID selfID = this.getSelfPosition().getID(); EntityID testID = human.getID(); if (selfID.equals(testID)) { return true; } else { return true; } } } /** * * @param threshold * 人数阀值 * @param times * 持续时间 * @return */ public boolean isSameAgentGather(int threshold, int times) { int nearNum = 0; for (int i : sameAgentNear.values()) { if (i > times) { nearNum++; } } if (nearNum > threshold) { return true; } return false; } /** * 判断是否扎堆 * * @return */ public boolean isTooMuchPeople() {// 判断是否扎堆 for (Map.Entry<EntityID, Integer> pf : PFNearby.entrySet()) { if (pf.getValue() >= 3) {// 有一个PF见的次数超过3次,判断扎堆 return true; } } return false; } /** * 更新连续几个周期都在身边的智能体 */ protected void updateSameAgentNear() { List<StandardEntity> sameAgents = new ArrayList<StandardEntity>(); // List<PoliceForce> samePFs = new ArrayList<>(); Set<Human> temp = new HashSet<Human>(); //每周期更新一次 if (getSelfHuman() instanceof AmbulanceTeam) { sameAgents.addAll(getAmbulanceTeams()); } else if (getSelfHuman() instanceof FireBrigade) { sameAgents.addAll(getFireBrigades()); } else if (getSelfHuman() instanceof PoliceForce) { sameAgents.addAll(getPoliceForces()); // samePFs.addAll(getPoliceForceList()); // for (PoliceForce pf : this.getPoliceForceList()) { // if (pf.getID().equals(this.getSelf().getID())) {// 就是自己 // continue; // } // if (PFNearby.containsKey(pf.getID())) {// 列表中已经有这个PF // if (this.canSee(pf) && this.isInSameArea(pf)) {// 发现可以看见他,并且在同一地点上 // PFNearby.put(pf.getID(), PFNearby.get(pf.getID()) + 1); // } else {// 看不见他,或者不在同一个地点 // PFNearby.put(pf.getID(), 0); // } // } else {// 列表中没有这个PF // PFNearby.put(pf.getID(), 0); // } // } } // 在视线内 for (StandardEntity agent : sameAgents) { if (canSee(agent)) { temp.add((Human) agent); } } // 更新附近同类Agent List<Human> removeList = new ArrayList<Human>(); // System.out.println("Agent Id : " + self.getID() + "\tsameAgentNear.keyset().size = " + sameAgentNear.keySet().size()); for (Human h : sameAgentNear.keySet()) { // System.out.println("Time is" + this.time + "\tAgent Id : " + self.getID() + "\t进入循环");//TODO 如何获得系统周期 2016 0828 // 仍然出现在身边 if (temp.contains(h)) { int num = sameAgentNear.get(h) + 1; sameAgentNear.put(h, num); temp.remove(h); } else { //在移除列表加入当前待移除智能体 removeList.add(h); } } //将移除列表的智能体全部移除 for (Human h : removeList) { sameAgentNear.remove(h); } // 加入新来的 for (Human h : temp) { sameAgentNear.put(h, 1); } //更新最大聚集事件 if (this.biggestGatherEvent[0] <= sameAgentNear.keySet().size()) { biggestGatherEvent[0] = sameAgentNear.keySet().size(); biggestGatherEvent[1] = this.agentInfo.getTime(); if (!historyLocation.isEmpty()) historyLocation.clear(); historyLocation.add(getSelfLocation()); } if (sameAgentNear.keySet().size() > 1) { lastMassiveGatherLocation = this.getSelfLocation(); lastMassiveGatherTime = this.agentInfo.getTime(); } companions.add(sameAgentNear.keySet().size());//记录这一周期身边相同的智能体数 } private boolean isInitTimeGather; // 初始期大范围聚集 public boolean isInitTimeGather() { return isInitTimeGather; } public boolean isGather() { // System.out.println("Time: " + this.getTime() + " Agent Id:" + self.getID() + "\t调用了world.isGather()"); int nearNum = 0; for (int i : sameAgentNear.values()) { if (i > 3) { nearNum++; } } if (this.getTime() < 4 && sameAgentNear.keySet().size() > 1) {//added 20160828 return true; } if (this.agentInfo.getTime() < 6 && sameAgentNear.keySet().size() > 10) isInitTimeGather = true; if (nearNum > 1) { return true; } return false; } public rescuecore2.misc.Pair<Integer, Integer> getSelfLocation() { return worldInfo.getLocation(agentInfo.getID()); } /** * 判断我是否还需要维持上一个任务 * * @return 返回true,继续工作,返回false任务切换 */ public boolean shouldIContinueTask() { List<EntityID> possiblePF = new ArrayList<EntityID>(); for (Map.Entry<EntityID, Integer> pf : PFNearby.entrySet()) { if (pf.getValue() >= 3) {// 有一个PF见的次数超过3次,判断扎堆 possiblePF.add(pf.getKey());// 加入列表 } } possiblePF.add(this.getSelf().getID());// 加入自身 if (possiblePF.size() <= 1) {// 本身就我一个人 return true; } Collections.sort(possiblePF, new EntityIDComparator()); if (!this.getSelf().getID().equals(possiblePF.get(0))) {// 自己不是最小编号的 return true; } else { return false; } } /** * 将里面所有PF跟随次数清0 */ public void resetPFNearby() { for (Map.Entry<EntityID, Integer> pf : PFNearby.entrySet()) { pf.setValue(0); } } public boolean shouldILeave(int threshold, int times) {//避免PF扎堆 List<EntityID> humanIDs = new ArrayList<EntityID>(); int nearNum = 0; for (Map.Entry<Human, Integer> entry : sameAgentNear.entrySet()) {//Entry<Human, Integer> --- <身边的同类Agent,Agent连续出现次数> int i = entry.getValue(); if (i > times) { nearNum++; humanIDs.add(entry.getKey().getID()); } } if (nearNum > threshold) {// 超过阀值 Collections.sort(humanIDs, new EntityIDComparator()); if (humanIDs.get(0).getValue() == this.getSelf().getID().getValue()) {// 自己该留下 return false; } else {// 自己该走 // System.out.println("我该走了"); sameAgentNear.clear();// 清空列表,避免重复删除任务 return true; } } return false; } /** * 近10个周期无同伴比例超过0.5,且最后一次聚集发生在3周期以前,则返回true * * @return * @author Yangjiedong */ public boolean isCompanionDecrease() { List<Integer> numerators = new ArrayList<Integer>(); List<Integer> denominators = new ArrayList<Integer>(); int numerator = 0; //分子 int index = 0; //距离现在index个周期以前出现过4聚集 System.out.println("Time: " + this.agentInfo.getTime() + " Agent Id:" + this.getSelfHuman().getID() + "\t companions size is : " + companions.size()); System.out.println("companions :" + companions); if (companions.size() < 12) return false; for (int i = 0; i < companions.size() - 11; i++) if (companions.get(i) > 1) { numerator++; if (companions.get(i) > 3) index = companions.size() - (i + 1); } for (int i = companions.size() - 11; i < companions.size(); i++) { if (companions.get(i) > 1) { numerator++; if (companions.get(i) > 3) index = companions.size() - (i + 1); } numerators.add(numerator); denominators.add(i + 1); } double[] fractions = new double[numerators.size()]; for (int i = 0; i < fractions.length; i++) fractions[i] = (1.0 * numerators.get(i)) / denominators.get(i); int noCompNum = 0; int hasCompNum = 0; for (int i = 1; i < fractions.length; i++) if (fractions[i - 1] > fractions[i]) { noCompNum++; } else { hasCompNum++; } System.out.print("fractions : "); for (int i = 0; i < fractions.length; i++) System.out.printf(" %.2f ", fractions[i]); System.out.println(); System.out.println("no companion number : " + noCompNum + " has companion number : " + hasCompNum + " indx : " + index); if ((1.0 * noCompNum) / (fractions.length - 1) > 0.75 && index > 2) return true; return false; } int judgeTime; // 孤独判断周期数 public void setJudgeTime(int time) { judgeTime = time; } public int getJudgeTime() { return this.judgeTime; } public List<Pair<Integer, Integer>> getHistoryLocation() { return this.historyLocation; } public int[] getBiggestGatherEvent() { return this.biggestGatherEvent; } public boolean isBuildingBurnt(Building building) { if (building == null || !building.isFierynessDefined()) { return false; } int fieriness = building.getFieryness(); return fieriness != 0 && fieriness != 4 && fieriness != 5; } public int getMyDistanceTo(StandardEntity entity) { return getDistance(getSelfPosition(), entity); } public int getMyDistanceTo(EntityID entityID) { return getDistance(getSelfPosition(), getEntity(entityID)); } public Set<FireBrigade> getFireBrigadesSeen() { return fireBrigadesSeen; } protected CommandTypes getCommandType(String str) { if (str.equalsIgnoreCase("Move")) { return CommandTypes.Move; } else if (str.equalsIgnoreCase("Move To Point")) { return CommandTypes.MoveToPoint; } else if (str.equalsIgnoreCase("Random Walk")) { return CommandTypes.RandomWalk; } else if (str.equalsIgnoreCase("Rest")) { return CommandTypes.Rest; } else if (str.equalsIgnoreCase("Rescue")) { return CommandTypes.Rescue; } else if (str.equalsIgnoreCase("Load")) { return CommandTypes.Load; } else if (str.equalsIgnoreCase("Unload")) { return CommandTypes.Unload; } else if (str.equalsIgnoreCase("Clear")) { return CommandTypes.Clear; } else if (str.equalsIgnoreCase("Extinguish")) { return CommandTypes.Extinguish; } return CommandTypes.Empty; } public int getLastCommand() { return lastCommand; } }
43,090
https://github.com/conema/chess-api/blob/master/node_modules/chess-ai-kong/src/search/alpha-beta-data.js
Github Open Source
Open Source
MIT
2,019
chess-api
conema
JavaScript
Code
50
148
'use-strict'; function AlphaBetaData(path, startTime) { if (path !== undefined) { this.path = path; } if(startTime !== undefined) { this.startTime = startTime; } else { this.startTime = new Date().getTime(); } } AlphaBetaData.prototype.next = function (pgn) { return new AlphaBetaData(this.path + '-' + pgn, this.startTime); }; module.exports = { AlphaBetaData: AlphaBetaData };
7,479
https://github.com/XiaoWeiChung/PYTBaseViewController/blob/master/Example/Pods/Target Support Files/Pods-PYTBaseViewController_Tests/Pods-PYTBaseViewController_Tests-dummy.m
Github Open Source
Open Source
MIT
2,020
PYTBaseViewController
XiaoWeiChung
Objective-C
Code
10
58
#import <Foundation/Foundation.h> @interface PodsDummy_Pods_PYTBaseViewController_Tests : NSObject @end @implementation PodsDummy_Pods_PYTBaseViewController_Tests @end
44,295
https://github.com/onyxim/explicitdev/blob/master/src/explicitdev/storage/factory/holiday.py
Github Open Source
Open Source
Apache-2.0
2,020
explicitdev
onyxim
Python
Code
158
557
from datetime import date from sqlalchemy.orm import Session from explicitdev.storage.factory.abstract import FactoryAbstract from explicitdev.storage.model import HolidayAttrs from explicitdev.storage.model.holiday import HolidayType HA = HolidayAttrs class FactoryHoliday(FactoryAbstract): YEAR_FIELD_NAME = 'Год/Месяц' SKIP_SYMBOL = '*' """A symbol from calenders on witch we skip days.""" def __init__(self, c): super().__init__(c) self.Holiday = c.Models.Holiday.Class def fill_dict_from_raw_dict(self, raw_json_dict, data, result_dict: dict = None) -> dict: """ :param raw_json_dict: :param data: :param result_dict: Actually passing this will not work, because result_dict generated internally. :return: """ if not result_dict: result_dict = dict() rjd = raw_json_dict year = int(rjd.pop(self.YEAR_FIELD_NAME)) for month, month_days in enumerate(rjd.values(), start=1): if month > 12: break for day in month_days.split(','): try: day = int(day) except ValueError: symbol = day[-1:] if symbol == self.SKIP_SYMBOL: continue day = int(day[:-1]) result_dict = { HA.date: date(year, month, day), HA.type: HolidayType.government, } self.solve_update_or_insert( data[self.Holiday.__name__], result_dict, result_dict[HA.date], ) return result_dict def get_existed_entities(self, session: Session, **kwargs) -> dict: # noinspection PyTypeChecker result = super().get_existed_entities( session=session, model=self.Holiday, columns=( HA.date, ), ) return result
5,002
https://github.com/wsdjeg/vim-fetch/blob/master/test/vimrc
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, MIT, Vim
2,023
vim-fetch
wsdjeg
Vim Script
Code
14
38
filetype off set rtp+=build/vader set rtp+=. set rtp+=after filetype plugin indent on syntax enable
44,851
https://github.com/anton-bot/mock-bank-ui/blob/master/src/types/AccountTransaction.ts
Github Open Source
Open Source
Unlicense
null
mock-bank-ui
anton-bot
TypeScript
Code
28
68
import { AccountTransactionType } from './AccountTransactionType'; import * as Amount from 'currency.js'; export type AccountTransaction = { transactionId: string; type: AccountTransactionType; datetime: string; description: string; amount: number; };
9,335
https://github.com/MJurczak-PMarchut/uec2_DeathRace/blob/master/src/sources_1/new/Title_Screen.v
Github Open Source
Open Source
MIT
2,018
uec2_DeathRace
MJurczak-PMarchut
Verilog
Code
128
575
`timescale 1ns / 1ps ////////////////////////////////////////////////////////////////////////////////// // Company: // Engineer: // // Create Date: 29.07.2018 21:07:56 // Design Name: // Module Name: Title_Screen // Project Name: // Target Devices: // Tool Versions: // Description: // // Dependencies: // // Revision: // Revision 0.01 - File Created // Additional Comments: // ////////////////////////////////////////////////////////////////////////////////// `include "verilog_macro_bus.vh" module Title_Screen( input wire pclk, input wire [`VGA_BUS_SIZE-1:0] vga_in, output wire [`VGA_BUS_SIZE-1:0] vga_out, input wire playerCount ); wire [`VGA_BUS_SIZE - 1 : 0] vga_bus [1:0]; wire [18:0] address; wire [3:0] rgb_back; wire [6:0] char_code; wire [7:0] char_line_pixels; wire [7:0] char_xy; wire [3:0] char_line; draw_background my_background( .vga_in(vga_in[37:0]), .vga_out(vga_bus[0]), .address(address), .rgb(rgb_back) ); draw_rect_char rect_char( .pclk(pclk), .vga_in(vga_bus[0]), .char_pixels(char_line_pixels), .char_xy(char_xy), .char_line(char_line), .vga_out(vga_out), .playerCount(playerCount) ); font_rom font_rom( .addr({char_code,char_line}), .data(char_line_pixels) ); char_rom_16x16 char_rom( .char_xy(char_xy), .code(char_code) ); start_screen screen( .address(address), .rgb(rgb_back) ); endmodule
24,890
https://github.com/Jorlejeu/podcast-transcriber/blob/master/podcast_transcriber/utilities.py
Github Open Source
Open Source
MIT
2,022
podcast-transcriber
Jorlejeu
Python
Code
272
832
import os import shutil import tempfile import urllib2 TEMP_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tmp') OUTPUT_DIR = os.path.join(os.getcwd(), 'output') def check_env_vars(): """ Checks if all necessary ENV variables are set. If not, prints an error message. """ if 'GOOGLE_API_KEY' not in os.environ: print "Google API key is missing.\n" \ + "To add run `export GOOGLE_API_KEY=<your-api-key>" return False return True def cleanup(): shutil.rmtree(TEMP_DIR) def create_ancillary_folders(): if not os.path.exists(OUTPUT_DIR): print "Output directory absent. Creating output directory..." os.makedirs(OUTPUT_DIR) if not os.path.exists(TEMP_DIR): print "Creating tmp directory..." os.makedirs(TEMP_DIR) def create_temporary_folder(): """ Creates a temporary directory to store all the intermediate files. """ dirpath = tempfile.mkdtemp(dir=TEMP_DIR) print "Created tmp dir at ", dirpath return dirpath def create_temporary_file_name(directory, suffix): """ Creates a temporary file name. Params: directory (string): The directory of the temp file suffix (string): The temp file name """ return os.path.join(directory, suffix) def write_output_file(filename, contents): """ Writes an output file to the directory defined by OUTPUT_DIR variable. Params: filename (string): The output file name contents (string): The contents of the file """ with open(os.path.join(OUTPUT_DIR, filename + '.txt'), 'w') as output_file: output_file.write(contents) def download_remote_file(url, dest): """ Downloads a remote file to the specified location. Params: url (string): The url of the remote file dest (string): The download destination """ remote_file = urllib2.urlopen(url) meta_info = remote_file.info() file_size = int(meta_info.getheaders("Content-Length")[0]) print "Downloading: %s" % url.split('/')[-1] file_size_dl = 0 block_sz = 8192 with open(dest, 'wb') as local_file: while True: buf = remote_file.read(block_sz) if not buf: break file_size_dl += len(buf) local_file.write(buf) status = r"Progress: %d / %d [%3.2f%%]" % ( file_size_dl, file_size, file_size_dl * 100. / file_size) status = status + chr(8) * (len(status) + 1) print status, print "\nFile downloaded to: %s" % dest
48,712
https://github.com/uppy19d0/gatsbyportafolio/blob/master/src/components/codigofacilito.js
Github Open Source
Open Source
RSA-MD
2,022
gatsbyportafolio
uppy19d0
JavaScript
Code
75
300
import React from "react"; import Posts from "../components/posts"; import {graphql, useStaticQuery} from "gatsby"; import CursoFinish from "../elements/cursosfinish"; import Curso from "../elements/cursos"; export default ()=>{ const data = useStaticQuery(graphql` { codigoFacilitoJson { id data { finished_courses { title url } courses{ title progress url } } } } `); console.log(data); return ( <section> <div className="mt-24"> <div className="max-w-4xl mx-auto"> <Posts data={data.codigoFacilitoJson.data.finished_courses} card={CursoFinish} title="Cursos hecho en CodigoFacilito"/> <Posts data={data.codigoFacilitoJson.data.courses.slice(1,4)} card={Curso} title="Cursos en CodigoFacilito"/> </div> </div> </section> ) }
11,095
https://github.com/forgotter/Snippets/blob/master/test/kurskal.cpp
Github Open Source
Open Source
MIT
2,022
Snippets
forgotter
C++
Code
145
496
#include <bits/stdc++.h> using namespace std; vector<int> root, root_size; void init_root(int n) { root_size.assign(n + 1, 1); root.resize(n + 1); for (int i = 1; i <= n; i++) root[i] = i; } int get_root(int x) { return (root[x] == x) ? x : root[x] = get_root(root[x]); } void combine_root(int x, int y) { int u = get_root(x); int v = get_root(y); if (u != v) { if (root_size[u] > root_size[v]) { root[v] = u; root_size[u] += root_size[v]; } else { root[u] = v; root_size[v] += root_size[u]; } } } // UnionFind int kruskal(vector< vector<int> >& edge, int n) { stable_sort(edge.begin(),edge.end()); init_root(n); int cost = 0; for(auto x: edge) { if(get_root(x[1]) != get_root(x[2])) { cost += x[0]; combine_root(x[1], x[2]); } } return cost; } int main() { int n,m; cin>>n>>m; vector< vector<int> >edge; for(int i=1; i<=m; i++) { int u,v,w; cin>>u>>v>>w; edge.push_back({w,v,u}); } cout<<kruskal(edge, n); }
15,294
https://github.com/joohncruz/venice/blob/master/packages/react-ds/src/components/SplitButton/SplitButton.tsx
Github Open Source
Open Source
Apache-2.0
2,020
venice
joohncruz
TSX
Code
127
435
import * as React from 'react' import classNames from 'classnames/bind' import { ISplitButton } from '@venice/core/models' import styles from '@venice/styles/components/SplitButton.module.scss' import Button from '../Button/Button' interface ISplitButtonProps extends ISplitButton { /** React Element */ children: React.ReactNode } const SplitButton: React.FC<ISplitButtonProps> = ({ text, children, color = 'default', size = 'large', direction = 'rtl', isFitMenu = false, openType = 'hover', ...props }: ISplitButtonProps) => { const [isOpen, setIsOpen] = React.useState(false) const clickType = openType === 'click' && isOpen const navClassNames = classNames(styles.splitButton, styles[openType], { [styles.active]: clickType, }) const menuClassNames = classNames( styles.dropdown, styles[size], styles[color], styles[direction], { [styles.fitbutton]: isFitMenu } ) return ( <nav className={navClassNames} {...props}> <Button className={styles['inner-button']} color={color} size={size} aria-expanded={isOpen} onClick={() => setIsOpen(!isOpen)} > {text} <span className={styles.caret}></span> </Button> <div className={menuClassNames} role="menu"> {children} </div> </nav> ) } export default SplitButton
27,776
https://github.com/geoffreywatson/proj/blob/master/build.sbt
Github Open Source
Open Source
Apache-2.0
2,017
proj
geoffreywatson
Scala
Code
55
253
name := """proj""" version := "2.6.x" lazy val root = (project in file(".")).enablePlugins(PlayScala) scalaVersion := "2.12.2" libraryDependencies ++= Seq( cache, ws, guice, "mysql" % "mysql-connector-java" % "5.1.34", "com.typesafe.play" %% "play-slick" % "3.0.0-M5", "com.typesafe.play" %% "play-slick-evolutions" % "3.0.0-M5", "com.typesafe.play" %% "play-mailer" % "6.0.0", "com.typesafe.play" %% "play-mailer-guice" % "6.0.0", "org.scalatestplus.play" %% "scalatestplus-play" % "3.0.0" % Test )
20,097
https://github.com/tomi44g/freETarget/blob/master/Software/C#/freETarget/Shot.cs
Github Open Source
Open Source
MIT
2,020
freETarget
tomi44g
C#
Code
263
767
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace freETarget { class Shot { public int index; public int count; public decimal x; public decimal y; public decimal radius; public decimal angle; public int score; public decimal decimalScore; public bool innerTen; public DateTime timestamp; public void computeScore(Session.TargetType type) { //using liner interpolation with the "official" values found here: http://targettalk.org/viewtopic.php?p=100591#p100591 if (type == Session.TargetType.Pistol) { double score = linearInterpolation(ISSF.pistol1X, ISSF.pistol1Y, ISSF.pistol2X, ISSF.pistol2Y, (float)this.radius); this.decimalScore = (decimal)(Math.Truncate(score * 10)) / 10m; this.decimalScore += 0.0m; //add a decimal is the result is an integer if (this.decimalScore < 1) { //shot outside the target this.decimalScore = 0; } this.score = (int)Math.Floor(this.decimalScore); //determine if inner ten (X) if (this.radius <= ISSF.innerTenRadiusPistol) { this.innerTen = true; } else { this.innerTen = false; } } else if (type == Session.TargetType.Rifle) { double score = linearInterpolation(ISSF.rifle1X, ISSF.rifle1Y, ISSF.rifle2X, ISSF.rifle2Y, (float)this.radius); this.decimalScore = (decimal)(Math.Truncate(score * 10)) / 10m; this.decimalScore += 0.0m; //add a decimal is the result is an integer if (this.decimalScore >= 11m) { //the linear interpolation returns 11.000003814 for 0 (dead centre) this.decimalScore = 10.9m; } if (this.decimalScore < 1) {//shot outside the target this.decimalScore = 0; } this.score = (int)Math.Floor(this.decimalScore); //determine if inner ten (X) if (this.radius <= ISSF.innerTenRadiusRifle) { this.innerTen = true; } else { this.innerTen = false; } } else { Console.WriteLine("Unknown current target " + type); } } private double linearInterpolation(float x1, float y1, float x2, float y2, float x) { double y = ((x2 - x) * y1 + (x - x1) * y2) / (x2 - x1); return y; } } }
32,062
https://github.com/DecentraCorp/dc_contracts/blob/master/contracts/DScore.sol
Github Open Source
Open Source
MIT
null
dc_contracts
DecentraCorp
Solidity
Code
1,094
2,560
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./interfaces/IDecentraCore.sol"; import "./interfaces/IDecentraStock.sol"; import "./interfaces/IDScore.sol"; //////////////////////////////////////////////////////////////////////////////////////////// /// @title DScore /// @author Christopher Dixon //////////////////////////////////////////////////////////////////////////////////////////// contract DScore is Ownable, IDScore { using SafeMath for uint256; ///stakedCounter is a tracker for the total number of DecentraStock staked uint256 public stakedCounter; /// @notice ds is the DecentraStock contract IDecentraStock public ds; /// @notice dc is the DecentraCore contract IDecentraCore public dc; ///@notice members tracks a members D-Score to their address mapping(address => DScoreTracker) public members; /** @notice the modifier onlyMember requires that the function caller must be a member of the DAO to call a function @dev this requires the caller to have atleast 1e18 of a token(standard 1 for ERC20's) **/ modifier onlyDSmod() { require( dc.dScoreMod(msg.sender), "DecentraCore: Caller is not a DScore MOD" ); _; } constructor(address _dStock) { ds = IDecentraStock(_dStock); } function setDC(address _dCore) external onlyOwner { dc = IDecentraCore(_dCore); } /** @notice DScoreTracker is a struct used to store a Decentracorp members D-Score parameters @param level is a members level that is determined by the DecentraCorp community as a way of rewarding members for non D-job related tasks such as a technical task, community service, or other work related reward. @param jobs is the number of completed jobs done by the member. @param votes is the number of DecentraCorp votes the member has participated in. @param reputation is the overall average of the rating of each job performed. @param staked is the number of DercentraStock a member has staked @param verified is the number of times this member has been audited by other members @param audit is the number of other members this account has audited */ struct DScoreTracker { uint256 level; uint256 jobs; uint256 votes; uint256 reputation; uint256 staked; uint256 verified; uint256 audit; } /** @notice stakeMembership allows a user to stake DecentraStock in-order to become a Decentracorp member @param _stakeAmount is the amount of DecentraStock being staked on the users membership */ function stakeMembership(uint256 _stakeAmount) external override { dc.proxyBurnDS(msg.sender, _stakeAmount); DScoreTracker storage dscore = members[msg.sender]; dscore.staked = dscore.staked.add(_stakeAmount); emit MembershipStaked(msg.sender, _stakeAmount); } /** @notice increaseDScore is a protected function that allows approved DecentraCorp contracts to increase a users D-Score @param _member is the address of the member who's D-Score is being increased @param _factor is the number representing which factor of the users D-Score is being increased @param _amount is the amount the user's D-Score is being increased by @dev D-Score factors are represented by a number within a mapping. The key for this mapping is as follows: 0 - Level: a members level is determined by the DecentraCorp community as a way of rewarding members for non D-job related tasks such as a technical task, community service, or other work related reward. 1 - Jobs: the number of completed jobs done by the member. 2 - Votes: the number of DecentraCorp votes the member has participated in. 3 - Reputation: the overall average of the rating of each job performed. 4 - Staked: the number of DercentraStock a member has staked 5 - Verified: number of times this member has been audited by other members 6 - Audit: number of other members this account has audited */ function increaseDScore( address _member, uint256 _factor, uint256 _amount ) public override onlyDSmod { require(_factor < 7, "D-Score: Invalid factor"); DScoreTracker storage dscore = members[msg.sender]; if (_factor == 0) { dscore.level = dscore.level.add(_amount); } if (_factor == 1) { dscore.jobs = dscore.jobs.add(_amount); } if (_factor == 2) { dscore.votes = dscore.votes.add(_amount); } if (_factor == 3) { dscore.reputation = dscore.reputation.add(_amount); } if (_factor == 4) { dscore.staked = dscore.staked.add(_amount); } if (_factor == 5) { dscore.verified = dscore.verified.add(_amount); } if (_factor == 6) { dscore.audit = dscore.audit.add(_amount); } emit DScoreIncreased(_member, _factor, _amount); } /** @notice increaseDScore is a protected function that allows approved DecentraCorp contracts to decrease a users D-Score @param _member is the address of the member who's D-Score is being decrease @param _factor is the number representing which factor of the users D-Score is being decrease @param _amount is the amount the user's D-Score is being decrease by */ function decreaseDScore( address _member, uint256 _factor, uint256 _amount ) public override onlyDSmod { require(_factor < 7, "D-Score: Invalid factor"); DScoreTracker storage dscore = members[msg.sender]; if (_factor == 0) { dscore.level = dscore.level.sub(_amount); } if (_factor == 1) { dscore.jobs = dscore.jobs.sub(_amount); } if (_factor == 2) { dscore.votes = dscore.votes.sub(_amount); } if (_factor == 3) { dscore.reputation = dscore.reputation.sub(_amount); } if (_factor == 4) { dscore.staked = dscore.staked.sub(_amount); } if (_factor == 5) { dscore.verified = dscore.verified.sub(_amount); } if (_factor == 6) { dscore.audit = dscore.audit.sub(_amount); } emit DScoreDecreased(_member, _factor, _amount); } /** @notice calculateVotingPower is used to calculate a members current voting power relative to their D-Score @param _member is the address of the member who's voting power is being retreived */ function calculateVotingPower(address _member) external view override returns (uint256) { DScoreTracker storage dscore = members[_member]; uint256 bal = ds.balanceOf(_member); uint256 ts = ds.totalSupply(); uint256 ratio = _balanceStake(bal, ts); uint256 balancer; if (ratio > 10) { balancer = 10; } else { balancer = ratio; } uint256 baseScore = balancer .add(dscore.reputation) .add(dscore.audit) .add(dscore.staked); baseScore = baseScore.add(dscore.votes).add(dscore.level).add( dscore.jobs ); return baseScore; } /** @notice checkStaked is a view only function to easily check if an account is a staked member @param _member is the address in question @dev this function returns a bool for "yes staked" or "not staked". This function does NOT return the amount a member has staked */ function checkStaked(address _member) external view override returns (bool) { DScoreTracker storage dscore = members[_member]; if (dscore.staked > 0) { return true; } else { return false; } } /** @notice getDscore returns a users DScore data @param _member is the address of the member whos DScore is being retreived */ function getDscore(address _member) external view returns ( uint256 level, uint256 jobs, uint256 votes, uint256 reputation, uint256 staked, uint256 verified, uint256 audit ) { DScoreTracker storage dscore = members[_member]; level = dscore.level; jobs = dscore.jobs; votes = dscore.votes; reputation = dscore.reputation; staked = dscore.staked; verified = dscore.verified; audit = dscore.audit; } /** @notice _balanceStake is an internal function used to calculate the ratio between a given numerator && denominator @param _numerator is the numerator of the equation @param _denominator is the denominator of the equation **/ function _balanceStake(uint256 _numerator, uint256 _denominator) internal pure returns (uint256 quotient) { // caution, check safe-to-multiply here uint256 numerator = _numerator * 10**(2 + 1); // with rounding of last digit uint256 _quotient = ((numerator / _denominator) + 5) / 10; return (_quotient); } }
49,203
https://github.com/CodeTanzania/emis-web/blob/master/src/GeographicalFeatures/components/EvacuationCenters/List/index.js
Github Open Source
Open Source
MIT
2,020
emis-web
CodeTanzania
JavaScript
Code
133
407
import { List } from 'antd'; import PropTypes from 'prop-types'; import React from 'react'; import EvacuationCenterListHeader from '../ListHeader'; import EvacuationCenterListItem from '../ListItem'; /** * @function * @name EvacuationCenterList * @description Render Evacuation Center list * * @param {object} props props object * @param {boolean} props.loading preload list of Evacuation Center * @param {Array} props.districts array list of Evacuation Center * @param {Function} props.onEdit function for editing Evacuation Center * * @returns {object} React component * * @version 0.1.0 * @since 0.1.0 */ const EvacuationCenterList = ({ evacuationCenters, loading, onEdit }) => ( <> <EvacuationCenterListHeader /> <List loading={loading} dataSource={evacuationCenters} renderItem={evacuationCenter => ( <EvacuationCenterListItem key={evacuationCenter.name} name={evacuationCenter.name} type={evacuationCenter.type} onEdit={() => onEdit(evacuationCenter)} /> )} /> </> ); EvacuationCenterList.propTypes = { onEdit: PropTypes.func.isRequired, loading: PropTypes.bool.isRequired, evacuationCenters: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string, type: PropTypes.string, }) ).isRequired, }; export default EvacuationCenterList;
15,918
https://github.com/fatman2021/E6510CPU/blob/master/examples/manual/defines/fbcygwin.bas
Github Open Source
Open Source
BSD-2-Clause
null
E6510CPU
fatman2021
Visual Basic
Code
43
128
'' examples/manual/defines/fbcygwin.bas '' '' NOTICE: This file is part of the FreeBASIC Compiler package and can't '' be included in other distributions without authorization. '' '' See Also: http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgDdfbcygwin '' -------- #ifdef __FB_CYGWIN__ '...instructions only for Cygwin... #else '...instructions not for Cygwin... #endif
51,021
https://github.com/gbartoczevicz/next-vaccination/blob/master/packages/server/http-server/prisma/migrations/20210610012600_create_cancellations_table/migration.sql
Github Open Source
Open Source
MIT
2,021
next-vaccination
gbartoczevicz
SQL
Code
117
361
/* Warnings: - A unique constraint covering the columns `[appointment_id]` on the table `conclusions` will be added. If there are existing duplicate values, this will fail. */ -- CreateTable CREATE TABLE "cancellations" ( "id" VARCHAR(50) NOT NULL, "reason" TEXT NOT NULL, "canceled_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "appointment_id" VARCHAR(50) NOT NULL, "cancelated_by_id" VARCHAR(50) NOT NULL, PRIMARY KEY ("id") ); -- CreateIndex CREATE UNIQUE INDEX "conclusions_appointment_id_unique" ON "conclusions"("appointment_id"); -- CreateIndex CREATE UNIQUE INDEX "cancellations.cancelated_by_id_unique" ON "cancellations"("cancelated_by_id"); -- CreateIndex CREATE UNIQUE INDEX "cancellations_appointment_id_unique" ON "cancellations"("appointment_id"); -- AddForeignKey ALTER TABLE "cancellations" ADD FOREIGN KEY ("appointment_id") REFERENCES "appointments"("id") ON DELETE CASCADE ON UPDATE CASCADE; -- AddForeignKey ALTER TABLE "cancellations" ADD FOREIGN KEY ("cancelated_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
17,152
https://github.com/microsoft/onnxruntime/blob/master/onnxruntime/core/mlas/lib/amd64/FgemmKernelCommon.inc
Github Open Source
Open Source
MIT
2,023
onnxruntime
microsoft
Assembly
Code
812
2,533
;++ ; ; Copyright (c) Microsoft Corporation. All rights reserved. ; ; Licensed under the MIT License. ; ; Module Name: ; ; FgemmKernelCommon.inc ; ; Abstract: ; ; This module contains common kernel macros and structures for the floating ; point matrix/matrix multiply operation (SGEMM and DGEMM). ; ;-- ; ; Stack frame layout for the floating point kernels. ; FgemmKernelFrame STRUCT SavedXmm6 OWORD ? SavedXmm7 OWORD ? SavedXmm8 OWORD ? SavedXmm9 OWORD ? SavedXmm10 OWORD ? SavedXmm11 OWORD ? SavedXmm12 OWORD ? SavedXmm13 OWORD ? SavedXmm14 OWORD ? SavedXmm15 OWORD ? Padding QWORD ? SavedR12 QWORD ? SavedR13 QWORD ? SavedR14 QWORD ? SavedR15 QWORD ? SavedRdi QWORD ? SavedRsi QWORD ? SavedRbx QWORD ? SavedRbp QWORD ? ReturnAddress QWORD ? PreviousP1Home QWORD ? PreviousP2Home QWORD ? PreviousP3Home QWORD ? PreviousP4Home QWORD ? CountM QWORD ? CountN QWORD ? lda QWORD ? ldc QWORD ? Alpha QWORD ? ZeroMode QWORD ? FgemmKernelFrame ENDS ; ; Define the number of elements per vector register. ; FgemmXmmElementCount EQU (16 / FgemmElementSize) FgemmYmmElementCount EQU (32 / FgemmElementSize) FgemmZmmElementCount EQU (64 / FgemmElementSize) ; ; Macro Description: ; ; This macro implements the common prologue code for the SGEMM and DGEMM ; kernels. ; ; Arguments: ; ; Isa - Supplies the instruction set architecture string. ; ; Return Registers: ; ; rax - Stores the length in bytes of a row from matrix C. ; ; rsi - Stores the address of the matrix A data. ; ; rbp - Stores the CountN argument from the stack frame. ; ; r10 - Stores the length in bytes of a row from matrix A. ; ; r11 - Stores the CountM argument from the stack frame. ; ; rbx, rsi, rdi - Previous values stored on the stack and the registers ; are available as temporaries. ; ; r15 - Stores the ZeroMode argument from the stack frame. ; FgemmKernelEntry MACRO Isa rex_push_reg rbp push_reg rbx push_reg rsi push_reg rdi push_reg r15 alloc_stack (FgemmKernelFrame.SavedR15) IFIDNI <Isa>, <Avx512F> save_reg r12,FgemmKernelFrame.SavedR12 save_reg r13,FgemmKernelFrame.SavedR13 save_reg r14,FgemmKernelFrame.SavedR14 ENDIF save_xmm128 xmm6,FgemmKernelFrame.SavedXmm6 save_xmm128 xmm7,FgemmKernelFrame.SavedXmm7 save_xmm128 xmm8,FgemmKernelFrame.SavedXmm8 save_xmm128 xmm9,FgemmKernelFrame.SavedXmm9 save_xmm128 xmm10,FgemmKernelFrame.SavedXmm10 save_xmm128 xmm11,FgemmKernelFrame.SavedXmm11 save_xmm128 xmm12,FgemmKernelFrame.SavedXmm12 save_xmm128 xmm13,FgemmKernelFrame.SavedXmm13 save_xmm128 xmm14,FgemmKernelFrame.SavedXmm14 save_xmm128 xmm15,FgemmKernelFrame.SavedXmm15 END_PROLOGUE IFDIFI <Isa>, <Sse> vzeroall ENDIF mov rsi,rcx mov rbp,FgemmKernelFrame.CountN[rsp] mov rax,FgemmKernelFrame.ldc[rsp] shl rax,FgemmElementShift ; convert ldc to bytes mov r10,FgemmKernelFrame.lda[rsp] shl r10,FgemmElementShift ; convert lda to bytes mov r11,FgemmKernelFrame.CountM[rsp] movzx r15,BYTE PTR FgemmKernelFrame.ZeroMode[rsp] ENDM ; ; Macro Description: ; ; This macro implements the common epilogue code for the SGEMM and DGEMM ; kernels. ; ; Arguments: ; ; Isa - Supplies the instruction set architecture string. ; ; Implicit Arguments: ; ; r11d - Stores the number of rows handled. ; FgemmKernelExit MACRO Isa mov eax,r11d movaps xmm6,FgemmKernelFrame.SavedXmm6[rsp] movaps xmm7,FgemmKernelFrame.SavedXmm7[rsp] movaps xmm8,FgemmKernelFrame.SavedXmm8[rsp] movaps xmm9,FgemmKernelFrame.SavedXmm9[rsp] movaps xmm10,FgemmKernelFrame.SavedXmm10[rsp] movaps xmm11,FgemmKernelFrame.SavedXmm11[rsp] movaps xmm12,FgemmKernelFrame.SavedXmm12[rsp] movaps xmm13,FgemmKernelFrame.SavedXmm13[rsp] movaps xmm14,FgemmKernelFrame.SavedXmm14[rsp] movaps xmm15,FgemmKernelFrame.SavedXmm15[rsp] IFIDNI <Isa>, <Avx512F> mov r12,FgemmKernelFrame.SavedR12[rsp] mov r13,FgemmKernelFrame.SavedR13[rsp] mov r14,FgemmKernelFrame.SavedR14[rsp] ENDIF add rsp,(FgemmKernelFrame.SavedR15) BEGIN_EPILOGUE pop r15 pop rdi pop rsi pop rbx pop rbp ret ENDM ; ; Macro Description: ; ; This macro generates code to execute the block compute macro multiple ; times and advancing the matrix A and matrix B data pointers. ; ; Arguments: ; ; ComputeBlock - Supplies the macro to compute a single block. ; ; RowCount - Supplies the number of rows to access from matrix A. ; ; AdvanceMatrixAPlusRows - Supplies a non-zero value if the data pointer ; in rbx should also be advanced as part of the loop. ; ; Implicit Arguments: ; ; rbx - Supplies the address into the matrix A data plus N rows. ; ; rcx - Supplies the address into the matrix A data. ; ; rdx - Supplies the address into the matrix B data. ; ; r9 - Supplies the number of columns from matrix A and the number of rows ; from matrix B to iterate over. ; ; ymm4-ymm15 - Supplies the block accumulators. ; ComputeBlockLoop MACRO ComputeBlock, RowCount, AdvanceMatrixAPlusRows LOCAL ComputeBlockBy4Loop LOCAL ProcessRemainingBlocks LOCAL ComputeBlockBy1Loop LOCAL OutputBlock mov rdi,r9 ; reload CountK sub rdi,4 jb ProcessRemainingBlocks ComputeBlockBy4Loop: ComputeBlock RowCount, 0, FgemmElementSize*0, 64*4 ComputeBlock RowCount, 2*32, FgemmElementSize*1, 64*4 add_immed rdx,2*2*32 ; advance matrix B by 128 bytes ComputeBlock RowCount, 0, FgemmElementSize*2, 64*4 ComputeBlock RowCount, 2*32, FgemmElementSize*3, 64*4 add_immed rdx,2*2*32 ; advance matrix B by 128 bytes add rcx,4*FgemmElementSize ; advance matrix A by 4 elements IF AdvanceMatrixAPlusRows add rbx,4*FgemmElementSize ; advance matrix A plus rows by 4 elements IF RowCount GE 12 add r13,4*FgemmElementSize add r14,4*FgemmElementSize ENDIF ENDIF sub rdi,4 jae ComputeBlockBy4Loop ProcessRemainingBlocks: add rdi,4 ; correct for over-subtract above jz OutputBlock ComputeBlockBy1Loop: ComputeBlock RowCount, 0, 0 add rdx,2*32 ; advance matrix B by 64 bytes add rcx,FgemmElementSize ; advance matrix A by 1 element IF AdvanceMatrixAPlusRows add rbx,FgemmElementSize ; advance matrix A plus rows by 1 element IF RowCount GE 12 add r13,FgemmElementSize add r14,FgemmElementSize ENDIF ENDIF dec rdi jne ComputeBlockBy1Loop OutputBlock: ENDM
19,269
https://github.com/huzaifasabir/alBurhanMetal/blob/master/application/controllers/ExpenseController.php
Github Open Source
Open Source
MIT
null
alBurhanMetal
huzaifasabir
PHP
Code
275
1,093
<?php class ExpenseController extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('expense'); $this->load->library('session'); } /* function for manage Expense. return all Expenses. created by your name created at 31-08-20. */ public function manageExpense() { $data1["expenses"] = $this->expense->getAllCategory(); $data['pageContent'] = $this->load->view('expense/manage-expense', $data1, TRUE); $data['pageTitle'] = "Expense"; $this->load->view('main', $data); // $this->load->view('expense/manage-expense', $data); } /* function for add Expense get created by your name created at 31-08-20. */ public function addExpense() { $data['pageContent'] = $this->load->view('expense/add-expense','', TRUE); $data['pageTitle'] = "Expense"; $this->load->view('main', $data); } /* function for add Expense post created by your name created at 31-08-20. */ public function addExpensePost() { $data['id'] = $this->input->post('id'); $data['category'] = $this->input->post('category'); $this->expense->insert($data); $this->session->set_flashdata('success', 'Expense added Successfully'); redirect('manage-expense'); } /* function for edit Expense get returns Expense by id. created by your name created at 31-08-20. */ public function editExpense($expense_id) { $data1['expense_id'] = $expense_id; $data1['expense'] = $this->expense->getDataById($expense_id); //$this->load->view('expense/edit-expense', $data); $data['pageContent'] = $this->load->view('expense/edit-expense', $data1, TRUE); $data['pageTitle'] = "Expense"; $this->load->view('main', $data); } /* function for edit Expense post created by your name created at 31-08-20. */ public function editExpensePost() { $expense_id = $this->input->post('expense_id'); $expense = $this->expense->getDataById($expense_id); $data['id'] = $this->input->post('id'); $data['category'] = $this->input->post('category'); $edit = $this->expense->update($expense_id,$data); if ($edit) { $this->session->set_flashdata('success', 'Expense Updated'); redirect('manage-expense'); } } /* function for view Expense get created by your name created at 31-08-20. */ public function viewExpense($expense_id) { $data['expense_id'] = $expense_id; $data['expense'] = $this->expense->getDataById($expense_id); $this->load->view('expense/view-expense', $data); } /* function for delete Expense created by your name created at 31-08-20. */ public function deleteExpense($expense_id) { $delete = $this->expense->delete($expense_id); $this->session->set_flashdata('success', 'expense deleted'); redirect('manage-expense'); } /* function for activation and deactivation of Expense. created by your name created at 31-08-20. */ public function changeStatusExpense($expense_id) { $edit = $this->expense->changeStatus($expense_id); $this->session->set_flashdata('success', 'expense '.$edit.' Successfully'); redirect('manage-expense'); } }
17,941
https://github.com/joseluis8906/chaletapp/blob/master/proxy/src/app.js
Github Open Source
Open Source
MIT
null
chaletapp
joseluis8906
JavaScript
Code
13
75
import redbird from 'redbird'; var proxy = redbird({port: 3000}); proxy.register('localhost:3000/', 'http://127.0.0.1:3003/'); proxy.register('localhost:3000/backend', 'http://127.0.0.1:3004/');
12,005
https://github.com/IBM-Security/ibm-application-gateway-resources/blob/master/python/packages/ibm_application_gateway/config/version.py
Github Open Source
Open Source
Apache-2.0
null
ibm-application-gateway-resources
IBM-Security
Python
Code
298
890
# coding: utf-8 """ IBM Application Gateway Configuration Specification (OpenAPI) No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: 21.12 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six class Version(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ allowed enum values """ _19_12 = "19.12" _20_01 = "20.01" _20_04 = "20.04" _20_07 = "20.07" _20_09 = "20.09" _20_12 = "20.12" _21_02 = "21.02" _21_04 = "21.04" _21_06 = "21.06" _21_09 = "21.09" _21_12 = "21.12" allowable_values = [_19_12, _20_01, _20_04, _20_07, _20_09, _20_12, _21_02, _21_04, _21_06, _21_09, _21_12] # noqa: E501 """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { } attribute_map = { } def __init__(self): # noqa: E501 """Version - a model defined in OpenAPI""" # noqa: E501 self.discriminator = None def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, Version): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, Version): return True return self.to_dict() != other.to_dict()
31,687
https://github.com/NSOiO/MLN/blob/master/MLN-iOS/MLN/Classes/MUICore/Protocol/MLNUIErrorHandlerProtocol.h
Github Open Source
Open Source
MIT
2,020
MLN
NSOiO
Objective-C
Code
76
320
// // MLNUIErrorHandlerProtocol.h // MLNUICore // // Created by MoMo on 2019/8/1. // #ifndef MLNUIErrorHandlerProtocol_h #define MLNUIErrorHandlerProtocol_h @class MLNUILuaCore; /** 错误处理协议 */ @protocol MLNUIErrorHandlerProtocol <NSObject> /** 是否处理Assert @param luaCore 当前Lua内核 @return YES / NO */ - (BOOL)canHandleAssert:(MLNUILuaCore *)luaCore; /** 出现错误 @param luaCore 当前Lua内核 @param error 错误信息 */ - (void)luaCore:(MLNUILuaCore *)luaCore error:(NSString *)error; /** 出现错误 @param luaCore 当前Lua内核 @param error 错误信息 @param luaTraceback 当前Lua中的调用栈信息 */ - (void)luaCore:(MLNUILuaCore *)luaCore luaError:(NSString *)error luaTraceback:(NSString *)luaTraceback; @end #endif /* MLNUIErrorHandlerProtocolN_h */
42,406
https://github.com/davenewcomb/f4d-vvv/blob/master/www/wp_baycare/public_html/wp-content/plugins/popover/css/tpl/cabriolet/style.php
Github Open Source
Open Source
MIT
null
f4d-vvv
davenewcomb
PHP
Code
10
29
<?php $info->name = __( 'Cabriolet', 'popover' ); $info->pro = true;
30,463
https://github.com/achristensen6/tvOS130Headers/blob/master/System/Library/PrivateFrameworks/SlideshowKit.framework/PlugIns/OpusMagazineProducer.opplugin/OKAutoLayoutLiveFeedContext.h
Github Open Source
Open Source
MIT
2,019
tvOS130Headers
achristensen6
Objective-C
Code
134
435
/* * This header is generated by classdump-dyld 1.0 * on Tuesday, November 5, 2019 at 2:45:02 AM Mountain Standard Time * Operating System: Version 13.0 (Build 17J586) * Image Source: /System/Library/PrivateFrameworks/SlideshowKit.framework/PlugIns/OpusMagazineProducer.opplugin/OpusMagazineProducer * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @class NSMutableDictionary, NSString; @interface OKAutoLayoutLiveFeedContext : NSObject { NSMutableDictionary* _layoutInfos; NSString* _primaryResolutionKey; long long _pagesGenerated; long long _mediasUsed; } @property (nonatomic,retain) NSMutableDictionary * layoutInfos; //@synthesize layoutInfos=_layoutInfos - In the implementation block @property (nonatomic,retain) NSString * primaryResolutionKey; //@synthesize primaryResolutionKey=_primaryResolutionKey - In the implementation block @property (assign,nonatomic) long long pagesGenerated; //@synthesize pagesGenerated=_pagesGenerated - In the implementation block @property (assign,nonatomic) long long mediasUsed; //@synthesize mediasUsed=_mediasUsed - In the implementation block -(void)setPagesGenerated:(long long)arg1 ; -(void)setPrimaryResolutionKey:(NSString *)arg1 ; -(NSString *)primaryResolutionKey; -(void)setMediasUsed:(long long)arg1 ; -(NSMutableDictionary *)layoutInfos; -(long long)mediasUsed; -(void)setLayoutInfos:(NSMutableDictionary *)arg1 ; -(long long)pagesGenerated; -(void)dealloc; @end
4,662
https://github.com/yuripourre-forks/GeoRegression/blob/master/main/test/georegression/geometry/polygon/TestCyclicalLinkedList.java
Github Open Source
Open Source
Apache-2.0
null
GeoRegression
yuripourre-forks
Java
Code
270
962
/* * Copyright (C) 2020, Peter Abeles. All Rights Reserved. * * This file is part of Geometric Regression Library (GeoRegression). * * 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 georegression.geometry.polygon; import org.ddogleg.struct.DogLinkedList; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * @author Peter Abeles */ @SuppressWarnings("ConstantConditions") public class TestCyclicalLinkedList { @Test void pushHead() { var alg = new CyclicalLinkedList<Integer>(); alg.pushHead(0); assertEquals(0, alg.getHead().object); assertEquals(1, alg.size()); alg.pushHead(1); assertEquals(2, alg.size()); DogLinkedList.Element<Integer> e = alg.getHead(); assertEquals(1, e.object); assertEquals(0, e.next.object); assertSame(e, e.next.next); assertSame(e, e.prev.prev); assertSame(e.next, alg.getTail()); } @Test void pushTail() { var alg = new CyclicalLinkedList<Integer>(); alg.pushTail(0); assertEquals(0, alg.getHead().object); assertEquals(1, alg.size()); alg.pushTail(1); assertEquals(2, alg.size()); DogLinkedList.Element<Integer> e = alg.getHead(); assertEquals(0, e.object); assertEquals(1, e.next.object); assertSame(e, e.next.next); assertSame(e, e.prev.prev); assertSame(e.next, alg.getTail()); } @Test void remove() { var alg = new CyclicalLinkedList<Integer>(); // see if it handles removing the last object correctly alg.pushHead(0); alg.remove(alg.getHead()); assertEquals(0, alg.size()); assertNull(alg.getHead()); assertNull(alg.getTail()); // Remove an object in the middle alg.pushHead(0); alg.pushHead(1); alg.pushHead(2); DogLinkedList.Element<Integer> e = alg.getHead(); alg.remove(e.next); assertEquals(2,alg.size()); assertSame(e,alg.getHead()); assertSame(e.next,alg.getTail()); assertSame(e, e.next.next); assertSame(e, e.prev.prev); // Remove an object at the head. make it size=3 to be more interesting alg.pushHead(3); assertEquals(3, alg.size()); alg.remove(alg.getHead()); assertEquals(2, alg.size()); assertSame(e,alg.getHead()); assertSame(e.prev, alg.getTail()); assertSame(e.next, alg.getTail()); } }
28,980
https://github.com/dhis2/d2-ui-analytics/blob/master/src/components/PeriodDimension/__tests__/PeriodSelector.spec.js
Github Open Source
Open Source
BSD-3-Clause
2,021
d2-ui-analytics
dhis2
JavaScript
Code
75
198
import { shallow } from 'enzyme' import React from 'react' import PeriodTransfer from '../PeriodTransfer.js' describe('The Period Selector component', () => { let props let shallowPeriodTransfer const getWrapper = () => { if (!shallowPeriodTransfer) { shallowPeriodTransfer = shallow(<PeriodTransfer {...props} />) } return shallowPeriodTransfer } beforeEach(() => { props = { initialSelectedPeriods: [], onSelect: jest.fn(), rightFooter: <></>, dataTest: 'period-dimension', } shallowPeriodTransfer = undefined }) it('matches the snapshot', () => { const wrapper = getWrapper() expect(wrapper).toMatchSnapshot() }) })
43,292
https://github.com/iliyaST/TelerikAcademy/blob/master/OOP/3-Extension-Methods-Delegates-Lambda-LINQ/03-05.StudentsInArray/ArrayOfStudents.cs
Github Open Source
Open Source
MIT
2,017
TelerikAcademy
iliyaST
C#
Code
189
456
using System; using System.Linq; namespace StudentsInArray { class ArrayOfStudents { static void Main() { //Array of students var students = new[] { new { FirstName = "Gandalf", LastName = "The Grey", age = 18}, new { FirstName = "Gandalf", LastName = "The White", age = 24}, new { FirstName = "Spider Man", LastName = "The Red", age = 56}, new { FirstName = "Spider Man", LastName = "The Black", age = 21}, new { FirstName = "Iron Man", LastName = "The Red", age = 16}, }; //Select students var selectedStudentsByFirstAndLastName = from student in students where student.FirstName.CompareTo(student.LastName) < 0 select student; //print them foreach (var student in selectedStudentsByFirstAndLastName) { Console.WriteLine(student.LastName + " " + student.FirstName); } //select by age var selectedStudentByAge = from student in students where student.age >= 18 && student.age <= 24 orderby student.age select student; foreach (var student in selectedStudentByAge) { Console.WriteLine(student); } //Order by and than by (sort the array using lampda) var sortedArrayOfStudents = students.OrderByDescending(x => x.FirstName) .ThenByDescending(x => x.LastName); //Order by and than by using LINQ var sortedArrayOfStudentsLINQ = from student in students orderby student.FirstName descending, student.LastName descending select student; } } }
7,338
https://github.com/kontab/google-cloud-dotnet/blob/master/apis/Google.Cloud.Spanner.Data/Google.Cloud.Spanner.Data/SpannerCommandTextBuilder.cs
Github Open Source
Open Source
Apache-2.0
null
google-cloud-dotnet
kontab
C#
Code
1,311
3,516
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; using System.Text; using Google.Api.Gax; // ReSharper disable UnusedParameter.Local namespace Google.Cloud.Spanner.Data { /// <summary> /// Builds the <see cref="SpannerCommand.CommandText"/> string for executing a query or operation /// on a Spanner database. /// </summary> public sealed class SpannerCommandTextBuilder { private const string InsertCommand = "INSERT"; private const string InsertUpdateCommand = "INSERTUPDATE"; private const string UpdateCommand = "UPDATE"; private const string DeleteCommand = "DELETE"; private const string SelectCommand = "SELECT"; private const string AlterCommand = "ALTER"; private const string CreateCommand = "CREATE"; private const string DropCommand = "DROP"; //TODO(benwu): verify if whitespace between CREATE/DROP and DB is allowed. private const string CreateDatabaseCommand = "CREATE DATABASE "; private const string DropDatabaseCommand = "DROP DATABASE "; private string _targetTable; /// <summary> /// Gets the resulting string to be used for <see cref="SpannerCommand.CommandText"/>. /// </summary> public string CommandText { get; private set; } /// <summary> /// Gets the type of Spanner command (Select, Update, Delete, InsertOrUpdate, Insert, Ddl). /// </summary> public SpannerCommandType SpannerCommandType { get; private set; } /// <summary> /// Gets the target Spanner database table if the command is Update, Delete, InsertOrUpdate, /// or Insert /// </summary> public string TargetTable { get => _targetTable; private set { ValidateTable(value); _targetTable = value; } } /// <summary> /// Initializes a new SpannerCommandTextBuilder with the given command text. /// The given text will be analyzed to choose the proper <see cref="SpannerCommandType"/>. /// </summary> /// <param name="commandText">The command text intended for <see cref="SpannerCommand.CommandText"/> /// If the intended <see cref="SpannerCommandType"/> is Select, then this string should be /// a SQL Query. If the intended <see cref="SpannerCommandType"/> is Ddl, then this string should be /// the Ddl statement (eg 'CREATE TABLE MYTABLE...') /// If the intended <see cref="SpannerCommandType"/> is Update, Delete, /// InsertOrUpdate, or Insert, then the text should be '[spannercommandtype] [tablename]' /// such as 'INSERT MYTABLE'. Must not be null. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="commandText"/> is null.</exception> /// <exception cref="InvalidOperationException"> /// Thrown when <paramref name="commandText"/> is not formatted correctly.</exception> public SpannerCommandTextBuilder(string commandText) { GaxPreconditions.CheckNotNullOrEmpty(commandText, nameof(commandText)); var commandSections = commandText.Trim().Split(' '); if (commandSections.Length < 2) { throw new InvalidOperationException($"'{commandText}' is not a recognized Spanner command."); } if (!TryParseCommand(this, DeleteCommand, SpannerCommandType.Delete, commandSections) && !TryParseCommand(this, UpdateCommand, SpannerCommandType.Update, commandSections) && !TryParseCommand(this, InsertCommand, SpannerCommandType.Insert, commandSections) && !TryParseCommand(this, InsertUpdateCommand, SpannerCommandType.InsertOrUpdate, commandSections)) { if (string.Equals(commandSections[0], SelectCommand, StringComparison.OrdinalIgnoreCase)) { CommandText = commandText; SpannerCommandType = SpannerCommandType.Select; } else if (IsDdl(commandSections[0])) { CommandText = commandText; SpannerCommandType = SpannerCommandType.Ddl; } else { throw new InvalidOperationException($"'{commandText}' is not a recognized Spanner command."); } } } private static bool IsDdl(string commandPart) { // These three form the ddl for spanner. // For reference: https://cloud.google.com/spanner/docs/data-definition-language return string.Equals(commandPart, CreateCommand, StringComparison.OrdinalIgnoreCase) || string.Equals(commandPart, AlterCommand, StringComparison.OrdinalIgnoreCase) || string.Equals(commandPart, DropCommand, StringComparison.OrdinalIgnoreCase); } internal bool IsCreateDatabaseCommand => CommandText?.StartsWith(CreateDatabaseCommand, StringComparison.OrdinalIgnoreCase) ?? false; internal bool IsDropDatabaseCommand => CommandText?.StartsWith(DropDatabaseCommand, StringComparison.OrdinalIgnoreCase) ?? false; internal string DatabaseToDrop { get { if (!IsDropDatabaseCommand) { return ""; } string commandText = CommandText; var dbName = new StringBuilder(); int i = DropDatabaseCommand.Length; for (; i < commandText.Length; i++) { if (char.IsWhiteSpace(commandText[i]) || commandText[i] == ';') { // if we see a whitespace after the dbname, we'll just bail. if (dbName.Length > 0) { break; } // keep looking for the start of the db name. continue; } dbName.Append(commandText[i]); } //ensure the rest of the string is whitespace while (i < commandText.Length) { if (!char.IsWhiteSpace(commandText[i]) && commandText[i] != ';') { throw new InvalidOperationException($"Could not parse the database to drop in `{CommandText}`."); } i++; } return dbName.ToString(); } } /// <summary> /// </summary> private SpannerCommandTextBuilder() { } /// <summary> /// Creates a <see cref="SpannerCommandTextBuilder"/> instance that generates <see cref="SpannerCommand.CommandText"/> /// for deleting rows. /// </summary> /// <param name="table">The name of the Spanner database table from which rows will be deleted. /// Must not be null.</param> /// <returns>A <see cref="SpannerCommandTextBuilder"/> representing a <see cref="F:SpannerCommandType.Delete"/> Spanner command.</returns> public static SpannerCommandTextBuilder CreateDeleteTextBuilder(string table) { ValidateTable(table); return new SpannerCommandTextBuilder { SpannerCommandType = SpannerCommandType.Delete, TargetTable = table, CommandText = $"{DeleteCommand} {table}" }; } /// <summary> /// Creates a <see cref="SpannerCommandTextBuilder"/> instance that generates <see cref="SpannerCommand.CommandText"/> /// for inserting or updating rows. /// </summary> /// <param name="table">The name of the Spanner database table from which rows will be updated or inserted. /// Must not be null.</param> /// <returns>A <see cref="SpannerCommandTextBuilder"/> representing a <see cref="F:SpannerCommandType.InsertOrUpdate"/> Spanner command.</returns> public static SpannerCommandTextBuilder CreateInsertOrUpdateTextBuilder(string table) { ValidateTable(table); return new SpannerCommandTextBuilder { SpannerCommandType = SpannerCommandType.InsertOrUpdate, TargetTable = table, CommandText = $"{InsertUpdateCommand} {table}" }; } /// <summary> /// Creates a <see cref="SpannerCommandTextBuilder"/> instance that generates <see cref="SpannerCommand.CommandText"/> /// for inserting rows. /// </summary> /// <param name="table">The name of the Spanner database table from which rows will be inserted. Must not be null.</param> /// <returns>A <see cref="SpannerCommandTextBuilder"/> representing a <see cref="F:SpannerCommandType.Insert"/> Spanner command.</returns> public static SpannerCommandTextBuilder CreateInsertTextBuilder(string table) { ValidateTable(table); return new SpannerCommandTextBuilder { SpannerCommandType = SpannerCommandType.Insert, TargetTable = table, CommandText = $"{InsertCommand} {table}" }; } /// <summary> /// Creates a <see cref="SpannerCommandTextBuilder"/> instance that generates <see cref="SpannerCommand.CommandText"/> /// for querying rows via a SQL query. /// </summary> /// <param name="sqlQuery">The full SQL query. Must not be null.</param> /// <returns>A <see cref="SpannerCommandTextBuilder"/> representing a <see cref="F:SpannerCommandType.Select"/> Spanner command.</returns> public static SpannerCommandTextBuilder CreateSelectTextBuilder(string sqlQuery) => new SpannerCommandTextBuilder { SpannerCommandType = SpannerCommandType.Select, CommandText = sqlQuery }; /// <summary> /// Creates a <see cref="SpannerCommandTextBuilder"/> instance that generates <see cref="SpannerCommand.CommandText"/> /// for updating rows. /// </summary> /// <param name="table">The name of the Spanner database table from which rows will be updated. Must not be null.</param> /// <returns>A <see cref="SpannerCommandTextBuilder"/> representing a <see cref="F:SpannerCommandType.Update"/> Spanner command.</returns> public static SpannerCommandTextBuilder CreateUpdateTextBuilder(string table) { ValidateTable(table); return new SpannerCommandTextBuilder { SpannerCommandType = SpannerCommandType.Update, TargetTable = table, CommandText = $"{UpdateCommand} {table}" }; } /// <summary> /// Creates a <see cref="SpannerCommandTextBuilder"/> instance that generates <see cref="SpannerCommand.CommandText"/> /// for executing a DDL statement. /// </summary> /// <param name="ddlStatement">The full DDL statement. Must not be null.</param> /// <param name="extraDdlStatements">An optional set of additional DDL statements to execute after /// the first statement. Extra Ddl statements cannot be used to create additional databases.</param> /// <returns>A <see cref="SpannerCommandTextBuilder"/> representing a <see cref="F:SpannerCommandType.Ddl"/> Spanner command.</returns> public static SpannerCommandTextBuilder CreateDdlTextBuilder(string ddlStatement, params string[] extraDdlStatements) { return new SpannerCommandTextBuilder { SpannerCommandType = SpannerCommandType.Ddl, CommandText = ddlStatement, ExtraStatements = extraDdlStatements }; } /// <summary> /// A set of additional statements to execute if supported by the command. /// </summary> public string[] ExtraStatements { get; private set; } /// <summary> /// Creates a <see cref="SpannerCommandTextBuilder"/> instance by parsing existing command text. /// </summary> /// <param name="commandText">The full command text containing a query, ddl statement or insert/update/delete /// operation. The given text will be parsed and validated. Must not be null.</param> /// <returns>A <see cref="SpannerCommandTextBuilder"/> whose <see cref="SpannerCommandType"/> is determined /// from parsing <paramref name="commandText"/>.</returns> public static SpannerCommandTextBuilder FromCommandText(string commandText) { GaxPreconditions.CheckNotNullOrEmpty(commandText, nameof(commandText)); return new SpannerCommandTextBuilder(commandText); } /// <inheritdoc /> public override string ToString() => CommandText; private static bool TryParseCommand( SpannerCommandTextBuilder newbuilder, string commandToParseFor, SpannerCommandType commandType, string[] commandSections) { string operationName = commandSections[0].ToUpperInvariant(); if (operationName == commandToParseFor) { if (commandSections.Length != 2) { throw new InvalidOperationException( $"Spanner {commandToParseFor} commands are specified as '{commandToParseFor} <table>' with " + "parameters added to customize the command with filtering or updated values."); } newbuilder.CommandText = $"{commandToParseFor} {commandSections[1]}"; newbuilder.SpannerCommandType = commandType; newbuilder.TargetTable = commandSections[1]; return true; } return false; } private static void ValidateTable(string databaseTableName) { GaxPreconditions.CheckNotNullOrEmpty(databaseTableName, nameof(databaseTableName)); if (!databaseTableName.All(c => char.IsLetterOrDigit(c) || c == '_')) { throw new ArgumentException($"{nameof(databaseTableName)} only allows letters, numbers or underscore"); } } } }
40,640
https://github.com/ggodlewski/labjack_kiplin/blob/master/ljswitchboard-module_manager/lib/switchboard_modules/device_overview/controller-new.js
Github Open Source
Open Source
MIT
2,021
labjack_kiplin
ggodlewski
JavaScript
Code
729
2,686
var LABJACK_OVERVIEW_IMG_SRC = 'https://raw.githubusercontent.com/Samnsparky/ljswitchboard/master/src/static/img/T7-cartoon.png'; var DEVICE_IMAGE_X_OFFSET = 150; var DEVICE_IMAGE_Y_OFFSET = 10; var DEVICE_IMG_WIDTH = 225; var DEVICE_IMG_HEIGHT = 525; var LINE_X_OFFSET = 100; var LINE_Y_OFFSET = 6; var DEVICE_IMAGE_X_OVERLAP = 30; var CONNECTOR_SIZE_X = DEVICE_IMAGE_X_OFFSET + DEVICE_IMAGE_X_OVERLAP; var REGISTER_DISPLAY_ID_TEMPLATE = Handlebars.compile('#{{register}}-display'); var TRANSLATE_TEMPLATE = Handlebars.compile('translate({{x}},{{y}})'); var REGISTER_OVERLAY_SPEC = [ {register: 'AIN0', yLocation: 0.783, type: null, board: 'device', side: 'left'}, {register: 'AIN1', yLocation: 0.757, type: null, board: 'device', side: 'left'}, {register: 'AIN2', yLocation: 0.664, type: null, board: 'device', side: 'left'}, {register: 'AIN3', yLocation: 0.639, type: null, board: 'device', side: 'left'}, {register: 'DAC0', yLocation: 0.545, type: 'dac', board: 'device', side: 'left'}, {register: 'DAC1', yLocation: 0.519, type: 'dac', board: 'device', side: 'left'}, {register: 'FIO0', yLocation: 0.426, type: 'fio', board: 'device', side: 'left'}, {register: 'FIO1', yLocation: 0.403, type: 'fio', board: 'device', side: 'left'}, {register: 'FIO2', yLocation: 0.308, type: 'fio', board: 'device', side: 'left'}, {register: 'FIO3', yLocation: 0.283, type: 'fio', board: 'device', side: 'left'}, {register: 'AIN1', yLocation: 0.900-0.01, type: null, board: 'connector', side: 'left'}, {register: 'AIN3', yLocation: 0.875-0.01, type: null, board: 'connector', side: 'left'}, {register: 'AIN5', yLocation: 0.850-0.01, type: null, board: 'connector', side: 'left'}, {register: 'AIN7', yLocation: 0.825-0.01, type: null, board: 'connector', side: 'left'}, {register: 'AIN9', yLocation: 0.800-0.01, type: null, board: 'connector', side: 'left'}, {register: 'AIN11', yLocation: 0.775-0.01, type: null, board: 'connector', side: 'left'}, {register: 'AIN13', yLocation: 0.750-0.01, type: null, board: 'connector', side: 'left'}, {register: 'DAC0', yLocation: 0.725-0.01, type: 'dac', board: 'connector', side: 'left'}, {register: 'MIO1', yLocation: 0.625-0.015, type: 'fio', board: 'connector', side: 'left'}, {register: 'FIO0', yLocation: 0.600-0.015, type: 'fio', board: 'connector', side: 'left'}, {register: 'FIO2', yLocation: 0.575-0.015, type: 'fio', board: 'connector', side: 'left'}, {register: 'FIO4', yLocation: 0.550-0.015, type: 'fio', board: 'connector', side: 'left'}, {register: 'FIO6', yLocation: 0.525-0.015, type: 'fio', board: 'connector', side: 'left'}, {register: 'EIO6', yLocation: 0.275+0.020, type: 'fio', board: 'connector', side: 'left'}, {register: 'EIO4', yLocation: 0.250+0.020, type: 'fio', board: 'connector', side: 'left'}, {register: 'EIO2', yLocation: 0.225+0.020, type: 'fio', board: 'connector', side: 'left'}, {register: 'EIO0', yLocation: 0.200+0.020, type: 'fio', board: 'connector', side: 'left'}, {register: 'CIO1', yLocation: 0.175+0.020, type: 'fio', board: 'connector', side: 'left'}, {register: 'CIO3', yLocation: 0.150+0.020, type: 'fio', board: 'connector', side: 'left'}, {register: 'AIN0', yLocation: 0.900 + 0.005, type: null, board: 'connector', side: 'right'}, {register: 'AIN2', yLocation: 0.875 + 0.005, type: null, board: 'connector', side: 'right'}, {register: 'AIN4', yLocation: 0.850 + 0.005, type: null, board: 'connector', side: 'right'}, {register: 'AIN6', yLocation: 0.825 + 0.005, type: null, board: 'connector', side: 'right'}, {register: 'AIN8', yLocation: 0.800 + 0.003, type: null, board: 'connector', side: 'right'}, {register: 'AIN10', yLocation: 0.775 + 0.003, type: null, board: 'connector', side: 'right'}, {register: 'AIN12', yLocation: 0.750 + 0.003, type: null, board: 'connector', side: 'right'}, {register: 'DAC1', yLocation: 0.700, type: 'dac', board: 'connector', side: 'right'}, {register: 'MIO2', yLocation: 0.625, type: 'dac', board: 'connector', side: 'right'}, {register: 'MIO0', yLocation: 0.600, type: 'dac', board: 'connector', side: 'right'}, {register: 'FIO1', yLocation: 0.575, type: 'dac', board: 'connector', side: 'right'}, {register: 'FIO3', yLocation: 0.550, type: 'dac', board: 'connector', side: 'right'}, {register: 'FIO5', yLocation: 0.525, type: 'dac', board: 'connector', side: 'right'}, {register: 'FIO7', yLocation: 0.500, type: 'dac', board: 'connector', side: 'right'}, {register: 'EIO7', yLocation: 0.300+0.010, type: 'fio', board: 'connector', side: 'right'}, {register: 'EIO5', yLocation: 0.275+0.010, type: 'fio', board: 'connector', side: 'right'}, {register: 'EIO3', yLocation: 0.250+0.010, type: 'fio', board: 'connector', side: 'right'}, {register: 'EIO1', yLocation: 0.225+0.010, type: 'fio', board: 'connector', side: 'right'}, {register: 'CIO2', yLocation: 0.175+0.010, type: 'fio', board: 'connector', side: 'right'}, {register: 'CIO0', yLocation: 0.150+0.010, type: 'fio', board: 'connector', side: 'right'} ]; var getOverlayYPos = function (registerInfo) { var yFromTopOfImage = registerInfo.yLocation * DEVICE_IMG_HEIGHT; return DEVICE_IMAGE_Y_OFFSET + yFromTopOfImage; }; var getOverlayYPosWithPx = function (registerInfo) { return getOverlayYPos(registerInfo) + 'px'; } var drawDevice = function () { // Add the image to the DIV containing the device visualization var image = d3.select('#device-display-container-svg') .append('image') .attr('xlink:href', LABJACK_OVERVIEW_IMG_SRC) .attr('x', DEVICE_IMAGE_X_OFFSET) .attr('y', DEVICE_IMAGE_Y_OFFSET) .attr('width', DEVICE_IMG_WIDTH) .attr('height', DEVICE_IMG_HEIGHT); var lineGroup = d3.select('#device-display-container-svg') .selectAll('.connector-line') .data(function () { return REGISTER_OVERLAY_SPEC.filter(function (registerInfo) { return registerInfo.board === 'device'; }); }) .enter() .append('g') .attr('transform', function (registerInfo) { var y = getOverlayYPos(registerInfo); return TRANSLATE_TEMPLATE({x: 0, y: y}); }); lineGroup.append('line') .attr('x1', LINE_X_OFFSET) .attr('y1', 0) .attr('x2', CONNECTOR_SIZE_X) .attr('y2', 0) .attr('stroke', 'white') .attr('stroke-width', 3); lineGroup.append('line') .attr('x1', LINE_X_OFFSET) .attr('y1', 0) .attr('x2', CONNECTOR_SIZE_X) .attr('y2', 0) .attr('stroke', 'black') .attr('stroke-width', 1); // Create a DIV for each of the registers for the main device var overlays = d3.select('#device-display-container') .selectAll('.register-overlay') .data(function () { return REGISTER_OVERLAY_SPEC.filter(function (registerInfo) { return registerInfo.board === 'device'; }); }) .enter() .append('div') .attr('class', 'register-overlay') .style('top', getOverlayYPosWithPx); overlays.append('span') .attr('id', function (registerInfo) { return REGISTER_DISPLAY_ID_TEMPLATE(registerInfo); }) .html(function (registerInfo, i) { return i; }); }; drawDevice();
42,593
https://github.com/mabuprojects/mbr-publicApp/blob/master/src/app/pages/singin-page/singin.component.js
Github Open Source
Open Source
MIT
null
mbr-publicApp
mabuprojects
JavaScript
Code
214
734
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var core_1 = require('@angular/core'); var forms_1 = require("@angular/forms"); var SinginComponent = (function () { function SinginComponent(fb, authenticationService, router) { this.fb = fb; this.authenticationService = authenticationService; this.router = router; this.error = false; this.errorMessage = ''; } SinginComponent.prototype.ngOnInit = function () { this.myForm = this.fb.group({ email: ['', forms_1.Validators.compose([ forms_1.Validators.required, forms_1.Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")])], password: ['', forms_1.Validators.required], }); }; SinginComponent.prototype.onSignin = function () { var _this = this; console.log("eoooo"); this.authenticationService.singin(this.myForm.controls['email'].value, this.myForm.controls['password'].value).subscribe(function (result) { if (result) { _this.router.navigate(['/']); } else { } }, function (err) { _this.error = true; _this.errorMessage = 'Username or password is incorrect'; }); }; SinginComponent = __decorate([ core_1.Component({ selector: 'app-singin', templateUrl: './singin.component.html', styles: ['.top-margin {margin-top: 10%;}'] }) ], SinginComponent); return SinginComponent; }()); exports.SinginComponent = SinginComponent;
37,360
https://github.com/twitter-zuiwanyuan/http4s/blob/master/project/Http4sBuild.scala
Github Open Source
Open Source
Apache-2.0
null
http4s
twitter-zuiwanyuan
Scala
Code
555
2,210
import sbt._ import Keys._ import scala.util.Properties.envOrNone object Http4sBuild { def extractApiVersion(version: String) = { val VersionExtractor = """(\d+)\.(\d+)\..*""".r version match { case VersionExtractor(major, minor) => (major.toInt, minor.toInt) } } lazy val sonatypeEnvCredentials = (for { user <- envOrNone("SONATYPE_USER") pass <- envOrNone("SONATYPE_PASS") } yield Credentials("Sonatype Nexus Repository Manager", "oss.sonatype.org", user, pass)).toSeq def compatibleVersion(version: String, scalazVersion: String) = { val currentVersionWithoutSnapshot = version.replaceAll("-SNAPSHOT$", "") val (targetMajor, targetMinor) = extractApiVersion(version) val targetVersion = scalazCrossBuild(s"${targetMajor}.${targetMinor}.0", scalazVersion) if (targetVersion != currentVersionWithoutSnapshot) Some(targetVersion) else None } val macroParadiseSetting = libraryDependencies ++= Seq( Seq(compilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full)), VersionNumber(scalaVersion.value).numbers match { case Seq(2, 10, _*) => Seq(quasiquotes) case _ => Seq.empty } ).flatten def scalazCrossBuild(version: String, scalazVersion: String) = VersionNumber(scalazVersion).numbers match { case Seq(7, 1, _*) => version case Seq(7, 2, _*) => if (version.endsWith("-SNAPSHOT")) version.replaceFirst("-SNAPSHOT$", "a-SNAPSHOT") else s"${version}a" } def specs2Version(scalazVersion: String) = VersionNumber(scalazVersion).numbers match { case Seq(7, 1, _*) => "3.8.5-scalaz-7.1.10" case Seq(7, 2, _*) => "3.8.5" } lazy val alpnBoot = "org.mortbay.jetty.alpn" % "alpn-boot" % "8.1.9.v20160720" def argonaut(scalazVersion: String) = "io.argonaut" %% "argonaut" % scalazCrossBuild("6.1", scalazVersion) def argonautShapeless(scalazVersion: String) = "com.github.alexarchambault" %% "argonaut-shapeless_6.1" % (VersionNumber(scalazVersion).numbers match { case Seq(7, 1, _*) => "1.1.0" case Seq(7, 2, _*) => "1.1.1" }) lazy val asyncHttpClient = "org.asynchttpclient" % "async-http-client" % "2.0.12" lazy val blaze = "org.http4s" %% "blaze-http" % "0.12.1" lazy val circeGeneric = "io.circe" %% "circe-generic" % circeJawn.revision lazy val circeJawn = "io.circe" %% "circe-jawn" % "0.5.1" lazy val discipline = "org.typelevel" %% "discipline" % "0.5" lazy val gatlingTest = "io.gatling" % "gatling-test-framework" % "2.2.1" lazy val gatlingHighCharts = "io.gatling.highcharts" % "gatling-charts-highcharts" % gatlingTest.revision lazy val http4sWebsocket = "org.http4s" %% "http4s-websocket" % "0.1.3" lazy val javaxServletApi = "javax.servlet" % "javax.servlet-api" % "3.1.0" lazy val jawnJson4s = "org.spire-math" %% "jawn-json4s" % jawnParser.revision lazy val jawnParser = "org.spire-math" %% "jawn-parser" % "0.8.4" def jawnStreamz(scalazVersion: String) = "org.http4s" %% "jawn-streamz" % scalazCrossBuild("0.9.0", scalazVersion) lazy val jettyServer = "org.eclipse.jetty" % "jetty-server" % "9.3.12.v20160915" lazy val jettyServlet = "org.eclipse.jetty" % "jetty-servlet" % jettyServer.revision lazy val json4sCore = "org.json4s" %% "json4s-core" % "3.4.0" lazy val json4sJackson = "org.json4s" %% "json4s-jackson" % json4sCore.revision lazy val json4sNative = "org.json4s" %% "json4s-native" % json4sCore.revision lazy val jspApi = "javax.servlet.jsp" % "javax.servlet.jsp-api" % "2.3.1" // YourKit hack lazy val log4s = "org.log4s" %% "log4s" % "1.3.0" lazy val logbackClassic = "ch.qos.logback" % "logback-classic" % "1.1.7" lazy val macroCompat = "org.typelevel" %% "macro-compat" % "1.1.1" lazy val metricsCore = "io.dropwizard.metrics" % "metrics-core" % "3.1.2" lazy val metricsJson = "io.dropwizard.metrics" % "metrics-json" % metricsCore.revision lazy val parboiled = "org.parboiled" %% "parboiled" % "2.1.2" lazy val quasiquotes = "org.scalamacros" %% "quasiquotes" % "2.1.0" lazy val reactiveStreamsTck = "org.reactivestreams" % "reactive-streams-tck" % "1.0.0" def scalaCompiler(sv: String) = "org.scala-lang" % "scala-compiler" % sv def scalaReflect(sv: String) = "org.scala-lang" % "scala-reflect" % sv lazy val scalaXml = "org.scala-lang.modules" %% "scala-xml" % "1.0.5" def scalazCore(version: String) = "org.scalaz" %% "scalaz-core" % version def scalazScalacheckBinding(version: String) = "org.scalaz" %% "scalaz-scalacheck-binding" % version def specs2Core(scalazVersion: String) = "org.specs2" %% "specs2-core" % specs2Version(scalazVersion) def specs2MatcherExtra(scalazVersion: String) = "org.specs2" %% "specs2-matcher-extra" % specs2Core(scalazVersion).revision def specs2Scalacheck(scalazVersion: String) = "org.specs2" %% "specs2-scalacheck" % specs2Core(scalazVersion).revision def scalazStream(scalazVersion: String) = "org.scalaz.stream" %% "scalaz-stream" % scalazCrossBuild("0.8.4", scalazVersion) lazy val tomcatCatalina = "org.apache.tomcat" % "tomcat-catalina" % "8.0.37" lazy val tomcatCoyote = "org.apache.tomcat" % "tomcat-coyote" % tomcatCatalina.revision lazy val twirlApi = "com.typesafe.play" %% "twirl-api" % "1.2.0" lazy val cryptbits = "org.reactormonk" %% "cryptobits" % "1.0" }
44,053
https://github.com/ayonadee/prizegenerator/blob/master/projectwo/coreservice/application/models.py
Github Open Source
Open Source
MIT
null
prizegenerator
ayonadee
Python
Code
26
114
from application import db class Users(db.Model): id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(30), nullable=False) last_name = db.Column(db.String(30), nullable=False) account_number = db.Column(db.String(15), nullable=False) message = db.Column(db.String(300), nullable=False)
46,664
https://github.com/dvsa/olcs-transfer/blob/master/src/Command/Scan/CreateDocument.php
Github Open Source
Open Source
MIT
2,018
olcs-transfer
dvsa
PHP
Code
93
348
<?php /** * CreateDocument - used by the olcs-scanning service to add scanned documents */ namespace Dvsa\Olcs\Transfer\Command\Scan; use Dvsa\Olcs\Transfer\Util\Annotation as Transfer; use Dvsa\Olcs\Transfer\Command\AbstractCommand; use Dvsa\Olcs\Transfer\Command\LoggerOmitContentInterface; /** * @Transfer\RouteName("backend/scan/create-document") * @Transfer\Method("POST") */ final class CreateDocument extends AbstractCommand implements LoggerOmitContentInterface { /** * @Transfer\Filter({"name":"Laminas\Filter\Digits"}) * @Transfer\Validator({"name":"Laminas\Validator\Digits"}) * @Transfer\Validator({"name":"Laminas\Validator\GreaterThan", "options": {"min": 0}}) */ protected $scanId; protected $content; protected $filename; /** * @return int */ public function getScanId() { return $this->scanId; } /** * @return mixed */ public function getContent() { return $this->content; } /** * @return mixed */ public function getFilename() { return $this->filename; } }
24,669
https://github.com/yffd/easy-parent/blob/master/easy-framework-web/src/main/java/com/yffd/easy/framework/web/mvc/model/RespModel.java
Github Open Source
Open Source
Apache-2.0
null
easy-parent
yffd
Java
Code
140
448
package com.yffd.easy.framework.web.mvc.model; import java.io.Serializable; import com.yffd.easy.framework.pojo.IPOJO; /** * * @Description 系统响应信息的标准类. * @Date 2017年8月7日 下午2:18:45 <br/> * @author zhangST * @version 1.0 * @since JDK 1.7+ * @see */ public class RespModel implements IPOJO, Serializable { /** * serialVersionUID:TODO(用一句话描述这个变量表示什么). * @since JDK 1.7+ */ private static final long serialVersionUID = -1521500074035646023L; /** 响应状态码 */ private String status; /** 请求方式,同步、异步 */ private String type; /** 提示信息 */ private String msg; /** 数据信息 */ private Object data; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
14,792
https://github.com/plobod/react-performance-testing/blob/master/example/src/list/Item.tsx
Github Open Source
Open Source
MIT
2,021
react-performance-testing
plobod
TSX
Code
24
63
import React from 'react'; interface Props { item: string; } export const Item = React.memo(function Item({ item, }: Props): React.ReactElement { return <li>{item}</li>; });
42,458
https://github.com/vmx/flexi_logger/blob/master/tests/test_reconfigure_methods.rs
Github Open Source
Open Source
Apache-2.0, MIT
2,021
flexi_logger
vmx
Rust
Code
333
1,356
use flexi_logger::{Logger, ReconfigurationHandle}; use log::*; #[test] fn test_reconfigure_methods() { let mut log_handle = Logger::with_str("info") .log_to_file() .start() .unwrap_or_else(|e| panic!("Logger initialization failed with {}", e)); test_parse_new_spec(&mut log_handle); test_push_new_spec(&mut log_handle); validate_logs(&mut log_handle); } fn test_parse_new_spec(log_handle: &mut ReconfigurationHandle) { error!("1-error message"); warn!("1-warning"); info!("1-info message"); debug!("1-debug message - you must not see it!"); trace!("1-trace message - you must not see it!"); log_handle.parse_new_spec("error"); error!("1-error message"); warn!("1-warning - you must not see it!"); info!("1-info message - you must not see it!"); debug!("1-debug message - you must not see it!"); trace!("1-trace message - you must not see it!"); log_handle.parse_new_spec("trace"); error!("1-error message"); warn!("1-warning"); info!("1-info message"); debug!("1-debug message"); trace!("1-trace message"); log_handle.parse_new_spec("info"); } #[allow(clippy::cognitive_complexity)] fn test_push_new_spec(log_handle: &mut ReconfigurationHandle) { error!("2-error message"); warn!("2-warning"); info!("2-info message"); debug!("2-debug message - you must not see it!"); trace!("2-trace message - you must not see it!"); log_handle.parse_and_push_temp_spec("error"); error!("2-error message"); warn!("2-warning - you must not see it!"); info!("2-info message - you must not see it!"); debug!("2-debug message - you must not see it!"); trace!("2-trace message - you must not see it!"); log_handle.parse_and_push_temp_spec("trace"); error!("2-error message"); warn!("2-warning"); info!("2-info message"); debug!("2-debug message"); trace!("2-trace message"); log_handle.pop_temp_spec(); // we should be back on error error!("2-error message"); warn!("2-warning - you must not see it!"); info!("2-info message - you must not see it!"); debug!("2-debug message - you must not see it!"); trace!("2-trace message - you must not see it!"); log_handle.pop_temp_spec(); // we should be back on info error!("2-error message"); warn!("2-warning"); info!("2-info message"); debug!("2-debug message - you must not see it!"); trace!("2-trace message - you must not see it!"); log_handle.pop_temp_spec(); // should be a no-op } #[allow(clippy::cognitive_complexity)] fn validate_logs(log_handle: &mut ReconfigurationHandle) { log_handle.validate_logs(&[ ("ERROR", "test_reconfigure_methods", "1-error"), ("WARN", "test_reconfigure_methods", "1-warning"), ("INFO", "test_reconfigure_methods", "1-info"), // ("ERROR", "test_reconfigure_methods", "1-error"), // ("ERROR", "test_reconfigure_methods", "1-error"), ("WARN", "test_reconfigure_methods", "1-warning"), ("INFO", "test_reconfigure_methods", "1-info"), ("DEBUG", "test_reconfigure_methods", "1-debug"), ("TRACE", "test_reconfigure_methods", "1-trace"), // ----- ("ERROR", "test_reconfigure_methods", "2-error"), ("WARN", "test_reconfigure_methods", "2-warning"), ("INFO", "test_reconfigure_methods", "2-info"), // ("ERROR", "test_reconfigure_methods", "2-error"), // ("ERROR", "test_reconfigure_methods", "2-error"), ("WARN", "test_reconfigure_methods", "2-warning"), ("INFO", "test_reconfigure_methods", "2-info"), ("DEBUG", "test_reconfigure_methods", "2-debug"), ("TRACE", "test_reconfigure_methods", "2-trace"), // ("ERROR", "test_reconfigure_methods", "2-error"), // ("ERROR", "test_reconfigure_methods", "2-error"), ("WARN", "test_reconfigure_methods", "2-warning"), ("INFO", "test_reconfigure_methods", "2-info"), ]); }
45,822
https://github.com/weaversa/sbsat/blob/master/src/solvers/funcsat/src/funcsat/config.h
Github Open Source
Open Source
BSD-3-Clause
2,020
sbsat
weaversa
C
Code
435
890
/* src/funcsat/config.h. Generated from config.h.in by configure. */ /* src/funcsat/config.h.in. Generated from configure.ac by autoheader. */ /* Define to 1 to compile in level-based logging. */ /* #undef FUNCSAT_LOG */ /* Define to 1 if you have the <dlfcn.h> header file. */ #define HAVE_DLFCN_H 1 /* Define to 1 if you have the <inttypes.h> header file. */ #define HAVE_INTTYPES_H 1 /* Define to 1 if you have the `z' library (-lz). */ #define HAVE_LIBZ 1 /* Define to 1 if you have the <limits.h> header file. */ #define HAVE_LIMITS_H 1 /* Define to 1 if you have the <memory.h> header file. */ #define HAVE_MEMORY_H 1 /* Define to 1 if stdbool.h conforms to C99. */ #define HAVE_STDBOOL_H 1 /* Define to 1 if you have the <stdint.h> header file. */ #define HAVE_STDINT_H 1 /* Define to 1 if you have the <stdlib.h> header file. */ #define HAVE_STDLIB_H 1 /* Define to 1 if you have the <strings.h> header file. */ #define HAVE_STRINGS_H 1 /* Define to 1 if you have the <string.h> header file. */ #define HAVE_STRING_H 1 /* Define to 1 if you have the <sys/resource.h> header file. */ #define HAVE_SYS_RESOURCE_H 1 /* Define to 1 if you have the <sys/stat.h> header file. */ #define HAVE_SYS_STAT_H 1 /* Define to 1 if you have the <sys/types.h> header file. */ #define HAVE_SYS_TYPES_H 1 /* Define to 1 if you have the <unistd.h> header file. */ #define HAVE_UNISTD_H 1 /* Define to 1 if you have the <zlib.h> header file. */ #define HAVE_ZLIB_H 1 /* Define to 1 if the system has the type `_Bool'. */ #define HAVE__BOOL 1 /* Define to the sub-directory where libtool stores uninstalled libraries. */ #define LT_OBJDIR ".libs/" /* Define to 1 if assertions should be disabled. */ /* #undef NDEBUG */ /* Name of package */ #define PACKAGE "funcsat" /* Define to the address where bug reports for this package should be sent. */ #define PACKAGE_BUGREPORT "denis.bueno@sandia.gov" /* Define to the full name of this package. */ #define PACKAGE_NAME "funcsat" /* Define to the full name and version of this package. */ #define PACKAGE_STRING "funcsat 2.14" /* Define to the one symbol short name of this package. */ #define PACKAGE_TARNAME "funcsat" /* Define to the home page for this package. */ #define PACKAGE_URL "" /* Define to the version of this package. */ #define PACKAGE_VERSION "2.14" /* Define to 1 if the `S_IS*' macros in <sys/stat.h> do not work properly. */ /* #undef STAT_MACROS_BROKEN */ /* Define to 1 if you have the ANSI C header files. */ #define STDC_HEADERS 1 /* Version number of package */ #define VERSION "2.14"
35,719
https://github.com/patil215/v8/blob/master/fuzzer_output/interesting/sample_1554095911699.js
Github Open Source
Open Source
BSD-3-Clause
null
v8
patil215
JavaScript
Code
27
70
function main() { Function[10] = Function; let v3 = "undefined"; let v7 = 0; v7 = 10; const v11 = [1337]; Function[1073741824] = v11; } %NeverOptimizeFunction(main); main();
43,954
https://github.com/ul-gaul/Avionique_Software/blob/master/BaseStation/src/ui/config_controller.py
Github Open Source
Open Source
MIT
2,019
Avionique_Software
ul-gaul
Python
Code
191
719
import configparser import sys import glob import serial from src.ui.setting_data import SettingData class ConfigController: def __init__(self, chemin_fichier): self.file_path = chemin_fichier self.config = configparser.ConfigParser() self.config.read(self.file_path) def save_to_file(self): with open(self.file_path, 'w') as f: self.config.write(f) def set_value(self, section, name, value): self.config[section][name] = value def get_value(self, section, name): return self.config[section][name] def get_parsed_sections(self): return self.config.sections() def get_sections(self): return set(self.get_parsed_sections() + self.get_dynamic_sections()) def get_settings(self, section=None): settings = {} if section in self.get_parsed_sections(): settings = { name: SettingData(name, value, section=section) for (name, value) in self.config[section].items() } if section in self.get_dynamic_sections(): settings.update(self.get_dynamic_settings(section)) return settings.values() def get_dynamic_sections(self): return ['serial_port'] def get_dynamic_settings(self, section_name): settings = {'serial_port': { 'port_com': SettingData('port_com', input_type='list', choices=self._get_serial_port_options(), section='serial_port') }} return settings.get(section_name) def _get_serial_port_options(self): return self.detect_serial_ports() @staticmethod def detect_serial_ports(): """ Lists serial port names :raises EnvironmentError On unsupported or unknown platforms :returns: A list of the serial ports available on the system """ if sys.platform.startswith('win'): ports = ['COM%s' % (i + 1) for i in range(256)] elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'): # this excludes your current terminal "/dev/tty" ports = glob.glob('/dev/tty[A-Za-z]*') elif sys.platform.startswith('darwin'): ports = glob.glob('/dev/tty.*') else: raise EnvironmentError('Unsupported platform') result = [] for port in ports: try: s = serial.Serial(port) s.close() result.append(port) except (OSError, serial.SerialException): pass return result
4,454
https://github.com/Mahmoudhadidi/GestionEcole/blob/master/src/ForumBundle/Repository/ReponseRepository.php
Github Open Source
Open Source
MIT
null
GestionEcole
Mahmoudhadidi
PHP
Code
147
519
<?php namespace ForumBundle\Repository; use Doctrine\ORM\EntityRepository; /** * ReponseRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class ReponseRepository extends EntityRepository { public function supprimerReponse() { $conn = $this->getEntityManager()->getConnection(); $b=$_GET['idReponse']; $sql = " DELETE FROM Reponse WHERE id= $b "; $stmt = $conn->prepare($sql); $stmt->execute(); } public function repondre($id,$reponse){ $query = $this->getEntityManager() ->createQuery(" UPDATE ForumBundle:reponse e SET e.reponse=:reponse where e.id=:id ") ->setParameter('id', $id) ->setParameter('reponse',$reponse); return $query->getResult(); } public function modifierReponse() { $conn = $this->getEntityManager()->getConnection(); $b=$_GET['idReponse']; $sql = " Edit FROM Reponse WHERE id= $b "; $stmt = $conn->prepare($sql); $stmt->execute(); } public function findByReponse($reponse,$date,$id_Q ) { $conn = $this->getEntityManager()->getConnection(); $sql = "INSERT INTO Reponse ( reponse, date, id_ques) VALUES ( '$reponse' , '$date' , $id_Q ); "; $stmt = $conn->prepare($sql); $stmt->execute(); } public function findreponse($idQ) { $query=$this->getEntityManager() ->createQuery("SELECT a FROM ForumBundle:Reponse a WHERE a.idQues='$idQ' "); return $query->getResult(); } }
27,823
https://github.com/DeAccountSystems/das-database/blob/master/timer/timer.go
Github Open Source
Open Source
MIT
2,021
das-database
DeAccountSystems
Go
Code
129
577
package timer import ( "context" "das_database/chain/chain_ckb" "das_database/dao" "github.com/scorpiotzh/mylog" "sync" "time" ) var log = mylog.NewLogger("timer", mylog.LevelDebug) // ParserTimer type ParserTimer struct { dbDao *dao.DbDao ctx context.Context wg *sync.WaitGroup ckbClient *chain_ckb.Client } type ParserTimerParam struct { DbDao *dao.DbDao Ctx context.Context Wg *sync.WaitGroup CkbClient *chain_ckb.Client } func NewParserTimer(p ParserTimerParam) *ParserTimer { var t ParserTimer t.dbDao = p.DbDao t.ctx = p.Ctx t.wg = p.Wg t.ckbClient = p.CkbClient return &t } func (p *ParserTimer) Run() error { p.updateTokenMap() tickerToken := time.NewTicker(time.Second * 180) tickerUSD := time.NewTicker(time.Second * 300) p.wg.Add(1) go func() { for { select { case <-tickerToken.C: log.Info("RunUpdateTokenPriceList start ...", time.Now().Format("2006-01-02 15:04:05")) p.updateTokenPriceInfoList() p.updateTokenMap() log.Info("RunUpdateTokenPriceList end ...", time.Now().Format("2006-01-02 15:04:05")) case <-tickerUSD.C: log.Info("RunUpdateUSDRate start ...", time.Now().Format("2006-01-02 15:04:05")) p.updateUSDRate() log.Info("RunUpdateUSDRate end ...", time.Now().Format("2006-01-02 15:04:05")) case <-p.ctx.Done(): p.wg.Done() return } } }() return nil }
49,887
https://github.com/CarlosAMolina/design-patterns/blob/master/creational-patterns/factories/abstract_factory.py
Github Open Source
Open Source
MIT
null
design-patterns
CarlosAMolina
Python
Code
256
724
from abc import ABC from enum import Enum, auto class HotDrink(ABC): def consume(self): pass class Tea(HotDrink): def consume(self): print('This tea is nice but I\'d prefer it with milk') class Coffee(HotDrink): def consume(self): print('This coffee is delicious') class HotDrinkFactory(ABC): """ Python does not require this ABC, but it helps as an API to know the factories structure. """ def prepare(self, amount): pass class TeaFactory(HotDrinkFactory): def prepare(self, amount): print(f'Put in tea bag, boil water, pour {amount}ml, enjoy!') return Tea() class CoffeeFactory(HotDrinkFactory): def prepare(self, amount): print(f'Grind some beans, boil water, pour {amount}ml, enjoy!') return Coffee() # How to use previous factories # Option 1. Using a function def make_drink(type): if type == 'tea': return TeaFactory().prepare(200) elif type == 'coffee': return CoffeeFactory().prepare(50) else: raise ValueError(type) # Option 2. Using a class class HotDrinkMachine: class AvailableDrink(Enum): """ This violates the OCP as it must be modified each time a new drink is added. """ COFFEE = auto() TEA = auto() factories = [] initialized = False def __init__(self): if not self.initialized: self.initialized = True for d in self.AvailableDrink: name = d.name[0] + d.name[1:].lower() factory_name = name + 'Factory' factory_instance = eval(factory_name)() self.factories.append((name, factory_instance)) def make_drink(self): print('Available drinks:') for index, factory in enumerate(self.factories): print(f"{index}) {factory[0]}") s = input(f'Please pick drink (0-{len(self.factories)-1}): ') idx = int(s) s = input(f'Specify amount: ') amount = int(s) return self.factories[idx][1].prepare(amount) if __name__ == '__main__': print("Option 1. Using a function") entry = input('What kind of drink would you like? (Write the name)') drink = make_drink(entry) drink.consume() print("\nOption 2. Using a class") hdm = HotDrinkMachine() drink = hdm.make_drink() drink.consume()
36,801
https://github.com/Number0000/LearningManagement/blob/master/src/main/java/com/LibraryManagement/app/Controller/BookCopyController.java
Github Open Source
Open Source
MIT
null
LearningManagement
Number0000
Java
Code
195
866
package com.LibraryManagement.app.Controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.LibraryManagement.app.Entity.BookCopy; import com.LibraryManagement.app.Exception.ResourceNotFoundException; import com.LibraryManagement.app.Repository.BookCopyRepository; @RestController @RequestMapping("/lms") public class BookCopyController { @Autowired private BookCopyRepository bookCopyRepository; // Get All BookCopy // @RequestMapping(value="/notes", method=RequestMethod.GET) @GetMapping("/bookCopies") public List<BookCopy> getAllBookCopy() { return bookCopyRepository.findAll(); } // Create a new bookCopy @PostMapping("/bookCopy") public BookCopy createBookCopy(@Valid @RequestBody BookCopy bookCopy) { return bookCopyRepository.save(bookCopy); } // Get a Single BookCopy @GetMapping("/bookCopy/{id}") public BookCopy getNoteById(@PathVariable(value = "id") int bookCopyId) { return bookCopyRepository.findById(bookCopyId) .orElseThrow(() -> new ResourceNotFoundException("BookCopy", "id", bookCopyId)); } // Get a Single Author by line within authors @GetMapping("/bookCopies/{line}") public List<BookCopy> getBookCopyByLine(@PathVariable(value = "line") int line) { Page<BookCopy> bookCopyPage = bookCopyRepository.findAll(PageRequest.of(line - 1, 1)); List<BookCopy> bookCopy = bookCopyPage.getContent(); return bookCopy; } // Update a BookCopy @PutMapping("/bookCopy/{bookid}/{branchId}") public BookCopy updateBookCopy(@PathVariable(value = "bookid") int bookId, @PathVariable(value = "branchid") int branchId, @Valid @RequestBody BookCopy bookCopyDetails) { BookCopy bookCopy = bookCopyRepository.getByBookIdAndBranchId(bookId, branchId); bookCopy.setNoOfCopies(bookCopyDetails.getNoOfCopies()); BookCopy updatedBookCopy = bookCopyRepository.save(bookCopy); return updatedBookCopy; } // Delete a BookCopy @DeleteMapping("/bookCopy/{id}") public ResponseEntity<?> deleteBookCopy(@PathVariable(value = "id") int bookCopyId) { BookCopy bookCopy = bookCopyRepository.findById(bookCopyId) .orElseThrow(() -> new ResourceNotFoundException("BookCopy", "id", bookCopyId)); bookCopyRepository.delete(bookCopy); return ResponseEntity.ok().build(); } }
11,074
https://github.com/hypercnt/login-example/blob/master/src/server/actions/user/index.js
Github Open Source
Open Source
MIT
2,019
login-example
hypercnt
JavaScript
Code
18
30
export { login } from './login' export { register } from './register' export { logout } from './logout'
13,694
https://github.com/brugere/manager/blob/master/packages/manager/modules/account-migration/src/notification/notification.component.js
Github Open Source
Open Source
BSD-3-Clause
2,022
manager
brugere
JavaScript
Code
14
34
import controller from './notification.controller'; import template from './notification.html'; export default { controller, template, };
28,215
https://github.com/VsevolodKurochka/tishenko.week/blob/master/app/assets/src/sass/layouts/nav/_nav-logo.sass
Github Open Source
Open Source
MIT
null
tishenko.week
VsevolodKurochka
Sass
Code
26
141
.nav &__logo font-size: 0 +max(md) +d('flex') align-items: center &-content display: inline-block img vertical-align: middle max-height: 35px +tr() +min(md) +w(60px) max-height: none &_scrolled &__logo img +min(md) +w(30px)
38,943
https://github.com/octoshell/octoshell-v2/blob/master/engines/support/db/migrate/20141110171648_add_attachment_fields_to_ticket.rb
Github Open Source
Open Source
MIT
2,023
octoshell-v2
octoshell
Ruby
Code
24
109
class AddAttachmentFieldsToTicket < ActiveRecord::Migration def change add_column :support_tickets, :attachment_file_name, :string add_column :support_tickets, :attachment_content_type, :string add_column :support_tickets, :attachment_file_size, :integer add_column :support_tickets, :attachment_updated_at, :datetime end end
278
https://github.com/BrianLudlam/block-dice65-turn3/blob/master/migrations/2_contract_migration.js
Github Open Source
Open Source
MIT
null
block-dice65-turn3
BrianLudlam
JavaScript
Code
19
133
const BlockDice65Turn3 = artifacts.require("BlockDice65Turn3"); //const BlockDiceAddress = '0xEbFefE3741461b4eE325c57D590BeB51bCd1e4Ba';//dev const BlockDiceAddress = '0x4b5D49a47a2031724Ad990C4D74461BC94E3db42';//loom module.exports = function(deployer) { deployer.deploy(BlockDice65Turn3, BlockDiceAddress); };
30,844
https://github.com/ShawnZhong/SplitFS/blob/master/kernel/linux-4.13/tools/testing/selftests/vm/on-fault-limit.c
Github Open Source
Open Source
Apache-2.0
2,022
SplitFS
ShawnZhong
C
Code
106
375
#include <sys/mman.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/time.h> #include <sys/resource.h> #ifndef MCL_ONFAULT #define MCL_ONFAULT (MCL_FUTURE << 1) #endif static int test_limit(void) { int ret = 1; struct rlimit lims; void *map; if (getrlimit(RLIMIT_MEMLOCK, &lims)) { perror("getrlimit"); return ret; } if (mlockall(MCL_ONFAULT | MCL_FUTURE)) { perror("mlockall"); return ret; } map = mmap(NULL, 2 * lims.rlim_max, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0); if (map != MAP_FAILED) printf("mmap should have failed, but didn't\n"); else { ret = 0; munmap(map, 2 * lims.rlim_max); } munlockall(); return ret; } int main(int argc, char **argv) { int ret = 0; ret += test_limit(); return ret; }
1,401
https://github.com/RichardFlanagan/OpenGLSolarSystem/blob/master/SolarSystem/vertexshader.glsl
Github Open Source
Open Source
MIT
null
OpenGLSolarSystem
RichardFlanagan
GLSL
Code
108
274
#version 330 layout (location = 0) in vec3 Position; // Position of the vertex layout (location = 1) in vec3 Normal; // Vertex normal out vec3 glPosition0; // The transformed position out vec3 Position0; // The original position out vec3 Normal0; // The vertex normal // Transformations uniform mat4 gModelToWorldTransform; uniform mat4 gWorldToViewTransform; uniform mat4 gProjectionTransform; /* Calculate the transformation for this vertex. */ void transformationPosition(out vec4 transform){ vec4 vertexPositionInModelSpace = vec4(Position, 1); vec4 vertexInWorldSpace = gModelToWorldTransform * vertexPositionInModelSpace; vec4 vertexInCameraSpace = gWorldToViewTransform * vertexInWorldSpace; vec4 vertexInClipSpace = gProjectionTransform * vertexInCameraSpace; transform = vertexInClipSpace; } void main(){ transformationPosition(gl_Position); glPosition0 = gl_Position.xyz; Position0 = Position; Normal0 = Normal; }
6,928
https://github.com/aws-deepracer/deepracer-env-config/blob/master/deepracer_env_config/configs/behaviour.py
Github Open Source
Open Source
Apache-2.0
null
deepracer-env-config
aws-deepracer
Python
Code
506
1,319
################################################################################# # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed under the Apache License, Version 2.0 (the "License"). # # You may not use this file except in compliance with the License. # # 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. # ################################################################################# """A class for Behaviour configuration.""" import json from typing import Union, Optional from deepracer_env_config.configs.config_interface import ConfigInterface from deepracer_env_config.configs.location import Location class Behaviour(ConfigInterface): """ DeepRacerBehaviour class """ def __init__(self, name: str, shell: str, start_location: Optional[Location] = None) -> None: """ Initialize DeepRacerBehaviour Args: name (str): name of behaviour shell (str): shell type start_location (Optional[Location]): start location w.r.t track """ super().__init__() self._name = str(name) self._shell = str(shell) self._start_location = start_location or Location() @property def name(self) -> str: """ Returns behaviour name Returns: str: behaviour name """ return self._name @property def shell(self) -> str: """ Returns shell type in str format Returns: str: shell type """ return self._shell @shell.setter def shell(self, value: str) -> None: """ Set shell type of this behaviour Args: value (str): shell type in str format """ self._shell = str(value) @property def start_location(self) -> Location: """ Returns Location instance Returns: StartLocation: start location info of this behaviour """ return self._start_location @start_location.setter def start_location(self, value: Location) -> None: """ Set start location of this behaviour. Args: value (Location): new start location of the behaviour. """ self._start_location = value def to_json(self) -> dict: """ Returns json object of the behaviour config in dict format Returns: dict: json object of the behaviour config in dict format. """ return {"name": self._name, "shell": self._shell, "start_location": self.start_location.to_json()} @staticmethod def from_json(json_obj: Union[dict, str]) -> 'Behaviour': """ Returns Behaviour instantiation from json object. Args: json_obj (Union[dict, str]): json object in dict format Returns: Behaviour: behaviour config instance created from given json object. """ if isinstance(json_obj, str): json_obj = json.loads(json_obj) return Behaviour(name=json_obj['name'], shell=json_obj['shell'], start_location=Location.from_json(json_obj['start_location'])) def copy(self) -> 'Behaviour': """ Returns a copy of self. Returns: Behaviour: a copy of self. """ return Behaviour(name=self._name, shell=self._shell, start_location=self._start_location.copy()) def __eq__(self, other: 'Behaviour') -> bool: """ Check equality. Args: other (Behaviour): other to compare Returns: bool: True if two behaviours are equal, Otherwise False. """ return (self._name == other._name and self._shell == other._shell and self._start_location == other._start_location) def __ne__(self, other: 'Behaviour') -> bool: """ Check inequality Args: other (Behaviour): other to compare Returns: bool: True if self and other are different, otherwise False. """ return not self.__eq__(other) def __str__(self) -> str: """ String representation of a behaviour Returns: str: String representation of a behaviour """ return "(name=%s, shell=%s, start_location=%s)" % (self.name, self.shell, repr(self.start_location)) def __repr__(self) -> str: """ String representation including class Returns: str: String representation including class """ return "DeepRacerBehaviour" + str(self)
34,308
https://github.com/zzj89082/shareworld/blob/master/app/Http/Controllers/Admin/ConfigController.php
Github Open Source
Open Source
MIT
2,020
shareworld
zzj89082
PHP
Code
331
1,677
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; use App\Models\Config; use App\Models\Rollimg; use \DB; class ConfigController extends Controller { /** * 加载网站配置界面 * * @return \Illuminate\Http\Response */ public function index() { //加载模板 return view('admin/config/create',['title'=>'网站配置']); } /** * 执行添加 * @return [type] [description] */ public function add(Request $request) { //接收PSOT信息 $data = $request -> except(['_token']); //判断是否为空 if(empty($data['config_title']) || empty($data['config_www']) || empty($data['config_setting'])) { return back()->with('error','配置失败'); } //调用模型 $config = Config::find(1); //拼接路径 执行上传 $logo_url = './admin/img/'; //前台logo //检测是否有文件上传 if($request -> hasFile('config_logo')) { //创建文件上传对象 $config_logo = $request -> file('config_logo'); //后缀名拼接 $homelogo = 'homelogo'.'.'.$config_logo->getClientOriginalExtension(); $config_logo->move($logo_url,$homelogo); //拼接路径插入数据库 $logo_data = ltrim($logo_url,'.').$homelogo; //执行插入 $config ->config_logo = $logo_data; } else { //如果没有上传 给默认路径插入 $config ->config_logo = $config ->config_logo; } //后台logo if($request -> hasFile('config_adminlogo')) { $config_adminlogo = $request -> file('config_adminlogo'); $adminlogo = 'adminlogo'.'.'.$config_adminlogo->getClientOriginalExtension(); $config_adminlogo->move($logo_url,$adminlogo); $admin_logo = ltrim($logo_url,'.').$adminlogo; //执行插入 $config ->config_adminlogo = $admin_logo; } else { //如果没有上传 给默认路径插入 $config ->config_adminlogo = $config ->config_adminlogo; } //网站ico if($request -> hasFile('config_ico')) { $config_ico = $request -> file('config_ico'); $icologo = 'icologo'.'.'.$config_ico->getClientOriginalExtension(); $config_ico->move($logo_url,$icologo); $ico_config = ltrim($logo_url,'.').$icologo; //执行插入 $config ->config_ico = $ico_config; } else { //如果没有上传 给默认路径插入 $config ->config_ico = $config ->config_ico; } //执行插入文字的 $config ->config_title = $data['config_title']; $config ->config_www = $data['config_www']; $config ->config_setting = $data['config_setting']; $rts = $config->save(); if($rts) { return redirect(url('admin/index'))->with('success','配置成功'); } else { return back()->with('error','配置失败'); } } /** * 加载更换轮播图模板 * @return [type] [description] */ public function rollimg() { return view('admin/config/rollimg',['title'=>'更换轮播图']); } /** * 执行添加轮播图 * @param Request $request [description] * @return [type] [description] */ public function insertimg(Request $request) { //接收post传值 $data = $request -> except(['_token']); //判断是否上传图片 最多上传多少张 if(empty($data['Rimg']) || empty($data['Ra'])) { return back()->with('error','不能为空'); } //图片上传 $Rimg = $request->file('Rimg'); $filename = $Rimg->getClientOriginalExtension(); //拼接文件名 路径 $dirname = './admin/lunbotu/'; $file_name = 'lunbotu'.date('Ymdhis',time()).'.'.$filename; $filedir = ltrim($dirname,'.').$file_name; //执行上传 $Rimg->move($dirname,$file_name); //判断是否上传成功 // 开启事务 DB::beginTransaction(); //实例化上传图片 $rollimg = new Rollimg; $res3 = $rollimg -> insertGetId(['created_at'=>date('Y-m-d H:i:s',time()),'Rimg'=>$filedir,'Ra'=>$data['Ra']]); //插入轮播图ID $config = Config::find(1); $config ->config_rollimg = $config->config_rollimg.$res3.','; $res4 = $config->save(); if($res3 && $res4) { //发送事务 DB::commit(); return redirect('/admin/index')->with('success','添加成功'); } else { //回滚操作 DB::rollBack(); return back()->with('error','添加失败'); } } public function delete($id) { $res = Rollimg::destroy($id); if($res){ return back()->with('success','删除成功'); }else{ return back()->with('error','删除失败'); } } }
4,453
https://github.com/nvuillam/kics/blob/master/assets/queries/terraform/aws/root_account_has_active_access_keys/query.rego
Github Open Source
Open Source
Apache-2.0
2,021
kics
nvuillam
Open Policy Agent
Code
84
400
package Cx import data.generic.common as common_lib CxPolicy[result] { resource := input.document[i].resource.aws_iam_access_key[name] contains(lower(resource.user), "root") not common_lib.valid_key(resource, "status") result := { "documentId": input.document[i].id, "searchKey": sprintf("aws_iam_access_key[%s]", [name]), "issueType": "MissingAttribute", "keyExpectedValue": sprintf("'aws_iam_access_key[%s].status' is defined and set to 'Inactive'", [name]), "keyActualValue": sprintf("'aws_iam_access_key[%s].status' is undefined, that defaults to 'Active'", [name]), } } CxPolicy[result] { resource := input.document[i].resource.aws_iam_access_key[name] contains(lower(resource.user), "root") resource.status == "Active" result := { "documentId": input.document[i].id, "searchKey": sprintf("aws_iam_access_key[%s].status", [name]), "issueType": "IncorrectValue", "keyExpectedValue": sprintf("'aws_iam_access_key[%s].status' is defined and set to 'Inactive'", [name]), "keyActualValue": sprintf("'aws_iam_access_key[%s].status' is set to 'Active'", [name]), } }
15,713
https://github.com/zkpursuit/kaka/blob/master/kaka-core/src/main/java/com/kaka/notice/MacroCommand.java
Github Open Source
Open Source
Apache-2.0
2,021
kaka
zkpursuit
Java
Code
109
418
package com.kaka.notice; import java.util.ArrayList; import java.util.Collection; /** * 可添加子命令的控制命令类 * * @author zkpursuit */ abstract public class MacroCommand extends Command { /** * 子命令存储容器 */ private Collection<Command> subCommands; /** * 构造方法 */ public MacroCommand() { this.subCommands = new ArrayList<>(); this.__init(); } /** * 初始化,间接调用添加所有子命令的方法 */ private void __init() { initializeMacroCommand(); } /** * 必须在子类中实现此方法,并在方法体中调用addSubCommand方法添加子命令 */ abstract protected void initializeMacroCommand(); /** * 添加子命令 * * @param commandClassRef 子命令 */ final protected void addSubCommand(Command commandClassRef) { this.subCommands.add(commandClassRef); } /** * 执行所有子命令 * * @param msg 事件消息 */ @Override public void execute(Message msg) { subCommands.stream().map((command) -> { command.cmd = cmd; command.facade = facade; return command; }).forEach((command) -> { command.execute(msg); }); } }
25,730
https://github.com/koenig125/grassroot-learning/blob/master/grassroot-nlu/install_dependencies.sh
Github Open Source
Open Source
BSD-3-Clause
2,018
grassroot-learning
koenig125
Shell
Code
128
362
#!/bin/sh sudo apt-get update if hash pip; then echo "pip is installed" else sudo apt install python3-pip fi if hash git; then echo "git is installed" else sudo apt install git fi # conda install libgcc # jvm pip install flask pip install pymongo pip install schedule pip install boto3 pip install rasa_nlu==0.10.6 pip install duckling pip install git+https://github.com/mit-nlp/MITIE.git pip install psutil pip install dateparser [ -f MITIE-models-v0.2.tar.bz2 ] && echo "Requirement already satisfied MITIE-models-v0.2.tar.bz2" || wget -P ./ https://github.com/mit-nlp/MITIE/releases/download/v0.4/MITIE-models-v0.2.tar.bz2 tar xvjf MITIE-models-v0.2.tar.bz2 --directory ./model/ if hash aws; then echo "aws is installed. You're ready to go. Run 'sudo bash activate_me.sh' to fire up the API." else sudo apt install awscli; echo "Your AWS credentials are not configured. Please run 'aws configure' and enter the associated details." fi
27,771
https://github.com/lovelycheng/JDK/blob/master/jdk-17/src/java.desktop/javax/print/attribute/standard/Destination.java
Github Open Source
Open Source
Apache-2.0
2,022
JDK
lovelycheng
Java
Code
509
1,006
/* * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.print.attribute.standard; import java.io.File; import java.io.Serial; import java.net.URI; import javax.print.attribute.Attribute; import javax.print.attribute.PrintJobAttribute; import javax.print.attribute.PrintRequestAttribute; import javax.print.attribute.URISyntax; /** * Class {@code Destination} is a printing attribute class, a {@code URI}, that * is used to indicate an alternate destination for the spooled printer * formatted data. Many {@code PrintServices} will not support the notion of a * destination other than the printer device, and so will not support this * attribute. * <p> * A common use for this attribute will be applications which want to redirect * output to a local disk file : eg."file:out.prn". Note that proper * construction of "file:" scheme {@code URI} instances should be performed * using the {@code toURI()} method of class {@link File File}. See the * documentation on that class for more information. * <p> * If a destination {@code URI} is specified in a PrintRequest and it is not * accessible for output by the {@code PrintService}, a {@code PrintException} * will be thrown. The {@code PrintException} may implement {@code URIException} * to provide a more specific cause. * <p> * <b>IPP Compatibility:</b> Destination is not an IPP attribute. * * @author Phil Race */ public final class Destination extends URISyntax implements PrintJobAttribute, PrintRequestAttribute { /** * Use serialVersionUID from JDK 1.4 for interoperability. */ @Serial private static final long serialVersionUID = 6776739171700415321L; /** * Constructs a new destination attribute with the specified {@code URI}. * * @param uri {@code URI} * @throws NullPointerException if {@code uri} is {@code null} */ public Destination(URI uri) { super (uri); } /** * Returns whether this destination attribute is equivalent to the passed in * object. To be equivalent, all of the following conditions must be true: * <ol type=1> * <li>{@code object} is not {@code null}. * <li>{@code object} is an instance of class {@code Destination}. * <li>This destination attribute's {@code URI} and {@code object}'s * {@code URI} are equal. * </ol> * * @param object {@code Object} to compare to * @return {@code true} if {@code object} is equivalent to this destination * attribute, {@code false} otherwise */ public boolean equals(Object object) { return (super.equals(object) && object instanceof Destination); } /** * Get the printing attribute class which is to be used as the "category" * for this printing attribute value. * <p> * For class {@code Destination}, the category is class {@code Destination} * itself. * * @return printing attribute class (category), an instance of class * {@link Class java.lang.Class} */ public final Class<? extends Attribute> getCategory() { return Destination.class; } /** * Get the name of the category of which this attribute value is an * instance. * <p> * For class {@code Destination}, the category name is * {@code "spool-data-destination"}. * * @return attribute category name */ public final String getName() { return "spool-data-destination"; } }
40,870
https://github.com/Protractor-Jasmine-JavaScript/my-canary-project-reference/blob/master/test/e2e/pages/login_page.js
Github Open Source
Open Source
MIT
null
my-canary-project-reference
Protractor-Jasmine-JavaScript
JavaScript
Code
57
308
'use strict'; var LoginPage = function() { this.username = element(by.model('login.credentials.username')); this.password = element(by.model('login.credentials.password')); this.loginButton = element(by.buttonText('Login')); this.error_msg_login = element(by.binding('login.error')); /** *Forgot Password */ this.forgotPasswordButton = element(by.id('forget-password')); this.forgotPasswordTitle = element(by.css('.login-title')); this.backButton = element(by.buttonText('Back')); this.submitButton = element(by.buttonText('Submit')); this.enterEmailBox = element(by.model('forgot.data.email')); this.error_msg = element(by.binding('forgot.alert.msg')); this.confirm_submit_msg = element(by.css('div[ng-if="!forgot.showForm"]')); this.login = function(username, password) { this.username.sendKeys(username); this.password.sendKeys(password); this.loginButton.click(); }; }; module.exports = LoginPage;
17,415
https://github.com/CoolestCat015/BrainlyTools_Extension/blob/master/src/scripts/views/0-Core/_/ModerationPanel/Components/MassManageUsers/ActionSection/DeleteUsers.ts
Github Open Source
Open Source
MIT
2,020
BrainlyTools_Extension
CoolestCat015
TypeScript
Code
320
1,495
import Action from "@BrainlyAction"; import Button, { JQueryButtonElementType } from "@components/Button"; import ActionSection, { RenderDetailsType } from "."; import type UserClassType from "../User"; export default class DeleteUsers extends ActionSection { started: boolean; openedConnection: number; $content: JQuery<HTMLElement>; $startButtonContainer: JQuery<HTMLElement>; $stopButton: JQueryButtonElementType; $startButton: JQueryButtonElementType; loopTryToDelete: number; constructor(main) { const renderDetails: RenderDetailsType = { content: { text: System.data.locale.core.massManageUsers.sections.deleteUsers .actionButton.title, style: " sg-text--peach-dark", }, actionButton: { ...System.data.locale.core.massManageUsers.sections.deleteUsers .actionButton, type: "transparent-peach", }, }; super(main, renderDetails); this.started = false; this.openedConnection = 0; this.RenderContent(); this.RenderStopButton(); this.RenderStartButton(); this.BindHandlers(); } RenderContent() { this.$content = $(` <div class="sg-actions-list sg-actions-list--no-wrap sg-actions-list--to-top sg-actions-list--centered"> <div class="sg-actions-list__hole sg-actions-list__hole--10-em"> <div class="sg-content-box"> <div class="sg-content-box__content sg-content-box__content--full sg-content-box__content--with-centered-text"></div> </div> </div> </div>`); this.$startButtonContainer = $(".sg-content-box__content", this.$content); this.$content.appendTo(this.$contentContainer); } RenderStopButton() { this.$stopButton = Button({ type: "solid-peach", size: "small", text: System.data.locale.common.stop, }); } RenderStartButton() { this.$startButton = Button({ type: "solid-mint", size: "small", text: System.data.locale.common.start, }); this.$startButton.appendTo(this.$startButtonContainer); } BindHandlers() { this.$startButton.on("click", this.StartDeleting.bind(this)); this.$stopButton.on("click", this.StopDeleting.bind(this)); } StartDeleting() { this.SetUsers(); if ( this.userIdList && confirm( System.data.locale.core.massManageUsers.notificationMessages .areYouSureAboutDeletingAllListedUsers, ) ) { this.started = true; this.ShowUserList(); this.ShowStopButton(); this.MoveDeletedAccountsFirst(); this.TryToDelete(); this.loopTryToDelete = window.setInterval( this.TryToDelete.bind(this), 1000, ); } } ShowUserList() { this.$userListContainer.appendTo(this.$content); } ShowStopButton() { this.HideStartButton(); this.$stopButton.appendTo(this.$startButtonContainer); } HideStartButton() { this.main.HideElement(this.$startButton); } HideStopButton() { this.main.HideElement(this.$stopButton); this.ShowStartButton(); } ShowStartButton() { this.$startButton.appendTo(this.$startButtonContainer); } MoveDeletedAccountsFirst() { /** * @type {number[]} */ this.userIdList = this.userIdList.filter(id => { const user = this.main.users[id]; if (!user || typeof user === "boolean") return false; if (user.details.is_deleted) return this.UserDeleted(user); return true; }); } TryToDelete() { if (!this.started) return; for (let i = 0; i < 7; i++) if (this.openedConnection < 7) { this.openedConnection++; const user = this.PickUser(); if (!user) { this.StopDeleting(); break; } if (typeof user !== "boolean") { this.DeleteUser(user); } } } StopDeleting() { this.started = false; this.HideStopButton(); clearInterval(this.loopTryToDelete); this.main.modal.Notification({ type: "success", html: System.data.locale.common.allDone, }); } async DeleteUser(user: UserClassType) { try { if (user.details.is_deleted) { this.openedConnection--; this.UserDeleted(user); return; } await new Action().DeleteAccount(user.details.id); // await System.TestDelay(); this.UserDeleted(user); } catch (error) { console.error(error); } this.openedConnection--; } /** * @param {import("../User").default} user */ UserDeleted(user) { user.Move$To$(this.$userList); user.ChangeBoxColor("sg-box--peach"); } }
14,024
https://github.com/DarkGuardsman/JsonContentBuilderLib/blob/master/modules/lib/src/main/java/com/builtbroken/builder/converter/strut/array/JsonConverterArrayDouble.java
Github Open Source
Open Source
MIT
2,021
JsonContentBuilderLib
DarkGuardsman
Java
Code
117
391
package com.builtbroken.builder.converter.strut.array; import com.builtbroken.builder.converter.JsonConverter; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; /** * Created by Robin Seifert on 2019-03-05. */ public class JsonConverterArrayDouble extends JsonConverter<Object> { public JsonConverterArrayDouble() { super("java:array.double", "array.double", "double[]"); } @Override public boolean canSupport(Object object) { return object instanceof double[]; } @Override public boolean canSupport(JsonElement json) { return json.isJsonArray(); } @Override public JsonElement toJson(Object input) { double[] array = (double[]) input; //Generate array final JsonArray jsonArray = new JsonArray(); for (double num : array) { jsonArray.add(new JsonPrimitive(num)); } return jsonArray; } @Override public double[] fromJson(JsonElement input) { final JsonArray jsonArray = input.getAsJsonArray(); double[] array = new double[jsonArray.size()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.get(i).getAsDouble(); } return array; } }
29,520
https://github.com/gennadykr/selenium-training/blob/master/selenium/python-example/test_litecart_admin_add_product.py
Github Open Source
Open Source
Apache-2.0
null
selenium-training
gennadykr
Python
Code
227
1,524
import pytest from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select from selenium.webdriver.common.keys import Keys import time import os @pytest.fixture def driver(request): # 1) Chrome: wd = webdriver.Chrome() # 2) Firefox: # wd = webdriver.Firefox() # 3) Edge: # wd = webdriver.Edge() # print(wd.capabilities) request.addfinalizer(wd.quit) return wd def select_element_by_text(elements, pattern): assert len(elements)>0, "Empty list of elements" for x in range(0, len(elements)): if (pattern in elements[x].text): elements[x].click() return elements[x] raise("No element found with "+pattern) def test_example(driver): # Log in to admin driver.get("http://localhost/litecart/admin/") driver.find_element_by_name("username").send_keys("admin") driver.find_element_by_name("password").send_keys("admin") driver.find_element_by_name("login").click() # Open Catalog menu wait = WebDriverWait(driver, 15) menu_items = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR , "#app- > a"))) select_element_by_text(menu_items,'Catalog') #wait.until(EC.presence_of_all_elements_located((By.XPATH, "//a/*[contains(.,'Catalog')]")))[0].click() # Click on "Add new Product" button add_buttons = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR , "#content a.button"))) select_element_by_text(add_buttons,'Product') #wait.until(EC.presence_of_all_elements_located((By.XPATH, "//a[contains(.,'Add New Product')]")))[0].click() # Fill the form product_name = 'Chizhik-Pyzhik' product_code = 'ch001' product_image = \ os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)),'chizhik_pyzhik_150x150.png')) print(product_image) tab_general = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR , "#tab-general")))[0] tab_general.find_element(By.CSS_SELECTOR,"input[type=radio]").click() tab_general.find_element(By.CSS_SELECTOR,"input[name='name[en]']").send_keys(product_name) tab_general.find_element(By.CSS_SELECTOR,"input[name=code]").send_keys(product_code) quantity_field = tab_general.find_element(By.CSS_SELECTOR,"input[name=quantity]") quantity_field.clear() quantity_field.send_keys('3') sold_out_status = tab_general.find_element(By.CSS_SELECTOR,"select[name=sold_out_status_id]") selector = Select(sold_out_status) selector.select_by_visible_text('Temporary sold out') tab_general.find_element(By.CSS_SELECTOR,"input[name='new_images[]'").send_keys(product_image) # Switch on Information tab #select_element_by_text(driver.find_elements(By.CSS_SELECTOR,".tabs .index a"),'Information') driver.find_element(By.XPATH,"//a[contains(.,'Information')]").click() tab_information = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR , "#tab-information")))[0] manufacturer_selector = tab_information.find_element(By.CSS_SELECTOR,"select[name=manufacturer_id]") selector = Select(manufacturer_selector) selector.select_by_visible_text('ACME Corp.') tab_information.find_element(By.CSS_SELECTOR,"[name='short_description[en]']").send_keys(product_name) tab_information.find_element(By.CSS_SELECTOR,".trumbowyg-editor").send_keys('Crystal crafts') # Switch on Information tab driver.find_element(By.XPATH,"//a[contains(.,'Prices')]").click() tab_prices = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR , "#tab-prices")))[0] price_field=tab_prices.find_element(By.CSS_SELECTOR,"input[name=purchase_price]") price_field.clear() price_field.send_keys("3") tab_prices.find_element(By.CSS_SELECTOR,"input[name='prices[USD]']").send_keys("6") # Save driver.find_element(By.CSS_SELECTOR,"button[name=save]").click() # Check xpath_string = './/a[contains(.,\''+product_name+'\')]' print(xpath_string) catalog_form = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR , "form[name=catalog_form")))[0] catalog_form.find_element(By.XPATH,xpath_string).click() time.sleep(5)
31,373
https://github.com/shove70/dlang.org/blob/master/book/d.en/function_overloading.d
Github Open Source
Open Source
CC-BY-NC-SA-4.0, BSL-1.0
2,023
dlang.org
shove70
D
Code
1,271
2,366
Ddoc $(DERS_BOLUMU $(IX function overloading) $(IX overloading, function) Function Overloading) $(P Defining more than one function having the same name is $(I function overloading). In order to be able to differentiate these functions, their parameters must be different. ) $(P The following code has multiple overloads of the $(C info()) function, each taking a different type of parameter: ) --- import std.stdio; void info($(HILITE double) number) { writeln("Floating point: ", number); } void info($(HILITE int) number) { writeln("Integer : ", number); } void info($(HILITE string) str) { writeln("String : ", str); } void main() { info(1.2); info(3); info("hello"); } --- $(P Although all of the functions are named $(C info()), the compiler picks the one that matches the argument that is used when making the call. For example, because the literal $(C 1.2) is of type $(C double), the $(C info()) function that takes a $(C double) gets called for it. ) $(P The choice of which function to call is made at compile time, which may not always be easy or clear. For example, because $(C int) can implicitly be converted to both $(C double) and $(C real), the compiler cannot decide which of the functions to call in the following program: ) --- real sevenTimes(real value) { return 7 * value; } double sevenTimes(double value) { return 7 * value; } void main() { int value = 5; auto result = sevenTimes(value); $(DERLEME_HATASI) } --- $(P $(I $(B Note:) It is usually unnecessary to write separate functions when the function bodies are exactly the same. We will see later in the $(LINK2 templates.html, Templates chapter) how a single definition can be used for multiple types.) ) $(P However, if there is another function overload that takes a $(C long) parameter, then the ambiguity would be resolved because $(C long) is a $(I better match) for $(C int) than $(C double) or $(C real): ) --- long sevenTimes(long value) { return 7 * value; } // ... auto result = sevenTimes(value); // now compiles --- $(H5 Overload resolution) $(P The compiler picks the overload that is the $(I best match) for the arguments. This is called overload resolution. ) $(P Although overload resolution is simple and intuitive in most cases, it is sometimes complicated. The following are the rules of overload resolution. They are being presented in a simplified way in this book. ) $(P There are four states of match, listed from the worst to the best: ) $(UL $(LI mismatch) $(LI match through automatic type conversion) $(LI match through $(C const) qualification) $(LI exact match) ) $(P The compiler considers all of the overloads of a function during overload resolution. It first determines the match state of every parameter for every overload. For each overload, the least match state among the parameters is taken to be the match state of that overload. ) $(P After all of the match states of the overloads are determined, then the overload with the best match is selected. If there are more than one overload that has the best match, then more complicated resolution rules are applied. I will not get into more details of these rules in this book. If your program is in a situation where it depends on complicated overload resolution rules, it may be an indication that it is time to change the design of the program. Another option is to take advantage of other features of D, like templates. An even simpler but not always desirable approach would be to abandon function overloading altogether by naming functions differently for each type e.g. like $(C sevenTimes_real()) and $(C sevenTimes_double()). ) $(H5 Function overloading for user-defined types) $(P Function overloading is useful with structs and classes as well. Additionally, overload resolution ambiguities are much less frequent with user-defined types. Let's overload the $(C info()) function above for some of the types that we have defined in the $(LINK2 struct.html, Structs chapter): ) --- struct TimeOfDay { int hour; int minute; } void info(TimeOfDay time) { writef("%02s:%02s", time.hour, time.minute); } --- $(P That overload enables $(C TimeOfDay) objects to be used with $(C info()). As a result, variables of user-defined types can be printed in exactly the same way as fundamental types: ) --- auto breakfastTime = TimeOfDay(7, 0); info(breakfastTime); --- $(P The $(C TimeOfDay) objects would be matched with that overload of $(C info()): ) $(SHELL 07:00 ) $(P The following is an overload of $(C info()) for the $(C Meeting) type: ) --- struct Meeting { string topic; size_t attendanceCount; TimeOfDay start; TimeOfDay end; } void info(Meeting meeting) { info(meeting.start); write('-'); info(meeting.end); writef(" \"%s\" meeting with %s attendees", meeting.topic, meeting.attendanceCount); } --- $(P Note that this overload makes use of the already-defined overload for $(C TimeOfDay). $(C Meeting) objects can now be printed in exactly the same way as fundamental types as well: ) --- auto bikeRideMeeting = Meeting("Bike Ride", 3, TimeOfDay(9, 0), TimeOfDay(9, 10)); info(bikeRideMeeting); --- $(P The output: ) $(SHELL 09:00-09:10 "Bike Ride" meeting with 3 attendees ) $(H5 Limitations) $(P Although the $(C info()) function overloads above are a great convenience, this method has some limitations: ) $(UL $(LI $(C info()) always prints to $(C stdout). It would be more useful if it could print to any $(C File). One way of achieving this is to pass the output stream as a parameter as well e.g. for the $(C TimeOfDay) type: --- void info(File file, TimeOfDay time) { file.writef("%02s:%02s", time.hour, time.minute); } --- $(P That would enable printing $(C TimeOfDay) objects to any file, including $(C stdout): ) --- info($(HILITE stdout), breakfastTime); auto file = File("a_file", "w"); info($(HILITE file), breakfastTime); --- $(P $(I $(B Note:) The special objects $(C stdin), $(C stdout), and $(C stderr) are of type $(C File).) ) ) $(LI More importantly, $(C info()) does not solve the more general problem of producing the string representation of variables. For example, it does not help with passing objects of user-defined types to $(C writeln()): --- writeln(breakfastTime); // Not useful: prints in generic format --- $(P The code above prints the object in a generic format that includes the name of the type and the values of its members, not in a way that would be useful in the program: ) $(SHELL TimeOfDay(7, 0) ) $(P It would be much more useful if there were a function that converted $(C TimeOfDay) objects to $(C string) in their special format as in $(STRING "12:34"). We will see how to define $(C string) representations of struct objects in the next chapter. ) ) ) $(PROBLEM_TEK $(P Overload the $(C info()) function for the following structs as well: ) --- struct Meal { TimeOfDay time; string address; } struct DailyPlan { Meeting amMeeting; Meal lunch; Meeting pmMeeting; } --- $(P Since $(C Meal) has only the start time, add an hour and a half to determine its end time. You can use the $(C addDuration()) function that we have defined earlier in the structs chapter: ) --- TimeOfDay addDuration(TimeOfDay start, TimeOfDay duration) { TimeOfDay result; result.minute = start.minute + duration.minute; result.hour = start.hour + duration.hour; result.hour += result.minute / 60; result.minute %= 60; result.hour %= 24; return result; } --- $(P Once the end times of $(C Meal) objects are calculated by $(C addDuration()), $(C DailyPlan) objects should be printed as in the following output: ) $(SHELL 10:30-11:45 "Bike Ride" meeting with 4 attendees 12:30-14:00 Meal, Address: İstanbul 15:30-17:30 "Budget" meeting with 8 attendees ) ) Macros: TITLE=Function Overloading DESCRIPTION=The function overloading feature of the D programming language, which increases the usability of functions by bringing uniformity through many types. KEYWORDS=d programming lesson book tutorial function overloading
10,653
https://github.com/helsinki-xr-center/Esteettomyys/blob/master/Assets/Resources/Prefabs/Colliders/ArabiaKeskus/Arabia2FloorColliders.prefab
Github Open Source
Open Source
MIT
2,019
Esteettomyys
helsinki-xr-center
Unity3D Asset
Code
232
1,019
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!1 &7088121580318548333 GameObject: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} serializedVersion: 6 m_Component: - component: {fileID: 4408415994146538944} - component: {fileID: 6178907090183984849} - component: {fileID: 1938166350415927194} - component: {fileID: 1931724483896268218} m_Layer: 16 m_Name: Arabia2FloorColliders m_TagString: Untagged m_Icon: {fileID: 0} m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 --- !u!4 &4408415994146538944 Transform: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7088121580318548333} m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} m_LocalPosition: {x: 0, y: 0, z: 0} m_LocalScale: {x: 1, y: 1, z: 1} m_Children: [] m_Father: {fileID: 0} m_RootOrder: 0 m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} --- !u!65 &6178907090183984849 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7088121580318548333} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 11.995533, y: 0.865675, z: 86.155365} m_Center: {x: 7.4458027, y: 0.52733994, z: -26.570427} --- !u!65 &1938166350415927194 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7088121580318548333} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 2.8531532, y: 0.865675, z: 25.263205} m_Center: {x: 2.8746128, y: 0.52733994, z: 29.147568} --- !u!65 &1931724483896268218 BoxCollider: m_ObjectHideFlags: 0 m_CorrespondingSourceObject: {fileID: 0} m_PrefabInstance: {fileID: 0} m_PrefabAsset: {fileID: 0} m_GameObject: {fileID: 7088121580318548333} m_Material: {fileID: 0} m_IsTrigger: 0 m_Enabled: 1 serializedVersion: 2 m_Size: {x: 5.8415985, y: 0.865675, z: 4.6006584} m_Center: {x: 4.3688354, y: 0.52733994, z: 18.82033}
31,145
https://github.com/xp-zhao/learn-java/blob/master/learn-algorithm/src/main/java/map/User1.java
Github Open Source
Open Source
MIT
2,018
learn-java
xp-zhao
Java
Code
20
43
package map; /** * Created by xp-zhao on 2019/3/5. */ public class User1 extends User { private String email; }
31,493
https://github.com/phpactor/phpactor/blob/master/lib/WorseReflection/Bridge/TolerantParser/Reflection/TraitImport/TraitImport.php
Github Open Source
Open Source
MIT
2,023
phpactor
phpactor
PHP
Code
52
185
<?php namespace Phpactor\WorseReflection\Bridge\TolerantParser\Reflection\TraitImport; class TraitImport { public function __construct(private string $traitName, private array $traitAliases = []) { } public function name(): string { return $this->traitName; } public function traitAliases(): array { return $this->traitAliases; } public function getAlias($name): TraitAlias { return $this->traitAliases[$name]; } public function hasAliasFor($name): bool { return array_key_exists($name, $this->traitAliases); } }
1,879
https://github.com/aiminickwong/docker-manager-ui/blob/master/client/config/grunt/connect.js
Github Open Source
Open Source
MIT
2,015
docker-manager-ui
aiminickwong
JavaScript
Code
68
232
module.exports = function(grunt, options){ return { options: { port: 9000, hostname: 'localhost', livereload: 35729 }, livereload: { options: { open: true, base: [ options.yeoman.tmp, options.yeoman.app ] } }, test: { options: { port: 9001, base: [ options.yeoman.tmp, options.yeoman.test, options.yeoman.app ] } }, dist: { options: { open: true, base: '<%= yeoman.dist %>' } }, docs: { options: { open: true, base: '<%= yeoman.distDocs %>' } } }; };
19,281
https://github.com/zabiksandbox/EliteDangerousCore/blob/master/EliteDangerous/EDSM/GalacticMapping.cs
Github Open Source
Open Source
Apache-2.0
2,021
EliteDangerousCore
zabiksandbox
C#
Code
467
1,292
/* * Copyright © 2016-2020 EDDiscovery development team * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. * * EDDiscovery is not affiliated with Frontier Developments plc. */ using EliteDangerousCore.DB; using BaseUtils.JSON; using System; using System.Collections.Generic; using System.IO; namespace EliteDangerousCore.EDSM { public class GalacticMapping { public List<GalacticMapObject> galacticMapObjects = null; public List<GalMapType> galacticMapTypes = null; public bool Loaded { get { return galacticMapObjects != null; } } public GalacticMapping() { galacticMapTypes = GalMapType.GetTypes(); // we always have the types. } public bool DownloadFromEDSM(string file) { try { EDSMClass edsm = new EDSMClass(); string url = EDSMClass.ServerAddress + "en/galactic-mapping/json-edd"; bool newfile; return BaseUtils.DownloadFile.HTTPDownloadFile(url, file, false, out newfile); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("DownloadFromEDSM exception:" + ex.Message); } return false; } public bool Parse(string file) { var gmobjects = new List<GalacticMapObject>(); try { string json = BaseUtils.FileHelpers.TryReadAllTextFromFile(file); if (json != null) { JArray galobjects = JArray.ParseThrowCommaEOL(json); foreach (JObject jo in galobjects) { GalacticMapObject galobject = new GalacticMapObject(jo); GalMapType ty = galacticMapTypes.Find(x => x.Typeid.Equals(galobject.type)); if (ty == null) { ty = galacticMapTypes[galacticMapTypes.Count - 1]; // last one is default.. System.Diagnostics.Trace.WriteLine("Unknown Gal Map object " + galobject.type + " " + galobject.name); } galobject.galMapType = ty; gmobjects.Add(galobject); if (galobject.points.Count == 1 && galobject.galMapSearch != null && galobject.galMapUrl != null) { var gms = new GalacticMapSystem(galobject); SystemCache.FindCachedJournalSystem(gms); } } galacticMapObjects = gmobjects; return true; } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("GalacticMapping.parsedata exception:" + ex.Message); } return false; } public GalacticMapObject Find(string name, bool contains = false) { if (galacticMapObjects != null && name.HasChars()) { foreach (GalacticMapObject gmo in galacticMapObjects) { if (gmo.name.Equals(name, StringComparison.InvariantCultureIgnoreCase) || (contains && gmo.name.IndexOf(name, StringComparison.InvariantCultureIgnoreCase) >= 0)) { return gmo; } } } return null; } public GalacticMapObject FindNearest(double x, double y, double z) { GalacticMapObject nearest = null; if (galacticMapObjects != null) { double mindist = double.MaxValue; foreach (GalacticMapObject gmo in galacticMapObjects) { if ( gmo.points.Count == 1 ) // only for single point bits { double distsq = (gmo.points[0].X - x) * (gmo.points[0].X - x) + (gmo.points[0].Y - y) * (gmo.points[0].Y - y) + (gmo.points[0].Z - z) * (gmo.points[0].Z - z); if ( distsq < mindist) { mindist = distsq; nearest = gmo; } } } } return nearest; } public List<string> GetGMONames() { List<string> ret = new List<string>(); if (galacticMapObjects != null) { foreach (GalacticMapObject gmo in galacticMapObjects) { ret.Add(gmo.name); } } return ret; } } }
48,162
https://github.com/bravegag/perfectjpattern/blob/master/perfectjpattern-examples/src/main/java/org/perfectjpattern/example/model/Customer.java
Github Open Source
Open Source
Apache-2.0
2,022
perfectjpattern
bravegag
Java
Code
317
732
//---------------------------------------------------------------------- // // PerfectJPattern: "Design patterns are good but components are better!" // Customer.java Copyright (c) 2012 Giovanni Azua Garcia // bravegag@hotmail.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.perfectjpattern.example.model; import java.util.*; /** * Customer Model object * * @author <a href="mailto:bravegag@hotmail.com">Giovanni Azua</a> * @version $ $Date: Dec 5, 2008 2:59:04 AM $ */ public class Customer { //------------------------------------------------------------------------ // public //------------------------------------------------------------------------ public Customer() { // do nothing } //------------------------------------------------------------------------ public Customer(String aName) { theName = aName; theOrders = new ArrayList<Order>(); } //------------------------------------------------------------------------ /** * Returns the id * * @return the id */ public Long getId() { return theId; } //------------------------------------------------------------------------ /** * Sets the id of the person * * @param anId the id to set */ public void setId(Long anId) { theId = anId; } //------------------------------------------------------------------------ /** * Returns the name * * @return the name */ public String getName() { return theName; } //------------------------------------------------------------------------ /** * Sets the name of the person * * @param aName the name to set */ public void setName(String aName) { theName = aName; } //------------------------------------------------------------------------ /** * Returns the orders * * @return the orders */ public List<Order> getOrders() { return theOrders; } //------------------------------------------------------------------------ /** * Sets the orders * * @param anOrders the orders to set */ public void setOrders(List<Order> anOrders) { theOrders = anOrders; } //------------------------------------------------------------------------ // members //------------------------------------------------------------------------ private Long theId; private String theName; private List<Order> theOrders; }
20,780
https://github.com/adobe/commerce-cif-graphql-client/blob/master/src/main/java/com/adobe/cq/commerce/graphql/client/GraphqlClient.java
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, Apache-2.0
2,022
commerce-cif-graphql-client
adobe
Java
Code
714
1,461
/******************************************************************************* * * Copyright 2019 Adobe. All rights reserved. * This file is licensed 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 REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. * ******************************************************************************/ package com.adobe.cq.commerce.graphql.client; import java.lang.reflect.Type; import org.osgi.annotation.versioning.ProviderType; @ProviderType public interface GraphqlClient { /** * Returns the identifier of this GraphQL client and backing OSGi service. * This can be set on JCR resources with the <code>cq:graphqlClient</code> property. * * @return The identifier value of this client. */ public String getIdentifier(); /** * Returns the URL of the used GraphQL server endpoint. * * @return The backend GraphQL server endpoint used by this client. */ public String getGraphQLEndpoint(); /** * Returns the complete configuration of the GraphQL client. * * @return GraphQL client configuration. */ public GraphqlClientConfiguration getConfiguration(); /** * Executes the given GraphQL request and deserializes the response data based on the types T and U. * The type T is used to deserialize the 'data' object of the GraphQL response, and the type U is used * to deserialize the 'errors' array of the GraphQL response. * Each generic type can be a simple class or a generic class. To specify a simple class, just do: * * <pre> * GraphqlResponse&lt;MyData, MyError&gt; response = graphqlClient.execute(request, MyData.class, MyError.class); * MyData data = response.getData(); * List&lt;MyError&gt; errors = response.getErrors(); * </pre> * * To specify a generic type (usually for the type T), one can use * the {@link com.google.gson.reflect.TypeToken} class. For example: * * <pre> * Type typeOfT = new TypeToken&lt;List&lt;String&gt;&gt;() {}.getType(); * GraphqlResponse&lt;List&lt;String&gt;, MyError&gt; response = graphqlClient.execute(request, typeOfT, MyError.class); * List&lt;String&gt; data = response.getData(); * </pre> * * @param request The GraphQL request. * @param typeOfT The type of the expected GraphQL response 'data' field. * @param typeOfU The type of the elements of the expected GraphQL response 'errors' field. * * @param <T> The generic type of the 'data' object in the JSON GraphQL response. * @param <U> The generic type of the elements of the 'errors' array in the JSON GraphQL response. * * @return A GraphQL response. * * @exception RuntimeException if the GraphQL HTTP request does not return 200 or if the JSON response cannot be parsed or deserialized. */ public <T, U> GraphqlResponse<T, U> execute(GraphqlRequest request, Type typeOfT, Type typeOfU); /** * Executes the given GraphQL request and deserializes the response data based on the types T and U. * The type T is used to deserialize the 'data' object of the GraphQL response, and the type U is used * to deserialize the 'errors' array of the GraphQL response. * Each generic type can be a simple class or a generic class. To specify a simple class, just do: * * <pre> * GraphqlResponse&lt;MyData, MyError&gt; response = graphqlClient.execute(request, MyData.class, MyError.class); * MyData data = response.getData(); * List&lt;MyError&gt; errors = response.getErrors(); * </pre> * * To specify a generic type (usually for the type T), one can use * the {@link com.google.gson.reflect.TypeToken} class. For example: * * <pre> * Type typeOfT = new TypeToken&lt;List&lt;String&gt;&gt;() {}.getType(); * GraphqlResponse&lt;List&lt;String&gt;, MyError&gt; response = graphqlClient.execute(request, typeOfT, MyError.class); * List&lt;String&gt; data = response.getData(); * </pre> * * @param request The GraphQL request. * @param typeOfT The type of the expected GraphQL response 'data' field. * @param typeOfU The type of the elements of the expected GraphQL response 'errors' field. * @param options An object holding options that can be set when executing the request. * * @param <T> The generic type of the 'data' object in the JSON GraphQL response. * @param <U> The generic type of the elements of the 'errors' array in the JSON GraphQL response. * * @return A GraphQL response. * * @exception RuntimeException if the GraphQL HTTP request does not return 200 or if the JSON response cannot be parsed or deserialized. */ public <T, U> GraphqlResponse<T, U> execute(GraphqlRequest request, Type typeOfT, Type typeOfU, RequestOptions options); }
38,282
https://github.com/PixArt-Imaging-Inc/openmv/blob/master/src/omv/sensors/paj6100u6.h
Github Open Source
Open Source
MIT
null
openmv
PixArt-Imaging-Inc
C
Code
56
163
/* * This file is part of the OpenMV project. * Copyright (c) 2019 Lake Fu <lake_fu@pixart.com> * This work is licensed under the MIT license, see the file LICENSE for details. * * PAJ6100U6 driver. * */ #ifndef __PAJ6100U6_H__ #define __PAJ6100U6_H__ #include <stdbool.h> #include "sensor.h" #define PAJ6100U6_XCLK_FREQ 6000000 bool findPaj6100(sensor_t *sensor); int paj6100u6_init(sensor_t *sensor); #endif
25,205
https://github.com/pawlean/couchers/blob/master/app/frontend/src/features/messages/messagelist/ControlMessageView.tsx
Github Open Source
Open Source
MIT
2,021
couchers
pawlean
TSX
Code
206
646
import { Box } from "@material-ui/core"; import { makeStyles } from "@material-ui/core/styles"; import { Skeleton } from "@material-ui/lab"; import classNames from "classnames"; import React from "react"; import TextBody from "../../../components/TextBody"; import { timestamp2Date } from "../../../utils/date"; import { firstName } from "../../../utils/names"; import useOnVisibleEffect from "../../../utils/useOnVisibleEffect"; import { useAuthContext } from "../../auth/AuthProvider"; import { useUser } from "../../userQueries/useUsers"; import { controlMessageText, messageTargetId } from "../utils"; import { messageElementId, MessageProps } from "./MessageView"; import TimeInterval from "./TimeInterval"; const useStyles = makeStyles((theme) => ({ message: { paddingInlineEnd: theme.spacing(1), }, root: { marginInlineEnd: "auto", marginInlineStart: "auto", textAlign: "center", }, skeleton: { minWidth: 100 }, timestamp: theme.typography.caption, })); export default function ControlMessageView({ message, onVisible, className, }: MessageProps) { const classes = useStyles(); const currentUserId = useAuthContext().authState.userId; const { data: author, isLoading: isAuthorLoading } = useUser( message.authorUserId ); const { data: target, isLoading: isTargetLoading } = useUser( messageTargetId(message) ); const { ref } = useOnVisibleEffect(onVisible); const isCurrentUser = author?.userId === currentUserId; const authorName = isCurrentUser ? "you" : firstName(author?.name); const targetName = firstName(target?.name); return ( <Box className={classNames(classes.root, className)} data-testid={`message-${message.messageId}`} ref={ref} id={messageElementId(message.messageId)} > <Box className={classes.timestamp}> <TimeInterval date={timestamp2Date(message.time!)} /> </Box> <Box className={classes.message}> {!isAuthorLoading && !isTargetLoading ? ( <TextBody> {controlMessageText(message, authorName, targetName)} </TextBody> ) : ( <Skeleton className={classes.skeleton} /> )} </Box> </Box> ); }
26,886
https://github.com/mmaarrttyy/lundium/blob/master/packages/lundium/src/components/FormField/index.js
Github Open Source
Open Source
MIT
2,019
lundium
mmaarrttyy
JavaScript
Code
6
11
export { default } from './FormField';
28,653
https://github.com/FuSoftware/AccdbTools/blob/master/AccdbTools/ACCDB/Jet4/Pages/Jet4DataPage.cs
Github Open Source
Open Source
MIT
2,021
AccdbTools
FuSoftware
C#
Code
128
478
using AccdbTools.ACCDB.Generic; using AccdbTools.ACCDB.Generic.Pages; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AccdbTools.ACCDB.Jet4.Pages { public class Jet4DataPage : DataPage { public class Jet4DataPageHeader : DataPageHeader { public uint A1 { get; set; } public Jet4DataPageHeader(byte[] data) { this.Load(data); } public void Load(byte[] data) { this.FreeSpace = BitConverter.ToUInt16(data, 2); if(Encoding.Default.GetString(data.Skip(8).Take(4).ToArray()) == "LAVL") { this.LVAL = true; } else { this.Owner = BitConverter.ToUInt32(data, 4); } this.A1 = BitConverter.ToUInt32(data, 8); this.RecordCount = BitConverter.ToUInt16(data, 12); this.RecordOffsets = new List<RecordOffset>(); for(uint i = 0; i < this.RecordCount; i++) { this.RecordOffsets.Add(new RecordOffset(BitConverter.ToUInt16(data, 14 + (int)i*2))); } } } public Jet4DataPage(byte[] data) : base(data) { } public override void LoadHeader(byte[] data) { this.PageSignature = (PageType)BitConverter.ToUInt16(data, 0); this.Header = new Jet4DataPageHeader(data); } public override void Load(byte[] data) { } } }
35,799
https://github.com/carlgao/lenga/blob/master/images/lenny64-peon/usr/share/texmf-texlive/fonts/afm/bluesky/ams/eusm7.afm
Github Open Source
Open Source
MIT
2,013
lenga
carlgao
Adobe Font Metrics
Code
771
1,401
StartFontMetrics 2.0 Comment Copyright (C) 1997 American Mathematical Society. All Rights Reserved. Comment Creation Date: Jan 12 1992 Comment UniqueID 5031994 FontName EUSM7 EncodingScheme FontSpecific FullName EUSM7 FamilyName Euler ItalicAngle 0.0 Weight Medium IsFixedPitch false Version 2.1 Notice Euler fonts were designed by Hermann Zapf FontBBox 0 -250 1178 750 XHeight 459.506 CapHeight 702.774 Ascender 702.774 Descender -189.056 Comment following is extra info from TFM file Comment FontID EUSM V2.1 Comment DesignSize 7 (pts) Comment CharacterCodingScheme TeX math symbols subset Comment Space 333.333 0 0 Comment ExtraSpace 0 Comment Quad 1000 Comment Num 378.416 270.297 297.326 Comment Denom 378.416 162.177 Comment Sup 405.446 378.416 324.356 Comment Sub 189.207 243.267 Comment Supdrop 405.446 Comment Subdrop 27.027 Comment Delim 2200.23 1000 Comment Axisheight 256.781 StartCharMetrics 41 C 0 ; WX 915.525 ; N minus ; B 0 -83.25 915.525 583.303 ; C 24 ; WX 684.211 ; N similar ; B 0 0 684.211 459.506 ; C 32 ; WX 333.333 ; N space ; B 0 0 0 0 ; C 48 ; WX 0 ; N ghost ; B 0 0 0 0 ; C 58 ; WX 834.349 ; N logicalnot ; B 0 0 834.349 459.506 ; C 60 ; WX 996.702 ; N Rfractur ; B 0 0 996.702 702.774 ; C 61 ; WX 687.559 ; N Ifractur ; B 0 0 687.559 702.774 ; C 64 ; WX 936.277 ; N aleph ; B 0 0 936.277 702.774 ; C 65 ; WX 931.7 ; N A ; B 0 0 931.7 702.774 ; C 66 ; WX 921.019 ; N B ; B 0 0 921.019 702.774 ; C 67 ; WX 741.88 ; N C ; B 0 0 741.88 702.774 ; C 68 ; WX 999.449 ; N D ; B 0 0 999.449 702.774 ; C 69 ; WX 748.289 ; N E ; B 0 0 748.289 702.774 ; C 70 ; WX 794.677 ; N F ; B 0 0 825.193 702.774 ; C 71 ; WX 744.017 ; N G ; B 0 -126.138 744.017 702.774 ; C 72 ; WX 1060.48 ; N H ; B 0 0 1075.74 702.774 ; C 73 ; WX 547.789 ; N I ; B 0 0 547.789 702.774 ; C 74 ; WX 632.933 ; N J ; B 0 -126.138 632.933 702.774 ; C 75 ; WX 990.904 ; N K ; B 0 0 990.904 702.774 ; C 76 ; WX 869.444 ; N L ; B 0 0 869.444 702.774 ; C 77 ; WX 1170.96 ; N M ; B 0 0 1170.96 702.774 ; C 78 ; WX 935.667 ; N N ; B 0 0 950.924 702.774 ; C 79 ; WX 860.594 ; N O ; B 0 0 860.594 702.774 ; C 80 ; WX 807.493 ; N P ; B 0 0 807.493 702.774 ; C 81 ; WX 809.629 ; N Q ; B 0 0 809.629 702.774 ; C 82 ; WX 877.684 ; N R ; B 0 0 877.684 702.774 ; C 83 ; WX 673.521 ; N S ; B 0 0 673.521 702.774 ; C 84 ; WX 724.18 ; N T ; B 0 0 769.955 702.774 ; C 85 ; WX 867.918 ; N U ; B 0 0 867.918 702.774 ; C 86 ; WX 812.071 ; N V ; B 0 0 812.071 702.774 ; C 87 ; WX 1178.89 ; N W ; B 0 0 1178.89 702.774 ; C 88 ; WX 870.968 ; N X ; B 0 0 870.968 702.774 ; C 89 ; WX 734.251 ; N Y ; B 0 0 734.251 702.774 ; C 90 ; WX 803.221 ; N Z ; B 0 0 803.221 702.774 ; C 94 ; WX 936.888 ; N logicaland ; B 0 0 936.888 702.774 ; C 95 ; WX 936.888 ; N logicalor ; B 0 0 936.888 702.774 ; C 102 ; WX 422.667 ; N braceleft ; B 0 -250 422.667 750.076 ; C 103 ; WX 422.667 ; N braceright ; B 0 -250 422.667 750.076 ; C 106 ; WX 302.122 ; N bar ; B 0 -250 302.122 750.076 ; C 110 ; WX 628.049 ; N backslash ; B 0 -250 628.049 750.076 ; C 120 ; WX 643.003 ; N section ; B 0 0 643.003 189.207 ; EndCharMetrics Comment The bogus kern pairs with `ghost' are for TeX positioning of accents StartKernData StartKernPairs 3 KPX A ghost 156.826 KPX I ghost 62.729 KPX J ghost 62.729 EndKernPairs EndKernData EndFontMetrics
22,125
https://github.com/jroelofs/uwh-display/blob/master/lib/display/BigNumber.cpp
Github Open Source
Open Source
BSD-3-Clause
null
uwh-display
jroelofs
C++
Code
1,933
16,118
//===-- BigNumber.cpp - Large Format Number Rendering ------------- c++ --===// // // UWH Timer // // This file is distributed under the BSD 3-Clause License. // See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "uwhd/display/BigNumber.h" #include "uwhd/canvas/Canvas.h" #include <cstdio> #include <cassert> #include <cstdarg> #define _ 0 static const char Number5x7_0[5*7] = { _,1,1,1,_, 1,_,_,_,1, 1,_,_,1,1, 1,_,1,_,1, 1,1,_,_,1, 1,_,_,_,1, _,1,1,1,_, }; static const char Number5x7_1[5*7] = { _,_,1,_,_, _,1,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,1,1,1,_, }; static const char Number5x7_2[5*7] = { _,1,1,1,_, 1,_,_,_,1, _,_,_,_,1, _,_,_,1,_, _,_,1,_,_, _,1,_,_,_, 1,1,1,1,1, }; static const char Number5x7_3[5*7] = { _,1,1,1,_, 1,_,_,_,1, _,_,_,_,1, _,_,1,1,1, _,_,_,_,1, 1,_,_,_,1, _,1,1,1,_, }; static const char Number5x7_4[5*7] = { _,_,_,1,_, _,_,1,1,_, _,1,_,1,_, 1,1,1,1,1, _,_,_,1,_, _,_,_,1,_, _,_,_,1,_, }; static const char Number5x7_5[5*7] = { 1,1,1,1,1, 1,_,_,_,_, 1,_,_,_,_, 1,1,1,1,_, _,_,_,_,1, 1,_,_,_,1, _,1,1,1,_, }; static const char Number5x7_6[5*7] = { _,1,1,1,_, 1,_,_,_,1, 1,_,_,_,_, 1,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, _,1,1,1,_, }; static const char Number5x7_7[5*7] = { 1,1,1,1,1, _,_,_,_,1, _,_,_,1,_, _,_,1,_,_, _,1,_,_,_, _,1,_,_,_, _,1,_,_,_, }; static const char Number5x7_8[5*7] = { _,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, _,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, _,1,1,1,_, }; static const char Number5x7_9[5*7] = { _,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, _,1,1,1,1, _,_,_,_,1, 1,_,_,_,1, _,1,1,1,_, }; static const char Ascii5x7_A[5*7] = { _,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, 1,1,1,1,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, }; static const char Ascii5x7_B[5*7] = { 1,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, 1,1,1,1,1, 1,_,_,_,1, 1,_,_,_,1, 1,1,1,1,_, }; static const char Ascii5x7_C[5*7] = { _,1,1,1,1, 1,_,_,_,_, 1,_,_,_,_, 1,_,_,_,_, 1,_,_,_,_, 1,_,_,_,_, _,1,1,1,1, }; static const char Ascii5x7_D[5*7] = { 1,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,1,1,1,_, }; static const char Ascii5x7_E[5*7] = { 1,1,1,1,1, 1,_,_,_,_, 1,_,_,_,_, 1,1,1,1,1, 1,_,_,_,_, 1,_,_,_,_, 1,1,1,1,1, }; static const char Ascii5x7_F[5*7] = { 1,1,1,1,1, 1,_,_,_,_, 1,_,_,_,_, 1,1,1,1,1, 1,_,_,_,_, 1,_,_,_,_, 1,_,_,_,_, }; static const char Ascii5x7_G[5*7] = { _,1,1,1,_, 1,_,_,_,_, 1,_,_,_,_, 1,_,_,1,1, 1,_,_,_,1, 1,_,_,_,1, _,1,1,1,_, }; static const char Ascii5x7_H[5*7] = { 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,1,1,1,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, }; static const char Ascii5x7_I[5*7] = { 1,1,1,1,1, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, 1,1,1,1,1, }; static const char Ascii5x7_J[5*7] = { 1,1,1,1,1, _,_,_,1,_, _,_,_,1,_, _,_,_,1,_, 1,_,_,1,_, 1,_,_,1,_, _,1,1,_,_, }; static const char Ascii5x7_K[5*7] = { 1,_,_,_,1, 1,_,_,1,_, 1,_,1,_,_, 1,1,_,_,_, 1,_,1,_,_, 1,_,_,1,_, 1,_,_,_,1, }; static const char Ascii5x7_L[5*7] = { 1,_,_,_,_, 1,_,_,_,_, 1,_,_,_,_, 1,_,_,_,_, 1,_,_,_,_, 1,_,_,_,_, 1,1,1,1,1, }; static const char Ascii5x7_M[5*7] = { 1,_,_,_,1, 1,1,_,1,1, 1,_,1,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, }; static const char Ascii5x7_N[5*7] = { 1,_,_,_,1, 1,1,_,_,1, 1,_,1,_,1, 1,_,_,1,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, }; static const char Ascii5x7_O[5*7] = { _,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, _,1,1,1,_, }; static const char Ascii5x7_P[5*7] = { 1,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, 1,1,1,1,_, 1,_,_,_,_, 1,_,_,_,_, 1,_,_,_,_, }; static const char Ascii5x7_Q[5*7] = { _,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,1,_,1, 1,_,_,1,_, _,1,1,_,1, }; static const char Ascii5x7_R[5*7] = { 1,1,1,1,_, 1,_,_,_,1, 1,_,_,_,1, 1,1,1,1,_, 1,_,1,_,_, 1,_,_,1,_, 1,_,_,_,1, }; static const char Ascii5x7_S[5*7] = { _,1,1,1,1, 1,_,_,_,_, 1,_,_,_,_, _,1,1,1,_, _,_,_,_,1, _,_,_,_,1, 1,1,1,1,_, }; static const char Ascii5x7_T[5*7] = { 1,1,1,1,1, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, }; static const char Ascii5x7_U[5*7] = { 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, _,1,1,1,_, }; static const char Ascii5x7_V[5*7] = { 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, _,1,_,1,_, _,_,1,_,_, }; static const char Ascii5x7_W[5*7] = { 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,_,_,1, 1,_,1,_,1, 1,_,1,_,1, _,1,_,1,_, }; static const char Ascii5x7_X[5*7] = { 1,_,_,_,1, _,1,_,1,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,1,_,1,_, 1,_,_,_,1, }; static const char Ascii5x7_Y[5*7] = { 1,_,_,_,1, _,1,_,1,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, }; static const char Ascii5x7_Z[5*7] = { 1,1,1,1,1, _,_,_,_,1, _,_,_,1,_, _,_,1,_,_, _,1,_,_,_, 1,_,_,_,_, 1,1,1,1,1, }; static const char Ascii5x7_LPAREN[5*7] = { _,_,_,1,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,_,1,_, }; static const char Ascii5x7_RPAREN[5*7] = { _,1,_,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,_,1,_,_, _,1,_,_,_, }; static const char Ascii5x7_HYPHEN[5*7] = { _,_,_,_,_, _,_,_,_,_, _,_,_,_,_, 1,1,1,1,1, _,_,_,_,_, _,_,_,_,_, _,_,_,_,_, }; static const char Ascii5x7_DOT[5*7] = { _,_,_,_,_, _,_,_,_,_, _,_,_,_,_, _,_,_,_,_, _,_,_,_,_, _,_,1,_,_, _,_,_,_,_, }; static const char Ascii5x7_LCURL[5*7] = { _,_,_,1,_, _,_,1,_,_, _,_,1,_,_, _,1,_,_,_, _,_,1,_,_, _,_,1,_,_, _,_,_,1,_, }; static const char Ascii5x7_RCURL[5*7] = { _,1,_,_,_, _,_,1,_,_, _,_,1,_,_, _,_,_,1,_, _,_,1,_,_, _,_,1,_,_, _,1,_,_,_, }; static const char Ascii5x7_FSLASH[5*7] = { _,_,_,_,_, _,_,_,_,1, _,_,_,1,_, _,_,1,_,_, _,1,_,_,_, 1,_,_,_,_, _,_,_,_,_, }; static const char Ascii5x7_COLON[5*7] = { _,_,_,_,_, _,_,_,_,_, _,_,1,_,_, _,_,_,_,_, _,_,1,_,_, _,_,_,_,_, _,_,_,_,_, }; static const char Ascii5x7_AT[5*7] = { _,1,1,1,_, 1,_,_,_,1, 1,_,1,_,1, 1,1,1,_,1, 1,_,1,1,1, 1,_,_,_,_, _,1,1,1,_, }; static const char Number11x20_0[11*20] = { _,_,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,_, 1,1,1,_,_,_,_,_,1,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,1,1,1, 1,1,_,_,_,_,_,1,1,1,1, 1,1,_,_,_,_,1,1,_,1,1, 1,1,_,_,_,1,1,_,_,1,1, 1,1,_,_,1,1,_,_,_,1,1, 1,1,_,1,1,_,_,_,_,1,1, 1,1,1,1,_,_,_,_,_,1,1, 1,1,1,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,1,_,_,_,_,_,1,1,1, _,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,_,_, }; static const char Number11x20_1[11*20] = { _,_,_,_,1,1,_,_,_,_,_, _,_,_,1,1,1,_,_,_,_,_, _,_,1,1,1,1,_,_,_,_,_, _,_,1,1,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,_,_,1,1,_,_,_,_,_, _,_,1,1,1,1,1,1,_,_,_, _,_,1,1,1,1,1,1,_,_,_, }; static const char Number11x20_2[11*20] = { _,_,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,_, 1,1,1,_,_,_,_,_,1,1,1, 1,1,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,1,1,1,_,_, _,_,_,_,_,1,1,1,_,_,_, _,_,_,_,1,1,1,_,_,_,_, _,_,_,1,1,1,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_, _,1,1,1,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_, 1,1,_,_,_,_,_,_,_,_,_, 1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1, }; static const char Number11x20_3[11*20] = { _,_,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,_, 1,1,1,_,_,_,_,_,1,1,1, 1,1,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,1,1,1,1,_,_, _,_,_,_,_,1,1,1,1,_,_, _,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,1,_,_,_,_,_,1,1,1, _,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,_,_, }; static const char Number11x20_4[11*20] = { _,_,_,_,_,_,_,_,1,1,_, _,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,1,1,1,1,_, _,_,_,_,_,1,1,1,1,1,_, _,_,_,_,1,1,1,_,1,1,_, _,_,_,1,1,1,_,_,1,1,_, _,_,1,1,1,_,_,_,1,1,_, _,1,1,1,_,_,_,_,1,1,_, 1,1,1,_,_,_,_,_,1,1,_, 1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1, _,_,_,_,_,_,_,_,1,1,_, _,_,_,_,_,_,_,_,1,1,_, _,_,_,_,_,_,_,_,1,1,_, _,_,_,_,_,_,_,_,1,1,_, _,_,_,_,_,_,_,_,1,1,_, _,_,_,_,_,_,_,_,1,1,_, _,_,_,_,_,_,_,_,1,1,_, _,_,_,_,_,_,_,_,1,1,_, _,_,_,_,_,_,_,_,1,1,_, }; static const char Number11x20_5[11*20] = { 1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1, 1,1,_,_,_,_,_,_,_,_,_, 1,1,_,_,_,_,_,_,_,_,_, 1,1,_,_,_,_,_,_,_,_,_, 1,1,_,_,_,_,_,_,_,_,_, 1,1,_,_,_,_,_,_,_,_,_, 1,1,_,_,_,_,_,_,_,_,_, 1,1,1,1,1,1,1,_,_,_,_, 1,1,1,1,1,1,1,1,_,_,_, _,_,_,_,_,_,1,1,1,_,_, _,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,1,_,_,_,_,_,1,1,1, _,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,_,_, }; static const char Number11x20_6[11*20] = { _,_,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,_, 1,1,1,_,_,_,_,_,1,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,_,_, 1,1,_,_,_,_,_,_,_,_,_, 1,1,_,_,_,_,_,_,_,_,_, 1,1,_,_,_,_,_,_,_,_,_, 1,1,_,_,_,_,_,_,_,_,_, 1,1,_,1,1,1,1,1,_,_,_, 1,1,1,1,1,1,1,1,1,_,_, 1,1,1,1,_,_,_,1,1,1,_, 1,1,1,_,_,_,_,_,1,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,1,_,_,_,_,_,1,1,1, _,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,_,_, }; static const char Number11x20_7[11*20] = { 1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,1,1,1,_,_, _,_,_,_,_,1,1,1,_,_,_, _,_,_,_,1,1,1,_,_,_,_, _,_,_,1,1,1,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_, _,_,1,1,_,_,_,_,_,_,_, _,_,1,1,_,_,_,_,_,_,_, _,_,1,1,_,_,_,_,_,_,_, _,_,1,1,_,_,_,_,_,_,_, _,_,1,1,_,_,_,_,_,_,_, _,_,1,1,_,_,_,_,_,_,_, _,_,1,1,_,_,_,_,_,_,_, _,_,1,1,_,_,_,_,_,_,_, _,_,1,1,_,_,_,_,_,_,_, _,_,1,1,_,_,_,_,_,_,_, }; static const char Number11x20_8[11*20] = { _,_,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,_, 1,1,1,_,_,_,_,_,1,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,1,_,_,_,_,_,1,1,1, _,1,1,1,_,_,_,1,1,1,_, _,_,1,1,1,1,1,1,1,_,_, _,_,1,1,1,1,1,1,1,_,_, _,1,1,1,_,_,_,1,1,1,_, 1,1,1,_,_,_,_,_,1,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,1,_,_,_,_,_,1,1,1, _,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,_,_, }; static const char Number11x20_9[11*20] = { _,_,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,_, 1,1,1,_,_,_,_,_,1,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,1,_,_,_,_,_,1,1,1, _,1,1,1,_,_,_,1,1,1,1, _,_,1,1,1,1,1,1,1,1,1, _,_,_,1,1,1,1,1,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, _,_,_,_,_,_,_,_,_,1,1, 1,1,_,_,_,_,_,_,_,1,1, 1,1,1,_,_,_,_,_,1,1,1, _,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,_,_, }; static const char Number15x29_0[15*29] = { _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,_,_,_,_,_,_,_,1,1,1,1,1, 1,1,1,_,_,_,_,_,_,1,1,1,1,1,1, 1,1,1,_,_,_,_,_,1,1,1,1,1,1,1, 1,1,1,_,_,_,_,1,1,1,1,1,1,1,1, 1,1,1,_,_,_,1,1,1,1,1,_,1,1,1, 1,1,1,_,_,1,1,1,1,1,_,_,1,1,1, 1,1,1,_,1,1,1,1,1,_,_,_,1,1,1, 1,1,1,1,1,1,1,1,_,_,_,_,1,1,1, 1,1,1,1,1,1,1,_,_,_,_,_,1,1,1, 1,1,1,1,1,1,_,_,_,_,_,_,1,1,1, 1,1,1,1,1,_,_,_,_,_,_,_,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, }; static const char Number15x29_1[15*29] = { _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,1,1,1,1,_,_,_,_,_,_, _,_,_,_,1,1,1,1,1,_,_,_,_,_,_, _,_,_,1,1,1,1,1,1,_,_,_,_,_,_, _,_,_,1,1,1,1,1,1,_,_,_,_,_,_, _,_,_,1,1,1,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,_,_,_,1,1,1,_,_,_,_,_,_, _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, }; static const char Number15x29_2[15*29] = { _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,1,1,1,1, _,_,_,_,_,_,_,_,_,_,1,1,1,1,1, _,_,_,_,_,_,_,_,_,1,1,1,1,1,_, _,_,_,_,_,_,_,_,1,1,1,1,1,_,_, _,_,_,_,_,_,_,1,1,1,1,1,_,_,_, _,_,_,_,_,_,1,1,1,1,1,_,_,_,_, _,_,_,_,_,1,1,1,1,1,_,_,_,_,_, _,_,_,_,1,1,1,1,1,_,_,_,_,_,_, _,_,_,1,1,1,1,1,_,_,_,_,_,_,_, _,_,1,1,1,1,1,_,_,_,_,_,_,_,_, _,1,1,1,1,1,_,_,_,_,_,_,_,_,_, 1,1,1,1,1,_,_,_,_,_,_,_,_,_,_, 1,1,1,1,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, }; static const char Number15x29_3[15*29] = { _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,1,1,1,1, _,_,_,_,_,_,_,_,_,_,1,1,1,1,_, _,_,_,_,_,1,1,1,1,1,1,1,1,_,_, _,_,_,_,_,1,1,1,1,1,1,1,1,_,_, _,_,_,_,_,1,1,1,1,1,1,1,1,_,_, _,_,_,_,_,_,_,_,_,_,1,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, }; static const char Number15x29_4[15*29] = { _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,1,1,1,1,_, _,_,_,_,_,_,_,_,_,1,1,1,1,1,_, _,_,_,_,_,_,_,_,1,1,1,1,1,1,_, _,_,_,_,_,_,_,1,1,1,1,1,1,1,_, _,_,_,_,_,_,1,1,1,1,_,1,1,1,_, _,_,_,_,_,1,1,1,1,_,_,1,1,1,_, _,_,_,_,1,1,1,1,_,_,_,1,1,1,_, _,_,_,1,1,1,1,_,_,_,_,1,1,1,_, _,_,1,1,1,1,_,_,_,_,_,1,1,1,_, _,1,1,1,1,_,_,_,_,_,_,1,1,1,_, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,_, 1,1,1,_,_,_,_,_,_,_,_,1,1,1,_, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, _,_,_,_,_,_,_,_,_,_,_,1,1,1,_, }; static const char Number15x29_5[15*29] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,1,1,1,1,1,1,1,1,_,_,_,_, 1,1,1,1,1,1,1,1,1,1,1,1,_,_,_, 1,1,1,1,1,1,1,1,1,1,1,1,1,_,_, _,_,_,_,_,_,_,_,_,1,1,1,1,1,_, _,_,_,_,_,_,_,_,_,_,1,1,1,1,1, _,_,_,_,_,_,_,_,_,_,_,1,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, }; static const char Number15x29_6[15*29] = { _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,_,_,_,_,_,_,_,_,_,_,_, 1,1,1,_,1,1,1,1,1,1,1,1,_,_,_, 1,1,1,1,1,1,1,1,1,1,1,1,1,_,_, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,_, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, }; static const char Number15x29_7[15*29] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,1,1,1,1, _,_,_,_,_,_,_,_,_,_,1,1,1,1,1, _,_,_,_,_,_,_,_,_,1,1,1,1,1,_, _,_,_,_,_,_,_,_,1,1,1,1,1,_,_, _,_,_,_,_,_,_,1,1,1,1,1,_,_,_, _,_,_,_,_,_,1,1,1,1,1,_,_,_,_, _,_,_,_,_,1,1,1,1,1,_,_,_,_,_, _,_,_,_,1,1,1,1,1,_,_,_,_,_,_, _,_,_,1,1,1,1,1,_,_,_,_,_,_,_, _,_,1,1,1,1,1,_,_,_,_,_,_,_,_, _,_,1,1,1,1,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, _,_,1,1,1,_,_,_,_,_,_,_,_,_,_, }; static const char Number15x29_8[15*29] = { _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, _,1,1,1,1,_,_,_,_,_,1,1,1,1,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,1,1,1,1,_,_,_,_,_,1,1,1,1,_, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, }; static const char Number15x29_9[15*29] = { _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, _,1,1,1,1,1,1,1,1,1,1,1,1,1,1, _,_,1,1,1,1,1,1,1,1,1,1,1,1,1, _,_,_,1,1,1,1,1,1,1,1,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, _,_,_,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,_,_,_,_,_,_,_,_,_,1,1,1, 1,1,1,1,_,_,_,_,_,_,_,1,1,1,1, 1,1,1,1,1,_,_,_,_,_,1,1,1,1,1, _,1,1,1,1,1,1,1,1,1,1,1,1,1,_, _,_,1,1,1,1,1,1,1,1,1,1,1,_,_, _,_,_,1,1,1,1,1,1,1,1,1,_,_,_, }; #undef _ static const char *HexUpper5x7[] = { Number5x7_0, Number5x7_1, Number5x7_2, Number5x7_3, Number5x7_4, Number5x7_5, Number5x7_6, Number5x7_7, Number5x7_8, Number5x7_9, Ascii5x7_A, Ascii5x7_B, Ascii5x7_C, Ascii5x7_D, Ascii5x7_E, Ascii5x7_F, }; static const char *Ascii5x7[128] = { // 0 1 2 3 4 5 6 7 // 8 9 A B C D E F /* 0x00 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 */ /* ! */0, 0, /* # */0, /* $ */0, /* % */0, /* & */0, /* ' */0, Ascii5x7_LPAREN, Ascii5x7_RPAREN, /* * */0, /* + */0, /* ' */0, /* , */0, Ascii5x7_HYPHEN, Ascii5x7_DOT, Ascii5x7_FSLASH, /* 0x30 */ Number5x7_0, Number5x7_1, Number5x7_2, Number5x7_3, Number5x7_4, Number5x7_5, Number5x7_6, Number5x7_7, Number5x7_8, Number5x7_9, Ascii5x7_COLON, /* ; */0, /* < */0, /* = */0, /* > */0, /* ? */0, /* 0x40 */ Ascii5x7_AT, Ascii5x7_A, Ascii5x7_B, Ascii5x7_C, Ascii5x7_D, Ascii5x7_E, Ascii5x7_F, Ascii5x7_G, Ascii5x7_H, Ascii5x7_I, Ascii5x7_J, Ascii5x7_K, Ascii5x7_L, Ascii5x7_M, Ascii5x7_N, Ascii5x7_O, /* 0x50 */ Ascii5x7_P, Ascii5x7_Q, Ascii5x7_R, Ascii5x7_S, Ascii5x7_T, Ascii5x7_U, Ascii5x7_V, Ascii5x7_W, Ascii5x7_X, Ascii5x7_Y, Ascii5x7_Z, /* [ */0, /* / */0, /* ] */0, /* ^ */0, /* _ */0, /* 0x60 */ /* ` */0, /* a */0, /* b */0, /* c */0, /* d */0, /* e */0, /* f */0, /* g */0, /* h */0, /* i */0, /* j */0, /* k */0, /* l */0, /* m */0, /* n */0, /* o */0, /* 0x70 */ /* p */0, /* q */0, /* r */0, /* s */0, /* t */0, /* u */0, /* v */0, /* w */0, /* x */0, /* y */0, /* z */0, Ascii5x7_LCURL, /* | */0, Ascii5x7_RCURL, /* ~ */0, /* DEL */0 }; static const char *Numbers5x7[] = { Number5x7_0, Number5x7_1, Number5x7_2, Number5x7_3, Number5x7_4, Number5x7_5, Number5x7_6, Number5x7_7, Number5x7_8, Number5x7_9, }; static const char *Numbers11x20[] = { Number11x20_0, Number11x20_1, Number11x20_2, Number11x20_3, Number11x20_4, Number11x20_5, Number11x20_6, Number11x20_7, Number11x20_8, Number11x20_9, }; static const char *Numbers15x29[] = { Number15x29_0, Number15x29_1, Number15x29_2, Number15x29_3, Number15x29_4, Number15x29_5, Number15x29_6, Number15x29_7, Number15x29_8, Number15x29_9, }; static unsigned width(enum BigNumber::Font F) { switch (F) { case BigNumber::Font::Ascii5x7: return 5; case BigNumber::Font::HexUpper5x7: return 5; case BigNumber::Font::Digit5x7: return 5; case BigNumber::Font::Digit11x20: return 11; case BigNumber::Font::Digit15x29: return 15; } return 0; } static unsigned height(enum BigNumber::Font F) { switch (F) { case BigNumber::Font::Ascii5x7: return 7; case BigNumber::Font::HexUpper5x7: return 7; case BigNumber::Font::Digit5x7: return 7; case BigNumber::Font::Digit11x20: return 20; case BigNumber::Font::Digit15x29: return 29; } return 0; } static const char *character(enum BigNumber::Font F, unsigned char Digit) { switch (F) { case BigNumber::Font::Ascii5x7: assert(Digit < 128); return Ascii5x7[Digit]; case BigNumber::Font::HexUpper5x7: assert(Digit < 16); return HexUpper5x7[Digit]; case BigNumber::Font::Digit5x7: assert(Digit < 10); return Numbers5x7[Digit]; case BigNumber::Font::Digit11x20: assert(Digit < 10); return Numbers11x20[Digit]; case BigNumber::Font::Digit15x29: assert(Digit < 10); return Numbers15x29[Digit]; } return nullptr; } void BigNumber::Render(UWHDCanvas *Canvas, unsigned Display, unsigned char Digit, unsigned XOffs, unsigned YOffs, enum BigNumber::Font F, const UWHDPixel &FG, const UWHDPixel *BG) { unsigned H = height(F); unsigned W = width(F); const char *Character = character(F, Digit); if (!Character) return; XOffs += Display * 32; for (unsigned y = 0; y < H; y++) { for (unsigned x = 0; x < W; x++) { if (Character[x + y * W]) Canvas->at(XOffs + x, YOffs + y) = FG; else if (BG) Canvas->at(XOffs + x, YOffs + y) = *BG; } } } void BigNumber::printf(UWHDCanvas *Canvas, unsigned XS, unsigned YS, const UWHDPixel &FG, const UWHDPixel *BG, const char *Fmt, ...) { va_list a_list; va_start(a_list, Fmt); char Buff[32]; vsnprintf(Buff, sizeof(Buff), Fmt, a_list); unsigned XOffs = XS; unsigned YOffs = YS; for (unsigned I = 0, E = sizeof(Buff); I != E; ++I, XOffs += 6) { if (!Buff[I]) break; Render(Canvas, 0, Buff[I], XOffs, YOffs, BigNumber::Font::Ascii5x7, FG, BG); } }
31,944
https://github.com/b4hand/sauce/blob/master/vendor/uncrustify-0.59/tests/input/cpp/indent-misc.cpp
Github Open Source
Open Source
MIT
null
sauce
b4hand
C++
Code
111
261
struct S { int one, two; S(int i = 1) { one = i; two = i + i; } bool check() const { return one == 1; } }; struct S { enum { twentythree = 23, fortytwoseven = 427 }; int one, two; S(int i = 1) { one = i; two = i + i; } bool check() const { return one == 1; } }; static uint jhash(K x) { ubyte *k; uint a, b, c; uint a, b, c; len = x.length; } const char *token_names[] = { [CT_POUND] = "POUND", [CT_PREPROC] = "PREPROC", }; struct whoopee * foo4( int param1, int param2, char *param2 );
29,480
https://github.com/nicedream7758/radar/blob/master/radar-dal/src/main/java/com.pgmmers.radar/vo/model/EntityVO.java
Github Open Source
Open Source
Apache-2.0
2,022
radar
nicedream7758
Java
Code
16
54
package com.pgmmers.radar.vo.model; import java.io.Serializable; public class EntityVO implements Serializable{ static final long serialVersionUID = 988234234L; }
25,050
https://github.com/alias2320/controladores/blob/master/app/Http/Controllers/PaginasControler.php
Github Open Source
Open Source
MIT
null
controladores
alias2320
PHP
Code
36
136
<?php namespace App\Http\Controllers; use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class PaginasControler extends Controller { // public function ayuda() { $nombre = 'Angelica'; $apellido = 'Sandoval'; return view('paginas/ayuda',compact('nombre','apellido')); } public function acerca() { return view('acerca'); } }
50,235
https://github.com/skylark-integration/skylark-maqetta/blob/master/.original/seperated/frontend/app/static/lib/gridx/1.0.0/nls/nl/QuickFilter.js.uncompressed.js
Github Open Source
Open Source
MIT
null
skylark-maqetta
skylark-integration
JavaScript
Code
16
66
define( "gridx/nls/nl/QuickFilter", ({ filterLabel: 'Filter', clearButtonTitle: 'Filter wissen', buildFilterMenuLabel: 'Filter bouwen&hellip;', apply: 'Filter toepassen' }) );
17,870
https://github.com/dreamteamrepos/ansible-role-zabbix-server/blob/master/molecule/default/tests/test_default.py
Github Open Source
Open Source
MIT
2,019
ansible-role-zabbix-server
dreamteamrepos
Python
Code
91
608
import os import pytest import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('zabbix') def test_zabbix_server_running_and_enabled(host): zabbix = host.service("zabbix-server") assert zabbix.is_enabled assert zabbix.is_running @pytest.mark.parametrize("server", [("zabbix-server-mysql")]) def test_zabbix_package(server, host): zabbix_server = host.package(server) assert zabbix_server.version.startswith("4.2") assert zabbix_server.is_installed def test_zabbix_server_dot_conf(host): zabbix_server_conf = host.file("/etc/zabbix/zabbix_server.conf") assert zabbix_server_conf.user == "zabbix" assert zabbix_server_conf.group == "zabbix" assert zabbix_server_conf.mode == 0o640 assert zabbix_server_conf.contains("ListenPort=10051") assert zabbix_server_conf.contains("DebugLevel=3") def test_zabbix_include_dir(host): zabbix_include_dir = host.file("/etc/zabbix/zabbix_server.conf.d") assert zabbix_include_dir.is_directory assert zabbix_include_dir.user == "zabbix" assert zabbix_include_dir.group == "zabbix" # assert zabbix_include_dir.mode == 0o644 def test_zabbix_server_connect_connection(host): zabbix_server_socket = host.socket('tcp://10050') zabbix_agent_socket = host.socket('tcp://10051') assert zabbix_server_socket.is_listening assert zabbix_agent_socket.is_listening def test_zabbix_web_interface(host): zabbix_web = host.socket('tcp://80') assert zabbix_web.is_listening
42,516
https://github.com/magicyqy/QStack.Framework/blob/master/QStack.Framework.Basic.Models/ViewModel/UploadFileDto.cs
Github Open Source
Open Source
MIT
2,021
QStack.Framework
magicyqy
C#
Code
217
765
using QStack.Framework.Basic.Model; using QStack.Framework.Basic.ViewModel; using QStack.Framework.Core.Model; using System; using System.Collections.Generic; using System.Text; namespace QStack.Framework.Basic.ViewModel { public class UploadFileDto:BaseDto { /// <summary> /// 文件的md5码 /// </summary> public virtual string MD5Code { get; set; } /// <summary> /// 资源类型,图片,视频,文档等 /// </summary> public virtual ResouceTypeEnum ResouceType { get; set; } /// <summary> /// 文件后缀,如.doc,.png,.jpg /// </summary> public virtual string Extention { get; set; } /// <summary> /// 资源相对路径 /// </summary> public virtual string RUrl { get; set; } /// <summary> /// 资源名称 /// </summary> public virtual string Filename { get; set; } /// <summary> /// 图片的缩略图 /// </summary> public virtual string ThumbnailUrl { get; set; } /// <summary> /// 源图片宽 /// </summary> public virtual int SWidth { get; set; } /// <summary> /// 源图片高 /// </summary> public virtual int SHeight { get; set; } /// <summary> /// 缩略图宽 /// </summary> public virtual int TWidth { get; set; } /// <summary> /// 缩略图高 /// </summary> public virtual int THeight { get; set; } /// <summary> /// 视频或其他种类文件的截图 /// </summary> public virtual string FileCaptureUrl { get; set; } /// <summary> /// 描述 /// </summary> public virtual string Description { get; set; } /// <summary> /// 资源绑定先关的功能名称描述,如首页图片 /// </summary> public virtual string RelativeFucDes { get; set; } /// <summary> /// 关联的ID,存在多个资源的,需将相关的Id绑定到此字段,通过此字段查询返回多个资源的列表 /// </summary> public virtual string RelativeId { get; set; } } }
42,216
https://github.com/exerro/observables-kt/blob/master/src/main/kotlin/me/exerro/observables/MutableObservableValue.kt
Github Open Source
Open Source
MIT
null
observables-kt
exerro
Kotlin
Code
330
847
package me.exerro.observables import kotlin.reflect.KProperty /** An [MutableObservableValue] is a wrapper around a mutable value, which can * be connected to, to get notified of changes. It is the mutable equivalent of * [ObservableValue], letting you directly set the value. * * ``` * // example usage * val observableValue = someLibraryFunction() * val value by observableValue * * println(value) * //> something * * observableValue.connect(::println) * value = "hello" * //> hello * ``` * @see create * @See createLateInit */ interface MutableObservableValue<T>: ObservableValue<T> { override var currentValue: T /** Implement [setValue] to make this a valid mutable property delegate. */ operator fun setValue(self: Any?, property: KProperty<*>, value: T) /** @see MutableObservableValue */ companion object { /** Create a [MutableObservableValue] with an [initialValue]. * * ``` * val value = MutableObservableValue.create(3) * * println(value.currentValue) * //> 3 * * value.connect(::println) * value.currentValue = 2 * //> 2 * ``` * @see createLateInit * */ fun <T> create( initialValue: T ) = object: MutableObservableValue<T> { override var currentValue = initialValue set(value) { field = value manager.forEach { it(value) } } override val isInitialised = true override fun setValue(self: Any?, property: KProperty<*>, value: T) { currentValue = value } override fun getValue(self: Any?, property: KProperty<*>): T = currentValue override fun connect(onChanged: (T) -> Unit) = manager.add(onChanged) private val manager = ConnectionHelper<(T) -> Unit>() } /** Create a [MutableObservableValue] to be initialised later. * * ``` * val value = MutableObservableValue.createLateInit<Int>() * * value.connect(::println) * value.currentValue = 4 * //> 4 * ``` * @see create * */ fun <T: Any> createLateInit() = object: MutableObservableValue<T> { override var currentValue: T get() = value set(value) { this.value = value manager.forEach { it(value) } } override val isInitialised = ::value.isInitialized override fun setValue(self: Any?, property: KProperty<*>, value: T) { currentValue = value } override fun getValue(self: Any?, property: KProperty<*>): T = currentValue override fun connect(onChanged: (T) -> Unit) = manager.add(onChanged) private lateinit var value: T private val manager = ConnectionHelper<(T) -> Unit>() } } }
8,409
https://github.com/sarkapalkovicova/perun/blob/master/perun-base/src/main/java/cz/metacentrum/perun/core/api/ConsentStatus.java
Github Open Source
Open Source
BSD-2-Clause
null
perun
sarkapalkovicova
Java
Code
10
44
package cz.metacentrum.perun.core.api; public enum ConsentStatus { UNSIGNED, GRANTED, REVOKED }
34,970
https://github.com/smourier/DirectN/blob/master/DirectN/DirectN/Manual/IPropertyStore.cs
Github Open Source
Open Source
MIT
2,023
DirectN
smourier
C#
Code
75
264
using System; using System.Runtime.InteropServices; namespace DirectN { [ComImport, Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public partial interface IPropertyStore { [PreserveSig] HRESULT GetCount(/* [out] __RPC__out */ out uint cProps); [PreserveSig] HRESULT GetAt(/* [in] */ uint iProp, /* [out] __RPC__out */ out PROPERTYKEY pkey); [PreserveSig] HRESULT GetValue(/* [in] __RPC__in */ ref PROPERTYKEY key, /* [out] __RPC__out */ [In, Out] PropVariant pv); [PreserveSig] HRESULT SetValue(/* [in] __RPC__in */ ref PROPERTYKEY key, /* [in] __RPC__in */ PropVariant propvar); [PreserveSig] HRESULT Commit(); } }
46,464