hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
|---|---|---|---|---|---|
d9bfda9dc9aec856d359134ab05168045fd8f06a
| 853
|
/*
* Copyright (c) Fundacion Jala. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
package org.fundacionjala.oblivion.navigator;
import com.sun.source.tree.Tree.Kind;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Base Implementation of a {@link DefaultMutableTreeNode} that hold the common attributes to show relevant information on navigation panel.
*
* @author nelson_alcocer
*/
public abstract class ParserMutableTreeNode extends DefaultMutableTreeNode {
public ParserMutableTreeNode(Object showedName) {
super(showedName, true);
}
public abstract int getLine();
public abstract Kind getKind();
public abstract String getDataType();
public abstract boolean getIsPrivate();
public abstract String getIconPath();
}
| 27.516129
| 140
| 0.754982
|
ee66c41aeea794d0f53ecf6dafafa242812243d7
| 6,719
|
package fr.free.nrw.commons.media;
import io.reactivex.Single;
import java.util.Map;
import org.wikipedia.dataclient.mwapi.MwQueryResponse;
import retrofit2.http.GET;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
/**
* Interface for interacting with Commons media related APIs
*/
public interface MediaInterface {
String MEDIA_PARAMS="&prop=imageinfo|coordinates&iiprop=url|extmetadata|user&&iiurlwidth=640" +
"&iiextmetadatafilter=DateTime|Categories|GPSLatitude|GPSLongitude|ImageDescription|DateTimeOriginal" +
"|Artist|LicenseShortName|LicenseUrl";
/**
* fetches category detail(title, hidden) for each category along with File information
*/
String MEDIA_PARAMS_WITH_CATEGORY_DETAILS ="&clprop=hidden&prop=categories|imageinfo&iiprop=url|extmetadata|user&&iiurlwidth=640" +
"&iiextmetadatafilter=DateTime|GPSLatitude|GPSLongitude|ImageDescription|DateTimeOriginal" +
"|Artist|LicenseShortName|LicenseUrl";
/**
* Checks if a page exists or not.
*
* @param title the title of the page to be checked
* @return
*/
@GET("w/api.php?action=query&format=json&formatversion=2")
Single<MwQueryResponse> checkPageExistsUsingTitle(@Query("titles") String title);
/**
* Check if file exists
*
* @param aisha1 the SHA of the media file to be checked
* @return
*/
@GET("w/api.php?action=query&format=json&formatversion=2&list=allimages")
Single<MwQueryResponse> checkFileExistsUsingSha(@Query("aisha1") String aisha1);
/**
* This method retrieves a list of Media objects filtered using image generator query
*
* @param category the category name. Must start with "Category:"
* @param itemLimit how many images are returned
* @param continuation the continuation string from the previous query or empty map
* @return
*/
@GET("w/api.php?action=query&format=json&formatversion=2" + //Basic parameters
"&generator=categorymembers&gcmtype=file&gcmsort=timestamp&gcmdir=desc" + //Category parameters
MEDIA_PARAMS)
Single<MwQueryResponse> getMediaListFromCategory(@Query("gcmtitle") String category, @Query("gcmlimit") int itemLimit, @QueryMap Map<String, String> continuation);
/**
* This method retrieves a list of Media objects for a given user name
*
* @param username user's Wikimedia Commons username.
* @param itemLimit how many images are returned
* @param continuation the continuation string from the previous query or empty map
* @return
*/
@GET("w/api.php?action=query&format=json&formatversion=2" + //Basic parameters
"&generator=allimages&gaisort=timestamp&gaidir=older" + MEDIA_PARAMS)
Single<MwQueryResponse> getMediaListForUser(@Query("gaiuser") String username,
@Query("gailimit") int itemLimit, @QueryMap(encoded = true) Map<String, String> continuation);
/**
* This method retrieves a list of Media objects filtered using image generator query
*
* @param keyword the searched keyword
* @param itemLimit how many images are returned
* @param offset the offset in the result set
* @return
*/
@GET("w/api.php?action=query&format=json&formatversion=2" + //Basic parameters
"&generator=search&gsrwhat=text&gsrnamespace=6" + //Search parameters
MEDIA_PARAMS)
Single<MwQueryResponse> getMediaListFromSearch(@Query("gsrsearch") String keyword,
@Query("gsrlimit") int itemLimit, @Query("gsroffset") int offset);
/**
* This method retrieves a list of Media objects filtered using list geosearch query. Example: https://commons.wikimedia.org/w/api.php?action=query&format=json&formatversion=2&generator=geosearch&ggsnamespace=6&prop=imageinfo|coordinates&iiprop=url|extmetadata|user&&iiurlwidth=640&iiextmetadatafilter=DateTime|Categories|GPSLatitude|GPSLongitude|ImageDescription|DateTimeOriginal|Artist|LicenseShortName|LicenseUrl&ggscoord=37.45579%7C-122.31369&ggslimit=30&ggsradius=10000
*
* @param location the search location
* @param itemLimit how many images are returned
* @return
*/
@GET("w/api.php?action=query&format=json&formatversion=2" + //Basic parameters
"&generator=geosearch&ggsnamespace=6" + //Search parameters
MEDIA_PARAMS)
Single<MwQueryResponse> getMediaListFromGeoSearch(@Query("ggscoord") String location, @Query("ggslimit") int itemLimit, @Query("ggsradius") int radius);
/**
* Fetches Media object from the imageInfo API
*
* @param title the tiles to be searched for. Can be filename or template name
* @return
*/
@GET("w/api.php?action=query&format=json&formatversion=2" +
MEDIA_PARAMS_WITH_CATEGORY_DETAILS)
Single<MwQueryResponse> getMedia(@Query("titles") String title);
/**
* Fetches Media object from the imageInfo API
*
* @param pageIds the ids to be searched for
* @return
*/
@GET("w/api.php?action=query&format=json&formatversion=2" +
MEDIA_PARAMS)
Single<MwQueryResponse> getMediaById(@Query("pageids") String pageIds);
/**
* Fetches Media object from the imageInfo API
* Passes an image generator parameter
*
* @param title the tiles to be searched for. Can be filename or template name
* @return
*/
@GET("w/api.php?action=query&format=json&formatversion=2&generator=images" +
MEDIA_PARAMS)
Single<MwQueryResponse> getMediaWithGenerator(@Query("titles") String title);
@GET("w/api.php?format=json&action=parse&prop=text")
Single<MwParseResponse> getPageHtml(@Query("page") String title);
/**
* Fetches caption using file name
*
* @param filename name of the file to be used for fetching captions
* */
@GET("w/api.php?action=wbgetentities&props=labels&format=json&languagefallback=1")
Single<MwQueryResponse> fetchCaptionByFilename(@Query("language") String language, @Query("titles") String filename);
/**
* Fetches list of images from a depiction entity
* @param query depictionEntityId
* @param srlimit the number of items to fetch
* @param sroffset number od depictions already fetched, this is useful in implementing pagination
*/
@GET("w/api.php?action=query&format=json&formatversion=2" + //Basic parameters
"&generator=search&gsrnamespace=6" + //Search parameters
MEDIA_PARAMS)
Single<MwQueryResponse> fetchImagesForDepictedItem(@Query("gsrsearch") String query,
@Query("gsrlimit")String srlimit, @Query("gsroffset") String sroffset);
}
| 44.496689
| 478
| 0.701146
|
42848e08f89c54c8a1c33ddda8c1689367775f2d
| 451
|
package edu.nju.githubstatistics;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author: Bright Chan
* @date: 2021/4/1 16:56
* @description: GithubStatisticsApplication
*/
@SpringBootApplication
public class GithubStatisticsApplication {
public static void main(String[] args) {
SpringApplication.run(GithubStatisticsApplication.class, args);
}
}
| 23.736842
| 71
| 0.773836
|
ab0ad7a5e6b05545c8e04e558039c93984a0df5a
| 1,851
|
package com.timeyang.amanda.user.service;
import com.timeyang.amanda.user.domain.Profile;
import com.timeyang.amanda.user.domain.User;
import com.timeyang.amanda.user.repository.ProfileRepository;
import com.timeyang.amanda.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Iterator;
/**
* @author chaokunyang
*/
@Service
public class ProfileServiceImpl implements ProfileService {
@Autowired
private ProfileRepository profileRepository;
@Autowired
private UserRepository userRepository;
@Override
public Profile getProfile() {
Iterator<Profile> iterator = profileRepository.findAll().iterator();
if (iterator.hasNext()) {
return iterator.next();
}
return new Profile();
}
@Transactional
@Override
public Profile getProfileByUserId(Long userId) {
return profileRepository.findUserByUserId(userId);
}
@Transactional
@Override
public Profile save(Profile profile) {
return profileRepository.save(profile);
}
@Override
public Profile update(Profile profile) {
if(profile.getUserId() != null) {
User user = userRepository.findOne(profile.getUserId());
profile.setUser(user); // 用于在更新Profile时维持关联关系
}
return profileRepository.save(profile);
}
@Transactional
@Override
public void delete(Profile profile) {
profileRepository.delete(profile);
}
@Transactional
@Override
public void delete(Long id) {
profileRepository.delete(id);
}
@Transactional
@Override
public void deleteAll() {
profileRepository.deleteAll();
}
}
| 25.356164
| 76
| 0.69584
|
8877087625b46fe68f674e008eff268b4fb9d6d0
| 4,194
|
/*
* 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.flink.table.filesystem;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.Path;
import org.apache.flink.table.api.ValidationException;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.factories.FactoryUtil;
import org.apache.flink.table.factories.FileSystemFormatFactory;
import org.apache.flink.table.factories.TableFactory;
import org.apache.flink.table.factories.TableSinkFactory;
import org.apache.flink.table.factories.TableSourceFactory;
import org.apache.flink.table.sinks.TableSink;
import org.apache.flink.table.sources.TableSource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.flink.table.descriptors.ConnectorDescriptorValidator.CONNECTOR;
import static org.apache.flink.table.descriptors.FormatDescriptorValidator.FORMAT;
import static org.apache.flink.table.filesystem.FileSystemOptions.PARTITION_DEFAULT_NAME;
import static org.apache.flink.table.filesystem.FileSystemOptions.PATH;
/**
* File system {@link TableFactory}.
*
* <p>1.The partition information should be in the file system path, whether it's a temporary
* table or a catalog table.
* 2.Support insert into (append) and insert overwrite.
* 3.Support static and dynamic partition inserting.
*
* <p>Migrate to new source/sink interface after FLIP-95 is ready.
*/
public class FileSystemTableFactory implements
TableSourceFactory<RowData>,
TableSinkFactory<RowData> {
public static final String IDENTIFIER = "filesystem";
@Override
public Map<String, String> requiredContext() {
Map<String, String> context = new HashMap<>();
context.put(CONNECTOR, IDENTIFIER);
return context;
}
@Override
public List<String> supportedProperties() {
// contains format properties.
return Collections.singletonList("*");
}
@Override
public TableSource<RowData> createTableSource(TableSourceFactory.Context context) {
Configuration conf = new Configuration();
context.getTable().getOptions().forEach(conf::setString);
return new FileSystemTableSource(
context.getTable().getSchema(),
getPath(conf),
context.getTable().getPartitionKeys(),
conf.get(PARTITION_DEFAULT_NAME),
context.getTable().getProperties());
}
@Override
public TableSink<RowData> createTableSink(TableSinkFactory.Context context) {
Configuration conf = new Configuration();
context.getTable().getOptions().forEach(conf::setString);
return new FileSystemTableSink(
context.getObjectIdentifier(),
context.isBounded(),
context.getTable().getSchema(),
getPath(conf),
context.getTable().getPartitionKeys(),
conf.get(PARTITION_DEFAULT_NAME),
context.getTable().getOptions());
}
private static Path getPath(Configuration conf) {
return new Path(conf.getOptional(PATH).orElseThrow(() ->
new ValidationException("Path should be not empty.")));
}
public static FileSystemFormatFactory createFormatFactory(Map<String, String> properties) {
String format = properties.get(FORMAT);
if (format == null) {
throw new ValidationException(String.format(
"Table options do not contain an option key '%s' for discovering a format.",
FORMAT));
}
return FactoryUtil.discoverFactory(
Thread.currentThread().getContextClassLoader(),
FileSystemFormatFactory.class,
format);
}
}
| 35.542373
| 93
| 0.768002
|
e3364cdba1c3d52354197c2c48e45ea3b4cd178d
| 1,651
|
package main.tools;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
/** <strong>Clean Printer</strong>
* <p>Clean printer is a class to easily access the print function of System,
* convert numbers from ugly long decimals to a limited amount, insert the
* comma (,) for larger digits, and print to files depending.</p>
* @author Zachary Vanscoit
*/
public class CP {
private static PrintWriter out = null;
private static File file = null;
/**<strong>println()</strong>
* <p>Pretty self explanatory. Prints to console with a line after.</p>
* @param str
*/
public static void println(String str) {
System.out.println(str);
}
/**<strong>print()</strong>
* <p>Pretty self explanatory. Prints to console WITHOUT a line after (cause some people do that).</p>
* @param str
*/
public static void print(String str) {
System.out.print(str);
}
/**<strong>printToFile()</strong>
* <p>This method is used to print a nice log file to a file :D</p>
* @param str
* @param location
* @return
*/
public static boolean printToFile(String str, String location) {
try {
file = new File(location);
if (file.createNewFile()) {
println("Created file that wasn't there.");
}
out = new PrintWriter(location);
out.println(str);
} catch (FileNotFoundException n) {
println("Ok, somehow the file was not created. Talk to your system administrator even though "+
"it's not their fault.");
}
catch (Exception e) {
println("Listen man, something happened, and it goes something like this:\n" + e.getMessage());
return false;
}
return true;
}
}
| 27.983051
| 103
| 0.682617
|
cef7efd03f1f2c37747aacd8d02f707d6d0e3e97
| 496
|
package org.csu.mypetstore.domain;
public class Banner {
private String favoriteCategory;
private String bannerName;
public String getFavoriteCategory() {
return favoriteCategory;
}
public void setFavoriteCategory(String favoriteCategory) {
this.favoriteCategory = favoriteCategory;
}
public String getBannerName() {
return bannerName;
}
public void setBannerName(String bannerName) {
this.bannerName = bannerName;
}
}
| 21.565217
| 62
| 0.689516
|
80cc266322d49ed061da7f52ca2b41c18244652f
| 6,108
|
/* Copyright 2008 - 2017 Hochschule Offenburg
* For a list of authors see README.md
* This software of HSOAutonomy is released under MIT License (see LICENSE).
*/
package hso.autonomy.agent.model.worldmodel.localizer.impl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.math3.geometry.euclidean.threed.Rotation;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import hso.autonomy.agent.model.worldmodel.localizer.IEnvironmentModel;
import hso.autonomy.agent.model.worldmodel.localizer.ILocalizationLine;
import hso.autonomy.agent.model.worldmodel.localizer.IReferenceLine;
import hso.autonomy.agent.model.worldmodel.localizer.IReferencePoint;
import hso.autonomy.util.geometry.Pose3D;
import hso.autonomy.util.misc.FuzzyCompare;
/**
* Implements a 3-dimensional localizer based on reference points and the
* estimated orientation.
*
* @author Stefan Glaser
*/
public class LocalizerGyro extends LocalizerBase
{
@Override
public Pose3D localize(IEnvironmentModel environment, List<ILocalizationLine> lines, Rotation estimatedOrientation)
{
if (estimatedOrientation == null) {
// there is no gyro information available
return null;
}
// fetch reference points and -lines
List<IReferencePoint> refPoints = getVisibleReferencePoints(environment);
List<IReferenceLine> refLines = getVisibleReferenceLines(environment);
if (refPoints.size() == 0) {
// there is no visible flag
return null;
}
return new Pose3D(
LocalizerUtil.calculatePosition(refPoints, refLines, estimatedOrientation), estimatedOrientation);
}
// ==================================================
// Below: experimental localizer implementations
// ==================================================
/**
* This method searches for line pints near by known flags, to extent the
* fix-point base for umeyama orientation estimation.
*/
private Pose3D lineSearchingUmeyamaLocalization(
Collection<IReferencePoint> flagsList, List<ILocalizationLine> lines)
{
if (flagsList.size() < 3 || (lines != null && lines.size() < 2)) {
return null;
}
List<Vector3D> visionVec = new ArrayList<>();
List<Vector3D> fixedVec = new ArrayList<>();
Vector3D fixedCOM;
Vector3D visionCOM;
Vector3D temp;
for (IReferencePoint flag : flagsList) {
// Add fixedPosition
fixedVec.add(flag.getKnownPosition());
// Add localPosition
visionVec.add(flag.getLocalPosition());
}
// Search for lines, ending at fix-points
for (IReferencePoint flag : flagsList) {
// Check on corner flag
if (FuzzyCompare.eq(0, flag.getKnownPosition().getZ(), 0.001)) {
for (ILocalizationLine line : lines) {
if (FuzzyCompare.eq(flag.getLocalPosition(), line.getLocalPosition1(), 0.5)) {
// We found a border line, starting/ending at the fix-point
fixedVec.add(flag.getKnownPosition());
visionVec.add(line.getLocalPosition1());
// System.out.println("found matching line to corner flag");
}
if (FuzzyCompare.eq(flag.getLocalPosition(), line.getLocalPosition2(), 0.5)) {
// We found a border line, starting/ending at the fix-point
fixedVec.add(flag.getKnownPosition());
visionVec.add(line.getLocalPosition2());
// System.out.println("found matching line to corner flag");
}
}
}
// Check on goal post flag
if (flag.getKnownPosition().getZ() > 0.1) {
for (ILocalizationLine line : lines) {
if (FuzzyCompare.eq(flag.getLocalPosition(), line.getLocalPosition1(), 1.5)) {
// We found a border line, starting/ending at the fix-point
temp = flag.getKnownPosition();
if (temp.getY() > 0) {
// Upper goal post
temp = temp.add(new Vector3D(0, 0.9, -0.8));
} else {
// Lower goal post
temp = temp.add(new Vector3D(0, -0.9, -0.8));
}
fixedVec.add(temp);
if (line.getLocalPosition2() != null) {
if (temp.getX() > 0) {
temp = temp.add(new Vector3D(-1.8, 0, 0));
} else {
temp = temp.add(new Vector3D(1.8, 0, 0));
}
fixedVec.add(temp);
}
visionVec.add(line.getLocalPosition1());
if (line.getLocalPosition2() != null) {
visionVec.add(line.getLocalPosition2());
}
// System.out.println("found matching line to goal post");
}
if (FuzzyCompare.eq(flag.getLocalPosition(), line.getLocalPosition2(), 1.5)) {
// We found a border line, starting/ending at the fix-point
temp = flag.getKnownPosition();
if (temp.getY() > 0) {
// Upper goal post
temp = temp.add(new Vector3D(0, 0.9, -0.8));
} else {
// Lower goal post
temp = temp.add(new Vector3D(0, -0.9, -0.8));
}
fixedVec.add(temp);
if (line.getLocalPosition1() != null) {
if (temp.getX() > 0) {
temp = temp.add(new Vector3D(-1.8, 0, 0));
} else {
temp = temp.add(new Vector3D(1.8, 0, 0));
}
fixedVec.add(temp);
}
visionVec.add(line.getLocalPosition2());
if (line.getLocalPosition1() != null) {
visionVec.add(line.getLocalPosition1());
}
// System.out.println("found matching line to goal post");
}
}
}
}
fixedCOM = Vector3D.ZERO;
for (Vector3D vec : fixedVec) {
fixedCOM = fixedCOM.add(vec);
}
fixedCOM = fixedCOM.scalarMultiply(1.0 / fixedVec.size());
visionCOM = Vector3D.ZERO;
for (Vector3D vec : visionVec) {
visionCOM = visionCOM.add(vec);
}
visionCOM = visionCOM.scalarMultiply(1.0 / visionVec.size());
Vector3D[] fixedVecArr = new Vector3D[visionVec.size()];
for (int i = 0; i < fixedVec.size(); i++) {
fixedVecArr[i] = fixedVec.get(i).subtract(fixedCOM);
}
Vector3D[] visionVecArr = new Vector3D[visionVec.size()];
for (int i = 0; i < visionVec.size(); i++) {
visionVecArr[i] = visionVec.get(i).subtract(visionCOM);
}
Rotation orientation = LocalizerUtil.umeyama(visionVecArr, fixedVecArr);
return new Pose3D(LocalizerUtil.calculatePosition(flagsList, orientation), orientation);
}
}
| 31.484536
| 116
| 0.658317
|
724aa3282cf4e5c49b15034528d67f152521fccc
| 1,078
|
package com.tesco.crypt.kmip.ttlv.model.enums.enumerations;
import com.tesco.crypt.kmip.ttlv.model.enums.ByteEnum;
import java.math.BigInteger;
public enum HashingAlgorithm implements ByteEnum<HashingAlgorithm> {
MD2("1"),
MD4("2"),
MD5("3"),
SHA_1("4"),
SHA_224("5"),
SHA_256("6"),
SHA_384("7"),
SHA_512("8"),
RIPEMD_160("9"),
TIGER("0000000A"),
WHIRLPOOL("0000000B"),
EXTENSIONS("8XXXXXXX");
private final BigInteger start;
private final BigInteger end;
HashingAlgorithm(String hexValue) {
if (hexValue.contains("X")) {
start = new BigInteger(hexValue.replaceAll("X", "0"), 16);
end = new BigInteger(hexValue.replaceAll("X", "F"), 16);
} else {
start = new BigInteger(hexValue, 16);
end = start;
}
}
@Override
public Class<HashingAlgorithm> getType() {
return this.getDeclaringClass();
}
public BigInteger getStart() {
return start;
}
public BigInteger getEnd() {
return end;
}
}
| 22.93617
| 70
| 0.595547
|
69b8e7ed586733b954e6845c20f5acfdc64ec4c3
| 142,070
|
package com.tatx.userapp.activities;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.gson.Gson;
import com.google.maps.model.Bounds;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.tatx.userapp.R;
import com.tatx.userapp.abstractclasses.PushNotificationListenerActivity;
import com.tatx.userapp.application.TATX;
import com.tatx.userapp.commonutills.Common;
import com.tatx.userapp.commonutills.Constants;
import com.tatx.userapp.constants.ServiceUrls;
import com.tatx.userapp.customviews.BackAwareEditText;
import com.tatx.userapp.customviews.CustomButton;
import com.tatx.userapp.customviews.CustomTextView;
import com.tatx.userapp.customviews.CustomTypefaceSpan;
import com.tatx.userapp.customviews.CustomerAlertDialog;
import com.tatx.userapp.enums.CabTypes;
import com.tatx.userapp.enums.DensityType;
import com.tatx.userapp.enums.PaymentType;
import com.tatx.userapp.googlemapadapters.Util;
import com.tatx.userapp.helpers.GeoDetails;
import com.tatx.userapp.interfaces.DialogClickListener;
import com.tatx.userapp.interfaces.GoogleMapOnTouchListener;
import com.tatx.userapp.library.AbstractRouting;
import com.tatx.userapp.library.Route;
import com.tatx.userapp.library.RouteException;
import com.tatx.userapp.library.Routing;
import com.tatx.userapp.library.RoutingListener;
import com.tatx.userapp.menuactivity.AboutActivity;
import com.tatx.userapp.menuactivity.AccountActivity;
import com.tatx.userapp.menuactivity.AddLocationActivity;
import com.tatx.userapp.menuactivity.DisplayProfileActivity;
import com.tatx.userapp.menuactivity.HelpActivity;
import com.tatx.userapp.menuactivity.NotificationsActivity;
import com.tatx.userapp.menuactivity.OfferActivity;
import com.tatx.userapp.menuactivity.ShareAndEarn;
import com.tatx.userapp.menuactivity.TripHistoryActivity;
import com.tatx.userapp.network.RetrofitRequester;
import com.tatx.userapp.network.RetrofitResponseListener;
import com.tatx.userapp.network.SocketResponseListener;
import com.tatx.userapp.pojos.AccountsCustomerVo;
import com.tatx.userapp.pojos.AirportByCountryVo;
import com.tatx.userapp.pojos.AirportDetail;
import com.tatx.userapp.pojos.ApiResponseVo;
import com.tatx.userapp.pojos.BroadcastLocationVo;
import com.tatx.userapp.pojos.Driver;
import com.tatx.userapp.pojos.FavLocation;
import com.tatx.userapp.pojos.GetCustomerProfileVo;
import com.tatx.userapp.pojos.GetFareVo;
import com.tatx.userapp.pojos.GetSavedLocationVo;
import com.tatx.userapp.pojos.GetLoyalityPointVo;
import com.tatx.userapp.pojos.OnTrip;
import com.tatx.userapp.pojos.OrderInitiatedVo;
import com.tatx.userapp.pojos.PlaceOrderVo;
import com.tatx.userapp.pojos.PromoValidityVo;
import com.tatx.userapp.pojos.PushNotificationResponseVo;
import com.tatx.userapp.pojos.RecentLocation;
import com.tatx.userapp.pojos.SetCustomerLoc;
import com.tatx.userapp.pojos.StateListDrawableWithBitmap;
import com.tatx.userapp.pojos.Type;
import com.tatx.userapp.pojos.UpdateDeviceTokenVo;
import com.tatx.userapp.pojos.UpdatePaymentTypeVo;
import com.tatx.userapp.pojos.UserLogoutVo;
import org.apache.commons.collections4.CollectionUtils;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
import ademar.phasedseekbar.PhasedListener;
import ademar.phasedseekbar.PhasedOnItemClickListener;
import ademar.phasedseekbar.PhasedSeekBar;
import ademar.phasedseekbar.SimplePhasedAdapter;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class GoogleMapDrawerActivity extends PushNotificationListenerActivity implements
View.OnClickListener,
NavigationView.OnNavigationItemSelectedListener,
RoutingListener,
GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
OnMapReadyCallback,
GoogleMap.OnMapLoadedCallback,
GoogleMapOnTouchListener,
SocketResponseListener,
RetrofitResponseListener,
View.OnTouchListener, PushNotificationListenerActivity.OnUnReadNotificationCountChangeListener {
public static final int notifyID = 9001;
private static final String LOG = GoogleMapDrawerActivity.class.getSimpleName();
private static final int DEFAULT_MIN_TIME_TO_REACH = 5000;
private static final String NO_DRIVER = "No";
private int PHASED_SEEKBAR_DEFAULT_INDEX = 0;
public static String currentPoromocode;
private GoogleMap googleMap = null;
protected LatLng end;
private static final String LOG_TAG = "MyActivity";
protected GoogleApiClient mGoogleApiClient;
// private PlaceAutoCompleteAdapter mAdapter;
private ArrayList<Polyline> polylines;
private static final int[] COLORS = new int[]{R.color.primary_dark, R.color.primary, R.color.primary_light, R.color.accent, R.color.primary_dark_material_light};
LocationRequest mLocationRequest;
private static final int REQUEST_CHECK_SETTINGS = 1;
private static final long INTERVAL = 1000 * 5;
private static final long FASTEST_INTERVAL = 1000 * 2;
private static final float MINIMUM_DISPLACEMENT_IN_METERS = 35;
double latitude = 0;
double longitude = 0;
private DrawerLayout drawer;
private SharedPreferences sp;
private SharedPreferences.Editor editor;
private ProgressDialog progressDialog;
private Location lastknownLocation = null;
private boolean isMarkerRotating = false;
// private int cabType;
private LatLng destinationLatLngSelected = null;
private boolean confirmValue = false;
private String addressSoruce;
private SlidingUpPanelLayout mLayout;
private SlidingUpPanelLayout.PanelState stateNew;
private LatLng sourceLatLngSelected;
private String sourceAddress = "";
int currentLeft = 5;
int currentRight = 5;
private String drop_address="";
private String pick_address;
private double destLat;
private double destLong;
private ImageView profilepic;
private TextView username;
private TextView userlname;
private TextView creditpoints;
private ImageView loyaltiicon;
private boolean destinationPressed=false;
private boolean sourcePressed=true;
private String addressDestination;
private CameraPosition currentCameraPosition;
private Dialog selectPaymentTypeDialog;
private Resources resources;
private BroadcastLocationVo broadcastLocationVo;
private boolean previousResponseSuccess=true;
private CountDownTimer countDownTimer=null;
private SetCustomerLoc setCustomerLoc;
private AccountsCustomerVo accountsCustomerVo;
private int paymentTypeId;
private MyBroadcastReceiver myBroadcastReceiver;
private int[] cabCatagoriesId=null;
private int cabTypeId=1;
public static GoogleMapDrawerActivity instance;
private LinearLayout llMarker;
private LinearLayout llTimeMin;
private ImageView ivFilledCircle;
private ImageView ivLoaderGif;
private ImageView ivTvTimeBg;
private TextView tvMin;
private ImageView ivLoaderFlash;
private GetSavedLocationVo getSavedLocationVo;
private BitmapDrawable categoryCarDrawable;
private String countryNameGeo=null;
private AirportByCountryVo airportByCountryVo;
private double previousLat=0.0;
private double previousLng=0.0;
private boolean isKeyboardOpen=false;
private boolean onConnectedCall=false;
private boolean isAirPortBoundary=false;
private Marker sourceMapMarker;
private Marker destinationMapMarker;
private View[] editableViews ;
private CustomerAlertDialog customerAlertDialog;
private Bitmap markerCategoryCarDrawable;
private Bitmap bitmapImg;
private StateListDrawableWithBitmap stateListDrawableWithBitmap;
private Bitmap[] markerBitmapImgs;
// public Bundle savedInstanceState;
protected void createLocationRequest()
{
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(MINIMUM_DISPLACEMENT_IN_METERS);
}
@BindView(R.id.btn_promo_code) CustomButton btnPromoCode;
@BindView(R.id.tv_estimate_time) TextView tvEstimateTime;
@BindView(R.id.tv_time) TextView tvTime;
@BindView(R.id.iv_picker_icon) ImageView ivPickerIcon;
@BindView(R.id.tv_source_selected) BackAwareEditText tvSourceSelected;
@BindView(R.id.tv_destination_selected)public BackAwareEditText tvDestinationSelected;
// @BindView(R.id.multicabs) ImageView multi;
@BindView(R.id.my_current_location) ImageButton myCurrentLocation;
@BindView(R.id.order_button) Button btnOrder;
@BindView(R.id.navigationClickRelativeL) RelativeLayout navigationClickRelativeL;
@BindView(R.id.navigation) ImageView navigationMenuIcon;
@BindView(R.id.dragView1) LinearLayout relativeLayoutSeekbar;
@BindView(R.id.order_layout) RelativeLayout orderLayout;
@BindView(R.id.enroute_layout) LinearLayout coifirmatonlinearLayout;
@BindView(R.id.farestimte) TextView farestimate;
@BindView(R.id.btn_cash) Button btncash;
@BindView(R.id.imageButton) ImageView imageButton;
@BindView(R.id.searchlayout) RelativeLayout searchlayout;
@BindView(R.id.tv_source_address_to_show) TextView sourceText;
@BindView(R.id.tv_destination_address_to_show) TextView destinationText;
@BindView(R.id.tv_cab_capacity) TextView tvCabCapacity;
@BindView(R.id.tv_sar_per_km) TextView tvSarPerKm;
@BindView(R.id.tv_min_fare) TextView tvMinFare;
@BindView(R.id.tv_base_fare) TextView tvBaseFare;
@BindView(R.id.tv_price_per_min) TextView tvPricePerMin;
@BindView(R.id.cab_name) TextView cab_name;
@BindView(R.id.psb_hor) PhasedSeekBar psbHorizontal;
@BindView(R.id.btn_confirm_order) Button btnConfirmOrder;
@BindView(R.id.bottomll) RelativeLayout hideRelativeLayout;
@BindView(R.id.clear_source) RelativeLayout clearSource;
@BindView(R.id.clear_destination) RelativeLayout clearDestination;
@BindView(R.id.ll_category_names) LinearLayout llCategoryNames;
@BindView(R.id.relSeekbarLayout) RelativeLayout relSeekbarLayout;
@BindView(R.id.faredetail_layout) RelativeLayout fareDetailLayout ;
@BindView(R.id.ll_drag_view_main) LinearLayout llDragViewMain;
@BindView(R.id.custom_animate_marker) View customAnimateMarker;
@BindView(R.id.nav_view) NavigationView navigationView;
// @BindView(R.id.tv_recent_location) TextView tvRecentLocation;
@BindView(R.id.coordinator_ll) CoordinatorLayout coordinator_ll;
@BindView(R.id.v_marker_bottom_line) View vMarkerBottomLine;
@BindView(R.id.rv_google_search)
RecyclerView mRecyclerView;
@BindView(R.id.recyclerview_saved_locatons) RecyclerView recyclerviewSavedLocatons;
@BindView(R.id.ll_suggtion_view) LinearLayout llSuggtionView;
@BindView(R.id.recyclerView1)
RecyclerView rvGoogleSearchDestination;
@BindView(R.id.recyclerview_saved_locatons1) RecyclerView rvSavedLocatonsDestination;
@BindView(R.id.ll_suggtion_view1) LinearLayout llSuggtionViewDestination;
@BindView(R.id.tv_normal) TextView tvNormal;
@BindView(R.id.tv_satellite) TextView tvSatellite;
@BindView(R.id.fl_map_view_tpye) FrameLayout flMapViewTpye;
private ArrayList<FavLocation> favLocationArrayList=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Fabric.with(this, new Crashlytics());
instance = this;
logUser();
setContentView(R.layout.activity_googlemap_drawer);
ButterKnife.bind(this);
setDisableHideKeyBoard(true);
if (!ServiceUrls.CURRENT_ENVIRONMENT.getEnvironmentType().equals("PRODUCTION ENVIRONMENT"))
{
Common.customToast(this, ServiceUrls.CURRENT_ENVIRONMENT.getEnvironmentType());
Common.customToast(this, DensityType.getEnumField(getResources().getDisplayMetrics().density).getDensityString());
}
Common.Log.i("getClass().getSimpleName() : " + getClass().getSimpleName());
navigationClickRelativeL.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event)
{
if (drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else
{
Common.hideSoftKeyboard(GoogleMapDrawerActivity.this);
drawer.openDrawer(GravityCompat.START);
}
return false;
}
});
navigationMenuIcon.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event)
{
if (drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else
{
Common.hideSoftKeyboard(GoogleMapDrawerActivity.this);
drawer.openDrawer(GravityCompat.START);
}
return false;
}
});
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView.setItemIconTintList(null);
profilepic = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.profilepic);
username = (TextView) navigationView.getHeaderView(0).findViewById(R.id.username);
userlname = (TextView) navigationView.getHeaderView(0).findViewById(R.id.userlname);
creditpoints = (TextView) navigationView.getHeaderView(0).findViewById(R.id.creditpoints);
loyaltiicon = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.loyaltiicon);
Menu m = navigationView.getMenu();
for (int i=0;i<m.size();i++) {
MenuItem mi = m.getItem(i);
//for aapplying a font to subMenu ...
SubMenu subMenu = mi.getSubMenu();
if (subMenu!=null && subMenu.size() >0 ) {
for (int j=0; j <subMenu.size();j++) {
MenuItem subMenuItem = subMenu.getItem(j);
applyFontToMenuItem(subMenuItem);
}
}
//the method we have create in activity
applyFontToMenuItem(mi);
}
profilepic.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawer.closeDrawer(GravityCompat.START);
Intent intent=new Intent(GoogleMapDrawerActivity.this,DisplayProfileActivity.class);
startActivity(intent);
}
});
navigationView.setNavigationItemSelectedListener(this);
if (!Util.isGooglePlayServicesAvailable(this)) {
finish();
}
Log.d(LOG, String.valueOf(Util.isGooglePlayServicesAvailable(this)));
createLocationRequest();
polylines = new ArrayList<>();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
displayGoogleLocationSettingPage(this);
HashMap<String, String> params = new HashMap<String, String>();
params.put(ServiceUrls.RequestParams.ROLE,Constants.CUSTOMER);
params.put(ServiceUrls.RequestParams.ONLINE,"1");
params.put(ServiceUrls.RequestParams.OS,Constants.ANDROID);
TATX.getInstance().sendSocketRequest(this, ServiceUrls.RequestNames.ON_SOCKET_OPEN,params);
initializedAll();
sildingUpPanel();
new RetrofitRequester(this).sendStringRequest(ServiceUrls.RequestNames.GET_CUSTOMER_PROFILE,null);
//Careem Marker Start.
RelativeLayout rlParent = (RelativeLayout) findViewById(R.id.rl_parent);
llMarker = (LinearLayout) findViewById(R.id.ll_marker);
llTimeMin = (LinearLayout) findViewById(R.id.ll_time_min);
ivFilledCircle = (ImageView) findViewById(R.id.iv_filled_circle);
ivLoaderGif = (ImageView) findViewById(R.id.iv_loader_gif);
ivTvTimeBg = (ImageView) findViewById(R.id.iv_tv_time_bg);
tvTime = (TextView) findViewById(R.id.tv_time);
tvMin = (TextView) findViewById(R.id.tv_min);
ivLoaderFlash = (ImageView) findViewById(R.id.iv_loader_flash);
setAnimatedMarkerColor(R.color.button_color);
setUnReadNotificationCountChangeListener(this);
}
private void setNotificationIconCountText(int count)
{
Menu menu = navigationView.getMenu();
MenuItem navNotification = menu.findItem(R.id.nav_notification);
if(count <=0)
{
navNotification.setIcon(R.drawable.notifications);
}
else
{
View inflatedView = getLayoutInflater().inflate(R.layout.actionbar_badge_layout, null);
TextView tvUnReadNotificationCount = (TextView) inflatedView.findViewById(R.id.tv_un_read_notification_count);
tvUnReadNotificationCount.setText(String.valueOf(count));
Bitmap bitmapFromView = Common.getBitmapFromView(inflatedView);
navNotification.setIcon(new BitmapDrawable(getResources(),bitmapFromView));
}
}
@Override
protected void onPushNotificationReceived(PushNotificationResponseVo pushNotificationResponseVo)
{
Common.Log.i("Inside CancelOrderActivity - onPushNotificationReceived().");
Common.Log.i("pushNotificationResponseVo.toString() : "+pushNotificationResponseVo.toString());
switch (pushNotificationResponseVo.code)
{
case 20000:
OnTrip onTrip = Common.getSpecificDataObject(pushNotificationResponseVo.data, OnTrip.class);
Intent intent = new Intent(this, OnTripMapActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("action", 2);
/*intent.putExtra("source", sourceAdd);
intent.putExtra("destination", destinationAdd);*/
intent.putExtra(Constants.IntentKeys.SOURCE_ADDRESS, Common.getCompleteAddressString(this,onTrip.pickLatitude,onTrip.pickLongitude).getCompleteAddress());
intent.putExtra(Constants.IntentKeys.DESTINATION_ADDRESS, Common.getCompleteAddressString(this,onTrip.dropLatitude,onTrip.dropLongitude).getCompleteAddress());
intent.putExtra(Constants.KEY_1, onTrip);
finish();
startActivity(intent);
break;
case ServiceUrls.PushResponseCodes._20007:
logoutApi(1);
break;
case ServiceUrls.PushResponseCodes.FROM_NOTIFICATION_MANAGEMENT_20008:
sendNotification(pushNotificationResponseVo.message);
break;
}
}
@Override
protected void onStart()
{
super.onStart();
if (!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
unregisterReceiver(myBroadcastReceiver);
}
public void initializedAll()
{
tvSourceSelected.setBackPressedListener(new BackAwareEditText.BackPressedListener() {
@Override
public void onImeBack(BackAwareEditText editText) {
isKeyboardOpen = false;
}
});
tvDestinationSelected.setBackPressedListener(new BackAwareEditText.BackPressedListener() {
@Override
public void onImeBack(BackAwareEditText editText) {
isKeyboardOpen = false;
}
});
String promoImage = getIntent().getStringExtra(Constants.IntentKeys.PROMO_IMG);
Common.Log.i("?? - promoImage : "+promoImage);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String thisDate = dateFormat.format(new Date());
Log.d("date_today","date_today"+thisDate);
if (promoImage!=null)
{
if ((Common.getDefaultSP(this).contains(Constants.SharedPreferencesKeys.SHOW_OFFER_SCREEN) && !Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.SHOW_OFFER_SCREEN, "").equalsIgnoreCase(thisDate)) || !Common.getDefaultSP(this).contains(Constants.SharedPreferencesKeys.SHOW_OFFER_SCREEN))
{
showOfferDialog(promoImage);
Common.getDefaultSP(this).edit().putString(Constants.SharedPreferencesKeys.SHOW_OFFER_SCREEN, thisDate).commit();
Log.d("date_today", "date_today " + Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.SHOW_OFFER_SCREEN, ""));
}
}
sp = PreferenceManager.getDefaultSharedPreferences(this);
editor = sp.edit();
new RetrofitRequester(this).sendStringRequest(ServiceUrls.RequestNames.GET_LOYALITY_POINT,null,Constants.RequestCodes.ONCREATE_REQUEST_CODE);
tvSourceSelected.setCursorVisible(false);
tvDestinationSelected.setCursorVisible(false);
btncash.setOnClickListener(this);
imageButton.setOnClickListener(this);
farestimate.setOnClickListener(this);
myCurrentLocation.setOnClickListener(this);
btnOrder.setOnClickListener(this);
btnConfirmOrder.setOnClickListener(this);
// multi.setOnClickListener(this);
btnConfirmOrder.setOnClickListener(this);
tvSourceSelected.setOnClickListener(this);
tvDestinationSelected.setOnClickListener(this);
//tvSourceSelected.requestFocus();
clearSource.setOnTouchListener(this);
clearDestination.setOnTouchListener(this);
tvSourceSelected.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Common.hideSoftKeyboard(GoogleMapDrawerActivity.this);
Log.d("onFocusChange A", "" + hasFocus);
if (hasFocus) {
Common.setViewsEnableStatuss(true,tvSourceSelected);
destinationPressed = false;
sourcePressed = true;
tvSourceSelected.setBackgroundDrawable(getResources().getDrawable(R.drawable.google_search_background_selected));
tvDestinationSelected.setBackgroundDrawable(getResources().getDrawable(R.drawable.google_search_background));
tvDestinationSelected.setTextColor(getResources().getColor(R.color.divider));
tvSourceSelected.setTextColor(getResources().getColor(R.color.black));
// vMarkerBottomLine.setBackgroundColor(Common.getColorFromResource(R.color.button_color));
setAnimatedMarkerColor(R.color.button_color);
tvEstimateTime.setVisibility(View.VISIBLE);
tvTime.setVisibility(View.VISIBLE);
Location location=new Location("");
location.setLatitude(latitude);
location.setLongitude(longitude);
myCurrentLocationCamera(location);
//suggetionSetAdapter(tvSourceSelected.getText().length());
Log.d("suggetionSetAdapter", "suggetionSetAdapter 747");
removeSourceMapMarker();
addDestinationMapMarker();
moveCameraToPosition(sourceLatLngSelected);
} else{
sourcePressed = false;
// Common.setViewsEnableStatuss(false,tvDestinationSelected);
}
}
});
tvDestinationSelected.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.d("onFocusChange B",""+hasFocus);
Common.hideSoftKeyboard(GoogleMapDrawerActivity.this);
if (hasFocus)
{
clearDestination.setVisibility(View.VISIBLE);
Common.setViewsEnableStatuss(true,tvDestinationSelected);
sourcePressed = false;
destinationPressed = true;
tvDestinationSelected.setBackgroundDrawable(getResources().getDrawable(R.drawable.google_search_background_selected));
tvSourceSelected.setBackgroundDrawable(getResources().getDrawable(R.drawable.google_search_background));
tvSourceSelected.setTextColor(getResources().getColor(R.color.divider));
tvDestinationSelected.setTextColor(getResources().getColor(R.color.black));
setAnimatedMarkerColor(R.color.black);
tvEstimateTime.setVisibility(View.GONE);
tvTime.setVisibility(View.VISIBLE);
// tvDestinationSelected.setText("");
//suggetionSetAdapter(tvDestinationSelected.getText().length());
Log.d("suggetionSetAdapter", "suggetionSetAdapter 774");
removeDestinationMapMarker();
addSourceMapMarker();
moveCameraToPosition(destinationLatLngSelected);
}
else
{
// Common.setViewsEnableStatuss(false,tvSourceSelected);
destinationPressed = false;
}
}
});
confirmationLayout(confirmValue);
resources = getResources();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit();
}
mapFragment.getMapAsync(this);
myBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter intentFilter_update = new IntentFilter(Constants.ACTION_MyUpdate);
intentFilter_update.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(myBroadcastReceiver, intentFilter_update);
}
private void setAnimatedMarkerColor(int colorResourceId)
{
tvTime.setText("");
GradientDrawable ivLoaderGifGradient = (GradientDrawable)ivLoaderGif.getBackground();
ivLoaderGifGradient.setColor(Common.getColorFromResource(colorResourceId));
GradientDrawable ivFilledCircleGradient = (GradientDrawable)ivFilledCircle.getBackground();
ivFilledCircleGradient.setColor(Common.getColorFromResource(colorResourceId));
GradientDrawable ivTvTimeBgGradient = (GradientDrawable)ivTvTimeBg.getBackground();
ivTvTimeBgGradient.setColor(Common.getColorFromResource(colorResourceId));
vMarkerBottomLine.setBackgroundColor(Common.getColorFromResource(colorResourceId));
}
public void sildingUpPanel() {
mLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
mLayout.addPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
@Override
public void onPanelSlide(View panel, float slideOffset) {
Log.i(LOG, "onPanelSlide, offset " + slideOffset);
}
@Override
public void onPanelStateChanged(View panel, SlidingUpPanelLayout.PanelState previousState, SlidingUpPanelLayout.PanelState newState) {
Log.i(LOG, "onPanelStateChanged " + newState);
Common.Log.i("onGoogleMapTouch - Down."+"setFadeOnClickListener"+ newState);
stateNew = newState;
}
});
mLayout.setFadeOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i(LOG, "onPanelStateChanged, offset " + "setFadeOnClickListener");
Common.Log.i("onGoogleMapTouch - Down."+"setFadeOnClickListener");
mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
}
});
countDownTimer = new CountDownTimer(2000, 1000)
{
public void onTick(long millisUntilFinished)
{
// tvTimeSec.setText("" + millisUntilFinished / 1000);
}
public void onFinish()
{
new Handler().post(new Runnable() {
@Override
public void run() {
if (sourcePressed)
callCameraChangeListner(currentCameraPosition);
else if (destinationPressed) {
selectDestinationByMapMove(currentCameraPosition);
}
}
});
}
};
}
public void onBackPressed()
{
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (confirmValue)
{
confirmValue = false;
confirmationLayout(confirmValue);
} else if (String.valueOf(stateNew).equalsIgnoreCase("EXPANDED")) {
mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else if (llSuggtionView.getVisibility()==View.VISIBLE || llSuggtionViewDestination.getVisibility()==View.VISIBLE){
llSuggtionView.setVisibility(View.GONE);
llSuggtionViewDestination.setVisibility(View.GONE);
return;
}else {
onBackPressed2();
}
}
public void onBackPressed2()
{
showExitConfirmationDialog(false);
}
private void showExitConfirmationDialog(final boolean logoutStatus)
{
String message = logoutStatus ? Common.getStringResourceText(R.string.are_you_sure_you_want_to_logout) : Common.getStringResourceText(R.string.do_you_want_to_exit);
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton( Common.getStringResourceText(R.string.yes), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
if(logoutStatus)
{
logoutApi(0);
}
else
{
finish();
}
}
})
.setNegativeButton(Common.getStringResourceText(R.string.no),null).create().show();
}
public void callCameraChangeListner(final CameraPosition position) {
new Handler().post(new Runnable() {
public GeoDetails geoDetails;
@Override
public void run() {
Log.d(LOG, "onCameraChange..socket...");
if (previousResponseSuccess) {
previousResponseSuccess = false;
LatLngBounds bounds = googleMap.getProjection().getVisibleRegion().latLngBounds;
// mAutoCompleteAdapter.setBounds(bounds);
if (!confirmValue) {
latitude = position.target.latitude;
longitude = position.target.longitude;
}
sourceLatLngSelected = new LatLng(latitude, longitude);
geoDetails = Common.getCompleteAddressString(GoogleMapDrawerActivity.this, latitude, longitude);
addressSoruce = geoDetails.getCompleteAddress();
tvSourceSelected.setText(addressSoruce);
addSourceMapMarker();
Log.d("Anil11111", "onCameraChange..socket...");
// tvSourceSelected.performCompletion();
sourceAddress = geoDetails.getAddress();
sendSocketRequestToSetCustomerLocationService();
// airPortFunctionality(geoDetails);
}
}
});
}
private void addSourceMapMarker() {
removeSourceMapMarker();
//
if (!sourcePressed && !TextUtils.isEmpty(tvSourceSelected.getText()) && sourceLatLngSelected!=null)
{
sourceMapMarker = googleMap.addMarker(new MarkerOptions().position(sourceLatLngSelected));
View inflatedView = getLayoutInflater().inflate(R.layout.marker_custom_view, null);
CustomTextView tvEstimateCabReachTime = (CustomTextView) inflatedView.findViewById(R.id.tv_estimate__cab_reach_time);
tvEstimateCabReachTime.setText("S");
sourceMapMarker.setIcon(BitmapDescriptorFactory.fromBitmap(Common.getBitmapFromView(inflatedView)));
}
//
}
private void addDestinationMapMarker()
{
removeDestinationMapMarker();
//
if (!destinationPressed && !TextUtils.isEmpty(tvDestinationSelected.getText()) && destinationLatLngSelected != null)
{
destinationMapMarker = googleMap.addMarker(new MarkerOptions().position(destinationLatLngSelected));
View inflatedView = getLayoutInflater().inflate(R.layout.marker_custom_view_black, null);
destinationMapMarker.setIcon(BitmapDescriptorFactory.fromBitmap(Common.getBitmapFromView(inflatedView)));
}
//
}
private void sendSocketRequestToSetCustomerLocationService()
{
Common.Log.i("? - Inside sendSocketRequestToSetCustomerLocationService().");
HashMap<String, String> params = new HashMap();
params.put(ServiceUrls.RequestParams.LATITUDE, String.valueOf(latitude));
params.put(ServiceUrls.RequestParams.LONGITUDE, String.valueOf(longitude));
params.put(ServiceUrls.RequestParams.CITY, sourceAddress);
TATX.getInstance().sendSocketRequest(GoogleMapDrawerActivity.this,ServiceUrls.RequestNames.SET_CUSTOMER_LOC,params,false);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item)
{
int id = item.getItemId();
switch (id)
{
case R.id.nav_profile:
Intent intent = new Intent(this, DisplayProfileActivity.class);
// Intent intent = new Intent(this, SuggetionClass.class);
startActivity(intent);
break;
case R.id.nav_accout:
Intent intent1 = new Intent(this, AccountActivity.class);
startActivity(intent1);
break;
case R.id.nav_trip_istory:
Intent intent2 = new Intent(this, TripHistoryActivity.class);
startActivity(intent2);
break;
case R.id.nav_notification:
//Toast.makeText(this, item.getTitle() + " section is under development", Toast.LENGTH_SHORT).show();
Intent intent3 = new Intent(this, NotificationsActivity.class);
startActivity(intent3);
break;
case R.id.nav_offers:
// Toast.makeText(this, item.getTitle() + " section is under development", Toast.LENGTH_SHORT).show();
Intent intent4 = new Intent(this, OfferActivity.class);
startActivity(intent4);
break;
case R.id.nav_loc:
Intent intentLocation = new Intent(this, AddLocationActivity.class);
startActivityForResult(intentLocation,Constants.RESULT_FROM_LOCATIONS);
break;
case R.id.nav_share:
//Toast.makeText(this, item.getTitle() + " section is under development", Toast.LENGTH_SHORT).show();
Intent intent5 = new Intent(this, ShareAndEarn.class);
startActivity(intent5);
break;
case R.id.nav_help:
// Toast.makeText(this, item.getTitle() + " section is under development", Toast.LENGTH_SHORT).show();
Intent intent6 = new Intent(this, HelpActivity.class);
startActivity(intent6);
break;
case R.id.nav_about:
//Toast.makeText(this, item.getTitle() + " section is under development", Toast.LENGTH_SHORT).show();
Intent intent7 = new Intent(this, AboutActivity.class);
startActivity(intent7);
break;
case R.id.nav_logout:
// logoutApi();
showExitConfirmationDialog(true);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void logoutApi(int logoutDueToPush)
{
HashMap<String, String> requestParams = new HashMap();
requestParams.put(ServiceUrls.RequestParams.DEVICE, Constants.ANDROID);
requestParams.put(ServiceUrls.RequestParams.DEVICE_ID,Common.getDeviceId(this));
requestParams.put(ServiceUrls.RequestParams.LOGOUT_DUE_TO_PUSH, String.valueOf(logoutDueToPush));
new RetrofitRequester(this).sendStringRequest(ServiceUrls.RequestNames.USER_LOGOUT,requestParams);
}
public void route(LatLng start, LatLng end) {
if (start == null || end == null) {
if (start == null) {
if (sourceText.getText().length() > 0) {
sourceText.setError(Common.getStringResourceText(R.string.please_choose_source));
} else {
Toast.makeText(this, Common.getStringResourceText(R.string.please_choose_source), Toast.LENGTH_SHORT).show();
}
}
if (end == null) {
if (tvDestinationSelected.getText().length() > 0) {
tvDestinationSelected.setError(Common.getStringResourceText(R.string.please_choose_destination));
} else {
Toast.makeText(this, Common.getStringResourceText(R.string.please_choose_destination), Toast.LENGTH_SHORT).show();
}
}
} else {
// progressDialog = ProgressDialog.show(this, Common.getStringResourceText(R.string.please_wait),
// Common.getStringResourceText(R.string.fetching_route_information), true);
Routing routing = new Routing.Builder()
.travelMode(AbstractRouting.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(true)
.waypoints(start, end)
.build();
routing.execute();
}
}
@Override
public void onRoutingFailure(RouteException e) {
// The Routing request failed
progressDialog.dismiss();
if (e != null) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, Common.getStringResourceText(R.string.something_went_wrong_try_again), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onRoutingStart() {
// The Routing Request starts
}
@Override
public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {
progressDialog.dismiss();
if (polylines.size() > 0) {
for (Polyline poly : polylines) {
poly.remove();
}
}
polylines = new ArrayList<>();
int dist = route.get(0).getDistanceValue();
int pos=0;
for (int i = 1; i < route.size(); i++) {
if (dist > route.get(i).getDistanceValue()) {
dist = route.get(i).getDistanceValue();
pos=i;
}
}
//In case of more than 5 alternative routes
int colorIndex = pos % COLORS.length;
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(getResources().getColor(COLORS[colorIndex]));
polyOptions.width(15 + pos * 2);
polyOptions.addAll(route.get(pos).getPoints());
Polyline polyline = googleMap.addPolyline(polyOptions);
polylines.add(polyline);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (int j = 0; j < route.get(pos).getPoints().size(); j++){
builder.include(route.get(pos).getPoints().get(j));
j=j+5;
}
// builder.include(destinationLatLngSelected);
LatLngBounds bounds = builder.build();
int padding = 100; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
googleMap.animateCamera(cu);
//Toast.makeText(getApplicationContext(), "Route " + (i + 1) + ": distance - " + route.get(i).getDistanceValue() + ": duration - " + route.get(i).getDurationValue(), Toast.LENGTH_SHORT).show();
// Start marker
MarkerOptions options = new MarkerOptions();
options.position(sourceLatLngSelected);
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.redpin));
googleMap.addMarker(options);
// End marker
options = new MarkerOptions();
options.position(destinationLatLngSelected);
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.blackpin));
googleMap.addMarker(options);
}
@Override
public void onRoutingCancelled() {
Log.i(LOG_TAG, "Routing was cancelled.");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.v(LOG_TAG, connectionResult.toString());
}
@Override
public void onConnected(Bundle bundle)
{
progressDialog = ProgressDialog.show(this, "",Common.getStringResourceText(R.string.please_wait), false);
onConnectedCall=true;
Common.Log.i("onConnected");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationListener() {
@Override
public void onLocationChanged(Location location)
{
// updateCameraBearing(googleMap,location.getBearing());
if (location!=null)
{
lastknownLocation=location;
if (onConnectedCall)
{
onConnectedCall=false;
sourceLatLngSelected = new LatLng(lastknownLocation.getLatitude(), lastknownLocation.getLongitude());
CameraUpdate center = CameraUpdateFactory.newLatLng(sourceLatLngSelected);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Constants.ZOOM_LEVEL);
sourceAddress = Common.getAddressString(getApplicationContext(), sourceLatLngSelected.latitude,sourceLatLngSelected.longitude);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
Common.Log.i("address : "+ sourceAddress);
Common.Log.i("onConnected.");
Common.Log.i("sourceLatLngSelected : "+sourceLatLngSelected);
Common.getCityBoundaries(GoogleMapDrawerActivity.this,sourceLatLngSelected);
callCameraChangeListner(googleMap.getCameraPosition());
if (progressDialog != null)
{
progressDialog.dismiss();
}
}
}
}
});
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onMapReady(GoogleMap map) {
googleMap = map;
// googleMap.getUiSettings().setRotateGesturesEnabled(false);
//googleMap.setMyLocationEnabled(true);
if (googleMap != null) {
Log.d(LOG, "onMapReady...");
float currentBottomF = getResources().getDimension(R.dimen._130sdp);
googleMap.setPadding(currentLeft, Math.round(currentBottomF), currentRight, Math.round(currentBottomF));
googleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
currentCameraPosition=cameraPosition;
Log.d("sourcePressed", "sourcePressed " + sourcePressed + " destinationPressed " + destinationPressed);
Common.Log.i("Inside onCameraChange().");
Common.Log.i("Camera LatLng : " + cameraPosition.target.latitude + "," + cameraPosition.target.longitude);
Location location = new Location("");
location.setLatitude(cameraPosition.target.latitude);
location.setLongitude(cameraPosition.target.longitude);
if (lastknownLocation != null) {
float distance = location.distanceTo(lastknownLocation);
if (Math.round(distance) < 30) {
myCurrentLocation.setVisibility(View.GONE);
} else {
myCurrentLocation.setVisibility(View.VISIBLE);
}
}
}
});
}
}
public void myCurrentLocationCamera(Location location) {
Log.d("lastknownLocation",location.toString());
if (location != null&&googleMap!=null) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Constants.ZOOM_LEVEL);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
Log.d("lastknownLocation",location.toString()+" "+googleMap.getCameraPosition());
if (sourcePressed)
callCameraChangeListner(googleMap.getCameraPosition());
else if (destinationPressed) {
selectDestinationByMapMove(googleMap.getCameraPosition());
}
}
}
public void displayGoogleLocationSettingPage(final Activity activity) {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest)
.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
// final LocationSettingsStates s= result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
//Toast.makeText(activity, "success...", Toast.LENGTH_SHORT).show();
/* Location location = lastknownLocation;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
String address = Common.getCompleteAddressString(GoogleMapDrawerActivity.this, latitude, longitude).getCompleteAddress();
// tvSourceSelected.setText(address);
LatLng lng = new LatLng(latitude, longitude);
startLntLng = lng;
Log.d(LOG, String.valueOf(location.getLatitude()) + address);
Log.d(LOG, "onCameraChange 1366" + latitude + " " + longitude);
}*/
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
Toast.makeText(activity, "RESOLUTION_REQUIRED", Toast.LENGTH_SHORT).show();
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
activity,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
@Override
public void onActivityResult(final int requestCode, int resultCode, Intent data) {
// final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
Log.d(LOG, "OnresultAxtivity1");
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
Log.d(LOG, "OnresultAxtivity4");
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
finish();
break;
default:
break;
}
break;
case Constants.RESULT_FROM_LOCATIONS:
switch (resultCode) {
case Activity.RESULT_OK:
new RetrofitRequester(this).sendStringRequest(ServiceUrls.RequestNames.GET_SAVED_LOCATIONS,null);
break;
case Activity.RESULT_CANCELED:
// The user was asked to change settings, but chose not to
// finish();
new RetrofitRequester(this).sendStringRequest(ServiceUrls.RequestNames.GET_SAVED_LOCATIONS,null);
break;
default:
break;
}
break;
}
}
public void zoomCamera(Double lat, Double lng) {
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat, lng)).zoom(Constants.ZOOM_LEVEL).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_source_selected:
isKeyboardOpen = true;
Log.d("suggetionSetAdapter", "suggetionSetAdapter 1832");
llSuggtionViewDestination.setVisibility(View.GONE);
llSuggtionView.setVisibility(View.VISIBLE);
Common.setSuggetions(this,mGoogleApiClient,recyclerviewSavedLocatons,mRecyclerView,favLocationArrayList,tvSourceSelected);
break;
case R.id.tv_destination_selected:
isKeyboardOpen = true;
Log.d("suggetionSetAdapter", "suggetionSetAdapter 1838");
llSuggtionView.setVisibility(View.GONE);
llSuggtionViewDestination.setVisibility(View.VISIBLE);
Common.setDestinationSuggetions(this,mGoogleApiClient,rvSavedLocatonsDestination,rvGoogleSearchDestination,favLocationArrayList,tvDestinationSelected);
break;
case R.id.my_current_location:
if (lastknownLocation != null) {
myCurrentLocationCamera(lastknownLocation);
}
break;
case R.id.order_button:
/*
if (true)
{
throw new RuntimeException("New Exception Raised from User App.");
}
*/ Log.d("GeoDetails anil"," latitude "+latitude+" longitude "+longitude);
Common.hideSoftKeyboard(this);
GeoDetails geoDetails = Common.getCompleteAddressString(GoogleMapDrawerActivity.this, latitude,longitude);
Log.d("GeoDetails anil",geoDetails.toString()+" latitude "+latitude+" longitude "+longitude);
if(TextUtils.isEmpty(tvSourceSelected.getText()))
{
Common.customToast(this,Common.getStringResourceText(R.string.please_choose_source));
return;
}
String estimateTimeText = minTimeToReach == DEFAULT_MIN_TIME_TO_REACH ? NO_DRIVER : minTimeToReach + "\nMin";
if (!estimateTimeText.equals(NO_DRIVER))
{
airPortFunctionality(geoDetails);
// getAccountDetailsApi();
new RetrofitRequester(GoogleMapDrawerActivity.this).sendStringRequest(ServiceUrls.RequestNames.ACCOUNTS_CUSTOMER,null,R.id.order_button);
if (currentPoromocode != null)
{
btnPromoCode.setText(currentPoromocode);
// btnPromoCode.setClickable(false);
}
if (tvSourceSelected.getText().toString().length() > 3 && tvDestinationSelected.getText().toString().length() > 3)
{
Common.Log.i("sourceLatLngSelected 2: "+sourceLatLngSelected);
Bounds sourceBounds = Common.getCityBoundaries(GoogleMapDrawerActivity.this,sourceLatLngSelected);
Common.Log.i("destinationLatLngSelected : "+destinationLatLngSelected);
Bounds destinationBounds = Common.getCityBoundaries(GoogleMapDrawerActivity.this,destinationLatLngSelected);
Common.Log.i("? - sourceBounds : "+sourceBounds);
Common.Log.i("? - destinationBounds : "+destinationBounds);
Common.Log.i("????? - sourceBounds : "+sourceBounds);
Common.Log.i("sourceBounds.northeast : "+sourceBounds.northeast);
if (destinationBounds==null)
{
Common.customToast(this,Common.getStringResourceText(R.string.invalid_destination));
return;
}
Location sourceNorthEastLocation = new Location("");
sourceNorthEastLocation.setLatitude(sourceBounds.northeast.lat);
sourceNorthEastLocation.setLongitude(sourceBounds.northeast.lng);
Location sourceSouthWestLocation = new Location("");
sourceSouthWestLocation.setLatitude(sourceBounds.southwest.lat);
sourceSouthWestLocation.setLongitude(sourceBounds.southwest.lng);
Location destinationNorthEastLocation = new Location("");
destinationNorthEastLocation.setLatitude(destinationBounds.northeast.lat);
destinationNorthEastLocation.setLongitude(destinationBounds.northeast.lng);
Location destinationSouthWestLocation = new Location("");
destinationSouthWestLocation.setLatitude(destinationBounds.southwest.lat);
destinationSouthWestLocation.setLongitude(destinationBounds.southwest.lng);
float northEastDistance = sourceNorthEastLocation.distanceTo(destinationNorthEastLocation);
Common.Log.i("northEarstDistance : "+ northEastDistance);
float southWestDistance = sourceSouthWestLocation.distanceTo(destinationSouthWestLocation);
Common.Log.i("southWestDistance : "+southWestDistance);
LatLngBounds sourceLatLngBounds = new LatLngBounds(new LatLng(sourceSouthWestLocation.getLatitude(),sourceSouthWestLocation.getLongitude()),new LatLng(sourceNorthEastLocation.getLatitude(),sourceNorthEastLocation.getLongitude()));
boolean inSideBoundary = sourceLatLngBounds.contains(destinationLatLngSelected);
Common.Log.i("sourceLatLngBounds.contains(destinationLatLngSelected) : "+sourceLatLngBounds.contains(destinationLatLngSelected));
Common.Log.i("sourceNorthEastLocation.toString() : "+sourceNorthEastLocation.toString());
Common.Log.i("sourceSouthWestLocation.toString() : "+sourceSouthWestLocation.toString());
Common.Log.i("destinationNorthEastLocation.toString() : "+destinationNorthEastLocation.toString());
Common.Log.i("destinationSouthWestLocation.toString() : "+destinationSouthWestLocation.toString());
if(southWestDistance <=20000 || northEastDistance <= 20000 || inSideBoundary)
{
googleMap.clear();
if (sourceLatLngSelected != null && destinationLatLngSelected != null)
{
Common.Log.i("sourceLatLngSelected 2:route new"+sourceLatLngSelected);
Common.Log.i("destinationLatLngSelected :route new"+destinationLatLngSelected);
// googleMap.setPadding(0,0,0, (int) getResources().getDimension(R.dimen.sp100));
route(sourceLatLngSelected, destinationLatLngSelected);
}
confirmValue = true;
confirmationLayout(confirmValue);
}
else
{
Common.customToast(this, Common.getStringResourceText(R.string.the_destination_entered_is_outside_our_coverage_area), Common.TOAST_TIME);
return;
}
}
else
{
resetCabsData();
if (sourceLatLngSelected != null && destinationLatLngSelected != null) {
Common.Log.i("sourceLatLngSelected 2:route else "+sourceLatLngSelected);
Common.Log.i("destinationLatLngSelected :route else"+destinationLatLngSelected);
route(sourceLatLngSelected, destinationLatLngSelected);
}
confirmValue = true;
confirmationLayout(confirmValue);
}
} else {
Common.customToast(this, Common.getStringResourceText(R.string.No_cab_found_please_try_after_some_time), Common.TOAST_TIME);
}
// btnOrder.setEnabled(true);
break;
/* case R.id.multicabs:
Common.customToast(this, "Comming soon...", Common.TOAST_TIME);
break;*/
case R.id.iv_picker_icon:
confirmValue = true;
confirmationLayout(confirmValue);
break;
case R.id.farestimte:
// farestimate.setEnabled(false);
if (destinationText.getText().toString().length() > 3)
{
String cvId = null;
for (int i = 0; i < setCustomerLoc.types.size(); i++) {
if (setCustomerLoc.types.get(i).typeId.equalsIgnoreCase(String.valueOf(cabTypeId))) {
cvId = setCustomerLoc.types.get(i).vcId;
}
}
HashMap<String, String> requestparams = new HashMap<>();
// requestparams.put(ServiceUrls.RequestParams.TYPE, String.valueOf(broadcastLocationVo.types.get(cabType).typeId));
requestparams.put(ServiceUrls.RequestParams.VC_ID, cvId);
requestparams.put(ServiceUrls.RequestParams.PICK_LATITUDE, String.valueOf(sourceLatLngSelected.latitude));
requestparams.put(ServiceUrls.RequestParams.PICK_LONGITUDE,String.valueOf(sourceLatLngSelected.longitude));
requestparams.put(ServiceUrls.RequestParams.DROP_LATITUDE,String.valueOf(destinationLatLngSelected.latitude));
requestparams.put(ServiceUrls.RequestParams.DROP_LONGITUDE,String.valueOf(destinationLatLngSelected.longitude));
new RetrofitRequester(this).sendStringRequest(ServiceUrls.RequestNames.GET_FARE,requestparams);
}
else
{
Common.customToast(this, Common.getStringResourceText(R.string.please_select_destination), Common.TOAST_TIME);
}
// farestimate.setEnabled(true);
break;
case R.id.btn_cash:
showPaymentOptionPopup();
break;
case R.id.btn_confirm_order:
if (destinationLatLngSelected != null) {
destLat = destinationLatLngSelected.latitude;
destLong = destinationLatLngSelected.longitude;
drop_address = Common.getCompleteAddressString(this, destLat, destLong).getCompleteAddress();
} else {
destLat = 0;
destLong = 0;
}
if (String.valueOf(latitude).length()>3&&String.valueOf(longitude).length()>3) {
pick_address = Common.getCompleteAddressString(this, latitude, longitude).getCompleteAddress();
}
String cvId = null;
for (int i = 0; i < setCustomerLoc.types.size(); i++) {
if (setCustomerLoc.types.get(i).typeId.equalsIgnoreCase(String.valueOf(cabTypeId))) {
cvId = setCustomerLoc.types.get(i).vcId;
}
}
HashMap<String, String> params = new HashMap();
params.put(ServiceUrls.RequestParams.PICK_LATITUDE, String.valueOf(latitude));
params.put(ServiceUrls.RequestParams.PICK_LONGITUDE, String.valueOf(longitude));
params.put(ServiceUrls.RequestParams.DROP_LATITUDE, String.valueOf(destLat));
params.put(ServiceUrls.RequestParams.DROP_LONGITUDE, String.valueOf(destLong));
// params.put(ServiceUrls.RequestParams.TYPE, String.valueOf(cabType));
params.put(ServiceUrls.RequestParams.TYPE, String.valueOf(cabTypeId));
params.put(ServiceUrls.RequestParams.VC_ID,cvId);
// params.put(ServiceUrls.RequestParams.TYPE, String.valueOf(setCustomerLoc.types.get(cabType).typeId));
// params.put(ServiceUrls.RequestParams.VC_ID, String.valueOf(setCustomerLoc.types.get(cabType).vcId));
// params.put(ServiceUrls.RequestParams.PAYMENT_TYPE, "1");
// params.put(ServiceUrls.RequestParams.PAYMENT_TYPE, String.valueOf(accountsCustomerVo.paymentTypeId));
params.put(ServiceUrls.RequestParams.PAYMENT_TYPE, String.valueOf(getPaymentTypeId()));
params.put(ServiceUrls.RequestParams.PICK_LOCATION, pick_address);
params.put(ServiceUrls.RequestParams.DROP_LOCATION, drop_address);
if (!btnPromoCode.getText().toString().equalsIgnoreCase(Common.getStringResourceText(R.string.add_promo_code)))
{
params.put(ServiceUrls.RequestParams.PCODE, String.valueOf(btnPromoCode.getText()));
}
params.put(ServiceUrls.RequestParams.isAirport,Common.booleanToIntString(isAirPortBoundary));
TATX.getInstance().sendSocketRequest(this,ServiceUrls.RequestNames.PLACE_ORDER,params);
/*
coifirmatonlinearLayout.setVisibility(View.GONE);
Intent intent2 = new Intent(this, CancelOrderActivity.class);
intent2.putExtra("sourceAdd", sourceText.getText().toString());
intent2.putExtra("destinationAdd", destinationText.getText().toString());
intent2.putExtra("source_lat", latitude);
intent2.putExtra("source_long", longitude);
intent2.putExtra("destination_lat", destLat);
intent2.putExtra("destination_long", destLong);
startActivity(intent2);
*/
break;
}
}
private void moveCameraToPosition(LatLng latLngSelected)
{
Common.Log.i("? - latLngSelected : "+latLngSelected);
if (latLngSelected != null)
{
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLngSelected));
/*
CameraUpdate center = CameraUpdateFactory.newLatLng(latLngSelected);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Constants.ZOOM_LEVEL);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
*/
Common.Log.i("? - latLngSelected : "+latLngSelected);
}
}
private void showPaymentOptionPopup()
{
final TextView online, cash, credits;
selectPaymentTypeDialog = new Dialog(this);
selectPaymentTypeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
selectPaymentTypeDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
selectPaymentTypeDialog.setContentView(R.layout.payment_option_popup);
online = (TextView) selectPaymentTypeDialog.findViewById(R.id.online);
cash = (TextView) selectPaymentTypeDialog.findViewById(R.id.cash);
credits = (TextView) selectPaymentTypeDialog.findViewById(R.id.credits);
online.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
new RetrofitRequester(GoogleMapDrawerActivity.this).sendStringRequest(ServiceUrls.RequestNames.ACCOUNTS_CUSTOMER,null,R.id.online);
}
});
cash.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callUpdatePaymetAPI(String.valueOf(PaymentType.CASH.getId()));
selectPaymentTypeDialog.cancel();
}
});
credits.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new RetrofitRequester(GoogleMapDrawerActivity.this).sendStringRequest(ServiceUrls.RequestNames.ACCOUNTS_CUSTOMER,null,R.id.credits);
}
});
selectPaymentTypeDialog.setCancelable(true);
selectPaymentTypeDialog.show();
}
@Override
public void onStop() {
super.onStop();
}
private void rotateMarker(final Marker marker, final float toRotation) {
if (!isMarkerRotating) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = marker.getRotation();
final long duration = 1000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
isMarkerRotating = true;
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
float rot = t * toRotation + (1 - t) * startRotation;
marker.setRotation(-rot > 180 ? rot / 2 : rot);
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
isMarkerRotating = false;
}
}
});
}
}
private void animateMarker(GoogleMap googleMap, final Marker marker, final LatLng toPosition,
final boolean hideMarker) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = googleMap.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 5000;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed
/ duration);
double lng = t * toPosition.longitude + (1 - t)
* startLatLng.longitude;
double lat = t * toPosition.latitude + (1 - t)
* startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
} else {
if (hideMarker) {
marker.setVisible(false);
} else {
marker.setVisible(true);
}
}
}
});
}
public void confirmationLayout(boolean confirmValue) {
if (confirmValue)
{
cab_name.setText(CabTypes.sliderDetails(cabTypeId).cabType);
navigationClickRelativeL.setVisibility(View.GONE);
imageButton.setVisibility(View.GONE);
searchlayout.setVisibility(View.GONE);
ivPickerIcon.setVisibility(View.GONE);
tvEstimateTime.setVisibility(View.GONE);
customAnimateMarker.setVisibility(View.GONE);
coifirmatonlinearLayout.setVisibility(View.VISIBLE);
relativeLayoutSeekbar.setVisibility(View.GONE);
orderLayout.setVisibility(View.GONE);
sourceText.setText(tvSourceSelected.getText().toString());
destinationText.setText(tvDestinationSelected.getText().toString());
flMapViewTpye.setVisibility(View.GONE);
} else {
if (googleMap != null) {
resetCabsData();
}
navigationClickRelativeL.setVisibility(View.VISIBLE);
imageButton.setVisibility(View.VISIBLE);
searchlayout.setVisibility(View.VISIBLE);
ivPickerIcon.setVisibility(View.VISIBLE);
tvEstimateTime.setVisibility(View.VISIBLE);
customAnimateMarker.setVisibility(View.VISIBLE);
coifirmatonlinearLayout.setVisibility(View.GONE);
relativeLayoutSeekbar.setVisibility(View.VISIBLE);
orderLayout.setVisibility(View.VISIBLE);
flMapViewTpye.setVisibility(View.VISIBLE);
}
}
@Override
public void onMapLoaded() {
Log.d("OnLoad", "OnLoad.......");
}
@Override
public void onGoogleMapTouch(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
Common.Log.i("onGoogleMapTouch - Down.");
if (confirmValue){
return;
}
llSuggtionView.setVisibility(View.GONE);
llSuggtionViewDestination.setVisibility(View.GONE);
if (String.valueOf(stateNew).equalsIgnoreCase("EXPANDED")||String.valueOf(stateNew).equalsIgnoreCase("ANCHORED")) {
mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
return;
}
Common.Log.i("onGoogleMapTouch - Down.2");
if (countDownTimer!=null) {
countDownTimer.cancel();
}
tvSourceSelected.setHint(Common.getStringResourceText(R.string.go_to_pin));
if (!confirmValue) {
slideToBottom(hideRelativeLayout);
slideToBottom(relativeLayoutSeekbar);
fareDetailLayout.setVisibility(View.GONE);
// sildingUpPanel();
Common.hideSoftKeyboard(this);
}
//Careem Marker
ScaleAnimation fade_out = new ScaleAnimation(1f, 0.5f, 1f, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 1.2f);
fade_out.setDuration(1000);
fade_out.setFillAfter(true);
llMarker.startAnimation(fade_out);
ivFilledCircle.setVisibility(View.VISIBLE);
ivTvTimeBg.setVisibility(View.GONE);
tvTime.setVisibility(View.GONE);
// tvMin.setVisibility(View.GONE);
//Careem Marker
break;
case MotionEvent.ACTION_UP:
Common.Log.i("onGoogleMapTouch - Up.");
if (confirmValue){
return;
}
if (String.valueOf(stateNew).equalsIgnoreCase("EXPANDED")||String.valueOf(stateNew).equalsIgnoreCase("ANCHORED")) {
mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
return;
}
if (!confirmValue) {
animateViewFromBottomToTop(hideRelativeLayout);
animateViewFromBottomToTop(relativeLayoutSeekbar);
// fareDetailLayout.setVisibility(View.VISIBLE);
// sildingUpPanel();
}
if (countDownTimer!=null) {
countDownTimer.start();
}
Log.d("Pressed::","sourcePressed "+sourcePressed+" destinationPressed "+destinationPressed+"confirmValue"+confirmValue);
//Careem Marker
ScaleAnimation fade_in = new ScaleAnimation(0.5f, 1f, 0.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 1.2f);
fade_in.setDuration(1000);
fade_in.setFillAfter(true);
llMarker.startAnimation(fade_in);
ivFilledCircle.setVisibility(View.GONE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
ivTvTimeBg.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
ScaleAnimation fade_in = new ScaleAnimation(0.5f, 1f, 0.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
fade_in.setDuration(500);
fade_in.setFillAfter(true);
llTimeMin.setVisibility(View.VISIBLE);
llTimeMin.startAnimation(fade_in);
ScaleAnimation loaderFlashAnim = new ScaleAnimation(0.5f, 1f, 0.5f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
loaderFlashAnim.setDuration(500);
ivLoaderFlash.startAnimation(loaderFlashAnim);
tvTime.setVisibility(View.VISIBLE);
// tvMin.setVisibility(View.VISIBLE);
}
},200);
}
},1000);
//Careem Marker
break;
}
}
@Override
public void onSocketMessageReceived(final ApiResponseVo apiResponseVo, int requestId)
{
// Common.Log.i("Inside onSocketMessageReceived()");
Common.Log.i("getClass().getSimpleName() : " + getClass().getSimpleName());
if (apiResponseVo.code != Constants.SUCCESS)
{
Common.customToast(this, apiResponseVo.status);
return;
}
Common.Log.i("apiResponseVo.requestname : "+apiResponseVo.requestname);
Common.Log.i("apiResponseVo.data : "+apiResponseVo.data);
Common.Log.i("Switch Case Started");
switch (apiResponseVo.requestname)
{
case ServiceUrls.RequestNames.ON_SOCKET_OPEN:
Common.Log.i("apiResponseVo.toString() : "+apiResponseVo.toString());
break;
case ServiceUrls.RequestNames.SET_CUSTOMER_LOC:
// BroadcastLocationVo broadcastLocationVo = Common.getSpecificDataObject(apiResponseVo.data, BroadcastLocationVo.class);
setCustomerLoc = Common.getSpecificDataObject(apiResponseVo.data, SetCustomerLoc.class);
Common.Log.i("? - setCustomerLoc.types.size() : "+setCustomerLoc.types.size());
if (setCustomerLoc.types.size() > 0)
{
// setCabDetails(PHASED_SEEKBAR_DEFAULT_INDEX);
// cabView(setCustomerLoc.types);
// int [] drawable=new int [setCustomerLoc.types.size()];
final StateListDrawable [] stateListDrawables = new StateListDrawable[setCustomerLoc.types.size()];
markerBitmapImgs=new Bitmap[setCustomerLoc.types.size()];
cabCatagoriesId = new int[setCustomerLoc.types.size()];
llCategoryNames.removeAllViews();
for (int i = 0; i< setCustomerLoc.types.size(); i++)
{
// drawable[i]=CabTypes.sliderDetails(Integer.parseInt(setCustomerLoc.types.get(i).typeId)).drawableImg;
String carImageUrl = setCustomerLoc.categoryCarImageUrl+setCustomerLoc.types.get(i).categoryCarImage;
Common.Log.i("carImageUrl : "+carImageUrl);
StateListDrawableWithBitmap stateListDrawableWithBitmap = getDrawableFromUrl(carImageUrl);
stateListDrawables[i] = stateListDrawableWithBitmap.getStateListDrawable();
String mapCarImageUrl = setCustomerLoc.mapCarImageUrl+setCustomerLoc.types.get(i).categoryCarImage;
markerBitmapImgs[i] = getBitmapFromUrl(mapCarImageUrl);
Common.Log.i("?????-Integer.parseInt(setCustomerLoc.types.get(i).typeId) : "+Integer.parseInt(setCustomerLoc.types.get(i).typeId));
cabCatagoriesId[i]=CabTypes.sliderDetails(Integer.parseInt(setCustomerLoc.types.get(i).typeId)).cabId;
TextView inflatedView = (TextView) getLayoutInflater().inflate(R.layout.category_name, null);
inflatedView.setText(setCustomerLoc.types.get(i).type);
inflatedView.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT,1));
llCategoryNames.addView(inflatedView);
}
Common.Log.i("? - setCustomerLoc.types.size() : "+setCustomerLoc.types.size());
Common.Log.i("? - drawable.length : "+stateListDrawables.length);
// SimplePhasedAdapter simplePhasedAdapter = new SimplePhasedAdapter(resources, drawable);
SimplePhasedAdapter simplePhasedAdapter = new SimplePhasedAdapter(resources, stateListDrawables);
psbHorizontal.setAdapter(simplePhasedAdapter);
Common.Log.i("? - simplePhasedAdapter.getCount() : "+simplePhasedAdapter.getCount());
psbHorizontal.setFirstDraw(true);
btnOrder.setVisibility(View.VISIBLE);
psbHorizontal.setVisibility(View.VISIBLE);
relSeekbarLayout.setVisibility(View.VISIBLE);
llDragViewMain.setVisibility(View.VISIBLE);
fareDetailLayout.setVisibility(View.VISIBLE);
psbHorizontal.setOnItemClickListener(new PhasedOnItemClickListener()
{
@Override
public void onItemClick(int position)
{
Dialog dialog = new Dialog(GoogleMapDrawerActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.fare_estimate_popup);
dialog.getWindow().setBackgroundDrawableResource(R.drawable.dialog_background);
RelativeLayout faredetailLayout = (RelativeLayout) dialog.findViewById(R.id.faredetail_layout);
faredetailLayout.setVisibility(View.VISIBLE);
faredetailLayout.setPadding(0,0,0,0);
TextView tvCabCapacity = (TextView) dialog.findViewById(R.id.tv_cab_capacity);
TextView tvSarPerKm = (TextView) dialog.findViewById(R.id.tv_sar_per_km);
TextView tvMinFare = (TextView) dialog.findViewById(R.id.tv_min_fare);
TextView tvBaseFare = (TextView) dialog.findViewById(R.id.tv_base_fare);
TextView tvPricePerMin = (TextView) dialog.findViewById(R.id.tv_price_per_min);
setCabDetails(position, tvCabCapacity, tvSarPerKm, tvMinFare, tvBaseFare, tvPricePerMin);
dialog.show();
}
});
psbHorizontal.setListener(new PhasedListener() {
@Override
public void onPositionSelected(final int position) {
Common.Log.i("Inside Phased Seekbar Listener.");
setCabDetails(position, tvCabCapacity, tvSarPerKm, tvMinFare, tvBaseFare, tvPricePerMin);
// cabType = position;
PHASED_SEEKBAR_DEFAULT_INDEX = position;
cabTypeId=cabCatagoriesId[position];
resetCabsData();
// refreshCabsData(setCustomerLoc.drivers);
}
});
psbHorizontal.setPosition(PHASED_SEEKBAR_DEFAULT_INDEX);
}
else
{
btnOrder.setVisibility(View.GONE);
psbHorizontal.setVisibility(View.GONE);
relSeekbarLayout.setVisibility(View.GONE);
llDragViewMain.setVisibility(View.GONE);
}
if (googleMap!=null)
{
refreshCabsData(setCustomerLoc.drivers);
}
previousResponseSuccess=true;
break;
case Constants.BROADCAST_LOCATION:
broadcastLocationVo = Common.getSpecificDataObject(apiResponseVo.data, BroadcastLocationVo.class);
Common.Log.i("broadcastLocationVo.drivers.size() : "+broadcastLocationVo.drivers.size());
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!confirmValue)
{
/*BroadcastLocationVo broadcastLocationVo = Common.getSpecificDataObject(apiResponseVo.data, BroadcastLocationVo.class);
Common.Log.i("broadcastLocationVo.drivers.size() : "+broadcastLocationVo.drivers.size());*/
if (googleMap!=null && markerBitmapImgs!=null)
{
refreshCabsData(broadcastLocationVo.drivers);
}
}
}
});
break;
case ServiceUrls.RequestNames.PLACE_ORDER:
// java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Handler.removeCallbacksAndMessages(java.lang.Object)' on a null object reference
// at com.tatx.userapp.activities.GoogleMapDrawerActivity.onSocketMessageReceived(GoogleMapDrawerActivity.java:2313)
//Make promo code null for next trip
currentPoromocode=null;
if (CancelOrderActivity.handlerCheckCustomerOnTripStatus!=null) {
CancelOrderActivity.handlerCheckCustomerOnTripStatus.removeCallbacksAndMessages(null);
CancelOrderActivity.instance().cancelTimer();
}
PlaceOrderVo placeOrderVo = Common.getSpecificDataObject(apiResponseVo.data, PlaceOrderVo.class);
if (placeOrderVo.orderStatus)
{
OnTrip onTrip = new OnTrip(Integer.parseInt(placeOrderVo.tripid),Integer.parseInt(placeOrderVo.orderid),Integer.parseInt(placeOrderVo.vcId),placeOrderVo.cancellationCharges,placeOrderVo.pickLatitude,placeOrderVo.pickLongitude,placeOrderVo.dropLatitude,placeOrderVo.dropLongitude,placeOrderVo.vehicleNo,placeOrderVo.make,placeOrderVo.model,placeOrderVo.profile,String.valueOf(placeOrderVo.rating),placeOrderVo.drivername,placeOrderVo.mobile,placeOrderVo.carImage,placeOrderVo.color,placeOrderVo.paymentType);
Common.getDefaultSP(this).edit().putLong(Constants.ORDER_CANCEL_TIME, System.currentTimeMillis()).commit();
Intent AddLocationMapActivityIntent = new Intent(this, OnTripMapActivity.class);
AddLocationMapActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
AddLocationMapActivityIntent.putExtra("action", 2);
AddLocationMapActivityIntent.putExtra(Constants.IntentKeys.SOURCE_ADDRESS, Common.getCompleteAddressString(this,placeOrderVo.pickLatitude,placeOrderVo.pickLongitude).getCompleteAddress());
AddLocationMapActivityIntent.putExtra(Constants.IntentKeys.DESTINATION_ADDRESS,Common.getCompleteAddressString(this,placeOrderVo.dropLatitude,placeOrderVo.dropLongitude).getCompleteAddress());
AddLocationMapActivityIntent.putExtra(Constants.KEY_1, onTrip);
startActivity(AddLocationMapActivityIntent);
}
else
{
Intent intent = new Intent(this, GoogleMapDrawerActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Common.customToast(GoogleMapDrawerActivity.this, placeOrderVo.message, Common.TOAST_TIME);
break;
case ServiceUrls.RequestNames.ORDER_INITIATED:
OrderInitiatedVo orderInitiatedVo = Common.getSpecificDataObject(apiResponseVo.data, OrderInitiatedVo.class);
Common.Log.i("orderInitiatedVo.toString() : "+orderInitiatedVo.toString());
coifirmatonlinearLayout.setVisibility(View.GONE);
Intent intent = new Intent(this, CancelOrderActivity.class);
/*
intent.putExtra("sourceAdd", sourceText.getText().toString());
intent.putExtra("destinationAdd", destinationText.getText().toString());
*/
intent.putExtra(Constants.IntentKeys.SOURCE_ADDRESS,sourceText.getText().toString().trim());
intent.putExtra(Constants.IntentKeys.DESTINATION_ADDRESS,destinationText.getText().toString().trim());
intent.putExtra("source_lat", latitude);
intent.putExtra("source_long", longitude);
intent.putExtra("destination_lat", destLat);
intent.putExtra("destination_long", destLong);
intent.putExtra(Constants.KEY_1,orderInitiatedVo);
startActivity(intent);
break;
}
}
private StateListDrawableWithBitmap getDrawableFromUrl(final String carImageUrl)
{
stateListDrawableWithBitmap = new StateListDrawableWithBitmap();
categoryCarDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.vip);
Common.Log.i("?????-carImageUrl : "+carImageUrl);
final boolean[] bitmapFetched = {false};
/*
final ProgressDialog categoryWaitProgressDialog = new ProgressDialog(this);
categoryWaitProgressDialog.setMessage("Please dlfkjiejflesdj");
runOnUiThread(new Runnable() {
@Override
public void run() {
categoryWaitProgressDialog.show();
}
});
// categoryWaitProgressDialog.show();
*/
Common.Log.i("????? - After categoryWaitProgressDialog.show()");
do
{
Common.Log.i("?????-carImageUrl : "+carImageUrl);
// Picasso.with(GoogleMapDrawerActivity.this).load(carImageUrl).networkPolicy(NetworkPolicy.NO_STORE).into(new Target()
Picasso.with(GoogleMapDrawerActivity.this).load(carImageUrl).networkPolicy(NetworkPolicy.NO_CACHE).into(new Target()
{
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
{
Common.Log.i("? - onBitmapLoaded");
categoryCarDrawable = new BitmapDrawable(getResources(), bitmap);
bitmapImg = bitmap;
bitmapFetched[0] = true;
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
Common.Log.i("? - onBitmapFailed");
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Common.Log.i("? - onPrepareLoad");
}
});
/*
try
{
URL url = new URL(carImageUrl);
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
categoryCarDrawable = new BitmapDrawable(getResources(), bitmap);
bitmapImg =bitmap;
bitmapFetched[0] = true;
}
catch (IOException e)
{
e.printStackTrace();
}
*/
}while (!bitmapFetched[0]);
// categoryWaitProgressDialog.dismiss();
Common.Log.i("????? - After categoryWaitProgressDialog.dismiss()");
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, categoryCarDrawable);
stateListDrawable.addState(new int[] {android.R.attr.state_focused}, categoryCarDrawable);
stateListDrawable.addState(new int[] {android.R.attr.state_selected}, categoryCarDrawable);
stateListDrawable.addState(new int[] { }, getResources().getDrawable(R.drawable.circle));
stateListDrawableWithBitmap.setStateListDrawable(stateListDrawable);
stateListDrawableWithBitmap.setBitmap(bitmapImg);
return stateListDrawableWithBitmap;
}
private Bitmap getBitmapFromUrl(String carImageUrl)
{
// markerCategoryCarDrawable = (Bitmap) getResources().getDrawable(R.drawable.vip);
final boolean[] bitmapFetched = {false};
do
{
Picasso.with(this).load(carImageUrl).into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// Common.getResizedBitmap(bitmap,(bitmap.getWidth()/100)*75,(bitmap.getHeight()/100)*75);
int newWidth=(int)(bitmap.getWidth()*DensityType.getEnumField(getResources().getDisplayMetrics().density).getDensityValue())/4;
int newHeight=(int)(bitmap.getHeight()*DensityType.getEnumField(getResources().getDisplayMetrics().density).getDensityValue())/4;
Common.Log.i("? - onBitmapLoaded"+getResources().getDisplayMetrics().density+" " +DensityType.getEnumField(getResources().getDisplayMetrics().density).getDensityValue());
Common.Log.i("? - onBitmapLoaded"+bitmap.getWidth()+" " +bitmap.getHeight()+"\n new height and width "+newWidth+" height "+newHeight);
bitmapImg = Common.getResizedBitmap(bitmap,newWidth,newHeight);
// bitmapImg=bitmap;
bitmapFetched[0] = true;
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
Common.Log.i("? - onBitmapFailed");
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Common.Log.i("? - onPrepareLoad");
}
});
}while (!bitmapFetched[0]);
return bitmapImg;
}
private void setCabDetails(int position, TextView tvCabCapacity, TextView tvSarPerKm, TextView tvMinFare, TextView tvBaseFare, TextView tvPricePerMin)
{
// Type type = broadcastLocationVo.types.get(PHASED_SEEKBAR_DEFAULT_INDEX);
Type type = setCustomerLoc.types.get(position);
tvCabCapacity.setText( type.capacity + " "+Common.getStringResourceText(R.string.people));
// tvSarPerKm.setText( type.pricePerKm + " per KM");
tvSarPerKm.setText("SAR " + type.pricePerKm);
tvMinFare.setText("SAR " + type.minfare);
tvBaseFare.setText("SAR " + type.baseFare);
tvPricePerMin.setText("SAR " + type.pricePerMinute);
}
List<Driver> previousDriversList = new ArrayList<Driver>();
HashMap<Integer,Marker> markersHashMap = new HashMap<Integer,Marker>();
private void refreshCabsData(List<Driver> currentDriversList)
{
Common.Log.i("refreshCabsData - currentDriversList.toString()"+new Gson().toJson(currentDriversList));
Common.Log.i("refreshCabsData - previousDriversList.toString()"+new Gson().toJson(previousDriversList));
Collection<Driver> updateDriversList = CollectionUtils.retainAll(previousDriversList, currentDriversList);
Collection<Driver> deleteDriversList = CollectionUtils.removeAll(previousDriversList, updateDriversList);
Collection<Driver> addDriversList = CollectionUtils.removeAll(currentDriversList, updateDriversList);
Common.Log.i("refreshCabsData - updateDriversList.toString()"+updateDriversList.toString());
Common.Log.i("refreshCabsData - deleteDriversList.toString()"+deleteDriversList.toString());
Common.Log.i("refreshCabsData - addDriversList.toString()"+addDriversList.toString());
previousDriversList.clear();
previousDriversList.addAll(currentDriversList);
minTimeToReach = DEFAULT_MIN_TIME_TO_REACH;
refreshMarkers(Constants.UPDATE,updateDriversList);
refreshMarkers(Constants.DELETE,deleteDriversList);
refreshMarkers(Constants.ADD,addDriversList);
String estimateTimeText = null;
if (sourcePressed)
{
estimateTimeText = minTimeToReach == DEFAULT_MIN_TIME_TO_REACH ? NO_DRIVER : minTimeToReach + "\nMin";
}
else
{
estimateTimeText = "D";
}
tvEstimateTime.setText(estimateTimeText);
/*
if (minTimeToReach == DEFAULT_MIN_TIME_TO_REACH)
{
tvMin.setVisibility(View.GONE);
}
else
{
tvMin.setVisibility(View.VISIBLE);
}
*/
// tvTime.setText(estimateTimeText.replace("\"\\nMin\"",""));
tvTime.setText(estimateTimeText);
}
public void setMinTimeToReach(int reachTime)
{
Common.Log.i("reachTime : "+reachTime);
if(minTimeToReach > reachTime)
{
minTimeToReach = reachTime;
}
Common.Log.i("minTimeToReach : "+minTimeToReach);
}
int minTimeToReach = DEFAULT_MIN_TIME_TO_REACH;
private void refreshMarkers(String operation, Collection<Driver> collection)
{
for (Driver driver:collection)
{
Common.Log.i("driver.typeId : anil "+driver.typeId +" driver "+driver.latitude);
Common.Log.i("cabTypeId : "+cabTypeId+"driver.typeId : "+driver.typeId +" \n"+collection.toString());
if(driver.typeId != cabTypeId)
{
continue;
}
switch (operation)
{
case Constants.UPDATE:
setMinTimeToReach(driver.time);
Log.d("UPDTAE_Markers","1-> "+markersHashMap.toString()+"\n"+markersHashMap.get(driver.driverId)+"\n"+driver.driverId);
Marker markerToUpdate = markersHashMap.get(driver.driverId);
LatLng previousLatLng = markerToUpdate.getPosition();
LatLng currentLatLng = new LatLng(driver.latitude, driver.longitude);
moveMarker(markerToUpdate, previousLatLng, currentLatLng);
Log.d("addMarkers","1-> "+driver.latitude+","+driver.longitude);
break;
case Constants.DELETE:
if (markersHashMap!=null&&markersHashMap.size()!=0) { //all other customer app getting crashed after accepting request to one user
markersHashMap.get(driver.driverId).remove();
markersHashMap.remove(driver.driverId);
}
break;
case Constants.ADD:
setMinTimeToReach(driver.time);
Marker markerToAdd = googleMap.addMarker(new MarkerOptions().position(new LatLng(driver.latitude, driver.longitude)).icon(BitmapDescriptorFactory.fromBitmap( markerBitmapImgs[PHASED_SEEKBAR_DEFAULT_INDEX])));
markersHashMap.put(driver.driverId,markerToAdd);
Log.d("addMarkers","3-> "+driver.latitude+","+driver.longitude);
break;
}
}
}
private void moveMarker(Marker marker, LatLng previousLatLng, LatLng currentLatLng)
{
Location previousLocation = new Location("");
previousLocation.setLatitude(previousLatLng.latitude);
previousLocation.setLongitude(previousLatLng.longitude);
Location currentLocation = new Location("");
currentLocation.setLatitude(currentLatLng.latitude);
currentLocation.setLongitude(currentLatLng.longitude);
float rotationValue = previousLocation.bearingTo(currentLocation);
if (previousLocation.distanceTo(currentLocation)>10) {
rotateMarker(marker, rotationValue);
animateMarker(googleMap, marker, currentLatLng, false);
}
}
@Override
public void onInternetConnected()
{
// Common.customToast(this, "GMDA - Internet Connected.");
super.onInternetConnected();
Common.Log.i("Inside GMDA - Internet Connected.");
sendSocketRequestToSetCustomerLocationService();
}
@Override
public void onInternetDisconnected()
{
super.onInternetDisconnected();
// Common.customToast(this, "GMDA - " + Constants.NO_INTERNET_CONNECTION_MESSAGE);
Common.Log.i("Inside GMDA - "+Constants.NO_INTERNET_CONNECTION_MESSAGE);
resetCabsData();
}
private void resetCabsData()
{
googleMap.clear();
previousDriversList.clear();
tvEstimateTime.setText(NO_DRIVER);
if (sourcePressed)
{
tvTime.setText(NO_DRIVER);
}
// tvMin.setVisibility(View.GONE);
}
@Override
public void onResponseSuccess(ApiResponseVo apiResponseVo, HashMap<String, String> requestParams, int requestId)
{
if (apiResponseVo.code != Constants.SUCCESS)
{
switch (apiResponseVo.requestname)
{
case ServiceUrls.RequestNames.CHECK_PROMO_VALIDITY:
switch (apiResponseVo.code)
{
case Constants._201 :
Common.customToast(this, Common.getStringResourceText(R.string.promo_code_already_used));
break;
case Constants._202 :
Common.customToast(this, Common.getStringResourceText(R.string.invalid_promo_code));
break;
}
break;
default:
// Common.customToast(this, apiResponseVo.status);
break;
}
return;
}
switch (apiResponseVo.requestname)
{
case ServiceUrls.RequestNames.GET_CUSTOMER_PROFILE:
GetCustomerProfileVo getCustomerProfileVo = Common.getSpecificDataObject(apiResponseVo.data, GetCustomerProfileVo.class);
username.setText(getCustomerProfileVo.firstName);
userlname.setText(getCustomerProfileVo.lastName);
Common.setCircleImageBackgroundFromUrl(GoogleMapDrawerActivity.this,profilepic,getCustomerProfileVo.profilePic);
// HashMap<String, String> params = new HashMap<>();
// params.put(ServiceUrls.RequestParams.TOKEN,Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.REG_ID,null));
// params.put(ServiceUrls.RequestParams.DEVICE_ID,Common.getDeviceId(this));
// params.put(ServiceUrls.RequestParams.DEVICE,Constants.ANDROID);
//
// new RetrofitRequester(this).sendStringRequest(ServiceUrls.RequestNames.UPDATE_DEVICE_TOKEN,params);
//if (getCustomerProfileVo.profilePic!=null&&getCustomerProfileVo.profilePic.length()>0)
setNotificationIconCountText(getCustomerProfileVo.unreadNotificationsCount);
new RetrofitRequester(this).sendStringRequest(ServiceUrls.RequestNames.GET_SAVED_LOCATIONS,null);
break;
case ServiceUrls.RequestNames.GET_LOYALITY_POINT:
GetLoyalityPointVo getLoyalityPointVo = Common.getSpecificDataObject(apiResponseVo.data, GetLoyalityPointVo.class);
creditpoints.setText(String.valueOf(getLoyalityPointVo.points));
switch (getLoyalityPointVo.loyality)
{
case Constants.LoyalityTypes.BRONZE:
loyaltiicon.setBackgroundResource(R.drawable.loyalty_bronz);
break;
case Constants.LoyalityTypes.SILVER:
loyaltiicon.setBackgroundResource(R.drawable.loyalty_silver);
break;
case Constants.LoyalityTypes.GOLD:
loyaltiicon.setBackgroundResource(R.drawable.loyalty_gold);
break;
case Constants.LoyalityTypes.DIAMOND:
loyaltiicon.setBackgroundResource(R.drawable.loyalty_diamond);
break;
case Constants.LoyalityTypes.LOYALTY_ZERO:
loyaltiicon.setBackgroundResource(R.drawable.ic_launcher);
break;
}
case ServiceUrls.RequestNames.ACCOUNTS_CUSTOMER:
// AccountsCustomerVo accountsCustomerVo = Common.getSpecificDataObject(apiResponseVo.data, AccountsCustomerVo.class);
accountsCustomerVo = Common.getSpecificDataObject(apiResponseVo.data, AccountsCustomerVo.class);
setPaymentTypeId(accountsCustomerVo.paymentTypeId);
switch (requestId)
{
case R.id.order_button:
orderButtonAccountsCustomerApiResponseFunctionality(accountsCustomerVo);
break;
case R.id.online:
Common.Log.i("? - accountsCustomerVo.cards.size() : "+ accountsCustomerVo.cards.size());
if(accountsCustomerVo.cards.size()!= 0)
{
if (accountsCustomerVo.credits>=0)
{
callUpdatePaymetAPI(String.valueOf(PaymentType.CREDIT_CARD.getId()));
}
else
{
Common.customToast(this,Common.getStringResourceText(R.string.as_of_now_this_feature_is_not_available));
// Common.showNegativeTatxBalanceErrorDialog(GoogleMapDrawerActivity.this,String.valueOf(accountsCustomerVo.credits));
}
}
else
{
showAddCreditCardConfirmationDialog(Common.getStringResourceText(R.string.no_cards_were_added), Common.getStringResourceText(R.string.please_add_card_to_process_do_you_want_to_add_credit_card), AccountActivity.class);
}
selectPaymentTypeDialog.cancel();
break;
case R.id.credits:
if(accountsCustomerVo.credits > 1)
{
callUpdatePaymetAPI(String.valueOf(PaymentType.TATX_BALANCE.getId()));
}
else
{
showAddCreditCardConfirmationDialog(Common.getStringResourceText(R.string.insufficient_tatx_balance), Common.getStringResourceText(R.string.please_add_tatx_balance_to_process_do_you_want_to_add_tatx_balance), AccountActivity.class);
}
selectPaymentTypeDialog.cancel();
break;
}
break;
case ServiceUrls.RequestNames.UPDATE_PAYMENT_TYPE:
UpdatePaymentTypeVo updatePaymentTypeVo = Common.getSpecificDataObject(apiResponseVo.data, UpdatePaymentTypeVo.class);
String paymentType = updatePaymentTypeVo.payment;
setPaymentTypeId(Integer.parseInt(paymentType));
Common.Log.i("Common.getPaymentTypeById(Integer.parseInt(paymentType)).name() : "+Common.getPaymentTypeById(Integer.parseInt(paymentType)).name());
btncash.setText(Common.getPaymentTypeById(Integer.parseInt(paymentType)).getString());
editor.putInt(ServiceUrls.RequestParams.PAYMENT_TYPE, Integer.parseInt(paymentType));
editor.commit();
Drawable [] img={getResources().getDrawable(R.drawable.card), getResources().getDrawable(R.drawable.logo), getResources().getDrawable(R.drawable.cash)};
switch (Integer.parseInt(paymentType))
{
case 2:
img[0].setBounds(0, 0, 90, 50);
btncash.setCompoundDrawables(img[0], null, null, null);
btncash.setText(Common.getStringResourceText(R.string.credit_card));
break;
case 3:
btncash.setText(getResources().getString(R.string.my_balance));
img[1].setBounds(0, 0, 50, 50);
btncash.setCompoundDrawables(img[1], null, null, null);
break;
default:
btncash.setText(Common.getStringResourceText(R.string.cash));
img[2].setBounds(0, 0, 90, 50);
btncash.setCompoundDrawables(img[2], null, null, null);
break;
}
break;
case ServiceUrls.RequestNames.USER_LOGOUT:
UserLogoutVo userLogoutVo = Common.getSpecificDataObject(apiResponseVo.data, UserLogoutVo.class);
Common.getDefaultSP(this).edit().putBoolean(Constants.SharedPreferencesKeys.LOGIN_STATUS, false).commit();
Common.getDefaultSP(this).edit().putInt(Constants.SharedPreferencesKeys.USERID, 0).commit();
//Common.getDefaultSP(this).edit().putString(Constants.SharedPreferencesKeys.REG_ID, "").commit();
Common.Log.i("Language Goo"+Locale.getDefault().getLanguage());
Common.customToast(this, userLogoutVo.status);
startActivity(new Intent(this,SplashScreen.class));
finish();
break;
case ServiceUrls.RequestNames.GET_FARE:
GetFareVo getFareVo = Common.getSpecificDataObject(apiResponseVo.data, GetFareVo.class);
Intent intent = new Intent(this, FareEstimateActivity.class);
intent.putExtra(Constants.KEY_1,getFareVo);
intent.putExtra(Constants.IntentKeys.SOURCE_ADDRESS,tvSourceSelected.getText().toString());
intent.putExtra(Constants.IntentKeys.DESTINATION_ADDRESS,tvDestinationSelected.getText().toString());
startActivity(intent);
break;
case ServiceUrls.RequestNames.UPDATE_DEVICE_TOKEN:
UpdateDeviceTokenVo updateDeviceTokenVo = Common.getSpecificDataObject(apiResponseVo.data,UpdateDeviceTokenVo.class);
Common.Log.i("updateDeviceTokenVo.message : "+updateDeviceTokenVo.message);
break;
/*
case ServiceUrls.RequestNames.CHECK_PROMO_VALIDITY:
// Common.customToast(this, apiResponseVo.status);
Common.customToast(this, Common.getStringResourceText(R.string.promo_code_validated_successfully));
break;
*/
case ServiceUrls.RequestNames.CHECK_PROMO_VALIDITY:
Common.customToast(this, apiResponseVo.status);
PromoValidityVo promoValidityVo = Common.getSpecificDataObject(apiResponseVo.data,PromoValidityVo.class);
btnPromoCode.setText(promoValidityVo.promoCode);
break;
case ServiceUrls.RequestNames.GET_SAVED_LOCATIONS:
getSavedLocationVo = Common.getSpecificDataObject(apiResponseVo.data, GetSavedLocationVo.class);
Common.Log.i("updateDeviceTokenVo.message : " + getSavedLocationVo.toString());
favLocationArrayList.addAll(getSavedLocationVo.favLocations);
for (RecentLocation recent:getSavedLocationVo.recentLocations){
FavLocation favLocation=new FavLocation();
favLocation.latitude=recent.pickLatitude;
favLocation.longitude=recent.pickLongitude;
favLocation.name=recent.pickupLocation;
favLocationArrayList.add(favLocation);
}
break;
case ServiceUrls.RequestNames.GET_COUNTRY_WISE_AIRPORT_DETAILS:
airportByCountryVo = Common.getSpecificDataObject(apiResponseVo.data, AirportByCountryVo.class);
//airPortFunctionality();
break;
}
}
private void orderButtonAccountsCustomerApiResponseFunctionality(final AccountsCustomerVo accountsCustomerVo) {
if (accountsCustomerVo.credits < 0) {
customerAlertDialog = new CustomerAlertDialog(this, "Your TATX balance is due " + accountsCustomerVo.currencyCode + " " + accountsCustomerVo.credits + "\n" + "to process further orders.", new DialogClickListener() {
@Override
public void onCancelClick() {
customerAlertDialog.dismiss();
}
@Override
public void onOkClick() {
if (accountsCustomerVo.cards.size() == 0) {
// Common.setPreviousActivity(GoogleMapDrawerActivity.this);
// startActivity(new Intent(GoogleMapDrawerActivity.this,AddCreditCardActivity.class));
} else {
// Common.setPreviousActivity(GoogleMapDrawerActivity.this);
// startActivity(new Intent(GoogleMapDrawerActivity.this,AddCreditBalanceActivity.class));
}
customerAlertDialog.dismiss();
}
});
customerAlertDialog.setCancelable(false);
customerAlertDialog.show();
confirmationLayout(false);
return;
}
Drawable[] img = {getResources().getDrawable(R.drawable.card), getResources().getDrawable(R.drawable.logo), getResources().getDrawable(R.drawable.cash)};
if ((accountsCustomerVo.paymentTypeId == PaymentType.CREDIT_CARD.getId() && accountsCustomerVo.cards.size() == 0) || (accountsCustomerVo.paymentTypeId == PaymentType.TATX_BALANCE.getId() && accountsCustomerVo.credits < 1) || (accountsCustomerVo.credits < 0 && accountsCustomerVo.paymentTypeId != PaymentType.CASH.getId())) {
// paymentId = PaymentType.CASH.getId();
callUpdatePaymetAPI(String.valueOf(PaymentType.CASH.getId()));
return;
}
switch (accountsCustomerVo.paymentTypeId) {
case 2:
img[0].setBounds(0, 0, 90, 50);
btncash.setCompoundDrawables(img[0], null, null, null);
btncash.setText(Common.getStringResourceText(R.string.credit_card));
break;
case 3:
btncash.setText(getResources().getString(R.string.my_balance));
img[1].setBounds(0, 0, 50, 50);
btncash.setCompoundDrawables(img[1], null, null, null);
break;
default:
btncash.setText(Common.getStringResourceText(R.string.cash));
img[2].setBounds(0, 0, 90, 50);
btncash.setCompoundDrawables(img[2], null, null, null);
break;
}
confirmValue = true;
// confirmationLayout(true);
Common.showContentView(this, true);
}
private void callUpdatePaymetAPI(String paymentType)
{
HashMap<String, String> params = new HashMap<String, String>();
params.put(ServiceUrls.RequestParams.PAYMENT_TYPE, paymentType);
new RetrofitRequester(GoogleMapDrawerActivity.this).sendStringRequest(ServiceUrls.RequestNames.UPDATE_PAYMENT_TYPE,params);
}
private void showAddCreditCardConfirmationDialog(String titleText, String messageText, final Class<?> activityToStart)
{
AlertDialog.Builder builder = new AlertDialog.Builder(GoogleMapDrawerActivity.this);
// builder.setTitle("No Cards were Added");
builder.setTitle(titleText);
// builder.setMessage("Please Add Card to process.\n\nDo You Want to Add Credit Card ?");
builder.setMessage(messageText);
builder.setPositiveButton(Common.getStringResourceText(R.string.yes), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// startActivity(new Intent(AccountActivity.this,AddCreditCardActivity.class));
startActivity(new Intent(GoogleMapDrawerActivity.this,activityToStart));
onBackPressed();
}
});
builder.setNegativeButton(Common.getStringResourceText(R.string.no), new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
builder.create().show();
}
// To animate view slide out from top to bottom
public void slideToBottom(View view){
TranslateAnimation animate = new TranslateAnimation(0,0,0,view.getHeight());
animate.setDuration(500);
animate.setFillAfter(false);
view.startAnimation(animate);
view.setVisibility(View.GONE);
}
// To animate view slide out from bottom to top
public void slideToTop(View view,int height){
Log.d("slidertop",String.valueOf(height));
TranslateAnimation animate = new TranslateAnimation(0,0,0,-height);
animate.setDuration(500);
animate.setFillAfter(false);
view.startAnimation(animate);
view.setVisibility(View.VISIBLE);
Log.d("slidertop",String.valueOf(height));
}
public static void animateViewFromBottomToTop(final View view){
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
final int TRANSLATION_Y = view.getHeight();
view.setTranslationY(TRANSLATION_Y);
view.setVisibility(View.GONE);
view.setVisibility(View.GONE);
view.animate()
.translationYBy(-TRANSLATION_Y)
.setDuration(100)
.setStartDelay(10)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(final Animator animation) {
view.setVisibility(View.VISIBLE);
}
})
.start();
}
});
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()){
case R.id.clear_source:
tvSourceSelected.setText("");
// mRecyclerView.setAdapter(null);
//suggetionSetAdapter(0);
Log.d("suggetionSetAdapter", "suggetionSetAdapter 3486");
//
removeSourceMapMarker();
//
break;
case R.id.clear_destination:
tvDestinationSelected.setText("");
//suggetionSetAdapter(0);
Log.d("suggetionSetAdapter", "suggetionSetAdapter 3491");
destinationLatLngSelected = null;
//
removeDestinationMapMarker();
//
break;
}
return false;
}
private void removeSourceMapMarker()
{
if (sourceMapMarker != null)
{
sourceMapMarker.remove();
}
}
private void removeDestinationMapMarker()
{
if (destinationMapMarker != null)
{
destinationMapMarker.remove();
}
}
public void selectDestinationByMapMove(CameraPosition cameraPosition) {
destinationLatLngSelected=new LatLng(cameraPosition.target.latitude,cameraPosition.target.longitude);
addressDestination = Common.getCompleteAddressString(GoogleMapDrawerActivity.this, destinationLatLngSelected.latitude, destinationLatLngSelected.longitude).getCompleteAddress();
tvDestinationSelected.setText(addressDestination);
addDestinationMapMarker();
// tvDestinationSelected.performCompletion();
}
private void setViewsVisibilityStatus(int status, View... views)
{
Common.Log.i("views.length : "+views.length);
for (View view : views)
{
view.setVisibility(status);
}
}
private void logUser()
{
Common.Log.i("? - String.valueOf(Common.getUserIdFromSP(this)) : "+String.valueOf(Common.getUserIdFromSP(this)));
Crashlytics.setUserIdentifier(String.valueOf(Common.getUserIdFromSP(this)));
Common.Log.i("? - Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.EMAIL_ID,\"\") : "+Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.EMAIL_ID,""));
Crashlytics.setUserEmail(Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.EMAIL_ID,""));
Common.Log.i("? - Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.FIRST_NAME,\"\") : "+Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.FIRST_NAME,""));
Common.Log.i("? - Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.LAST_NAME,\"\") : "+Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.LAST_NAME,""));
Crashlytics.setUserName(Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.FIRST_NAME,"")+" "+Common.getDefaultSP(this).getString(Constants.SharedPreferencesKeys.LAST_NAME,""));
Common.Log.i("? - Common.getDeviceId(this) : "+Common.getDeviceId(this));
Crashlytics.setString(ServiceUrls.RequestParams.DEVICE_ID,Common.getDeviceId(this));
}
public int getPaymentTypeId() {
return paymentTypeId;
}
public void setPaymentTypeId(int paymentTypeId) {
this.paymentTypeId = paymentTypeId;
}
public static GoogleMapDrawerActivity getInstatnce() {
return instance;
}
@Override
public void onUnReadNotificationCountChage(int count)
{
setNotificationIconCountText(count);
}
public void mRecyclerViewSourceClickListner(LatLng latLng) {
latitude = latLng.latitude;
longitude = latLng.longitude;
// suggetionOnBackPressed();
GeoDetails geoDetails = Common.getCompleteAddressString(GoogleMapDrawerActivity.this, latLng.latitude, latLng.longitude);
Log.d("geoDetails",geoDetails.toString()+latitude+" ,"+longitude+" OR "+latLng.latitude+" "+ latLng.longitude);
sourceAddress =geoDetails.getAddress();
// tvSourceSelected.setText(place.getAddress().toString());
addSourceMapMarker();
llSuggtionView.setVisibility(View.GONE);
zoomCamera(latLng.latitude, latLng.longitude);
sendSocketRequestToSetCustomerLocationService();
}
public void mRecyclerViewDestinationClickListner(LatLng latLng) {
destinationLatLngSelected = latLng;
//tvDestinationSelected.setText(place.getAddress().toString());
llSuggtionViewDestination.setVisibility(View.GONE);
addDestinationMapMarker();
//suggetionOnBackPressed();
zoomCamera(destinationLatLngSelected.latitude, destinationLatLngSelected.longitude);
}
public class MyBroadcastReceiver extends BroadcastReceiver {
int code=0;
@Override
public void onReceive(Context context, Intent intent) {
Common.Log.i("intent.getStringExtra(\"from\") : "+intent.getStringExtra("from"));
Bundle bundle=intent.getExtras();
FavLocation favLocation = (FavLocation) bundle.getSerializable(Constants.FAVOURITE_LOCATION);
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(favLocation.latitude, favLocation.longitude));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(Constants.ZOOM_LEVEL);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
selectDestinationByMapMove(googleMap.getCameraPosition());
}
}
private void applyFontToMenuItem(MenuItem mi) {
Typeface font = Typeface.createFromAsset(getAssets(), Constants.CUSTOM_FONT_PATH);
SpannableString mNewTitle = new SpannableString(mi.getTitle());
mNewTitle.setSpan(new CustomTypefaceSpan("" , font), 0 , mNewTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
mi.setTitle(mNewTitle);
}
@OnClick(R.id.btn_promo_code)
void usePromoCode()
{
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.add_promo_manually);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog.show();
dialog.getWindow().setAttributes(lp);
final EditText cetEnterPromoCode = (EditText) dialog.findViewById(R.id.cet_enter_promo_code);
TextView tvValidateButton = (TextView) dialog.findViewById(R.id.tv_validate_button);
TextView tvCancelButton = (TextView) dialog.findViewById(R.id.tv_cancel_button);
final RelativeLayout removePromo = (RelativeLayout) dialog.findViewById(R.id.clear_source);
if (!btnPromoCode.getText().toString().equalsIgnoreCase(Common.getStringResourceText(R.string.add_promo_code)))
{
cetEnterPromoCode.setText(btnPromoCode.getText().toString());
//removePromo.setVisibility(View.VISIBLE);
}
tvValidateButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (cetEnterPromoCode.getText().toString().trim().length()<1){
btnPromoCode.setText(Common.getStringResourceText(R.string.add_promo_code));
dialog.dismiss();
return;
}
Common.hideSoftKeyboardFromDialog(dialog,GoogleMapDrawerActivity.this);
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put(ServiceUrls.RequestParams.PCODE,cetEnterPromoCode.getText().toString().trim());
new RetrofitRequester(GoogleMapDrawerActivity.this).sendStringRequest(ServiceUrls.RequestNames.CHECK_PROMO_VALIDITY,hashMap);
dialog.dismiss();
}
});
tvCancelButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
dialog.dismiss();
}
});
removePromo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cetEnterPromoCode.setText("");
dialog.dismiss();
btnPromoCode.setText(Common.getStringResourceText(R.string.add_promo_code));
}
});
}
private void showOfferDialog(String offerImg)
{
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.offer_popup_home);
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
ImageView offerImage=(ImageView) dialog.findViewById(R.id.offer_image);
ImageView cancel=(ImageView) dialog.findViewById(R.id.cancel);
Picasso.with(this).load(offerImg).into(offerImage);
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel();
}
});
dialog.show();
}
private void showAirportDialog(String city,String sourceName)
{
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.airport_popup);
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
TextView tvSourceSelected=(TextView) dialog.findViewById(R.id.tv_source_selected);
TextView welcome=(TextView) dialog.findViewById(R.id.welcome);
final RelativeLayout rootLayout = (RelativeLayout)dialog.findViewById(R.id.root_layout);
tvSourceSelected.setText(sourceName);
welcome.setText(city);
rootLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
dialog.dismiss();
return true;
}
});
dialog.show();
}
private void allAirportDataApiCall(String countryName){
HashMap<String, String> params = new HashMap();
params.put(ServiceUrls.RequestParams.COUNTRY_NAME, countryName);
new RetrofitRequester(this).sendStringRequest(ServiceUrls.RequestNames.GET_COUNTRY_WISE_AIRPORT_DETAILS, params);
}
private void airPortFunctionality(){
GeoDetails geoDetails=new GeoDetails(null,null,null,null);
airPortFunctionality(geoDetails);
}
private void airPortFunctionality(GeoDetails geoDetails){
boolean inAirPortBoundary = false;
if (countryNameGeo==null&&geoDetails.getCountry()!=null) {
countryNameGeo = geoDetails.getCountry();
allAirportDataApiCall(geoDetails.getCountry());
}
if (!countryNameGeo.equalsIgnoreCase(geoDetails.getCountry())){
allAirportDataApiCall(geoDetails.getCountry());
}
if (airportByCountryVo != null && airportByCountryVo.airportDetails.size() > 0) {
for (AirportDetail airportDetail : airportByCountryVo.airportDetails) {
if (airportDetail.latNE==0.0|| airportDetail.lngNE==0.0 || airportDetail.latSW==0.0 || airportDetail.lngSW==0.0) {
continue;
}
LatLngBounds sourceLatLngBounds = new LatLngBounds(new LatLng(airportDetail.latSW, airportDetail.lngSW), new LatLng(airportDetail.latNE, airportDetail.lngNE));
inAirPortBoundary = sourceLatLngBounds.contains(new LatLng(latitude,longitude));
Location location=new Location("");
location.setLatitude(latitude);
location.setLongitude(longitude);
Location location1=new Location("");
location1.setLatitude(airportDetail.lat);
location1.setLongitude(airportDetail.lng);
float radius = location.distanceTo(location1);
Log.d("airport","airport 0 "+ inAirPortBoundary+"\n previousLat" +previousLat+"\n previousLng "+previousLng+"\n airportDetail.lat "+airportDetail.lat+"\n airportDetail.lng "+airportDetail.lng);
if (inAirPortBoundary || Math.abs(radius)<300) {
Log.d("airport","airport 1 "+ inAirPortBoundary+"\n previousLat" +previousLat+"\n previousLng "+previousLng+"\n airportDetail.lat "+airportDetail.lat+"\n airportDetail.lng "+airportDetail.lng);
// if ((airportDetail.lat!=previousLat&& airportDetail.lng!=previousLng) || (previousLat==0.0&&previousLng==0.0)) {
Log.d("airport","airport 2 "+ inAirPortBoundary+"\n previousLat" +previousLat+"\n previousLng "+previousLng+"\n airportDetail.lat "+airportDetail.lat+"\n airportDetail.lng "+airportDetail.lng);
// previousLat=airportDetail.lat;
// previousLng=airportDetail.lng;
// GeoDetails addresses = Common.getCompleteAddressString(this, airportDetail.lat, airportDetail.lng);
showAirportDialog("Welcome to "+airportDetail.city,airportDetail.name);
// Log.d("addresses",addresses.getCityName());
isAirPortBoundary=true;
Log.d("airport","airport 3 "+ inAirPortBoundary+"\n previousLat" +previousLat+"\n previousLng "+previousLng+"\n airportDetail.lat "+airportDetail.lat+"\n airportDetail.lng "+airportDetail.lng);
// }
break;
}
}
if (!inAirPortBoundary){
previousLat=0.0;
previousLng=0.0;
isAirPortBoundary=false;
}
}
}
private void updateCameraBearing(GoogleMap googleMap, float bearing)
{
Common.Log.i("? - googleMap : "+googleMap+" bearing "+bearing);
if (googleMap == null) return;
CameraPosition camPos = CameraPosition.builder(googleMap.getCameraPosition() /*Current Camera*/).bearing(bearing).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(camPos));
}
private void sendNotification(String msg) {
Intent resultIntent = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
resultIntent.putExtra("msg", msg);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,resultIntent,PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder mNotifyBuilder;
NotificationManager mNotificationManager;
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Tatx")
.setContentText(msg)
.setSmallIcon(R.drawable.ic_untitled_1);
// Set pending intent
// mNotifyBuilder.setContentIntent(resultPendingIntent);
// Set Vibrate, Sound and Light
int defaults = 0;
defaults = defaults | Notification.DEFAULT_LIGHTS;
defaults = defaults | Notification.DEFAULT_VIBRATE;
defaults = defaults | Notification.DEFAULT_SOUND;
mNotifyBuilder.setDefaults(defaults);
// Set autocancel
mNotifyBuilder.setAutoCancel(true);
// Post a notification
mNotificationManager.notify(notifyID, mNotifyBuilder.build());
}
@OnClick(R.id.tv_normal) void setMapViewNormal(){
tvNormal.setBackgroundResource(R.drawable.button_bg_red_zero_radius);
tvSatellite.setBackgroundResource(R.drawable.white_view);
tvNormal.setTextColor(getResources().getColor(R.color.white));
tvSatellite.setTextColor(getResources().getColor(R.color.primary_text));
if (googleMap!=null) {
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
}
@OnClick(R.id.tv_satellite) void setMapViewSatellite(){
tvNormal.setBackgroundResource(R.drawable.white_view);
tvSatellite.setBackgroundResource(R.drawable.button_bg_red_zero_radius);
tvNormal.setTextColor(getResources().getColor(R.color.primary_text));
tvSatellite.setTextColor(getResources().getColor(R.color.white));
if (googleMap!=null) {
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
}
}
| 35.849104
| 527
| 0.622763
|
ec806c8b9253538930043f2afa2a5d731dd4845f
| 2,657
|
package es.tid.pce.client.tester;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Inet4Address;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import es.tid.pce.client.emulator.AutomaticTesterStatistics;
import es.tid.pce.pcep.messages.PCEPRequest;
import es.tid.pce.pcep.messages.PCEPTELinkTearDownSuggestion;
import es.tid.pce.pcep.objects.EndPointsIPv4;
public class RealiseMLCapacityTask extends TimerTask {
private Logger log;
private ArrayList<String> sourceList;
private ArrayList<String> destinationList;
private AutomaticTesterStatistics stats;
/*Variable used for counter how many requests there are*/
PCEPRequest request;
public RealiseMLCapacityTask(ArrayList<String> sourceList, ArrayList<String> destinationList,AutomaticTesterStatistics stats ){
log=LoggerFactory.getLogger("PCCClient");
this.sourceList = sourceList;
this.destinationList=destinationList;
this.stats=stats;
}
@Override
public void run() {
log.info("Deleting LSP, releasing capacity");
if (stats != null){
stats.releaseNumberActiveLSP();
}
String s1;
EndPointsIPv4 endPointsIPv4 = new EndPointsIPv4();
for (int i =0; i<sourceList.size();i++){
PCEPTELinkTearDownSuggestion telinkTD = new PCEPTELinkTearDownSuggestion();
try {
endPointsIPv4.setSourceIP((Inet4Address)Inet4Address.getByName(sourceList.get(i)));
endPointsIPv4.setDestIP((Inet4Address)Inet4Address.getByName(destinationList.get(i)));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
telinkTD.setEndPoints(endPointsIPv4);
// s1 = releaseCapacity(sourceList.get(i), destinationList.get(i),String.valueOf(1));
// System.out.println(s1);
// sendUpdate("172.16.3.1", 4190, s1);
}
}//End run
public static void sendUpdate(String address, int port, String update) {
try {
Socket socket = new Socket(address, port);
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bufferedWriter.write(update);
bufferedWriter.flush();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String releaseCapacity(String sourceVector, String destVector, String bw) {
String s = "RELEASE:";
s += sourceVector + ":" + destVector + ":" + bw;
return s;
}
}
| 31.258824
| 128
| 0.728641
|
9caaddddd92c8eeb13b1455b8906d28e9f968b3a
| 8,695
|
package org.mafagafogigante.labyrint.util;
import org.mafagafogigante.labyrint.game.Name;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
/**
* A collection of Selectable objects that listMatches a given query.
*/
public class Matches<T extends Selectable> {
private final List<T> matches = new ArrayList<>();
private final boolean disjoint;
private int differentNames = 0;
private boolean differentNamesUpToDate = true;
private Matches(boolean disjoint) {
this.disjoint = disjoint;
}
/**
* Converts a Collection to Matches.
*/
public static <T extends Selectable> Matches<T> fromCollection(Collection<T> collection) {
return fromCollection(collection, true);
}
/**
* Converts a Collection to possibly not disjoint Matches.
*/
private static <T extends Selectable> Matches<T> fromCollection(Collection<T> collection, boolean disjoint) {
Matches<T> newInstance = new Matches<>(disjoint);
for (T t : collection) {
newInstance.addMatch(t);
}
return newInstance;
}
/**
* Finds the best matches to the provided tokens among the {@code Selectable}s of a specified {@code Collection}.
*
* @param collection a {@code Collection} of {@code Selectable} objects
* @param tokens the search Strings
* @param <T> a type T that extends {@code Selectable}
* @return a {@code Matches} object with zero or more elements of type T
*/
public static <T extends Selectable> Matches<T> findBestMatches(Collection<T> collection, String... tokens) {
return findMatches(collection, tokens, false);
}
/**
* Finds the best complete matches to the provided tokens among the {@code Selectable}s of a specified {@code
* Collection}. A listMatches is considered complete if it has a word for each provided token.
*
* <p>This is the method that should be used to select objects of the class {@code Entity}, as, for instance, {@code
* "Fruit Bat"} should never listMatches a {@code "Bat"}.
*
* @param <T> a type T that extends {@code Selectable}
* @param elements a {@code Collection} of {@code Selectable} elements
* @param tokens the search Strings
* @return a {@code Matches} object with zero or more elements of type T
*/
public static <T extends Selectable> Matches<T> findBestCompleteMatches(Collection<T> elements, String... tokens) {
return findMatches(elements, tokens, true);
}
private static double calculateSimilarity(String[] nameWords, String[] tokens, boolean full) {
if (!full || nameWords.length >= tokens.length) {
int matches = countMatches(tokens, nameWords);
SummaryStatistics statistics = new SummaryStatistics();
statistics.addValue(matches / (double) nameWords.length);
statistics.addValue(matches / (double) tokens.length);
return statistics.getMean();
} else {
return 0.0;
}
}
private static double calculateSingularSimilarity(Name name, String[] tokens, boolean full) {
return calculateSimilarity(StringUtils.split(name.getSingular()), tokens, full);
}
private static double calculatePluralSimilarity(Name name, String[] tokens, boolean full) {
return calculateSimilarity(StringUtils.split(name.getPlural()), tokens, full);
}
private static MatchResult evaluateMatch(Name name, int frequency, String[] tokens, boolean full) {
double singularSimilarity = calculateSingularSimilarity(name, tokens, full);
if (frequency < 2) {
return new MatchResult(singularSimilarity, false);
}
double pluralSimilarity = calculatePluralSimilarity(name, tokens, full);
if (DungeonMath.fuzzyCompare(singularSimilarity, pluralSimilarity) >= 0) {
// Disjoint matches are preferred.
return new MatchResult(singularSimilarity, true);
} else {
return new MatchResult(pluralSimilarity, false);
}
}
/**
* Finds matches of {@code Selectable}s based on a given {@code Collection} of objects and an array of search tokens.
*
* @param <T> a type T that extends {@code Selectable}
* @param elements a {@code Collection} of {@code Selectable} elements
* @param tokens the search Strings
* @param full if true, only elements that match all tokens are returned
* @return a {@code Matches} object with zero or more elements of type T
*/
private static <T extends Selectable> Matches<T> findMatches(Collection<T> elements, String[] tokens, boolean full) {
List<T> list = new ArrayList<>();
double maximumSimilarity = 0.0;
boolean disjoint = true;
CounterMap<Name> nameCounters = new CounterMap<>();
for (T element : elements) {
nameCounters.incrementCounter(element.getName());
}
for (T element : elements) {
Name name = element.getName();
MatchResult result = evaluateMatch(name, nameCounters.getCounter(name), tokens, full);
if (DungeonMath.fuzzyCompare(result.similarity, 0.0) > 0) {
boolean isBetter = DungeonMath.fuzzyCompare(result.similarity, maximumSimilarity) > 0;
boolean isAsGood = DungeonMath.fuzzyCompare(result.similarity, maximumSimilarity) == 0;
if (isBetter) {
maximumSimilarity = result.similarity;
disjoint = result.disjoint;
list.clear();
list.add(element);
} else if (isAsGood) {
if (disjoint == result.disjoint) {
list.add(element);
} else if (result.disjoint) {
// Disjoint matches are preferred.
// Discard the current non-disjoint matches in favor of the disjoint ones.
disjoint = true;
list.clear();
list.add(element);
}
}
}
}
return fromCollection(list, disjoint);
}
/**
* Counts how many Strings in the entry array start with the Strings of the query array.
*/
private static int countMatches(String[] query, String[] entry) {
int matches = 0;
int indexOfLastMatchPlusOne = 0;
for (int i = 0; i < query.length && indexOfLastMatchPlusOne < entry.length; i++) {
for (int j = indexOfLastMatchPlusOne; j < entry.length; j++) {
if (StringUtils.startsWithIgnoreCase(entry[j], query[i])) {
indexOfLastMatchPlusOne = j + 1;
matches++;
}
}
}
return matches;
}
/**
* Returns whether or not the Matches are disjoint.
*
* <p>If they are, any element constitutes a listMatches, otherwise, only all elements together constitute a
* listMatches.
*/
public boolean isDisjoint() {
return disjoint;
}
private void addMatch(T match) {
matches.add(match);
differentNamesUpToDate = false;
}
public T getMatch(int index) {
return matches.get(index);
}
public List<T> toList() {
return new ArrayList<>(matches);
}
/**
* Returns true if there is a listMatches with the given name, false otherwise.
*
* @param name the name used for comparison
* @return true if there is a listMatches with the given name, false otherwise
*/
public boolean hasMatchWithName(Name name) {
for (T match : matches) {
if (match.getName().equals(name)) {
return true;
}
}
return false;
}
/**
* Returns the number of matches.
*/
public int size() {
return matches.size();
}
/**
* Returns how many different names the matches have. For instance, if the matches consist of two Entity objects with
* identical names, this method will return 1.
*
* <p>This method will calculate how many different names are in the list of matches or use the last calculated value,
* if the matches list did not change since the last calculation. Therefore, after adding all matches and calling this
* method once, subsequent method calls should be substantially faster.
*/
public int getDifferentNames() {
if (!differentNamesUpToDate) {
updateDifferentNamesCount();
}
return differentNames;
}
/**
* Updates the differentNames variable after iterating over the list of matches.
*/
private void updateDifferentNamesCount() {
HashSet<Name> uniqueNames = new HashSet<>();
for (T match : matches) {
uniqueNames.add(match.getName());
}
differentNames = uniqueNames.size();
differentNamesUpToDate = true;
}
private static class MatchResult {
private final double similarity;
private final boolean disjoint;
private MatchResult(double similarity, boolean disjoint) {
this.similarity = similarity;
this.disjoint = disjoint;
}
}
}
| 34.641434
| 120
| 0.681196
|
331e8b6b895a86d22b766807ef31edc76fc22a3b
| 250
|
package se.kth.castor.user;
import se.kth.castor.types.ImplInter;
public class ImplInterSimpleCall3 {
ImplInter var1 = se.kth.castor.types.Helper.publicImplInter();
public void m() {
se.kth.castor.types.Concrete var2 = var1.getConcrete();
}
}
| 22.727273
| 63
| 0.752
|
593570028ca8eb3368f0416343ef052c59bd9d46
| 4,940
|
/*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.alibaba.polardbx.executor.mdl;
import com.alibaba.polardbx.common.model.lifecycle.AbstractLifecycle;
import com.alibaba.polardbx.executor.mdl.context.MdlContextStamped;
import com.alibaba.polardbx.executor.mdl.context.PreemptiveMdlContextStamped;
import com.alibaba.polardbx.executor.mdl.manager.MdlManagerStamped;
import com.google.common.base.Preconditions;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
/**
* @author chenmo.cm
*/
public abstract class MdlManager extends AbstractLifecycle {
protected static final Map<String, MdlManager> SCHEMA_MDL_MANAGERS = new ConcurrentHashMap<>();
protected final String schema;
/**
* <pre>
* Hold all MdlContext, every front connection(ServerConnection) should remove its own context before closed
* map<front_conn_id, MdlContext>
* </pre>
*/
protected static final Map<String, MdlContext> contextMap = new ConcurrentHashMap<>();
public MdlManager(String schema) {
this.schema = schema;
}
/**
* For show metadata lock.
*/
public static Map<String, MdlContext> getContextMap() {
return contextMap;
}
/**
* For each schema element there will be a MdlManager
*/
public static MdlManager getInstance(@NotNull String schema) {
return SCHEMA_MDL_MANAGERS.computeIfAbsent(schema, MdlManagerStamped::new);
}
/**
* Remove MdlManager after schema unloaded
*/
public static MdlManager removeInstance(@NotNull String schema) {
final MdlManager removed = SCHEMA_MDL_MANAGERS.remove(schema);
if (null != removed) {
removed.destroy();
}
return removed;
}
/**
* Context of the owner of metadata locks. I.e. each server connection has
* such a context.
*/
public static MdlContext addContext(@NotNull Long connId) {
return contextMap.computeIfAbsent(connId.toString(), MdlContextStamped::new);
}
public static MdlContext addContext(@NotNull String schemaName, boolean preemptive) {
if(preemptive){
return contextMap.computeIfAbsent(
schemaName,
s -> new PreemptiveMdlContextStamped(schemaName, 15, 15, TimeUnit.SECONDS)
);
}
return contextMap.computeIfAbsent(schemaName, MdlContextStamped::new);
}
public static MdlContext addContext(@NotNull String schemaName, long initWait, long interval, TimeUnit timeUnit) {
Preconditions.checkArgument(initWait > 0);
Preconditions.checkArgument(interval > 0);
Preconditions.checkArgument(timeUnit != null);
return contextMap.computeIfAbsent(
schemaName,
s -> new PreemptiveMdlContextStamped(schemaName, initWait, interval, timeUnit)
);
}
/**
* Remove MdlContext before ServerConnection closed. Make sure
* MdlContext.releaseAllTransactionalLocks() is called before removal.
*
* @param context context to be remove
* @return context removed, return null if context not exists.
*/
public static MdlContext removeContext(@NotNull MdlContext context) {
return contextMap.remove(context.getConnId());
}
/**
* release lock and set ticket to invalidate
*/
public abstract void releaseLock(@NotNull MdlTicket ticket);
/**
* acquires the lock, block until lock available.
*
* @param request MdlRequest
* @param context MdlContext, The Reference of result will also be added to MdlRequest.ticket
* @return MdlTicket
*/
public abstract MdlTicket acquireLock(@NotNull MdlRequest request, @NotNull MdlContext context);
public abstract List<MdlTicket> getWaitFor(MdlKey mdlKey);
protected static boolean isReadLock(@NotNull MdlType type) {
boolean readLock;
switch (type) {
case MDL_EXCLUSIVE:
readLock = false;
break;
case MDL_SHARED_WRITE:
readLock = true;
break;
default:
throw new RuntimeException("unsupported MDL type: " + type);
}
return readLock;
}
}
| 33.378378
| 118
| 0.686235
|
5e285c8fec195fa830c6d0e531b11d7992d314a3
| 1,045
|
package com.cp.s2si.exception;
import java.time.LocalDateTime;
/**
*
* @author panther
*
*/
public class JWTExpiredException extends Exception {
private static final long serialVersionUID = 5372049449306522122L;
private LocalDateTime expiredTime = null;
private String subject = null;
public JWTExpiredException() {
}
public JWTExpiredException(String message) {
super(message);
}
public JWTExpiredException(String message, String subject, LocalDateTime expiredTime) {
super(message);
this.subject = subject;
this.expiredTime = expiredTime;
}
public JWTExpiredException(Throwable cause) {
super(cause);
}
public JWTExpiredException(String message, Throwable cause) {
super(message, cause);
}
public JWTExpiredException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public String getSubject() {
return subject;
}
public LocalDateTime getExpiredTime() {
return expiredTime;
}
}
| 20.096154
| 117
| 0.755981
|
7aa2cf7a89f3b9e21fa960208b81f87bb44ded89
| 2,738
|
package skyestudios.buildx.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import skyestudios.buildx.R;
import skyestudios.buildx.databinding.ProjectItemsBinding;
import skyestudios.buildx.interfaces.IProjectAdapter;
import skyestudios.buildx.models.Project;
public class ProjectAdapter extends RecyclerView.Adapter<ProjectAdapter.ProjectViewHolder> {
List<Project> list = new ArrayList<>();
Context mContext;
private OnProjectClicked onProjectClicked;
public ProjectAdapter(Context context, List<Project> list, OnProjectClicked onProjectClicked){
mContext = context;
this.list = list;
this.onProjectClicked = onProjectClicked;
}
@NonNull
@Override
public ProjectViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
ProjectItemsBinding binding = ProjectItemsBinding.inflate(inflater,parent,false);
return new ProjectViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull ProjectViewHolder holder, int position) {
final Project project = list.get(position);
holder.bindView(project);
}
@Override
public int getItemCount() {
return list.size();
}
class ProjectViewHolder extends RecyclerView.ViewHolder{
ProjectItemsBinding binding;
public ProjectViewHolder(@NonNull ProjectItemsBinding binding) {
super(binding.getRoot());
this.binding = binding;
binding.getRoot().setOnClickListener(view -> {
onProjectClicked.projectItemClicked(list.get(getAdapterPosition()));
});
}
public void bindView(Project project){
Picasso.get().load(project.icon).placeholder(R.drawable.ic_round_android_24).into(binding.projectIcon, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError(Exception e) {
binding.projectIcon.setImageResource(R.drawable.ic_round_android_24);
}
});
binding.packageName.setText(project.packageName);
binding.projectName.setText(project.projectName);
}
}
public interface OnProjectClicked{
void projectItemClicked(Project project);
}
}
| 31.113636
| 131
| 0.692476
|
9e7ca7df440ec3ebe0e25bd24a57366c01efdeb6
| 2,075
|
// Licensed to Cloudera, Inc. under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Cloudera, Inc. licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.cloudera.hue;
import org.apache.hadoop.fs.FsShell;
import org.apache.hadoop.security.UserGroupInformation;
import java.security.PrivilegedExceptionAction;
/**
* Tool that allows a user with proxyuser privileges to act on behalf
* of another user on HDFS. Hue currently uses this tool in order to
* upload files using the "-put" shell command on behalf of the logged-in
* user.
*/
public class SudoFsShell {
private static void usage() {
System.err.println("usage: SudoFsShell <username> <shell args ...>");
}
public static void main(String []args) throws Exception {
if (args.length < 1) {
usage();
System.exit(1);
}
String username = args[0];
final String shellArgs[] = new String[args.length - 1];
System.arraycopy(args, 1, shellArgs, 0, args.length - 1);
UserGroupInformation sudoUgi;
if (UserGroupInformation.isSecurityEnabled()) {
sudoUgi = UserGroupInformation.createProxyUser(
username, UserGroupInformation.getCurrentUser());
} else {
sudoUgi = UserGroupInformation.createRemoteUser(username);
}
sudoUgi.doAs(new PrivilegedExceptionAction<Void>() {
public Void run() throws Exception {
FsShell.main(shellArgs);
return null;
}
});
}
}
| 35.169492
| 75
| 0.710843
|
3efcf7b09e3d0539627e452541c66aa159da1133
| 16,910
|
package com.softwareverde.bitcoin.app.android.adapter;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.softwareverde.android.util.AndroidUtil;
import com.softwareverde.bitcoin.address.Address;
import com.softwareverde.bitcoin.app.R;
import com.softwareverde.bitcoin.app.android.BitcoinUtil;
import com.softwareverde.bitcoin.transaction.output.TransactionOutput;
import com.softwareverde.bitcoin.transaction.output.identifier.TransactionOutputIdentifier;
import com.softwareverde.bitcoin.util.StringUtil;
import com.softwareverde.bitcoin.wallet.utxo.SpendableTransactionOutput;
import com.softwareverde.constable.list.List;
import com.softwareverde.constable.list.mutable.MutableList;
import com.softwareverde.cryptography.hash.sha256.Sha256Hash;
import com.softwareverde.util.Util;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
public class TransactionOutputsAdapter extends RecyclerView.Adapter<TransactionOutputsAdapter.ViewHolder> {
protected static int[] CONFIRMATION_COUNT_COLORS = new int[] {
Color.parseColor("#CCCCCC"),
Color.parseColor("#FF0000"),
Color.parseColor("#FFAA00"),
Color.parseColor("#EEEE00"),
Color.parseColor("#AAFF00"),
Color.parseColor("#00FF00")
};
public interface OnClickListener {
void onClick(TransactionOutputIdentifier transactionOutputIdentifier);
}
protected interface _OnClickListener {
void onClick(int position);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final View view;
public final TextView addressView;
public final View leftPaneView;
public final TextView amountView;
public final TextView tokenAmountView;
public final TextView transactionHashView;
public final TextView transactionIndexView;
public final View[] confirmationViews;
public ViewHolder(final View view) {
super(view);
this.view = view;
this.addressView = view.findViewById(R.id.txo_address);
this.leftPaneView = view.findViewById(R.id.txo_left_pane);
this.amountView = view.findViewById(R.id.txo_amount);
this.tokenAmountView = view.findViewById(R.id.txo_token_amount);
this.transactionHashView = view.findViewById(R.id.txo_transaction_hash);
this.transactionIndexView = view.findViewById(R.id.txo_transaction_index);
this.confirmationViews = new View[] {
view.findViewById(R.id.txo_confirmation_0),
view.findViewById(R.id.txo_confirmation_1),
view.findViewById(R.id.txo_confirmation_2),
view.findViewById(R.id.txo_confirmation_3),
view.findViewById(R.id.txo_confirmation_4),
view.findViewById(R.id.txo_confirmation_5)
};
}
}
protected Activity _activity;
protected LayoutInflater _inflater;
protected MutableList<SpendableTransactionOutput> _dataSet = new MutableList<SpendableTransactionOutput>();
protected HashSet<TransactionOutputIdentifier> _selectedTransactionOutputs = new HashSet<TransactionOutputIdentifier>();
protected HashSet<TransactionOutputIdentifier> _highlightedTransactionOutputs = new HashSet<TransactionOutputIdentifier>();
protected HashMap<TransactionOutputIdentifier, Long> _confirmationCounts = new HashMap<TransactionOutputIdentifier, Long>();
protected HashMap<TransactionOutputIdentifier, Long> _tokenAmounts = new HashMap<TransactionOutputIdentifier, Long>();
protected HashSet<TransactionOutputIdentifier> _tokenBatonHolders = new HashSet<TransactionOutputIdentifier>();
protected OnClickListener _onClickListener;
protected Comparator<SpendableTransactionOutput> _sortAlgorithm = SortAlgorithms.AMOUNT_ASCENDING_UNSPENT_BEFORE_SPENT;
protected final _OnClickListener __onClickListener = new _OnClickListener() {
@Override
public void onClick(final int position) {
final OnClickListener onClickListener = _onClickListener;
if (onClickListener == null) { return; }
final SpendableTransactionOutput spendableTransactionOutput = _dataSet.get(position);
final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier();
onClickListener.onClick(transactionOutputIdentifier);
}
};
protected void _sortDataSet() {
final Comparator<SpendableTransactionOutput> sortAlgorithm = _sortAlgorithm;
if (sortAlgorithm != null) {
_dataSet.sort(sortAlgorithm);
}
}
public TransactionOutputsAdapter(final Activity activity) {
_activity = activity;
_inflater = LayoutInflater.from(_activity.getApplicationContext());
}
@Override
public TransactionOutputsAdapter.ViewHolder onCreateViewHolder(final ViewGroup viewGroup, final int position) {
final View view = _inflater.inflate(R.layout.transaction_output_item, viewGroup, false);
final ViewHolder viewHolder = new TransactionOutputsAdapter.ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
final int position = viewHolder.getAdapterPosition();
if (position < 0) { return; }
__onClickListener.onClick(position);
}
});
return viewHolder;
}
@Override
public void onBindViewHolder(final TransactionOutputsAdapter.ViewHolder viewHolder, final int position) {
final SpendableTransactionOutput spendableTransactionOutput = _dataSet.get(position);
final TransactionOutput transactionOutput = spendableTransactionOutput.getTransactionOutput();
final TransactionOutputIdentifier transactionOutputIdentifier = spendableTransactionOutput.getIdentifier();
final Resources resources = _activity.getResources();
final int primaryColor = resources.getColor(R.color.colorPrimary, null);
{ // Set the textViews content...
final Address address = spendableTransactionOutput.getAddress();
viewHolder.addressView.setText((address != null) ? address.toBase58CheckEncoded() : "");
viewHolder.amountView.setText(StringUtil.formatNumberString(transactionOutput.getAmount()));
final Sha256Hash transactionHash = transactionOutputIdentifier.getTransactionHash();
final String transactionHashString = BitcoinUtil.spaceHex(transactionHash.toString(), 8, 2);
viewHolder.transactionHashView.setText(transactionHashString);
viewHolder.transactionIndexView.setText(StringUtil.formatNumberString(transactionOutputIdentifier.getOutputIndex()));
final Long tokenAmount = _tokenAmounts.get(transactionOutputIdentifier);
if (Util.coalesce(tokenAmount) > 0) {
viewHolder.tokenAmountView.setVisibility(View.VISIBLE);
final String tokenAmountString = StringUtil.formatNumberString(tokenAmount);
viewHolder.tokenAmountView.setText(tokenAmountString);
if (Util.coalesce(tokenAmountString).length() > 10) {
viewHolder.tokenAmountView.setTextSize(8F);
}
else {
viewHolder.tokenAmountView.setTextSize(14F);
}
}
else if (_tokenBatonHolders.contains(transactionOutputIdentifier)) {
viewHolder.tokenAmountView.setVisibility(View.VISIBLE);
viewHolder.tokenAmountView.setTextSize(14F);
viewHolder.tokenAmountView.setText("BATON");
}
else {
viewHolder.tokenAmountView.setVisibility(View.GONE);
}
}
final boolean isSpent = (spendableTransactionOutput.isSpent());
{ // Render the item-spent effects...
if (isSpent) {
final int spentTextColor = Color.parseColor("#A0A0A0");
viewHolder.addressView.setTextColor(spentTextColor);
viewHolder.amountView.setTextColor(spentTextColor);
viewHolder.transactionHashView.setTextColor(spentTextColor);
viewHolder.transactionIndexView.setTextColor(spentTextColor);
final int spentBackgroundColor = Color.parseColor("#505050");
viewHolder.view.setBackgroundColor(spentBackgroundColor);
final int unspentAmountBackgroundColor = Color.parseColor("#303530");
final int spentAmountBackgroundColor = AndroidUtil.setAlpha(unspentAmountBackgroundColor, 0.25F);
viewHolder.amountView.setBackgroundColor(spentAmountBackgroundColor);
final int unspentTokenAmountBackgroundColor = primaryColor;
final int spentTokenAmountBackgroundColor = AndroidUtil.setAlpha(unspentTokenAmountBackgroundColor, 0.25F);
viewHolder.tokenAmountView.setBackgroundColor(spentTokenAmountBackgroundColor);
}
else {
final int unspentTextColor = Color.parseColor("#FFFFFF");
viewHolder.addressView.setTextColor(unspentTextColor);
viewHolder.amountView.setTextColor(unspentTextColor);
viewHolder.transactionHashView.setTextColor(unspentTextColor);
viewHolder.transactionIndexView.setTextColor(unspentTextColor);
final int unspentBackgroundColor = Color.parseColor("#505050");
viewHolder.view.setBackgroundColor(unspentBackgroundColor);
final int unspentAmountBackgroundColor = Color.parseColor("#303530");
viewHolder.amountView.setBackgroundColor(unspentAmountBackgroundColor);
final int unspentTokenAmountBackgroundColor = primaryColor;
viewHolder.tokenAmountView.setBackgroundColor(unspentTokenAmountBackgroundColor);
}
}
final boolean isHighlighted = (_highlightedTransactionOutputs.contains(transactionOutputIdentifier));
final boolean isSelected = (_selectedTransactionOutputs.contains(transactionOutputIdentifier));
{ // Render the item-selected/highlighted effects...
if (isSelected) {
viewHolder.view.setBackgroundResource(R.drawable.selected_transaction_output_background);
}
else if (isHighlighted) {
viewHolder.view.setBackgroundResource(R.drawable.highlighted_transaction_output_border);
}
else {
viewHolder.view.setBackgroundResource(0);
viewHolder.view.setBackgroundColor(Color.parseColor("#202020"));;
}
}
{ // Render the confirmation count bars...
final Long confirmationCount = Util.coalesce(_confirmationCounts.get(transactionOutputIdentifier));
final int colorIndex = (confirmationCount >= CONFIRMATION_COUNT_COLORS.length ? (CONFIRMATION_COUNT_COLORS.length - 1) : confirmationCount.intValue());
final int color = (spendableTransactionOutput.isSpent() ? CONFIRMATION_COUNT_COLORS[0] : CONFIRMATION_COUNT_COLORS[colorIndex]);
final int disabledColor = CONFIRMATION_COUNT_COLORS[0];
for (int i = 0; i < viewHolder.confirmationViews.length; ++i) {
final View confirmationView = viewHolder.confirmationViews[i];
confirmationView.setBackgroundColor((i < confirmationCount) ? color : disabledColor);
}
}
}
@Override
public int getItemCount() {
return _dataSet.getSize();
}
public boolean isEmpty() {
return (_dataSet.getSize() == 0);
}
public void setSortAlgorithm(final Comparator<SpendableTransactionOutput> sortAlgorithm) {
_sortAlgorithm = sortAlgorithm;
}
public SpendableTransactionOutput getItem(final int position) {
if ( (position < 0) || (position >= _dataSet.getSize()) ) { return null; }
return _dataSet.get(position);
}
public List<SpendableTransactionOutput> getItems() {
return _dataSet;
}
public void selectItem(final TransactionOutputIdentifier transactionOutputIdentifier) {
_selectedTransactionOutputs.add(transactionOutputIdentifier);
}
public void deselectItem(final TransactionOutputIdentifier transactionOutputIdentifier) {
_selectedTransactionOutputs.remove(transactionOutputIdentifier);
}
public void toggleItem(final TransactionOutputIdentifier transactionOutputIdentifier) {
if (_selectedTransactionOutputs.contains(transactionOutputIdentifier)) {
_selectedTransactionOutputs.remove(transactionOutputIdentifier);
}
else {
_selectedTransactionOutputs.add(transactionOutputIdentifier);
}
}
public void clearSelectedItems() {
_selectedTransactionOutputs.clear();
}
public Boolean isItemSelected(final TransactionOutputIdentifier transactionOutputIdentifier) {
return _selectedTransactionOutputs.contains(transactionOutputIdentifier);
}
public List<TransactionOutputIdentifier> getSelectedItems() {
final MutableList<TransactionOutputIdentifier> selectedTransactionOutputIdentifiers = new MutableList<TransactionOutputIdentifier>(_selectedTransactionOutputs.size());
for (final TransactionOutputIdentifier transactionOutputIdentifier : _selectedTransactionOutputs) {
selectedTransactionOutputIdentifiers.add(transactionOutputIdentifier);
}
return selectedTransactionOutputIdentifiers;
}
public void setOnClickListener(final OnClickListener onClickListener) {
_onClickListener = onClickListener;
}
public void add(final SpendableTransactionOutput spendableTransactionOutput) {
_dataSet.add(spendableTransactionOutput);
_sortDataSet();
}
public void addAll(final List<SpendableTransactionOutput> spendableTransactionOutputs) {
_dataSet.addAll(spendableTransactionOutputs);
_sortDataSet();
}
public void removeItem(final TransactionOutputIdentifier transactionOutputIdentifier) {
final Iterator<SpendableTransactionOutput> dataSetIterator = _dataSet.mutableIterator();
while (dataSetIterator.hasNext()) {
final SpendableTransactionOutput spendableTransactionOutput = dataSetIterator.next();
if (Util.areEqual(spendableTransactionOutput.getIdentifier(), transactionOutputIdentifier)) {
dataSetIterator.remove();
break;
}
}
_selectedTransactionOutputs.remove(transactionOutputIdentifier);
_highlightedTransactionOutputs.remove(transactionOutputIdentifier);
_confirmationCounts.remove(transactionOutputIdentifier);
_tokenAmounts.remove(transactionOutputIdentifier);
}
public void setConfirmationCount(final TransactionOutputIdentifier transactionOutputIdentifier, final Long confirmationCount) {
_confirmationCounts.put(transactionOutputIdentifier, confirmationCount);
}
public void setTokenAmount(final TransactionOutputIdentifier transactionOutputIdentifier, final Long confirmationCount) {
_tokenAmounts.put(transactionOutputIdentifier, confirmationCount);
}
public void setIsTokenBatonHolder(final TransactionOutputIdentifier transactionOutputIdentifier) {
_tokenBatonHolders.add(transactionOutputIdentifier);
}
public List<TransactionOutputIdentifier> getHighlightedItems() {
final MutableList<TransactionOutputIdentifier> highlightedTransactionOutputIdentifiers = new MutableList<TransactionOutputIdentifier>(_highlightedTransactionOutputs.size());
for (final TransactionOutputIdentifier transactionOutputIdentifier : _highlightedTransactionOutputs) {
highlightedTransactionOutputIdentifiers.add(transactionOutputIdentifier);
}
return highlightedTransactionOutputIdentifiers;
}
public void highlightItem(final TransactionOutputIdentifier transactionOutputIdentifier) {
_highlightedTransactionOutputs.add(transactionOutputIdentifier);
}
public void clearHighlightedItems() {
_highlightedTransactionOutputs.clear();
}
public void clear() {
_dataSet.clear();
_selectedTransactionOutputs.clear();
_highlightedTransactionOutputs.clear();
_confirmationCounts.clear();
_tokenAmounts.clear();
}
}
| 46.202186
| 181
| 0.715849
|
fd222534dc8ca5cdd00d5b36404171176bde4724
| 718
|
package com.SmartCity.tsp;
public class SwapOperator {
private int x;
private int y;
private double probability;
private int opProb = 1;
SwapOperator(int x, int y, double probability){
this.x = x;
this.y = y;
this.probability = probability;
//this.opProb = opProb;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public double getProbability() {
return probability;
}
public void setProbability(double probability) {
this.probability = probability;
}
/*
public int getOpProb() {
return opProb;
}
public void setOpProb(int opProb) {
this.opProb = opProb;
}
*/
}
| 15.276596
| 49
| 0.655989
|
1ed955c7bfcadd5674ac8ec647d3283fa7edce60
| 892
|
package group92.spectrangle.tests;
import group92.spectrangle.board.Bag;
import group92.spectrangle.board.Tile;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class BagTest {
@Test
public void testSwap() {
Bag bag = new Bag();
Tile tile = bag.take();
bag.swap(tile);
boolean result = false;
while (!bag.isEmpty()) {
if (bag.take() == tile) {
result = true;
break;
}
}
assertTrue(result);
}
@Test
public void testTake() {
Bag bag = new Bag();
System.out.println(Bag.TILES.length);
for (int i = 0; i < 36; i++) {
assertNotEquals(bag.take(), null);
}
assertTrue(bag.isEmpty());
}
}
| 22.871795
| 63
| 0.566143
|
552f0c7d393807cf6a83fca097654b491b531a8a
| 51,969
|
/*
* generated by Xtext 2.9.1
*/
package org.mobadsl.grammar.serializer;
import com.google.inject.Inject;
import java.util.Set;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.xtext.Action;
import org.eclipse.xtext.Parameter;
import org.eclipse.xtext.ParserRule;
import org.eclipse.xtext.serializer.ISerializationContext;
import org.eclipse.xtext.serializer.acceptor.SequenceFeeder;
import org.eclipse.xtext.serializer.sequencer.AbstractDelegatingSemanticSequencer;
import org.eclipse.xtext.serializer.sequencer.ITransientValueService.ValueTransient;
import org.mobadsl.grammar.services.MobaGrammarAccess;
import org.mobadsl.semantic.model.moba.MobaAppInstallTrigger;
import org.mobadsl.semantic.model.moba.MobaAppUpdateTrigger;
import org.mobadsl.semantic.model.moba.MobaApplication;
import org.mobadsl.semantic.model.moba.MobaAuthorization;
import org.mobadsl.semantic.model.moba.MobaBluetoothModule;
import org.mobadsl.semantic.model.moba.MobaCache;
import org.mobadsl.semantic.model.moba.MobaConstant;
import org.mobadsl.semantic.model.moba.MobaConstantValue;
import org.mobadsl.semantic.model.moba.MobaDataType;
import org.mobadsl.semantic.model.moba.MobaDeviceStartupTrigger;
import org.mobadsl.semantic.model.moba.MobaDigitsConstraint;
import org.mobadsl.semantic.model.moba.MobaDto;
import org.mobadsl.semantic.model.moba.MobaDtoAttribute;
import org.mobadsl.semantic.model.moba.MobaDtoEmbeddable;
import org.mobadsl.semantic.model.moba.MobaDtoReference;
import org.mobadsl.semantic.model.moba.MobaEmailTrigger;
import org.mobadsl.semantic.model.moba.MobaEntity;
import org.mobadsl.semantic.model.moba.MobaEntityAttribute;
import org.mobadsl.semantic.model.moba.MobaEntityEmbeddable;
import org.mobadsl.semantic.model.moba.MobaEntityIndex;
import org.mobadsl.semantic.model.moba.MobaEntityReference;
import org.mobadsl.semantic.model.moba.MobaEnum;
import org.mobadsl.semantic.model.moba.MobaEnumLiteral;
import org.mobadsl.semantic.model.moba.MobaFriend;
import org.mobadsl.semantic.model.moba.MobaGenerator;
import org.mobadsl.semantic.model.moba.MobaGeneratorIDFeature;
import org.mobadsl.semantic.model.moba.MobaGeneratorMixinFeature;
import org.mobadsl.semantic.model.moba.MobaGeneratorSlot;
import org.mobadsl.semantic.model.moba.MobaGeofenceTrigger;
import org.mobadsl.semantic.model.moba.MobaMaxConstraint;
import org.mobadsl.semantic.model.moba.MobaMaxLengthConstraint;
import org.mobadsl.semantic.model.moba.MobaMinConstraint;
import org.mobadsl.semantic.model.moba.MobaMinLengthConstraint;
import org.mobadsl.semantic.model.moba.MobaModel;
import org.mobadsl.semantic.model.moba.MobaMuliplicity;
import org.mobadsl.semantic.model.moba.MobaNFCModule;
import org.mobadsl.semantic.model.moba.MobaNotNullConstraint;
import org.mobadsl.semantic.model.moba.MobaNullConstraint;
import org.mobadsl.semantic.model.moba.MobaPackage;
import org.mobadsl.semantic.model.moba.MobaPersistenceType;
import org.mobadsl.semantic.model.moba.MobaProject;
import org.mobadsl.semantic.model.moba.MobaProperty;
import org.mobadsl.semantic.model.moba.MobaPushModule;
import org.mobadsl.semantic.model.moba.MobaPushTrigger;
import org.mobadsl.semantic.model.moba.MobaQueue;
import org.mobadsl.semantic.model.moba.MobaQueueReference;
import org.mobadsl.semantic.model.moba.MobaRESTAttribute;
import org.mobadsl.semantic.model.moba.MobaRESTCrud;
import org.mobadsl.semantic.model.moba.MobaRESTCustomService;
import org.mobadsl.semantic.model.moba.MobaRESTDtoAttribute;
import org.mobadsl.semantic.model.moba.MobaRESTHeader;
import org.mobadsl.semantic.model.moba.MobaRESTPayloadDefinition;
import org.mobadsl.semantic.model.moba.MobaRESTWorkflow;
import org.mobadsl.semantic.model.moba.MobaRegexpConstraint;
import org.mobadsl.semantic.model.moba.MobaSMSTrigger;
import org.mobadsl.semantic.model.moba.MobaServer;
import org.mobadsl.semantic.model.moba.MobaSettings;
import org.mobadsl.semantic.model.moba.MobaSettingsAttribute;
import org.mobadsl.semantic.model.moba.MobaSettingsEntityReference;
import org.mobadsl.semantic.model.moba.MobaTemplate;
import org.mobadsl.semantic.model.moba.MobaTransportSerializationType;
@SuppressWarnings("all")
public class MobaSemanticSequencer extends AbstractDelegatingSemanticSequencer {
@Inject
private MobaGrammarAccess grammarAccess;
@Override
public void sequence(ISerializationContext context, EObject semanticObject) {
EPackage epackage = semanticObject.eClass().getEPackage();
ParserRule rule = context.getParserRule();
Action action = context.getAssignedAction();
Set<Parameter> parameters = context.getEnabledBooleanParameters();
if (epackage == MobaPackage.eINSTANCE)
switch (semanticObject.eClass().getClassifierID()) {
case MobaPackage.MOBA_APP_INSTALL_TRIGGER:
sequence_MobaAppInstallTrigger(context, (MobaAppInstallTrigger) semanticObject);
return;
case MobaPackage.MOBA_APP_UPDATE_TRIGGER:
sequence_MobaAppUpdateTrigger(context, (MobaAppUpdateTrigger) semanticObject);
return;
case MobaPackage.MOBA_APPLICATION:
sequence_MobaApplication_MobaFriendsAble(context, (MobaApplication) semanticObject);
return;
case MobaPackage.MOBA_AUTHORIZATION:
sequence_MobaAuthorization_MobaFriendsAble(context, (MobaAuthorization) semanticObject);
return;
case MobaPackage.MOBA_BLUETOOTH_MODULE:
sequence_MobaBluetoothModule_MobaFriendsAble(context, (MobaBluetoothModule) semanticObject);
return;
case MobaPackage.MOBA_CACHE:
sequence_MobaCache(context, (MobaCache) semanticObject);
return;
case MobaPackage.MOBA_CONSTANT:
sequence_MobaConstant_MobaFriendsAble(context, (MobaConstant) semanticObject);
return;
case MobaPackage.MOBA_CONSTANT_VALUE:
sequence_MobaConstantValue(context, (MobaConstantValue) semanticObject);
return;
case MobaPackage.MOBA_DATA_TYPE:
sequence_MobaDataType_MobaFriendsAble(context, (MobaDataType) semanticObject);
return;
case MobaPackage.MOBA_DEVICE_STARTUP_TRIGGER:
sequence_MobaDeviceStartupTrigger(context, (MobaDeviceStartupTrigger) semanticObject);
return;
case MobaPackage.MOBA_DIGITS_CONSTRAINT:
sequence_MobaDigitsConstraint(context, (MobaDigitsConstraint) semanticObject);
return;
case MobaPackage.MOBA_DTO:
sequence_MobaDto_MobaFriendsAble(context, (MobaDto) semanticObject);
return;
case MobaPackage.MOBA_DTO_ATTRIBUTE:
sequence_MobaDtoAttribute_MobaFriendsAble_MobaMultiplicityAble(context, (MobaDtoAttribute) semanticObject);
return;
case MobaPackage.MOBA_DTO_EMBEDDABLE:
sequence_MobaDtoEmbeddable_MobaFriendsAble_MobaMultiplicityAble(context, (MobaDtoEmbeddable) semanticObject);
return;
case MobaPackage.MOBA_DTO_REFERENCE:
sequence_MobaDtoReference_MobaFriendsAble_MobaMultiplicityAble(context, (MobaDtoReference) semanticObject);
return;
case MobaPackage.MOBA_EMAIL_TRIGGER:
sequence_MobaEmailTrigger(context, (MobaEmailTrigger) semanticObject);
return;
case MobaPackage.MOBA_ENTITY:
sequence_MobaEntity_MobaFriendsAble(context, (MobaEntity) semanticObject);
return;
case MobaPackage.MOBA_ENTITY_ATTRIBUTE:
sequence_MobaEntityAttribute_MobaFriendsAble_MobaMultiplicityAble(context, (MobaEntityAttribute) semanticObject);
return;
case MobaPackage.MOBA_ENTITY_EMBEDDABLE:
sequence_MobaEntityEmbeddable_MobaFriendsAble_MobaMultiplicityAble(context, (MobaEntityEmbeddable) semanticObject);
return;
case MobaPackage.MOBA_ENTITY_INDEX:
sequence_MobaEntityIndex(context, (MobaEntityIndex) semanticObject);
return;
case MobaPackage.MOBA_ENTITY_REFERENCE:
sequence_MobaEntityReference_MobaFriendsAble_MobaMultiplicityAble(context, (MobaEntityReference) semanticObject);
return;
case MobaPackage.MOBA_ENUM:
sequence_MobaEnum(context, (MobaEnum) semanticObject);
return;
case MobaPackage.MOBA_ENUM_LITERAL:
sequence_MobaEnumLiteral(context, (MobaEnumLiteral) semanticObject);
return;
case MobaPackage.MOBA_FRIEND:
sequence_MobaFriend(context, (MobaFriend) semanticObject);
return;
case MobaPackage.MOBA_GENERATOR:
sequence_MobaGenerator(context, (MobaGenerator) semanticObject);
return;
case MobaPackage.MOBA_GENERATOR_ID_FEATURE:
sequence_MobaGeneratorIDFeature(context, (MobaGeneratorIDFeature) semanticObject);
return;
case MobaPackage.MOBA_GENERATOR_MIXIN_FEATURE:
sequence_MobaGeneratorMixinFeature(context, (MobaGeneratorMixinFeature) semanticObject);
return;
case MobaPackage.MOBA_GENERATOR_SLOT:
sequence_MobaGeneratorSlot(context, (MobaGeneratorSlot) semanticObject);
return;
case MobaPackage.MOBA_GEOFENCE_TRIGGER:
sequence_MobaGeofenceTrigger(context, (MobaGeofenceTrigger) semanticObject);
return;
case MobaPackage.MOBA_MAX_CONSTRAINT:
sequence_MobaMaxConstraint(context, (MobaMaxConstraint) semanticObject);
return;
case MobaPackage.MOBA_MAX_LENGTH_CONSTRAINT:
sequence_MobaMaxLengthConstraint(context, (MobaMaxLengthConstraint) semanticObject);
return;
case MobaPackage.MOBA_MIN_CONSTRAINT:
sequence_MobaMinConstraint(context, (MobaMinConstraint) semanticObject);
return;
case MobaPackage.MOBA_MIN_LENGTH_CONSTRAINT:
sequence_MobaMinLengthConstraint(context, (MobaMinLengthConstraint) semanticObject);
return;
case MobaPackage.MOBA_MODEL:
sequence_MobaModel(context, (MobaModel) semanticObject);
return;
case MobaPackage.MOBA_MULIPLICITY:
sequence_MobaMuliplicity(context, (MobaMuliplicity) semanticObject);
return;
case MobaPackage.MOBA_NFC_MODULE:
sequence_MobaFriendsAble_MobaNFCModule(context, (MobaNFCModule) semanticObject);
return;
case MobaPackage.MOBA_NOT_NULL_CONSTRAINT:
sequence_MobaNotNullConstraint(context, (MobaNotNullConstraint) semanticObject);
return;
case MobaPackage.MOBA_NULL_CONSTRAINT:
sequence_MobaNullConstraint(context, (MobaNullConstraint) semanticObject);
return;
case MobaPackage.MOBA_PERSISTENCE_TYPE:
sequence_MobaFriendsAble_MobaPersistenceType(context, (MobaPersistenceType) semanticObject);
return;
case MobaPackage.MOBA_PROJECT:
sequence_MobaFriendsAble_MobaProject(context, (MobaProject) semanticObject);
return;
case MobaPackage.MOBA_PROPERTY:
sequence_MobaProperty(context, (MobaProperty) semanticObject);
return;
case MobaPackage.MOBA_PUSH_MODULE:
sequence_MobaFriendsAble_MobaPushModule(context, (MobaPushModule) semanticObject);
return;
case MobaPackage.MOBA_PUSH_TRIGGER:
sequence_MobaPushTrigger(context, (MobaPushTrigger) semanticObject);
return;
case MobaPackage.MOBA_QUEUE:
sequence_MobaFriendsAble_MobaQueue(context, (MobaQueue) semanticObject);
return;
case MobaPackage.MOBA_QUEUE_REFERENCE:
sequence_MobaFriendsAble_MobaQueueReference(context, (MobaQueueReference) semanticObject);
return;
case MobaPackage.MOBA_REST_ATTRIBUTE:
if (rule == grammarAccess.getMobaRESTAbstractAttributeRule()
|| rule == grammarAccess.getMobaRESTAttributeRule()) {
sequence_MobaRESTAttribute(context, (MobaRESTAttribute) semanticObject);
return;
}
else if (rule == grammarAccess.getMobaRESTAbstractMultipartAttributeRule()
|| rule == grammarAccess.getMobaRESTMultipartAttributeRule()) {
sequence_MobaRESTMultipartAttribute(context, (MobaRESTAttribute) semanticObject);
return;
}
else break;
case MobaPackage.MOBA_REST_CRUD:
sequence_MobaFriendsAble_MobaRESTCrud(context, (MobaRESTCrud) semanticObject);
return;
case MobaPackage.MOBA_REST_CUSTOM_SERVICE:
sequence_MobaFriendsAble_MobaRESTCustomService(context, (MobaRESTCustomService) semanticObject);
return;
case MobaPackage.MOBA_REST_DTO_ATTRIBUTE:
if (rule == grammarAccess.getMobaRESTAbstractAttributeRule()
|| rule == grammarAccess.getMobaRESTDtoAttributeRule()) {
sequence_MobaRESTDtoAttribute(context, (MobaRESTDtoAttribute) semanticObject);
return;
}
else if (rule == grammarAccess.getMobaRESTAbstractMultipartAttributeRule()
|| rule == grammarAccess.getMobaRESTMultipartDtoAttributeRule()) {
sequence_MobaRESTMultipartDtoAttribute(context, (MobaRESTDtoAttribute) semanticObject);
return;
}
else break;
case MobaPackage.MOBA_REST_HEADER:
sequence_MobaRestHeader(context, (MobaRESTHeader) semanticObject);
return;
case MobaPackage.MOBA_REST_PAYLOAD_DEFINITION:
sequence_MobaRESTPayloadDefinition(context, (MobaRESTPayloadDefinition) semanticObject);
return;
case MobaPackage.MOBA_REST_WORKFLOW:
sequence_MobaFriendsAble_MobaRESTWorkflow(context, (MobaRESTWorkflow) semanticObject);
return;
case MobaPackage.MOBA_REGEXP_CONSTRAINT:
sequence_MobaRegexpConstraint(context, (MobaRegexpConstraint) semanticObject);
return;
case MobaPackage.MOBA_SMS_TRIGGER:
sequence_MobaSMSTrigger(context, (MobaSMSTrigger) semanticObject);
return;
case MobaPackage.MOBA_SERVER:
sequence_MobaFriendsAble_MobaServer(context, (MobaServer) semanticObject);
return;
case MobaPackage.MOBA_SETTINGS:
sequence_MobaFriendsAble_MobaSettings(context, (MobaSettings) semanticObject);
return;
case MobaPackage.MOBA_SETTINGS_ATTRIBUTE:
sequence_MobaFriendsAble_MobaMultiplicityAble_MobaSettingsAttribute(context, (MobaSettingsAttribute) semanticObject);
return;
case MobaPackage.MOBA_SETTINGS_ENTITY_REFERENCE:
sequence_MobaFriendsAble_MobaMultiplicityAble_MobaSettingsEntityReference(context, (MobaSettingsEntityReference) semanticObject);
return;
case MobaPackage.MOBA_TEMPLATE:
sequence_MobaTemplate(context, (MobaTemplate) semanticObject);
return;
case MobaPackage.MOBA_TRANSPORT_SERIALIZATION_TYPE:
sequence_MobaFriendsAble_MobaTransportSerializationType(context, (MobaTransportSerializationType) semanticObject);
return;
}
if (errorAcceptor != null)
errorAcceptor.accept(diagnosticProvider.createInvalidContextOrTypeDiagnostic(semanticObject, context));
}
/**
* Contexts:
* MobaApplicationFeature returns MobaAppInstallTrigger
* MobaTrigger returns MobaAppInstallTrigger
* MobaAppInstallTrigger returns MobaAppInstallTrigger
*
* Constraint:
* name=ID
*/
protected void sequence_MobaAppInstallTrigger(ISerializationContext context, MobaAppInstallTrigger semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getMobaAppInstallTriggerAccess().getNameIDTerminalRuleCall_1_0(), semanticObject.getName());
feeder.finish();
}
/**
* Contexts:
* MobaApplicationFeature returns MobaAppUpdateTrigger
* MobaTrigger returns MobaAppUpdateTrigger
* MobaAppUpdateTrigger returns MobaAppUpdateTrigger
*
* Constraint:
* name=ID
*/
protected void sequence_MobaAppUpdateTrigger(ISerializationContext context, MobaAppUpdateTrigger semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getMobaAppUpdateTriggerAccess().getNameIDTerminalRuleCall_1_0(), semanticObject.getName());
feeder.finish();
}
/**
* Contexts:
* MobaModelFeature returns MobaApplication
* MobaApplication returns MobaApplication
*
* Constraint:
* (
* name=ID
* version=VERSION
* defaultCache=[MobaCache|ID]?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* (javaPackage=FQN | features+=MobaApplicationFeature)*
* )
*/
protected void sequence_MobaApplication_MobaFriendsAble(ISerializationContext context, MobaApplication semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaAuthorization
* MobaAuthorization returns MobaAuthorization
*
* Constraint:
* (name=CONSTANT ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*)
*/
protected void sequence_MobaAuthorization_MobaFriendsAble(ISerializationContext context, MobaAuthorization semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaBluetoothModule
* MobaExternalModule returns MobaBluetoothModule
* MobaBluetoothModule returns MobaBluetoothModule
*
* Constraint:
* (name=ID type=MobaBlueToothModuleType ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*)
*/
protected void sequence_MobaBluetoothModule_MobaFriendsAble(ISerializationContext context, MobaBluetoothModule semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaCache
* MobaCache returns MobaCache
*
* Constraint:
* (
* name=ID
* (
* cacheTypeString=STRING |
* cacheTypeConst=[MobaConstant|CONSTANT] |
* cacheStrategyString=STRING |
* cacheStrategyConst=[MobaConstant|CONSTANT] |
* cacheIntervalInt=INT |
* cacheIntervalConst=[MobaConstant|CONSTANT] |
* cachePersistence=[MobaPersistenceType|CONSTANT]
* )*
* )
*/
protected void sequence_MobaCache(ISerializationContext context, MobaCache semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaConstantValue returns MobaConstantValue
*
* Constraint:
* (
* (valueString=STRING | valueInt=INT | valueDouble=DOUBLE | (valueConst=[MobaConstant|CONSTANT] valueConstFunctions+=MobaConstantValueFunction*))
* tail=MobaConstantValue?
* )
*/
protected void sequence_MobaConstantValue(ISerializationContext context, MobaConstantValue semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaConstant
* MobaConstant returns MobaConstant
*
* Constraint:
* (name=CONSTANT valueAST=MobaConstantValue ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*)
*/
protected void sequence_MobaConstant_MobaFriendsAble(ISerializationContext context, MobaConstant semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaDataType
* MobaDataType returns MobaDataType
*
* Constraint:
* (
* name=ID
* superType=[MobaDataType|ID]?
* (
* (array?='isArray' | enumAST=MobaEnum | predefined?='isPredefined')?
* (string?='isString' primitive?='isPrimitive'?)?
* (bool?='isBool' primitive?='isPrimitive'?)?
* (numeric?='isNumeric' primitive?='isPrimitive'?)?
* (decimal?='isDecimal' primitive?='isPrimitive'?)?
* (constraints+=MobaConstraint constraints+=MobaConstraint*)?
* ((date?='isDate' | time?='isTime' | timestamp?='isTimestamp') (dateFormatString=STRING | dateFormatConst=[MobaConstant|CONSTANT])?)?
* )+
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* )
*/
protected void sequence_MobaDataType_MobaFriendsAble(ISerializationContext context, MobaDataType semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaDeviceStartupTrigger
* MobaTrigger returns MobaDeviceStartupTrigger
* MobaDeviceStartupTrigger returns MobaDeviceStartupTrigger
*
* Constraint:
* name=ID
*/
protected void sequence_MobaDeviceStartupTrigger(ISerializationContext context, MobaDeviceStartupTrigger semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getMobaDeviceStartupTriggerAccess().getNameIDTerminalRuleCall_1_0(), semanticObject.getName());
feeder.finish();
}
/**
* Contexts:
* MobaConstraint returns MobaDigitsConstraint
* MobaDigitsConstraint returns MobaDigitsConstraint
*
* Constraint:
* ((filterIntegerValue=INT | filterIntegerConst=[MobaConstant|CONSTANT]) (filterFractionValue=INT | filterFractionConst=[MobaConstant|CONSTANT]))
*/
protected void sequence_MobaDigitsConstraint(ISerializationContext context, MobaDigitsConstraint semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaDtoFeature returns MobaDtoAttribute
* MobaDtoAttribute returns MobaDtoAttribute
*
* Constraint:
* (
* (
* (lazy?='lazy' | transient?='transient' | domainKey?='domainKey' | domainDescription?='domainDescription')?
* (constraints+=MobaConstraint constraints+=MobaConstraint*)?
* )+
* type=[MobaDataType|ID]
* multiplicity=MobaMuliplicity?
* name=ID
* (alias=ID | formatString=STRING | formatConst=[MobaConstant|CONSTANT])*
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* )
*/
protected void sequence_MobaDtoAttribute_MobaFriendsAble_MobaMultiplicityAble(ISerializationContext context, MobaDtoAttribute semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaDtoFeature returns MobaDtoEmbeddable
* MobaDtoEmbeddable returns MobaDtoEmbeddable
*
* Constraint:
* (
* transient?='transient'?
* type=[MobaDto|ID]
* multiplicity=MobaMuliplicity?
* name=ID
* alias=ID?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* )
*/
protected void sequence_MobaDtoEmbeddable_MobaFriendsAble_MobaMultiplicityAble(ISerializationContext context, MobaDtoEmbeddable semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaDtoFeature returns MobaDtoReference
* MobaDtoReference returns MobaDtoReference
*
* Constraint:
* (
* (cascading?='cascading' | lazy?='lazy' | transient?='transient')*
* type=[MobaDto|ID]
* multiplicity=MobaMuliplicity?
* name=ID
* alias=ID?
* opposite=[MobaDtoReference|ID]?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* )
*/
protected void sequence_MobaDtoReference_MobaFriendsAble_MobaMultiplicityAble(ISerializationContext context, MobaDtoReference semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaDto
* MobaData returns MobaDto
* MobaDto returns MobaDto
*
* Constraint:
* (
* name=ID
* superType=[MobaDto|ID]?
* wrappedEntity=[MobaEntity|ID]?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* features+=MobaDtoFeature*
* )
*/
protected void sequence_MobaDto_MobaFriendsAble(ISerializationContext context, MobaDto semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaEmailTrigger
* MobaTrigger returns MobaEmailTrigger
* MobaEmailTrigger returns MobaEmailTrigger
*
* Constraint:
* name=ID
*/
protected void sequence_MobaEmailTrigger(ISerializationContext context, MobaEmailTrigger semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getMobaEmailTriggerAccess().getNameIDTerminalRuleCall_1_0(), semanticObject.getName());
feeder.finish();
}
/**
* Contexts:
* MobaEntityFeature returns MobaEntityAttribute
* MobaEntityAttribute returns MobaEntityAttribute
*
* Constraint:
* (
* (
* (lazy?='lazy' | transient?='transient' | domainKey?='domainKey' | domainDescription?='domainDescription')?
* (constraints+=MobaConstraint constraints+=MobaConstraint*)?
* )+
* type=[MobaDataType|ID]
* multiplicity=MobaMuliplicity?
* name=ID
* (formatString=STRING | formatConst=[MobaConstant|CONSTANT])?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* )
*/
protected void sequence_MobaEntityAttribute_MobaFriendsAble_MobaMultiplicityAble(ISerializationContext context, MobaEntityAttribute semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaEntityFeature returns MobaEntityEmbeddable
* MobaEntityEmbeddable returns MobaEntityEmbeddable
*
* Constraint:
* (
* transient?='transient'?
* type=[MobaEntity|ID]
* multiplicity=MobaMuliplicity?
* name=ID
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* )
*/
protected void sequence_MobaEntityEmbeddable_MobaFriendsAble_MobaMultiplicityAble(ISerializationContext context, MobaEntityEmbeddable semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaEntityIndex returns MobaEntityIndex
*
* Constraint:
* (unique?='unique'? name=ID attributes+=[MobaEntityAttribute|ID] attributes+=[MobaEntityAttribute|ID]*)
*/
protected void sequence_MobaEntityIndex(ISerializationContext context, MobaEntityIndex semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaEntityFeature returns MobaEntityReference
* MobaEntityReference returns MobaEntityReference
*
* Constraint:
* (
* (cascading?='cascading' | lazy?='lazy' | transient?='transient')*
* type=[MobaEntity|ID]
* multiplicity=MobaMuliplicity?
* name=ID
* opposite=[MobaEntityReference|ID]?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* )
*/
protected void sequence_MobaEntityReference_MobaFriendsAble_MobaMultiplicityAble(ISerializationContext context, MobaEntityReference semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaEntity
* MobaData returns MobaEntity
* MobaEntity returns MobaEntity
*
* Constraint:
* (
* name=ID
* (superType=[MobaEntity|ID] | cache=[MobaCache|ID])*
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* features+=MobaEntityFeature*
* indizes+=MobaEntityIndex*
* )
*/
protected void sequence_MobaEntity_MobaFriendsAble(ISerializationContext context, MobaEntity semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaEnumLiteral returns MobaEnumLiteral
*
* Constraint:
* (name=CONSTANT literal=STRING value=INT (default?='isDefault' | undefined?='isUndefined' | hidden?='isHidden')*)
*/
protected void sequence_MobaEnumLiteral(ISerializationContext context, MobaEnumLiteral semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaEnum returns MobaEnum
*
* Constraint:
* literals+=MobaEnumLiteral*
*/
protected void sequence_MobaEnum(ISerializationContext context, MobaEnum semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaFriend returns MobaFriend
*
* Constraint:
* (valueString=STRING | valueConst=[MobaConstant|CONSTANT])
*/
protected void sequence_MobaFriend(ISerializationContext context, MobaFriend semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaSettingsFeature returns MobaSettingsAttribute
* MobaSettingsAttribute returns MobaSettingsAttribute
*
* Constraint:
* (
* (
* (lazy?='lazy' | transient?='transient' | domainKey?='domainKey' | domainDescription?='domainDescription')?
* (constraints+=MobaConstraint constraints+=MobaConstraint*)?
* )+
* type=[MobaDataType|ID]
* multiplicity=MobaMuliplicity?
* name=ID
* (formatString=STRING | formatConst=[MobaConstant|CONSTANT])?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* )
*/
protected void sequence_MobaFriendsAble_MobaMultiplicityAble_MobaSettingsAttribute(ISerializationContext context, MobaSettingsAttribute semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaSettingsFeature returns MobaSettingsEntityReference
* MobaSettingsEntityReference returns MobaSettingsEntityReference
*
* Constraint:
* (
* (cascading?='cascading' | lazy?='lazy' | transient?='transient')*
* type=[MobaEntity|ID]
* multiplicity=MobaMuliplicity?
* name=ID
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* )
*/
protected void sequence_MobaFriendsAble_MobaMultiplicityAble_MobaSettingsEntityReference(ISerializationContext context, MobaSettingsEntityReference semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaNFCModule
* MobaExternalModule returns MobaNFCModule
* MobaNFCModule returns MobaNFCModule
*
* Constraint:
* (name=ID type=MobaNFCModuleType ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*)
*/
protected void sequence_MobaFriendsAble_MobaNFCModule(ISerializationContext context, MobaNFCModule semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaPersistenceType
* MobaPersistenceType returns MobaPersistenceType
*
* Constraint:
* (name=CONSTANT ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*)
*/
protected void sequence_MobaFriendsAble_MobaPersistenceType(ISerializationContext context, MobaPersistenceType semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaModelFeature returns MobaProject
* MobaProject returns MobaProject
*
* Constraint:
* (
* name=ID
* version=VERSION
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* (uiApplication=[MobaApplication|ID] | backgroundApplication=[MobaApplication|ID])*
* )
*/
protected void sequence_MobaFriendsAble_MobaProject(ISerializationContext context, MobaProject semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaPushModule
* MobaExternalModule returns MobaPushModule
* MobaPushModule returns MobaPushModule
*
* Constraint:
* (name=ID ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*)
*/
protected void sequence_MobaFriendsAble_MobaPushModule(ISerializationContext context, MobaPushModule semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaQueueFeature returns MobaQueueReference
* MobaQueueReference returns MobaQueueReference
*
* Constraint:
* (restService=[MobaREST|ID] name=ID ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*)
*/
protected void sequence_MobaFriendsAble_MobaQueueReference(ISerializationContext context, MobaQueueReference semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaQueue
* MobaData returns MobaQueue
* MobaQueue returns MobaQueue
*
* Constraint:
* (
* name=ID
* superType=[MobaQueue|ID]?
* cache=[MobaCache|ID]?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* features+=MobaQueueFeature*
* )
*/
protected void sequence_MobaFriendsAble_MobaQueue(ISerializationContext context, MobaQueue semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaRESTCrud
* MobaREST returns MobaRESTCrud
* MobaRESTCrud returns MobaRESTCrud
*
* Constraint:
* (name=ID superType=[MobaRESTCrud|ID]? ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*)
*/
protected void sequence_MobaFriendsAble_MobaRESTCrud(ISerializationContext context, MobaRESTCrud semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaRESTCustomService
* MobaREST returns MobaRESTCustomService
* MobaRESTCustomService returns MobaRESTCustomService
*
* Constraint:
* (
* bigData?='bigData'?
* name=ID
* superType=[MobaRESTCustomService|ID]?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* (
* path=STRING |
* headers+=MobaRestHeader |
* parameters+=MobaRESTAbstractAttribute |
* multipartParameters+=MobaRESTAbstractMultipartAttribute |
* authorization=[MobaAuthorization|CONSTANT] |
* requestDto=MobaRESTPayloadDefinition |
* responseDto=MobaRESTPayloadDefinition |
* errorDto=MobaRESTPayloadDefinition |
* contextDto=MobaRESTPayloadDefinition |
* operation=MobaRESTMethods
* )*
* )
*/
protected void sequence_MobaFriendsAble_MobaRESTCustomService(ISerializationContext context, MobaRESTCustomService semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaRESTWorkflow
* MobaREST returns MobaRESTWorkflow
* MobaRESTWorkflow returns MobaRESTWorkflow
*
* Constraint:
* (
* name=ID
* superType=[MobaRESTWorkflow|ID]?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* services+=[MobaREST|ID]*
* )
*/
protected void sequence_MobaFriendsAble_MobaRESTWorkflow(ISerializationContext context, MobaRESTWorkflow semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaServer
* MobaServer returns MobaServer
*
* Constraint:
* (
* name=ID
* (urlString=STRING | urlConst=[MobaConstant|CONSTANT])
* superType=[MobaServer|ID]?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* (authorization=[MobaAuthorization|CONSTANT]? (services+=[MobaREST|ID] services+=[MobaREST|ID]*)?)+
* )
*/
protected void sequence_MobaFriendsAble_MobaServer(ISerializationContext context, MobaServer semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaSettings
* MobaSettings returns MobaSettings
*
* Constraint:
* (
* active?='active'?
* name=ID
* superType=[MobaSettings|ID]?
* ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*
* features+=MobaSettingsFeature*
* )
*/
protected void sequence_MobaFriendsAble_MobaSettings(ISerializationContext context, MobaSettings semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaTransportSerializationType
* MobaTransportSerializationType returns MobaTransportSerializationType
*
* Constraint:
* (name=CONSTANT ((friends+=MobaFriend friends+=MobaFriend*) | (properties+=MobaProperty properties+=MobaProperty*))*)
*/
protected void sequence_MobaFriendsAble_MobaTransportSerializationType(ISerializationContext context, MobaTransportSerializationType semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaGeneratorFeature returns MobaGeneratorIDFeature
* MobaGeneratorIDFeature returns MobaGeneratorIDFeature
*
* Constraint:
* (generatorId=FQN generatorVersion=VERSION)
*/
protected void sequence_MobaGeneratorIDFeature(ISerializationContext context, MobaGeneratorIDFeature semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_GENERATOR_ID_FEATURE__GENERATOR_ID) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_GENERATOR_ID_FEATURE__GENERATOR_ID));
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_GENERATOR_ID_FEATURE__GENERATOR_VERSION) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_GENERATOR_ID_FEATURE__GENERATOR_VERSION));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getMobaGeneratorIDFeatureAccess().getGeneratorIdFQNTerminalRuleCall_1_0(), semanticObject.getGeneratorId());
feeder.accept(grammarAccess.getMobaGeneratorIDFeatureAccess().getGeneratorVersionVERSIONTerminalRuleCall_3_0(), semanticObject.getGeneratorVersion());
feeder.finish();
}
/**
* Contexts:
* MobaGeneratorFeature returns MobaGeneratorMixinFeature
* MobaGeneratorMixinFeature returns MobaGeneratorMixinFeature
*
* Constraint:
* generatorRef=[MobaGenerator|ID]
*/
protected void sequence_MobaGeneratorMixinFeature(ISerializationContext context, MobaGeneratorMixinFeature semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_GENERATOR_MIXIN_FEATURE__GENERATOR_REF) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_GENERATOR_MIXIN_FEATURE__GENERATOR_REF));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getMobaGeneratorMixinFeatureAccess().getGeneratorRefMobaGeneratorIDTerminalRuleCall_1_0_1(), semanticObject.getGeneratorRef());
feeder.finish();
}
/**
* Contexts:
* MobaApplicationFeature returns MobaGeneratorSlot
* MobaGeneratorSlot returns MobaGeneratorSlot
*
* Constraint:
* (name=ID type=STRING?)
*/
protected void sequence_MobaGeneratorSlot(ISerializationContext context, MobaGeneratorSlot semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaGenerator
* MobaGenerator returns MobaGenerator
*
* Constraint:
* (active?='active'? name=ID features+=MobaGeneratorFeature*)
*/
protected void sequence_MobaGenerator(ISerializationContext context, MobaGenerator semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaGeofenceTrigger
* MobaTrigger returns MobaGeofenceTrigger
* MobaGeofenceTrigger returns MobaGeofenceTrigger
*
* Constraint:
* (name=ID eventType=MobaGeofenceEvent)
*/
protected void sequence_MobaGeofenceTrigger(ISerializationContext context, MobaGeofenceTrigger semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME));
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_GEOFENCE_TRIGGER__EVENT_TYPE) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_GEOFENCE_TRIGGER__EVENT_TYPE));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getMobaGeofenceTriggerAccess().getNameIDTerminalRuleCall_1_0(), semanticObject.getName());
feeder.accept(grammarAccess.getMobaGeofenceTriggerAccess().getEventTypeMobaGeofenceEventEnumRuleCall_4_0(), semanticObject.getEventType());
feeder.finish();
}
/**
* Contexts:
* MobaConstraint returns MobaMaxConstraint
* MobaMaxConstraint returns MobaMaxConstraint
*
* Constraint:
* (filterValue=DOUBLE | filterConst=[MobaConstant|CONSTANT])
*/
protected void sequence_MobaMaxConstraint(ISerializationContext context, MobaMaxConstraint semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaConstraint returns MobaMaxLengthConstraint
* MobaMaxLengthConstraint returns MobaMaxLengthConstraint
*
* Constraint:
* (filterValue=INT | filterConst=[MobaConstant|CONSTANT])
*/
protected void sequence_MobaMaxLengthConstraint(ISerializationContext context, MobaMaxLengthConstraint semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaConstraint returns MobaMinConstraint
* MobaMinConstraint returns MobaMinConstraint
*
* Constraint:
* (filterValue=DOUBLE | filterConst=[MobaConstant|CONSTANT])
*/
protected void sequence_MobaMinConstraint(ISerializationContext context, MobaMinConstraint semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaConstraint returns MobaMinLengthConstraint
* MobaMinLengthConstraint returns MobaMinLengthConstraint
*
* Constraint:
* (filterValue=INT | filterConst=[MobaConstant|CONSTANT])
*/
protected void sequence_MobaMinLengthConstraint(ISerializationContext context, MobaMinLengthConstraint semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaModel returns MobaModel
*
* Constraint:
* ((copyright=STRING features+=MobaModelFeature+) | features+=MobaModelFeature+)?
*/
protected void sequence_MobaModel(ISerializationContext context, MobaModel semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaMuliplicity returns MobaMuliplicity
*
* Constraint:
* (lower=MobaLowerBound upper=MobaUpperBound?)
*/
protected void sequence_MobaMuliplicity(ISerializationContext context, MobaMuliplicity semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaConstraint returns MobaNotNullConstraint
* MobaNotNullConstraint returns MobaNotNullConstraint
*
* Constraint:
* {MobaNotNullConstraint}
*/
protected void sequence_MobaNotNullConstraint(ISerializationContext context, MobaNotNullConstraint semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaConstraint returns MobaNullConstraint
* MobaNullConstraint returns MobaNullConstraint
*
* Constraint:
* {MobaNullConstraint}
*/
protected void sequence_MobaNullConstraint(ISerializationContext context, MobaNullConstraint semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaProperty returns MobaProperty
*
* Constraint:
* ((keyString=STRING | keyConst=[MobaConstant|CONSTANT]) (valueString=STRING | valueConst=[MobaConstant|CONSTANT]))
*/
protected void sequence_MobaProperty(ISerializationContext context, MobaProperty semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaPushTrigger
* MobaTrigger returns MobaPushTrigger
* MobaPushTrigger returns MobaPushTrigger
*
* Constraint:
* name=ID
*/
protected void sequence_MobaPushTrigger(ISerializationContext context, MobaPushTrigger semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getMobaPushTriggerAccess().getNameIDTerminalRuleCall_1_0(), semanticObject.getName());
feeder.finish();
}
/**
* Contexts:
* MobaRESTAbstractAttribute returns MobaRESTAttribute
* MobaRESTAttribute returns MobaRESTAttribute
*
* Constraint:
* (
* type=[MobaDataType|ID]
* (keyString=ID | keyConst=[MobaConstant|CONSTANT])
* (aliasString=STRING | aliasConst=[MobaConstant|CONSTANT])?
* (valueString=STRING | valueInt=INT | valueDouble=DOUBLE | valueConst=[MobaConstant|CONSTANT])?
* )
*/
protected void sequence_MobaRESTAttribute(ISerializationContext context, MobaRESTAttribute semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaRESTAbstractAttribute returns MobaRESTDtoAttribute
* MobaRESTDtoAttribute returns MobaRESTDtoAttribute
*
* Constraint:
* (dtoFeature=[MobaDtoFeature|ID] (aliasString=STRING | aliasConst=[MobaConstant|CONSTANT])?)
*/
protected void sequence_MobaRESTDtoAttribute(ISerializationContext context, MobaRESTDtoAttribute semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaRESTAbstractMultipartAttribute returns MobaRESTAttribute
* MobaRESTMultipartAttribute returns MobaRESTAttribute
*
* Constraint:
* (
* attachment?='attachment'?
* type=[MobaDataType|ID]
* (keyString=ID | keyConst=[MobaConstant|CONSTANT])
* (aliasString=STRING | aliasConst=[MobaConstant|CONSTANT])?
* (valueString=STRING | valueInt=INT | valueDouble=DOUBLE | valueConst=[MobaConstant|CONSTANT])?
* )
*/
protected void sequence_MobaRESTMultipartAttribute(ISerializationContext context, MobaRESTAttribute semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaRESTAbstractMultipartAttribute returns MobaRESTDtoAttribute
* MobaRESTMultipartDtoAttribute returns MobaRESTDtoAttribute
*
* Constraint:
* (attachment?='attachment'? dtoFeature=[MobaDtoFeature|ID] (aliasString=STRING | aliasConst=[MobaConstant|CONSTANT])?)
*/
protected void sequence_MobaRESTMultipartDtoAttribute(ISerializationContext context, MobaRESTDtoAttribute semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaRESTPayloadDefinition returns MobaRESTPayloadDefinition
*
* Constraint:
* (dto=[MobaDto|ID] (array?='isArray' | serializationType=[MobaTransportSerializationType|CONSTANT])*)
*/
protected void sequence_MobaRESTPayloadDefinition(ISerializationContext context, MobaRESTPayloadDefinition semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaConstraint returns MobaRegexpConstraint
* MobaRegexpConstraint returns MobaRegexpConstraint
*
* Constraint:
* (filterString=STRING | filterConst=[MobaConstant|CONSTANT])
*/
protected void sequence_MobaRegexpConstraint(ISerializationContext context, MobaRegexpConstraint semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaRestHeader returns MobaRESTHeader
*
* Constraint:
* (
* (contentTypeHeader?='ContentTypeHeader' (keyString=STRING | keyConst=[MobaConstant|CONSTANT])) |
* (rawHeader?='RawHeader' (keyString=STRING | keyConst=[MobaConstant|CONSTANT]) (valueString=STRING | valueConst=[MobaConstant|CONSTANT]))
* )
*/
protected void sequence_MobaRestHeader(ISerializationContext context, MobaRESTHeader semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
/**
* Contexts:
* MobaApplicationFeature returns MobaSMSTrigger
* MobaTrigger returns MobaSMSTrigger
* MobaSMSTrigger returns MobaSMSTrigger
*
* Constraint:
* name=ID
*/
protected void sequence_MobaSMSTrigger(ISerializationContext context, MobaSMSTrigger semanticObject) {
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME) == ValueTransient.YES)
errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject, MobaPackage.Literals.MOBA_TRIGGER__NAME));
}
SequenceFeeder feeder = createSequencerFeeder(context, semanticObject);
feeder.accept(grammarAccess.getMobaSMSTriggerAccess().getNameIDTerminalRuleCall_1_0(), semanticObject.getName());
feeder.finish();
}
/**
* Contexts:
* MobaApplicationFeature returns MobaTemplate
* MobaTemplate returns MobaTemplate
*
* Constraint:
* (template=[MobaApplication|ID] | downloadTemplate=DOWNLOAD_TEMPLATE)
*/
protected void sequence_MobaTemplate(ISerializationContext context, MobaTemplate semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
}
| 38.840807
| 166
| 0.751121
|
be3ce7b24499ae3139e2c2a325bfc9aaa27aba15
| 2,314
|
package com.codineers.springopenapi.sample.complete;
import com.codineers.springopenapi.sample.complete.model.ResponseWrapper;
import com.codineers.springopenapi.sample.complete.model.User;
import com.codineers.springopenapi.sample.complete.model.UserId;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController("/complete")
public class CompleteRestController {
@PostMapping(
name = "createGroupUser",
path = {"/groups/{groupId}/users", "/users"},
headers = {"x-trace-id", "x-span-id"},
params = {"correlationId", "mustChangePassword"},
consumes = {"application/json", "application/xml"},
produces = {"application/json", "application/xml"}
)
@ResponseStatus(HttpStatus.CREATED)
public ResponseWrapper<UserId> createGroupUser(
@RequestBody(required = true) User user,
@PathVariable(name = "gid", required = true) String groupId,
@RequestParam(name = "mcp", required = false, defaultValue = "true") boolean mustChangePassword,
@RequestParam(name = "cid", required = true) String correlationId
) {
return null;
}
@PutMapping
public void completePutMapping() {
}
@DeleteMapping
public void completeDeleteMapping() {
}
@GetMapping(
name = "getGroupUser",
path = "/postMapping/groups/{groupId}/users/{userId}/",
produces = "application/json"
)
public String completeGetMapping() {
return "";
}
@PatchMapping
public void completePatchMapping() {
}
@RequestMapping
public String completeRequestMapping() {
return "";
}
}
| 34.537313
| 104
| 0.722126
|
9d57788c914d1114694f6c50fc5f4a7fa9e18d4a
| 467
|
package com.mindasoft;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableEurekaClient // Eureka Client 标识
@SpringBootApplication
public class SpringCloudEurekaClientProviderApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudEurekaClientProviderApplication.class, args);
}
}
| 31.133333
| 80
| 0.841542
|
9e071b277b2aab19e973c6a69f2874f0a8e4a3a2
| 1,294
|
package utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Iterator;
public class CassConn {
private static RoundRobin<Connection> connectionPool = new RoundRobin<Connection>();
private static Iterator<Connection> connections = connectionPool.iterator();
private static int _NUMBER_OF_CONNECTIONS_PER_NODE = 4;
public static void prepareConnections(int n, int c, String bench) {
try {
Class.forName("org.postgresql.Driver");
for (int i = 1; i <= n; i++)
for (int j = 0; j < _NUMBER_OF_CONNECTIONS_PER_NODE; j++) {
Connection connect = (Connection) DriverManager.getConnection("jdbc:postgresql://"
+ "n" + String.valueOf(i) + ":9042/" + bench, "postgres", "123");
connectionPool.add(connect);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection(String localAddr) {
Connection connect = null;
connect = connections.next();
// System.out.println("GET CONNECTION: " + connect.getClusterMetadata());
return connect;
}
public static void closeConnection(Connection connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| 28.755556
| 87
| 0.70711
|
7e8f1c52f3d658d87f8479fad4bf8399eeb38a80
| 843
|
package uk.ac.ebi.fgpt.zooma.exception;
/**
* An exception that is thrown whenever an attempt to load data into ZOOMA fails
*
* @author Tony Burdett
* @date 04/10/12
*/
public class ZoomaLoadingException extends Exception {
public ZoomaLoadingException() {
}
public ZoomaLoadingException(String message) {
super(message);
}
public ZoomaLoadingException(String message, Throwable cause) {
super(message, cause);
}
public ZoomaLoadingException(Throwable cause) {
super(cause);
}
public ZoomaLoadingException(String message,
Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 26.34375
| 80
| 0.625148
|
2c460254567b16b94558456bc181c78db2f117bf
| 10,022
|
package com.hedera.mirror.importer.parser.record.entity.sql;
/*-
*
* Hedera Mirror Node
*
* Copyright (C) 2019 - 2020 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.data.repository.CrudRepository;
import org.testcontainers.shaded.org.bouncycastle.util.Strings;
import com.hedera.mirror.importer.IntegrationTest;
import com.hedera.mirror.importer.domain.ContractResult;
import com.hedera.mirror.importer.domain.CryptoTransfer;
import com.hedera.mirror.importer.domain.FileData;
import com.hedera.mirror.importer.domain.LiveHash;
import com.hedera.mirror.importer.domain.NonFeeTransfer;
import com.hedera.mirror.importer.domain.RecordFile;
import com.hedera.mirror.importer.domain.TopicMessage;
import com.hedera.mirror.importer.domain.Transaction;
import com.hedera.mirror.importer.exception.DuplicateFileException;
import com.hedera.mirror.importer.parser.domain.StreamFileData;
import com.hedera.mirror.importer.repository.ContractResultRepository;
import com.hedera.mirror.importer.repository.CryptoTransferRepository;
import com.hedera.mirror.importer.repository.FileDataRepository;
import com.hedera.mirror.importer.repository.LiveHashRepository;
import com.hedera.mirror.importer.repository.NonFeeTransferRepository;
import com.hedera.mirror.importer.repository.RecordFileRepository;
import com.hedera.mirror.importer.repository.TopicMessageRepository;
import com.hedera.mirror.importer.repository.TransactionRepository;
public class SqlEntityListenerTest extends IntegrationTest {
@Resource
protected TransactionRepository transactionRepository;
@Resource
protected CryptoTransferRepository cryptoTransferRepository;
@Resource
protected NonFeeTransferRepository nonFeeTransferRepository;
@Resource
protected ContractResultRepository contractResultRepository;
@Resource
protected LiveHashRepository liveHashRepository;
@Resource
protected FileDataRepository fileDataRepository;
@Resource
protected TopicMessageRepository topicMessageRepository;
@Resource
protected RecordFileRepository recordFileRepository;
@Resource
protected SqlEntityListener sqlEntityListener;
@Resource
protected SqlProperties sqlProperties;
private String fileName;
@BeforeEach
final void beforeEach() {
fileName = UUID.randomUUID().toString();
sqlEntityListener.onStart(new StreamFileData(fileName, null));
}
void completeFileAndCommit() {
sqlEntityListener
.onEnd(new RecordFile(0L, 0L, null, fileName, 0L, 0L, UUID.randomUUID().toString(), "", 0));
}
@Test
void onCryptoTransferList() throws Exception {
// given
CryptoTransfer cryptoTransfer1 = new CryptoTransfer(1L, 1L, 0L, 1L);
CryptoTransfer cryptoTransfer2 = new CryptoTransfer(2L, -2L, 0L, 2L);
// when
sqlEntityListener.onCryptoTransfer(cryptoTransfer1);
sqlEntityListener.onCryptoTransfer(cryptoTransfer2);
completeFileAndCommit();
// then
assertEquals(2, cryptoTransferRepository.count());
assertExistsAndEquals(cryptoTransferRepository, cryptoTransfer1, 1L);
assertExistsAndEquals(cryptoTransferRepository, cryptoTransfer2, 2L);
}
@Test
void onNonFeeTransfer() throws Exception {
// given
NonFeeTransfer nonFeeTransfer1 = new NonFeeTransfer(1L, 1L, 0L, 1L);
NonFeeTransfer nonFeeTransfer2 = new NonFeeTransfer(2L, -2L, 0L, 2L);
// when
sqlEntityListener.onNonFeeTransfer(nonFeeTransfer1);
sqlEntityListener.onNonFeeTransfer(nonFeeTransfer2);
completeFileAndCommit();
// then
assertEquals(2, nonFeeTransferRepository.count());
assertExistsAndEquals(nonFeeTransferRepository, nonFeeTransfer1, 1L);
assertExistsAndEquals(nonFeeTransferRepository, nonFeeTransfer2, 2L);
}
@Test
void onTopicMessage() throws Exception {
// given
byte[] message = Strings.toByteArray("test message");
byte[] runningHash = Strings.toByteArray("running hash");
TopicMessage expectedTopicMessage = new TopicMessage(1L, message, 0, runningHash, 10L, 1001, 1);
// when
sqlEntityListener.onTopicMessage(expectedTopicMessage);
completeFileAndCommit();
// then
assertEquals(1, topicMessageRepository.count());
assertExistsAndEquals(topicMessageRepository, expectedTopicMessage, 1L);
}
@Test
void onFileData() throws Exception {
// given
FileData expectedFileData = new FileData(11L, Strings.toByteArray("file data"));
// when
sqlEntityListener.onFileData(expectedFileData);
completeFileAndCommit();
// then
assertEquals(1, fileDataRepository.count());
assertExistsAndEquals(fileDataRepository, expectedFileData, 11L);
}
@Test
void onContractResult() throws Exception {
// given
ContractResult expectedContractResult = new ContractResult(15L, Strings.toByteArray("function parameters"),
10000L, Strings.toByteArray("call result"), 10000L);
// when
sqlEntityListener.onContractResult(expectedContractResult);
completeFileAndCommit();
// then
assertEquals(1, contractResultRepository.count());
assertExistsAndEquals(contractResultRepository, expectedContractResult, 15L);
}
@Test
void onLiveHash() throws Exception {
// given
LiveHash expectedLiveHash = new LiveHash(20L, Strings.toByteArray("live hash"));
// when
sqlEntityListener.onLiveHash(expectedLiveHash);
completeFileAndCommit();
// then
assertEquals(1, liveHashRepository.count());
assertExistsAndEquals(liveHashRepository, expectedLiveHash, 20L);
}
@Test
void onTransaction() throws Exception {
// given
Transaction expectedTransaction = new Transaction(101L, 0L, Strings.toByteArray("memo"), 0, 0, 1L, 1L, 1L, null,
1L, 1L, 1L, Strings.toByteArray("transactionHash"), null);
// when
sqlEntityListener.onTransaction(expectedTransaction);
completeFileAndCommit();
// then
assertEquals(1, transactionRepository.count());
assertExistsAndEquals(transactionRepository, expectedTransaction, 101L);
}
// Test that on seeing 'batchSize' number of transactions, 'executeBatch()' is called for all PreparedStatements
// issued by the connection.
@Test
void batchSize() throws Exception {
// given
int batchSize = 10;
sqlProperties.setBatchSize(batchSize);
Connection connection = mock(Connection.class);
List<PreparedStatement> insertStatements = new ArrayList<>(); // tracks all PreparedStatements
when(connection.prepareStatement(any())).then(ignored -> {
PreparedStatement preparedStatement = mock(PreparedStatement.class);
when(preparedStatement.executeBatch()).thenReturn(new int[] {});
insertStatements.add(preparedStatement);
return preparedStatement;
});
DataSource dataSource = mock(DataSource.class);
when(dataSource.getConnection()).thenReturn(connection);
SqlEntityListener sqlEntityListener2 =
new SqlEntityListener(sqlProperties, dataSource, recordFileRepository);
sqlEntityListener2.onStart(new StreamFileData(UUID.randomUUID().toString(), null)); // setup connection
// when
for (int i = 0; i < batchSize; i++) {
sqlEntityListener2.onTransaction(mock(Transaction.class));
}
// then
for (PreparedStatement ps : insertStatements) {
verify(ps).executeBatch();
}
completeFileAndCommit(); // close connection
}
@Test
void onError() {
// when
sqlEntityListener.onNonFeeTransfer(new NonFeeTransfer(1L, 1L, 0L, 1L));
sqlEntityListener.onCryptoTransfer(new CryptoTransfer(2L, -2L, 0L, 2L));
sqlEntityListener.onError();
// then
assertEquals(0, nonFeeTransferRepository.count());
assertEquals(0, cryptoTransferRepository.count());
}
@Test
void onDuplicateFileReturnEmpty() {
// given: file processed once
completeFileAndCommit();
// when, then
assertThrows(DuplicateFileException.class, () -> {
sqlEntityListener.onStart(new StreamFileData(fileName, null));
});
sqlEntityListener.onError(); // close connection
}
// TODO: add test to check contents of recordFileRepo
static <T, ID> void assertExistsAndEquals(CrudRepository<T, ID> repository, T expected, ID id) throws Exception {
Optional<T> actual = repository.findById(id);
assertTrue(actual.isPresent());
assertEquals(expected, actual.get());
}
}
| 35.288732
| 120
| 0.709539
|
95ae94ed1e0e0f4640794bd8bb61caa19d5e8025
| 474
|
package com.google.api.client.http;
import com.google.api.client.util.Beta;
@Beta
public interface HttpBackOffUnsuccessfulResponseHandler$BackOffRequired {
HttpBackOffUnsuccessfulResponseHandler$BackOffRequired ALWAYS = new HttpBackOffUnsuccessfulResponseHandler$BackOffRequired$1();
HttpBackOffUnsuccessfulResponseHandler$BackOffRequired ON_SERVER_ERROR = new HttpBackOffUnsuccessfulResponseHandler$BackOffRequired$2();
boolean isRequired(HttpResponse var1);
}
| 39.5
| 139
| 0.85865
|
e983a0459b854a7ab0dd8f5caa5be99e38fb94d8
| 5,898
|
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.control.aggregator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import com.google.api.MetricDescriptor.MetricKind;
import com.google.api.control.model.Distributions;
import com.google.api.servicecontrol.v1.Distribution;
import com.google.api.servicecontrol.v1.MetricValue;
import com.google.api.servicecontrol.v1.MetricValue.Builder;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.protobuf.Timestamp;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.HashMap;
import java.util.Map;
/**
* Tests {@link MetricValues}
*/
@RunWith(JUnit4.class)
public class MetricValuesTests {
private static final double TOLERANCE = 1e-5;
private static final double A_DOUBLE_VALUE = 0.1;
private static final Timestamp EARLY = Timestamp.newBuilder().setNanos(1).setSeconds(100).build();
private static final Timestamp LATER = Timestamp.newBuilder().setNanos(2).setSeconds(100).build();
private static final Map<String, String> TEST_LABELS =
ImmutableMap.<String, String>of("key1", "value1", "key2", "value2");
private MetricValue testValue;
private MetricValue otherValue;
private MetricValue earlyEndingTestValue;
private MetricValue laterEndingTestValue;
@Before
public void setUpMetricValue() {
testValue =
MetricValue.newBuilder().putAllLabels(TEST_LABELS).setDoubleValue(A_DOUBLE_VALUE).build();
Builder fromTestValue = testValue.toBuilder();
earlyEndingTestValue = fromTestValue.setEndTime(EARLY).build();
laterEndingTestValue = fromTestValue.setEndTime(LATER).build();
otherValue =
MetricValue.newBuilder().setDoubleValue(A_DOUBLE_VALUE).putAllLabels(TEST_LABELS).build();
}
@Test
public void putMetricValueShouldUpdateHashesConsistently() {
HashFunction hf = Hashing.md5();
Hasher hasher1 = hf.newHasher();
Hasher hasher2 = hf.newHasher();
HashCode hash1 = MetricValues.putMetricValue(hasher1, testValue).hash();
HashCode hash2 = MetricValues.putMetricValue(hasher2, otherValue).hash();
assertEquals(hash1, hash2);
}
@Test
public void signShouldProduceConsistentHashCodes() {
assertEquals(MetricValues.sign(testValue), MetricValues.sign(otherValue));
}
@Test
public void mergeOfNonDeltaKindsShouldReturnMetricWithLatestEndtime() {
MetricKind[] nonDeltas =
new MetricKind[] {MetricKind.CUMULATIVE, MetricKind.GAUGE, MetricKind.UNRECOGNIZED};
for (MetricKind kind : nonDeltas) {
assertEquals(MetricValues.merge(kind, earlyEndingTestValue, laterEndingTestValue),
laterEndingTestValue);
assertEquals(MetricValues.merge(kind, laterEndingTestValue, earlyEndingTestValue),
laterEndingTestValue);
}
}
@Test
public void mergeShouldFailForMetricsWithDifferentTypesOfValues() {
MetricValue withChangedType = testValue.toBuilder().setInt64Value(1L).build();
MetricKind[] testKinds =
new MetricKind[] {MetricKind.CUMULATIVE, MetricKind.GAUGE, MetricKind.UNRECOGNIZED, MetricKind.DELTA};
for (MetricKind kind : testKinds) {
try {
MetricValues.merge(kind, testValue, withChangedType);
fail("Should have raised IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
}
@Test
public void mergeShouldFailForDeltaMetricsWithUnmergableTypes() {
MetricValue withBooleanType = testValue.toBuilder().setBoolValue(true).build();
MetricValue withStringType = testValue.toBuilder().setStringValue("test").build();
MetricValue withNoneSet = testValue.toBuilder().clearDoubleValue().build();
MetricValue[] unmergeables = new MetricValue[] {
withBooleanType,
withStringType,
withNoneSet
};
for (MetricValue mv : unmergeables) {
try {
MetricValues.merge(MetricKind.DELTA, mv, mv);
fail("Should have raised IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
}
@Test
public void mergeShouldSucceedForDeltaMetricsOfTheDoubleType() {
MetricValue merged = MetricValues.merge(MetricKind.DELTA, testValue, testValue);
assertEquals(merged.getDoubleValue(), 2 * testValue.getDoubleValue(), TOLERANCE);
}
@Test
public void mergeShouldSucceedForDeltaMetricsOfTheInt64Type() {
MetricValue withInt64 = testValue.toBuilder().setInt64Value(1L).build();
MetricValue merged = MetricValues.merge(MetricKind.DELTA, withInt64, withInt64);
assertEquals(merged.getInt64Value(), 2 * withInt64.getInt64Value());
}
@Test
public void mergeShouldSucceedForDeltaMetricsOfTheDistributionType() {
Distribution d = Distributions.createExplicit(new double[] {0.1, 0.3, 0.5});
Distributions.addSample(0.4, d);
MetricValue withDistribution = testValue.toBuilder().setDistributionValue(d).build();
MetricValue merged = MetricValues.merge(MetricKind.DELTA, withDistribution, withDistribution);
assertEquals(merged.getDistributionValue().getCount(), 2 * d.getCount());
}
}
| 38.298701
| 110
| 0.747202
|
56a3f0ae5af34b71baa78b71f44bc7292dd4b36a
| 3,380
|
/*
* #%L
* fujion
* %%
* Copyright (C) 2021 Fujion Framework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* #L%
*/
package org.fujion.component;
import org.fujion.annotation.Component.PropertyGetter;
import org.fujion.annotation.Component.PropertySetter;
import org.springframework.util.NumberUtils;
import org.springframework.util.StringUtils;
/**
* The base class for input box components that support the entry of numeric values.
*
* @param <T> The type of numeric value supported.
*/
public abstract class BaseNumberboxComponent<T extends Number> extends BaseInputboxComponent<T> {
private final Class<T> clazz;
private T step;
protected BaseNumberboxComponent(Class<T> clazz) {
this.clazz = clazz;
}
@Override
@PropertyGetter(value = "synchronized", description = "A true value means that the client will notify the server "
+ "as the value of the input box changes. A false value means that the client will notify "
+ "server of the new value only when the input element loses focus.")
public boolean getSynchronized() {
return super.getSynchronized();
}
@Override
@PropertySetter(value = "synchronized", defaultValue = "false", description = "A true value means that the client will notify the server "
+ "as the value of the input box changes. A false value means that the client will notify "
+ "server of the new value only when the input element loses focus.")
public void setSynchronized(boolean synchronize) {
super.setSynchronized(synchronize);
}
/**
* Gets the step value. If non-zero, a spinner will appear within the input element.
*
* @return The step value. Null or zero disables the step function.
*/
@PropertyGetter(value = "step", description = "The increment or decrement when the spinner element is clicked.")
public T getStep() {
return step;
}
@PropertySetter(value = "step", description = "The increment or decrement when the spinner element is clicked.")
private void _setStep(String step) {
setStep(_toValue(step));
}
/**
* Sets the step value. If non-zero, a spinner will appear within the input element.
*
* @param step The step value. Null or zero disables the step function.
*/
public void setStep(T step) {
if (propertyChange("step", this.step, this.step = step, false)) {
sync("step", _toString(step));
}
}
@Override
protected String _toString(T value) {
return value == null ? null : value.toString();
}
@Override
protected T _toValue(String value) {
value = value == null ? "" : StringUtils.trimAllWhitespace(value);
return value.isEmpty() ? null : NumberUtils.parseNumber(value, clazz);
}
}
| 34.845361
| 142
| 0.676331
|
b2ab6124c3952b41026cb31d40c1e9b47c155dbf
| 1,081
|
package com.charleskelly.magic.puzzles.sudoku.pairs;
import com.charleskelly.magic.puzzles.cubes.MagicCube;
import com.charleskelly.magic.tuple.coordinates.CellCoordinates;
/**
* Created by Charles on 9/27/2016.
*/
public class SudokuCoordinatesContentsPair
{
private CellCoordinates cellCoordinates;
private MagicCube magicCube;
/**
* @throws Exception if any input parameter is null
*/
public SudokuCoordinatesContentsPair(CellCoordinates cellCoordinates, MagicCube magicCube) throws Exception
{
super(); // auto-generated
if (null == cellCoordinates)
throw new Exception ("cellCoordinates parameter is null");
if (null == magicCube)
throw new Exception ("hyperSquare parameter is null");
this.magicCube = magicCube;
this.cellCoordinates = cellCoordinates;
}
public CellCoordinates getCellCoordinates()
{
return cellCoordinates;
}
public MagicCube getMagicCube()
{
return magicCube;
}
}
| 27.025
| 112
| 0.66235
|
32092f89c2a1f798da726aea103405a0271060c4
| 1,128
|
package ${package};
import java.util.List;
#if ($mode == "server")
import java.util.UUID;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;
#end
#if ($mode == "client")
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
#end
import com.graphql_java_generator.annotation.GraphQLNonScalar;
import com.graphql_java_generator.annotation.GraphQLScalar;
/**
* @author generated by graphql-java-generator
* @see <a href="https://github.com/graphql-java-generator/graphql-java-generator">https://github.com/graphql-java-generator/graphql-java-generator</a>
*/
public interface ${object.name} #if($object.implementz.size()>0)implements #foreach($impl in $object.implementz)$impl#if($foreach.hasNext), #end#end#end {
#foreach ($field in $object.fields)
${field.annotation}
public void set${field.pascalCaseName}(#if(${field.list})List<#end${field.type.classSimpleName}#if(${field.list})>#end ${field.name});
${field.annotation}
public #if(${field.list})List<#end${field.type.classSimpleName}#if(${field.list})>#end get${field.pascalCaseName}();
#end
}
| 33.176471
| 154
| 0.753546
|
1a55e3bebcd1ca1c92e26dd693b7c846cb18aa99
| 3,285
|
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.dao;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Tests {@link Customer}.
*/
public class CustomerTest {
private Customer customer;
private static final int ID = 1;
private static final String FIRSTNAME = "Winston";
private static final String LASTNAME = "Churchill";
@BeforeEach
public void setUp() {
customer = new Customer(ID, FIRSTNAME, LASTNAME);
}
@Test
public void getAndSetId() {
final int newId = 2;
customer.setId(newId);
assertEquals(newId, customer.getId());
}
@Test
public void getAndSetFirstname() {
final String newFirstname = "Bill";
customer.setFirstName(newFirstname);
assertEquals(newFirstname, customer.getFirstName());
}
@Test
public void getAndSetLastname() {
final String newLastname = "Clinton";
customer.setLastName(newLastname);
assertEquals(newLastname, customer.getLastName());
}
@Test
public void notEqualWithDifferentId() {
final int newId = 2;
final Customer otherCustomer = new Customer(newId, FIRSTNAME, LASTNAME);
assertNotEquals(customer, otherCustomer);
assertNotEquals(customer.hashCode(), otherCustomer.hashCode());
}
@Test
public void equalsWithSameObjectValues() {
final Customer otherCustomer = new Customer(ID, FIRSTNAME, LASTNAME);
assertEquals(customer, otherCustomer);
assertEquals(customer.hashCode(), otherCustomer.hashCode());
}
@Test
public void equalsWithSameObjects() {
assertEquals(customer, customer);
assertEquals(customer.hashCode(), customer.hashCode());
}
@Test
public void testToString() {
final StringBuffer buffer = new StringBuffer();
buffer.append("Customer{id=")
.append("" + customer.getId())
.append(", firstName='")
.append(customer.getFirstName())
.append("\', lastName='")
.append(customer.getLastName() + "\'}");
assertEquals(buffer.toString(), customer.toString());
}
}
| 32.524752
| 80
| 0.716591
|
dd8e733ec416a04e36d80364d3098ee3599f2298
| 6,732
|
package depspace.extension;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import bftsmart.tom.core.messages.TOMMessageType;
import depspace.general.Context;
import depspace.general.DepSpaceException;
import depspace.general.DepSpaceOperation;
import depspace.general.DepTuple;
import depspace.server.DepSpaceEventHandler;
import depspace.server.DepSpaceManager;
public class EDSExtensionManager extends DepSpaceManager implements EDSExtensionGate, DepSpaceEventHandler {
public static final String EXTENSION_MANAGER_TUPLE_SPACE_NAME = "EDS_SPACE";
private final Map<Integer, EDSExtension> extensions;
private final DepSpaceEventHandler defaultEventHandler;
private final EDSBuiltInExtension builtInExtension;
private Context currentContext;
public EDSExtensionManager(int processID, DepSpaceEventHandler eventHandler) {
super(processID, null);
this.extensions = new HashMap<Integer, EDSExtension>();
// Use the extension manager as a proxy event handler
this.defaultEventHandler = eventHandler;
setEventHandler(this);
// Register built-in extension
this.builtInExtension = new EDSBuiltInExtension();
builtInExtension.setExtensionGate(this);
extensions.put(0, builtInExtension);
}
@Override
public Object invokeOperation(String tsName, DepSpaceOperation operation, Object arg, Context ctx) throws DepSpaceException {
// Try to match subscriptions
int[] ids = new int[] { 0, ctx.session };
EDSExtension extension = null;
for(int id: ids) {
EDSExtension ext = extensions.get(id);
if(ext == null) continue;
if(ext.matchesOperation(tsName, operation, arg)) {
extension = ext;
break;
}
}
if(extension == null) return super.invokeOperation(tsName, operation, arg, ctx);
// Execute extension
currentContext = ctx;
try {
return extension.handleOperation(tsName, operation, arg, ctx);
} catch(NoClassDefFoundError ncdfe) {
ncdfe.printStackTrace();
throw new DepSpaceException(ncdfe.getCause().getMessage());
}
}
// ##################
// # EVENT HANDLING #
// ##################
@Override
public void handleEvent(DepSpaceOperation operation, DepTuple tuple, Context ctx) {
// Execute extension if it matches
EDSExtension extension = extensions.get(ctx.session);
if((extension != null) && extension.matchesEvent(ctx.tsName, operation, tuple)) {
// Ensure that the current timestamp is used during event handling
ctx.updateTime(currentContext.time);
try {
Context savedContext = currentContext;
currentContext = ctx;
boolean handled = extension.handleEvent(ctx.tsName, operation, tuple, ctx);
currentContext = savedContext;
if(handled) return;
} catch(DepSpaceException dse) {
System.err.println(dse);
// Fall back to default event handler
} catch(NoClassDefFoundError ncdfe) {
ncdfe.printStackTrace();
// Fall back to default event handler
}
}
// Use default event handler
defaultEventHandler.handleEvent(operation, tuple, ctx);
}
// ##########################
// # EXTENSION REGISTRATION #
// ##########################
public EDSExtension registerExtension(String extensionName, String extensionCode, int sessionID) throws DepSpaceException {
// Compile extension
EDSExtensionCompiler extensionCompiler = new EDSExtensionCompiler(extensionName, extensionCode);
byte[] extensionBinary = extensionCompiler.compileExtension();
// Load extension
EDSExtensionLoader extensionLoader = new EDSExtensionLoader(extensionName, extensionBinary);
EDSExtension extension = extensionLoader.loadExtension();
extension.setExtensionGate(this);
// Register extension
extensions.put(sessionID, extension);
return extension;
}
// ##################
// # EXTENSION GATE #
// ##################
private Object extensionGateInvoke(DepSpaceOperation operation, Object arg) throws DepSpaceException {
// Ensure that unordered requests do not perform modifying operations
if((operation.getRequestType() == TOMMessageType.ORDERED_REQUEST) && (currentContext.requestType == TOMMessageType.UNORDERED_REQUEST)) {
throw new DepSpaceException("Unordered requests must not perform modifying operations!");
}
/***** Implement additional extension policies here *****/
// Invoke upper layer
return super.invokeOperation(currentContext.tsName, operation, arg, currentContext);
}
@Override
public void out(DepTuple tuple) throws DepSpaceException {
extensionGateInvoke(DepSpaceOperation.OUT, tuple);
}
@Override
public void outAll(List<DepTuple> tuplesBag) throws DepSpaceException {
extensionGateInvoke(DepSpaceOperation.OUTALL, tuplesBag);
}
@Override
public DepTuple renew(DepTuple template) throws DepSpaceException {
return (DepTuple) extensionGateInvoke(DepSpaceOperation.RENEW, template);
}
@Override
public DepTuple rdp(DepTuple template) throws DepSpaceException {
return (DepTuple) extensionGateInvoke(DepSpaceOperation.RDP, template);
}
@Override
public DepTuple inp(DepTuple template) throws DepSpaceException {
return (DepTuple) extensionGateInvoke(DepSpaceOperation.INP, template);
}
@Override
public DepTuple rd(DepTuple template) throws DepSpaceException {
return (DepTuple) extensionGateInvoke(DepSpaceOperation.RD, template);
}
@Override
public DepTuple in(DepTuple template) throws DepSpaceException {
return (DepTuple) extensionGateInvoke(DepSpaceOperation.IN, template);
}
@Override
public DepTuple cas(DepTuple template, DepTuple tuple) throws DepSpaceException {
return (DepTuple) extensionGateInvoke(DepSpaceOperation.CAS, new DepTuple[] { template, tuple });
}
@Override
public DepTuple replace(DepTuple template, DepTuple tuple) throws DepSpaceException {
return (DepTuple) extensionGateInvoke(DepSpaceOperation.REPLACE, new DepTuple[] { template, tuple });
}
@SuppressWarnings("unchecked")
@Override
public Collection<DepTuple> rdAll(DepTuple template) throws DepSpaceException {
return (Collection<DepTuple>) extensionGateInvoke(DepSpaceOperation.RDALL, template);
}
@SuppressWarnings("unchecked")
@Override
public Collection<DepTuple> rdAll() throws DepSpaceException {
return (Collection<DepTuple>) extensionGateInvoke(DepSpaceOperation.RDALL, null);
}
@SuppressWarnings("unchecked")
@Override
public Collection<DepTuple> inAll(DepTuple template) throws DepSpaceException {
return (Collection<DepTuple>) extensionGateInvoke(DepSpaceOperation.INALL, template);
}
// #######################
// # SAFE HELPER METHODS #
// #######################
@Override
public void error(String message) throws DepSpaceException {
throw new DepSpaceException(message);
}
}
| 31.905213
| 138
| 0.748515
|
3bf2228204714226867bdda1390fbc4a1fbeb630
| 753
|
package Chapter03.P70_FindFirstAndLastDayOfMonth.src.modern.challenge;
import java.time.DayOfWeek;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
public class NextSaturdayAdjuster implements TemporalAdjuster {
@Override
public Temporal adjustInto(Temporal temporal) {
DayOfWeek dayOfWeek = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK));
if (dayOfWeek == DayOfWeek.SATURDAY) {
return temporal;
}
if (dayOfWeek == DayOfWeek.SUNDAY) {
return temporal.plus(6, ChronoUnit.DAYS);
}
return temporal.plus(6 - dayOfWeek.getValue(), ChronoUnit.DAYS);
}
}
| 26.892857
| 82
| 0.714475
|
4f3f11905924aefc52fdd854511a6d60d8cedb16
| 3,061
|
// 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.cloudstack.storage.datastore.api;
import org.apache.commons.lang3.StringUtils;
public class StoragePoolStatistics {
String maxCapacityInKb; // total capacity
String spareCapacityInKb; // spare capacity, space not used for volumes creation/allocation
String netCapacityInUseInKb; // user data capacity in use
String netUnusedCapacityInKb; // capacity available for volume creation (volume space to write)
public Long getMaxCapacityInKb() {
if (StringUtils.isEmpty(maxCapacityInKb)) {
return Long.valueOf(0);
}
return Long.valueOf(maxCapacityInKb);
}
public void setMaxCapacityInKb(String maxCapacityInKb) {
this.maxCapacityInKb = maxCapacityInKb;
}
public Long getSpareCapacityInKb() {
if (StringUtils.isEmpty(spareCapacityInKb)) {
return Long.valueOf(0);
}
return Long.valueOf(spareCapacityInKb);
}
public void setSpareCapacityInKb(String spareCapacityInKb) {
this.spareCapacityInKb = spareCapacityInKb;
}
public Long getNetCapacityInUseInKb() {
if (StringUtils.isEmpty(netCapacityInUseInKb)) {
return Long.valueOf(0);
}
return Long.valueOf(netCapacityInUseInKb);
}
public void setNetCapacityInUseInKb(String netCapacityInUseInKb) {
this.netCapacityInUseInKb = netCapacityInUseInKb;
}
public Long getNetUnusedCapacityInKb() {
if (StringUtils.isEmpty(netUnusedCapacityInKb)) {
return Long.valueOf(0);
}
return Long.valueOf(netUnusedCapacityInKb);
}
public Long getNetUnusedCapacityInBytes() {
return (getNetUnusedCapacityInKb() * 1024);
}
public void setNetUnusedCapacityInKb(String netUnusedCapacityInKb) {
this.netUnusedCapacityInKb = netUnusedCapacityInKb;
}
public Long getNetMaxCapacityInBytes() {
// total usable capacity = ("maxCapacityInKb" - "spareCapacityInKb") / 2
Long netMaxCapacityInKb = getMaxCapacityInKb() - getSpareCapacityInKb();
return ((netMaxCapacityInKb / 2) * 1024);
}
public Long getNetUsedCapacityInBytes() {
return (getNetMaxCapacityInBytes() - getNetUnusedCapacityInBytes());
}
}
| 35.593023
| 99
| 0.709245
|
acd261d9b2e7e14aaca763a44a4a37ce92fa4151
| 7,095
|
package tests.restapi.in_app_purchases;
import java.io.IOException;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.JSONException;
import org.apache.wink.json4j.JSONObject;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import tests.com.ibm.qautils.FileUtils;
import tests.restapi.AirlockUtils;
import tests.restapi.FeaturesRestApi;
import tests.restapi.InAppPurchasesRestApi;
import tests.restapi.ProductsRestApi;
public class DeletePurchaseIncludedInPurchase {
protected String seasonID;
protected String filePath;
protected ProductsRestApi p;
protected FeaturesRestApi f;
private AirlockUtils baseUtils;
protected String productID;
protected String m_url;
private String sessionToken = "";
protected InAppPurchasesRestApi purchasesApi;
protected String inAppPurID1;
protected String inAppPurID2;
protected String bundleID;
@BeforeClass
@Parameters({"url", "analyticsUrl", "translationsUrl", "configPath", "sessionToken", "userName", "userPassword", "appName", "productsToDeleteFile"})
public void init(String url, String analyticsUrl, String translationsUrl, String configPath, String sToken, String userName, String userPassword, String appName, String productsToDeleteFile) throws Exception{
m_url = url;
filePath = configPath;
f = new FeaturesRestApi();
f.setURL(m_url);
p = new ProductsRestApi();
p.setURL(m_url);
purchasesApi = new InAppPurchasesRestApi();
purchasesApi.setURL(m_url);
baseUtils = new AirlockUtils(url, analyticsUrl, translationsUrl, configPath, sToken, userName, userPassword, appName, productsToDeleteFile);
sessionToken = baseUtils.sessionToken;
productID = baseUtils.createProduct();
baseUtils.printProductToFile(productID);
seasonID = baseUtils.createSeason(productID);
}
@Test (description = "add 2 in-app-purchase one purchase including the 2")
public void addComponents() throws JSONException, IOException, InterruptedException{
String inAppPur = FileUtils.fileToString(filePath + "purchases/inAppPurchase1.txt", "UTF-8", false);
inAppPurID1 = purchasesApi.addPurchaseItem(seasonID, inAppPur, "ROOT", sessionToken);
Assert.assertFalse (inAppPurID1.contains("error"), "Can't add inAppPurchase: " + inAppPurID1);
inAppPur = FileUtils.fileToString(filePath + "purchases/inAppPurchase2.txt", "UTF-8", false);
inAppPurID2 = purchasesApi.addPurchaseItem(seasonID, inAppPur, "ROOT", sessionToken);
Assert.assertFalse (inAppPurID2.contains("error"), "Can't add inAppPurchase: " + inAppPurID2);
String purchaseOptions = FileUtils.fileToString(filePath + "purchases/purchaseOptions1.txt", "UTF-8", false);
JSONObject jsonIP = new JSONObject(purchaseOptions);
jsonIP.put("name", RandomStringUtils.randomAlphabetic(5));
String puOptID = purchasesApi.addPurchaseItem(seasonID, jsonIP.toString(), inAppPurID1, sessionToken);
Assert.assertFalse (puOptID.contains("error"), "Can't add purchaseOptions: " + puOptID);
JSONArray includedPurchases = new JSONArray();
includedPurchases.add(inAppPurID1);
includedPurchases.add(inAppPurID2);
JSONObject iapObj = new JSONObject(inAppPur);
iapObj.put("name", "bundle");
iapObj.put("includedEntitlements", includedPurchases);
bundleID = purchasesApi.addPurchaseItem(seasonID, iapObj.toString(), "ROOT", sessionToken);
Assert.assertFalse (bundleID.contains("error"), "Can't add inAppPurchase: " + bundleID);
String bundleStr = purchasesApi.getPurchaseItem(bundleID, sessionToken);
JSONObject bundleObj = new JSONObject(bundleStr);
Assert.assertTrue(bundleObj.getJSONArray("includedEntitlements").size()==2, "wrong number of includedPurchases in bundle");
Assert.assertTrue(bundleObj.getJSONArray("includedEntitlements").get(0).equals(inAppPurID1), "wrong includedPurchase");
Assert.assertTrue(bundleObj.getJSONArray("includedEntitlements").get(1).equals(inAppPurID2), "wrong includedPurchase");
}
@Test (dependsOnMethods = "addComponents", description = "delete a purchase that is part of a bundle")
public void deletePurcahse() throws JSONException, IOException, InterruptedException{
int res = purchasesApi.deletePurchaseItem(inAppPurID1, sessionToken);
Assert.assertTrue(res != 200, "can delete inAppPurID1 even though part of bundle");
res = purchasesApi.deletePurchaseItem(inAppPurID2, sessionToken);
Assert.assertTrue(res != 200, "can delete inAppPurID2 even though part of bundle");
}
@Test (dependsOnMethods = "deletePurcahse", description = "update bundle - remove purchase 1")
public void updateBundle() throws JSONException, IOException, InterruptedException{
String bundle = purchasesApi.getPurchaseItem(bundleID, sessionToken);
JSONObject bundleJson = new JSONObject(bundle);
JSONArray includedPurchases = new JSONArray();
includedPurchases.add(inAppPurID2);
bundleJson.put("includedEntitlements", includedPurchases);
String response = purchasesApi.updatePurchaseItem(seasonID, bundleID, bundleJson.toString(), sessionToken);
Assert.assertFalse(response.contains("error"), "cannot update bundle: " + response);
String bundleStr = purchasesApi.getPurchaseItem(bundleID, sessionToken);
JSONObject bundleObj = new JSONObject(bundleStr);
Assert.assertTrue(bundleObj.getJSONArray("includedEntitlements").size()==1, "wrong number of includedPurchases in bundle");
Assert.assertTrue(bundleObj.getJSONArray("includedEntitlements").get(0).equals(inAppPurID2), "wrong includedPurchase");
}
@Test (dependsOnMethods = "updateBundle", description = "delete a purchase that is part of a bundle")
public void deletePurcahse2() throws JSONException, IOException, InterruptedException{
int res = purchasesApi.deletePurchaseItem(inAppPurID1, sessionToken);
Assert.assertTrue(res == 200, "cannot delete inAppPurID1 even though it is not a part of bundle anymore ");
res = purchasesApi.deletePurchaseItem(inAppPurID2, sessionToken);
Assert.assertTrue(res != 200, "can delete inAppPurID2 even though part of bundle");
}
@Test (dependsOnMethods = "deletePurcahse2", description = "delete a purchase bundle")
public void deleteBundle() throws JSONException, IOException, InterruptedException{
int res = purchasesApi.deletePurchaseItem(bundleID, sessionToken);
Assert.assertTrue(res == 200, "cannot delete bundle ");
}
@Test (dependsOnMethods = "deleteBundle", description = "delete a purchase that is part of a bundle")
public void deletePurcahse3() throws JSONException, IOException, InterruptedException{
int res = purchasesApi.deletePurchaseItem(inAppPurID2, sessionToken);
Assert.assertTrue(res == 200, "cannot delete inAppPurID2 even though it is not a part of bundle anymore ");
}
@AfterTest
private void reset(){
baseUtils.reset(productID, sessionToken);
}
}
| 49.270833
| 210
| 0.765891
|
1c38a9abcc398b75679022c12000e4cb965c2da2
| 12,817
|
/*
* Copyright (C) 2012-2015 DataStax 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.datastax.driver.core;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import java.util.*;
/**
* Base class for Tables and Materialized Views metadata.
*/
public abstract class AbstractTableMetadata {
static final Comparator<ColumnMetadata> columnMetadataComparator = new Comparator<ColumnMetadata>() {
@Override
public int compare(ColumnMetadata c1, ColumnMetadata c2) {
return c1.getName().compareTo(c2.getName());
}
};
static final Predicate<ClusteringOrder> isAscending = new Predicate<ClusteringOrder>() {
@Override
public boolean apply(ClusteringOrder o) {
return o == ClusteringOrder.ASC;
}
};
protected final KeyspaceMetadata keyspace;
protected final String name;
protected final UUID id;
protected final List<ColumnMetadata> partitionKey;
protected final List<ColumnMetadata> clusteringColumns;
protected final Map<String, ColumnMetadata> columns;
protected final TableOptionsMetadata options;
protected final List<ClusteringOrder> clusteringOrder;
protected final VersionNumber cassandraVersion;
protected AbstractTableMetadata(KeyspaceMetadata keyspace,
String name,
UUID id,
List<ColumnMetadata> partitionKey,
List<ColumnMetadata> clusteringColumns,
Map<String, ColumnMetadata> columns,
TableOptionsMetadata options,
List<ClusteringOrder> clusteringOrder,
VersionNumber cassandraVersion) {
this.keyspace = keyspace;
this.name = name;
this.id = id;
this.partitionKey = partitionKey;
this.clusteringColumns = clusteringColumns;
this.columns = columns;
this.options = options;
this.clusteringOrder = clusteringOrder;
this.cassandraVersion = cassandraVersion;
}
/**
* Returns the name of this table.
*
* @return the name of this CQL table.
*/
public String getName() {
return name;
}
/**
* Returns the unique id of this table.
* <p/>
* Note: this id is available in Cassandra 2.1 and above. It will be
* {@code null} for earlier versions.
*
* @return the unique id of the table.
*/
public UUID getId() {
return id;
}
/**
* Returns the keyspace this table belong to.
*
* @return the keyspace metadata of the keyspace this table belong to.
*/
public KeyspaceMetadata getKeyspace() {
return keyspace;
}
/**
* Returns metadata on a column of this table.
*
* @param name the name of the column to retrieve ({@code name} will be
* interpreted as a case-insensitive identifier unless enclosed in double-quotes,
* see {@link Metadata#quote}).
* @return the metadata for the column if it exists, or
* {@code null} otherwise.
*/
public ColumnMetadata getColumn(String name) {
return columns.get(Metadata.handleId(name));
}
/**
* Returns a list containing all the columns of this table.
* <p/>
* The order of the columns in the list is consistent with
* the order of the columns returned by a {@code SELECT * FROM thisTable}:
* the first column is the partition key, next are the clustering
* columns in their defined order, and then the rest of the
* columns follow in alphabetic order.
*
* @return a list containing the metadata for the columns of this table.
*/
public List<ColumnMetadata> getColumns() {
return new ArrayList<ColumnMetadata>(columns.values());
}
/**
* Returns the list of columns composing the primary key for this table.
* <p/>
* A table will always at least have a partition key (that
* may itself be one or more columns), so the returned list at least
* has one element.
*
* @return the list of columns composing the primary key for this table.
*/
public List<ColumnMetadata> getPrimaryKey() {
List<ColumnMetadata> pk = new ArrayList<ColumnMetadata>(partitionKey.size() + clusteringColumns.size());
pk.addAll(partitionKey);
pk.addAll(clusteringColumns);
return pk;
}
/**
* Returns the list of columns composing the partition key for this table.
* <p/>
* A table always has a partition key so the returned list has
* at least one element.
*
* @return the list of columns composing the partition key for this table.
*/
public List<ColumnMetadata> getPartitionKey() {
return Collections.unmodifiableList(partitionKey);
}
/**
* Returns the list of clustering columns for this table.
*
* @return the list of clustering columns for this table.
* If there is no clustering columns, an empty list is returned.
*/
public List<ColumnMetadata> getClusteringColumns() {
return Collections.unmodifiableList(clusteringColumns);
}
/**
* Returns the clustering order for this table.
* <p/>
* The returned contains the clustering order of each clustering column. The
* {@code i}th element of the result correspond to the order (ascending or
* descending) of the {@code i}th clustering column (see
* {@link #getClusteringColumns}). Note that a table defined without any
* particular clustering order is equivalent to one for which all the
* clustering keys are in ascending order.
*
* @return a list with the clustering order for each clustering column.
*/
public List<ClusteringOrder> getClusteringOrder() {
return clusteringOrder;
}
/**
* Returns the options for this table.
*
* @return the options for this table.
*/
public TableOptionsMetadata getOptions() {
return options;
}
void add(ColumnMetadata column) {
columns.put(column.getName(), column);
}
/**
* Returns a {@code String} containing CQL queries representing this
* table and the index on it.
* <p/>
* In other words, this method returns the queries that would allow you to
* recreate the schema of this table, along with the indexes and views defined on
* this table, if any.
* <p/>
* Note that the returned String is formatted to be human readable (for
* some definition of human readable at least).
*
* @return the CQL queries representing this table schema as a {code
* String}.
*/
public String exportAsString() {
StringBuilder sb = new StringBuilder();
sb.append(asCQLQuery(true));
return sb.toString();
}
/**
* Returns a CQL query representing this table.
* <p/>
* This method returns a single 'CREATE TABLE' query with the options
* corresponding to this table definition.
* <p/>
* Note that the returned string is a single line; the returned query
* is not formatted in any way.
*
* @return the 'CREATE TABLE' query corresponding to this table.
* @see #exportAsString
*/
public String asCQLQuery() {
return asCQLQuery(false);
}
protected abstract String asCQLQuery(boolean formatted);
protected StringBuilder appendOptions(StringBuilder sb, boolean formatted) {
// Options
sb.append(" WITH ");
if (options.isCompactStorage())
and(sb.append("COMPACT STORAGE"), formatted);
if (!Iterables.all(clusteringOrder, isAscending))
and(appendClusteringOrder(sb), formatted);
sb.append("read_repair_chance = ").append(options.getReadRepairChance());
and(sb, formatted).append("dclocal_read_repair_chance = ").append(options.getLocalReadRepairChance());
if (cassandraVersion.getMajor() < 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() == 0))
and(sb, formatted).append("replicate_on_write = ").append(options.getReplicateOnWrite());
and(sb, formatted).append("gc_grace_seconds = ").append(options.getGcGraceInSeconds());
and(sb, formatted).append("bloom_filter_fp_chance = ").append(options.getBloomFilterFalsePositiveChance());
if (cassandraVersion.getMajor() < 2 || cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() < 1)
and(sb, formatted).append("caching = '").append(options.getCaching().get("keys")).append('\'');
else
and(sb, formatted).append("caching = ").append(formatOptionMap(options.getCaching()));
if (options.getComment() != null)
and(sb, formatted).append("comment = '").append(options.getComment().replace("'", "''")).append('\'');
and(sb, formatted).append("compaction = ").append(formatOptionMap(options.getCompaction()));
and(sb, formatted).append("compression = ").append(formatOptionMap(options.getCompression()));
if (cassandraVersion.getMajor() >= 2) {
and(sb, formatted).append("default_time_to_live = ").append(options.getDefaultTimeToLive());
and(sb, formatted).append("speculative_retry = '").append(options.getSpeculativeRetry()).append('\'');
if (options.getIndexInterval() != null)
and(sb, formatted).append("index_interval = ").append(options.getIndexInterval());
}
if (cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1)) {
and(sb, formatted).append("min_index_interval = ").append(options.getMinIndexInterval());
and(sb, formatted).append("max_index_interval = ").append(options.getMaxIndexInterval());
}
if (cassandraVersion.getMajor() > 2) {
and(sb, formatted).append("crc_check_chance = ").append(options.getCrcCheckChance());
}
if (cassandraVersion.getMajor() > 3 || (cassandraVersion.getMajor() == 3 && cassandraVersion.getMinor() >= 8)) {
and(sb, formatted).append("cdc = ").append(options.isCDC());
}
sb.append(';');
return sb;
}
@Override
public String toString() {
return asCQLQuery();
}
private StringBuilder appendClusteringOrder(StringBuilder sb) {
sb.append("CLUSTERING ORDER BY (");
for (int i = 0; i < clusteringColumns.size(); i++) {
if (i > 0) sb.append(", ");
sb.append(clusteringColumns.get(i).getName()).append(' ').append(clusteringOrder.get(i));
}
return sb.append(')');
}
private static String formatOptionMap(Map<String, String> m) {
StringBuilder sb = new StringBuilder();
sb.append("{ ");
boolean first = true;
for (Map.Entry<String, String> entry : m.entrySet()) {
if (first) first = false;
else sb.append(", ");
sb.append('\'').append(entry.getKey()).append('\'');
sb.append(" : ");
try {
sb.append(Integer.parseInt(entry.getValue()));
} catch (NumberFormatException e) {
sb.append('\'').append(entry.getValue()).append('\'');
}
}
sb.append(" }");
return sb.toString();
}
private StringBuilder and(StringBuilder sb, boolean formatted) {
return newLine(sb, formatted).append(spaces(2, formatted)).append(" AND ");
}
static String spaces(int n, boolean formatted) {
if (!formatted)
return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
sb.append(' ');
return sb.toString();
}
static StringBuilder newLine(StringBuilder sb, boolean formatted) {
if (formatted)
sb.append('\n');
return sb;
}
static StringBuilder spaceOrNewLine(StringBuilder sb, boolean formatted) {
sb.append(formatted ? '\n' : ' ');
return sb;
}
}
| 37.80826
| 120
| 0.624171
|
a0e8d0aebcafb03dccf8c595b428f5591e309b43
| 4,707
|
package com.som_service.pdfreader.textobject;
import tech.utilis.common.lang.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
*
* @author Eugene Dementiev
*/
public class TextObjectLineMap {
public final Map<Double, List<TextObject>> map;
public final List<TextObject> list;
private double spaceScaleMultiplier = 10.1;
public TextObjectLineMap(){
list = new ArrayList<>();
map = new TreeMap<>();
}
public TextObjectLineMap(TreeMap<Double, List<TextObject>> map){
this.map = map;
this.list = new ArrayList<>();
for(Double key: map.keySet()){
List line = map.get(key);
line.stream().forEach(tx -> this.list.add((TextObject)tx));
}
}
public List<TextObject> get(Double key){
return map.get(key);
}
public void put(Double key, TextObject tx){
if (!map.containsKey(key)){
map.put(key, new ArrayList<>());
}
map.get(key).add(tx);
list.add(tx);
}
public static final Comparator<TextObject> COMPARATOR_X = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
double o1x = ((TextObject)o1).x;
double o2x = ((TextObject)o2).x;
/*
if (o1x > o2x){
return 1;
}
if (o1x < o2x){
return -1;
}
return 0;
*/
return (int)((o1x-o2x)*10000);
}
};
public static final Comparator<TextObject> COMPARATOR_Y = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
double o1y = ((TextObject)o1).y;
double o2y = ((TextObject)o2).y;
if (o1y > o2y){
return 1;
}
if (o1y < o2y){
return -1;
}
return 0;
}
};
public void sortBy(Comparator<TextObject> comparator){
for(Double key: map.keySet()){
Collections.sort(map.get(key), comparator);
}
}
public List<List<TextObjectWord>> asWords(){
List<List<TextObjectWord>> lines = new ArrayList<>();
for(Double index: map.keySet()){
List<TextObjectWord> words = new ArrayList<>();
List<TextObject> word_members = new ArrayList<>();
double word_prefix_distance = -1;
double last_end = 0;
double last_pos_diff = 0;
for(TextObject tx: map.get(index)){
if(StringUtils.isVisibleWhiteSpace(tx.text.charAt(0))){
// Do not count white spaces
continue;
}
double pos_diff = tx.x - last_end;
// Distance between last token's bbox in word members to this token's bbox greater than a space (scaled and multiplied)
boolean condition1 = pos_diff > tx.space_width * tx.tp.getXScale() / spaceScaleMultiplier;
// wtf?
boolean condition2 = last_pos_diff <= 0 && pos_diff > 0;
condition2 = false;
if (condition1 || condition2){
if (!word_members.isEmpty()){
TextObjectWord word = new TextObjectWord(word_members);
word.setSpaceBefore(word_prefix_distance);
words.add(word);
word_members = new ArrayList<>();
}
}
word_members.add(tx);
if (word_prefix_distance < 0){
// Set prefix distance for the very first word
word_prefix_distance = Double.max(0, word_members.get(0).x);
}
else if(word_members.size() == 1){
// Set prefix distance for consecutive words
word_prefix_distance = tx.x - last_end;
}
last_end = tx.bbox.right;
last_pos_diff = pos_diff;
}
if (word_members.isEmpty()){
continue;
}
TextObjectWord word = new TextObjectWord(word_members);
word.setSpaceBefore(word_prefix_distance);
words.add(word);
lines.add(words);
}
return lines;
}
public TextObjectLineMap clone(TextObjectLineMapFilter txf){
TextObjectLineMap txolm = new TextObjectLineMap();
list.stream().forEach(tx -> {
Double evaluation_result = txf.evaluate(tx);
if(evaluation_result != null){
txolm.put(evaluation_result, tx);
}
});
return txolm;
}
/**
* Gets the value of space scale multiplier
* @return spaceScaleMultiplier
*/
public double getSpaceScaleMultiplier() {
return spaceScaleMultiplier;
}
/**
* Sets space scale multiplier, which impacts how symbols are grouped into words<br/>
* Larger number decreases space between symbols required to qualify as a word separator<br/>
* Smaller number increases space between symbols required to qualify as a word separator
* @param spaceScaleMultiplier
*/
public void setSpaceScaleMultiplier(double spaceScaleMultiplier) {
this.spaceScaleMultiplier = spaceScaleMultiplier;
}
}
| 25.306452
| 124
| 0.642872
|
7ab307d81b6d881c35c31fdec27fbe082d5cd74d
| 1,794
|
package com.backpackcloud.papi.hateoas.impl;
import com.backpackcloud.papi.hateoas.ApiCollectionModel;
import com.backpackcloud.papi.hateoas.ApiLink;
import com.backpackcloud.papi.hateoas.ApiModel;
import com.backpackcloud.papi.hateoas.LinkMapper;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.*;
import java.util.stream.Collectors;
public class CollectionModel<E> implements ApiCollectionModel<E> {
@JsonProperty("values")
private final Collection<ApiModel<E>> values;
@JsonProperty("_links")
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private final Map<String, ApiLink> links;
@JsonProperty("total")
@JsonInclude(JsonInclude.Include.NON_NULL)
private final Long total;
public CollectionModel(Collection<E> values, Long total) {
this.values = values.stream()
.map(EntityModel::new)
.collect(Collectors.toList());
this.links = new HashMap<>();
this.total = total;
}
public CollectionModel(Collection<E> values) {
this(values, null);
}
@Override
public LinkMapper<ApiCollectionModel<E>> link(String uri) {
return new LinkMapper<>() {
String title;
@Override
public LinkMapper<ApiCollectionModel<E>> title(String title) {
this.title = title;
return this;
}
@Override
public CollectionModel<E> to(String rel) {
links.put(rel, new EntityLink(uri, rel, title));
return CollectionModel.this;
}
};
}
@JsonProperty("size")
public int size() {
return values.size();
}
@Override
public Collection<ApiModel<E>> values() {
return values;
}
@Override
public Optional<ApiLink> linkTo(String rel) {
return Optional.ofNullable(links.get(rel));
}
}
| 25.267606
| 68
| 0.704571
|
b0292c779de013410bdf5edba1d826303d26272d
| 378
|
package com.hiyouka.source.aop;
import com.hiyouka.source.code.BaseUtil;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
/**
* @author hiyouka
* @since JDK 1.8
*/
@Component
public class AopTest2 {
private Logger logger = BaseUtil.getLogger(getClass());
public void testIntercept(){
logger.info("testIntercept execute");
}
}
| 18.9
| 59
| 0.716931
|
9fc334d2d688939475ee461e37af742355d47742
| 553
|
package com.liuscoding.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @className: SentinelApplication8041
* @description:
* @author: liusCoding
* @create: 2020-06-11 12:38
*/
@EnableDiscoveryClient
@SpringBootApplication
public class SentinelApplication8041 {
public static void main(String[] args) {
SpringApplication.run(SentinelApplication8041.class,args);
}
}
| 26.333333
| 72
| 0.792043
|
0a7fab9ced7c2df33f786c920517750df050bb53
| 349
|
//,temp,AbstractJavaKeyStoreProvider.java,161,167,temp,DeleteCompletionCallback.java,40,48
//,3
public class xxx {
@Override
public void processResult(CuratorFramework client,
CuratorEvent event) throws
Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("Delete event {}", event);
}
events.incrementAndGet();
}
};
| 24.928571
| 90
| 0.69341
|
0e8b07dc21a89e4109bd4dabb16895fef16ca2ff
| 10,942
|
/*
* MIT License
*
* Copyright (c) 2018 i4one Interactive, LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.i4one.base.model.balanceexpense;
import com.i4one.base.core.Utils;
import com.i4one.base.model.ActivityType;
import com.i4one.base.model.SingleClientType;
import com.i4one.base.model.ErrorMessage;
import com.i4one.base.model.Errors;
import com.i4one.base.model.ReturnType;
import com.i4one.base.model.balance.Balance;
import com.i4one.base.model.i18n.IString;
import com.i4one.base.model.manager.activity.BaseActivityManager;
import com.i4one.base.model.manager.pagination.PaginationFilter;
import com.i4one.base.model.transaction.Transaction;
import com.i4one.base.model.transaction.TransactionManager;
import com.i4one.base.model.user.User;
import com.i4one.base.model.user.UserBalance;
import com.i4one.base.model.user.UserBalanceManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Hamid Badiozamani
*/
@Service("base.UserBalanceExpenseManager")
public class SimpleUserBalanceExpenseManager extends BaseActivityManager<UserBalanceExpenseRecord, UserBalanceExpense, BalanceExpense> implements UserBalanceExpenseManager
{
private TransactionManager transactionManager;
private UserBalanceManager userBalanceManager;
private BalanceExpenseManager balanceExpenseManager;
@Override
public UserBalanceExpense emptyInstance()
{
return new UserBalanceExpense();
}
@Override
public Set<UserBalanceExpense> getByUser(User user, PaginationFilter pagination)
{
return convertDelegates(getDao().getByUser(user.getSer(), pagination));
}
@Override
public Set<UserBalanceExpense> getAllUserBalanceExpenses(BalanceExpense balanceExpense, User user, PaginationFilter pagination)
{
//return getAllUserBalanceExpenses(balanceExpense, user, pagination);
return convertDelegates(getDao().getAll(balanceExpense.getSer(), user.getSer(), pagination));
}
@Transactional(readOnly = false)
@Override
public <T extends SingleClientType<?>> List<ReturnType<UserBalanceExpense>> processExpenses(User user, T item, ActivityType<?, T> activity, PaginationFilter pagination)
{
// Then the specific item expenses
//
Set<BalanceExpense> expenses = getBalanceExpenseManager().getAllExpensesByFeature(item);
int currTime = Utils.currentTimeSeconds();
List<ReturnType<UserBalanceExpense>> retVal = new ArrayList<>();
for ( BalanceExpense expense : expenses)
{
getLogger().debug("Considering expense " + expense);
// It's more likely that there are one or two expenses associated with a given feature, so this
// loop will be very short. If the loop was longer, it might be worth considering getting all
// of the user's expenses and filtering the array in memory rather than hitting the database
// on each call
//
UserBalanceExpense userBalanceExpense = new UserBalanceExpense();
userBalanceExpense.setQuantity(activity.getQuantity());
userBalanceExpense.setActivityId(activity.getSer());
userBalanceExpense.setBalanceExpense(expense);
userBalanceExpense.setUser(user);
userBalanceExpense.setTimeStampSeconds(currTime);
int amount = userBalanceExpense.getQuantity() * expense.getAmount();
ReturnType<UserBalance> updateStatus = getUserBalanceManager().increment(
new UserBalance(user, expense.getBalance(), currTime),
-1 * amount);
if ( updateStatus.getPost().exists() )
{
// See if we got a transaction record, and if we did we can update our record
// with its serial number. Consider moving this to its own manager (i.e.
// TransactionalSimpleUserBalanceExpenseManager)
//
Transaction transaction = (Transaction)updateStatus.get("transaction");
if ( transaction != null )
{
transaction.setDescr(new IString(""));
getTransactionManager().update(transaction);
userBalanceExpense.setTransaction(transaction);
}
// Record that we processed the expense
//
ReturnType<UserBalanceExpense> createVal = create(userBalanceExpense);
createVal.addChain(getUserBalanceManager(), "increment", updateStatus);
retVal.add(createVal);
}
else
{
throw new Errors(getInterfaceName() + ".processExpenses", new ErrorMessage("msg.rewards.userBalanceExpenseManager.create.nsf", "You do not have sufficient currency: You need $amount #IString($item.balance.formatName($amount)) to continue. Your current balance is $item.total #IString($item.balance.formatName($item.total))", new Object[] { "item", updateStatus.getPost(), "amount", amount }, null));
}
}
getLogger().debug("Processed expenses = " + retVal);
return retVal;
}
private <T extends SingleClientType<?>> Set<UserBalanceExpense> getUserBalanceExpenses(BalanceExpense expense, ActivityType<?, T> activity)
{
return convertDelegates(getDao().getByActivity(expense.getSer(), activity.getSer()));
}
@Transactional(readOnly = false)
@Override
public <T extends SingleClientType<?>> List<ReturnType<UserBalance>> revertExpenses(T item, ActivityType<?, T> activity)
{
getLogger().debug("Reverting expenses for {} activity record {}", item, activity);
// Since expenses are exclusive and at the very least cannot be removed if they have activity,
// we'll be sure to get all of the expenses associated with the given item here
//
Set<BalanceExpense> expenses = getBalanceExpenseManager().getAllExpensesByFeature(item);
// We collect the credits due to a user at the end
//
Map<Balance, Integer> credits = expenses
.stream()
.collect(Collectors.toMap(
(balanceExpense) -> { return balanceExpense.getBalance(); },
(balanceExpense) -> { return 0; }));
User user = new User();
for ( BalanceExpense expense : expenses)
{
getLogger().debug("Considering expense " + expense);
// NOTE: BalanceExpenses are always exclusive. As such reverting all records should
// not result in a member having currency refunded for any expense incurred outside
// of this item.
//
Set<UserBalanceExpense> userBalanceExpenses = getUserBalanceExpenses(expense, activity);
getLogger().debug("Got {} userbalance expenses ", userBalanceExpenses.size() );
for ( UserBalanceExpense userExpense : userBalanceExpenses)
{
if ( user.exists() && !user.equals(userExpense.getUser(false)))
{
getLogger().error("User {} should be the same as {} but isn't", user, userExpense.getUser(false));
throw new Errors(getInterfaceName() + ".revertExpenses", new ErrorMessage("msg.rewards.userBalanceExpenseManager.revertExpenses.error", "Unexpected error", new Object[] { "item", item, "activity", activity }, null));
}
else
{
user = userExpense.getUser(false);
getLogger().debug("Set user to {}", user );
}
// The amount the user actually spent for these entries
//
int amount = 0;
// We go off of the transaction log and not what the current balance expense is
// indicating since balance expenses can be changed after users enter transactions
//
Transaction transaction = userExpense.getTransaction();
if ( transaction.exists() )
{
// This is reflective of what the amount was at the time the transaction took place
//
amount = transaction.getAmountTransacted();
}
else
{
// As a back up, if there's no transaction record of how much was actually spent,
// we can go by the current expense amount
//
amount += -1 * userExpense.getQuantity() * expense.getAmount();
}
// We add the amount the user is due for any existing amount
//
Integer expenseAmount = credits.get(expense.getBalance());
expenseAmount += amount;
credits.put(expense.getBalance(), expenseAmount);
// We're done with this expense, note that the transaction record
// is left untouched for record keeping.
//
remove(userExpense);
}
}
// At this point we should have a list of balances and amounts to be credited back to those
// balances.
//
if ( user.exists() )
{
List<ReturnType<UserBalance>> retVal = new ArrayList<>();
for ( Balance balance : credits.keySet() )
{
UserBalance userBalance = new UserBalance();
userBalance.setUser(user);
userBalance.setBalance(balance);
userBalance = getUserBalanceManager().getUserBalanceForUpdate(userBalance);
ReturnType<UserBalance> credited = getUserBalanceManager().increment(userBalance, -1 * credits.get(balance));
retVal.add(credited);
}
getLogger().debug("Reverted balances = " + retVal);
return retVal;
}
else
{
return Collections.EMPTY_LIST;
}
}
@Override
public List<ReturnType<UserBalanceExpense>> revert(BalanceExpense item, PaginationFilter pagination)
{
throw new UnsupportedOperationException("Please use revertExpenses(..) instead.");
}
@Override
public UserBalanceExpenseRecordDao getDao()
{
return (UserBalanceExpenseRecordDao) super.getDao();
}
public UserBalanceManager getUserBalanceManager()
{
return userBalanceManager;
}
@Autowired
public void setUserBalanceManager(UserBalanceManager userBalanceManager)
{
this.userBalanceManager = userBalanceManager;
}
public BalanceExpenseManager getBalanceExpenseManager()
{
return balanceExpenseManager;
}
@Autowired
public void setBalanceExpenseManager(BalanceExpenseManager balanceExpenseManager)
{
this.balanceExpenseManager = balanceExpenseManager;
}
public TransactionManager getTransactionManager()
{
return transactionManager;
}
@Autowired
public void setTransactionManager(TransactionManager transactionManager)
{
this.transactionManager = transactionManager;
}
}
| 36.231788
| 403
| 0.746481
|
2a42dc9a092b9fbca03fccfc96fcd4d441c0c908
| 4,849
|
package io.lindstrom.mpd.support;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.Duration;
import java.time.format.DateTimeParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DurationDeserializer extends JsonDeserializer<Duration> {
private static final int HOURS_PER_YEAR = 8766;
private static final int MINUTES_PER_MONTH = 43830;
private static final int HOURS_PER_DAY = 24;
// PnYnMnDTnHnMnS
private static final Pattern PATTERN =
Pattern.compile("([-+]?)P" +
"(?:([-+]?[0-9]+)Y)?" +
"(?:([-+]?[0-9]+)M)?" +
"(?:([-+]?[0-9]+)D)?" +
"(T(?:([-+]?[0-9]+)H)?(?:([-+]?[0-9]+)M)?(?:([-+]?[0-9]+)(?:[.,]([0-9]+))?S)?)?",
Pattern.CASE_INSENSITIVE);
private static Duration estimateDuration(long years, long months, long days) {
if (years > 0 || months > 0 || days > 0) {
return Duration.ofHours(HOURS_PER_YEAR * years)
.plusMinutes(MINUTES_PER_MONTH * months)
.plusHours(HOURS_PER_DAY * days);
} else {
return Duration.ZERO;
}
}
private static boolean isNegative(CharSequence text, int start, int end) {
return (start >= 0 && end == start + 1 && text.charAt(start) == '-');
}
static long parseFraction(CharSequence text, int start, int end, boolean negate) {
// regex limits to [0-9]{0,12}
if (start < 0 || end < 0 || end - start == 0) {
return 0;
}
// Duration only handle nano second resolution but xs:duration allows 12 decimals.
if (end - start > 9) {
end = start + 9;
}
long fraction = Long.parseLong(text, start, end, 10);
// for number strings smaller than 9 digits, interpret as if there were trailing zeros
for (int i = end - start; i < 9; i++) {
fraction *= 10;
}
if (negate) {
return -fraction;
} else {
return fraction;
}
}
private Duration parse(String text) {
Matcher matcher = PATTERN.matcher(text);
if (!matcher.matches()) {
throw new DateTimeParseException("Text cannot be parsed to a Duration", text, 0);
}
boolean negate = isNegative(text, matcher.start(1), matcher.end(1));
int yearStart = matcher.start(2), yearEnd = matcher.end(2);
int monthStart = matcher.start(3), monthEnd = matcher.end(3);
int dayStart = matcher.start(4), dayEnd = matcher.end(4);
int hourStart = matcher.start(6), hourEnd = matcher.end(6);
int minuteStart = matcher.start(7), minuteEnd = matcher.end(7);
int secondStart = matcher.start(8), secondEnd = matcher.end(8);
int fractionStart = matcher.start(9), fractionEnd = matcher.end(9);
int years = 0;
int months = 0;
int days = 0;
long hoursAsSecs = 0;
long minutesAsSecs = 0;
long seconds = 0;
long nanos = 0;
if (yearStart >= 0) {
years = Integer.parseInt(text, yearStart, yearEnd, 10);
}
if (monthStart >= 0) {
months = Integer.parseInt(text, monthStart, monthEnd, 10);
}
if (dayStart >= 0) {
days = Integer.parseInt(text, dayStart, dayEnd, 10);
}
if (hourStart >= 0) {
hoursAsSecs = Math.multiplyExact(3600L, Integer.parseInt(text, hourStart, hourEnd, 10));
}
if (minuteStart >= 0) {
minutesAsSecs = Math.multiplyExact(60L, Integer.parseInt(text, minuteStart, minuteEnd, 10));
}
if (secondStart >= 0) {
seconds = Integer.parseInt(text, secondStart, secondEnd, 10);
boolean negativeSecs = text.charAt(secondStart) == '-';
nanos = parseFraction(text, fractionStart, fractionEnd, negativeSecs);
}
long secondsTotal = Math.addExact(hoursAsSecs, Math.addExact(minutesAsSecs, seconds));
Duration duration = Duration.ofSeconds(secondsTotal, nanos).plus(estimateDuration(years, months, days));
if (negate) {
return duration.negated();
}
return duration;
}
@Override
public Duration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String text = p.getText();
try {
return parse(text);
} catch (Exception e) {
ctxt.reportWrongTokenException(this, p.currentToken(), "Text cannot be parsed to a Duration");
}
return null;
}
}
| 34.390071
| 112
| 0.573108
|
9b9fcc32d60e571736e4f9b8d91cb746ec1e9beb
| 1,759
|
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.nokee.ide.visualstudio;
import dev.nokee.ide.base.IdeProjectReference;
import org.gradle.api.file.FileSystemLocation;
import org.gradle.api.provider.Provider;
import java.util.Set;
/**
* A reference to an Visual Studio IDE project.
*
* @since 0.5
* @see IdeProjectReference for more information.
*/
public interface VisualStudioIdeProjectReference extends IdeProjectReference {
/**
* Returns the project location, that is the location of the .vcxproj, for this project reference.
*
* @return a provider of this project reference's vcxproj, never null.
*/
Provider<FileSystemLocation> getProjectLocation();
/**
* Returns the project global universal identifier of this project reference.
*
* @return a provider of {@link VisualStudioIdeGuid} of this project reference, never null.
*/
Provider<VisualStudioIdeGuid> getProjectGuid();
/**
* Returns the project configuration of this project reference.
*
* @return a provider of {@link VisualStudioIdeProjectConfiguration} of this project reference, never null.
*/
Provider<Set<VisualStudioIdeProjectConfiguration>> getProjectConfigurations();
}
| 33.826923
| 108
| 0.757248
|
0c8f82aac0e708433b388a487f2994fb6412671e
| 1,551
|
// we only need to reverse 'D' substrings
public class Solution {
public int[] findPermutation(String s) {
int n = s.length() + 1;
int[] res = new int[n];
for (int i = 0; i < n; i++) res[i] = i + 1;
for (int i = 0; i < n-1; i++) {
int j = i;
while (i < n-1 && s.charAt(i) == 'D') i++;
reverse(res, j, i);
}
return res;
}
private void reverse(int[] res, int i, int j) {
while (i < j) {
res[i] ^= res[j];
res[j] ^= res[i];
res[i++] ^= res[j--];
}
}
}
// not a good solution.
public class Solution {
public int[] findPermutation(String s) {
int n = s.length() + 1;
int[] res = new int[n];
int i = 0, preMax = 0, idx = 0;
while (i < s.length()) {
char c = s.charAt(i);
int j = i, count = 0;
while (j < s.length() && c == s.charAt(j)) {
j++; count++;
}
if (c == 'D') {
for (int k = count + preMax + 1; k >= preMax + 1; k--)
res[idx++] = k;
preMax = preMax + count + 1;
} else {
for (int k = preMax + 1; k < preMax + count + (preMax == 0 ? 1 : 0); k++)
res[idx++] = k;
preMax = preMax + count - (preMax == 0 ? 0 : 1);
}
i = j;
if (c == 'I' && i >= s.length()) res[idx] = preMax + 1;
}
return res;
}
}
| 29.826923
| 89
| 0.373308
|
22fe4403841307ffd73f0e59e045622af3bd2082
| 475
|
package com.atguigu.gmallpublishertest;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "com.atguigu.gmallpublishertest.mapper")
public class GmallPublisherTestApplication {
public static void main(String[] args) {
SpringApplication.run(GmallPublisherTestApplication.class, args);
}
}
| 31.666667
| 73
| 0.818947
|
e6c12571ca7b640861283a90d84ec3130dd65c5b
| 1,786
|
package com.wix.reactnativeuilib.keyboardinput;
import android.app.Application;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class KeyboardInputPackage implements ReactPackage {
private CustomKeyboardLayout.Box mLayout = new CustomKeyboardLayout.Box();
public KeyboardInputPackage(Application application) {
AppContextHolder.setApplication(application);
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
init(reactContext);
return Arrays.<NativeModule>asList(new KeyboardInputModule(reactContext, mLayout));
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
init(reactContext);
return Arrays.<ViewManager>asList(new CustomKeyboardRootViewManager(mLayout));
}
// Deprecated in RN 0.47
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
private synchronized void init(ReactApplicationContext reactContext) {
if (ReactContextHolder.getContext() != reactContext) {
ReactContextHolder.setContext(reactContext);
final ReactScreenMonitor screenMonitor = new ReactScreenMonitor(reactContext);
final ReactSoftKeyboardMonitor keyboardMonitor = new ReactSoftKeyboardMonitor(screenMonitor);
mLayout.setInstance(new CustomKeyboardLayout(reactContext, keyboardMonitor, screenMonitor));
}
}
}
| 35.72
| 105
| 0.760918
|
6c88bd5d95a59831b78a0b6b977cb2b4c7b8c855
| 5,354
|
package io.choerodon.test.manager.api.controller.v1;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import io.choerodon.core.iam.ResourceLevel;
import io.choerodon.test.manager.api.vo.TestCycleCaseVO;
import io.swagger.annotations.ApiOperation;
import org.hzero.starter.keyencrypt.core.Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.choerodon.test.manager.api.vo.agile.IssueCreateDTO;
import io.choerodon.test.manager.api.vo.agile.IssueDTO;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.iam.InitRoleCode;
import io.choerodon.swagger.annotation.Permission;
import io.choerodon.test.manager.api.vo.IssueInfosVO;
import io.choerodon.test.manager.api.vo.TestCycleCaseDefectRelVO;
import io.choerodon.test.manager.app.service.TestCaseService;
import io.choerodon.test.manager.app.service.TestCycleCaseDefectRelService;
/**
* Created by 842767365@qq.com on 6/25/18.
*/
@RestController
@RequestMapping(value = "/v1/projects/{project_id}/defect")
public class TestCycleCaseDefectRelController {
@Autowired
TestCycleCaseDefectRelService testCycleCaseDefectRelService;
@Autowired
TestCaseService testCaseService;
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("增加缺陷")
@PostMapping
public ResponseEntity<List<TestCycleCaseDefectRelVO>> insert(@PathVariable(name = "project_id") Long projectId,
@RequestBody List<TestCycleCaseDefectRelVO> testCycleCaseDefectRelVO,
@RequestParam Long organizationId) {
List<TestCycleCaseDefectRelVO> dtos = new ArrayList<>();
testCycleCaseDefectRelVO.forEach(v -> {
v.setProjectId(projectId);
dtos.add(testCycleCaseDefectRelService.insert(v, projectId, organizationId));
});
return Optional.ofNullable(dtos)
.map(result -> new ResponseEntity<>(result, HttpStatus.CREATED))
.orElseThrow(() -> new CommonException("error.testDefect.insert"));
}
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("删除缺陷")
@DeleteMapping("/delete/{defectId}")
public ResponseEntity removeAttachment(@PathVariable(name = "project_id") Long projectId,
@PathVariable(name = "defectId")
@Encrypt Long defectId,
@RequestParam Long organizationId) {
TestCycleCaseDefectRelVO testCycleCaseDefectRelVO = new TestCycleCaseDefectRelVO();
testCycleCaseDefectRelVO.setId(defectId);
testCycleCaseDefectRelService.delete(testCycleCaseDefectRelVO, projectId, organizationId);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("创建一个缺陷并且关联到对应case或者step")
@PostMapping("/createIssueAndDefect/{defectType}/{id}")
public TestCycleCaseDefectRelVO createIssueAndLinkDefect(@RequestBody IssueCreateDTO issueCreateDTO,
@PathVariable("project_id") Long projectId,
@RequestParam("applyType") String applyType,
@PathVariable("defectType") String defectType,
@RequestParam Long organizationId,
@PathVariable("id") @Encrypt Long id) {
IssueDTO issueDTO = testCaseService.createTest(issueCreateDTO, projectId, applyType);
TestCycleCaseDefectRelVO defectRelDTO = new TestCycleCaseDefectRelVO();
defectRelDTO.setIssueId(issueDTO.getIssueId());
defectRelDTO.setProjectId(projectId);
defectRelDTO.setDefectType(defectType);
defectRelDTO.setDefectLinkId(id);
TestCycleCaseDefectRelVO defect = testCycleCaseDefectRelService.insert(defectRelDTO, projectId, organizationId);
defect.setIssueInfosVO(new IssueInfosVO(issueDTO));
return defect;
}
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("修改缺陷的projectId")
@PutMapping("/fix")
public void fixDefectData(@PathVariable(name = "project_id") Long projectId,
@RequestParam Long organizationId) {
TestCycleCaseDefectRelVO testCycleCaseDefectRelVO = new TestCycleCaseDefectRelVO();
testCycleCaseDefectRelVO.setProjectId(projectId);
testCycleCaseDefectRelService.updateIssuesProjectId(testCycleCaseDefectRelVO, organizationId);
}
@Permission(level = ResourceLevel.ORGANIZATION)
@ApiOperation("删除缺陷后解除对应关系")
@DeleteMapping("/delete_relation/{defectId}")
public ResponseEntity deleteCaseRel(@PathVariable(name = "project_id") Long projectId,
@PathVariable(name = "defectId") Long defectId) {
testCycleCaseDefectRelService.deleteCaseRel(projectId,defectId);
return new ResponseEntity<>(HttpStatus.OK);
}
}
| 49.574074
| 134
| 0.677811
|
1acb0299699942697355a1b527cd878f64e03b0b
| 968
|
package com.vladsch.flexmark.test;
import com.vladsch.flexmark.ast.util.TextCollectingVisitorTest;
import com.vladsch.flexmark.parser.internal.HtmlDeepParserTest;
import org.junit.runners.Suite;
@org.junit.runner.RunWith(Suite.class)
@Suite.SuiteClasses({
AbstractVisitorTest.class,
DelimitedNodeTest.class,
DelimiterProcessorTest.class,
HtmlRendererTest.class,
ParserTest.class,
PathologicalTest.class,
PrefixedSubSequenceTest.class,
FullOrigSpecCoreTest.class,
FullOrigSpec027CoreTest.class,
FullOrigSpec028CoreTest.class,
ComboCoreSpecTest.class,
ComboCoreDirectionalSpecTest.class,
ComboExtraSpecTest.class,
SpecialInputTest.class,
UsageExampleTest.class,
CoreCompatibilityTestSuite.class,
ComboIssuesSpecTest.class,
TextCollectingVisitorTest.class,
HtmlDeepParserTest.class,
})
public class CoreTestSuite {
}
| 31.225806
| 63
| 0.729339
|
0d0b94de2e1ec3e89111537af6b96afa6ddfcd61
| 2,030
|
/*
* JFLAP - Formal Languages and Automata Package
*
*
* Susan H. Rodger
* Computer Science Department
* Duke University
* August 27, 2009
* Copyright (c) 2002-2009
* All rights reserved.
* JFLAP is open source software. Please see the LICENSE for terms.
*
*/
package edu.duke.cs.jflap.pumping.reg;
import edu.duke.cs.jflap.pumping.LemmaMath;
import edu.duke.cs.jflap.pumping.RegularPumpingLemma;
/**
* The regular pumping lemma for <i>L</i> =
* {<i>a<sup>n</sup>b<sup>k</sup></i> : <i>n</i> is
* odd or <i>k</i> is even}.
*
* @author Chris Morgan
*/
public class AnBk extends RegularPumpingLemma {
public String getTitle()
{
return "a^n b^k : n is odd or k is even";
}
public String getHTMLTitle()
{
return "<i>a<sup>n</sup>b<sup>k</sup></i> : <i>n</i> is odd"
+ " or <i>k</i> is even.";
}
public void setDescription()
{
partitionIsValid = true;
explanation = "Because this is a regular language, a valid decomposition exists. If <i>m</i> " + GREATER_OR_EQ +
" 3, a <i>y</i> value of \"aa\" or \"bb\" will always pump the string. At least one of those substrings " +
"can be the <i>y</i> value.";
}
protected void setRange()
{
myRange = new int[]{3, 10};
}
public void chooseI()
{
i = LemmaMath.flipCoin();
}
protected void chooseW()
{
if (m % 2 == 0)
w = pumpString("a", m-2) + "bb";
else
w = "a" + pumpString("b", m);
}
public void chooseDecomposition()
{
int firstB = w.indexOf('b');
//One of these should be valid
if (firstB == -1 || firstB>=2)
setDecomposition(new int[] {0, 2});
else
setDecomposition(new int[] {firstB, 2});
}
public boolean isInLang(String s)
{
int a, b;
char[] list = new char[] {'a', 'b'};
if (LemmaMath.isMixture(s, list))
return false;
a = LemmaMath.countInstances(s, 'a');
b = LemmaMath.countInstances(s, 'b');
if (a%2 == 1 || b%2 == 0)
return true;
return false;
}
}
| 21.145833
| 118
| 0.585222
|
dff6f257fc8e6e1aa2f072dfb915f0806533642c
| 2,307
|
package com.acmerobotics.dashboard.canvas;
import java.util.ArrayList;
import java.util.List;
public class Canvas {
private List<CanvasOp> ops;
public Canvas() {
ops = new ArrayList<>();
}
public Canvas strokeCircle(double x, double y, double radius) {
ops.add(new Circle(x, y, radius, true));
return this;
}
public Canvas fillCircle(double x, double y, double radius) {
ops.add(new Circle(x, y, radius, false));
return this;
}
public Canvas strokePolygon(double[] xPoints, double[] yPoints) {
ops.add(new Polygon(xPoints, yPoints, true));
return this;
}
public Canvas fillPolygon(double[] xPoints, double[] yPoints) {
ops.add(new Polygon(xPoints, yPoints, false));
return this;
}
public Canvas strokePolyline(double[] xPoints, double[] yPoints) {
ops.add(new Polyline(xPoints, yPoints));
return this;
}
public Canvas strokeLine(double x1, double y1, double x2, double y2) {
strokePolyline(new double[] { x1, x2 }, new double[] { y1, y2 });
return this;
}
public Canvas fillRect(double x, double y, double width, double height) {
fillPolygon(new double[] { x, x + width, x + width, x }, new double[] { y, y, y + height, y + height });
return this;
}
public Canvas strokeRect(double x, double y, double width, double height) {
strokePolygon(new double[] { x, x + width, x + width, x }, new double[] { y, y, y + height, y + height });
return this;
}
public Canvas strokeSpline(double knotDistance, double xOffset, double yOffset, double headingOffset, double a, double b, double c, double d, double e) {
ops.add(new Spline(knotDistance, xOffset, yOffset, headingOffset, a, b, c, d, e));
return this;
}
public Canvas setFill(String color) {
ops.add(new Fill(color));
return this;
}
public Canvas setStroke(String color) {
ops.add(new Stroke(color));
return this;
}
public Canvas setStrokeWidth(int width) {
ops.add(new StrokeWidth(width));
return this;
}
public List<CanvasOp> getOperations() {
return ops;
}
public void clear() {
this.ops.clear();
}
}
| 28.481481
| 157
| 0.60945
|
412fb47b9ec9667a958b395a6a925a4890346f06
| 4,190
|
package org.graylog2.gelf4j.cb;
import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.graylog2.gelf4j.message.Payload;
import org.graylog2.gelf4j.transmitters.PayloadTransmitter;
/**
* CircuitBreaker.
* <p/>
* Implementation of <a href="https://martinfowler.com/bliki/CircuitBreaker.html">Circuit breaker</a> using to
* control failover withing failed third party resources.
*
* @author Andrey Minov.
* @since 2017.02
*/
public class CircuitBreakerTransmitter implements PayloadTransmitter {
private final long maxFailures;
private final long recoverPeriod;
private final TimeUnit timeUnit;
private final AtomicLong failCounter;
private final AtomicReference<State> state;
private volatile long stopTime;
private PayloadTransmitter delegate;
/**
* Instantiates a new Circuit breaker.
*
* @param maxFailures the max failures number before circuit goes to close state
* @param recoverPeriod the recover period aften which circuit breaker will try once again to ask for
* resource
* @param timeUnit the time unit of recovery period
* @param delegate actual transmitter for the payload
*/
public CircuitBreakerTransmitter(long maxFailures, long recoverPeriod, TimeUnit timeUnit,
PayloadTransmitter delegate) {
this.maxFailures = maxFailures;
this.recoverPeriod = recoverPeriod;
this.timeUnit = timeUnit;
this.state = new AtomicReference<>(State.CLOSED);
this.failCounter = new AtomicLong();
this.delegate = delegate;
}
/**
* Send value to delegate if possible or throw exception in case problem happens.
*
* @throws CircuitOpenException in case when circuit is open
*/
@Override
public void transmit(Payload payload) throws Exception {
State initialState = getInitialState();
if (EnumSet.of(State.CLOSED, State.PARTIALLY_OPEN).contains(initialState)) {
try {
delegate.transmit(payload);
markClosed();
return;
} catch (Exception e) {
if (connectionException(e)) {
processException();
}
}
}
throw new CircuitOpenException("Circuit is open and request cannot be processed");
}
@Override
public void close() throws IOException {
delegate.close();
}
@Override
public void open() throws IOException {
delegate.open();
}
private State getInitialState() {
// put it here as function must be side-affect-free (values must not be changed inside function).
// be aware that it will bring one more volative get operation overhead.
long stopShapshot = stopTime;
State newState = state.getAndUpdate(val -> {
if (val != State.OPEN
|| System.currentTimeMillis() - timeUnit.toMillis(recoverPeriod) < stopShapshot) {
return val;
}
return State.PARTIALLY_OPEN;
});
if (newState == State.PARTIALLY_OPEN) {
failCounter.decrementAndGet();
}
return newState;
}
private void markClosed() {
State prev = state.getAndSet(State.CLOSED);
if (prev != State.CLOSED) {
failCounter.set(0);
}
}
private void processException() {
long value = failCounter.updateAndGet(v -> Math.min(v + 1, maxFailures));
if (value >= maxFailures) {
if (state.getAndSet(State.OPEN) != State.OPEN) {
stopTime = System.currentTimeMillis();
}
}
}
private boolean connectionException(Throwable exception) {
return exception instanceof SocketException || exception instanceof URISyntaxException
|| exception instanceof UnknownHostException
|| exception instanceof SocketTimeoutException || exception instanceof IOException;
}
private enum State {
/**
* Open state.
*/
OPEN, /**
* Partially open state.
*/
PARTIALLY_OPEN, /**
* Closed state.
*/
CLOSED
}
}
| 29.507042
| 110
| 0.688544
|
597a6bfcba0b40596db9f21afa778e0abfc047af
| 534
|
package com.tony.popwindow.entity;
/**
* Created by tonycheng on 2015/9/19.
*/
public class ProvinceList {
private String province_id;
private String province_name;
public String getProvince_id() {
return province_id;
}
public void setProvince_id(String province_id) {
this.province_id = province_id;
}
public String getProvince_name() {
return province_name;
}
public void setProvince_name(String province_name) {
this.province_name = province_name;
}
}
| 20.538462
| 56
| 0.67603
|
69bb6b1aa440ed9c921c5c16de9f299a5bebe4dc
| 1,096
|
package io.github.sdacode;
import com.amazonaws.services.secretsmanager.AWSSecretsManager;
import com.amazonaws.services.secretsmanager.model.GetSecretValueRequest;
import com.amazonaws.services.secretsmanager.model.GetSecretValueResult;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
public class SecretsManagerPropertySourceTest {
@Test
public void testProperty() {
final String ID = "AwsSecretsManager::test", EXPECTED = "success";
var client = Mockito.mock(AWSSecretsManager.class);
var response = new GetSecretValueResult().withSecretString(EXPECTED);
Mockito
.when(client.getSecretValue(ArgumentMatchers.any(GetSecretValueRequest.class)))
.thenReturn(response);
Assertions.assertEquals(EXPECTED, new SecretsManagerPropertySource(client).getProperty(ID));
}
@Test
public void testPropertyInvalid() {
Assertions.assertNull(new SecretsManagerPropertySource(null).getProperty("test-notfound"));
}
}
| 36.533333
| 100
| 0.757299
|
f7e96e6c90f3233a1d900d99224fbe40ef075e71
| 4,290
|
package fi.om.municipalityinitiative.service.email;
import com.google.common.collect.Lists;
import com.mysema.commons.lang.Assert;
import fi.om.municipalityinitiative.conf.EnvironmentSettings;
import fi.om.municipalityinitiative.dao.EmailDao;
import fi.om.municipalityinitiative.util.EmailAttachmentType;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;
public class EmailMessageConstructor {
@Resource
private EnvironmentSettings environmentSettings;
@Resource
private FreeMarkerConfigurer freemarkerConfig;
@Resource
private EmailDao emailDao;
private static final Logger log = LoggerFactory.getLogger(EmailMessageConstructor.class);
private String solveEmailFrom() {
return "Kuntalaisaloitepalvelu" + (environmentSettings.hasAnyTestOptionsEnabled() ? " TEST" : "");
}
private String processTemplate(String templateName, Map<String, Object> dataMap) {
final Configuration cfg = freemarkerConfig.getConfiguration();
try {
Template template;
template = cfg.getTemplate("emails/" + templateName + ".ftl");
Writer out = new StringWriter();
template.process(dataMap, out);
out.flush();
return out.toString();
} catch (IOException | TemplateException e) {
throw new RuntimeException(e);
}
}
public EmailMessageDraft fromTemplate(Long initiativeId, String templateName) {
return new EmailMessageDraft(initiativeId, templateName);
}
public class EmailMessageDraft {
private final Long initiativeId;
private final String templateName;
private List<String> recipients = Lists.newArrayList();
private String subject;
private Map<String, Object> dataMap;
private EmailAttachmentType attachmentType = EmailAttachmentType.NONE;
public EmailMessageDraft(Long initiativeId, String templateName) {
this.initiativeId = initiativeId;
this.templateName = templateName;
}
public EmailMessageDraft withSubject(String subject) {
this.subject = subject;
return this;
}
public EmailMessageDraft addRecipients(List<String> givenRecipients) {
this.recipients.addAll(givenRecipients);
return this;
}
public EmailMessageDraft addRecipient(String sendTo) {
this.recipients.add(sendTo);
return this;
}
public EmailMessageDraft withDataMap(Map<String, Object> dataMap) {
this.dataMap = dataMap;
return this;
}
public void send() {
Assert.isTrue(recipients.size() > 0, "recipients");
Assert.notNull(subject, "subject");
Assert.notNull(templateName, "templateName");
Assert.notNull(dataMap, "dataMap");
log.info("Persisting email to " + recipients + ": " + subject);
emailDao.addEmail(initiativeId, subject, recipients,
processTemplate(templateName + "-html", dataMap),
processTemplate(templateName + "-text", dataMap),
solveEmailFrom(),
environmentSettings.getDefaultReplyTo(),
attachmentType
);
// Uncomment this if you want to print all email-html files for preview etc and run EmailTests.
// try {
// String content = processTemplate(templateName + "-html", dataMap);
// new FileOutputStream(subject.replace("/", "")+".html").write(content.getBytes());
// } catch (IOException e) {
// e.printStackTrace();
// }
}
public EmailMessageDraft withAttachment(EmailAttachmentType attachmentType) {
this.attachmentType = attachmentType;
return this;
}
}
}
| 34.878049
| 107
| 0.652448
|
9cbd3e8adc0451913211154b04b440bedce108fe
| 4,459
|
/*
* Copyright (C) the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.iff.infra.util.jaxrs.gson;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import com.google.common.base.Charsets;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.gson.Gson;
import com.google.gson.stream.JsonWriter;
/**
* Base class from Gson-based JSON JAX-RS providers.
* @author Andres Rodriguez.
*/
public abstract class GenericGsonProvider<T> implements MessageBodyReader<T>, MessageBodyWriter<T> {
/** Gson supplier. */
private final Supplier<Gson> supplier;
/**
* Constructor.
* @param supplier Gson supplier to use.
*/
protected GenericGsonProvider(Supplier<Gson> supplier) {
this.supplier = checkNotNull(supplier, "The Gson supplier must be provided");
}
/**
* Constructor.
* @param gson Gson instance to use.
*/
protected GenericGsonProvider(Gson gson) {
this(Suppliers.ofInstance(checkNotNull(gson, "The Gson instance must be provided")));
}
/** Default constructor. */
protected GenericGsonProvider() {
this(new Gson());
}
/** Returns the Gson object to use. */
protected final Gson getGson() {
return checkNotNull(supplier.get(), "The provided Gson object is null");
}
/*
* (non-Javadoc)
* @see javax.ws.rs.ext.MessageBodyReader#isReadable(java.lang.Class, java.lang.reflect.Type,
* java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType)
*/
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return true;
}
/*
* (non-Javadoc)
* @see javax.ws.rs.ext.MessageBodyReader#readFrom(java.lang.Class, java.lang.reflect.Type,
* java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType, javax.ws.rs.core.MultivaluedMap,
* java.io.InputStream)
*/
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
return getGson().fromJson(new InputStreamReader(entityStream, Charsets.UTF_8), type);
}
/*
* (non-Javadoc)
* @see javax.ws.rs.ext.MessageBodyWriter#isWriteable(java.lang.Class, java.lang.reflect.Type,
* java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType)
*/
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return true;
}
/*
* (non-Javadoc)
* @see javax.ws.rs.ext.MessageBodyWriter#getSize(java.lang.Object, java.lang.Class,
* java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType)
*/
public long getSize(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return -1;
}
/*
* (non-Javadoc)
* @see javax.ws.rs.ext.MessageBodyWriter#writeTo(java.lang.Object, java.lang.Class,
* java.lang.reflect.Type, java.lang.annotation.Annotation[], javax.ws.rs.core.MediaType,
* javax.ws.rs.core.MultivaluedMap, java.io.OutputStream)
*/
public void writeTo(T t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException,
WebApplicationException {
final Writer w = new OutputStreamWriter(entityStream, Charsets.UTF_8);
final JsonWriter jsw = new JsonWriter(w);
getGson().toJson(t, type, jsw);
jsw.close();
}
}
| 34.565891
| 118
| 0.74658
|
377d37a48f67dc404aad5fb83a09379c42b3287e
| 1,314
|
/*
Copyright 2018, Infor 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.logicblox.cloudstore;
/**
* CommandOptions holds shared properties used by all options. Builders
* are used to create the CommandOptions objects that configure
* cloud-store command execution.
*
* @see CommandOptionsBuilder
* @see OptionsBuilderFactory
* @see CloudStoreClient#getOptionsBuilderFactory()
*/
public class CommandOptions
{
private final CloudStoreClient _cloudStoreClient;
CommandOptions(CloudStoreClient cloudStoreClient)
{
_cloudStoreClient = cloudStoreClient;
}
/**
* Return the CloudStoreClient interface used to create these options.
*
* @return cloud store service interface
*/
public CloudStoreClient getCloudStoreClient()
{
return _cloudStoreClient;
}
}
| 27.957447
| 74
| 0.758752
|
55ae724a099218b20adb7aac994c7be7e64c6e6b
| 17,228
|
package com.fitpay.android.paymentdevice.impl.ble;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import com.fitpay.android.paymentdevice.constants.States;
import com.fitpay.android.paymentdevice.enums.ApduExecutionError;
import com.fitpay.android.paymentdevice.impl.ble.message.ApduResultMessage;
import com.fitpay.android.paymentdevice.impl.ble.message.ApplicationControlMessage;
import com.fitpay.android.paymentdevice.impl.ble.message.ContinuationControlBeginMessage;
import com.fitpay.android.paymentdevice.impl.ble.message.ContinuationControlEndMessage;
import com.fitpay.android.paymentdevice.impl.ble.message.ContinuationControlMessage;
import com.fitpay.android.paymentdevice.impl.ble.message.ContinuationControlMessageFactory;
import com.fitpay.android.paymentdevice.impl.ble.message.ContinuationPacketMessage;
import com.fitpay.android.paymentdevice.impl.ble.message.NotificationMessage;
import com.fitpay.android.paymentdevice.impl.ble.message.SecurityStateMessage;
import com.fitpay.android.paymentdevice.interfaces.ISecureMessage;
import com.fitpay.android.paymentdevice.interfaces.PaymentDeviceConnectable;
import com.fitpay.android.paymentdevice.utils.Crc32;
import com.fitpay.android.utils.FPLog;
import com.fitpay.android.utils.Hex;
import com.fitpay.android.utils.RxBus;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import io.reactivex.Completable;
import io.reactivex.CompletableEmitter;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
/**
* Manager that works with Bluetooth GATT Profile.
**/
final class GattManager {
private static final String TAG = GattManager.class.getSimpleName();
private PaymentDeviceConnectable paymentDeviceConnector;
private Context mContext;
private BluetoothGatt mGatt;
private BluetoothDevice mDevice;
private OperationQueue mQueue;
private GattOperation mCurrentOperation = null;
private ContinuationPayload mContinuationPayload = null;
private int mLastApduSequenceId;
private Disposable mCurrentOperationTimeout;
public GattManager(PaymentDeviceConnectable paymentDeviceConnector, Context context, BluetoothDevice device) {
this.paymentDeviceConnector = paymentDeviceConnector;
mContext = context;
mDevice = device;
mQueue = new OperationQueue();
}
public void reconnect() {
queue(new GattSubscribeOperation());
}
public synchronized void disconnect() {
if (mCurrentOperationTimeout != null) {
mCurrentOperationTimeout.dispose();
}
setCurrentOperation(null);
mQueue.clear();
paymentDeviceConnector.setState(States.DISCONNECTING);
if (mGatt != null) {
mGatt.disconnect();
}
}
public synchronized void close() {
mQueue.clear();
if (mGatt != null) {
mGatt.close();
mGatt = null;
}
}
public synchronized void cancelCurrentOperationBundle() {
FPLog.w(TAG, "Cancelling current operation. Queue size before: " + mQueue.size());
processError(ApduExecutionError.ON_TIMEOUT);
}
public synchronized void queue(GattOperation gattOperation) {
mQueue.add(gattOperation);
FPLog.i(TAG, "Queueing Gatt operation, size will now become: " + mQueue.size());
drive();
}
private synchronized void drive() {
if (mCurrentOperation != null) {
FPLog.e(TAG, "tried to drive, but currentOperation was not null, " + mCurrentOperation);
return;
}
if (mQueue.size() == 0) {
FPLog.i(TAG, "Queue empty, drive loop stopped.");
mCurrentOperation = null;
if (mCurrentOperationTimeout != null) {
mCurrentOperationTimeout.dispose();
}
return;
}
final GattOperation operation = mQueue.getFirst();
setCurrentOperation(operation);
resetTimer(operation.getTimeoutMs());
if (operation instanceof GattApduBaseOperation) {
mLastApduSequenceId = ((GattApduBaseOperation) operation).getSequenceId();
}
if (mGatt != null) {
execute(mGatt, operation);
} else {
paymentDeviceConnector.setState(States.CONNECTING);
mDevice.connectGatt(mContext, false, new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
switch (newState) {
case BluetoothProfile.STATE_CONNECTED:
paymentDeviceConnector.setState(States.CONNECTED);
FPLog.i(TAG, "Gatt connected to device " + mDevice.getAddress());
mGatt = gatt;
mGatt.discoverServices();
break;
case BluetoothProfile.STATE_DISCONNECTED:
paymentDeviceConnector.setState(States.DISCONNECTED);
FPLog.i(TAG, "Disconnected from gatt server " + mDevice.getAddress() + ", newState: " + newState);
setCurrentOperation(null);
//Fix: Android Issue 97501: BLE reconnect issue
if (mGatt != null) {
close();
} else {
mQueue.clear();
gatt.close();
}
break;
case BluetoothProfile.STATE_CONNECTING:
paymentDeviceConnector.setState(States.CONNECTING);
break;
case BluetoothProfile.STATE_DISCONNECTING:
paymentDeviceConnector.setState(States.DISCONNECTING);
break;
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
FPLog.d(TAG, "services discovered, status: " + status);
execute(gatt, operation);
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
if (mCurrentOperation instanceof DataReader) {
((DataReader) mCurrentOperation).onRead(characteristic.getValue());
}
driveNext();
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
FPLog.d(TAG, "Characteristic " + characteristic.getUuid() + "written to on device " + mDevice.getAddress());
driveNext();
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
UUID uuid = characteristic.getUuid();
byte[] value = characteristic.getValue();
FPLog.d(TAG, "Characteristic changed: " + uuid);
if (PaymentServiceConstants.CHARACTERISTIC_SECURITY_STATE.equals(uuid)) {
ISecureMessage securityStateMessage = new SecurityStateMessage().withData(value);
RxBus.getInstance().post(paymentDeviceConnector.id(), securityStateMessage);
} else if (PaymentServiceConstants.CHARACTERISTIC_NOTIFICATION.equals(uuid)) {
NotificationMessage notificationMessage = new NotificationMessage().withData(value);
RxBus.getInstance().post(paymentDeviceConnector.id(), notificationMessage);
} else if (PaymentServiceConstants.CHARACTERISTIC_APDU_RESULT.equals(uuid)) {
ApduResultMessage apduResultMessage = new ApduResultMessage().withMessage(value);
if (mLastApduSequenceId == apduResultMessage.getSequenceId()) {
postMessage(apduResultMessage);
// RxBus.getInstance().post(apduResultMessage);
// driveNext();
} else {
FPLog.e(TAG, "Wrong sequenceID. lastSequenceID:" + mLastApduSequenceId + " currentID:" + apduResultMessage.getSequenceId());
processError(ApduExecutionError.WRONG_SEQUENCE);
}
} else if (PaymentServiceConstants.CHARACTERISTIC_CONTINUATION_CONTROL.equals(uuid)) {
FPLog.d(TAG, "continuation control write received [" + Hex.bytesToHexString(value) + "], length [" + value.length + "]");
ContinuationControlMessage continuationControlMessage = ContinuationControlMessageFactory.withMessage(value);
FPLog.d(TAG, "continuation control message: " + continuationControlMessage);
// start continuation packet
if (continuationControlMessage instanceof ContinuationControlBeginMessage) {
if (mContinuationPayload != null) {
FPLog.d(TAG, "continuation was previously started, resetting to blank");
}
mContinuationPayload = new ContinuationPayload(((ContinuationControlBeginMessage) continuationControlMessage).getUuid());
FPLog.d(TAG, "continuation start control received, ready to receive continuation data");
} else if (continuationControlMessage instanceof ContinuationControlEndMessage) {
FPLog.d(TAG, "continuation control end received. process update to characteristic: " + mContinuationPayload.getTargetUuid());
UUID targetUuid = mContinuationPayload.getTargetUuid();
byte[] payloadValue;
try {
payloadValue = mContinuationPayload.getValue();
mContinuationPayload = null;
FPLog.d(TAG, "complete continuation data [" + Hex.bytesToHexString(payloadValue) + "]");
} catch (IOException e) {
FPLog.e(TAG, "error parsing continuation data" + e.getMessage());
processError(ApduExecutionError.CONTINUATION_ERROR);
return;
}
long checkSumValue = Crc32.getCRC32Checksum(payloadValue);
long expectedChecksumValue = ((ContinuationControlEndMessage) continuationControlMessage).getChecksum();
if (checkSumValue != expectedChecksumValue) {
FPLog.e(TAG, "Checksums not equal. input data checksum: " + checkSumValue
+ ", expected value as provided on continuation end: " + expectedChecksumValue);
processError(ApduExecutionError.WRONG_CHECKSUM);
return;
}
if (PaymentServiceConstants.CHARACTERISTIC_APDU_RESULT.equals(targetUuid)) {
FPLog.d(TAG, "continuation is for APDU Result");
ApduResultMessage apduResultMessage = new ApduResultMessage().withMessage(payloadValue);
// RxBus.getInstance().post(apduResultMessage);
//
// driveNext();
postMessage(apduResultMessage);
} else {
FPLog.w(TAG, "Code does not handle continuation for characteristic: " + targetUuid);
processError(ApduExecutionError.CONTINUATION_ERROR);
}
}
} else if (PaymentServiceConstants.CHARACTERISTIC_CONTINUATION_PACKET.equals(uuid)) {
FPLog.d(TAG, "continuation data packet received [" + Hex.bytesToHexString(value) + "]");
ContinuationPacketMessage continuationPacketMessage = new ContinuationPacketMessage().withMessage(value);
FPLog.d(TAG, "parsed continuation packet message: " + continuationPacketMessage);
if (mContinuationPayload == null) {
FPLog.e(TAG, "invalid continuation, no start received on control characteristic");
processError(ApduExecutionError.CONTINUATION_ERROR);
return;
}
try {
mContinuationPayload.processPacket(continuationPacketMessage);
} catch (Exception e) {
FPLog.e(TAG, "exception handling continuation packet:" + e.getMessage());
processError(ApduExecutionError.CONTINUATION_ERROR);
}
} else if (PaymentServiceConstants.CHARACTERISTIC_APPLICATION_CONTROL.equals(uuid)) {
ApplicationControlMessage applicationControlMessage = new ApplicationControlMessage()
.withData(value);
RxBus.getInstance().post(paymentDeviceConnector.id(), applicationControlMessage);
}
}
@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorRead(gatt, descriptor, status);
if (mCurrentOperation instanceof DataReader) {
((GattDescriptorReadOperation) mCurrentOperation).onRead(descriptor.getValue());
}
driveNext();
}
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
driveNext();
}
});
}
}
private void driveNext() {
setCurrentOperation(null);
drive();
}
private void execute(BluetoothGatt gatt, GattOperation operation) {
if (operation != mCurrentOperation) {
return;
}
operation.execute(gatt);
if (operation.canRunNextOperation()) {
driveNext();
}
}
public synchronized void setCurrentOperation(GattOperation currentOperation) {
mCurrentOperation = currentOperation;
}
private void processError(@ApduExecutionError.Reason int reason) {
GattOperation parent = null;
if (mCurrentOperation != null) {
parent = GattOperation.getRoot(mCurrentOperation);
mQueue.remove(parent);
}
if (parent != null && parent instanceof GattApduOperation) {
RxBus.getInstance().post(paymentDeviceConnector.id(), new ApduExecutionError(reason));
} else {
driveNext();
}
}
private void resetTimer(final long timeout) {
if (mCurrentOperationTimeout != null) {
mCurrentOperationTimeout.dispose();
}
mCurrentOperationTimeout = Single.timer(timeout, TimeUnit.MILLISECONDS)
.doOnDispose(() -> FPLog.i(TAG, "The timeout was cancelled, so we do nothing."))
.subscribe(x -> {
FPLog.i(TAG, "Timeout ran to completion, time to cancel the entire operation bundle. Abort, abort!");
cancelCurrentOperationBundle();
});
}
@SuppressWarnings("CheckResult")
private void postMessage(final ApduResultMessage message) {
RxBus.getInstance().post(paymentDeviceConnector.id(), message);
Completable.create(CompletableEmitter::onComplete)
.compose(RxBus.applySchedulersMainThread(Completable.class))
.subscribe(this::driveNext, throwable -> {
});
}
}
| 43.725888
| 154
| 0.588112
|
450c0d9bc72d930e7b3abbd872ff16bd2d3474ae
| 1,262
|
package classify.tree;
import tools.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class BinaryTreeInorderTraversal {
/**
* Recursive Approach
* T(n) = O(n) 0ms 100.00%
* S(n) = O(log n) 36.1MB 75.34%
*/
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
helper(root, res);
return res;
}
private void helper(TreeNode root, List<Integer> res) {
if (root != null) {
helper(root.left, res);
res.add(root.val);
helper(root.right, res);
}
}
/**
* Iterating method using Stack
* T(n) = O(n) 0ms 100.00%
* S(n) = O(n) 36.2MB 40.53%
*/
public List<Integer> inorderTraversal2(TreeNode root) {
List<Integer> res = new ArrayList<>();
LinkedList<TreeNode> stack = new LinkedList<>();
TreeNode cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
res.add(cur.val);
cur = cur.right;
}
return res;
}
}
| 23.37037
| 59
| 0.517433
|
0ec338950bab4f686567fece5240672376bea600
| 1,575
|
package com.terwergreen.test;
import com.terwergreen.dao.IUSerDao;
import com.terwergreen.io.Resources;
import com.terwergreen.pojo.User;
import com.terwergreen.sqlsession.SqlSession;
import com.terwergreen.sqlsession.SqlSessionFactory;
import com.terwergreen.sqlsession.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
/**
* 测试类
*
* @name: IPersistenceTest
* @author: terwer
* @date: 2022-03-14 13:01
**/
public class IPersistenceTest {
@Test
public void test() throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = new User();
user.setId(1);
user.setUsername("tyw");
IUSerDao userDao = sqlSession.getMapper(IUSerDao.class);
User user2 = userDao.findByCondition(user);
System.out.println(user2);
}
@Test
public void test2() throws Exception {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
IUSerDao userDao = sqlSession.getMapper(IUSerDao.class);
List<User> userList = userDao.findAll();
for (User user : userList) {
System.out.println(user);
}
}
}
| 30.882353
| 101
| 0.712381
|
b2b21448789f99691b1faf3412381e8de212b1ba
| 667
|
package com.sds3.dsvendas.dto;
import com.sds3.dsvendas.entities.Seller;
import java.io.Serializable;
public class SaleSumDTO implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Double sum;
public SaleSumDTO() {
}
public SaleSumDTO(Seller seller, Double sum) {
this.name = seller.getName();
this.sum = sum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSum() {
return sum;
}
public void setSum(Double sum) {
this.sum = sum;
}
}
| 18.027027
| 52
| 0.62069
|
8ee076d24d0f5547b1ca17882c0ca7c582244919
| 14,897
|
/*
* 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.empire.jsf2.components;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.convert.ConverterException;
import javax.faces.view.AttachedObjectHandler;
import org.apache.empire.data.Column;
import org.apache.empire.db.DBRecord;
import org.apache.empire.db.exceptions.FieldIllegalValueException;
import org.apache.empire.exceptions.EmpireException;
import org.apache.empire.exceptions.InvalidArgumentException;
import org.apache.empire.jsf2.controls.InputControl;
import org.apache.empire.jsf2.utils.TagEncodingHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class InputTag extends UIInput implements NamingContainer
{
// Logger
private static final Logger log = LoggerFactory.getLogger(InputTag.class);
// private static final String inpControlPropName = InputControl.class.getSimpleName();
// private static final String inputInfoPropName = InputControl.InputInfo.class.getSimpleName();
protected static final String readOnlyState = "readOnlyState";
protected final TagEncodingHelper helper = new TagEncodingHelper(this, "eInput");
protected InputControl control = null;
protected InputControl.InputInfo inpInfo = null;
protected boolean hasRequiredFlagSet = false;
/*
private static int itemIdSeq = 0;
private final int itemId;
*/
public InputTag()
{
super();
// Debug stuff
/*
itemId = ++itemIdSeq;
if (log.isDebugEnabled())
log.debug("InputTag {} created", itemId);
*/
}
@Override
public String getFamily()
{
return "javax.faces.NamingContainer";
}
protected void saveState()
{
// getStateHelper().put(inpControlPropName, control);
// getStateHelper().put(inputInfoPropName, inpInfo);
getStateHelper().put(readOnlyState, (inpInfo == null));
}
protected boolean initState(FacesContext context)
{
// Check visibility
if (helper.isVisible() == false)
return false; // not visible
// Read only State
Boolean ros = (Boolean) getStateHelper().get(readOnlyState);
if (ros != null && ros.booleanValue())
return false;
// Must have children
if (getChildCount() == 0)
{ log.warn("InputTag has no children! Unable to init Input state for id={}", getClientId());
log.warn("Problem might be related to Mojarra's state context saving for dynamic components (affects all versions > 2.1.6). See com.sun.faces.context.StateContext.java:AddRemoveListener");
return false;
}
// Init Control and inputInfo;
control = helper.getInputControl();
inpInfo = helper.getInputInfo(context);
return (control != null && inpInfo != null);
}
/**
* remember original clientId
* necessary only inside UIData
*/
private String treeClientId = null;
@Override
public boolean visitTree(VisitContext visitContext, VisitCallback callback)
{
FacesContext context = visitContext.getFacesContext();
treeClientId = getClientId(context);
return super.visitTree(visitContext, callback);
}
@Override
public String getClientId(FacesContext context)
{
// Check if dynamic components are being created
if (this.treeClientId != null && control != null && control.isCreatingComponents())
{ // return the original tree client id
return treeClientId;
}
// default behavior
return super.getClientId(context);
}
@Override
public void encodeBegin(FacesContext context)
throws IOException
{
// add label and input components when the view is loaded for the first time
super.encodeBegin(context);
// Check visiblity
if (helper.isVisible() == false)
{ // not visible
setRendered(false);
// Check column
Column column = helper.getColumn();
if (column==null)
throw new InvalidArgumentException("column", null);
// Check record
Object record = helper.getRecord();
if (record!=null && (record instanceof DBRecord))
{ // Record is not null
if (((DBRecord)record).isValid())
{ // Check if column exists
if (((DBRecord)record).getFieldIndex(column)<0)
throw new InvalidArgumentException("column", column.getName());
// not visible
log.info("Column {} is not visible for record of {} and will not be rendered!", column.getName(), ((DBRecord)record).getRowSet().getName());
}
else
{ // Record not valid
log.warn("Invalid Record provided for column {}. Input will not be rendered!", column.getName());
}
}
else
{ // Column not visible
log.warn("Column {} is not visible will not be rendered!", column.getName());
}
return; // not visible
}
// init
helper.encodeBegin();
control = helper.getInputControl();
inpInfo = helper.getInputInfo(context);
// set required
if (hasRequiredFlagSet == false)
super.setRequired(helper.isValueRequired());
// create input
if (this.getChildCount()==0)
{ // create input
control.createInput(this, inpInfo, context);
attachEvents(context);
}
else
{ // update state
control.updateInputState(this, inpInfo, context, true);
}
// set readonly
boolean readOnly = helper.isRecordReadOnly();
setRenderInput(!readOnly);
// render components
if (readOnly)
{ // render value
ResponseWriter writer = context.getResponseWriter();
String tag = writeStartElement(inpInfo, writer);
control.renderValue(inpInfo, writer);
writer.endElement(tag);
}
else
{ // render input
control.renderInput(this, inpInfo, context);
}
saveState();
}
@Override
public void setId(String id)
{
super.setId(id);
// reset record
helper.setRecord(null);
}
@Override
public void processDecodes(FacesContext context)
{
if (helper.isInsideUIData())
{ // Check input controls
if (getChildCount()>0)
{ // Set readOnly and disabled for each row
boolean readOnly = helper.isRecordReadOnly();
setRenderInput(!readOnly);
// get control
if (control==null)
control = helper.getInputControl();
if (inpInfo==null)
inpInfo = helper.getInputInfo(context);
// update control
control.updateInputState(this, inpInfo, context, false);
}
}
// default
super.processDecodes(context);
}
@Override
public void setRequired(boolean required)
{
super.setRequired(required);
// flag has been set
hasRequiredFlagSet = true;
}
@Override
public Object getValue()
{
// check for record
if (helper.getRecord() != null)
return helper.getDataValue(true);
// default
Object value = super.getValue();
return value;
}
@Override
public Object getSubmittedValue()
{ // Check state
if (control == null || inpInfo == null || helper.isReadOnly())
return null;
// get Input Value
return control.getInputValue(this, inpInfo, true);
}
@Override
protected Object getConvertedValue(FacesContext context, Object newSubmittedValue)
throws ConverterException
{ // Check state
if (control == null || inpInfo == null || helper.isReadOnly())
return null;
// parse and convert value
return this.control.getConvertedValue(this, this.inpInfo, newSubmittedValue);
}
@Override
public void validateValue(FacesContext context, Object value)
{ // Check state
if (inpInfo == null)
return;
// Skip Null values if not required
if (UIInput.isEmpty(value) && isPartialSubmit(context)) // && helper.isValueRequired()
{ // Value is null
log.debug("Skipping validation for {} due to Null value.", inpInfo.getColumn().getName());
return;
}
// Validate value
inpInfo.validate(value);
setValid(true);
// don't call base class!
// super.validateValue(context, value);
}
@Override
public void validate(FacesContext context)
{
if (initState(context) == false)
return;
// get submitted value and validate
if (log.isDebugEnabled())
log.debug("Validating input for {}.", inpInfo.getColumn().getName());
// Validate value
try
{ // Will internally call getSubmittedValue() and validateValue()
super.validate(context);
} catch (Exception e) {
// Value is not valid
if (!(e instanceof EmpireException))
e = new FieldIllegalValueException(helper.getColumn(), "", e);
// Add error message
helper.addErrorMessage(context, e);
setValid(false);
}
}
@Override
public void updateModel(FacesContext context)
{
if (initState(context) == false)
return;
// No Action
if (!isValid() || !isLocalValueSet())
return;
// check required
Object value = getLocalValue();
if (UIInput.isEmpty(value) && isPartialSubmit(context) && !helper.isTempoaryNullable())
{ // Value is null, but required
log.debug("Skipping model update for {} due to Null value.", inpInfo.getColumn().getName());
return;
}
// super.updateModel(context);
log.debug("Updating model input for {}.", inpInfo.getColumn().getName());
inpInfo.setValue(value);
setValue(null);
setLocalValueSet(false);
// Post update
control.postUpdateModel(this, inpInfo, context);
}
public Column getInputColumn()
{
return helper.getColumn();
}
public boolean isInputReadOnly()
{
return helper.isRecordReadOnly();
}
public boolean isInputRequired()
{
return helper.isValueRequired();
}
protected void setRenderInput(boolean renderInput)
{
for (UIComponent child : getChildren())
{
if (child.isRendered()!=renderInput)
{
if (log.isDebugEnabled())
log.debug("Changing UIInput rendered state for {} to {}", helper.getColumnName(), renderInput);
child.setRendered(renderInput);
}
}
}
protected boolean isPartialSubmit(FacesContext context)
{
// Check Required Flag
if (hasRequiredFlagSet && !isRequired())
return true;
// partial
return helper.isPartialSubmit(context);
}
/**
* write value element
*
* @param vi
* @param writer
* @return
* @throws IOException
*/
protected String writeStartElement(InputControl.ValueInfo vi, ResponseWriter writer)
throws IOException
{
// tag and class name
String tagName = "span";
String className = helper.getTagStyleClass("eInpDis");
// other attributes
Map<String, Object> map = getAttributes();
Object style = map.get("style");
Object title = map.get("title");
// Write tag
writer.startElement(tagName, this);
helper.writeAttribute(writer, "class", className);
helper.writeAttribute(writer, "style", style);
helper.writeAttribute(writer, "title", helper.getValueTooltip(title));
return tagName;
}
protected void attachEvents(FacesContext context)
{
// Events available?
@SuppressWarnings("unchecked")
List<AttachedObjectHandler> result = (List<AttachedObjectHandler>) getAttributes().get("javax.faces.RetargetableHandlers");
if (result == null)
{
return;
}
UIInput inputComponent = null;
for (UIComponent c : getChildren())
{
if (c instanceof UIInput)
{ // found
inputComponent = (UIInput)c;
break;
}
}
if (inputComponent == null)
return;
// Attach Events
for (AttachedObjectHandler aoh : result)
{
aoh.applyAttachedObject(context, inputComponent);
}
// remove
result.clear();
getAttributes().remove("javax.faces.RetargetableHandlers");
}
}
| 34.011416
| 201
| 0.579848
|
a84e463e6b56fd59074be6f3a2a993750dafb78b
| 1,287
|
package lejos.nxt.startup;
import lejos.nxt.LCD;
/**
* Abrams version of a more detailed GraphicMenu for the file menu.
*
* @author Abram Early
*
*/
public class GraphicListMenu extends GraphicMenu {
public GraphicListMenu(String[] items, String[] icons) {
super(items, icons, -1);
}
@Override
protected void animate(int selectedIndex, int finalIndex, int animateDirection)
{
this.display(finalIndex, animateDirection, 0);
}
@Override
protected void display(int selectedIndex, int animateDirection, int tick)
{
//LCD.asyncRefreshWait();
if(_title != null)
LCD.drawString(_title, 0, _topRow - 1);
int max = _topRow + _height;
for (int i = _topRow; i < max; i++){
LCD.drawString(BLANK, 0, i);
int idx = i - _topRow + _topIndex;
if (idx >= 0 && idx < _length){
LCD.bitBlt(_icons[idx], 7, 8, 0, 0, 6, 8*i, 7, 8, LCD.ROP_COPY);
LCD.drawChar(idx == selectedIndex ? SEL_CHAR : ' ', 0, i);
LCD.drawString(_items[idx], 3, i);
}
}
LCD.asyncRefresh();
}
@Override
public void clearArea(){
LCD.bitBlt(null, 30, 100, 0, 0, 0, 16, 30, 100, LCD.ROP_CLEAR);
}
@Override
protected int getIconSize(){return 7;}// Returns the icon size (In Bytes)
@Override
protected boolean get2IconMode(){return true;}// Wrap With 2 Icons
}
| 24.75
| 80
| 0.665113
|
047e92bb9c35c3b5b0678833632e1480732cc432
| 1,435
|
package nl.jqno.equalsverifier.internal.prefabvalues;
import java.util.HashMap;
import java.util.Map;
/** Contains a cache of prefabricated values, for {@link PrefabValues}. */
class Cache {
@SuppressWarnings("rawtypes")
private final Map<TypeTag, Tuple> cache = new HashMap<>();
/**
* Adds a prefabricated value to the cache for the given type.
*
* @param tag A description of the type. Takes generics into account.
* @param red A "red" value for the given type.
* @param blue A "blue" value for the given type.
* @param redCopy A shallow copy of the given red value.
*/
public <T> void put(TypeTag tag, T red, T blue, T redCopy) {
cache.put(tag, new Tuple<>(red, blue, redCopy));
}
/**
* Returns a {@link Tuple} of prefabricated values for the specified type.
*
* <p>What happens when there is no value, is undefined. Always call {@link #contains(TypeTag)}
* first.
*
* @param tag A description of the type. Takes generics into account.
*/
@SuppressWarnings("unchecked")
public <T> Tuple<T> getTuple(TypeTag tag) {
return cache.get(tag);
}
/**
* Returns whether prefabricated values are available for the given type.
*
* @param tag A description of the type. Takes generics into account.
*/
public boolean contains(TypeTag tag) {
return cache.containsKey(tag);
}
}
| 31.195652
| 99
| 0.644599
|
4ec907e8c29465cbe580d50c52b0e3f3698cf899
| 943
|
package com.arhohuttunen.junit5;
import java.math.BigDecimal;
public class ProductBuilder {
private Long id = 1L;
private String name = "Some product";
private BigDecimal price = BigDecimal.valueOf(5.0);
public static ProductBuilder aProduct() {
return new ProductBuilder();
}
public static ProductBuilder anInvalidProduct() {
ProductBuilder builder = new ProductBuilder();
builder.id = null;
builder.name = null;
builder.price = null;
return builder;
}
public ProductBuilder withId(Long id) {
this.id = id;
return this;
}
public ProductBuilder withName(String name) {
this.name = name;
return this;
}
public ProductBuilder withPrice(Double price) {
this.price = BigDecimal.valueOf(price);
return this;
}
public Product build() {
return new Product(id, name, price);
}
}
| 23
| 55
| 0.626723
|
cd9dea4a5976b88685f549f04525ec25abb0be48
| 3,381
|
package de.b4.fbc.service;
import javax.enterprise.context.ApplicationScoped;
import de.b4.fbc.model.Plan;
import de.b4.fbc.model.Target;
@ApplicationScoped
public class TargetService {
public Target getTarget(Integer day, Plan theplan, Boolean noTraining) {
if (day < 1 || day > plan.length || theplan.getWeight() == 0) {
return null;
}
Target t = new Target();
t.setDay(day);
t.setDate(theplan.getStartDate().plusDays(day));
t.setUser(theplan.getUser());
t.setWeight(theplan.getWeight());
if (noTraining != null && noTraining == true) {
t.setProtein(noTrainingDay.protein * theplan.getWeight());
t.setCarbohydrates(noTrainingDay.carbonate * theplan.getWeight());
t.setFat(noTrainingDay.fat * theplan.getWeight());
}
else {
t.setProtein(plan[day - 1].protein * theplan.getWeight());
t.setCarbohydrates(plan[day - 1].carbonate * theplan.getWeight());
t.setFat(plan[day - 1].fat * theplan.getWeight());
}
return t;
}
public Target[] getAllTargets(Plan theplan) {
Target[] targets = new Target[30];
for (int i = 0; i < plan.length; i++) {
targets[i] = getTarget(i + 1, theplan, false);
}
return targets;
}
static TargetValues noTrainingDay = new TargetValues(2.2, 0.5, 1.0);
static TargetValues[] plan = {
// Day 1 to 7
new TargetValues(2.2, 2.0, 1.0),
new TargetValues(2.2, 2.0, 1.0),
new TargetValues(2.2, 2.0, 1.0),
new TargetValues(2.2, 2.0, 1.0),
new TargetValues(2.2, 2.0, 1.0),
new TargetValues(2.2, 2.0, 1.0),
new TargetValues(2.2, 2.0, 1.0),
// Day 8
new TargetValues(2.2, 4.0, 0.0),
// Day 9 to 15
new TargetValues(2.2, 1.0, 0.8),
new TargetValues(2.2, 1.0, 0.8),
new TargetValues(2.2, 1.0, 0.8),
new TargetValues(2.2, 1.0, 0.8),
new TargetValues(2.2, 1.0, 0.8),
new TargetValues(2.2, 1.0, 0.8),
new TargetValues(2.2, 1.0, 0.8),
// Day 16
new TargetValues(2.2, 4.0, 0.0),
// Day 17 to 30
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5),
new TargetValues(2.2, 1.0, 0.5)
};
public static class TargetValues {
private final Double protein;
private final Double carbonate;
private final Double fat;
public TargetValues(Double protein, Double carbonate, Double fat) {
this.protein = protein;
this.carbonate = carbonate;
this.fat = fat;
}
public Double getProtein() {
return protein;
}
public Double getCarbonate() {
return carbonate;
}
public Double getFat() {
return fat;
}
}
}
| 32.509615
| 78
| 0.546288
|
7b816f192f0bb899c0e4efec53779f99cf2b5ac4
| 2,419
|
package todomvc.smoketests;
import net.serenitybdd.core.environment.EnvironmentSpecificConfiguration;
import net.serenitybdd.junit5.SerenityJUnit5Extension;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import net.serenitybdd.screenplay.actions.Open;
import net.serenitybdd.screenplay.annotations.CastMember;
import net.serenitybdd.screenplay.ensure.Ensure;
import net.serenitybdd.screenplay.targets.SearchableTarget;
import net.serenitybdd.screenplay.ui.PageElement;
import net.thucydides.core.annotations.Managed;
import net.thucydides.core.annotations.SingleBrowser;
import net.thucydides.core.util.EnvironmentVariables;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.util.Locale;
@SingleBrowser
@ExtendWith(SerenityJUnit5Extension.class)
public class WhenCheckingTheTodoMVCApps {
public static final SearchableTarget APP_TITLE = PageElement.located(By.tagName("h3"));
@CastMember
Actor todd;
EnvironmentVariables environmentVariables;
@ParameterizedTest
@CsvSource( {
"pages.vue, Vue.js",
"pages.react, React",
"pages.polymer, Polymer",
})
void shouldOpenTheTodoMVCAppInAngular(String startPage, String expectedTitle) {
String currentDomain = EnvironmentSpecificConfiguration.from(environmentVariables).getProperty(startPage);
todd.attemptsTo(
Open.browserOn().thePageNamed(startPage),
Ensure.that(PageElement.withCSSClass("new-todo")).isDisplayed(),
Ensure.that(APP_TITLE).textContent().isEqualTo(expectedTitle)
);
}
@Test
void shouldOpenTheTodoMVCAppInReact() {
todd.attemptsTo(
Open.url("https://todomvc.com/examples/react/#/"),
Ensure.that(PageElement.withCSSClass("new-todo")).isDisplayed()
);
}
@Test
void shouldOpenTheTodoMVCAppInPolymer() {
todd.attemptsTo(
Open.url("https://todomvc.com/examples/polymer/index.html"),
Ensure.that(PageElement.withCSSClass("new-todo")).isDisplayed()
);
}
}
| 34.557143
| 114
| 0.726333
|
aee68ef8f30926dcd6f351caec556a7d0cf1ee66
| 4,248
|
/********************************************************************************
* Copyright (c) {date} Red Hat Inc. and/or its affiliates and others
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/
package org.eclipse.ceylon.ide.intellij.wizard;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
public abstract class CreateCeylonModuleWizard extends DialogWrapper {
protected JPanel contentPane;
protected JTextField moduleName;
protected JTextField moduleVersion;
protected JTextField compilationUnit;
public CreateCeylonModuleWizard(@NotNull Project project) {
super(project, true);
$$$setupUI$$$();
}
abstract void createUIComponents();
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPane = new JPanel();
contentPane.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayoutManager(4, 2, new Insets(0, 10, 0, 10), -1, -1));
contentPane.add(panel1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(300, -1), null, 1, false));
final Spacer spacer1 = new Spacer();
panel1.add(spacer1, new GridConstraints(3, 0, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
final JLabel label1 = new JLabel();
label1.setText("Module name:");
panel1.add(label1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
moduleName = new JTextField();
panel1.add(moduleName, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(311, 26), null, 0, false));
final JLabel label2 = new JLabel();
label2.setText("Module version:");
panel1.add(label2, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
moduleVersion = new JTextField();
moduleVersion.setText("1.0.0");
panel1.add(moduleVersion, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(311, 26), null, 0, false));
final JLabel label3 = new JLabel();
label3.setText("Runnable unit name:");
panel1.add(label3, new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
compilationUnit.setText("");
panel1.add(compilationUnit, new GridConstraints(2, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(311, 26), null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
}
| 55.168831
| 323
| 0.697505
|
6ca96e43263cff2242e7e4967504ee99f24018a7
| 1,679
|
package cellsociety_team03;
import java.util.*;
public class AntCell extends Cell{
private int homepheromones=100;
private int foodpheromones=100;
private List<AntAnimal> ants;
private boolean foodsource;
private boolean ishome;
private int myfoodpmax;
private int myhomepmax;
private String ANT="ant";
private String BLACK="black";
private String EMPTY="empty";
private String GREEN="green";
private String HOME="home";
private String PURPLE="purple";
private String OBSTACLE="obstacle";
private String FOOD="food";
private String YELLOW="yellow";
private String RED="red";
public AntCell(String state){
super(state);
gettypes().put(ANT, BLACK);
gettypes().put(FOOD, YELLOW);
gettypes().put(EMPTY, GREEN);
gettypes().put(HOME, RED);
gettypes().put(OBSTACLE, PURPLE);
homepheromones=0;
foodpheromones=0;
if(state.equals(HOME)){
ishome=true;
}
if(state.equals(FOOD)){
foodsource=true;
}
}
public void incrementant(AntAnimal ant){
ants.add(ant);
}
public void decrementant(AntAnimal ant){
ants.remove(ant);
}
public boolean getisfoodsource(){
return foodsource;
}
public void incrementfoodpheromones(int x){
foodpheromones+=x;
if (foodpheromones> myfoodpmax){
foodpheromones=myfoodpmax;
}
}
public void incrementhomepheromones(int x){
homepheromones+=x;
if(homepheromones>myhomepmax){
homepheromones=myhomepmax;
}
}
public int getfoodpheromones(){
return foodpheromones;
}
public int gethomepheromones(){
return homepheromones;
}
public int getnumberants(){
return ants.size();
}
public boolean getishome(){
return ishome;
}
}
| 17.489583
| 44
| 0.705777
|
ee0a252a40441f5e709e4743c914c1595f551008
| 3,418
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.sofa.jraft.example.counter.rpc;
import java.nio.ByteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alipay.remoting.AsyncContext;
import com.alipay.remoting.BizContext;
import com.alipay.remoting.exception.CodecException;
import com.alipay.remoting.rpc.protocol.AsyncUserProcessor;
import com.alipay.remoting.serialization.SerializerManager;
import com.alipay.sofa.jraft.entity.Task;
import com.alipay.sofa.jraft.example.counter.CounterServer;
import com.alipay.sofa.jraft.example.counter.IncrementAndAddClosure;
/**
* IncrementAndGetRequest processor.
*
* @author boyan (boyan@alibaba-inc.com)
*
* 2018-Apr-09 5:43:57 PM
*/
public class IncrementAndGetRequestProcessor extends AsyncUserProcessor<IncrementAndGetRequest> {
private static final Logger LOG = LoggerFactory.getLogger(IncrementAndGetRequestProcessor.class);
private final CounterServer counterServer;
public IncrementAndGetRequestProcessor(CounterServer counterServer) {
super();
this.counterServer = counterServer;
}
@Override
public void handleRequest(final BizContext bizCtx, final AsyncContext asyncCtx, final IncrementAndGetRequest request) {
if (!this.counterServer.getFsm().isLeader()) {
asyncCtx.sendResponse(this.counterServer.redirect());
return;
}
final ValueResponse response = new ValueResponse();
final IncrementAndAddClosure closure = new IncrementAndAddClosure(counterServer, request, response,
status -> {
if (!status.isOk()) {
response.setErrorMsg(status.getErrorMsg());
response.setSuccess(false);
}
asyncCtx.sendResponse(response);
});
try {
final Task task = new Task();
task.setDone(closure);
task.setData(ByteBuffer
.wrap(SerializerManager.getSerializer(SerializerManager.Hessian2).serialize(request)));
//调用node处理请求
// apply task to raft group.
LOG.info("task IncrementAndGetRequest delta: "+ request.getDelta());
counterServer.getNode().apply(task);
} catch (final CodecException e) {
LOG.error("Fail to encode IncrementAndGetRequest", e);
response.setSuccess(false);
response.setErrorMsg(e.getMessage());
asyncCtx.sendResponse(response);
}
}
@Override
public String interest() {
return IncrementAndGetRequest.class.getName();
}
}
| 37.56044
| 123
| 0.691633
|
557ba52f6cdd28475cc8e9c606ddc7728533cb01
| 490
|
package com.sark110.sarkplotsandroid;
import android.os.Bundle;
import android.preference.PreferenceFragment;
/**
* SARK Plots for Android software
*
* @author EA4FRB - Melchor Varela <melchor.varela@gmail.com>
* Copyright 2018
*/
public class DefaultPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.default_preferences);
}
}
| 24.5
| 67
| 0.759184
|
1ace4bcb7b766a68361d5f0b604e0affff91e8ff
| 1,354
|
package com.github.lany192.arch.items;
import android.content.Context;
import androidx.annotation.LayoutRes;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.elvishew.xlog.Logger;
import com.elvishew.xlog.XLog;
public abstract class ItemDelegate<T> implements MultiItemEntity {
protected final String TAG = this.getClass().getSimpleName();
private Context mContext;
protected Logger.Builder log = XLog.tag(TAG);
protected final T mData;
public ItemDelegate(final T data) {
this.mData = data;
}
/**
* 根据类class的名称生成对应的唯一id
*
* @return item类型
*/
@Override
public int getItemType() {
return ItemTypeHelper.getInstance().getViewType(this);
}
/**
* 站位的大小,默认是2。如需修改复现该方法
*
* @return 大小
*/
public int getSpanSize() {
return 2;
}
/**
* 返回布局文件id
*
* @return 布局文件id
*/
@LayoutRes
public abstract int getLayoutId();
/**
* 初始化方法
*/
public abstract void init();
public void convert(BaseViewHolder helper, Context context) {
this.mContext = context;
init();
}
public Context getContext() {
return mContext;
}
public T getData() {
return mData;
}
}
| 20.208955
| 66
| 0.629985
|
de4a34cdc9777e8cb325f07b0684fb1189f06578
| 775
|
package uk.gov.hmcts.lifeevents.client.service;
import uk.gov.hmcts.lifeevents.client.api.DeathApiClient;
import uk.gov.hmcts.lifeevents.client.model.V1Death;
import java.time.LocalDate;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class DeathService {
private final DeathApiClient deathApiClient;
public DeathService(DeathApiClient deathApiClient) {
this.deathApiClient = deathApiClient;
}
public List<V1Death> searchForDeathRecordsByNamesAndDate(String forenames, String surname, LocalDate date){
return deathApiClient.searchV1Death(forenames, surname, date).getBody();
}
public V1Death getDeathRecordById(Integer id){
return deathApiClient.readV1Death(id).getBody();
}
}
| 27.678571
| 111
| 0.769032
|
9465771d51ac1e9a6f79587f40d61e870b7600d2
| 9,584
|
package com.fdzc.oracle0.dao;
import com.fdzc.oracle0.bean.Game;
import com.fdzc.oracle0.bean.User;
import com.fdzc.oracle0.bean.UserType;
import com.fdzc.oracle0.utils.DBUtils;
import oracle.jdbc.OracleCallableStatement;
import org.springframework.stereotype.Repository;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
@Repository
public class UserDaoImpl implements IUserDao{
private List<User> users;
private void setTestUser(){
users = new ArrayList<>();
users.add(new User(1001, UserType.DEFAULT ,"TypeAlpha","123456aa","",10000,"TypeAlpha12333"));
users.add(new User(1002, UserType.DEFAULT ,"Komachi","123456aa","",10000,"Komachi12333"));
users.add(new User(1003, UserType.DEFAULT ,"Kirin","123456aa","",10000,"Kirin12333"));
users.add(new User(1004, UserType.ADMINISTER ,"G_fat","123456aa","",10000,"G_fat12333"));
}
@Override
public List<Game> getUserGames(int uid) {
return null;
}
@Override
public void addUser(User user) {
Connection conn = DBUtils.getConn();
String SQL_ADD_USERS = "insert into TBL_USERS values(t_user_id_seq.nextval,?,?,?,'/',0,?)";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL_ADD_USERS);
switch (user.getType()){
case DEFAULT:
pstmt.setInt(1,0);
break;
case ADMINISTER:
pstmt.setInt(1,1);
break;
case DEACTIVATED:
pstmt.setInt(1,2);
break;
case BANNED:
pstmt.setInt(1,3);
break;
}
pstmt.setString(2,user.getName());
pstmt.setString(3,user.getPassword());
// 还管他什么加密算法?
pstmt.setString(4,user.getName()+"1234555");
pstmt.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
@Override
public void changePass(int uid,String password) { // 修改密码
Connection conn = DBUtils.getConn();
String SQL_UPD_PSS = "update TBL_USERS set PASSWORD = ? where USERID = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL_UPD_PSS);
pstmt.setString(1,password);
pstmt.setInt(2,uid);
pstmt.executeUpdate();
//update: insert,delete,update. query: select
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void banUser(int uid) {
Connection conn = DBUtils.getConn();
String SQL_DELETE_USERS = "delete from TBL_USERS where userid = ?";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL_DELETE_USERS);
pstmt.setInt(1,uid);
pstmt.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
@Override
public User getUser(int uid) {
CallableStatement call = null;
ResultSet rs = null;
User user = new User();
Connection conn = DBUtils.getConn();
try {
call = conn.prepareCall("{ call GetUserByID(?,?) }");
call.setInt(1, uid);
call.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR); //需要注册输出的参数
call.execute(); //执行存储过程
rs = ((OracleCallableStatement) call).getCursor(2); //获取结果
user.setUid(rs.getInt("UID"));
switch (rs.getInt("TYPE")){
case 0:
user.setType(UserType.DEFAULT);
break;
case 1:
user.setType(UserType.ADMINISTER);
break;
case 2:
user.setType(UserType.DEACTIVATED);
break;
case 3:
user.setType(UserType.BANNED);
break;
}
user.setName(rs.getString("NAME"));
user.setPassword(rs.getString("PASSWORD"));
user.setAvatar(rs.getString("AVATAR"));
user.setBalance(rs.getInt("BALANCE"));
user.setCookie(rs.getString("COOKIE"));
} catch (SQLException e) {
e.printStackTrace();
}
return user;
/* setTestUser();
for(User u:users){
if(uid==u.getUid()){
return u;
}
}
return null;*/
}
@Override
public User getUser(String name) {
CallableStatement call = null;
ResultSet rs = null;
User user = new User();
Connection conn = DBUtils.getConn();
try {
call = conn.prepareCall("{ call GetUserByName(?,?) }");
call.setString(1, name);
call.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR); //需要注册输出的参数
call.execute(); //执行存储过程
rs = ((OracleCallableStatement) call).getCursor(2); //获取结果
rs.next();
user.setUid(rs.getInt("USERID"));
switch (rs.getInt("TYPE")){
case 0:
user.setType(UserType.DEFAULT);
break;
case 1:
user.setType(UserType.ADMINISTER);
break;
case 2:
user.setType(UserType.DEACTIVATED);
break;
case 3:
user.setType(UserType.BANNED);
break;
}
user.setName(rs.getString("NAME"));
user.setPassword(rs.getString("PASSWORD"));
user.setAvatar(rs.getString("AVATAR"));
user.setBalance(rs.getInt("SURPLUS"));
user.setCookie(rs.getString("COOKIE"));
} catch (SQLException e) {
e.printStackTrace();
}
return user;
/*// 设置测试用代码
setTestUser();
for(User u:users){
if(name.equals(u.getName())){
return u;
}
}
return null;*/
}
@Override
public User getUserByCookie(String cookie) {
CallableStatement call = null;
ResultSet rs = null;
User user = new User();
Connection conn = DBUtils.getConn();
try {
call = conn.prepareCall("{ call GetUserByCookie(?,?) }");
call.setString(1, cookie);
call.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR); //需要注册输出的参数
call.execute(); //执行存储过程
rs = ((OracleCallableStatement) call).getCursor(2); //获取结果
rs.next();
user.setUid(rs.getInt("USERID"));
switch (rs.getInt("TYPE")){
case 0:
user.setType(UserType.DEFAULT);
break;
case 1:
user.setType(UserType.ADMINISTER);
break;
case 2:
user.setType(UserType.DEACTIVATED);
break;
case 3:
user.setType(UserType.BANNED);
break;
}
user.setName(rs.getString("NAME"));
user.setPassword(rs.getString("PASSWORD"));
user.setAvatar(rs.getString("AVATAR"));
user.setBalance(rs.getInt("SURPLUS"));
user.setCookie(rs.getString("COOKIE"));
} catch (SQLException e) {
e.printStackTrace();
}
return user;
/* setTestUser();
for (User u:users){
if(cookie.equals(u.getCookie())){
return u;
}
}
return null;*/
}
@Override
public List<User> getUsers(String keyword,int page) {
List<User> users = new ArrayList<>();
Connection conn = DBUtils.getConn();
String SQL_SELECT_USERS = "select * from TBL_USERS where rownum >= ? and rownum <= ? and name like ?";
try {
PreparedStatement pstmt = conn.prepareStatement(SQL_SELECT_USERS);
pstmt.setInt(1,(page-1)*10+1);
pstmt.setInt(2,page*10);
pstmt.setString(3,"%"+keyword+"%");
ResultSet rset = pstmt.executeQuery();
while (rset.next()){
User user = new User();
user.setUid(rset.getInt("USERID"));
switch (rset.getInt("TYPE")){
case 0:
user.setType(UserType.DEFAULT);
break;
case 1:
user.setType(UserType.ADMINISTER);
break;
case 2:
user.setType(UserType.DEACTIVATED);
break;
case 3:
user.setType(UserType.BANNED);
break;
}
user.setName(rset.getString("NAME"));
user.setPassword(rset.getString("PASSWORD"));
user.setAvatar(rset.getString("AVATAR"));
user.setBalance(rset.getInt("SURPLUS"));
user.setCookie(rset.getString("COOKIE"));
users.add(user);
}
//update: insert,delete,update. query: select
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
@Override
public boolean setBalance(int uid) {
return false;
}
}
| 32.26936
| 110
| 0.506782
|
c0b96c13665bc2f0fd8489435147b321555ea1bf
| 2,622
|
/*==============================================================================
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 gr.forth;
import gr.forth.ics.isl.x3ml.X3MLGeneratorPolicy.CustomGenerator;
import gr.forth.ics.isl.x3ml.X3MLGeneratorPolicy.CustomGeneratorException;
import lombok.extern.log4j.Log4j;
/**
*
*/
@Log4j
public class DateRangeLabel implements CustomGenerator {
private String date1 = "";
private String date2 = "";
@Override
public void setArg(String name, String value) throws CustomGeneratorException {
if ("date1".equals(name)) {
date1 = value;
} else if ("date2".equals(name)) {
date2 = value;
} else {
throw new CustomGeneratorException("Unrecognized argument name: " + name);
}
}
@Override
public String getValue() throws CustomGeneratorException {
if (date1.equalsIgnoreCase(date2)) {
return date1;
}
if (!date1.isEmpty() && !date2.isEmpty()) {
return (date1 + " - " + date2);
}
if (date1.isEmpty()) {
return date2;
} else {
return date1;
}
}
@Override
public String getValueType() throws CustomGeneratorException {
return "Literal";
}
@Override
public void usesNamespacePrefix() {
log.debug("The "+this.getClass().getName()+" custom generator creates only Literals therefore it does not support injecting prefix");
;
}
/** Returns a boolean flag (with value set to false) indicating that this
* generator DOES NOT support merging values from similar elements
* (elements having the same name).
*
* @return false*/
@Override
public boolean mergeMultipleValues(){
return false;
}
}
| 32.37037
| 141
| 0.630435
|
d9b31192eb549c30bf6b6f4b121bb1efffc51830
| 144
|
import javax.ws.rs.GET;
import javax.ws.rs.Path;
@Path("secure")
public class SecuredResource {
@GET
public void securedMethod(){
}
}
| 11.076923
| 30
| 0.6875
|
74deeeb9002f34c5fc377e0520119c7a299b1ef9
| 989
|
package com.whcm.report.mapper;
import com.whcm.report.domain.Banner;
import java.util.List;
/**
* 轮播图 数据层
*
* @author dong.chao
* @date 2019-03-28
*/
public interface BannerMapper
{
/**
* 查询轮播图信息
*
* @param bannerId 轮播图ID
* @return 轮播图信息
*/
public Banner selectBannerById(Integer bannerId);
/**
* 查询轮播图列表
*
* @param banner 轮播图信息
* @return 轮播图集合
*/
public List<Banner> selectBannerList(Banner banner);
/**
* 新增轮播图
*
* @param banner 轮播图信息
* @return 结果
*/
public int insertBanner(Banner banner);
/**
* 修改轮播图
*
* @param banner 轮播图信息
* @return 结果
*/
public int updateBanner(Banner banner);
/**
* 删除轮播图
*
* @param bannerId 轮播图ID
* @return 结果
*/
public int deleteBannerById(Integer bannerId);
/**
* 批量删除轮播图
*
* @param bannerIds 需要删除的数据ID
* @return 结果
*/
public int deleteBannerByIds(String[] bannerIds);
}
| 15.951613
| 53
| 0.571284
|
feac513c1d7170149d4fdcf7c9547cc08c61ea04
| 1,558
|
package br.copacabana.cache;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import br.com.copacabana.cb.entities.MealOrder;
import br.com.copacabana.cb.entities.Restaurant;
import com.google.appengine.api.datastore.Key;
public class OrdersCacheEntry implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4118182471330264172L;
private Map<Key, Set<Long>> newOrdersByRestaurant = new HashMap<Key, Set<Long>>();
private long logicClock = 0;
public void addOrder(MealOrder mo) {
logicClock++;
Set<Long> setList = newOrdersByRestaurant.get(mo.getRestaurant());
if (setList == null) {
setList = new HashSet<Long>();
}
setList.add(mo.getId().getId());
newOrdersByRestaurant.put(mo.getRestaurant(), setList);
}
public void removeOrder(MealOrder mo) {
logicClock++;
Set<Long> setList = newOrdersByRestaurant.get(mo.getRestaurant());
if (setList != null) {
setList.remove(mo.getId().getId());
newOrdersByRestaurant.put(mo.getRestaurant(), setList);
}
}
public boolean hasNewOrders(Restaurant rest) {
return this.hasNewOrders(rest.getId());
}
public long getLogicClock() {
return logicClock;
}
public boolean hasAny() {
return newOrdersByRestaurant!=null && newOrdersByRestaurant.size()>0;
}
public boolean hasNewOrders(Key id) {
Set<Long> setList = newOrdersByRestaurant.get(id);
return setList != null && setList.size() > 0;
}
}
| 25.540984
| 84
| 0.700257
|
77f1ad8113d5a903de2b844c537676b8d97ad695
| 2,345
|
package pl.dawidgdanski.tictactoe.ui.dialog;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.View;
import butterknife.Bind;
import butterknife.ButterKnife;
import pl.dawidgdanski.tictactoe.Constants;
import pl.dawidgdanski.tictactoe.R;
import pl.dawidgdanski.tictactoe.game.TicTacToeGame;
import pl.dawidgdanski.tictactoe.ui.activity.ActivityHelper;
import pl.dawidgdanski.tictactoe.ui.activity.GameActivity;
import pl.dawidgdanski.tictactoe.ui.view.PlayerChoiceSection;
public class CpuVsCpuStartDialog extends DialogFragment {
@Bind(R.id.turn_choice_radio_group)
PlayerChoiceSection playerChoiceSection;
public static CpuVsCpuStartDialog newInstance() {
CpuVsCpuStartDialog dialog = new CpuVsCpuStartDialog();
Bundle arguments = new Bundle();
dialog.setArguments(arguments);
return dialog;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_human_vs_human, null);
ButterKnife.bind(this, view);
return new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle(getString(R.string.cpu_vs_cpu))
.setPositiveButton(R.string.start, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final TicTacToeGame.Player player = playerChoiceSection.getPlayer();
Bundle bundle = new Bundle();
bundle.putSerializable(Constants.GameActivity.EXTRA_GAME_MODE, GameActivity.GameMode.CPU_VS_CPU);
bundle.putSerializable(Constants.GameActivity.EXTRA_FIRST_TURN, player);
ActivityHelper.startActivity(getActivity(), GameActivity.class, bundle);
}
})
.setNegativeButton(getString(android.R.string.cancel), null)
.show();
}
@Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
| 34.485294
| 121
| 0.686141
|
cc78ba9a31507d96b6020e8ad23ca0025d95499d
| 1,815
|
package com.example.super_power_naps.Room_Database;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.super_power_naps.R;
import java.util.ArrayList;
import java.util.List;
public class AlarmAdapter extends RecyclerView.Adapter<AlarmAdapter.AlarmViewHolder> {
private ArrayList<String> tips;
private LayoutInflater layoutInflater;
public class AlarmViewHolder extends RecyclerView.ViewHolder {
private TextView alarmTextView;
public AlarmViewHolder(View itemView) {
super(itemView);
alarmTextView = itemView.findViewById(R.id.cv_alarm);
}
public void setData(String tip) {
alarmTextView.setText(tip);
}
}
public AlarmAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
}
@NonNull
@Override
public AlarmViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.list_item, parent, false);
return new AlarmViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull AlarmViewHolder holder, int position) {
if (tips != null) {
String tip = tips.get(position);
holder.setData(tip);
} else {
holder.alarmTextView.setText(R.string.error);
}
}
@Override
public int getItemCount() {
if (tips != null) {
return tips.size();
} else {
return 0;
}
}
public void setTips(ArrayList<String> tips) {
this.tips = tips;
}
}
| 26.691176
| 88
| 0.66832
|
3788b1d73cd62cd7b8d8938c328161ff613ce55d
| 3,194
|
package com.flipkart.android.proteus.support.parser;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.flipkart.android.proteus.ProteusContext;
import com.flipkart.android.proteus.ProteusView;
import com.flipkart.android.proteus.ViewTypeParser;
import com.flipkart.android.proteus.processor.ColorResourceProcessor;
import com.flipkart.android.proteus.processor.DrawableResourceProcessor;
import com.flipkart.android.proteus.processor.EventProcessor;
import com.flipkart.android.proteus.processor.NumberAttributeProcessor;
import com.flipkart.android.proteus.processor.StringAttributeProcessor;
import com.flipkart.android.proteus.support.view.ProteusOtpView;
import com.flipkart.android.proteus.support.view.custom.OtpEntryEditText;
import com.flipkart.android.proteus.toolbox.Attributes;
import com.flipkart.android.proteus.value.Layout;
import com.flipkart.android.proteus.value.ObjectValue;
import com.flipkart.android.proteus.value.Value;
/**
* Created by Prasad Rao on 30-04-2020 15:43
**/
public class OtpViewParser<V extends OtpEntryEditText> extends ViewTypeParser<V> {
@NonNull
@Override
public String getType() {
return "OtpEntryEditText";
}
@Nullable
@Override
public String getParentType() {
return "AppCompatEditText";
}
@NonNull
@Override
public ProteusView createView(@NonNull ProteusContext context, @NonNull Layout layout,
@NonNull ObjectValue data, @Nullable ViewGroup parent, int dataIndex) {
return new ProteusOtpView(context);
}
@Override
protected void addAttributeProcessors() {
addAttributeProcessor("itemBackground", new DrawableResourceProcessor<V>() {
@Override
public void setDrawable(V view, Drawable drawable) {
view.setItemBackground(drawable);
}
});
addAttributeProcessor("itemCount", new NumberAttributeProcessor<V>() {
@Override
public void setNumber(V view, @NonNull Number value) {
view.setItemCount(value.intValue());
}
});
addAttributeProcessor("lineColor", new ColorResourceProcessor<V>() {
@Override
public void setColor(V view, int color) {
view.setLineColor(color);
}
@Override
public void setColor(V view, ColorStateList colors) {
view.setLineColor(colors);
}
});
addAttributeProcessor("viewType", new StringAttributeProcessor<V>() {
@Override
public void setString(V view, String value) {
view.setViewType(value);
}
});
addAttributeProcessor(Attributes.EditText.onOtpCompleted, new EventProcessor<V>() {
@Override
public void setOnEventListener(final V view, final Value value) {
view.setOtpCompletionListener(otp -> trigger(Attributes.EditText.onOtpCompleted, value, (ProteusView) view));
}
});
}
}
| 35.098901
| 125
| 0.688478
|
baf5dd469fae606d1d024904c0acf530c61af4eb
| 1,024
|
package ru.sdroman.carsales.repository;
import ru.sdroman.carsales.models.Engine;
import java.util.List;
/**
* @author sdroman
* @since 06.2018
*/
public class EngineRepository extends Repository {
/**
* Returns list of engine.
*
* @return List
*/
public List<Engine> getEngines() {
return super.execute(session -> session.createQuery("from ru.sdroman.carsales.models.Engine").list());
}
/**
* Returns engine by name.
*
* @param name String
* @return Engine
*/
public Engine getEngineByName(String name) {
return (Engine) super.execute(session -> session.createQuery("from ru.sdroman.carsales.models.Engine where name=:name")
.setParameter("name", name)
.uniqueResult());
}
/**
* Adds engine to db.
*
* @param engine Engine
* @return int engineId
*/
public int addEngine(Engine engine) {
return (int) super.execute(session -> session.save(engine));
}
}
| 23.272727
| 127
| 0.608398
|
3db11213a022b10280735ba885481f3cca7fa68e
| 2,273
|
package pl.wcislo.sbql4j.typecheck;
import static pl.wcislo.sbql4j.typecheck.TypeCheckTestUtils.checkCard;
import static pl.wcislo.sbql4j.typecheck.TypeCheckTestUtils.checkValueType;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import pl.wcislo.sbql4j.ast.literal.BooleanLiteral;
import pl.wcislo.sbql4j.ast.literal.DoubleLiteral;
import pl.wcislo.sbql4j.ast.literal.IntegerLiteral;
import pl.wcislo.sbql4j.ast.literal.StringLiteral;
import pl.wcislo.sbql4j.typecheck.signature.CardinalityType;
import pl.wcislo.sbql4j.typecheck.signature.Signature;
public class TypeCheckLiteralTest {
private TypeChecker tChecker;
@BeforeClass
@BeforeGroups(groups="typecheck.literal")
public void setup() {
tChecker = new TypeChecker();
}
@Test(groups="typecheck.literal")
public void integerLiteral() {
IntegerLiteral integerLiteral = new IntegerLiteral(10);
integerLiteral.accept(tChecker);
Signature resSig = integerLiteral.getSignature();
checkCard(resSig, CardinalityType.SINGLE_RESULT);
checkValueType(resSig, Integer.class);
}
@Test(groups="typecheck.literal")
public void doubleLiteral() {
DoubleLiteral doubleLiteral = new DoubleLiteral(10.1);
doubleLiteral.accept(tChecker);
Signature resSig = doubleLiteral.getSignature();
checkCard(resSig, CardinalityType.SINGLE_RESULT);
checkValueType(resSig, Double.class);
}
@Test(groups="typecheck.literal")
public void stringLiteral() {
StringLiteral stringLiteral = new StringLiteral("asdf");
stringLiteral.accept(tChecker);
Signature resSig = stringLiteral.getSignature();
checkCard(resSig, CardinalityType.SINGLE_RESULT);
checkValueType(resSig, String.class);
}
@Test(groups="typecheck.literal")
public void booleanLiteral() {
BooleanLiteral booleanLiteral = new BooleanLiteral(true);
booleanLiteral.accept(tChecker);
Signature resSig = booleanLiteral.getSignature();
checkCard(resSig, CardinalityType.SINGLE_RESULT);
checkValueType(resSig, Boolean.class);
}
// @Test
// public void plus() {
// PlusExpression ex = new PlusExpression(leftExpr, rightExpr)
// }
}
| 31.569444
| 76
| 0.763748
|
77b51be2dfb1c9a50849b1c729a12ac79590b60c
| 824
|
package com.syqu.shop.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.syqu.shop.object.Order;
import com.syqu.shop.object.OrderProduct;
@Repository
public interface OrderProductRepository extends JpaRepository<OrderProduct, Long> {
Iterable<OrderProduct> findByOrder(Order order);
OrderProduct findById(long id);
@Query(value="select * from order_product op where op.data is null and op.order_id in (SELECT id FROM ORDERS where status = 'PAID' ) limit 1", nativeQuery = true)
OrderProduct getOrderProduct();
@Query(value="select count(*) from order_product op where op.data is null and op.order_id = ?1", nativeQuery = true)
long isOrderCompleted(long order_id);
}
| 34.333333
| 163
| 0.790049
|
bf99714abd088a82a3d1984bf9a01a5db6923b54
| 2,097
|
/* Copyright (c) 2014 OpenJAX
*
* 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.
*
* You should have received a copy of The MIT License (MIT) along with this
* program. If not, see <http://opensource.org/licenses/MIT/>.
*/
package org.openjax.measure;
/**
* A scalar dimension representing an angle.
*/
public final class Angle extends Dimension.Scalar<Dimension.Unit> {
public static class Unit extends Dimension.Unit {
public static final Unit RAD = new Unit("rad", 1, null);
public static final Unit DEG = new Unit("deg", Math.PI / 180, Unit.RAD);
protected Unit(final String name, final double factor, final Dimension.Unit basis) {
super(name, factor, basis);
}
}
private static final int[] factors = {1, 60, 3600};
private static double parseDMS(final String dms) {
final int factor = dms.endsWith("S") || dms.endsWith("W") ? -1 : 1;
final String[] parts = dms.split("[^.0-9]");
double deg = 0;
for (int i = 0; i < factors.length && i < parts.length; ++i)
deg += Double.parseDouble(parts[i]) / factors[i];
return factor * deg;
}
public Angle(final double value, final Unit unit) {
super(value, unit);
}
public Angle(final String dms) {
super(parseDMS(dms), Unit.DEG);
}
public String toDMS() {
final double deg = value(Unit.DEG);
if (Double.isNaN(deg))
return null;
final int d = (int)deg;
final int m = (int)((deg - d) * 60) % 60;
final float s = (float)((deg - d) * 3600 - m * 60) % 60;
return d + "˚" + m + "'" + s + "\"";
}
}
| 33.822581
| 88
| 0.661898
|
c86483316080f1e649efee3ccb60f7eb6ca5eb51
| 10,639
|
package com.capitalone.dashboard;
import java.util.*;
import com.capitalone.dashboard.model.ScoreWeight;
import org.apache.commons.collections.CollectionUtils;
import com.capitalone.dashboard.model.score.settings.ScoreThresholdSettings;
import com.capitalone.dashboard.model.score.settings.ScoreTypeValue;
import com.capitalone.dashboard.exception.ThresholdException;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.LocalDate;
public class ThresholdUtils {
public static void sortByValueType(List<ScoreThresholdSettings> scoreThresholdSettings) {
if (CollectionUtils.isEmpty(scoreThresholdSettings)) {
return;
}
Collections.sort(scoreThresholdSettings, VALUE_TYPE_COMPATATOR);
}
private static final Comparator<ScoreThresholdSettings> VALUE_TYPE_COMPATATOR = new Comparator<ScoreThresholdSettings>() {
@Override
public int compare(ScoreThresholdSettings o1, ScoreThresholdSettings o2) {
int typeCompare = o1.getType().compareTo(o2.getType());
if (0 != typeCompare) {
return typeCompare;
}
if (isComparatorForGreater(o1.getComparator()) &&
isComparatorForGreater(o2.getComparator())) {
return o2.getValue().compareTo(o1.getValue());
}
return o1.getValue().compareTo(o2.getValue());
}
private boolean isComparatorForGreater(ScoreThresholdSettings.ComparatorType comparatorType) {
return (comparatorType == ScoreThresholdSettings.ComparatorType.greater
|| comparatorType == ScoreThresholdSettings.ComparatorType.greater_or_equal);
}
};
public static List<ScoreThresholdSettings> findAllThresholdsByType(List<ScoreThresholdSettings> scoreThresholdSettings, ScoreThresholdSettings.ValueType valueType) {
if (CollectionUtils.isEmpty(scoreThresholdSettings)) {
return null;
}
List<ScoreThresholdSettings> filteredByType = new ArrayList<>();
for (ScoreThresholdSettings scoreThresholdSetting : scoreThresholdSettings) {
if (scoreThresholdSetting.getType() == valueType) {
filteredByType.add(scoreThresholdSetting);
}
}
return filteredByType;
}
public static List<ScoreThresholdSettings> findAllPercentThresholds(List<ScoreThresholdSettings> scoreThresholdSettings) {
return findAllThresholdsByType(scoreThresholdSettings, ScoreThresholdSettings.ValueType.percent);
}
public static List<ScoreThresholdSettings> findAllDaysThresholds(List<ScoreThresholdSettings> scoreThresholdSettings) {
return findAllThresholdsByType(scoreThresholdSettings, ScoreThresholdSettings.ValueType.days);
}
public static void checkPercentThresholds(List<ScoreThresholdSettings> percentThresholds, Double coveragePercent)
throws ThresholdException {
for (ScoreThresholdSettings percentThreshold : percentThresholds) {
ScoreTypeValue scoreTypeValue = getScoreForThreshold(percentThreshold, coveragePercent.compareTo(percentThreshold.getValue()));
if (null != scoreTypeValue) {
throw new ThresholdException(
getThresholdFailureMessage(percentThreshold),
scoreTypeValue
);
}
}
}
public static void checkPercentThresholds(
List<ScoreThresholdSettings> percentThresholds,
List<Long> timestamps,
int days)
throws ThresholdException {
for (ScoreThresholdSettings percentThreshold : percentThresholds) {
Integer numDaysToCheck = percentThreshold.getNumDaysToCheck();
int checkLastDays = (null != numDaysToCheck) ? numDaysToCheck : days;
Double coveragePercent = getPercentCoverage(timestamps, checkLastDays, days);
ScoreTypeValue scoreTypeValue = getScoreForThreshold(percentThreshold, coveragePercent.compareTo(percentThreshold.getValue()));
if (null != scoreTypeValue) {
throw new ThresholdException(
getThresholdFailureMessage(percentThreshold, checkLastDays),
scoreTypeValue
);
}
}
}
public static void checkDaysThresholds(
List<ScoreThresholdSettings> daysThresholds,
List<Long> timestamps,
int days)
throws ThresholdException {
for (ScoreThresholdSettings daysThreshold : daysThresholds) {
Integer numDaysToCheck = daysThreshold.getNumDaysToCheck();
int checkLastDays = (null != numDaysToCheck) ? numDaysToCheck : days;
Double coverageDays = Double.valueOf(getDaysCoverage(timestamps, checkLastDays, days));
ScoreTypeValue scoreTypeValue = ThresholdUtils.getScoreForThreshold(daysThreshold, coverageDays.compareTo(daysThreshold.getValue()));
if (null != scoreTypeValue) {
throw new ThresholdException(
ThresholdUtils.getThresholdFailureMessage(daysThreshold, checkLastDays),
scoreTypeValue
);
}
}
}
private static Double getPercentCoverage(List<Long> timestamps, int checkLastDays, int days) {
List<Long> filteredTimestamps;
if (checkLastDays == days) {
filteredTimestamps = timestamps;
} else {
filteredTimestamps = filterTimestampsForDays(timestamps, checkLastDays);
}
Set<String> dates = new HashSet<>();
for (Long timestamp : filteredTimestamps) {
dates.add(Constants.DAY_FORMAT.format(new Date(timestamp)));
}
return (dates.size() * 100) / ((double) checkLastDays);
}
private static int getDaysCoverage(List<Long> timestamps, int checkLastDays, int days) {
List<Long> filteredTimestamps;
if (checkLastDays == days) {
filteredTimestamps = timestamps;
} else {
filteredTimestamps = filterTimestampsForDays(timestamps, checkLastDays);
}
Set<String> dates = new HashSet<>();
for (Long timestamp : filteredTimestamps) {
dates.add(Constants.DAY_FORMAT.format(new Date(timestamp)));
}
return dates.size();
}
private static List<Long> filterTimestampsForDays(List<Long> timestamps, int checkLastDays) {
long startTimeTarget = new LocalDate().minusDays(checkLastDays).toDate().getTime();
List<Long> filteredTimestamps = new ArrayList<>();
for (Long timestamp : timestamps) {
if (timestamp >= startTimeTarget) {
filteredTimestamps.add(timestamp);
}
}
return filteredTimestamps;
}
public static Pair<String, String> getThresholdFailureMessage(ScoreThresholdSettings scoreThresholdSettings) {
return getThresholdFailureMessage(scoreThresholdSettings, null);
}
public static Pair<String, String> getThresholdFailureMessage(ScoreThresholdSettings scoreThresholdSettings, Integer days) {
String prefixPass = "",
prefixFail = "",
suffix = "",
typeMessage = "",
value = Utils.roundAlloc(scoreThresholdSettings.getValue());
boolean daysPresent = false;
boolean isValueMax = (scoreThresholdSettings.getValue().compareTo(Double.valueOf(Constants.MAX_SCORE)) == 0);
if (null == days || days == 0) {
prefixPass = prefixFail = "Value is ";
} else {
daysPresent = true;
prefixPass = "Data is present for ";
prefixFail = "Data should be present for ";
suffix = " days of last " + days + " days";
}
Pair<String, String> comparatorMessage = getComparatorMessage(
scoreThresholdSettings.getComparator(),
daysPresent,
isValueMax
);
if (scoreThresholdSettings.getType() == ScoreThresholdSettings.ValueType.percent) {
typeMessage = "%";
} else if (scoreThresholdSettings.getType() == ScoreThresholdSettings.ValueType.days) {
typeMessage = " days";
}
String passMessage = prefixPass + comparatorMessage.getLeft() +
value + typeMessage + suffix;
String failMessage = prefixFail + comparatorMessage.getRight() +
value + typeMessage + suffix;
return Pair.of(passMessage, failMessage);
}
private static Pair<String, String> getComparatorMessage(
ScoreThresholdSettings.ComparatorType comparatorType,
boolean daysPresent,
boolean isValueMax
) {
String greaterOrMore = daysPresent ? "more" : "greater",
less = "less than ",
greater = greaterOrMore + " than ",
lessOrEqual = "less than or equal to ",
greaterOrEqual = greaterOrMore + " than or equal to ",
comparatorMessagePass = "",
comparatorMessageFail = "";
switch (comparatorType) {
case equals:
break;
case less:
comparatorMessagePass = less;
if (!daysPresent) {
comparatorMessageFail = comparatorMessagePass;
} else if (!isValueMax) {
comparatorMessageFail = greaterOrEqual;
}
break;
case greater:
comparatorMessagePass = greater;
if (!daysPresent) {
comparatorMessageFail = comparatorMessagePass;
} else {
comparatorMessageFail = lessOrEqual;
}
break;
case less_or_equal:
comparatorMessagePass = lessOrEqual;
if (!daysPresent) {
comparatorMessageFail = comparatorMessagePass;
} else {
comparatorMessageFail = greater;
}
break;
case greater_or_equal:
if (!isValueMax) {
comparatorMessagePass = greaterOrEqual;
}
if (!daysPresent) {
comparatorMessageFail = comparatorMessagePass;
} else {
comparatorMessageFail = less;
}
break;
default:
break;
}
return Pair.of(comparatorMessagePass, comparatorMessageFail);
}
public static ScoreTypeValue getScoreForThreshold(ScoreThresholdSettings percentThreshold, int compareResult) {
switch (percentThreshold.getComparator()) {
case equals:
if (compareResult == 0) {
return percentThreshold.getScore();
}
return null;
case less:
if (compareResult == -1) {
return percentThreshold.getScore();
}
return null;
case greater:
if (compareResult == 1) {
return percentThreshold.getScore();
}
return null;
case less_or_equal:
if (compareResult == 0 || compareResult == -1) {
return percentThreshold.getScore();
}
return null;
case greater_or_equal:
if (compareResult == 0 || compareResult == 1) {
return percentThreshold.getScore();
}
return null;
default:
return null;
}
}
public static ScoreWeight.ProcessingState getCriteriaStateFromScore(ScoreTypeValue scoreTypeValue) {
if (scoreTypeValue.getScoreValue().compareTo(Constants.ZERO_SCORE) > 0) {
return ScoreWeight.ProcessingState.criteria_passed;
}
return ScoreWeight.ProcessingState.criteria_failed;
}
}
| 34.881967
| 167
| 0.69734
|
c9aab9db3b113cee76b7167fb0c0074594d79ff8
| 1,690
|
// Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.Shooting;
import edu.wpi.first.wpilibj2.command.ParallelCommandGroup;
import edu.wpi.first.wpilibj2.command.ParallelDeadlineGroup;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
import frc.robot.Constants;
import frc.robot.commands.Driving.TurnToAngle;
import frc.robot.subsystems.DriveTrain;
import frc.robot.subsystems.Index;
import frc.robot.subsystems.Shooter;
import frc.robot.subsystems.limeLight;
// NOTE: Consider using this command inline, rather than writing a subclass. For more
// information, see:
// https://docs.wpilib.org/en/stable/docs/software/commandbased/convenience-features.html
public class ShootingFullRoutine extends SequentialCommandGroup {
/** Creates a new ShootingFullRoutine. */
DriveTrain m_dt;
Shooter m_shoot;
limeLight m_lime;
Index m_index;
public ShootingFullRoutine(DriveTrain d, Shooter s, limeLight l, Index i) {
m_dt = d ;
m_shoot = s;
m_lime = l;
m_index = i;
// Add your commands in the addCommands() call, e.g.
// addCommands(new FooCommand(), new BarCommand());
addCommands(
new ParallelDeadlineGroup(
new KickBack(m_index),
new TurnToAngle(m_dt, () -> -m_lime.yeeYawww()),
new Shoot(m_shoot, () -> Constants.shooterTicksFromDistance(m_lime.getDistanceToTarget()), true, m_index)
),
new Shoot(m_shoot, () -> Constants.shooterTicksFromDistance(m_lime.getDistanceToTarget()), false, m_index)
);
}
}
| 35.208333
| 113
| 0.737278
|
eceb37752fc8c267315a6428510c534ac0917da8
| 7,664
|
package org.deeplearning4j.optimize;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.deeplearning4j.nn.NeuralNetwork;
import org.deeplearning4j.nn.NeuralNetwork.LossFunction;
import org.deeplearning4j.nn.NeuralNetwork.OptimizationAlgorithm;
import org.deeplearning4j.nn.gradient.NeuralNetworkGradient;
import org.deeplearning4j.plot.NeuralNetPlotter;
import org.deeplearning4j.util.ArrayUtil;
import org.deeplearning4j.util.OptimizerMatrix;
import org.jblas.DoubleMatrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cc.mallet.optimize.Optimizable;
/**
* Performs basic beam search based on the network's loss function
* @author Adam Gibson
*
*/
public abstract class NeuralNetworkOptimizer implements OptimizableByGradientValueMatrix,Serializable,NeuralNetEpochListener {
private static final long serialVersionUID = 4455143696487934647L;
protected NeuralNetwork network;
protected double lr;
protected Object[] extraParams;
protected double tolerance = 0.00001;
protected static Logger log = LoggerFactory.getLogger(NeuralNetworkOptimizer.class);
protected List<Double> errors = new ArrayList<Double>();
protected double minLearningRate = 0.001;
protected transient OptimizerMatrix opt;
protected OptimizationAlgorithm optimizationAlgorithm;
protected LossFunction lossFunction;
protected NeuralNetPlotter plotter = new NeuralNetPlotter();
protected double maxStep = -1;
protected int numParams = -1;
protected int currIteration = -1;
/**
*
* @param network
* @param lr
* @param trainingParams
*/
public NeuralNetworkOptimizer(NeuralNetwork network,double lr,Object[] trainingParams,OptimizationAlgorithm optimizationAlgorithm,LossFunction lossFunction) {
this.network = network;
this.lr = lr;
//add current iteration as an extra parameter
this.extraParams = new Object[trainingParams.length + 1];
System.arraycopy(trainingParams,0,extraParams,0,trainingParams.length);
this.optimizationAlgorithm = optimizationAlgorithm;
this.lossFunction = lossFunction;
}
private void createOptimizationAlgorithm() {
if(optimizationAlgorithm == OptimizationAlgorithm.CONJUGATE_GRADIENT) {
opt = new VectorizedNonZeroStoppingConjugateGradient(this,this);
((VectorizedNonZeroStoppingConjugateGradient) opt).setTolerance(tolerance);
}
else {
opt = new VectorizedDeepLearningGradientAscent(this,this);
((VectorizedDeepLearningGradientAscent) opt).setTolerance(tolerance);
if(maxStep > 0)
((VectorizedDeepLearningGradientAscent) opt).setMaxStepSize(maxStep);
}
}
@Override
public DoubleMatrix getParameters() {
return new DoubleMatrix(ArrayUtil.combine(network.getW().data,network.getvBias().data,network.gethBias().data));
}
public void train(DoubleMatrix x) {
if(opt == null) {
createOptimizationAlgorithm();
}
network.setInput(x);
int epochs = extraParams.length < 3 ? 1000 : (int) extraParams[2];
opt.setMaxIterations(epochs);
opt.optimize(epochs);
network.backProp(lr,epochs,extraParams);
}
@Override
public void iterationDone(int iterationDone) {
int plotEpochs = network.getRenderIterations();
if(plotEpochs <= 0)
return;
if(iterationDone % plotEpochs == 0) {
plotter.plotNetworkGradient(network,network.getGradient(extraParams),100);
}
}
@Override
public int getNumParameters() {
if(numParams < 0) {
numParams = network.getW().length + network.gethBias().length + network.getvBias().length;
return numParams;
}
return numParams;
}
@Override
public double getParameter(int index) {
//beyond weight matrix
if(index >= network.getW().length) {
int i = getAdjustedIndex(index);
//beyond visible bias
if(index >= network.getvBias().length + network.getW().length) {
return network.gethBias().get(i);
}
else
return network.getvBias().get(i);
}
else
return network.getW().get(index);
}
@Override
public void setParameters(DoubleMatrix params) {
for(int i = 0; i < params.length; i++)
setParameter(i, params.get(i));
}
@Override
public void setParameter(int index, double value) {
//beyond weight matrix
if(index >= network.getW().length) {
//beyond visible bias
if(index >= network.getvBias().length + network.getW().length) {
int i = getAdjustedIndex(index);
network.gethBias().put(i, value);
}
else {
int i = getAdjustedIndex(index);
network.getvBias().put(i,value);
}
}
else {
network.getW().put(index,value);
}
}
private int getAdjustedIndex(int index) {
int wLength = network.getW().length;
int vBiasLength = network.getvBias().length;
if(index < wLength)
return index;
else if(index >= wLength + vBiasLength) {
int hIndex = index - wLength - vBiasLength;
return hIndex;
}
else {
int vIndex = index - wLength;
return vIndex;
}
}
@Override
public DoubleMatrix getValueGradient(int iteration) {
if(iteration >= 1)
extraParams[extraParams.length - 1] = iteration;
NeuralNetworkGradient g = network.getGradient(extraParams);
double[] buffer = new double[getNumParameters()];
/*
* Treat params as linear index. Always:
* W
* Visible Bias
* Hidden Bias
*/
int idx = 0;
for (int i = 0; i < g.getwGradient().length; i++) {
buffer[idx++] = g.getwGradient().get(i);
}
for (int i = 0; i < g.getvBiasGradient().length; i++) {
buffer[idx++] = g.getvBiasGradient().get(i);
}
for (int i = 0; i < g.gethBiasGradient().length; i++) {
buffer[idx++] = g.gethBiasGradient().get(i);
}
return new DoubleMatrix(buffer);
}
@Override
public double getValue() {
if(this.lossFunction == LossFunction.RECONSTRUCTION_CROSSENTROPY)
return network.getReConstructionCrossEntropy();
else if(this.lossFunction == LossFunction.SQUARED_LOSS)
return - network.squaredLoss();
else if(this.lossFunction == LossFunction.NEGATIVELOGLIKELIHOOD)
return -network.negativeLogLikelihood();
else if(lossFunction == LossFunction.MSE)
return -network.mse();
else if(lossFunction == LossFunction.RMSE_XENT)
return -network.mseRecon();
return network.getReConstructionCrossEntropy();
}
@Override
public void setCurrentIteration(int value) {
if(value < 1) {
return;
}
this.currIteration = value;
}
public double getTolerance() {
return tolerance;
}
public void setTolerance(double tolerance) {
this.tolerance = tolerance;
}
public double getMaxStep() {
return maxStep;
}
public void setMaxStep(double maxStep) {
this.maxStep = maxStep;
}
public int getCurrIteration() {
return currIteration;
}
}
| 29.030303
| 162
| 0.629958
|
1e5d1c413c66bf48534dc1dd900ad0c8b0a9fe94
| 14,535
|
/*#######################################################
*
* Maintained by Gregor Santner, 2017-
* https://gsantner.net/
*
* License of this file: Apache 2.0 (Commercial upon request)
* https://www.apache.org/licenses/LICENSE-2.0
*
#########################################################*/
package net.gsantner.markor.activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceFragmentCompat;
import android.support.v7.preference.PreferenceScreen;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import net.gsantner.markor.R;
import net.gsantner.markor.activity.openeditor.OpenEditorLinkBoxActivity;
import net.gsantner.markor.activity.openeditor.OpenEditorQuickNoteActivity;
import net.gsantner.markor.activity.openeditor.OpenEditorTodoActivity;
import net.gsantner.markor.ui.FilesystemDialogCreator;
import net.gsantner.markor.util.ActivityUtils;
import net.gsantner.markor.util.AppSettings;
import net.gsantner.markor.util.ContextUtils;
import net.gsantner.markor.util.PermissionChecker;
import net.gsantner.opoc.preference.GsPreferenceFragmentCompat;
import net.gsantner.opoc.preference.SharedPreferencesPropertyBackend;
import net.gsantner.opoc.ui.FilesystemDialogData;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
public class SettingsActivity extends AppCompatActivity {
static class RESULT {
static final int NOCHANGE = -1;
static final int CHANGED = 1;
static final int RESTART_REQ = 2;
}
public static int activityRetVal = RESULT.NOCHANGE;
private static int iconColor = Color.WHITE;
@BindView(R.id.toolbar)
protected Toolbar toolbar;
public void onCreate(Bundle b) {
// Must be applied before setContentView
super.onCreate(b);
AppSettings appSettings = new AppSettings(this);
ContextUtils contextUtils = new ContextUtils(this);
contextUtils.setAppLanguage(appSettings.getLanguage());
setTheme(appSettings.isDarkThemeEnabled() ? R.style.AppTheme_Dark : R.style.AppTheme_Light);
/*
ActivityUtils au = new ActivityUtils(this);
boolean extraLaunchersEnabled = appSettings.isSpecialFileLaunchersEnabled();
au.setLauncherActivityEnabled(OpenEditorLinkBoxActivity.class, extraLaunchersEnabled);
au.setLauncherActivityEnabled(OpenEditorQuickNoteActivity.class, extraLaunchersEnabled);
au.setLauncherActivityEnabled(OpenEditorTodoActivity.class, extraLaunchersEnabled);*/
// Load UI
setContentView(R.layout.settings__activity);
ButterKnife.bind(this);
// Custom code
iconColor = contextUtils.rcolor(appSettings.isDarkThemeEnabled() ? R.color.dark__primary_text : R.color.light__primary_text);
toolbar.setTitle(R.string.settings);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp));
toolbar.setNavigationOnClickListener(view -> SettingsActivity.this.onBackPressed());
showFragment(SettingsFragmentMaster.TAG, false);
}
protected void showFragment(String tag, boolean addToBackStack) {
String toolbarTitle = getString(R.string.settings);
GsPreferenceFragmentCompat prefFrag = (GsPreferenceFragmentCompat) getSupportFragmentManager().findFragmentByTag(tag);
if (prefFrag == null) {
switch (tag) {
case SettingsFragmentMaster.TAG:
default: {
prefFrag = new SettingsFragmentMaster();
toolbarTitle = prefFrag.getTitleOrDefault(toolbarTitle);
break;
}
}
}
toolbar.setTitle(toolbarTitle);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
if (addToBackStack) {
t.addToBackStack(tag);
}
t.replace(R.id.settings__activity__fragment_placeholder, prefFrag, tag).commit();
}
@Override
protected void onStop() {
setResult(activityRetVal);
super.onStop();
}
public static abstract class MarkorSettingsFragment extends GsPreferenceFragmentCompat {
protected AppSettings _as;
@Override
protected SharedPreferencesPropertyBackend getAppSettings(Context context) {
if (_as == null) {
_as = new AppSettings(context);
}
return _as;
}
@Override
public Integer getIconTintColor() {
return iconColor;
}
@Override
protected void onPreferenceChanged(SharedPreferences prefs, String key) {
activityRetVal = RESULT.CHANGED;
}
@Override
protected void onPreferenceScreenChanged(PreferenceFragmentCompat preferenceFragmentCompat, PreferenceScreen preferenceScreen) {
super.onPreferenceScreenChanged(preferenceFragmentCompat, preferenceScreen);
if (!TextUtils.isEmpty(preferenceScreen.getTitle())) {
SettingsActivity a = (SettingsActivity) getActivity();
if (a != null) {
a.toolbar.setTitle(preferenceScreen.getTitle());
}
}
}
}
@Override
public void onBackPressed() {
GsPreferenceFragmentCompat prefFrag = (GsPreferenceFragmentCompat) getSupportFragmentManager().findFragmentByTag(SettingsFragmentMaster.TAG);
if (prefFrag != null && prefFrag.canGoBack()) {
prefFrag.goBack();
return;
}
super.onBackPressed();
}
public static class SettingsFragmentMaster extends MarkorSettingsFragment {
public static final String TAG = "SettingsFragmentMaster";
@Override
public int getPreferenceResourceForInflation() {
return R.xml.preferences_master;
}
@Override
public String getFragmentTag() {
return TAG;
}
@Override
public void doUpdatePreferences() {
String remove = "/storage/emulated/0/";
updateSummary(R.string.pref_key__notebook_directory,
_cu.htmlToSpanned("<small><small>" + AppSettings.get().getNotebookDirectoryAsStr().replace(remove, "") + "</small></small>")
);
updateSummary(R.string.pref_key__quicknote_filepath,
_cu.htmlToSpanned("<small><small>" + _as.getQuickNoteFile().getAbsolutePath().replace(remove, "") + "</small></small>")
);
updateSummary(R.string.pref_key__todo_filepath,
_cu.htmlToSpanned("<small><small>" + _as.getTodoFile().getAbsolutePath().replace(remove, "") + "</small></small>")
);
updateSummary(R.string.pref_key__linkbox_filepath,
_cu.htmlToSpanned("<small><small>" + _as.getLinkBoxFile().getAbsolutePath().replace(remove, "") + "</small></small>")
);
updateSummary(R.string.pref_key__app_theme,
getString(_as.isDarkThemeEnabled() ? R.string.dark : R.string.light)
);
updatePreference(R.string.pref_key__is_launcher_for_special_files_enabled, null,
("Launcher (" + getString(R.string.special_documents) + ")"),
getString(R.string.app_drawer_launcher_special_files_description), true
);
updateSummary(R.string.pref_key__todotxt__alternative_naming_context_project,
getString(R.string.category_to_context_project_to_tag, getString(R.string.context), getString(R.string.category), getString(R.string.project), getString(R.string.tag)));
}
@Override
protected void onPreferenceChanged(SharedPreferences prefs, String key) {
super.onPreferenceChanged(prefs, key);
if (eq(key, R.string.pref_key__language)) {
activityRetVal = RESULT.RESTART_REQ;
_as.setRecreateMainRequired(true);
} else if (eq(key, R.string.pref_key__app_theme)) {
restartActivity();
_as.setRecreateMainRequired(true);
} else if (eq(key, R.string.pref_key__is_overview_statusbar_hidden)) {
activityRetVal = RESULT.RESTART_REQ;
_as.setRecreateMainRequired(true);
} else if (eq(key, R.string.pref_key__is_launcher_for_special_files_enabled)) {
boolean extraLaunchersEnabled = prefs.getBoolean(key, false);
ActivityUtils au = new ActivityUtils(getActivity());
au.setLauncherActivityEnabled(OpenEditorLinkBoxActivity.class, extraLaunchersEnabled);
au.setLauncherActivityEnabled(OpenEditorQuickNoteActivity.class, extraLaunchersEnabled);
au.setLauncherActivityEnabled(OpenEditorTodoActivity.class, extraLaunchersEnabled);
}
}
@Override
@SuppressWarnings({"ConstantConditions", "ConstantIfStatement", "StatementWithEmptyBody"})
public Boolean onPreferenceClicked(Preference preference) {
PermissionChecker permc = new PermissionChecker(getActivity());
if (isAdded() && preference.hasKey()) {
if (false) {
} else if (eq(preference, R.string.pref_key__notebook_directory)) {
if (permc.doIfExtStoragePermissionGranted()) {
FragmentManager fragManager = getActivity().getSupportFragmentManager();
FilesystemDialogCreator.showFolderDialog(new FilesystemDialogData.SelectionListenerAdapter() {
@Override
public void onFsSelected(String request, File file) {
AppSettings as = AppSettings.get();
as.setSaveDirectory(file.getAbsolutePath());
as.setRecreateMainRequired(true);
as.setLastOpenedDirectory(as.getNotebookDirectoryAsStr());
doUpdatePreferences();
}
@Override
public void onFsDialogConfig(FilesystemDialogData.Options opt) {
opt.titleText = R.string.select_storage_folder;
if (!permc.mkdirIfStoragePermissionGranted()) {
opt.rootFolder = Environment.getExternalStorageDirectory();
}
}
}, fragManager, getActivity());
}
return true;
} else if (eq(preference, R.string.pref_key__quicknote_filepath)) {
if (permc.doIfExtStoragePermissionGranted()) {
FragmentManager fragManager = getActivity().getSupportFragmentManager();
FilesystemDialogCreator.showFileDialog(new FilesystemDialogData.SelectionListenerAdapter() {
@Override
public void onFsSelected(String request, File file) {
AppSettings as = AppSettings.get();
as.setQuickNoteFile(file);
as.setRecreateMainRequired(true);
}
@Override
public void onFsDialogConfig(FilesystemDialogData.Options opt) {
opt.titleText = R.string.quicknote;
opt.rootFolder = Environment.getExternalStorageDirectory();
}
}, fragManager, getActivity());
}
return true;
} else if (eq(preference, R.string.pref_key__todo_filepath)) {
if (permc.doIfExtStoragePermissionGranted()) {
FragmentManager fragManager = getActivity().getSupportFragmentManager();
FilesystemDialogCreator.showFileDialog(new FilesystemDialogData.SelectionListenerAdapter() {
@Override
public void onFsSelected(String request, File file) {
AppSettings as = AppSettings.get();
as.setTodoFile(file);
as.setRecreateMainRequired(true);
}
@Override
public void onFsDialogConfig(FilesystemDialogData.Options opt) {
opt.titleText = R.string.todo;
opt.rootFolder = Environment.getExternalStorageDirectory();
}
}, fragManager, getActivity());
}
return true;
} else if (eq(preference, R.string.pref_key__linkbox_filepath)) {
if (permc.doIfExtStoragePermissionGranted()) {
FragmentManager fragManager = getActivity().getSupportFragmentManager();
FilesystemDialogCreator.showFileDialog(new FilesystemDialogData.SelectionListenerAdapter() {
@Override
public void onFsSelected(String request, File file) {
AppSettings as = AppSettings.get();
as.setLinkBoxFile(file);
as.setRecreateMainRequired(true);
}
@Override
public void onFsDialogConfig(FilesystemDialogData.Options opt) {
opt.titleText = R.string.linkbox;
opt.rootFolder = Environment.getExternalStorageDirectory();
}
}, fragManager, getActivity());
}
return true;
}
}
return null;
}
}
}
| 47.5
| 189
| 0.6
|
292d0eb11505008bb205385bce4be6b9c77c09fe
| 15,489
|
package com.brightsight.signing;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1InputStream;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
@Keep
public class SignBoot {
private static final int BOOT_IMAGE_HEADER_V1_RECOVERY_DTBO_SIZE_OFFSET = 1632;
private static final int BOOT_IMAGE_HEADER_V2_DTB_SIZE_OFFSET = 1648;
// Arbitrary maximum header version value; when greater assume the field is dt/extra size
private static final int BOOT_IMAGE_HEADER_VERSION_MAXIMUM = 8;
// Maximum header size byte value to read (currently the bootimg minimum page size)
private static final int BOOT_IMAGE_HEADER_SIZE_MAXIMUM = 2048;
private static class PushBackRWStream extends FilterInputStream {
private OutputStream out;
private int pos = 0;
private byte[] backBuf;
PushBackRWStream(InputStream in, OutputStream o) {
super(in);
out = o;
}
@Override
public int read() throws IOException {
int b;
if (backBuf != null && backBuf.length > pos) {
b = backBuf[pos++];
} else {
b = super.read();
out.write(b);
}
return b;
}
@Override
public int read(byte[] bytes, int off, int len) throws IOException {
int read = 0;
if (backBuf != null && backBuf.length > pos) {
read = Math.min(len, backBuf.length - pos);
System.arraycopy(backBuf, pos, bytes, off, read);
pos += read;
off += read;
len -= read;
}
if (len > 0) {
int ar = super.read(bytes, off, len);
read += ar;
out.write(bytes, off, ar);
}
return read;
}
void unread(byte[] buf) {
backBuf = buf;
}
}
private static int fullRead(InputStream in, byte[] b) throws IOException {
return fullRead(in, b, 0, b.length);
}
private static int fullRead(InputStream in, byte[] b, int off, int len) throws IOException {
int n = 0;
while (n < len) {
int count = in.read(b, off + n, len - n);
if (count <= 0)
break;
n += count;
}
return n;
}
public static boolean doSignature(
@Nullable X509Certificate cert, @Nullable PrivateKey key,
@NonNull InputStream imgIn, @NonNull OutputStream imgOut, @NonNull String target
) {
try {
PushBackRWStream in = new PushBackRWStream(imgIn, imgOut);
byte[] hdr = new byte[BOOT_IMAGE_HEADER_SIZE_MAXIMUM];
// First read the header
fullRead(in, hdr);
int signableSize = getSignableImageSize(hdr);
// Unread header
in.unread(hdr);
BootSignature bootsig = new BootSignature(target, signableSize);
if (cert == null) {
cert = CryptoUtils.readCertificate(
new ByteArrayInputStream(KeyData.verityCert()));
}
bootsig.setCertificate(cert);
if (key == null) {
key = CryptoUtils.readPrivateKey(
new ByteArrayInputStream(KeyData.verityKey()));
}
byte[] sig = bootsig.sign(key, in, signableSize);
bootsig.setSignature(sig, CryptoUtils.getSignatureAlgorithmIdentifier(key));
byte[] encoded_bootsig = bootsig.getEncoded();
imgOut.write(encoded_bootsig);
imgOut.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static boolean verifySignature(InputStream imgIn, X509Certificate cert) {
try {
// Read the header for size
byte[] hdr = new byte[BOOT_IMAGE_HEADER_SIZE_MAXIMUM];
if (fullRead(imgIn, hdr) != hdr.length) {
System.err.println("Unable to read image header");
return false;
}
int signableSize = getSignableImageSize(hdr);
// Read the rest of the image
byte[] rawImg = Arrays.copyOf(hdr, signableSize);
int remain = signableSize - hdr.length;
if (fullRead(imgIn, rawImg, hdr.length, remain) != remain) {
System.err.println("Unable to read image");
return false;
}
// Read footer, which contains the signature
byte[] signature = new byte[4096];
if (imgIn.read(signature) == -1 || Arrays.equals(signature, new byte [signature.length])) {
System.err.println("Invalid image: not signed");
return false;
}
BootSignature bootsig = new BootSignature(signature);
if (cert != null) {
bootsig.setCertificate(cert);
}
if (bootsig.verify(rawImg, signableSize)) {
System.err.println("Signature is VALID");
return true;
} else {
System.err.println("Signature is INVALID");
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
public static int getSignableImageSize(byte[] data) throws Exception {
if (!Arrays.equals(Arrays.copyOfRange(data, 0, 8),
"ANDROID!".getBytes("US-ASCII"))) {
throw new IllegalArgumentException("Invalid image header: missing magic");
}
ByteBuffer image = ByteBuffer.wrap(data);
image.order(ByteOrder.LITTLE_ENDIAN);
image.getLong(); // magic
int kernelSize = image.getInt();
image.getInt(); // kernel_addr
int ramdskSize = image.getInt();
image.getInt(); // ramdisk_addr
int secondSize = image.getInt();
image.getLong(); // second_addr + tags_addr
int pageSize = image.getInt();
if (pageSize >= 0x02000000) {
throw new IllegalArgumentException("Invalid image header: PXA header detected");
}
int length = pageSize // include the page aligned image header
+ ((kernelSize + pageSize - 1) / pageSize) * pageSize
+ ((ramdskSize + pageSize - 1) / pageSize) * pageSize
+ ((secondSize + pageSize - 1) / pageSize) * pageSize;
int headerVersion = image.getInt(); // boot image header version or dt/extra size
if (headerVersion > 0 && headerVersion < BOOT_IMAGE_HEADER_VERSION_MAXIMUM) {
image.position(BOOT_IMAGE_HEADER_V1_RECOVERY_DTBO_SIZE_OFFSET);
int recoveryDtboLength = image.getInt();
length += ((recoveryDtboLength + pageSize - 1) / pageSize) * pageSize;
image.getLong(); // recovery_dtbo address
int headerSize = image.getInt();
if (headerVersion == 2) {
image.position(BOOT_IMAGE_HEADER_V2_DTB_SIZE_OFFSET);
int dtbLength = image.getInt();
length += ((dtbLength + pageSize - 1) / pageSize) * pageSize;
image.getLong(); // dtb address
}
if (image.position() != headerSize) {
throw new IllegalArgumentException("Invalid image header: invalid header length");
}
} else {
// headerVersion is 0 or actually dt/extra size in this case
length += ((headerVersion + pageSize - 1) / pageSize) * pageSize;
}
length = ((length + pageSize - 1) / pageSize) * pageSize;
if (length <= 0) {
throw new IllegalArgumentException("Invalid image header: invalid length");
}
return length;
}
static class BootSignature extends ASN1Object {
private ASN1Integer formatVersion;
private ASN1Encodable certificate;
private AlgorithmIdentifier algId;
private DERPrintableString target;
private ASN1Integer length;
private DEROctetString signature;
private PublicKey publicKey;
private static final int FORMAT_VERSION = 1;
/**
* Initializes the object for signing an image file
* @param target Target name, included in the signed data
* @param length Length of the image, included in the signed data
*/
public BootSignature(String target, int length) {
this.formatVersion = new ASN1Integer(FORMAT_VERSION);
this.target = new DERPrintableString(target);
this.length = new ASN1Integer(length);
}
/**
* Initializes the object for verifying a signed image file
* @param signature Signature footer
*/
public BootSignature(byte[] signature) throws Exception {
ASN1InputStream stream = new ASN1InputStream(signature);
ASN1Sequence sequence = (ASN1Sequence) stream.readObject();
formatVersion = (ASN1Integer) sequence.getObjectAt(0);
if (formatVersion.getValue().intValue() != FORMAT_VERSION) {
throw new IllegalArgumentException("Unsupported format version");
}
certificate = sequence.getObjectAt(1);
byte[] encoded = ((ASN1Object) certificate).getEncoded();
ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate c = (X509Certificate) cf.generateCertificate(bis);
publicKey = c.getPublicKey();
ASN1Sequence algId = (ASN1Sequence) sequence.getObjectAt(2);
this.algId = new AlgorithmIdentifier((ASN1ObjectIdentifier) algId.getObjectAt(0));
ASN1Sequence attrs = (ASN1Sequence) sequence.getObjectAt(3);
target = (DERPrintableString) attrs.getObjectAt(0);
length = (ASN1Integer) attrs.getObjectAt(1);
this.signature = (DEROctetString) sequence.getObjectAt(4);
}
public ASN1Object getAuthenticatedAttributes() {
ASN1EncodableVector attrs = new ASN1EncodableVector();
attrs.add(target);
attrs.add(length);
return new DERSequence(attrs);
}
public byte[] getEncodedAuthenticatedAttributes() throws IOException {
return getAuthenticatedAttributes().getEncoded();
}
public void setSignature(byte[] sig, AlgorithmIdentifier algId) {
this.algId = algId;
signature = new DEROctetString(sig);
}
public void setCertificate(X509Certificate cert)
throws CertificateEncodingException, IOException {
ASN1InputStream s = new ASN1InputStream(cert.getEncoded());
certificate = s.readObject();
publicKey = cert.getPublicKey();
}
public byte[] sign(PrivateKey key, InputStream is, int len) throws Exception {
Signature signer = Signature.getInstance(CryptoUtils.getSignatureAlgorithm(key));
signer.initSign(key);
int read;
byte buffer[] = new byte[4096];
while ((read = is.read(buffer, 0, Math.min(len, buffer.length))) > 0) {
signer.update(buffer, 0, read);
len -= read;
}
signer.update(getEncodedAuthenticatedAttributes());
return signer.sign();
}
public boolean verify(byte[] image, int length) throws Exception {
if (this.length.getValue().intValue() != length) {
throw new IllegalArgumentException("Invalid image length");
}
String algName = CryptoUtils.ID_TO_ALG.get(algId.getAlgorithm().getId());
if (algName == null) {
throw new IllegalArgumentException("Unsupported algorithm " + algId.getAlgorithm());
}
Signature verifier = Signature.getInstance(algName);
verifier.initVerify(publicKey);
verifier.update(image, 0, length);
verifier.update(getEncodedAuthenticatedAttributes());
return verifier.verify(signature.getOctets());
}
@Override
public ASN1Primitive toASN1Primitive() {
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(formatVersion);
v.add(certificate);
v.add(algId);
v.add(getAuthenticatedAttributes());
v.add(signature);
return new DERSequence(v);
}
}
public static void main(String[] args) throws Exception {
if (args.length > 0 && "-verify".equals(args[0])) {
X509Certificate cert = null;
if (args.length >= 2) {
// args[1] is the path to a public key certificate
cert = CryptoUtils.readCertificate(new FileInputStream(args[1]));
}
boolean signed = SignBoot.verifySignature(System.in, cert);
System.exit(signed ? 0 : 1);
} else if (args.length > 0 && "-sign".equals(args[0])) {
X509Certificate cert = null;
PrivateKey key = null;
String name = "/boot";
if (args.length >= 3) {
cert = CryptoUtils.readCertificate(new FileInputStream(args[1]));
key = CryptoUtils.readPrivateKey(new FileInputStream(args[2]));
}
if (args.length == 2) {
name = args[1];
} else if (args.length >= 4) {
name = args[3];
}
boolean result = SignBoot.doSignature(cert, key, System.in, System.out, name);
System.exit(result ? 0 : 1);
} else {
System.err.println(
"BootSigner <actions> [args]\n" +
"Input from stdin, output to stdout\n" +
"\n" +
"Actions:\n" +
" -verify [x509.pem]\n" +
" verify image. cert is optional.\n" +
" -sign [x509.pem] [pk8] [name]\n" +
" sign image. name and the cert/key pair are optional.\n" +
" name should be either /boot (default) or /recovery.\n"
);
}
}
}
| 40.231169
| 103
| 0.585383
|
11766087c7c1d3345482ea85e57c33a5aaaa6dc1
| 1,049
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: globalLockQueryRequest.proto
package io.seata.serializer.protobuf.generated;
public interface GlobalLockQueryRequestProtoOrBuilder extends
// @@protoc_insertion_point(interface_extends:io.seata.protocol.protobuf.GlobalLockQueryRequestProto)
com.google.protobuf.MessageOrBuilder {
/**
* <code>.io.seata.protocol.protobuf.BranchRegisterRequestProto branchRegisterRequest = 1;</code>
* @return Whether the branchRegisterRequest field is set.
*/
boolean hasBranchRegisterRequest();
/**
* <code>.io.seata.protocol.protobuf.BranchRegisterRequestProto branchRegisterRequest = 1;</code>
* @return The branchRegisterRequest.
*/
io.seata.serializer.protobuf.generated.BranchRegisterRequestProto getBranchRegisterRequest();
/**
* <code>.io.seata.protocol.protobuf.BranchRegisterRequestProto branchRegisterRequest = 1;</code>
*/
io.seata.serializer.protobuf.generated.BranchRegisterRequestProtoOrBuilder getBranchRegisterRequestOrBuilder();
}
| 41.96
| 113
| 0.79123
|
8843c228e4257c5dacd5c3dd183d94d347beb803
| 1,236
|
import java.util.ArrayList;
import java.util.List;
/**
*
* @author surajs
*/
public class Cup {
List<Die> dice = new ArrayList<>();
Cup() {
for (int i = 0; i < 6; i++) {
Die d = new Die(1);
dice.add(d);
}
for (int i = 0; i < 4; i++) {
Die d = new Die(2);
dice.add(d);
}
for (int i = 0; i < 3; i++) {
Die d = new Die(3);
dice.add(d);
}
}
Die pickDieFromCup() {
Die d = new Die();
boolean atleastOneincup = false;
for(int i =0; i<13;i++)
{
if(dice.get(i).inCup)
atleastOneincup = true;
}
if(!atleastOneincup)
{
for(int i = 0; i<=13;i++)
{
if (dice.get(i).value==1)
dice.get(i).inCup= false;
}
}
while (true) {
int index = 1 + (int) (Math.random() * 13) -1;
d = dice.get(index);
if ((d.inCup)) {
dice.get(index).inCup = false;
}
break;
}
return d;
}
}
| 17.657143
| 58
| 0.351942
|
74b0c69f8e83235592642205bf5c8f76a7e3becb
| 1,910
|
package com.redhat.idaas.datasynthesis.services;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import javax.transaction.Transactional;
import com.redhat.idaas.datasynthesis.models.DataGeneratedAddressesEntity;
import com.redhat.idaas.datasynthesis.dtos.NameLast;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import io.quarkus.test.TestTransaction;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
@TestTransaction
public class AddressServiceTest {
@Inject
AddressService addressService;
@Inject
NameLastService nameService;
@Test
@Transactional
public void testAddressGeneration() throws Exception {
Common.seed();
nameService.insertNameLast(new NameLast("Last1"));
nameService.insertNameLast(new NameLast("Last2"));
List<DataGeneratedAddressesEntity> list = addressService.generateAddresses(10);
Assertions.assertEquals(10, list.size());
Assertions.assertEquals(10, DataGeneratedAddressesEntity.count());
for (DataGeneratedAddressesEntity entity : list) {
validateAddressEntry(entity);
}
}
private void validateAddressEntry(DataGeneratedAddressesEntity entity) {
String address = entity.getAddressStreet();
String[] segments = address.split(" ");
Assertions.assertTrue(segments.length == 3 || segments.length == 4);
int i = 0;
Assertions.assertTrue(Integer.parseInt(segments[i++]) < 10000);
if (segments.length == 4) {
Assertions.assertTrue(Arrays.stream(AddressService.DIRECTIONS).anyMatch(segments[i]::equals));
i++;
}
Assertions.assertTrue(segments[i].equals("Last1") || segments[i].equals("Last2"));
i++;
Assertions.assertTrue(Arrays.stream(AddressService.STREET_TYPES).anyMatch(segments[i]::equals));
}
}
| 32.372881
| 106
| 0.70733
|
8605124c96be2e1c5a71d02d15c6fd04c09aeed3
| 2,393
|
package org.axesoft.jaxos;
import com.google.protobuf.ByteString;
import io.netty.util.CharsetUtil;
import org.axesoft.jaxos.algo.Event;
import org.axesoft.jaxos.algo.Instance;
import org.axesoft.jaxos.logger.InstanceValueRingCache;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* @author gaoyuan
* @sine 2019/10/15.
*/
public class InstanceRingCacheTest {
private Instance newValue(long instanceId) {
return new Instance(1, instanceId, 2,
Event.BallotValue.appValue(instanceId, ByteString.copyFrom(Long.toString(instanceId), CharsetUtil.UTF_8)));
}
@Test
public void testSize() {
InstanceValueRingCache cache = new InstanceValueRingCache(256);
assertEquals(0, cache.size());
int i0 = 10000;
for (int i = i0; i < i0 + 256; i++) {
cache.put(newValue(i));
assertEquals(i - i0 + 1, cache.size());
}
for (int j = 0; j < 10; j++) {
cache.put(newValue(i0 + 256 + j));
assertEquals(256, cache.size());
}
}
@Test
public void testGet1() {
InstanceValueRingCache cache = new InstanceValueRingCache(256);
long i0 = 10000;
for (long i = i0; i < i0 + 128; i++) {
cache.put(newValue(i));
}
List<Instance> ix1 = cache.get(i0, i0 + 9);
assertEquals(10, ix1.size());
assertEquals(i0, ix1.get(0).id());
assertEquals(i0 + 9, ix1.get(9).id());
}
@Test
public void testGet2() {
InstanceValueRingCache cache = new InstanceValueRingCache(256);
long i0 = 10000;
for (long i = i0; i < i0 + 128; i++) {
cache.put(newValue(i));
}
List<Instance> ix1 = cache.get(i0 + 120, i0 + 130);
assertEquals(8, ix1.size());
assertEquals(i0 + 120, ix1.get(0).id());
assertEquals(i0 + 127, ix1.get(7).id());
}
@Test
public void testGet3() {
InstanceValueRingCache cache = new InstanceValueRingCache(256);
long i0 = 10000;
for (long i = i0; i < i0 + 300; i++) {
cache.put(newValue(i));
}
List<Instance> ix1 = cache.get(i0 + 201, i0 + 290);
assertEquals(90, ix1.size());
assertEquals(i0 + 201, ix1.get(0).id());
assertEquals(i0 + 290, ix1.get(89).id());
}
}
| 28.152941
| 123
| 0.5771
|
a48829e9b6d908f20e2e5a431bacc2d186a63552
| 467
|
package com.ruoyi.web.wexin.jwt;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 用于跳过token的验证
*/
//{ElementType.METHOD用于的方法的注解目标
//{ElementType.TYPE用于类,接口,枚举,注解的注解目标
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)//这种注解将被jvm或被反射机制的代码锁读取和使用
public @interface PassToken {
boolean required() default true;
}
| 25.944444
| 61
| 0.800857
|
b550c6f9bdaca7e0db916a4470cc7275e0222c3f
| 2,056
|
package com.learn.code.linkedlist;
/**
* https://leetcode.com/problems/palindrome-linked-list/
*/
public class PalindromeLinkedList {
public static void main(String[] args) {
ListNode six1 = new ListNode(1);
ListNode five1 = new ListNode(2, six1);
ListNode four1 = new ListNode(3, five1);
ListNode three1 = new ListNode(4, four1);
ListNode two1 = new ListNode(5, three1);
ListNode one1 = new ListNode(6, two1);
ListNode six = new ListNode(6, one1);
ListNode five = new ListNode(5, six);
ListNode four = new ListNode(4, five);
ListNode three = new ListNode(3, four);
ListNode two = new ListNode(2, three);
ListNode one = new ListNode(1, two);
System.out.println(PalindromeLinkedList.isPalindrome(one));
}
public static ListNode reverse(ListNode head) {
ListNode prev = null;
while(head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
public static boolean isPalindrome(ListNode head) {
ListNode slow = head, fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
if (fast != null) {
slow = slow.next;
}
slow = reverse(slow);
fast = head;
while(slow != null ) {
if(fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
public static int count(ListNode head) {
int count = 1;
ListNode slow = head, fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow != null) {
count++;
}
if(fast != null) {
count++;
}
}
return count;
}
}
| 27.413333
| 67
| 0.508755
|
e4fc5cda1b264e6370546c487372e78e639249c0
| 452
|
/*
Desenvolvido pelo Laboratório de Segurança em Computação (LabSEC) do Departamento de Informática e Estatística (INE),
da Universidade Federal de Santa Catarina (UFSC).
Apoio: Colégio Notarial do Brasil (CNB) e Instituto Nacional de Tecnologia da Informação (ITI).
*/
package br.ufsc.labsec.signature.conformanceVerifier.xades;
/**
* Enumeração dos formatos de assinatura.
*/
public enum SignatureFormat {
XAdES, CounterSignature_XAdES
}
| 25.111111
| 117
| 0.776549
|
641bbb81857d2da6b9c0ee3b86962049b9e3766e
| 1,349
|
package com.box.boxjavalibv2.requests;
import com.box.boxjavalibv2.IBoxConfig;
import com.box.boxjavalibv2.jsonparsing.IBoxJSONParser;
import com.box.restclientv2.RestMethod;
import com.box.restclientv2.exceptions.BoxRestException;
import com.box.restclientv2.requestsbase.BoxDefaultRequestObject;
import com.box.restclientv2.requestsbase.DefaultBoxRequest;
/**
* Request to get a comment.
*/
public class GetCommentRequest extends DefaultBoxRequest {
public static final String URI = "/comments/%s";
/**
* Constructor.
*
* @param config
* config
* @param parser
* json parser
* @param commentId
* id of the comment to be fetched
* @param requestObject
* request object
* @throws BoxRestException
* exception
*/
public GetCommentRequest(final IBoxConfig config, final IBoxJSONParser parser, String commentId, BoxDefaultRequestObject requestObject)
throws BoxRestException {
super(config, parser, getUri(commentId), RestMethod.GET, requestObject);
}
/**
* Get uri.
*
* @param commentId
* id of the comment to be fetched
* @return uri
*/
public static String getUri(String commentId) {
return String.format(URI, commentId);
}
}
| 28.702128
| 139
| 0.661231
|
092dd8ecbb50f0940b1b997604eafac7ca5d6136
| 139
|
package com.chanpreet.AbstractShapeProg;
public class Trapezoid extends Shapes {
@Override
int numberOfSides() {
return 4;
}
}
| 11.583333
| 40
| 0.719424
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.