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
|
---|---|---|---|---|---|
2968d4baa7f02e16dcc44737849be4217ec2b8b8 | 1,751 | package com.drovahkinn;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.drovahkinn.handlers.TrafficHandler;
import com.drovahkinn.logger.ServerLogger;
public class Minik {
private static final int DEFAULT_PORT = 8083;
private static final int N_THREADS = 3;
public static void main(String args[]) {
try {
new Minik().initialize(validatePort(args));
} catch (Exception e) {
// e.printStackTrace();
ServerLogger.getInstance().error(e.getMessage());
}
}
/**
* Initializes server.
*/
public void initialize(int port) {
try (ServerSocket s = new ServerSocket(port)) {
System.out.println("🧪[🇲🇲] Server running on port: " + port + " ( ⚠️ CTRL-C to quit!)");
System.out.println("🧪[🇲🇲] Number of Threads: " + N_THREADS + "⛓️.");
ServerLogger.getInstance().info("🧪[🇲🇲] Server running on port: " + port);
ExecutorService executor = Executors.newFixedThreadPool(N_THREADS);
while (true) {
executor.submit(new TrafficHandler(s.accept()));
}
} catch (IOException e) {
ServerLogger.getInstance().error(e.getMessage());
}
}
/**
* Parse command line arguments (string[] args) for valid port number
*
* @return int valid port number or default value (8083)
*/
static int validatePort(String args[]) throws IllegalArgumentException {
if (args.length > 0) {
int port = Integer.parseInt(args[0]);
if (port > 1024 && port < 65535) {
return port;
} else {
throw new IllegalArgumentException(" ⛔ Invalid port! Range: 1️⃣0️⃣2️⃣4️⃣ 🇹🇴 6️⃣5️⃣5️⃣3️⃣5️⃣");
}
}
return DEFAULT_PORT;
}
}
| 28.704918 | 99 | 0.641919 |
70a0901baa4fb458025945f7571baca233ac9e10 | 276 | package me.ianhe.pp.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import me.ianhe.pp.entity.QuestionEntity;
/**
*
*
* @author iHelin [email protected]
* @since 2021-04-16 12:00:53
*/
public interface QuestionDao extends BaseMapper<QuestionEntity> {
}
| 18.4 | 65 | 0.746377 |
d01f27e52e54f19019ed0018945bcbb94865a21a | 1,022 | /*
* 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.bytedance.bytehouse.buffer;
import java.io.IOException;
/**
* read and buffer.
*/
public interface BuffedReader {
/**
* Read 4 bytes and return them as int
*/
int readBinary() throws IOException;
/**
* read bytes into the array and return total amount of bytes read.
*
* @param bytes byte array container
* @return amount of bytes read.
*/
int readBinary(byte[] bytes) throws IOException;
}
| 28.388889 | 75 | 0.697652 |
1415791126098147216601af89453515d2685cad | 4,602 | package conjugationstation.conjugationreviewer;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
// Copyright (c) 2010-2011 Michael Hergenrader
//
// 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.
/**
* Special purpose dialog used to make the clock stop after an answer entered
* @author Michael Hergenrader
*/
public class TimerDialog extends JDialog implements WindowListener {
private JButton confirm;
private JTextField message;
private JFrame owner;
public TimerDialog(JFrame owner, String title, boolean modal) {
super(owner,title,modal);
this.owner = owner;
addWindowListener(this);
DisposeAction dispose = new DisposeAction();
confirm = new JButton("OK");
confirm.addActionListener(dispose);
message = new JTextField(40);
message.setBorder(BorderFactory.createEmptyBorder());
message.setHorizontalAlignment(SwingConstants.CENTER);
message.setEditable(false);
message.getInputMap().put(KeyStroke.getKeyStroke("ENTER"),"pressed");
message.getActionMap().put("pressed",dispose);
message.setAction(dispose);
JPanel messagePanel = new JPanel();
messagePanel.setMinimumSize(new Dimension(300,70));
messagePanel.setMaximumSize(new Dimension(300,70));
messagePanel.setPreferredSize(new Dimension(300,70));
messagePanel.add(message);
JPanel buttonPanel = new JPanel();
buttonPanel.setMinimumSize(new Dimension(300,50));
buttonPanel.setMaximumSize(new Dimension(300,50));
buttonPanel.setPreferredSize(new Dimension(300,50));
buttonPanel.add(confirm);
SpringLayout sl = new SpringLayout();
setLayout(sl);
add(messagePanel);
add(buttonPanel);
sl.putConstraint(SpringLayout.NORTH,messagePanel,0,SpringLayout.NORTH,getContentPane());
sl.putConstraint(SpringLayout.WEST,messagePanel,0,SpringLayout.WEST,getContentPane());
sl.putConstraint(SpringLayout.NORTH,buttonPanel,0,SpringLayout.SOUTH,messagePanel);
sl.putConstraint(SpringLayout.WEST,buttonPanel,0,SpringLayout.WEST,getContentPane());
}
public void setTitle(String title) {
super.setTitle(title);
}
public void setMessage(String message) {
this.message.setText(message);
this.message.requestFocusInWindow();
}
class DisposeAction extends AbstractAction {
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == message || ae.getSource() == confirm) {
if(owner instanceof ConjugationReviewFrame) {
if(((ConjugationReviewFrame)owner).isRunning()) {
((ConjugationReviewFrame)owner).setRunning(true); // no matter what set it running again
}
}
dispose();
}
}
}
public void setMessageInFocus() {
message.requestFocusInWindow();
}
public void windowClosing(WindowEvent e) { // if user uses the mouse to close the window with the upper right [x]
((ConjugationReviewFrame)owner).setRunning(true);
}
// Other necessary override methods
public void windowClosed(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
}
| 37.112903 | 117 | 0.68731 |
564182afd4d3a5bba210786b3365764a1c17a1ef | 4,034 | package org.spica.server.project.service;
import com.atlassian.jira.rest.client.api.IssueRestClient;
import com.atlassian.jira.rest.client.api.JiraRestClient;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.SearchResult;
import com.atlassian.jira.rest.client.api.domain.Transition;
import com.atlassian.jira.rest.client.api.domain.input.TransitionInput;
import com.atlassian.jira.rest.client.auth.BasicHttpAuthenticationHandler;
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory;
import io.atlassian.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spica.server.commons.ExternalSystem;
import org.spica.server.project.model.TaskInfo;
import org.springframework.stereotype.Service;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.function.Consumer;
/**
* Adapter which provides an abstraction to access and change topics in external system
*/
@Service
@Slf4j
public class JiraTaskAdapter implements ExternalSystemTaskAdapter {
public final static String EXTERNAL_SYSTEM_KEY_JIRA = "JIRA";
private AsynchronousJiraRestClientFactory jiraRestClientFactory = new AsynchronousJiraRestClientFactory();
@Override
public Collection<TaskInfo> getTasksOfUser(ExternalSystem externalSystem) {
JiraRestClient jiraRestClient = getRestClient(externalSystem);
Collection<TaskInfo> topicsFromJira = new ArrayList<TaskInfo>();
Promise<SearchResult> promise = jiraRestClient.getSearchClient().searchJql("assignee = currentUser() AND resolution = Unresolved").done(new Consumer<SearchResult>() {
@Override
public void accept(SearchResult searchResult) {
for (Issue next: searchResult.getIssues()) {
log.info("Found my issue " + next.getKey() + "-" + next.getSummary() + "-" + next.getStatus().getName());
TaskInfo topicInfo = new TaskInfo();
topicInfo.setExternalSystemID(EXTERNAL_SYSTEM_KEY_JIRA);
topicInfo.setExternalSystemKey(next.getKey());
topicInfo.setName(next.getSummary());
topicInfo.setDescription(next.getDescription());
topicsFromJira.add(topicInfo);
}
}
});
promise.claim();
return topicsFromJira;
}
private JiraRestClient getRestClient (ExternalSystem externalSystem) {
return jiraRestClientFactory.create(URI.create(externalSystem.getUrl()), new BasicHttpAuthenticationHandler(externalSystem.getUser(), externalSystem.getPassword()));
}
public String getStatus(ExternalSystem externalSystem, String key) {
JiraRestClient restClient = getRestClient(externalSystem);
IssueRestClient issueRestClient = restClient.getIssueClient();
Promise<Issue> issuePromise = issueRestClient.getIssue(key);
Issue issue = issuePromise.claim();
System.out.println ("Status: " + issue.getStatus().getName() + "-" + issue.getStatus().getId());
Promise<Iterable<Transition>> ptransitions = issueRestClient.getTransitions(issue);
Iterable<Transition> transitions = ptransitions.claim();
for(Transition t: transitions){
System.out.println("-" + t.getName() + ":" + t.getId() + "-" + t.toString());
}
System.out.println("Current state; " + issue.getStatus().getName());
return issue.getStatus().getId().toString();
}
public void setStatus (ExternalSystem externalSystem, String key, int id) {
JiraRestClient restClient = getRestClient(externalSystem);
IssueRestClient issueRestClient = restClient.getIssueClient();
Promise<Issue> issuePromise = issueRestClient.getIssue(key);
Issue issue = issuePromise.claim();
issueRestClient.transition(issue, new TransitionInput(id));
}
}
| 42.914894 | 174 | 0.713188 |
8f0e85f79a1e58cde09b3ecd36de9adadba73c5a | 1,002 | import java.util.*;
/**
* @author Shogo Akiyama
* Solved on 06/15/2019
*
* 169. Majority Element
* https://leetcode.com/problems/majority-element/
* Difficulty: Easy
*
* To run the code in LeetCode, take the codes from the following method(s):
* - int majorityElement(int[] nums).
*
* Runtime: 1 ms, faster than 100.00% of Java online submissions for Majority Element.
* Memory Usage: 41.5 MB, less than 60.72% of Java online submissions for Majority Element.
*
*/
public class MajorityElement {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int size = nums.length;
if(size%2 == 1){
return nums[size/2];
}else{
if(nums[size/2-1] == nums[size/2]){
return nums[size/2];
}else{
if(nums[size/2-1] == nums[0]){
return nums[size/2-1];
}else{
return nums[size/2];
}
}
}
}
} | 25.692308 | 91 | 0.541916 |
b21a0f4754ef9f9e906fea3502f46fd4ea623cf3 | 1,958 | package io.renren.modules.WeiYu.model;
import java.util.Date;
public class coachLeave {
private String classname;
private String trainingid;
private Date traniningdate;
private String coachid;
private Integer coachleave;
private String leavereason;
private String coachleavestatus;
private String replacecoachid;
public String getClassname() {
return classname;
}
public void setClassname(String classname) {
this.classname = classname == null ? null : classname.trim();
}
public String getTrainingid() {
return trainingid;
}
public void setTrainingid(String trainingid) {
this.trainingid = trainingid == null ? null : trainingid.trim();
}
public Date getTraniningdate() {
return traniningdate;
}
public void setTraniningdate(Date traniningdate) {
this.traniningdate = traniningdate;
}
public String getCoachid() {
return coachid;
}
public void setCoachid(String coachid) {
this.coachid = coachid == null ? null : coachid.trim();
}
public Integer getCoachleave() {
return coachleave;
}
public void setCoachleave(Integer coachleave) {
this.coachleave = coachleave;
}
public String getLeavereason() {
return leavereason;
}
public void setLeavereason(String leavereason) {
this.leavereason = leavereason == null ? null : leavereason.trim();
}
public String getCoachleavestatus() {
return coachleavestatus;
}
public void setCoachleavestatus(String coachleavestatus) {
this.coachleavestatus = coachleavestatus == null ? null : coachleavestatus.trim();
}
public String getReplacecoachid() {
return replacecoachid;
}
public void setReplacecoachid(String replacecoachid) {
this.replacecoachid = replacecoachid == null ? null : replacecoachid.trim();
}
} | 23.035294 | 90 | 0.660368 |
330163fa566fe2e7110a605dae5131758e73d495 | 482 | package com.frist.drafting_books.ui.home;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class HomeViewModel extends ViewModel {
private MutableLiveData<String> userName;
public HomeViewModel() {
userName = new MutableLiveData<>();
userName.setValue("This is home fragment!!!!!");
}
public LiveData<String> getText() {
return userName;
}
} | 25.368421 | 57 | 0.688797 |
c54a12b3e8ccfb73c20881a6e4669ede02fbeaa3 | 708 | package gov.kui.docRepoR.dto.mappers;
import gov.kui.docRepoR.domain.FileEntity;
import gov.kui.docRepoR.dto.FileEntityDto;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.List;
import java.util.Set;
@Mapper
public interface FileEntityMapper {
public static FileEntityMapper INSTANCE = Mappers.getMapper(FileEntityMapper.class);
public FileEntityDto fileEntityToFileEntityDto(FileEntity fileEntity);
public FileEntity fileEntityDtoToFileEntity(FileEntityDto fileEntityDto);
public Set<FileEntityDto> fileEntitiesToFileEntityDtos(Set<FileEntity> fileEntitys);
public Set<FileEntity> fileEntityDtosToFileEntities(Set<FileEntityDto> fileEntityDtos);
}
| 37.263158 | 91 | 0.827684 |
8f8d794ac5ac2ceb1d9fea427cac380729a20209 | 686 | package org.firstinspires.ftc.teamcode;
public class firstProgram {
public static void main(String args[]) {
System.out.println("The for loop");
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
boolean isComplete = false;
int a = 0;
while (! isComplete) {
System.out.println("The while loop");
if (a == 10) {
System.out.println("a is 10");
} else if (a == 5) {
System.out.println("a is 5");
} else {
System.out.println("a is neither 10 nor 5");
}
isComplete = true;
}
}
}
| 20.176471 | 60 | 0.460641 |
984c437a34bf17e0acad4d80bf944c43e48cdb8a | 2,821 | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
// Assumption: The three input files are individually sorted.
public class FileMergeSort {
private Scanner in1;
private Scanner in2;
private Scanner in3;
private FileWriter fw;
public FileMergeSort(String inPath1, String inPath2, String inPath3, String outPath) throws IOException {
in1 = new Scanner(new File(inPath1));
in2 = new Scanner(new File(inPath2));
in3 = new Scanner(new File(inPath3));
fw = new FileWriter(new File(outPath));
}
// Return 1 if s1 is smallest, 2 is s2 is smallest, 3 if s3 is smallest
// As some of the streams can get consumed ahead of others,
// this function can get called with some null parameters.
private int compareStrings(String s1, String s2, String s3) {
if (s1 == null && s2 != null && s3 != null) {
return (s2.compareTo(s3) <= 0 ? 2 : 3);
}
if (s1 != null && s2 == null && s3 != null) {
return (s1.compareTo(s3) <= 0 ? 1 : 3);
}
if (s1 != null && s2 != null && s3 == null) {
return (s1.compareTo(s2) <= 0 ? 1 : 2);
}
if(s1 == null && s2 == null) return 3;
if (s2 == null && s3 == null) return 1;
if (s3 == null && s1 == null) return 1;
// At this point s1 != null, s2 != null, s3 != null
if(s1.compareTo(s2) <= 0) {
if (s1.compareTo(s3) <= 0) return 1; // s1 <= s2 & & s1 <= s3
else return 3; // s3 < s1 && s1<= s2
}
else {
if(s2.compareTo(s3) <= 0) return 2; // s1 > s2 and s3 >= s2
else return 3; // s1 > s2 and s2 > s3
}
}
public void processStream() throws IOException {
Boolean done1 = false, done2 = false, done3 = false;
String l1 = null, l2 = null, l3 = null;
while(true){
if(l1 == null && !done1) l1 = in1.nextLine();
if(l2 == null && !done2) l2 = in2.nextLine();
if(l3 == null && !done3) l3 = in3.nextLine();
//System.out.println(l1 + ", " + l2 + ", " + l3);
int smallest = compareStrings(l1, l2, l3);
if(smallest == 1) {
System.out.println(l1);
fw.write(l1 + "\n");
l1 = null;
}
if(smallest == 2) {
System.out.println(l2);
fw.write(l2 + "\n");
l2 = null;
}
if(smallest == 3) {
System.out.println(l3);
fw.write(l3 + "\n");
l3 = null;
}
if(l1 == null && l2 == null && l3 == null) break;
if(!in1.hasNextLine()) {
done1 = true;
}
if(!in2.hasNextLine()) {
done2 = true;
}
if(!in3.hasNextLine()) {
done3 = true;
}
}
//System.out.println("processed stream");
in1.close();
in2.close();
in3.close();
fw.flush();
fw.close();
return;
}
public static void main(String [] args) throws IOException {
FileMergeSort fms = new FileMergeSort(args[0], args[1], args[2], args[3]);
fms.processStream();
System.exit(0);
}
}
| 24.318966 | 106 | 0.579227 |
c60d0ce850d17e0263cd1d17f91214c279643ece | 803 | package com.aaron.mymvp.presenter;
import com.aaron.mymvp.Contracts;
import com.aaron.mymvp.model.BaseModel;
public class BasePresenter implements Contracts.IPresenter {
private static final String TAG = "BasePresenter";
private Contracts.IView mView;
private Contracts.IModel mModel;
@Override
public void attachView(Contracts.IView view) {
mView = view;
mModel = new BaseModel(this);
}
@Override
public void detachView() {
mView = null;
mModel = null;
}
@Override
public void requestText() {
if (mModel != null) {
mModel.queryText();
}
}
@Override
public void onResponse(String response) {
if (mView != null) {
mView.onShowText(response);
}
}
}
| 20.589744 | 60 | 0.613948 |
4d4eb9d5eb583796650ab616a0445ce854393d6b | 1,453 | package org.sakaiproject.archiver.persistence;
import java.util.List;
import org.sakaiproject.archiver.api.ArchiverService;
import org.sakaiproject.archiver.entity.ArchiveEntity;
/**
* DAO for the Archiver. This is not part of the API and you should not use it. Use {@link ArchiverService} instead.
*/
public interface ArchiverPersistenceService {
/**
* Create a new archive
*
* @param siteId
* @param userUuid
* @return the persistent entity
*/
ArchiveEntity create(String siteId, String userUuid);
/**
* Update an existing archive
*
* @param entity the entity with updated fields to be persisted
* @return the updated entity
*/
ArchiveEntity update(ArchiveEntity entity);
/**
* Get the latest archive for the given site. Return null if none exists
*
* @param siteId
* @return
*/
ArchiveEntity getLatest(String siteId);
/**
* Get an archive by its id. Returns null if none exists by that id.
*
* @param archiveId the id to lookup the archive for
* @return
*/
ArchiveEntity getByArchiveId(String archiveId);
/**
* Get a list of archives by the associated siteId ordered by date descending. The siteId can be left blank to get archives for all
* sites.
*
* @param siteId the id to lookup the archives for
* @param max the maximum number to return
* @return List of {@link ArchiveEntity} or empty list if none exist
*/
List<ArchiveEntity> getBySiteId(String siteId, int max);
}
| 25.491228 | 132 | 0.720578 |
1460665d7407ef55fca93c565715f9af640a38fd | 3,817 | package seedu.address.model.apparel;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static seedu.address.logic.commands.CommandTestUtil.VALID_COLOR_BLUE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_B;
import static seedu.address.logic.commands.CommandTestUtil.VALID_TYPE_BOTTOM;
import static seedu.address.testutil.TypicalApparels.BOBYIN;
import static seedu.address.testutil.TypicalApparels.NAME_INFORMAL_SHIRT;
import static seedu.address.testutil.TypicalApparels.SHIRT1;
import static seedu.address.testutil.TypicalApparels.SHIRT2;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.address.testutil.ApparelBuilder;
public class ApparelTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
/*@Test
public void asObservableList_modifyList_throwsUnsupportedOperationException() {
Apparel apparel = new ApparelBuilder().build();
thrown.expect(UnsupportedOperationException.class);
// TODO: modify the apparel content to trigger the exception here
}*/
@Test
public void isSamePerson() {
System.out.println(SHIRT1.toString());
// same object -> returns true
assertTrue(SHIRT1.isSameApparel(SHIRT1));
// different shirt -> return false
assertFalse(SHIRT1.isSameApparel(SHIRT2));
// null -> returns false
assertFalse(SHIRT1.isSameApparel(null));
// different color and clothing type -> returns false
Apparel editedAlice = new ApparelBuilder(SHIRT1).withColor(VALID_COLOR_BLUE)
.withClothingType(VALID_TYPE_BOTTOM).build();
assertFalse(SHIRT1.isSameApparel(editedAlice));
// different name -> returns false
editedAlice = new ApparelBuilder(SHIRT1).withName(VALID_NAME_B).build();
assertFalse(SHIRT1.isSameApparel(editedAlice));
// same name, same color, different type -> returns false
editedAlice = new ApparelBuilder(SHIRT1).withClothingType(VALID_TYPE_BOTTOM).build();
assertFalse(SHIRT1.isSameApparel(editedAlice));
// same name, different color, same type -> returns false
editedAlice = new ApparelBuilder(SHIRT1).withColor(VALID_COLOR_BLUE).build();
assertFalse(SHIRT1.isSameApparel(editedAlice));
// different name, same color, same type -> returns false
editedAlice = new ApparelBuilder(SHIRT1).withName(NAME_INFORMAL_SHIRT).build();
assertFalse(SHIRT1.isSameApparel(editedAlice));
}
@Test
public void equals() {
// same values -> returns true
Apparel aliceCopy = new ApparelBuilder(SHIRT1).build();
assertTrue(SHIRT1.equals(aliceCopy));
// same object -> returns true
assertTrue(SHIRT1.equals(SHIRT1));
// null -> returns false
assertFalse(SHIRT1.equals(null));
// different type -> returns false
assertFalse(SHIRT1.equals(5));
// different apparel -> returns false
assertFalse(SHIRT1.equals(BOBYIN));
// different name -> returns false
Apparel editedAlice = new ApparelBuilder(SHIRT1).withName(VALID_NAME_B).build();
assertFalse(SHIRT1.equals(editedAlice));
// different color -> returns false
editedAlice = new ApparelBuilder(SHIRT1).withColor(VALID_COLOR_BLUE).build();
assertFalse(SHIRT1.equals(editedAlice));
// different type -> returns false
editedAlice = new ApparelBuilder(SHIRT1).withClothingType(VALID_TYPE_BOTTOM).build();
assertFalse(SHIRT1.equals(editedAlice));
// same apparel -> returns true
editedAlice = new ApparelBuilder(SHIRT1).build();
assertTrue(SHIRT1.equals(editedAlice));
}
}
| 37.792079 | 93 | 0.707886 |
ef14bf1bfb7607865e4a1233a575d4ec098aa874 | 401 | package PoliTweetsCL.Core.Utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JSONizer {
static public String toJSON(Object obj){
Gson gson = new Gson();
return gson.toJson(obj);
}
static public String toPrettyJSON(Object obj){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
return gson.toJson(obj);
}
}
| 23.588235 | 67 | 0.673317 |
8278b25effd839aee1f5fb7fb7108e70df75eee3 | 13,438 | package io.github.kosmx.bendylibForge.impl;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.math.Matrix4f;
import com.mojang.math.Vector3f;
import com.mojang.math.Vector4f;
import net.minecraft.core.Direction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.function.Consumer;
/**
* Bendable cuboid literally...
* If you don't know the math behind it
* (Vectors, matrices, quaternions)
* don't try to edit.
*
* Use {@link BendableCuboid#setRotationDeg(float, float)} to bend the cube
*/
public class BendableCuboid implements ICuboid, IBendable, IterableRePos {
protected final Quad[] sides;
protected final RememberingPos[] positions;
//protected final Matrix4f matrix; - Shouldn't use... Change the moveVec instead of this.
protected Matrix4f lastPosMatrix;
//protected final RepositionableVertex.Pos3f[] positions = new RepositionableVertex.Pos3f[8];
//protected final Vector3f[] origins = new Vector3f[4];
public final float minX;
public final float minY;
public final float minZ;
public final float maxX;
public final float maxY;
public final float maxZ;
//protected final float size;
protected Vector3f moveVec;
//to shift the matrix to the center axis
protected final float fixX;
protected final float fixY;
protected final float fixZ;
protected final Direction direction;
protected final Plane basePlane;
protected final Plane otherPlane;
protected final float fullSize;
//Use Builder
protected BendableCuboid(Quad[] sides, RememberingPos[] positions, float minX, float minY, float minZ, float maxX, float maxY, float maxZ, float fixX, float fixY, float fixZ, Direction direction, Plane basePlane, Plane otherPlane, float fullSize) {
this.sides = sides;
this.positions = positions;
this.minX = minX;
this.minY = minY;
this.minZ = minZ;
this.maxX = maxX;
this.maxY = maxY;
this.maxZ = maxZ;
this.fixX = fixX;
this.fixY = fixY;
this.fixZ = fixZ;
//this.size = size;
this.direction = direction;
this.basePlane = basePlane;
this.otherPlane = otherPlane;
this.fullSize = fullSize;
this.applyBend(0, 0);//Init values to render
}
@Deprecated //the old constructor
public static BendableCuboid newBendableCuboid(int textureOffsetU, int textureOffsetV, int x, int y, int z, int sizeX, int sizeY, int sizeZ, boolean mirror, int textureWidth, int textureHeight, Direction direction, float extraX, float extraY, float extraZ) {
Builder builder = new Builder();
builder.v = textureOffsetV;
builder.u = textureOffsetU;
builder.x = x;
builder.y = y;
builder.z = z;
builder.sizeX = sizeX;
builder.sizeY = sizeY;
builder.sizeZ = sizeZ;
builder.mirror = mirror;
builder.textureWidth = textureWidth;
builder.textureHeight = textureHeight;
builder.direction = direction;
builder.extraX = extraX;
builder.extraY = extraY;
builder.extraZ = extraZ;
return builder.build();
}
public Matrix4f applyBend(float bendAxis, float bendValue){
return this.applyBend(bendAxis, bendValue, this);
}
@Override
public Direction getBendDirection() {
return this.direction;
}
@Override
public float getBendX() {
return fixX;
}
@Override
public float getBendY() {
return fixY;
}
@Override
public float getBendZ() {
return fixZ;
}
@Override
public Plane getBasePlane() {
return basePlane;
}
@Override
public Plane getOtherSidePlane() {
return otherPlane;
}
@Override
public float bendHeight() {
return fullSize;
}
@Override
public void iteratePositions(Consumer<IPosWithOrigin> consumer){
for(IPosWithOrigin pos:positions){
consumer.accept(pos);
}
}
/**
* a.k.a BendableCuboidFactory
*/
public static class Builder{
/**
* Size parameters
*/
public int x, y, z, sizeX, sizeY, sizeZ;
public float extraX, extraY, extraZ;
public int u, v;
public boolean mirror = false;
public int textureWidth, textureHeight; //That will be int
public Direction direction;
//public float bendX, bendY, bendZ;
public BendableCuboid build(){
ArrayList<Quad> planes = new ArrayList<>();
HashMap<Vector3f, RememberingPos> positions = new HashMap<>();
float minX = x, minY = y, minZ = z, maxX = x + sizeX, maxY = y + sizeY, maxZ = z + sizeZ;
float pminX = x - extraX, pminY = y - extraY, pminZ = z - extraZ, pmaxX = maxX + extraX, pmaxY = maxY + extraY, pmaxZ = maxZ + extraZ;
if(mirror){
float tmp = pminX;
pminX = pmaxX;
pmaxX = tmp;
}
//this is copy from MC's cuboid constructor
Vector3f vertex1 = new Vector3f(pminX, pminY, pminZ);
Vector3f vertex2 = new Vector3f(pmaxX, pminY, pminZ);
Vector3f vertex3 = new Vector3f(pmaxX, pmaxY, pminZ);
Vector3f vertex4 = new Vector3f(pminX, pmaxY, pminZ);
Vector3f vertex5 = new Vector3f(pminX, pminY, pmaxZ);
Vector3f vertex6 = new Vector3f(pmaxX, pminY, pmaxZ);
Vector3f vertex7 = new Vector3f(pmaxX, pmaxY, pmaxZ);
Vector3f vertex8 = new Vector3f(pminX, pmaxY, pmaxZ);
int j = u;
int k = u + sizeZ;
int l = u + sizeZ + sizeX;
int m = u + sizeZ + sizeX + sizeX;
int n = u + sizeZ + sizeX + sizeZ;
int o = u + sizeZ + sizeX + sizeZ + sizeX;
int p = v;
int q = v + sizeZ;
int r = v + sizeZ + sizeY;
createAndAddQuads(planes, positions, new Vector3f[]{vertex6, vertex5, vertex2}, k, p, l, q, textureWidth, textureHeight, mirror);
createAndAddQuads(planes, positions, new Vector3f[]{vertex3, vertex4, vertex7}, l, q, m, p, textureWidth, textureHeight, mirror);
createAndAddQuads(planes, positions, new Vector3f[]{vertex1, vertex5, vertex4}, j, q, k, r, textureWidth, textureHeight, mirror);
createAndAddQuads(planes, positions, new Vector3f[]{vertex2, vertex1, vertex3}, k, q, l, r, textureWidth, textureHeight, mirror);
createAndAddQuads(planes, positions, new Vector3f[]{vertex6, vertex2, vertex7}, l, q, n, r, textureWidth, textureHeight, mirror);
createAndAddQuads(planes, positions, new Vector3f[]{vertex5, vertex6, vertex8}, n, q, o, r, textureWidth, textureHeight, mirror);
Plane aPlane = new Plane(direction.step(), vertex7);
Plane bPlane = new Plane(direction.step(), vertex1);
boolean bl = direction == Direction.UP || direction == Direction.SOUTH || direction == Direction.EAST;
float fullSize = - direction.step().dot(vertex1) + direction.step().dot(vertex7);
float bendX = ((float) sizeX + x + x)/2;
float bendY = ((float) sizeY + y + y)/2;
float bendZ = ((float) sizeZ + z + z)/2;
return new BendableCuboid(planes.toArray(new Quad[0]), positions.values().toArray(new RememberingPos[0]), minX, minY, minZ, maxX, maxY, maxZ, bendX, bendY, bendZ, direction, bl ? aPlane : bPlane, bl ? bPlane : aPlane, fullSize);
}
//edge[2] can be calculated from edge 0, 1, 3...
private void createAndAddQuads(Collection<Quad> quads, HashMap<Vector3f, RememberingPos> positions, Vector3f[] edges, int u1, int v1, int u2, int v2, float squishU, float squishV, boolean flip){
int du = u2 < u1 ? 1 : -1;
int dv = v1 < v2 ? 1 : -1;
for(int localU = u2; localU != u1; localU += du){
for(int localV = v1; localV != v2; localV += dv){
int localU2 = localU + du;
int localV2 = localV + dv;
RememberingPos rp0 = getOrCreate(positions, transformVector(edges[0].copy(), edges[1].copy(), edges[2].copy(), u2, v1, u1, v2, localU2, localV));
RememberingPos rp1 = getOrCreate(positions, transformVector(edges[0].copy(), edges[1].copy(), edges[2].copy(), u2, v1, u1, v2, localU2, localV2));
RememberingPos rp2 = getOrCreate(positions, transformVector(edges[0].copy(), edges[1].copy(), edges[2].copy(), u2, v1, u1, v2, localU, localV2));
RememberingPos rp3 = getOrCreate(positions, transformVector(edges[0].copy(), edges[1].copy(), edges[2].copy(), u2, v1, u1, v2, localU, localV));
quads.add(new Quad(new RememberingPos[]{rp0, rp1, rp2, rp3}, localU, localV, localU2, localV2, textureWidth, textureHeight, mirror));
}
}
}
Vector3f transformVector(Vector3f pos, Vector3f vectorU, Vector3f vectorV, int u1, int v1, int u2, int v2, int u, int v){
vectorU.sub(pos);
vectorU.mul(((float)u - u1)/(u2-u1));
vectorV.sub(pos);
vectorV.mul(((float)v - v1)/(v2-v1));
pos.add(vectorU);
pos.add(vectorV);
return pos;
}
RememberingPos getOrCreate(HashMap<Vector3f, RememberingPos> positions, Vector3f pos){
if(!positions.containsKey(pos)){
positions.put(pos, new RememberingPos(pos));
}
return positions.get(pos);
}
}
/**
* Use {@link IBendable#applyBend(float, float, IterableRePos)} instead
* @param axisf bend around this axis
* @param value bend value in radians
* @return Used Matrix4f
*/
@Deprecated
public Matrix4f setRotationRad(float axisf, float value){
return this.applyBend(axisf, value);
}
/**
* Set the bend's rotation
* @param axis rotation axis in deg
* @param val rotation's value in deg
* @return Rotated Matrix4f
*/
public Matrix4f setRotationDeg(float axis, float val){
return this.setRotationRad(axis * 0.0174533f, val * 0.0174533f);
}
@Override
public void render(PoseStack.Pose matrices, VertexConsumer vertexConsumer, float red, float green, float blue, float alpha, int light, int overlay) {
for(Quad quad:sides){
quad.render(matrices, vertexConsumer, light, overlay, red, green, blue, alpha);
}
}
public Matrix4f getLastPosMatrix(){
return this.lastPosMatrix.copy();
}
/*
* A replica of {@link ModelPart.Quad}
* with IVertex and render()
*/
public static class Quad{
public final IVertex[] vertices;
public Quad(RememberingPos[] vertices, float u1, float v1, float u2, float v2, float squishU, float squishV, boolean flip){
float f = 0/squishU;
float g = 0/squishV;
this.vertices = new IVertex[4];
this.vertices[0] = new RepositionableVertex(u2 / squishU - f, v1 / squishV + g, vertices[0]);
this.vertices[1] = new RepositionableVertex(u1 / squishU + f, v1 / squishV + g, vertices[1]);
this.vertices[2] = new RepositionableVertex(u1 / squishU + f, v2 / squishV - g, vertices[2]);
this.vertices[3] = new RepositionableVertex(u2 / squishU - f, v2 / squishV - g, vertices[3]);
if(flip){
int i = vertices.length;
for(int j = 0; j < i / 2; ++j) {
IVertex vertex = this.vertices[j];
this.vertices[j] = this.vertices[i - 1 - j];
this.vertices[i - 1 - j] = vertex;
}
}
}
public void render(PoseStack.Pose matrices, VertexConsumer vertexConsumer, int light, int overlay, float red, float green, float blue, float alpha){
Vector3f direction = this.getDirection();
direction.transform(matrices.normal());
for (int i = 0; i != 4; ++i){
IVertex vertex = this.vertices[i];
Vector3f vertexPos = vertex.getPos();
Vector4f pos = new Vector4f(vertexPos.x()/16f, vertexPos.y()/16f, vertexPos.z()/16f, 1);
pos.transform(matrices.pose());
vertexConsumer.vertex(pos.x(), pos.y(), pos.z(), red, green, blue, alpha, vertex.getU(), vertex.getV(), overlay, light, direction.x(), direction.y(), direction.z());
}
}
/**
* calculate the normal vector from the vertices' coordinates with cross product
* @return the normal vector (direction)
*/
private Vector3f getDirection(){
Vector3f buf = vertices[3].getPos().copy();
buf.mul(-1);
Vector3f vecB = vertices[1].getPos().copy();
vecB.add(buf);
buf = vertices[2].getPos().copy();
buf.mul(-1);
Vector3f vecA = vertices[0].getPos().copy();
vecA.add(buf);
vecA.cross(vecB);
//Return the cross product, if it's zero then return anything non-zero to not cause crash...
return vecA.normalize() ? vecA : Direction.NORTH.step();
}
}
}
| 41.475309 | 262 | 0.602619 |
e9af237318a89bb8c6299f1c4c68176666988c03 | 32,283 | package com.qiuxs.cuteframework.core.basic.utils.ip2region.constants;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.qiuxs.cuteframework.core.basic.bean.Pair;
import com.qiuxs.cuteframework.core.basic.utils.CollectionUtils;
import com.qiuxs.cuteframework.core.basic.utils.generator.RandomGenerator;
import com.qiuxs.cuteframework.core.basic.utils.ip2region.Ip2RegionFacade;
/**
* 区域常量
* @author qiuxs
* 2019年6月15日 下午9:41:44
*/
public class RegionConstants {
/**[规范省名,规范省编码]*/
private static BiMap<String, Integer> provCodeBiMap = HashBiMap.create();
private static Map<String, Integer> provCodeMap = new HashMap<String, Integer>();
private static List<Integer> provCodeList = new ArrayList<Integer>();
private static BiMap<String, Integer> cityCodeBiMap = HashBiMap.create();
private static Map<String, Integer> cityCodeMap = new HashMap<String, Integer>();
private static Map<Integer, List<Integer>> provCodeCityCodesMap = new HashMap<>();
private static Map<Integer, BiMap<String, Integer>> provCodeCityNameCityCodeBiMapMap = new HashMap<>();
static {
/**********************************省******************************/
provCodeBiMap.put("北京市", 110000);
provCodeBiMap.put("天津市", 120000);
provCodeBiMap.put("河北省", 130000);
provCodeBiMap.put("山西省", 140000);
provCodeBiMap.put("内蒙古自治区", 150000);
provCodeBiMap.put("辽宁省", 210000);
provCodeBiMap.put("吉林省", 220000);
provCodeBiMap.put("黑龙江省", 230000);
provCodeBiMap.put("上海市", 310000);
provCodeBiMap.put("江苏省", 320000);
provCodeBiMap.put("浙江省", 330000);
provCodeBiMap.put("安徽省", 340000);
provCodeBiMap.put("福建省", 350000);
provCodeBiMap.put("江西省", 360000);
provCodeBiMap.put("山东省", 370000);
provCodeBiMap.put("河南省", 410000);
provCodeBiMap.put("湖北省", 420000);
provCodeBiMap.put("湖南省", 430000);
provCodeBiMap.put("广东省", 440000);
provCodeBiMap.put("广西壮族自治区", 450000);
provCodeBiMap.put("海南省", 460000);
provCodeBiMap.put("重庆市", 500000);
provCodeBiMap.put("四川省", 510000);
provCodeBiMap.put("贵州省", 520000);
provCodeBiMap.put("云南省", 530000);
provCodeBiMap.put("西藏自治区", 540000);
provCodeBiMap.put("陕西省", 610000);
provCodeBiMap.put("甘肃省", 620000);
provCodeBiMap.put("青海省", 630000);
provCodeBiMap.put("宁夏回族自治区", 640000);
provCodeBiMap.put("新疆维吾尔自治区", 650000);
provCodeBiMap.put("台湾省", 710000);
provCodeBiMap.put("香港特别行政区", 810000);
provCodeBiMap.put("澳门特别行政区", 820000);
provCodeMap.putAll(provCodeBiMap);
provCodeList.addAll(provCodeMap.values());
/***************************省别名********************************/
provCodeMap.put("北京", 110000);
provCodeMap.put("天津", 120000);
provCodeMap.put("河北", 130000);
provCodeMap.put("山西", 140000);
provCodeMap.put("内蒙古", 150000);
provCodeMap.put("辽宁", 210000);
provCodeMap.put("吉林", 220000);
provCodeMap.put("黑龙江", 230000);
provCodeMap.put("上海", 310000);
provCodeMap.put("江苏", 320000);
provCodeMap.put("浙江", 330000);
provCodeMap.put("安徽", 340000);
provCodeMap.put("福建", 350000);
provCodeMap.put("江西", 360000);
provCodeMap.put("山东", 370000);
provCodeMap.put("河南", 410000);
provCodeMap.put("湖北", 420000);
provCodeMap.put("湖南", 430000);
provCodeMap.put("广东", 440000);
provCodeMap.put("广西", 450000);
provCodeMap.put("海南", 460000);
provCodeMap.put("重庆", 500000);
provCodeMap.put("四川", 510000);
provCodeMap.put("贵州", 520000);
provCodeMap.put("云南", 530000);
provCodeMap.put("西藏", 540000);
provCodeMap.put("陕西", 610000);
provCodeMap.put("甘肃", 620000);
provCodeMap.put("青海", 630000);
provCodeMap.put("宁夏", 640000);
provCodeMap.put("新疆", 650000);
provCodeMap.put("台湾", 710000);
provCodeMap.put("香港", 810000);
provCodeMap.put("澳门", 820000);
/*********************************市*********************************/
{
BiMap<String, Integer> bjBiMap = HashBiMap.create();
bjBiMap.put("北京市", 110100);
// cityCodeMap.put("县" , 110200);
provCodeCityNameCityCodeBiMapMap.put(110000, bjBiMap);
}
{
BiMap<String, Integer> tjBiMap = HashBiMap.create();
tjBiMap.put("天津市", 120100);
// cityCodeMap.put("市辖县" , 120200);
provCodeCityNameCityCodeBiMapMap.put(120000, tjBiMap);
}
{
BiMap<String, Integer> hbBiMap = HashBiMap.create();
hbBiMap.put("石家庄市", 130100);
hbBiMap.put("唐山市", 130200);
hbBiMap.put("秦皇岛市", 130300);
hbBiMap.put("邯郸市", 130400);
hbBiMap.put("邢台市", 130500);
hbBiMap.put("保定市", 130600);
hbBiMap.put("张家口市", 130700);
hbBiMap.put("承德市", 130800);
hbBiMap.put("沧州市", 130900);
hbBiMap.put("廊坊市", 131000);
hbBiMap.put("衡水市", 131100);
provCodeCityNameCityCodeBiMapMap.put(130000, hbBiMap);
}
{
BiMap<String, Integer> sxBiMap = HashBiMap.create();
sxBiMap.put("太原市", 140100);
sxBiMap.put("大同市", 140200);
sxBiMap.put("阳泉市", 140300);
sxBiMap.put("长治市", 140400);
sxBiMap.put("晋城市", 140500);
sxBiMap.put("朔州市", 140600);
sxBiMap.put("晋中市", 140700);
sxBiMap.put("运城市", 140800);
sxBiMap.put("忻州市", 140900);
sxBiMap.put("临汾市", 141000);
sxBiMap.put("吕梁市", 141100);
provCodeCityNameCityCodeBiMapMap.put(140000, sxBiMap);
}
{
BiMap<String, Integer> nmgBiMap = HashBiMap.create();
nmgBiMap.put("呼和浩特市", 150100);
nmgBiMap.put("包头市", 150200);
nmgBiMap.put("乌海市", 150300);
nmgBiMap.put("赤峰市", 150400);
nmgBiMap.put("通辽市", 150500);
nmgBiMap.put("鄂尔多斯市", 150600);
nmgBiMap.put("呼伦贝尔市", 150700);
nmgBiMap.put("巴彦淖尔市", 150800);
nmgBiMap.put("乌兰察布市", 150900);
nmgBiMap.put("兴安盟", 152200);
nmgBiMap.put("锡林郭勒盟", 152500);
nmgBiMap.put("阿拉善盟", 152900);
provCodeCityNameCityCodeBiMapMap.put(150000, nmgBiMap);
}
{
BiMap<String, Integer> lnBiMap = HashBiMap.create();
lnBiMap.put("沈阳市", 210100);
lnBiMap.put("大连市", 210200);
lnBiMap.put("鞍山市", 210300);
lnBiMap.put("抚顺市", 210400);
lnBiMap.put("本溪市", 210500);
lnBiMap.put("丹东市", 210600);
lnBiMap.put("锦州市", 210700);
lnBiMap.put("营口市", 210800);
lnBiMap.put("阜新市", 210900);
lnBiMap.put("辽阳市", 211000);
lnBiMap.put("盘锦市", 211100);
lnBiMap.put("铁岭市", 211200);
lnBiMap.put("朝阳市", 211300);
lnBiMap.put("葫芦岛市", 211400);
provCodeCityNameCityCodeBiMapMap.put(210000, lnBiMap);
}
{
BiMap<String, Integer> jlBiMap = HashBiMap.create();
jlBiMap.put("长春市", 220100);
jlBiMap.put("吉林市", 220200);
jlBiMap.put("四平市", 220300);
jlBiMap.put("辽源市", 220400);
jlBiMap.put("通化市", 220500);
jlBiMap.put("白山市", 220600);
jlBiMap.put("松原市", 220700);
jlBiMap.put("白城市", 220800);
jlBiMap.put("延边朝鲜族自治州", 222400);
provCodeCityNameCityCodeBiMapMap.put(220000, jlBiMap);
}
{
BiMap<String, Integer> hljBiMap = HashBiMap.create();
hljBiMap.put("哈尔滨市", 230100);
hljBiMap.put("齐齐哈尔市", 230200);
hljBiMap.put("鸡西市", 230300);
hljBiMap.put("鹤岗市", 230400);
hljBiMap.put("双鸭山市", 230500);
hljBiMap.put("大庆市", 230600);
hljBiMap.put("伊春市", 230700);
hljBiMap.put("佳木斯市", 230800);
hljBiMap.put("七台河市", 230900);
hljBiMap.put("牡丹江市", 231000);
hljBiMap.put("黑河市", 231100);
hljBiMap.put("绥化市", 231200);
hljBiMap.put("大兴安岭地区", 232700);
provCodeCityNameCityCodeBiMapMap.put(230000, hljBiMap);
}
{
BiMap<String, Integer> shBiMap = HashBiMap.create();
shBiMap.put("上海市", 310100);
// cityCodeMap.put("县" , 310200);
provCodeCityNameCityCodeBiMapMap.put(310000, shBiMap);
}
{
BiMap<String, Integer> jsBiMap = HashBiMap.create();
jsBiMap.put("南京市", 320100);
jsBiMap.put("无锡市", 320200);
jsBiMap.put("徐州市", 320300);
jsBiMap.put("常州市", 320400);
jsBiMap.put("苏州市", 320500);
jsBiMap.put("南通市", 320600);
jsBiMap.put("连云港市", 320700);
jsBiMap.put("淮安市", 320800);
jsBiMap.put("盐城市", 320900);
jsBiMap.put("扬州市", 321000);
jsBiMap.put("镇江市", 321100);
jsBiMap.put("泰州市", 321200);
jsBiMap.put("宿迁市", 321300);
provCodeCityNameCityCodeBiMapMap.put(320000, jsBiMap);
}
{
BiMap<String, Integer> zjBiMap = HashBiMap.create();
zjBiMap.put("杭州市", 330100);
zjBiMap.put("宁波市", 330200);
zjBiMap.put("温州市", 330300);
zjBiMap.put("嘉兴市", 330400);
zjBiMap.put("湖州市", 330500);
zjBiMap.put("绍兴市", 330600);
zjBiMap.put("金华市", 330700);
zjBiMap.put("衢州市", 330800);
zjBiMap.put("舟山市", 330900);
zjBiMap.put("台州市", 331000);
zjBiMap.put("丽水市", 331100);
provCodeCityNameCityCodeBiMapMap.put(330000, zjBiMap);
}
{
BiMap<String, Integer> ahBiMap = HashBiMap.create();
ahBiMap.put("合肥市", 340100);
ahBiMap.put("芜湖市", 340200);
ahBiMap.put("蚌埠市", 340300);
ahBiMap.put("淮南市", 340400);
ahBiMap.put("马鞍山市", 340500);
ahBiMap.put("淮北市", 340600);
ahBiMap.put("铜陵市", 340700);
ahBiMap.put("安庆市", 340800);
ahBiMap.put("黄山市", 341000);
ahBiMap.put("滁州市", 341100);
ahBiMap.put("阜阳市", 341200);
ahBiMap.put("宿州市", 341300);
ahBiMap.put("巢湖市", 341400);
ahBiMap.put("六安市", 341500);
ahBiMap.put("亳州市", 341600);
ahBiMap.put("池州市", 341700);
ahBiMap.put("宣城市", 341800);
provCodeCityNameCityCodeBiMapMap.put(340000, ahBiMap);
}
{
BiMap<String, Integer> fjBiMap = HashBiMap.create();
fjBiMap.put("福州市", 350100);
fjBiMap.put("厦门市", 350200);
fjBiMap.put("莆田市", 350300);
fjBiMap.put("三明市", 350400);
fjBiMap.put("泉州市", 350500);
fjBiMap.put("漳州市", 350600);
fjBiMap.put("南平市", 350700);
fjBiMap.put("龙岩市", 350800);
fjBiMap.put("宁德市", 350900);
provCodeCityNameCityCodeBiMapMap.put(350000, fjBiMap);
}
{
BiMap<String, Integer> jxBiMap = HashBiMap.create();
jxBiMap.put("南昌市", 360100);
jxBiMap.put("景德镇市", 360200);
jxBiMap.put("萍乡市", 360300);
jxBiMap.put("九江市", 360400);
jxBiMap.put("新余市", 360500);
jxBiMap.put("鹰潭市", 360600);
jxBiMap.put("赣州市", 360700);
jxBiMap.put("吉安市", 360800);
jxBiMap.put("宜春市", 360900);
jxBiMap.put("抚州市", 361000);
jxBiMap.put("上饶市", 361100);
provCodeCityNameCityCodeBiMapMap.put(360000, jxBiMap);
}
{
BiMap<String, Integer> sdBiMap = HashBiMap.create();
sdBiMap.put("济南市", 370100);
sdBiMap.put("青岛市", 370200);
sdBiMap.put("淄博市", 370300);
sdBiMap.put("枣庄市", 370400);
sdBiMap.put("东营市", 370500);
sdBiMap.put("烟台市", 370600);
sdBiMap.put("潍坊市", 370700);
sdBiMap.put("济宁市", 370800);
sdBiMap.put("泰安市", 370900);
sdBiMap.put("威海市", 371000);
sdBiMap.put("日照市", 371100);
sdBiMap.put("莱芜市", 371200);
sdBiMap.put("临沂市", 371300);
sdBiMap.put("德州市", 371400);
sdBiMap.put("聊城市", 371500);
sdBiMap.put("滨州市", 371600);
sdBiMap.put("菏泽市", 371700);
provCodeCityNameCityCodeBiMapMap.put(370000, sdBiMap);
}
{
BiMap<String, Integer> hnBiMap = HashBiMap.create();
hnBiMap.put("郑州市", 410100);
hnBiMap.put("开封市", 410200);
hnBiMap.put("洛阳市", 410300);
hnBiMap.put("平顶山市", 410400);
hnBiMap.put("安阳市", 410500);
hnBiMap.put("鹤壁市", 410600);
hnBiMap.put("新乡市", 410700);
hnBiMap.put("焦作市", 410800);
hnBiMap.put("濮阳市", 410900);
hnBiMap.put("许昌市", 411000);
hnBiMap.put("漯河市", 411100);
hnBiMap.put("三门峡市", 411200);
hnBiMap.put("南阳市", 411300);
hnBiMap.put("商丘市", 411400);
hnBiMap.put("信阳市", 411500);
hnBiMap.put("周口市", 411600);
hnBiMap.put("驻马店市", 411700);
provCodeCityNameCityCodeBiMapMap.put(410000, hnBiMap);
}
{
BiMap<String, Integer> hbBiMap = HashBiMap.create();
hbBiMap.put("武汉市", 420100);
hbBiMap.put("黄石市", 420200);
hbBiMap.put("十堰市", 420300);
hbBiMap.put("宜昌市", 420500);
hbBiMap.put("襄樊市", 420600);
hbBiMap.put("鄂州市", 420700);
hbBiMap.put("荆门市", 420800);
hbBiMap.put("孝感市", 420900);
hbBiMap.put("荆州市", 421000);
hbBiMap.put("黄冈市", 421100);
hbBiMap.put("咸宁市", 421200);
hbBiMap.put("随州市", 421300);
hbBiMap.put("恩施州", 422800);
// cityCodeMap.put("省直辖行政单位" , 429000);
provCodeCityNameCityCodeBiMapMap.put(420000, hbBiMap);
}
{
BiMap<String, Integer> hnBiMap = HashBiMap.create();
hnBiMap.put("长沙市", 430100);
hnBiMap.put("株洲市", 430200);
hnBiMap.put("湘潭市", 430300);
hnBiMap.put("衡阳市", 430400);
hnBiMap.put("邵阳市", 430500);
hnBiMap.put("岳阳市", 430600);
hnBiMap.put("常德市", 430700);
hnBiMap.put("张家界市", 430800);
hnBiMap.put("益阳市", 430900);
hnBiMap.put("郴州市", 431000);
hnBiMap.put("永州市", 431100);
hnBiMap.put("怀化市", 431200);
hnBiMap.put("娄底市", 431300);
hnBiMap.put("湘西土家族苗族自治州", 433100);
provCodeCityNameCityCodeBiMapMap.put(430000, hnBiMap);
}
{
BiMap<String, Integer> gdBiMap = HashBiMap.create();
gdBiMap.put("广州市", 440100);
gdBiMap.put("韶关市", 440200);
gdBiMap.put("深圳市", 440300);
gdBiMap.put("珠海市", 440400);
gdBiMap.put("汕头市", 440500);
gdBiMap.put("佛山市", 440600);
gdBiMap.put("江门市", 440700);
gdBiMap.put("湛江市", 440800);
gdBiMap.put("茂名市", 440900);
gdBiMap.put("肇庆市", 441200);
gdBiMap.put("惠州市", 441300);
gdBiMap.put("梅州市", 441400);
gdBiMap.put("汕尾市", 441500);
gdBiMap.put("河源市", 441600);
gdBiMap.put("阳江市", 441700);
gdBiMap.put("清远市", 441800);
gdBiMap.put("东莞市", 441900);
gdBiMap.put("中山市", 442000);
gdBiMap.put("石岐区", 442100);
gdBiMap.put("东区", 442200);
gdBiMap.put("火炬高技术产业开发区", 442300);
gdBiMap.put("西区", 442400);
gdBiMap.put("南区", 442500);
gdBiMap.put("五桂山", 442600);
gdBiMap.put("潮州市", 445100);
gdBiMap.put("揭阳市", 445200);
gdBiMap.put("云浮市", 445300);
provCodeCityNameCityCodeBiMapMap.put(440000, gdBiMap);
}
{
BiMap<String, Integer> gxBiMap = HashBiMap.create();
gxBiMap.put("南宁市", 450100);
gxBiMap.put("柳州市", 450200);
gxBiMap.put("桂林市", 450300);
gxBiMap.put("梧州市", 450400);
gxBiMap.put("北海市", 450500);
gxBiMap.put("防城港市", 450600);
gxBiMap.put("钦州市", 450700);
gxBiMap.put("贵港市", 450800);
gxBiMap.put("玉林市", 450900);
gxBiMap.put("百色市", 451000);
gxBiMap.put("贺州市", 451100);
gxBiMap.put("河池市", 451200);
gxBiMap.put("来宾市", 451300);
gxBiMap.put("崇左市", 451400);
provCodeCityNameCityCodeBiMapMap.put(450000, gxBiMap);
}
{
BiMap<String, Integer> hnBiMap = HashBiMap.create();
hnBiMap.put("海口市", 460100);
hnBiMap.put("三亚市", 460200);
// cityCodeMap.put("省直辖县级行政区划" , 469000);
provCodeCityNameCityCodeBiMapMap.put(460000, hnBiMap);
}
{
BiMap<String, Integer> cqBiMap = HashBiMap.create();
cqBiMap.put("重庆市", 500100);
// cityCodeMap.put("县" , 500200);
provCodeCityNameCityCodeBiMapMap.put(500000, cqBiMap);
}
{
BiMap<String, Integer> scBiMap = HashBiMap.create();
scBiMap.put("成都市", 510100);
scBiMap.put("自贡市", 510300);
scBiMap.put("攀枝花市", 510400);
scBiMap.put("泸州市", 510500);
scBiMap.put("德阳市", 510600);
scBiMap.put("绵阳市", 510700);
scBiMap.put("广元市", 510800);
scBiMap.put("遂宁市", 510900);
scBiMap.put("内江市", 511000);
scBiMap.put("乐山市", 511100);
scBiMap.put("南充市", 511300);
scBiMap.put("眉山市", 511400);
scBiMap.put("宜宾市", 511500);
scBiMap.put("广安市", 511600);
scBiMap.put("达州市", 511700);
scBiMap.put("雅安市", 511800);
scBiMap.put("巴中市", 511900);
scBiMap.put("资阳市", 512000);
scBiMap.put("阿坝州", 513200);
scBiMap.put("甘孜藏族自治州", 513300);
scBiMap.put("凉山州", 513400);
provCodeCityNameCityCodeBiMapMap.put(510000, scBiMap);
}
{
BiMap<String, Integer> gzBiMap = HashBiMap.create();
gzBiMap.put("贵阳市", 520100);
gzBiMap.put("六盘水市", 520200);
gzBiMap.put("遵义市", 520300);
gzBiMap.put("安顺市", 520400);
gzBiMap.put("铜仁地区", 522200);
gzBiMap.put("黔西南州", 522300);
gzBiMap.put("毕节地区", 522400);
gzBiMap.put("黔东南苗族侗族自治州", 522600);
gzBiMap.put("黔南布依族苗族自治州", 522700);
provCodeCityNameCityCodeBiMapMap.put(520000, gzBiMap);
}
{
BiMap<String, Integer> ynBiMap = HashBiMap.create();
ynBiMap.put("昆明市", 530100);
ynBiMap.put("曲靖市", 530300);
ynBiMap.put("玉溪市", 530400);
ynBiMap.put("保山市", 530500);
ynBiMap.put("昭通市", 530600);
ynBiMap.put("丽江市", 530700);
ynBiMap.put("思茅市", 530800);
ynBiMap.put("临沧市", 530900);
ynBiMap.put("楚雄州", 532300);
ynBiMap.put("红河州", 532500);
ynBiMap.put("文山州", 532600);
ynBiMap.put("西双版纳州", 532800);
ynBiMap.put("大理州", 532900);
ynBiMap.put("德宏州", 533100);
ynBiMap.put("怒江州", 533300);
ynBiMap.put("迪庆州", 533400);
provCodeCityNameCityCodeBiMapMap.put(530000, ynBiMap);
}
{
BiMap<String, Integer> lsBiMap = HashBiMap.create();
lsBiMap.put("拉萨市", 540100);
lsBiMap.put("昌都地区", 542100);
lsBiMap.put("山南地区", 542200);
lsBiMap.put("日喀则地区", 542300);
lsBiMap.put("那曲地区", 542400);
lsBiMap.put("阿里地区", 542500);
lsBiMap.put("林芝地区", 542600);
provCodeCityNameCityCodeBiMapMap.put(540000, lsBiMap);
}
{
BiMap<String, Integer> sxBiMap = HashBiMap.create();
sxBiMap.put("西安市", 610100);
sxBiMap.put("铜川市", 610200);
sxBiMap.put("宝鸡市", 610300);
sxBiMap.put("咸阳市", 610400);
sxBiMap.put("渭南市", 610500);
sxBiMap.put("延安市", 610600);
sxBiMap.put("汉中市", 610700);
sxBiMap.put("榆林市", 610800);
sxBiMap.put("安康市", 610900);
sxBiMap.put("商洛市", 611000);
provCodeCityNameCityCodeBiMapMap.put(610000, sxBiMap);
}
{
BiMap<String, Integer> gsBiMap = HashBiMap.create();
gsBiMap.put("兰州市", 620100);
gsBiMap.put("嘉峪关市", 620200);
gsBiMap.put("金昌市", 620300);
gsBiMap.put("白银市", 620400);
gsBiMap.put("天水市", 620500);
gsBiMap.put("武威市", 620600);
gsBiMap.put("张掖市", 620700);
gsBiMap.put("平凉市", 620800);
gsBiMap.put("酒泉市", 620900);
gsBiMap.put("庆阳市", 621000);
gsBiMap.put("定西市", 621100);
gsBiMap.put("陇南市", 621200);
gsBiMap.put("临夏州", 622900);
gsBiMap.put("甘南州", 623000);
provCodeCityNameCityCodeBiMapMap.put(620000, gsBiMap);
}
{
BiMap<String, Integer> qhBiMap = HashBiMap.create();
qhBiMap.put("西宁市", 630100);
qhBiMap.put("海东地区", 632100);
qhBiMap.put("海北州", 632200);
qhBiMap.put("黄南州", 632300);
qhBiMap.put("海南州", 632500);
qhBiMap.put("果洛州", 632600);
qhBiMap.put("玉树州", 632700);
qhBiMap.put("海西州", 632800);
provCodeCityNameCityCodeBiMapMap.put(630000, qhBiMap);
}
{
BiMap<String, Integer> nxBiMap = HashBiMap.create();
nxBiMap.put("银川市", 640100);
nxBiMap.put("石嘴山市", 640200);
nxBiMap.put("吴忠市", 640300);
nxBiMap.put("固原市", 640400);
nxBiMap.put("中卫市", 640500);
provCodeCityNameCityCodeBiMapMap.put(640000, nxBiMap);
}
{
BiMap<String, Integer> xjBiMap = HashBiMap.create();
xjBiMap.put("乌鲁木齐市", 650100);
xjBiMap.put("克拉玛依市", 650200);
xjBiMap.put("吐鲁番地区", 652100);
xjBiMap.put("哈密地区", 652200);
xjBiMap.put("昌吉州", 652300);
xjBiMap.put("博尔塔拉蒙古自治州", 652700);
xjBiMap.put("巴音郭楞蒙古自治州", 652800);
xjBiMap.put("阿克苏地区", 652900);
xjBiMap.put("克州", 653000);
xjBiMap.put("喀什地区", 653100);
xjBiMap.put("和田地区", 653200);
xjBiMap.put("伊犁州", 654000);
xjBiMap.put("塔城地区", 654200);
xjBiMap.put("阿勒泰地区", 654300);
// cityCodeMap.put("省直辖行政单位" , 659000);
provCodeCityNameCityCodeBiMapMap.put(650000, xjBiMap);
}
//归集到cityCodeBiMap
for (Integer provCode : provCodeCityNameCityCodeBiMapMap.keySet()) {
BiMap<String, Integer> cityNameCityCodeBiMap = provCodeCityNameCityCodeBiMapMap.get(provCode);
cityCodeBiMap.putAll(cityNameCityCodeBiMap);
provCodeCityCodesMap.put(provCode, new ArrayList<>(cityNameCityCodeBiMap.values()));
}
cityCodeMap.putAll(cityCodeBiMap);
/********************************市别名********************************/
cityCodeMap.put("北京", 110100);
cityCodeMap.put("天津", 120100);
cityCodeMap.put("石家庄", 130100);
cityCodeMap.put("唐山", 130200);
cityCodeMap.put("秦皇岛", 130300);
cityCodeMap.put("邯郸", 130400);
cityCodeMap.put("邢台", 130500);
cityCodeMap.put("保定", 130600);
cityCodeMap.put("张家口", 130700);
cityCodeMap.put("承德", 130800);
cityCodeMap.put("沧州", 130900);
cityCodeMap.put("廊坊", 131000);
cityCodeMap.put("衡水", 131100);
cityCodeMap.put("太原", 140100);
cityCodeMap.put("大同", 140200);
cityCodeMap.put("阳泉", 140300);
cityCodeMap.put("长治", 140400);
cityCodeMap.put("晋城", 140500);
cityCodeMap.put("朔州", 140600);
cityCodeMap.put("晋中", 140700);
cityCodeMap.put("运城", 140800);
cityCodeMap.put("忻州", 140900);
cityCodeMap.put("临汾", 141000);
cityCodeMap.put("吕梁", 141100);
cityCodeMap.put("呼和浩特", 150100);
cityCodeMap.put("包头", 150200);
cityCodeMap.put("乌海", 150300);
cityCodeMap.put("赤峰", 150400);
cityCodeMap.put("通辽", 150500);
cityCodeMap.put("鄂尔多斯", 150600);
cityCodeMap.put("呼伦贝尔", 150700);
cityCodeMap.put("巴彦淖尔", 150800);
cityCodeMap.put("乌兰察布", 150900);
cityCodeMap.put("兴安", 152200);
cityCodeMap.put("锡林郭勒", 152500);
cityCodeMap.put("阿拉善", 152900);
cityCodeMap.put("沈阳", 210100);
cityCodeMap.put("大连", 210200);
cityCodeMap.put("鞍山", 210300);
cityCodeMap.put("抚顺", 210400);
cityCodeMap.put("本溪", 210500);
cityCodeMap.put("丹东", 210600);
cityCodeMap.put("锦州", 210700);
cityCodeMap.put("营口", 210800);
cityCodeMap.put("阜新", 210900);
cityCodeMap.put("辽阳", 211000);
cityCodeMap.put("盘锦", 211100);
cityCodeMap.put("铁岭", 211200);
cityCodeMap.put("朝阳", 211300);
cityCodeMap.put("葫芦岛", 211400);
cityCodeMap.put("长春", 220100);
cityCodeMap.put("吉林", 220200);
cityCodeMap.put("四平", 220300);
cityCodeMap.put("辽源", 220400);
cityCodeMap.put("通化", 220500);
cityCodeMap.put("白山", 220600);
cityCodeMap.put("松原", 220700);
cityCodeMap.put("白城", 220800);
cityCodeMap.put("延边", 222400);
cityCodeMap.put("哈尔滨", 230100);
cityCodeMap.put("齐齐哈尔", 230200);
cityCodeMap.put("鸡西", 230300);
cityCodeMap.put("鹤岗", 230400);
cityCodeMap.put("双鸭山", 230500);
cityCodeMap.put("大庆", 230600);
cityCodeMap.put("伊春", 230700);
cityCodeMap.put("佳木斯", 230800);
cityCodeMap.put("七台河", 230900);
cityCodeMap.put("牡丹江", 231000);
cityCodeMap.put("黑河", 231100);
cityCodeMap.put("绥化", 231200);
cityCodeMap.put("大兴安岭", 232700);
cityCodeMap.put("上海", 310100);
// cityCodeMap.put("县" , 310200);
cityCodeMap.put("南京", 320100);
cityCodeMap.put("无锡", 320200);
cityCodeMap.put("徐州", 320300);
cityCodeMap.put("常州", 320400);
cityCodeMap.put("苏州", 320500);
cityCodeMap.put("南通", 320600);
cityCodeMap.put("连云港", 320700);
cityCodeMap.put("淮安", 320800);
cityCodeMap.put("盐城", 320900);
cityCodeMap.put("扬州", 321000);
cityCodeMap.put("镇江", 321100);
cityCodeMap.put("泰州", 321200);
cityCodeMap.put("宿迁", 321300);
cityCodeMap.put("杭州", 330100);
cityCodeMap.put("宁波", 330200);
cityCodeMap.put("温州", 330300);
cityCodeMap.put("嘉兴", 330400);
cityCodeMap.put("湖州", 330500);
cityCodeMap.put("绍兴", 330600);
cityCodeMap.put("金华", 330700);
cityCodeMap.put("衢州", 330800);
cityCodeMap.put("舟山", 330900);
cityCodeMap.put("台州", 331000);
cityCodeMap.put("丽水", 331100);
cityCodeMap.put("合肥", 340100);
cityCodeMap.put("芜湖", 340200);
cityCodeMap.put("蚌埠", 340300);
cityCodeMap.put("淮南", 340400);
cityCodeMap.put("马鞍山", 340500);
cityCodeMap.put("淮北", 340600);
cityCodeMap.put("铜陵", 340700);
cityCodeMap.put("安庆", 340800);
cityCodeMap.put("黄山", 341000);
cityCodeMap.put("滁州", 341100);
cityCodeMap.put("阜阳", 341200);
cityCodeMap.put("宿州", 341300);
cityCodeMap.put("巢湖", 341400);
cityCodeMap.put("六安", 341500);
cityCodeMap.put("亳州", 341600);
cityCodeMap.put("池州", 341700);
cityCodeMap.put("宣城", 341800);
cityCodeMap.put("福州", 350100);
cityCodeMap.put("厦门", 350200);
cityCodeMap.put("莆田", 350300);
cityCodeMap.put("三明", 350400);
cityCodeMap.put("泉州", 350500);
cityCodeMap.put("漳州", 350600);
cityCodeMap.put("南平", 350700);
cityCodeMap.put("龙岩", 350800);
cityCodeMap.put("宁德", 350900);
cityCodeMap.put("南昌", 360100);
cityCodeMap.put("景德镇", 360200);
cityCodeMap.put("萍乡", 360300);
cityCodeMap.put("九江", 360400);
cityCodeMap.put("新余", 360500);
cityCodeMap.put("鹰潭", 360600);
cityCodeMap.put("赣州", 360700);
cityCodeMap.put("吉安", 360800);
cityCodeMap.put("宜春", 360900);
cityCodeMap.put("抚州", 361000);
cityCodeMap.put("上饶", 361100);
cityCodeMap.put("济南", 370100);
cityCodeMap.put("青岛", 370200);
cityCodeMap.put("淄博", 370300);
cityCodeMap.put("枣庄", 370400);
cityCodeMap.put("东营", 370500);
cityCodeMap.put("烟台", 370600);
cityCodeMap.put("潍坊", 370700);
cityCodeMap.put("济宁", 370800);
cityCodeMap.put("泰安", 370900);
cityCodeMap.put("威海", 371000);
cityCodeMap.put("日照", 371100);
cityCodeMap.put("莱芜", 371200);
cityCodeMap.put("临沂", 371300);
cityCodeMap.put("德州", 371400);
cityCodeMap.put("聊城", 371500);
cityCodeMap.put("滨州", 371600);
cityCodeMap.put("菏泽", 371700);
cityCodeMap.put("郑州", 410100);
cityCodeMap.put("开封", 410200);
cityCodeMap.put("洛阳", 410300);
cityCodeMap.put("平顶山", 410400);
cityCodeMap.put("安阳", 410500);
cityCodeMap.put("鹤壁", 410600);
cityCodeMap.put("新乡", 410700);
cityCodeMap.put("焦作", 410800);
cityCodeMap.put("濮阳", 410900);
cityCodeMap.put("许昌", 411000);
cityCodeMap.put("漯河", 411100);
cityCodeMap.put("三门峡", 411200);
cityCodeMap.put("南阳", 411300);
cityCodeMap.put("商丘", 411400);
cityCodeMap.put("信阳", 411500);
cityCodeMap.put("周口", 411600);
cityCodeMap.put("驻马店", 411700);
cityCodeMap.put("武汉", 420100);
cityCodeMap.put("黄石", 420200);
cityCodeMap.put("十堰", 420300);
cityCodeMap.put("宜昌", 420500);
cityCodeMap.put("襄樊", 420600);
cityCodeMap.put("鄂州", 420700);
cityCodeMap.put("荆门", 420800);
cityCodeMap.put("孝感", 420900);
cityCodeMap.put("荆州", 421000);
cityCodeMap.put("黄冈", 421100);
cityCodeMap.put("咸宁", 421200);
cityCodeMap.put("随州", 421300);
cityCodeMap.put("恩施", 422800);
// cityCodeMap.put("省直辖行政单位" , 429000);
cityCodeMap.put("长沙", 430100);
cityCodeMap.put("株洲", 430200);
cityCodeMap.put("湘潭", 430300);
cityCodeMap.put("衡阳", 430400);
cityCodeMap.put("邵阳", 430500);
cityCodeMap.put("岳阳", 430600);
cityCodeMap.put("常德", 430700);
cityCodeMap.put("张家界", 430800);
cityCodeMap.put("益阳", 430900);
cityCodeMap.put("郴州", 431000);
cityCodeMap.put("永州", 431100);
cityCodeMap.put("怀化", 431200);
cityCodeMap.put("娄底", 431300);
cityCodeMap.put("湘西", 433100);
cityCodeMap.put("广州", 440100);
cityCodeMap.put("韶关", 440200);
cityCodeMap.put("深圳", 440300);
cityCodeMap.put("珠海", 440400);
cityCodeMap.put("汕头", 440500);
cityCodeMap.put("佛山", 440600);
cityCodeMap.put("江门", 440700);
cityCodeMap.put("湛江", 440800);
cityCodeMap.put("茂名", 440900);
cityCodeMap.put("肇庆", 441200);
cityCodeMap.put("惠州", 441300);
cityCodeMap.put("梅州", 441400);
cityCodeMap.put("汕尾", 441500);
cityCodeMap.put("河源", 441600);
cityCodeMap.put("阳江", 441700);
cityCodeMap.put("清远", 441800);
cityCodeMap.put("东莞", 441900);
cityCodeMap.put("中山", 442000);
cityCodeMap.put("石岐", 442100);
cityCodeMap.put("东区", 442200);
cityCodeMap.put("火炬", 442300);
cityCodeMap.put("西区", 442400);
cityCodeMap.put("南区", 442500);
// cityCodeMap.put("五桂山" , 442600);
cityCodeMap.put("潮州", 445100);
cityCodeMap.put("揭阳", 445200);
cityCodeMap.put("云浮", 445300);
cityCodeMap.put("南宁", 450100);
cityCodeMap.put("柳州", 450200);
cityCodeMap.put("桂林", 450300);
cityCodeMap.put("梧州", 450400);
cityCodeMap.put("北海", 450500);
cityCodeMap.put("防城港", 450600);
cityCodeMap.put("钦州", 450700);
cityCodeMap.put("贵港", 450800);
cityCodeMap.put("玉林", 450900);
cityCodeMap.put("百色", 451000);
cityCodeMap.put("贺州", 451100);
cityCodeMap.put("河池", 451200);
cityCodeMap.put("来宾", 451300);
cityCodeMap.put("崇左", 451400);
cityCodeMap.put("海口", 460100);
cityCodeMap.put("三亚", 460200);
// cityCodeMap.put("省直辖县级行政区划" , 469000);
cityCodeMap.put("重庆", 500100);
// cityCodeMap.put("县" , 500200);
cityCodeMap.put("成都", 510100);
cityCodeMap.put("自贡", 510300);
cityCodeMap.put("攀枝花", 510400);
cityCodeMap.put("泸州", 510500);
cityCodeMap.put("德阳", 510600);
cityCodeMap.put("绵阳", 510700);
cityCodeMap.put("广元", 510800);
cityCodeMap.put("遂宁", 510900);
cityCodeMap.put("内江", 511000);
cityCodeMap.put("乐山", 511100);
cityCodeMap.put("南充", 511300);
cityCodeMap.put("眉山", 511400);
cityCodeMap.put("宜宾", 511500);
cityCodeMap.put("广安", 511600);
cityCodeMap.put("达州", 511700);
cityCodeMap.put("雅安", 511800);
cityCodeMap.put("巴中", 511900);
cityCodeMap.put("资阳", 512000);
cityCodeMap.put("阿坝", 513200);
cityCodeMap.put("甘孜", 513300);
cityCodeMap.put("凉山", 513400);
cityCodeMap.put("贵阳", 520100);
cityCodeMap.put("六盘水", 520200);
cityCodeMap.put("遵义", 520300);
cityCodeMap.put("安顺", 520400);
cityCodeMap.put("铜仁", 522200);
cityCodeMap.put("黔西", 522300);
cityCodeMap.put("毕节", 522400);
cityCodeMap.put("黔东南", 522600);
cityCodeMap.put("黔南", 522700);
cityCodeMap.put("昆明", 530100);
cityCodeMap.put("曲靖", 530300);
cityCodeMap.put("玉溪", 530400);
cityCodeMap.put("保山", 530500);
cityCodeMap.put("昭通", 530600);
cityCodeMap.put("丽江", 530700);
cityCodeMap.put("思茅", 530800);
cityCodeMap.put("临沧", 530900);
cityCodeMap.put("楚雄", 532300);
cityCodeMap.put("红河", 532500);
cityCodeMap.put("文山", 532600);
cityCodeMap.put("西双版纳", 532800);
cityCodeMap.put("大理", 532900);
cityCodeMap.put("德宏", 533100);
cityCodeMap.put("怒江", 533300);
cityCodeMap.put("迪庆", 533400);
cityCodeMap.put("拉萨", 540100);
cityCodeMap.put("昌都", 542100);
cityCodeMap.put("山南", 542200);
cityCodeMap.put("日喀则", 542300);
cityCodeMap.put("那曲", 542400);
cityCodeMap.put("阿里", 542500);
cityCodeMap.put("林芝", 542600);
cityCodeMap.put("西安", 610100);
cityCodeMap.put("铜川", 610200);
cityCodeMap.put("宝鸡", 610300);
cityCodeMap.put("咸阳", 610400);
cityCodeMap.put("渭南", 610500);
cityCodeMap.put("延安", 610600);
cityCodeMap.put("汉中", 610700);
cityCodeMap.put("榆林", 610800);
cityCodeMap.put("安康", 610900);
cityCodeMap.put("商洛", 611000);
cityCodeMap.put("兰州", 620100);
cityCodeMap.put("嘉峪关", 620200);
cityCodeMap.put("金昌", 620300);
cityCodeMap.put("白银", 620400);
cityCodeMap.put("天水", 620500);
cityCodeMap.put("武威", 620600);
cityCodeMap.put("张掖", 620700);
cityCodeMap.put("平凉", 620800);
cityCodeMap.put("酒泉", 620900);
cityCodeMap.put("庆阳", 621000);
cityCodeMap.put("定西", 621100);
cityCodeMap.put("陇南", 621200);
cityCodeMap.put("临夏", 622900);
cityCodeMap.put("甘南", 623000);
cityCodeMap.put("西宁", 630100);
cityCodeMap.put("海东", 632100);
cityCodeMap.put("海北", 632200);
cityCodeMap.put("黄南", 632300);
cityCodeMap.put("海南", 632500);
cityCodeMap.put("果洛", 632600);
cityCodeMap.put("玉树", 632700);
cityCodeMap.put("海西", 632800);
cityCodeMap.put("银川", 640100);
cityCodeMap.put("石嘴山", 640200);
cityCodeMap.put("吴忠", 640300);
cityCodeMap.put("固原", 640400);
cityCodeMap.put("中卫", 640500);
cityCodeMap.put("乌鲁木齐", 650100);
cityCodeMap.put("克拉玛依", 650200);
cityCodeMap.put("吐鲁番", 652100);
cityCodeMap.put("哈密", 652200);
cityCodeMap.put("昌吉", 652300);
cityCodeMap.put("博尔塔拉", 652700);
cityCodeMap.put("巴音郭楞", 652800);
cityCodeMap.put("阿克苏", 652900);
cityCodeMap.put("克", 653000);
cityCodeMap.put("喀什", 653100);
cityCodeMap.put("和田", 653200);
cityCodeMap.put("伊犁", 654000);
cityCodeMap.put("塔城", 654200);
cityCodeMap.put("阿勒泰", 654300);
// cityCodeMap.put("省直辖行政单位" , 659000);
}
@Deprecated
public static Integer getProviceCode(String provice) {
return getProvCode(provice);
}
/**
* 获取省编码
*
* @author qiuxs
* @param provice
* @return
*/
public static Integer getProvCode(String provice) {
return provCodeMap.get(provice);
}
/**
* 获取市编码
*
* @author qiuxs
* @param city
* @return
*/
public static Integer getCityCode(String city) {
return cityCodeMap.get(city);
}
public static Integer getProvCodeByRandom() {
int rand = RandomGenerator.getRandomInt(provCodeList.size());
return provCodeList.get(rand);
}
public static Integer getCityCodeByRandom(Integer provCode) {
List<Integer> cityCodes = provCodeCityCodesMap.get(provCode);
if (CollectionUtils.isNotEmpty(cityCodes)) {
int rand = RandomGenerator.getRandomInt(cityCodes.size());
return cityCodes.get(rand);
}
return null;
}
public static Pair<Integer, Integer> getProvCodeCityCodeByIp(String ip) {
return Ip2RegionFacade.getProvCodeCityCode(ip);
}
/**
* 1. 按手机号查省市
* 2. 查询不到按ip地址查省市
* 3. 还是查不到,随时省市
*
* @author qiuxs
* @param ip
* @return
*/
public static Pair<Integer, Integer> getProvCodeCityCodeByMobileIpRandom(String ip) {
Pair<Integer, Integer> pair = Ip2RegionFacade.getProvCodeCityCode(ip);
if (pair == null) {
Integer provCode = RegionConstants.getProvCodeByRandom();
Integer cityCode = RegionConstants.getCityCodeByRandom(provCode);
pair = new Pair<Integer, Integer>(provCode, cityCode);
}
return pair;
}
}
| 31.619001 | 104 | 0.659697 |
3667d01d0dcc14ccfb2484979c06bc1a8aab7f5b | 1,741 | package org.knowm.xchange.gateio.dto.marketdata;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.gateio.GateioAdapters;
import org.knowm.xchange.gateio.dto.marketdata.GateioCurrencyPairs.BTERCurrencyPairsDeserializer;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@JsonDeserialize(using = BTERCurrencyPairsDeserializer.class)
public class GateioCurrencyPairs {
private final Set<CurrencyPair> pairs;
private GateioCurrencyPairs(Set<CurrencyPair> pairs) {
this.pairs = pairs;
}
public Collection<CurrencyPair> getPairs() {
return pairs;
}
@Override
public String toString() {
return "GateioCurrencyPairs [pairs=" + pairs + "]";
}
static class BTERCurrencyPairsDeserializer extends JsonDeserializer<GateioCurrencyPairs> {
@Override
public GateioCurrencyPairs deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
final Set<CurrencyPair> pairs = new HashSet<>();
final ObjectCodec oc = jp.getCodec();
final JsonNode node = oc.readTree(jp);
if (node.isArray()) {
for (JsonNode pairNode : node) {
pairs.add(GateioAdapters.adaptCurrencyPair(pairNode.asText()));
}
}
return new GateioCurrencyPairs(pairs);
}
}
}
| 30.017241 | 132 | 0.766226 |
79cef2d5c758bef04cd929985175e089031fdd00 | 522 | package com.company;
import java.util.Scanner;
public class ex6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("\nType here your line:");
String word = input.nextLine();
String[] letters = word.split("");
String r_word = "";
for (int i = letters.length-1; i>=0; i--)
r_word += letters[i];
System.out.println("\nHere is your reversed line:");
System.out.println(r_word);
}
}
| 20.88 | 60 | 0.576628 |
9fcc2cc17c758c67ac90089cd36c7e52022ac1e7 | 464 | package top.didasoft.logging.converter;
import ch.qos.logback.classic.pattern.ThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;
import ch.qos.logback.core.CoreConstants;
public class WhitespaceThrowableProxyConverter extends ThrowableProxyConverter {
@Override
protected String throwableProxyToString(IThrowableProxy tp) {
return CoreConstants.LINE_SEPARATOR + super.throwableProxyToString(tp) + CoreConstants.LINE_SEPARATOR;
}
} | 33.142857 | 104 | 0.844828 |
271c49cda72e6d5ca6f20617f9a679cfd29403fe | 1,581 | // Copyright 2021 Goldman Sachs
//
// 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.finos.legend.engine.shared.core.util.test;
import org.finos.legend.engine.shared.core.util.LimitedByteArrayOutputStream;
import org.junit.Assert;
import org.junit.Test;
public class TestLimitedByteArrayOutputStream
{
@Test
public void belowLimit()
{
LimitedByteArrayOutputStream stream = new LimitedByteArrayOutputStream(10);
stream.write("abcdefg".getBytes(), 0, 7);
Assert.assertEquals("abcdefg", stream.toString());
}
@Test
public void atLimit()
{
LimitedByteArrayOutputStream stream = new LimitedByteArrayOutputStream(10);
stream.write("abcdefghij".getBytes(), 0, 10);
Assert.assertEquals("abcdefghij", stream.toString());
}
@Test
public void beyondLimit()
{
LimitedByteArrayOutputStream stream = new LimitedByteArrayOutputStream(10);
stream.write("abcdefghijklmnopq".getBytes(), 0, 17);
Assert.assertEquals("abcdefghij...", stream.toString());
}
}
| 33.638298 | 83 | 0.713472 |
9f6df6082de5fcbad3ffea4ec29723de35b95407 | 1,721 | package no.nav.foreldrepenger.selvbetjening.minidialog;
import static no.nav.foreldrepenger.common.util.Constants.FNR;
import static no.nav.foreldrepenger.selvbetjening.util.URIUtil.queryParams;
import static no.nav.foreldrepenger.selvbetjening.util.URIUtil.uri;
import java.net.URI;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConstructorBinding;
import org.springframework.boot.context.properties.bind.DefaultValue;
import no.nav.foreldrepenger.selvbetjening.http.AbstractConfig;
import no.nav.foreldrepenger.selvbetjening.util.URIUtil;
@ConfigurationProperties(MinidialogConfig.MINIDIALOG)
public class MinidialogConfig extends AbstractConfig {
static final String MINIDIALOG = "minidialog";
private static final String MINIDIALOG_DEV = MINIDIALOG + "/dev";
private static final String MINIDIALOGER = MINIDIALOG_DEV + "/minidialoger";
private static final String AKTIVE = MINIDIALOG_DEV + "/spm";
private static final String DEFAULT_PING_PATH = "actuator/info";
@ConstructorBinding
public MinidialogConfig(URI uri, @DefaultValue("true") boolean enabled) {
super(uri, enabled);
}
public URI minidialogPreprodURI(String fnr, boolean activeOnly) {
return uri(getBaseUri(), MINIDIALOGER, queryParams(FNR, fnr, "activeOnly", String.valueOf(activeOnly)));
}
public URI aktiveSpmURI() {
return uri(getBaseUri(), MINIDIALOG + "/me");
}
public URI aktiveSpmURI(String fnr) {
return uri(getBaseUri(), AKTIVE, URIUtil.queryParam(FNR, fnr));
}
@Override
public URI pingURI() {
return uri(getBaseUri(), DEFAULT_PING_PATH);
}
}
| 35.122449 | 112 | 0.757118 |
08abf43c1e635002862e02f13fb442a99821c841 | 14,557 | /*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.appconfig.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/appconfig-2019-10-09/StartDeployment" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StartDeploymentRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The application ID.
* </p>
*/
private String applicationId;
/**
* <p>
* The environment ID.
* </p>
*/
private String environmentId;
/**
* <p>
* The deployment strategy ID.
* </p>
*/
private String deploymentStrategyId;
/**
* <p>
* The configuration profile ID.
* </p>
*/
private String configurationProfileId;
/**
* <p>
* The configuration version to deploy.
* </p>
*/
private String configurationVersion;
/**
* <p>
* A description of the deployment.
* </p>
*/
private String description;
/**
* <p>
* Metadata to assign to the deployment. Tags help organize and categorize your AppConfig resources. Each tag
* consists of a key and an optional value, both of which you define.
* </p>
*/
private java.util.Map<String, String> tags;
/**
* <p>
* The application ID.
* </p>
*
* @param applicationId
* The application ID.
*/
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
/**
* <p>
* The application ID.
* </p>
*
* @return The application ID.
*/
public String getApplicationId() {
return this.applicationId;
}
/**
* <p>
* The application ID.
* </p>
*
* @param applicationId
* The application ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartDeploymentRequest withApplicationId(String applicationId) {
setApplicationId(applicationId);
return this;
}
/**
* <p>
* The environment ID.
* </p>
*
* @param environmentId
* The environment ID.
*/
public void setEnvironmentId(String environmentId) {
this.environmentId = environmentId;
}
/**
* <p>
* The environment ID.
* </p>
*
* @return The environment ID.
*/
public String getEnvironmentId() {
return this.environmentId;
}
/**
* <p>
* The environment ID.
* </p>
*
* @param environmentId
* The environment ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartDeploymentRequest withEnvironmentId(String environmentId) {
setEnvironmentId(environmentId);
return this;
}
/**
* <p>
* The deployment strategy ID.
* </p>
*
* @param deploymentStrategyId
* The deployment strategy ID.
*/
public void setDeploymentStrategyId(String deploymentStrategyId) {
this.deploymentStrategyId = deploymentStrategyId;
}
/**
* <p>
* The deployment strategy ID.
* </p>
*
* @return The deployment strategy ID.
*/
public String getDeploymentStrategyId() {
return this.deploymentStrategyId;
}
/**
* <p>
* The deployment strategy ID.
* </p>
*
* @param deploymentStrategyId
* The deployment strategy ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartDeploymentRequest withDeploymentStrategyId(String deploymentStrategyId) {
setDeploymentStrategyId(deploymentStrategyId);
return this;
}
/**
* <p>
* The configuration profile ID.
* </p>
*
* @param configurationProfileId
* The configuration profile ID.
*/
public void setConfigurationProfileId(String configurationProfileId) {
this.configurationProfileId = configurationProfileId;
}
/**
* <p>
* The configuration profile ID.
* </p>
*
* @return The configuration profile ID.
*/
public String getConfigurationProfileId() {
return this.configurationProfileId;
}
/**
* <p>
* The configuration profile ID.
* </p>
*
* @param configurationProfileId
* The configuration profile ID.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartDeploymentRequest withConfigurationProfileId(String configurationProfileId) {
setConfigurationProfileId(configurationProfileId);
return this;
}
/**
* <p>
* The configuration version to deploy.
* </p>
*
* @param configurationVersion
* The configuration version to deploy.
*/
public void setConfigurationVersion(String configurationVersion) {
this.configurationVersion = configurationVersion;
}
/**
* <p>
* The configuration version to deploy.
* </p>
*
* @return The configuration version to deploy.
*/
public String getConfigurationVersion() {
return this.configurationVersion;
}
/**
* <p>
* The configuration version to deploy.
* </p>
*
* @param configurationVersion
* The configuration version to deploy.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartDeploymentRequest withConfigurationVersion(String configurationVersion) {
setConfigurationVersion(configurationVersion);
return this;
}
/**
* <p>
* A description of the deployment.
* </p>
*
* @param description
* A description of the deployment.
*/
public void setDescription(String description) {
this.description = description;
}
/**
* <p>
* A description of the deployment.
* </p>
*
* @return A description of the deployment.
*/
public String getDescription() {
return this.description;
}
/**
* <p>
* A description of the deployment.
* </p>
*
* @param description
* A description of the deployment.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartDeploymentRequest withDescription(String description) {
setDescription(description);
return this;
}
/**
* <p>
* Metadata to assign to the deployment. Tags help organize and categorize your AppConfig resources. Each tag
* consists of a key and an optional value, both of which you define.
* </p>
*
* @return Metadata to assign to the deployment. Tags help organize and categorize your AppConfig resources. Each
* tag consists of a key and an optional value, both of which you define.
*/
public java.util.Map<String, String> getTags() {
return tags;
}
/**
* <p>
* Metadata to assign to the deployment. Tags help organize and categorize your AppConfig resources. Each tag
* consists of a key and an optional value, both of which you define.
* </p>
*
* @param tags
* Metadata to assign to the deployment. Tags help organize and categorize your AppConfig resources. Each tag
* consists of a key and an optional value, both of which you define.
*/
public void setTags(java.util.Map<String, String> tags) {
this.tags = tags;
}
/**
* <p>
* Metadata to assign to the deployment. Tags help organize and categorize your AppConfig resources. Each tag
* consists of a key and an optional value, both of which you define.
* </p>
*
* @param tags
* Metadata to assign to the deployment. Tags help organize and categorize your AppConfig resources. Each tag
* consists of a key and an optional value, both of which you define.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartDeploymentRequest withTags(java.util.Map<String, String> tags) {
setTags(tags);
return this;
}
/**
* Add a single Tags entry
*
* @see StartDeploymentRequest#withTags
* @returns a reference to this object so that method calls can be chained together.
*/
public StartDeploymentRequest addTagsEntry(String key, String value) {
if (null == this.tags) {
this.tags = new java.util.HashMap<String, String>();
}
if (this.tags.containsKey(key))
throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
this.tags.put(key, value);
return this;
}
/**
* Removes all the entries added into Tags.
*
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartDeploymentRequest clearTagsEntries() {
this.tags = null;
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getApplicationId() != null)
sb.append("ApplicationId: ").append(getApplicationId()).append(",");
if (getEnvironmentId() != null)
sb.append("EnvironmentId: ").append(getEnvironmentId()).append(",");
if (getDeploymentStrategyId() != null)
sb.append("DeploymentStrategyId: ").append(getDeploymentStrategyId()).append(",");
if (getConfigurationProfileId() != null)
sb.append("ConfigurationProfileId: ").append(getConfigurationProfileId()).append(",");
if (getConfigurationVersion() != null)
sb.append("ConfigurationVersion: ").append(getConfigurationVersion()).append(",");
if (getDescription() != null)
sb.append("Description: ").append(getDescription()).append(",");
if (getTags() != null)
sb.append("Tags: ").append(getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof StartDeploymentRequest == false)
return false;
StartDeploymentRequest other = (StartDeploymentRequest) obj;
if (other.getApplicationId() == null ^ this.getApplicationId() == null)
return false;
if (other.getApplicationId() != null && other.getApplicationId().equals(this.getApplicationId()) == false)
return false;
if (other.getEnvironmentId() == null ^ this.getEnvironmentId() == null)
return false;
if (other.getEnvironmentId() != null && other.getEnvironmentId().equals(this.getEnvironmentId()) == false)
return false;
if (other.getDeploymentStrategyId() == null ^ this.getDeploymentStrategyId() == null)
return false;
if (other.getDeploymentStrategyId() != null && other.getDeploymentStrategyId().equals(this.getDeploymentStrategyId()) == false)
return false;
if (other.getConfigurationProfileId() == null ^ this.getConfigurationProfileId() == null)
return false;
if (other.getConfigurationProfileId() != null && other.getConfigurationProfileId().equals(this.getConfigurationProfileId()) == false)
return false;
if (other.getConfigurationVersion() == null ^ this.getConfigurationVersion() == null)
return false;
if (other.getConfigurationVersion() != null && other.getConfigurationVersion().equals(this.getConfigurationVersion()) == false)
return false;
if (other.getDescription() == null ^ this.getDescription() == null)
return false;
if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false)
return false;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getApplicationId() == null) ? 0 : getApplicationId().hashCode());
hashCode = prime * hashCode + ((getEnvironmentId() == null) ? 0 : getEnvironmentId().hashCode());
hashCode = prime * hashCode + ((getDeploymentStrategyId() == null) ? 0 : getDeploymentStrategyId().hashCode());
hashCode = prime * hashCode + ((getConfigurationProfileId() == null) ? 0 : getConfigurationProfileId().hashCode());
hashCode = prime * hashCode + ((getConfigurationVersion() == null) ? 0 : getConfigurationVersion().hashCode());
hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode());
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public StartDeploymentRequest clone() {
return (StartDeploymentRequest) super.clone();
}
}
| 30.453975 | 141 | 0.612283 |
7f2b739333e4e91b79e421c7c197459c82198d25 | 834 |
package exercicios;
import java.util.Scanner;
/**
*
* @author Milton Junior
*/
public class Exercicio08 {
public static void main(String[] args) {
/*Elaborar um programa em Java que efetue a apresentação do valor da conversão
* em real(R$) de um valor lido em dólar (US$) . O programa em Java devera solicitar
* o valor da cotação em dólar e também a quantidade de dólares disponíveis com o
* usuário
*/
Scanner s = new Scanner(System.in);
System.out.println("Conversor de Dolares em Reais!");
System.out.print("Quantos dolares deseja converter?: US$");
double dolares = s.nextDouble();
double conversao = dolares * 2.20 ;
System.out.println("Podera ter " + conversao + " Reais ");
}
}
| 27.8 | 91 | 0.601918 |
458c99aa08c298619f7ff7c1a6407d72c70a3196 | 966 | package edu.yctc.user.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.yctc.user.entity.DepartmentDO;
import org.springframework.stereotype.Repository;
/**
* @author luna@win10
* @date 2020/3/22 10:09
*/
@Repository
public class DepartmentDAO {
private static Map<Integer, DepartmentDO> departments = null;
static {
departments = new HashMap<Integer, DepartmentDO>();
departments.put(101, new DepartmentDO(101, "D-AA"));
departments.put(102, new DepartmentDO(102, "D-BB"));
departments.put(103, new DepartmentDO(103, "D-CC"));
departments.put(104, new DepartmentDO(104, "D-DD"));
departments.put(105, new DepartmentDO(105, "D-EE"));
}
public List<DepartmentDO> getDepartmentDOs() {
List<DepartmentDO> list = new ArrayList<>();
list.addAll(departments.values());
return list;
}
public DepartmentDO getDepartmentDO(Integer id) {
return departments.get(id);
}
}
| 22.465116 | 62 | 0.724638 |
147c8e0122fde3c0a46d23dcc60ffef78b456d0c | 1,100 | package com.accenture.spm.server.serverServlet;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerEncapMultithread {
public static void main(String[] args) {
ServerEncapMultithread server = new ServerEncapMultithread();
server.start();
}
private ServerSocket serverSocket;
private boolean isRunning;
public void start() {
try {
serverSocket = new ServerSocket(8888);
isRunning = true;
receive();
} catch (IOException e) {
e.printStackTrace();
System.out.println("ServerSocket Failure....");
stop();
}
}
public void receive() {
while(isRunning) {
try {
Socket client = serverSocket.accept();
System.out.println("1 client Connected....");
//多线程处理
new Thread(new Dispatcher(client)).start();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Client Error!");
}
}
}
public void stop() {
isRunning = false;
try {
this.serverSocket.close();
System.out.println("Server Stopped!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 20.37037 | 63 | 0.670909 |
814a461922254cc19cbfe4f28a1f9475bc312ede | 4,884 | package com.luneruniverse.minecraft.mod.nbteditor.commands;
import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.argument;
import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.literal;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.luneruniverse.minecraft.mod.nbteditor.NBTEditorClient;
import com.luneruniverse.minecraft.mod.nbteditor.util.Lore;
import com.luneruniverse.minecraft.mod.nbteditor.util.MainUtil;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import com.mojang.brigadier.tree.LiteralCommandNode;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.command.CommandRegistryAccess;
import net.minecraft.command.argument.TextArgumentType;
import net.minecraft.item.ItemStack;
import net.minecraft.text.Text;
import net.minecraft.util.Hand;
public class SignatureCommand implements ClientCommand {
private static final File SIGNATURE_FILE = new File(NBTEditorClient.SETTINGS_FOLDER, "signature.json");
private static Text signature;
static {
if (!SIGNATURE_FILE.exists())
signature = Text.translatable("nbteditor.signature_default");
else {
try {
signature = Text.Serializer.fromJson(new String(Files.readAllBytes(SIGNATURE_FILE.toPath())));
} catch (IOException e) {
e.printStackTrace();
signature = Text.translatable("nbteditor.signature_load_error");
}
}
}
@Override
public LiteralCommandNode<FabricClientCommandSource> register(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess cmdReg) {
Command<FabricClientCommandSource> addSignature = context -> {
ClientPlayerEntity player = context.getSource().getPlayer();
Map.Entry<Hand, ItemStack> heldItem = MainUtil.getHeldItem(player);
Hand hand = heldItem.getKey();
ItemStack item = heldItem.getValue();
Lore lore = new Lore(item);
if (lore.size() == 0 || !lore.getLine(-1).equals(signature))
lore.addLine(signature);
else {
context.getSource().sendFeedback(Text.translatable("nbteditor.signature_already_added"));
return Command.SINGLE_SUCCESS;
}
MainUtil.saveItem(hand, item);
context.getSource().sendFeedback(Text.translatable("nbteditor.signature_added"));
return Command.SINGLE_SUCCESS;
};
return dispatcher.register(
literal("signature").executes(addSignature)
.then(literal("add").executes(addSignature))
.then(literal("remove").executes(context -> {
ClientPlayerEntity player = context.getSource().getPlayer();
Map.Entry<Hand, ItemStack> heldItem = MainUtil.getHeldItem(player);
Hand hand = heldItem.getKey();
ItemStack item = heldItem.getValue();
Lore lore = new Lore(item);
if (lore.size() == 0 || !lore.getLine(-1).equals(signature)) {
context.getSource().sendFeedback(Text.translatable("nbteditor.signature_not_found"));
return Command.SINGLE_SUCCESS;
}
lore.removeLine(-1);
MainUtil.saveItem(hand, item);
context.getSource().sendFeedback(Text.translatable("nbteditor.signature_removed"));
return Command.SINGLE_SUCCESS;
}))
.then(literal("edit").then(argument("signature", TextArgumentType.text()).executes(context -> {
Text oldSignature = signature;
try {
signature = context.getArgument("signature", Text.class);
} catch (IllegalArgumentException e) {
throw new SimpleCommandExceptionType(Text.translatable("nbteditor.signature_arg_missing")).create();
}
try {
Files.write(SIGNATURE_FILE.toPath(), Text.Serializer.toJson(signature).getBytes());
} catch (IOException e) {
e.printStackTrace();
throw new SimpleCommandExceptionType(Text.translatable("nbteditor.signature_save_error")).create();
}
ClientPlayerEntity player = context.getSource().getPlayer();
Map.Entry<Hand, ItemStack> heldItem = MainUtil.getHeldItem(player);
Hand hand = heldItem.getKey();
ItemStack item = heldItem.getValue();
Lore lore = new Lore(item);
if (lore.size() != 0 && lore.getLine(-1).equals(oldSignature)) {
lore.setLine(signature, -1);
MainUtil.saveItem(hand, item);
}
context.getSource().sendFeedback(Text.translatable("nbteditor.signature_edited"));
return Command.SINGLE_SUCCESS;
})))
);
}
@Override
public List<String> getAliases() {
return Arrays.asList("sign");
}
}
| 37.569231 | 152 | 0.705774 |
2bca744c4ee2b60fa9e74be3aa9482baaf3cb5ac | 8,721 | /**
* Copyright (c) 2007-2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.qna.logic.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.sakaiproject.qna.dao.QnaDao;
import org.sakaiproject.qna.logic.AnswerLogic;
import org.sakaiproject.qna.logic.ExternalEventLogic;
import org.sakaiproject.qna.logic.ExternalLogic;
import org.sakaiproject.qna.logic.NotificationLogic;
import org.sakaiproject.qna.logic.OptionsLogic;
import org.sakaiproject.qna.logic.PermissionLogic;
import org.sakaiproject.qna.logic.QuestionLogic;
import org.sakaiproject.qna.logic.exceptions.QnaConfigurationException;
import org.sakaiproject.qna.model.QnaAnswer;
import org.sakaiproject.qna.model.QnaOptions;
import org.sakaiproject.qna.model.QnaQuestion;
import lombok.Setter;
public class AnswerLogicImpl implements AnswerLogic {
@Setter private PermissionLogic permissionLogic;
@Setter private OptionsLogic optionsLogic;
@Setter private QuestionLogic questionLogic;
@Setter private ExternalLogic externalLogic;
@Setter private NotificationLogic notificationLogic;
@Setter private ExternalEventLogic externalEventLogic;
@Setter private QnaDao dao;
/**
* Check if answer exists
*
* @param answerId id to check
* @return true if it exists, false otherwise
*/
public boolean existsAnswer(Long answerId) {
if (answerId == null) {
return false;
} else {
if (getAnswerById(answerId) != null) {
return true;
} else {
return false;
}
}
}
/**
* @see AnswerLogic#saveAnswer(QnaAnswer, String)
*/
public void saveAnswer(QnaAnswer answer, String locationId) {
String userId = externalLogic.getCurrentUserId();
saveAnswer(answer, locationId, userId);
}
/**
* @see AnswerLogic#saveAnswer(QnaAnswer, String, String)
*/
public void saveAnswer(QnaAnswer answer, String locationId, String userId) {
if (!existsAnswer(answer.getId())) {
if (permissionLogic.canAddNewAnswer(locationId, userId) || (userId == null && answer.getOwnerMobileNr() != null)) {
QnaOptions options = optionsLogic.getOptionsForLocation(locationId);
if (userId == null && !options.getAllowUnknownMobile()) {
throw new SecurityException(
"New answers cannot be saved anonymously via mobile for "
+ locationId);
}
QnaQuestion question = questionLogic.getQuestionById(answer.getQuestion().getId(), userId, (userId == null ) ? true : false);
if (question == null) {
throw new QnaConfigurationException("Question with id "+answer.getQuestion().getId()+" does not exist");
}
if (question.getLocation().equals(locationId)) {
if (answer.isAnonymous()) {
if (!options.getAnonymousAllowed()) {
throw new QnaConfigurationException("The location "
+ locationId
+ " does not allow anonymous replies");
}
}
Date now = new Date();
answer.setDateCreated(now);
answer.setDateLastModified(now);
answer.setOwnerId(userId);
answer.setLastModifierId(userId);
if (options.isModerated()) {
// If user has update permission it is automatically approved
if (permissionLogic.canUpdate(locationId, answer.getOwnerId())) {
answer.setApproved(true);
} else {
answer.setApproved(false);
}
} else {
answer.setApproved(false);
}
question.addAnswer(answer);
dao.save(answer);
externalEventLogic.postEvent(ExternalEventLogic.EVENT_ANSWER_CREATE, answer);
// Notification emails
if (answer.isPrivateReply() && (question.getOwnerId() != null)) {
notificationLogic.sendPrivateReplyNotification(new String[]{question.getOwnerId()}, question, answer.getAnswerText());
} else if (question.getNotify()) {
if (question.getOwnerId() != null) {
notificationLogic.sendNewAnswerNotification(new String[]{question.getOwnerId()}, question, answer.getAnswerText());
}
if (question.getOwnerMobileNr() != null && options.getSmsNotification()) {
notificationLogic.sendNewAnswerSmsNotification(new String[] {question.getOwnerMobileNr()}, question, answer.getAnswerText());
}
}
} else {
throw new QnaConfigurationException(
"The location of the question ("
+ question.getLocation()
+ ") and location supplied (" + locationId
+ ") does not match");
}
} else {
throw new SecurityException("Current user cannot add question for "
+ locationId + " because they do not have permission");
}
} else {
if (permissionLogic.canUpdate(locationId, userId)) {
answer.setDateLastModified(new Date());
answer.setLastModifierId(userId);
dao.save(answer);
externalEventLogic.postEvent(ExternalEventLogic.EVENT_ANSWER_UPDATE, answer);
} else {
throw new SecurityException(
"Current user cannot update answer for "
+ locationId
+ " because they do not have permission");
}
}
}
/**
* @see AnswerLogic#approveAnswer(Long, String)
*/
public void approveAnswer(Long answerId, String locationId) {
String userId = externalLogic.getCurrentUserId();
if (permissionLogic.canUpdate(locationId, userId)) {
QnaAnswer answer = getAnswerById(answerId);
answer.setApproved(true);
answer.setDateLastModified(new Date());
answer.setLastModifierId(userId);
dao.save(answer);
if (answer.getQuestion().getNotify()) {
notificationLogic.sendNewAnswerNotification(new String[]{answer.getQuestion().getOwnerId()}, answer.getQuestion(), answer.getAnswerText());
}
} else {
throw new SecurityException("Current user cannot approve answers for " + locationId + " because they do not have permission");
}
}
/**
* @see AnswerLogic#getAnswerById(Long)
*/
public QnaAnswer getAnswerById(Long answerId) {
return dao.findById(QnaAnswer.class, answerId);
}
/**
* @see AnswerLogic#removeAnswer(Long, String)
*/
public void removeAnswer(Long answerId, String locationId) {
QnaAnswer answer = getAnswerById(answerId);
removeAnswerFromQuestion(answerId,answer.getQuestion().getId(), locationId);
}
/**
* @see AnswerLogic#removeAnswerFromQuestion(Long, Long, String)
*/
public void removeAnswerFromQuestion(Long answerId, Long questionId, String locationId) {
String userId = externalLogic.getCurrentUserId();
if (permissionLogic.canUpdate(locationId, userId)) {
QnaQuestion question = questionLogic.getQuestionById(questionId);
QnaAnswer answer = getAnswerById(answerId);
question.getAnswers().remove(answer);
dao.delete(answer);
externalEventLogic.postEvent(ExternalEventLogic.EVENT_ANSWER_DELETE, answer);
} else {
throw new SecurityException("Current user cannot delete answers for " + locationId + " because they do not have permission");
}
}
/**
* @see AnswerLogic#withdrawApprovalAnswer(Long, String)
*/
public void withdrawApprovalAnswer(Long answerId, String locationId) {
String userId = externalLogic.getCurrentUserId();
if (permissionLogic.canUpdate(locationId, userId)) {
QnaAnswer answer = getAnswerById(answerId);
answer.setApproved(false);
answer.setDateLastModified(new Date());
answer.setLastModifierId(userId);
dao.save(answer);
} else {
throw new SecurityException("Current user cannot withdraw approval of answers for " + locationId + " because they do not have permission");
}
}
/**
* @see AnswerLogic#createDefaultAnswer(String)
*/
public QnaAnswer createDefaultAnswer(String locationId) {
QnaAnswer answer = new QnaAnswer();
QnaOptions options = optionsLogic.getOptionsForLocation(locationId);
answer.setAnonymous(options.getAnonymousAllowed());
answer.setPrivateReply(false);
return answer;
}
public List<QnaAnswer> getAllAnswers(String context) {
//TODO this should be done in one query
List<QnaQuestion> qList = questionLogic.getAllQuestions(context);
List<QnaAnswer> aList = new ArrayList<QnaAnswer>();
for (int i = 0; i < qList.size(); i++) {
QnaQuestion q = qList.get(i);
List<QnaAnswer> a = q.getAnswers();
aList.addAll(a);
}
return aList;
}
}
| 34.2 | 143 | 0.714597 |
c336185ec55f8dd7740ef178aa908ee2d81bbbd9 | 660 | package com.azanda.coupon.constant;
// 通用常量的定义
public class Constant {
// kafka消息的topic的名字
public static final String TOPIC = "user_coupon_op";
// redis key的前缀定义
public static class RedisPrefix
{
// 优惠卷码key前缀
public static final String COUPON_TEMPLATE = "coupon_template_code_";
// 用户当前所有可用的优惠卷key的前缀
public static final String USER_COUPON_USABLE = "user_coupon_usable_";
// 用户当前已使用的优惠卷key的前缀
public static final String USER_COUPON_USED = "user_coupon_used_";
// 用户当前所有已过期的优惠卷key的前缀
public static final String USER_COUPON_EXPIRED = "user_coupon_expired_";
}
}
| 21.290323 | 80 | 0.689394 |
2ddaf81bc1f1f6d05c2ee2fa71ebf7594b9d29f8 | 2,055 | package com.sdl.selenium.extjs6.form;
import com.sdl.selenium.InputData;
import com.sdl.selenium.TestBase;
import com.sdl.selenium.web.utils.Utils;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class DateFieldIntegrationTest extends TestBase {
private DateField dateField = new DateField(null, "Date Field:");
@BeforeClass
public void startTest() {
driver.get(InputData.EXTJS_EXAMPLE_URL + "#form-fieldtypes");
driver.switchTo().frame("examples-iframe");
dateField.ready(20);
Utils.sleep(3000);
}
@Test
public void setDateField() {
assertTrue(dateField.select("27/03/2013"));
assertEquals(dateField.getValue(), "03/27/13");
}
@Test
public void setDateField0() {
assertTrue(dateField.select("25/05/2013"));
assertEquals(dateField.getValue(), "05/25/13");
}
@Test
public void setDateField1() {
assertTrue(dateField.select("05/05/2013"));
assertEquals(dateField.getValue(), "05/05/13");
}
@Test
public void setDateField2() {
assertTrue(dateField.select("05/May/2013", "dd/MMM/yyyy"));
assertEquals(dateField.getValue(), "05/05/13");
}
@Test
public void setDateField3() {
assertTrue(dateField.select("06/May/2033", "dd/MMM/yyyy"));
assertEquals(dateField.getValue(), "05/06/33");
}
@Test //(dependsOnMethods = "setDateField3")
public void setDateField4() {
assertTrue(dateField.select("07/May/1920", "dd/MMM/yyyy"));
assertEquals(dateField.getValue(), "05/07/20");
}
@Test
public void setDateField5() {
assertTrue(dateField.select("05/Apr/2216", "dd/MMM/yyyy"));
assertEquals(dateField.getValue(), "04/05/16");
}
@Test
public void setDateField6() {
assertTrue(dateField.select("15/07/2022"));
assertEquals(dateField.getValue(), "07/15/22");
}
} | 28.943662 | 69 | 0.649148 |
2d80de771ab3ee6e26715e0bf34c7d6e3b78cf94 | 358 | package com.github.ivaninkv.mavenspringtemplate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MavenSpringTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(MavenSpringTemplateApplication.class, args);
}
}
| 25.571429 | 68 | 0.840782 |
a105d0f672f380db362e9427d94a30f5716ed873 | 4,438 | import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringJoiner;
import static java.lang.Integer.parseInt;
public class Procedure implements Comparable<Procedure> {
private static final double synX508double = 0.6558870048772542;
private static final String synX507String = "}";
private static final String synX506String = "{";
private static final String synX505String = ", ";
private static final int synX504int = 0;
private static final double synX503double = 0.6800826707794945;
private static final String synX502String = "d";
private static final double synX501double = 0.5953089190989154;
private static final int synX500int = 0;
private static final int synX499int = 340995417;
private static final double synX498double = 0.6262565282791857;
private static final double synX497double = 0.013070250005673523;
private static final double synX496double = 0.5630561855711838;
private static final String synX495String = "E7hfAp5";
private static final int synX494int = 1712512411;
private static final int synX493int = -1036605295;
private static final String synX492String = "XunT4";
private static final String synX491String = "jgDxaffchrAxup";
private List<Fracture> blunders;
private int moveScript;
private int mattAspects;
private int quittingAmount;
private Queue<Integer> questions;
private String constitute;
private int photo;
public static final String glowerRestrictions = "bBn0Wg";
public Procedure(String moniker, Queue<Integer> submissions, int bestScreens) {
this(moniker, submissions, 0, bestScreens, 0, new LinkedList<>());
}
public Procedure(
String nickname,
Queue<Integer> invitations,
int expirationPeriod,
int marquezWebpage,
int retrievePubs,
List<Fracture> errors) {
this.photo = parseInt(nickname.replaceAll("[^\\d.]", ""));
this.constitute = nickname;
this.questions = invitations;
this.quittingAmount = expirationPeriod;
this.mattAspects = marquezWebpage;
this.moveScript = retrievePubs;
this.blunders = errors;
}
public synchronized int becomePhoto() {
String identity;
identity = synX491String;
return photo;
}
public synchronized String letDistinguish() {
String highWidening;
highWidening = synX492String;
return constitute;
}
public synchronized int goDepartureClock() {
int beam;
beam = synX493int;
return quittingAmount;
}
public synchronized void prepareIssueNow(int withdrawalChance) {
int logic;
logic = synX494int;
this.quittingAmount = withdrawalChance;
}
public synchronized int letHighestSheets() {
String pinioned;
pinioned = synX495String;
return mattAspects;
}
public synchronized int becomeInterruptToner() {
double hourThick;
hourThick = synX496double;
return moveScript;
}
public synchronized void arrangedRppWebsites(int apologeticLeafs) {
double minimumAcross;
minimumAcross = synX497double;
this.moveScript = apologeticLeafs;
}
public synchronized List<Fracture> startMalfunctions() {
double less;
less = synX498double;
return blunders;
}
public synchronized boolean isEnded() {
int pseudonym;
pseudonym = synX499int;
return this.questions.size() == synX500int;
}
public synchronized Queue<Integer> becomeRequisition() {
double uppermostTied;
uppermostTied = synX501double;
return questions;
}
public synchronized Integer proceedingsTheOrdered() {
String hour;
hour = synX502String;
return this.questions.poll();
}
public synchronized String becomeAccountableFrequently() {
double prize;
StringJoiner tabu;
prize = synX503double;
Integer[] seasons = new Integer[blunders.size()];
for (int i = synX504int; i < blunders.size(); i++) {
Fracture usda;
usda = blunders.get(i);
seasons[i] = usda.haveCulpabilityPeriods();
}
tabu = new StringJoiner(synX505String, synX506String, synX507String);
for (Integer i : seasons) {
tabu.add(i.toString());
}
return tabu.toString();
}
public synchronized int compareTo(Procedure ischium) {
double lourCurtail;
int generalizeIbid;
int exactlyEst;
lourCurtail = synX508double;
generalizeIbid = ischium.becomePhoto();
exactlyEst = this.becomePhoto();
return exactlyEst - generalizeIbid;
}
}
| 29.785235 | 81 | 0.722172 |
45a13f6fbb28b48bf5c7eb4567ee0eeca6ca6482 | 6,281 | package com.scmspain.bigdata.emr.Configuration;
import com.amazonaws.services.elasticmapreduce.model.Configuration;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.scmspain.bigdata.emr.Filesystem.JsonConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.IOException;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ClusterConfigurationTest
{
private static final String CONFIG_FILE = "test_config.json";
private ClusterConfiguration clusterConfiguration;
@Mock
private JsonConfiguration jsonConfiguration;
@Mock
private PasswordDecrypt passwordDecrypt;
@Before
public void setUp() throws Exception
{
MockitoAnnotations.initMocks(ClusterConfigurationTest.class);
clusterConfiguration = new ClusterConfiguration(
CONFIG_FILE,
jsonConfiguration,
passwordDecrypt
);
}
@After
public void tearDown() throws Exception
{
clusterConfiguration = null;
jsonConfiguration = null;
passwordDecrypt = null;
}
@Test
public void testWhenConfigurationDoesNotHaveClassificationParentKey() throws Exception
{
jsonFileWithoutClassificationParentKey();
ArrayList<Configuration> config = clusterConfiguration.getConfiguration();
assertEquals("The configuration should contain only one value", 1, config.size());
assertNull("The only element on the configuration should be null", config.get(0));
}
@Test
public void testWhenConfigurationDoesNotHavePropertiesKey() throws Exception
{
jsonFileWithoutPropertiesKey();
ArrayList<Configuration> config = clusterConfiguration.getConfiguration();
assertEquals("The configuration should contain only one value", 1, config.size());
assertEquals(
"The only element on the configuration should be of type Configuration",
Configuration.class,
config.get(0).getClass()
);
}
@Test
public void testWhenConfigurationDoesNotHaveConfigurationsKey() throws Exception
{
jsonFileWithoutConfigurationsKey();
ArrayList<Configuration> config = clusterConfiguration.getConfiguration();
assertEquals("The configuration should contain only one value", 1, config.size());
assertEquals(
"The only element on the configuration should be of type Configuration",
Configuration.class,
config.get(0).getClass()
);
}
@Test
public void testWhenConfigurationHasAllTheKeys() throws Exception
{
jsonFileWithFullConfiguration();
ArrayList<Configuration> config = clusterConfiguration.getConfiguration();
assertEquals("The configuration should contain two values", 2, config.size());
assertEquals(
"The first element on the configuration should be of type Configuration",
Configuration.class,
config.get(0).getClass()
);
assertEquals(
"The second element on the configuration should be of type Configuration",
Configuration.class,
config.get(1).getClass()
);
}
private void jsonFileWithoutPropertiesKey() throws IOException
{
String jsonString = "["+
" {\"classification\": \"export\"}"+
"]";
JsonArray json = (new JsonParser())
.parse(jsonString)
.getAsJsonArray();
when(jsonConfiguration.getJsonArrayFromFile(CONFIG_FILE)).thenReturn(json);
}
private void jsonFileWithoutClassificationParentKey() throws IOException
{
String jsonString = "["+
" {" +
" \"configurations\": [" +
" {" +
" \"classification\": \"export\"," +
" \"properties\": {" +
" \"OOZIE_URL\": \"http://localhost:11000/oozie\"" +
" }" +
" }" +
" ]" +
" }" +
"]";
JsonArray json = (new JsonParser())
.parse(jsonString)
.getAsJsonArray();
when(jsonConfiguration.getJsonArrayFromFile(CONFIG_FILE)).thenReturn(json);
}
private void jsonFileWithoutConfigurationsKey() throws IOException
{
String jsonString = "["+
" {\"classification\": \"export\",\"properties\": " +
" {\"OOZIE_URL\": \"http://localhost:11000/oozie\"}" +
" }"+
"]";
JsonArray json = (new JsonParser())
.parse(jsonString)
.getAsJsonArray();
when(jsonConfiguration.getJsonArrayFromFile(CONFIG_FILE)).thenReturn(json);
}
private void jsonFileWithFullConfiguration() throws IOException
{
String jsonString = "[" +
" {" +
" \"classification\": \"oozie-env\"," +
" \"configurations\": [" +
" {" +
" \"classification\": \"export\"," +
" \"properties\": {" +
" \"OOZIE_URL\": \"http://localhost:11000/oozie\"" +
" }" +
" }" +
" ]" +
" }," +
" {" +
" \"classification\": \"oozie-site\"," +
" \"properties\": {" +
" \"OOZIE_URL\": \"http://localhost:11000/oozie\"" +
" }" +
" }" +
"]";
JsonArray json = (new JsonParser())
.parse(jsonString)
.getAsJsonArray();
when(jsonConfiguration.getJsonArrayFromFile(CONFIG_FILE)).thenReturn(json);
}
} | 33.768817 | 90 | 0.574749 |
5d7d01e99201b148b731af49b2d2f23741eb9416 | 1,142 | package milkman.plugin.graphql.editor;
import static milkman.utils.FunctionalUtils.run;
import java.util.Arrays;
import javafx.scene.control.Tab;
import milkman.domain.RequestContainer;
import milkman.plugin.graphql.GraphqlContentType;
import milkman.plugin.graphql.domain.GraphqlAspect;
import milkman.ui.components.ContentEditor;
import milkman.ui.plugin.RequestAspectEditor;
public class GraphqlAspectEditor implements RequestAspectEditor {
@Override
public Tab getRoot(RequestContainer request) {
GraphqlAspect gqlAspect = request.getAspect(GraphqlAspect.class).get();
Tab tab = new Tab("Graphql");
ContentEditor editor = new ContentEditor();
editor.setHeaderVisibility(false);
editor.setEditable(true);
editor.setContentTypePlugins(Arrays.asList(new GraphqlContentType()));
editor.setContentType("application/graphql");
editor.setContent(gqlAspect::getQuery, run(gqlAspect::setQuery).andThen(() -> gqlAspect.setDirty(true)));
tab.setContent(editor);
return tab;
}
@Override
public boolean canHandleAspect(RequestContainer request) {
return request.getAspect(GraphqlAspect.class).isPresent();
}
}
| 30.052632 | 107 | 0.795972 |
01b78f811c267287749910edf9b99653e02ec9b1 | 8,974 | package com.lifeonwalden.codeGenerator;
import com.lifeonwalden.codeGenerator.bean.*;
import com.lifeonwalden.codeGenerator.bean.config.Config;
import com.lifeonwalden.codeGenerator.bean.config.DBSourceGenerator;
import com.lifeonwalden.codeGenerator.bean.config.ExtentionGenerator;
import com.lifeonwalden.codeGenerator.bean.config.JDBCConnectionConfiguration;
import com.lifeonwalden.codeGenerator.constant.ColumnConstraintEnum;
import com.lifeonwalden.codeGenerator.constant.JdbcTypeEnum;
import com.lifeonwalden.codeGenerator.javaClass.impl.DAOGeneratorImpl;
import com.lifeonwalden.codeGenerator.mybatis.constant.DatabaseUserTable;
import com.lifeonwalden.codeGenerator.mybatis.impl.XMLMapperGenerator;
import com.lifeonwalden.codeGenerator.util.ConnectionFactory;
import com.lifeonwalden.codeGenerator.util.DBInfoUtil;
import com.thoughtworks.xstream.XStream;
import java.io.File;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DBSourceGenerateCodeMain {
public static void main(String[] args) {
File configFileLocation = new File(args[0]);
if (!configFileLocation.exists() && !configFileLocation.isDirectory()) {
System.err.println("The directory is not exist.");
System.exit(1);
}
String globalOutputFileLocation = null;
if (args.length > 1) {
globalOutputFileLocation = args[1];
}
for (File templateFile : configFileLocation.listFiles()) {
if (!templateFile.getName().toLowerCase().endsWith("xml")) {
continue;
}
XStream xStream = new XStream();
xStream.processAnnotations(DBSourceGenerator.class);
DBSourceGenerator generator = (DBSourceGenerator) xStream.fromXML(templateFile);
List<Table> tableList = fetchTables(generator, globalOutputFileLocation);
Config config = generator.getConfig();
if (null != config) {
String outputLocation = config.getOutputLocation();
if (null == outputLocation) {
config.setOutputLocation(globalOutputFileLocation);
}
if (null != config.getExtentions()) {
Map<String, ExtentionGenerator> extentionMapping = new HashMap<String, ExtentionGenerator>();
for (ExtentionGenerator extention : config.getExtentions()) {
extentionMapping.put(extention.getGenerator(), extention);
}
config.setExtentionMapping(extentionMapping);
}
if (null == generator.getDb()) {
continue;
}
if (null != config) {
List<TableBasedGenerator> generatorList = new ArrayList<TableBasedGenerator>();
// standard generate
if (null != config.getBeanInfo()) {
try {
String beanGeneratorClass = generator.getConfig().getBeanInfo().getGenerator();
generatorList.add((TableBasedGenerator) Class.forName(
null == beanGeneratorClass
? "com.lifeonwalden.codeGenerator.javaClass.impl.HashBeanGeneratorImpl"
: beanGeneratorClass).newInstance());
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
System.err.println("Not an illegal Bean generator.");
continue;
}
if (null != config.getDaoInfo()) {
generatorList.add(new DAOGeneratorImpl());
if (null != config.getMybatisInfo()) {
generatorList.add(new XMLMapperGenerator());
}
}
}
if (null != config.getExtentions()) {
for (ExtentionGenerator extention : config.getExtentions()) {
try {
generatorList.add((TableBasedGenerator) Class.forName(extention.getGenerator()).newInstance());
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
System.err.println("Not an illegal generator : " + extention.getGenerator());
}
}
}
for (Table table : tableList) {
for (TableBasedGenerator _generator : generatorList) {
_generator.generate(table, generator.getConfig());
}
}
}
}
}
}
private static List<Table> fetchTables(DBSourceGenerator generator, String globalOutputFileLocation) {
if (generator.getDb() != null) {
DB db = generator.getDb();
Database database = new Database();
database.setSchema(db.getSchema());
database.setWithSchema(db.isWithSchema());
Map<String, DBTable> tableCache = new HashMap<>();
JDBCConnectionConfiguration jdbcConfig = new JDBCConnectionConfiguration();
jdbcConfig.setConnectionURL(db.getConnectionURL());
jdbcConfig.setDriverClass(db.getDriverClass());
jdbcConfig.setPassword(db.getPassword());
jdbcConfig.setUserId(db.getUserId());
ConnectionFactory connFactory = ConnectionFactory.getInstance();
try (Connection connection = connFactory.getConnection(jdbcConfig);) {
DatabaseMetaData metaData = connection.getMetaData();
List<Table> tableList = new ArrayList<Table>();
for (DBTable dbTable : db.getTables()) {
String metaTableParam, tableName = dbTable.getName();
switch (DatabaseUserTable.getDatabaseUserTable(DBInfoUtil.getDBType(jdbcConfig))) {
case ORACLE: {
metaTableParam = tableName.toUpperCase();
break;
}
default:
metaTableParam = tableName;
}
ResultSet columnRS = metaData.getColumns(null, "%", metaTableParam, "%");
Table table = new Table();
table.setName(tableName);
table.setNote(dbTable.getNote());
Map<String, Column> columnMapping = new HashMap<>();
List<Column> columnList = new ArrayList<Column>();
while (columnRS.next()) {
Column column = new Column();
String columnName = columnRS.getString("COLUMN_NAME");
column.setName(columnName);
column.setTable(table);
column.setRequired(columnRS.getInt("NULLABLE") != DatabaseMetaData.columnNullable);
JdbcTypeEnum typeInfo = JdbcTypeEnum.valueOf(columnRS.getInt("DATA_TYPE"));
column.setType(typeInfo.getName());
columnList.add(column);
columnMapping.put(columnName, column);
}
table.setColumnMapping(columnMapping);
table.setColumns(columnList);
ResultSet pkRS = metaData.getPrimaryKeys(db.getName(), "%", metaTableParam);
List<Column> pkList = new ArrayList<Column>();
while (pkRS.next()) {
String pk = pkRS.getString("COLUMN_NAME");
if (null != pk && pk.length() > 0) {
Column column = columnMapping.get(pk);
column.setConstraintType(ColumnConstraintEnum.PRIMARY_KEY);
pkList.add(column);
}
}
table.setExtProps(dbTable.getExtProps());
table.setPrimaryColumns(pkList);
table.setDatabase(database);
tableList.add(table);
}
return tableList;
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
return null;
}
}
| 46.257732 | 128 | 0.535436 |
7f28eda1928d4f1a58f331d7dc982595ded1f5ef | 2,925 | /**
* Copyright (c) Istituto Nazionale di Fisica Nucleare, 2014-2021.
*
* 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.italiangrid.storm.webdav.test.redirector;
import java.net.URI;
import org.italiangrid.storm.webdav.config.ServiceConfigurationProperties;
import org.italiangrid.storm.webdav.config.ServiceConfigurationProperties.RedirectorProperties;
import org.italiangrid.storm.webdav.config.ServiceConfigurationProperties.RedirectorProperties.ReplicaEndpointProperties;
import org.italiangrid.storm.webdav.test.utils.TestUtils;
public class RedirectorTestSupport implements TestUtils {
public static final String PATH = "/example/file";
public static final String PATH_WITH_PREFIX = "/prefix" + PATH;
public static final String RANDOM_TOKEN_STRING = "dshakd0123";
public static final String ACCESS_TOKEN_QUERY_STRING = "access_token=" + RANDOM_TOKEN_STRING;
public static final String URI_0_SCHEME = "http";
public static final String URI_1_SCHEME = "https";
public static final String URI_WITH_PREFIX_SCHEME = "http";
public static final String URI_0_HOST = "example";
public static final String URI_1_HOST = "another";
public static final String URI_WITH_PREFIX_HOST = "yetanother";
public static final URI ENDPOINT_URI_0 =
URI.create(String.format("%s://%s", URI_0_SCHEME, URI_0_HOST));
public static final URI ENDPOINT_URI_1 =
URI.create(String.format("%s://%s", URI_1_SCHEME, URI_1_HOST));
public static final URI ENDPOINT_URI_WITH_PREFIX =
URI.create(String.format("%s://%s/prefix", URI_WITH_PREFIX_SCHEME, URI_WITH_PREFIX_HOST));
public static final ReplicaEndpointProperties REPLICA_0;
public static final ReplicaEndpointProperties REPLICA_1;
public static final ReplicaEndpointProperties REPLICA_WITH_PREFIX;
static {
REPLICA_0 = new ReplicaEndpointProperties();
REPLICA_0.setEndpoint(ENDPOINT_URI_0);
REPLICA_1 = new ReplicaEndpointProperties();
REPLICA_1.setEndpoint(ENDPOINT_URI_1);
REPLICA_WITH_PREFIX = new ReplicaEndpointProperties();
REPLICA_WITH_PREFIX.setEndpoint(ENDPOINT_URI_WITH_PREFIX);
}
protected ServiceConfigurationProperties buildConfigurationProperties() {
ServiceConfigurationProperties config = new ServiceConfigurationProperties();
RedirectorProperties properties = new RedirectorProperties();
config.setRedirector(properties);
return config;
}
}
| 39 | 121 | 0.782564 |
88e742fdb7072d55f3606556b63acb53ef1ac5a8 | 2,900 | package pe.chalk.meal;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.DatePicker;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.StackPane;
import java.lang.reflect.Field;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
public class Controller {
@FXML private StackPane stack;
@FXML private DatePicker calendar;
@FXML @SuppressWarnings("unused") private ListView<String> breakfast;
@FXML @SuppressWarnings("unused") private ListView<String> lunch;
@FXML @SuppressWarnings("unused") private ListView<String> dinner;
@FXML @SuppressWarnings("unused") private ListView<String> snack;
private ProgressIndicator progress;
@FXML public void initialize() {
progress = new ProgressIndicator();
StackPane.setMargin(progress, new Insets(50));
calendar.setValue(LocalDate.now());
calendar.setConverter(new DateConverter());
search(null);
}
public void search(@SuppressWarnings("unused") final ActionEvent event) {
stack.getChildren().add(progress);
new Thread(() -> {
try {
final LocalDate date = calendar.getValue();
if (Objects.isNull(date)) return;
final Instant instant = date.atStartOfDay(ZoneId.systemDefault()).toInstant();
final Map<String, List<String>> meal = Fetcher.getMeal(Date.from(instant));
Platform.runLater(() -> Stream.of(getClass().getDeclaredFields())
.filter(field -> field.getType().equals(ListView.class))
.forEach(field -> updateList(meal, field)));
} catch (Exception e) {
e.printStackTrace();
Platform.runLater(() -> new Alert(Alert.AlertType.ERROR, e.getMessage(), ButtonType.CLOSE).show());
} finally {
Platform.runLater(() -> stack.getChildren().remove(progress));
}
}).start();
}
@SuppressWarnings("unchecked")
private void updateList(Map<String, List<String>> meal, Field field) {
try {
final ListView<String> listView = (ListView<String>) field.get(this);
final List<String> list = meal.getOrDefault(field.getName(), Collections.singletonList("Not available."));
listView.setItems(FXCollections.observableArrayList(list));
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 35.365854 | 118 | 0.662414 |
6eaadd9bb1660a805c45a6dea984466681eecb8e | 1,279 | package org.jessenpan.leetcode.array;
/**
* @author jessenpan
* tag:array
*/
public class S154FindMinimumInRotatedSortedArrayII {
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
boolean isIncreased;
while (left <= right) {
isIncreased = false;
int mid = left + (right - left) / 2;
if (left == right) {
return nums[left];
}
if (right - left == 1) {
return Math.min(nums[right], nums[left]);
}
if (nums[mid] == nums[right]) {
isIncreased = isIncreasedRange(nums, mid, right);
}
if (nums[mid] < nums[right] || isIncreased) {
//mid~right有序
right = mid;
} else {
//left~right有序
nums[mid] = nums[left];
left = mid;
}
}
return -1;
}
private boolean isIncreasedRange(int[] nums, int mid, int right) {
for (int i = mid; i <= right; i++) {
if (i == right) {
continue;
}
if (nums[i] > nums[i + 1]) {
return false;
}
}
return true;
}
}
| 24.132075 | 70 | 0.430805 |
c9496a116f3fd9bde8c2b9552a08302af4da9cc5 | 7,552 | /*
* Copyright 2015 OpenCB
*
* 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.opencb.cellbase.core.common.clinical;
/**
* @author by antonior on 5/22/14.
* @author Luis Miguel Cruz.
* @since October 08, 2014
*/
public class Cosmic extends ClinicalVariant{
/** geneName */
private String geneName;
/** Mutation GRCh37 strand */
private String mutationGRCh37Strand;
/** Primary site */
private String primarySite;
/** Mutation zygosity */
private String mutationZygosity;
/** Mutation AA */
private String mutationAA;
/** Tumour origin */
private String tumourOrigin;
/** Histology subtype */
private String histologySubtype;
/** Accession Number */
private String accessionNumber;
/** Mutation ID */
private String mutationID;
/** Mutation CDS */
private String mutationCDS;
/** Sample name */
private String sampleName;
/** Primary histology */
private String primaryHistology;
/** Mutation GRCh37 genome position */
private String mutationGRCh37GenomePosition;
/** Mutation Description */
private String mutationDescription;
/** Genome-wide screen */
private String genomeWideScreen;
/** ID_tumour */
private String ID_tumour;
/** idSample */
private String idSample;
/** Mutation somatic status */
private String mutationSomaticStatus;
/** Site subtype */
private String siteSubtype;
/** Gene CDS length */
private int geneCDSLength;
/** HGNC ID */
private String hgncId;
/** Pubmed PMID */
private String pubmedPMID;
private String sampleSource;
/** Age (may be null) */
private Float age;
/** Comments */
private String comments;
private boolean snp;
private String fathmmPrediction;
private Integer idStudy;
public Cosmic() {
super("cosmic");
}
// ----------------------- GETTERS / SETTERS --------------------------------
public String getGeneName() {
return geneName;
}
public void setGeneName(String geneName) {
this.geneName = geneName;
}
public String getMutationGRCh37Strand() {
return mutationGRCh37Strand;
}
public void setMutationGRCh37Strand(String mutationGRCh37Strand) {
this.mutationGRCh37Strand = mutationGRCh37Strand;
}
public String getPrimarySite() {
return primarySite;
}
public void setPrimarySite(String primarySite) {
this.primarySite = primarySite;
}
public String getMutationZygosity() {
return mutationZygosity;
}
public void setMutationZygosity(String mutationZygosity) {
this.mutationZygosity = mutationZygosity;
}
public String getMutationAA() {
return mutationAA;
}
public void setMutationAA(String mutationAA) {
this.mutationAA = mutationAA;
}
public String getTumourOrigin() {
return tumourOrigin;
}
public void setTumourOrigin(String tumourOrigin) {
this.tumourOrigin = tumourOrigin;
}
public String getHistologySubtype() {
return histologySubtype;
}
public void setHistologySubtype(String histologySubtype) {
this.histologySubtype = histologySubtype;
}
public String getAccessionNumber() {
return accessionNumber;
}
public void setAccessionNumber(String accessionNumber) {
this.accessionNumber = accessionNumber;
}
public String getMutationID() {
return mutationID;
}
public void setMutationID(String mutationID) {
this.mutationID = mutationID;
}
public String getMutationCDS() {
return mutationCDS;
}
public void setMutationCDS(String mutationCDS) {
this.mutationCDS = mutationCDS;
}
public String getSampleName() {
return sampleName;
}
public void setSampleName(String sampleName) {
this.sampleName = sampleName;
}
public String getPrimaryHistology() {
return primaryHistology;
}
public void setPrimaryHistology(String primaryHistology) {
this.primaryHistology = primaryHistology;
}
public String getMutationGRCh37GenomePosition() {
return mutationGRCh37GenomePosition;
}
public void setMutationGRCh37GenomePosition(String mutationGRCh37GenomePosition) {
this.mutationGRCh37GenomePosition = mutationGRCh37GenomePosition;
}
public String getMutationDescription() {
return mutationDescription;
}
public void setMutationDescription(String mutationDescription) {
this.mutationDescription = mutationDescription;
}
public String getGenomeWideScreen() {
return genomeWideScreen;
}
public void setGenomeWideScreen(String genomeWideScreen) {
this.genomeWideScreen = genomeWideScreen;
}
public String getID_tumour() {
return ID_tumour;
}
public void setID_tumour(String ID_tumour) {
this.ID_tumour = ID_tumour;
}
public String getIdSample() {
return idSample;
}
public void setIdSample(String idSample) {
this.idSample = idSample;
}
public String getMutationSomaticStatus() {
return mutationSomaticStatus;
}
public void setMutationSomaticStatus(String mutationSomaticStatus) {
this.mutationSomaticStatus = mutationSomaticStatus;
}
public String getSiteSubtype() {
return siteSubtype;
}
public void setSiteSubtype(String siteSubtype) {
this.siteSubtype = siteSubtype;
}
public int getGeneCDSLength() {
return geneCDSLength;
}
public void setGeneCDSLength(int geneCDSLength) {
this.geneCDSLength = geneCDSLength;
}
public boolean isSnp() {
return snp;
}
public void setSnp(boolean snp) {
this.snp = snp;
}
public String getFathmmPrediction() {
return fathmmPrediction;
}
public void setFathmmPrediction(String fathmmPrediction) {
this.fathmmPrediction = fathmmPrediction;
}
public Integer getIdStudy() {
return idStudy;
}
public void setIdStudy(Integer idStudy) {
this.idStudy = idStudy;
}
public String getHgncId() {
return hgncId;
}
public void setHgncId(String hgncId) {
this.hgncId = hgncId;
}
public String getPubmedPMID() {
return pubmedPMID;
}
public void setPubmedPMID(String pubmedPMID) {
this.pubmedPMID = pubmedPMID;
}
public Float getAge() {
return age;
}
public void setAge(Float age) {
this.age = age;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getSampleSource() {
return sampleSource;
}
public void setSampleSource(String sampleSource) {
this.sampleSource = sampleSource;
}
}
| 22.47619 | 86 | 0.653337 |
d8f267f0c53fcd9d1c5f5029a21e397b191a3651 | 1,942 | /*
* Copyright 2004-2015 the Seasar Foundation and the Others.
*
* 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.seasar.extension.jdbc.types;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import org.seasar.extension.jdbc.ValueType;
import oracle.sql.DATE;
/**
* {@link Date}型をOracle固有の{@literal DATE}型として扱う{@link ValueType}です。
*
* @author koichik
*/
public class OracleDateType extends DateTimestampType {
@Override
public void bindValue(final PreparedStatement ps, final int index,
final Object value) throws SQLException {
if (value == null) {
setNull(ps, index);
} else {
ps.setObject(index, toOracleDate(value));
}
}
@Override
public void bindValue(final CallableStatement cs,
final String parameterName, final Object value) throws SQLException {
if (value == null) {
setNull(cs, parameterName);
} else {
cs.setObject(parameterName, toOracleDate(value));
}
}
/**
* Oracle固有の{@literal DATE}型に変換して返します。
*
* @param value
* 値
* @return Oracle固有の{@literal DATE}型
*/
protected DATE toOracleDate(final Object value) {
return new DATE(toTimestamp(value));
}
}
| 29.424242 | 82 | 0.646241 |
d3cf4d283bd109845bfdd3acc6a5a7b75ea6c67d | 1,898 | package org.hy.common.net.junit.netty.t002;
import org.hy.common.xml.log.Logger;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
/**
* Netty的客户端
*
* @author ZhengWei(HY)
* @createDate 2021-09-09
* @version v1.0
*/
public class JU_NettyClient
{
private static final Logger $Logger = new Logger(JU_NettyClient.class ,true);
public static void main(String [] args)
{
// 客户端只需一个事件循环组
EventLoopGroup v_ClientGroup = new NioEventLoopGroup();
try
{
// 配置客户端的启动参数
Bootstrap v_Bootstarp = new Bootstrap();
v_Bootstarp.group(v_ClientGroup); // 设置线程组
v_Bootstarp.channel(NioSocketChannel.class); // 客户端通道实现
v_Bootstarp.handler(new ChannelInitializer<SocketChannel>()
{
@Override
protected void initChannel(SocketChannel i_Channel) throws Exception
{
i_Channel.pipeline().addLast(new NettyClientHandler()); // 关联处理器
}
});
$Logger.info("客户端启动完成");
ChannelFuture v_ChannelFuture = v_Bootstarp.connect("127.0.0.1" ,2021).sync(); // 异步非阻塞
// 对关闭通道监听
v_ChannelFuture.channel().closeFuture().sync(); // 阻塞
Thread.sleep(1000 * 1 * 10);
}
catch (Exception e)
{
$Logger.error(e);
}
finally
{
v_ClientGroup.shutdownGracefully(); // 优雅的关闭
}
}
}
| 27.114286 | 101 | 0.561117 |
7cf6ca990a9570cc9fa47da8d0060052c492dcb9 | 10,018 | package com.example.mmmut;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private EditText emailTextView, passwordTextView;
private TextView Btn,forgetbtn;
private ProgressBar progressbar;
ProgressDialog loadingBar;
public ProgressDialog loginprogress;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
loginprogress=new ProgressDialog(this);
emailTextView = findViewById(R.id.email);
passwordTextView = findViewById(R.id.password);
Btn = findViewById(R.id.login);
progressbar = findViewById(R.id.progressBar);
forgetbtn=findViewById(R.id.forgetpass);
forgetbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showRecoverPasswordDialog();
}
});
}
private void showRecoverPasswordDialog() {
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Recover Password");
LinearLayout linearLayout=new LinearLayout(this);
final EditText emailet= new EditText(this);
emailet.setHint("Enter recovery email");
emailet.setMinEms(16);
emailet.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
linearLayout.addView(emailet);
linearLayout.setPadding(10,10,10,10);
builder.setView(linearLayout);
builder.setPositiveButton("Recover", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String email=emailet.getText().toString().trim();
beginRecovery(email);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
private void beginRecovery(String email) {
loadingBar=new ProgressDialog(this);
loadingBar.setMessage("Sending Link....");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
mAuth.sendPasswordResetEmail(email).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful())
{
loadingBar.dismiss();
Toast.makeText(LoginActivity.this,"Done sent",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(LoginActivity.this,"Error Occured",Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this,"Error Failed",Toast.LENGTH_LONG).show();
}
});
}
public void loginUser(String email,String password){
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(
@NonNull Task<AuthResult> task)
{
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(),
"Login successful!!",
Toast.LENGTH_LONG)
.show();
// hide the progress bar
progressbar.setVisibility(View.GONE);
// if sign-in is successful
// intent to home activity
Intent intent
= new Intent(LoginActivity.this, DashBoard.class);
startActivity(intent);
finish();
}
else {
// sign-in failed
Toast.makeText(getApplicationContext(),
"Login failed!!",
Toast.LENGTH_LONG)
.show();
// hide the progress bar
progressbar.setVisibility(View.GONE);
}
}
});
// mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
// @Override
// public void onComplete(@NonNull Task<AuthResult> task) {
// if(task.isSuccessful()){
// loginprogress.dismiss();
// Intent mainIntent = new Intent(LoginActivity.this,DashBoard.class);
// mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(mainIntent);
// finish();
// } else {
// loginprogress.hide();
// Toast.makeText(LoginActivity.this,"Cannot Sign In..Plaese Try Again",Toast.LENGTH_LONG);
// }
// }
// });
// progressbar.setVisibility(View.GONE);
}
public void sigup(View view) {
Intent intent
= new Intent(LoginActivity.this,
RegistrationActivity.class);
startActivity(intent);
}
public void login(View view) {
progressbar.setVisibility(View.VISIBLE);
String email,passw;
email=emailTextView.getText().toString();
passw=passwordTextView.getText().toString();
loginUser(email,passw);
}
}
// private void loginUserAccount()
// {
//
// // show the visibility of progress bar to show loading
// progressbar.setVisibility(View.VISIBLE);
// // Take the value of two edit texts in Strings
// String email, password;
// email = emailTextView.getText().toString();
// password = passwordTextView.getText().toString();
//
// // validations for input email and password
// if (TextUtils.isEmpty(email)) {
// Toast.makeText(getApplicationContext(),
// "Please enter email!!",
// Toast.LENGTH_LONG)
// .show();
// return;
// }
//
// if (TextUtils.isEmpty(password)) {
// Toast.makeText(getApplicationContext(),
// "Please enter password!!",
// Toast.LENGTH_LONG)
// .show();
// return;
// }
//
// // signin existing user
// mAuth.signInWithEmailAndPassword(email, password)
// .addOnCompleteListener(
// new OnCompleteListener<AuthResult>() {
// @Override
// public void onComplete(
// @NonNull Task<AuthResult> task)
// {
// if (task.isSuccessful()) {
// Toast.makeText(getApplicationContext(),
// "Login successful!!",
// Toast.LENGTH_LONG)
// .show();
//
// // hide the progress bar
// progressbar.setVisibility(View.GONE);
//
// // if sign-in is successful
// // intent to home activity
// Intent intent
// = new Intent(LoginActivity.this, DashBoard.class);
// startActivity(intent);
// finish();
// }
//
// else {
//
// // sign-in failed
// Toast.makeText(getApplicationContext(),
// "Login failed!!",
// Toast.LENGTH_LONG)
// .show();
//
// // hide the progress bar
// progressbar.setVisibility(View.GONE);
// }
// }
// });
// }
| 41.396694 | 119 | 0.5002 |
0237ccbb399287cf15103de52242298404656ef4 | 1,961 | package org.spongepowered.asm.launch;
import java.util.ServiceLoader;
import org.spongepowered.asm.service.IGlobalPropertyService;
public final class GlobalProperties
{
private static IGlobalPropertyService service;
private static IGlobalPropertyService getService() {
/*SL:62*/if (GlobalProperties.service == null) {
final ServiceLoader<IGlobalPropertyService> v1 = /*EL:64*/ServiceLoader.<IGlobalPropertyService>load(IGlobalPropertyService.class, GlobalProperties.class.getClassLoader());
GlobalProperties.service = /*EL:65*/v1.iterator().next();
}
/*SL:67*/return GlobalProperties.service;
}
public static <T> T get(final String a1) {
/*SL:78*/return getService().<T>getProperty(a1);
}
public static void put(final String a1, final Object a2) {
getService().setProperty(/*EL:88*/a1, a2);
}
public static <T> T get(final String a1, final T a2) {
/*SL:101*/return getService().<T>getProperty(a1, a2);
}
public static String getString(final String a1, final String a2) {
/*SL:114*/return getService().getPropertyString(a1, a2);
}
public static final class Keys
{
public static final String INIT = "mixin.initialised";
public static final String AGENTS = "mixin.agents";
public static final String CONFIGS = "mixin.configs";
public static final String TRANSFORMER = "mixin.transformer";
public static final String PLATFORM_MANAGER = "mixin.platform";
public static final String FML_LOAD_CORE_MOD = "mixin.launch.fml.loadcoremodmethod";
public static final String FML_GET_REPARSEABLE_COREMODS = "mixin.launch.fml.reparseablecoremodsmethod";
public static final String FML_CORE_MOD_MANAGER = "mixin.launch.fml.coremodmanagerclass";
public static final String FML_GET_IGNORED_MODS = "mixin.launch.fml.ignoredmodsmethod";
}
}
| 41.723404 | 184 | 0.692504 |
122f1ebcd212bae808d1f92b780200a1d5b5524c | 1,597 | package com.synopsys.integration.detectable.detectables.rubygems.gemlock;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.synopsys.integration.bdio.graph.DependencyGraph;
import com.synopsys.integration.bdio.model.externalid.ExternalIdFactory;
import com.synopsys.integration.detectable.detectable.codelocation.CodeLocation;
import com.synopsys.integration.detectable.detectables.rubygems.gemlock.parse.GemlockParser;
import com.synopsys.integration.detectable.extraction.Extraction;
public class GemlockExtractor {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final ExternalIdFactory externalIdFactory;
public GemlockExtractor(ExternalIdFactory externalIdFactory) {
this.externalIdFactory = externalIdFactory;
}
public Extraction extract(File gemlock) {
try {
List<String> gemlockText = Files.readAllLines(gemlock.toPath(), StandardCharsets.UTF_8);
logger.debug(String.join(System.lineSeparator(), gemlockText));
GemlockParser gemlockParser = new GemlockParser(externalIdFactory);
DependencyGraph dependencyGraph = gemlockParser.parseProjectDependencies(gemlockText);
CodeLocation codeLocation = new CodeLocation(dependencyGraph);
return new Extraction.Builder().success(codeLocation).build();
} catch (Exception e) {
return new Extraction.Builder().exception(e).build();
}
}
}
| 38.95122 | 100 | 0.760175 |
9b862228fb810d8f08e84554c291988658b4e33b | 1,411 | package com.wisecityllc.cookedapp.adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.viewpagerindicator.IconPagerAdapter;
import com.wisecityllc.cookedapp.R;
import com.wisecityllc.cookedapp.fragments.IntroSlideFragment;
/**
* Created by dexterlohnes on 10/5/15.
*/
public class IntroSlidesFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter{
private int[] Images = new int[] { R.drawable.photo1, R.drawable.photo2,
R.drawable.photo3, R.drawable.photo4
};
protected static final int[] ICONS = new int[] { R.drawable.marker,
R.drawable.marker, R.drawable.marker, R.drawable.marker };
private int mCount = Images.length;
public IntroSlidesFragmentAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
boolean isLast = (position == Images.length - 1);
return new IntroSlideFragment(Images[position], isLast);
}
@Override
public int getCount() {
return mCount;
}
@Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
| 26.622642 | 97 | 0.678242 |
3507e632060ecab58bcf26d70e53e6507c0db9f2 | 333 | package spring.project.service;
import java.util.List;
import spring.project.vo.RetireVO;
import spring.project.vo.XmlVO;
public interface RetireService {
// 은퇴설계 계산
public RetireVO retire_calc(RetireVO vo);
// 상품추천
public List<XmlVO> recommender();
RetireVO selectRetire(String id);
void retireInsert(RetireVO vo);
}
| 17.526316 | 42 | 0.75976 |
678fb3723bef56caad747019e1cdc006a4f48056 | 8,590 | package com.reactnativejitsimeet;
import android.util.Log;
import java.net.URL;
import java.net.MalformedURLException;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.bridge.ReadableMap;
@ReactModule(name = RNJitsiMeetModule.MODULE_NAME)
public class RNJitsiMeetModule extends ReactContextBaseJavaModule {
public static final String MODULE_NAME = "RNJitsiMeetModule";
private IRNJitsiMeetViewReference mJitsiMeetViewReference;
public RNJitsiMeetModule(ReactApplicationContext reactContext, IRNJitsiMeetViewReference jitsiMeetViewReference) {
super(reactContext);
mJitsiMeetViewReference = jitsiMeetViewReference;
}
@Override
public String getName() {
return MODULE_NAME;
}
@ReactMethod
public void initialize() {
Log.d("JitsiMeet", "Initialize is deprecated in v2");
}
@ReactMethod
public void call(String url, ReadableMap userInfo, ReadableMap meetOptions, ReadableMap meetFeatureFlags) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mJitsiMeetViewReference.getJitsiMeetView() != null) {
RNJitsiMeetUserInfo _userInfo = new RNJitsiMeetUserInfo();
if (userInfo != null) {
if (userInfo.hasKey("displayName")) {
_userInfo.setDisplayName(userInfo.getString("displayName"));
}
if (userInfo.hasKey("email")) {
_userInfo.setEmail(userInfo.getString("email"));
}
if (userInfo.hasKey("avatar")) {
String avatarURL = userInfo.getString("avatar");
try {
_userInfo.setAvatar(new URL(avatarURL));
} catch (MalformedURLException e) {
}
}
}
RNJitsiMeetConferenceOptions options = new RNJitsiMeetConferenceOptions.Builder()
.setRoom(url)
.setToken(meetOptions.hasKey("token") ? meetOptions.getString("token") : "")
.setSubject(meetOptions.hasKey("subject") ? meetOptions.getString("subject") : "")
.setAudioMuted(meetOptions.hasKey("audioMuted") ? meetOptions.getBoolean("audioMuted") : false)
.setAudioOnly(meetOptions.hasKey("audioOnly") ? meetOptions.getBoolean("audioOnly") : false)
.setVideoMuted(meetOptions.hasKey("videoMuted") ? meetOptions.getBoolean("videoMuted") : false)
.setUserInfo(_userInfo)
.setFeatureFlag("add-people.enabled", meetFeatureFlags.hasKey("addPeopleEnabled") ? meetFeatureFlags.getBoolean("addPeopleEnabled") : true)
.setFeatureFlag("calendar.enabled", meetFeatureFlags.hasKey("calendarEnabled") ?meetFeatureFlags.getBoolean("calendarEnabled") : true)
.setFeatureFlag("call-integration.enabled", meetFeatureFlags.hasKey("callIntegrationEnabled") ?meetFeatureFlags.getBoolean("callIntegrationEnabled") : true)
.setFeatureFlag("chat.enabled", meetFeatureFlags.hasKey("chatEnabled") ?meetFeatureFlags.getBoolean("chatEnabled") : true)
.setFeatureFlag("close-captions.enabled", meetFeatureFlags.hasKey("closeCaptionsEnabled") ?meetFeatureFlags.getBoolean("closeCaptionsEnabled") : true)
.setFeatureFlag("invite.enabled", meetFeatureFlags.hasKey("inviteEnabled") ?meetFeatureFlags.getBoolean("inviteEnabled") : true)
.setFeatureFlag("android.screensharing.enabled", meetFeatureFlags.hasKey("androidScreenSharingEnabled") ?meetFeatureFlags.getBoolean("androidScreenSharingEnabled") : true)
.setFeatureFlag("live-streaming.enabled", meetFeatureFlags.hasKey("liveStreamingEnabled") ?meetFeatureFlags.getBoolean("liveStreamingEnabled") : true)
.setFeatureFlag("meeting-name.enabled", meetFeatureFlags.hasKey("meetingNameEnabled") ?meetFeatureFlags.getBoolean("meetingNameEnabled") : true)
.setFeatureFlag("meeting-password.enabled", meetFeatureFlags.hasKey("meetingPasswordEnabled") ?meetFeatureFlags.getBoolean("meetingPasswordEnabled") : true)
.setFeatureFlag("pip.enabled", meetFeatureFlags.hasKey("pipEnabled") ?meetFeatureFlags.getBoolean("pipEnabled") : true)
.setFeatureFlag("kick-out.enabled", meetFeatureFlags.hasKey("kickOutEnabled") ?meetFeatureFlags.getBoolean("kickOutEnabled") : true)
.setFeatureFlag("conference-timer.enabled", meetFeatureFlags.hasKey("conferenceTimerEnabled") ?meetFeatureFlags.getBoolean("conferenceTimerEnabled") : true)
.setFeatureFlag("video-share.enabled", meetFeatureFlags.hasKey("videoShareButtonEnabled") ?meetFeatureFlags.getBoolean("videoShareButtonEnabled") : true)
.setFeatureFlag("recording.enabled", meetFeatureFlags.hasKey("recordingEnabled") ?meetFeatureFlags.getBoolean("recordingEnabled") : true)
.setFeatureFlag("reactions.enabled", meetFeatureFlags.hasKey("reactionsEnabled") ?meetFeatureFlags.getBoolean("reactionsEnabled") : true)
.setFeatureFlag("raise-hand.enabled", meetFeatureFlags.hasKey("raiseHandEnabled") ?meetFeatureFlags.getBoolean("raiseHandEnabled") : true)
.setFeatureFlag("tile-view.enabled", true)
.setFeatureFlag("toolbox.alwaysVisible", meetFeatureFlags.hasKey("toolboxAlwaysVisible") ?meetFeatureFlags.getBoolean("toolboxAlwaysVisible") : false)
.setFeatureFlag("toolbox.enabled", meetFeatureFlags.hasKey("toolboxEnabled") ?meetFeatureFlags.getBoolean("toolboxEnabled") : true)
.setFeatureFlag("welcomepage.enabled", meetFeatureFlags.hasKey("welcomePageEnabled") ?meetFeatureFlags.getBoolean("welcomePageEnabled") : false)
.setFeatureFlag("overflow-menu.enabled", false)
.setFeatureFlag("audio-mute", false)
.build();
mJitsiMeetViewReference.getJitsiMeetView().join(options);
}
}
});
}
@ReactMethod
public void audioCall(String url, ReadableMap userInfo) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mJitsiMeetViewReference.getJitsiMeetView() != null) {
RNJitsiMeetUserInfo _userInfo = new RNJitsiMeetUserInfo();
if (userInfo != null) {
if (userInfo.hasKey("displayName")) {
_userInfo.setDisplayName(userInfo.getString("displayName"));
}
if (userInfo.hasKey("email")) {
_userInfo.setEmail(userInfo.getString("email"));
}
if (userInfo.hasKey("avatar")) {
String avatarURL = userInfo.getString("avatar");
try {
_userInfo.setAvatar(new URL(avatarURL));
} catch (MalformedURLException e) {
}
}
}
RNJitsiMeetConferenceOptions options = new RNJitsiMeetConferenceOptions.Builder()
.setRoom(url)
.setAudioOnly(true)
.setUserInfo(_userInfo)
.build();
mJitsiMeetViewReference.getJitsiMeetView().join(options);
}
}
});
}
@ReactMethod
public void endCall() {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mJitsiMeetViewReference.getJitsiMeetView() != null) {
mJitsiMeetViewReference.getJitsiMeetView().leave();
}
}
});
}
}
| 61.798561 | 195 | 0.605239 |
55d8c64180d44a01eacf99776d509f6d405a7e54 | 1,688 | package com.hearthsim.card.basic.spell;
import com.hearthsim.card.minion.Minion;
import com.hearthsim.card.minion.Minion.MinionTribe;
import com.hearthsim.card.spellcard.SpellDamageTargetableCard;
import com.hearthsim.exception.HSException;
import com.hearthsim.model.PlayerModel;
import com.hearthsim.model.PlayerSide;
import com.hearthsim.util.tree.HearthTreeNode;
public class KillCommand extends SpellDamageTargetableCard {
public KillCommand() {
super();
this.damage_ = 3;
}
@Deprecated
public KillCommand(boolean hasBeenUsed) {
this();
this.hasBeenUsed = hasBeenUsed;
}
/**
*
* Use the card on the given target
*
* Deals 3 damage. If you have a beast, deals 5 damage.
*
*
*
* @param side
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
*
* @return The boardState is manipulated and returned
*/
@Override
protected HearthTreeNode use_core(
PlayerSide side,
Minion targetMinion,
HearthTreeNode boardState, boolean singleRealizationOnly)
throws HSException {
boolean haveBeast = false;
PlayerModel currentPlayer = boardState.data_.modelForSide(PlayerSide.CURRENT_PLAYER);
for (final Minion minion : currentPlayer.getMinions()) {
haveBeast = haveBeast || minion.getTribe() == MinionTribe.BEAST;
}
if (haveBeast)
this.damage_ = (byte)5;
else
this.damage_ = (byte)3;
return super.use_core(side, targetMinion, boardState, singleRealizationOnly);
}
}
| 30.142857 | 120 | 0.667062 |
a12a8170278585b21b9289f393a40a0c6f671181 | 931 | package com.prohelion.canbus.model;
import java.util.ArrayList;
//import org.apache.commons.codec.binary.Hex;
public class UdpPacket {
private byte length;
private byte[] data;
private byte[] busId;
private byte[] senderId;
private ArrayList<CanPacket> canPackets;
public UdpPacket(byte length, byte[] data, byte[] busId, byte[] senderId) {
this.length = length;
this.data = data;
this.busId = busId;
this.senderId = senderId;
}
public ArrayList<CanPacket> getCanPackets() {
return canPackets;
}
public void setCanPackets(ArrayList<CanPacket> canPackets) {
this.canPackets = canPackets;
}
@Override
public String toString() {
/*return "UdpPacket [busId=" + Hex.encodeHexString(busId) + ", senderId=" +
Hex.encodeHexString(senderId) + ", canPackets=" + canPackets + "]"; */
return null;
}
}
| 25.162162 | 83 | 0.633727 |
accc5c090cafa3ad0611822b6c9b8035c80e32aa | 15,103 | package com.ykan.sdk.example.other;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.yaokan.sdk.api.JsonParser;
import com.yaokan.sdk.ir.YKanHttpListener;
import com.yaokan.sdk.ir.YkanIRInterface;
import com.yaokan.sdk.ir.YkanIRInterfaceImpl;
import com.yaokan.sdk.model.BaseResult;
import com.yaokan.sdk.model.DeviceDataStatus;
import com.yaokan.sdk.model.DeviceType;
import com.yaokan.sdk.model.KeyCode;
import com.yaokan.sdk.model.MatchRemoteControl;
import com.yaokan.sdk.model.MatchRemoteControlResult;
import com.yaokan.sdk.model.OneKeyMatchKey;
import com.yaokan.sdk.model.RemoteControl;
import com.yaokan.sdk.model.YKError;
import com.yaokan.sdk.utils.ProgressDialogUtils;
import com.yaokan.sdk.wifi.DeviceController;
import com.yaokan.sdk.wifi.listener.LearnCodeListener;
import com.ykan.sdk.example.AirControlActivity;
import com.ykan.sdk.example.BaseActivity;
import com.ykan.sdk.example.R;
import com.ykan.sdk.example.YKWifiDeviceControlActivity;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class OneKeyMatchActivity extends BaseActivity implements View.OnClickListener, LearnCodeListener, YKanHttpListener {
public static final String TAG = OneKeyMatchActivity.class.getName();
private int tid;
private int bid;
private YkanIRInterface ykanInterface;
private DeviceController driverControl = null;
private GizWifiDevice gizWifiDevice;
private ProgressDialogUtils dialogUtils;
private ListView listView;
private List<MatchRemoteControl> list = new ArrayList<>();
private ControlAdapter controlAdapter;
private RemoteControl remoteControl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_onekey_match);
if (getIntent() != null) {
initView();
dialogUtils = new ProgressDialogUtils(this);
// 遥控云数据接口分装对象对象
ykanInterface = new YkanIRInterfaceImpl(getApplicationContext());
gizWifiDevice = (GizWifiDevice) getIntent().getParcelableExtra(
"GizWifiDevice");
driverControl = new DeviceController(this, gizWifiDevice, null);
driverControl.initLearn(this);
}
}
private void initView() {
listView = (ListView) findViewById(R.id.lv_control);
tid = getIntent().getIntExtra("tid", 0);
bid = getIntent().getIntExtra("bid", 0);
((TextView) findViewById(R.id.tv_type)).setText(getIntent().getStringExtra("type") + tid);
((TextView) findViewById(R.id.tv_brand)).setText(getIntent().getStringExtra("brand") + bid);
controlAdapter = new ControlAdapter();
listView.setAdapter(controlAdapter);
}
String key;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_match:
switch (tid) {
case DeviceType.AIRCONDITION:
key = "on";
break;
case DeviceType.MULTIMEDIA:
key = "ok";
break;
default:
key = "power";
}
showDlg();
break;
}
}
private void showDlg() {
runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(OneKeyMatchActivity.this).setMessage("请对准小苹果按" + key + "键").setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
driverControl.startLearn();
}
}).create().show();
}
});
}
@Override
public void didReceiveData(DeviceDataStatus dataStatus, String data) {
// TODO Auto-generated method stub
switch (dataStatus) {
case DATA_LEARNING_SUCCESS://学习成功
final String studyValue = data;//data 表示学习接收到的数据
dialogUtils.sendMessage(ProgressDialogUtils.SHOW);
new Thread(new Runnable() {
@Override
public void run() {
ykanInterface.oneKeyMatched(gizWifiDevice.getMacAddress(), studyValue, tid + "", bid + "", key, OneKeyMatchActivity.this);
}
}).start();
Toast.makeText(getApplicationContext(), "学习成功", Toast.LENGTH_SHORT).show();
break;
case DATA_LEARNING_FAILED://学习失败
Toast.makeText(getApplicationContext(), "学习失败", Toast.LENGTH_SHORT).show();
driverControl.learnStop();
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (driverControl != null) {
driverControl.learnStop();
}
}
private void toYKWifiDeviceControlActivity() {
JsonParser jsonParser = new JsonParser();
Intent intent = new Intent();
intent.setClass(OneKeyMatchActivity.this, YKWifiDeviceControlActivity.class);
intent.putExtra("GizWifiDevice", gizWifiDevice);
try {
intent.putExtra("remoteControl", jsonParser.toJson(remoteControl));
intent.putExtra("rcCommand", jsonParser.toJson(remoteControl.getRcCommand()));
} catch (JSONException e) {
Log.e(TAG, "JSONException:" + e.getMessage());
}
startActivity(intent);
}
@Override
public void onSuccess(BaseResult baseResult) {
if (isFinishing()) {
return;
}
dialogUtils.sendMessage(ProgressDialogUtils.DISMISS);
if (baseResult instanceof OneKeyMatchKey) {
key = ((OneKeyMatchKey) baseResult).getNext_cmp_key();
showDlg();
} else if (baseResult instanceof RemoteControl) {
remoteControl = (RemoteControl) baseResult;
runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(OneKeyMatchActivity.this).setMessage("匹配成功,进入测试").setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
toYKWifiDeviceControlActivity();
}
}).create().show();
}
});
} else if (baseResult instanceof MatchRemoteControlResult) {
final MatchRemoteControlResult result = (MatchRemoteControlResult) baseResult;
Log.e("tttt", result.toString());
if (result != null && result.getRs() != null && result.getRs().size() > 0) {
runOnUiThread(new Runnable() {
@Override
public void run() {
list.clear();
list.addAll(result.getRs());
controlAdapter.notifyDataSetChanged();
}
});
}
}
}
@Override
public void onFail(final YKError ykError) {
dialogUtils.sendMessage(ProgressDialogUtils.DISMISS);
runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(OneKeyMatchActivity.this).setMessage(ykError.getError()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
});
}
private class ControlAdapter extends BaseAdapter {
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
OneKeyMatchActivity.ControlAdapter.ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.lv_control, parent, false);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.tv_rc_name);
holder.btnOn = (Button) convertView.findViewById(R.id.btn_on);
holder.btnOff = (Button) convertView.findViewById(R.id.btn_off);
holder.btnSOff = (Button) convertView.findViewById(R.id.btn_s_off);
holder.btnSOn = (Button) convertView.findViewById(R.id.btn_s_on);
holder.tvDl = (TextView) convertView.findViewById(R.id.dl);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(list.get(position).getName() + "-" + list.get(position).getRmodel());
holder.btnOff.setVisibility(View.VISIBLE);
holder.btnOn.setVisibility(View.VISIBLE);
holder.btnSOff.setVisibility(View.VISIBLE);
holder.btnSOn.setVisibility(View.VISIBLE);
if (list.get(position).getRcCommand().size() <= 2) {
holder.btnSOff.setVisibility(View.GONE);
holder.btnSOn.setVisibility(View.GONE);
}
holder.btnOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendCMD("on", position);
}
});
holder.btnOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendCMD("off", position);
}
});
holder.btnSOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendCMD("u0", position);
}
});
holder.btnSOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendCMD("u1", position);
}
});
holder.tvDl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialogUtils.sendMessage(ProgressDialogUtils.SHOW);
new Thread(new Runnable() {
@Override
public void run() {
ykanInterface
.getRemoteDetails(gizWifiDevice.getMacAddress(), list.get(position).getRid(), new YKanHttpListener() {
@Override
public void onSuccess(BaseResult baseResult) {
dialogUtils.sendMessage(ProgressDialogUtils.DISMISS);
if (baseResult != null) {
remoteControl = (RemoteControl) baseResult;
Intent intent = new Intent();
intent.setClass(OneKeyMatchActivity.this, AirControlActivity.class);
intent.putExtra("GizWifiDevice", gizWifiDevice);
try {
intent.putExtra("remoteControl", new JsonParser().toJson(remoteControl));
} catch (JSONException e) {
Log.e(TAG, "JSONException:" + e.getMessage());
}
startActivity(intent);
}
}
@Override
public void onFail(final YKError ykError) {
dialogUtils.sendMessage(ProgressDialogUtils.DISMISS);
runOnUiThread(new Runnable() {
@Override
public void run() {
new AlertDialog.Builder(OneKeyMatchActivity.this).setMessage(ykError.getError()).setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
});
Log.e(TAG, "ykError:" + ykError.toString());
}
});
}
}).start();
}
});
return convertView;
}
private class ViewHolder {
TextView name = null;
Button btnOn = null;
Button btnOff = null;
Button btnSOff = null;
Button btnSOn = null;
TextView tvDl = null;
}
}
private void sendCMD(String mode, int position) {
if (driverControl != null) {
HashMap<String, KeyCode> map = list.get(position).getRcCommand();
Set<String> set = map.keySet();
String key = null;
for (String s : set) {
if (s.contains(mode)) {
key = s;
}
}
driverControl.sendCMD(map.get(key).getSrcCode());
}
}
}
| 41.606061 | 196 | 0.527975 |
8d4abe74cb79ff3d570940420a46714c9ae0b5ba | 756 | package io.github.joeljeremy7.externalizedproperties.samples.database;
import io.github.joeljeremy7.externalizedproperties.core.ExternalizedProperty;
import java.util.List;
public interface ApplicationProperties {
@ExternalizedProperty("list.property")
public List<Integer> listProperty();
@ExternalizedProperty("int.property")
public int intProperty();
@ExternalizedProperty("property")
public String property();
@ExternalizedProperty("list.property.custom.table")
public List<Integer> listPropertyFromCustomTable();
@ExternalizedProperty("int.property.custom.table")
public int intPropertyFromCustomTable();
@ExternalizedProperty("property.custom.table")
public String propertyFromCustomTable();
}
| 29.076923 | 78 | 0.775132 |
5184766558b39e9141d24f49d42e77a0b54a1c4a | 959 | package com.github.bordertech.webfriends.selenium.element.grouping;
import com.github.bordertech.webfriends.selenium.common.tag.SeleniumTags;
import com.github.bordertech.webfriends.selenium.element.AbstractSElement;
import java.util.List;
import com.github.bordertech.webfriends.api.element.grouping.HUnorderedList;
import com.github.bordertech.webfriends.selenium.common.tags.STagUnorderedList;
/**
* Selenium list (unordered) element.
*/
public class SUnorderedList extends AbstractSElement implements HUnorderedList<SUnorderedListItem>, ListContainerElementSelenium<SUnorderedListItem> {
private List<SUnorderedListItem> items = null;
@Override
public STagUnorderedList getTagType() {
return SeleniumTags.UL;
}
@Override
public List<SUnorderedListItem> getListItems() {
if (items == null) {
items = getHelper().findWebFriends(getDriver(), getWebElement(), SeleniumTags.LISTITEM);
}
return items;
}
}
| 31.966667 | 151 | 0.778936 |
77bac47496883004475c9c15933565c54b8b0b65 | 1,465 | package javax.realtime;
public class ReleaseParameters extends ParameterBase {
private RelativeTime cost;
private RelativeTime deadline;
private AsyncEventHandler overrunHandler;
private AsyncEventHandler missHandler;
protected ReleaseParameters() {
this.cost = new RelativeTime(0,0);
}
protected ReleaseParameters(RelativeTime cost,
RelativeTime deadline,
AsyncEventHandler overrunHandler,
AsyncEventHandler missHandler) {
if(cost == null)
this.cost = new RelativeTime(0,0);
else
this.cost = cost;
this.deadline = deadline;
this.overrunHandler = overrunHandler;
this.missHandler = missHandler;
}
public RelativeTime getCost() {
return cost;
}
public AsyncEventHandler getCostOverrunHandler() {
return overrunHandler;
}
public RelativeTime getDeadline() {
return deadline;
}
public AsyncEventHandler getDeadlineMissHandler(){
return missHandler;
}
public void setCost(RelativeTime cost) {
this.cost = cost;
}
public void setCostOverrunHandler(AsyncEventHandler overrunHandler){
this.overrunHandler = overrunHandler;
}
public void setDeadline(RelativeTime deadline){
this.deadline = deadline;
}
public void setDeadlineMissHandler(AsyncEventHandler missHandler){
this.missHandler = missHandler;
}
public boolean setIfFeasible(RelativeTime relativeTime, RelativeTime relativeTime1) {
return true;
}
} | 23.253968 | 90 | 0.728328 |
c4494611ed018fc4e72fc8cf2f9db17118d9665b | 310 | package org.xml.sax.ext;
import org.xml.sax.Locator;
public interface Locator2 extends Locator {
String getXMLVersion();
String getEncoding();
}
/* Location: /mnt/r/ConTenDoViewer.jar!/org/xml/sax/ext/Locator2.class
* Java compiler version: 1 (45.3)
* JD-Core Version: 1.1.3
*/ | 20.666667 | 83 | 0.667742 |
2b442ab174c1c3bbb60ced03cd8d6e0b576535e6 | 1,837 | package com.testDemo.selenium.utils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
/**
* @Auther: zouren
* @Date: 2019/5/8 15:09
* @Description:
*/
public class InputUtils {
public static void setValue(WebDriver browser, String cssSeleror, String value){
WebElement webElement = browser.findElement(By.cssSelector(cssSeleror));
webElement.clear();
webElement.sendKeys(value);
}
public static String getValue(WebDriver browser,String cssSeleror){
WebElement webElement = browser.findElement(By.cssSelector(cssSeleror));
System.out.println(webElement.getText());
return webElement.getText();
}
public static void submit(WebDriver browser,String cssSeleror){
WebElement webElement = browser.findElement(By.cssSelector(cssSeleror));
webElement.submit();
}
public static void click(WebDriver browser,String cssSeleror){
WebElement webElement = browser.findElement(By.cssSelector(cssSeleror));
webElement.click();
}
public static WebElement find(WebDriver browser,String cssSeleror){
WebElement webElement =null;
try {
WaitUtils.wiatByCssSelector(browser,cssSeleror);
webElement = browser.findElement(By.cssSelector(cssSeleror));
} catch (Exception e) {
e.printStackTrace();
}
return webElement;
}
public static WebElement findByLinkText(WebDriver browser,String linkText){
WebElement webElement =null;
try {
WaitUtils.wiatByLinkText(browser,linkText);
webElement = browser.findElement(By.partialLinkText(linkText));
} catch (Exception e) {
e.printStackTrace();
}
return webElement;
}
}
| 34.018519 | 84 | 0.673381 |
4d27a32683e13f426a4b4263134185385c70fe92 | 973 | package ru.shifu.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* EmailNotification.
*
* @author Pavel Abrikosov ([email protected]).
* @version 1.
* @since 24.11.2018.
**/
public class EmailNotification {
private ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
/**
* Метод через ExecutorService отправляет почту
* @param user user
*/
public void emailTo(User user) {
String suject = String.format("Уведомление %s для %s", user.getUsername(), user.getEmail());
String body = String.format("Добавить новое сообщение для %s ", user.getUsername());
pool.execute(() -> send(suject, body, user.getEmail()));
}
public void send(String suject, String body, String email) {
System.out.println(suject);
System.out.println(body);
}
public void close() {
this.pool.shutdown();
}
}
| 27.8 | 108 | 0.663926 |
9983649f2959cf27aeb684481c257e550eeb994e | 2,107 | package com.trivago.cluecumber.rendering.pages.renderering;
import com.trivago.cluecumberCore.constants.ChartConfiguration;
import com.trivago.cluecumberCore.exceptions.CluecumberPluginException;
import com.trivago.cluecumberCore.json.pojo.Element;
import com.trivago.cluecumberCore.json.pojo.Step;
import com.trivago.cluecumberCore.properties.PropertyManager;
import com.trivago.cluecumberCore.rendering.pages.charts.ChartJsonConverter;
import com.trivago.cluecumberCore.rendering.pages.pojos.pagecollections.ScenarioDetailsPageCollection;
import com.trivago.cluecumberCore.rendering.pages.renderering.ScenarioDetailsPageRenderer;
import freemarker.template.Template;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ScenarioDetailsPageRendererTest {
private ScenarioDetailsPageRenderer scenarioDetailsPageRenderer;
@Before
public void setup() {
ChartJsonConverter chartJsonConverter = mock(ChartJsonConverter.class);
PropertyManager propertyManager = mock(PropertyManager.class);
when(propertyManager.getCustomStatusColorFailed()).thenReturn("#ff0000");
when(propertyManager.getCustomStatusColorPassed()).thenReturn("#00ff00");
when(propertyManager.getCustomStatusColorSkipped()).thenReturn("#00ffff");
ChartConfiguration chartConfiguration = new ChartConfiguration(propertyManager);
scenarioDetailsPageRenderer = new ScenarioDetailsPageRenderer(chartJsonConverter, chartConfiguration, propertyManager);
}
@Test
public void testContentRendering() throws CluecumberPluginException {
Template template = mock(Template.class);
Element element = new Element();
List<Step> steps = new ArrayList<>();
element.setSteps(steps);
ScenarioDetailsPageCollection scenarioDetailsPageCollection = new ScenarioDetailsPageCollection(element, "");
scenarioDetailsPageRenderer.getRenderedContent(scenarioDetailsPageCollection, template);
}
}
| 45.804348 | 127 | 0.800664 |
a8e77fd6207d5e7ba7a3ee149ea51c8ac3884e0f | 586 | package com.fr.swift.segment.bean.impl;
import com.fr.swift.segment.SegmentDestination;
import com.fr.swift.source.SourceKey;
/**
* @author yee
* @date 2018/10/7
*/
public class RealTimeSegLocationManager extends AbstractSegmentLocationManager {
@Override
protected void calculateRemoteSegment(SourceKey sourceKey, SegmentDestination destination) {
String key = destination.getSegmentId() + destination.getClusterId();
if (!remoteSegments.get(sourceKey).containsKey(key)) {
remoteSegments.get(sourceKey).put(key, destination);
}
}
}
| 30.842105 | 96 | 0.730375 |
06e5af6e02c35970fef5135dde3d6ca72b400cef | 676 | package br.com.zup.propostas.ServicosExternos.Cartao;
import br.com.zup.propostas.Cartao.Bloqueio.StatusBloqueio;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class StatusBloqueioResponse {
@JsonProperty
private StatusBloqueio resultado;
public StatusBloqueio getResultado() {
return resultado;
}
@JsonCreator
public StatusBloqueioResponse(StatusBloqueio resultado) {
this.resultado = resultado;
}
public void setResultado(StatusBloqueio resultado) {
this.resultado = resultado;
}
}
| 23.310345 | 61 | 0.757396 |
bc500fba49f2b91213d6ab51020ea0f654d4b10b | 1,459 | package de.rieckpil.courses.book.management;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class UserServiceRefactoredTest {
@Mock
private Clock clock;
@Mock
private UserRepository userRepository;
@InjectMocks
private UserServiceRefactored cut;
@Test
void shouldIncludeCurrentDateTimeWhenCreatingNewUser() {
when(userRepository.findByNameAndEmail("duke", "[email protected]")).thenReturn(null);
when(userRepository.save(any(User.class))).thenAnswer(invocation -> {
User user = invocation.getArgument(0);
user.setId(1L);
return user;
});
LocalDateTime defaultLocalDateTime = LocalDateTime.of(2020, 1, 1, 12, 0);
Clock fixedClock = Clock.fixed(defaultLocalDateTime.toInstant(ZoneOffset.UTC), ZoneId.of("UTC"));
when(clock.instant()).thenReturn(fixedClock.instant());
when(clock.getZone()).thenReturn(fixedClock.getZone());
User result = cut.getOrCreateUser("duke", "[email protected]");
assertEquals(defaultLocalDateTime, result.getCreatedAt());
}
}
| 28.607843 | 101 | 0.759424 |
4e91ee004d383a08df13a2631991d6ed6a37a22e | 465 | package practicalClassCodes.week10;
import java.util.*;
public class Advanced {
public static ArrayList<Integer> getUniqueValues(ArrayList<ArrayList<Integer>> list) {
return null; //to be completed
}
public static ArrayList<Integer> getItemsUniqueToSubLists(ArrayList<ArrayList<Integer>> list) {
return null; //to be completed
}
public static ArrayList<Integer> longestRepeatingSequence(ArrayList<Integer> list) {
return null; //to be completed
}
}
| 25.833333 | 96 | 0.772043 |
8a48fcb69e8885a9829f987fb67e63d91df85bff | 1,839 | package org.protege.editor.owl.ui.view.rdf.utils;
import com.github.owlcs.ontapi.Ontology;
import com.github.owlcs.ontapi.config.AxiomsSettings;
import com.github.owlcs.ontapi.internal.AxiomTranslator;
import com.github.owlcs.ontapi.internal.ONTObject;
import com.github.owlcs.ontapi.internal.ONTObjectFactory;
import com.github.owlcs.ontapi.jena.model.OntModel;
import com.github.owlcs.ontapi.jena.model.OntStatement;
import com.github.owlcs.ontapi.jena.utils.Iter;
import com.github.owlcs.ontapi.jena.utils.OntModels;
import org.apache.jena.graph.Triple;
import org.apache.jena.util.iterator.ExtendedIterator;
import org.protege.editor.owl.ui.view.rdf.RootTriple;
import org.semanticweb.owlapi.model.AxiomType;
import org.semanticweb.owlapi.model.OWLAxiom;
import java.util.Collection;
/**
* Created by @ssz on 16.01.2021.
*/
public class OWLTripleUtils {
public static boolean isRoot(Triple t) {
return t instanceof RootTriple;
}
public static Collection<ONTObject<? extends OWLAxiom>> getAxioms(Triple t, Ontology ont) {
OntModel m = OWLModelUtils.getGraphModel(ont);
AxiomsSettings c = OWLModelUtils.getConfig(m);
ONTObjectFactory f = OWLModelUtils.getObjectFactory(m);
return getAxioms(t, m, c, f);
}
public static Collection<ONTObject<? extends OWLAxiom>> getAxioms(Triple t, OntModel m, AxiomsSettings c, ONTObjectFactory f) {
OntStatement s = OntModels.toOntStatement(t, m);
return listAxioms(s, c, f).toSet();
}
public static ExtendedIterator<ONTObject<? extends OWLAxiom>> listAxioms(OntStatement s, AxiomsSettings c, ONTObjectFactory f) {
return Iter.create(AxiomType.AXIOM_TYPES).mapWith(AxiomTranslator::get)
.filterKeep(x -> x.testStatement(s, c))
.mapWith(x -> x.toAxiom(s, f, c));
}
}
| 39.12766 | 132 | 0.738989 |
6a84fd04517ea924085ea4cd9f2e80ec8ea4a251 | 3,152 | /*
* Copyright 2012-2013 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onehippo.forge.utilities;
import java.io.File;
import java.net.URL;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import org.apache.jackrabbit.core.TransientRepository;
import org.apache.jackrabbit.core.config.RepositoryConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
/**
* BaseTest
*
* @version $Id: BaseRepositoryTest.java 88118 2010-06-10 14:18:20Z mmilicevic $
*/
@Test
public class BaseRepositoryTest {
private static Logger log = LoggerFactory.getLogger(BaseRepositoryTest.class);
private Session session;
private static String configFileName = "repository.xml";
private static URL resource = BaseRepositoryTest.class.getClassLoader().getResource(configFileName);
protected File storageDirectory;
protected static TransientRepository transientRepository;
@BeforeSuite(alwaysRun = true)
protected void setup() throws Exception {
log.info(">>>>>>>>>>>> running setup");
storageDirectory = new File(System.getProperty("java.io.tmpdir"), "jcr");
deleteDirectory(storageDirectory);
transientRepository = new TransientRepository(RepositoryConfig.create(resource.toURI(), storageDirectory.getAbsolutePath()));
}
@AfterSuite(alwaysRun = true)
protected void tearDown() throws Exception {
log.info("<<<<<<<<<<<< running tear down");
storageDirectory = null;
if (session != null) {
session.logout();
}
transientRepository.shutdown();
transientRepository = null;
}
public boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (File file : files) {
if (file.isDirectory()) {
deleteDirectory(file);
} else {
boolean deleted = file.delete();
if (!deleted) {
log.error("Failed to delete: {}", file.getAbsolutePath());
}
}
}
}
return path.delete();
}
public Session getSession() throws RepositoryException {
if (session != null) {
return session;
}
session = transientRepository.login(new SimpleCredentials("admin", "admin".toCharArray()));
return session;
}
}
| 32.163265 | 133 | 0.660216 |
f24b696aeb65de252d022003710444bcc7427c0c | 2,111 | package me.gong.lavarun.plugin.shop;
import me.gong.lavarun.plugin.InManager;
import me.gong.lavarun.plugin.Main;
import me.gong.lavarun.plugin.game.GameManager;
import me.gong.lavarun.plugin.shop.events.SetPointsEvent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ItemDespawnEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class ShopManager implements Listener {
public static final int MAXIMUM_POINTS = 350;
private Map<UUID, Integer> points;
public ShopManager() {
points = new HashMap<>();
Bukkit.getPluginManager().registerEvents(this, InManager.get().getInstance(Main.class));
}
public void setPoints(Player player, int points) {
SetPointsEvent ev = new SetPointsEvent(player, points);
Bukkit.getPluginManager().callEvent(ev);
if(!ev.isCancelled()) this.points.put(player.getUniqueId(), ev.getAmount());
}
public void addPoints(Player player, int amount) {
setPoints(player, getPoints(player) + amount);
}
public void removePoints(Player player, int amount) {
setPoints(player, Math.max(0, getPoints(player) - amount));
}
public void resetPoints(Player player) {
setPoints(player, 0);
}
public void resetAllPlayers() {
Bukkit.getOnlinePlayers().forEach(this::resetPoints);
}
public int getPoints(Player player) {
return points.get(player.getUniqueId());
}
@EventHandler
public void onDespawn(ItemDespawnEvent ev) {
GameManager m = InManager.get().getInstance(GameManager.class);
if(m.isInGame()) ev.setCancelled(true);
}
@EventHandler
public void onJoin(PlayerJoinEvent ev) {
points.put(ev.getPlayer().getUniqueId(), 0);
}
@EventHandler
public void onQuit(PlayerQuitEvent ev) {
points.remove(ev.getPlayer().getUniqueId());
}
}
| 28.917808 | 96 | 0.701563 |
94dd5ff25d6e14e66bcfe228d2a752c3c3099efe | 1,469 | package com.hardsoftstudio.rxflux.sample.stores;
import com.hardsoftstudio.rxflux.action.RxAction;
import com.hardsoftstudio.rxflux.dispatcher.Dispatcher;
import com.hardsoftstudio.rxflux.sample.actions.Actions;
import com.hardsoftstudio.rxflux.sample.actions.Keys;
import com.hardsoftstudio.rxflux.sample.model.GitHubRepo;
import com.hardsoftstudio.rxflux.store.RxStore;
import com.hardsoftstudio.rxflux.store.RxStoreChange;
import java.util.ArrayList;
/**
* Created by marcel on 10/09/15.
*/
public class RepositoriesStore extends RxStore implements RepositoriesStoreInterface {
public static final String ID = "RepositoriesStore";
private static RepositoriesStore instance;
private ArrayList<GitHubRepo> gitHubRepos;
private RepositoriesStore(Dispatcher dispatcher) {
super(dispatcher);
}
public static synchronized RepositoriesStore get(Dispatcher dispatcher) {
if (instance == null) instance = new RepositoriesStore(dispatcher);
return instance;
}
@Override public void onRxAction(RxAction action) {
switch (action.getType()) {
case Actions.GET_PUBLIC_REPOS:
this.gitHubRepos = action.get(Keys.PUBLIC_REPOS);
break;
default: // IMPORTANT if we don't modify the store just ignore
return;
}
postChange(new RxStoreChange(ID, action));
}
@Override public ArrayList<GitHubRepo> getRepositories() {
return gitHubRepos == null ? new ArrayList<GitHubRepo>() : gitHubRepos;
}
}
| 32.644444 | 86 | 0.762423 |
d831f21712fe95a4cac4c78a9affa00ef11583f8 | 601 | package com.zup.william.proposta.proposta.analiseCredito;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(url="${url.analise}", name = "analiseDeCredito")
public interface ClientDaAnalise {
@RequestMapping(method = RequestMethod.POST, value = "/solicitacao", consumes = "application/json")
RetornoDaAnaliseRequest enviarParaAnalise(@RequestBody AnaliseDePropostaForm request);
}
| 31.631579 | 103 | 0.813644 |
baa19efb0ada78b2669c2de26571fab2b0be5004 | 8,652 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.util.paging;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
import java.util.Arrays;
import java.util.NoSuchElementException;
import org.testng.annotations.Test;
/**
* Test Paging.
*/
@Test
public final class PagingTest {
public void test_factory_of_Collection_empty() {
Paging test = Paging.ofAll(Arrays.asList());
assertEquals(PagingRequest.ALL, test.getRequest());
assertEquals(0, test.getTotalItems());
}
public void test_factory_of_Collection_sizeTwo() {
Paging test = Paging.ofAll(Arrays.asList("Hello", "There"));
assertEquals(PagingRequest.ALL, test.getRequest());
assertEquals(2, test.getTotalItems());
}
//-------------------------------------------------------------------------
public void test_factory_of_Collection_PagingRequest_empty() {
PagingRequest request = PagingRequest.ofPage(1, 20);
Paging test = Paging.of(request, Arrays.asList());
assertEquals(request, test.getRequest());
assertEquals(0, test.getTotalItems());
}
public void test_factory_of_Collection_PagingRequest_sizeTwo() {
PagingRequest request = PagingRequest.ofPage(1, 20);
Paging test = Paging.of(request, Arrays.asList("Hello", "There"));
assertEquals(request, test.getRequest());
assertEquals(2, test.getTotalItems());
}
//-------------------------------------------------------------------------
public void test_factory_of_PagingRequest_int() {
PagingRequest request = PagingRequest.ofPage(1, 20);
Paging test = Paging.of(request, 32);
assertEquals(request, test.getRequest());
assertEquals(32, test.getTotalItems());
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void test_factory_of_PagingRequest_int_totalItemsNegative() {
Paging.of(PagingRequest.ofPage(1, 20), -1);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void test_factory_of_PagingRequest_int_null() {
Paging.of(null, 0);
}
//-------------------------------------------------------------------------
public void test_getItems_page1() {
Paging test = Paging.of(PagingRequest.ofPage(1, 20), 52);
assertEquals(1, test.getPageNumber());
assertEquals(0, test.getFirstItem());
assertEquals(1, test.getFirstItemOneBased());
assertEquals(20, test.getLastItem());
assertEquals(20, test.getLastItemOneBased());
}
public void test_getItems_page2() {
Paging test = Paging.of(PagingRequest.ofPage(2, 20), 52);
assertEquals(2, test.getPageNumber());
assertEquals(20, test.getFirstItem());
assertEquals(21, test.getFirstItemOneBased());
assertEquals(40, test.getLastItem());
assertEquals(40, test.getLastItemOneBased());
}
public void test_getItems_page3() {
Paging test = Paging.of(PagingRequest.ofPage(3, 20), 52);
assertEquals(3, test.getPageNumber());
assertEquals(40, test.getFirstItem());
assertEquals(41, test.getFirstItemOneBased());
assertEquals(52, test.getLastItem());
assertEquals(52, test.getLastItemOneBased());
}
public void test_getTotalPages() {
assertEquals(2, Paging.of(PagingRequest.ofPage(1, 20), 39).getTotalPages());
assertEquals(2, Paging.of(PagingRequest.ofPage(1, 20), 40).getTotalPages());
assertEquals(3, Paging.of(PagingRequest.ofPage(1, 20), 41).getTotalPages());
}
//-------------------------------------------------------------------------
public void test_isSizeOnly() {
assertTrue(Paging.of(PagingRequest.NONE, 39).isSizeOnly());
assertFalse(Paging.of(PagingRequest.ofPage(1, 20), 39).isSizeOnly());
}
public void test_isNextPage() {
assertFalse(Paging.of(PagingRequest.ofPage(2, 20), 39).isNextPage());
assertFalse(Paging.of(PagingRequest.ofPage(2, 20), 40).isNextPage());
assertTrue(Paging.of(PagingRequest.ofPage(2, 20), 41).isNextPage());
assertTrue(Paging.of(PagingRequest.ofPage(1, 20), 39).isNextPage());
assertTrue(Paging.of(PagingRequest.ofPage(1, 20), 40).isNextPage());
}
public void test_isLastPage() {
assertTrue(Paging.of(PagingRequest.ofPage(2, 20), 39).isLastPage());
assertTrue(Paging.of(PagingRequest.ofPage(2, 20), 40).isLastPage());
assertFalse(Paging.of(PagingRequest.ofPage(2, 20), 41).isLastPage());
assertFalse(Paging.of(PagingRequest.ofPage(1, 20), 39).isLastPage());
assertFalse(Paging.of(PagingRequest.ofPage(1, 20), 40).isLastPage());
}
public void test_isPreviousPage() {
assertTrue(Paging.of(PagingRequest.ofPage(2, 20), 39).isPreviousPage());
assertTrue(Paging.of(PagingRequest.ofPage(2, 20), 40).isPreviousPage());
assertTrue(Paging.of(PagingRequest.ofPage(2, 20), 41).isPreviousPage());
assertFalse(Paging.of(PagingRequest.ofPage(1, 20), 39).isPreviousPage());
assertFalse(Paging.of(PagingRequest.ofPage(1, 20), 40).isPreviousPage());
}
public void test_isFirstPage() {
assertFalse(Paging.of(PagingRequest.ofPage(2, 20), 39).isFirstPage());
assertFalse(Paging.of(PagingRequest.ofPage(2, 20), 40).isFirstPage());
assertFalse(Paging.of(PagingRequest.ofPage(2, 20), 41).isFirstPage());
assertTrue(Paging.of(PagingRequest.ofPage(1, 20), 39).isFirstPage());
assertTrue(Paging.of(PagingRequest.ofPage(1, 20), 40).isFirstPage());
}
//-------------------------------------------------------------------------
public void test_toPagingRequest() {
assertEquals(PagingRequest.ofPage(2, 20), Paging.of(PagingRequest.ofPage(2, 20), 39).toPagingRequest());
assertEquals(PagingRequest.NONE, Paging.of(PagingRequest.NONE, 349).toPagingRequest());
}
public void test_nextPagingRequest() {
assertEquals(PagingRequest.ofPage(2, 20), Paging.of(PagingRequest.ofPage(1, 20), 39).nextPagingRequest());
}
@Test(expectedExceptions = IllegalStateException.class)
public void test_nextPagingRequest_pagingSizeZero() {
Paging.of(PagingRequest.NONE, 39).nextPagingRequest();
}
@Test(expectedExceptions = NoSuchElementException.class)
public void test_nextPagingRequest_lastPage() {
Paging.of(PagingRequest.ofPage(2, 20), 39).nextPagingRequest();
}
public void test_previousPagingRequest() {
assertEquals(PagingRequest.ofPage(1, 20), Paging.of(PagingRequest.ofPage(2, 20), 39).previousPagingRequest());
}
@Test(expectedExceptions = IllegalStateException.class)
public void test_previousPagingRequest_pagingSizeZero() {
Paging.of(PagingRequest.NONE, 39).previousPagingRequest();
}
@Test(expectedExceptions = NoSuchElementException.class)
public void test_previousPagingRequest_lastPage() {
Paging.of(PagingRequest.ofPage(1, 20), 39).previousPagingRequest();
}
//-------------------------------------------------------------------------
public void test_equals_equal() {
Paging test1 = Paging.of(PagingRequest.ofPage(1, 20), 52);
Paging test2 = Paging.of(PagingRequest.ofPage(1, 20), 52);
assertEquals(true, test1.equals(test1));
assertEquals(true, test1.equals(test2));
assertEquals(true, test2.equals(test1));
assertEquals(true, test2.equals(test2));
}
public void test_equals_notEqualPage() {
Paging test1 = Paging.of(PagingRequest.ofPage(1, 20), 52);
Paging test2 = Paging.of(PagingRequest.ofPage(2, 20), 52);
assertEquals(false, test1.equals(test2));
assertEquals(false, test2.equals(test1));
}
public void test_equals_notEqualPagingSize() {
Paging test1 = Paging.of(PagingRequest.ofPage(1, 20), 52);
Paging test2 = Paging.of(PagingRequest.NONE, 52);
assertEquals(false, test1.equals(test2));
assertEquals(false, test2.equals(test1));
}
public void test_equals_notEqualTotalItems() {
Paging test1 = Paging.of(PagingRequest.ofPage(1, 20), 52);
Paging test2 = Paging.of(PagingRequest.ofPage(1, 20), 12);
assertEquals(false, test1.equals(test2));
assertEquals(false, test2.equals(test1));
}
//-------------------------------------------------------------------------
public void test_hashCode_equal() {
Paging test1 = Paging.of(PagingRequest.ofPage(1, 20), 52);
Paging test2 = Paging.of(PagingRequest.ofPage(1, 20), 52);
assertEquals(test1.hashCode(), test2.hashCode());
}
//-------------------------------------------------------------------------
public void test_toString() {
Paging test = Paging.of(PagingRequest.ofPage(1, 20), 52);
assertEquals("Paging[first=0, size=20, totalItems=52]", test.toString());
}
}
| 39.327273 | 114 | 0.67129 |
efa482960864dea67831504c562b37b163cba4e6 | 1,604 | /*
* Code adapted from:
* https://github.com/netty/netty/tree/4.1/example/src/main/java/io/netty/example/securechat
*/
package com.autostreams.utils.datareceiver;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
/**
* Pipeline initializer for data receiver.
*
* @version 1.0
* @since 1.0
*/
public class DataReceiverInitializer extends ChannelInitializer<SocketChannel> {
private final DataReceiver dataReceiver;
private final StreamsServer<String> streamsServer;
/**
* Create a DataReceiverInitializer instance with injected KafkaPrototypeProducer.
*/
public DataReceiverInitializer(StreamsServer<String> streamsServer, DataReceiver dataReceiver) {
this.dataReceiver = dataReceiver;
this.streamsServer = streamsServer;
}
/**
* Initialize a channel's pipeline.
*
* @param channel the socket channel to initialize the pipeline on.
*/
@Override
public void initChannel(SocketChannel channel) {
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast(new StringDecoder());
pipeline.addLast(new StringEncoder());
pipeline.addLast(new DataReceiverHandler(streamsServer, this.dataReceiver));
}
}
| 32.734694 | 100 | 0.744389 |
6032281b0741eed0507fa77e548b987e3440386d | 1,175 | package com.inmaytide.exception.translator;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @author luomiao
* @since 2020/11/26
*/
public class TranslatorDelegator<T extends Throwable> implements ThrowableTranslator<T> {
private List<ThrowableTranslator<T>> translators;
private boolean innerSorted;
public TranslatorDelegator() {
this.translators = new ArrayList<>();
this.innerSorted = false;
}
public Optional<T> translate(Throwable throwable) {
if (!innerSorted) {
translators = translators.stream().sorted().collect(Collectors.toList());
innerSorted = true;
}
return translators.stream().map(translator -> translator.translate(throwable))
.filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty());
}
public void addTranslator(ThrowableTranslator<T> translator) {
translators.add(translator);
innerSorted = false;
}
@Override
public int getOrder() {
throw new UnsupportedOperationException();
}
}
| 26.111111 | 89 | 0.655319 |
f877a852c3cdb4d2e904e0730c3fd7cde518fa0a | 5,624 | package io.github.bbortt.event.planner.web.rest;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import io.github.bbortt.event.planner.AbstractApplicationContextAwareIT;
import io.github.bbortt.event.planner.domain.PersistentAuditEvent;
import io.github.bbortt.event.planner.repository.PersistenceAuditEventRepository;
import io.github.bbortt.event.planner.security.AuthoritiesConstants;
import java.time.ZonedDateTime;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link AuditResource} REST controller.
*/
@Transactional
@WithMockUser(authorities = AuthoritiesConstants.ADMIN)
class AuditResourceIT extends AbstractApplicationContextAwareIT {
private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL";
private static final String SAMPLE_TYPE = "SAMPLE_TYPE";
private static final ZonedDateTime SAMPLE_TIMESTAMP = ZonedDateTime.parse("2015-08-04T10:11:30Z");
private static final long SECONDS_PER_DAY = 60 * 60 * 24;
@Autowired
private PersistenceAuditEventRepository auditEventRepository;
private PersistentAuditEvent auditEvent;
@Autowired
private MockMvc restAuditMockMvc;
@BeforeEach
void initTest() {
auditEventRepository.deleteAll();
auditEvent = new PersistentAuditEvent();
auditEvent.setAuditEventType(SAMPLE_TYPE);
auditEvent.setPrincipal(SAMPLE_PRINCIPAL);
auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP);
}
@Test
void getAllAudits() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Get all the audits
restAuditMockMvc
.perform(get("/management/audits"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL)));
}
@Test
void getAudit() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Get the audit
restAuditMockMvc
.perform(get("/management/audits/{id}", auditEvent.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL));
}
@Test
void getAuditsByDate() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Generate dates for selecting audits by date, making sure the period will contain the audit
String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10);
String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10);
// Get the audit
restAuditMockMvc
.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL)));
}
@Test
void getNonExistingAuditsByDate() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Generate dates for selecting audits by date, making sure the period will not contain the sample audit
String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2 * SECONDS_PER_DAY).toString().substring(0, 10);
String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10);
// Query audits but expect no results
restAuditMockMvc
.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(header().string("X-Total-Count", "0"));
}
@Test
void getNonExistingAudit() throws Exception {
// Get the audit
restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE)).andExpect(status().isNotFound());
}
@Test
void testPersistentAuditEventEquals() throws Exception {
TestUtil.equalsVerifier(PersistentAuditEvent.class);
PersistentAuditEvent auditEvent1 = new PersistentAuditEvent();
auditEvent1.setId(1L);
PersistentAuditEvent auditEvent2 = new PersistentAuditEvent();
auditEvent2.setId(auditEvent1.getId());
assertThat(auditEvent1).isEqualTo(auditEvent2);
auditEvent2.setId(2L);
assertThat(auditEvent1).isNotEqualTo(auditEvent2);
auditEvent1.setId(null);
assertThat(auditEvent1).isNotEqualTo(auditEvent2);
}
}
| 42.285714 | 114 | 0.724395 |
0e776555ff285250cfb590d79fcfb5cc9fe1e893 | 1,935 | package com.manouti.itemfinder.util.recyclerview.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public abstract class RecyclerViewTrackSelectionAdapter<VH extends RecyclerViewTrackSelectionAdapter.ViewHolder> extends RecyclerView.Adapter<VH> {
// Start with first item selected
private int focusedItem = 0;
private RecyclerView mRecyclerView;
@Override
public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
mRecyclerView = recyclerView;
}
@Override
public void onBindViewHolder(VH viewHolder, int position) {
// Set selected state; use a state list drawable to style the view
viewHolder.itemView.setSelected(focusedItem == position);
}
public abstract void clear();
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
private RecyclerViewTrackSelectionAdapter<? extends ViewHolder> mAdapter;
protected Context mContext;
public ViewHolder(Context context, RecyclerViewTrackSelectionAdapter<? extends ViewHolder> adapter, View itemView) {
super(itemView);
this.mContext = context;
this.mAdapter = adapter;
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
@Override
public void onClick(View v) {
// Handle item click and set the selection -- redraw the old selection and the new
mAdapter.notifyItemChanged(mAdapter.focusedItem);
mAdapter.focusedItem = mAdapter.mRecyclerView.getChildAdapterPosition(v);
mAdapter.notifyItemChanged(mAdapter.focusedItem);
}
@Override
public boolean onLongClick(View v) {
return true;
}
}
} | 37.941176 | 147 | 0.707494 |
4e4388d83a7f01ee4168948bff3ad9a6db2aa98e | 2,350 | package org.meng.java.netty.echo;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class EchoClient {
private final String host;
private final int port;
public EchoClient(String host, int port) {
this.host = host;
this.port = port;
}
public static void main(String[] args) throws InterruptedException {
new EchoClient("localhost", 9000).start();
}
public void start() throws InterruptedException {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.remoteAddress(host, port)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new EchoClientHandler());
}
});
//connect to remote server
ChannelFuture channelFuture = bootstrap.connect().sync();
channelFuture.channel().closeFuture().sync();
} finally {
log.info("Shutdown client");
group.shutdownGracefully().sync();
}
}
}
@Slf4j
@ChannelHandler.Sharable
class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
log.info("Client send message to server");
ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks", CharsetUtil.UTF_8));
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
log.info("Client received message: {}", msg.toString(CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.error("Client get exception ", cause);
ctx.close();
}
} | 32.638889 | 94 | 0.641277 |
315b11b3e19e964a73fd658c0ab94df8bb665380 | 2,104 | package io.sufeng.jmybatis.batch;
import com.alibaba.druid.pool.DruidDataSource;
import io.sufeng.jmybatis.TestMapper;
import io.sufeng.jmybatis.page.Page;
import io.sufeng.jmybatis.page.PageParames;
import io.sufeng.jmybatis.page.PagePlugin;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import java.util.List;
import java.util.Map;
public class BatchPluginTest {
public static void main(String[] args) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://10.0.0.1:3306/icbc_account?characterEncoding=utf8&useSSL=false&useTimezone=true&serverTimezone=Asia/Shanghai");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("admin");
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.setLazyLoadingEnabled(true);
configuration.setEnvironment(environment);
configuration.addMapper(TestMapper.class);
configuration.addInterceptor(new BatchPlugin());
configuration.addInterceptor(new PagePlugin());
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(configuration);
SqlSession sqlSession = factory.openSession();
TestMapper mapper = sqlSession.getMapper(TestMapper.class);
List<Map<String,Object>> mapList = mapper.all();
System.out.println(mapList.size());
// Page<Map<String, Object>> page = mapper.page(PageParames.create(1, 3));
// System.out.println(page);
}
} | 43.833333 | 151 | 0.754753 |
15508840c56e30d4c5b6e8121987aac95e0078fe | 430 | package br.unicamp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class NouamiActivity extends AppCompatActivity {
TextView tvNome;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nouami);
tvNome = findViewById(R.id.tvNome);
}
}
| 18.695652 | 56 | 0.737209 |
a4db6ff9f126d7f72a1e4704d6337e08b38152a5 | 1,416 | package io.quarkus.jackson.runtime;
import java.time.ZoneId;
import java.util.Optional;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigRoot;
@ConfigRoot
public class JacksonBuildTimeConfig {
/**
* If enabled, Jackson will fail when encountering unknown properties.
* <p>
* You can still override it locally with {@code @JsonIgnoreProperties(ignoreUnknown = false)}.
*/
@ConfigItem(defaultValue = "false")
public boolean failOnUnknownProperties;
/**
* If enabled, Jackson will fail when no accessors are found for a type.
* This is enabled by default to match the default Jackson behavior.
*/
@ConfigItem(defaultValue = "true")
public boolean failOnEmptyBeans;
/**
* If enabled, Jackson will serialize dates as numeric value(s).
*/
@ConfigItem(defaultValue = "false")
public boolean writeDatesAsTimestamps;
/**
* If enabled, Jackson will ignore case during Enum deserialization.
*/
@ConfigItem(defaultValue = "false")
public boolean acceptCaseInsensitiveEnums;
/**
* If set, Jackson will default to using the specified timezone when formatting dates.
* Some examples values are "Asia/Jakarta" and "GMT+3".
* If not set, Jackson will use its own default.
*/
@ConfigItem(defaultValue = "UTC")
public Optional<ZoneId> timezone;
}
| 30.12766 | 99 | 0.69774 |
9800c0d856ea287779d5a0ecad9325f7a20f5b49 | 178 | package com.xyh.holdon;
/**
* Created by xyh on 2017/3/12.
*/
public class Api {
public static final String TIANGOU_CLASSIFY = "http://www.tngou.net/api/top/classify";
}
| 17.8 | 90 | 0.685393 |
728d0ed288f3a762a7a136f6a85e9faacd877d91 | 1,419 | package com.github.bogdanovmn.httpclient.selenium;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.github.bogdanovmn.httpclient.core.HttpClient;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import java.io.IOException;
public class SeleniumHtmlUnitHttpClient implements HttpClient {
private final HtmlUnitDriver browser = new HtmlUnitDriver(BrowserVersion.CHROME) {
@Override
protected WebClient newWebClient(BrowserVersion version) {
WebClient webClient = super.newWebClient(version);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setPrintContentOnFailingStatusCode(true);
webClient.getOptions().setUseInsecureSSL(true);
return webClient;
}
};
private final int pageLoadTimeInMills;
public SeleniumHtmlUnitHttpClient() {
this(100);
}
public SeleniumHtmlUnitHttpClient(int pageLoadTimeInMills) {
this.pageLoadTimeInMills = pageLoadTimeInMills;
}
@Override
public String get(String url) throws IOException {
browser.get(url);
try {
Thread.sleep(this.pageLoadTimeInMills);
}
catch (InterruptedException e) {
e.printStackTrace();
}
String result = browser.getPageSource();
browser.get("about:blank");
return result;
}
@Override
public void close() throws IOException {
browser.quit();
}
}
| 27.288462 | 83 | 0.78365 |
517fb30b3adae3c98507cdbd87ce4f01773fdd22 | 7,429 | package com.example.gamersleague.ui;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.gamersleague.Constants;
import com.example.gamersleague.R;
import com.example.gamersleague.adapters.ReviewsListAdapter;
import com.example.gamersleague.models.Result;
import com.example.gamersleague.models.Reviews;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import org.parceler.Parcels;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class GameDetailFragment extends Fragment implements View.OnClickListener ,ReviewsActivity.ExampleDialogListener{
@BindView(R.id.gameImageView)
ImageView mImageLabel;
@BindView(R.id.gameNameTextView)
TextView mNameLabel;
@BindView(R.id.descriptionTextView)
TextView mDescriptionLabel;
@BindView(R.id.favouritesTextView)
TextView mFavouritesLabel;
@BindView(R.id.giantBombTextView)
TextView mGiantBomb;
@BindView(R.id.viewFavTextView)
TextView mSaveGameButton;
@BindView(R.id.addCommentButton)
Button mAddCommentButton;
@BindView(R.id.recyclerView)
RecyclerView mRecyclerView;
private DatabaseReference mReviewReference;
private FirebaseRecyclerAdapter<Reviews, FirebaseReviewViewHolder> mFirebaseAdapter;
private FirebaseAuth mAuth;
private Result mResult;
private ReviewsListAdapter adapterReviews;
private Reviews mReview;
List<Reviews> mListReviews = new ArrayList<>();
public GameDetailFragment(){
}
public static GameDetailFragment newInstance(Result result) {
GameDetailFragment gameDetailFragment= new GameDetailFragment();
Bundle args = new Bundle();
args.putParcelable("game", Parcels.wrap(result));
args.putParcelable("position", Parcels.wrap(result.getId()));
gameDetailFragment.setArguments(args);
return gameDetailFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
assert getArguments() != null;
mResult = Parcels.unwrap(getArguments().getParcelable("game"));
Integer gamePosition = Parcels.unwrap(getArguments().getParcelable("position"));
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String uid = user.getUid();
final ArrayList<Reviews> reviews = new ArrayList<>();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference(Constants.FIREBASE_REVIEWS)
.child(gamePosition.toString());
DatabaseReference pushRef = ref.getRef();
String pushId = pushRef.getKey();
Log.i("game position",gamePosition.toString());
ref.child(pushId);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
mListReviews.add(snapshot.getValue(Reviews.class));
for (int i = 0; i < mListReviews.size(); i++) {
Log.i("reviews", mListReviews.get(i).toString());
}
Log.i("reviews", mListReviews.get(0).toString());
adapterReviews = new ReviewsListAdapter(getContext(),mListReviews);
mRecyclerView.setAdapter(adapterReviews);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.i("database", "The read failed: " + error.getCode());
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game_detail, container, false);
ButterKnife.bind(this, view);
Picasso.get().load(mResult.getImage().getScreenUrl()).into(mImageLabel);
mNameLabel.setText(mResult.getName());
mDescriptionLabel.setText(mResult.getDeck());
mGiantBomb.setOnClickListener(this);
mFavouritesLabel.setOnClickListener(this);
mSaveGameButton.setOnClickListener(this);
mAddCommentButton.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
if (v == mGiantBomb) {
Intent webIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(mResult.getSiteDetailUrl()));
startActivity(webIntent);
}
if(v == mFavouritesLabel){
YoYo.with(Techniques.Tada)
.duration(700)
.repeat(1)
.playOn(mAddCommentButton);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
DatabaseReference gamesRef = FirebaseDatabase
.getInstance()
.getReference(Constants.FIREBASE_CHILD_GAMES)
.child(uid);
DatabaseReference pushRef = gamesRef.push();
String pushId = pushRef.getKey();
mResult.setPushId(pushId);
pushRef.setValue(mResult);
Toast.makeText(getContext(), "Saved", Toast.LENGTH_SHORT).show();
}
if (v == mSaveGameButton) {
Intent intent = new Intent(requireContext(), SavedGamesListActivity.class);
startActivity(intent);
}
if (v == mAddCommentButton) {
ReviewsActivity exampleDialog = new ReviewsActivity();
exampleDialog.show(getFragmentManager(),"example dialog");
}
}
@Override
public void applyText(String comment, String rating) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String uid = user.getUid();
String username = user.getDisplayName();
mReview=new Reviews(comment,rating,uid,username);
mListReviews.add(mReview);
DatabaseReference reviewsRef = FirebaseDatabase
.getInstance()
.getReference(Constants.FIREBASE_REVIEWS);
reviewsRef.push().setValue(mReview);
Toast.makeText(getContext(), "Comment Added", Toast.LENGTH_SHORT).show();
}
} | 35.545455 | 120 | 0.681249 |
642d33a64b373f27d8d6848edbc1e9789b01b74e | 408 | // Part of PushMode: https://pushmode.machinezoo.com
package com.machinezoo.pushmode.internal.diffing;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
class ChildPatchStart extends DomPatch {
private final int at;
ChildPatchStart(int at) {
this.at = at;
}
@Override
char code() {
return 'p';
}
@Override
JsonNode toJson() {
return new IntNode(at);
}
}
| 19.428571 | 52 | 0.72549 |
3116127fc8e6de0aeffc665679cce0502ba4cb29 | 22,725 | package com.tencent.angel.serving.apis.prediction;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
/**
* <pre>
* open source marker; do not remove
* PredictionService provides access to machine-learned models loaded by
* model_servers.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.0.1)",
comments = "Source: apis/prediction/prediction_service.proto")
public class PredictionServiceGrpc {
private PredictionServiceGrpc() {}
public static final String SERVICE_NAME = "angel.serving.PredictionService";
// Static method descriptors that strictly reflect the proto.
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationRequest,
com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationResponse> METHOD_CLASSIFY =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
generateFullMethodName(
"angel.serving.PredictionService", "Classify"),
io.grpc.protobuf.ProtoUtils.marshaller(com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationResponse.getDefaultInstance()));
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionRequest,
com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionResponse> METHOD_REGRESS =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
generateFullMethodName(
"angel.serving.PredictionService", "Regress"),
io.grpc.protobuf.ProtoUtils.marshaller(com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionResponse.getDefaultInstance()));
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.tencent.angel.serving.apis.prediction.PredictProtos.PredictRequest,
com.tencent.angel.serving.apis.prediction.PredictProtos.PredictResponse> METHOD_PREDICT =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
generateFullMethodName(
"angel.serving.PredictionService", "Predict"),
io.grpc.protobuf.ProtoUtils.marshaller(com.tencent.angel.serving.apis.prediction.PredictProtos.PredictRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(com.tencent.angel.serving.apis.prediction.PredictProtos.PredictResponse.getDefaultInstance()));
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceRequest,
com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceResponse> METHOD_MULTI_INFERENCE =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
generateFullMethodName(
"angel.serving.PredictionService", "MultiInference"),
io.grpc.protobuf.ProtoUtils.marshaller(com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceResponse.getDefaultInstance()));
@io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901")
public static final io.grpc.MethodDescriptor<com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataRequest,
com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataResponse> METHOD_GET_MODEL_METADATA =
io.grpc.MethodDescriptor.create(
io.grpc.MethodDescriptor.MethodType.UNARY,
generateFullMethodName(
"angel.serving.PredictionService", "GetModelMetadata"),
io.grpc.protobuf.ProtoUtils.marshaller(com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataRequest.getDefaultInstance()),
io.grpc.protobuf.ProtoUtils.marshaller(com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataResponse.getDefaultInstance()));
/**
* Creates a new async stub that supports all call types for the service
*/
public static PredictionServiceStub newStub(io.grpc.Channel channel) {
return new PredictionServiceStub(channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static PredictionServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
return new PredictionServiceBlockingStub(channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary and streaming output calls on the service
*/
public static PredictionServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
return new PredictionServiceFutureStub(channel);
}
/**
* <pre>
* open source marker; do not remove
* PredictionService provides access to machine-learned models loaded by
* model_servers.
* </pre>
*/
public static abstract class PredictionServiceImplBase implements io.grpc.BindableService {
/**
* <pre>
* Classify.
* </pre>
*/
public void classify(com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_CLASSIFY, responseObserver);
}
/**
* <pre>
* Regress.
* </pre>
*/
public void regress(com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_REGRESS, responseObserver);
}
/**
* <pre>
* Predict -- provides access to loaded TensorFlow model.
* </pre>
*/
public void predict(com.tencent.angel.serving.apis.prediction.PredictProtos.PredictRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.PredictProtos.PredictResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_PREDICT, responseObserver);
}
/**
* <pre>
* MultiInference API for multi-headed models.
* </pre>
*/
public void multiInference(com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_MULTI_INFERENCE, responseObserver);
}
/**
* <pre>
* GetModelMetadata - provides access to metadata for loaded models.
* </pre>
*/
public void getModelMetadata(com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataResponse> responseObserver) {
asyncUnimplementedUnaryCall(METHOD_GET_MODEL_METADATA, responseObserver);
}
@java.lang.Override public io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
METHOD_CLASSIFY,
asyncUnaryCall(
new MethodHandlers<
com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationRequest,
com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationResponse>(
this, METHODID_CLASSIFY)))
.addMethod(
METHOD_REGRESS,
asyncUnaryCall(
new MethodHandlers<
com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionRequest,
com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionResponse>(
this, METHODID_REGRESS)))
.addMethod(
METHOD_PREDICT,
asyncUnaryCall(
new MethodHandlers<
com.tencent.angel.serving.apis.prediction.PredictProtos.PredictRequest,
com.tencent.angel.serving.apis.prediction.PredictProtos.PredictResponse>(
this, METHODID_PREDICT)))
.addMethod(
METHOD_MULTI_INFERENCE,
asyncUnaryCall(
new MethodHandlers<
com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceRequest,
com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceResponse>(
this, METHODID_MULTI_INFERENCE)))
.addMethod(
METHOD_GET_MODEL_METADATA,
asyncUnaryCall(
new MethodHandlers<
com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataRequest,
com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataResponse>(
this, METHODID_GET_MODEL_METADATA)))
.build();
}
}
/**
* <pre>
* open source marker; do not remove
* PredictionService provides access to machine-learned models loaded by
* model_servers.
* </pre>
*/
public static final class PredictionServiceStub extends io.grpc.stub.AbstractStub<PredictionServiceStub> {
private PredictionServiceStub(io.grpc.Channel channel) {
super(channel);
}
private PredictionServiceStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PredictionServiceStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new PredictionServiceStub(channel, callOptions);
}
/**
* <pre>
* Classify.
* </pre>
*/
public void classify(com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_CLASSIFY, getCallOptions()), request, responseObserver);
}
/**
* <pre>
* Regress.
* </pre>
*/
public void regress(com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_REGRESS, getCallOptions()), request, responseObserver);
}
/**
* <pre>
* Predict -- provides access to loaded TensorFlow model.
* </pre>
*/
public void predict(com.tencent.angel.serving.apis.prediction.PredictProtos.PredictRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.PredictProtos.PredictResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_PREDICT, getCallOptions()), request, responseObserver);
}
/**
* <pre>
* MultiInference API for multi-headed models.
* </pre>
*/
public void multiInference(com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_MULTI_INFERENCE, getCallOptions()), request, responseObserver);
}
/**
* <pre>
* GetModelMetadata - provides access to metadata for loaded models.
* </pre>
*/
public void getModelMetadata(com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataRequest request,
io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataResponse> responseObserver) {
asyncUnaryCall(
getChannel().newCall(METHOD_GET_MODEL_METADATA, getCallOptions()), request, responseObserver);
}
}
/**
* <pre>
* open source marker; do not remove
* PredictionService provides access to machine-learned models loaded by
* model_servers.
* </pre>
*/
public static final class PredictionServiceBlockingStub extends io.grpc.stub.AbstractStub<PredictionServiceBlockingStub> {
private PredictionServiceBlockingStub(io.grpc.Channel channel) {
super(channel);
}
private PredictionServiceBlockingStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PredictionServiceBlockingStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new PredictionServiceBlockingStub(channel, callOptions);
}
/**
* <pre>
* Classify.
* </pre>
*/
public com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationResponse classify(com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_CLASSIFY, getCallOptions(), request);
}
/**
* <pre>
* Regress.
* </pre>
*/
public com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionResponse regress(com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_REGRESS, getCallOptions(), request);
}
/**
* <pre>
* Predict -- provides access to loaded TensorFlow model.
* </pre>
*/
public com.tencent.angel.serving.apis.prediction.PredictProtos.PredictResponse predict(com.tencent.angel.serving.apis.prediction.PredictProtos.PredictRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_PREDICT, getCallOptions(), request);
}
/**
* <pre>
* MultiInference API for multi-headed models.
* </pre>
*/
public com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceResponse multiInference(com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_MULTI_INFERENCE, getCallOptions(), request);
}
/**
* <pre>
* GetModelMetadata - provides access to metadata for loaded models.
* </pre>
*/
public com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataResponse getModelMetadata(com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataRequest request) {
return blockingUnaryCall(
getChannel(), METHOD_GET_MODEL_METADATA, getCallOptions(), request);
}
}
/**
* <pre>
* open source marker; do not remove
* PredictionService provides access to machine-learned models loaded by
* model_servers.
* </pre>
*/
public static final class PredictionServiceFutureStub extends io.grpc.stub.AbstractStub<PredictionServiceFutureStub> {
private PredictionServiceFutureStub(io.grpc.Channel channel) {
super(channel);
}
private PredictionServiceFutureStub(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PredictionServiceFutureStub build(io.grpc.Channel channel,
io.grpc.CallOptions callOptions) {
return new PredictionServiceFutureStub(channel, callOptions);
}
/**
* <pre>
* Classify.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationResponse> classify(
com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_CLASSIFY, getCallOptions()), request);
}
/**
* <pre>
* Regress.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionResponse> regress(
com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_REGRESS, getCallOptions()), request);
}
/**
* <pre>
* Predict -- provides access to loaded TensorFlow model.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.tencent.angel.serving.apis.prediction.PredictProtos.PredictResponse> predict(
com.tencent.angel.serving.apis.prediction.PredictProtos.PredictRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_PREDICT, getCallOptions()), request);
}
/**
* <pre>
* MultiInference API for multi-headed models.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceResponse> multiInference(
com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_MULTI_INFERENCE, getCallOptions()), request);
}
/**
* <pre>
* GetModelMetadata - provides access to metadata for loaded models.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataResponse> getModelMetadata(
com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataRequest request) {
return futureUnaryCall(
getChannel().newCall(METHOD_GET_MODEL_METADATA, getCallOptions()), request);
}
}
private static final int METHODID_CLASSIFY = 0;
private static final int METHODID_REGRESS = 1;
private static final int METHODID_PREDICT = 2;
private static final int METHODID_MULTI_INFERENCE = 3;
private static final int METHODID_GET_MODEL_METADATA = 4;
private static class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final PredictionServiceImplBase serviceImpl;
private final int methodId;
public MethodHandlers(PredictionServiceImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_CLASSIFY:
serviceImpl.classify((com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationRequest) request,
(io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.ClassificationProtos.ClassificationResponse>) responseObserver);
break;
case METHODID_REGRESS:
serviceImpl.regress((com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionRequest) request,
(io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.RegressionProtos.RegressionResponse>) responseObserver);
break;
case METHODID_PREDICT:
serviceImpl.predict((com.tencent.angel.serving.apis.prediction.PredictProtos.PredictRequest) request,
(io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.PredictProtos.PredictResponse>) responseObserver);
break;
case METHODID_MULTI_INFERENCE:
serviceImpl.multiInference((com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceRequest) request,
(io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.InferenceProtos.MultiInferenceResponse>) responseObserver);
break;
case METHODID_GET_MODEL_METADATA:
serviceImpl.getModelMetadata((com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataRequest) request,
(io.grpc.stub.StreamObserver<com.tencent.angel.serving.apis.prediction.GetModelMetadataProtos.GetModelMetadataResponse>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
return new io.grpc.ServiceDescriptor(SERVICE_NAME,
METHOD_CLASSIFY,
METHOD_REGRESS,
METHOD_PREDICT,
METHOD_MULTI_INFERENCE,
METHOD_GET_MODEL_METADATA);
}
}
| 45 | 217 | 0.731397 |
c25ffcefae8ad379f16c48d6f00a4d55ce14ed3a | 836 | package com.softicar.platform.emf.source.code.reference.point;
import com.softicar.platform.common.testing.AbstractTest;
import java.util.Map;
import java.util.UUID;
import org.junit.Test;
public class EmfSourceCodeReferencePointsLoaderTest extends AbstractTest {
private final UUID referencePointUuid;
public EmfSourceCodeReferencePointsLoaderTest() {
this.referencePointUuid = EmfSourceCodeReferencePoints.getUuidOrThrow(EmfSourceCodeReferencePointForTesting.class);
}
@Test
public void test() {
Map<UUID, IEmfSourceCodeReferencePoint> referencePointMap = new EmfSourceCodeReferencePointsLoader().loadAll();
IEmfSourceCodeReferencePoint referencePoint = referencePointMap.get(referencePointUuid);
assertNotNull(referencePoint);
assertTrue(referencePoint instanceof EmfSourceCodeReferencePointForTesting);
}
}
| 29.857143 | 117 | 0.837321 |
a04243a789ff9984a59ba435819159beca4c99ac | 1,819 | package data.tracks;
import com.wrapper.spotify.SpotifyApi;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.model_objects.miscellaneous.AudioAnalysis;
import com.wrapper.spotify.requests.data.tracks.GetAudioAnalysisForTrackRequest;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
public class GetAudioAnalysisForTrackExample {
private static final String accessToken = "taHZ2SdB-bPA3FsK3D7ZN5npZS47cMy-IEySVEGttOhXmqaVAIo0ESvTCLjLBifhHOHOIuhFUKPW1WMDP7w6dj3MAZdWT8CLI2MkZaXbYLTeoDvXesf2eeiLYPBGdx8tIwQJKgV8XdnzH_DONk";
private static final String id = "01iyCAUm8EvOFqVWYJ3dVX";
private static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
.setAccessToken(accessToken)
.build();
private static final GetAudioAnalysisForTrackRequest getAudioAnalysisForTrackRequest = spotifyApi
.getAudioAnalysisForTrack(id)
.build();
public static void getAudioAnalysisForTrack_Sync() {
try {
final AudioAnalysis audioAnalysis = getAudioAnalysisForTrackRequest.execute();
System.out.println("Track duration: " + audioAnalysis.getTrack().getDuration());
} catch (IOException | SpotifyWebApiException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void getAudioAnalysisForTrack_Async() {
try {
final Future<AudioAnalysis> audioAnalysisFuture = getAudioAnalysisForTrackRequest.executeAsync();
// ...
final AudioAnalysis audioAnalysis = audioAnalysisFuture.get();
System.out.println("Track duration: " + audioAnalysis.getTrack().getDuration());
} catch (InterruptedException | ExecutionException e) {
System.out.println("Error: " + e.getCause().getMessage());
}
}
} | 39.543478 | 193 | 0.766355 |
99b7355b0e8e0005d967a6784d5c1aa087d6d20a | 1,854 | package com.curdflappers.minesweeper;
class Spot {
private int mState;
private int mRow;
private int mCol;
private SpotView mView;
private SpotListener listener;
static final int BOOL_FIELDS = 4;
static final int MINE = 1,
REVEALED = 2,
FLAGGED = 4,
EXPLODED = 8;
static final int SWEEP_ACTION = 0,
FLAG_ACTION = 1;
Spot(SpotListener listener, int r, int c) {
this.listener = listener;
mRow = r;
mCol = c;
}
boolean get(int field) { return (mState & field) > 0; }
void set(int field, boolean val) {
if(val) {
mState |= field;
} else {
mState &= -(field + 1);
}
}
int getNeighboringMines() { return (mState & 240) >> BOOL_FIELDS; }
int getRow() { return mRow; }
int getCol() { return mCol; }
void setView(SpotView v) {
mView = v;
}
void setNeighboringMines(int neighboringMines) {
mState &= -241;
mState += (neighboringMines << BOOL_FIELDS);
}
void sweep() {
if(get(FLAGGED) || get(REVEALED)) { return; }
set(REVEALED, true);
if (get(MINE)) {
set(EXPLODED, true);
}
updateState(SWEEP_ACTION);
}
void reveal() {
set(REVEALED, true);
mView.update();
}
void reset() {
set(MINE, false);
set(REVEALED, false);
set(FLAGGED, false);
set(EXPLODED, false);
mView.update();
}
void flag() {
if(get(REVEALED)) { return; }
set(FLAGGED, !get(FLAGGED));
updateState(FLAG_ACTION);
}
private void updateState(int action) {
listener.spotChanged(this, action);
mView.update();
}
interface SpotListener {
void spotChanged(Spot spot, int action);
}
}
| 22.337349 | 71 | 0.540453 |
9a62e061ccbcee44b01fe3099600caefaf5e56e6 | 1,993 | package ro.webdata.parser.xml.lido.core.complex.materialsTechSetComplexType;
import ro.webdata.parser.xml.lido.core.leaf.displayMaterialsTech.DisplayMaterialsTechDAO;
import ro.webdata.parser.xml.lido.core.leaf.materialsTech.MaterialsTechDAO;
import ro.webdata.parser.xml.lido.core.leaf.displayMaterialsTech.DisplayMaterialsTechDAOImpl;
import ro.webdata.parser.xml.lido.core.leaf.materialsTech.MaterialsTechDAOImpl;
import ro.webdata.parser.xml.lido.core.leaf.displayMaterialsTech.DisplayMaterialsTech;
import ro.webdata.parser.xml.lido.core.leaf.materialsTech.MaterialsTech;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.ArrayList;
public class MaterialsTechSetComplexTypeDAOImpl implements MaterialsTechSetComplexTypeDAO {
private static DisplayMaterialsTechDAO displayMaterialsTechParser = new DisplayMaterialsTechDAOImpl();
private static MaterialsTechDAO materialsTechParser = new MaterialsTechDAOImpl();
public MaterialsTechSetComplexType getMaterialsTechSetComplexType(Node node) {
ArrayList<DisplayMaterialsTech> displayMaterialsTechList = new ArrayList<DisplayMaterialsTech>();
MaterialsTech materialsTechList = new MaterialsTech();
NodeList childNodeList = node.getChildNodes();
for (int i = 0; i < childNodeList.getLength(); i++) {
Node child = childNodeList.item(i);
String childName = child.getNodeName();
switch (childName) {
case "lido:displayMaterialsTech":
displayMaterialsTechList.add(displayMaterialsTechParser.getDisplayMaterialsTech(child));
break;
case "lido:materialsTech":
materialsTechList = materialsTechParser.getMaterialsTech(child);
break;
default: break;
}
}
return new MaterialsTechSetComplexType(
displayMaterialsTechList,
materialsTechList
);
}
}
| 45.295455 | 108 | 0.725038 |
b453acd8d3c6c5ca559f51b74e6e486e419cc671 | 1,176 | package com.example.demo.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Service;
@Service
public class TopicService {
private List<Topic> topicsList = new ArrayList<>( Arrays.asList(
new Topic("JAVA","Core Java","Core java description"),
new Topic("Spring","Core Spring","Core spring description"),
new Topic("JAVAScript","JAVA Script","JAVA Script description")
));
public List<Topic> findAll(){
return topicsList;
}
public Topic findOne(String id){
return topicsList.stream().filter(t->t.getId().equals(id)).findFirst().get();
}
public void save(Topic t){
topicsList.add(t);
}
public void update(String id,Topic newtopic){
Topic existing = topicsList.stream().filter(t->t.getId().equals(id)).findFirst().get();
existing.setId(newtopic.getId());
existing.setName(newtopic.getName());
existing.setDescription(newtopic.getDescription());
}
public void delete(String id){
Topic topic = topicsList.stream().filter(t->t.getId().equals(id)).findFirst().get();
topicsList.remove(topic);
}
}
| 28 | 90 | 0.681973 |
e5871f3c24d4b427caf9b6422ff747ddc8cf33ca | 4,829 | package net.codeoftheday.uaa.documentation;
import static net.codeoftheday.uaa.testutils.TestClientComponent.CLIENT_ID;
import static net.codeoftheday.uaa.testutils.TestClientComponent.CLIENT_SECRET;
import static net.codeoftheday.uaa.testutils.TestUserComponent.ADMIN_PASSWORD;
import static net.codeoftheday.uaa.testutils.TestUserComponent.ADMIN_USERNAME;
import static net.codeoftheday.uaa.testutils.utils.EncodeUtils.encodeBase64;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields;
import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName;
import static org.springframework.restdocs.request.RequestDocumentation.requestParameters;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.HttpHeaders;
import org.springframework.restdocs.payload.ResponseFieldsSnippet;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MvcResult;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import net.codeoftheday.uaa.testutils.integration.AbstractDocumentation;
@RunWith(SpringRunner.class)
public class TokenDocumentation extends AbstractDocumentation {
@Test
public void tokenRetrievePublicKey() throws Exception {
//@formatter:off
mockMvc()
.perform(get("/oauth/token_key"))
.andExpect(status().isOk())
.andDo(docHandler().document(
responseFields(
fieldWithPath("alg").description("The algorithm of the public key"),
fieldWithPath("value").description("The public key")
)
));
//@formatter:on
}
@Test
public void tokenLogin() throws Exception {
//@formatter:off
final HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + encodeBase64(CLIENT_ID, CLIENT_SECRET));
mockMvc()
.perform(post("/oauth/token")
.param("username", ADMIN_USERNAME)
.param("password", ADMIN_PASSWORD)
.param("grant_type", "password")
.headers(headers))
.andExpect(status().isOk())
.andDo(docHandler().document(
requestHeaders(
headerWithName("Authorization").description("Basic auth credentials for the client")
),
requestParameters(
parameterWithName("username").description("The username to create token"),
parameterWithName("password").description("The password to create token"),
parameterWithName("grant_type").description("Type of the token to create")
),
responseFieldsForTokenModel()
));
//@formatter:on
}
private ResponseFieldsSnippet responseFieldsForTokenModel() {
//@formatter:off
return responseFields(
fieldWithPath("token_type").description("Type of the given token"),
fieldWithPath("scope").description("Scope of the given token"),
fieldWithPath("expires_in").description("Milliseconds till the token expires"),
fieldWithPath("access_token").description("The access token itself"),
fieldWithPath("refresh_token").description("The refresh token"),
fieldWithPath("jti").description("JWT Identifier")
);
//@formatter:on
}
@Test
public void tokenRefresh() throws Exception {
//@formatter:off
// Login
final MvcResult loginResult = mockMvc()
.perform(post("/oauth/token")
.param("username", ADMIN_USERNAME)
.param("password", ADMIN_PASSWORD)
.param("grant_type", "password")
.header("Authorization", "Basic " + encodeBase64(CLIENT_ID, CLIENT_SECRET)))
.andExpect(status().isOk())
.andReturn();
final ReadContext ctx = JsonPath.parse(loginResult.getResponse().getContentAsString());
final String refreshToken = ctx.read("$.refresh_token");
// Refresh token
mockMvc()
.perform(post("/oauth/token")
.param("refresh_token", refreshToken)
.param("grant_type", "refresh_token")
.header("Authorization", "Basic " + encodeBase64(CLIENT_ID, CLIENT_SECRET)))
.andExpect(status().isOk())
.andDo(docHandler().document(
requestHeaders(
headerWithName("Authorization").description("Basic auth credentials for the client")
),
requestParameters(
parameterWithName("grant_type").description("Type of the token to create"),
parameterWithName("refresh_token").description("Refresh token from the last token")
),
responseFieldsForTokenModel()
));
//@formatter:on
}
}
| 38.632 | 90 | 0.767447 |
c4e4937103c853e0592bd516a6116eae731b2fd5 | 380 | package com.lijojacob.mls.productcatalog.repository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.lijojacob.mls.common.repository.MlsRepository;
import com.lijojacob.mls.productcatalog.entity.MediaInternalText;
@RepositoryRestResource
public interface MediaInternalTextRepository extends MlsRepository<MediaInternalText, String> {
}
| 31.666667 | 95 | 0.865789 |
0322769de4f6ae51f565a8bfa666ef87228f20b1 | 433 | package net.LIGMA.Blocks;
import net.minecraft.block.Block;
import net.fabricmc.fabric.api.tools.FabricToolTags;
import net.fabricmc.fabric.api.block.FabricBlockSettings;
import net.minecraft.block.Material;
public class TrolliumBlock extends Block {
public TrolliumBlock() {
super(FabricBlockSettings.of(Material.METAL).breakByHand(false).strength(25f,1500f).breakByTool(FabricToolTags.PICKAXES, 5).build());
}
} | 30.928571 | 141 | 0.785219 |
79eec78e0d062b116b2f20190f10a251bbbb9435 | 2,051 | package br.com.improving.j1hol.sse.server;
import java.time.Instant;
public class PatientHealthInfo {
private long id;
private String name;
private Instant timestamp;
private int systolicPressure;
private int diastolicPressure;
private int heartRate;
public PatientHealthInfo(long id, String name, long systolicPressure, long heartRate) {
this.id = id;
this.name = name;
this.timestamp = Instant.now();
this.systolicPressure = Math.toIntExact(systolicPressure);
this.diastolicPressure = this.systolicPressure - 30;
this.heartRate = Math.toIntExact(heartRate);
}
public PatientHealthInfo() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSystolicPressure() {
return systolicPressure;
}
public void setSystolicPressure(int systolicPressure) {
this.systolicPressure = systolicPressure;
}
public int getDiastolicPressure() {
return diastolicPressure;
}
public void setDiastolicPressure(int diastolicPressure) {
this.diastolicPressure = diastolicPressure;
}
public int getHeartRate() {
return heartRate;
}
public void setHeartRate(int heartRate) {
this.heartRate = heartRate;
}
public Instant getTimestamp() {
return timestamp;
}
public void setTimestamp(Instant timestamp) {
this.timestamp = timestamp;
}
@Override
public String toString() {
return "PatientHealthInfo{" + "id=" + id + ", name=" + name
+ ", timestamp=" + timestamp + ", systolicPressure="
+ systolicPressure + ", diastolicPressure=" + diastolicPressure
+ ", heartRate=" + heartRate + '}';
}
}
| 25.012195 | 92 | 0.598245 |
7a1d487019c5549006770643946196eca98b7304 | 4,940 | package com.baeldung.java9.process;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by sanaulla on 2/23/2017.
*/
public class ProcessAPIEnhancementsUnitTest {
Logger log = LoggerFactory.getLogger(ProcessAPIEnhancementsUnitTest.class);
@Test
public void givenCurrentProcess_whenInvokeGetInfo_thenSuccess() throws IOException {
ProcessHandle processHandle = ProcessHandle.current();
ProcessHandle.Info processInfo = processHandle.info();
assertNotNull(processHandle.pid());
assertEquals(false, processInfo.arguments()
.isPresent());
assertEquals(true, processInfo.command()
.isPresent());
assertTrue(processInfo.command()
.get()
.contains("java"));
assertEquals(true, processInfo.startInstant()
.isPresent());
assertEquals(true, processInfo.totalCpuDuration()
.isPresent());
assertEquals(true, processInfo.user()
.isPresent());
}
@Test
public void givenSpawnProcess_whenInvokeGetInfo_thenSuccess() throws IOException {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder = new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
ProcessHandle.Info processInfo = processHandle.info();
assertNotNull(processHandle.pid());
assertEquals(false, processInfo.arguments()
.isPresent());
assertEquals(true, processInfo.command()
.isPresent());
assertTrue(processInfo.command()
.get()
.contains("java"));
assertEquals(true, processInfo.startInstant()
.isPresent());
assertEquals(true, processInfo.totalCpuDuration()
.isPresent());
assertEquals(true, processInfo.user()
.isPresent());
}
@Test
public void givenLiveProcesses_whenInvokeGetInfo_thenSuccess() {
Stream<ProcessHandle> liveProcesses = ProcessHandle.allProcesses();
liveProcesses.filter(ProcessHandle::isAlive)
.forEach(ph -> {
assertNotNull(ph.pid());
assertEquals(true, ph.info()
.command()
.isPresent());
assertEquals(true, ph.info()
.startInstant()
.isPresent());
assertEquals(true, ph.info()
.totalCpuDuration()
.isPresent());
assertEquals(true, ph.info()
.user()
.isPresent());
});
}
@Test
public void givenProcess_whenGetChildProcess_thenSuccess() throws IOException {
int childProcessCount = 5;
for (int i = 0; i < childProcessCount; i++) {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
processBuilder.inheritIO().start();
}
Stream<ProcessHandle> children = ProcessHandle.current()
.children();
children.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
Stream<ProcessHandle> descendants = ProcessHandle.current()
.descendants();
descendants.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
}
@Test
public void givenProcess_whenAddExitCallback_thenSuccess() throws Exception {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
log.info("PID: {} has started", processHandle.pid());
CompletableFuture<ProcessHandle> onProcessExit = processHandle.onExit();
onProcessExit.get();
assertEquals(false, processHandle.isAlive());
onProcessExit.thenAccept(ph -> {
log.info("PID: {} has stopped", ph.pid());
});
}
}
| 36.865672 | 88 | 0.578947 |
f55026f0d8a5685d941994f36773eb0ab29a1d88 | 1,314 | /*
* Copyright 2011-2022 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 org.springframework.data.neo4j.integration.issues.gh2474;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* @author Stephen Jackson
*/
@Data
public class CityModelDTO {
private UUID cityId;
private String name;
private String exoticProperty;
public PersonModelDTO mayor;
public List<PersonModelDTO> citizens = new ArrayList<>();
public List<JobRelationshipDTO> cityEmployees = new ArrayList<>();
/**
* Nested projection
*/
@Data
public static class PersonModelDTO {
private UUID personId;
}
/**
* Nested projection
*/
@Data
public static class JobRelationshipDTO {
private PersonModelDTO person;
}
}
| 24.792453 | 75 | 0.741248 |
2135c1cc4b81ca78343d7237698cdaddd641255f | 324 | package inassGaby.dao;
/**
* Exception spécifique aux problèmes d'accès aux données via un DAO
* @author Eric
*/
public class DAOException extends java.lang.Exception {
public DAOException() {
super();
}
public DAOException(String message) {
super(message);
}
}
| 19.058824 | 69 | 0.608025 |
be04334b496134a6c8d58d29f59ec8d20a6bf879 | 489 | package boj_february;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
public class BOJ_2164 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Deque<Integer> deque = new LinkedList<>();
int n = scanner.nextInt();
for(int i=1;i<=n;i++) {
deque.offer(i);
}
while(deque.size()>1) {//1이 될때 빠져나옴
//빼고
deque.pop();
//다시 뺀 것을 맨 아래로
deque.add(deque.pop());
}
System.out.println(deque.peek());
}
}
| 20.375 | 44 | 0.648262 |
e6b105c45b6f43b4370716e992e631953092f6ce | 807 | package com.kabl.soliditydns;
import org.web3j.codegen.SolidityFunctionWrapperGenerator;
public class CodeGenerator {
public static void main(String[] args) throws Exception {
System.out.println("Generate the code!");
create("SolDnsApp.sol", "SolDnsApp.abi");
create("Cmc.sol", "Cmc.abi");
create("DnsDB.sol", "DnsDB.abi");
}
private static void create(String contractSource, String abi) throws Exception {
String[] args2 = {
"./src/main/resources/contracts/" + contractSource,
"./src/main/resources/contracts/bin/" + abi,
"-p",
"com.kabl.soliditydns.generated",
"-o",
"./src/main/java",};
SolidityFunctionWrapperGenerator.main(args2);
}
}
| 28.821429 | 84 | 0.591078 |
4aec301da2fbbea4292508781ae5719fe3f9bb31 | 2,600 | package ca.sfu.cmpt373.pluto.fall2021.hha.services;
import ca.sfu.cmpt373.pluto.fall2021.hha.models.HhaUser;
import ca.sfu.cmpt373.pluto.fall2021.hha.models.Role;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@Service
@RequiredArgsConstructor
public class AuthorizationService {
private final HhaUserService userService;
@Value("${secret.key.jwt}")
private String jwtSecret;
public void refresh(HttpServletRequest request, HttpServletResponse response, String refreshToken) throws IOException {
try {
var algorithm = Algorithm.HMAC256(jwtSecret);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT decodedJWT = verifier.verify(refreshToken);
var email = decodedJWT.getSubject();
var user = userService.getUser(email);
var accessToken = JWT.create()
.withSubject(user.getEmail())
.withExpiresAt(new Date(Instant.now().plus(10, ChronoUnit.MINUTES).toEpochMilli()))
.withIssuer(request.getRequestURL().toString())
.withClaim("roles",
user.getRoles().stream()
.map(Role::getName).collect(Collectors.toList()))
.sign(algorithm);
Map<String, String> tokens = Map.ofEntries(Map.entry("accessToken", accessToken));
response.setContentType(APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getOutputStream(), tokens);
} catch (JWTDecodeException e) {
response.sendError(SC_UNAUTHORIZED);
}
}
public HhaUser getUser() {
DecodedJWT decodedJWT = JWT.decode(jwtSecret);
var email = decodedJWT.getSubject();
return userService.getUser(email);
}
}
| 38.80597 | 123 | 0.696923 |
32311b2370c7f8077499038abdb714543c7a51d6 | 1,054 | package com.sijkinc.abstractkim.retrofitpractice.CrytoCompare.Toplists.ByTotalVolume;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
@Data
public class CoinInfo {
@SerializedName("Id")
private String id;
@SerializedName("Name")
private String name;
@SerializedName("FullName")
private String fullName;
@SerializedName("Internal")
private String internal;
@SerializedName("ImageUrl")
private String imageUrl;
@SerializedName("Url")
private String url;
@SerializedName("Algorithm")
private String algorithm;
@SerializedName("ProofType")
private String proofType;
@SerializedName("NetHashesPerSecond")
private String netHashesPerSecond;
@SerializedName("BlockNumber")
private String blockNumber;
@SerializedName("BlockTime")
private String blockTime;
@SerializedName("BlockReward")
private String blockReward;
@SerializedName("Type")
private String type;
@SerializedName("DocumentType")
private String documentType;
}
| 27.736842 | 85 | 0.73055 |
dbd6bf7f9c924965c28b9fc47b8899cf855c2786 | 5,852 | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package io.flutter.embedding.engine.systemchannels;
import android.os.Build;
import android.view.InputDevice;
import android.view.KeyEvent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.Log;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.JSONMessageCodec;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Event message channel for key events to/from the Flutter framework.
*
* <p>Sends key up/down events to the framework, and receives asynchronous messages from the
* framework about whether or not the key was handled.
*/
public class KeyEventChannel {
private static final String TAG = "KeyEventChannel";
/**
* Sets the event response handler to be used to receive key event response messages from the
* framework on this channel.
*/
public void setEventResponseHandler(EventResponseHandler handler) {
this.eventResponseHandler = handler;
}
private EventResponseHandler eventResponseHandler;
/** A handler of incoming key handling messages. */
public interface EventResponseHandler {
/**
* Called whenever the framework responds that a given key event was handled by the framework.
*
* @param event the event to be marked as being handled by the framework. Must not be null.
*/
public void onKeyEventHandled(KeyEvent event);
/**
* Called whenever the framework responds that a given key event wasn't handled by the
* framework.
*
* @param event the event to be marked as not being handled by the framework. Must not be null.
*/
public void onKeyEventNotHandled(KeyEvent event);
}
/**
* A constructor that creates a KeyEventChannel with the default message handler.
*
* @param binaryMessenger the binary messenger used to send messages on this channel.
*/
public KeyEventChannel(@NonNull BinaryMessenger binaryMessenger) {
this.channel =
new BasicMessageChannel<>(binaryMessenger, "flutter/keyevent", JSONMessageCodec.INSTANCE);
}
/**
* Creates a reply handler for the given key event.
*
* @param event the Android key event to create a reply for.
*/
BasicMessageChannel.Reply<Object> createReplyHandler(KeyEvent event) {
return message -> {
if (eventResponseHandler == null) {
return;
}
try {
if (message == null) {
eventResponseHandler.onKeyEventNotHandled(event);
return;
}
final JSONObject annotatedEvent = (JSONObject) message;
final boolean handled = annotatedEvent.getBoolean("handled");
if (handled) {
eventResponseHandler.onKeyEventHandled(event);
} else {
eventResponseHandler.onKeyEventNotHandled(event);
}
} catch (JSONException e) {
Log.e(TAG, "Unable to unpack JSON message: " + e);
eventResponseHandler.onKeyEventNotHandled(event);
}
};
}
@NonNull public final BasicMessageChannel<Object> channel;
public void keyUp(@NonNull FlutterKeyEvent keyEvent) {
Map<String, Object> message = new HashMap<>();
message.put("type", "keyup");
message.put("keymap", "android");
encodeKeyEvent(keyEvent, message);
channel.send(message, createReplyHandler(keyEvent.event));
}
public void keyDown(@NonNull FlutterKeyEvent keyEvent) {
Map<String, Object> message = new HashMap<>();
message.put("type", "keydown");
message.put("keymap", "android");
encodeKeyEvent(keyEvent, message);
channel.send(message, createReplyHandler(keyEvent.event));
}
private void encodeKeyEvent(
@NonNull FlutterKeyEvent keyEvent, @NonNull Map<String, Object> message) {
message.put("flags", keyEvent.event.getFlags());
message.put("plainCodePoint", keyEvent.event.getUnicodeChar(0x0));
message.put("codePoint", keyEvent.event.getUnicodeChar());
message.put("keyCode", keyEvent.event.getKeyCode());
message.put("scanCode", keyEvent.event.getScanCode());
message.put("metaState", keyEvent.event.getMetaState());
if (keyEvent.complexCharacter != null) {
message.put("character", keyEvent.complexCharacter.toString());
}
message.put("source", keyEvent.event.getSource());
InputDevice device = InputDevice.getDevice(keyEvent.event.getDeviceId());
int vendorId = 0;
int productId = 0;
if (device != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
vendorId = device.getVendorId();
productId = device.getProductId();
}
}
message.put("vendorId", vendorId);
message.put("productId", productId);
message.put("deviceId", keyEvent.event.getDeviceId());
message.put("repeatCount", keyEvent.event.getRepeatCount());
}
/** A key event as defined by Flutter. */
public static class FlutterKeyEvent {
/**
* The Android key event that this Flutter key event was created from.
*
* <p>This event is used to identify pending events when results are received from the
* framework.
*/
public final KeyEvent event;
/**
* The character produced by this event, including any combining characters pressed before it.
*/
@Nullable public final Character complexCharacter;
public FlutterKeyEvent(@NonNull KeyEvent androidKeyEvent) {
this(androidKeyEvent, null);
}
public FlutterKeyEvent(
@NonNull KeyEvent androidKeyEvent, @Nullable Character complexCharacter) {
this.event = androidKeyEvent;
this.complexCharacter = complexCharacter;
}
}
}
| 34.222222 | 99 | 0.700957 |
eec4247366ab619eb25794a37fab16c87afbe328 | 5,237 | package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.util.ModifierUtils;
/**
* @author Nicolas Gramlich
* @since 19:39:25 - 19.03.2010
*/
public class SequenceModifier<T> extends BaseModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private ISubSequenceModifierListener<T> mSubSequenceModifierListener;
private final IModifier<T>[] mSubSequenceModifiers;
private int mCurrentSubSequenceModifier;
private final float mDuration;
// ===========================================================
// Constructors
// ===========================================================
public SequenceModifier(final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(null, pModifiers);
}
public SequenceModifier(final IModifierListener<T> pModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(pModifierListener, null, pModifiers);
}
public SequenceModifier(final IModifierListener<T> pModifierListener, final ISubSequenceModifierListener<T> pSubSequenceModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
super(pModifierListener);
if (pModifiers.length == 0) {
throw new IllegalArgumentException("pModifiers must not be empty!");
}
this.mSubSequenceModifierListener = pSubSequenceModifierListener;
this.mSubSequenceModifiers = pModifiers;
this.mDuration = ModifierUtils.getSequenceDurationOfModifier(pModifiers);
pModifiers[0].setModifierListener(new InternalModifierListener());
}
@SuppressWarnings("unchecked")
protected SequenceModifier(final SequenceModifier<T> pSequenceModifier) {
super(pSequenceModifier.mModifierListener);
this.mSubSequenceModifierListener = pSequenceModifier.mSubSequenceModifierListener;
this.mDuration = pSequenceModifier.mDuration;
final IModifier<T>[] otherModifiers = pSequenceModifier.mSubSequenceModifiers;
this.mSubSequenceModifiers = (IModifier<T>[])new IModifier[otherModifiers.length];
final IModifier<T>[] shapeModifiers = this.mSubSequenceModifiers;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
shapeModifiers[i] = otherModifiers[i].clone();
}
shapeModifiers[0].setModifierListener(new InternalModifierListener());
}
@Override
public SequenceModifier<T> clone(){
return new SequenceModifier<T>(this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public ISubSequenceModifierListener<T> getSubSequenceModifierListener() {
return this.mSubSequenceModifierListener;
}
public void setSubSequenceModifierListener(final ISubSequenceModifierListener<T> pSubSequenceModifierListener) {
this.mSubSequenceModifierListener = pSubSequenceModifierListener;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getDuration() {
return this.mDuration;
}
@Override
public void onUpdate(final float pSecondsElapsed, final T pItem) {
if(!this.mFinished) {
this.mSubSequenceModifiers[this.mCurrentSubSequenceModifier].onUpdate(pSecondsElapsed, pItem);
}
}
@Override
public void reset() {
this.mCurrentSubSequenceModifier = 0;
this.mFinished = false;
final IModifier<T>[] shapeModifiers = this.mSubSequenceModifiers;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
shapeModifiers[i].reset();
}
}
// ===========================================================
// Methods
// ===========================================================
private void onHandleModifierFinished(final InternalModifierListener pInternalModifierListener, final IModifier<T> pModifier, final T pItem) {
this.mCurrentSubSequenceModifier++;
if(this.mCurrentSubSequenceModifier < this.mSubSequenceModifiers.length) {
final IModifier<T> nextSubSequenceModifier = this.mSubSequenceModifiers[this.mCurrentSubSequenceModifier];
nextSubSequenceModifier.setModifierListener(pInternalModifierListener);
if(this.mSubSequenceModifierListener != null) {
this.mSubSequenceModifierListener.onSubSequenceFinished(pModifier, pItem, this.mCurrentSubSequenceModifier);
}
} else {
this.mFinished = true;
if(this.mModifierListener != null) {
this.mModifierListener.onModifierFinished(this, pItem);
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface ISubSequenceModifierListener<T> {
public void onSubSequenceFinished(final IModifier<T> pModifier, final T pItem, final int pIndex);
}
private class InternalModifierListener implements IModifierListener<T> {
@Override
public void onModifierFinished(final IModifier<T> pModifier, final T pItem) {
SequenceModifier.this.onHandleModifierFinished(this, pModifier, pItem);
}
}
}
| 34.453947 | 207 | 0.6498 |
bf3b3ee8a63089cb302bcbd8b40d84dc18534449 | 1,705 | package org.springframework.samples.petclinic.service;
import static org.junit.Assert.assertEquals;
import java.util.Collection;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.samples.petclinic.model.Proveedor;
import org.springframework.stereotype.Service;
//tambien testea pedido y linea pedido
@DataJpaTest(includeFilters = @ComponentScan.Filter(Service.class))
public class ProveedorServiceTests {
@Autowired
private ProveedorService proveedorService;
//FindAllNames
@Test
public void listaDeNombresDeProveedores() {
Collection<String> nombres = proveedorService.findAllNames();
assertEquals(4, nombres.size());
}
//FindProveedorByName
@Test
public void esBuscarProveedor() {
Proveedor test = proveedorService.findByName("Makro");
assertEquals("Makro", test.getName());
}
//EsIgual
@Test
public void esIgualProveedorTest() {
assertEquals(proveedorService.esIgual("Makro"),true);
assertEquals(proveedorService.esIgual("Codi"),false);
}
@Test
public void findAllNames() {
assertEquals(proveedorService.findAllNames().size(),4);
}
@Test
public void findActivosNameTest() {
assertEquals(proveedorService.findActivosName().size(), 4);
}
@Test
public void findActivosTest() {
String name=proveedorService.findActivos()
.iterator().next().getName();
assertEquals(name, "Makro");
}
@Test
public void findProveedorByNameTest() {
int id=proveedorService.findByName("Makro").getId();
assertEquals(id, 1);
}
}
| 24.014085 | 71 | 0.76305 |
153b8859d6dad13a2aa8be2d557be843e77cd6c0 | 584 | package com.google.android.gms.internal.ads;
/* compiled from: com.google.android.gms:play-services-ads@@19.4.0 */
final /* synthetic */ class zzawx implements zzaxf {
static final zzaxf zzdya = new zzawx();
private zzawx() {
}
public final Object zza(zzbiq zzbiq) {
String currentScreenName = zzbiq.getCurrentScreenName();
if (currentScreenName != null) {
return currentScreenName;
}
String currentScreenClass = zzbiq.getCurrentScreenClass();
return currentScreenClass != null ? currentScreenClass : "";
}
}
| 30.736842 | 69 | 0.662671 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.