repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
lucasbiel7/pasc
|
src/test/java/br/com/unibh/compiler/pasc/lexic/states/impl/IdentifierStateTest.java
|
package br.com.unibh.compiler.pasc.lexic.states.impl;
import br.com.unibh.compiler.pasc.lexic.model.KeyWorld;
import br.com.unibh.compiler.pasc.lexic.states.State;
import br.com.unibh.compiler.pasc.lexic.states.ValidateStateHelperTest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.util.Locale;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@DisplayName("Testando quando aparecer um identificador")
class IdentifierStateTest extends ValidateStateHelperTest {
@DisplayName("Teste Identificador de Palavra Reservada")
@Test
void testWhenFindIdentifierKW() {
State state = runProgram("if");
assertTrue(state instanceof IdentifierState);
if (state instanceof IdentifierState identifierState) {
assertEquals("if", identifierState.value());
assertEquals(KeyWorld.IF.getTokenName(), identifierState.name());
}
}
@DisplayName("Teste Identificador de palavra")
@Test
void testWhenFindIdentifier() {
State state = runProgram("var");
assertTrue(state instanceof IdentifierState);
if (state instanceof IdentifierState identifierState) {
assertEquals("var", identifierState.value());
assertEquals("ID", identifierState.name());
}
}
@DisplayName("Testando todas as palavras reservadas")
@ParameterizedTest(name = "keyword")
@EnumSource(value = KeyWorld.class, names = {
"PROGRAM",
"IF",
"ELSE",
"WHILE",
"WRITE",
"READ",
"NUM",
"CHAR",
"NOT",
"OR",
"AND"
})
void testWhenUseAllKeyWorlds(KeyWorld keyWorld) {
State state = runProgram(keyWorld.getValue());
assertTrue(state instanceof IdentifierState);
if (state instanceof IdentifierState identifierState) {
assertEquals(keyWorld.getValue(), identifierState.value());
assertEquals(keyWorld.getTokenName(), identifierState.name());
}
}
@DisplayName("Testando todas as palavras reservadas em Upper Case")
@ParameterizedTest(name = "keyword")
@EnumSource(value = KeyWorld.class, names = {
"PROGRAM",
"IF",
"ELSE",
"WHILE",
"WRITE",
"READ",
"NUM",
"CHAR",
"NOT",
"OR",
"AND"
})
void testWhenUseAllKeyWorldsUpperCase(KeyWorld keyWorld) {
State state = runProgram(keyWorld.getValue().toUpperCase(Locale.ROOT));
assertTrue(state instanceof IdentifierState);
if (state instanceof IdentifierState identifierState) {
assertEquals(keyWorld.getValue().toUpperCase(Locale.ROOT), identifierState.value());
assertEquals(keyWorld.getTokenName(), identifierState.name());
}
}
@DisplayName("Teste Identificador de palavra com numeros")
@Test
void testWhenFindIdentifierWithNumber() {
State state = runProgram("var1");
assertTrue(state instanceof IdentifierState);
if (state instanceof IdentifierState identifierState) {
assertEquals("var1", identifierState.value());
assertEquals("ID", identifierState.name());
}
}
@DisplayName("Teste Identificador de palavra com símbolos ")
@Test
void testWhenFindIdentifierWithSymbol() {
assertThrows(UnsupportedOperationException.class, () -> runProgram("var@v"));
}
}
|
suhwanhwang/problem-solving
|
google/2017/r1a/b/b.1.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void printSolution1(int n, int p, const vector<int> &in, const vector<vector<int>> &qu) {
int max_count = 0;
for (int i = 0; i < n; ++i) {
int count = 0;
for (int j = 0; j < p; ++j) {
int q = qu[i][j];
int portion = 0;
for (int k = q/in[i]; k <= q/in[i] + 1; ++k) {
int low = in[i] * k * 0.9;
int high = in[i] * k * 1.1;
if (low <= q && q <= high) {
portion = k;
break;
}
}
if (portion == 0) {
continue;
}
bool isOK = true;
for (int k = 0; k < n; ++k) {
int low = in[k] * portion * 0.9;
int high = in[k] * portion * 1.1;
bool found = false;
for (int l = 0; l < p; ++l) {
if (low <= qu[k][l] && qu[k][l] <= high) {
found = true;
break;
}
}
if (!found) {
isOK = false;
break;
}
}
if (isOK) {
count++;
}
}
max_count = max(max_count, count);
}
cout << max_count << endl;
}
void printSolution(int n, int p, const vector<int> &in, const vector<vector<int>> &qu) {
int max_portion = 0;
for (int i = 0; i < n; ++i) {
max_portion = max(max_portion, qu[i].back() / in[i] + 1);
}
int total_count = 0;
for (int i = 1; i <= max_portion; ++i) {
bool isOk = true;
int min_count = INT_MAX;
for (int j = 0; j < n; ++j) {
int quantity = in[j] * i;
int low = quantity * 0.9;
int high = quantity * 1.1;
// auto it_lo = lower_bound(qu[j].begin(), qu[j].end(), low);
// auto it_hi = upper_bound(qu[j].begin(), qu[j].end(), high);
// if (it_lo == it_hi) {
// break;
// }
// if (it_lo == qu[j].end() && it_hi == qu[j].end()) {
// break;
// }
int count = 0;
for (int k = 0; k < p; ++k) {
if (low <= qu[j][k] && qu[j][k] <= high) {
count++;
}
}
if (count == 0) {
isOk = false;
break;
}
min_count = min(min_count, count);
}
if (isOk) {
total_count += min_count;
}
}
if (total_count > p) {
total_count = p;
}
cout << total_count << endl;
}
int main(int argc, char* argv[]) {
int t;
cin >> t;
for (int i = 1; i <=t; ++i) {
int n, p;
cin >> n >> p;
vector<int> ingredient;
for (int j = 0; j < n; ++j) {
int temp;
cin >> temp;
ingredient.push_back(temp);
}
vector<vector<int>> quantity;
for (int j = 0; j < n; ++j) {
vector<int> q;
for (int k = 0; k < p; ++k) {
int temp;
cin >> temp;
q.push_back(temp);
}
sort(q.begin(), q.end());
quantity.push_back(q);
}
cout << "Case #" << i << ": ";
printSolution(n, p, ingredient, quantity);
}
return 0;
}
|
Dearyu/NetPresenter
|
netpresenter-code/src/main/java/netpresenter/annotations/NetListener.java
|
package netpresenter.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author junweiliu
* @Description 网络监听
* @Version 1.0
* @CreateDate 2021/3/9
* @QQ 1007271386
*/
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface NetListener {
}
|
jinziyi/notes
|
notes-server/test/chai.test.js
|
<gh_stars>0
/**
* Created by cjy on 16/11/23.
*/
const {expect} = require('chai');
describe('chai expect demo', () => {
it('expect equal', function () {
expect(1 + 1).to.equal(2);
expect(1 + 1).not.equal(3);
})
})
|
Bart0llo/share
|
src/validation/api/v2/upload.js
|
<filename>src/validation/api/v2/upload.js<gh_stars>10-100
const isEmpty = require('../../isEmpty');
module.exports = (req, res, next) => {
try {
let errors = {};
if (typeof req.files.file === 'undefined') {
errors = 'File is required.';
}
if (!isEmpty(errors)) {
return res.status(400).json({
auth: true,
success: false,
errors
});
}
next();
} catch (err) {
console.error(err);
res.status(500).send('Server error');
}
};
|
akazad13/competitive-programming
|
Online Judges/LightOJ/1088 - Points in Segments.cpp
|
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define read(n) scanf("%d",&n)
int main()
{
int test,arr[100010],seg,n,p,q,element;
read(test);
for(int Case = 1 ; Case<=test ; Case++)
{
read(n);
read(seg);
for(int i=0;i<n;i++)
read(arr[i]);
printf("Case %d:\n",Case);
for(int i=0;i<seg;i++)
{
read(p);read(q);
element = upper_bound(arr,arr+n,q)-lower_bound(arr,arr+n,p);
printf("%d\n",element);
}
}
return 0;
}
|
MouchenHung-QUANTA/OpenBIC
|
meta-facebook/yv35-bb/src/platform/plat_def.h
|
#ifndef PLAT_DEF_H
#define PLAT_DEF_H
#define BMC_USB_PORT "CDC_ACM_0"
#define ENABLE_FAN
#define HSC_DEVICE_READY_DELAY_MS 2000
#endif
|
fahimfarhan/cancer-web-app
|
surgeryhormone/forms.py
|
from django import forms
from surgeryhormone.models import Surgery, Hormone
class SurgeryForm(forms.ModelForm):
class Meta:
model = Surgery
fields = ('details',)
class HormoneForm(forms.ModelForm):
class Meta:
model = Hormone
fields = ('details',)
|
PharrellWANG/HTM_16_9_AppCode
|
source/codemapsHTM/search/enumvalues_4.js
|
<gh_stars>0
var searchData=
[
['no_5fslices',['NO_SLICES',['../d7/dca/_type_def_8h.html#add7235a66eb4e5f93c692468c39dde44af8644cb7c6cd021a2f8a34fba0419a13',1,'TypeDef.h']]]
];
|
teamleadercrm/ui
|
src/components/datagrid/Row.js
|
import React, { forwardRef, PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
class Row extends PureComponent {
render() {
const { backgroundColor, className, children, forwardedRef, ...others } = this.props;
const classNames = cx(theme['row'], theme[`has-background-${backgroundColor}`], className);
return (
<Box className={classNames} ref={forwardedRef} {...others}>
{children}
</Box>
);
}
}
Row.propTypes = {
backgroundColor: PropTypes.oneOf(['white', 'neutral']),
className: PropTypes.string,
children: PropTypes.any,
};
Row.defaultProps = {
backgroundColor: 'white',
};
const ForwardedRow = forwardRef((props, ref) => <Row {...props} forwardedRef={ref} />);
ForwardedRow.displayName = 'Row';
export default ForwardedRow;
|
syslogic/androidx-github
|
mobile/src/main/java/io/syslogic/github/content/RepositorySyncAdapter.java
|
<gh_stars>1-10
package io.syslogic.github.content;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SyncResult;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import java.util.ArrayList;
import java.util.List;
import io.syslogic.github.BuildConfig;
import io.syslogic.github.Constants;
import io.syslogic.github.model.QueryString;
import io.syslogic.github.model.Repositories;
import io.syslogic.github.model.Repository;
import io.syslogic.github.model.User;
import io.syslogic.github.network.TokenHelper;
import io.syslogic.github.retrofit.GithubClient;
import io.syslogic.github.room.Abstraction;
import io.syslogic.github.room.QueryStringsDao;
import io.syslogic.github.room.RepositoriesDao;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Repository {@link AbstractThreadedSyncAdapter}
* @author <NAME>
*/
public class RepositorySyncAdapter extends AbstractThreadedSyncAdapter {
/** Log Tag */
@NonNull
private static final String LOG_TAG = RepositorySyncAdapter.class.getSimpleName();
/** Debug Output */
static final boolean mDebug = BuildConfig.DEBUG;
private final String accessToken;
private final SharedPreferences prefs;
private final QueryStringsDao queryStringsDao;
private final RepositoriesDao repositoriesDao;
private ArrayList<Repository> repositories = new ArrayList<>();
private List<QueryString> queryStrings;
private User user;
/** Constructor. */
public RepositorySyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
super(context, autoInitialize, allowParallelSyncs);
this.accessToken = TokenHelper.getAccessToken(context);
this.prefs = PreferenceManager.getDefaultSharedPreferences(context);
this.repositoriesDao = Abstraction.getInstance(context).repositoriesDao();
this.queryStringsDao = Abstraction.getInstance(context).queryStringsDao();
if (mDebug && this.prefs.getBoolean(Constants.PREFERENCE_KEY_DEBUG_LOGGING, false)) {
Log.d(LOG_TAG, "Verbose logging is active.");
}
}
/**
* Perform a sync for this account. SyncAdapter-specific parameters may be specified in extras,
* which is guaranteed to not be null. Invocations of this method are guaranteed to be serialized.
*
* @param account the account that should be synced
* @param extras SyncAdapter-specific parameters
* @param authority the authority of this sync request
* @param provider a ContentProviderClient that points to the ContentProvider for this authority
* @param syncResult SyncAdapter-specific parameters
*/
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
if (this.accessToken != null) {
Call<User> api = GithubClient.getUser(this.accessToken);
this.log("" + api.request().url());
api.enqueue(new Callback<User>() {
@Override
public void onResponse(@NonNull Call<User> call, @NonNull Response<User> response) {
if (response.body() != null) {
onUser(response.body());
Abstraction.executorService.execute(() -> onQueryStrings(queryStringsDao.getItems()));
}
}
public void onFailure(@NonNull Call<User> call, @NonNull Throwable t) {
if (mDebug) {Log.e(LOG_TAG, "" + t.getMessage());}
}
});
}
}
private void onUser(@NonNull User item) {
this.log("onUser: " + item.getLogin());
this.user = item;
}
private void onQueryStrings(@NonNull List<QueryString> items) {
this.log("onQueryStrings: " + items.size());
this.queryStrings = items;
for (QueryString item: items) {
Call<Repositories> api = GithubClient.getRepositories(this.accessToken, item.toQueryString(), "forks", "desc", 1);
this.log("Building content cache for query-string: " + item.toQueryString());
this.log("" + api.request().url());
api.enqueue(new Callback<Repositories>() {
@Override
public void onResponse(@NonNull Call<Repositories> call, @NonNull Response<Repositories> response) {
if (response.body() != null) {onRepositories(response.body());}
}
@Override
public void onFailure(@NonNull Call<Repositories> call, @NonNull Throwable t) {
if (mDebug) {Log.e(LOG_TAG, "" + t.getMessage());}
}
});
}
}
private void onRepositories(@NonNull Repositories item) {
this.log("onRepositories: " + item.getRepositories().size());
for (Repository repository: item.getRepositories()) {
this.log("Repo: " + repository.getUrl());
this.repositories.add(repository);
}
this.log("expected item count: " + item.getTotalCount());
this.log("expected page count: " + item.getPageCount());
this.log("loaded so far: " + this.repositories.size());
}
private void log(String message) {
if (mDebug && this.prefs.getBoolean(Constants.PREFERENCE_KEY_DEBUG_LOGGING, false)) {
Log.d(LOG_TAG, message);
}
}
}
|
icred/base
|
model/src/model-generated/eu/icred/model/node/entity/Property.java
|
package eu.icred.model.node.entity;
import eu.icred.model.annotation.ChildList;
import eu.icred.model.annotation.DataField;
import eu.icred.model.annotation.GroupNode;
import eu.icred.model.annotation.Node;
import eu.icred.model.datatype.Amount;
import eu.icred.model.datatype.Area;
import eu.icred.model.datatype.enumeration.AreaMeasurement;
import eu.icred.model.datatype.enumeration.AreaType;
import eu.icred.model.datatype.enumeration.AssetAccountType;
import eu.icred.model.datatype.enumeration.AssetCategory;
import eu.icred.model.datatype.enumeration.BuildingType;
import eu.icred.model.datatype.enumeration.ConstructionPhase;
import eu.icred.model.datatype.enumeration.HeatingType;
import eu.icred.model.datatype.enumeration.InteriorQuality;
import eu.icred.model.datatype.enumeration.LocationType;
import eu.icred.model.datatype.enumeration.MonumentsType;
import eu.icred.model.datatype.enumeration.ObjectCondition;
import eu.icred.model.datatype.enumeration.OptRate;
import eu.icred.model.datatype.enumeration.OwnershipType;
import eu.icred.model.datatype.enumeration.PortfolioType;
import eu.icred.model.datatype.enumeration.RestorationStatus;
import eu.icred.model.datatype.enumeration.RetailLocationType;
import eu.icred.model.datatype.enumeration.RiskSegment;
import eu.icred.model.node.entity.AbstractEntityNode;
import eu.icred.model.node.group.Address;
import java.lang.Boolean;
import java.lang.Double;
import java.lang.Integer;
import java.lang.String;
import java.util.Currency;
import java.util.Map;
import org.joda.time.LocalDate;
@Node
public class Property extends AbstractEntityNode {
@DataField
protected Amount administrationCosts;
public Amount getAdministrationCosts() {
return this.administrationCosts;
}
public void setAdministrationCosts(Amount administrationCosts) {
this.administrationCosts = administrationCosts;
}
@DataField
protected Boolean airconditioning;
public Boolean getAirconditioning() {
return this.airconditioning;
}
public void setAirconditioning(Boolean airconditioning) {
this.airconditioning = airconditioning;
}
@DataField
protected LocalDate archValidFrom;
public LocalDate getArchValidFrom() {
return this.archValidFrom;
}
public void setArchValidFrom(LocalDate archValidFrom) {
this.archValidFrom = archValidFrom;
}
@DataField
protected LocalDate archValidTo;
public LocalDate getArchValidTo() {
return this.archValidTo;
}
public void setArchValidTo(LocalDate archValidTo) {
this.archValidTo = archValidTo;
}
@DataField
protected AreaMeasurement areaMeasurement;
public AreaMeasurement getAreaMeasurement() {
return this.areaMeasurement;
}
public void setAreaMeasurement(AreaMeasurement areaMeasurement) {
this.areaMeasurement = areaMeasurement;
}
@DataField
protected AreaType areaType;
public AreaType getAreaType() {
return this.areaType;
}
public void setAreaType(AreaType areaType) {
this.areaType = areaType;
}
@DataField
protected AssetAccountType assetAccountType;
public AssetAccountType getAssetAccountType() {
return this.assetAccountType;
}
public void setAssetAccountType(AssetAccountType assetAccountType) {
this.assetAccountType = assetAccountType;
}
@DataField
protected AssetCategory assetCategory;
public AssetCategory getAssetCategory() {
return this.assetCategory;
}
public void setAssetCategory(AssetCategory assetCategory) {
this.assetCategory = assetCategory;
}
@DataField
protected String assetManager;
public String getAssetManager() {
return this.assetManager;
}
public void setAssetManager(String assetManager) {
this.assetManager = assetManager;
}
@DataField
protected Amount assetValue;
public Amount getAssetValue() {
return this.assetValue;
}
public void setAssetValue(Amount assetValue) {
this.assetValue = assetValue;
}
@DataField
protected Boolean balcony;
public Boolean getBalcony() {
return this.balcony;
}
public void setBalcony(Boolean balcony) {
this.balcony = balcony;
}
@DataField
protected Boolean barrierfree;
public Boolean getBarrierfree() {
return this.barrierfree;
}
public void setBarrierfree(Boolean barrierfree) {
this.barrierfree = barrierfree;
}
@DataField
protected Amount capitalIncome;
public Amount getCapitalIncome() {
return this.capitalIncome;
}
public void setCapitalIncome(Amount capitalIncome) {
this.capitalIncome = capitalIncome;
}
@DataField
protected Boolean cellar;
public Boolean getCellar() {
return this.cellar;
}
public void setCellar(Boolean cellar) {
this.cellar = cellar;
}
@DataField
protected ObjectCondition condition;
public ObjectCondition getCondition() {
return this.condition;
}
public void setCondition(ObjectCondition condition) {
this.condition = condition;
}
@DataField
protected LocalDate constructionDate;
public LocalDate getConstructionDate() {
return this.constructionDate;
}
public void setConstructionDate(LocalDate constructionDate) {
this.constructionDate = constructionDate;
}
@DataField
protected ConstructionPhase constructionPhase;
public ConstructionPhase getConstructionPhase() {
return this.constructionPhase;
}
public void setConstructionPhase(ConstructionPhase constructionPhase) {
this.constructionPhase = constructionPhase;
}
@DataField
protected Amount courtage;
public Amount getCourtage() {
return this.courtage;
}
public void setCourtage(Amount courtage) {
this.courtage = courtage;
}
@DataField
protected Currency currency;
public Currency getCurrency() {
return this.currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
@DataField
protected Double distanceToAirport;
public Double getDistanceToAirport() {
return this.distanceToAirport;
}
public void setDistanceToAirport(Double distanceToAirport) {
this.distanceToAirport = distanceToAirport;
}
@DataField
protected Double distanceToHighway;
public Double getDistanceToHighway() {
return this.distanceToHighway;
}
public void setDistanceToHighway(Double distanceToHighway) {
this.distanceToHighway = distanceToHighway;
}
@DataField
protected Double distanceToPublicTransport;
public Double getDistanceToPublicTransport() {
return this.distanceToPublicTransport;
}
public void setDistanceToPublicTransport(Double distanceToPublicTransport) {
this.distanceToPublicTransport = distanceToPublicTransport;
}
@DataField
protected Double distanceToRailStation;
public Double getDistanceToRailStation() {
return this.distanceToRailStation;
}
public void setDistanceToRailStation(Double distanceToRailStation) {
this.distanceToRailStation = distanceToRailStation;
}
@DataField
protected LocalDate economicConstructionDate;
public LocalDate getEconomicConstructionDate() {
return this.economicConstructionDate;
}
public void setEconomicConstructionDate(LocalDate economicConstructionDate) {
this.economicConstructionDate = economicConstructionDate;
}
@DataField
protected Boolean elevator;
public Boolean getElevator() {
return this.elevator;
}
public void setElevator(Boolean elevator) {
this.elevator = elevator;
}
@DataField
protected String facilityManager;
public String getFacilityManager() {
return this.facilityManager;
}
public void setFacilityManager(String facilityManager) {
this.facilityManager = facilityManager;
}
@DataField
protected Amount fairValue;
public Amount getFairValue() {
return this.fairValue;
}
public void setFairValue(Amount fairValue) {
this.fairValue = fairValue;
}
@DataField
protected Amount groundRent;
public Amount getGroundRent() {
return this.groundRent;
}
public void setGroundRent(Amount groundRent) {
this.groundRent = groundRent;
}
@DataField
protected HeatingType heatingType;
public HeatingType getHeatingType() {
return this.heatingType;
}
public void setHeatingType(HeatingType heatingType) {
this.heatingType = heatingType;
}
@DataField
protected InteriorQuality interiorQuality;
public InteriorQuality getInteriorQuality() {
return this.interiorQuality;
}
public void setInteriorQuality(InteriorQuality interiorQuality) {
this.interiorQuality = interiorQuality;
}
@DataField
protected String ipdObjectId;
public String getIpdObjectId() {
return this.ipdObjectId;
}
public void setIpdObjectId(String ipdObjectId) {
this.ipdObjectId = ipdObjectId;
}
@DataField
protected String ipdPortfolioId;
public String getIpdPortfolioId() {
return this.ipdPortfolioId;
}
public void setIpdPortfolioId(String ipdPortfolioId) {
this.ipdPortfolioId = ipdPortfolioId;
}
@DataField
protected Boolean lanCables;
public Boolean getLanCables() {
return this.lanCables;
}
public void setLanCables(Boolean lanCables) {
this.lanCables = lanCables;
}
@DataField
protected LocalDate lastRefurbishmentDate;
public LocalDate getLastRefurbishmentDate() {
return this.lastRefurbishmentDate;
}
public void setLastRefurbishmentDate(LocalDate lastRefurbishmentDate) {
this.lastRefurbishmentDate = lastRefurbishmentDate;
}
@DataField
protected Area leasedArea;
public Area getLeasedArea() {
return this.leasedArea;
}
public void setLeasedArea(Area leasedArea) {
this.leasedArea = leasedArea;
}
@DataField
protected LocationType locationClassificationType;
public LocationType getLocationClassificationType() {
return this.locationClassificationType;
}
public void setLocationClassificationType(LocationType locationClassificationType) {
this.locationClassificationType = locationClassificationType;
}
@DataField
protected Amount maintenanceCosts;
public Amount getMaintenanceCosts() {
return this.maintenanceCosts;
}
public void setMaintenanceCosts(Amount maintenanceCosts) {
this.maintenanceCosts = maintenanceCosts;
}
@DataField
protected Amount marketRentalValue;
public Amount getMarketRentalValue() {
return this.marketRentalValue;
}
public void setMarketRentalValue(Amount marketRentalValue) {
this.marketRentalValue = marketRentalValue;
}
@DataField
protected RestorationStatus modernisationStatus;
public RestorationStatus getModernisationStatus() {
return this.modernisationStatus;
}
public void setModernisationStatus(RestorationStatus modernisationStatus) {
this.modernisationStatus = modernisationStatus;
}
@DataField
protected MonumentsType monumentProtectionCategory;
public MonumentsType getMonumentProtectionCategory() {
return this.monumentProtectionCategory;
}
public void setMonumentProtectionCategory(MonumentsType monumentProtectionCategory) {
this.monumentProtectionCategory = monumentProtectionCategory;
}
@DataField
protected Amount netIncome;
public Amount getNetIncome() {
return this.netIncome;
}
public void setNetIncome(Amount netIncome) {
this.netIncome = netIncome;
}
@DataField
protected String note;
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
@DataField
protected Integer numberOfBathrooms;
public Integer getNumberOfBathrooms() {
return this.numberOfBathrooms;
}
public void setNumberOfBathrooms(Integer numberOfBathrooms) {
this.numberOfBathrooms = numberOfBathrooms;
}
@DataField
protected Integer numberOfBedrooms;
public Integer getNumberOfBedrooms() {
return this.numberOfBedrooms;
}
public void setNumberOfBedrooms(Integer numberOfBedrooms) {
this.numberOfBedrooms = numberOfBedrooms;
}
@DataField
protected Integer numberOfCanteen;
public Integer getNumberOfCanteen() {
return this.numberOfCanteen;
}
public void setNumberOfCanteen(Integer numberOfCanteen) {
this.numberOfCanteen = numberOfCanteen;
}
@DataField
protected Integer numberOfParkingSpaces;
public Integer getNumberOfParkingSpaces() {
return this.numberOfParkingSpaces;
}
public void setNumberOfParkingSpaces(Integer numberOfParkingSpaces) {
this.numberOfParkingSpaces = numberOfParkingSpaces;
}
@DataField
protected Double numberOfRooms;
public Double getNumberOfRooms() {
return this.numberOfRooms;
}
public void setNumberOfRooms(Double numberOfRooms) {
this.numberOfRooms = numberOfRooms;
}
@DataField
protected Amount operatingCosts;
public Amount getOperatingCosts() {
return this.operatingCosts;
}
public void setOperatingCosts(Amount operatingCosts) {
this.operatingCosts = operatingCosts;
}
@DataField
protected Amount operatingCostsSettled;
public Amount getOperatingCostsSettled() {
return this.operatingCostsSettled;
}
public void setOperatingCostsSettled(Amount operatingCostsSettled) {
this.operatingCostsSettled = operatingCostsSettled;
}
@DataField
protected OptRate optRate;
public OptRate getOptRate() {
return this.optRate;
}
public void setOptRate(OptRate optRate) {
this.optRate = optRate;
}
@DataField
protected Amount otherCosts;
public Amount getOtherCosts() {
return this.otherCosts;
}
public void setOtherCosts(Amount otherCosts) {
this.otherCosts = otherCosts;
}
@DataField
protected Boolean ownerOccupation;
public Boolean getOwnerOccupation() {
return this.ownerOccupation;
}
public void setOwnerOccupation(Boolean ownerOccupation) {
this.ownerOccupation = ownerOccupation;
}
@DataField
protected Double ownershipShare;
public Double getOwnershipShare() {
return this.ownershipShare;
}
public void setOwnershipShare(Double ownershipShare) {
this.ownershipShare = ownershipShare;
}
@DataField
protected OwnershipType ownershipType;
public OwnershipType getOwnershipType() {
return this.ownershipType;
}
public void setOwnershipType(OwnershipType ownershipType) {
this.ownershipType = ownershipType;
}
@DataField
protected Amount partialPurchase;
public Amount getPartialPurchase() {
return this.partialPurchase;
}
public void setPartialPurchase(Amount partialPurchase) {
this.partialPurchase = partialPurchase;
}
@DataField
protected Amount partialSales;
public Amount getPartialSales() {
return this.partialSales;
}
public void setPartialSales(Amount partialSales) {
this.partialSales = partialSales;
}
@DataField
protected Area plotArea;
public Area getPlotArea() {
return this.plotArea;
}
public void setPlotArea(Area plotArea) {
this.plotArea = plotArea;
}
@DataField
protected String portfolioName;
public String getPortfolioName() {
return this.portfolioName;
}
public void setPortfolioName(String portfolioName) {
this.portfolioName = portfolioName;
}
@DataField
protected String portfolioPartName;
public String getPortfolioPartName() {
return this.portfolioPartName;
}
public void setPortfolioPartName(String portfolioPartName) {
this.portfolioPartName = portfolioPartName;
}
@DataField
protected PortfolioType portfolioType;
public PortfolioType getPortfolioType() {
return this.portfolioType;
}
public void setPortfolioType(PortfolioType portfolioType) {
this.portfolioType = portfolioType;
}
@DataField
protected String propertyManager;
public String getPropertyManager() {
return this.propertyManager;
}
public void setPropertyManager(String propertyManager) {
this.propertyManager = propertyManager;
}
@DataField
protected Amount purchaseAdditionalCosts;
public Amount getPurchaseAdditionalCosts() {
return this.purchaseAdditionalCosts;
}
public void setPurchaseAdditionalCosts(Amount purchaseAdditionalCosts) {
this.purchaseAdditionalCosts = purchaseAdditionalCosts;
}
@DataField
protected Amount purchaseBrokerage;
public Amount getPurchaseBrokerage() {
return this.purchaseBrokerage;
}
public void setPurchaseBrokerage(Amount purchaseBrokerage) {
this.purchaseBrokerage = purchaseBrokerage;
}
@DataField
protected LocalDate purchaseDate;
public LocalDate getPurchaseDate() {
return this.purchaseDate;
}
public void setPurchaseDate(LocalDate purchaseDate) {
this.purchaseDate = purchaseDate;
}
@DataField
protected Amount purchaseGrossPrice;
public Amount getPurchaseGrossPrice() {
return this.purchaseGrossPrice;
}
public void setPurchaseGrossPrice(Amount purchaseGrossPrice) {
this.purchaseGrossPrice = purchaseGrossPrice;
}
@DataField
protected Amount purchaseLegalFees;
public Amount getPurchaseLegalFees() {
return this.purchaseLegalFees;
}
public void setPurchaseLegalFees(Amount purchaseLegalFees) {
this.purchaseLegalFees = purchaseLegalFees;
}
@DataField
protected Amount purchaseNetPrice;
public Amount getPurchaseNetPrice() {
return this.purchaseNetPrice;
}
public void setPurchaseNetPrice(Amount purchaseNetPrice) {
this.purchaseNetPrice = purchaseNetPrice;
}
@DataField
protected Amount purchaseTransferTax;
public Amount getPurchaseTransferTax() {
return this.purchaseTransferTax;
}
public void setPurchaseTransferTax(Amount purchaseTransferTax) {
this.purchaseTransferTax = purchaseTransferTax;
}
@DataField
protected Amount rentalIncomeAdditional;
public Amount getRentalIncomeAdditional() {
return this.rentalIncomeAdditional;
}
public void setRentalIncomeAdditional(Amount rentalIncomeAdditional) {
this.rentalIncomeAdditional = rentalIncomeAdditional;
}
@DataField
protected Amount rentalIncomeMain;
public Amount getRentalIncomeMain() {
return this.rentalIncomeMain;
}
public void setRentalIncomeMain(Amount rentalIncomeMain) {
this.rentalIncomeMain = rentalIncomeMain;
}
@DataField
protected Boolean rented;
public Boolean getRented() {
return this.rented;
}
public void setRented(Boolean rented) {
this.rented = rented;
}
@DataField
protected RetailLocationType retailLocation;
public RetailLocationType getRetailLocation() {
return this.retailLocation;
}
public void setRetailLocation(RetailLocationType retailLocation) {
this.retailLocation = retailLocation;
}
@DataField
protected RiskSegment riskStyle;
public RiskSegment getRiskStyle() {
return this.riskStyle;
}
public void setRiskStyle(RiskSegment riskStyle) {
this.riskStyle = riskStyle;
}
@DataField
protected Amount saleAdditionalCosts;
public Amount getSaleAdditionalCosts() {
return this.saleAdditionalCosts;
}
public void setSaleAdditionalCosts(Amount saleAdditionalCosts) {
this.saleAdditionalCosts = saleAdditionalCosts;
}
@DataField
protected Amount saleBrokerage;
public Amount getSaleBrokerage() {
return this.saleBrokerage;
}
public void setSaleBrokerage(Amount saleBrokerage) {
this.saleBrokerage = saleBrokerage;
}
@DataField
protected LocalDate saleDate;
public LocalDate getSaleDate() {
return this.saleDate;
}
public void setSaleDate(LocalDate saleDate) {
this.saleDate = saleDate;
}
@DataField
protected Amount saleGrossPrice;
public Amount getSaleGrossPrice() {
return this.saleGrossPrice;
}
public void setSaleGrossPrice(Amount saleGrossPrice) {
this.saleGrossPrice = saleGrossPrice;
}
@DataField
protected Amount saleNetPrice;
public Amount getSaleNetPrice() {
return this.saleNetPrice;
}
public void setSaleNetPrice(Amount saleNetPrice) {
this.saleNetPrice = saleNetPrice;
}
@DataField
protected Amount saleTransferTax;
public Amount getSaleTransferTax() {
return this.saleTransferTax;
}
public void setSaleTransferTax(Amount saleTransferTax) {
this.saleTransferTax = saleTransferTax;
}
@DataField
protected String titleOfExposee;
public String getTitleOfExposee() {
return this.titleOfExposee;
}
public void setTitleOfExposee(String titleOfExposee) {
this.titleOfExposee = titleOfExposee;
}
@DataField
protected Amount totalApportionableCosts;
public Amount getTotalApportionableCosts() {
return this.totalApportionableCosts;
}
public void setTotalApportionableCosts(Amount totalApportionableCosts) {
this.totalApportionableCosts = totalApportionableCosts;
}
@DataField
protected Amount totalGrossCosts;
public Amount getTotalGrossCosts() {
return this.totalGrossCosts;
}
public void setTotalGrossCosts(Amount totalGrossCosts) {
this.totalGrossCosts = totalGrossCosts;
}
@DataField
protected Amount totalNetCosts;
public Amount getTotalNetCosts() {
return this.totalNetCosts;
}
public void setTotalNetCosts(Amount totalNetCosts) {
this.totalNetCosts = totalNetCosts;
}
@DataField
protected BuildingType useTypePrimary;
public BuildingType getUseTypePrimary() {
return this.useTypePrimary;
}
public void setUseTypePrimary(BuildingType useTypePrimary) {
this.useTypePrimary = useTypePrimary;
}
@DataField
protected BuildingType useTypeSecondary;
public BuildingType getUseTypeSecondary() {
return this.useTypeSecondary;
}
public void setUseTypeSecondary(BuildingType useTypeSecondary) {
this.useTypeSecondary = useTypeSecondary;
}
@DataField
protected Amount vacancyOperatingCosts;
public Amount getVacancyOperatingCosts() {
return this.vacancyOperatingCosts;
}
public void setVacancyOperatingCosts(Amount vacancyOperatingCosts) {
this.vacancyOperatingCosts = vacancyOperatingCosts;
}
@DataField
protected Amount valueIncreasingReconstructCosts;
public Amount getValueIncreasingReconstructCosts() {
return this.valueIncreasingReconstructCosts;
}
public void setValueIncreasingReconstructCosts(Amount valueIncreasingReconstructCosts) {
this.valueIncreasingReconstructCosts = valueIncreasingReconstructCosts;
}
@GroupNode
protected Address address;
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
@ChildList
protected Map<String, Project> projects;
public Map<String, Project> getProjects() {
return this.projects;
}
public void setProjects(Map<String, Project> projects) {
this.projects = projects;
}
@ChildList
protected Map<String, Land> lands;
public Map<String, Land> getLands() {
return this.lands;
}
public void setLands(Map<String, Land> lands) {
this.lands = lands;
}
@ChildList
protected Map<String, Building> buildings;
public Map<String, Building> getBuildings() {
return this.buildings;
}
public void setBuildings(Map<String, Building> buildings) {
this.buildings = buildings;
}
@ChildList
protected Map<String, Lease> leases;
public Map<String, Lease> getLeases() {
return this.leases;
}
public void setLeases(Map<String, Lease> leases) {
this.leases = leases;
}
@ChildList
protected Map<String, ServiceContract> serviceContracts;
public Map<String, ServiceContract> getServiceContracts() {
return this.serviceContracts;
}
public void setServiceContracts(Map<String, ServiceContract> serviceContracts) {
this.serviceContracts = serviceContracts;
}
@ChildList
protected Map<String, Valuation> valuations;
public Map<String, Valuation> getValuations() {
return this.valuations;
}
public void setValuations(Map<String, Valuation> valuations) {
this.valuations = valuations;
}
@ChildList
protected Map<String, Record> records;
public Map<String, Record> getRecords() {
return this.records;
}
public void setRecords(Map<String, Record> records) {
this.records = records;
}
@ChildList
protected Map<String, Account> accounts;
public Map<String, Account> getAccounts() {
return this.accounts;
}
public void setAccounts(Map<String, Account> accounts) {
this.accounts = accounts;
}
}
|
wizardsoftheweb/humble-library
|
cmd/logger.go
|
package wotwhb
import (
"os"
"github.com/sirupsen/logrus"
prefixed "github.com/x-cray/logrus-prefixed-formatter"
)
var (
formatter = &prefixed.TextFormatter{
FullTimestamp: true,
TimestampFormat: "2006-01-02 15:04:05",
QuoteEmptyFields: true,
ForceFormatting: true,
ForceColors: true,
}
formatterColorScheme = &prefixed.ColorScheme{
PrefixStyle: "cyan",
TimestampStyle: "black+h",
DebugLevelStyle: "blue+h:",
InfoLevelStyle: "green+h:",
WarnLevelStyle: "yellow",
ErrorLevelStyle: "red",
FatalLevelStyle: "red+b",
PanicLevelStyle: "red+B",
}
Logger = &logrus.Logger{
Out: os.Stderr,
Formatter: formatter,
}
fatalHandler = Logger.Fatal
)
func setLoggerLevel(verbosityLevel int) {
switch {
case -2 >= verbosityLevel:
Logger.SetLevel(logrus.PanicLevel)
break
case -1 == verbosityLevel:
Logger.SetLevel(logrus.FatalLevel)
break
case 0 == verbosityLevel:
Logger.SetLevel(logrus.ErrorLevel)
break
case 1 == verbosityLevel:
Logger.SetLevel(logrus.WarnLevel)
break
case 2 == verbosityLevel:
Logger.SetLevel(logrus.InfoLevel)
break
case 3 == verbosityLevel:
Logger.SetLevel(logrus.TraceLevel)
break
default:
Logger.SetLevel(logrus.DebugLevel)
break
}
}
func BootstrapLogger(verbosityLevel int) {
formatter.SetColorScheme(formatterColorScheme)
setLoggerLevel(verbosityLevel)
}
func fatalCheck(err error) {
if nil != err {
fatalHandler(err)
}
}
|
wangguanquan/eec
|
src/test/java/org/ttzero/excel/entity/ListObjectSheetTest.java
|
<gh_stars>10-100
/*
* Copyright (c) 2017-2019, <EMAIL> All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ttzero.excel.entity;
import org.junit.Test;
import org.ttzero.excel.Print;
import org.ttzero.excel.annotation.ExcelColumn;
import org.ttzero.excel.annotation.IgnoreExport;
import org.ttzero.excel.entity.style.Fill;
import org.ttzero.excel.entity.style.Font;
import org.ttzero.excel.entity.style.PatternType;
import org.ttzero.excel.entity.style.Styles;
import org.ttzero.excel.manager.Const;
import org.ttzero.excel.manager.docProps.Core;
import org.ttzero.excel.processor.IntConversionProcessor;
import org.ttzero.excel.processor.StyleProcessor;
import org.ttzero.excel.reader.Dimension;
import org.ttzero.excel.reader.ExcelReader;
import org.ttzero.excel.reader.ExcelReaderTest;
import java.awt.Color;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import static org.ttzero.excel.Print.println;
import static org.ttzero.excel.reader.ExcelReaderTest.testResourceRoot;
/**
* @author guanquan.wang at 2019-04-28 19:17
*/
public class ListObjectSheetTest extends WorkbookTest {
@Test
public void testWrite() throws IOException {
new Workbook("test object", author)
.watch(Print::println)
.addSheet(Item.randomTestData())
.writeTo(defaultTestPath);
}
@Test public void testAllTypeWrite() throws IOException {
new Workbook("all type object", author)
.watch(Print::println)
.addSheet(AllType.randomTestData())
.writeTo(defaultTestPath);
}
@Test public void testAnnotation() throws IOException {
new Workbook("annotation object", author)
.watch(Print::println)
.addSheet(Student.randomTestData())
.writeTo(defaultTestPath);
}
@Test public void testAnnotationAutoSize() throws IOException {
new Workbook("annotation object auto-size", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<>(Student.randomTestData()))
.writeTo(defaultTestPath);
}
@Test public void testStringWaterMark() throws IOException {
new Workbook("object string water mark", author)
.watch(Print::println)
.setWaterMark(WaterMark.of("SECRET"))
.addSheet(Item.randomTestData())
.writeTo(defaultTestPath);
}
@Test public void testLocalPicWaterMark() throws IOException {
new Workbook("object local pic water mark", author)
.watch(Print::println)
.setWaterMark(WaterMark.of(testResourceRoot().resolve("mark.png")))
.addSheet(Item.randomTestData())
.writeTo(defaultTestPath);
}
@Test public void testStreamWaterMark() throws IOException {
new Workbook("object input stream water mark", author)
.watch(Print::println)
.setWaterMark(WaterMark.of(getClass().getClassLoader().getResourceAsStream("mark.png")))
.addSheet(Item.randomTestData())
.writeTo(defaultTestPath);
}
@Test public void testAutoSize() throws IOException {
new Workbook("all type auto size", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(AllType.randomTestData())
.writeTo(defaultTestPath);
}
@Test public void testIntConversion() throws IOException {
new Workbook("test int conversion", author)
.watch(Print::println)
.addSheet(Student.randomTestData()
, new Column("学号", "id")
, new Column("姓名", "name")
, new Column("成绩", "score", n -> n < 60 ? "不及格" : n)
)
.writeTo(defaultTestPath);
}
@Test public void testStyleConversion() throws IOException {
new Workbook("object style processor", author)
.watch(Print::println)
.addSheet(Student.randomTestData()
, new Column("学号", "id")
, new Column("姓名", "name")
, new Column("成绩", "score")
.setStyleProcessor((o, style, sst) -> {
if ((int)o < 60) {
style = Styles.clearFill(style)
| sst.addFill(new Fill(PatternType.solid, Color.orange));
}
return style;
})
)
.writeTo(defaultTestPath);
}
@Test public void testConvertAndStyleConversion() throws IOException {
new Workbook("object style and style processor", author)
.watch(Print::println)
.addSheet(Student.randomTestData()
, new Column("学号", "id")
, new Column("姓名", "name")
, new Column("成绩", "score", n -> n < 60 ? "不及格" : n)
.setStyleProcessor((o, style, sst) -> {
if ((int)o < 60) {
style = Styles.clearFill(style)
| sst.addFill(new Fill(PatternType.solid, new Color(246, 209, 139)));
}
return style;
})
)
.writeTo(defaultTestPath);
}
@Test public void testCustomizeDataSource() throws IOException {
new Workbook("customize datasource", author)
.watch(Print::println)
.addSheet(new CustomizeDataSourceSheet())
.writeTo(defaultTestPath);
}
@Test public void testBoxAllTypeWrite() throws IOException {
new Workbook("box all type object", author)
.watch(Print::println)
.addSheet(BoxAllType.randomTestData())
.writeTo(defaultTestPath);
}
// -----AUTO SIZE
@Test public void testBoxAllTypeAutoSizeWrite() throws IOException {
new Workbook("auto-size box all type object", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(BoxAllType.randomTestData())
.writeTo(defaultTestPath);
}
@Test public void testCustomizeDataSourceAutoSize() throws IOException {
new Workbook("auto-size customize datasource", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new CustomizeDataSourceSheet())
.writeTo(defaultTestPath);
}
@Test public void testConstructor1() throws IOException {
new Workbook("test list sheet Constructor1", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<Item>())
.writeTo(defaultTestPath);
}
@Test public void testConstructor2() throws IOException {
new Workbook("test list sheet Constructor2", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<Item>("Item").setData(Item.randomTestData(10)))
.writeTo(defaultTestPath);
}
@Test public void testConstructor3() throws IOException {
new Workbook("test list sheet Constructor3", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<Item>("Item"
, new Column("ID", "id")
, new Column("NAME", "name"))
.setData(Item.randomTestData(10)))
.writeTo(defaultTestPath);
}
@Test public void testConstructor4() throws IOException {
new Workbook("test list sheet Constructor4", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<Item>("Item", WaterMark.of(author)
, new Column("ID", "id")
, new Column("NAME", "name"))
.setData(Item.randomTestData(10)))
.writeTo(defaultTestPath);
}
@Test public void testConstructor5() throws IOException {
new Workbook("test list sheet Constructor5", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<>(Item.randomTestData(10)))
.writeTo(defaultTestPath);
}
@Test public void testConstructor6() throws IOException {
new Workbook("test list sheet Constructor6", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<>("ITEM", Item.randomTestData(10)))
.writeTo(defaultTestPath);
}
@Test public void testConstructor7() throws IOException {
new Workbook("test list sheet Constructor7", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<>(Item.randomTestData(10)
, new Column("ID", "id")
, new Column("NAME", "name")))
.writeTo(defaultTestPath);
}
@Test public void testConstructor8() throws IOException {
new Workbook("test list sheet Constructor8", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<>("ITEM", Item.randomTestData(10)
, new Column("ID", "id")
, new Column("NAME", "name")))
.writeTo(defaultTestPath);
}
@Test public void testConstructor9() throws IOException {
new Workbook("test list sheet Constructor9", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<>(Item.randomTestData(10)
, WaterMark.of(author)
, new Column("ID", "id")
, new Column("NAME", "name")))
.writeTo(defaultTestPath);
}
@Test public void testConstructor10() throws IOException {
new Workbook("test list sheet Constructor10", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<>("ITEM"
, Item.randomTestData(10)
, WaterMark.of(author)
, new Column("ID", "id")
, new Column("NAME", "name")))
.writeTo(defaultTestPath);
}
@Test public void testArray() throws IOException {
new Workbook()
.watch(Print::println)
.addSheet(new ListSheet<>()
.setData(Arrays.asList(new Item(1, "abc"), new Item(2, "xyz"))))
.writeTo(defaultTestPath);
}
@Test public void testSingleList() throws IOException {
new Workbook()
.watch(Print::println)
.addSheet(new ListSheet<>()
.setData(Collections.singletonList(new Item(1, "a b c"))))
.writeTo(defaultTestPath);
}
public static StyleProcessor sp = (o, style, sst) -> {
if ((int)o < 60) {
style = Styles.clearFill(style)
| sst.addFill(new Fill(PatternType.solid, Color.orange));
}
return style;
};
// 定义一个int值转换lambda表达式,成绩低于60分显示"不及格",其余显示正常分数
public static IntConversionProcessor conversion = n -> n < 60 ? "不及格" : n;
@Test
public void testStyleConversion1() throws IOException {
new Workbook("object style processor1", "guanquan.wang")
.addSheet(new ListSheet<>("期末成绩", Student.randomTestData()
, new Column("学号", "id")
, new Column("姓名", "name")
, new Column("成绩", "score", conversion)
.setStyleProcessor(sp)
)
)
.writeTo(defaultTestPath);
}
@Test public void testNullValue() throws IOException {
new Workbook("test null value", author)
.watch(Print::println)
.setAutoSize(true)
.addSheet(new ListSheet<>("EXT-ITEM", ExtItem.randomTestData(10)))
.writeTo(defaultTestPath);
}
@Test public void testReflect() throws IntrospectionException, IllegalAccessException {
PropertyDescriptor[] array = Introspector.getBeanInfo(ExtItem.class).getPropertyDescriptors();
for (PropertyDescriptor pd : array) {
println(pd);
}
ExtItem item = new ExtItem(1, "guanquan.wang");
item.nice = "colvin";
Field[] fields = item.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
println(field + ": " + field.get(item));
}
}
@Test public void testFieldUnDeclare() throws IOException {
new Workbook("field un-declare", author)
.addSheet(new ListSheet<>("期末成绩", Student.randomTestData()
, new Column("学号", "id")
, new Column("姓名", "name")
, new Column("成绩", "score") // un-declare field
)
)
.writeTo(defaultTestPath);
}
@Test public void testResetMethod() throws IOException {
new Workbook("重写期末成绩", author)
.addSheet(new ListSheet<Student>("重写期末成绩", Collections.singletonList(new Student(9527, author, 0) {
@Override
public int getScore() {
return 100;
}
}))
)
.writeTo(defaultTestPath);
}
@Test public void testMethodAnnotation() throws IOException {
new Workbook("重写方法注解", author)
.addSheet(new ListSheet<Student>("重写方法注解", Collections.singletonList(new ExtStudent(9527, author, 0) {
@Override
@ExcelColumn("ID")
public int getId() {
return super.getId();
}
@Override
@ExcelColumn("成绩")
public int getScore() {
return 97;
}
}))
)
.writeTo(defaultTestPath);
try (ExcelReader reader = ExcelReader.read(defaultTestPath.resolve("重写方法注解.xlsx"))) {
Optional<ExtStudent> opt = reader.sheets().flatMap(org.ttzero.excel.reader.Sheet::dataRows)
.map(row -> row.too(ExtStudent.class)).findAny();
assert opt.isPresent();
ExtStudent student = opt.get();
assert student.getId() == 9527;
assert student.getScore() == 0; // The setter column name is 'score'
}
}
@Test public void testIgnoreSupperMethod() throws IOException {
new Workbook("忽略父类属性", author)
.addSheet(new ListSheet<Student>("重写方法注解", Collections.singletonList(new ExtStudent(9527, author, 0))))
.writeTo(defaultTestPath);
try (ExcelReader reader = ExcelReader.read(defaultTestPath.resolve("忽略父类属性.xlsx"))) {
Optional<ExtStudent> opt = reader.sheets().flatMap(org.ttzero.excel.reader.Sheet::dataRows)
.map(row -> row.too(ExtStudent.class)).findAny();
assert opt.isPresent();
ExtStudent student = opt.get();
assert student.getId() == 0;
assert student.getScore() == 0;
}
}
// Issue #93
@Test public void testListSheet_93() throws IOException {
new Workbook("Issue#93 List Object").addSheet(new ListSheet<Student>() {
private int i;
@Override
protected List<Student> more() {
return i++ < 10 ? Student.randomTestData(100) : null;
}
}).writeTo(defaultTestPath);
}
// Issue #95
@Test public void testIssue_95() throws IOException {
new Workbook("Issue #95").addSheet(new ListSheet<NotSharedObject>() {
private boolean c = true;
@Override
protected List<NotSharedObject> more() {
if (!c) return null;
c = false;
List<NotSharedObject> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new NotSharedObject(getRandomString()));
}
return list;
}
}).writeTo(defaultTestPath);
}
@Test public void testSpecifyCore() throws IOException {
Core core = new Core();
core.setCreator("一名光荣的测试人员");
core.setTitle("空白文件");
core.setSubject("主题");
core.setCategory("IT;木工");
core.setDescription("为了艾尔");
core.setKeywords("机枪兵;光头");
core.setVersion("1.0");
// core.setRevision("1.2");
core.setLastModifiedBy("TTT");
new Workbook("Specify Core")
.setCore(core)
.addSheet(new ListSheet<>(Collections.singletonList(new NotSharedObject(getRandomString()))))
.writeTo(defaultTestPath);
}
@Test public void testLarge() throws IOException {
new Workbook("large07").forceExport().addSheet(new ListSheet<ExcelReaderTest.LargeData>() {
private int i = 0, n;
@Override
public List<ExcelReaderTest.LargeData> more() {
if (n++ >= 10) return null;
List<ExcelReaderTest.LargeData> list = new ArrayList<>();
int size = i + 5000;
for (; i < size; i++) {
ExcelReaderTest.LargeData largeData = new ExcelReaderTest.LargeData();
list.add(largeData);
largeData.setStr1("str1-" + i);
largeData.setStr2("str2-" + i);
largeData.setStr3("str3-" + i);
largeData.setStr4("str4-" + i);
largeData.setStr5("str5-" + i);
largeData.setStr6("str6-" + i);
largeData.setStr7("str7-" + i);
largeData.setStr8("str8-" + i);
largeData.setStr9("str9-" + i);
largeData.setStr10("str10-" + i);
largeData.setStr11("str11-" + i);
largeData.setStr12("str12-" + i);
largeData.setStr13("str13-" + i);
largeData.setStr14("str14-" + i);
largeData.setStr15("str15-" + i);
largeData.setStr16("str16-" + i);
largeData.setStr17("str17-" + i);
largeData.setStr18("str18-" + i);
largeData.setStr19("str19-" + i);
largeData.setStr20("str20-" + i);
largeData.setStr21("str21-" + i);
largeData.setStr22("str22-" + i);
largeData.setStr23("str23-" + i);
largeData.setStr24("str24-" + i);
largeData.setStr25("str25-" + i);
}
return list;
}
}).writeTo(defaultTestPath);
try (ExcelReader reader = ExcelReader.read(defaultTestPath.resolve("large07.xlsx"))) {
assert Dimension.of("A1:Y50001").equals(reader.sheet(0).getDimension());
}
}
// #132
@Test public void testEmptyList() throws IOException {
new Workbook().addSheet(new ListSheet<>(new ArrayList<>())).writeTo(defaultTestPath);
}
@Test public void testNoForceExport() throws IOException {
new Workbook("testNoForceExport").addSheet(new ListSheet<>(NoColumnAnnotation.randomTestData())).writeTo(defaultTestPath);
try (ExcelReader reader = ExcelReader.read(defaultTestPath.resolve("testNoForceExport.xlsx"))) {
assert Dimension.of("A1").equals(reader.sheet(0).getDimension());
}
}
@Test public void testForceExportOnWorkbook() throws IOException {
int lines = random.nextInt(100) + 3;
new Workbook("testForceExportOnWorkbook").forceExport().addSheet(new ListSheet<>(NoColumnAnnotation.randomTestData(lines))).writeTo(defaultTestPath);
try (ExcelReader reader = ExcelReader.read(defaultTestPath.resolve("testForceExportOnWorkbook.xlsx"))) {
assert reader.sheet(0).dataRows().count() == lines;
}
}
@Test public void testForceExportOnWorkSheet() throws IOException {
int lines = random.nextInt(100) + 3;
new Workbook("testForceExportOnWorkSheet").addSheet(new ListSheet<>(NoColumnAnnotation.randomTestData(lines)).forceExport()).writeTo(defaultTestPath);
try (ExcelReader reader = ExcelReader.read(defaultTestPath.resolve("testForceExportOnWorkSheet.xlsx"))) {
assert reader.sheet(0).dataRows().count() == lines;
}
}
@Test public void testForceExportOnWorkbook2() throws IOException {
int lines = random.nextInt(100) + 3, lines2 = random.nextInt(100) + 4;
new Workbook("testForceExportOnWorkbook2")
.forceExport()
.addSheet(new ListSheet<>(NoColumnAnnotation.randomTestData(lines)))
.addSheet(new ListSheet<>(NoColumnAnnotation2.randomTestData(lines2)))
.writeTo(defaultTestPath);
try (ExcelReader reader = ExcelReader.read(defaultTestPath.resolve("testForceExportOnWorkbook2.xlsx"))) {
assert reader.sheet(0).dataRows().count() == lines;
assert reader.sheet(1).dataRows().count() == lines2;
}
}
@Test public void testForceExportOnWorkbook2Cancel1() throws IOException {
int lines = random.nextInt(100) + 3, lines2 = random.nextInt(100) + 4;
new Workbook("testForceExportOnWorkbook2Cancel1")
.forceExport()
.addSheet(new ListSheet<>(NoColumnAnnotation.randomTestData(lines)).cancelForceExport())
.addSheet(new ListSheet<>(NoColumnAnnotation2.randomTestData(lines2)))
.writeTo(defaultTestPath);
try (ExcelReader reader = ExcelReader.read(defaultTestPath.resolve("testForceExportOnWorkbook2Cancel1.xlsx"))) {
assert reader.sheets().count() == 2L;
assert reader.sheet(0).dataRows().count() == 0L;
assert reader.sheet(1).dataRows().count() == lines2;
}
}
@Test public void testForceExportOnWorkbook2Cancel2() throws IOException {
int lines = random.nextInt(100) + 3, lines2 = random.nextInt(100) + 4;
new Workbook("testForceExportOnWorkbook2Cancel2")
.forceExport()
.addSheet(new ListSheet<>(NoColumnAnnotation.randomTestData(lines)).cancelForceExport())
.addSheet(new ListSheet<>(NoColumnAnnotation2.randomTestData(lines2)).cancelForceExport())
.writeTo(defaultTestPath);
try (ExcelReader reader = ExcelReader.read(defaultTestPath.resolve("testForceExportOnWorkbook2Cancel2.xlsx"))) {
assert reader.sheets().count() == 2L;
assert reader.sheet(0).dataRows().count() == 0L;
assert reader.sheet(1).dataRows().count() == 0L;
}
}
@Test public void testWrapText() throws IOException {
new Workbook("WRAP TEXT")
.addSheet(new ListSheet<>()
.setData(Arrays.asList(new Item(1, "a b c\r\n1 2 3\r\n中文\t测试\r\nAAAAAA")
, new Item(2, "fdsafdsafdsafdsafdsafdsafdsafdsfadsafdsafdsafdsafdsafdsafds"))))
.writeTo(defaultTestPath);
}
@Test public void testClearHeadStyle() throws IOException {
Workbook workbook = new Workbook("clear style").addSheet(new ListSheet<>(Item.randomTestData()));
Sheet sheet = workbook.getSheetAt(0);
sheet.cancelOddStyle(); // Clear odd style
int headStyle = sheet.defaultHeadStyle();
sheet.setHeadStyle(Styles.clearFill(headStyle) & Styles.clearFont(headStyle));
sheet.setHeadStyle(sheet.getHeadStyle() | workbook.getStyles().addFont(new Font("宋体", 11, Font.Style.BOLD, Color.BLACK)));
workbook.writeTo(defaultTestPath);
}
@Test public void testOrderColumn() throws IOException {
new Workbook(("Order column")).addSheet(new ListSheet<>(OrderEntry.randomTestData())).writeTo(defaultTestPath);
}
@Test public void testSameOrderColumn() throws IOException {
new Workbook(("Same order column")).addSheet(new ListSheet<>(SameOrderEntry.randomTestData())).writeTo(defaultTestPath);
}
@Test public void testFractureOrderColumn() throws IOException {
new Workbook(("Fracture order column")).addSheet(new ListSheet<>(FractureOrderEntry.randomTestData())).writeTo(defaultTestPath);
}
@Test public void testLargeOrderColumn() throws IOException {
new Workbook(("Large order column")).addSheet(new ListSheet<>(LargeOrderEntry.randomTestData())).writeTo(defaultTestPath);
}
@Test public void testOverLargeOrderColumn() throws IOException {
try {
new Workbook(("Over Large order column")).addSheet(new ListSheet<>(OverLargeOrderEntry.randomTestData())).writeTo(defaultTestPath);
assert false;
} catch (TooManyColumnsException e) {
assert true;
}
}
@Test public void testOrderColumnSpecifyOnColumn() throws IOException {
new Workbook("Order column 2")
.addSheet(new ListSheet<>("期末成绩", Student.randomTestData()
, new Column("学号", "id").setColIndex(3)
, new Column("姓名", "name")
, new Column("成绩", "score").setColIndex(5) // un-declare field
)).writeTo(defaultTestPath);
}
@Test public void testBasicType() throws IOException {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < 35; i++) list.add(i);
new Workbook("Integer array").addSheet(new ListSheet<Integer>(list) {
@Override
public org.ttzero.excel.entity.Column[] getHeaderColumns() {
return new org.ttzero.excel.entity.Column[]{ new ListSheet.EntryColumn().setClazz(Integer.class) };
}
}.ignoreHeader()).writeTo(defaultTestPath);
try (ExcelReader reader = ExcelReader.read(defaultTestPath.resolve("Integer array.xlsx"))) {
Integer[] array = reader.sheets().flatMap(org.ttzero.excel.reader.Sheet::rows).map(row -> row.getInt(0)).toArray(Integer[]::new);
assert array.length == list.size();
for (int i = 0; i < array.length; i++) {
assert array[i].equals(list.get(i));
}
}
}
public static class Item {
@ExcelColumn
private int id;
@ExcelColumn(wrapText = true)
private String name;
public Item(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public static List<Item> randomTestData(int n) {
List<Item> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(new Item(i, getRandomString()));
}
return list;
}
public static List<Item> randomTestData() {
int n = random.nextInt(100) + 1;
return randomTestData(n);
}
}
public static class AllType {
@ExcelColumn
private boolean bv;
@ExcelColumn
private char cv;
@ExcelColumn
private short sv;
@ExcelColumn
private int nv;
@ExcelColumn
private long lv;
@ExcelColumn
private float fv;
@ExcelColumn
private double dv;
@ExcelColumn
private String s;
@ExcelColumn
private BigDecimal mv;
@ExcelColumn
private Date av;
@ExcelColumn
private Timestamp iv;
@ExcelColumn
private Time tv;
@ExcelColumn
private LocalDate ldv;
@ExcelColumn
private LocalDateTime ldtv;
@ExcelColumn
private LocalTime ltv;
public static List<AllType> randomTestData(int size) {
List<AllType> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
AllType o = new AllType();
o.bv = random.nextInt(10) == 5;
o.cv = charArray[random.nextInt(charArray.length)];
o.sv = (short) (random.nextInt() & 0xFFFF);
o.nv = random.nextInt();
o.lv = random.nextLong();
o.fv = random.nextFloat();
o.dv = random.nextDouble();
o.s = getRandomString();
o.mv = BigDecimal.valueOf(random.nextDouble());
o.av = new Date();
o.iv = new Timestamp(System.currentTimeMillis() - random.nextInt(9999999));
o.tv = new Time(random.nextLong());
o.ldv = LocalDate.now();
o.ldtv = LocalDateTime.now();
o.ltv = LocalTime.now();
list.add(o);
}
return list;
}
public static List<AllType> randomTestData() {
int size = random.nextInt(100) + 1;
return randomTestData(size);
}
public boolean isBv() {
return bv;
}
public char getCv() {
return cv;
}
public short getSv() {
return sv;
}
public int getNv() {
return nv;
}
public long getLv() {
return lv;
}
public float getFv() {
return fv;
}
public double getDv() {
return dv;
}
public String getS() {
return s;
}
public BigDecimal getMv() {
return mv;
}
public Date getAv() {
return av;
}
public Timestamp getIv() {
return iv;
}
public Time getTv() {
return tv;
}
public LocalDate getLdv() {
return ldv;
}
public LocalDateTime getLdtv() {
return ldtv;
}
public LocalTime getLtv() {
return ltv;
}
public void setBv(boolean bv) {
this.bv = bv;
}
public void setCv(char cv) {
this.cv = cv;
}
public void setSv(short sv) {
this.sv = sv;
}
public void setNv(int nv) {
this.nv = nv;
}
public void setLv(long lv) {
this.lv = lv;
}
public void setFv(float fv) {
this.fv = fv;
}
public void setDv(double dv) {
this.dv = dv;
}
public void setS(String s) {
this.s = s;
}
public void setMv(BigDecimal mv) {
this.mv = mv;
}
public void setAv(Date av) {
this.av = av;
}
public void setIv(Timestamp iv) {
this.iv = iv;
}
public void setTv(Time tv) {
this.tv = tv;
}
public void setLdv(LocalDate ldv) {
this.ldv = ldv;
}
public void setLdtv(LocalDateTime ldtv) {
this.ldtv = ldtv;
}
public void setLtv(LocalTime ltv) {
this.ltv = ltv;
}
@Override
public String toString() {
return "" + bv + '|' + cv + '|' + sv + '|' + nv + '|' + lv
+ '|' + fv + '|' + dv + '|' + s + '|' + mv + '|' + av
+ '|' + tv + '|' + ldv + '|' + ldtv + '|' + ltv;
}
}
/**
* Annotation Object
*/
public static class Student {
@IgnoreExport
private int id;
@ExcelColumn("姓名")
private String name;
@ExcelColumn("成绩")
private int score;
public Student() { }
protected Student(int id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public static List<Student> randomTestData(int pageNo, int limit) {
List<Student> list = new ArrayList<>(limit);
for (int i = pageNo * limit, n = i + limit; i < n; i++) {
Student e = new Student(i, getRandomString(), random.nextInt(50) + 50);
list.add(e);
}
return list;
}
public static List<Student> randomTestData(int n) {
return randomTestData(0, n);
}
public static List<Student> randomTestData() {
int n = random.nextInt(100) + 1;
return randomTestData(n);
}
@Override
@ExcelColumn
public String toString() {
return "id: " + id + ", name: " + name + ", score: " + score;
}
}
public static class BoxAllType {
@ExcelColumn
private Boolean bv;
@ExcelColumn
private Character cv;
@ExcelColumn
private Short sv;
@ExcelColumn
private Integer nv;
@ExcelColumn
private Long lv;
@ExcelColumn
private Float fv;
@ExcelColumn
private Double dv;
@ExcelColumn
private String s;
@ExcelColumn
private BigDecimal mv;
@ExcelColumn
private Date av;
@ExcelColumn
private Timestamp iv;
@ExcelColumn
private Time tv;
@ExcelColumn
private LocalDate ldv;
@ExcelColumn
private LocalDateTime ldtv;
@ExcelColumn
private LocalTime ltv;
public static List<AllType> randomTestData(int size) {
List<AllType> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
AllType o = new AllType();
o.bv = random.nextInt(10) == 5;
o.cv = charArray[random.nextInt(charArray.length)];
o.sv = (short) (random.nextInt() & 0xFFFF);
o.nv = random.nextInt();
o.lv = random.nextLong();
o.fv = random.nextFloat();
o.dv = random.nextDouble();
o.s = getRandomString();
o.mv = BigDecimal.valueOf(random.nextDouble());
o.av = new Date();
o.iv = new Timestamp(System.currentTimeMillis() - random.nextInt(9999999));
o.tv = new Time(random.nextLong());
o.ldv = LocalDate.now();
o.ldtv = LocalDateTime.now();
o.ltv = LocalTime.now();
list.add(o);
}
return list;
}
public static List<AllType> randomTestData() {
int size = random.nextInt(100) + 1;
return randomTestData(size);
}
public Boolean getBv() {
return bv;
}
public Character getCv() {
return cv;
}
public Short getSv() {
return sv;
}
public Integer getNv() {
return nv;
}
public Long getLv() {
return lv;
}
public Float getFv() {
return fv;
}
public Double getDv() {
return dv;
}
public String getS() {
return s;
}
public BigDecimal getMv() {
return mv;
}
public Date getAv() {
return av;
}
public Timestamp getIv() {
return iv;
}
public Time getTv() {
return tv;
}
public LocalDate getLdv() {
return ldv;
}
public LocalDateTime getLdtv() {
return ldtv;
}
public LocalTime getLtv() {
return ltv;
}
public void setBv(Boolean bv) {
this.bv = bv;
}
public void setCv(Character cv) {
this.cv = cv;
}
public void setSv(Short sv) {
this.sv = sv;
}
public void setNv(Integer nv) {
this.nv = nv;
}
public void setLv(Long lv) {
this.lv = lv;
}
public void setFv(Float fv) {
this.fv = fv;
}
public void setDv(Double dv) {
this.dv = dv;
}
public void setS(String s) {
this.s = s;
}
public void setMv(BigDecimal mv) {
this.mv = mv;
}
public void setAv(Date av) {
this.av = av;
}
public void setIv(Timestamp iv) {
this.iv = iv;
}
public void setTv(Time tv) {
this.tv = tv;
}
public void setLdv(LocalDate ldv) {
this.ldv = ldv;
}
public void setLdtv(LocalDateTime ldtv) {
this.ldtv = ldtv;
}
public void setLtv(LocalTime ltv) {
this.ltv = ltv;
}
@Override
public String toString() {
return "" + bv + '|' + cv + '|' + sv + '|' + nv + '|' + lv
+ '|' + fv + '|' + dv + '|' + s + '|' + mv + '|' + av
+ '|' + tv + '|' + ldv + '|' + ldtv + '|' + ltv;
}
}
public static class ExtItem extends Item {
@ExcelColumn
private String nice;
public ExtItem(int id, String name) {
super(id, name);
}
// public String getNice() {
// return nice;
// }
//
// public void setNice(String nice) {
// this.nice = nice;
// }
public static List<Item> randomTestData(int n) {
List<Item> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(new ExtItem(i, getRandomString()));
}
return list;
}
}
public static class NotSharedObject {
@ExcelColumn(share = false)
private String name;
public NotSharedObject(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class ExtStudent extends Student {
public ExtStudent() { }
protected ExtStudent(int id, String name, int score) {
super(id, name, score);
}
@Override
@ExcelColumn("ID")
@IgnoreExport
public int getId() {
return super.getId();
}
@ExcelColumn("ID")
@Override
public void setId(int id) {
super.setId(id);
}
@Override
@ExcelColumn("SCORE")
@IgnoreExport
public int getScore() {
return super.getScore();
}
@ExcelColumn("SCORE")
@Override
public void setScore(int score) {
super.setScore(score);
}
}
public static class NoColumnAnnotation {
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
public NoColumnAnnotation(int id, String name) {
this.id = id;
this.name = name;
}
public static List<NoColumnAnnotation> randomTestData(int n) {
List<NoColumnAnnotation> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(new NoColumnAnnotation(i, getRandomString()));
}
return list;
}
public static List<NoColumnAnnotation> randomTestData() {
int n = random.nextInt(100) + 1;
return randomTestData(n);
}
}
public static class NoColumnAnnotation2 {
private int age;
private String abc;
public int getAge() {
return age;
}
public String getAbc() {
return abc;
}
public NoColumnAnnotation2(int age, String abc) {
this.age = age;
this.abc = abc;
}
public static List<NoColumnAnnotation2> randomTestData(int n) {
List<NoColumnAnnotation2> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(new NoColumnAnnotation2(i, getRandomString()));
}
return list;
}
public static List<NoColumnAnnotation2> randomTestData() {
int n = random.nextInt(100) + 1;
return randomTestData(n);
}
}
public static class OrderEntry {
@ExcelColumn(colIndex = 0)
private String s;
@ExcelColumn( colIndex = 1)
private Date date;
@ExcelColumn(colIndex = 2)
private Double d;
@ExcelColumn(colIndex = 3)
private String s2 = "a";
@ExcelColumn(colIndex = 4)
private String s3 = "b";
@ExcelColumn(colIndex = 5)
private String s4 = "c";
public OrderEntry() {}
public OrderEntry(String s, Date date, Double d) {
this.s = s;
this.date = date;
this.d = d;
}
public static List<OrderEntry> randomTestData(int n) {
List<OrderEntry> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(new OrderEntry(getRandomString(), new Timestamp(System.currentTimeMillis() - random.nextInt(9999999)), (double) i));
}
return list;
}
public static List<OrderEntry> randomTestData() {
int n = random.nextInt(100) + 1;
return randomTestData(n);
}
public String getS() {
return s;
}
public Date getDate() {
return date;
}
public Double getD() {
return d;
}
public String getS2() {
return s2;
}
public String getS3() {
return s3;
}
public String getS4() {
return s4;
}
}
public static class SameOrderEntry extends OrderEntry {
public SameOrderEntry() {}
public SameOrderEntry(String s, Date date, Double d) {
super(s, date, d);
}
@Override
@ExcelColumn(colIndex = 5)
public Double getD() {
return super.getD();
}
@Override
@ExcelColumn(colIndex = 5)
public String getS2() {
return super.getS2();
}
public static List<OrderEntry> randomTestData(int n) {
List<OrderEntry> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(new SameOrderEntry(getRandomString(), new Timestamp(System.currentTimeMillis() - random.nextInt(9999999)), (double) i));
}
return list;
}
public static List<OrderEntry> randomTestData() {
int n = random.nextInt(100) + 1;
return randomTestData(n);
}
}
public static class FractureOrderEntry extends OrderEntry {
public FractureOrderEntry() {}
public FractureOrderEntry(String s, Date date, Double d) {
super(s, date, d);
}
@Override
@ExcelColumn
public String getS() {
return super.getS();
}
@Override
@ExcelColumn
public Date getDate() {
return super.getDate();
}
@Override
@ExcelColumn(colIndex = 2)
public Double getD() {
return super.getD();
}
@Override
@ExcelColumn(colIndex = 0)
public String getS2() {
return super.getS2();
}
@Override
@ExcelColumn
public String getS3() {
return super.getS3();
}
@Override
@ExcelColumn(colIndex = 4)
public String getS4() {
return super.getS4();
}
public static List<OrderEntry> randomTestData(int n) {
List<OrderEntry> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(new FractureOrderEntry(getRandomString(), new Timestamp(System.currentTimeMillis() - random.nextInt(9999999)), (double) i));
}
return list;
}
public static List<OrderEntry> randomTestData() {
int n = random.nextInt(100) + 1;
return randomTestData(n);
}
}
public static class LargeOrderEntry extends OrderEntry {
public LargeOrderEntry() {}
public LargeOrderEntry(String s, Date date, Double d) {
super(s, date, d);
}
@Override
@ExcelColumn(colIndex = 1)
public String getS() {
return super.getS();
}
@Override
@ExcelColumn(colIndex = Const.Limit.MAX_COLUMNS_ON_SHEET - 1)
public Date getDate() {
return super.getDate();
}
@Override
@ExcelColumn(colIndex = 189)
public String getS2() {
return super.getS2();
}
public static List<OrderEntry> randomTestData(int n) {
List<OrderEntry> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(new LargeOrderEntry(getRandomString(), new Timestamp(System.currentTimeMillis() - random.nextInt(9999999)), (double) i));
}
return list;
}
public static List<OrderEntry> randomTestData() {
int n = random.nextInt(100) + 1;
return randomTestData(n);
}
}
public static class OverLargeOrderEntry extends OrderEntry {
public OverLargeOrderEntry() {}
public OverLargeOrderEntry(String s, Date date, Double d) {
super(s, date, d);
}
@Override
@ExcelColumn(colIndex = 16_384)
public String getS() {
return super.getS();
}
public static List<OrderEntry> randomTestData(int n) {
List<OrderEntry> list = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
list.add(new OverLargeOrderEntry(getRandomString(), new Timestamp(System.currentTimeMillis() - random.nextInt(9999999)), (double) i));
}
return list;
}
public static List<OrderEntry> randomTestData() {
int n = random.nextInt(100) + 1;
return randomTestData(n);
}
}
}
|
s-sajid-ali/comsyl
|
tests/parallel/ParallelLinearOperatorTest.py
|
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/
__authors__ = ["<NAME> - ESRF ISDD Advanced Analysis and Modelling"]
__license__ = "MIT"
__date__ = "20/04/2017"
import unittest
import numpy as np
from comsyl.parallel.ParallelMatrix import ParallelMatrix
from comsyl.parallel.ParallelLinearOperator import ParallelLinearOperator
from tests.parallel.ParallelVectorTest import createVector
from tests.parallel.ParallelMatrixTest import createMatrix
from comsyl.math.Eigensolver import Operator, Eigensolver
class ParallelLinearOperatorTest(unittest.TestCase):
def testParallelDot(self):
n_rows = 20
n_columns = n_rows
vector = createVector(rows=n_rows, columns=n_columns)
matrix = ParallelMatrix(vector.distributionPlan())
communicator = vector.communicator()
if communicator.Get_rank() == 0:
entire_vector = np.array(np.random.random(n_columns), dtype=np.complex128)
entire_vector /= np.linalg.norm(entire_vector)
entire_matrix = np.zeros((n_rows, n_columns), dtype=np.complex128)
entire_matrix[:, :] = np.random.random((n_rows, n_columns)) + 1j * np.random.random((n_rows, n_columns))
entire_matrix /= np.linalg.norm(entire_matrix)
entire_result = entire_matrix.dot(entire_matrix.dot(entire_matrix.dot(entire_vector)))
else:
entire_vector = None
entire_matrix = None
entire_result = None
vector.broadcast(entire_vector, root=0)
#self.assertLess(np.linalg.norm(vector.fullData()-entire_vector), 1e-10)
matrix.broadcast(entire_matrix, root=0)
#self.assertLess(np.linalg.norm(matrix.localMatrix()-entire_matrix), 1e-10)
entire_result = communicator.bcast(entire_result, root=0)
operator = ParallelLinearOperator(matrix, vector)
operator.listenIfSlave()
if communicator.Get_rank() == 0:
for i in range(3):
operator.matvec(vector.fullData())
operator.finishListen()
self.assertLess(np.linalg.norm(vector.fullData()-entire_result), 1e-10)
def testParallelDiagonalization(self):
n_rows = 1000
n_columns = n_rows
matrix = createMatrix(rows=n_rows, columns=n_columns)
communicator = matrix.communicator()
if communicator.Get_rank() == 0:
entire_matrix = np.array(np.diag(np.arange(n_rows)), dtype=np.complex128)
else:
entire_matrix = None
matrix.broadcast(entire_matrix, root=0)
operator = ParallelLinearOperator(matrix)
operator.listenIfSlave()
if communicator.Get_rank() == 0:
#S=entire_matrix
#S2n = np.hstack((np.vstack((S.real,-S.imag)), np.vstack((S.imag,S.real)))).real
#eigenvalue, eigenfunctions = eigs(entire_matrix, 190)
op = Operator.fromLinearOperator(operator)
solver = Eigensolver()
number_eigenvectors = 100
eigenvalue, eigenfunctions = solver.arnoldi(op, number_eigenvectors)
self.assertLess(np.linalg.norm(eigenvalue - np.arange(n_rows-number_eigenvectors, n_rows)[::-1]), 1e-8)
for i in range(eigenfunctions.shape[1]):
self.assertLess(np.abs(np.linalg.norm(eigenfunctions[:, i])-1), 1e-8)
self.assertEqual(np.abs(eigenfunctions[:,i]).argmax(), n_rows-1-i)
operator.finishListen()
def testParallelDiagonalizationComplex(self):
n_rows = 1000
n_columns = n_rows
matrix = createMatrix(rows=n_rows, columns=n_columns)
communicator = matrix.communicator()
if communicator.Get_rank() == 0:
entire_matrix = np.array(np.random.random((n_rows,n_columns)), dtype=np.complex128)
entire_matrix += 1j* np.random.random((n_rows,n_columns))
entire_matrix = entire_matrix.conj().transpose()+entire_matrix
else:
entire_matrix = None
matrix.broadcast(entire_matrix, root=0)
operator = ParallelLinearOperator(matrix)
operator.listenIfSlave()
if communicator.Get_rank() == 0:
op = Operator.fromLinearOperator(operator)
eig = Eigensolver()
number_eigenfunctions = 100
eigenvalue, eigenfunctions = eig.arnoldi(op, number_eigenfunctions, 1e-13)
eigenvalue_c, eigenfunctions_c = np.linalg.eigh(entire_matrix)
s_eigenvalue_c = eigenvalue_c[eigenvalue_c>0.0]
s_eigenfunctions_c = eigenfunctions_c[:, eigenvalue_c>0.0]
s_eigenvalue_c = s_eigenvalue_c[s_eigenvalue_c.argsort()[::-1]]
s_eigenfunctions_c = s_eigenfunctions_c[:,s_eigenvalue_c.argsort()]
def rayleigh(matrix, vector):
return vector.conj().dot(matrix.dot(vector))/vector.conj().dot(vector)
for i in range(number_eigenfunctions):
error_rayleigh = np.abs(rayleigh(entire_matrix, eigenfunctions[:, i])-s_eigenvalue_c[i])
self.assertLess(error_rayleigh, 1e-10)
error_ritz = np.linalg.norm(entire_matrix.dot(eigenfunctions[:, i]) - eigenvalue[i] * eigenfunctions[:,i])
self.assertLess(error_ritz, 1e-10)
alpha = eigenfunctions[0, i] / s_eigenfunctions_c[0, i]
error_l2 = np.linalg.norm(eigenfunctions[:, i] - alpha * s_eigenfunctions_c[:, i])
self.assertLess(error_l2, 1e-10)
operator.finishListen()
|
bruh-boys/dune
|
lib/routing_test.go
|
package lib
import (
"fmt"
"testing"
)
func TestRoute(t *testing.T) {
var tests = []struct {
route *httpRoute
url string
match bool
params string
}{
{NewRoute("*"), "/", true, "*"},
{NewRoute("*"), "/llll", true, "*"},
{NewRoute("/foo"), "/foo", true, "*"},
{NewRoute("/foo/*"), "/foo", true, "*"},
{NewRoute("/foo/bar/*"), "/foo/bar/cxxx", true, "*"},
}
router := newRouter()
for i, test := range tests {
router.Reset()
if test.route.URL != "" {
router.Add(test.route)
}
err := assertRoute(router, test.route, test.url, test.match, test.params)
if err != nil {
t.Fatalf("Test %d: %s -> %s", i, test.url, err.Error())
}
}
}
func TestRoute1(t *testing.T) {
var tests = []struct {
route *httpRoute
url string
match bool
params string
}{
{NewRoute("*"), "/", true, "*"},
{NewRoute("/:foo/bar"), "/foo/bar/xxx", true, "*"},
}
router := newRouter()
for i, test := range tests {
if test.route.URL != "" {
router.Add(test.route)
}
err := assertRoute(router, test.route, test.url, test.match, test.params)
if err != nil {
t.Fatalf("Test %d: %s -> %s", i, test.url, err.Error())
}
}
}
func TestRoute2(t *testing.T) {
var tests = []struct {
route *httpRoute
url string
match bool
params string
}{
{NewRoute("/:foo/*"), "/foo", true, "*"},
{NewRoute("/:foo/bar.json"), "/foo/bar", true, "*"},
}
router := newRouter()
for i, test := range tests {
if test.route.URL != "" {
router.Add(test.route)
}
err := assertRoute(router, test.route, test.url, test.match, test.params)
if err != nil {
t.Fatalf("Test %d: %s -> %s", i, test.url, err.Error())
}
}
}
func TestRoute3(t *testing.T) {
router := newRouter()
router.Reset()
var tests = []struct {
route *httpRoute
url string
match bool
params string
}{
{
NewRoute("/:namespace/:action"),
"/app1/test", true, "namespace=app1,action=test",
},
{
NewRoute("/customers"),
"/customers", true, "",
},
{
// capture action as a parameter
NewRoute("/customers/:id"),
"/customers/234", true, "id=234",
},
{
// capture the extension as a parameter
NewRoute("/foo.:ext"),
"/foo.js", true, "ext=js",
},
{
NewRoute("/customers/foo"),
"/customers/foo", true, "",
},
{
NewRoute("/customers/:id/print"),
"/customers/234/print", true, "id=234",
},
{
NewRoute("/public/*"),
"/public/images/pics/dog.jpeg", true, "",
},
{
NewRoute("/:namespace/public/*"),
"/demo/public/images/pics/dog.jpeg", true, "namespace=demo",
},
{
NewRoute(""), "/foo", false, "",
},
{
NewRoute(""), "/customers/10/foo", false, "",
},
}
for _, test := range tests {
if test.route.URL != "" {
router.Add(test.route)
}
}
for i, test := range tests {
err := assertRoute(router, test.route, test.url, test.match, test.params)
if err != nil {
t.Fatalf("Test %d: %s -> %s", i+1, test.url, err.Error())
}
}
}
func TestRoute4(t *testing.T) {
router := newRouter()
router.Add(NewRoute("GET/foo/*"))
m, ok := router.Match("GET/foo/404.svg")
if !ok {
t.Fatal()
}
if m.Route == nil {
t.Fatal("No route")
}
if m.Route.URL != "GET/foo/*" {
t.Fatal(m.Route)
}
}
func TestRoute5(t *testing.T) {
router := newRouter()
router.Add(NewRoute("GET/*"))
m, ok := router.Match("GET//foo/404.svg")
if !ok {
t.Fatal("no match")
}
if m.Route == nil {
t.Fatal("No route")
}
if m.Route.URL != "GET/*" {
t.Fatal("route", m.Route)
}
}
func TestRoute6(t *testing.T) {
router := newRouter()
r := NewRoute("*")
router.Add(r)
r = NewRoute(":bar")
router.Add(r)
m, ok := router.Match("/foo")
if !ok {
t.Fatal("no match")
}
if m.Route.URL != ":bar" {
t.Fatal("params precede wildcards")
}
}
func TestRoute7(t *testing.T) {
var tests = []struct {
route *httpRoute
url string
match bool
}{
{NewRoute("/:foo"), "/foo/bar.json", false},
{NewRoute("/:foo/bar.json"), "/foo/bar.json", true},
}
router := newRouter()
for i, test := range tests {
if test.route.URL != "" {
router.Add(test.route)
}
err := assertRoute(router, test.route, test.url, test.match, "*")
if err != nil {
t.Fatalf("Test %d: %s -> %s", i, test.url, err.Error())
}
}
}
func TestRouteBug1(t *testing.T) {
r := newRouter()
r.Add(NewRoute("/foo/bar/:id"))
r.Add(NewRoute("/foo/bar.json"))
m, ok := r.Match("/foo/bar.json")
if !ok {
t.Fatal("no match")
}
if m.Route.URL != "/foo/bar/json" {
t.Fatal(m.Route.URL)
}
}
func TestRoute8(t *testing.T) {
router := newRouter()
router.Add(NewRoute("GET/events/:entity/info.json"))
router.Add(NewRoute("GET/events/event"))
router.Add(NewRoute("GET/events/event/create"))
m, ok := router.Match("GET/events/event/info.json")
if !ok {
t.Fatal()
}
if len(m.Params) != 1 {
t.Fatal()
}
if m.Params[0] != "event" {
t.Fatal(m.Params)
}
}
func TestRoute9(t *testing.T) {
router := newRouter()
router.Add(NewRoute("/:namespace/:action"))
router.Add(NewRoute("/:namespace/public/*"))
m, ok := router.Match("/demo/public/images/pics/dog.jpeg")
if !ok {
t.Fatal()
}
if len(m.Params) != 1 {
t.Fatal()
}
}
func TestRoute10(t *testing.T) {
router := newRouter()
router.Add(NewRoute("/:namespace/:action"))
router.Add(NewRoute("/public/*"))
m, ok := router.Match("/public/images/pics/dog.jpeg")
if !ok {
t.Fatal()
}
if len(m.Params) != 0 {
t.Fatal()
}
}
func TestRoute11(t *testing.T) {
router := newRouter()
router.Add(NewRoute("/foo/:bar"))
router.Add(NewRoute("/foo/:action/info.json"))
m, ok := router.Match("/foo/xxx/info.json")
if !ok {
t.Fatal()
}
if len(m.Params) != 1 {
t.Fatal()
}
if m.Params[0] != "xxx" {
t.Fatal(m.Params)
}
}
func assertRoute(router *httpRouter, r *httpRoute, url string, match bool, params string) error {
m, ok := router.Match(url)
if ok != match {
if ok {
fmt.Println(m.Route.URL)
}
return fmt.Errorf("expected match: %t, got: %t", match, ok)
}
if params != "*" {
items := Split(params, ",")
if len(items) != len(m.Params) {
fmt.Println(m.Route.URL)
return fmt.Errorf("params: expected %d, got %d", len(items), len(m.Params))
}
for _, item := range items {
parts := Split(item, "=")
key := parts[0]
value := parts[1]
if m.GetParam(key) != value {
fmt.Println(m.Route.URL)
return fmt.Errorf("param %s: expected '%s', got '%s'", key, value, m.GetParam(key))
}
}
}
return nil
}
|
wet-interface/tatbook.web.rest
|
src/main/java/me/m92/tatbook_web/communication/text/producers/TextProducer.java
|
<gh_stars>0
package me.m92.tatbook_web.communication.text.producers;
import me.m92.tatbook_web.communication.text.Text;
import java.util.Map;
public interface TextProducer {
Text produce(Map<String, String> parameters);
}
|
XiaoyuanXie/coming
|
src/main/java/fr/inria/prophet4j/defined/extended/ExtendedFeatureExtractor.java
|
<filename>src/main/java/fr/inria/prophet4j/defined/extended/ExtendedFeatureExtractor.java
package fr.inria.prophet4j.defined.extended;
import java.util.*;
import fr.inria.prophet4j.defined.Feature;
import fr.inria.prophet4j.defined.Feature.Position;
import fr.inria.prophet4j.defined.extended.ExtendedFeature.CrossType;
import fr.inria.prophet4j.defined.extended.ExtendedFeature.AtomicFeature;
import fr.inria.prophet4j.defined.extended.ExtendedFeature.RepairFeature;
import fr.inria.prophet4j.defined.extended.ExtendedFeature.ValueFeature;
import fr.inria.prophet4j.defined.Structure.FeatureVector;
import fr.inria.prophet4j.defined.Structure.Repair;
import fr.inria.prophet4j.defined.extended.util.ExtendedFeatureVisitor;
import fr.inria.prophet4j.defined.FeatureExtractor;
import spoon.reflect.code.CtArrayAccess;
import spoon.reflect.code.CtIf;
import spoon.reflect.code.CtLiteral;
import spoon.reflect.code.CtLocalVariable;
import spoon.reflect.code.CtStatement;
import spoon.reflect.code.CtStatementList;
import spoon.reflect.code.CtVariableAccess;
import spoon.reflect.declaration.CtElement;
import spoon.reflect.declaration.CtField;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtParameter;
import spoon.reflect.reference.CtExecutableReference;
import spoon.reflect.visitor.filter.TypeFilter;
// based on FeatureExtract.cpp, RepairGenerator.cpp
public class ExtendedFeatureExtractor implements FeatureExtractor {
private Map<String, CtElement> valueExprInfo = new HashMap<>();
private EnumSet<RepairFeature> getRepairFeatures(Repair repair) {
EnumSet<RepairFeature> repairFeatures = EnumSet.noneOf(RepairFeature.class);
if (repair.kind == null) {
// I used null in FeatureExtractorTest.java
return repairFeatures;
}
switch (repair.kind) {
case IfExitKind:
// RepairFeature.INSERT_CONTROL_RF == AddControlRepair
repairFeatures.add(RepairFeature.INSERT_CONTROL_RF);
break;
case GuardKind:
case SpecialGuardKind:
// RepairFeature.INSERT_GUARD_RF == GuardRepair
repairFeatures.add(RepairFeature.INSERT_GUARD_RF);
break;
case AddInitKind:
case AddAndReplaceKind:
// RepairFeature.INSERT_STMT_RF == AddStmtRepair
repairFeatures.add(RepairFeature.INSERT_STMT_RF);
break;
case TightenConditionKind:
case LoosenConditionKind:
// RepairFeature.REPLACE_COND_RF == CondRepair
repairFeatures.add(RepairFeature.REPLACE_COND_RF);
break;
case ReplaceKind:
case ReplaceStringKind:
// RepairFeature.REPLACE_STMT_RF == ReplaceStmtRepair
repairFeatures.add(RepairFeature.REPLACE_STMT_RF);
break;
}
return repairFeatures;
}
private EnumSet<ValueFeature> getValueFeature(final String valueStr, final Repair repair, Map<String, CtElement> valueExprInfo) {
EnumSet<ValueFeature> valueFeatures = EnumSet.noneOf(ValueFeature.class);
if (repair.oldRExpr != null && repair.newRExpr != null) {
String oldStr = repair.oldRExpr.toString();
String newStr = repair.newRExpr.toString();
if (valueStr.equals(newStr))
valueFeatures.add(ValueFeature.MODIFIED_VF);
// I can not figure out the meaning of MODIFIED_SIMILAR_VF
if (oldStr.length() > 0 && newStr.length() > 0) {
double ratio = ((double)oldStr.length()) / newStr.length();
if (ratio > 0.5 && ratio < 2 && oldStr.length() > 3 && newStr.length() > 3)
if (oldStr.contains(newStr) || newStr.contains(oldStr))
valueFeatures.add(ValueFeature.MODIFIED_SIMILAR_VF);
}
}
CtElement element = repair.dstElem;
if (element != null) {
CtMethod FD = element.getParent(new TypeFilter<>(CtMethod.class));
if (FD != null) {
for (Object parameter: FD.getParameters()) {
if (parameter instanceof CtParameter) {
CtParameter VD = (CtParameter) parameter;
if (VD.getSimpleName().equals(valueStr))
valueFeatures.add(ValueFeature.FUNC_ARGUMENT_VF);
}
}
}
}
assert(valueExprInfo.containsKey(valueStr));
CtElement E = valueExprInfo.get(valueStr);
if (E instanceof CtVariableAccess || E instanceof CtArrayAccess || E instanceof CtLocalVariable) {
if (E instanceof CtLocalVariable) {
valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF);
} else {
valueFeatures.add(ValueFeature.GLOBAL_VARIABLE_VF);
}
} else if (E instanceof CtExecutableReference){
// to make CALLEE_AF be meaningful todo improve
if (((CtExecutableReference) E).getParameters().size() > 0){
valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF);
}
} else if (E instanceof CtIf){
// to make R_STMT_COND_AF be meaningful todo improve
valueFeatures.add(ValueFeature.LOCAL_VARIABLE_VF);
}
// if (E instanceof CtVariable) {
// if (E instanceof CtLocalVariable)
// valueFeatures.add(SchemaFeature.LOCAL_VARIABLE_VF);
// else
// valueFeatures.add(SchemaFeature.GLOBAL_VARIABLE_VF);
// } else if (E instanceof CtVariableReference) {
// if (E instanceof CtLocalVariableReference)
// valueFeatures.add(SchemaFeature.LOCAL_VARIABLE_VF);
// else
// valueFeatures.add(SchemaFeature.GLOBAL_VARIABLE_VF);
// }
if (valueStr.contains("get"))
valueFeatures.add(ValueFeature.LI_GET_VF);
if (valueStr.contains("size"))
valueFeatures.add(ValueFeature.LI_SIZE_VF);
if (valueStr.contains("length"))
valueFeatures.add(ValueFeature.LI_LENGTH_VF);
if (valueStr.contains("equals"))
valueFeatures.add(ValueFeature.LI_EQUALS_VF);
// i feel this may be incorrect todo check
if (E.getElements(new TypeFilter<>(CtField.class)).size() > 0)
valueFeatures.add(ValueFeature.MEMBER_VF);
if (E instanceof CtLiteral) {
Object value = ((CtLiteral)E).getValue();
if (value == null) {
valueFeatures.add(ValueFeature.LV_NULL_VF);
}
if (value instanceof Byte) {
if ((Byte) value == 0) {
valueFeatures.add(ValueFeature.LV_ZERO_VF);
}
valueFeatures.add(ValueFeature.LT_BYTE_VF);
} else if (value instanceof Character) {
if ((Character) value == 0) {
valueFeatures.add(ValueFeature.LV_ZERO_VF);
}
valueFeatures.add(ValueFeature.LT_CHAR_VF);
} else if (value instanceof Short) {
if ((Short) value == 0) {
valueFeatures.add(ValueFeature.LV_ZERO_VF);
}
valueFeatures.add(ValueFeature.LT_SHORT_VF);
} else if (value instanceof Integer) {
if ((Integer) value == 0) {
valueFeatures.add(ValueFeature.LV_ZERO_VF);
}
valueFeatures.add(ValueFeature.LT_INT_VF);
} else if (value instanceof Long) {
if ((Long) value == 0) {
valueFeatures.add(ValueFeature.LV_ZERO_VF);
}
valueFeatures.add(ValueFeature.LT_LONG_VF);
} else if (value instanceof Float) {
if ((Float) value == 0.0) {
valueFeatures.add(ValueFeature.LV_ZERO_VF);
}
valueFeatures.add(ValueFeature.LT_FLOAT_VF);
} else if (value instanceof Double) {
if ((Double) value == 0.0) {
valueFeatures.add(ValueFeature.LV_ZERO_VF);
}
valueFeatures.add(ValueFeature.LT_DOUBLE_VF);
} else if (value instanceof Boolean) {
valueFeatures.add(ValueFeature.LT_BOOLEAN_VF);
} else if (value instanceof Enum) {
valueFeatures.add(ValueFeature.LT_ENUM_VF);
} else if (value instanceof String) {
if (((String) value).equals("")) {
valueFeatures.add(ValueFeature.LV_BLANK_VF);
}
valueFeatures.add(ValueFeature.LT_STRING_VF);
} else if (value instanceof List) {
if (((List) value).isEmpty()) {
valueFeatures.add(ValueFeature.LV_EMPTY_VF);
}
valueFeatures.add(ValueFeature.LT_LIST_VF);
} else if (value instanceof Map) {
if (((Map) value).isEmpty()) {
valueFeatures.add(ValueFeature.LV_EMPTY_VF);
}
valueFeatures.add(ValueFeature.LT_MAP_VF);
} else if (value instanceof Queue) {
if (((Queue) value).isEmpty()) {
valueFeatures.add(ValueFeature.LV_EMPTY_VF);
}
valueFeatures.add(ValueFeature.LT_QUEUE_VF);
} else if (value instanceof Set) {
if (((Set) value).isEmpty()) {
valueFeatures.add(ValueFeature.LV_EMPTY_VF);
}
valueFeatures.add(ValueFeature.LT_SET_VF);
}
}
return valueFeatures;
}
// this is for CodeDiffer.java
public FeatureVector extractFeature(Repair repair, CtElement atom) {
List<CtElement> stmtsC = getCurrentStmts(repair);
List<CtElement> stmtsF = new ArrayList<>();
List<CtElement> stmtsL = new ArrayList<>();
getNearbyStmts(repair, stmtsF, stmtsL); // update values by reference
Map<String, Set<AtomicFeature>> srcMapC = new HashMap<>();
Map<String, Set<AtomicFeature>> srcMapF = new HashMap<>();
Map<String, Set<AtomicFeature>> srcMapL = new HashMap<>();
Map<String, Set<AtomicFeature>> dstMap = new ExtendedFeatureVisitor(valueExprInfo).traverseRepair(repair, atom);
for (CtElement stmt : stmtsC) {
Map<String, Set<AtomicFeature>> map = new ExtendedFeatureVisitor(valueExprInfo).traverseStmt(stmt);
map.forEach((k, v) -> srcMapC.merge(k, v, (v1, v2) -> {
v1.addAll(v2);
return v1;
}));
}
for (CtElement stmt : stmtsF) {
Map<String, Set<AtomicFeature>> map = new ExtendedFeatureVisitor(valueExprInfo).traverseStmt(stmt);
map.forEach((k, v) -> srcMapF.merge(k, v, (v1, v2) -> {
v1.addAll(v2);
return v1;
}));
}
for (CtElement stmt : stmtsL) {
Map<String, Set<AtomicFeature>> map = new ExtendedFeatureVisitor(valueExprInfo).traverseStmt(stmt);
map.forEach((k, v) -> srcMapL.merge(k, v, (v1, v2) -> {
v1.addAll(v2);
return v1;
}));
}
// this will be merged so we do not care about this value named marked
FeatureVector featureVector = new FeatureVector(false);
// RepairFeatureNum = RepairFeatureNum = 5
EnumSet<RepairFeature> repairFeatures = getRepairFeatures(repair);
// ModKind should be synonyms of RepairType
for (Feature repairFeature : repairFeatures) {
// RF_CT
List<Feature> features = new ArrayList<>();
features.add(repairFeature);
featureVector.addFeatureCross(new ExtendedFeatureCross(CrossType.RF_CT, features));
}
// GlobalFeatureNum = 3 * AtomFeatureNum * RepairFeatureNum = 450
for (Feature repairFeature : repairFeatures) {
if (srcMapC.containsKey("@")) {
Set<AtomicFeature> atomicFeatures = srcMapC.get("@");
for (Feature atomicFeature : atomicFeatures) {
// POS_AF_RF_CT
List<Feature> globalFeatures = new ArrayList<>();
globalFeatures.add(Position.POS_C);
globalFeatures.add(atomicFeature);
globalFeatures.add(repairFeature);
featureVector.addFeatureCross(new ExtendedFeatureCross(CrossType.POS_AF_RF_CT, globalFeatures));
}
}
if (srcMapF.containsKey("@")) {
Set<AtomicFeature> atomicFeatures = srcMapF.get("@");
for (Feature atomicFeature : atomicFeatures) {
// POS_AF_RF_CT
List<Feature> globalFeatures = new ArrayList<>();
globalFeatures.add(Position.POS_F);
globalFeatures.add(atomicFeature);
globalFeatures.add(repairFeature);
featureVector.addFeatureCross(new ExtendedFeatureCross(CrossType.POS_AF_RF_CT, globalFeatures));
}
}
if (srcMapL.containsKey("@")) {
Set<AtomicFeature> atomicFeatures = srcMapL.get("@");
for (Feature atomicFeature : atomicFeatures) {
// POS_AF_RF_CT
List<Feature> globalFeatures = new ArrayList<>();
globalFeatures.add(Position.POS_L);
globalFeatures.add(atomicFeature);
globalFeatures.add(repairFeature);
featureVector.addFeatureCross(new ExtendedFeatureCross(CrossType.POS_AF_RF_CT, globalFeatures));
}
}
}
srcMapC.remove("@");
srcMapF.remove("@");
srcMapL.remove("@");
dstMap.remove("@");
// VarCrossFeatureNum = 3 * AtomFeatureNum * AtomFeatureNum = 2700
for (String key : dstMap.keySet()) {
if (valueExprInfo.containsKey(key)) {
CtElement E = valueExprInfo.get(key);
if (E instanceof CtLiteral)
if (((CtLiteral)E).getValue() instanceof Integer) // ?
continue;
}
if (srcMapC.containsKey(key)) {
Set<AtomicFeature> dstAtomicFeatures = dstMap.get(key);
Set<AtomicFeature> srcAtomicFeatures = srcMapC.get(key);
for (Feature dstAtomicFeature : dstAtomicFeatures) {
for (Feature srcAtomicFeature : srcAtomicFeatures) {
// POS_AF_AF_CT
List<Feature> varCrossFeatures = new ArrayList<>();
varCrossFeatures.add(Position.POS_C);
varCrossFeatures.add(srcAtomicFeature);
varCrossFeatures.add(dstAtomicFeature);
featureVector.addFeatureCross(new ExtendedFeatureCross(CrossType.POS_AF_AF_CT, varCrossFeatures));
}
}
}
if (srcMapF.containsKey(key)) {
Set<AtomicFeature> dstAtomicFeatures = dstMap.get(key);
Set<AtomicFeature> srcAtomicFeatures = srcMapF.get(key);
for (Feature dstAtomicFeature : dstAtomicFeatures) {
for (Feature srcAtomicFeature : srcAtomicFeatures) {
// POS_AF_AF_CT
List<Feature> varCrossFeatures = new ArrayList<>();
varCrossFeatures.add(Position.POS_F);
varCrossFeatures.add(srcAtomicFeature);
varCrossFeatures.add(dstAtomicFeature);
featureVector.addFeatureCross(new ExtendedFeatureCross(CrossType.POS_AF_AF_CT, varCrossFeatures));
}
}
}
if (srcMapL.containsKey(key)) {
Set<AtomicFeature> dstAtomicFeatures = dstMap.get(key);
Set<AtomicFeature> srcAtomicFeatures = srcMapL.get(key);
for (Feature dstAtomicFeature : dstAtomicFeatures) {
for (Feature srcAtomicFeature : srcAtomicFeatures) {
// POS_AF_AF_CT
List<Feature> varCrossFeatures = new ArrayList<>();
varCrossFeatures.add(Position.POS_L);
varCrossFeatures.add(srcAtomicFeature);
varCrossFeatures.add(dstAtomicFeature);
featureVector.addFeatureCross(new ExtendedFeatureCross(CrossType.POS_AF_AF_CT, varCrossFeatures));
}
}
}
}
// ValueCrossFeatureNum = AtomFeatureNum * ValueFeatureNum = 360
for (String key : dstMap.keySet()) {
Set<AtomicFeature> atomicFeatures = dstMap.get(key);
Set<ValueFeature> valueFeatures = getValueFeature(key, repair, valueExprInfo);
for (Feature atomicFeature : atomicFeatures) {
for (Feature valueFeature : valueFeatures) {
// RF_SF_CT
List<Feature> valueCrossFeature = new ArrayList<>();
valueCrossFeature.add(atomicFeature);
valueCrossFeature.add(valueFeature);
featureVector.addFeatureCross(new ExtendedFeatureCross(CrossType.AF_VF_CT, valueCrossFeature));
}
}
}
return featureVector;
}
private List<CtElement> getCurrentStmts(Repair repair) {
List<CtElement> ret = new ArrayList<>();
CtElement srcElem = repair.srcElem;
if (!repair.isReplace) {
ret.add(srcElem);
return ret;
}
else {
ret.add(srcElem);
CtStatement ElseB = null;
if (repair.dstElem instanceof CtIf) {
CtIf IFS = (CtIf) repair.dstElem;
if (IFS.getThenStatement() instanceof CtStatementList) {
CtStatementList CS = IFS.getThenStatement();
ret.addAll(CS.getStatements());
}
else
ret.add(IFS.getThenStatement());
ElseB = IFS.getElseStatement();
if (ElseB != null) {
if (ElseB instanceof CtStatementList) {
CtStatementList CS = IFS.getThenStatement();
ret.addAll(CS.getStatements());
}
else
ret.add(ElseB);
}
}
if (ElseB==null) {
CtElement parent = srcElem.getParent();
if (parent instanceof CtStatementList) {
CtStatementList CS = (CtStatementList) parent;
boolean found = false;
for (CtStatement stmt : CS.getStatements()) {
if (found) {
ret.add(stmt);
break;
}
if (stmt.equals(srcElem))
found = true;
}
}
}
return ret;
}
}
private void getNearbyStmts(Repair repair, List<CtElement> stmtsF, List<CtElement> stmtsL) {
final int LOOKUP_DIS = 3;
CtElement srcElem = repair.srcElem;
CtElement parent = srcElem.getParent();
if (parent instanceof CtStatementList) {
CtStatementList CS = (CtStatementList) parent;
List<CtStatement> tmp = new ArrayList<>();
int idx = 0;
boolean found = false;
for (CtStatement stmt: CS.getStatements()) {
if (stmt.equals(srcElem)) {
found = true;
idx = tmp.size();
}
tmp.add(stmt);
}
assert(found);
int s = 0;
if (idx > LOOKUP_DIS)
s = idx - LOOKUP_DIS;
int e = tmp.size();
if (idx + LOOKUP_DIS + 1 < tmp.size())
e = idx + LOOKUP_DIS + 1;
boolean above = true;
for (int i = s; i < e; i++) {
if (tmp.get(i).equals(srcElem)) {
if (above)
stmtsF.add(tmp.get(i));
else
stmtsL.add(tmp.get(i));
}
if (tmp.get(i).equals(srcElem))
above = false;
}
}
if (!repair.isReplace)
stmtsL.add(srcElem);
}
}
|
Groenbech96/J--Compiler-Implementation
|
src/jminusminus/NGraphRegisterAllocator.java
|
<filename>src/jminusminus/NGraphRegisterAllocator.java
// Copyright 2013 <NAME>, <NAME> and <NAME>
package jminusminus;
import java.util.ArrayList;
/**
* Implements register allocation using graph coloring algorithm.
*/
public class NGraphRegisterAllocator extends NRegisterAllocator {
/**
* Construct a NGraphRegisterAllocator.
*
* @param cfg an instance of a control flow graph.
*/
public NGraphRegisterAllocator(NControlFlowGraph cfg) {
super(cfg);
}
/**
* Build intervals with register allocation information in them.
*/
public void allocation() {
buildIntervals();
}
}
|
hekar/luminousforts-2013
|
mp/src/game/server/Mod/PhaseControl.cpp
|
/* ***** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/LGPL 2.1/GPL 2.0
The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
...
for the specific language governing rights and limitations under the
License.
The Original Code is for LuminousForts.
The Initial Developer of the Original Code is <NAME>.
Portions created by the Hekar Khani are Copyright (C) 2010
<NAME>. All Rights Reserved.
Contributor(s):
<NAME> <<EMAIL>>
Alternatively, the contents of this file may be used under the terms of
either of the GNU General Public License Version 2 or later (the "GPL"),
...
the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK ***** */
#include "cbase.h"
#include "PhaseControl.h"
//
// Name: CPhaseBase
// Author: <NAME>
// Description: Base for each phase
// Notes:
//
CPhaseBase::CPhaseBase( int ID, const char *Name ) :
m_ID (ID)
{
Q_strncpy( m_Name, Name, sizeof( m_Name ) );
}
CPhaseBase::~CPhaseBase()
{
}
int CPhaseBase::GetPhaseTime()
{
return m_PhaseTime;
}
void CPhaseBase::SetPhaseTime( int Seconds )
{
m_PhaseTime = Seconds;
IGameEvent* pEvent = gameeventmanager->CreateEvent( "phase_time", true );
Assert( pEvent );
pEvent->SetInt( "newtime", ( int )m_PhaseTime ); // BEWARE OF FLOAT TO INT
gameeventmanager->FireEvent( pEvent, false );
}
//
// Name: CPhaseManager
// Author: <NAME>
// Description: Manager for game phases
// Notes: This is not a Singleton or global.
// Use as your own object.
//
CPhaseManager::CPhaseManager ()
{
UTIL_PrecacheOther( "precache_sourceforts_sounds" );
}
CPhaseManager::~CPhaseManager ()
{
m_PhaseTable.Purge();
}
void CPhaseManager::AddPhase( CPhaseBase *Phase )
{
m_PhaseTable.AddToTail( Phase );
}
CPhaseBase *CPhaseManager::PreviousPhase()
{
unsigned short index = m_PhaseTable.Find( m_CurrentPhase );
return m_PhaseTable.Element( index % m_PhaseTable.Count() );
}
CPhaseBase *CPhaseManager::NextPhase()
{
unsigned short index = m_PhaseTable.Find( m_CurrentPhase );
return m_PhaseTable.Element( index % m_PhaseTable.Count() );
}
void CPhaseManager::SwitchToPhase( const char *name )
{
CPhaseBase *foundPhase = NULL;
for ( int i = 0; i < m_PhaseTable.Count(); i++ )
{
if ( !Q_stricmp( m_PhaseTable.Element( i )->GetName(), name ) )
{
foundPhase = m_PhaseTable.Element( i );
}
}
if ( foundPhase )
{
SwitchToPhase( foundPhase );
}
}
void CPhaseManager::SwitchToPhase( CPhaseBase *phase )
{
m_CurrentPhase = phase;
m_CurrentPhase->SwitchTo();
IGameEvent* pEvent = gameeventmanager->CreateEvent( "phase_switch", true );
// We always want this event for now
Assert( pEvent );
if ( pEvent )
{
pEvent->SetInt( "phaseid", GetCurrentPhaseID() );
gameeventmanager->FireEvent( pEvent, false );
}
}
int CPhaseManager::GetCurrentPhaseID()
{
return m_CurrentPhase->GetID();
}
const char *CPhaseManager::GetCurrentPhaseName() const
{
return m_CurrentPhase->GetName();
}
CPhaseBase *CPhaseManager::GetCurrentPhase()
{
return m_CurrentPhase;
}
|
oliveira-italo/compras
|
src/main/java/com/udemy/compras/handler/GraphQLHandler.java
|
<gh_stars>0
package com.udemy.compras.handler;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.udemy.compras.exception.DomainException;
import graphql.ExceptionWhileDataFetching;
import graphql.GraphQLError;
import graphql.servlet.GenericGraphQLError;
import graphql.servlet.GraphQLErrorHandler;
import graphql.validation.ValidationError;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component
public class GraphQLHandler implements GraphQLErrorHandler {
@Autowired
private Environment environment;
@Override
public List<GraphQLError> processErrors(List<GraphQLError> list) {
return list.stream().map(this::getErrors).collect(Collectors.toList());
}
private GraphQLError getErrors(GraphQLError error) {
if (error instanceof ExceptionWhileDataFetching) {
if (((ExceptionWhileDataFetching) error).getException() instanceof DomainException) {
String message = ((ExceptionWhileDataFetching) error).getException().getMessage();
return new SimpleError(message);
}
String[] profiles = environment.getActiveProfiles();
boolean isDev = ArrayUtils.contains(profiles, "dev");
if(!isDev) {
return new SimpleError("Ocorreu um erro ao processar a transação");
}
} else if (error instanceof ValidationError) {
return new SimpleError(error.getMessage());
}
return error;
}
class SimpleError extends GenericGraphQLError {
public SimpleError(String message) {
super(message);
}
@Override
@JsonIgnore
public List<Object> getPath() {
return null;
}
@Override
@JsonIgnore
public Map<String, Object> getExtensions() {
return null;
}
}
}
|
jmini/e-mp-oa-code
|
empoa-generator/src/main/java/fr/jmini/empoa/generator/simple/SimpleGeneratorMain.java
|
package fr.jmini.empoa.generator.simple;
import java.nio.file.Paths;
import fr.jmini.empoa.generator.Input;
import fr.jmini.empoa.specs.Element;
import fr.jmini.empoa.specs.OpenAPISpec;
public class SimpleGeneratorMain {
public static void main(String[] args) throws Exception {
Input input = new Input(Paths.get("../empoa-simple-models-impl/src/main/java"), "fr.jmini.empoa.simple.internal");
for (Element element : OpenAPISpec.elements()) {
SimpleGenerator generator = new SimpleGenerator(element, input);
generator.writeFile();
}
}
}
|
marianamtd/Java
|
unirio/src/modulo1/arrays/Exer11Aula19.java
|
package modulo1.arrays;
import java.util.Scanner;
public class Exer11Aula19 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] vetorA = new int[10];
int varPar = 0;
for(int i = 0; i < vetorA.length; i++){
vetorA[i] = scanner.nextInt();
if(vetorA[i] % 2 == 0) {
varPar++;
}
}
System.out.print("Vetor A = [");
for (int var:vetorA){
System.out.print(var + " ");
}
System.out.print("]");
System.out.println("Qtd de pares : " + varPar);
}
}
|
boyombo/pharmrep
|
pharmrep/core/forms.py
|
from datetime import date, timedelta
from django import forms
from product.models import Rep
def sixdaysago():
return date.today() - timedelta(6)
class SearchForm(forms.Form):
start = forms.DateField(initial=sixdaysago, required=False)
end = forms.DateField(initial=date.today, required=False)
rep = forms.ModelChoiceField(queryset=Rep.objects.all, empty_label='Me')
def __init__(self, supervisor, *args, **kwargs):
subordinates = Rep.objects.filter(supervisor=supervisor)
super(SearchForm, self).__init__(*args, **kwargs)
self.fields['rep'] = forms.ModelChoiceField(
queryset=subordinates,
empty_label='{} (You)'.format(supervisor.name),
required=False)
|
jradtilbrook/he-react-ui
|
src/components/Tutorial/tests/TutorialStep.test.js
|
// @flow
import { mount } from 'enzyme';
import React from 'react';
import TutorialOwner from '../TutorialOwner';
import TutorialStep from '../TutorialStep';
import TutorialSpy from './TutorialSpy';
jest.mock('../getCoordsForElementId.js');
function makeHarness(attachTo = null) {
return mount(
<TutorialOwner autoStart steps={['A', 'Z']}>
<TutorialStep id="A" showCarousel attachTo={attachTo}>
<span id="inStepA" />
</TutorialStep>
<TutorialStep id="Z" showCarousel>
<span id="inStepZ" />
</TutorialStep>
<TutorialSpy />
</TutorialOwner>,
);
}
describe('TutorialStep', () => {
it('Should allow advancing by clicking the next button', () => {
const harness = makeHarness();
const stepShown = id => harness.find(`#inStep${id}`).exists();
expect(stepShown('A')).toBeTruthy();
expect(stepShown('Z')).toBeFalsy();
harness.find('.nextBtn').simulate('click');
expect(stepShown('A')).toBeFalsy();
expect(stepShown('Z')).toBeTruthy();
expect(harness.find('.nextBtn').exists()).toBeFalsy();
harness.unmount();
});
it('Should allow dismissing', () => {
const harness = makeHarness();
const stepShown = id => harness.find(`#inStep${id}`).exists();
expect(stepShown('A')).toBeTruthy();
expect(stepShown('Z')).toBeFalsy();
harness.find('svg.close').simulate('click');
expect(stepShown('A')).toBeFalsy();
expect(stepShown('Z')).toBeFalsy();
harness.unmount();
});
it('Should dismiss on click outside', () => {
const harness = makeHarness();
const stepShown = id => harness.find(`#inStep${id}`).exists();
expect(stepShown('A')).toBeTruthy();
harness
.find('TutorialStep')
.first()
.instance()
.handleClickOutside();
expect(harness.find('#tutorialIndex').text()).toBe('-1');
harness.unmount();
});
it('should follow its target element', () => {
const harness = makeHarness('100-200-300');
expect(
harness
.find('#inStepA')
.closest('.outer')
.prop('style'),
).toMatchSnapshot();
harness.unmount();
});
});
|
Chen188/chalice
|
tests/functional/test_local.py
|
<reponame>Chen188/chalice<gh_stars>1000+
import os
import socket
import time
import contextlib
from threading import Thread
from threading import Event
from threading import Lock
import json
import subprocess
from contextlib import contextmanager
import pytest
import requests
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
from chalice import app
from chalice.local import create_local_server
from chalice.config import Config
from chalice.utils import OSUtils
APPS_DIR = os.path.dirname(os.path.abspath(__file__))
ENV_APP_DIR = os.path.join(APPS_DIR, 'envapp')
BASIC_APP = os.path.join(APPS_DIR, 'basicapp')
NEW_APP_VERSION = """
from chalice import Chalice
app = Chalice(app_name='basicapp')
@app.route('/')
def index():
return {'version': 'reloaded'}
"""
@contextmanager
def cd(path):
try:
original_dir = os.getcwd()
os.chdir(path)
yield
finally:
os.chdir(original_dir)
@pytest.fixture()
def basic_app(tmpdir):
tmpdir = str(tmpdir.mkdir('basicapp'))
OSUtils().copytree(BASIC_APP, tmpdir)
return tmpdir
class ThreadedLocalServer(Thread):
def __init__(self, port, host='localhost'):
super(ThreadedLocalServer, self).__init__()
self._app_object = None
self._config = None
self._host = host
self._port = port
self._server = None
self._server_ready = Event()
def wait_for_server_ready(self):
self._server_ready.wait()
def configure(self, app_object, config):
self._app_object = app_object
self._config = config
def run(self):
self._server = create_local_server(
self._app_object, self._config, self._host, self._port)
self._server_ready.set()
self._server.serve_forever()
def make_call(self, method, path, port, timeout=0.5):
self._server_ready.wait()
return method('http://{host}:{port}{path}'.format(
path=path, host=self._host, port=port), timeout=timeout)
def shutdown(self):
if self._server is not None:
self._server.server.shutdown()
@pytest.fixture
def config():
return Config()
@pytest.fixture()
def unused_tcp_port():
with contextlib.closing(socket.socket()) as sock:
sock.bind(('127.0.0.1', 0))
return sock.getsockname()[1]
@pytest.fixture()
def http_session():
session = requests.Session()
retry = Retry(
# How many connection-related errors to retry on.
connect=10,
# A backoff factor to apply between attempts after the second try.
backoff_factor=2,
method_whitelist=['GET', 'POST', 'PUT'],
)
session.mount('http://', HTTPAdapter(max_retries=retry))
return HTTPFetcher(session)
class HTTPFetcher(object):
def __init__(self, session):
self.session = session
def json_get(self, url):
response = self.session.get(url)
response.raise_for_status()
return json.loads(response.content)
@pytest.fixture()
def local_server_factory(unused_tcp_port):
threaded_server = ThreadedLocalServer(unused_tcp_port)
def create_server(app_object, config):
threaded_server.configure(app_object, config)
threaded_server.start()
return threaded_server, unused_tcp_port
try:
yield create_server
finally:
threaded_server.shutdown()
@pytest.fixture
def sample_app():
demo = app.Chalice('demo-app')
thread_safety_check = []
lock = Lock()
@demo.route('/', methods=['GET'])
def index():
return {'hello': 'world'}
@demo.route('/test-cors', methods=['POST'], cors=True)
def test_cors():
return {'hello': 'world'}
@demo.route('/count', methods=['POST'])
def record_counter():
# An extra delay helps ensure we consistently fail if we're
# not thread safe.
time.sleep(0.001)
count = int(demo.current_request.json_body['counter'])
with lock:
thread_safety_check.append(count)
@demo.route('/count', methods=['GET'])
def get_record_counter():
return thread_safety_check[:]
return demo
def test_has_thread_safe_current_request(config, sample_app,
local_server_factory):
local_server, port = local_server_factory(sample_app, config)
local_server.wait_for_server_ready()
num_requests = 25
num_threads = 5
# The idea here is that each requests.post() has a unique 'counter'
# integer. If the current request is thread safe we should see a number
# for each 0 - (num_requests * num_threads). If it's not thread safe
# we'll see missing numbers and/or duplicates.
def make_requests(counter_start):
for i in range(counter_start * num_requests,
(counter_start + 1) * num_requests):
# We're slowing the sending rate down a bit. The threaded
# http server is good, but not great. You can still overwhelm
# it pretty easily.
time.sleep(0.001)
requests.post(
'http://localhost:%s/count' % port, json={'counter': i})
threads = []
for i in range(num_threads):
threads.append(Thread(target=make_requests, args=(i,)))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
response = requests.get('http://localhost:%s/count' % port)
assert len(response.json()) == len(range(num_requests * num_threads))
assert sorted(response.json()) == list(range(num_requests * num_threads))
def test_can_accept_get_request(config, sample_app, local_server_factory):
local_server, port = local_server_factory(sample_app, config)
response = local_server.make_call(requests.get, '/', port)
assert response.status_code == 200
assert response.text == '{"hello":"world"}'
def test_can_get_unicode_string_content_length(
config, local_server_factory):
demo = app.Chalice('app-name')
@demo.route('/')
def index_view():
return u'\u2713'
local_server, port = local_server_factory(demo, config)
response = local_server.make_call(requests.get, '/', port)
assert response.headers['Content-Length'] == '3'
def test_can_accept_options_request(config, sample_app, local_server_factory):
local_server, port = local_server_factory(sample_app, config)
response = local_server.make_call(requests.options, '/test-cors', port)
assert response.headers['Content-Length'] == '0'
assert response.headers['Access-Control-Allow-Methods'] == 'POST,OPTIONS'
assert response.text == ''
def test_can_accept_multiple_options_request(config, sample_app,
local_server_factory):
local_server, port = local_server_factory(sample_app, config)
response = local_server.make_call(requests.options, '/test-cors', port)
assert response.headers['Content-Length'] == '0'
assert response.headers['Access-Control-Allow-Methods'] == 'POST,OPTIONS'
assert response.text == ''
response = local_server.make_call(requests.options, '/test-cors', port)
assert response.headers['Content-Length'] == '0'
assert response.headers['Access-Control-Allow-Methods'] == 'POST,OPTIONS'
assert response.text == ''
def test_can_accept_multiple_connections(config, sample_app,
local_server_factory):
# When a GET request is made to Chalice from a browser, it will send the
# connection keep-alive header in order to hold the connection open and
# reuse it for subsequent requests. If the conncetion close header is sent
# back by the server the connection will be closed, but the browser will
# reopen a new connection just in order to have it ready when needed.
# In this case, since it does not send any content we do not have the
# opportunity to send a connection close header back in a response to
# force it to close the socket.
# This is an issue in Chalice since the single threaded local server will
# now be blocked waiting for IO from the browser socket. If a request from
# any other source is made it will be blocked until the browser sends
# another request through, giving us a chance to read from another socket.
local_server, port = local_server_factory(sample_app, config)
local_server.wait_for_server_ready()
# We create a socket here to emulate a browser's open connection and then
# make a request. The request should succeed.
socket.create_connection(('localhost', port), timeout=1)
try:
response = local_server.make_call(requests.get, '/', port)
except requests.exceptions.ReadTimeout:
assert False, (
'Read timeout occurred, the socket is blocking the next request '
'from going though.'
)
assert response.status_code == 200
assert response.text == '{"hello":"world"}'
def test_can_import_env_vars(unused_tcp_port, http_session):
with cd(ENV_APP_DIR):
p = subprocess.Popen(['chalice', 'local', '--port',
str(unused_tcp_port)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
_wait_for_server_ready(p)
try:
_assert_env_var_loaded(unused_tcp_port, http_session)
finally:
p.terminate()
def _wait_for_server_ready(process):
if process.poll() is not None:
raise AssertionError(
'Local server immediately exited with rc: %s' % process.poll()
)
def _assert_env_var_loaded(port_number, http_session):
response = http_session.json_get('http://localhost:%s/' % port_number)
assert response == {'hello': 'bar'}
def test_can_reload_server(unused_tcp_port, basic_app, http_session):
with cd(basic_app):
p = subprocess.Popen(['chalice', 'local', '--port',
str(unused_tcp_port)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
_wait_for_server_ready(p)
url = 'http://localhost:%s/' % unused_tcp_port
try:
assert http_session.json_get(url) == {'version': 'original'}
# Updating the app should trigger a reload.
with open(os.path.join(basic_app, 'app.py'), 'w') as f:
f.write(NEW_APP_VERSION)
time.sleep(2)
assert http_session.json_get(url) == {'version': 'reloaded'}
finally:
p.terminate()
|
itinycheng/flink-learn
|
api/src/main/scala/com/tiny/flink/streaming/function/QueryableStateFunction.scala
|
package com.tiny.flink.streaming.function
import org.apache.flink.api.common.functions.RichMapFunction
import org.apache.flink.api.common.state.{ValueState, ValueStateDescriptor}
import org.apache.flink.api.common.typeinfo.{TypeHint, TypeInformation}
import org.apache.flink.configuration.Configuration
class QueryableStateFunction extends RichMapFunction[(String, Int), (String, Int)] {
/**
* NOTE - TINY:
* client must keep Type[[java.lang.Integer]] consistent with server
* that's why user Integer instead of scala.Int
*/
private[this] var state: ValueState[Integer] = _
override def map(value: (String, Int)): (String, Int) = {
val tmp = state
val count = if (null == tmp.value()) 0 else tmp.value() + 1
tmp.update(count)
(value._1, count)
}
override def open(parameters: Configuration): Unit = {
val descriptor = new ValueStateDescriptor[Integer]("sum",
TypeInformation.of(new TypeHint[Integer] {}))
descriptor.setQueryable("word_count")
state = getRuntimeContext.getState(descriptor)
}
override def close(): Unit = {
println("close")
}
}
object QueryableStateFunction {
def apply(): QueryableStateFunction = new QueryableStateFunction()
}
|
timm-gs/bazel
|
src/main/java/com/google/devtools/build/lib/bazel/rules/common/BazelFilegroupRule.java
|
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.bazel.rules.common;
import static com.google.devtools.build.lib.packages.Attribute.ConfigurationTransition.DATA;
import static com.google.devtools.build.lib.packages.Attribute.attr;
import static com.google.devtools.build.lib.packages.BuildType.LABEL_LIST;
import static com.google.devtools.build.lib.packages.BuildType.LICENSE;
import static com.google.devtools.build.lib.syntax.Type.STRING;
import com.google.devtools.build.lib.analysis.BaseRuleClasses;
import com.google.devtools.build.lib.analysis.RuleDefinition;
import com.google.devtools.build.lib.analysis.RuleDefinitionEnvironment;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClass.Builder;
import com.google.devtools.build.lib.rules.filegroup.Filegroup;
import com.google.devtools.build.lib.util.FileTypeSet;
/**
* Rule object implementing "filegroup".
*/
public final class BazelFilegroupRule implements RuleDefinition {
@Override
public RuleClass build(Builder builder, RuleDefinitionEnvironment env) {
// filegroup ignores any filtering set with setSrcsAllowedFiles.
return builder
/*<!-- #BLAZE_RULE(filegroup).ATTRIBUTE(srcs) -->
The list of targets that are members of the file group.
<p>
It is common to use the result of a <a href="${link glob}">glob</a> expression for
the value
of the <code>srcs</code> attribute. If a rule and a source file with the same name both
exist in the package, the glob will return the outputs of the rule instead of the source
file.
</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
.add(attr("srcs", LABEL_LIST).allowedFileTypes(FileTypeSet.ANY_FILE))
/*<!-- #BLAZE_RULE(filegroup).ATTRIBUTE(output_group) -->
The output group from which to gather artifacts from sources. If this attribute is
specified, artifacts from the specified output group of the dependencies will be exported
instead of the default output group.
<p>An "output group" is a category of output artifacts of a target, specified in that
rule's implementation.
</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
.add(attr("output_group", STRING))
/*<!-- #BLAZE_RULE(filegroup).ATTRIBUTE(data) -->
The list of files needed by this rule at runtime.
<p>
Targets named in the <code>data</code> attribute will be added to the
<code>runfiles</code> of this <code>filegroup</code> rule. When the
<code>filegroup</code> is referenced in the <code>data</code> attribute of
another rule its <code>runfiles</code> will be added to the <code>runfiles</code>
of the depending rule. See the <a href="../build-ref.html#data">data dependencies</a>
section and <a href="${link common-definitions#common.data}">general documentation of
<code>data</code></a> for more information about how to depend on and use data files.
</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
.add(
attr("data", LABEL_LIST)
.cfg(DATA)
.allowedFileTypes(FileTypeSet.ANY_FILE)
.dontCheckConstraints())
.add(attr("output_licenses", LICENSE))
/*<!-- #BLAZE_RULE(filegroup).ATTRIBUTE(path) -->
An optional string to set a path to the files in the group, relative to the package path.
<p>
This attribute can be used internally by other rules depending on this
<code>filegroup</code> to find the name of the directory holding the files.
</p>
<!-- #END_BLAZE_RULE.ATTRIBUTE -->*/
.add(
attr("path", STRING)
.undocumented(
"only used to expose FilegroupPathProvider, which is not currently used"))
.build();
}
@Override
public Metadata getMetadata() {
return RuleDefinition.Metadata.builder()
.name("filegroup")
.ancestors(BaseRuleClasses.BaseRule.class)
.factoryClass(Filegroup.class)
.build();
}
}
/*<!-- #BLAZE_RULE (NAME = filegroup, TYPE = BINARY, FAMILY = General)[GENERIC_RULE] -->
<p>
Use <code>filegroup</code> to give a convenient name to a collection of targets.
These can then be referenced from other rules.
</p>
<p>
Using <code>filegroup</code> is encouraged instead of referencing directories directly.
The latter is unsound since the build system does not have full knowledge of all files
below the directory, so it may not rebuild when these files change. When combined with
<a href="${link glob}">glob</a>, <code>filegroup</code> can ensure that all files are
explicitly known to the build system.
</p>
<h4 id="filegroup_example">Examples</h4>
<p>
To create a <code>filegroup</code> consisting of two source files, do
</p>
<pre class="code">
filegroup(
name = "mygroup",
srcs = [
"a_file.txt",
"some/subdirectory/another_file.txt",
],
)
</pre>
<p>
Or, use a <code>glob</code> to grovel a testdata directory:
</p>
<pre class="code">
filegroup(
name = "exported_testdata",
srcs = glob([
"testdata/*.dat",
"testdata/logs/**/*.log",
]),
)
</pre>
<p>
To make use of these definitions, reference the <code>filegroup</code> with a label from any rule:
</p>
<pre class="code">
cc_library(
name = "my_library",
srcs = ["foo.cc"],
data = [
"//my_package:exported_testdata",
"//my_package:mygroup",
],
)
</pre>
<!-- #END_BLAZE_RULE -->*/
|
Memristor-Robotics/mep-dash-kibana
|
src/ui/public/agg_response/point_series/_tooltip_formatter.js
|
<reponame>Memristor-Robotics/mep-dash-kibana
define(function (require) {
return function PointSeriesTooltipFormatter($compile, $rootScope) {
let $ = require('jquery');
let $tooltipScope = $rootScope.$new();
let $tooltip = $(require('ui/agg_response/point_series/_tooltip.html'));
$compile($tooltip)($tooltipScope);
return function tooltipFormatter(event) {
let datum = event.datum;
if (!datum || !datum.aggConfigResult) return '';
let details = $tooltipScope.details = [];
let result = { $parent: datum.aggConfigResult };
function addDetail(result) {
let agg = result.aggConfig;
let value = result.value;
let detail = {
value: agg.fieldFormatter()(value),
label: agg.makeLabel()
};
if (agg === datum.aggConfigResult.aggConfig) {
detail.percent = event.percent;
if (datum.yScale != null) {
detail.value = agg.fieldFormatter()(value * datum.yScale);
}
}
details.push(detail);
}
datum.extraMetrics.forEach(addDetail);
while ((result = result.$parent) && result.aggConfig) {
addDetail(result);
}
$tooltipScope.$apply();
return $tooltip[0].outerHTML;
};
};
});
|
leanwithdata/hop
|
plugins/transforms/concatfields/src/main/java/org/apache/hop/pipeline/transforms/concatfields/ConcatFieldsDialog.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hop.pipeline.transforms.concatfields;
import org.apache.hop.core.Const;
import org.apache.hop.core.Props;
import org.apache.hop.core.exception.HopException;
import org.apache.hop.core.row.IRowMeta;
import org.apache.hop.core.row.IValueMeta;
import org.apache.hop.core.row.value.ValueMetaBase;
import org.apache.hop.core.util.StringUtil;
import org.apache.hop.core.variables.IVariables;
import org.apache.hop.i18n.BaseMessages;
import org.apache.hop.pipeline.PipelineMeta;
import org.apache.hop.pipeline.transform.BaseTransformMeta;
import org.apache.hop.pipeline.transform.ITransformDialog;
import org.apache.hop.pipeline.transform.TransformMeta;
import org.apache.hop.pipeline.transforms.textfileoutput.TextFileField;
import org.apache.hop.ui.core.dialog.BaseDialog;
import org.apache.hop.ui.core.dialog.ErrorDialog;
import org.apache.hop.ui.core.widget.ColumnInfo;
import org.apache.hop.ui.core.widget.TableView;
import org.apache.hop.ui.core.widget.TextVar;
import org.apache.hop.ui.pipeline.transform.BaseTransformDialog;
import org.apache.hop.ui.pipeline.transform.ITableItemInsertListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.*;
import java.util.List;
import java.util.*;
/*
* ConcatFieldsDialog
*
*/
public class ConcatFieldsDialog extends BaseTransformDialog implements ITransformDialog {
private static final Class<?> PKG = ConcatFieldsMeta.class; // For Translator
private TextVar wTargetFieldName;
private Text wTargetFieldLength;
private TextVar wSeparator;
private TextVar wEnclosure;
private TableView wFields;
private ConcatFieldsMeta input;
private boolean gotEncodings = false;
private ColumnInfo[] colinf;
private Map<String, Integer> inputFields;
public ConcatFieldsDialog(
Shell parent, IVariables variables, Object in, PipelineMeta pipelineMeta, String sname) {
super(parent, variables, (BaseTransformMeta) in, pipelineMeta, sname);
input = (ConcatFieldsMeta) in;
inputFields = new HashMap<>();
}
@Override
public String open() {
Shell parent = getParent();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
setShellImage(shell, input);
ModifyListener lsMod =
new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG, "ConcatFieldsDialog.DialogTitle"));
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// These buttons go at the very bottom
//
wOk = new Button(shell, SWT.PUSH);
wOk.setText(BaseMessages.getString(PKG, "System.Button.OK"));
wOk.addListener(SWT.Selection, e -> ok());
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel"));
wCancel.addListener(SWT.Selection, e -> cancel());
setButtonPositions(new Button[] {wOk, wCancel}, margin, null);
// transformName line
wlTransformName = new Label(shell, SWT.RIGHT);
wlTransformName.setText(BaseMessages.getString(PKG, "System.Label.TransformName"));
props.setLook(wlTransformName);
fdlTransformName = new FormData();
fdlTransformName.left = new FormAttachment(0, 0);
fdlTransformName.top = new FormAttachment(0, margin);
fdlTransformName.right = new FormAttachment(middle, -margin);
wlTransformName.setLayoutData(fdlTransformName);
wTransformName = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wTransformName.setText(transformName);
props.setLook(wTransformName);
wTransformName.addModifyListener(lsMod);
fdTransformName = new FormData();
fdTransformName.left = new FormAttachment(middle, 0);
fdTransformName.top = new FormAttachment(0, margin);
fdTransformName.right = new FormAttachment(100, 0);
wTransformName.setLayoutData(fdTransformName);
// TargetFieldName line
Label wlTargetFieldName = new Label(shell, SWT.RIGHT);
wlTargetFieldName.setText(
BaseMessages.getString(PKG, "ConcatFieldsDialog.TargetFieldName.Label"));
wlTargetFieldName.setToolTipText(
BaseMessages.getString(PKG, "ConcatFieldsDialog.TargetFieldName.Tooltip"));
props.setLook(wlTargetFieldName);
FormData fdlTargetFieldName = new FormData();
fdlTargetFieldName.left = new FormAttachment(0, 0);
fdlTargetFieldName.top = new FormAttachment(wTransformName, margin);
fdlTargetFieldName.right = new FormAttachment(middle, -margin);
wlTargetFieldName.setLayoutData(fdlTargetFieldName);
wTargetFieldName = new TextVar(variables, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
wTargetFieldName.setText("");
props.setLook(wTargetFieldName);
wTargetFieldName.addModifyListener(lsMod);
FormData fdTargetFieldName = new FormData();
fdTargetFieldName.left = new FormAttachment(middle, 0);
fdTargetFieldName.top = new FormAttachment(wTransformName, margin);
fdTargetFieldName.right = new FormAttachment(100, 0);
wTargetFieldName.setLayoutData(fdTargetFieldName);
// TargetFieldLength line
Label wlTargetFieldLength = new Label(shell, SWT.RIGHT);
wlTargetFieldLength.setText(
BaseMessages.getString(PKG, "ConcatFieldsDialog.TargetFieldLength.Label"));
wlTargetFieldLength.setToolTipText(
BaseMessages.getString(PKG, "ConcatFieldsDialog.TargetFieldLength.Tooltip"));
props.setLook(wlTargetFieldLength);
FormData fdlTargetFieldLength = new FormData();
fdlTargetFieldLength.left = new FormAttachment(0, 0);
fdlTargetFieldLength.top = new FormAttachment(wTargetFieldName, margin);
fdlTargetFieldLength.right = new FormAttachment(middle, -margin);
wlTargetFieldLength.setLayoutData(fdlTargetFieldLength);
wTargetFieldLength = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wTargetFieldLength);
wTargetFieldLength.addModifyListener(lsMod);
FormData fdTargetFieldLength = new FormData();
fdTargetFieldLength.left = new FormAttachment(middle, 0);
fdTargetFieldLength.top = new FormAttachment(wTargetFieldName, margin);
fdTargetFieldLength.right = new FormAttachment(100, 0);
wTargetFieldLength.setLayoutData(fdTargetFieldLength);
// Separator
Label wlSeparator = new Label(shell, SWT.RIGHT);
wlSeparator.setText(BaseMessages.getString(PKG, "ConcatFieldsDialog.Separator.Label"));
props.setLook(wlSeparator);
FormData fdlSeparator = new FormData();
fdlSeparator.left = new FormAttachment(0, 0);
fdlSeparator.top = new FormAttachment(wTargetFieldLength, margin);
fdlSeparator.right = new FormAttachment(middle, -margin);
wlSeparator.setLayoutData(fdlSeparator);
Button wbSeparator = new Button(shell, SWT.PUSH | SWT.CENTER);
props.setLook(wbSeparator);
wbSeparator.setText(BaseMessages.getString(PKG, "ConcatFieldsDialog.Separator.Button"));
FormData fdbSeparator = new FormData();
fdbSeparator.right = new FormAttachment(100, 0);
fdbSeparator.top = new FormAttachment(wTargetFieldLength, margin);
wbSeparator.setLayoutData(fdbSeparator);
wbSeparator.addSelectionListener(
new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent se) {
wSeparator.getTextWidget().insert("\t");
}
});
wSeparator = new TextVar(variables, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wSeparator);
wSeparator.addModifyListener(lsMod);
FormData fdSeparator = new FormData();
fdSeparator.left = new FormAttachment(middle, 0);
fdSeparator.top = new FormAttachment(wTargetFieldLength, margin);
fdSeparator.right = new FormAttachment(wbSeparator, -margin);
wSeparator.setLayoutData(fdSeparator);
// Enclosure line...
Label wlEnclosure = new Label(shell, SWT.RIGHT);
wlEnclosure.setText(BaseMessages.getString(PKG, "ConcatFieldsDialog.Enclosure.Label"));
props.setLook(wlEnclosure);
FormData fdlEnclosure = new FormData();
fdlEnclosure.left = new FormAttachment(0, 0);
fdlEnclosure.top = new FormAttachment(wSeparator, margin);
fdlEnclosure.right = new FormAttachment(middle, -margin);
wlEnclosure.setLayoutData(fdlEnclosure);
wEnclosure = new TextVar(variables, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wEnclosure);
wEnclosure.addModifyListener(lsMod);
FormData fdEnclosure = new FormData();
fdEnclosure.left = new FormAttachment(middle, 0);
fdEnclosure.top = new FormAttachment(wSeparator, margin);
fdEnclosure.right = new FormAttachment(100, 0);
wEnclosure.setLayoutData(fdEnclosure);
// ////////////////////////
// START OF TABS
// /
CTabFolder wTabFolder = new CTabFolder(shell, SWT.BORDER);
props.setLook(wTabFolder, Props.WIDGET_STYLE_TAB);
// Fields tab...
//
CTabItem wFieldsTab = new CTabItem(wTabFolder, SWT.NONE);
wFieldsTab.setText(BaseMessages.getString(PKG, "ConcatFieldsDialog.FieldsTab.TabTitle"));
FormLayout fieldsLayout = new FormLayout();
fieldsLayout.marginWidth = Const.FORM_MARGIN;
fieldsLayout.marginHeight = Const.FORM_MARGIN;
Composite wFieldsComp = new Composite(wTabFolder, SWT.NONE);
wFieldsComp.setLayout(fieldsLayout);
props.setLook(wFieldsComp);
wGet = new Button(wFieldsComp, SWT.PUSH);
wGet.setText(BaseMessages.getString(PKG, "System.Button.GetFields"));
wGet.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.GetFields"));
wGet.addListener(SWT.Selection, e -> get());
Button wMinWidth = new Button(wFieldsComp, SWT.PUSH);
wMinWidth.setText(BaseMessages.getString(PKG, "ConcatFieldsDialog.MinWidth.Button"));
wMinWidth.setToolTipText(BaseMessages.getString(PKG, "ConcatFieldsDialog.MinWidth.Tooltip"));
wMinWidth.addListener(SWT.Selection, e -> setMinimalWidth());
setButtonPositions(new Button[] {wGet, wMinWidth}, margin, null);
final int FieldsCols = 10;
final int FieldsRows = input.getOutputFields().length;
// Prepare a list of possible formats...
String[] dats = Const.getDateFormats();
String[] nums = Const.getNumberFormats();
int totsize = dats.length + nums.length;
String[] formats = new String[totsize];
for (int x = 0; x < dats.length; x++) {
formats[x] = dats[x];
}
for (int x = 0; x < nums.length; x++) {
formats[dats.length + x] = nums[x];
}
colinf = new ColumnInfo[FieldsCols];
colinf[0] =
new ColumnInfo(
BaseMessages.getString(PKG, "ConcatFieldsDialog.NameColumn.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO,
new String[] {""},
false);
colinf[1] =
new ColumnInfo(
BaseMessages.getString(PKG, "ConcatFieldsDialog.TypeColumn.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO,
ValueMetaBase.getTypes());
colinf[2] =
new ColumnInfo(
BaseMessages.getString(PKG, "ConcatFieldsDialog.FormatColumn.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO,
formats);
colinf[3] =
new ColumnInfo(
BaseMessages.getString(PKG, "ConcatFieldsDialog.LengthColumn.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false);
colinf[4] =
new ColumnInfo(
BaseMessages.getString(PKG, "ConcatFieldsDialog.PrecisionColumn.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false);
colinf[5] =
new ColumnInfo(
BaseMessages.getString(PKG, "ConcatFieldsDialog.CurrencyColumn.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false);
colinf[6] =
new ColumnInfo(
BaseMessages.getString(PKG, "ConcatFieldsDialog.DecimalColumn.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false);
colinf[7] =
new ColumnInfo(
BaseMessages.getString(PKG, "ConcatFieldsDialog.GroupColumn.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false);
colinf[8] =
new ColumnInfo(
BaseMessages.getString(PKG, "ConcatFieldsDialog.TrimTypeColumn.Column"),
ColumnInfo.COLUMN_TYPE_CCOMBO,
ValueMetaBase.trimTypeDesc,
true);
colinf[9] =
new ColumnInfo(
BaseMessages.getString(PKG, "ConcatFieldsDialog.NullColumn.Column"),
ColumnInfo.COLUMN_TYPE_TEXT,
false);
wFields =
new TableView(
variables,
wFieldsComp,
SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI,
colinf,
FieldsRows,
lsMod,
props);
FormData fdFields = new FormData();
fdFields.left = new FormAttachment(0, 0);
fdFields.top = new FormAttachment(0, 0);
fdFields.right = new FormAttachment(100, 0);
fdFields.bottom = new FormAttachment(wGet, -margin);
wFields.setLayoutData(fdFields);
//
// Search the fields in the background
final Runnable runnable =
new Runnable() {
@Override
public void run() {
TransformMeta transformMeta = pipelineMeta.findTransform(transformName);
if (transformMeta != null) {
try {
IRowMeta row = pipelineMeta.getPrevTransformFields(variables, transformMeta);
// Remember these fields...
for (int i = 0; i < row.size(); i++) {
inputFields.put(row.getValueMeta(i).getName(), Integer.valueOf(i));
}
setComboBoxes();
} catch (HopException e) {
logError(BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Message"));
}
}
}
};
new Thread(runnable).start();
FormData fdFieldsComp = new FormData();
fdFieldsComp.left = new FormAttachment(0, 0);
fdFieldsComp.top = new FormAttachment(0, 0);
fdFieldsComp.right = new FormAttachment(100, 0);
fdFieldsComp.bottom = new FormAttachment(100, 0);
wFieldsComp.setLayoutData(fdFieldsComp);
wFieldsComp.layout();
wFieldsTab.setControl(wFieldsComp);
FormData fdTabFolder = new FormData();
fdTabFolder.left = new FormAttachment(0, 0);
fdTabFolder.top = new FormAttachment(wEnclosure, margin);
fdTabFolder.right = new FormAttachment(100, 0);
fdTabFolder.bottom = new FormAttachment(wOk, -2 * margin);
wTabFolder.setLayoutData(fdTabFolder);
// Whenever something changes, set the tooltip to the expanded version:
wTargetFieldName.addModifyListener(
new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
wTargetFieldName.setToolTipText(variables.resolve(wTargetFieldName.getText()));
}
});
lsResize =
event -> {
Point size = shell.getSize();
wFields.setSize(size.x - 10, size.y - 50);
wFields.table.setSize(size.x - 10, size.y - 50);
wFields.redraw();
};
shell.addListener(SWT.Resize, lsResize);
wTabFolder.setSelection(0);
getData();
BaseDialog.defaultShellHandling(shell, c -> ok(), c -> cancel());
return transformName;
}
protected void setComboBoxes() {
// Something was changed in the row.
//
final Map<String, Integer> fields = new HashMap<>();
// Add the currentMeta fields...
fields.putAll(inputFields);
Set<String> keySet = fields.keySet();
List<String> entries = new ArrayList<>(keySet);
String[] fieldNames = entries.toArray(new String[entries.size()]);
Const.sortStrings(fieldNames);
colinf[0].setComboValues(fieldNames);
}
/** Copy information from the meta-data input to the dialog fields. */
public void getData() {
// New concat fields
if (input.getTargetFieldName() != null) {
wTargetFieldName.setText(input.getTargetFieldName());
}
wTargetFieldLength.setText("" + input.getTargetFieldLength());
wSeparator.setText(Const.NVL(input.getSeparator(), ""));
wEnclosure.setText(Const.NVL(input.getEnclosure(), ""));
logDebug("getting fields info...");
for (int i = 0; i < input.getOutputFields().length; i++) {
TextFileField field = input.getOutputFields()[i];
TableItem item = wFields.table.getItem(i);
if (field.getName() != null) {
item.setText(1, field.getName());
}
item.setText(2, field.getTypeDesc());
if (field.getFormat() != null) {
item.setText(3, field.getFormat());
}
if (field.getLength() >= 0) {
item.setText(4, "" + field.getLength());
}
if (field.getPrecision() >= 0) {
item.setText(5, "" + field.getPrecision());
}
if (field.getCurrencySymbol() != null) {
item.setText(6, field.getCurrencySymbol());
}
if (field.getDecimalSymbol() != null) {
item.setText(7, field.getDecimalSymbol());
}
if (field.getGroupingSymbol() != null) {
item.setText(8, field.getGroupingSymbol());
}
String trim = field.getTrimTypeDesc();
if (trim != null) {
item.setText(9, trim);
}
if (field.getNullString() != null) {
item.setText(10, field.getNullString());
}
}
wFields.optWidth(true);
wTransformName.selectAll();
wTransformName.setFocus();
}
private void cancel() {
transformName = null;
input.setChanged(backupChanged);
dispose();
}
private void getInfo(ConcatFieldsMeta tfoi) {
// New concat fields
tfoi.setTargetFieldName(wTargetFieldName.getText());
tfoi.setTargetFieldLength(Const.toInt(wTargetFieldLength.getText(), 0));
tfoi.setSeparator(wSeparator.getText());
tfoi.setEnclosure(wEnclosure.getText());
int i;
int nrFields = wFields.nrNonEmpty();
tfoi.allocate(nrFields);
for (i = 0; i < nrFields; i++) {
TextFileField field = new TextFileField();
TableItem item = wFields.getNonEmpty(i);
field.setName(item.getText(1));
field.setType(item.getText(2));
field.setFormat(item.getText(3));
field.setLength(Const.toInt(item.getText(4), -1));
field.setPrecision(Const.toInt(item.getText(5), -1));
field.setCurrencySymbol(item.getText(6));
field.setDecimalSymbol(item.getText(7));
field.setGroupingSymbol(item.getText(8));
field.setTrimType(ValueMetaBase.getTrimTypeByDesc(item.getText(9)));
field.setNullString(item.getText(10));
// CHECKSTYLE:Indentation:OFF
tfoi.getOutputFields()[i] = field;
}
}
private void ok() {
if (StringUtil.isEmpty(wTransformName.getText())) {
return;
}
transformName = wTransformName.getText(); // return value
getInfo(input);
dispose();
}
private void get() {
try {
IRowMeta r = pipelineMeta.getPrevTransformFields(variables, transformName);
if (r != null) {
ITableItemInsertListener listener =
new ITableItemInsertListener() {
@Override
public boolean tableItemInserted(TableItem tableItem, IValueMeta v) {
if (v.isNumber()) {
if (v.getLength() > 0) {
int le = v.getLength();
int pr = v.getPrecision();
if (v.getPrecision() <= 0) {
pr = 0;
}
String mask = "";
for (int m = 0; m < le - pr; m++) {
mask += "0";
}
if (pr > 0) {
mask += ".";
}
for (int m = 0; m < pr; m++) {
mask += "0";
}
tableItem.setText(3, mask);
}
}
return true;
}
};
BaseTransformDialog.getFieldsFromPrevious(
r, wFields, 1, new int[] {1}, new int[] {2}, 4, 5, listener);
}
} catch (HopException ke) {
new ErrorDialog(
shell,
BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Title"),
BaseMessages.getString(PKG, "System.Dialog.GetFieldsFailed.Message"),
ke);
}
}
/** Sets the output width to minimal width... */
public void setMinimalWidth() {
int nrNonEmptyFields = wFields.nrNonEmpty();
for (int i = 0; i < nrNonEmptyFields; i++) {
TableItem item = wFields.getNonEmpty(i);
item.setText(4, "");
item.setText(5, "");
item.setText(9, ValueMetaBase.getTrimTypeDesc(IValueMeta.TRIM_TYPE_BOTH));
int type = ValueMetaBase.getType(item.getText(2));
switch (type) {
case IValueMeta.TYPE_STRING:
item.setText(3, "");
break;
case IValueMeta.TYPE_INTEGER:
item.setText(3, "0");
break;
case IValueMeta.TYPE_NUMBER:
item.setText(3, "0.#####");
break;
case IValueMeta.TYPE_DATE:
break;
default:
break;
}
}
for (int i = 0; i < input.getOutputFields().length; i++) {
input.getOutputFields()[i].setTrimType(IValueMeta.TRIM_TYPE_BOTH);
}
wFields.optWidth(true);
}
}
|
dmgerman/guava
|
guava/src/com/google/common/base/AbstractIterator.java
|
<reponame>dmgerman/guava<gh_stars>0
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */
end_comment
begin_package
DECL|package|com.google.common.base
package|package
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
package|;
end_package
begin_import
import|import static
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
operator|.
name|NullnessCasts
operator|.
name|uncheckedCastNullableTToT
import|;
end_import
begin_import
import|import static
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
operator|.
name|Preconditions
operator|.
name|checkState
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|annotations
operator|.
name|GwtCompatible
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|errorprone
operator|.
name|annotations
operator|.
name|CanIgnoreReturnValue
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Iterator
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|NoSuchElementException
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|annotation
operator|.
name|CheckForNull
import|;
end_import
begin_import
import|import
name|org
operator|.
name|checkerframework
operator|.
name|checker
operator|.
name|nullness
operator|.
name|qual
operator|.
name|Nullable
import|;
end_import
begin_comment
comment|/** * Note this class is a copy of {@link com.google.common.collect.AbstractIterator} (for dependency * reasons). */
end_comment
begin_annotation
annotation|@
name|GwtCompatible
end_annotation
begin_annotation
annotation|@
name|ElementTypesAreNonnullByDefault
end_annotation
begin_expr_stmt
DECL|class|AbstractIterator
specifier|abstract
name|class
name|AbstractIterator
operator|<
name|T
expr|extends @
name|Nullable
name|Object
operator|>
expr|implements
name|Iterator
argument_list|<
name|T
argument_list|>
block|{
DECL|field|state
specifier|private
name|State
name|state
operator|=
name|State
operator|.
name|NOT_READY
block|;
DECL|method|AbstractIterator ()
specifier|protected
name|AbstractIterator
argument_list|()
block|{}
DECL|enum|State
specifier|private
expr|enum
name|State
block|{
DECL|enumConstant|READY
name|READY
block|,
DECL|enumConstant|NOT_READY
name|NOT_READY
block|,
DECL|enumConstant|DONE
name|DONE
block|,
DECL|enumConstant|FAILED
name|FAILED
block|, }
DECL|field|next
expr|@
name|CheckForNull
specifier|private
name|T
name|next
block|; @
name|CheckForNull
DECL|method|computeNext ()
specifier|protected
specifier|abstract
name|T
name|computeNext
argument_list|()
block|; @
name|CanIgnoreReturnValue
expr|@
name|CheckForNull
DECL|method|endOfData ()
specifier|protected
name|final
name|T
name|endOfData
argument_list|()
block|{
name|state
operator|=
name|State
operator|.
name|DONE
block|;
return|return
literal|null
return|;
block|}
expr|@
name|Override
DECL|method|hasNext ()
specifier|public
name|final
name|boolean
name|hasNext
argument_list|()
block|{
name|checkState
argument_list|(
name|state
operator|!=
name|State
operator|.
name|FAILED
argument_list|)
block|;
switch|switch
condition|(
name|state
condition|)
block|{
case|case
name|DONE
case|:
return|return
literal|false
return|;
case|case
name|READY
case|:
return|return
literal|true
return|;
default|default:
block|}
end_expr_stmt
begin_return
return|return
name|tryToComputeNext
argument_list|()
return|;
end_return
begin_function
unit|} private
DECL|method|tryToComputeNext ()
name|boolean
name|tryToComputeNext
parameter_list|()
block|{
name|state
operator|=
name|State
operator|.
name|FAILED
expr_stmt|;
comment|// temporary pessimism
name|next
operator|=
name|computeNext
argument_list|()
expr_stmt|;
if|if
condition|(
name|state
operator|!=
name|State
operator|.
name|DONE
condition|)
block|{
name|state
operator|=
name|State
operator|.
name|READY
expr_stmt|;
return|return
literal|true
return|;
block|}
return|return
literal|false
return|;
block|}
end_function
begin_function
annotation|@
name|Override
annotation|@
name|ParametricNullness
DECL|method|next ()
specifier|public
specifier|final
name|T
name|next
parameter_list|()
block|{
if|if
condition|(
operator|!
name|hasNext
argument_list|()
condition|)
block|{
throw|throw
operator|new
name|NoSuchElementException
argument_list|()
throw|;
block|}
name|state
operator|=
name|State
operator|.
name|NOT_READY
expr_stmt|;
comment|// Safe because hasNext() ensures that tryToComputeNext() has put a T into `next`.
name|T
name|result
init|=
name|uncheckedCastNullableTToT
argument_list|(
name|next
argument_list|)
decl_stmt|;
name|next
operator|=
literal|null
expr_stmt|;
return|return
name|result
return|;
block|}
end_function
begin_function
annotation|@
name|Override
DECL|method|remove ()
specifier|public
specifier|final
name|void
name|remove
parameter_list|()
block|{
throw|throw
operator|new
name|UnsupportedOperationException
argument_list|()
throw|;
block|}
end_function
unit|}
end_unit
|
reid47/cnjs
|
src/index.js
|
import { buildRule } from './build-rule';
const rule = (parts, ...args) => buildRule(parts, args);
const global = (parts, ...args) => buildRule(parts, args, true);
export { rule, global };
export { rehydrate } from './rehydrate';
export { renderStatic } from './render-static';
|
kiranparajuli589/reva
|
pkg/storage/utils/decomposedfs/node/permissions_unix.go
|
<filename>pkg/storage/utils/decomposedfs/node/permissions_unix.go<gh_stars>100-1000
// Copyright 2018-2021 CERN
//
// 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.
//
// In applying this license, CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
//go:build !darwin
// +build !darwin
package node
import (
"syscall"
"github.com/pkg/xattr"
)
func isAttrUnset(err error) bool {
if xerr, ok := err.(*xattr.Error); ok {
if serr, ok2 := xerr.Err.(syscall.Errno); ok2 {
return serr == syscall.ENODATA
}
}
return false
}
|
francomamani/cealm-branch
|
public/scripts/services/product.js
|
<filename>public/scripts/services/product.js<gh_stars>0
app.factory('Product', ['$http', function ($http) {
return {
all: function () {
return $http.get('api/v1/auth/products');
},
getPage: function (new_page) {
return $http.get('api/v1/auth/products?page='+new_page);
},
store: function (product) {
var settings = {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
};
return $http.post('api/v1/auth/products', product, settings);
},
update: function (product) {
return $http.put('api/v1/auth/products/'+product.id, product);
},
delete: function (product) {
return $http.delete('api/v1/auth/products/'+product.id);
//return this.all();
},
search: function (value) {
return $http.post('api/v1/search/products', value);
}
};
}])
|
RonSherfey/data-act-broker-backend
|
dataactbroker/scripts/update_transaction_agency_codes.py
|
import logging
import argparse
from dataactcore.logging import configure_logging
from dataactcore.interfaces.db import GlobalDB
from dataactvalidator.health_check import create_app
logger = logging.getLogger(__name__)
def update_table(sess, agency_type, table, args):
""" Update the given table's agency codes. If provided, only update a specific sub tier code, otherwise update
any entry with a 999 in the agency code (awarding and funding separately).
Args:
sess: the database connection
agency_type: string indicating what agency type we're checking, either 'funding' or 'awarding'
table: string indicating which table to update, either 'detached_award_procurement' or
'published_award_financial_assistance'
args: object containing the arguments provided by the user
"""
# Setting the type of update we are running on the procurement table for logging purposes
update_type = {'level': 'cgac', 'codes': ['999']} if args.missing_agency \
else {'level': 'subtier', 'codes': args.subtier_codes}
logger.info('Updating ' + agency_type + ' ' + update_type['level'] + ' agency codes ' + str(update_type['codes'])
+ ' for ' + table + ' table')
# The name of the column depends on the type because of limited string length
suffix = 'o' if agency_type == "funding" else ''
row_count, condition_sql = set_update_condition(agency_type, table, suffix, sess, args.subtier_codes)
# updates table based off the parent of the sub_tier_agency code
sess.execute(
"""
UPDATE {table_name}
SET
{agency_type}_agency_code = agency.agency_code,
{agency_type}_agency_name = agency.agency_name
FROM (
SELECT sub.sub_tier_agency_code, sub.cgac_id, sub.frec_id, sub.is_frec,
CASE WHEN sub.is_frec
THEN (SELECT agency_name from frec WHERE frec.frec_id = sub.frec_id)
ELSE (SELECT agency_name from cgac where cgac.cgac_id = sub.cgac_id) END agency_name,
CASE WHEN sub.is_frec
THEN (SELECT frec_code from frec WHERE frec.frec_id = sub.frec_id)
ELSE (SELECT cgac_code from cgac where cgac.cgac_id = sub.cgac_id) END agency_code
FROM sub_tier_agency sub
INNER JOIN cgac ON cgac.cgac_id = sub.cgac_id
INNER JOIN frec ON frec.frec_id = sub.frec_id ) agency
WHERE {condition_sql}
AND {table_name}.{agency_type}_sub_tier_agency_c{suffix} = agency.sub_tier_agency_code;
""".format(table_name=table, agency_type=agency_type, condition_sql=condition_sql, suffix=suffix)
)
sess.commit()
final_row_count = 0 if args.subtier_codes else get_row_count(condition_sql, table, sess)
print_report(row_count, final_row_count, agency_type, True)
if args.missing_agency:
logger.info("{} agency code 999 remaining: {} rows ".format(agency_type.title(), final_row_count))
def set_update_condition(agency_type, table, suffix, sess, subtier_codes=None):
""" Changes the condition on which to update based on the type of update (999 vs subtier code).
Args:
agency_type: string indicating what agency type we're checking, either 'funding' or 'awarding'
table: string indicating which table to update, either 'detached_award_procurement' or
'published_award_financial_assistance'
suffix: string to add an 'o' to a column name if it's a funding agency
sess: the database connection
subtier_codes: the list of sub tier codes to update if provided, otherwise None
Returns:
The row count for the number of rows that match the query and "WHERE" condition created
"""
if subtier_codes and len(subtier_codes) == 1:
sql_statement = "{}.{}_sub_tier_agency_c{} = '{}' ".format(table, agency_type, suffix, str(subtier_codes[0]))
elif subtier_codes and len(subtier_codes) > 1:
subtiers_str = '({})'.format(','.join(['\'{}\''.format(subtier_code) for subtier_code in subtier_codes]))
sql_statement = "{}.{}_sub_tier_agency_c{} IN {}".format(table, agency_type, suffix, subtiers_str)
else:
sql_statement = "{}.{}_agency_code = '999' ".format(table, agency_type)
row_count = get_row_count(sql_statement, table, sess)
print_report(row_count, 0, agency_type)
return row_count, sql_statement
def get_row_count(sql_statement, table, sess):
""" Runs a SQL query to get the count of transaction rows based on the type of update. SQL Statement will either be
agency_code = '999' or sub_tier_agency_code = 'XXXX' for awarding and funding.
Args:
sql_statement: string containing the WHERE statement for the query
table: string indicating which table to count from, either 'detached_award_procurement' or
'published_award_financial_assistance'
sess: the database connection
Returns:
The count of how many rows in the provided table match the provided WHERE statement
"""
rows = sess.execute("SELECT COUNT(*) FROM " + table + " WHERE " + sql_statement + ";")
row_count = rows.fetchone()[0]
return row_count
def print_report(initial, final, agency_type, is_updated=False):
""" Logs row count before and after and update.
Args:
initial: The total number of rows before the updates
final: The number of rows remaining after the fix (0 if being logged before update)
agency_type: string indicating what agency type we're checking, either 'funding' or 'awarding'
is_updated: boolean indicating if this print is for before or after the update
"""
logger.info("{} codes {}: {} rows".format(agency_type.title(), 'updated' if is_updated else 'to update',
initial - final))
def main():
parser = argparse.ArgumentParser(description='Update contract transaction and/or fabs rows based on updates to the '
'agency list')
parser.add_argument('-a', '--missing_agency', help='Perform an update on 999 agency codes', action='store_true',
required=False, default=False)
parser.add_argument('-s', '--subtier_codes', help='Select specific subtiers to update. Must be a 4-digit code',
type=str, nargs='+', required=False)
parser.add_argument('-t', '--tables', help='Which tables (fabs, fpds, or both) to update. Defaults to both.',
required=False, default='both', choices=['fabs', 'fpds', 'both'])
args = parser.parse_args()
if not args.subtier_codes and not args.missing_agency:
logger.error('Missing either subtier_code or missing_agency argument')
return
if args.subtier_codes:
for subtier_code in args.subtier_codes:
if len(subtier_code) != 4:
logger.error('Subtier not a correct format, must be 4 digits')
return
sess = GlobalDB.db().session
if args.tables in ('fpds', 'both'):
update_table(sess, 'awarding', 'detached_award_procurement', args)
update_table(sess, 'funding', 'detached_award_procurement', args)
logger.info("Procurement Update Complete")
if args.tables in ('fabs', 'both'):
update_table(sess, 'awarding', 'published_award_financial_assistance', args)
update_table(sess, 'funding', 'published_award_financial_assistance', args)
logger.info("Award Financial Assistance Update Complete")
if __name__ == '__main__':
configure_logging()
with create_app().app_context():
main()
|
swinstonMirada/opencv
|
platforms/build_android_arm/src/org/opencv/objdetect/CascadeClassifier.java
|
<reponame>swinstonMirada/opencv
//
// This file is auto-generated. Please don't modify it!
//
package org.opencv.objdetect;
import java.lang.String;
import org.opencv.core.Mat;
import org.opencv.core.MatOfDouble;
import org.opencv.core.MatOfInt;
import org.opencv.core.MatOfRect;
import org.opencv.core.Size;
// C++: class CascadeClassifier
/**
* <p>Cascade classifier class for object detection.</p>
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier">org.opencv.objdetect.CascadeClassifier</a>
*/
public class CascadeClassifier {
protected final long nativeObj;
protected CascadeClassifier(long addr) { nativeObj = addr; }
//
// C++: CascadeClassifier()
//
/**
* <p>Loads a classifier from a file.</p>
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-cascadeclassifier">org.opencv.objdetect.CascadeClassifier.CascadeClassifier</a>
*/
public CascadeClassifier()
{
nativeObj = CascadeClassifier_0();
return;
}
//
// C++: CascadeClassifier(String filename)
//
/**
* <p>Loads a classifier from a file.</p>
*
* @param filename Name of the file from which the classifier is loaded.
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-cascadeclassifier">org.opencv.objdetect.CascadeClassifier.CascadeClassifier</a>
*/
public CascadeClassifier(String filename)
{
nativeObj = CascadeClassifier_1(filename);
return;
}
//
// C++: static bool convert(String oldcascade, String newcascade)
//
public static boolean convert(String oldcascade, String newcascade)
{
boolean retVal = convert_0(oldcascade, newcascade);
return retVal;
}
//
// C++: void detectMultiScale(Mat image, vector_Rect& objects, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size())
//
/**
* <p>Detects objects of different sizes in the input image. The detected objects
* are returned as a list of rectangles.</p>
*
* <p>The function is parallelized with the TBB library.</p>
*
* <p>Note:</p>
* <ul>
* <li> (Python) A face detection example using cascade classifiers can be
* found at opencv_source_code/samples/python2/facedetect.py
* </ul>
*
* @param image Matrix of the type <code>CV_8U</code> containing an image where
* objects are detected.
* @param objects Vector of rectangles where each rectangle contains the
* detected object, the rectangles may be partially outside the original image.
* @param scaleFactor Parameter specifying how much the image size is reduced at
* each image scale.
* @param minNeighbors Parameter specifying how many neighbors each candidate
* rectangle should have to retain it.
* @param flags Parameter with the same meaning for an old cascade as in the
* function <code>cvHaarDetectObjects</code>. It is not used for a new cascade.
* @param minSize Minimum possible object size. Objects smaller than that are
* ignored.
* @param maxSize Maximum possible object size. Objects larger than that are
* ignored.
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-detectmultiscale">org.opencv.objdetect.CascadeClassifier.detectMultiScale</a>
*/
public void detectMultiScale(Mat image, MatOfRect objects, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize)
{
Mat objects_mat = objects;
detectMultiScale_0(nativeObj, image.nativeObj, objects_mat.nativeObj, scaleFactor, minNeighbors, flags, minSize.width, minSize.height, maxSize.width, maxSize.height);
return;
}
/**
* <p>Detects objects of different sizes in the input image. The detected objects
* are returned as a list of rectangles.</p>
*
* <p>The function is parallelized with the TBB library.</p>
*
* <p>Note:</p>
* <ul>
* <li> (Python) A face detection example using cascade classifiers can be
* found at opencv_source_code/samples/python2/facedetect.py
* </ul>
*
* @param image Matrix of the type <code>CV_8U</code> containing an image where
* objects are detected.
* @param objects Vector of rectangles where each rectangle contains the
* detected object, the rectangles may be partially outside the original image.
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-detectmultiscale">org.opencv.objdetect.CascadeClassifier.detectMultiScale</a>
*/
public void detectMultiScale(Mat image, MatOfRect objects)
{
Mat objects_mat = objects;
detectMultiScale_1(nativeObj, image.nativeObj, objects_mat.nativeObj);
return;
}
//
// C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& numDetections, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size())
//
/**
* <p>Detects objects of different sizes in the input image. The detected objects
* are returned as a list of rectangles.</p>
*
* <p>The function is parallelized with the TBB library.</p>
*
* <p>Note:</p>
* <ul>
* <li> (Python) A face detection example using cascade classifiers can be
* found at opencv_source_code/samples/python2/facedetect.py
* </ul>
*
* @param image Matrix of the type <code>CV_8U</code> containing an image where
* objects are detected.
* @param objects Vector of rectangles where each rectangle contains the
* detected object, the rectangles may be partially outside the original image.
* @param numDetections Vector of detection numbers for the corresponding
* objects. An object's number of detections is the number of neighboring
* positively classified rectangles that were joined together to form the
* object.
* @param scaleFactor Parameter specifying how much the image size is reduced at
* each image scale.
* @param minNeighbors Parameter specifying how many neighbors each candidate
* rectangle should have to retain it.
* @param flags Parameter with the same meaning for an old cascade as in the
* function <code>cvHaarDetectObjects</code>. It is not used for a new cascade.
* @param minSize Minimum possible object size. Objects smaller than that are
* ignored.
* @param maxSize Maximum possible object size. Objects larger than that are
* ignored.
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-detectmultiscale">org.opencv.objdetect.CascadeClassifier.detectMultiScale</a>
*/
public void detectMultiScale2(Mat image, MatOfRect objects, MatOfInt numDetections, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize)
{
Mat objects_mat = objects;
Mat numDetections_mat = numDetections;
detectMultiScale2_0(nativeObj, image.nativeObj, objects_mat.nativeObj, numDetections_mat.nativeObj, scaleFactor, minNeighbors, flags, minSize.width, minSize.height, maxSize.width, maxSize.height);
return;
}
/**
* <p>Detects objects of different sizes in the input image. The detected objects
* are returned as a list of rectangles.</p>
*
* <p>The function is parallelized with the TBB library.</p>
*
* <p>Note:</p>
* <ul>
* <li> (Python) A face detection example using cascade classifiers can be
* found at opencv_source_code/samples/python2/facedetect.py
* </ul>
*
* @param image Matrix of the type <code>CV_8U</code> containing an image where
* objects are detected.
* @param objects Vector of rectangles where each rectangle contains the
* detected object, the rectangles may be partially outside the original image.
* @param numDetections Vector of detection numbers for the corresponding
* objects. An object's number of detections is the number of neighboring
* positively classified rectangles that were joined together to form the
* object.
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-detectmultiscale">org.opencv.objdetect.CascadeClassifier.detectMultiScale</a>
*/
public void detectMultiScale2(Mat image, MatOfRect objects, MatOfInt numDetections)
{
Mat objects_mat = objects;
Mat numDetections_mat = numDetections;
detectMultiScale2_1(nativeObj, image.nativeObj, objects_mat.nativeObj, numDetections_mat.nativeObj);
return;
}
//
// C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& rejectLevels, vector_double& levelWeights, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size(), bool outputRejectLevels = false)
//
/**
* <p>Detects objects of different sizes in the input image. The detected objects
* are returned as a list of rectangles.</p>
*
* <p>The function is parallelized with the TBB library.</p>
*
* <p>Note:</p>
* <ul>
* <li> (Python) A face detection example using cascade classifiers can be
* found at opencv_source_code/samples/python2/facedetect.py
* </ul>
*
* @param image Matrix of the type <code>CV_8U</code> containing an image where
* objects are detected.
* @param objects Vector of rectangles where each rectangle contains the
* detected object, the rectangles may be partially outside the original image.
* @param rejectLevels a rejectLevels
* @param levelWeights a levelWeights
* @param scaleFactor Parameter specifying how much the image size is reduced at
* each image scale.
* @param minNeighbors Parameter specifying how many neighbors each candidate
* rectangle should have to retain it.
* @param flags Parameter with the same meaning for an old cascade as in the
* function <code>cvHaarDetectObjects</code>. It is not used for a new cascade.
* @param minSize Minimum possible object size. Objects smaller than that are
* ignored.
* @param maxSize Maximum possible object size. Objects larger than that are
* ignored.
* @param outputRejectLevels Boolean. If <code>True</code>, it returns the
* rejectLevels and levelWeights. Default value is <code>False</code>.
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-detectmultiscale">org.opencv.objdetect.CascadeClassifier.detectMultiScale</a>
*/
public void detectMultiScale3(Mat image, MatOfRect objects, MatOfInt rejectLevels, MatOfDouble levelWeights, double scaleFactor, int minNeighbors, int flags, Size minSize, Size maxSize, boolean outputRejectLevels)
{
Mat objects_mat = objects;
Mat rejectLevels_mat = rejectLevels;
Mat levelWeights_mat = levelWeights;
detectMultiScale3_0(nativeObj, image.nativeObj, objects_mat.nativeObj, rejectLevels_mat.nativeObj, levelWeights_mat.nativeObj, scaleFactor, minNeighbors, flags, minSize.width, minSize.height, maxSize.width, maxSize.height, outputRejectLevels);
return;
}
/**
* <p>Detects objects of different sizes in the input image. The detected objects
* are returned as a list of rectangles.</p>
*
* <p>The function is parallelized with the TBB library.</p>
*
* <p>Note:</p>
* <ul>
* <li> (Python) A face detection example using cascade classifiers can be
* found at opencv_source_code/samples/python2/facedetect.py
* </ul>
*
* @param image Matrix of the type <code>CV_8U</code> containing an image where
* objects are detected.
* @param objects Vector of rectangles where each rectangle contains the
* detected object, the rectangles may be partially outside the original image.
* @param rejectLevels a rejectLevels
* @param levelWeights a levelWeights
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-detectmultiscale">org.opencv.objdetect.CascadeClassifier.detectMultiScale</a>
*/
public void detectMultiScale3(Mat image, MatOfRect objects, MatOfInt rejectLevels, MatOfDouble levelWeights)
{
Mat objects_mat = objects;
Mat rejectLevels_mat = rejectLevels;
Mat levelWeights_mat = levelWeights;
detectMultiScale3_1(nativeObj, image.nativeObj, objects_mat.nativeObj, rejectLevels_mat.nativeObj, levelWeights_mat.nativeObj);
return;
}
//
// C++: bool empty()
//
/**
* <p>Checks whether the classifier has been loaded.</p>
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-empty">org.opencv.objdetect.CascadeClassifier.empty</a>
*/
public boolean empty()
{
boolean retVal = empty_0(nativeObj);
return retVal;
}
//
// C++: int getFeatureType()
//
public int getFeatureType()
{
int retVal = getFeatureType_0(nativeObj);
return retVal;
}
//
// C++: Size getOriginalWindowSize()
//
public Size getOriginalWindowSize()
{
Size retVal = new Size(getOriginalWindowSize_0(nativeObj));
return retVal;
}
//
// C++: bool isOldFormatCascade()
//
public boolean isOldFormatCascade()
{
boolean retVal = isOldFormatCascade_0(nativeObj);
return retVal;
}
//
// C++: bool load(String filename)
//
/**
* <p>Loads a classifier from a file.</p>
*
* @param filename Name of the file from which the classifier is loaded. The
* file may contain an old HAAR classifier trained by the haartraining
* application or a new cascade classifier trained by the traincascade
* application.
*
* @see <a href="http://docs.opencv.org/modules/objdetect/doc/cascade_classification.html#cascadeclassifier-load">org.opencv.objdetect.CascadeClassifier.load</a>
*/
public boolean load(String filename)
{
boolean retVal = load_0(nativeObj, filename);
return retVal;
}
//
// C++: bool read(FileNode node)
//
// Unknown type 'FileNode' (I), skipping the function
@Override
protected void finalize() throws Throwable {
delete(nativeObj);
}
// C++: CascadeClassifier()
private static native long CascadeClassifier_0();
// C++: CascadeClassifier(String filename)
private static native long CascadeClassifier_1(String filename);
// C++: static bool convert(String oldcascade, String newcascade)
private static native boolean convert_0(String oldcascade, String newcascade);
// C++: void detectMultiScale(Mat image, vector_Rect& objects, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size())
private static native void detectMultiScale_0(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, double scaleFactor, int minNeighbors, int flags, double minSize_width, double minSize_height, double maxSize_width, double maxSize_height);
private static native void detectMultiScale_1(long nativeObj, long image_nativeObj, long objects_mat_nativeObj);
// C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& numDetections, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size())
private static native void detectMultiScale2_0(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long numDetections_mat_nativeObj, double scaleFactor, int minNeighbors, int flags, double minSize_width, double minSize_height, double maxSize_width, double maxSize_height);
private static native void detectMultiScale2_1(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long numDetections_mat_nativeObj);
// C++: void detectMultiScale(Mat image, vector_Rect& objects, vector_int& rejectLevels, vector_double& levelWeights, double scaleFactor = 1.1, int minNeighbors = 3, int flags = 0, Size minSize = Size(), Size maxSize = Size(), bool outputRejectLevels = false)
private static native void detectMultiScale3_0(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long rejectLevels_mat_nativeObj, long levelWeights_mat_nativeObj, double scaleFactor, int minNeighbors, int flags, double minSize_width, double minSize_height, double maxSize_width, double maxSize_height, boolean outputRejectLevels);
private static native void detectMultiScale3_1(long nativeObj, long image_nativeObj, long objects_mat_nativeObj, long rejectLevels_mat_nativeObj, long levelWeights_mat_nativeObj);
// C++: bool empty()
private static native boolean empty_0(long nativeObj);
// C++: int getFeatureType()
private static native int getFeatureType_0(long nativeObj);
// C++: Size getOriginalWindowSize()
private static native double[] getOriginalWindowSize_0(long nativeObj);
// C++: bool isOldFormatCascade()
private static native boolean isOldFormatCascade_0(long nativeObj);
// C++: bool load(String filename)
private static native boolean load_0(long nativeObj, String filename);
// native support for java finalize()
private static native void delete(long nativeObj);
}
|
Li-YangZhong/professional-javascript-for-web-developers
|
Chapter14TheDocumentObjectModel/HierarchyOfNodes/TheDocumentTypeType/TheDocumentTypeTypeExample01.js
|
<!DOCTYPE HTML PUBLIC "-// W3C// DTD HTML 4.01// EN"
"http:// www.w3.org/TR/html4/strict.dtd">
|
Dr-Horv/Advent-of-Code-2016
|
src/day22/StateExpander.java
|
package day22;
import utils.Position;
import utils.graph.Node;
import utils.graph.NodeExpander;
import java.util.ArrayList;
import java.util.List;
public class StateExpander implements NodeExpander<Node<State>> {
private StorageNode[][] storageNodes;
public StateExpander(List<StorageNode> ns) {
int maxY = 0;
int maxX = 0;
for (StorageNode n : ns) {
Position pos = n.getPosition();
if(pos.y > maxY) {
maxY = pos.y;
}
if(pos.x > maxX) {
maxX = pos.x;
}
}
storageNodes = new StorageNode[maxY+1][maxX+1];
for (StorageNode n : ns) {
Position pos = n.getPosition();
storageNodes[pos.y][pos.x] = new StorageNode(n);
}
}
private boolean validPair(StorageNode a, StorageNode b) {
if(a.getUsed() > 0) {
if (!a.equals(b)) {
return a.getUsed() <= b.getAvailable();
}
}
return false;
}
@Override
public List<Node<State>> getNeighbouringNodes(Node<State> n) {
ArrayList<Node<State>> list = new ArrayList<>();
State s = n.getElement();
/*
System.out.println("---STATE---");
prettyPrint(s);
System.out.println("--- --- ---");
*/
StorageNode emptyNode = s.getEmptyNode();
generateNeighbour(emptyNode.getPosition().add(new Position(0,1)), emptyNode, s, list);
generateNeighbour(emptyNode.getPosition().add(new Position(0,-1)), emptyNode, s, list);
generateNeighbour(emptyNode.getPosition().add(new Position(1,0)), emptyNode, s, list);
generateNeighbour(emptyNode.getPosition().add(new Position(-1,0)), emptyNode, s, list);
/*
System.out.println("--- NEIGHBOURS ---");
list.forEach(snnn -> prettyPrint(snnn.getElement()));
System.out.println("--- ---- ---");
*/
return list;
}
private void generateNeighbour(Position dpos, StorageNode emptyNode, State s, ArrayList<Node<State>> list) {
if(!validPos(dpos.y, dpos.x, storageNodes)) {
return;
}
StorageNode dNode = new StorageNode(storageNodes[dpos.y][dpos.x]);
if(dNode.getType() != StorageNode.Type.BLOCKED) {
StorageNode goalNode = new StorageNode(s.getStorageNodeWithGoalData());
if(goalNode.getPosition().equals(dNode.getPosition())) {
goalNode = new StorageNode(emptyNode);
goalNode.setType(StorageNode.Type.MOVABLE);
goalNode.setHasGoalData(true);
}
dNode.setType(StorageNode.Type.EMPTY);
State s2 = new State(dNode, goalNode);
list.add(new Node<>(s2));
}
}
private boolean validPos(int i, int j, StorageNode[][] storageNodes) {
boolean test = storageNodes.length > i && i >= 0 && storageNodes[i].length > j && j >= 0;
return test;
}
@Override
public int estimatedCost(Node<State> sn) {
StorageNode n = sn.getElement().getStorageNodeWithGoalData();
Position diff = new Position(0,0).subtract(n.getPosition());
return Math.abs(diff.x) + Math.abs(diff.y);
}
public void prettyPrint(State s) {
StorageNode goalNode = s.getStorageNodeWithGoalData();
StorageNode emptyNode = s.getEmptyNode();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < storageNodes.length; i++) {
sb.append("\n");
for (int j = 0; j < storageNodes[i].length; j++) {
StorageNode sn = storageNodes[i][j];
Position p = new Position(j,i);
if(goalNode.getPosition().equals(p)) {
sb.append("g");
continue;
} else if (emptyNode.getPosition().equals(p)) {
sb.append("_");
continue;
}
if(sn.getType() == StorageNode.Type.BLOCKED) {
sb.append("#");
} else if (sn.getType() == StorageNode.Type.MOVABLE) {
if(sn.hasGoalData()) {
sb.append("G");
} else {
sb.append(".");
}
} else {
sb.append("E");
}
}
}
System.out.println(sb.toString());
}
}
|
buddhimihara/component-dep
|
components/jaggery-apps/manage/src/main/manage/site/themes/default/templates/utils/dojo-release-1.8.3/dojox/gfx/Moveable.js
|
<reponame>buddhimihara/component-dep<filename>components/jaggery-apps/manage/src/main/manage/site/themes/default/templates/utils/dojo-release-1.8.3/dojox/gfx/Moveable.js
//>>built
define("dojox/gfx/Moveable",["dojo/_base/lang","dojo/_base/declare","dojo/_base/array","dojo/_base/event","dojo/topic","dojo/has","dojo/dom-class","dojo/_base/window","./Mover"],function(_1,_2,_3,_4,_5,_6,_7,_8,_9){
return _2("dojox.gfx.Moveable",null,{constructor:function(_a,_b){
this.shape=_a;
this.delay=(_b&&_b.delay>0)?_b.delay:0;
this.mover=(_b&&_b.mover)?_b.mover:_9;
this.events=[this.shape.connect(_6("touch")?"touchstart":"mousedown",this,"onMouseDown")];
},destroy:function(){
_3.forEach(this.events,this.shape.disconnect,this.shape);
this.events=this.shape=null;
},onMouseDown:function(e){
if(this.delay){
this.events.push(this.shape.connect(_6("touch")?"touchmove":"mousemove",this,"onMouseMove"),this.shape.connect(_6("touch")?"touchend":"mouseup",this,"onMouseUp"));
this._lastX=_6("touch")?(e.changedTouches?e.changedTouches[0]:e).clientX:e.clientX;
this._lastY=_6("touch")?(e.changedTouches?e.changedTouches[0]:e).clientY:e.clientY;
}else{
new this.mover(this.shape,e,this);
}
_4.stop(e);
},onMouseMove:function(e){
var _c=_6("touch")?(e.changedTouches?e.changedTouches[0]:e).clientX:e.clientX,_d=_6("touch")?(e.changedTouches?e.changedTouches[0]:e).clientY:e.clientY;
if(Math.abs(_c-this._lastX)>this.delay||Math.abs(_d-this._lastY)>this.delay){
this.onMouseUp(e);
new this.mover(this.shape,e,this);
}
_4.stop(e);
},onMouseUp:function(e){
this.shape.disconnect(this.events.pop());
},onMoveStart:function(_e){
_5.publish("/gfx/move/start",_e);
_7.add(_8.body(),"dojoMove");
},onMoveStop:function(_f){
_5.publish("/gfx/move/stop",_f);
_7.remove(_8.body(),"dojoMove");
},onFirstMove:function(_10){
},onMove:function(_11,_12){
this.onMoving(_11,_12);
this.shape.applyLeftTransform(_12);
this.onMoved(_11,_12);
},onMoving:function(_13,_14){
},onMoved:function(_15,_16){
}});
});
|
ritcat14/TheMysteriousMindOfJack
|
src/main/java/entities/items/armour/Head.java
|
<filename>src/main/java/entities/items/armour/Head.java
package entities.items.armour;
import entities.Player;
import entities.items.Item;
import handler.Vector;
public class Head extends Item {
public Head(Vector pos) {
super(pos, 1);
}
@Override
public void onEvent(Player player) {
player.addHead(image);
player.adjustSheild(40);
remove();
}
}
|
patil215/v8
|
src/objects/js-generator.h
|
<gh_stars>1-10
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_OBJECTS_JS_GENERATOR_H_
#define V8_OBJECTS_JS_GENERATOR_H_
#include "src/objects/js-objects.h"
#include "src/objects/struct.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
// Forward declarations.
class JSPromise;
class JSGeneratorObject : public JSObject {
public:
// [function]: The function corresponding to this generator object.
DECL_ACCESSORS(function, JSFunction)
// [context]: The context of the suspended computation.
DECL_ACCESSORS(context, Context)
// [receiver]: The receiver of the suspended computation.
DECL_ACCESSORS(receiver, Object)
// [input_or_debug_pos]
// For executing generators: the most recent input value.
// For suspended generators: debug information (bytecode offset).
// There is currently no need to remember the most recent input value for a
// suspended generator.
DECL_ACCESSORS(input_or_debug_pos, Object)
// [resume_mode]: The most recent resume mode.
enum ResumeMode { kNext, kReturn, kThrow };
DECL_INT_ACCESSORS(resume_mode)
// [continuation]
//
// A positive value indicates a suspended generator. The special
// kGeneratorExecuting and kGeneratorClosed values indicate that a generator
// cannot be resumed.
inline int continuation() const;
inline void set_continuation(int continuation);
inline bool is_closed() const;
inline bool is_executing() const;
inline bool is_suspended() const;
// For suspended generators: the source position at which the generator
// is suspended.
int source_position() const;
// [parameters_and_registers]: Saved interpreter register file.
DECL_ACCESSORS(parameters_and_registers, FixedArray)
DECL_CAST(JSGeneratorObject)
// Dispatched behavior.
DECL_PRINTER(JSGeneratorObject)
DECL_VERIFIER(JSGeneratorObject)
// Magic sentinel values for the continuation.
static const int kGeneratorExecuting = -2;
static const int kGeneratorClosed = -1;
// Layout description.
#define JS_GENERATOR_FIELDS(V) \
V(kFunctionOffset, kTaggedSize) \
V(kContextOffset, kTaggedSize) \
V(kReceiverOffset, kTaggedSize) \
V(kInputOrDebugPosOffset, kTaggedSize) \
V(kResumeModeOffset, kTaggedSize) \
V(kContinuationOffset, kTaggedSize) \
V(kParametersAndRegistersOffset, kTaggedSize) \
/* Header size. */ \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(JSObject::kHeaderSize, JS_GENERATOR_FIELDS)
#undef JS_GENERATOR_FIELDS
OBJECT_CONSTRUCTORS(JSGeneratorObject, JSObject);
};
class JSAsyncFunctionObject : public JSGeneratorObject {
public:
DECL_CAST(JSAsyncFunctionObject)
// Dispatched behavior.
DECL_VERIFIER(JSAsyncFunctionObject)
// [promise]: The promise of the async function.
DECL_ACCESSORS(promise, JSPromise)
// Layout description.
#define JS_ASYNC_FUNCTION_FIELDS(V) \
V(kPromiseOffset, kTaggedSize) \
/* Header size. */ \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(JSGeneratorObject::kSize,
JS_ASYNC_FUNCTION_FIELDS)
#undef JS_ASYNC_FUNCTION_FIELDS
OBJECT_CONSTRUCTORS(JSAsyncFunctionObject, JSGeneratorObject);
};
class JSAsyncGeneratorObject : public JSGeneratorObject {
public:
DECL_CAST(JSAsyncGeneratorObject)
// Dispatched behavior.
DECL_VERIFIER(JSAsyncGeneratorObject)
// [queue]
// Pointer to the head of a singly linked list of AsyncGeneratorRequest, or
// undefined.
DECL_ACCESSORS(queue, HeapObject)
// [is_awaiting]
// Whether or not the generator is currently awaiting.
DECL_INT_ACCESSORS(is_awaiting)
// Layout description.
#define JS_ASYNC_GENERATOR_FIELDS(V) \
V(kQueueOffset, kTaggedSize) \
V(kIsAwaitingOffset, kTaggedSize) \
/* Header size. */ \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(JSGeneratorObject::kSize,
JS_ASYNC_GENERATOR_FIELDS)
#undef JS_ASYNC_GENERATOR_FIELDS
OBJECT_CONSTRUCTORS(JSAsyncGeneratorObject, JSGeneratorObject);
};
class AsyncGeneratorRequest : public Struct {
public:
// Holds an AsyncGeneratorRequest, or Undefined.
DECL_ACCESSORS(next, Object)
DECL_INT_ACCESSORS(resume_mode)
DECL_ACCESSORS(value, Object)
DECL_ACCESSORS(promise, Object)
// Layout description.
#define ASYNC_GENERATOR_REQUEST_FIELDS(V) \
V(kNextOffset, kTaggedSize) \
V(kResumeModeOffset, kTaggedSize) \
V(kValueOffset, kTaggedSize) \
V(kPromiseOffset, kTaggedSize) \
/* Total size. */ \
V(kSize, 0)
DEFINE_FIELD_OFFSET_CONSTANTS(Struct::kHeaderSize,
ASYNC_GENERATOR_REQUEST_FIELDS)
#undef ASYNC_GENERATOR_REQUEST_FIELDS
DECL_CAST(AsyncGeneratorRequest)
DECL_PRINTER(AsyncGeneratorRequest)
DECL_VERIFIER(AsyncGeneratorRequest)
OBJECT_CONSTRUCTORS(AsyncGeneratorRequest, Struct);
};
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_JS_GENERATOR_H_
|
boschman32/Crime-Engine
|
CrimeEngine/include/Gameplay/Map/MapEvent.h
|
#pragma once
#include <sstream>
#include "Events/EventService.h"
#include "LevelMap.h"
namespace ce
{
class MapLoadedEvent : public IEvent
{
public:
MapLoadedEvent(LevelMap* a_loadedMap)
: m_loadedMap(a_loadedMap) { }
LevelMap& GetLoadedMap() const { return *m_loadedMap; }
std::string ToString() const override
{
std::stringstream ss;
ss << "[Map loaded event]: (" << m_loadedMap->GetFileName() << " )";
return ss.str();
}
EVENT_CLASS_TYPE(EventType, MapLoaded);
EVENT_CLASS_CATEGORY(EventCategory::EventCategoryMap);
private:
LevelMap* m_loadedMap;
};
class MapBuiltEvent : public IEvent
{
public:
MapBuiltEvent(LevelMap* a_builtMap)
: m_builtMap(a_builtMap) { }
LevelMap& GetBuiltMap() const { return *m_builtMap; }
std::string ToString() const override
{
std::stringstream ss;
ss << "[Map built event]: (" << m_builtMap->GetFileName() << " )";
return ss.str();
}
EVENT_CLASS_TYPE(EventType, MapBuilt);
EVENT_CLASS_CATEGORY(EventCategory::EventCategoryMap);
private:
LevelMap* m_builtMap;
};
}
|
pradeepkumarcm-egov/DIGIT-Dev
|
edcr/service/egov/egov-edcr-extract/src/main/java/org/egov/edcr/utility/math/Rectangle.java
|
<filename>edcr/service/egov/egov-edcr-extract/src/main/java/org/egov/edcr/utility/math/Rectangle.java
package org.egov.edcr.utility.math;
public class Rectangle {
double x = Double.MAX_VALUE;
double y = Double.MAX_VALUE;
double d = Double.MIN_VALUE;
double e = Double.MIN_VALUE;
public Rectangle(double minX2, double minY2, double d, double e) {
x = minX2;
y = minY2;
this.d = d;
this.e = e;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getD() {
return d;
}
public void setD(double d) {
this.d = d;
}
public double getE() {
return e;
}
public void setE(double e) {
this.e = e;
}
}
|
PetaVision/ObsoletePV
|
weightinit/InitSubUnitWeights.hpp
|
<filename>weightinit/InitSubUnitWeights.hpp
/*
* InitSubUnitWeights.hpp
*
* Created on: Aug 14, 2011
* Author: kpeterson
*/
#ifndef INITSUBUNITWEIGHTS_HPP_
#define INITSUBUNITWEIGHTS_HPP_
#include "InitWeights.hpp"
namespace PV {
class InitWeightsParams;
class InitSubUnitWeightsParams;
class InitSubUnitWeights: public PV::InitWeights {
public:
InitSubUnitWeights(HyPerConn * conn);
virtual ~InitSubUnitWeights();
virtual int calcWeights(/* PVPatch * patch */ pvdata_t * dataStart, int patchIndex, int arborId);
virtual InitWeightsParams * createNewWeightParams();
// void calcOtherParams(PVPatch * patch, int patchIndex);
protected:
InitSubUnitWeights();
int initialize(HyPerConn * conn);
private:
int initialize_base();
int subUnitWeights(/* PVPatch * patch */ pvdata_t * dataStart, InitSubUnitWeightsParams * weightParamPtr);
};
} /* namespace PV */
#endif /* INITSUBUNITWEIGHTS_HPP_ */
|
HeRaNO/OI-ICPC-Codes
|
Codeforces/1269B.cpp
|
<reponame>HeRaNO/OI-ICPC-Codes
#include <bits/stdc++.h>
#define MAXN 2005
using namespace std;
int n,m,x,a[MAXN];
set <int> s;
vector <int> b,c;
int main()
{
scanf("%d %d",&n,&m);
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
for (int i=1;i<=n;i++)
{
scanf("%d",&x);
b.push_back(x);
}
sort(b.begin(),b.end());
for (int j=0;j<n;j++) s.insert((b[j]-a[1]+m)%m);
for (auto pp:s)
{
c.clear();
for (int i=1;i<=n;i++) c.push_back((a[i]+pp)%m);
sort(c.begin(),c.end());
if (b==c) return printf("%d\n",pp),0;
}
return 0;
}
|
TheFrainD/soge
|
docs/html/search/classes_5.js
|
<reponame>TheFrainD/soge
var searchData=
[
['texture_0',['texture',['../structtexture.html',1,'']]],
['transform_1',['transform',['../structtransform.html',1,'']]]
];
|
isabella232/aistreams
|
third_party/gst-plugins-bad/ext/lv2/gstlv2utils.c
|
<filename>third_party/gst-plugins-bad/ext/lv2/gstlv2utils.c
/* GStreamer
* Copyright (C) 2016 <NAME> <<EMAIL>>
* 2016 <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "string.h"
#include "stdlib.h"
#include "gstlv2.h"
#include "gstlv2utils.h"
#include "lv2/lv2plug.in/ns/ext/atom/atom.h"
#include "lv2/lv2plug.in/ns/ext/atom/forge.h"
#include <lv2/lv2plug.in/ns/ext/log/log.h>
#include <lv2/lv2plug.in/ns/ext/state/state.h>
#include <lv2/lv2plug.in/ns/ext/urid/urid.h>
GST_DEBUG_CATEGORY_EXTERN (lv2_debug);
#define GST_CAT_DEFAULT lv2_debug
/* host features */
/* - log extension */
static int
lv2_log_printf (LV2_Log_Handle handle, LV2_URID type, const char *fmt, ...)
{
va_list ap;
va_start (ap, fmt);
gst_debug_log_valist (lv2_debug, GST_LEVEL_INFO, "", "", 0, NULL, fmt, ap);
va_end (ap);
return 1;
}
static int
lv2_log_vprintf (LV2_Log_Handle handle, LV2_URID type,
const char *fmt, va_list ap)
{
gst_debug_log_valist (lv2_debug, GST_LEVEL_INFO, "", "", 0, NULL, fmt, ap);
return 1;
}
static LV2_Log_Log lv2_log = {
/* handle = */ NULL, lv2_log_printf, lv2_log_vprintf
};
static const LV2_Feature lv2_log_feature = { LV2_LOG__log, &lv2_log };
/* - urid map/unmap extension */
static LV2_URID
lv2_urid_map (LV2_URID_Map_Handle handle, const char *uri)
{
return (LV2_URID) g_quark_from_string (uri);
}
static const char *
lv2_urid_unmap (LV2_URID_Unmap_Handle handle, LV2_URID urid)
{
return g_quark_to_string ((GQuark) urid);
}
static LV2_URID_Map lv2_map = {
/* handle = */ NULL, lv2_urid_map
};
static LV2_URID_Unmap lv2_unmap = {
/* handle = */ NULL, lv2_urid_unmap
};
static const LV2_Feature lv2_map_feature = { LV2_URID__map, &lv2_map };
static const LV2_Feature lv2_unmap_feature = { LV2_URID__unmap, &lv2_unmap };
/* feature list */
static const LV2_Feature *lv2_features[] = {
&lv2_log_feature,
&lv2_map_feature,
&lv2_unmap_feature,
NULL
};
gboolean
gst_lv2_check_required_features (const LilvPlugin * lv2plugin)
{
LilvNodes *required_features = lilv_plugin_get_required_features (lv2plugin);
if (required_features) {
LilvIter *i;
gint j;
gboolean missing = FALSE;
for (i = lilv_nodes_begin (required_features);
!lilv_nodes_is_end (required_features, i);
i = lilv_nodes_next (required_features, i)) {
const LilvNode *required_feature = lilv_nodes_get (required_features, i);
const char *required_feature_uri = lilv_node_as_uri (required_feature);
missing = TRUE;
for (j = 0; lv2_features[j]; j++) {
if (!strcmp (lv2_features[j]->URI, required_feature_uri)) {
missing = FALSE;
break;
}
}
if (missing) {
GST_FIXME ("lv2 plugin %s needs host feature: %s",
lilv_node_as_uri (lilv_plugin_get_uri (lv2plugin)),
required_feature_uri);
break;
}
}
lilv_nodes_free (required_features);
return (!missing);
}
return TRUE;
}
static LV2_Atom_Forge forge;
void
gst_lv2_host_init (void)
{
lv2_atom_forge_init (&forge, &lv2_map);
}
/* preset interface */
static char *
make_bundle_name (GstObject * obj, const gchar * name)
{
GstElementFactory *factory;
gchar *basename, *s, *bundle;
factory = gst_element_get_factory ((GstElement *) obj);
basename = g_strdup (gst_element_factory_get_metadata (factory,
GST_ELEMENT_METADATA_LONGNAME));
s = basename;
while ((s = strchr (s, ' '))) {
*s = '_';
}
bundle = g_strjoin (NULL, basename, "_", name, ".preset.lv2", NULL);
g_free (basename);
return bundle;
}
gchar **
gst_lv2_get_preset_names (GstLV2 * lv2, GstObject * obj)
{
/* lazily scan for presets when first called */
if (!lv2->presets) {
LilvNodes *presets;
if ((presets = lilv_plugin_get_related (lv2->klass->plugin, preset_class))) {
LilvIter *j;
lv2->presets = g_hash_table_new_full (g_str_hash, g_str_equal, g_free,
(GDestroyNotify) lilv_node_free);
for (j = lilv_nodes_begin (presets);
!lilv_nodes_is_end (presets, j); j = lilv_nodes_next (presets, j)) {
const LilvNode *preset = lilv_nodes_get (presets, j);
LilvNodes *titles;
lilv_world_load_resource (world, preset);
titles = lilv_world_find_nodes (world, preset, label_pred, NULL);
if (titles) {
const LilvNode *title = lilv_nodes_get_first (titles);
g_hash_table_insert (lv2->presets,
g_strdup (lilv_node_as_string (title)),
lilv_node_duplicate (preset));
lilv_nodes_free (titles);
} else {
GST_WARNING_OBJECT (obj, "plugin has preset '%s' without rdfs:label",
lilv_node_as_string (preset));
}
}
lilv_nodes_free (presets);
}
}
if (lv2->presets) {
GList *node, *keys = g_hash_table_get_keys (lv2->presets);
gchar **names = g_new0 (gchar *, g_hash_table_size (lv2->presets) + 1);
gint i = 0;
for (node = keys; node; node = g_list_next (node)) {
names[i++] = g_strdup (node->data);
}
g_list_free (keys);
return names;
}
return NULL;
}
static void
set_port_value (const char *port_symbol, void *data, const void *value,
uint32_t size, uint32_t type)
{
gpointer *user_data = (gpointer *) data;
GstLV2Class *klass = user_data[0];
GstObject *obj = user_data[1];
gchar *prop_name = g_hash_table_lookup (klass->sym_to_name, port_symbol);
gfloat fvalue;
if (!prop_name) {
GST_WARNING_OBJECT (obj, "Preset port '%s' is missing", port_symbol);
return;
}
if (type == forge.Float) {
fvalue = *(const gfloat *) value;
} else if (type == forge.Double) {
fvalue = *(const gdouble *) value;
} else if (type == forge.Int) {
fvalue = *(const gint32 *) value;
} else if (type == forge.Long) {
fvalue = *(const gint64 *) value;
} else {
GST_WARNING_OBJECT (obj, "Preset '%s' value has bad type '%s'",
port_symbol, lv2_unmap.unmap (lv2_unmap.handle, type));
return;
}
g_object_set (obj, prop_name, fvalue, NULL);
}
gboolean
gst_lv2_load_preset (GstLV2 * lv2, GstObject * obj, const gchar * name)
{
LilvNode *preset = g_hash_table_lookup (lv2->presets, name);
LilvState *state = lilv_state_new_from_world (world, &lv2_map, preset);
gpointer user_data[] = { lv2->klass, obj };
GST_INFO_OBJECT (obj, "loading preset <%s>", lilv_node_as_string (preset));
lilv_state_restore (state, lv2->instance, set_port_value,
(gpointer) user_data, 0, NULL);
lilv_state_free (state);
return FALSE;
}
static const void *
get_port_value (const char *port_symbol, void *data, uint32_t * size,
uint32_t * type)
{
gpointer *user_data = (gpointer *) data;
GstLV2Class *klass = user_data[0];
GstObject *obj = user_data[1];
gchar *prop_name = g_hash_table_lookup (klass->sym_to_name, port_symbol);
static gfloat fvalue;
if (!prop_name) {
GST_WARNING_OBJECT (obj, "Preset port '%s' is missing", port_symbol);
*size = *type = 0;
return NULL;
}
*size = sizeof (float);
*type = forge.Float;
g_object_get (obj, prop_name, &fvalue, NULL);
/* FIXME: can we return &lv2->ports.{in,out}[x]; */
return &fvalue;
}
gboolean
gst_lv2_save_preset (GstLV2 * lv2, GstObject * obj, const gchar * name)
{
gchar *filename, *bundle, *dir, *tmp_dir;
gpointer user_data[] = { lv2->klass, obj };
LilvState *state;
LilvNode *bundle_dir;
const LilvNode *state_uri;
LilvInstance *instance = lv2->instance;
gboolean res;
#ifndef HAVE_LILV_0_22
gchar *filepath;
#endif
filename = g_strjoin (NULL, name, ".ttl", NULL);
bundle = make_bundle_name (obj, name);
/* dir needs to end on a dir separator for the lilv_new_file_uri() to work */
dir =
g_build_filename (g_get_home_dir (), ".lv2", bundle, G_DIR_SEPARATOR_S,
NULL);
tmp_dir = g_dir_make_tmp ("gstlv2-XXXXXX", NULL);
g_mkdir_with_parents (dir, 0750);
if (!instance) {
/* instance is NULL until we play!! */
instance = lilv_plugin_instantiate (lv2->klass->plugin, GST_AUDIO_DEF_RATE,
lv2_features);
}
state = lilv_state_new_from_instance (lv2->klass->plugin, instance, &lv2_map,
tmp_dir, dir, dir, dir, get_port_value, user_data,
LV2_STATE_IS_POD | LV2_STATE_IS_PORTABLE, NULL);
lilv_state_set_label (state, name);
res = lilv_state_save (world, &lv2_map, &lv2_unmap, state, /*uri */ NULL, dir,
filename) != 0;
/* reload bundle into the world */
bundle_dir = lilv_new_file_uri (world, NULL, dir);
lilv_world_unload_bundle (world, bundle_dir);
lilv_world_load_bundle (world, bundle_dir);
lilv_node_free (bundle_dir);
#ifdef HAVE_LILV_0_22
state_uri = lilv_state_get_uri (state);
#else
filepath = g_build_filename (dir, filename, NULL);
state_uri = lilv_new_uri (world, filepath);
g_free (filepath);
#endif
lilv_world_load_resource (world, state_uri);
g_hash_table_insert (lv2->presets, g_strdup (name),
lilv_node_duplicate (state_uri));
#ifndef HAVE_LILV_0_22
lilv_node_free ((LilvNode *) state_uri);
#endif
lilv_state_free (state);
if (!lv2->instance) {
lilv_instance_free (instance);
}
g_free (tmp_dir);
g_free (dir);
g_free (bundle);
g_free (filename);
return res;
}
#if 0
gboolean
gst_lv2_rename_preset (GstLV2 * lv2, GstObject * obj,
const gchar * old_name, const gchar * new_name)
{
/* need to relabel the preset */
return FALSE;
}
#endif
gboolean
gst_lv2_delete_preset (GstLV2 * lv2, GstObject * obj, const gchar * name)
{
#ifdef HAVE_LILV_0_22
LilvNode *preset = g_hash_table_lookup (lv2->presets, name);
LilvState *state = lilv_state_new_from_world (world, &lv2_map, preset);
lilv_world_unload_resource (world, lilv_state_get_uri (state));
lilv_state_delete (world, state);
lilv_state_free (state);
#endif
g_hash_table_remove (lv2->presets, name);
return FALSE;
}
/* api helpers */
void
gst_lv2_init (GstLV2 * lv2, GstLV2Class * lv2_class)
{
lv2->klass = lv2_class;
lv2->instance = NULL;
lv2->activated = FALSE;
lv2->ports.control.in = g_new0 (gfloat, lv2_class->control_in_ports->len);
lv2->ports.control.out = g_new0 (gfloat, lv2_class->control_out_ports->len);
}
void
gst_lv2_finalize (GstLV2 * lv2)
{
if (lv2->presets) {
g_hash_table_destroy (lv2->presets);
}
g_free (lv2->ports.control.in);
g_free (lv2->ports.control.out);
}
gboolean
gst_lv2_setup (GstLV2 * lv2, unsigned long rate)
{
GstLV2Class *lv2_class = lv2->klass;
GstLV2Port *port;
GArray *ports;
gint i;
if (lv2->instance)
lilv_instance_free (lv2->instance);
if (!(lv2->instance =
lilv_plugin_instantiate (lv2_class->plugin, rate, lv2_features)))
return FALSE;
/* connect the control ports */
ports = lv2_class->control_in_ports;
for (i = 0; i < ports->len; i++) {
port = &g_array_index (ports, GstLV2Port, i);
if (port->type != GST_LV2_PORT_CONTROL)
continue;
lilv_instance_connect_port (lv2->instance, port->index,
&(lv2->ports.control.in[i]));
}
ports = lv2_class->control_out_ports;
for (i = 0; i < ports->len; i++) {
port = &g_array_index (ports, GstLV2Port, i);
if (port->type != GST_LV2_PORT_CONTROL)
continue;
lilv_instance_connect_port (lv2->instance, port->index,
&(lv2->ports.control.out[i]));
}
lilv_instance_activate (lv2->instance);
lv2->activated = TRUE;
return TRUE;
}
gboolean
gst_lv2_cleanup (GstLV2 * lv2, GstObject * obj)
{
if (lv2->activated == FALSE) {
GST_ERROR_OBJECT (obj, "Deactivating but LV2 plugin not activated");
return TRUE;
}
if (lv2->instance == NULL) {
GST_ERROR_OBJECT (obj, "Deactivating but no LV2 plugin set");
return TRUE;
}
GST_DEBUG_OBJECT (obj, "deactivating");
lilv_instance_deactivate (lv2->instance);
lv2->activated = FALSE;
lilv_instance_free (lv2->instance);
lv2->instance = NULL;
return TRUE;
}
void
gst_lv2_object_set_property (GstLV2 * lv2, GObject * object,
guint prop_id, const GValue * value, GParamSpec * pspec)
{
GType base, type = pspec->value_type;
/* remember, properties have an offset */
prop_id -= lv2->klass->properties;
/* only input ports */
g_return_if_fail (prop_id < lv2->klass->control_in_ports->len);
while ((base = g_type_parent (type)))
type = base;
/* now see what type it is */
switch (type) {
case G_TYPE_BOOLEAN:
lv2->ports.control.in[prop_id] =
g_value_get_boolean (value) ? 1.0f : 0.0f;
break;
case G_TYPE_INT:
lv2->ports.control.in[prop_id] = g_value_get_int (value);
break;
case G_TYPE_FLOAT:
lv2->ports.control.in[prop_id] = g_value_get_float (value);
break;
case G_TYPE_ENUM:
lv2->ports.control.in[prop_id] = g_value_get_enum (value);
break;
default:
GST_WARNING_OBJECT (object, "unhandled type: %s",
g_type_name (pspec->value_type));
g_assert_not_reached ();
}
}
void
gst_lv2_object_get_property (GstLV2 * lv2, GObject * object,
guint prop_id, GValue * value, GParamSpec * pspec)
{
GType base, type = pspec->value_type;
gfloat *controls;
/* remember, properties have an offset */
prop_id -= lv2->klass->properties;
if (prop_id < lv2->klass->control_in_ports->len) {
controls = lv2->ports.control.in;
} else if (prop_id < lv2->klass->control_in_ports->len +
lv2->klass->control_out_ports->len) {
controls = lv2->ports.control.out;
prop_id -= lv2->klass->control_in_ports->len;
} else {
g_return_if_reached ();
}
while ((base = g_type_parent (type)))
type = base;
/* now see what type it is */
switch (type) {
case G_TYPE_BOOLEAN:
g_value_set_boolean (value, controls[prop_id] > 0.0f);
break;
case G_TYPE_INT:
g_value_set_int (value, CLAMP (controls[prop_id], G_MININT, G_MAXINT));
break;
case G_TYPE_FLOAT:
g_value_set_float (value, controls[prop_id]);
break;
case G_TYPE_ENUM:
g_value_set_enum (value, (gint) controls[prop_id]);
break;
default:
GST_WARNING_OBJECT (object, "unhandled type: %s",
g_type_name (pspec->value_type));
g_return_if_reached ();
}
}
static gchar *
gst_lv2_class_get_param_name (GstLV2Class * klass, GObjectClass * object_class,
const gchar * port_symbol)
{
gchar *ret = g_strdup (port_symbol);
/* this is the same thing that param_spec_* will do */
g_strcanon (ret, G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "-", '-');
/* satisfy glib2 (argname[0] must be [A-Za-z]) */
if (!((ret[0] >= 'a' && ret[0] <= 'z') || (ret[0] >= 'A' && ret[0] <= 'Z'))) {
gchar *tempstr = ret;
ret = g_strconcat ("param-", ret, NULL);
g_free (tempstr);
}
/* check for duplicate property names */
if (g_object_class_find_property (object_class, ret)) {
gint n = 1;
gchar *nret = g_strdup_printf ("%s-%d", ret, n++);
while (g_object_class_find_property (object_class, nret)) {
g_free (nret);
nret = g_strdup_printf ("%s-%d", ret, n++);
}
g_free (ret);
ret = nret;
}
GST_DEBUG ("built property name '%s' from port name '%s'", ret, port_symbol);
return ret;
}
static gchar *
gst_lv2_class_get_param_nick (GstLV2Class * klass, const LilvPort * port)
{
const LilvPlugin *lv2plugin = klass->plugin;
return g_strdup (lilv_node_as_string (lilv_port_get_name (lv2plugin, port)));
}
static int
enum_val_cmp (GEnumValue * p1, GEnumValue * p2)
{
return p1->value - p2->value;
}
static GParamSpec *
gst_lv2_class_get_param_spec (GstLV2Class * klass, GObjectClass * object_class,
gint portnum)
{
const LilvPlugin *lv2plugin = klass->plugin;
const LilvPort *port = lilv_plugin_get_port_by_index (lv2plugin, portnum);
LilvNode *lv2def, *lv2min, *lv2max;
LilvScalePoints *points;
GParamSpec *ret;
gchar *name, *nick;
gint perms;
gfloat lower = 0.0f, upper = 1.0f, def = 0.0f;
GType enum_type = G_TYPE_INVALID;
const gchar *port_symbol =
lilv_node_as_string (lilv_port_get_symbol (lv2plugin, port));
nick = gst_lv2_class_get_param_nick (klass, port);
name = gst_lv2_class_get_param_name (klass, object_class, port_symbol);
GST_DEBUG ("%s trying port %s : %s",
lilv_node_as_string (lilv_plugin_get_uri (lv2plugin)), name, nick);
perms = G_PARAM_READABLE;
if (lilv_port_is_a (lv2plugin, port, input_class))
perms |= G_PARAM_WRITABLE | G_PARAM_CONSTRUCT;
if (lilv_port_is_a (lv2plugin, port, control_class) ||
lilv_port_is_a (lv2plugin, port, cv_class))
perms |= GST_PARAM_CONTROLLABLE;
if (lilv_port_has_property (lv2plugin, port, toggled_prop)) {
ret = g_param_spec_boolean (name, nick, nick, FALSE, perms);
goto done;
}
lilv_port_get_range (lv2plugin, port, &lv2def, &lv2min, &lv2max);
if (lv2def)
def = lilv_node_as_float (lv2def);
if (lv2min)
lower = lilv_node_as_float (lv2min);
if (lv2max)
upper = lilv_node_as_float (lv2max);
lilv_node_free (lv2def);
lilv_node_free (lv2min);
lilv_node_free (lv2max);
if (def < lower) {
if (lv2def && lv2min) {
GST_WARNING ("%s:%s has lower bound %f > default %f",
lilv_node_as_string (lilv_plugin_get_uri (lv2plugin)), name, lower,
def);
}
lower = def;
}
if (def > upper) {
if (lv2def && lv2max) {
GST_WARNING ("%s:%s has upper bound %f < default %f",
lilv_node_as_string (lilv_plugin_get_uri (lv2plugin)), name, upper,
def);
}
upper = def;
}
if ((points = lilv_port_get_scale_points (lv2plugin, port))) {
GEnumValue *enums;
LilvIter *i;
gint j = 0, n, def_ix = -1;
n = lilv_scale_points_size (points);
enums = g_new (GEnumValue, n + 1);
for (i = lilv_scale_points_begin (points);
!lilv_scale_points_is_end (points, i);
i = lilv_scale_points_next (points, i)) {
const LilvScalePoint *point = lilv_scale_points_get (points, i);
gfloat v = lilv_node_as_float (lilv_scale_point_get_value (point));
const gchar *l = lilv_node_as_string (lilv_scale_point_get_label (point));
/* check if value can be safely converted to int */
if (v != (gint) v) {
GST_INFO ("%s:%s non integer scale point %lf, %s",
lilv_node_as_string (lilv_plugin_get_uri (lv2plugin)), name, v, l);
break;
}
if (v == def) {
def_ix = j;
}
enums[j].value = (gint) v;
enums[j].value_nick = enums[j].value_name = l;
GST_LOG ("%s:%s enum: %lf, %s",
lilv_node_as_string (lilv_plugin_get_uri (lv2plugin)), name, v, l);
j++;
}
if (j == n) {
gchar *type_name;
/* scalepoints are not sorted */
qsort (enums, n, sizeof (GEnumValue),
(int (*)(const void *, const void *)) enum_val_cmp);
if (def_ix == -1) {
if (lv2def) {
GST_WARNING ("%s:%s has default %f outside of scalepoints",
lilv_node_as_string (lilv_plugin_get_uri (lv2plugin)), name, def);
}
def = enums[0].value;
}
/* terminator */
enums[j].value = 0;
enums[j].value_name = enums[j].value_nick = NULL;
type_name = g_strdup_printf ("%s%s",
g_type_name (G_TYPE_FROM_CLASS (object_class)), name);
enum_type = g_enum_register_static (type_name, enums);
g_free (type_name);
} else {
g_free (enums);
}
lilv_scale_points_free (points);
}
if (enum_type != G_TYPE_INVALID) {
ret = g_param_spec_enum (name, nick, nick, enum_type, def, perms);
} else if (lilv_port_has_property (lv2plugin, port, integer_prop))
ret = g_param_spec_int (name, nick, nick, lower, upper, def, perms);
else
ret = g_param_spec_float (name, nick, nick, lower, upper, def, perms);
done:
// build a map of (port_symbol to ret->name) for extensions
g_hash_table_insert (klass->sym_to_name, (gchar *) port_symbol,
(gchar *) ret->name);
g_free (name);
g_free (nick);
return ret;
}
void
gst_lv2_class_install_properties (GstLV2Class * lv2_class,
GObjectClass * object_class, guint offset)
{
GParamSpec *p;
guint i;
lv2_class->properties = offset;
for (i = 0; i < lv2_class->control_in_ports->len; i++, offset++) {
p = gst_lv2_class_get_param_spec (lv2_class, object_class,
g_array_index (lv2_class->control_in_ports, GstLV2Port, i).index);
g_object_class_install_property (object_class, offset, p);
}
for (i = 0; i < lv2_class->control_out_ports->len; i++, offset++) {
p = gst_lv2_class_get_param_spec (lv2_class, object_class,
g_array_index (lv2_class->control_out_ports, GstLV2Port, i).index);
g_object_class_install_property (object_class, offset, p);
}
}
void
gst_lv2_element_class_set_metadata (GstLV2Class * lv2_class,
GstElementClass * elem_class, const gchar * lv2_class_tags)
{
const LilvPlugin *lv2plugin = lv2_class->plugin;
LilvNode *val;
const LilvPluginClass *lv2plugin_class;
const LilvNode *cval;
gchar *longname, *author, *class_tags = NULL;
val = lilv_plugin_get_name (lv2plugin);
if (val) {
longname = g_strdup (lilv_node_as_string (val));
lilv_node_free (val);
} else {
longname = g_strdup ("no description available");
}
val = lilv_plugin_get_author_name (lv2plugin);
if (val) {
// TODO: check lilv_plugin_get_author_email(lv2plugin);
author = g_strdup (lilv_node_as_string (val));
lilv_node_free (val);
} else {
author = g_strdup ("no author available");
}
// TODO: better description from:
// lilv_plugin_get_author_homepage() and lilv_plugin_get_project()
lv2plugin_class = lilv_plugin_get_class (lv2plugin);
cval = lilv_plugin_class_get_label (lv2plugin_class);
if (cval) {
class_tags = g_strconcat (lv2_class_tags, "/", lilv_node_as_string (cval),
NULL);
}
gst_element_class_set_metadata (elem_class, longname,
(class_tags ? class_tags : lv2_class_tags), longname, author);
g_free (longname);
g_free (author);
g_free (class_tags);
}
void
gst_lv2_class_init (GstLV2Class * lv2_class, GType type)
{
const GValue *value =
gst_structure_get_value (lv2_meta_all, g_type_name (type));
GstStructure *lv2_meta = g_value_get_boxed (value);
const LilvPlugin *lv2plugin;
guint j, in_pad_index = 0, out_pad_index = 0;
const LilvPlugins *plugins = lilv_world_get_all_plugins (world);
LilvNode *plugin_uri;
const gchar *element_uri;
GST_DEBUG ("LV2 initializing class");
element_uri = gst_structure_get_string (lv2_meta, "element-uri");
plugin_uri = lilv_new_uri (world, element_uri);
g_assert (plugin_uri);
lv2plugin = lilv_plugins_get_by_uri (plugins, plugin_uri);
g_assert (lv2plugin);
lv2_class->plugin = lv2plugin;
lilv_node_free (plugin_uri);
lv2_class->sym_to_name = g_hash_table_new (g_str_hash, g_str_equal);
lv2_class->in_group.ports = g_array_new (FALSE, TRUE, sizeof (GstLV2Port));
lv2_class->out_group.ports = g_array_new (FALSE, TRUE, sizeof (GstLV2Port));
lv2_class->control_in_ports = g_array_new (FALSE, TRUE, sizeof (GstLV2Port));
lv2_class->control_out_ports = g_array_new (FALSE, TRUE, sizeof (GstLV2Port));
/* find ports and groups */
for (j = 0; j < lilv_plugin_get_num_ports (lv2plugin); j++) {
const LilvPort *port = lilv_plugin_get_port_by_index (lv2plugin, j);
const gboolean is_input = lilv_port_is_a (lv2plugin, port, input_class);
const gboolean is_optional = lilv_port_has_property (lv2plugin, port,
optional_pred);
GstLV2Port desc = { j, GST_LV2_PORT_AUDIO, -1, };
LilvNodes *lv2group = lilv_port_get (lv2plugin, port, group_pred);
/* FIXME Handle channels positionning
* GstAudioChannelPosition position = GST_AUDIO_CHANNEL_POSITION_INVALID; */
if (lv2group) {
/* port is part of a group */
const gchar *group_uri = lilv_node_as_uri (lv2group);
GstLV2Group *group = is_input
? &lv2_class->in_group : &lv2_class->out_group;
if (group->uri == NULL) {
group->uri = g_strdup (group_uri);
group->pad = is_input ? in_pad_index++ : out_pad_index++;
group->ports = g_array_new (FALSE, TRUE, sizeof (GstLV2Port));
}
/* FIXME Handle channels positionning
position = GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT;
sub_values = lilv_port_get_value (lv2plugin, port, designation_pred);
if (lilv_nodes_size (sub_values) > 0) {
LilvNode *role = lilv_nodes_get_at (sub_values, 0);
position = gst_lv2_filter_role_to_position (role);
}
lilv_nodes_free (sub_values);
if (position != GST_AUDIO_CHANNEL_POSITION_INVALID) {
desc.position = position;
} */
g_array_append_val (group->ports, desc);
} else {
/* port is not part of a group, or it is part of a group but that group
* is illegal so we just ignore it */
if (lilv_port_is_a (lv2plugin, port, audio_class)) {
if (is_input) {
desc.pad = in_pad_index++;
g_array_append_val (lv2_class->in_group.ports, desc);
} else {
desc.pad = out_pad_index++;
g_array_append_val (lv2_class->out_group.ports, desc);
}
} else if (lilv_port_is_a (lv2plugin, port, control_class)) {
desc.type = GST_LV2_PORT_CONTROL;
if (is_input) {
lv2_class->num_control_in++;
g_array_append_val (lv2_class->control_in_ports, desc);
} else {
lv2_class->num_control_out++;
g_array_append_val (lv2_class->control_out_ports, desc);
}
} else if (lilv_port_is_a (lv2plugin, port, cv_class)) {
desc.type = GST_LV2_PORT_CV;
if (is_input) {
lv2_class->num_cv_in++;
g_array_append_val (lv2_class->control_in_ports, desc);
} else {
lv2_class->num_cv_out++;
g_array_append_val (lv2_class->control_out_ports, desc);
}
} else if (lilv_port_is_a (lv2plugin, port, event_class)) {
LilvNodes *supported = lilv_port_get_value (lv2plugin, port,
supports_event_pred);
GST_INFO ("%s: unhandled event port %d: %s, optional=%d, input=%d",
element_uri, j,
lilv_node_as_string (lilv_port_get_symbol (lv2plugin, port)),
is_optional, is_input);
if (lilv_nodes_size (supported) > 0) {
LilvIter *i;
for (i = lilv_nodes_begin (supported);
!lilv_nodes_is_end (supported, i);
i = lilv_nodes_next (supported, i)) {
const LilvNode *value = lilv_nodes_get (supported, i);
GST_INFO (" type = %s", lilv_node_as_uri (value));
}
}
lilv_nodes_free (supported);
// FIXME: handle them
} else {
/* unhandled port type */
const LilvNodes *classes = lilv_port_get_classes (lv2plugin, port);
GST_INFO ("%s: unhandled port %d: %s, optional=%d, input=%d",
element_uri, j,
lilv_node_as_string (lilv_port_get_symbol (lv2plugin, port)),
is_optional, is_input);
if (classes && lilv_nodes_size (classes) > 0) {
LilvIter *i;
// FIXME: we getting the same classe multiple times
for (i = lilv_nodes_begin (classes);
!lilv_nodes_is_end (classes, i);
i = lilv_nodes_next (classes, i)) {
const LilvNode *value = lilv_nodes_get (classes, i);
GST_INFO (" class = %s", lilv_node_as_uri (value));
}
}
}
}
}
}
void
gst_lv2_class_finalize (GstLV2Class * lv2_class)
{
GST_DEBUG ("LV2 finalizing class");
g_hash_table_destroy (lv2_class->sym_to_name);
g_array_free (lv2_class->in_group.ports, TRUE);
lv2_class->in_group.ports = NULL;
g_array_free (lv2_class->out_group.ports, TRUE);
lv2_class->out_group.ports = NULL;
g_array_free (lv2_class->control_in_ports, TRUE);
lv2_class->control_in_ports = NULL;
g_array_free (lv2_class->control_out_ports, TRUE);
lv2_class->control_out_ports = NULL;
}
|
FalconLK/FaCoY
|
RQs/dyclink/GoogleCodeJam_data/2011/2011_dan.banica.java
|
<reponame>FalconLK/FaCoY<filename>RQs/dyclink/GoogleCodeJam_data/2011/2011_dan.banica.java<gh_stars>10-100
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
import java.util.regex.*;
import java.text.*;
import java.math.*;
import java.awt.geom.*;
public class A2 {
static class Pair implements Comparable<Pair> {
Integer a;
Integer b;
double yl, yh;
int idx = -1;
boolean up = false;
public Pair(int a1, int b1) {
a = a1;
b = b1;
}
@Override
public int compareTo(Pair p) {
if (a.compareTo(p.a) != 0) {
return a.compareTo(p.a);
}
return b.compareTo(p.b);
}
public String toString() {
return "(" + a + ", " + b + ")";
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("A.in"));
PrintWriter pw = new PrintWriter("A.out");
int T = sc.nextInt();
for (int test=1; test<=T; test++) {
System.out.println(test);
Vector<Pair> vl = new Vector<Pair>();
Vector<Pair> vu = new Vector<Pair>();
Vector<Pair> v = new Vector<Pair>();
pw.println("Case #"+test+": ");
int w = sc.nextInt();
int l = sc.nextInt();
int u = sc.nextInt();
int g = sc.nextInt();
double sl = 0;
double su = 0;
for (int i=0; i<l; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
Pair p = new Pair(x, y);
p.up = false;
p.idx = i;
vl.add(p);
if (i>0) {
int xv = vl.get(i-1).a;
int yv = vl.get(i-1).b;
sl += (x - xv) * ((double)y + yv)/2;
}
}
for (int j=0; j<u; j++) {
int x = sc.nextInt();
int y = sc.nextInt();
Pair p = new Pair(x, y);
p.up = true;
p.idx = j;
vu.add(p);
if (j>0) {
int xv = vu.get(j-1).a;
int yv = vu.get(j-1).b;
su += (x - xv) * ((double)y + yv)/2;
}
}
v.addAll(vl);
v.addAll(vu);
Collections.sort(v);
int ll=0;
for (int i=0; i<u; i++) {
Pair p = vu.get(i);
int x = p.a;
int y = p.b;
p.yh = y;
while (x > vl.get(ll+1).a) {
ll++;
}
int x00 = vl.get(ll).a;
int x01 = vl.get(ll+1).a;
int y00 = vl.get(ll).b;
int y01 = vl.get(ll+1).b;
p.yl = ((double)(x-x00)) / (x01-x00) * (y01-y00) + y00;
}
int lu=0;
for (int i=0; i<l; i++) {
Pair p = vl.get(i);
int x = p.a;
int y = p.b;
p.yl = y;
while (x > vu.get(lu+1).a) {
lu++;
}
int x00 = vu.get(lu).a;
int x01 = vu.get(lu+1).a;
int y00 = vu.get(lu).b;
int y01 = vu.get(lu+1).b;
p.yh = ((double)(x-x00)) / (x01-x00) * (y01-y00) + y00;
}
double s = su - sl;
double s0 = s / g;
for_i:
for (int i=1; i<g; i++) {
// find x with i*s0
double st = i*s0;
double scrt = 0;
for (int k=0; k<l+u; k++) {
Pair p1 = v.get(k);
Pair p2 = v.get(k+1);
int x0 = p1.a;
int x1 = p2.a;
double dy0 = p1.yh - p1.yl;
double dy1 = p2.yh - p2.yl;
double crt = (dy0+dy1) * (x1-x0) / 2;
if (crt + scrt > st) {
double area = st - scrt;
double xmin = x0;
double xmax = x1;
while (xmax - xmin > 0.00000001) {
double xh = (xmin+xmax)/2;
double yh = dy0 + (dy1-dy0) * ((double)(xh-x0))/(x1-x0);
double sh = (yh+dy0) * (xh-x0)/2;
if (sh > area) {
xmax = xh;
}
else {
xmin = xh;
}
}
pw.println(xmin);
continue for_i;
}
else {
scrt += crt;
}
}
}
}
pw.close();
}
}
|
agmen-hu/consoloid-console
|
Consoloid/Speech/test/InputButtonTest.js
|
<reponame>agmen-hu/consoloid-console
require('../InputButton');
require('consoloid-framework/Consoloid/Test/UnitTest');
describeUnitTest('Consoloid.Speech.InputButton', function() {
var
button;
beforeEach(function() {
button = env.create('Consoloid.Speech.InputButton', {
buttonNode: {
click: sinon.spy(),
css: sinon.spy()
},
outputNode: {
val: sinon.spy()
},
recognizer: {
start: sinon.stub().returns("foo"),
abort: sinon.stub()
},
grammerFixer: {
fix: sinon.spy(function(text){ return text; })
}
});
});
describe('#__constructor()', function() {
it('should require a recognizer options', function() {
(function() {
env.create('Consoloid.Speech.InputButton', {});
}).should.throwError('recognizer must be injected');
});
it('should not try to bind on click if button is not present', function() {
env.create('Consoloid.Speech.InputButton', { recognizer: {}});
});
it('should bind on click of the button if button is present', function() {
button.buttonNode.click.calledOnce.should.be.true;
});
});
describe('#setOutputNode(node)', function(){
it('should set the outputNode', function(){
button.setOutputNode({ foo: true});
button.outputNode.foo.should.be.true;
});
});
describe('#setButtonNode(node)', function(){
it('should bind on click of a button', function(){
button = env.create('Consoloid.Speech.InputButton', {recognizer:{}});
button.setButtonNode({ click: sinon.spy()});
button.buttonNode.click.calledOnce.should.be.true;
});
});
describe('#clicked()', function() {
it('should start speech recognizing', function() {
button.clicked();
button.recognizer.start.calledOnce.should.be.true;
});
it('should abort speech recognizing if recognition is underway', function() {
button.clicked();
button.clicked();
button.recognizer.abort.calledOnce.should.be.true;
});
});
describe('#handleRecognitionCompleted()', function() {
beforeEach(function(){
button.handleRecognitionCompleted({
options: [
{
text: 'What is this?',
confidence: 0.9
},
{
text: 'What is that?',
confidence: 0.1
}
]
});
});
it('should fill outputNode with value from recognizer', function() {
button.outputNode.val.calledOnce.should.be.true;
button.outputNode.val.calledWith('What is this?').should.be.true;
});
it('should use the grammer fixer if have it', function() {
button.grammerFixer.fix.calledWith('What is this?').should.be.true;
});
});
});
|
lechium/iPhoneOS_12.1.1_Headers
|
System/Library/PrivateFrameworks/AirPlaySupport.framework/APSAWDAirPlayDiscoveryDetailedModeStats.h
|
<reponame>lechium/iPhoneOS_12.1.1_Headers<filename>System/Library/PrivateFrameworks/AirPlaySupport.framework/APSAWDAirPlayDiscoveryDetailedModeStats.h
/*
* This header is generated by classdump-dyld 1.0
* on Saturday, June 1, 2019 at 6:47:41 PM Mountain Standard Time
* Operating System: Version 12.1.1 (Build 16C5050a)
* Image Source: /System/Library/PrivateFrameworks/AirPlaySupport.framework/AirPlaySupport
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <AirPlaySupport/AirPlaySupport-Structs.h>
#import <ProtocolBuffer/PBCodable.h>
#import <libobjc.A.dylib/NSCopying.h>
@class NSString;
@interface APSAWDAirPlayDiscoveryDetailedModeStats : PBCodable <NSCopying> {
unsigned long long _durationMs;
unsigned long long _firstAWDLDeviceFoundMs;
unsigned long long _firstSrcPresenceBeaconSentMs;
unsigned long long _startTime;
unsigned long long _timestamp;
int _apRSSI;
unsigned _devicePickedMs;
NSString* _discoverySessionUUID;
int _status;
unsigned _totalAWDLPeersDiscovered;
unsigned _totalAWDLmDNSPeers;
unsigned _totalPeersDiscovered;
SCD_Struct_AP7 _has;
}
@property (assign,nonatomic) BOOL hasTimestamp;
@property (assign,nonatomic) unsigned long long timestamp; //@synthesize timestamp=_timestamp - In the implementation block
@property (nonatomic,readonly) BOOL hasDiscoverySessionUUID;
@property (nonatomic,retain) NSString * discoverySessionUUID; //@synthesize discoverySessionUUID=_discoverySessionUUID - In the implementation block
@property (assign,nonatomic) BOOL hasStatus;
@property (assign,nonatomic) int status; //@synthesize status=_status - In the implementation block
@property (assign,nonatomic) BOOL hasStartTime;
@property (assign,nonatomic) unsigned long long startTime; //@synthesize startTime=_startTime - In the implementation block
@property (assign,nonatomic) BOOL hasFirstSrcPresenceBeaconSentMs;
@property (assign,nonatomic) unsigned long long firstSrcPresenceBeaconSentMs; //@synthesize firstSrcPresenceBeaconSentMs=_firstSrcPresenceBeaconSentMs - In the implementation block
@property (assign,nonatomic) BOOL hasFirstAWDLDeviceFoundMs;
@property (assign,nonatomic) unsigned long long firstAWDLDeviceFoundMs; //@synthesize firstAWDLDeviceFoundMs=_firstAWDLDeviceFoundMs - In the implementation block
@property (assign,nonatomic) BOOL hasDurationMs;
@property (assign,nonatomic) unsigned long long durationMs; //@synthesize durationMs=_durationMs - In the implementation block
@property (assign,nonatomic) BOOL hasTotalPeersDiscovered;
@property (assign,nonatomic) unsigned totalPeersDiscovered; //@synthesize totalPeersDiscovered=_totalPeersDiscovered - In the implementation block
@property (assign,nonatomic) BOOL hasDevicePickedMs;
@property (assign,nonatomic) unsigned devicePickedMs; //@synthesize devicePickedMs=_devicePickedMs - In the implementation block
@property (assign,nonatomic) BOOL hasApRSSI;
@property (assign,nonatomic) int apRSSI; //@synthesize apRSSI=_apRSSI - In the implementation block
@property (assign,nonatomic) BOOL hasTotalAWDLPeersDiscovered;
@property (assign,nonatomic) unsigned totalAWDLPeersDiscovered; //@synthesize totalAWDLPeersDiscovered=_totalAWDLPeersDiscovered - In the implementation block
@property (assign,nonatomic) BOOL hasTotalAWDLmDNSPeers;
@property (assign,nonatomic) unsigned totalAWDLmDNSPeers; //@synthesize totalAWDLmDNSPeers=_totalAWDLmDNSPeers - In the implementation block
-(BOOL)readFrom:(id)arg1 ;
-(void)writeTo:(id)arg1 ;
-(void)mergeFrom:(id)arg1 ;
-(void)setHasTimestamp:(BOOL)arg1 ;
-(BOOL)hasTimestamp;
-(void)setHasStatus:(BOOL)arg1 ;
-(BOOL)hasStatus;
-(void)setHasStartTime:(BOOL)arg1 ;
-(BOOL)hasStartTime;
-(BOOL)hasDiscoverySessionUUID;
-(NSString *)discoverySessionUUID;
-(void)setDiscoverySessionUUID:(NSString *)arg1 ;
-(void)setFirstSrcPresenceBeaconSentMs:(unsigned long long)arg1 ;
-(void)setHasFirstSrcPresenceBeaconSentMs:(BOOL)arg1 ;
-(BOOL)hasFirstSrcPresenceBeaconSentMs;
-(void)setFirstAWDLDeviceFoundMs:(unsigned long long)arg1 ;
-(void)setHasFirstAWDLDeviceFoundMs:(BOOL)arg1 ;
-(BOOL)hasFirstAWDLDeviceFoundMs;
-(void)setTotalPeersDiscovered:(unsigned)arg1 ;
-(void)setHasTotalPeersDiscovered:(BOOL)arg1 ;
-(BOOL)hasTotalPeersDiscovered;
-(void)setDevicePickedMs:(unsigned)arg1 ;
-(void)setHasDevicePickedMs:(BOOL)arg1 ;
-(BOOL)hasDevicePickedMs;
-(void)setApRSSI:(int)arg1 ;
-(void)setHasApRSSI:(BOOL)arg1 ;
-(BOOL)hasApRSSI;
-(void)setTotalAWDLPeersDiscovered:(unsigned)arg1 ;
-(void)setHasTotalAWDLPeersDiscovered:(BOOL)arg1 ;
-(BOOL)hasTotalAWDLPeersDiscovered;
-(void)setTotalAWDLmDNSPeers:(unsigned)arg1 ;
-(void)setHasTotalAWDLmDNSPeers:(BOOL)arg1 ;
-(BOOL)hasTotalAWDLmDNSPeers;
-(unsigned long long)firstSrcPresenceBeaconSentMs;
-(unsigned long long)firstAWDLDeviceFoundMs;
-(unsigned)totalPeersDiscovered;
-(unsigned)devicePickedMs;
-(int)apRSSI;
-(unsigned)totalAWDLPeersDiscovered;
-(unsigned)totalAWDLmDNSPeers;
-(void)setDurationMs:(unsigned long long)arg1 ;
-(void)setHasDurationMs:(BOOL)arg1 ;
-(BOOL)hasDurationMs;
-(unsigned long long)durationMs;
-(void)dealloc;
-(BOOL)isEqual:(id)arg1 ;
-(unsigned long long)hash;
-(id)description;
-(id)copyWithZone:(NSZone*)arg1 ;
-(unsigned long long)timestamp;
-(unsigned long long)startTime;
-(void)setStartTime:(unsigned long long)arg1 ;
-(id)dictionaryRepresentation;
-(int)status;
-(void)setTimestamp:(unsigned long long)arg1 ;
-(void)copyTo:(id)arg1 ;
-(void)setStatus:(int)arg1 ;
@end
|
Brokenshire/codewars-projects
|
Python/six_kyu/song_decoder.py
|
<gh_stars>1-10
# Python solution for 'Dubstep' codewars question.
# Level: 6 kyu
# Tags: Fundamentals, and Strings.
# Author: <NAME>
# Date: 06/02/2020
import unittest
def song_decoder(song):
"""
Removes 'WUB' from a string to find the true message of the song.
:param song: The input consists of a single non-empty string, consisting only of uppercase English letters, the string's length doesn't exceed 200 characters
:return: the words of the initial song that Polycarpus used to make a dubsteb remix. Separate the words with a space.
"""
return " ".join(song.replace('WUB', ' ').split())
class TestSongDecoder(unittest.TestCase):
"""Class to test 'song_decoder' function"""
def test_song_decoder(self):
self.assertEqual(song_decoder("AWUBBWUBC"), "A B C");
self.assertEqual(song_decoder("AWUBWUBWUBBWUBWUBWUBC"), "A B C");
self.assertEqual(song_decoder("WUBAWUBBWUBCWUB"), "A B C");
if __name__ == '__main__':
unittest.main()
|
ss-jugg/YCAssistivePlugin
|
YCAssistivePlugin/Classes/Plugins/Memory/YCAssistiveMemoryPluginWindow.h
|
<gh_stars>1-10
//
// YCAssistiveMemoryPluginWindow.h
// YCAssistivePlugin
//
// Created by shenweihang on 2019/9/27.
//
#import "YCAssistivePluginWindow.h"
NS_ASSUME_NONNULL_BEGIN
@interface YCAssistiveMemoryPluginWindow : YCAssistivePluginWindow
@end
NS_ASSUME_NONNULL_END
|
uvbs/FullSource
|
Source/Source/Server/SO3Gateway/KRelayAgency.h
|
#ifndef _KRELAYAGENCY_H_
#define _KRELAYAGENCY_H_
#include "GatewayRelayProtocol.h"
class KPlayerManager;
class KPaysysAgency;
class KSO3Gateway;
class KQueueManager;
class KSndaAgency;
class KRelayAgency
{
public:
KRelayAgency();
BOOL Init();
void UnInit();
void Activate();
private:
BOOL ProcessPackage();
BOOL Send(IKG_Buffer* piBuffer);
public:
BOOL GetGameWorldVersion(int* pnLowerVersion, int* pnUpperVersion);
BOOL IsAccountBlocked(const char cszAcc[]);
void AttachModule(KPlayerManager* pModule) { m_pPlayerManager = pModule; }
void AttachModule(KPaysysAgency* pModule) { m_pPaysysAgency = pModule; }
void AttachModule(KSO3Gateway* pModule) { m_pGateway = pModule; }
void AttachModule(KQueueManager* pModule) { m_pQueueManager = pModule; }
void AttachModule(KSndaAgency* pModule) { m_pSndaAgency = pModule; }
public:
BOOL DoPingSignal();
BOOL DoQueryAccountState(KPlayerAgency* pPlayer);
BOOL DoKickAccountNotify(KPlayerAgency* pPlayer);
BOOL DoQueryRoleList(KPlayerAgency* pPlayer);
BOOL DoQueryNewbieMaps(int nPlayerIndex);
BOOL DoCreateRoleRequest(int nPlayerIndex, const char cszAcc[], BYTE* pbyData, size_t uDataLen);
BOOL DoDeleteRoleRequest(KPlayerAgency* pPlayer, DWORD dwRoleID);
BOOL DoGameLoginRequest(KPlayerAgency* pPlayer, DWORD dwRoleID, BYTE* pbyData, size_t uDataLen);
BOOL DoChangeExtPointRespond(BOOL bSucceed, DWORD dwRoleID);
BOOL DoSetChargeFlagRespond(
BOOL bSucceed, DWORD dwRoleID, int nChargeFlag, const tagExtPointInfo& rExtPointInfo,
DWORD dwEndTimeOfFee
);
BOOL DoGetZoneChargeFlagNotify(int nZoneChargeFlag);
BOOL DoActivePresentCodeRespond(BOOL bSucceed, DWORD dwRoleID, const char* pszPresentCode, DWORD dwPresentType);
BOOL DoFreezeCoinRespond(BOOL bSucceed, DWORD dwRequestID, BOOL bFreezeFlag, int nCoin);
BOOL DoAccountExchangeRespond(BOOL bSucceed, DWORD dwRequestID);
BOOL DoRenameRequest(int nPlayerIndex, DWORD dwRoleID, char szNewName[]);
private:
void OnPingSignal(BYTE* pbyData, size_t uDataLen);
void OnSetGameWorldVersion(BYTE* pbyData, size_t uDataLen);
void OnSyncAccountState(BYTE* pbyData, size_t uDataLen);
void OnSyncRoleList(BYTE* pbyData, size_t uDataLen);
void OnCreateRoleRespond(BYTE* pbyData, size_t uDataLen);
void OnDeleteRoleRespond(BYTE* pbyData, size_t uDataLen);
void OnGameLoginRespond(BYTE* pbyData, size_t uDataLen);
void OnSyncNewbieMaps(BYTE* pbyData, size_t uDataLen);
void OnPlayerLeaveGame(BYTE* pbyData, size_t uDataLen);
void OnChangeExtPointRequest(BYTE* pbyData, size_t uDataLen);
void OnSetChargeFlagRequest(BYTE* pbyData, size_t uDataLen);
void OnActivePresentCodeRequest(BYTE* pbyData, size_t uDataLen);
void OnFreezeCoinRequest(BYTE* pbyData, size_t uDataLen);
void OnAccountExchangeRequest(BYTE* pbyData, size_t uDataLen);
void OnRenameRespond(BYTE* pbyData, size_t uDataLen);
private:
int m_nGameWorldLowerVersion;
int m_nGameWorldUpperVersion;
DWORD m_dwNextPingTime;
int m_nPingCycle;
KPlayerManager* m_pPlayerManager;
KPaysysAgency* m_pPaysysAgency;
KSO3Gateway* m_pGateway;
KQueueManager* m_pQueueManager;
KSndaAgency* m_pSndaAgency;
private:
typedef void (KRelayAgency::*PR2G_PROTOCOL_FUNC)(BYTE* pbyData, size_t uDataLen);
PR2G_PROTOCOL_FUNC m_PakProcessor[r2g_protocol_total];
size_t m_uPakSize[r2g_protocol_total];
IKG_SocketStream* m_piSocket;
BOOL m_bSocketError;
};
#endif
|
enrpan/spring-framework-2.5
|
samples/petclinic/src/org/springframework/samples/petclinic/web/AddPetForm.java
|
<gh_stars>0
package org.springframework.samples.petclinic.web;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.Clinic;
import org.springframework.samples.petclinic.Owner;
import org.springframework.samples.petclinic.Pet;
import org.springframework.samples.petclinic.PetType;
import org.springframework.samples.petclinic.validation.PetValidator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
/**
* JavaBean form controller that is used to add a new <code>Pet</code> to the
* system.
*
* @author <NAME>
* @author <NAME>
*/
@Controller
@RequestMapping("/addPet.do")
@SessionAttributes("pet")
public class AddPetForm {
private final Clinic clinic;
@Autowired
public AddPetForm(Clinic clinic) {
this.clinic = clinic;
}
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {
Owner owner = this.clinic.loadOwner(ownerId);
Pet pet = new Pet();
owner.addPet(pet);
model.addAttribute("pet", pet);
return "petForm";
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}
else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId=" + pet.getOwner().getId();
}
}
}
|
PacktPublishing/Python-Machine-Learning-Solutions-V-
|
Section_04_code/PyQT4/Lib/site-packages/PyQt4/examples/painting/basicdrawing/basicdrawing.pyw
|
<reponame>PacktPublishing/Python-Machine-Learning-Solutions-V-
#!/usr/bin/env python
#############################################################################
##
## Copyright (C) 2010 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may use this file under the terms of the BSD license as follows:
##
## "Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are
## met:
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or other materials provided with the
## distribution.
## * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
## the names of its contributors may be used to endorse or promote
## products derived from this software without specific prior written
## permission.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
## $QT_END_LICENSE$
##
#############################################################################
# This is only needed for Python v2 but is harmless for Python v3.
import sip
sip.setapi('QVariant', 2)
from PyQt4 import QtCore, QtGui
import basicdrawing_rc
class RenderArea(QtGui.QWidget):
points = QtGui.QPolygon([
QtCore.QPoint(10, 80),
QtCore.QPoint(20, 10),
QtCore.QPoint(80, 30),
QtCore.QPoint(90, 70)
])
Line, Points, Polyline, Polygon, Rect, RoundedRect, Ellipse, Arc, Chord, \
Pie, Path, Text, Pixmap = range(13)
def __init__(self, parent=None):
super(RenderArea, self).__init__(parent)
self.pen = QtGui.QPen()
self.brush = QtGui.QBrush()
self.pixmap = QtGui.QPixmap()
self.shape = RenderArea.Polygon
self.antialiased = False
self.transformed = False
self.pixmap.load(':/images/qt-logo.png')
self.setBackgroundRole(QtGui.QPalette.Base)
self.setAutoFillBackground(True)
def minimumSizeHint(self):
return QtCore.QSize(100, 100)
def sizeHint(self):
return QtCore.QSize(400, 200)
def setShape(self, shape):
self.shape = shape
self.update()
def setPen(self, pen):
self.pen = pen
self.update()
def setBrush(self, brush):
self.brush = brush
self.update()
def setAntialiased(self, antialiased):
self.antialiased = antialiased
self.update()
def setTransformed(self, transformed):
self.transformed = transformed
self.update()
def paintEvent(self, event):
rect = QtCore.QRect(10, 20, 80, 60)
path = QtGui.QPainterPath()
path.moveTo(20, 80)
path.lineTo(20, 30)
path.cubicTo(80, 0, 50, 50, 80, 80)
startAngle = 30 * 16
arcLength = 120 * 16
painter = QtGui.QPainter(self)
painter.setPen(self.pen)
painter.setBrush(self.brush)
if self.antialiased:
painter.setRenderHint(QtGui.QPainter.Antialiasing)
for x in range(0, self.width(), 100):
for y in range(0, self.height(), 100):
painter.save()
painter.translate(x, y)
if self.transformed:
painter.translate(50, 50)
painter.rotate(60.0)
painter.scale(0.6, 0.9)
painter.translate(-50, -50)
if self.shape == RenderArea.Line:
painter.drawLine(rect.bottomLeft(), rect.topRight())
elif self.shape == RenderArea.Points:
painter.drawPoints(RenderArea.points)
elif self.shape == RenderArea.Polyline:
painter.drawPolyline(RenderArea.points)
elif self.shape == RenderArea.Polygon:
painter.drawPolygon(RenderArea.points)
elif self.shape == RenderArea.Rect:
painter.drawRect(rect)
elif self.shape == RenderArea.RoundedRect:
painter.drawRoundedRect(rect, 25, 25,
QtCore.Qt.RelativeSize)
elif self.shape == RenderArea.Ellipse:
painter.drawEllipse(rect)
elif self.shape == RenderArea.Arc:
painter.drawArc(rect, startAngle, arcLength)
elif self.shape == RenderArea.Chord:
painter.drawChord(rect, startAngle, arcLength)
elif self.shape == RenderArea.Pie:
painter.drawPie(rect, startAngle, arcLength)
elif self.shape == RenderArea.Path:
painter.drawPath(path)
elif self.shape == RenderArea.Text:
painter.drawText(rect, QtCore.Qt.AlignCenter,
"Qt by\nQt Software")
elif self.shape == RenderArea.Pixmap:
painter.drawPixmap(10, 10, self.pixmap)
painter.restore()
painter.setPen(self.palette().dark().color())
painter.setBrush(QtCore.Qt.NoBrush)
painter.drawRect(QtCore.QRect(0, 0, self.width() - 1,
self.height() - 1))
IdRole = QtCore.Qt.UserRole
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.renderArea = RenderArea()
self.shapeComboBox = QtGui.QComboBox()
self.shapeComboBox.addItem("Polygon", RenderArea.Polygon)
self.shapeComboBox.addItem("Rectangle", RenderArea.Rect)
self.shapeComboBox.addItem("Rounded Rectangle", RenderArea.RoundedRect)
self.shapeComboBox.addItem("Ellipse", RenderArea.Ellipse)
self.shapeComboBox.addItem("Pie", RenderArea.Pie)
self.shapeComboBox.addItem("Chord", RenderArea.Chord)
self.shapeComboBox.addItem("Path", RenderArea.Path)
self.shapeComboBox.addItem("Line", RenderArea.Line)
self.shapeComboBox.addItem("Polyline", RenderArea.Polyline)
self.shapeComboBox.addItem("Arc", RenderArea.Arc)
self.shapeComboBox.addItem("Points", RenderArea.Points)
self.shapeComboBox.addItem("Text", RenderArea.Text)
self.shapeComboBox.addItem("Pixmap", RenderArea.Pixmap)
shapeLabel = QtGui.QLabel("&Shape:")
shapeLabel.setBuddy(self.shapeComboBox)
self.penWidthSpinBox = QtGui.QSpinBox()
self.penWidthSpinBox.setRange(0, 20)
self.penWidthSpinBox.setSpecialValueText("0 (cosmetic pen)")
penWidthLabel = QtGui.QLabel("Pen &Width:")
penWidthLabel.setBuddy(self.penWidthSpinBox)
self.penStyleComboBox = QtGui.QComboBox()
self.penStyleComboBox.addItem("Solid", QtCore.Qt.SolidLine)
self.penStyleComboBox.addItem("Dash", QtCore.Qt.DashLine)
self.penStyleComboBox.addItem("Dot", QtCore.Qt.DotLine)
self.penStyleComboBox.addItem("Dash Dot", QtCore.Qt.DashDotLine)
self.penStyleComboBox.addItem("Dash Dot Dot", QtCore.Qt.DashDotDotLine)
self.penStyleComboBox.addItem("None", QtCore.Qt.NoPen)
penStyleLabel = QtGui.QLabel("&Pen Style:")
penStyleLabel.setBuddy(self.penStyleComboBox)
self.penCapComboBox = QtGui.QComboBox()
self.penCapComboBox.addItem("Flat", QtCore.Qt.FlatCap)
self.penCapComboBox.addItem("Square", QtCore.Qt.SquareCap)
self.penCapComboBox.addItem("Round", QtCore.Qt.RoundCap)
penCapLabel = QtGui.QLabel("Pen &Cap:")
penCapLabel.setBuddy(self.penCapComboBox)
self.penJoinComboBox = QtGui.QComboBox()
self.penJoinComboBox.addItem("Miter", QtCore.Qt.MiterJoin)
self.penJoinComboBox.addItem("Bevel", QtCore.Qt.BevelJoin)
self.penJoinComboBox.addItem("Round", QtCore.Qt.RoundJoin)
penJoinLabel = QtGui.QLabel("Pen &Join:")
penJoinLabel.setBuddy(self.penJoinComboBox)
self.brushStyleComboBox = QtGui.QComboBox()
self.brushStyleComboBox.addItem("Linear Gradient",
QtCore.Qt.LinearGradientPattern)
self.brushStyleComboBox.addItem("Radial Gradient",
QtCore.Qt.RadialGradientPattern)
self.brushStyleComboBox.addItem("Conical Gradient",
QtCore.Qt.ConicalGradientPattern)
self.brushStyleComboBox.addItem("Texture", QtCore.Qt.TexturePattern)
self.brushStyleComboBox.addItem("Solid", QtCore.Qt.SolidPattern)
self.brushStyleComboBox.addItem("Horizontal", QtCore.Qt.HorPattern)
self.brushStyleComboBox.addItem("Vertical", QtCore.Qt.VerPattern)
self.brushStyleComboBox.addItem("Cross", QtCore.Qt.CrossPattern)
self.brushStyleComboBox.addItem("Backward Diagonal",
QtCore.Qt.BDiagPattern)
self.brushStyleComboBox.addItem("Forward Diagonal",
QtCore.Qt.FDiagPattern)
self.brushStyleComboBox.addItem("Diagonal Cross",
QtCore.Qt.DiagCrossPattern)
self.brushStyleComboBox.addItem("Dense 1", QtCore.Qt.Dense1Pattern)
self.brushStyleComboBox.addItem("Dense 2", QtCore.Qt.Dense2Pattern)
self.brushStyleComboBox.addItem("Dense 3", QtCore.Qt.Dense3Pattern)
self.brushStyleComboBox.addItem("Dense 4", QtCore.Qt.Dense4Pattern)
self.brushStyleComboBox.addItem("Dense 5", QtCore.Qt.Dense5Pattern)
self.brushStyleComboBox.addItem("Dense 6", QtCore.Qt.Dense6Pattern)
self.brushStyleComboBox.addItem("Dense 7", QtCore.Qt.Dense7Pattern)
self.brushStyleComboBox.addItem("None", QtCore.Qt.NoBrush)
brushStyleLabel = QtGui.QLabel("&Brush Style:")
brushStyleLabel.setBuddy(self.brushStyleComboBox)
otherOptionsLabel = QtGui.QLabel("Other Options:")
self.antialiasingCheckBox = QtGui.QCheckBox("&Antialiasing")
self.transformationsCheckBox = QtGui.QCheckBox("&Transformations")
self.shapeComboBox.activated.connect(self.shapeChanged)
self.penWidthSpinBox.valueChanged.connect(self.penChanged)
self.penStyleComboBox.activated.connect(self.penChanged)
self.penCapComboBox.activated.connect(self.penChanged)
self.penJoinComboBox.activated.connect(self.penChanged)
self.brushStyleComboBox.activated.connect(self.brushChanged)
self.antialiasingCheckBox.toggled.connect(self.renderArea.setAntialiased)
self.transformationsCheckBox.toggled.connect(self.renderArea.setTransformed)
mainLayout = QtGui.QGridLayout()
mainLayout.setColumnStretch(0, 1)
mainLayout.setColumnStretch(3, 1)
mainLayout.addWidget(self.renderArea, 0, 0, 1, 4)
mainLayout.setRowMinimumHeight(1, 6)
mainLayout.addWidget(shapeLabel, 2, 1, QtCore.Qt.AlignRight)
mainLayout.addWidget(self.shapeComboBox, 2, 2)
mainLayout.addWidget(penWidthLabel, 3, 1, QtCore.Qt.AlignRight)
mainLayout.addWidget(self.penWidthSpinBox, 3, 2)
mainLayout.addWidget(penStyleLabel, 4, 1, QtCore.Qt.AlignRight)
mainLayout.addWidget(self.penStyleComboBox, 4, 2)
mainLayout.addWidget(penCapLabel, 5, 1, QtCore.Qt.AlignRight)
mainLayout.addWidget(self.penCapComboBox, 5, 2)
mainLayout.addWidget(penJoinLabel, 6, 1, QtCore.Qt.AlignRight)
mainLayout.addWidget(self.penJoinComboBox, 6, 2)
mainLayout.addWidget(brushStyleLabel, 7, 1, QtCore.Qt.AlignRight)
mainLayout.addWidget(self.brushStyleComboBox, 7, 2)
mainLayout.setRowMinimumHeight(8, 6)
mainLayout.addWidget(otherOptionsLabel, 9, 1, QtCore.Qt.AlignRight)
mainLayout.addWidget(self.antialiasingCheckBox, 9, 2)
mainLayout.addWidget(self.transformationsCheckBox, 10, 2)
self.setLayout(mainLayout)
self.shapeChanged()
self.penChanged()
self.brushChanged()
self.antialiasingCheckBox.setChecked(True)
self.setWindowTitle("Basic Drawing")
def shapeChanged(self):
shape = self.shapeComboBox.itemData(self.shapeComboBox.currentIndex(),
IdRole)
self.renderArea.setShape(shape)
def penChanged(self):
width = self.penWidthSpinBox.value()
style = QtCore.Qt.PenStyle(self.penStyleComboBox.itemData(
self.penStyleComboBox.currentIndex(), IdRole))
cap = QtCore.Qt.PenCapStyle(self.penCapComboBox.itemData(
self.penCapComboBox.currentIndex(), IdRole))
join = QtCore.Qt.PenJoinStyle(self.penJoinComboBox.itemData(
self.penJoinComboBox.currentIndex(), IdRole))
self.renderArea.setPen(QtGui.QPen(QtCore.Qt.blue, width, style, cap, join))
def brushChanged(self):
style = QtCore.Qt.BrushStyle(self.brushStyleComboBox.itemData(
self.brushStyleComboBox.currentIndex(), IdRole))
if style == QtCore.Qt.LinearGradientPattern:
linearGradient = QtGui.QLinearGradient(0, 0, 100, 100)
linearGradient.setColorAt(0.0, QtCore.Qt.white)
linearGradient.setColorAt(0.2, QtCore.Qt.green)
linearGradient.setColorAt(1.0, QtCore.Qt.black)
self.renderArea.setBrush(QtGui.QBrush(linearGradient))
elif style == QtCore.Qt.RadialGradientPattern:
radialGradient = QtGui.QRadialGradient(50, 50, 50, 70, 70)
radialGradient.setColorAt(0.0, QtCore.Qt.white)
radialGradient.setColorAt(0.2, QtCore.Qt.green)
radialGradient.setColorAt(1.0, QtCore.Qt.black)
self.renderArea.setBrush(QtGui.QBrush(radialGradient))
elif style == QtCore.Qt.ConicalGradientPattern:
conicalGradient = QtGui.QConicalGradient(50, 50, 150)
conicalGradient.setColorAt(0.0, QtCore.Qt.white)
conicalGradient.setColorAt(0.2, QtCore.Qt.green)
conicalGradient.setColorAt(1.0, QtCore.Qt.black)
self.renderArea.setBrush(QtGui.QBrush(conicalGradient))
elif style == QtCore.Qt.TexturePattern:
self.renderArea.setBrush(QtGui.QBrush(QtGui.QPixmap(':/images/brick.png')))
else:
self.renderArea.setBrush(QtGui.QBrush(QtCore.Qt.green, style))
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
|
ocomsoft/cerealbox
|
tests/cerealbox_frommap_test.go
|
<filename>tests/cerealbox_frommap_test.go
package tests
import (
"github.com/ocomsoft/cerealbox"
validation "github.com/ocomsoft/cerealbox/validation"
"testing"
)
func TestFromMapWithFunc(t *testing.T) {
example := Example{}
serializerFunc := func(builder cerealbox.ISerializer) cerealbox.ISerializer {
return builder.DoString("name", "Name", true, validation.StringVal().MinLength(0).MaxLength(255)).
DoInt("age", "Age", true, validation.IntVal().Min(0).Max(255)).
DoBool("hidden", "Hide", true)
}
json := map[string]interface{}{
"age": 10,
"name": "<NAME>",
"hidden": true,
}
cerealbox.FromMapWithFunc(&example, json, serializerFunc)
if example.Age != 10 {
t.Fail()
}
if example.Name != "<NAME>" {
t.Fail()
}
if !example.Hide {
t.Fail()
}
}
|
Robbbert/messui
|
src/mame/drivers/pb1000.cpp
|
// license:BSD-3-Clause
// copyright-holders:<NAME>
/***************************************************************************
Casio PB-1000 / PB-2000c driver
Driver by <NAME>
TODO:
- improve the pb2000c gate array emulation
- i/o port
Known issues:
- the second memory card is not recognized by the HW
- pb2000c, ai1000: the shift key has to be released before hitting
the key that is to be shifted. Therefore natural keyboard/paste
will misbehave for shifted characters.
More info:
http://www.itkp.uni-bonn.de/~wichmann/pb1000-wrobel.html
****************************************************************************/
#include "emu.h"
#include "cpu/hd61700/hd61700.h"
#include "machine/nvram.h"
#include "sound/beep.h"
#include "video/hd44352.h"
#include "emupal.h"
#include "screen.h"
#include "softlist.h"
#include "speaker.h"
#include "bus/generic/carts.h"
#include "bus/generic/slot.h"
class pb1000_state : public driver_device
{
public:
pb1000_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag)
, m_maincpu(*this, "maincpu")
, m_beeper(*this, "beeper")
, m_hd44352(*this, "hd44352")
, m_card1(*this, "cardslot1")
, m_card2(*this, "cardslot2")
, m_io_keyboard(*this, "KO%u", 0U)
{ }
void pb2000c(machine_config &config);
void pb1000(machine_config &config);
private:
required_device<hd61700_cpu_device> m_maincpu;
required_device<beep_device> m_beeper;
required_device<hd44352_device> m_hd44352;
optional_device<generic_slot_device> m_card1;
optional_device<generic_slot_device> m_card2;
required_ioport_array<13> m_io_keyboard;
emu_timer *m_kb_timer;
uint8_t m_kb_matrix;
uint8_t m_gatearray[2];
memory_region *m_rom_reg;
memory_region *m_card1_reg;
memory_region *m_card2_reg;
virtual void machine_start() override;
void gatearray_w(offs_t offset, uint16_t data);
uint16_t pb1000_kb_r();
uint16_t pb2000c_kb_r();
void kb_matrix_w(uint8_t data);
uint8_t pb1000_port_r();
uint8_t pb2000c_port_r();
void port_w(uint8_t data);
uint16_t read_touchscreen(uint8_t line);
void pb1000_palette(palette_device &palette) const;
TIMER_CALLBACK_MEMBER(keyboard_timer);
void pb1000_mem(address_map &map);
void pb2000c_mem(address_map &map);
};
void pb1000_state::pb1000_mem(address_map &map)
{
map.unmap_value_low();
map(0x00000, 0x00bff).rom();
//map(0x00c00, 0x00c0f).noprw(); //I/O
map(0x06000, 0x07fff).ram().share("nvram1");
map(0x08000, 0x0ffff).bankr("bank1");
map(0x18000, 0x1ffff).ram().share("nvram2");
}
void pb1000_state::pb2000c_mem(address_map &map)
{
map.unmap_value_low();
map(0x00000, 0x0ffff).bankr("bank1");
map(0x00000, 0x00bff).rom();
//map(0x00c00, 0x00c0f).noprw(); //I/O
map(0x00c10, 0x00c11).w(FUNC(pb1000_state::gatearray_w));
map(0x10000, 0x1ffff).ram().share("nvram1");
map(0x20000, 0x27fff).r(m_card1, FUNC(generic_slot_device::read16_rom));
map(0x28000, 0x2ffff).ram().share("nvram2");
}
/* Input ports */
static INPUT_PORTS_START( pb1000 )
PORT_START("KO0")
PORT_START("KO1")
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("BRK") PORT_CODE(KEYCODE_F10) PORT_CHAR(UCHAR_MAMEKEY(F10))
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("OFF") PORT_CODE(KEYCODE_7_PAD)
PORT_START("KO2")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("EXE") PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13)
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("IN") PORT_CODE(KEYCODE_F4) PORT_CHAR(UCHAR_MAMEKEY(F4))
PORT_BIT(0x2000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("MEMO IN") PORT_CODE(KEYCODE_0_PAD)
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(", ?") PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('?')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("\" !") PORT_CODE(KEYCODE_QUOTE) PORT_CHAR('"') PORT_CHAR('!')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("$ #") PORT_CODE(KEYCODE_1_PAD) PORT_CHAR('$') PORT_CHAR('#')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("& %") PORT_CODE(KEYCODE_2_PAD) PORT_CHAR('&') PORT_CHAR('%')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("= '") PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('=') PORT_CHAR('\'')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("; <") PORT_CODE(KEYCODE_COLON) PORT_CHAR(';') PORT_CHAR('<')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(": >") PORT_CODE(KEYCODE_BACKSLASH2) PORT_CHAR(':') PORT_CHAR('>')
PORT_START("KO3")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(UTF8_RIGHT) PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("OUT") PORT_CODE(KEYCODE_F3) PORT_CHAR(UCHAR_MAMEKEY(F3))
PORT_BIT(0x2000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("MEMO") PORT_CODE(KEYCODE_F11) PORT_CHAR(UCHAR_MAMEKEY(F11))
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("U") PORT_CODE(KEYCODE_U) PORT_CHAR('U')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Q") PORT_CODE(KEYCODE_Q) PORT_CHAR('Q')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("W") PORT_CODE(KEYCODE_W) PORT_CHAR('W')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("E") PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("R") PORT_CODE(KEYCODE_R) PORT_CHAR('R')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("T") PORT_CODE(KEYCODE_T) PORT_CHAR('T')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Y") PORT_CODE(KEYCODE_Y) PORT_CHAR('Y')
PORT_START("KO4")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(UTF8_DOWN) PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("CALC") PORT_CODE(KEYCODE_HOME)
PORT_BIT(0x2000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("CAL") PORT_CODE(KEYCODE_F9) PORT_CHAR(UCHAR_MAMEKEY(F9))
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("H") PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("CAPS") PORT_CODE(KEYCODE_CAPSLOCK)
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("A") PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("S") PORT_CODE(KEYCODE_S) PORT_CHAR('S')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("D") PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("F") PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("G") PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_START("KO5")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(UTF8_UP) PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP))
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(UTF8_LEFT) PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
PORT_BIT(0x2000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("MENU") PORT_CODE(KEYCODE_F5) PORT_CHAR(UCHAR_MAMEKEY(F5))
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("M") PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Z") PORT_CODE(KEYCODE_Z) PORT_CHAR('Z')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("X") PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("C") PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("V") PORT_CODE(KEYCODE_V) PORT_CHAR('V')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("B") PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("N") PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_START("KO6")
PORT_BIT(0x2000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("LCKEY") PORT_CODE(KEYCODE_F1) PORT_CHAR(UCHAR_MAMEKEY(F1))
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("CONTRAST") PORT_CODE(KEYCODE_F2) PORT_CHAR(UCHAR_MAMEKEY(F2))
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(")") PORT_CODE(KEYCODE_PGDN) PORT_CHAR(')') PORT_CHAR(']')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("STOP") PORT_CODE(KEYCODE_F7) PORT_CHAR(UCHAR_MAMEKEY(F7))
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("INS") PORT_CODE(KEYCODE_INSERT)
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("NEW ALL") PORT_CODE(KEYCODE_ESC) PORT_CHAR(27)
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("BS") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("CLS") PORT_CODE(KEYCODE_DEL) PORT_CHAR(12)
PORT_START("KO7")
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("^") PORT_CODE(KEYCODE_3_PAD) PORT_CHAR('^')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("/") PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('}')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("(") PORT_CODE(KEYCODE_PGUP) PORT_CHAR('(') PORT_CHAR('[')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("9") PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR('\'')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("8") PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('_')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("7") PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('@')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("ENG") PORT_CODE(KEYCODE_F6) PORT_CHAR(UCHAR_MAMEKEY(F6))
PORT_START("KO8")
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("I") PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("*") PORT_CODE(KEYCODE_ASTERISK) PORT_CHAR('*') PORT_CHAR('{')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("6") PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('\\')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("5") PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('~')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("4") PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('|')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("P") PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("O") PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_START("KO9")
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("J") PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("+") PORT_CODE(KEYCODE_PLUS_PAD) PORT_CHAR('+')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("3") PORT_CODE(KEYCODE_3) PORT_CHAR('3')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("2") PORT_CODE(KEYCODE_2) PORT_CHAR('2')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("1") PORT_CODE(KEYCODE_1) PORT_CHAR('1')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("L") PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("K") PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_START("KO10")
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("SPACE") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("-") PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("EXE") PORT_CODE(KEYCODE_ENTER)
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("ANS") PORT_CODE(KEYCODE_END)
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(".") PORT_CODE(KEYCODE_STOP) PORT_CHAR('.')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("0") PORT_CODE(KEYCODE_0) PORT_CHAR('0')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("??") PORT_CODE(KEYCODE_5_PAD)
PORT_START("KO11")
PORT_BIT(0x0040, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("SHIFT") PORT_CODE(KEYCODE_LSHIFT) PORT_CHAR(UCHAR_SHIFT_1)
PORT_START("KO12")
PORT_BIT(0x0040, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("White F") PORT_CODE(KEYCODE_LALT)
//touchscreen
PORT_START("POSX")
PORT_BIT( 0xff, 0x00, IPT_MOUSE_X ) PORT_CROSSHAIR(X, 1, 0, 0) PORT_SENSITIVITY(20) PORT_KEYDELTA(0)
PORT_START("POSY")
PORT_BIT( 0xff, 0x00, IPT_MOUSE_Y ) PORT_CROSSHAIR(Y, 1, 0, 0) PORT_SENSITIVITY(120) PORT_KEYDELTA(0)
PORT_START("TOUCH")
PORT_BIT(0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_CODE(MOUSECODE_BUTTON1) PORT_NAME("Touchscreen")
INPUT_PORTS_END
static INPUT_PORTS_START( pb2000c )
PORT_START("KO0")
PORT_START("KO1")
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("BRK") PORT_CODE(KEYCODE_F10) PORT_CHAR(UCHAR_MAMEKEY(F10))
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("OFF") PORT_CODE(KEYCODE_7_PAD)
PORT_START("KO2")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("TAB") PORT_CODE(KEYCODE_TAB) PORT_CHAR(9)
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("'") PORT_CODE(KEYCODE_1_PAD) PORT_CHAR(39) PORT_CHAR('!')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("CAPS") PORT_CODE(KEYCODE_CAPSLOCK)
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Z") PORT_CODE(KEYCODE_Z) PORT_CHAR('Z')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("A") PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Q") PORT_CODE(KEYCODE_Q) PORT_CHAR('Q') PORT_CHAR('?')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("W") PORT_CODE(KEYCODE_W) PORT_CHAR('W') PORT_CHAR('@')
PORT_START("KO3")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("(") PORT_CODE(KEYCODE_PGUP) PORT_CHAR('(') PORT_CHAR('"')
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(")") PORT_CODE(KEYCODE_PGDN) PORT_CHAR(')') PORT_CHAR('#')
PORT_BIT(0x1000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("M1") PORT_CODE(KEYCODE_F1) PORT_CHAR(UCHAR_MAMEKEY(F1))
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("X") PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("C") PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("S") PORT_CODE(KEYCODE_S) PORT_CHAR('S')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("D") PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("E") PORT_CODE(KEYCODE_E) PORT_CHAR('E') PORT_CHAR('\\')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("R") PORT_CODE(KEYCODE_R) PORT_CHAR('R') PORT_CHAR('_')
PORT_START("KO4")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("[") PORT_CODE(KEYCODE_OPENBRACE) PORT_CHAR('[') PORT_CHAR('$')
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("]") PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR(']') PORT_CHAR('%')
PORT_BIT(0x1000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("M2") PORT_CODE(KEYCODE_F2) PORT_CHAR(UCHAR_MAMEKEY(F2))
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("V") PORT_CODE(KEYCODE_V) PORT_CHAR('V')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("B") PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("F") PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("G") PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("T") PORT_CODE(KEYCODE_T) PORT_CHAR('T') PORT_CHAR('`')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Y") PORT_CODE(KEYCODE_Y) PORT_CHAR('Y') PORT_CHAR('{')
PORT_START("KO5")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("|") PORT_CODE(KEYCODE_BACKSLASH) PORT_CHAR('|') PORT_CHAR('&')
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("MEMO") PORT_CODE(KEYCODE_F11) PORT_CHAR(UCHAR_MAMEKEY(F11))
PORT_BIT(0x1000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("M3") PORT_CODE(KEYCODE_F3) PORT_CHAR(UCHAR_MAMEKEY(F3))
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("N") PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("M") PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("H") PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("J") PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("U") PORT_CODE(KEYCODE_U) PORT_CHAR('U') PORT_CHAR('}')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("I") PORT_CODE(KEYCODE_I) PORT_CHAR('I') PORT_CHAR('~')
PORT_START("KO6")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("IN") PORT_CODE(KEYCODE_F6) PORT_CHAR(UCHAR_MAMEKEY(F6))
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("OUT") PORT_CODE(KEYCODE_F7) PORT_CHAR(UCHAR_MAMEKEY(F7))
PORT_BIT(0x1000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("M4") PORT_CODE(KEYCODE_F4) PORT_CHAR(UCHAR_MAMEKEY(F4))
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(",") PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("SPACE") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("K") PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("L") PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("O") PORT_CODE(KEYCODE_O) PORT_CHAR('O') PORT_CHAR('<')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("P") PORT_CODE(KEYCODE_P) PORT_CHAR('P') PORT_CHAR('>')
PORT_START("KO7")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("CALC") PORT_CODE(KEYCODE_HOME)
PORT_BIT(0x1000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("ETC") PORT_CODE(KEYCODE_F12) PORT_CHAR(UCHAR_MAMEKEY(F12))
PORT_BIT(0x0040, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("Red S") PORT_CODE(KEYCODE_LSHIFT) // PORT_CHAR(UCHAR_SHIFT_1) design of the computer breaks this
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("ANS") PORT_CODE(KEYCODE_END)
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(";") PORT_CODE(KEYCODE_COLON) PORT_CHAR(';')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(":") PORT_CODE(KEYCODE_BACKSLASH) PORT_CHAR(':')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("=") PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('=') PORT_CHAR('^')
PORT_START("KO8")
PORT_BIT(0x2000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("NEW ALL") PORT_CODE(KEYCODE_ESC) PORT_CHAR(27)
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("7") PORT_CODE(KEYCODE_7) PORT_CHAR('7')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("0") PORT_CODE(KEYCODE_0) PORT_CHAR('0')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("1") PORT_CODE(KEYCODE_1) PORT_CHAR('1')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("2") PORT_CODE(KEYCODE_2) PORT_CHAR('2')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("4") PORT_CODE(KEYCODE_4) PORT_CHAR('4')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("5") PORT_CODE(KEYCODE_5) PORT_CHAR('5')
PORT_START("KO9")
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("9") PORT_CODE(KEYCODE_9) PORT_CHAR('9')
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME(".") PORT_CODE(KEYCODE_STOP) PORT_CHAR('.')
PORT_BIT(0x0010, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("EXE") PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13)
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("3") PORT_CODE(KEYCODE_3) PORT_CHAR('3')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("+") PORT_CODE(KEYCODE_PLUS_PAD) PORT_CHAR('+')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("6") PORT_CODE(KEYCODE_6) PORT_CHAR('6')
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("-") PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-')
PORT_START("KO10")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("DEL") PORT_CODE(KEYCODE_F8) PORT_CHAR(UCHAR_MAMEKEY(F8))
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("MENU") PORT_CODE(KEYCODE_F5) PORT_CHAR(UCHAR_MAMEKEY(F5))
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("*") PORT_CODE(KEYCODE_ASTERISK) PORT_CHAR('*')
PORT_BIT(0x0008, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("BS") PORT_CODE(KEYCODE_BACKSPACE) PORT_CHAR(8)
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("/") PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/')
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("RIGHT") PORT_CODE(KEYCODE_RIGHT) PORT_CHAR(UCHAR_MAMEKEY(RIGHT))
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("CAL") PORT_CODE(KEYCODE_F9) PORT_CHAR(UCHAR_MAMEKEY(F9))
PORT_START("KO11")
PORT_BIT(0x8000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("INS") PORT_CODE(KEYCODE_INSERT)
PORT_BIT(0x4000, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("UP") PORT_CODE(KEYCODE_UP) PORT_CHAR(UCHAR_MAMEKEY(UP))
PORT_BIT(0x0080, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("8") PORT_CODE(KEYCODE_8) PORT_CHAR('8')
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("CLS") PORT_CODE(KEYCODE_DEL) PORT_CHAR(12)
PORT_BIT(0x0002, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("LEFT") PORT_CODE(KEYCODE_LEFT) PORT_CHAR(UCHAR_MAMEKEY(LEFT))
PORT_BIT(0x0001, IP_ACTIVE_HIGH, IPT_KEYBOARD) PORT_NAME("DOWN") PORT_CODE(KEYCODE_DOWN) PORT_CHAR(UCHAR_MAMEKEY(DOWN))
PORT_START("KO12")
INPUT_PORTS_END
void pb1000_state::pb1000_palette(palette_device &palette) const
{
palette.set_pen_color(0, rgb_t(138, 146, 148));
palette.set_pen_color(1, rgb_t(92, 83, 88));
}
static const gfx_layout pb1000_charlayout =
{
8, 8, /* 8 x 8 characters */
256, /* 256 characters */
1, /* 1 bits per pixel */
{ 0 }, /* no bitplanes */
{ 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8},
{ 0, 1, 2, 3, 4, 5, 6, 7},
8*8 /* 8 bytes */
};
static GFXDECODE_START( gfx_pb1000 )
GFXDECODE_ENTRY( "hd44352", 0x0000, pb1000_charlayout, 0, 1 )
GFXDECODE_END
void pb1000_state::gatearray_w(offs_t offset, uint16_t data)
{
m_gatearray[offset] = data&0xff;
if (m_gatearray[0] && m_card1 && m_card1_reg)
membank("bank1")->set_base(m_card1_reg->base());
else if (m_gatearray[1] && m_card2 && m_card2_reg)
membank("bank1")->set_base(m_card2_reg->base());
else
membank("bank1")->set_base(m_rom_reg->base());
}
uint16_t pb1000_state::read_touchscreen(uint8_t line)
{
uint8_t x = ioport("POSX")->read()/0x40;
uint8_t y = ioport("POSY")->read()/0x40;
if (ioport("TOUCH")->read())
{
if (x == line-7)
return (0x1000<<y);
}
return 0x0000;
}
uint16_t pb1000_state::pb1000_kb_r()
{
uint16_t data = 0;
u8 kb = m_kb_matrix & 15;
if (kb == 13)
{
//Read all the input lines
for (u8 line = 1; line < 13; line++)
{
data |= m_io_keyboard[line]->read();
data |= read_touchscreen(line);
}
}
else
if (kb < 13)
{
data = m_io_keyboard[kb]->read();
data |= read_touchscreen(kb);
}
return data;
}
uint16_t pb1000_state::pb2000c_kb_r()
{
uint16_t data = 0;
u8 kb = m_kb_matrix & 15;
if (kb == 13)
{
//Read all the input lines
for (u8 line = 1; line < 12; line++)
data |= m_io_keyboard[line]->read();
}
else
if (kb < 12)
data = m_io_keyboard[kb]->read();
return data;
}
void pb1000_state::kb_matrix_w(uint8_t data)
{
if (BIT(data, 7))
{
if (!BIT(m_kb_matrix, 7))
m_kb_timer->adjust(attotime::never, 0, attotime::never);
}
else
{
if (BIT(m_kb_matrix, 6) != BIT(data, 6))
{
if (BIT(data, 6))
m_kb_timer->adjust(attotime::from_hz(32), 0, attotime::from_hz(32));
else
m_kb_timer->adjust(attotime::from_hz(256), 0, attotime::from_hz(256));
}
}
m_kb_matrix = data;
}
uint8_t pb1000_state::pb1000_port_r()
{
//TODO
return 0x00;
}
uint8_t pb1000_state::pb2000c_port_r()
{
//TODO
return 0xfc;
}
void pb1000_state::port_w(uint8_t data)
{
m_beeper->set_state((BIT(data,7) ^ BIT(data,6)));
//printf("%x\n", data);
}
TIMER_CALLBACK_MEMBER(pb1000_state::keyboard_timer)
{
m_maincpu->set_input_line(HD61700_KEY_INT, ASSERT_LINE);
m_maincpu->set_input_line(HD61700_KEY_INT, CLEAR_LINE);
}
void pb1000_state::machine_start()
{
std::string region_tag;
m_rom_reg = memregion("rom");
if (m_card1)
m_card1_reg = memregion(region_tag.assign(m_card1->tag()).append(GENERIC_ROM_REGION_TAG).c_str());
if (m_card2)
m_card2_reg = memregion(region_tag.assign(m_card2->tag()).append(GENERIC_ROM_REGION_TAG).c_str());
membank("bank1")->set_base(m_rom_reg->base());
m_kb_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(pb1000_state::keyboard_timer),this));
m_kb_timer->adjust(attotime::from_hz(192), 0, attotime::from_hz(192));
}
void pb1000_state::pb1000(machine_config &config)
{
/* basic machine hardware */
HD61700(config, m_maincpu, 910000);
m_maincpu->set_addrmap(AS_PROGRAM, &pb1000_state::pb1000_mem);
m_maincpu->lcd_ctrl().set(m_hd44352, FUNC(hd44352_device::control_write));
m_maincpu->lcd_read().set(m_hd44352, FUNC(hd44352_device::data_read));
m_maincpu->lcd_write().set(m_hd44352, FUNC(hd44352_device::data_write));
m_maincpu->kb_read().set(FUNC(pb1000_state::pb1000_kb_r));
m_maincpu->kb_write().set(FUNC(pb1000_state::kb_matrix_w));
m_maincpu->port_read().set(FUNC(pb1000_state::pb1000_port_r));
m_maincpu->port_write().set(FUNC(pb1000_state::port_w));
/* video hardware */
screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_LCD));
screen.set_refresh_hz(50);
screen.set_vblank_time(ATTOSECONDS_IN_USEC(2500)); /* not accurate */
screen.set_screen_update("hd44352", FUNC(hd44352_device::screen_update));
screen.set_size(192, 32);
screen.set_visarea(0, 192-1, 0, 32-1);
screen.set_palette("palette");
PALETTE(config, "palette", FUNC(pb1000_state::pb1000_palette), 2);
GFXDECODE(config, "gfxdecode", "palette", gfx_pb1000);
HD44352(config, m_hd44352, 910000);
m_hd44352->on_cb().set_inputline("maincpu", HD61700_ON_INT);
NVRAM(config, "nvram1", nvram_device::DEFAULT_ALL_0);
NVRAM(config, "nvram2", nvram_device::DEFAULT_ALL_0);
/* sound hardware */
SPEAKER(config, "mono").front_center();
BEEP(config, m_beeper, 3250).add_route(ALL_OUTPUTS, "mono", 1.00);
}
void pb1000_state::pb2000c(machine_config &config)
{
pb1000(config);
/* basic machine hardware */
m_maincpu->set_addrmap(AS_PROGRAM, &pb1000_state::pb2000c_mem);
m_maincpu->kb_read().set(FUNC(pb1000_state::pb2000c_kb_r));
m_maincpu->port_read().set(FUNC(pb1000_state::pb2000c_port_r));
GENERIC_CARTSLOT(config, m_card1, generic_plain_slot, "pb2000c_card");
GENERIC_CARTSLOT(config, m_card2, generic_plain_slot, "pb2000c_card");
/* Software lists */
SOFTWARE_LIST(config, "card_list").set_original("pb2000c");
}
/* ROM definition */
ROM_START( pb1000 )
ROM_REGION( 0x30000, "maincpu", ROMREGION_ERASEFF )
ROM_LOAD( "hd61700.bin", 0x0000, 0x1800, CRC(b28c21a3) SHA1(be7ea62a15ff0c612f6efb2c95e6c2a11a738423))
ROM_REGION( 0x10000, "rom", ROMREGION_ERASE )
ROM_SYSTEM_BIOS(0, "basic", "BASIC")
ROMX_LOAD( "pb1000.bin", 0x0000, 0x8000, CRC(8127a090) SHA1(067c1c2e7efb5249e95afa7805bb98543b30b630), ROM_BIOS(0) | ROM_SKIP(1))
ROM_SYSTEM_BIOS(1, "basicj", "BASIC Jap")
ROMX_LOAD( "pb1000j.bin", 0x0000, 0x8000, CRC(14a0df57) SHA1(ab47bb54eb2a24dcd9d2663462e9272d974fa7da), ROM_BIOS(1) | ROM_SKIP(1))
ROM_REGION( 0x0800, "hd44352", 0 )
ROM_LOAD( "charset.bin", 0x0000, 0x0800, CRC(7f144716) SHA1(a02f1ecc6dc0ac55b94f00931d8f5cb6b9ffb7b4))
ROM_END
ROM_START( pb2000c )
ROM_REGION( 0x1800, "maincpu", ROMREGION_ERASEFF )
ROM_LOAD( "hd61700.bin", 0x0000, 0x1800, CRC(25f9540c) SHA1(ecf98efadbdd4d1a74bc183eaf23f7113f2a12b1))
ROM_REGION( 0x20000, "rom", ROMREGION_ERASE )
ROMX_LOAD( "pb2000c.bin", 0x0000, 0x10000, CRC(41933631) SHA1(70b654dc375b647afa042baf8b0a139e7fa604e8), ROM_SKIP(1))
ROM_REGION( 0x0800, "hd44352", 0 )
ROM_LOAD( "charset.bin", 0x0000, 0x0800, CRC(7f144716) SHA1(a02f1ecc6dc0ac55b94f00931d8f5cb6b9ffb7b4))
ROM_END
ROM_START( ai1000 )
ROM_REGION( 0x1800, "maincpu", ROMREGION_ERASEFF )
ROM_LOAD( "hd61700.bin", 0x0000, 0x1800, CRC(25f9540c) SHA1(ecf98efadbdd4d1a74bc183eaf23f7113f2a12b1))
ROM_REGION( 0x20000, "rom", ROMREGION_ERASE )
ROMX_LOAD( "ai1000.bin", 0x0000, 0x10000, CRC(72aa3ee3) SHA1(ed1d0bc470902ea73bc4588147a589b1793afb40), ROM_SKIP(1))
ROM_REGION( 0x0800, "hd44352", 0 )
ROM_LOAD( "charset.bin", 0x0000, 0x0800, CRC(7f144716) SHA1(a02f1ecc6dc0ac55b94f00931d8f5cb6b9ffb7b4))
ROM_END
/* Driver */
/* YEAR NAME PARENT COMPAT MACHINE INPUT CLASS INIT COMPANY FULLNAME FLAGS */
COMP( 1987, pb1000, 0, 0, pb1000, pb1000, pb1000_state, empty_init, "Casio", "PB-1000", MACHINE_NOT_WORKING)
COMP( 1989, pb2000c, 0, 0, pb2000c, pb2000c, pb1000_state, empty_init, "Casio", "PB-2000c", MACHINE_NOT_WORKING)
COMP( 1989, ai1000, pb2000c, 0, pb2000c, pb2000c, pb1000_state, empty_init, "Casio", "AI-1000", MACHINE_NOT_WORKING)
|
dennisnderitu254/Hackerrank-Algorithms
|
Strings/SherlockAndValidString.java
|
package Strings;
import java.util.*;
import java.io.*;
/*
* @author -- rajatgoyal715
*/
public class SherlockAndValidString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char s[] = sc.nextLine().toCharArray();
int c[] = new int[26];
for(char i : s){
c[i-97]++;
}
int temp = c[0];
int great = 0;
int small = 0;
int greater = 0;
int smaller = 0;
int diffg=0;
int diffs=0;
int check=0;
int diff1 = Math.abs(c[1]-c[0]);
int diff2 = diff1;
for(int i=0;i<26;i++){
if(c[i]!=0){
if(c[i]>temp){
great++;
greater = greater + c[i];
diffg = c[i]-temp;
if(diffg>diff1){
diff1 = diffg;
}
}
if(c[i]<temp){
small++;
check = c[i];
smaller = smaller + c[i];
diffs = temp - c[i];
if(diffs>diff2){
diff2 = diffs;
}
}
}
}
int valid=0;
if(small==1&&check==1)
valid=1;
else if(diff1>1||diff2>1)
valid=0;
else if(great==1&&diffg==1)
valid=1;
else if(small==1&&diffs==1)
valid=1;
else if((greater==s.length-c[0]&&diff1==1)||(smaller==s.length-c[0]&&diff2==1))
valid=1;
else if(small==0&&great==0)
valid = 1;
else
valid=0;
if(valid==1)
System.out.println("YES");
else
System.out.println("NO");
}
}
|
lovecrossyou/Puzzle
|
ios/Module/Discover/FreeBuy/View/FBPublicListCell.h
|
//
// FBPublicListCell.h
// Puzzle
//
// Created by huibei on 16/12/14.
// Copyright © 2016年 HuiBei. All rights reserved.
//
#import <UIKit/UIKit.h>
#define NOTIFICATION_TIME_CELL @"NotificationTimeCell"
@interface FBPublicListCell : UITableViewCell
// 获取table view cell 的indexPath
@property (nonatomic, weak) NSIndexPath *m_indexPath;
@property (nonatomic) BOOL m_isDisplayed;
- (void)loadData:(id)data indexPath:(NSIndexPath *)indexPath;
@end
|
Szturmowiec/agent-based-simulation
|
mock/src/main/scala/pl.edu.agh.mock/model/Mock.scala
|
package pl.edu.agh.mock.model
import pl.edu.agh.mock.config.MockConfig
import pl.edu.agh.xinuk.config.XinukConfig
import pl.edu.agh.xinuk.model.{CellContents, Signal, SignalMap}
case object Mock extends CellContents {
override def generateSignal(iteration: Long)(implicit config: XinukConfig): Signal = config.asInstanceOf[MockConfig].mockInitialSignal
}
|
xeren/Dat3M
|
dartagnan/src/main/java/com/dat3m/dartagnan/program/Register.java
|
package com.dat3m.dartagnan.program;
import com.google.common.collect.ImmutableSet;
import com.microsoft.z3.Context;
import com.microsoft.z3.Expr;
import com.microsoft.z3.Model;
import com.dat3m.dartagnan.expression.ExprInterface;
import com.dat3m.dartagnan.expression.IConst;
import com.dat3m.dartagnan.expression.IExpr;
import com.dat3m.dartagnan.program.event.Event;
public class Register extends IExpr implements ExprInterface {
private static int dummyCount = 0;
private final String name;
private String cVar;
private final int threadId;
private final int precision;
public Register(String name, int threadId, int precision) {
if(name == null){
name = "DUMMY_REG_" + dummyCount++;
}
this.name = name;
this.threadId = threadId;
this.precision = precision;
}
public String getName() {
return name;
}
public String getCVar() {
return cVar;
}
public void setCVar(String name) {
this.cVar = name;
}
public int getThreadId(){
return threadId;
}
@Override
public String toString() {
return name;
}
@Override
public int hashCode(){
return (name.hashCode() << 8) + threadId;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
Register rObj = (Register) obj;
return name.equals(rObj.name) && threadId == rObj.threadId;
}
@Override
public Expr toZ3Int(Event e, Context ctx) {
String name = getName() + "(" + e.repr() + ")";
return precision > 0 ? ctx.mkBVConst(name, precision) : ctx.mkIntConst(name);
}
public Expr toZ3IntResult(Event e, Context ctx) {
String name = getName() + "(" + e.repr() + "_result)";
return precision > 0 ? ctx.mkBVConst(name, precision) : ctx.mkIntConst(name);
}
@Override
public ImmutableSet<Register> getRegs() {
return ImmutableSet.of(this);
}
@Override
public Expr getLastValueExpr(Context ctx){
return precision > 0 ? ctx.mkBVConst(getName() + "_" + threadId + "_final", precision) : ctx.mkIntConst(getName() + "_" + threadId + "_final");
}
@Override
public int getIntValue(Event e, Model model, Context ctx){
return Integer.parseInt(model.getConstInterp(toZ3Int(e, ctx)).toString());
}
@Override
public IConst reduce() {
throw new UnsupportedOperationException("Reduce not supported for " + this);
}
@Override
public int getPrecision() {
return precision;
}
}
|
KaterinaPetrova87/SoftUniProgrammingBasicsJava
|
6.DrawingFiguresWithLoops/src/p09_House.java
|
<gh_stars>0
import java.util.Scanner;
public class p09_House {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int startAsteriskCount = 0;
int dishesCount = 0;
if (n % 2 == 0) {
startAsteriskCount = 2;
dishesCount = (n - 2) / 2;
System.out.println(repeatString("-", dishesCount)
+ repeatString("*", startAsteriskCount) + repeatString("-", dishesCount));
for (int i = 1; i < (n + 1) / 2; i++) {
startAsteriskCount += 2;
dishesCount -= 1;
System.out.println(repeatString("-", dishesCount) + repeatString("*", startAsteriskCount)
+ repeatString("-", dishesCount));
}
for (int i = 1; i <= n / 2; i++) {
System.out.println("|" + repeatString("*", n - 2) + "|");
}
} else {
startAsteriskCount = 1;
dishesCount = (n - 1) / 2;
System.out.println(repeatString("-", dishesCount) + repeatString("*", startAsteriskCount)
+ repeatString("-", dishesCount));
for (int i = 1; i < (n + 1) / 2; i++) {
startAsteriskCount += 2;
dishesCount -= 1;
System.out.println(repeatString("-", dishesCount) + repeatString("*", startAsteriskCount)
+ repeatString("-", dishesCount));
}
for (int i = 1; i <= n / 2; i++) {
System.out.println("|" + repeatString("*", n - 2) + "|");
}
}
}
public static String repeatString(String text, int repeatCount) {
String result = "";
for (int i = 0; i < repeatCount; i++) {
result += text;
}
return result;
}
}
|
leha-bot/eve
|
include/eve/module/real/core/function/saturated/generic/minmag.hpp
|
<reponame>leha-bot/eve
//==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/concept/compatible.hpp>
#include <eve/concept/value.hpp>
#include <eve/detail/apply_over.hpp>
#include <eve/detail/implementation.hpp>
#include <eve/detail/skeleton_calls.hpp>
#include <eve/function/if_else.hpp>
#include <eve/function/is_nan.hpp>
#include <eve/function/is_not_greater_equal.hpp>
#include <eve/function/saturated/abs.hpp>
#include <eve/function/min.hpp>
#include <eve/function/saturated.hpp>
namespace eve::detail
{
template<real_value T, real_value U>
EVE_FORCEINLINE auto minmag_(EVE_SUPPORTS(cpu_), saturated_type const &, T const &a, U const &b) noexcept
requires compatible_values<T, U>
{
return arithmetic_call(saturated(minmag), a, b);
}
template<real_value T>
EVE_FORCEINLINE auto minmag_(EVE_SUPPORTS(cpu_), saturated_type const &, T const &a, T const &b) noexcept
{
auto aa = saturated(eve::abs)(a);
auto bb = saturated(eve::abs)(b);
if constexpr( simd_value<T> )
{
auto tmp = if_else(is_not_greater_equal(bb, aa), b, eve::min(a, b));
return if_else(is_not_greater_equal(aa, bb), a, tmp);
}
else
{
return aa < bb ? a : bb < aa ? b : eve::min(a, b);
}
}
}
|
emil-wcislo/sbql4j8
|
sbql4j8/src/test/openjdk/tools/javac/annotations/typeAnnotations/newlocations/MethodReturnType.java
|
/*
* Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.lang.annotation.*;
/*
* @test
* @bug 6843077 8006775
* @summary new type annotation location: method return type array/generics
* @author <NAME>
* @compile MethodReturnType.java
*/
class DefaultScope {
Parameterized<String, String> unannotated() { return null; }
Parameterized<@A String, String> firstTypeArg() { return null; }
Parameterized<String, @A String> secondTypeArg() { return null; }
Parameterized<@A String, @B String> bothTypeArgs() { return null; }
Parameterized<@A Parameterized<@A String, @B String>, @B String>
nestedParameterized() { return null; }
public <T> @A String method() { return null; }
@A String [] array1() { return null; }
@A String @B [] array1Deep() { return null; }
@A String [] [] array2() { return null; }
@A String @A [] @B [] array2Deep() { return null; }
String @A [] [] array2First() { return null; }
String [] @B [] array2Second() { return null; }
// Old-style array syntax
String array2FirstOld() @A [] { return null; }
String array2SecondOld() [] @B [] { return null; }
}
class ModifiedScoped {
public final Parameterized<String, String> unannotated() { return null; }
public final Parameterized<@A String, String> firstTypeArg() { return null; }
public final Parameterized<String, @A String> secondTypeArg() { return null; }
public final Parameterized<@A String, @B String> bothTypeArgs() { return null; }
public final Parameterized<@A Parameterized<@A String, @B String>, @B String>
nestedParameterized() { return null; }
public final @A String [] array1() { return null; }
public final @A String @B [] array1Deep() { return null; }
public final @A String [] [] array2() { return null; }
public final @A String @A [] @B [] array2Deep() { return null; }
public final String @A [] [] array2First() { return null; }
public final String [] @B [] array2Second() { return null; }
}
class Parameterized<K, V> { }
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
@interface A { }
@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
@interface B { }
|
OlegPt/spark
|
sql/core/src/main/java/org/apache/spark/sql/connector/read/V1Scan.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.sql.connector.read;
import org.apache.spark.annotation.Unstable;
import org.apache.spark.sql.SQLContext;
import org.apache.spark.sql.sources.BaseRelation;
import org.apache.spark.sql.sources.TableScan;
/**
* A trait that should be implemented by V1 DataSources that would like to leverage the DataSource
* V2 read code paths.
*
* This interface is designed to provide Spark DataSources time to migrate to DataSource V2 and
* will be removed in a future Spark release.
*
* @since 3.0.0
*/
@Unstable
public interface V1Scan extends Scan {
/**
* Create an `BaseRelation` with `TableScan` that can scan data from DataSource v1 to RDD[Row].
*
* @since 3.0.0
*/
<T extends BaseRelation & TableScan> T toV1TableScan(SQLContext context);
}
|
richardcbrown/PulseTile-RA
|
src/core/dataProviders/dataProvider.js
|
import get from "lodash/get";
import moment from "moment";
import {
fetchUtils,
GET_LIST,
GET_ONE,
GET_MANY,
GET_MANY_REFERENCE,
CREATE,
UPDATE,
UPDATE_MANY,
DELETE,
DELETE_MANY,
HttpError,
} from "react-admin";
import sort, { ASC, DESC } from 'sort-array-objects';
import pluginFilters from "../config/pluginFilters";
import { token, domainName } from "../token";
import dummyPatients from "../pages/PatientsList/dummyPatients";
import { httpErrorAction } from '../actions/httpErrorAction';
const apiPatientsUser = 'api/patients';
const patientID = localStorage.getItem('patientId') ? localStorage.getItem('patientId') : localStorage.getItem('userId');
/**
* This constant prepare data for requests (URL and options)
*
* @author <NAME> <<EMAIL>>
* @param {shape} type
* @param {string} resource
* @param {shape} params
*/
const convertDataRequestToHTTP = (type, resource, params) => {
let url = "";
const options = {};
switch (type) {
case GET_LIST: {
if (resource === 'patients') {
url = `${domainName}/api/${resource}`;
} else {
url = `${domainName}/${apiPatientsUser}/${patientID}/${resource}`;
}
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
options.headers = {
Authorization: "Bearer " + token,
'X-Requested-With': "XMLHttpRequest",
};
break;
}
case GET_ONE:
url = `${domainName}/${apiPatientsUser}/${patientID}/${resource}/${params.id}`;
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
options.headers = {
Authorization: "Bearer " + token,
'X-Requested-With': "XMLHttpRequest",
};
break;
case UPDATE:
let data = Object.assign({userId: patientID}, params.data);
url = `${domainName}/${apiPatientsUser}/${patientID}/${resource}/${params.id}`;
options.method = "PUT";
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
options.headers = {
Authorization: "Bearer " + token,
'Content-Type': 'application/json',
'X-Requested-With': "XMLHttpRequest",
};
options.body = JSON.stringify(data);
break;
case CREATE:
data = Object.assign({userId: patientID}, params.data);
url = `${domainName}/${apiPatientsUser}/${patientID}/${resource}`;
options.method = "POST";
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
options.headers = {
Authorization: "Bearer " + token,
'Content-Type': 'application/json',
'X-Requested-With': "XMLHttpRequest",
};
options.body = JSON.stringify(params.data);
break;
default:
throw new Error(`Unsupported fetch action type ${type}`);
}
return { url, options };
};
/**
* This function filters patients list by department
*
* @author <NAME> <<EMAIL>>
* @param {shape} response
* @param {shape} params
* @return {Array}
*/
function getPatientsList(response, params) {
const departmentsArray = ["CommunityCare", "Hospital", "MentalHealth", "Neighbourhood", "PrimaryCare"];
const ageArray = ["first", "second", "third", "fourth"];
const ageLimits = {
first: { min: 19, max: 30 },
second: { min: 31, max: 60 },
third: { min: 61, max: 80 },
fourth: { min: 81, max: 100 },
};
const filter = get(params, 'sort.field', null);
let results = [];
if (departmentsArray.indexOf(filter) !== -1) {
results = Object.values(response).filter(item => {
let filterWithSpaces = filter
.replace(/([A-Z])/g, ' $1')
.replace(/^./, function(str){ return str.toUpperCase(); })
.trim();
return (item.department === filterWithSpaces);
});
} else if (ageArray.indexOf(filter) !== -1) {
const currentDate = new Date().getTime();
const endDate = new moment(currentDate);
results = Object.values(response).filter(item => {
let birthDate = get(item, 'dateOfBirth', null);
let startDate = new moment(birthDate);
let duration = moment.duration(endDate.diff(startDate)).get('year');
return (duration > ageLimits[filter].min && duration < ageLimits[filter].max);
})
} else {
results = Object.values(response).map(item => {
return Object.assign({id: item.sourceId}, item);
});
}
return results;
}
/**
* This function extracts results from response
*
* @author <NAME> <<EMAIL>>
* @param {string} resource
* @param {shape} response
* @param {shape} params
* @return {array}
*/
function getResultsFromResponse(resource, response, params) {
let results = [];
if (resource !== 'patients') {
results = response.map((item, id) => {
return Object.assign({id: item.sourceId}, item);
});
} else {
results = getPatientsList(response, params);
}
return results;
}
/**
* This function cheks is current item consider to filter condition
*
* @author <NAME> <<EMAIL>>
* @param {shape} item
* @param {shape} filters
* @param {string} filterText
* @return {boolean}
*/
function isItemConsider(item, filters, filterText) {
let result = false;
filters.forEach(filterItem => {
let string = item[filterItem];
if (String(string).toLowerCase().search(filterText) >= 0) {
result = true;
}
});
return result;
}
/**
* This function filters response array
*
* @author <NAME> <<EMAIL>>
* @param {string} resource
* @param {array} results
* @param {shape} params
* @return {array}
*/
function getFilterResults(resource, results, params) {
const filterText = get(params, 'filter.filterText', null);
const filters = pluginFilters[resource];
return !filterText ? results : results.filter(item => isItemConsider(item, filters, filterText));
}
/**
* This function sorts response array
*
* @author <NAME> <<EMAIL>>
* @param {array} results
* @param {shape} params
* @return {array}
*/
function getSortedResults(results, params) {
const sortField = get(params, 'sort.field', null);
const sortOrder = (get(params, 'sort.order', null) === 'DESC') ? DESC : ASC;
return sort(results, [sortField], sortOrder);
}
/**
* This constant handle response data
*
* @author <NAME> <<EMAIL>>
* @param {shape} response
* @param {shape} type
* @param {string} resource
* @param {shape} params
*/
const convertHTTPResponse = (response, type, resource, params) => {
switch (type) {
case GET_LIST:
const pageNumber = get(params, 'pagination.page', 1);
const numberPerPage = get(params, 'pagination.perPage', 10);
const results = getResultsFromResponse(resource, response, params);
const resultsFiltering = getFilterResults(resource, results, params);
const resultsSorting = getSortedResults(resultsFiltering, params);
const startItem = (pageNumber - 1) * numberPerPage;
const endItem = pageNumber * numberPerPage;
const paginationResults = resultsSorting.slice(startItem, endItem);
return {
data: paginationResults,
total: resultsSorting.length,
};
case GET_ONE:
return {
data: Object.assign({id: response.sourceId}, response),
};
case UPDATE:
return params;
case CREATE:
const dataFromRequest = get(params, 'data', null);
const compositionUid = get(response, 'compositionUid', null);
let sourceID = '';
if (compositionUid) {
const compositionUidArray = compositionUid.split('::');
sourceID = compositionUidArray[0];
}
dataFromRequest.id = get(response, 'host', null) + '-' + sourceID;
if (!get(params, 'source', null)) {
dataFromRequest.source = 'ethercis';
}
return {
data: dataFromRequest,
};
default:
return { data: 'No results' };
}
};
const dataProvider = (type, resource, params) => {
let { url, options } = convertDataRequestToHTTP(type, resource, params);
let responseInfo = '';
return fetch(url, options).then(response => {
responseInfo = get(response, 'status', null);
return response.json();
})
.then(res => {
if (responseInfo !== 200) {
responseInfo += '|' + get(res, 'error', null);
throw new HttpError(responseInfo);
}
return convertHTTPResponse(res, type, resource, params)
})
.catch(err => {
console.log('Error: ', err);
throw new Error(err);
});
};
const fakePatientsProvider = (type, resource, params) => {
switch (type) {
case GET_LIST:
const pageNumber = get(params, 'pagination.page', 1);
const numberPerPage = get(params, 'pagination.perPage', 10);
const results = getResultsFromResponse(resource, dummyPatients, params);
const resultsFiltering = getFilterResults(resource, results, params);
const resultsSorting = getSortedResults(resultsFiltering, params);
const startItem = (pageNumber - 1) * numberPerPage;
const endItem = pageNumber * numberPerPage;
const paginationResults = resultsSorting.slice(startItem, endItem);
return {
data: paginationResults,
total: resultsSorting.length,
};
case GET_ONE:
case UPDATE:
let response = {};
for (let i = 0, n = dummyPatients.length; i < n; i++) {
let item = dummyPatients[i];
if (item.id === params.id) {
response = item;
break;
}
}
return {
data: Object.assign({id: params.id}, response),
};
case CREATE:
return {
data: Object.assign({id: params.data.nhsNumber}, params.data)
};
default:
return { data: 'No results' };
}
};
/**
* This function provides requests/response to server
*
* @author <NAME> <<EMAIL>>
* @param {shape} type
* @param {string} resource
* @param {shape} params
*/
export default (type, resource, params) => {
if (resource === `patients`) {
return fakePatientsProvider(type, resource, params);
}
return dataProvider(type, resource, params);
};
|
Mu-L/kotlin
|
build-common/test/org/jetbrains/kotlin/library/metadata/DebugKlibMetadataProtoBuf.java
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: compiler/util-klib-metadata/src/KlibMetadataProtoBuf.debug.proto
package org.jetbrains.kotlin.library.metadata;
public final class DebugKlibMetadataProtoBuf {
private DebugKlibMetadataProtoBuf() {}
public static void registerAllExtensions(
org.jetbrains.kotlin.protobuf.ExtensionRegistry registry) {
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.packageFqName);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.classAnnotation);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.classFile);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.classKdoc);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.classUniqId);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.constructorAnnotation);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.constructorKdoc);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.constructorUniqId);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.functionAnnotation);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.functionFile);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.functionKdoc);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.functionUniqId);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.propertyAnnotation);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.propertyGetterAnnotation);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.propertySetterAnnotation);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.compileTimeValue);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.propertyFile);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.propertyKdoc);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.propertyUniqId);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.enumEntryAnnotation);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.enumEntryOrdinal);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.enumEntryUniqId);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.parameterAnnotation);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.typeAnnotation);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.typeParameterAnnotation);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.typeParamUniqId);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.packageFragmentFiles);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.isEmpty);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.fqName);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.className);
registry.add(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.typeAliasUniqId);
}
public interface HeaderOrBuilder extends
// @@protoc_insertion_point(interface_extends:org.jetbrains.kotlin.library.metadata.Header)
org.jetbrains.kotlin.protobuf.MessageOrBuilder {
/**
* <code>required string module_name = 1;</code>
*/
boolean hasModuleName();
/**
* <code>required string module_name = 1;</code>
*/
java.lang.String getModuleName();
/**
* <code>required string module_name = 1;</code>
*/
org.jetbrains.kotlin.protobuf.ByteString
getModuleNameBytes();
/**
* <code>optional int32 flags = 2;</code>
*
* <pre>
*0x1 = preRelease
* </pre>
*/
boolean hasFlags();
/**
* <code>optional int32 flags = 2;</code>
*
* <pre>
*0x1 = preRelease
* </pre>
*/
int getFlags();
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
boolean hasStrings();
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable getStrings();
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTableOrBuilder getStringsOrBuilder();
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
boolean hasQualifiedNames();
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable getQualifiedNames();
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTableOrBuilder getQualifiedNamesOrBuilder();
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>
getAnnotationList();
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation getAnnotation(int index);
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
int getAnnotationCount();
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
java.util.List<? extends org.jetbrains.kotlin.metadata.DebugProtoBuf.AnnotationOrBuilder>
getAnnotationOrBuilderList();
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
org.jetbrains.kotlin.metadata.DebugProtoBuf.AnnotationOrBuilder getAnnotationOrBuilder(
int index);
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
org.jetbrains.kotlin.protobuf.ProtocolStringList
getPackageFragmentNameList();
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
int getPackageFragmentNameCount();
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
java.lang.String getPackageFragmentName(int index);
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
org.jetbrains.kotlin.protobuf.ByteString
getPackageFragmentNameBytes(int index);
/**
* <code>repeated string empty_package = 8;</code>
*/
org.jetbrains.kotlin.protobuf.ProtocolStringList
getEmptyPackageList();
/**
* <code>repeated string empty_package = 8;</code>
*/
int getEmptyPackageCount();
/**
* <code>repeated string empty_package = 8;</code>
*/
java.lang.String getEmptyPackage(int index);
/**
* <code>repeated string empty_package = 8;</code>
*/
org.jetbrains.kotlin.protobuf.ByteString
getEmptyPackageBytes(int index);
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
java.util.List<org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File>
getFileList();
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File getFile(int index);
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
int getFileCount();
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
java.util.List<? extends org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.FileOrBuilder>
getFileOrBuilderList();
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.FileOrBuilder getFileOrBuilder(
int index);
}
/**
* Protobuf type {@code org.jetbrains.kotlin.library.metadata.Header}
*/
public static final class Header extends
org.jetbrains.kotlin.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:org.jetbrains.kotlin.library.metadata.Header)
HeaderOrBuilder {
// Use Header.newBuilder() to construct.
private Header(org.jetbrains.kotlin.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private Header(boolean noInit) { this.unknownFields = org.jetbrains.kotlin.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final Header defaultInstance;
public static Header getDefaultInstance() {
return defaultInstance;
}
public Header getDefaultInstanceForType() {
return defaultInstance;
}
private final org.jetbrains.kotlin.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final org.jetbrains.kotlin.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Header(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
org.jetbrains.kotlin.protobuf.UnknownFieldSet.Builder unknownFields =
org.jetbrains.kotlin.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
org.jetbrains.kotlin.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000001;
moduleName_ = bs;
break;
}
case 16: {
bitField0_ |= 0x00000002;
flags_ = input.readInt32();
break;
}
case 34: {
org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.Builder subBuilder = null;
if (((bitField0_ & 0x00000004) == 0x00000004)) {
subBuilder = strings_.toBuilder();
}
strings_ = input.readMessage(org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.PARSER, extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(strings_);
strings_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000004;
break;
}
case 42: {
org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.Builder subBuilder = null;
if (((bitField0_ & 0x00000008) == 0x00000008)) {
subBuilder = qualifiedNames_.toBuilder();
}
qualifiedNames_ = input.readMessage(org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.PARSER, extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(qualifiedNames_);
qualifiedNames_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000008;
break;
}
case 50: {
if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) {
annotation_ = new java.util.ArrayList<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>();
mutable_bitField0_ |= 0x00000010;
}
annotation_.add(input.readMessage(org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.PARSER, extensionRegistry));
break;
}
case 58: {
org.jetbrains.kotlin.protobuf.ByteString bs = input.readBytes();
if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) {
packageFragmentName_ = new org.jetbrains.kotlin.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000020;
}
packageFragmentName_.add(bs);
break;
}
case 66: {
org.jetbrains.kotlin.protobuf.ByteString bs = input.readBytes();
if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) {
emptyPackage_ = new org.jetbrains.kotlin.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000040;
}
emptyPackage_.add(bs);
break;
}
case 74: {
if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) {
file_ = new java.util.ArrayList<org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File>();
mutable_bitField0_ |= 0x00000080;
}
file_.add(input.readMessage(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.PARSER, extensionRegistry));
break;
}
}
}
} catch (org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000010) == 0x00000010)) {
annotation_ = java.util.Collections.unmodifiableList(annotation_);
}
if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) {
packageFragmentName_ = packageFragmentName_.getUnmodifiableView();
}
if (((mutable_bitField0_ & 0x00000040) == 0x00000040)) {
emptyPackage_ = emptyPackage_.getUnmodifiableView();
}
if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) {
file_ = java.util.Collections.unmodifiableList(file_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_Header_descriptor;
}
protected org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_Header_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header.class, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header.Builder.class);
}
public static org.jetbrains.kotlin.protobuf.Parser<Header> PARSER =
new org.jetbrains.kotlin.protobuf.AbstractParser<Header>() {
public Header parsePartialFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return new Header(input, extensionRegistry);
}
};
@java.lang.Override
public org.jetbrains.kotlin.protobuf.Parser<Header> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int MODULE_NAME_FIELD_NUMBER = 1;
private java.lang.Object moduleName_;
/**
* <code>required string module_name = 1;</code>
*/
public boolean hasModuleName() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string module_name = 1;</code>
*/
public java.lang.String getModuleName() {
java.lang.Object ref = moduleName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
org.jetbrains.kotlin.protobuf.ByteString bs =
(org.jetbrains.kotlin.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
moduleName_ = s;
}
return s;
}
}
/**
* <code>required string module_name = 1;</code>
*/
public org.jetbrains.kotlin.protobuf.ByteString
getModuleNameBytes() {
java.lang.Object ref = moduleName_;
if (ref instanceof java.lang.String) {
org.jetbrains.kotlin.protobuf.ByteString b =
org.jetbrains.kotlin.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
moduleName_ = b;
return b;
} else {
return (org.jetbrains.kotlin.protobuf.ByteString) ref;
}
}
public static final int FLAGS_FIELD_NUMBER = 2;
private int flags_;
/**
* <code>optional int32 flags = 2;</code>
*
* <pre>
*0x1 = preRelease
* </pre>
*/
public boolean hasFlags() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional int32 flags = 2;</code>
*
* <pre>
*0x1 = preRelease
* </pre>
*/
public int getFlags() {
return flags_;
}
public static final int STRINGS_FIELD_NUMBER = 4;
private org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable strings_;
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public boolean hasStrings() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable getStrings() {
return strings_;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTableOrBuilder getStringsOrBuilder() {
return strings_;
}
public static final int QUALIFIED_NAMES_FIELD_NUMBER = 5;
private org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable qualifiedNames_;
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public boolean hasQualifiedNames() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable getQualifiedNames() {
return qualifiedNames_;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTableOrBuilder getQualifiedNamesOrBuilder() {
return qualifiedNames_;
}
public static final int ANNOTATION_FIELD_NUMBER = 6;
private java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation> annotation_;
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation> getAnnotationList() {
return annotation_;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public java.util.List<? extends org.jetbrains.kotlin.metadata.DebugProtoBuf.AnnotationOrBuilder>
getAnnotationOrBuilderList() {
return annotation_;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public int getAnnotationCount() {
return annotation_.size();
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation getAnnotation(int index) {
return annotation_.get(index);
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.AnnotationOrBuilder getAnnotationOrBuilder(
int index) {
return annotation_.get(index);
}
public static final int PACKAGE_FRAGMENT_NAME_FIELD_NUMBER = 7;
private org.jetbrains.kotlin.protobuf.LazyStringList packageFragmentName_;
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public org.jetbrains.kotlin.protobuf.ProtocolStringList
getPackageFragmentNameList() {
return packageFragmentName_;
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public int getPackageFragmentNameCount() {
return packageFragmentName_.size();
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public java.lang.String getPackageFragmentName(int index) {
return packageFragmentName_.get(index);
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public org.jetbrains.kotlin.protobuf.ByteString
getPackageFragmentNameBytes(int index) {
return packageFragmentName_.getByteString(index);
}
public static final int EMPTY_PACKAGE_FIELD_NUMBER = 8;
private org.jetbrains.kotlin.protobuf.LazyStringList emptyPackage_;
/**
* <code>repeated string empty_package = 8;</code>
*/
public org.jetbrains.kotlin.protobuf.ProtocolStringList
getEmptyPackageList() {
return emptyPackage_;
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public int getEmptyPackageCount() {
return emptyPackage_.size();
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public java.lang.String getEmptyPackage(int index) {
return emptyPackage_.get(index);
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public org.jetbrains.kotlin.protobuf.ByteString
getEmptyPackageBytes(int index) {
return emptyPackage_.getByteString(index);
}
public static final int FILE_FIELD_NUMBER = 9;
private java.util.List<org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File> file_;
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public java.util.List<org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File> getFileList() {
return file_;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public java.util.List<? extends org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.FileOrBuilder>
getFileOrBuilderList() {
return file_;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public int getFileCount() {
return file_.size();
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File getFile(int index) {
return file_.get(index);
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.FileOrBuilder getFileOrBuilder(
int index) {
return file_.get(index);
}
private void initFields() {
moduleName_ = "";
flags_ = 0;
strings_ = org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.getDefaultInstance();
qualifiedNames_ = org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.getDefaultInstance();
annotation_ = java.util.Collections.emptyList();
packageFragmentName_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
emptyPackage_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
file_ = java.util.Collections.emptyList();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasModuleName()) {
memoizedIsInitialized = 0;
return false;
}
if (hasQualifiedNames()) {
if (!getQualifiedNames().isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
for (int i = 0; i < getAnnotationCount(); i++) {
if (!getAnnotation(i).isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
for (int i = 0; i < getFileCount(); i++) {
if (!getFile(i).isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(org.jetbrains.kotlin.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getModuleNameBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeInt32(2, flags_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeMessage(4, strings_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeMessage(5, qualifiedNames_);
}
for (int i = 0; i < annotation_.size(); i++) {
output.writeMessage(6, annotation_.get(i));
}
for (int i = 0; i < packageFragmentName_.size(); i++) {
output.writeBytes(7, packageFragmentName_.getByteString(i));
}
for (int i = 0; i < emptyPackage_.size(); i++) {
output.writeBytes(8, emptyPackage_.getByteString(i));
}
for (int i = 0; i < file_.size(); i++) {
output.writeMessage(9, file_.get(i));
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeBytesSize(1, getModuleNameBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeInt32Size(2, flags_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeMessageSize(4, strings_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeMessageSize(5, qualifiedNames_);
}
for (int i = 0; i < annotation_.size(); i++) {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeMessageSize(6, annotation_.get(i));
}
{
int dataSize = 0;
for (int i = 0; i < packageFragmentName_.size(); i++) {
dataSize += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeBytesSizeNoTag(packageFragmentName_.getByteString(i));
}
size += dataSize;
size += 1 * getPackageFragmentNameList().size();
}
{
int dataSize = 0;
for (int i = 0; i < emptyPackage_.size(); i++) {
dataSize += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeBytesSizeNoTag(emptyPackage_.getByteString(i));
}
size += dataSize;
size += 1 * getEmptyPackageList().size();
}
for (int i = 0; i < file_.size(); i++) {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeMessageSize(9, file_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parseFrom(
org.jetbrains.kotlin.protobuf.ByteString data)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parseFrom(
org.jetbrains.kotlin.protobuf.ByteString data,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parseFrom(byte[] data)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parseFrom(
byte[] data,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parseFrom(
java.io.InputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parseDelimitedFrom(
java.io.InputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parseFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parseFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
org.jetbrains.kotlin.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code org.jetbrains.kotlin.library.metadata.Header}
*/
public static final class Builder extends
org.jetbrains.kotlin.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:org.jetbrains.kotlin.library.metadata.Header)
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.HeaderOrBuilder {
public static final org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_Header_descriptor;
}
protected org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_Header_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header.class, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header.Builder.class);
}
// Construct using org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
org.jetbrains.kotlin.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (org.jetbrains.kotlin.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getStringsFieldBuilder();
getQualifiedNamesFieldBuilder();
getAnnotationFieldBuilder();
getFileFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
moduleName_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
flags_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
if (stringsBuilder_ == null) {
strings_ = org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.getDefaultInstance();
} else {
stringsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000004);
if (qualifiedNamesBuilder_ == null) {
qualifiedNames_ = org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.getDefaultInstance();
} else {
qualifiedNamesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000008);
if (annotationBuilder_ == null) {
annotation_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000010);
} else {
annotationBuilder_.clear();
}
packageFragmentName_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000020);
emptyPackage_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000040);
if (fileBuilder_ == null) {
file_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000080);
} else {
fileBuilder_.clear();
}
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_Header_descriptor;
}
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header getDefaultInstanceForType() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header.getDefaultInstance();
}
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header build() {
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header buildPartial() {
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header result = new org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.moduleName_ = moduleName_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.flags_ = flags_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
if (stringsBuilder_ == null) {
result.strings_ = strings_;
} else {
result.strings_ = stringsBuilder_.build();
}
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
if (qualifiedNamesBuilder_ == null) {
result.qualifiedNames_ = qualifiedNames_;
} else {
result.qualifiedNames_ = qualifiedNamesBuilder_.build();
}
if (annotationBuilder_ == null) {
if (((bitField0_ & 0x00000010) == 0x00000010)) {
annotation_ = java.util.Collections.unmodifiableList(annotation_);
bitField0_ = (bitField0_ & ~0x00000010);
}
result.annotation_ = annotation_;
} else {
result.annotation_ = annotationBuilder_.build();
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
packageFragmentName_ = packageFragmentName_.getUnmodifiableView();
bitField0_ = (bitField0_ & ~0x00000020);
}
result.packageFragmentName_ = packageFragmentName_;
if (((bitField0_ & 0x00000040) == 0x00000040)) {
emptyPackage_ = emptyPackage_.getUnmodifiableView();
bitField0_ = (bitField0_ & ~0x00000040);
}
result.emptyPackage_ = emptyPackage_;
if (fileBuilder_ == null) {
if (((bitField0_ & 0x00000080) == 0x00000080)) {
file_ = java.util.Collections.unmodifiableList(file_);
bitField0_ = (bitField0_ & ~0x00000080);
}
result.file_ = file_;
} else {
result.file_ = fileBuilder_.build();
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(org.jetbrains.kotlin.protobuf.Message other) {
if (other instanceof org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header) {
return mergeFrom((org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header other) {
if (other == org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header.getDefaultInstance()) return this;
if (other.hasModuleName()) {
bitField0_ |= 0x00000001;
moduleName_ = other.moduleName_;
onChanged();
}
if (other.hasFlags()) {
setFlags(other.getFlags());
}
if (other.hasStrings()) {
mergeStrings(other.getStrings());
}
if (other.hasQualifiedNames()) {
mergeQualifiedNames(other.getQualifiedNames());
}
if (annotationBuilder_ == null) {
if (!other.annotation_.isEmpty()) {
if (annotation_.isEmpty()) {
annotation_ = other.annotation_;
bitField0_ = (bitField0_ & ~0x00000010);
} else {
ensureAnnotationIsMutable();
annotation_.addAll(other.annotation_);
}
onChanged();
}
} else {
if (!other.annotation_.isEmpty()) {
if (annotationBuilder_.isEmpty()) {
annotationBuilder_.dispose();
annotationBuilder_ = null;
annotation_ = other.annotation_;
bitField0_ = (bitField0_ & ~0x00000010);
annotationBuilder_ =
org.jetbrains.kotlin.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getAnnotationFieldBuilder() : null;
} else {
annotationBuilder_.addAllMessages(other.annotation_);
}
}
}
if (!other.packageFragmentName_.isEmpty()) {
if (packageFragmentName_.isEmpty()) {
packageFragmentName_ = other.packageFragmentName_;
bitField0_ = (bitField0_ & ~0x00000020);
} else {
ensurePackageFragmentNameIsMutable();
packageFragmentName_.addAll(other.packageFragmentName_);
}
onChanged();
}
if (!other.emptyPackage_.isEmpty()) {
if (emptyPackage_.isEmpty()) {
emptyPackage_ = other.emptyPackage_;
bitField0_ = (bitField0_ & ~0x00000040);
} else {
ensureEmptyPackageIsMutable();
emptyPackage_.addAll(other.emptyPackage_);
}
onChanged();
}
if (fileBuilder_ == null) {
if (!other.file_.isEmpty()) {
if (file_.isEmpty()) {
file_ = other.file_;
bitField0_ = (bitField0_ & ~0x00000080);
} else {
ensureFileIsMutable();
file_.addAll(other.file_);
}
onChanged();
}
} else {
if (!other.file_.isEmpty()) {
if (fileBuilder_.isEmpty()) {
fileBuilder_.dispose();
fileBuilder_ = null;
file_ = other.file_;
bitField0_ = (bitField0_ & ~0x00000080);
fileBuilder_ =
org.jetbrains.kotlin.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getFileFieldBuilder() : null;
} else {
fileBuilder_.addAllMessages(other.file_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasModuleName()) {
return false;
}
if (hasQualifiedNames()) {
if (!getQualifiedNames().isInitialized()) {
return false;
}
}
for (int i = 0; i < getAnnotationCount(); i++) {
if (!getAnnotation(i).isInitialized()) {
return false;
}
}
for (int i = 0; i < getFileCount(); i++) {
if (!getFile(i).isInitialized()) {
return false;
}
}
return true;
}
public Builder mergeFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.Header) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object moduleName_ = "";
/**
* <code>required string module_name = 1;</code>
*/
public boolean hasModuleName() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string module_name = 1;</code>
*/
public java.lang.String getModuleName() {
java.lang.Object ref = moduleName_;
if (!(ref instanceof java.lang.String)) {
org.jetbrains.kotlin.protobuf.ByteString bs =
(org.jetbrains.kotlin.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
moduleName_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string module_name = 1;</code>
*/
public org.jetbrains.kotlin.protobuf.ByteString
getModuleNameBytes() {
java.lang.Object ref = moduleName_;
if (ref instanceof String) {
org.jetbrains.kotlin.protobuf.ByteString b =
org.jetbrains.kotlin.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
moduleName_ = b;
return b;
} else {
return (org.jetbrains.kotlin.protobuf.ByteString) ref;
}
}
/**
* <code>required string module_name = 1;</code>
*/
public Builder setModuleName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
moduleName_ = value;
onChanged();
return this;
}
/**
* <code>required string module_name = 1;</code>
*/
public Builder clearModuleName() {
bitField0_ = (bitField0_ & ~0x00000001);
moduleName_ = getDefaultInstance().getModuleName();
onChanged();
return this;
}
/**
* <code>required string module_name = 1;</code>
*/
public Builder setModuleNameBytes(
org.jetbrains.kotlin.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
moduleName_ = value;
onChanged();
return this;
}
private int flags_ ;
/**
* <code>optional int32 flags = 2;</code>
*
* <pre>
*0x1 = preRelease
* </pre>
*/
public boolean hasFlags() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional int32 flags = 2;</code>
*
* <pre>
*0x1 = preRelease
* </pre>
*/
public int getFlags() {
return flags_;
}
/**
* <code>optional int32 flags = 2;</code>
*
* <pre>
*0x1 = preRelease
* </pre>
*/
public Builder setFlags(int value) {
bitField0_ |= 0x00000002;
flags_ = value;
onChanged();
return this;
}
/**
* <code>optional int32 flags = 2;</code>
*
* <pre>
*0x1 = preRelease
* </pre>
*/
public Builder clearFlags() {
bitField0_ = (bitField0_ & ~0x00000002);
flags_ = 0;
onChanged();
return this;
}
private org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable strings_ = org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.getDefaultInstance();
private org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable, org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTableOrBuilder> stringsBuilder_;
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public boolean hasStrings() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable getStrings() {
if (stringsBuilder_ == null) {
return strings_;
} else {
return stringsBuilder_.getMessage();
}
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public Builder setStrings(org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable value) {
if (stringsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
strings_ = value;
onChanged();
} else {
stringsBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public Builder setStrings(
org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.Builder builderForValue) {
if (stringsBuilder_ == null) {
strings_ = builderForValue.build();
onChanged();
} else {
stringsBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public Builder mergeStrings(org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable value) {
if (stringsBuilder_ == null) {
if (((bitField0_ & 0x00000004) == 0x00000004) &&
strings_ != org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.getDefaultInstance()) {
strings_ =
org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.newBuilder(strings_).mergeFrom(value).buildPartial();
} else {
strings_ = value;
}
onChanged();
} else {
stringsBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000004;
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public Builder clearStrings() {
if (stringsBuilder_ == null) {
strings_ = org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.getDefaultInstance();
onChanged();
} else {
stringsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000004);
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.Builder getStringsBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getStringsFieldBuilder().getBuilder();
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTableOrBuilder getStringsOrBuilder() {
if (stringsBuilder_ != null) {
return stringsBuilder_.getMessageOrBuilder();
} else {
return strings_;
}
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.StringTable strings = 4;</code>
*/
private org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable, org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTableOrBuilder>
getStringsFieldBuilder() {
if (stringsBuilder_ == null) {
stringsBuilder_ = new org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable, org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTable.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.StringTableOrBuilder>(
getStrings(),
getParentForChildren(),
isClean());
strings_ = null;
}
return stringsBuilder_;
}
private org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable qualifiedNames_ = org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.getDefaultInstance();
private org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable, org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTableOrBuilder> qualifiedNamesBuilder_;
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public boolean hasQualifiedNames() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable getQualifiedNames() {
if (qualifiedNamesBuilder_ == null) {
return qualifiedNames_;
} else {
return qualifiedNamesBuilder_.getMessage();
}
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public Builder setQualifiedNames(org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable value) {
if (qualifiedNamesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
qualifiedNames_ = value;
onChanged();
} else {
qualifiedNamesBuilder_.setMessage(value);
}
bitField0_ |= 0x00000008;
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public Builder setQualifiedNames(
org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.Builder builderForValue) {
if (qualifiedNamesBuilder_ == null) {
qualifiedNames_ = builderForValue.build();
onChanged();
} else {
qualifiedNamesBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000008;
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public Builder mergeQualifiedNames(org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable value) {
if (qualifiedNamesBuilder_ == null) {
if (((bitField0_ & 0x00000008) == 0x00000008) &&
qualifiedNames_ != org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.getDefaultInstance()) {
qualifiedNames_ =
org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.newBuilder(qualifiedNames_).mergeFrom(value).buildPartial();
} else {
qualifiedNames_ = value;
}
onChanged();
} else {
qualifiedNamesBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000008;
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public Builder clearQualifiedNames() {
if (qualifiedNamesBuilder_ == null) {
qualifiedNames_ = org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.getDefaultInstance();
onChanged();
} else {
qualifiedNamesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000008);
return this;
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.Builder getQualifiedNamesBuilder() {
bitField0_ |= 0x00000008;
onChanged();
return getQualifiedNamesFieldBuilder().getBuilder();
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTableOrBuilder getQualifiedNamesOrBuilder() {
if (qualifiedNamesBuilder_ != null) {
return qualifiedNamesBuilder_.getMessageOrBuilder();
} else {
return qualifiedNames_;
}
}
/**
* <code>optional .org.jetbrains.kotlin.metadata.QualifiedNameTable qualified_names = 5;</code>
*/
private org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable, org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTableOrBuilder>
getQualifiedNamesFieldBuilder() {
if (qualifiedNamesBuilder_ == null) {
qualifiedNamesBuilder_ = new org.jetbrains.kotlin.protobuf.SingleFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable, org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTable.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.QualifiedNameTableOrBuilder>(
getQualifiedNames(),
getParentForChildren(),
isClean());
qualifiedNames_ = null;
}
return qualifiedNamesBuilder_;
}
private java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation> annotation_ =
java.util.Collections.emptyList();
private void ensureAnnotationIsMutable() {
if (!((bitField0_ & 0x00000010) == 0x00000010)) {
annotation_ = new java.util.ArrayList<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>(annotation_);
bitField0_ |= 0x00000010;
}
}
private org.jetbrains.kotlin.protobuf.RepeatedFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation, org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.AnnotationOrBuilder> annotationBuilder_;
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation> getAnnotationList() {
if (annotationBuilder_ == null) {
return java.util.Collections.unmodifiableList(annotation_);
} else {
return annotationBuilder_.getMessageList();
}
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public int getAnnotationCount() {
if (annotationBuilder_ == null) {
return annotation_.size();
} else {
return annotationBuilder_.getCount();
}
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation getAnnotation(int index) {
if (annotationBuilder_ == null) {
return annotation_.get(index);
} else {
return annotationBuilder_.getMessage(index);
}
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public Builder setAnnotation(
int index, org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation value) {
if (annotationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAnnotationIsMutable();
annotation_.set(index, value);
onChanged();
} else {
annotationBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public Builder setAnnotation(
int index, org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Builder builderForValue) {
if (annotationBuilder_ == null) {
ensureAnnotationIsMutable();
annotation_.set(index, builderForValue.build());
onChanged();
} else {
annotationBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public Builder addAnnotation(org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation value) {
if (annotationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAnnotationIsMutable();
annotation_.add(value);
onChanged();
} else {
annotationBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public Builder addAnnotation(
int index, org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation value) {
if (annotationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureAnnotationIsMutable();
annotation_.add(index, value);
onChanged();
} else {
annotationBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public Builder addAnnotation(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Builder builderForValue) {
if (annotationBuilder_ == null) {
ensureAnnotationIsMutable();
annotation_.add(builderForValue.build());
onChanged();
} else {
annotationBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public Builder addAnnotation(
int index, org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Builder builderForValue) {
if (annotationBuilder_ == null) {
ensureAnnotationIsMutable();
annotation_.add(index, builderForValue.build());
onChanged();
} else {
annotationBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public Builder addAllAnnotation(
java.lang.Iterable<? extends org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation> values) {
if (annotationBuilder_ == null) {
ensureAnnotationIsMutable();
org.jetbrains.kotlin.protobuf.AbstractMessageLite.Builder.addAll(
values, annotation_);
onChanged();
} else {
annotationBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public Builder clearAnnotation() {
if (annotationBuilder_ == null) {
annotation_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
} else {
annotationBuilder_.clear();
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public Builder removeAnnotation(int index) {
if (annotationBuilder_ == null) {
ensureAnnotationIsMutable();
annotation_.remove(index);
onChanged();
} else {
annotationBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Builder getAnnotationBuilder(
int index) {
return getAnnotationFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.AnnotationOrBuilder getAnnotationOrBuilder(
int index) {
if (annotationBuilder_ == null) {
return annotation_.get(index); } else {
return annotationBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public java.util.List<? extends org.jetbrains.kotlin.metadata.DebugProtoBuf.AnnotationOrBuilder>
getAnnotationOrBuilderList() {
if (annotationBuilder_ != null) {
return annotationBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(annotation_);
}
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Builder addAnnotationBuilder() {
return getAnnotationFieldBuilder().addBuilder(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Builder addAnnotationBuilder(
int index) {
return getAnnotationFieldBuilder().addBuilder(
index, org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
}
/**
* <code>repeated .org.jetbrains.kotlin.metadata.Annotation annotation = 6;</code>
*
* <pre>
* Annotations on the whole module
* </pre>
*/
public java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Builder>
getAnnotationBuilderList() {
return getAnnotationFieldBuilder().getBuilderList();
}
private org.jetbrains.kotlin.protobuf.RepeatedFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation, org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.AnnotationOrBuilder>
getAnnotationFieldBuilder() {
if (annotationBuilder_ == null) {
annotationBuilder_ = new org.jetbrains.kotlin.protobuf.RepeatedFieldBuilder<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation, org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Builder, org.jetbrains.kotlin.metadata.DebugProtoBuf.AnnotationOrBuilder>(
annotation_,
((bitField0_ & 0x00000010) == 0x00000010),
getParentForChildren(),
isClean());
annotation_ = null;
}
return annotationBuilder_;
}
private org.jetbrains.kotlin.protobuf.LazyStringList packageFragmentName_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
private void ensurePackageFragmentNameIsMutable() {
if (!((bitField0_ & 0x00000020) == 0x00000020)) {
packageFragmentName_ = new org.jetbrains.kotlin.protobuf.LazyStringArrayList(packageFragmentName_);
bitField0_ |= 0x00000020;
}
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public org.jetbrains.kotlin.protobuf.ProtocolStringList
getPackageFragmentNameList() {
return packageFragmentName_.getUnmodifiableView();
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public int getPackageFragmentNameCount() {
return packageFragmentName_.size();
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public java.lang.String getPackageFragmentName(int index) {
return packageFragmentName_.get(index);
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public org.jetbrains.kotlin.protobuf.ByteString
getPackageFragmentNameBytes(int index) {
return packageFragmentName_.getByteString(index);
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public Builder setPackageFragmentName(
int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensurePackageFragmentNameIsMutable();
packageFragmentName_.set(index, value);
onChanged();
return this;
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public Builder addPackageFragmentName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensurePackageFragmentNameIsMutable();
packageFragmentName_.add(value);
onChanged();
return this;
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public Builder addAllPackageFragmentName(
java.lang.Iterable<java.lang.String> values) {
ensurePackageFragmentNameIsMutable();
org.jetbrains.kotlin.protobuf.AbstractMessageLite.Builder.addAll(
values, packageFragmentName_);
onChanged();
return this;
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public Builder clearPackageFragmentName() {
packageFragmentName_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000020);
onChanged();
return this;
}
/**
* <code>repeated string package_fragment_name = 7;</code>
*/
public Builder addPackageFragmentNameBytes(
org.jetbrains.kotlin.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
ensurePackageFragmentNameIsMutable();
packageFragmentName_.add(value);
onChanged();
return this;
}
private org.jetbrains.kotlin.protobuf.LazyStringList emptyPackage_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
private void ensureEmptyPackageIsMutable() {
if (!((bitField0_ & 0x00000040) == 0x00000040)) {
emptyPackage_ = new org.jetbrains.kotlin.protobuf.LazyStringArrayList(emptyPackage_);
bitField0_ |= 0x00000040;
}
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public org.jetbrains.kotlin.protobuf.ProtocolStringList
getEmptyPackageList() {
return emptyPackage_.getUnmodifiableView();
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public int getEmptyPackageCount() {
return emptyPackage_.size();
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public java.lang.String getEmptyPackage(int index) {
return emptyPackage_.get(index);
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public org.jetbrains.kotlin.protobuf.ByteString
getEmptyPackageBytes(int index) {
return emptyPackage_.getByteString(index);
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public Builder setEmptyPackage(
int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureEmptyPackageIsMutable();
emptyPackage_.set(index, value);
onChanged();
return this;
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public Builder addEmptyPackage(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureEmptyPackageIsMutable();
emptyPackage_.add(value);
onChanged();
return this;
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public Builder addAllEmptyPackage(
java.lang.Iterable<java.lang.String> values) {
ensureEmptyPackageIsMutable();
org.jetbrains.kotlin.protobuf.AbstractMessageLite.Builder.addAll(
values, emptyPackage_);
onChanged();
return this;
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public Builder clearEmptyPackage() {
emptyPackage_ = org.jetbrains.kotlin.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000040);
onChanged();
return this;
}
/**
* <code>repeated string empty_package = 8;</code>
*/
public Builder addEmptyPackageBytes(
org.jetbrains.kotlin.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
ensureEmptyPackageIsMutable();
emptyPackage_.add(value);
onChanged();
return this;
}
private java.util.List<org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File> file_ =
java.util.Collections.emptyList();
private void ensureFileIsMutable() {
if (!((bitField0_ & 0x00000080) == 0x00000080)) {
file_ = new java.util.ArrayList<org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File>(file_);
bitField0_ |= 0x00000080;
}
}
private org.jetbrains.kotlin.protobuf.RepeatedFieldBuilder<
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.FileOrBuilder> fileBuilder_;
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public java.util.List<org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File> getFileList() {
if (fileBuilder_ == null) {
return java.util.Collections.unmodifiableList(file_);
} else {
return fileBuilder_.getMessageList();
}
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public int getFileCount() {
if (fileBuilder_ == null) {
return file_.size();
} else {
return fileBuilder_.getCount();
}
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File getFile(int index) {
if (fileBuilder_ == null) {
return file_.get(index);
} else {
return fileBuilder_.getMessage(index);
}
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public Builder setFile(
int index, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File value) {
if (fileBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFileIsMutable();
file_.set(index, value);
onChanged();
} else {
fileBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public Builder setFile(
int index, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder builderForValue) {
if (fileBuilder_ == null) {
ensureFileIsMutable();
file_.set(index, builderForValue.build());
onChanged();
} else {
fileBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public Builder addFile(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File value) {
if (fileBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFileIsMutable();
file_.add(value);
onChanged();
} else {
fileBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public Builder addFile(
int index, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File value) {
if (fileBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFileIsMutable();
file_.add(index, value);
onChanged();
} else {
fileBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public Builder addFile(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder builderForValue) {
if (fileBuilder_ == null) {
ensureFileIsMutable();
file_.add(builderForValue.build());
onChanged();
} else {
fileBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public Builder addFile(
int index, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder builderForValue) {
if (fileBuilder_ == null) {
ensureFileIsMutable();
file_.add(index, builderForValue.build());
onChanged();
} else {
fileBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public Builder addAllFile(
java.lang.Iterable<? extends org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File> values) {
if (fileBuilder_ == null) {
ensureFileIsMutable();
org.jetbrains.kotlin.protobuf.AbstractMessageLite.Builder.addAll(
values, file_);
onChanged();
} else {
fileBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public Builder clearFile() {
if (fileBuilder_ == null) {
file_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000080);
onChanged();
} else {
fileBuilder_.clear();
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public Builder removeFile(int index) {
if (fileBuilder_ == null) {
ensureFileIsMutable();
file_.remove(index);
onChanged();
} else {
fileBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder getFileBuilder(
int index) {
return getFileFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.FileOrBuilder getFileOrBuilder(
int index) {
if (fileBuilder_ == null) {
return file_.get(index); } else {
return fileBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public java.util.List<? extends org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.FileOrBuilder>
getFileOrBuilderList() {
if (fileBuilder_ != null) {
return fileBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(file_);
}
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder addFileBuilder() {
return getFileFieldBuilder().addBuilder(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.getDefaultInstance());
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder addFileBuilder(
int index) {
return getFileFieldBuilder().addBuilder(
index, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.getDefaultInstance());
}
/**
* <code>repeated .org.jetbrains.kotlin.library.metadata.File file = 9;</code>
*/
public java.util.List<org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder>
getFileBuilderList() {
return getFileFieldBuilder().getBuilderList();
}
private org.jetbrains.kotlin.protobuf.RepeatedFieldBuilder<
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.FileOrBuilder>
getFileFieldBuilder() {
if (fileBuilder_ == null) {
fileBuilder_ = new org.jetbrains.kotlin.protobuf.RepeatedFieldBuilder<
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.FileOrBuilder>(
file_,
((bitField0_ & 0x00000080) == 0x00000080),
getParentForChildren(),
isClean());
file_ = null;
}
return fileBuilder_;
}
// @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.library.metadata.Header)
}
static {
defaultInstance = new Header(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.library.metadata.Header)
}
public interface FileOrBuilder extends
// @@protoc_insertion_point(interface_extends:org.jetbrains.kotlin.library.metadata.File)
org.jetbrains.kotlin.protobuf.MessageOrBuilder {
/**
* <code>required string name = 1;</code>
*/
boolean hasName();
/**
* <code>required string name = 1;</code>
*/
java.lang.String getName();
/**
* <code>required string name = 1;</code>
*/
org.jetbrains.kotlin.protobuf.ByteString
getNameBytes();
}
/**
* Protobuf type {@code org.jetbrains.kotlin.library.metadata.File}
*/
public static final class File extends
org.jetbrains.kotlin.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:org.jetbrains.kotlin.library.metadata.File)
FileOrBuilder {
// Use File.newBuilder() to construct.
private File(org.jetbrains.kotlin.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private File(boolean noInit) { this.unknownFields = org.jetbrains.kotlin.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final File defaultInstance;
public static File getDefaultInstance() {
return defaultInstance;
}
public File getDefaultInstanceForType() {
return defaultInstance;
}
private final org.jetbrains.kotlin.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final org.jetbrains.kotlin.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private File(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
org.jetbrains.kotlin.protobuf.UnknownFieldSet.Builder unknownFields =
org.jetbrains.kotlin.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
org.jetbrains.kotlin.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000001;
name_ = bs;
break;
}
}
}
} catch (org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_File_descriptor;
}
protected org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_File_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.class, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder.class);
}
public static org.jetbrains.kotlin.protobuf.Parser<File> PARSER =
new org.jetbrains.kotlin.protobuf.AbstractParser<File>() {
public File parsePartialFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return new File(input, extensionRegistry);
}
};
@java.lang.Override
public org.jetbrains.kotlin.protobuf.Parser<File> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int NAME_FIELD_NUMBER = 1;
private java.lang.Object name_;
/**
* <code>required string name = 1;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
org.jetbrains.kotlin.protobuf.ByteString bs =
(org.jetbrains.kotlin.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
}
}
/**
* <code>required string name = 1;</code>
*/
public org.jetbrains.kotlin.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
org.jetbrains.kotlin.protobuf.ByteString b =
org.jetbrains.kotlin.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (org.jetbrains.kotlin.protobuf.ByteString) ref;
}
}
private void initFields() {
name_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasName()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(org.jetbrains.kotlin.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getNameBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeBytesSize(1, getNameBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parseFrom(
org.jetbrains.kotlin.protobuf.ByteString data)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parseFrom(
org.jetbrains.kotlin.protobuf.ByteString data,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parseFrom(byte[] data)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parseFrom(
byte[] data,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parseFrom(
java.io.InputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parseDelimitedFrom(
java.io.InputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parseFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parseFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
org.jetbrains.kotlin.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code org.jetbrains.kotlin.library.metadata.File}
*/
public static final class Builder extends
org.jetbrains.kotlin.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:org.jetbrains.kotlin.library.metadata.File)
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.FileOrBuilder {
public static final org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_File_descriptor;
}
protected org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_File_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.class, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.Builder.class);
}
// Construct using org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
org.jetbrains.kotlin.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (org.jetbrains.kotlin.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
name_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_File_descriptor;
}
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File getDefaultInstanceForType() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.getDefaultInstance();
}
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File build() {
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File buildPartial() {
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File result = new org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.name_ = name_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(org.jetbrains.kotlin.protobuf.Message other) {
if (other instanceof org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File) {
return mergeFrom((org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File other) {
if (other == org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File.getDefaultInstance()) return this;
if (other.hasName()) {
bitField0_ |= 0x00000001;
name_ = other.name_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasName()) {
return false;
}
return true;
}
public Builder mergeFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.File) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object name_ = "";
/**
* <code>required string name = 1;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string name = 1;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
org.jetbrains.kotlin.protobuf.ByteString bs =
(org.jetbrains.kotlin.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>required string name = 1;</code>
*/
public org.jetbrains.kotlin.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
org.jetbrains.kotlin.protobuf.ByteString b =
org.jetbrains.kotlin.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (org.jetbrains.kotlin.protobuf.ByteString) ref;
}
}
/**
* <code>required string name = 1;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
name_ = value;
onChanged();
return this;
}
/**
* <code>required string name = 1;</code>
*/
public Builder clearName() {
bitField0_ = (bitField0_ & ~0x00000001);
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <code>required string name = 1;</code>
*/
public Builder setNameBytes(
org.jetbrains.kotlin.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
name_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.library.metadata.File)
}
static {
defaultInstance = new File(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.library.metadata.File)
}
public interface DescriptorUniqIdOrBuilder extends
// @@protoc_insertion_point(interface_extends:org.jetbrains.kotlin.library.metadata.DescriptorUniqId)
org.jetbrains.kotlin.protobuf.MessageOrBuilder {
/**
* <code>required int64 index = 1;</code>
*/
boolean hasIndex();
/**
* <code>required int64 index = 1;</code>
*/
long getIndex();
}
/**
* Protobuf type {@code org.jetbrains.kotlin.library.metadata.DescriptorUniqId}
*/
public static final class DescriptorUniqId extends
org.jetbrains.kotlin.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:org.jetbrains.kotlin.library.metadata.DescriptorUniqId)
DescriptorUniqIdOrBuilder {
// Use DescriptorUniqId.newBuilder() to construct.
private DescriptorUniqId(org.jetbrains.kotlin.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private DescriptorUniqId(boolean noInit) { this.unknownFields = org.jetbrains.kotlin.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final DescriptorUniqId defaultInstance;
public static DescriptorUniqId getDefaultInstance() {
return defaultInstance;
}
public DescriptorUniqId getDefaultInstanceForType() {
return defaultInstance;
}
private final org.jetbrains.kotlin.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final org.jetbrains.kotlin.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private DescriptorUniqId(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
org.jetbrains.kotlin.protobuf.UnknownFieldSet.Builder unknownFields =
org.jetbrains.kotlin.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
index_ = input.readInt64();
break;
}
}
}
} catch (org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_DescriptorUniqId_descriptor;
}
protected org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_DescriptorUniqId_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.class, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.Builder.class);
}
public static org.jetbrains.kotlin.protobuf.Parser<DescriptorUniqId> PARSER =
new org.jetbrains.kotlin.protobuf.AbstractParser<DescriptorUniqId>() {
public DescriptorUniqId parsePartialFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return new DescriptorUniqId(input, extensionRegistry);
}
};
@java.lang.Override
public org.jetbrains.kotlin.protobuf.Parser<DescriptorUniqId> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int INDEX_FIELD_NUMBER = 1;
private long index_;
/**
* <code>required int64 index = 1;</code>
*/
public boolean hasIndex() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int64 index = 1;</code>
*/
public long getIndex() {
return index_;
}
private void initFields() {
index_ = 0L;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (!hasIndex()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(org.jetbrains.kotlin.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeInt64(1, index_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += org.jetbrains.kotlin.protobuf.CodedOutputStream
.computeInt64Size(1, index_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parseFrom(
org.jetbrains.kotlin.protobuf.ByteString data)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parseFrom(
org.jetbrains.kotlin.protobuf.ByteString data,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parseFrom(byte[] data)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parseFrom(
byte[] data,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parseFrom(
java.io.InputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parseDelimitedFrom(
java.io.InputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parseFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parseFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
org.jetbrains.kotlin.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code org.jetbrains.kotlin.library.metadata.DescriptorUniqId}
*/
public static final class Builder extends
org.jetbrains.kotlin.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:org.jetbrains.kotlin.library.metadata.DescriptorUniqId)
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqIdOrBuilder {
public static final org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_DescriptorUniqId_descriptor;
}
protected org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_DescriptorUniqId_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.class, org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.Builder.class);
}
// Construct using org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
org.jetbrains.kotlin.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (org.jetbrains.kotlin.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
index_ = 0L;
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.internal_static_org_jetbrains_kotlin_library_metadata_DescriptorUniqId_descriptor;
}
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId getDefaultInstanceForType() {
return org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.getDefaultInstance();
}
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId build() {
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId buildPartial() {
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId result = new org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.index_ = index_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(org.jetbrains.kotlin.protobuf.Message other) {
if (other instanceof org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId) {
return mergeFrom((org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId other) {
if (other == org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.getDefaultInstance()) return this;
if (other.hasIndex()) {
setIndex(other.getIndex());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasIndex()) {
return false;
}
return true;
}
public Builder mergeFrom(
org.jetbrains.kotlin.protobuf.CodedInputStream input,
org.jetbrains.kotlin.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (org.jetbrains.kotlin.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private long index_ ;
/**
* <code>required int64 index = 1;</code>
*/
public boolean hasIndex() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required int64 index = 1;</code>
*/
public long getIndex() {
return index_;
}
/**
* <code>required int64 index = 1;</code>
*/
public Builder setIndex(long value) {
bitField0_ |= 0x00000001;
index_ = value;
onChanged();
return this;
}
/**
* <code>required int64 index = 1;</code>
*/
public Builder clearIndex() {
bitField0_ = (bitField0_ & ~0x00000001);
index_ = 0L;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:org.jetbrains.kotlin.library.metadata.DescriptorUniqId)
}
static {
defaultInstance = new DescriptorUniqId(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:org.jetbrains.kotlin.library.metadata.DescriptorUniqId)
}
public static final int PACKAGE_FQ_NAME_FIELD_NUMBER = 171;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Package { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Package,
java.lang.Integer> packageFqName = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int CLASS_ANNOTATION_FIELD_NUMBER = 170;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class,
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>> classAnnotation = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int CLASS_FILE_FIELD_NUMBER = 175;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class,
java.lang.Integer> classFile = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int CLASS_KDOC_FIELD_NUMBER = 176;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class,
java.lang.String> classKdoc = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.String.class,
null);
public static final int CLASS_UNIQ_ID_FIELD_NUMBER = 171;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Class { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Class,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId> classUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.class,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.getDefaultInstance());
public static final int CONSTRUCTOR_ANNOTATION_FIELD_NUMBER = 170;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Constructor { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Constructor,
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>> constructorAnnotation = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int CONSTRUCTOR_KDOC_FIELD_NUMBER = 173;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Constructor { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Constructor,
java.lang.String> constructorKdoc = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.String.class,
null);
public static final int CONSTRUCTOR_UNIQ_ID_FIELD_NUMBER = 172;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Constructor { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Constructor,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId> constructorUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.class,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.getDefaultInstance());
public static final int FUNCTION_ANNOTATION_FIELD_NUMBER = 170;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Function { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Function,
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>> functionAnnotation = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int FUNCTION_FILE_FIELD_NUMBER = 172;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Function { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Function,
java.lang.Integer> functionFile = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int FUNCTION_KDOC_FIELD_NUMBER = 174;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Function { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Function,
java.lang.String> functionKdoc = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.String.class,
null);
public static final int FUNCTION_UNIQ_ID_FIELD_NUMBER = 173;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Function { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Function,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId> functionUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.class,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.getDefaultInstance());
public static final int PROPERTY_ANNOTATION_FIELD_NUMBER = 170;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Property,
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>> propertyAnnotation = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int PROPERTY_GETTER_ANNOTATION_FIELD_NUMBER = 177;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Property,
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>> propertyGetterAnnotation = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int PROPERTY_SETTER_ANNOTATION_FIELD_NUMBER = 178;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Property,
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>> propertySetterAnnotation = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int COMPILE_TIME_VALUE_FIELD_NUMBER = 173;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Property,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Argument.Value> compileTimeValue = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Argument.Value.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.Argument.Value.getDefaultInstance());
public static final int PROPERTY_FILE_FIELD_NUMBER = 176;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Property,
java.lang.Integer> propertyFile = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int PROPERTY_KDOC_FIELD_NUMBER = 180;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Property,
java.lang.String> propertyKdoc = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.String.class,
null);
public static final int PROPERTY_UNIQ_ID_FIELD_NUMBER = 179;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Property { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Property,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId> propertyUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.class,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.getDefaultInstance());
public static final int ENUM_ENTRY_ANNOTATION_FIELD_NUMBER = 170;
/**
* <code>extend .org.jetbrains.kotlin.metadata.EnumEntry { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.EnumEntry,
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>> enumEntryAnnotation = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int ENUM_ENTRY_ORDINAL_FIELD_NUMBER = 171;
/**
* <code>extend .org.jetbrains.kotlin.metadata.EnumEntry { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.EnumEntry,
java.lang.Integer> enumEntryOrdinal = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int ENUM_ENTRY_UNIQ_ID_FIELD_NUMBER = 172;
/**
* <code>extend .org.jetbrains.kotlin.metadata.EnumEntry { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.EnumEntry,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId> enumEntryUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.class,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.getDefaultInstance());
public static final int PARAMETER_ANNOTATION_FIELD_NUMBER = 170;
/**
* <code>extend .org.jetbrains.kotlin.metadata.ValueParameter { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.ValueParameter,
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>> parameterAnnotation = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int TYPE_ANNOTATION_FIELD_NUMBER = 170;
/**
* <code>extend .org.jetbrains.kotlin.metadata.Type { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.Type,
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>> typeAnnotation = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int TYPE_PARAMETER_ANNOTATION_FIELD_NUMBER = 170;
/**
* <code>extend .org.jetbrains.kotlin.metadata.TypeParameter { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.TypeParameter,
java.util.List<org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation>> typeParameterAnnotation = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.class,
org.jetbrains.kotlin.metadata.DebugProtoBuf.Annotation.getDefaultInstance());
public static final int TYPE_PARAM_UNIQ_ID_FIELD_NUMBER = 171;
/**
* <code>extend .org.jetbrains.kotlin.metadata.TypeParameter { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.TypeParameter,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId> typeParamUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.class,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.getDefaultInstance());
public static final int PACKAGE_FRAGMENT_FILES_FIELD_NUMBER = 170;
/**
* <code>extend .org.jetbrains.kotlin.metadata.PackageFragment { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.PackageFragment,
java.util.List<java.lang.Integer>> packageFragmentFiles = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int IS_EMPTY_FIELD_NUMBER = 172;
/**
* <code>extend .org.jetbrains.kotlin.metadata.PackageFragment { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.PackageFragment,
java.lang.Boolean> isEmpty = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Boolean.class,
null);
public static final int FQ_NAME_FIELD_NUMBER = 173;
/**
* <code>extend .org.jetbrains.kotlin.metadata.PackageFragment { ... }</code>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.PackageFragment,
java.lang.String> fqName = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.String.class,
null);
public static final int CLASS_NAME_FIELD_NUMBER = 174;
/**
* <code>extend .org.jetbrains.kotlin.metadata.PackageFragment { ... }</code>
*
* <pre>
* id in StringTable
* </pre>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.PackageFragment,
java.util.List<java.lang.Integer>> className = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
java.lang.Integer.class,
null);
public static final int TYPE_ALIAS_UNIQ_ID_FIELD_NUMBER = 131;
/**
* <code>extend .org.jetbrains.kotlin.metadata.TypeAlias { ... }</code>
*
* <pre>
* TODO repeated org.jetbrains.kotlin.metadata.Annotation type_alias_annotation = 130;
* </pre>
*/
public static final
org.jetbrains.kotlin.protobuf.GeneratedMessage.GeneratedExtension<
org.jetbrains.kotlin.metadata.DebugProtoBuf.TypeAlias,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId> typeAliasUniqId = org.jetbrains.kotlin.protobuf.GeneratedMessage
.newFileScopedGeneratedExtension(
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.class,
org.jetbrains.kotlin.library.metadata.DebugKlibMetadataProtoBuf.DescriptorUniqId.getDefaultInstance());
private static final org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
internal_static_org_jetbrains_kotlin_library_metadata_Header_descriptor;
private static
org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_org_jetbrains_kotlin_library_metadata_Header_fieldAccessorTable;
private static final org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
internal_static_org_jetbrains_kotlin_library_metadata_File_descriptor;
private static
org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_org_jetbrains_kotlin_library_metadata_File_fieldAccessorTable;
private static final org.jetbrains.kotlin.protobuf.Descriptors.Descriptor
internal_static_org_jetbrains_kotlin_library_metadata_DescriptorUniqId_descriptor;
private static
org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_org_jetbrains_kotlin_library_metadata_DescriptorUniqId_fieldAccessorTable;
public static org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n@compiler/util-klib-metadata/src/KlibMe" +
"tadataProtoBuf.debug.proto\022%org.jetbrain" +
"s.kotlin.library.metadata\032&core/metadata" +
"/src/metadata.debug.proto\032)core/metadata" +
"/src/ext_options.debug.proto\"\345\002\n\006Header\022" +
"\023\n\013module_name\030\001 \002(\t\022\r\n\005flags\030\002 \001(\005\022;\n\007s" +
"trings\030\004 \001(\0132*.org.jetbrains.kotlin.meta" +
"data.StringTable\022J\n\017qualified_names\030\005 \001(" +
"\01321.org.jetbrains.kotlin.metadata.Qualif" +
"iedNameTable\022=\n\nannotation\030\006 \003(\0132).org.j",
"etbrains.kotlin.metadata.Annotation\022\035\n\025p" +
"ackage_fragment_name\030\007 \003(\t\022\025\n\rempty_pack" +
"age\030\010 \003(\t\0229\n\004file\030\t \003(\0132+.org.jetbrains." +
"kotlin.library.metadata.File\"\024\n\004File\022\014\n\004" +
"name\030\001 \002(\t\"\'\n\020DescriptorUniqId\022\r\n\005index\030" +
"\001 \002(\003:\004\240\273\030\001:@\n\017package_fq_name\022&.org.jet" +
"brains.kotlin.metadata.Package\030\253\001 \001(\005:j\n" +
"\020class_annotation\022$.org.jetbrains.kotlin" +
".metadata.Class\030\252\001 \003(\0132).org.jetbrains.k" +
"otlin.metadata.Annotation:?\n\nclass_file\022",
"$.org.jetbrains.kotlin.metadata.Class\030\257\001" +
" \001(\005B\004\200\265\030\001:?\n\nclass_kdoc\022$.org.jetbrains" +
".kotlin.metadata.Class\030\260\001 \001(\tB\004\200\265\030\001:u\n\rc" +
"lass_uniq_id\022$.org.jetbrains.kotlin.meta" +
"data.Class\030\253\001 \001(\01327.org.jetbrains.kotlin" +
".library.metadata.DescriptorUniqId:v\n\026co" +
"nstructor_annotation\022*.org.jetbrains.kot" +
"lin.metadata.Constructor\030\252\001 \003(\0132).org.je" +
"tbrains.kotlin.metadata.Annotation:K\n\020co" +
"nstructor_kdoc\022*.org.jetbrains.kotlin.me",
"tadata.Constructor\030\255\001 \001(\tB\004\200\265\030\001:\201\001\n\023cons" +
"tructor_uniq_id\022*.org.jetbrains.kotlin.m" +
"etadata.Constructor\030\254\001 \001(\01327.org.jetbrai" +
"ns.kotlin.library.metadata.DescriptorUni" +
"qId:p\n\023function_annotation\022\'.org.jetbrai" +
"ns.kotlin.metadata.Function\030\252\001 \003(\0132).org" +
".jetbrains.kotlin.metadata.Annotation:E\n" +
"\rfunction_file\022\'.org.jetbrains.kotlin.me" +
"tadata.Function\030\254\001 \001(\005B\004\200\265\030\001:E\n\rfunction" +
"_kdoc\022\'.org.jetbrains.kotlin.metadata.Fu",
"nction\030\256\001 \001(\tB\004\200\265\030\001:{\n\020function_uniq_id\022" +
"\'.org.jetbrains.kotlin.metadata.Function" +
"\030\255\001 \001(\01327.org.jetbrains.kotlin.library.m" +
"etadata.DescriptorUniqId:p\n\023property_ann" +
"otation\022\'.org.jetbrains.kotlin.metadata." +
"Property\030\252\001 \003(\0132).org.jetbrains.kotlin.m" +
"etadata.Annotation:w\n\032property_getter_an" +
"notation\022\'.org.jetbrains.kotlin.metadata" +
".Property\030\261\001 \003(\0132).org.jetbrains.kotlin." +
"metadata.Annotation:w\n\032property_setter_a",
"nnotation\022\'.org.jetbrains.kotlin.metadat" +
"a.Property\030\262\001 \003(\0132).org.jetbrains.kotlin" +
".metadata.Annotation:~\n\022compile_time_val" +
"ue\022\'.org.jetbrains.kotlin.metadata.Prope" +
"rty\030\255\001 \001(\01328.org.jetbrains.kotlin.metada" +
"ta.Annotation.Argument.Value:E\n\rproperty" +
"_file\022\'.org.jetbrains.kotlin.metadata.Pr" +
"operty\030\260\001 \001(\005B\004\200\265\030\001:E\n\rproperty_kdoc\022\'.o" +
"rg.jetbrains.kotlin.metadata.Property\030\264\001" +
" \001(\tB\004\200\265\030\001:{\n\020property_uniq_id\022\'.org.jet",
"brains.kotlin.metadata.Property\030\263\001 \001(\01327" +
".org.jetbrains.kotlin.library.metadata.D" +
"escriptorUniqId:s\n\025enum_entry_annotation" +
"\022(.org.jetbrains.kotlin.metadata.EnumEnt" +
"ry\030\252\001 \003(\0132).org.jetbrains.kotlin.metadat" +
"a.Annotation:E\n\022enum_entry_ordinal\022(.org" +
".jetbrains.kotlin.metadata.EnumEntry\030\253\001 " +
"\001(\005:~\n\022enum_entry_uniq_id\022(.org.jetbrain" +
"s.kotlin.metadata.EnumEntry\030\254\001 \001(\01327.org" +
".jetbrains.kotlin.library.metadata.Descr",
"iptorUniqId:w\n\024parameter_annotation\022-.or" +
"g.jetbrains.kotlin.metadata.ValueParamet" +
"er\030\252\001 \003(\0132).org.jetbrains.kotlin.metadat" +
"a.Annotation:h\n\017type_annotation\022#.org.je" +
"tbrains.kotlin.metadata.Type\030\252\001 \003(\0132).or" +
"g.jetbrains.kotlin.metadata.Annotation:{" +
"\n\031type_parameter_annotation\022,.org.jetbra" +
"ins.kotlin.metadata.TypeParameter\030\252\001 \003(\013" +
"2).org.jetbrains.kotlin.metadata.Annotat" +
"ion:\202\001\n\022type_param_uniq_id\022,.org.jetbrai",
"ns.kotlin.metadata.TypeParameter\030\253\001 \001(\0132" +
"7.org.jetbrains.kotlin.library.metadata." +
"DescriptorUniqId:U\n\026package_fragment_fil" +
"es\022..org.jetbrains.kotlin.metadata.Packa" +
"geFragment\030\252\001 \003(\005B\004\200\265\030\001:A\n\010is_empty\022..or" +
"g.jetbrains.kotlin.metadata.PackageFragm" +
"ent\030\254\001 \001(\010:@\n\007fq_name\022..org.jetbrains.ko" +
"tlin.metadata.PackageFragment\030\255\001 \001(\t:G\n\n" +
"class_name\022..org.jetbrains.kotlin.metada" +
"ta.PackageFragment\030\256\001 \003(\005B\002\020\001:~\n\022type_al",
"ias_uniq_id\022(.org.jetbrains.kotlin.metad" +
"ata.TypeAlias\030\203\001 \001(\01327.org.jetbrains.kot" +
"lin.library.metadata.DescriptorUniqIdB\033B" +
"\031DebugKlibMetadataProtoBuf"
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public org.jetbrains.kotlin.protobuf.ExtensionRegistry assignDescriptors(
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor[] {
org.jetbrains.kotlin.metadata.DebugProtoBuf.getDescriptor(),
org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.getDescriptor(),
}, assigner);
internal_static_org_jetbrains_kotlin_library_metadata_Header_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_org_jetbrains_kotlin_library_metadata_Header_fieldAccessorTable = new
org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_org_jetbrains_kotlin_library_metadata_Header_descriptor,
new java.lang.String[] { "ModuleName", "Flags", "Strings", "QualifiedNames", "Annotation", "PackageFragmentName", "EmptyPackage", "File", });
internal_static_org_jetbrains_kotlin_library_metadata_File_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_org_jetbrains_kotlin_library_metadata_File_fieldAccessorTable = new
org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_org_jetbrains_kotlin_library_metadata_File_descriptor,
new java.lang.String[] { "Name", });
internal_static_org_jetbrains_kotlin_library_metadata_DescriptorUniqId_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_org_jetbrains_kotlin_library_metadata_DescriptorUniqId_fieldAccessorTable = new
org.jetbrains.kotlin.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_org_jetbrains_kotlin_library_metadata_DescriptorUniqId_descriptor,
new java.lang.String[] { "Index", });
packageFqName.internalInit(descriptor.getExtensions().get(0));
classAnnotation.internalInit(descriptor.getExtensions().get(1));
classFile.internalInit(descriptor.getExtensions().get(2));
classKdoc.internalInit(descriptor.getExtensions().get(3));
classUniqId.internalInit(descriptor.getExtensions().get(4));
constructorAnnotation.internalInit(descriptor.getExtensions().get(5));
constructorKdoc.internalInit(descriptor.getExtensions().get(6));
constructorUniqId.internalInit(descriptor.getExtensions().get(7));
functionAnnotation.internalInit(descriptor.getExtensions().get(8));
functionFile.internalInit(descriptor.getExtensions().get(9));
functionKdoc.internalInit(descriptor.getExtensions().get(10));
functionUniqId.internalInit(descriptor.getExtensions().get(11));
propertyAnnotation.internalInit(descriptor.getExtensions().get(12));
propertyGetterAnnotation.internalInit(descriptor.getExtensions().get(13));
propertySetterAnnotation.internalInit(descriptor.getExtensions().get(14));
compileTimeValue.internalInit(descriptor.getExtensions().get(15));
propertyFile.internalInit(descriptor.getExtensions().get(16));
propertyKdoc.internalInit(descriptor.getExtensions().get(17));
propertyUniqId.internalInit(descriptor.getExtensions().get(18));
enumEntryAnnotation.internalInit(descriptor.getExtensions().get(19));
enumEntryOrdinal.internalInit(descriptor.getExtensions().get(20));
enumEntryUniqId.internalInit(descriptor.getExtensions().get(21));
parameterAnnotation.internalInit(descriptor.getExtensions().get(22));
typeAnnotation.internalInit(descriptor.getExtensions().get(23));
typeParameterAnnotation.internalInit(descriptor.getExtensions().get(24));
typeParamUniqId.internalInit(descriptor.getExtensions().get(25));
packageFragmentFiles.internalInit(descriptor.getExtensions().get(26));
isEmpty.internalInit(descriptor.getExtensions().get(27));
fqName.internalInit(descriptor.getExtensions().get(28));
className.internalInit(descriptor.getExtensions().get(29));
typeAliasUniqId.internalInit(descriptor.getExtensions().get(30));
org.jetbrains.kotlin.protobuf.ExtensionRegistry registry =
org.jetbrains.kotlin.protobuf.ExtensionRegistry.newInstance();
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.skipMessageInComparison);
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.skipInComparison);
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.skipInComparison);
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.skipInComparison);
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.skipInComparison);
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.skipInComparison);
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.skipInComparison);
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.skipInComparison);
registry.add(org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.skipInComparison);
org.jetbrains.kotlin.protobuf.Descriptors.FileDescriptor
.internalUpdateFileDescriptor(descriptor, registry);
org.jetbrains.kotlin.metadata.DebugProtoBuf.getDescriptor();
org.jetbrains.kotlin.metadata.DebugExtOptionsProtoBuf.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
pangolindex/mobile
|
pangolin_backend/api/createWallet/helper.js
|
const csvtojson = require("csvtojson");
const path = require("path");
const fs = require('fs');
const AWS = require('aws-sdk');
require('dotenv').config();
const ipfsFolder = '../ipfs-server/';
/**
* create csv files
*/
exports.postCSV = () => {
return new Promise(async (resolve, reject) => {
try {
let data = await csvtojson().fromFile(path.resolve(ipfsFolder, 'pangolinCollections.csv'));
if (data) return resolve(data)
return reject('no file found');
} catch (e) { reject(e) }
});
}
/**
* upload json files to s3 bucket
*/
const s3 = new AWS.S3({
accessKeyId: process['env']['accessKeyId'],
secretAccessKey: process['env']['secretAccessKey']
});
exports.uploadFile = (value) => {
return new Promise(async (resolve, reject) => {
try {
const fileName = `./json/${value}.json`;
fs.readFile(fileName, (err, data) => {
if (err) throw err;
const params = {
Bucket: 'test-pangolin-collections', // pass your bucket name
Key: `${value}.json`, // file will be saved as testBucket/contacts.csv
ACL: 'public-read',
"ContentType": "application/json",
Body: data
};
s3.upload(params, function (s3Err, data) {
if (s3Err) throw s3Err
resolve(data.Location);
console.log(`File uploaded successfully at ${data.Location}`)
});
});
} catch (e) { reject(e) }
});
};
|
kusumandaru/bpm-sbh
|
src/main/java/com/sbh/bpm/service/CityService.java
|
package com.sbh.bpm.service;
import java.util.List;
import com.sbh.bpm.model.City;
import com.sbh.bpm.repository.CityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CityService implements ICityService {
@Autowired
private CityRepository repository;
@Override
public List<City> findAll() {
return (List<City>) repository.findAll();
}
@Override
public List<City> findByProvinceId(Integer provinceId) {
return (List<City>) repository.findByProvinceId(provinceId);
}
@Override
public City findById(Integer cityId) {
return repository.findById(cityId).get();
}
@Override
public City save(City city) {
return repository.save(city);
}
}
|
caputomarcos/tuiuiu.io
|
tuiuiu/tuiuiucustomers/__init__.py
|
<gh_stars>1-10
default_app_config = 'tuiuiu.tuiuiucustomers.apps.TuiuiuCustomersConfig'
|
Boatdude55/staging-website
|
closure-templates/java/src/com/google/template/soy/i18ndirectives/FormatNumDirective.java
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.i18ndirectives;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.template.soy.data.SoyValue;
import com.google.template.soy.data.restricted.StringData;
import com.google.template.soy.internal.targetexpr.TargetExpr;
import com.google.template.soy.jbcsrc.restricted.BytecodeUtils;
import com.google.template.soy.jbcsrc.restricted.Expression;
import com.google.template.soy.jbcsrc.restricted.JbcSrcPluginContext;
import com.google.template.soy.jbcsrc.restricted.MethodRef;
import com.google.template.soy.jbcsrc.restricted.SoyExpression;
import com.google.template.soy.jbcsrc.restricted.SoyJbcSrcPrintDirective;
import com.google.template.soy.jssrc.restricted.JsExpr;
import com.google.template.soy.jssrc.restricted.SoyLibraryAssistedJsSrcPrintDirective;
import com.google.template.soy.pysrc.restricted.PyExpr;
import com.google.template.soy.pysrc.restricted.PyExprUtils;
import com.google.template.soy.pysrc.restricted.PyFunctionExprBuilder;
import com.google.template.soy.pysrc.restricted.SoyPySrcPrintDirective;
import com.google.template.soy.shared.restricted.ApiCallScopeBindingAnnotations.LocaleString;
import com.google.template.soy.shared.restricted.SoyJavaPrintDirective;
import com.ibm.icu.util.ULocale;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Provider;
import org.objectweb.asm.Type;
/**
* A directive that formats an input number based on Locale of the current SoyMsgBundle. The
* directive takes up to four optional arguments:
*
* <p>The first is a lower-case string describing the type of format to apply, which can be one of
* 'decimal', 'currency', 'percent', 'scientific', 'compact_short', or 'compact_long'. If this
* argument is not provided, the default 'decimal' will be used.
*
* <p>The second argument is the "numbers" keyword passed to the ICU4J's locale. For instance, it
* can be "native" so that we show native characters in languages like arabic (this argument is
* ignored for templates running in JavaScript).
*
* <p>The third and fourth arguments are min and max fractional digits. If only one is supplied,
* this will be treated as # of significant digits after the decimal point, and applied as both min
* and max fractional digits; trailing zeros will not be stripped in this case. If you wish to have
* trailing zeros removed, minFractionalDigits should be set to 0.
*
* <p>Note: the third and fourth arguments are not supported in pysrc. Using them will cause a
* runtime error.
*
* <p>Usage examples: {@code {$value|formatNum} {$value|formatNum:'decimal'}
* {$value|formatNum:'decimal','native'} {$value|formatNum:'decimal','native', 1}
* {$value|formatNum:'decimal','native', 1, 3}}
*
*/
class FormatNumDirective
implements SoyJavaPrintDirective,
SoyLibraryAssistedJsSrcPrintDirective,
SoyPySrcPrintDirective,
SoyJbcSrcPrintDirective {
// Map of format arguments to the Closure Format enum.
private static final ImmutableMap<String, String> JS_ARGS_TO_ENUM =
ImmutableMap.<String, String>builder()
.put("'decimal'", "goog.i18n.NumberFormat.Format.DECIMAL")
.put("'currency'", "goog.i18n.NumberFormat.Format.CURRENCY")
.put("'percent'", "goog.i18n.NumberFormat.Format.PERCENT")
.put("'scientific'", "goog.i18n.NumberFormat.Format.SCIENTIFIC")
.put("'compact_short'", "goog.i18n.NumberFormat.Format.COMPACT_SHORT")
.put("'compact_long'", "goog.i18n.NumberFormat.Format.COMPACT_LONG")
.build();
// This directive can be called with no arguments, with one argument setting the format type,
// or with two arguments setting the format type and the 'numbers' keyword for the ICU4J
// formatter.
private static final ImmutableSet<Integer> VALID_ARGS_SIZES = ImmutableSet.of(0, 1, 2, 3, 4);
private static final ImmutableSet<String> REQUIRED_JS_LIBS =
ImmutableSet.of("goog.i18n.NumberFormat");
private static final String DEFAULT_FORMAT = "decimal";
/**
* Provide the current Locale string.
*
* <p>Note that this Locale value is only used in the Java environment. Closure does not provide a
* clear mechanism to override the NumberFormat defined when the NumberFormat module loads. This
* is probably not a significant loss of functionality, since the primary reason to inject the
* LocaleString is because the Java VM's default Locale may not be the same as the desired Locale
* for the page, while in the JavaScript environment, the value of goog.LOCALE should reliably
* indicate which Locale Soy should use. Similarly, the Python backend relies on implementation
* specific runtime locale support.
*/
private final Provider<String> localeStringProvider;
@Inject
FormatNumDirective(@LocaleString Provider<String> localeStringProvider) {
this.localeStringProvider = localeStringProvider;
}
@Override
public String getName() {
return "|formatNum";
}
@Override
public Set<Integer> getValidArgsSizes() {
return VALID_ARGS_SIZES;
}
@Override
public boolean shouldCancelAutoescape() {
return false;
}
@Override
public SoyValue applyForJava(SoyValue value, List<SoyValue> args) {
ULocale uLocale = I18nUtils.parseULocale(localeStringProvider.get());
String formatType = args.isEmpty() ? DEFAULT_FORMAT : args.get(0).stringValue();
String numbersKeyword = "local";
if (args.size() > 1) {
// A keyword for ULocale was passed (like 'native', for instance, to use native characters).
numbersKeyword = args.get(1).stringValue();
}
// Minimum and maximum fraction digits. If only one value was specified, use as both min and max
// (i.e. significant digits after the decimal point).
Integer minFractionDigits =
args.size() > 2 ? Integer.valueOf((int) args.get(2).numberValue()) : null;
Integer maxFractionDigits =
args.size() > 3 ? Integer.valueOf((int) args.get(3).numberValue()) : minFractionDigits;
double number = value.numberValue();
return StringData.forValue(
I18NDirectivesRuntime.formatNum(
uLocale, number, formatType, numbersKeyword, minFractionDigits, maxFractionDigits));
}
@Override
public JsExpr applyForJsSrc(JsExpr value, List<JsExpr> args) {
String numberFormatType = parseFormat(args);
StringBuilder expr = new StringBuilder();
expr.append("(new goog.i18n.NumberFormat(" + JS_ARGS_TO_ENUM.get(numberFormatType) + "))");
// If min and max fractional digits were specified, apply those. If only one value was
// specified, use as both min and max. If no values were specified, apply default significant
// digits for compact short and long numbers.
if (args.size() > 2) {
String minFractionDigits = args.get(2).getText();
String maxFractionDigits = args.size() > 3 ? args.get(3).getText() : minFractionDigits;
expr.append(".setMinimumFractionDigits(").append(minFractionDigits).append(")");
expr.append(".setMaximumFractionDigits(").append(maxFractionDigits).append(")");
} else if ("'compact_short'".equals(numberFormatType)
|| "'compact_long'".equals(numberFormatType)) {
expr.append(".setSignificantDigits(3)"); // Note that this trims trailing zeros.
}
expr.append(".format(" + value.getText() + ")");
return new JsExpr(expr.toString(), Integer.MAX_VALUE);
}
@Override
public PyExpr applyForPySrc(PyExpr value, List<PyExpr> args) {
String numberFormatType = parseFormat(args);
PyFunctionExprBuilder builder =
new PyFunctionExprBuilder(
PyExprUtils.TRANSLATOR_NAME
// TODO: consider making this a compile-time error. It's a runtime error for now
// so that it works with our integration testing infrastructure.
+ ".format_num")
.addArg(value)
.addArg(new PyExpr(numberFormatType, Integer.MAX_VALUE));
if (args.size() > 2) {
String minFractionDigits = args.get(2).getText();
String maxFractionDigits = args.size() > 3 ? args.get(3).getText() : minFractionDigits;
builder.addArg(minFractionDigits).addArg(maxFractionDigits);
}
return builder.asPyStringExpr();
}
@Override
public ImmutableSet<String> getRequiredJsLibNames() {
return REQUIRED_JS_LIBS;
}
private static final class JbcSrcMethods {
static final MethodRef FORMAT_NUM =
MethodRef.create(
I18NDirectivesRuntime.class,
"formatNum",
ULocale.class,
double.class,
String.class,
String.class,
Integer.class,
Integer.class)
.asNonNullable();
}
@Override
public SoyExpression applyForJbcSrc(
JbcSrcPluginContext context, SoyExpression value, List<SoyExpression> args) {
Expression minFractionDigits =
args.size() > 2
? MethodRef.create(Integer.class, "valueOf", int.class)
.invoke(
BytecodeUtils.numericConversion(args.get(2).unboxAs(long.class), Type.INT_TYPE))
: BytecodeUtils.constantNull(Type.getType(Integer.class));
Expression maxFractionDigits =
args.size() > 3
? MethodRef.create(Integer.class, "valueOf", int.class)
.invoke(
BytecodeUtils.numericConversion(args.get(3).unboxAs(long.class), Type.INT_TYPE))
: minFractionDigits;
return SoyExpression.forString(
JbcSrcMethods.FORMAT_NUM.invoke(
context.getULocale(),
value.coerceToDouble(),
!args.isEmpty()
? args.get(0).unboxAs(String.class)
: BytecodeUtils.constant(DEFAULT_FORMAT),
args.size() > 1 ? args.get(1).unboxAs(String.class) : BytecodeUtils.constant("local"),
minFractionDigits,
maxFractionDigits));
}
/**
* Validates that the provided format matches a supported format, and returns the value, if not,
* this throws an exception.
*
* @param args The list of provided arguments.
* @return String The number format type.
*/
private static String parseFormat(List<? extends TargetExpr> args) {
String numberFormatType = !args.isEmpty() ? args.get(0).getText() : "'" + DEFAULT_FORMAT + "'";
if (!JS_ARGS_TO_ENUM.containsKey(numberFormatType)) {
String validKeys = Joiner.on("', '").join(JS_ARGS_TO_ENUM.keySet());
throw new IllegalArgumentException(
"First argument to formatNum must be " + "constant, and one of: '" + validKeys + "'.");
}
return numberFormatType;
}
}
|
tkeycoin/tkeycoin2
|
lib/primitive/src/utils/Buffer.hpp
|
<reponame>tkeycoin/tkeycoin2<filename>lib/primitive/src/utils/Buffer.hpp<gh_stars>1-10
// Copyright (c) 2017-2019 Tkeycoin Dao. All rights reserved.
// Copyright (c) 2019-2020 TKEY DMCC LLC & Tkeycoin Dao. All rights reserved.
// Website: www.tkeycoin.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.
//
// Buffer.hpp
#pragma once
#include "Reader.hpp"
#include "Writer.hpp"
#include <cstddef>
#include <mutex>
#include <vector>
class Buffer : public Reader, public Writer
{
protected:
/// Мютекс защиты буфера ввода
mutable std::recursive_mutex _mutex;
/// Вектор, контейнер данных буфера
std::vector<char> _data;
/// Смещение на точку, откуда будут извлекаться данные из буфера
size_t _getPosition;
/// Смещение на точку, куда будут добавляться данные в буфер
size_t _putPosition;
public:
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
Buffer(Buffer&&) noexcept = delete;
Buffer& operator=(Buffer&&) noexcept = delete;
Buffer();
virtual ~Buffer() = default;
inline auto& mutex()
{ return _mutex; }
size_t size() const;
virtual const std::vector<char>& data();
const char* dataPtr() const override;
size_t dataLen() const override;
bool show(void* data, size_t length) const override;
bool skip(size_t length) override;
bool read(void* data, size_t length) override;
// virtual std::vector<char>& space() const;
char* spacePtr() const override;
size_t spaceLen() const override;
bool prepare(size_t length) override;
bool forward(size_t length) override;
bool write(const void* data, size_t length) override;
};
|
TheCarvalho/atividades-wikipython
|
EstruturaDeRepeticao/04.py
|
'''
4. Supondo que a população de um país A seja da ordem de 80000 habitantes com uma taxa anual de crescimento de 3% e
que a população de B seja 200000 habitantes com uma taxa de crescimento de 1.5%. Faça um programa que calcule e
escreva o número de anos necessários para que a população do país A ultrapasse ou iguale a população do país B,
mantidas as taxas de crescimento.
'''
anos = 0
mod_a = 80000
mod_b = 200000
while mod_b > mod_a:
mod_a += ((mod_a*3)/100)
mod_b += ((mod_b*1.5)/100)
anos += 1
print(f'O país A ultrapassa o país B em {anos} anos')
print(f'País A: {int(mod_a)} Habitantes')
print(f'País B: {int(mod_b)} Habitantes')
input()
|
eegeo/android-api-samples
|
apisamples/src/main/java/com/eegeo/apisamples/BlueSphereIndoorsActivity.java
|
package com.eegeo.apisamples;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.widget.RelativeLayout;
import com.eegeo.indoors.IndoorMapView;
import com.eegeo.mapapi.EegeoApi;
import com.eegeo.mapapi.EegeoMap;
import com.eegeo.mapapi.MapView;
import com.eegeo.mapapi.geometry.LatLng;
import com.eegeo.mapapi.map.OnMapReadyCallback;
import com.eegeo.mapapi.bluesphere.BlueSphere;
public class BlueSphereIndoorsActivity extends WrldExampleActivity {
private MapView m_mapView;
private EegeoMap m_eegeoMap = null;
private BlueSphere m_bluesphere = null;
private boolean m_locationToggle = false;
private Handler m_timerHandler = new Handler();
private IndoorMapView m_indoorMapView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EegeoApi.init(this, getString(R.string.eegeo_api_key));
setLockedOrientation();
setContentView(R.layout.bluesphere_change_location_activity);
m_mapView = (MapView) findViewById(R.id.bluesphere_change_location_mapview);
m_mapView.onCreate(savedInstanceState);
m_mapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(final EegeoMap map) {
m_eegeoMap = map;
RelativeLayout uiContainer = (RelativeLayout) findViewById(R.id.eegeo_ui_container);
m_indoorMapView = new IndoorMapView(m_mapView, uiContainer, m_eegeoMap);
final LatLng locationA = new LatLng(56.460017, -2.978245);
final LatLng locationB = new LatLng(56.459943, -2.978216);
m_bluesphere = m_eegeoMap.getBlueSphere();
m_bluesphere.setEnabled(true);
m_bluesphere.setPosition(locationA);
m_bluesphere.setIndoorMap("westport_house", 2);
m_timerHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (m_eegeoMap != null) {
m_locationToggle = !m_locationToggle;
LatLng newLocation = m_locationToggle ? locationB : locationA;
m_bluesphere.setPosition(newLocation);
m_timerHandler.postDelayed(this, 2000);
}
}
}, 2000);
}
});
}
@Override
protected void onResume() {
super.onResume();
m_mapView.onResume();
}
@Override
protected void onPause() {
super.onPause();
m_mapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (m_eegeoMap != null) {
m_eegeoMap = null;
}
m_mapView.onDestroy();
}
private void setLockedOrientation() {
if (getResources().getBoolean(R.bool.is_large_device)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
} else {
// force portrait on phone
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
|
vmelnychuk/coding
|
java-core/src/main/java/io/learn/javacore/parallel/ExecutionSchedulingDemo.java
|
package io.learn.javacore.parallel;
class VegetableChopper extends Thread {
public int vegetableCount = 0;
public static boolean chopping = true;
public VegetableChopper(String name) {
this.setName(name);
}
public void run() {
while(chopping) {
System.out.println(this.getName() + " chopped a vegetable!");
vegetableCount++;
}
}
}
public class ExecutionSchedulingDemo {
public static void main(String args[]) throws InterruptedException {
VegetableChopper barron = new VegetableChopper("Barron");
VegetableChopper olivia = new VegetableChopper("Olivia");
barron.start();
olivia.start();
Thread.sleep(1000);
VegetableChopper.chopping = false;
barron.join();
olivia.join();
System.out.format("%s chopped %d vegetables.\n", barron.getName(), barron.vegetableCount);
System.out.format("%s chopped %d vegetables.\n", olivia.getName(), olivia.vegetableCount);
}
}
|
CharLemAznable/char-elves
|
src/test/java/com/github/charlemaznable/core/lang/ListtTest.java
|
package com.github.charlemaznable.core.lang;
import lombok.val;
import org.junit.jupiter.api.Test;
import java.util.List;
import static com.github.charlemaznable.core.lang.Listt.isEmpty;
import static com.github.charlemaznable.core.lang.Listt.newArrayList;
import static com.github.charlemaznable.core.lang.Listt.newArrayListOfType;
import static com.github.charlemaznable.core.lang.Listt.shuffle;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ListtTest {
@Test
public void testUnique() {
val temp = newArrayList("aaa", "aaa", "aaa");
val list = newArrayList(temp.iterator());
val unique = Listt.unique(list);
assertEquals(1, unique.size());
assertEquals("aaa", unique.get(0));
}
@Test
public void testShuffle() {
val list = newArrayList();
List newList = shuffle(list);
assertEquals(newList, list);
for (int i = 0; i < 10; i++) list.add(i);
newList = shuffle(list);
assertNotEquals(newList, list);
}
@Test
public void testIsEmpty() {
val list = newArrayListOfType(1, String.class);
assertFalse(isEmpty(list));
list.clear();
assertTrue(isEmpty(list));
}
}
|
lorraneidevic/twu-biblioteca-lorrane
|
src/main/java/com/twu/biblioteca/view/ListMoviesMenu.java
|
<gh_stars>0
package com.twu.biblioteca.view;
import com.twu.biblioteca.domain.movie.Movie;
import com.twu.biblioteca.domain.movie.MovieController;
import java.util.ArrayList;
public class ListMoviesMenu implements Option {
private MovieController movieController;
public ListMoviesMenu(MovieController movieController) {
this.movieController = movieController;
}
@Override
public void print() {
printAvailableBooks();
}
public void printAvailableBooks() {
ArrayList<Movie> movies = movieController.listMovies();
if(hasAvailableBooks()) {
System.out.println("\nAvailable movies:");
for (int i = 0; i < movies.size(); i++) {
if(!movies.get(i).isBooked()) {
System.out.println((i + 1) + " - " + movies.get(i).getDetails());
}
}
} else {
System.out.println("\nThere is no movie left to checkout.");
}
}
private boolean hasAvailableBooks(){
return movieController.listAvailableMovies().size() > 0;
}
@Override
public String getName() {
return "List Movies";
}
}
|
Yukikamome316/MineCode
|
src/src/primary/str.cpp
|
<filename>src/src/primary/str.cpp
#include <eval.h>
#include <primary/str.hpp>
parserTypes::primary::Str::~Str() {}
void parserTypes::primary::Str::eval(parserCore& ctx, int dest) {}
|
doutoraovivo/doutoraovivo.github.io
|
catalog/src/components/operations/operation-list/ko/operationListViewModelBinder.js
|
<filename>catalog/src/components/operations/operation-list/ko/operationListViewModelBinder.js
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OperationListViewModelBinder = void 0;
const operationListViewModel_1 = require("./operationListViewModel");
const operationListModel_1 = require("../operationListModel");
class OperationListViewModelBinder {
constructor(eventManager) {
this.eventManager = eventManager;
}
modelToViewModel(model, viewModel, bindingContext) {
return __awaiter(this, void 0, void 0, function* () {
if (!viewModel) {
viewModel = new operationListViewModel_1.OperationListViewModel();
}
viewModel.runtimeConfig(JSON.stringify({
allowSelection: model.allowSelection,
wrapText: model.wrapText,
showToggleUrlPath: model.showToggleUrlPath,
defaultShowUrlPath: model.defaultShowUrlPath,
defaultGroupByTagToEnabled: model.defaultGroupByTagToEnabled,
detailsPageUrl: model.detailsPageHyperlink
? model.detailsPageHyperlink.href
: undefined
}));
viewModel["widgetBinding"] = {
displayName: "List of operations",
model: model,
draggable: true,
flow: "block",
editor: "operation-list-editor",
applyChanges: (updatedModel) => __awaiter(this, void 0, void 0, function* () {
yield this.modelToViewModel(updatedModel, viewModel, bindingContext);
this.eventManager.dispatchEvent("onContentUpdate");
})
};
return viewModel;
});
}
canHandleModel(model) {
return model instanceof operationListModel_1.OperationListModel;
}
}
exports.OperationListViewModelBinder = OperationListViewModelBinder;
//# sourceMappingURL=operationListViewModelBinder.js.map
|
akashtalole/python-flask-restful-api
|
app/api/schema/email_notifications.py
|
from marshmallow_jsonapi import fields
from marshmallow_jsonapi.flask import Relationship
from app.api.helpers.utilities import dasherize
from app.api.schema.base import SoftDeletionSchema
from utils.common import use_defaults
@use_defaults()
class EmailNotificationSchema(SoftDeletionSchema):
"""
API Schema for email notification Model
"""
class Meta:
"""
Meta class for email notification API schema
"""
type_ = 'email-notification'
self_view = 'v1.email_notification_detail'
self_view_kwargs = {'id': '<id>'}
inflect = dasherize
id = fields.Integer(dump_only=True)
next_event = fields.Boolean(default=False, allow_none=True)
new_paper = fields.Boolean(default=False, allow_none=True)
session_accept_reject = fields.Boolean(default=False, allow_none=True)
session_schedule = fields.Boolean(default=False, allow_none=True)
after_ticket_purchase = fields.Boolean(default=True, allow_none=True)
event_id = fields.Integer(allow_none=True)
event = Relationship(attribute='event',
self_view='v1.email_notification_event',
self_view_kwargs={'id': '<id>'},
related_view='v1.event_detail',
related_view_kwargs={'email_notification_id': '<id>'},
schema='EventSchemaPublic',
type_='event'
)
user = Relationship(attribute='user',
self_view='v1.email_notification_user',
self_view_kwargs={'id': '<id>'},
related_view='v1.user_detail',
related_view_kwargs={'email_notification_id': '<id>'},
schema='UserSchema',
type_='user'
)
|
juncture-short/sacnview
|
src/sacn/sacnsocket.h
|
// Copyright 2016 <NAME>
// http://www.tomsteer.net
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SACNSOCKET_H
#define SACNSOCKET_H
#include <QObject>
#include <QUdpSocket>
#include <QNetworkInterface>
class sACNRxSocket : public QUdpSocket
{
Q_OBJECT
public:
sACNRxSocket(QNetworkInterface iface, QObject *parent = Q_NULLPTR);
enum eBindStatus
{
BIND_UNKNOWN,
BIND_OK,
BIND_FAILED
};
struct sBindStatus
{
sBindStatus() {
unicast = BIND_UNKNOWN;
multicast = BIND_UNKNOWN;
}
eBindStatus unicast;
eBindStatus multicast;
};
sBindStatus bind(quint16 universe);
int getBoundUniverse() { return m_universe; }
QNetworkInterface getBoundInterface() { return m_interface; }
private:
QNetworkInterface m_interface;
int m_universe;
};
class sACNTxSocket : public QUdpSocket
{
Q_OBJECT
public:
sACNTxSocket(QNetworkInterface iface, QObject *parent = Q_NULLPTR);
bool bind();
//qint64 writeDatagram(const QNetworkDatagram &datagram);
qint64 writeDatagram(const char *data, qint64 len, const QHostAddress &host, quint16 port);
inline qint64 writeDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)
{ return writeDatagram(datagram.constData(), datagram.size(), host, port); }
private:
QNetworkInterface m_interface;
};
#endif // SACNSOCKET_H
|
rbabari/blender
|
intern/cycles/util/util_logging.h
|
<filename>intern/cycles/util/util_logging.h
/*
* Copyright 2011-2014 Blender Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __UTIL_LOGGING_H__
#define __UTIL_LOGGING_H__
#if defined(WITH_CYCLES_LOGGING) && !defined(__KERNEL_GPU__)
# include <gflags/gflags.h>
# include <glog/logging.h>
#endif
#include <iostream>
CCL_NAMESPACE_BEGIN
#if !defined(WITH_CYCLES_LOGGING) || defined(__KERNEL_GPU__)
class StubStream {
public:
template<class T> StubStream &operator<<(const T &)
{
return *this;
}
};
class LogMessageVoidify {
public:
LogMessageVoidify()
{
}
void operator&(StubStream &)
{
}
};
# define LOG_SUPPRESS() (true) ? ((void)0) : LogMessageVoidify() & StubStream()
# define LOG(severity) LOG_SUPPRESS()
# define VLOG(severity) LOG_SUPPRESS()
# define VLOG_IF(severity, condition) LOG_SUPPRESS()
#endif
#define VLOG_ONCE(level, flag) \
if (!flag) \
flag = true, VLOG(level)
struct int2;
struct float3;
void util_logging_init(const char *argv0);
void util_logging_start();
void util_logging_verbosity_set(int verbosity);
std::ostream &operator<<(std::ostream &os, const int2 &value);
std::ostream &operator<<(std::ostream &os, const float3 &value);
CCL_NAMESPACE_END
#endif /* __UTIL_LOGGING_H__ */
|
targeter21/drools
|
drools-model/drools-mvel-compiler/src/main/java/org/drools/mvelcompiler/bigdecimal/BigDecimalConversion.java
|
package org.drools.mvelcompiler.bigdecimal;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Optional;
import com.github.javaparser.ast.expr.AssignExpr;
import org.drools.mvelcompiler.ast.AssignExprT;
import org.drools.mvelcompiler.ast.MethodCallExprT;
import org.drools.mvelcompiler.ast.TypedExpression;
import static java.util.Collections.singletonList;
import static java.util.Optional.of;
public abstract class BigDecimalConversion {
TypedExpression rhs;
BigDecimalConversion(TypedExpression rhs) {
this.rhs = rhs;
}
public static BigDecimalConversion shouldConvertPlusEqualsOperatorBigDecimal(AssignExpr n, Optional<TypedExpression> optRHS) {
if(!optRHS.isPresent() || (!optRHS.get().getType().isPresent())) {
return new DoNotConvert(null);
}
TypedExpression rhs = optRHS.get();
Optional<Type> optRHSType = rhs.getType();
if(!optRHSType.isPresent()) {
return new DoNotConvert(null);
}
Type rhsType = optRHSType.get();
boolean isBigDecimal = BigDecimal.class.equals(rhsType);
if(isBigDecimal) {
if(AssignExpr.Operator.PLUS.equals(n.getOperator())) {
return new ConvertPlus(rhs);
} else if(AssignExpr.Operator.MINUS.equals(n.getOperator())) {
return new ConvertMinus(rhs);
} else {
return new DoNotConvert(rhs);
}
}
return new DoNotConvert(null);
}
public abstract boolean shouldConvert();
protected abstract TypedExpression convertPlusEqualsOperatorBigDecimal(TypedExpression target);
public TypedExpression convertExpression(TypedExpression target) {
TypedExpression arithmeticExpression = convertPlusEqualsOperatorBigDecimal(target);
return new AssignExprT(AssignExpr.Operator.ASSIGN, target, arithmeticExpression);
}
static class ConvertPlus extends BigDecimalConversion {
ConvertPlus(TypedExpression rhs) {
super(rhs);
}
@Override
public boolean shouldConvert() {
return true;
}
@Override
public TypedExpression convertPlusEqualsOperatorBigDecimal(TypedExpression target) {
return new MethodCallExprT("add", of(target), singletonList(rhs), of(BigDecimal.class));
}
}
static class ConvertMinus extends BigDecimalConversion {
ConvertMinus(TypedExpression rhs) {
super(rhs);
}
@Override
public boolean shouldConvert() {
return true;
}
@Override
public TypedExpression convertPlusEqualsOperatorBigDecimal(TypedExpression target) {
return new MethodCallExprT("subtract", of(target), singletonList(rhs), of(BigDecimal.class));
}
}
static class DoNotConvert extends BigDecimalConversion {
DoNotConvert(TypedExpression rhs) {
super(rhs);
}
@Override
public boolean shouldConvert() {
return false;
}
@Override
public TypedExpression convertPlusEqualsOperatorBigDecimal(TypedExpression target) {
throw new UnsupportedOperationException();
}
}
}
|
codetaylor/artisan-worktables-1.16
|
src/main/java/com/codetaylor/mc/artisanworktables/common/tile/ToolboxTileEntity.java
|
package com.codetaylor.mc.artisanworktables.common.tile;
import com.codetaylor.mc.artisanworktables.ArtisanWorktablesMod;
import com.codetaylor.mc.artisanworktables.ArtisanWorktablesModCommonConfig;
import com.codetaylor.mc.artisanworktables.common.block.ToolboxMechanicalBlock;
import com.codetaylor.mc.artisanworktables.common.tile.handler.ToolboxItemStackHandler;
import com.codetaylor.mc.artisanworktables.common.util.ToolValidationHelper;
import com.codetaylor.mc.athenaeum.network.spi.tile.ITileData;
import com.codetaylor.mc.athenaeum.network.spi.tile.TileEntityDataBase;
import com.codetaylor.mc.athenaeum.network.spi.tile.data.TileDataItemStackHandler;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.inventory.ItemStackHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.util.Direction;
import net.minecraft.util.NonNullList;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.function.Predicate;
public class ToolboxTileEntity
extends TileEntityDataBase {
public static final String NAME = "toolbox";
private final ToolboxItemStackHandler itemStackHandler;
private final LazyOptional<ItemStackHandler> itemCapability;
public ToolboxTileEntity() {
super(
ArtisanWorktablesMod.TileEntityTypes.TOOLBOX,
ArtisanWorktablesMod.getProxy().getTileDataService()
);
Predicate<ItemStack> predicate = itemStack -> itemStack.isEmpty()
|| this.allowNonToolItems()
|| ToolValidationHelper.isValidTool(itemStack, ArtisanWorktablesMod.getProxy().getRecipeManager());
this.itemStackHandler = new ToolboxItemStackHandler(predicate, 27);
this.itemStackHandler.addObserver((stackHandler, slotIndex) -> this.markDirty());
this.itemCapability = LazyOptional.of(() -> this.itemStackHandler);
this.registerTileDataForNetwork(new ITileData[]{
new TileDataItemStackHandler<>(this.itemStackHandler)
});
}
// ---------------------------------------------------------------------------
// Accessors
// ---------------------------------------------------------------------------
public boolean isMechanical() {
return this.world != null
&& this.world.getBlockState(this.pos).getBlock() instanceof ToolboxMechanicalBlock;
}
public ToolboxItemStackHandler getItemStackHandler() {
return this.itemStackHandler;
}
public boolean canPlayerUse(PlayerEntity player) {
return this.world != null
&& this.world.getTileEntity(this.getPos()) == this
&& player.getDistanceSq(this.pos.getX() + 0.5, this.pos.getY() + 0.5, this.pos.getZ() + 0.5) <= 64;
}
private boolean allowNonToolItems() {
return ArtisanWorktablesModCommonConfig.allowNonToolItemsInToolboxes;
}
// ---------------------------------------------------------------------------
// Capability
// ---------------------------------------------------------------------------
@Nonnull
@Override
public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> capability, @Nullable Direction side) {
if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
return this.itemCapability.cast();
}
return super.getCapability(capability, side);
}
// ---------------------------------------------------------------------------
// Serialization
// ---------------------------------------------------------------------------
@Override
public void read(@Nonnull BlockState state, @Nonnull CompoundNBT nbt) {
super.read(state, nbt);
this.itemStackHandler.deserializeNBT(nbt.getCompound("itemStackHandler"));
if (nbt.contains("Items", Constants.NBT.TAG_LIST)) {
NonNullList<ItemStack> itemStacks = NonNullList.withSize(27, ItemStack.EMPTY);
ItemStackHelper.loadAllItems(nbt, itemStacks);
for (int i = 0; i < 27; i++) {
this.itemStackHandler.forceStackInSlot(i, itemStacks.get(i));
}
}
}
@Nonnull
@Override
public CompoundNBT write(@Nonnull CompoundNBT nbt) {
super.write(nbt);
nbt.put("itemStackHandler", this.itemStackHandler.serializeNBT());
return nbt;
}
}
|
OnBlock/KiloEssentials
|
src/main/java/org/kilocraft/essentials/api/event/eventImpl/playerEventsImpl/PlayerEvent$OnPlaceBlockImpl.java
|
package org.kilocraft.essentials.api.event.eventImpl.playerEventsImpl;
import net.minecraft.block.Block;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import org.kilocraft.essentials.api.event.playerEvents.PlayerEvent$OnPlaceBlock;
public class PlayerEvent$OnPlaceBlockImpl implements PlayerEvent$OnPlaceBlock {
private final ServerPlayerEntity player;
private final ItemUsageContext context;
private final Block block;
private boolean isCancelled;
public PlayerEvent$OnPlaceBlockImpl(ItemUsageContext itemUsageContext_1, ServerPlayerEntity player, Block block) {
this.context = itemUsageContext_1;
this.player = player;
this.block = block;
}
public ServerPlayerEntity getPlayer() {
return player;
}
@Override
public boolean isCancelled() {
return isCancelled;
}
@Override
public void setCancelled(boolean isCancelled) {
this.isCancelled = isCancelled;
}
@Override
public Vec3d getLocation() {
BlockPos pos = context.getBlockPos();
return new Vec3d(pos.getX(), pos.getY(), pos.getZ());
}
@Override
public Block getBlock() {
return block;
}
}
|
Valeri12580/Gladiators
|
src/main/java/project/gladiators/service/serviceModels/SubCategoryServiceModel.java
|
<gh_stars>0
package project.gladiators.service.serviceModels;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Set;
@Getter
@Setter
@NoArgsConstructor
public class SubCategoryServiceModel extends BaseServiceModel{
private String name;
private boolean isEmpty;
private Set<ProductServiceModel> products;
private CategoryServiceModel category;
}
|
allegro/akubra
|
internal/akubra/storages/merger/bucket_meta_data.go
|
<reponame>allegro/akubra<gh_stars>10-100
package merger
import (
"bytes"
"io/ioutil"
"net/http"
"github.com/allegro/akubra/internal/akubra/log"
backend "github.com/allegro/akubra/internal/akubra/storages/backend"
)
const (
inconsitentRespInfo = "Inconsistent responses among backends"
warningHeader = "X-akubra-warning"
)
// MergePartially will return first success response that will have 200 or 203 status code
// to distinguish identical backend responses from differing ones.
// Applicable for ?acl ?policy ?cors ?metrics ?logging ?location ?lifecycle
func MergePartially(firstResponse backend.Response, successes []backend.Response) (*http.Response, error) {
resp := firstResponse.Response
firstResponseBodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Could not read first response body reqID %s, reason %s", firstResponse.ReqID(), err)
}
for _, bresp := range successes {
responseBodyBytes, readErr := ioutil.ReadAll(bresp.Response.Body)
if readErr != nil || !bytes.Equal(firstResponseBodyBytes, responseBodyBytes) {
resp.Header.Set(warningHeader, inconsitentRespInfo)
}
err = bresp.DiscardBody()
if err != nil {
log.Printf("Cannot close success response body reqId %s, reason: %s", firstResponse.ReqID(), err)
}
}
resp.Body = ioutil.NopCloser(bytes.NewReader(firstResponseBodyBytes))
return resp, firstResponse.Error
}
|
fbobee/Alpenglow
|
python/cpp_bridge/FactorModelReader.h
|
#ifndef FACTOR_MODEL_READER_H
#define FACTOR_MODEL_READER_H
#include <fstream>
#include <vector>
#include <string>
#include "models/factor/FactorModel.h"
#include "models/factor/EigenFactorModel.h"
using namespace std;
struct FactorRepr{
int entity;
vector<double> factors;
};
struct UserItemFactors{
vector<FactorRepr> user_factors;
vector<FactorRepr> item_factors;
};
class FactorModelReader{
public:
UserItemFactors read(string file_name, int dimension){
ifstream ifs(file_name, ios::binary);
FactorsParameters p;
p.begin_min = -0.01;
p.begin_max = 0.01;
p.dimension = dimension;
Factors userf(p);
Factors itemf(p);
userf.read(ifs);
itemf.read(ifs);
ifs.close();
UserItemFactors uifactors;
for(uint i=0;i<userf.factors.size();i++){
if(userf.factors[i]!=NULL){
FactorRepr user_vector;
user_vector.entity=i;
for(int j=0;j<userf.dimension;j++){
user_vector.factors.push_back(userf.factors[i]->at(j));
}
uifactors.user_factors.push_back(user_vector);
}
}
for(uint i=0;i<itemf.factors.size();i++){
if(itemf.factors[i]!=NULL){
FactorRepr item_vector;
item_vector.entity=i;
for(int j=0;j<itemf.dimension;j++){
item_vector.factors.push_back(itemf.factors[i]->at(j));
}
uifactors.item_factors.push_back(item_vector);
}
}
return uifactors;
}
};
class EigenFactorModelReader{
public:
UserItemFactors read(string file_name){
ifstream ifs(file_name, ios::binary);
EigenFactorModelParameters p;
EigenFactorModel m(&p);
m.read(ifs);
ifs.close();
UserItemFactors uifactors;
auto &user_factors = m.get_user_factors();
auto &item_factors = m.get_item_factors();
for(uint i=0;i<user_factors.factors.rows();i++){
FactorRepr user_vector;
user_vector.entity=i;
for(int j=0;j<user_factors.factors.cols();j++){
user_vector.factors.push_back(user_factors.factors(i,j));
}
uifactors.user_factors.push_back(user_vector);
}
for(uint i=0;i<item_factors.factors.rows();i++){
FactorRepr item_vector;
item_vector.entity=i;
for(int j=0;j<item_factors.factors.cols();j++){
item_vector.factors.push_back(item_factors.factors(i,j));
}
uifactors.item_factors.push_back(item_vector);
}
return uifactors;
}
};
#endif
|
bingchunjin/1806_SDK
|
linux-4.14.90-dev/linux-4.14.90/drivers/ide/serverworks.c
|
<reponame>bingchunjin/1806_SDK
/*
* Copyright (C) 1998-2000 <NAME>
* Copyright (C) 1998-2000 <NAME>
* Copyright (C) 1998-2000 <NAME> <<EMAIL>>
* Copyright (C) 2007-2010 <NAME>
* Portions copyright (c) 2001 Sun Microsystems
*
*
* RCC/ServerWorks IDE driver for Linux
*
* OSB4: `Open South Bridge' IDE Interface (fn 1)
* supports UDMA mode 2 (33 MB/s)
*
* CSB5: `Champion South Bridge' IDE Interface (fn 1)
* all revisions support UDMA mode 4 (66 MB/s)
* revision A2.0 and up support UDMA mode 5 (100 MB/s)
*
* *** The CSB5 does not provide ANY register ***
* *** to detect 80-conductor cable presence. ***
*
* CSB6: `Champion South Bridge' IDE Interface (optional: third channel)
*
* HT1000: AKA BCM5785 - Hypertransport Southbridge for Opteron systems. IDE
* controller same as the CSB6. Single channel ATA100 only.
*
* Documentation:
* Available under NDA only. Errata info very hard to get.
*
*/
#include <linux/types.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <asm/io.h>
#define DRV_NAME "serverworks"
#define SVWKS_CSB5_REVISION_NEW 0x92 /* min PCI_REVISION_ID for UDMA5 (A2.0) */
#define SVWKS_CSB6_REVISION 0xa0 /* min PCI_REVISION_ID for UDMA4 (A1.0) */
/* Seagate Barracuda ATA IV Family drives in UDMA mode 5
* can overrun their FIFOs when used with the CSB5 */
static const char *svwks_bad_ata100[] = {
"ST320011A",
"ST340016A",
"ST360021A",
"ST380021A",
NULL
};
static int check_in_drive_lists (ide_drive_t *drive, const char **list)
{
char *m = (char *)&drive->id[ATA_ID_PROD];
while (*list)
if (!strcmp(*list++, m))
return 1;
return 0;
}
static u8 svwks_udma_filter(ide_drive_t *drive)
{
struct pci_dev *dev = to_pci_dev(drive->hwif->dev);
if (dev->device == PCI_DEVICE_ID_SERVERWORKS_HT1000IDE) {
return 0x1f;
} else if (dev->revision < SVWKS_CSB5_REVISION_NEW) {
return 0x07;
} else {
u8 btr = 0, mode, mask;
pci_read_config_byte(dev, 0x5A, &btr);
mode = btr & 0x3;
/* If someone decides to do UDMA133 on CSB5 the same
issue will bite so be inclusive */
if (mode > 2 && check_in_drive_lists(drive, svwks_bad_ata100))
mode = 2;
switch(mode) {
case 3: mask = 0x3f; break;
case 2: mask = 0x1f; break;
case 1: mask = 0x07; break;
default: mask = 0x00; break;
}
return mask;
}
}
static u8 svwks_csb_check (struct pci_dev *dev)
{
switch (dev->device) {
case PCI_DEVICE_ID_SERVERWORKS_CSB5IDE:
case PCI_DEVICE_ID_SERVERWORKS_CSB6IDE:
case PCI_DEVICE_ID_SERVERWORKS_CSB6IDE2:
case PCI_DEVICE_ID_SERVERWORKS_HT1000IDE:
return 1;
default:
break;
}
return 0;
}
static void svwks_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
static const u8 pio_modes[] = { 0x5d, 0x47, 0x34, 0x22, 0x20 };
static const u8 drive_pci[] = { 0x41, 0x40, 0x43, 0x42 };
struct pci_dev *dev = to_pci_dev(hwif->dev);
const u8 pio = drive->pio_mode - XFER_PIO_0;
pci_write_config_byte(dev, drive_pci[drive->dn], pio_modes[pio]);
if (svwks_csb_check(dev)) {
u16 csb_pio = 0;
pci_read_config_word(dev, 0x4a, &csb_pio);
csb_pio &= ~(0x0f << (4 * drive->dn));
csb_pio |= (pio << (4 * drive->dn));
pci_write_config_word(dev, 0x4a, csb_pio);
}
}
static void svwks_set_dma_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
static const u8 udma_modes[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
static const u8 dma_modes[] = { 0x77, 0x21, 0x20 };
static const u8 drive_pci2[] = { 0x45, 0x44, 0x47, 0x46 };
struct pci_dev *dev = to_pci_dev(hwif->dev);
const u8 speed = drive->dma_mode;
u8 unit = drive->dn & 1;
u8 ultra_enable = 0, ultra_timing = 0, dma_timing = 0;
pci_read_config_byte(dev, (0x56|hwif->channel), &ultra_timing);
pci_read_config_byte(dev, 0x54, &ultra_enable);
ultra_timing &= ~(0x0F << (4*unit));
ultra_enable &= ~(0x01 << drive->dn);
if (speed >= XFER_UDMA_0) {
dma_timing |= dma_modes[2];
ultra_timing |= (udma_modes[speed - XFER_UDMA_0] << (4 * unit));
ultra_enable |= (0x01 << drive->dn);
} else if (speed >= XFER_MW_DMA_0)
dma_timing |= dma_modes[speed - XFER_MW_DMA_0];
pci_write_config_byte(dev, drive_pci2[drive->dn], dma_timing);
pci_write_config_byte(dev, (0x56|hwif->channel), ultra_timing);
pci_write_config_byte(dev, 0x54, ultra_enable);
}
static int init_chipset_svwks(struct pci_dev *dev)
{
unsigned int reg;
u8 btr;
/* force Master Latency Timer value to 64 PCICLKs */
pci_write_config_byte(dev, PCI_LATENCY_TIMER, 0x40);
/* OSB4 : South Bridge and IDE */
if (dev->device == PCI_DEVICE_ID_SERVERWORKS_OSB4IDE) {
struct pci_dev *isa_dev =
pci_get_device(PCI_VENDOR_ID_SERVERWORKS,
PCI_DEVICE_ID_SERVERWORKS_OSB4, NULL);
if (isa_dev) {
pci_read_config_dword(isa_dev, 0x64, ®);
reg &= ~0x00002000; /* disable 600ns interrupt mask */
if(!(reg & 0x00004000))
printk(KERN_DEBUG DRV_NAME " %s: UDMA not BIOS "
"enabled.\n", pci_name(dev));
reg |= 0x00004000; /* enable UDMA/33 support */
pci_write_config_dword(isa_dev, 0x64, reg);
pci_dev_put(isa_dev);
}
}
/* setup CSB5/CSB6 : South Bridge and IDE option RAID */
else if ((dev->device == PCI_DEVICE_ID_SERVERWORKS_CSB5IDE) ||
(dev->device == PCI_DEVICE_ID_SERVERWORKS_CSB6IDE) ||
(dev->device == PCI_DEVICE_ID_SERVERWORKS_CSB6IDE2)) {
/* Third Channel Test */
if (!(PCI_FUNC(dev->devfn) & 1)) {
struct pci_dev * findev = NULL;
u32 reg4c = 0;
findev = pci_get_device(PCI_VENDOR_ID_SERVERWORKS,
PCI_DEVICE_ID_SERVERWORKS_CSB5, NULL);
if (findev) {
pci_read_config_dword(findev, 0x4C, ®4c);
reg4c &= ~0x000007FF;
reg4c |= 0x00000040;
reg4c |= 0x00000020;
pci_write_config_dword(findev, 0x4C, reg4c);
pci_dev_put(findev);
}
outb_p(0x06, 0x0c00);
dev->irq = inb_p(0x0c01);
} else {
struct pci_dev * findev = NULL;
u8 reg41 = 0;
findev = pci_get_device(PCI_VENDOR_ID_SERVERWORKS,
PCI_DEVICE_ID_SERVERWORKS_CSB6, NULL);
if (findev) {
pci_read_config_byte(findev, 0x41, ®41);
reg41 &= ~0x40;
pci_write_config_byte(findev, 0x41, reg41);
pci_dev_put(findev);
}
/*
* This is a device pin issue on CSB6.
* Since there will be a future raid mode,
* early versions of the chipset require the
* interrupt pin to be set, and it is a compatibility
* mode issue.
*/
if ((dev->class >> 8) == PCI_CLASS_STORAGE_IDE)
dev->irq = 0;
}
// pci_read_config_dword(dev, 0x40, &pioreg)
// pci_write_config_dword(dev, 0x40, 0x99999999);
// pci_read_config_dword(dev, 0x44, &dmareg);
// pci_write_config_dword(dev, 0x44, 0xFFFFFFFF);
/* setup the UDMA Control register
*
* 1. clear bit 6 to enable DMA
* 2. enable DMA modes with bits 0-1
* 00 : legacy
* 01 : udma2
* 10 : udma2/udma4
* 11 : udma2/udma4/udma5
*/
pci_read_config_byte(dev, 0x5A, &btr);
btr &= ~0x40;
if (!(PCI_FUNC(dev->devfn) & 1))
btr |= 0x2;
else
btr |= (dev->revision >= SVWKS_CSB5_REVISION_NEW) ? 0x3 : 0x2;
pci_write_config_byte(dev, 0x5A, btr);
}
/* Setup HT1000 SouthBridge Controller - Single Channel Only */
else if (dev->device == PCI_DEVICE_ID_SERVERWORKS_HT1000IDE) {
pci_read_config_byte(dev, 0x5A, &btr);
btr &= ~0x40;
btr |= 0x3;
pci_write_config_byte(dev, 0x5A, btr);
}
return 0;
}
static u8 ata66_svwks_svwks(ide_hwif_t *hwif)
{
return ATA_CBL_PATA80;
}
/* On Dell PowerEdge servers with a CSB5/CSB6, the top two bits
* of the subsystem device ID indicate presence of an 80-pin cable.
* Bit 15 clear = secondary IDE channel does not have 80-pin cable.
* Bit 15 set = secondary IDE channel has 80-pin cable.
* Bit 14 clear = primary IDE channel does not have 80-pin cable.
* Bit 14 set = primary IDE channel has 80-pin cable.
*/
static u8 ata66_svwks_dell(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
if (dev->subsystem_vendor == PCI_VENDOR_ID_DELL &&
dev->vendor == PCI_VENDOR_ID_SERVERWORKS &&
(dev->device == PCI_DEVICE_ID_SERVERWORKS_CSB5IDE ||
dev->device == PCI_DEVICE_ID_SERVERWORKS_CSB6IDE))
return ((1 << (hwif->channel + 14)) &
dev->subsystem_device) ? ATA_CBL_PATA80 : ATA_CBL_PATA40;
return ATA_CBL_PATA40;
}
/* Sun Cobalt Alpine hardware avoids the 80-pin cable
* detect issue by attaching the drives directly to the board.
* This check follows the Dell precedent (how scary is that?!)
*
* WARNING: this only works on Alpine hardware!
*/
static u8 ata66_svwks_cobalt(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
if (dev->subsystem_vendor == PCI_VENDOR_ID_SUN &&
dev->vendor == PCI_VENDOR_ID_SERVERWORKS &&
dev->device == PCI_DEVICE_ID_SERVERWORKS_CSB5IDE)
return ((1 << (hwif->channel + 14)) &
dev->subsystem_device) ? ATA_CBL_PATA80 : ATA_CBL_PATA40;
return ATA_CBL_PATA40;
}
static u8 svwks_cable_detect(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
/* Server Works */
if (dev->subsystem_vendor == PCI_VENDOR_ID_SERVERWORKS)
return ata66_svwks_svwks (hwif);
/* Dell PowerEdge */
if (dev->subsystem_vendor == PCI_VENDOR_ID_DELL)
return ata66_svwks_dell (hwif);
/* Cobalt Alpine */
if (dev->subsystem_vendor == PCI_VENDOR_ID_SUN)
return ata66_svwks_cobalt (hwif);
/* Per Specified Design by OEM, and ASIC Architect */
if ((dev->device == PCI_DEVICE_ID_SERVERWORKS_CSB6IDE) ||
(dev->device == PCI_DEVICE_ID_SERVERWORKS_CSB6IDE2))
return ATA_CBL_PATA80;
return ATA_CBL_PATA40;
}
static const struct ide_port_ops osb4_port_ops = {
.set_pio_mode = svwks_set_pio_mode,
.set_dma_mode = svwks_set_dma_mode,
};
static const struct ide_port_ops svwks_port_ops = {
.set_pio_mode = svwks_set_pio_mode,
.set_dma_mode = svwks_set_dma_mode,
.udma_filter = svwks_udma_filter,
.cable_detect = svwks_cable_detect,
};
static const struct ide_port_info serverworks_chipsets[] = {
{ /* 0: OSB4 */
.name = DRV_NAME,
.init_chipset = init_chipset_svwks,
.port_ops = &osb4_port_ops,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = 0x00, /* UDMA is problematic on OSB4 */
},
{ /* 1: CSB5 */
.name = DRV_NAME,
.init_chipset = init_chipset_svwks,
.port_ops = &svwks_port_ops,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
},
{ /* 2: CSB6 */
.name = DRV_NAME,
.init_chipset = init_chipset_svwks,
.port_ops = &svwks_port_ops,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
},
{ /* 3: CSB6-2 */
.name = DRV_NAME,
.init_chipset = init_chipset_svwks,
.port_ops = &svwks_port_ops,
.host_flags = IDE_HFLAG_SINGLE,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
},
{ /* 4: HT1000 */
.name = DRV_NAME,
.init_chipset = init_chipset_svwks,
.port_ops = &svwks_port_ops,
.host_flags = IDE_HFLAG_SINGLE,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
}
};
/**
* svwks_init_one - called when a OSB/CSB is found
* @dev: the svwks device
* @id: the matching pci id
*
* Called when the PCI registration layer (or the IDE initialization)
* finds a device matching our IDE device tables.
*/
static int svwks_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
struct ide_port_info d;
u8 idx = id->driver_data;
d = serverworks_chipsets[idx];
if (idx == 1)
d.host_flags |= IDE_HFLAG_CLEAR_SIMPLEX;
else if (idx == 2 || idx == 3) {
if ((PCI_FUNC(dev->devfn) & 1) == 0) {
if (pci_resource_start(dev, 0) != 0x01f1)
d.host_flags |= IDE_HFLAG_NON_BOOTABLE;
d.host_flags |= IDE_HFLAG_SINGLE;
} else
d.host_flags &= ~IDE_HFLAG_SINGLE;
}
return ide_pci_init_one(dev, &d, NULL);
}
static const struct pci_device_id svwks_pci_tbl[] = {
{ PCI_VDEVICE(SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_OSB4IDE), 0 },
{ PCI_VDEVICE(SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_CSB5IDE), 1 },
{ PCI_VDEVICE(SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_CSB6IDE), 2 },
{ PCI_VDEVICE(SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_CSB6IDE2), 3 },
{ PCI_VDEVICE(SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_HT1000IDE), 4 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, svwks_pci_tbl);
static struct pci_driver svwks_pci_driver = {
.name = "Serverworks_IDE",
.id_table = svwks_pci_tbl,
.probe = svwks_init_one,
.remove = ide_pci_remove,
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init svwks_ide_init(void)
{
return ide_pci_register_driver(&svwks_pci_driver);
}
static void __exit svwks_ide_exit(void)
{
pci_unregister_driver(&svwks_pci_driver);
}
module_init(svwks_ide_init);
module_exit(svwks_ide_exit);
MODULE_AUTHOR("<NAME>. <NAME>, <NAME>, <NAME>");
MODULE_DESCRIPTION("PCI driver module for Serverworks OSB4/CSB5/CSB6 IDE");
MODULE_LICENSE("GPL");
|
Khuongnb1997/game-aladdin
|
game/prefabs/FinishEntrancePrefab.cpp
|
<filename>game/prefabs/FinishEntrancePrefab.cpp<gh_stars>1-10
#include "FinishEntrancePrefab.h"
#include "../Define.h"
USING_NAMESPACE_ALA;
ALA_CLASS_SOURCE_1(FinishEntrancePrefab, ala::PrefabV2)
void FinishEntrancePrefab::doInstantiate( ala::GameObject* object, std::istringstream& argsStream ) const {
// args
const auto width = nextFloat( argsStream );
const auto height = nextFloat( argsStream );
// components
const auto body = new Rigidbody( object, PhysicsMaterial(), ALA_BODY_TYPE_STATIC );
const auto collider = new Collider( object, true, Vec2(), Size( width, height ) );
// collider renderers
// new ColliderRenderer( collider );
// flags
collider->setFlags( COLLIDE_ALADDIN_FLAG | STATIC_FLAG );
collider->ignoreIfHasAnyFlags( STATIC_FLAG );
// configurations
object->setLayer( "Debug" );
object->setTag( FINISH_ENTRANCE_TAG );
}
|
asedl/XpaPDPM_Calc
|
TestData/HomeHealthGrouper/HH_PPS_Java_source/com/mmm/cms/homehealth/vut/oasis/ValidateStageMostProblematicPressureUlcer_OASIS_C2.java
|
<reponame>asedl/XpaPDPM_Calc
/*
* Home Health Grouper
* Developer for the Center for Medicare and Medicaid Services CMS
* by 3M Health Information Systems for CMS Home Health.
*
* All code is provided as is.
*/
package com.mmm.cms.homehealth.vut.oasis;
import com.mmm.cms.homehealth.vut.proto.CollectionValidationEditsIF;
import com.mmm.cms.homehealth.vut.proto.OasisEditIF;
import com.mmm.cms.homehealth.vut.proto.OasisEditsEN;
import com.mmm.cms.homehealth.proto.record.HomeHealthRecordIF;
import com.mmm.cms.homehealth.proto.record.HomeHealthRecord_C2_IF;
import com.mmm.cms.homehealth.proto.RecordItemValidatorIF;
import com.mmm.cms.homehealth.vut.HHOasisDataItem;
import com.mmm.cms.homehealth.vut.OasisValidationEdit;
import com.mmm.cms.util.IntegerUtils;
import com.mmm.cms.util.ValidateUtils;
import java.util.List;
/**
* Validates Stage Most Problematic Pressure Ulcer for edits: 3060,
* 4170, 4181, 4191, 4201
*
* @author 3M Health Information Systems for CMS Home Health
*/
public class ValidateStageMostProblematicPressureUlcer_OASIS_C2 extends AbstractClinicalItemValidator implements RecordItemValidatorIF {
/**
* returns the edit list
*
* @return non-null list of edits for this validator
*/
public List<OasisEditIF> getEditIdsUsed() {
return super.getEditIdsUsed_base(OasisEditsEN.EDIT_3060, OasisEditsEN.EDIT_4170,
OasisEditsEN.EDIT_4181, OasisEditsEN.EDIT_4191, OasisEditsEN.EDIT_4201);
}
public int validate(HomeHealthRecordIF record, CollectionValidationEditsIF edits) {
int count = 0;
if (ValidateUtils.isValidValue(record.getASSMT_REASON(), AbstractItemValidator.ASSESSMENT_1_3_4_5_9_ONLY)) {
final String problemUlcer = record.getSTG_PRBLM_ULCER();
String tmpStr;
// check the value of the Stage of Most Problematic Pressure Ulcer
if ("01".equals(problemUlcer)) {
// number of pressure Ulcer stage 1 must be > 0
tmpStr = record.getNBR_PRSULC_STG1();
// if (ValidateUtils.isValidValue(tmpStr, ValidateUtils.ARRAY_CARET_VALUES) || ValidateUtils.DOUBLE_ZERO.equals(tmpStr)) {
if (ValidateUtils.isValidValue(tmpStr, ValidateUtils.ARRAY_CARET_VALUES) || IntegerUtils.parseInt(tmpStr, 0) <= 0) {
count++;
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4170,
new HHOasisDataItem(HomeHealthRecord_C2_IF.OASIS_C2_ITEM_M1324_STG_PRBLM_ULCER, problemUlcer)));
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4170,
new HHOasisDataItem(HomeHealthRecord_C2_IF.OASIS_C2_ITEM_M1322_NBR_PRSULC_STG1, tmpStr)));
}
} else if ("02".equals(problemUlcer)) {
// number of pressure Ulcer stage 2 must be > 0
tmpStr = record.getNBR_PRSULC_STG2();
// if (ValidateUtils.isValidValue(tmpStr, ValidateUtils.ARRAY_CARET_VALUES) || ValidateUtils.DOUBLE_ZERO.equals(tmpStr)) {
if (ValidateUtils.isValidValue(tmpStr, ValidateUtils.ARRAY_CARET_VALUES) || IntegerUtils.parseInt(tmpStr, 0) <= 0) {
count++;
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4181,
new HHOasisDataItem(HomeHealthRecord_C2_IF.OASIS_C2_ITEM_M1324_STG_PRBLM_ULCER, problemUlcer)));
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4181,
new HHOasisDataItem(HomeHealthRecord_C2_IF.OASIS_C2_ITEM_M1311_NBR_PRSULC_STG2_A1, tmpStr)));
}
} else if ("03".equals(problemUlcer)) {
// number of pressure Ulcer stage 3 must be > 0
tmpStr = record.getNBR_PRSULC_STG3();
// if (ValidateUtils.isValidValue(tmpStr, ValidateUtils.ARRAY_CARET_VALUES) || ValidateUtils.DOUBLE_ZERO.equals(tmpStr)) {
if (ValidateUtils.isValidValue(tmpStr, ValidateUtils.ARRAY_CARET_VALUES) || IntegerUtils.parseInt(tmpStr, 0) <= 0) {
count++;
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4191,
new HHOasisDataItem(HomeHealthRecord_C2_IF.OASIS_C2_ITEM_M1324_STG_PRBLM_ULCER, problemUlcer)));
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4191,
new HHOasisDataItem(HomeHealthRecord_C2_IF.OASIS_C2_ITEM_M1311_NBR_PRSULC_STG3_B1, tmpStr)));
}
} else if ("04".equals(problemUlcer)) {
// number of pressure Ulcer stage 4 must be > 0
tmpStr = record.getNBR_PRSULC_STG4();
// if (ValidateUtils.isValidValue(tmpStr, ValidateUtils.ARRAY_CARET_VALUES) || ValidateUtils.DOUBLE_ZERO.equals(tmpStr)) {
if (ValidateUtils.isValidValue(tmpStr, ValidateUtils.ARRAY_CARET_VALUES) || IntegerUtils.parseInt(tmpStr, 0) <= 0) {
count++;
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4201,
new HHOasisDataItem(HomeHealthRecord_C2_IF.OASIS_C2_ITEM_M1324_STG_PRBLM_ULCER, problemUlcer)));
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4201,
new HHOasisDataItem(HomeHealthRecord_C2_IF.OASIS_C2_ITEM_M1311_NBR_PRSULC_STG4_C1, tmpStr)));
}
}
}
return count;
}
/**
* Gets the description
*
* @return non-null string
*/
public String getDescription() {
return "Validates Stage Most Problematic Pressure Ulcer for edits: 3060, 4170, 4181, 4191, 4201\n";
}
}
|
Sheikh-Aman/aion
|
modAionImpl/test/org/aion/zero/impl/vm/AvmTestConfig.java
|
<gh_stars>100-1000
package org.aion.zero.impl.vm;
import org.aion.zero.impl.vm.avm.AvmConfigurations;
import org.aion.zero.impl.vm.avm.schedule.AvmVersionSchedule;
public final class AvmTestConfig {
/**
* Uses an avm version schedule that only supports version 1 - no version 2 support at all.
* Version 1 is active from block zero onwards.
*/
public static void supportOnlyAvmVersion1() {
AvmVersionSchedule schedule = AvmVersionSchedule.newScheduleForOnlySingleVersionSupport(0, 0);
String projectRoot = AvmPathManager.getPathOfProjectRootDirectory();
AvmConfigurations.initializeConfigurationsAsReadAndWriteable(schedule, projectRoot);
}
/**
* Uses an avm version schedule that supports both version 1 and 2 at the specified block
* numbers.
*
* The tolerance parameter is the amount of blocks (plus/minus) to keep an avm version alive
* at a block where it is no longer used.
*
* @param blockNumberToUseVersion1 The block number at which version 1 starts being used.
* @param blockNumberToUseVersion2 The block number at which version 2 starts being used.
* @param activeVersionTolerance The amount of blocks to keep an old version alive.
*/
public static void supportBothAvmVersions(long blockNumberToUseVersion1, long blockNumberToUseVersion2, long activeVersionTolerance) {
AvmVersionSchedule schedule = AvmVersionSchedule.newScheduleForBothVersions(blockNumberToUseVersion1, blockNumberToUseVersion2, activeVersionTolerance);
String projectRoot = AvmPathManager.getPathOfProjectRootDirectory();
AvmConfigurations.initializeConfigurationsAsReadAndWriteable(schedule, projectRoot);
}
/**
* Clears the current avm configurations.
*/
public static void clearConfigurations() {
AvmConfigurations.clear();
}
}
|
aiplan4eu/unified-planning
|
unified_planning/engines/compilers/negative_conditions_remover.py
|
<filename>unified_planning/engines/compilers/negative_conditions_remover.py
# Copyright 2021 AIPlan4EU project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""This module defines the negative preconditions remover class."""
import unified_planning as up
import unified_planning.engines as engines
from unified_planning.engines.mixins.compiler import CompilationKind, CompilerMixin
from unified_planning.engines.results import CompilerResult
from unified_planning.model import Fluent, Problem, InstantaneousAction, DurativeAction, FNode, Action, Effect, Timing, ProblemKind
from unified_planning.walkers import Simplifier
from unified_planning.engines.compilers.utils import get_fresh_name, replace_action
from unified_planning.walkers.identitydag import IdentityDagWalker
from unified_planning.exceptions import UPExpressionDefinitionError, UPProblemDefinitionError
from typing import List, Dict, Union
from functools import partial
class NegativeFluentRemover(IdentityDagWalker):
def __init__(self, problem, env):
self._env = env
IdentityDagWalker.__init__(self, self._env)
self._fluent_mapping: Dict[Fluent, Fluent] = {}
self._problem = problem
def remove_negative_fluents(self, expression:FNode) -> FNode:
return self.walk(expression)
def walk_not(self, expression: FNode, args: List[FNode], **kwargs) -> FNode:
assert len(args) == 1
if not args[0].is_fluent_exp():
raise UPExpressionDefinitionError(f"Expression: {expression} is not in NNF.")
neg_fluent = self._fluent_mapping.get(args[0].fluent(), None)
if neg_fluent is not None:
return self._env.expression_manager.FluentExp(neg_fluent, tuple(args[0].args))
f = args[0].fluent()
nf = Fluent(get_fresh_name(self._problem, f.name), f.type, f.signature, f._env)
self._fluent_mapping[f] = nf
return self._env.expression_manager.FluentExp(nf, tuple(args[0].args))
@property
def fluent_mapping(self) -> Dict[Fluent, Fluent]:
return self._fluent_mapping
class NegativeConditionsRemover(engines.engine.Engine, CompilerMixin):
'''Negative conditions remover class: this class offers the capability
to transform a problem with negative conditions into one
without negative conditions.
This is done by substituting every fluent that appears with a Not into the conditions
with different fluent representing his negation.'''
@property
def name(self):
return 'ncrm'
@staticmethod
def supported_kind() -> ProblemKind:
supported_kind = ProblemKind()
supported_kind.set_problem_class('ACTION_BASED') # type: ignore
supported_kind.set_typing('FLAT_TYPING') # type: ignore
supported_kind.set_typing('HIERARCHICAL_TYPING') # type: ignore
supported_kind.set_numbers('CONTINUOUS_NUMBERS') # type: ignore
supported_kind.set_numbers('DISCRETE_NUMBERS') # type: ignore
supported_kind.set_fluents_type('NUMERIC_FLUENTS') # type: ignore
supported_kind.set_fluents_type('OBJECT_FLUENTS') # type: ignore
supported_kind.set_conditions_kind('NEGATIVE_CONDITIONS') # type: ignore
supported_kind.set_conditions_kind('DISJUNCTIVE_CONDITIONS') # type: ignore
supported_kind.set_conditions_kind('EQUALITY') # type: ignore
supported_kind.set_conditions_kind('EXISTENTIAL_CONDITIONS') # type: ignore
supported_kind.set_conditions_kind('UNIVERSAL_CONDITIONS') # type: ignore
supported_kind.set_effects_kind('CONDITIONAL_EFFECTS') # type: ignore
supported_kind.set_effects_kind('INCREASE_EFFECTS') # type: ignore
supported_kind.set_effects_kind('DECREASE_EFFECTS') # type: ignore
supported_kind.set_time('CONTINUOUS_TIME') # type: ignore
supported_kind.set_time('DISCRETE_TIME') # type: ignore
supported_kind.set_time('INTERMEDIATE_CONDITIONS_AND_EFFECTS') # type: ignore
supported_kind.set_time('TIMED_EFFECT') # type: ignore
supported_kind.set_time('TIMED_GOALS') # type: ignore
supported_kind.set_time('DURATION_INEQUALITIES') # type: ignore
return supported_kind
@staticmethod
def supports(problem_kind):
return problem_kind <= NegativeConditionsRemover.supported_kind()
@staticmethod
def supports_compilation(compilation_kind: CompilationKind) -> bool:
return compilation_kind == CompilationKind.NEGATIVE_CONDITIONS_REMOVING
def _compile(self, problem: 'up.model.AbstractProblem',
compilation_kind: 'up.engines.CompilationKind') -> CompilerResult:
assert isinstance(problem, Problem)
env = problem.env
simplifier = Simplifier(env)
fluent_remover = NegativeFluentRemover(problem, env)
new_to_old: Dict[Action, Action] = {}
new_problem = Problem(f'{self.name}_{problem.name}', env)
for o in problem.all_objects:
new_problem.add_object(o)
name_action_map: Dict[str, Union[InstantaneousAction, DurativeAction]] = {}
for action in problem.actions:
if isinstance(action, InstantaneousAction):
new_action = action.clone()
new_action.name = get_fresh_name(new_problem, action.name)
new_action.clear_preconditions()
for p in action.preconditions:
np = fluent_remover.remove_negative_fluents(p)
new_action.add_precondition(np)
for ce in new_action.conditional_effects:
ce.set_condition(fluent_remover.remove_negative_fluents(ce.condition))
name_action_map[action.name] = new_action
elif isinstance(action, DurativeAction):
new_durative_action = action.clone()
new_durative_action.name = get_fresh_name(new_problem, action.name)
new_durative_action.clear_conditions()
for i, cl in action.conditions.items():
for c in cl:
nc = fluent_remover.remove_negative_fluents(c)
new_durative_action.add_condition(i, nc)
for t, cel in new_durative_action.conditional_effects.items():
for ce in cel:
ce.set_condition(fluent_remover.remove_negative_fluents(ce.condition))
name_action_map[action.name] = new_durative_action
else:
raise NotImplementedError
for t, el in problem.timed_effects.items():
for e in el:
new_problem._add_effect_instance(t, e.clone())
for t, el in new_problem.timed_effects.items():
for e in el:
if e.is_conditional():
e.set_condition(fluent_remover.remove_negative_fluents(e.condition))
for i, gl in problem.timed_goals.items():
for g in gl:
ng = fluent_remover.remove_negative_fluents(g)
new_problem.add_timed_goal(i, ng)
for g in problem.goals:
ng = fluent_remover.remove_negative_fluents(g)
new_problem.add_goal(ng)
#fluent_mapping is the map between a fluent and it's negation, when the
# negation is None it means the fluent is never found in a negation into
# every condititon analized before; therefore it does not need to exist.
fluent_mapping = fluent_remover.fluent_mapping
for f in problem.fluents:
new_problem.add_fluent(f)
fneg = fluent_mapping.get(f, None)
if fneg is not None:
new_problem.add_fluent(fneg)
for fl, v in problem.initial_values.items():
fneg = fluent_mapping.get(fl.fluent(), None)
new_problem.set_initial_value(fl, v)
if fneg is not None:
if v.bool_constant_value():
new_problem.set_initial_value(env.expression_manager.FluentExp(fneg,
tuple(fl.args)), env.expression_manager.FALSE())
else:
new_problem.set_initial_value(env.expression_manager.FluentExp(fneg,
tuple(fl.args)), env.expression_manager.TRUE())
for action in problem.actions:
if isinstance(action, InstantaneousAction):
new_action = name_action_map[action.name]
new_effects: List[Effect] = []
for e in new_action.effects:
fl, v = e.fluent, e.value
fneg = fluent_mapping.get(fl.fluent(), None)
if fneg is not None:
simplified_not_v = simplifier.simplify(env.expression_manager.Not(v))
new_effects.append(Effect(env.expression_manager.FluentExp(fneg, tuple(fl.args)),
simplified_not_v, e.condition, e.kind))
for ne in new_effects:
new_action._add_effect_instance(ne)
new_problem.add_action(new_action)
new_to_old[new_action] = action
elif isinstance(action, DurativeAction):
new_durative_action = name_action_map[action.name]
new_durative_action.set_duration_constraint(action.duration)
for t, el in new_durative_action.effects.items():
for e in el:
fl, v = e.fluent, e.value
fneg = fluent_mapping.get(fl.fluent(), None)
if fneg is not None:
simplified_not_v = simplifier.simplify(env.expression_manager.Not(v))
new_durative_action._add_effect_instance(t, Effect(env.expression_manager.FluentExp(fneg, tuple(fl.args)),
simplified_not_v, e.condition, e.kind))
new_problem.add_action(new_durative_action)
new_to_old[new_durative_action] = action
else:
raise NotImplementedError
for t, el in new_problem.timed_effects.items():
for e in el:
fl, v = e.fluent, e.value
fneg = fluent_mapping.get(fl.fluent(), None)
if fneg is not None:
simplified_not_v = simplifier.simplify(env.expression_manager.Not(v))
new_problem._add_effect_instance(t, Effect(env.expression_manager.FluentExp(fneg, tuple(fl.args)),
simplified_not_v, e.condition, e.kind))
return CompilerResult(new_problem, partial(replace_action, map=new_to_old), self.name)
|
stijn1989/cphalcon
|
ext/phalcon/validation/validator/identical.zep.c
|
<filename>ext/phalcon/validation/validator/identical.zep.c<gh_stars>1000+
#ifdef HAVE_CONFIG_H
#include "../../../ext_config.h"
#endif
#include <php.h>
#include "../../../php_ext.h"
#include "../../../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/fcall.h"
#include "kernel/memory.h"
#include "ext/spl/spl_exceptions.h"
#include "kernel/exception.h"
#include "kernel/object.h"
#include "kernel/operators.h"
#include "kernel/array.h"
/**
* This file is part of the Phalcon Framework.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
/**
* Checks if a value is identical to other
*
* ```php
* use Phalcon\Validation;
* use Phalcon\Validation\Validator\Identical;
*
* $validator = new Validation();
*
* $validator->add(
* "terms",
* new Identical(
* [
* "accepted" => "yes",
* "message" => "Terms and conditions must be accepted",
* ]
* )
* );
*
* $validator->add(
* [
* "terms",
* "anotherTerms",
* ],
* new Identical(
* [
* "accepted" => [
* "terms" => "yes",
* "anotherTerms" => "yes",
* ],
* "message" => [
* "terms" => "Terms and conditions must be accepted",
* "anotherTerms" => "Another terms must be accepted",
* ],
* ]
* )
* );
* ```
*/
ZEPHIR_INIT_CLASS(Phalcon_Validation_Validator_Identical)
{
ZEPHIR_REGISTER_CLASS_EX(Phalcon\\Validation\\Validator, Identical, phalcon, validation_validator_identical, phalcon_validation_abstractvalidator_ce, phalcon_validation_validator_identical_method_entry, 0);
zend_declare_property_string(phalcon_validation_validator_identical_ce, SL("template"), "Field :field does not have the expected value", ZEND_ACC_PROTECTED);
return SUCCESS;
}
/**
* Constructor
*
* @param array options = [
* 'message' => '',
* 'template' => '',
* 'accepted' => '',
* 'value' => '',
* 'allowEmpty' => false
* ]
*/
PHP_METHOD(Phalcon_Validation_Validator_Identical, __construct)
{
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS;
zephir_fcall_cache_entry *_0 = NULL;
zval *options_param = NULL;
zval options;
zval *this_ptr = getThis();
ZVAL_UNDEF(&options);
#if PHP_VERSION_ID >= 80000
bool is_null_true = 1;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY(options)
ZEND_PARSE_PARAMETERS_END();
#endif
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 0, 1, &options_param);
if (!options_param) {
ZEPHIR_INIT_VAR(&options);
array_init(&options);
} else {
ZEPHIR_OBS_COPY_OR_DUP(&options, options_param);
}
ZEPHIR_CALL_PARENT(NULL, phalcon_validation_validator_identical_ce, getThis(), "__construct", &_0, 0, &options);
zephir_check_call_status();
ZEPHIR_MM_RESTORE();
}
/**
* Executes the validation
*/
PHP_METHOD(Phalcon_Validation_Validator_Identical, validate)
{
zend_bool valid = 0;
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS;
zval *validation, validation_sub, *field, field_sub, value, accepted, _0, _1, _2, _3$$3, _4$$4, _5$$6, _6$$7;
zval *this_ptr = getThis();
ZVAL_UNDEF(&validation_sub);
ZVAL_UNDEF(&field_sub);
ZVAL_UNDEF(&value);
ZVAL_UNDEF(&accepted);
ZVAL_UNDEF(&_0);
ZVAL_UNDEF(&_1);
ZVAL_UNDEF(&_2);
ZVAL_UNDEF(&_3$$3);
ZVAL_UNDEF(&_4$$4);
ZVAL_UNDEF(&_5$$6);
ZVAL_UNDEF(&_6$$7);
#if PHP_VERSION_ID >= 80000
bool is_null_true = 1;
ZEND_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_OBJECT_OF_CLASS(validation, phalcon_validation_ce)
Z_PARAM_ZVAL(field)
ZEND_PARSE_PARAMETERS_END();
#endif
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 2, 0, &validation, &field);
ZEPHIR_CALL_METHOD(&value, validation, "getvalue", NULL, 0, field);
zephir_check_call_status();
ZEPHIR_INIT_VAR(&_1);
ZVAL_STRING(&_1, "accepted");
ZEPHIR_CALL_METHOD(&_0, this_ptr, "hasoption", NULL, 0, &_1);
zephir_check_call_status();
ZEPHIR_INIT_NVAR(&_1);
ZVAL_STRING(&_1, "value");
ZEPHIR_CALL_METHOD(&_2, this_ptr, "hasoption", NULL, 0, &_1);
zephir_check_call_status();
if (zephir_is_true(&_0)) {
ZEPHIR_INIT_VAR(&_3$$3);
ZVAL_STRING(&_3$$3, "accepted");
ZEPHIR_CALL_METHOD(&accepted, this_ptr, "getoption", NULL, 0, &_3$$3);
zephir_check_call_status();
} else if (zephir_is_true(&_2)) {
ZEPHIR_INIT_VAR(&_4$$4);
ZVAL_STRING(&_4$$4, "value");
ZEPHIR_CALL_METHOD(&accepted, this_ptr, "getoption", NULL, 0, &_4$$4);
zephir_check_call_status();
}
if (zephir_is_true(&accepted)) {
if (Z_TYPE_P(&accepted) == IS_ARRAY) {
zephir_array_fetch(&_5$$6, &accepted, field, PH_NOISY | PH_READONLY, "phalcon/Validation/Validator/Identical.zep", 94);
ZEPHIR_CPY_WRT(&accepted, &_5$$6);
}
valid = ZEPHIR_IS_EQUAL(&value, &accepted);
}
if (!(valid)) {
ZEPHIR_CALL_METHOD(&_6$$7, this_ptr, "messagefactory", NULL, 0, validation, field);
zephir_check_call_status();
ZEPHIR_CALL_METHOD(NULL, validation, "appendmessage", NULL, 0, &_6$$7);
zephir_check_call_status();
RETURN_MM_BOOL(0);
}
RETURN_MM_BOOL(1);
}
|
tied/innovation-funding-service
|
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/user/repository/RoleProfileStatusRepository.java
|
<reponame>tied/innovation-funding-service
package org.innovateuk.ifs.user.repository;
import org.innovateuk.ifs.user.domain.RoleProfileStatus;
import org.innovateuk.ifs.user.resource.ProfileRole;
import org.innovateuk.ifs.user.resource.RoleProfileState;
import org.innovateuk.ifs.user.resource.UserStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import java.util.Optional;
public interface RoleProfileStatusRepository extends CrudRepository<RoleProfileStatus, Long> {
List<RoleProfileStatus> findByUserId(long userId);
Optional<RoleProfileStatus> findByUserIdAndProfileRole(long userId, ProfileRole role);
Page<RoleProfileStatus> findByRoleProfileStateAndProfileRoleAndUserEmailContainingAndUserStatus(
RoleProfileState roleProfileState, ProfileRole role, String filter, UserStatus userStatus, Pageable pageable);
}
|
yoelcortes/pyflowsheet
|
pyflowsheet/annotations/textelement.py
|
from ..core import UnitOperation
from ..core.enums import HorizontalLabelAlignment, VerticalLabelAlignment
class TextElement(UnitOperation):
def __init__(self, text, position=(0, 0)):
super().__init__("text", "text", position=position, size=(20, 20))
self.text = text
self.drawBoundingBox = False
self.showTitle = False
self.fontFamily = "Consolas"
return
def draw(self, ctx):
# html = self.data.to_html()
# ctx.html(html, self.position, self.size)
ctx.text(
self.position,
text=self.text,
fontFamily=self.fontFamily,
textColor=self.textColor,
textAnchor="start",
)
# super().draw(ctx)
return
|
jaredpreston/web-1
|
generated/docs/kratos/algolia.328d59c6.js
|
<reponame>jaredpreston/web-1
(window.webpackJsonp=window.webpackJsonp||[]).push([[47],{322:function(n,w,o){}}]);
|
Kstar0722/avoinministerio
|
db/migrate/20120229153530_add_friendly_id_to_idea.rb
|
class AddFriendlyIdToIdea < ActiveRecord::Migration
def change
add_column :ideas, :slug, :string
add_index :ideas, :slug, unique: true
end
end
|
inspectIT/inspectit-oce
|
inspectit-ocelot-core/src/test/java/rocks/inspectit/ocelot/core/testutils/ReflectionUtils.java
|
<reponame>inspectIT/inspectit-oce<gh_stars>10-100
package rocks.inspectit.ocelot.core.testutils;
import java.lang.reflect.Field;
public class ReflectionUtils {
public static void writeField(Object target, String fieldName, Object value) {
try {
Class<?> targetClass = target.getClass();
Field targetField = targetClass.getDeclaredField(fieldName);
targetField.setAccessible(true);
targetField.set(target, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static void writeStaticField(Class<?> targetClass, String fieldName, Object value) {
try {
Field targetField = targetClass.getDeclaredField(fieldName);
targetField.setAccessible(true);
targetField.set(null, value);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
|
aliyun/CicadaPlayer
|
framework/utils/UrlUtils.h
|
<filename>framework/utils/UrlUtils.h
//
// Created by lifujun on 2020/5/19.
//
#ifndef SAASMEDIA_URLUTILS_H
#define SAASMEDIA_URLUTILS_H
#include <string>
#include <map>
#include "CicadaType.h"
namespace Cicada {
class URLComponents {
public:
std::string proto{};
std::string auth{};
std::string host{};
std::string path{};
int port;
};
class CICADA_CPLUS_EXTERN UrlUtils {
public:
static std::map<std::string, std::string> getArgs(const std::string &url);
static std::string getBaseUrl(const std::string& url);
static void parseUrl(URLComponents &urlComponents, const std::string &url);
static std::string urlEncode( const std::string &c);
private:
static std::string char2hex(char dec );
static void url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size,
int *port_ptr, char *path, int path_size, const char *url);
};
}
#endif //SAASMEDIA_URLUTILS_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.