text
stringlengths 10
2.72M
|
|---|
/*
* Copyright (c) 2019, inoshi
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.inoshi.narumi;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import net.inoshi.narumi.common.transformation.ZonedDateTimeTransformer;
import net.inoshi.narumi.service.message.MessageService;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import java.time.ZonedDateTime;
import java.util.concurrent.Executors;
/**
* @author vocan
* @since 30.07.2019
*/
public final class Narumi {
private final MessageService messageService;
public Narumi(final String token) {
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.API_URL)
.client(new OkHttpClient().newBuilder()
.addInterceptor(chain -> chain.proceed(chain.request().newBuilder().addHeader("Authorization", "Bot " + token).build())).build())
.addConverterFactory(JacksonConverterFactory.create(new ObjectMapper()
.registerModule(new SimpleModule()
.addSerializer(ZonedDateTime.class, new ZonedDateTimeTransformer.Serializer())
.addDeserializer(ZonedDateTime.class, new ZonedDateTimeTransformer.Deserializer()))))
.callbackExecutor(Executors.newFixedThreadPool(4))
.build();
this.messageService = retrofit.create(MessageService.class);
}
public MessageService getMessageService() {
return this.messageService;
}
}
|
package backjoon.stack;
import java.io.*;
import java.util.Stack;
public class Backjoon1874 {
private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
private static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
int n = Integer.parseInt(br.readLine());
if(solve(n)) bw.write(sb.toString());
else bw.write("NO");
bw.close();
br.close();
}
public static boolean solve(int n) throws IOException {
Stack<Integer> stk = new Stack<>();
int curVal = 1;
while(n-- > 0){
int num = Integer.parseInt(br.readLine());
if(num >= curVal){
for(int i = curVal; i <= num; i++){
stk.push(i);
sb.append("+\n");
}
curVal = num + 1;
}
else if(stk.peek() != num) return false;
stk.pop();
sb.append("-\n");
}
return true;
}
}
|
/*
* UniTime 3.2 - 3.5 (University Timetabling Application)
* Copyright (C) 2008 - 2013, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.unitime.timetable.form.ExamCbsForm;
import org.unitime.timetable.security.SessionContext;
import org.unitime.timetable.security.rights.Right;
import org.unitime.timetable.solver.exam.ExamSolverProxy;
import org.unitime.timetable.solver.exam.ui.ExamConflictStatisticsInfo;
import org.unitime.timetable.solver.service.SolverService;
/**
* @author Tomas Muller
*/
@Service("/ecbs")
public class ExamCbsAction extends Action {
@Autowired SessionContext sessionContext;
@Autowired SolverService<ExamSolverProxy> examinationSolverService;
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
ExamCbsForm myForm = (ExamCbsForm) form;
// Check Access
sessionContext.checkPermission(Right.ExaminationConflictStatistics);
// Read operation to be performed
String op = (myForm.getOp()!=null?myForm.getOp():request.getParameter("op"));
if (op==null) op="Refresh";
if ("Change".equals(op)) {
sessionContext.getUser().setProperty("Ecbs.limit", String.valueOf(myForm.getLimit()));
sessionContext.getUser().setProperty("Ecbs.type", String.valueOf(myForm.getTypeInt()));
} else {
myForm.reset(mapping,request);
myForm.setTypeInt(Integer.parseInt(sessionContext.getUser().getProperty("Ecbs.type", String.valueOf(ExamCbsForm.sDefaultType))));
myForm.setLimit(Double.parseDouble(sessionContext.getUser().getProperty("Ecbs.limit", String.valueOf(ExamCbsForm.sDefaultLimit))));
}
ExamConflictStatisticsInfo cbs = null;
if (examinationSolverService.getSolver() != null)
cbs = examinationSolverService.getSolver().getCbsInfo();
if (cbs != null) {
request.setAttribute("cbs", cbs);
} else {
if (examinationSolverService.getSolver() == null)
request.setAttribute("warning", "No examination data are loaded into the solver, conflict-based statistics is not available.");
else
request.setAttribute("warning", "Conflict-based statistics is not available at the moment.");
}
return mapping.findForward("show");
}
}
|
package estructurasdecontrol;
import java.util.Scanner;
public class imprimenumerocaracteres {
//Esta mierda imprime caracteres dependiendo de cuanto pongas.
public static void main(String[] args)
{
Scanner entrada = new Scanner(System.in);
System.out.println("Introduce la altura");
int alto=entrada.nextInt();
System.out.println("El largo");
int largo=entrada.nextInt();
for (int i=1; i<=alto; i++)
{System.out.println("");
for(int j=0; j<=largo; j++)
{
System.out.print("*");
}
}
}
}
|
package com.gxuwz.attend.entity;
/**
* Admin entity. @author MyEclipse Persistence Tools
*/
public class Admin implements java.io.Serializable {
// Fields
private String adminId;
private String adminPwd;
private String adminType;
// Constructors
/** default constructor */
public Admin() {
}
/** minimal constructor */
public Admin(String adminId) {
this.adminId = adminId;
}
/** full constructor */
public Admin(String adminId, String adminPwd, String adminType) {
this.adminId = adminId;
this.adminPwd = adminPwd;
this.adminType = adminType;
}
// Property accessors
public String getAdminId() {
return this.adminId;
}
public void setAdminId(String adminId) {
this.adminId = adminId;
}
public String getAdminPwd() {
return this.adminPwd;
}
public void setAdminPwd(String adminPwd) {
this.adminPwd = adminPwd;
}
public String getAdminType() {
return this.adminType;
}
public void setAdminType(String adminType) {
this.adminType = adminType;
}
}
|
package algorithm.baekjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class _1992_QuadTree {
static int N;
static char[][] map;
public static void main(String[] args) throws IOException {
//입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
map = new char[N][N];
for (int i = 0; i < N; i++) {
char[] tmp = br.readLine().toCharArray();
for (int j = 0; j < N; j++) {
map[i][j] = tmp[j];
}
}
System.out.println(quadCompress(N, 0, N - 1, 0, N - 1));
}
// 1 2
// 3 4 의 4로 분할한다고 생각한다
// return 타입을 String으로!
private static String quadCompress(int size, int rowStart, int rowEnd, int colStart, int colEnd) {
if (size == 1) {
// 굳이 part를 사용할 필요 없이 이 크기는 1이므로 rowStart, colStart가 map의 특정 인덱스가 됨
return Character.toString(map[rowStart][colStart]);
}
// 4분할 실시
int midr = (rowStart + rowEnd) / 2;
int midc = (colStart + colEnd) / 2;
int half = size / 2;
String part1 = quadCompress(half, rowStart, midr, colStart, midc); // 1
String part2 = quadCompress(half, rowStart, midr, midc + 1, colEnd); // 2
String part3 = quadCompress(half, midr + 1, rowEnd, colStart, midc); // 3
String part4 = quadCompress(half, midr + 1, rowEnd, midc + 1, colEnd); // 4
// part1.length() == 1이 있는 이유?
// length가 1보다 큰 경우에는 재귀적으로 쌓여온 문자열들을 가지고 있는 상태이므로 함부로 파트 2,3,4를 제외시킬 수 없다
if (part1.length() == 1 && part1.equals(part2) && part2.equals(part3) && part3.equals(part4)) {
return part1;
} else {
StringBuilder sb = new StringBuilder();
sb.append("(").append(part1).append(part2).append(part3).append(part4).append(")");
return sb.toString();
}
}
}
/*
8
11110000
11110000
00011100
00011100
11110000
11110000
11110011
11110011
answer: ((110(0101))(0010)1(0001))
*/
|
/*
Dois carros (X e Y) partem em uma mesma direção. O carro X sai com velocidade constante de 60 Km/h e o carro Y sai com
velocidade constante de 90 Km/h.
Em uma hora (60 minutos) o carro Y consegue se distanciar 30 quilômetros do carro X, ou seja, consegue se afastar um
quilômetro a cada 2 minutos.
Leia a distância (em Km) e calcule quanto tempo leva (em minutos) para o carro Y tomar essa distância do outro carro.
Entrada
O arquivo de entrada contém um número inteiro.
Saída
Imprima o tempo necessário seguido da mensagem "minutos".
Exemplo de Entrada Exemplo de Saída
30 60 minutos
110 220 minutos
7 14 minutos
*/
import java.util.Scanner;
public class exc1016 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int distancia = scanner.nextInt();
int tempo = 2;
int minutos;
minutos = distancia * tempo;
System.out.println(minutos + " minutos ");
scanner.close();
}
}
|
/* */ package datechooser.view.appearance.swing;
/* */
/* */ import datechooser.view.appearance.CellAppearance;
/* */ import java.awt.Color;
/* */ import java.awt.Component;
/* */ import java.awt.Font;
/* */ import java.awt.Graphics2D;
/* */ import java.awt.Insets;
/* */ import javax.swing.ButtonModel;
/* */ import javax.swing.JButton;
/* */ import javax.swing.border.Border;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class ButtonPainter
/* */ implements Painter, SwingCellAttributes
/* */ {
/* */ private JButton button;
/* */ private ButtonModel model;
/* */
/* */ public ButtonPainter()
/* */ {
/* 28 */ setButton(new JButton("?"));
/* 29 */ this.model = this.button.getModel();
/* 30 */ this.button.setMargin(new Insets(2, 2, 2, 2));
/* 31 */ this.button.setOpaque(true);
/* */ }
/* */
/* */ public JButton getButton() {
/* 35 */ return this.button;
/* */ }
/* */
/* */ public void setButton(JButton button) {
/* 39 */ this.button = button;
/* */ }
/* */
/* */ public void setText(String text) {
/* 43 */ this.button.setText(text);
/* */ }
/* */
/* */ public void setFont(Font font) {
/* 47 */ this.button.setFont(font);
/* */ }
/* */
/* */ public Font getFont() {
/* 51 */ return this.button.getFont();
/* */ }
/* */
/* */ public void setTextColor(Color color) {
/* 55 */ this.button.setForeground(color);
/* */ }
/* */
/* */ public void updateUI() {
/* 59 */ this.button.updateUI();
/* */ }
/* */
/* */ public void setSize(int width, int height) {
/* 63 */ this.button.setSize(width, height);
/* */ }
/* */
/* */ public void paint(Graphics2D g) {
/* 67 */ this.button.paint(g);
/* */ }
/* */
/* */ public Border getBorder() {
/* 71 */ return this.button.getBorder();
/* */ }
/* */
/* */ public void setPressed(boolean pressed) {
/* 75 */ this.model.setPressed(pressed);
/* 76 */ this.model.setArmed(pressed);
/* */ }
/* */
/* */ public void setEnabled(boolean enabled) {
/* 80 */ this.model.setEnabled(enabled);
/* */ }
/* */
/* */ public Color getTextColor() {
/* 84 */ return this.button.getForeground();
/* */ }
/* */
/* */ public Object clone() {
/* 88 */ return new ButtonPainter();
/* */ }
/* */
/* */ public void assign(CellAppearance newAppearance) {}
/* */
/* */ public Component getComponent(Component c)
/* */ {
/* 95 */ return this.button;
/* */ }
/* */ }
/* Location: /home/work/vm/shared-folder/reverse/ketonix/KetonixUSB-20170310.jar!/datechooser/view/appearance/swing/ButtonPainter.class
* Java compiler version: 5 (49.0)
* JD-Core Version: 0.7.1
*/
|
package gui;
import game.TextOutput;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class PlayerPanelHoverListener implements MouseListener{
PlayerPanel caller;
public PlayerPanelHoverListener(PlayerPanel caller)
{
this.caller = caller;
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
caller.setHover(true);
repaint();
}
@Override
public void mouseExited(MouseEvent e) {
caller.setHover(false);
repaint();
}
private void repaint()
{
caller.revalidate();
caller.repaint();
}
}
|
package org.maven.ide.eclipse.io;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import junit.framework.TestSuite;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.maven.ide.eclipse.authentication.AuthFacade;
import org.sonatype.tests.http.runner.junit.Junit3SuiteConfiguration;
import org.sonatype.tests.http.runner.annotations.Configurators;
import org.sonatype.tests.http.server.jetty.configurations.DefaultSuiteConfigurator;
import org.sonatype.tests.http.server.jetty.configurations.SslSuiteConfigurator;
import org.sonatype.tests.http.server.api.ServerProvider;
@Configurators( { DefaultSuiteConfigurator.class, SslSuiteConfigurator.class } )
public class UrlFetcherTest
extends AbstractIOTest
{
private UrlFetcher fetcher;
@Override
public void setUp()
throws Exception
{
super.setUp();
fetcher = new UrlFetcher();
}
/*
* Tests the error thrown when a file is not found.
*/
public void testHttpOpenstreamFileNotFound()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + "/nonExistentFile" );
try
{
readstream( fetcher.openStream( address, new NullProgressMonitor(), AuthFacade.getAuthService(), null ) );
fail( "NotFoundException should be thrown." );
}
catch ( NotFoundException e )
{
assertTrue( e.getMessage(), e.getMessage().contains( String.valueOf( HttpURLConnection.HTTP_NOT_FOUND ) ) );
}
}
/*
* Tests the error thrown when a user does not have permission to access a file.
*/
public void testHttpOpenstreamForbidden()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + SECURE_FILE );
try
{
readstream( fetcher.openStream( address, new NullProgressMonitor(), AuthFacade.getAuthService(), null ) );
fail( "UnauthorizedException should be thrown." );
}
catch ( UnauthorizedException e )
{
assertTrue( e.getMessage(), e.getMessage().contains( String.valueOf( HttpURLConnection.HTTP_UNAUTHORIZED ) ) );
}
}
/*
* Tests the contents of a file remote file
*/
public void testHttpOpenStream()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + FILE_PATH );
assertEquals( readstream( new FileInputStream( "resources/file.txt" ) ),
readstream( fetcher.openStream( address, new NullProgressMonitor(), AuthFacade.getAuthService(),
null ) ) );
}
/*
* Tests that the authentication header contains both a username and password.
*/
public void testHttpUsernameAndPasswordSent()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + FILE_PATH );
addRealmAndURL( "testUsernameAndPasswordSent", address.toString(), "username", "password" );
readstream( fetcher.openStream( address, new NullProgressMonitor(), AuthFacade.getAuthService(), null ) );
assertAuthentication( "username", "password", server.getRecordedHeaders( FILE_PATH ) );
}
/*
* Tests that the authentication header only contains a username.
*/
public void testHttpUsernameOnly()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + FILE_PATH );
addRealmAndURL( "testUsernameOnly", address.toString(), "username", "" );
readstream( fetcher.openStream( address, new NullProgressMonitor(), AuthFacade.getAuthService(), null ) );
assertAuthentication( "username", "", server.getRecordedHeaders( FILE_PATH ) );
}
/*
* Tests that the authentication header only contains a password.
*/
public void testHttpPasswordOnly()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + FILE_PATH );
addRealmAndURL( "testPasswordOnly", address.toString(), "", "password" );
readstream( fetcher.openStream( address, new NullProgressMonitor(), AuthFacade.getAuthService(), null ) );
assertAuthentication( "", "password", server.getRecordedHeaders( FILE_PATH ) );
}
/*
* Tests that no header is set for anonymous authentication.
*/
public void testHttpAnonymous()
throws Exception
{
URI address = URI.create( server.getHttpUrl() + FILE_PATH );
addRealmAndURL( "testAnonymous", address.toString(), "", "" );
readstream( fetcher.openStream( address, new NullProgressMonitor(), AuthFacade.getAuthService(), null ) );
assertNull( "No Auth header should be set",
server.getRecordedHeaders( FILE_PATH ).get( "Authorization" ) );
}
/*
* Tests reading a stream from a local file.
*/
public void testFileOpenStream()
throws Exception
{
assertEquals( readstream( new FileInputStream( "resources/file.txt" ) ),
readstream( fetcher.openStream( new File( RESOURCES, "file.txt" ).toURI(), monitor,
AuthFacade.getAuthService(), null ) ) );
}
@Override
public void configureProvider( ServerProvider provider )
{
provider().addAuthentication( "/secured/*", "BASIC" );
provider().addUser( VALID_USERNAME, PASSWORD );
super.configureProvider( provider );
}
public static TestSuite suite()
throws Exception
{
return Junit3SuiteConfiguration.suite( UrlFetcherTest.class );
}
}
|
package com.legalzoom.api.test.dto;
public class OverallRulesStatusByClientIdDTO implements DTO{
private String requestid;
private String ruleType;
public String getRuleType() {
return ruleType;
}
public void setRuleType(String ruleType) {
this.ruleType = ruleType;
}
public String getRequestid() {
return requestid;
}
public void setRequestid(String requestid) {
this.requestid = requestid;
}
}
|
package croco.com.yumingluan;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import croco.com.yumingluan.Adapter.JobsAdapter;
import croco.com.yumingluan.bean.Company;
public class DetailActivity extends AppCompatActivity {
TextView textView_name;
TextView textView_item;
TextView textView_url;
List<String> jobs_list=new ArrayList();
ListView listView_jobs;
JobsAdapter jobsAdapter;
Company company;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
textView_name=findViewById(R.id.name);
textView_item=findViewById(R.id.conpany_item);
textView_url=findViewById(R.id.company_url);
listView_jobs=findViewById(R.id.list_jobs);
Bundle bundle=getIntent().getExtras();
String name=bundle.getString("name");
company=(Company) bundle.getSerializable("company");
jobs_list=company.getJob_list();
jobsAdapter=new JobsAdapter(DetailActivity.this,R.layout.jobs,jobs_list);
listView_jobs.setAdapter(jobsAdapter);
textView_name.setText(company.getName());
textView_item.setText(company.getItem()+"");
textView_url.setText(company.getUrl());
}
/**
* 公司网址
* @param v
*/
public void showCompanyHome(View v) {
String url=company.getUrl();
Uri uri=Uri.parse("https:"+company.getUrl());
//进行跳转的intent
Intent intent=new Intent(Intent.ACTION_VIEW,uri);
//进行跳转
startActivity(intent);
}
}
|
package com.tencent.mm.plugin.sns.ui;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import com.tencent.mm.plugin.sns.i.e;
import com.tencent.mm.plugin.sns.i.f;
import com.tencent.mm.plugin.sns.i.g;
import com.tencent.mm.plugin.sns.model.af;
import com.tencent.mm.pluginsdk.ui.a.b;
import com.tencent.mm.sdk.platformtools.c;
import com.tencent.mm.storage.z;
import java.util.List;
class SnsSelectContactDialog$a extends BaseAdapter {
private Context context;
private List<String> dEw;
private int nKI = 0;
final /* synthetic */ SnsSelectContactDialog nZA;
private int type;
public SnsSelectContactDialog$a(SnsSelectContactDialog snsSelectContactDialog, Context context, int i) {
this.nZA = snsSelectContactDialog;
this.dEw = i;
this.context = context;
this.type = 0;
refresh();
}
public final void refresh() {
if (this.dEw == null) {
this.nKI = 0;
} else {
this.nKI = this.dEw.size();
}
this.nKI++;
notifyDataSetChanged();
}
public final int getCount() {
return this.nKI;
}
public final Object getItem(int i) {
return this.dEw.get(i);
}
public final long getItemId(int i) {
return 0;
}
public final View getView(int i, View view, ViewGroup viewGroup) {
SnsSelectContactDialog$b snsSelectContactDialog$b;
View inflate;
if (view == null) {
snsSelectContactDialog$b = new SnsSelectContactDialog$b();
if (this.type == 0) {
inflate = View.inflate(this.context, g.sns_upload_alert_item, null);
} else {
inflate = View.inflate(this.context, g.sns_alert_item, null);
}
snsSelectContactDialog$b.ilX = (ImageView) inflate.findViewById(f.image);
snsSelectContactDialog$b.nZB = (ImageView) inflate.findViewById(f.item_del);
inflate.setTag(snsSelectContactDialog$b);
} else {
snsSelectContactDialog$b = (SnsSelectContactDialog$b) view.getTag();
inflate = view;
}
inflate.setVisibility(0);
if (i == this.nKI - 1) {
snsSelectContactDialog$b.ilX.setBackgroundDrawable(null);
snsSelectContactDialog$b.ilX.setImageResource(e.sns_add_item);
snsSelectContactDialog$b.nZB.setVisibility(8);
if (this.dEw.size() >= z.sOr) {
inflate.setVisibility(8);
}
} else {
snsSelectContactDialog$b.ilX.setBackgroundDrawable(null);
snsSelectContactDialog$b.nZB.setVisibility(0);
if (this.type == 0) {
b.a(snsSelectContactDialog$b.ilX, (String) this.dEw.get(i));
} else {
snsSelectContactDialog$b.ilX.setImageBitmap(c.e((String) this.dEw.get(i), af.byw(), af.byw(), true));
}
}
snsSelectContactDialog$b.ilX.setScaleType(ScaleType.CENTER_CROP);
return inflate;
}
}
|
package ua.babiy.online_store.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ua.babiy.online_store.entity.Cart;
import ua.babiy.online_store.entity.InCartProduct;
import ua.babiy.online_store.entity.Product;
import ua.babiy.online_store.entity.User;
import ua.babiy.online_store.exceptions.StockIsNotEnoughException;
import ua.babiy.online_store.repository.CartRepository;
import ua.babiy.online_store.repository.InCartProductRepository;
import ua.babiy.online_store.repository.ProductRepository;
import ua.babiy.online_store.service.CartService;
import ua.babiy.online_store.service.ProductService;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class CartServiceImpl implements CartService {
final private ProductRepository productRepository;
final private UserServiceImpl userServiceImpl;
final private ProductService productService;
final private CartRepository cartRepository;
final private InCartProductRepository inCartProductRepository;
@Autowired
public CartServiceImpl(ProductRepository productRepository, UserServiceImpl userServiceImpl,
ProductService productService,
CartRepository cartRepository, InCartProductRepository inCartProductRepository) {
this.productRepository = productRepository;
this.userServiceImpl = userServiceImpl;
this.productService = productService;
this.cartRepository = cartRepository;
this.inCartProductRepository = inCartProductRepository;
}
@Transactional
@Override
public void removeProductFromCart(User user, Long productId) {
inCartProductRepository.deleteByCartAndProductId(user.getCart(), productId);
}
// TODO make new Exception for this method and adding quantity
@Transactional
@Override
public void addProductToCart(User user, Long productId) throws Exception {
Product product = productService.findProductById(productId).orElseThrow(Exception::new);
Cart cart = cartRepository.findById(user.getCart().getId()).orElseThrow(Exception::new);
Optional<InCartProduct> optionalInCartProduct = inCartProductRepository.findByCartAndProductId(user.getCart(), productId);
if (optionalInCartProduct.isPresent())
System.out.println("product already in cart");
else {
InCartProduct inCartProduct = new InCartProduct();
inCartProduct.setProduct(product);
inCartProduct.setCart(cart);
inCartProductRepository.save(inCartProduct);
}
}
@Override
public Map<Product, Integer> getAllProductsInCart(User user) {
return inCartProductRepository.findAllByCart(user.getCart()).stream()
.collect(Collectors
.toMap(inCartProduct -> inCartProduct.getProduct(),
productQuantity -> productQuantity.getNeededQuantity()));
}
@Override
public BigDecimal getTotal(Map<Product, Integer> productsWithNeededQuantity) {
return productsWithNeededQuantity.entrySet().stream()
.map(entry -> entry.getKey().getPrice().multiply(BigDecimal.valueOf(entry.getValue())))
.reduce(BigDecimal::add)
.orElse(BigDecimal.ZERO);
}
@Transactional
@Override
public void clearProductsFromCart(User user) {
inCartProductRepository.deleteAllByCart(user.getCart());
}
//TODO make new Exception (Product has not been founded in cart)
@Override
public void updateNeededQuantity(User user, Long productId, Integer neededQuantity) throws Exception {
InCartProduct inCartProduct = inCartProductRepository
.findByCartAndProductId(user.getCart(), productId).orElseThrow(Exception::new);
Product product = productRepository.getOne(productId);
if (neededQuantity <= product.getQuantity()) {
inCartProduct.setNeededQuantity(neededQuantity);
inCartProductRepository.save(inCartProduct);
} else {
throw new StockIsNotEnoughException();
}
}
}
|
import ch02.stacks.*;
import support.LLNode;
public class LinkedStackDriver {
public static void main (String args[]) {
myLinkedStack myStack;
myStack = new myLinkedStack <> ();
//Add five elements to the stack
myStack.push(11);
myStack.push(22);
myStack.push(33);
myStack.push(44);
myStack.push(55);
// Print out the stack and the number of items
System.out.println("Here is what's on the stack: " + myStack.toString());
System.out.println("The stack size is: " + myStack.size());
// Pop some items off the stack and then show remaining items and stack size
myStack.popSome(3); // Change this parameter for testing
System.out.println("Here is what's on the stack: " + myStack.toString());
System.out.println("The stack size is: " + myStack.size());
// // Push some more items on the stack before swapStart
myStack.push(66);
myStack.push(77);
myStack.push(88);
System.out.println("Here is what's on the stack now: " + myStack.toString());
boolean moreThan2 = myStack.swapStart();
if (moreThan2){
System.out.println("There are at least 2 items on the stack so I swapped the top 2.");
System.out.println("Here is what's on the stack now: " + myStack.toString());
}
else
System.out.println("Can't swap the top two items as the stack has less than 2 elements.");
System.out.println((myStack.popTop()) + " just got popped off the stack."); // Pop the top and return top
System.out.println("Here is what's on the stack now: " + myStack.toString());
}
}
|
package myproject.game.services;
import myproject.game.models.dto.SessionDto;
import myproject.game.models.dto.UserDto;
public interface SessionService {
SessionDto generateToken(UserDto userDto);
SessionDto getSessionInfo(String token);
}
|
package com.qty.internalstorageexample;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.FileOutputStream;
import java.io.IOException;
public class InternalStorageExample extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_internal_storage_example);
// The name of the file
String fileName = "my_file.txt";
// String to be written to file
String msg = "Hello World.";
try {
// Create the file and write
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(msg.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package OrientacaoObjetos.ExemploExercicio;
public class Player {
private int life = 100; // vida player
//obrigatoriamente algum objeto do tipo Inimigo vai entrar aqui
public void atacarInimigo(Inimigo inimigo) {
inimigo.life--; // diminuí a vida do Inimigo inserido por atributo
}
}
|
package GUI.BankTellerWindow;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import java.sql.*;
import GUI.BankTellerMonitor.*;
public class customerReportWindow extends JFrame{
private JLabel CustomerName;
private createReportWindow crw;
public customerReportWindow(createReportWindow crw){
this.crw = crw;
}
public void launchCustomerReportWindow() {
this.getContentPane().setLayout(new BoxLayout(this.getContentPane(),BoxLayout.Y_AXIS));
this.setLayout(new FlowLayout());
this.setTitle("");
this.setSize(370, 400);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
CustomerName = new JLabel("Customer Name: " + this.crw.getCname().getText());
this.add(CustomerName);
JLabel Text = new JLabel("Account ID: Account Type: Status:");
this.add(Text);
final String JDBC_DRIVER = "oracle.jdbc.driver.OracleDriver";
final String DB_URL = "jdbc:oracle:thin:@cloud-34-133.eci.ucsb.edu:1521:XE";
final String USERNAME = "fliang";
final String PASSWORD = "123455";
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
System.out.println(this.crw.getCname().getText());
//String sql = "SELECT A.Aid, A.Type, A.Open FROM Account A, Customer C WHERE A.TaxID = C.TaxID AND C.Name = '" + this.crw.getCname().getText() + "'";
String sql = "SELECT O.Aid, A.Type, A.Open FROM Own_by O INNER JOIN Customer C ON C.TaxID = '" + this.crw.getCname().getText() + "' AND O.TaxID = C.TaxID INNER JOIN Account A ON O.Aid = A.Aid";
final DefaultListModel a3 = new DefaultListModel();
System.out.println("succeed");
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String type = "";
type = rs.getString("Type");
a3.addElement(rs.getString("Aid") + " " + type + " " + rs.getString("Open"));
}
final JList ClosedID = new JList(a3);
ClosedID.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ClosedID.setSelectedIndex(0);
JScrollPane ClosedIDScrollPane = new JScrollPane(ClosedID);
ClosedIDScrollPane.setPreferredSize(new Dimension(300, 300));
ClosedIDScrollPane.setAlignmentX(Component.CENTER_ALIGNMENT);
ClosedIDScrollPane.setAlignmentY(Component.CENTER_ALIGNMENT);
this.add(ClosedIDScrollPane);
JButton back = new JButton("Back");
customerReportMonitor crm = new customerReportMonitor(this);
back.setAlignmentX(Component.CENTER_ALIGNMENT);
back.setAlignmentY(Component.CENTER_ALIGNMENT);
back.addActionListener(crm);
this.add(back);
}catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception ea) {
// Handle errors for Class.forName
ea.printStackTrace();
} finally {
// finally block used to close resources
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
} // do nothing
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} // end finally try
}
this.setVisible(true);
}
}
|
package com.example.demo.entity;
import javax.persistence.*;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.HashSet;
import java.util.Set;
@Entity(name ="group_meta")
public class Group {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Size(max = 40)
private String name;
@NotBlank
@Size(max = 100)
private String description;
@ManyToMany(fetch = FetchType.LAZY, cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "group_service",
joinColumns = @JoinColumn(name = "group_id"),
inverseJoinColumns = @JoinColumn(name = "service_id"))
private Set<Service> services = new HashSet<>();
public Group(@NotBlank @Size(max = 40) String name, @NotBlank @Size(max = 100) String description, Set<Service> services) {
this.name = name;
this.description = description;
this.services = services;
}
public Group() {}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public void setServices(Set<Service> services) {
this.services = services;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Set<Service> getServices() {
return services;
}
public void addService(Service service) {
services.add(service);
}
}
|
package com.mctoybox.toybox.classes;
import org.bukkit.event.Listener;
import org.getspout.spoutapi.player.SpoutPlayer;
import com.mctoybox.toybox.MainClass;
import com.mctoybox.toybox.exceptions.PlayerNotAllowedClassException;
import com.mctoybox.toybox.util.Permissions;
public abstract class ClassBase implements Listener {
protected MainClass mainClass;
protected String className;
protected ClassType classRef;
protected Permissions permRequired;
protected ClassBase(MainClass mainClass, String ClassName, Permissions permRequired) {
this.mainClass = mainClass;
this.className = ClassName;
this.classRef = ClassType.getByName(className);
this.permRequired = permRequired;
mainClass.getServer().getPluginManager().registerEvents(this, mainClass);
}
public abstract void assignPlayerToClass(SpoutPlayer player) throws PlayerNotAllowedClassException;
}
|
package com.demo.modules.base.service;
import com.demo.common.entity.R;
import com.demo.modules.base.entity.SysAreaEntity;
import java.util.List;
import java.util.Map;
/**
* 行政区域
*
* @author Centling Techonlogies
* @email xxx@demo.com
* @url www.demo.com
* @date 2017年8月18日 下午3:40:18
*/
public interface SysAreaService {
List<SysAreaEntity> listAreaByParentCode(String areaCode);
R listAreaByParentCode(Map<String, Object> params);
R saveArea(SysAreaEntity area);
R getAreaById(Long areaId);
R updateArea(SysAreaEntity area);
R batchRemoveArea(Long[] id);
}
|
package avex.models;
import java.util.HashMap;
public class AthleteWINSDictionary {
public HashMap<String, AthleteWINTeamStats> getAthleteWINSDictionary() {
return AthleteWINSDictionary;
}
public void setAthleteWINSDictionary(HashMap<String, AthleteWINTeamStats> athleteWINSDictionary) {
AthleteWINSDictionary = athleteWINSDictionary;
}
private HashMap<String,AthleteWINTeamStats> AthleteWINSDictionary;
}
|
package Task2;
import lombok.SneakyThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.*;
class SymbolIOTest {
HashMap<String, Integer> expected;
@BeforeEach
void setUp() {
String[] keys = {"abstract ", "continue ", "for ", "new ", "switch ", "assert ", "default ", "goto ",
"package ", "synchronized ", "boolean ", "do ", "if ", "private ", "this ", "break;", "double ", "implements ",
"protected ", "throw ", "byte ", "else ", "import ", "public ", "throws ", "case ", "enum ", "instanceof ", "return ",
"transient ", "catch ", "extends ", "int ", "short ", "try ", "char ", "final ", "interface ", "static ", "void ",
"class ", "finally ", "long ", "strictfp ", "volatile ", "const ", "float ", "native ", "super ", "while "};
expected = new HashMap<>();
for(String key : keys)
expected.put(key, 0);
}
@Test
@SneakyThrows
void calculateKeyWords() {
expected.put("for ", 3);
expected.put("new ", 2);
expected.put("package ", 1);
expected.put("if ", 3);
expected.put("private ", 1);
expected.put("break;", 1);
expected.put("import ", 5);
expected.put("public ", 5);
expected.put("return ", 3);
expected.put("int ", 2);
expected.put("void ", 2);
expected.put("class ", 1);
expected.put("while ", 1);
assertEquals(expected, SymbolIO.calculateKeyWords());
}
}
|
package com.rile.methotels.pages;
public class Error404
{
}
|
package com.java.smart_garage.serviceTest;
import com.java.smart_garage.contracts.repoContracts.UserRepository;
import com.java.smart_garage.exceptions.DuplicateEntityException;
import com.java.smart_garage.exceptions.EntityNotFoundException;
import com.java.smart_garage.exceptions.UnauthorizedOperationException;
import com.java.smart_garage.models.User;
import com.java.smart_garage.services.UserServiceImpl;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Optional;
import static com.java.smart_garage.Helpers.*;
import static com.java.smart_garage.Helpers.createMockUser;
@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
@Mock
UserRepository mockUserRepository;
@InjectMocks
UserServiceImpl service;
@Test
public void getAllUsers_Should_Return_AllUsers() {
List<User> result = service.getAllUsers();
result.add(createMockUser());
// Assert
Mockito.verify(mockUserRepository, Mockito.timeout(1)).getAllUsers();
}
@Test
public void getById_Should_Return_Correct_User() {
// Arrange
Mockito.when(mockUserRepository.getById(1)).
thenReturn(createMockUser());
//Act
User result = service.getById(1);
// Assert
Assertions.assertEquals(1, result.getUserId());
}
@Test
public void create_Should_Throw_When_User_Exists() {
// Arrange
var mockUserCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
var mockUserEmployee = createMockUser();
// Act, Assert
Assertions.assertThrows(DuplicateEntityException.class, () -> service.create(mockUserCustomer, mockUserEmployee));
}
@Test
public void create_Should_Throw_When_UserIsCustomer() {
// Arrange
var mockUserCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
var mockUserEmployee = createMockUser();
// Act, Assert
Assertions.assertThrows(UnauthorizedOperationException.class, () -> service.create(mockUserCustomer, mockUserEmployee));
}
@Test
public void create_Should_Pass_When_Put_Correct_User() {
// Arrange
var mockUserCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
var mockUserEmployee = createMockUser();
Mockito.when(mockUserRepository.getById(mockUserEmployee.getUserId()))
.thenThrow(new EntityNotFoundException("User", "id", mockUserEmployee.getUserId()));
// Act, Assert
Assertions.assertDoesNotThrow(() -> service.create(mockUserCustomer, mockUserEmployee));
}
@Test
public void update_Should_Pass_When_Put_Correct_User() {
// Arrange
var mockUserCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
var mockUserEmployee = createMockUser();
// Act, Assert
Assertions.assertDoesNotThrow(() -> service.update(mockUserCustomer, mockUserEmployee));
}
@Test
public void update_Should_Throw_When_Put_Not_Existing_Id() {
// Arrange
var mockUserCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
var mockUserEmployee = createMockUser();
Mockito.when(mockUserRepository.getById(mockUserEmployee.getUserId()))
.thenThrow(new EntityNotFoundException("User", "id", mockUserEmployee.getUserId()));
// Act, Assert
Assertions.assertThrows(EntityNotFoundException.class, () -> service.update(mockUserCustomer, mockUserEmployee));
}
@Test
public void update_Should_Throw_When_UserIsCustomer() {
// Arrange
var mockUserCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
var mockUserAnotherCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
// Act, Assert
Assertions.assertThrows(UnauthorizedOperationException.class, () -> service.update(mockUserCustomer, mockUserAnotherCustomer));
}
@Test
public void delete_Should_Throw_When_UserIsCustomer() {
// Arrange
var mockUserCustomer = createMockUser();
var mockUser = createMockUser();
mockUser.setUserType(createMockUserTypeCustomer());
// Act, Assert
Assertions.assertThrows(UnauthorizedOperationException.class, () -> service.delete(mockUserCustomer.getUserId(), mockUser));
}
@Test
public void delete_Should_Pass_When_User_Exists() {
// Arrange
var mockUserCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
var mockUser = createMockUser();
// Act, Assert
Assertions.assertDoesNotThrow(() -> service.delete(mockUserCustomer.getUserId(),mockUser));
}
@Test
public void filter_Should_Pass_When_Put_Correct_Data() {
// Arrange
var mockUserEmployee = createMockUser();
// Act, Assert
Assertions.assertDoesNotThrow(() -> service.filterCustomers(Optional.empty(), Optional.of("Georgiev"),
Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), mockUserEmployee));
}
@Test
public void filter_Should_Throw_When_UserIsCustomer() {
// Arrange
var mockUserCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
// Act, Assert
Assertions.assertThrows(UnauthorizedOperationException.class, () -> service.filterCustomers(Optional.empty(), Optional.of("Georgiev"),
Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), mockUserCustomer));
}
/*
@Test
public void sortByName_Should_Pass_When_Put_Correct_Data() {
// Arrange
var mockUserEmployee = createMockUser();
// Act, Assert
Assertions.assertDoesNotThrow(() -> service.sortCustomersByName(true, mockUserEmployee));
}
@Test
public void sortByName_Should_Throw_When_UserIsCustomer() {
// Arrange
var mockUserCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
// Act, Assert
Assertions.assertThrows(UnauthorizedOperationException.class, () -> service.sortCustomersByName(false, mockUserCustomer));
}
@Test
public void sortByVisits_Should_Pass_When_Put_Correct_Data() {
// Arrange
var mockUserEmployee = createMockUser();
// Act, Assert
Assertions.assertDoesNotThrow(() -> service.sortCustomersByVisits(false, mockUserEmployee));
}
@Test
public void sortByVisits_Should_Throw_When_UserIsCustomer() {
// Arrange
var mockUserCustomer = createMockUser();
mockUserCustomer.setUserType(createMockUserTypeCustomer());
// Act, Assert
Assertions.assertThrows(UnauthorizedOperationException.class, () -> service.sortCustomersByVisits(true, mockUserCustomer));
}
*/
}
|
import java.util.*;
import java.math.*;
class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
BigInteger a = BigInteger.ONE;
BigInteger b = BigInteger.ONE;
for(long i = N; i>N-M;i--){
a = a.multiply(new BigInteger(String.valueOf(i)));
}
for(long i = 1;i<=M;i++){
b = b.multiply(new BigInteger(String.valueOf(i)));
}
BigInteger answer = a.divide(b);
System.out.println(answer);
}
}
|
package com.kprojekt.alonespace.data;
import java.util.Random;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.opengl.font.IFont;
import com.kprojekt.alonespace.data.model.AloneSpaceModel;
import com.kprojekt.locale.Locale;
/**
* @author Krzysiek Bobnis
*/
public class Core
{
public static final int widthInMeters = 400;
public static int heightInMeters;
public static final float PixelsPerMeterInGraphics = 4f;
public static boolean fullScreen = true;
public static ScreenOrientation orientation = ScreenOrientation.LANDSCAPE_SENSOR;
public static Random random = new Random( System.currentTimeMillis() );
public static RatioResolutionPolicy ratioResPolicy;
public static IFont font;
public static Settings settings = new Settings();
public static Locale locale;
public static AloneSpaceModel model;
public static DataBase db;
public static PlayerProfile loggedProfile;
public static float pixelsToMeters( float pixels )
{
return pixels / Core.PixelsPerMeterInGraphics;
}
public static float metersToPixels( float meters )
{
return meters * Core.PixelsPerMeterInGraphics;
}
}
|
package bonimed.vn;
import android.app.Application;
import com.androidnetworking.AndroidNetworking;
/**
* Created by mac on 10/24/17.
*/
public class BonimedApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
AndroidNetworking.initialize(getApplicationContext());
}
}
|
/*
* Copyright (C), 2013-2015, 上海汽车集团股份有限公司
* FileName: CookieParam.java
* Author: baowenzhou
* Date: 2016年03月22日 下午5:27:08
* Description: //模块目的、功能描述
* History: //修改记录
* <author> <time> <version> <desc>
* 修改人姓名 修改时间 版本号 描述
*/
package com.xjf.wemall.annotation;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Cookie对象参数声明<BR>
*
* 需要CookieObject的方法参数上添加此annotation<BR>
* @see com.saic.wemall.api.entity.common.CookieObject
*
* @author baowenzhou
*/
@Target({PARAMETER})
@Retention(RUNTIME)
public @interface CookieParam {
}
|
package com.zhowin.miyou;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.zhowin.base_library.base.BaseApplication;
import com.zhowin.miyou.db.manager.DBManager;
import com.zhowin.miyou.main.activity.MainActivity;
import com.zhowin.miyou.rongIM.IMManager;
import com.zhowin.miyou.rongIM.manager.ThreadManager;
/**
* author : zho
* date :2020/9/19
* desc :
*/
public class MiApplication extends BaseApplication {
/**
* 应用是否在后台
*/
private boolean isAppInForeground;
private String lastVisibleActivityName;
private Intent nextOnForegroundIntent;
private boolean isMainActivityIsCreated;
@Override
public void onCreate() {
super.onCreate();
if (!getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {
return;
}
DBManager.initDao();
IMManager.getInstance().init(this);
//初始化线程管理
ThreadManager.getInstance().init();
// 监听 App 前后台变化
observeAppInBackground();
}
private void observeAppInBackground() {
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (activity instanceof MainActivity) {
isMainActivityIsCreated = true;
}
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
// 当切换为前台时启动预设的优先显示界面
if (isMainActivityIsCreated && !isAppInForeground && nextOnForegroundIntent != null) {
activity.startActivity(nextOnForegroundIntent);
nextOnForegroundIntent = null;
}
lastVisibleActivityName = activity.getClass().getSimpleName();
isAppInForeground = true;
}
@Override
public void onActivityPaused(Activity activity) {
String pauseActivityName = activity.getClass().getSimpleName();
/*
* 介于 Activity 生命周期在切换画面时现进行要跳转画面的 onResume,
* 再进行当前画面 onPause,所以当用户且到后台时肯定会为当前画面直接进行 onPause,
* 同过此来判断是否应用在前台
*/
if (pauseActivityName.equals(lastVisibleActivityName)) {
isAppInForeground = false;
}
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
if (activity instanceof MainActivity) {
isMainActivityIsCreated = false;
}
}
});
}
/**
* 当前 App 是否在前台
*
* @return
*/
public boolean isAppInForeground() {
return isAppInForeground;
}
/**
* 设置当 App 切换为前台时启动的 intent,该 intent 在启动后情况
*
* @param intent
*/
public void setOnAppForegroundStartIntent(Intent intent) {
nextOnForegroundIntent = intent;
}
/**
* 获取最近设置的未触发的启动 intent
*
* @return
*/
public Intent getLastOnAppForegroundStartIntent() {
return nextOnForegroundIntent;
}
/**
* 判断是否进入到了主界面
*
* @return
*/
public boolean isMainActivityCreated() {
return isMainActivityIsCreated;
}
}
|
package dao.mapper;
import constants.FieldsConstants;
import entity.DiagnosisStatus;
import entity.UserHasDiagnosis;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UHDMapper implements EntityMapper<UserHasDiagnosis> {
@Override
public UserHasDiagnosis map(ResultSet resultSet) throws SQLException {
return new UserHasDiagnosis()
.setUser_id(resultSet.getInt(FieldsConstants.UHD_USER_ID))
.setDiagnosis_id(resultSet.getInt(FieldsConstants.UHD_DIAGNOSIS_ID))
.setDate(resultSet.getString((FieldsConstants.UHD_DATE)))
.setStatus(DiagnosisStatus.valueOf(resultSet.getString((FieldsConstants.UHD_STATUS))))
.setTreat_id(resultSet.getInt(FieldsConstants.UHD_TREAT_ID));
}
@Override
public int unMap(PreparedStatement statement, UserHasDiagnosis entity) throws SQLException {
int index = 0;
statement.setInt(index++,entity.getUser_id());
statement.setInt(index++,entity.getDiagnosis_id());
statement.setString(index++,entity.getDate());
statement.setString(index++,String.valueOf(entity.getStatus()));
statement.setInt(index++,entity.getTreat_id());
return index;
}
}
|
package com.codegym.checkinhotel.service.hoteldetail;
import com.codegym.checkinhotel.model.HotelDetails;
import com.codegym.checkinhotel.repository.IHotelDetailRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class HotelDetailService implements IHotelDetailService{
@Autowired
IHotelDetailRepository hotelDetailRepository;
@Override
public Iterable<HotelDetails> findAll() {
return hotelDetailRepository.findAll();
}
@Override
public Optional<HotelDetails> findById(Long id) {
return hotelDetailRepository.findById(id);
}
@Override
public HotelDetails save(HotelDetails hotelDetails) {
return hotelDetailRepository.save(hotelDetails);
}
@Override
public void remove(Long id) {
hotelDetailRepository.deleteById(id);
}
}
|
package com.example.admin.recyclerview;
/**
* Created by ADMIN on 9/1/2017.
*/
public class product {
public String tenSP;
public int Hinh;
public product() {
}
public product(String tenSP,int hinh) {
this.tenSP = tenSP;
Hinh = hinh;
}
public String getTenSP() {
return tenSP;
}
public void setTenSP(String tenSP) {
this.tenSP = tenSP;
}
public int getHinh() {
return Hinh;
}
public void setHinh(int hinh) {
Hinh = hinh;
}
}
|
package com.wt.jiaduo.utils;
/**
* 内存中的变量
* @author wu
*
*/
public class InMemeryVariable {
//序号的生成方式目前未确定先返回一个假值
// TODO
public static long rand=1;
}
|
package com.thoughtworks.data.repository.database;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
/**
* Created on 14-06-2018.
*/
public class CategoryInfo extends RealmObject {
@PrimaryKey
private int id;
private String name;
public CategoryInfo() {
}
public CategoryInfo(final int id, final String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public static final class ColumnName {
public static final String ID = "id";
public static final String NAME = "name";
}
}
|
/*
* Copyright 2017 University of Michigan
*
* 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 edu.umich.verdict.relation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import edu.umich.verdict.VerdictContext;
import edu.umich.verdict.datatypes.TableUniqueName;
import edu.umich.verdict.exceptions.VerdictException;
import edu.umich.verdict.relation.expr.ColNameExpr;
import edu.umich.verdict.relation.expr.Expr;
import edu.umich.verdict.relation.expr.FuncExpr;
import edu.umich.verdict.relation.expr.OrderByExpr;
import edu.umich.verdict.relation.expr.SelectElem;
import edu.umich.verdict.relation.expr.TableNameExpr;
import edu.umich.verdict.util.VerdictLogger;
/**
* ApproxRelation indicates what samples should be used for computing the answer
* to the original query. ApproxRelation includes some helper functions for
* retrieving sample-related information.
*
* @author Yongjoo Park
*
*/
public abstract class ApproxRelation extends Relation {
protected final String partitionSizeAlias = "__vpsize";
protected ExactRelation original;
public ApproxRelation(VerdictContext vc) {
super(vc);
approximate = true;
original = null;
}
protected void setOriginalRelation(ExactRelation r) {
original = r;
}
protected ExactRelation getOriginalRelation() {
return original;
}
public String sourceTableName() {
if (this instanceof ApproxSingleRelation) {
ApproxSingleRelation r = (ApproxSingleRelation) this;
if (r.getAlias() != null) {
return r.getAlias();
} else {
return r.getSampleName().getTableName();
}
} else {
return this.getAlias();
}
}
/*
* Aggregations
*/
public ApproxGroupedRelation groupby(String group) {
String[] tokens = group.split(",");
return groupby(Arrays.asList(tokens));
}
public ApproxGroupedRelation groupby(List<String> group_list) {
List<Expr> groups = new ArrayList<Expr>();
for (String t : group_list) {
groups.add(Expr.from(vc, t));
}
return new ApproxGroupedRelation(vc, this, groups);
}
/*
* Approx
*/
public ApproxAggregatedRelation agg(Object... elems) {
return agg(Arrays.asList(elems));
}
public ApproxAggregatedRelation agg(List<Object> elems) {
List<SelectElem> se = new ArrayList<SelectElem>();
// first insert possible groupby list
if (this instanceof ApproxGroupedRelation) {
List<Expr> groupby = ((ApproxGroupedRelation) this).getGroupby();
for (Expr g : groupby) {
se.add(new SelectElem(vc, g));
}
}
// now insert aggregation list
for (Object e : elems) {
se.add(SelectElem.from(vc, e.toString()));
}
return new ApproxAggregatedRelation(vc, this, se);
}
@Override
public ApproxAggregatedRelation count() throws VerdictException {
return agg(FuncExpr.count());
}
@Override
public ApproxAggregatedRelation sum(String expr) throws VerdictException {
return agg(FuncExpr.sum(Expr.from(vc, expr)));
}
@Override
public ApproxAggregatedRelation avg(String expr) throws VerdictException {
return agg(FuncExpr.avg(Expr.from(vc, expr)));
}
@Override
public ApproxAggregatedRelation countDistinct(String expr) throws VerdictException {
return agg(FuncExpr.countDistinct(Expr.from(vc, expr)));
}
/**
* Properly scale all aggregation functions so that the final answers are
* correct. For ApproxAggregatedRelation: returns a AggregatedRelation instance
* whose result is approximately correct. For ApproxSingleRelation,
* ApproxJoinedRelation, and ApproxFilteredRelaation: returns a select statement
* from sample tables. The rewritten sql doesn't have much meaning if not used
* by ApproxAggregatedRelation.
*
* @return
*/
public ExactRelation rewrite() {
if (vc.getConf().errorBoundMethod().equals("nobound")) {
return rewriteForPointEstimate();
} else if (vc.getConf().errorBoundMethod().equals("subsampling")) {
return rewriteWithSubsampledErrorBounds();
} else if (vc.getConf().errorBoundMethod().equals("bootstrapping")) {
return rewriteWithBootstrappedErrorBounds();
} else {
VerdictLogger.error(this,
"Unsupported error bound computation method: " + vc.getConf().get("verdict.error_bound_method"));
return null;
}
}
public abstract ExactRelation rewriteForPointEstimate();
/**
* Creates an exact relation that computes approximate aggregates and their
* error bounds using subsampling.
*
* If a sample plan does not include any sample tables, it will simply be exact
* answers; thus, no error bounds are necessary.
*
* If a sample plan includes at least one sample table in the table sources,
* there must exists a partition column (__vpart by default).
* {@link ExactRelation#partitionColumn()} finds and returns an appropriate
* column name for a given source relation. See the method for details on how
* the partition column of a table is determined. Note that the partition
* columns are defined for rewritten relations.
*
* @return
*/
public ExactRelation rewriteWithSubsampledErrorBounds() {
VerdictLogger.error(this,
String.format("Calling a method, %s, on unappropriate class", "rewriteWithSubsampledErrorBounds()"));
return null;
}
/**
* Internal method for
* {@link ApproxRelation#rewriteWithSubsampledErrorBounds()}.
*
* @return
*/
protected abstract ExactRelation rewriteWithPartition();
// These functions are moved to ExactRelation
// This is because partition column name could be only properly resolved after
// the rewriting to the
// exact relation is finished.
// protected String partitionColumnName() {
// return vc.getDbms().partitionColumnName();
// }
// returns effective partition column name for a possibly joined table.
// protected abstract ColNameExpr partitionColumn();
public ExactRelation rewriteWithBootstrappedErrorBounds() {
return null;
}
/**
* Computes an appropriate sampling probability for a particular aggregate
* function. For uniform random sample, returns the ratio between the sample
* table and the original table. For universe sample, if the aggregate function
* is COUNT, AVG, SUM, returns the ratio between the sample table and the
* original table. if the aggregate function is COUNT-DISTINCT, returns the
* sampling probability. For stratified sample, this method returns the sampling
* probability only for the joined tables.
*
* Verdict sample rules.
*
* For COUNT, AVG, and SUM, uniform random samples, universe samples, stratified
* samples, or no samples can be used. For COUNT-DISTINCT, universe sample,
* stratified samples, or no samples can be used. For stratified samples, the
* distinct number of groups is assumed to be limited.
*
* Verdict join rules.
*
* (uniform, uniform) -> uniform (uniform, stratified) -> stratified (uniform,
* universe) -> uniform (uniform, no sample) -> uniform (stratified, stratified)
* -> stratified (stratified, universe) -> no allowed (stratified, no sample) ->
* stratified (universe, universe) -> universe (only when the columns on which
* samples are built coincide) (universe, no sample) -> universe
*
* @param f
* @return
*/
@Deprecated
protected abstract List<Expr> samplingProbabilityExprsFor(FuncExpr f);
/**
* rough sampling probability, which is obtained from the sampling params.
*
* @return
*/
public abstract double samplingProbability();
public abstract double cost();
/**
* The returned contains the tuple-level sampling probability. For universe and
* uniform samples, this is basically the ratio of the sample size to the
* original table size.
*
* @return
*/
public abstract Expr tupleProbabilityColumn();
/**
* The returned column contains
*
* @return
*/
public abstract Expr tableSamplingRatio();
/**
* Returns an effective sample type of this relation.
*
* @return One of "uniform", "universe", "stratified", "nosample".
*/
public abstract String sampleType();
// protected abstract List<ColNameExpr> accumulateSamplingProbColumns();
/**
* Returns a set of columns on which a sample is created. Only meaningful for
* stratified and universe samples.
*
* @return
*/
protected abstract List<String> getColumnsOnWhichSamplesAreCreated();
/**
* Pairs of original table name and a sample table name. This function does not
* inspect subqueries. The substitution expression is an alias (thus, string
* type).
*
* @return
*/
protected abstract Map<TableUniqueName, String> tableSubstitution();
/**
* Returns true if any of the table sources include an non-nosample relation.
*
* @return
*/
protected abstract boolean doesIncludeSample();
/*
* order by and limit
*/
public ApproxRelation orderby(String orderby) {
String[] tokens = orderby.split(",");
List<OrderByExpr> o = new ArrayList<OrderByExpr>();
for (String t : tokens) {
o.add(OrderByExpr.from(vc, t));
}
return new ApproxOrderedRelation(vc, this, o);
}
public ApproxRelation limit(long limit) {
return new ApproxLimitedRelation(vc, this, limit);
}
/*
* sql
*/
@Override
public String toSql() {
ExactRelation r = rewrite();
return r.toSql();
}
@Override
public String toString() {
return toStringWithIndent("");
}
public abstract boolean equals(ApproxRelation o);
protected abstract String toStringWithIndent(String indent);
/*
* Helpers
*/
protected double confidenceIntervalMultiplier() {
double confidencePercentage = vc.getConf().errorBoundConfidenceInPercentage();
if (confidencePercentage == 0.999) {
return 3.291;
} else if (confidencePercentage == 0.995) {
return 2.807;
} else if (confidencePercentage == 0.99) {
return 2.576;
} else if (confidencePercentage == 0.95) {
return 1.96;
} else if (confidencePercentage == 0.90) {
return 1.645;
} else if (confidencePercentage == 0.85) {
return 1.44;
} else if (confidencePercentage == 0.80) {
return 1.282;
} else {
VerdictLogger.warn(this,
String.format("Unsupported confidence: %s%%. Uses the default 95%%.", confidencePercentage * 100));
return 1.96; // 95% by default.
}
}
protected Expr exprWithTableNamesSubstituted(Expr expr, Map<TableUniqueName, String> sub) {
TableNameReplacerInExpr v = new TableNameReplacerInExpr(vc, sub);
return v.visit(expr);
}
protected static Pair<List<Expr>, ApproxRelation> allPrecedingGroupbys(ApproxRelation r) {
List<Expr> groupbys = new ArrayList<Expr>();
ApproxRelation t = r;
while (true) {
if (t instanceof ApproxGroupedRelation) {
groupbys.addAll(((ApproxGroupedRelation) t).getGroupby());
t = ((ApproxGroupedRelation) t).getSource();
} else {
break;
}
}
return Pair.of(groupbys, t);
}
/**
* @param tabExpr Restricted to this table.
* @return A list of all column names.
*/
abstract public List<ColNameExpr> getAssociatedColumnNames(TableNameExpr tabExpr);
}
|
package kr.hs.gshs.blebeaconprotocollibrary;
/**
* Created by kjh on 2017-12-09.
*/
public enum StructTypes {
TEXT_UNCOMPRESSED("Text (Uncompressed)"),
TEXT_RLE("Text (Run-length Encoding)"),
TEXT_HUFFMAN_CODING("Text (Huffman Coding)"),
REGULAR_URL("Regular URL"),
GOOGL_URL("goo.gl URL"),
DEVICE_NAME("Device Name"),
SERVICE_NAME("Service Name");
private String displayName;
private static StructTypes[] values = values();
StructTypes(String displayName) {
this.displayName = displayName;
}
public String displayName() {
return displayName;
}
public static StructTypes fromOrdinal(int ordinal) {
return values[ordinal];
}
public static StructTypes[] getValues() {
return values;
}
}
|
package com.feecalculator.feecalculatorApp.Service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import com.feecalculator.feecalculatorApp.Model.InputTransactions;
import com.feecalculator.feecalculatorApp.Repository.InputTransactionsRepository;
@Component
public class ReadFileService {
@Autowired
InputTransactionsRepository inputRepository;
public static InputTransactions getTransactionsFromFile(String[] transactions) {
InputTransactions inputTransactions = new InputTransactions();
inputTransactions.setExternal_Transaction_Id(transactions[0]);
inputTransactions.setClient_Id(transactions[1]);
inputTransactions.setSecurity_Id(transactions[2]);
inputTransactions.setTransaction_Type(transactions[3]);
Date date1 = null;
try {
date1 = new SimpleDateFormat("MM/dd/yyyy").parse(transactions[4]);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
inputTransactions.setTransaction_Date(date1);
inputTransactions.setMarket_Value(BigDecimal.valueOf(Double.parseDouble(transactions[5])));
inputTransactions.setPriority_Flag(transactions[6]);
return inputTransactions;
}
public List<InputTransactions> readInputTransactionFromFile() {
// String fileName = "InputData.csv";
//File resource = new ClassPathResource("data/employees.dat").getFile();
String fileName = "C:\\Users\\Public\\InputData.csv";
List<InputTransactions> inputTransactionList = new ArrayList<InputTransactions>();
String line = "";
BufferedReader br = null;
try {
int count = 1;
br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine()) != null) {
String[] transactions = line.split(",");
if (count > 1) {
InputTransactions inputTrans = ReadFileService.getTransactionsFromFile(transactions);
inputTransactionList.add(inputTrans);
inputRepository.save(inputTrans);
}
count++;
}
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException s) {
System.out.println(s);
}
return inputTransactionList;
}
}
|
package prj.betfair.api.betting.navigation;
import java.util.List;
public class BaseItem implements Item{
private Item parent;
private String name;
private String type;
private String id;
private List<Item> children;
@Override
public String getName() {
return name;
}
@Override
public String getType() {
return type;
}
@Override
public String getId() {
return id;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setType(String type) {
this.type = type;
}
@Override
public void setId(String id) {
this.id = id;
}
@Override
public List<Item> getChildren() {
return this.children;
}
@Override
public void setChildren(List<Item> children) {
this.children = children;
}
@Override
public Item getParent() {
return parent;
}
@Override
public void setParent(Item item) {
parent = item;
}
@Override
public String toString(){
return name;
}
}
|
package de.madjosz.adventofcode.y2020;
import static org.junit.jupiter.api.Assertions.assertEquals;
import de.madjosz.adventofcode.AdventOfCodeUtil;
import java.util.List;
import org.junit.jupiter.api.Test;
class Day21Test {
@Test
void day21() {
List<String> lines = AdventOfCodeUtil.readLines(2020, 21);
Day21 day21 = new Day21(lines);
assertEquals(2485, day21.a1());
assertEquals("bqkndvb,zmb,bmrmhm,snhrpv,vflms,bqtvr,qzkjrtl,rkkrx", day21.a2());
}
@Test
void day21_exampleInput() {
List<String> lines = AdventOfCodeUtil.readLines(2020, 21, "test");
Day21 day21 = new Day21(lines);
assertEquals(5, day21.a1());
assertEquals("mxmxvkd,sqjhc,fvjkl", day21.a2());
}
}
|
package snakesandladders.main;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import javax.swing.JPanel;
import snakesandladders.Squares.LadderSquare;
import snakesandladders.Squares.SnakeSquare;
import snakesandladders.Squares.Square;
/**
* The panel that is used to draw the
* snakes and the ladders.
* @author Zac
*/
public class BoardPanel extends JPanel {
private Snake snake;
private Ladder ladder;
private Board board;
/**
* Constructor, gets and creates a reference of the
* board.
* @param board
*/
public BoardPanel(Board board) {
setOpaque(false);
snake = new Snake();
ladder = new Ladder();
this.board = board;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
for (Square boardSquare : board.getBoardSquares()) {
double width = board.getBoardSquares()[1].getWidth() * 0.5;
double height = board.getBoardSquares()[1].getHeight() * 0.5;
if (boardSquare instanceof SnakeSquare) {
int dest_index = ((SnakeSquare) boardSquare).getDest().getNumber(); //cast boardSquare to snake, getDest returns object, get number the number of target dest
int source_index = boardSquare.getNumber(); //same for source
Point2D dest = board.getBoardSquares()[dest_index].getLocation(); //find the location on screen (Point2D) coords
Point2D source = board.getBoardSquares()[source_index].getLocation(); //same for source
dest.setLocation(dest.getX() + width, dest.getY() + height); //set their coords to be in the middle of the square
source.setLocation(source.getX() + width, source.getY() + height); //->>-
snake.setPoints(source, dest); //add to snake so it can draw
snake.draw(g2);
} else if (boardSquare instanceof LadderSquare) {
int dest_index = ((LadderSquare) boardSquare).getDest().getNumber();
int source_index = boardSquare.getNumber();
Point2D dest = board.getBoardSquares()[dest_index].getLocation();
Point2D source = board.getBoardSquares()[source_index].getLocation();
dest.setLocation(dest.getX() + width, dest.getY() + height);
source.setLocation(source.getX() + width, source.getY() + height);
ladder.drawLadderBetweenPoints(g2, source, dest);
}
}
g2.dispose();
}
}
|
package com.example.shashankshekhar.application3s1.Graph;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.support.annotation.IntegerRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import com.androidplot.Plot;
import com.androidplot.util.PixelUtils;
import com.androidplot.xy.BoundaryMode;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;
import com.androidplot.xy.XYStepMode;
import com.example.shashankshekhar.application3s1.R;
import com.example.shashankshekhar.smartcampuslib.HelperClass.CommonUtils;
import com.example.shashankshekhar.smartcampuslib.ServiceAdapter;
import org.json.JSONException;
import org.json.JSONObject;
import org.osmdroid.views.overlay.compass.CompassOverlay;
import java.text.DecimalFormat;
import java.util.Observable;
import java.util.Observer;
public class DynamicGraphActivity extends AppCompatActivity {
private XYPlot dynamicPlot;
private MyPlotUpdater plotUpdater;
SampleDynamicXYDatasource data;
private Thread myThread;
private String topicName;
boolean resetTimeStamp = true;
Integer initalTimeStamp;
ServiceAdapter serviceAdapter;
private class MyPlotUpdater implements Observer {
Plot plot;
public MyPlotUpdater(Plot plot) {
this.plot = plot;
}
@Override
public void update(Observable o, Object arg) {
plot.redraw();
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Integer timeStamp = 0;
Integer waterLevel =0;
String messageString = intent.getStringExtra("message");
// break it based on comma and first is timeStamp, second
String[] strArray = messageString.split(",");
if (strArray.length != 3) {
return;
}
timeStamp = Integer.parseInt(strArray[0]);
String waterLevelStr = (strArray[2].split(":"))[1];
Double waterLvl = Double.parseDouble(waterLevelStr);
waterLevel = waterLvl.intValue();
if (resetTimeStamp == true) {
initalTimeStamp = timeStamp;
resetTimeStamp = false;
}
data.updateXY((timeStamp - initalTimeStamp), waterLevel);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_graph);
serviceAdapter = ServiceAdapter.getServiceAdapterinstance(getApplicationContext());
CommonUtils.printLog("onCreateCalled, DynamicGraphActivity");
setupDynamicPlot();
topicName = getIntent().getStringExtra("topicName");
if (topicName != null) {
setupBroadcastReceiver();
}
}
@Override
public void onStart() {
if(topicName != null) {
serviceAdapter.subscribeToTopic(topicName);
}
super.onStart();
}
@Override
public void onResume() {
setupBroadcastReceiver();
super.onResume();
}
@Override
public void onPause() {
try {
unregisterReceiver(broadcastReceiver);
} catch (IllegalArgumentException ex)
{
// do nothing. already unregistered or not registered at all
}
super.onPause();
}
@Override
public void onStop() {
serviceAdapter.unsubscribeFromTopic(topicName);
try {
unregisterReceiver(broadcastReceiver);
} catch (IllegalArgumentException ex)
{
// do nothing. already unregistered or not registered at all
}
super.onStop();
}
@Override
public void onDestroy() {
super.onDestroy();
// kill the plotter thread
data.stopPlotterThread();
}
private void setupDynamicPlot () {
dynamicPlot = (XYPlot)findViewById(R.id.dynamicXYPlot);
plotUpdater = new MyPlotUpdater(dynamicPlot);
// set up whole numbers in domain
dynamicPlot.getGraphWidget().setDomainValueFormat(new DecimalFormat("0"));
data = new SampleDynamicXYDatasource();
SampleDynamicSeries sine1Series = new SampleDynamicSeries(data, 0, "Plot 1");
LineAndPointFormatter formatter1 = new LineAndPointFormatter(
Color.rgb(0, 0, 0), null, null, null);
formatter1.getLinePaint().setStrokeJoin(Paint.Join.ROUND);
formatter1.getLinePaint().setStrokeWidth(10);
dynamicPlot.addSeries(sine1Series,
formatter1);
// hook up the plotUpdater to the data model:
data.addObserver(plotUpdater);
data.startPlotting();// starts a new thread
// thin out domain tick labels so they dont overlap each other:
dynamicPlot.setDomainStepMode(XYStepMode.INCREMENT_BY_VAL);
dynamicPlot.setDomainStepValue(5);
dynamicPlot.setRangeStepMode(XYStepMode.INCREMENT_BY_VAL);
dynamicPlot.setRangeStepValue(1);
dynamicPlot.setRangeValueFormat(new DecimalFormat("###.#"));
// uncomment this line to freeze the range boundaries:
dynamicPlot.setRangeBoundaries(0, 10, BoundaryMode.FIXED);
// create a dash effect for domain and range grid lines:
DashPathEffect dashFx = new DashPathEffect(
new float[] {PixelUtils.dpToPix(3), PixelUtils.dpToPix(3)}, 0);
dynamicPlot.getGraphWidget().getDomainGridLinePaint().setPathEffect(dashFx);
dynamicPlot.getGraphWidget().getRangeGridLinePaint().setPathEffect(dashFx);
}
public void setupBroadcastReceiver () {
if (topicName == null) {
return;
}
resetTimeStamp = true;
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(topicName);
try {
registerReceiver(broadcastReceiver, intentFilter);
} catch (IllegalArgumentException ex) {
// recevier already registered
}
}
class SampleDynamicSeries implements XYSeries {
private SampleDynamicXYDatasource datasource;
private int seriesIndex;
private String title;
public SampleDynamicSeries(SampleDynamicXYDatasource datasource, int seriesIndex, String title) {
this.datasource = datasource;
this.seriesIndex = seriesIndex;
this.title = title;
}
@Override
public String getTitle() {
return title;
}
@Override
public int size() {
return datasource.getItemCount(seriesIndex);
}
@Override
public Number getX(int index) {
Number number = datasource.getX(seriesIndex, index);
// CommonUtils.printLog("getX called in SampleDynamicSeries with index: "+ Integer.toString
// (index) + "with val: "+ number);
return number;
}
@Override
public Number getY(int index) {
Number num = datasource.getY(seriesIndex, index);
// CommonUtils.printLog("getY called in SampleDynamicSerieswith index: "+ Integer.toString(index));
return num;
}
}
}
|
package com.tencent.tencentmap.mapsdk.a;
import android.graphics.Rect;
public interface iw {
Rect a(hh hhVar);
boolean a(hh hhVar, float f, float f2);
void b(hs hsVar, hh hhVar);
}
|
package org.surkovp.pythonliterals;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Util {
public static @NotNull List<String> getLiterals(@NotNull String line) {
char[] chars = line.toCharArray();
boolean isEscaping = false;
boolean isSmallQuote = false;
boolean isBigQuote = false;
List<String> literals = new ArrayList<>();
StringBuilder currentQuote = new StringBuilder();
for (char c : chars) {
if (isEscaping) {
isEscaping = false;
if (isSmallQuote || isBigQuote) {
currentQuote.append(c);
}
continue;
}
if (c == '\'') {
if (isSmallQuote) {
literals.add(currentQuote.toString());
currentQuote.setLength(0);
}
isSmallQuote = !isSmallQuote;
continue;
}
if (c == '"') {
if (isBigQuote) {
literals.add(currentQuote.toString());
currentQuote.setLength(0);
}
isBigQuote = !isBigQuote;
continue;
}
if (c == '\\') {
isEscaping = true;
continue;
}
if (isSmallQuote || isBigQuote) {
currentQuote.append(c);
continue;
}
if (c == '#') {
break;
}
}
return literals;
}
public static Map<String, List<Integer>> getLiteralLines(@NotNull Stream<@NotNull String> lines) {
class Literal {
private final String literal;
private final int line;
public Literal(@NotNull String literal, int line) {
this.line = line;
this.literal = literal;
}
public int getLine() {
return line;
}
@NotNull
public String getLiteral() {
return literal;
}
}
return lines.flatMap(new Function<String, Stream<Literal>>() {
private int lineNumber = 0;
@Override
public Stream<Literal> apply(String line) {
final int lineNumberFinalCopy = lineNumber;
Stream<Literal> literals = getLiterals(line).stream()
.map(literal -> new Literal(literal, lineNumberFinalCopy));
lineNumber++;
return literals;
}
}).collect(Collectors.groupingBy(
Literal::getLiteral,
Collectors.mapping(Literal::getLine, Collectors.toList())
));
}
public static Map<String, List<Integer>> getLiteralLinesOccurringAtLeastOnce(@NotNull Stream<@NotNull String> lines) {
return getLiteralLines(lines).entrySet().stream()
.filter(entry -> entry.getValue().size() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
}
|
package com.dazhi.authdemo.modules.auth.vo;
import lombok.Data;
import java.io.Serializable;
@Data
public class CenterVO implements Serializable {
private static final long serialVersionUID = 1L;
public CenterVO() {}
public CenterVO(String centerId, String centerName, String jxsNum, String hsrNum, String orderNum) {
this.centerId = centerId;
this.centerName = centerName;
this.jxsNum = jxsNum;
this.hsrNum = hsrNum;
this.orderNum = orderNum;
}
// 中心id
private String centerId;
// 中心 名称
private String centerName;
// 经销商 88码
private String jsxAccount;
// 经销商name
private String jsxName;
// 经销商 数量
private String jxsNum;
// 合伙人数量
private String hsrNum;
// 带单数量
private String orderNum;
// 积分
private String score;
// 合伙人账号
private String hhrAccount;
// 用户姓名
private String userName;
// 电话
private String telephone;
// 时间
private String time;
// 地址
private String address;
// 密码
private String password;
// 状态 0 未审核 1 已审核 2 未审核
private String status;
// 成交单id
private Integer dealId;
private String ProductName;
}
|
package com.framework.util;
import java.sql.Connection;
import java.sql.DriverManager;
import com.framework.servlet.PropertiesManger;
public class JdbcUtil {
public static Connection getConn(){
Connection connection = null;
try{
Class.forName(PropertiesManger.get("jdbc.driver"));
connection = DriverManager.getConnection(PropertiesManger.get("jdbc.url"), PropertiesManger.get("jdbc.username"), PropertiesManger.get("jdbc.password"));
}catch(Exception e){
e.printStackTrace();
}
return connection;
}
}
|
package com.adelphia2004.tomcat;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
String data = "997f743f-ac3b-4e0d-83e4-5210c657a1092014-03-15 \n" +
"00:00:142014-03-15 00:06:55SUCCESS 50366436189285597836 997f743f-ac3b-4e0d-83e4-5210c657a1092014-03-15 \n" +
"00:00:142014-03-15 00:06:55SUCCESS 50366436189285597836";
String regex = "(.{36})([0-9]{4}-[0-9]{2}-[0-9]{2}\\s+[0-9]{2}:[0-9]{2}:[0-9]{2})([0-9]{4}-[0-9]{2}-[0-9]{2}\\s+[0-9]{2}:[0-9]{2}:[0-9]{2})([A-Z]\\w+)\\s+(\\d{10})(\\d{10})";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(data);
while(m.find()){
String result = m.group();
}
}
}
|
package pack1;
public class Example1 {
String carname="BMW";
static String bikename="Yamaha";
int carspeed=10;
static int bikespeed=20;
public void m1(){
System.out.println(carname+carspeed+bikename+bikespeed);
}
public static void m2(){
System.out.println(bikename+bikespeed+new Example1().carname+new Example1().carspeed);
}
}
|
package com.mx.profuturo.bolsa.model.service.vacancies.vo;
import com.mx.profuturo.bolsa.model.vo.common.BasicCatalogVO;
public class ContenidoCodigoBolsaVO {
private String bolsaTrabajo;
private String codigo;
private String contenido;
public String getBolsaTrabajo() {
return bolsaTrabajo;
}
public void setBolsaTrabajo(String bolsaTrabajo) {
this.bolsaTrabajo = bolsaTrabajo;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getContenido() {
return contenido;
}
public void setContenido(String contenido) {
this.contenido = contenido;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.netcracker.financeapp.service;
import java.util.ArrayList;
import org.springframework.stereotype.Service;
import com.netcracker.financeapp.dao.BankCardMapper;
import com.netcracker.financeapp.mapping.BankCard;
@Service
public class BankCardService {
BankCardMapper bankCardMapper;
public void setBankCardMapper(BankCardMapper bankCardMapper) {
this.bankCardMapper = bankCardMapper;
}
public BankCard getBankCardByNumber(String cardNumber) {
return bankCardMapper.getBankCardByNumber(cardNumber);
}
public ArrayList<String> getBankCardNumbers() {
return bankCardMapper.getBankCardNumbers();
}
public int insertBankCard(int amount,int cvv,int expireMonth,int expireYear,
String cardNumber, String ownerName, String ownerSurname){
return bankCardMapper.insertBankCard(amount,cvv,expireMonth,expireYear,cardNumber,
ownerName, ownerSurname);
}
public int getAllMoney(){
ArrayList<Integer> allMoneyList = bankCardMapper.getAllMoney();
int allMoney = 0;
for(int oneCardMoney : allMoneyList){
allMoney+=oneCardMoney;
}
return allMoney;
}
public int editCardAmount(int idCard, int newAmount){
return bankCardMapper.editCardAmount(idCard, newAmount);
}
public int deleteCardByNumber(String cardNumber){
return bankCardMapper.deleteCardByNumber(cardNumber);
}
public BankCard getBankCardById(int idCard){
return bankCardMapper.getBankCardById(idCard);
}
}
|
package Iface;
public class Profile {
private String cellphone_number;
private String relationship;
private String city;
private String job;
private String born;
private String description;
public void Set_CellPhoneNumber(String number)
{
this.cellphone_number = number;
}
public String Get_CellPhoneNumber()
{
return cellphone_number;
}
public void Set_relationship(String relationship)
{
this.relationship = relationship;
}
public String Get_relationship()
{
return relationship;
}
public void Set_city(String city)
{
this.city = city;
}
public String Get_city()
{
return city;
}
public void Set_job(String job)
{
this.job = job;
}
public String Get_job()
{
return job;
}
public void Set_born(String born)
{
this.born = born;
}
public String Get_born()
{
return born;
}
public void Set_description(String description)
{
this.description = description;
}
public String Get_description()
{
return description;
}
}
|
/*
* Copyright (c) 2015. ReviewBot by Jeremy Tidwell is licensed under a Creative Commons
* Attribution-NonCommercial-ShareAlike 4.0 International License.
* Based on a work at https://github.com/necanthrope/ReviewBot.
*/
package reviewbot.repository.metadata;
import org.hibernate.*;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Repository;
import reviewbot.dto.metadata.AwardDTO;
import reviewbot.dto.metadata.GenreDTO;
import reviewbot.entity.Book;
import reviewbot.entity.GenreMap;
import reviewbot.entity.metadata.Genre;
import reviewbot.repository.AbstractRepository;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jtidwell on 4/7/2015.
*/
@Repository
@Transactional
public class GenreRepository extends AbstractRepository<Genre> {
@Override
public Genre create(Genre genre) {
getCurrentSession().save(genre);
return genre;
}
@Override
public List<Genre> readAll() {
return _entityManager.createQuery("from Genre").getResultList();
}
@Override
public List<Genre> readRange(Integer offset, Integer length) {
final Integer len = length;
final Integer offs = offset;
List<Genre> genreEntities = (List<Genre>) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Query q = getSessionFactory().getCurrentSession().createQuery("from Genre");
q.setFirstResult(offs);
q.setMaxResults(len);
return q.list();
}
});
return genreEntities;
}
@Override
public Genre readOne(Integer id) {
return (Genre) getCurrentSession().get(Genre.class, id);
}
@Override
@SuppressWarnings("unchecked")
public List<Genre> readList(Integer[] idsIn) {
final Integer[] ids = idsIn;
List<Genre> genreEntities = (List<Genre>) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria criteria = session.createCriteria(Genre.class);
criteria.add(Restrictions.in("id",ids));
criteria.addOrder(Order.asc("name"));
return criteria.list();
}
});
return genreEntities;
}
@Override
public Genre update(Genre inGenre) {
Genre genre = (Genre) getCurrentSession().get(Genre.class, inGenre.getId());
genre.setName(inGenre.getName());
genre.setDescription(inGenre.getDescription());
getCurrentSession().merge(genre);
return genre;
}
@Override
public void delete(Integer id) {
Genre genre = (Genre) getCurrentSession().get(Genre.class, id);
if (genre != null) {
getCurrentSession().delete(genre);
getCurrentSession().flush();
}
}
}
|
package com.ricex.cartracker.androidrequester.request.user;
import com.ricex.cartracker.androidrequester.request.AbstractRequest;
import com.ricex.cartracker.androidrequester.request.ApplicationPreferences;
import com.ricex.cartracker.androidrequester.request.response.RequestResponse;
import com.ricex.cartracker.androidrequester.request.exception.RequestException;
import com.ricex.cartracker.androidrequester.request.type.BooleanResponseType;
import com.ricex.cartracker.common.auth.AuthToken;
/** A Server Request to login to the server to obtain a Session Token.
*
* The login is performed with a previously aquired Authentication Token
*
* @author Mitchell Caisse
*
*/
public class LoginTokenRequest extends AbstractRequest<Boolean> {
/** The user's username */
private final String username;
/** The user's authentication token */
private final String token;
/** Creates a new instance of Login Token Request
*
* @param applicationPreferences
* @param token
*/
public LoginTokenRequest(ApplicationPreferences applicationPreferences, String token) {
this(applicationPreferences, applicationPreferences.getUsername(), token);
}
/** Creates a new instance of Login Token Request
*
* @param token The authorization token to use to login
*/
public LoginTokenRequest(ApplicationPreferences applicationPreferences, String username, String token) {
super(applicationPreferences);
this.username = username;
this.token = token;
}
/** Executes the request
*
* @return The AFTResponse representing the results of the request
* @throws RequestException If an error occurred while making the request
*/
protected RequestResponse<Boolean> executeRequest() throws RequestException {
AuthToken authToken = new AuthToken(username, token, getDeviceUID());
return postForObject(getTokenLoginAddress(), authToken, new BooleanResponseType());
}
}
|
package ar.com.model.domain;
import java.io.Serializable;
import ar.com.model.domain.*;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
@Entity
public class Archivo implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int Id_Archivo;
private String Nombre;
private String Tipo;
private int CantPag;
private String URL;
private double Peso; //expresado en mb
private boolean Publico;
private String fecha;
private boolean Aprobado;
@Column(length=140)
private String Resumen;
private boolean Deleted;
public boolean isDeleted() {
return Deleted;
}
public void setDeleted(boolean deleted) {
Deleted = deleted;
}
@ManyToOne
@JoinColumn(name="Id_Materia")
private Materias materia;
@ManyToOne
@JoinColumn(name="id_Carrera")
private Carreras carrera;
@ManyToOne
@JoinColumn(name="Id_Usuario")
private Usuario user;
public Archivo() {
super();
}
public Archivo(String nombre, String tipo, int cantPag, String uRL, double peso, boolean publico) {
super();
Nombre = nombre;
Tipo = tipo;
CantPag = cantPag;
URL = uRL;
Peso = peso;
Publico = publico;
}
public int getId_Archivo() {
return Id_Archivo;
}
public void setId_Archivo(int id_Archivo) {
Id_Archivo = id_Archivo;
}
public String getNombre() {
return Nombre;
}
public void setNombre(String nombre) {
Nombre = nombre;
}
public String getTipo() {
return Tipo;
}
public void setTipo(String tipo) {
Tipo = tipo;
}
public int getCantPag() {
return CantPag;
}
public void setCantPag(int cantPag) {
CantPag = cantPag;
}
public String getURL() {
return URL;
}
public void setURL(String uRL) {
URL = uRL;
}
public double getPeso() {
return Peso;
}
public void setPeso(double peso) {
Peso = peso;
}
public boolean isPublico() {
return Publico;
}
public void setPublico(boolean publico) {
this.Publico = publico;
}
public Usuario getUser() {
return user;
}
public void setUser(Usuario user) {
this.user = user;
}
public Materias getMateria() {
return materia;
}
public void setMateria(Materias materia) {
this.materia = materia;
}
public Carreras getCarrera() {
return carrera;
}
public void setCarrera(Carreras carrera) {
this.carrera = carrera;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public boolean isAprobado() {
return Aprobado;
}
public void setAprobado(boolean aprobado) {
Aprobado = aprobado;
}
public String getResumen() {
return Resumen;
}
public void setResumen(String resumen) {
Resumen = resumen;
}
}
|
package com.example.watcher;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class Menu extends AppCompatActivity {
private CardView cv_supervisiones;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_menu );
cv_supervisiones = findViewById(R.id.cv_supervisiones);
cv_supervisiones.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =new Intent(Menu.this, Supervisiones.class);
startActivity(intent);
}
});
}
}
|
package com.example.yintangwen.homedemo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
public class MainFragmentActivity extends AppCompatActivity {
private RelativeLayout locLayout;
private RelativeLayout naviLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_fragment);
locLayout = (RelativeLayout)findViewById(R.id.loc_layout);
naviLayout = (RelativeLayout)findViewById(R.id.navi_layout);
}
public void onSwitch(View view){
if (locLayout.getVisibility() == View.VISIBLE){
locLayout.setVisibility(View.GONE);
naviLayout.setVisibility(View.VISIBLE);
}else{
locLayout.setVisibility(View.VISIBLE);
naviLayout.setVisibility(View.GONE);
}
}
}
|
package com.ad.system.service;
import java.util.Set;
public interface SysRoleService {
public Set<String> findRoleNameByUserId(Integer userId);
}
|
package com.plivo.utilities;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.Markup;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.plivo.testbase.TestSetup;
import org.testng.*;
public class CustomListerners extends TestSetup implements ITestListener, ISuiteListener {
public void onFinish(ISuite arg0) {
// TODO Auto-generated method stub
}
public void onStart(ISuite arg0) {
// TODO Auto-generated method stub
}
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
}
public void onStart(ITestContext arg0) {
// TODO Auto-generated method stub
}
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
public void onTestFailure(ITestResult arg0) {
String failureLogg = "This Test case got Failed";
Markup m = MarkupHelper.createLabel(failureLogg, ExtentColor.RED);
testLog.get().log(Status.FAIL, m);
}
public void onTestSkipped(ITestResult arg0) {
String methodName = arg0.getMethod().getMethodName();
String logText = "<b>" + "Test Case:- " + methodName + " Skipped" + "</b>";
Markup m = MarkupHelper.createLabel(logText, ExtentColor.YELLOW);
testLog.get().skip(m);
extent.flush();
}
public void onTestStart(ITestResult arg0) {
String methodName = arg0.getMethod().getMethodName();
System.out.println(methodName.split(".").length);
ExtentTest child = parentTest.get().createNode(methodName);
testLog.set(child);
//testCaseLogger.get().log(Status.INFO, "Starting execution of Test Case:- "+methodName);
testLog.get().info("<b>" + "Starting execution of Test Case:- " + methodName + "</b>");
}
public void onTestSuccess(ITestResult arg0) {
String methodName = arg0.getMethod().getMethodName();
String logText = "<b>" + "Test Case:- " + methodName + " Passed" + "</b>";
Markup m = MarkupHelper.createLabel(logText, ExtentColor.GREEN);
testLog.get().pass(m);
}
}
|
package uk.ac.ed.inf.aqmaps.testUtilities;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Deque;
import java.util.Queue;
import com.mapbox.geojson.Point;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.PrecisionModel;
import org.locationtech.jts.math.Vector2D;
import uk.ac.ed.inf.aqmaps.client.AQSensor;
import uk.ac.ed.inf.aqmaps.client.data.SensorData;
import uk.ac.ed.inf.aqmaps.client.data.W3WAddressData;
import uk.ac.ed.inf.aqmaps.client.data.W3WSquareData;
import uk.ac.ed.inf.aqmaps.pathfinding.Obstacle;
import uk.ac.ed.inf.aqmaps.simulation.Sensor;
import uk.ac.ed.inf.aqmaps.simulation.planning.path.PathSegment;
public class TestUtilities {
public static PrecisionModel precisionModel = new PrecisionModel(PrecisionModel.FLOATING_SINGLE);
public static GeometryFactory gf = new GeometryFactory(precisionModel);
/**
* 7 digit precision epsilon
*/
public static double epsilon = 0.00000001d;
public static void assertPathGoesThroughInOrder(Queue<PathSegment> path,double epsilon,Coordinate ...coordinates){
if(coordinates.length == 0)
return;
int currCoordinateIdx = 0;
PathSegment lastSegment = null;
boolean foundAll = false;
for (PathSegment pathSegment : path) {
lastSegment = pathSegment;
Coordinate currCoordinate = coordinates[currCoordinateIdx];
double distance = currCoordinate.distance(pathSegment.getStartPoint());
if(distance <= epsilon)
currCoordinateIdx += 1;
if(currCoordinateIdx == coordinates.length) {
foundAll = true;
break;
}
}
if(!foundAll
&& currCoordinateIdx == coordinates.length - 1 // if only one coordinate left
&& coordinates[currCoordinateIdx].distance(lastSegment.getEndPoint()) <= epsilon){
foundAll = true;
}
Coordinate unpassedCoordinate = foundAll ? null : coordinates[currCoordinateIdx];
assertTrue(foundAll,"Path does not go through: " + unpassedCoordinate + ", at step:" + currCoordinateIdx);
}
public static void assertPointsConsecutive(Queue<PathSegment> path){
PathSegment previousSegment = null;
for (PathSegment pathSegment : path) {
if(previousSegment != null){
Coordinate previousEnd = previousSegment.getEndPoint();
Coordinate currentStart = pathSegment.getStartPoint();
assertCoordinateEquals(
previousEnd,
currentStart,
epsilon,null);
}
previousSegment = pathSegment;
}
}
public static void assertVectorEquals(Vector2D expected, Vector2D actual, double epsilon, String msg){
assertEquals(expected.getX(), actual.getX(),epsilon,msg == null ?"X component is not the same":msg);
assertEquals(expected.getY(), actual.getY(),epsilon,msg == null ?"Y component is not the same":msg);
}
public static void assertCoordinateEquals(Coordinate expected, Coordinate actual, double epsilon, String msg){
assertVectorEquals(new Vector2D(expected), new Vector2D(actual), epsilon,msg);
}
public static void assertDirectionValid(PathSegment p){
Vector2D vector = new Vector2D(p.getStartPoint(), p.getEndPoint());
double angle = Math.toDegrees(vector.angle()) ;
if(angle < 0){
angle += 360;
}
assertEquals(
(int)((Math.round(angle / 10) * 10) % 360) ,
p.getDirection(),"direction of the path segment is incorrect");
}
public static void assertDirectionValid(int minAngle,int maxAngle,int angleIncrement,PathSegment p){
Vector2D vector = new Vector2D(p.getStartPoint(), p.getEndPoint());
double angle = Math.toDegrees(vector.angle()) ;
if(angle < 0){
angle += 360;
}
int angleRounded = ((int)Math.round(angle) % (maxAngle+1));
int distance = Math.abs(angleRounded - p.getDirection());
assertTrue(
distance <= angleIncrement,
"direction of the path segment is incorrect");
}
public static void assertMoveLengthsEqual(double length,double epsilon,PathSegment... p){
int idx = 0;
for (PathSegment pathSegment : p) {
Vector2D vector = new Vector2D(pathSegment.getStartPoint(),pathSegment.getEndPoint());
assertEquals(length,vector.length(),epsilon,"segment at idx: "+ idx++ + ", has a different length");
}
}
public static void assertDirectionsValid(PathSegment... p){
int i = 0;
for (PathSegment pathSegment : p) {
assertDoesNotThrow(()->{
assertDirectionValid(pathSegment);
},"Direction at idx: " + i++ + " has invalid direction");
}
}
public static void assertDirectionsValid(int minAngle,int maxAngle,int angleIncrement,PathSegment... p){
int i = 0;
for (PathSegment pathSegment : p) {
assertDoesNotThrow(()->{
assertDirectionValid(minAngle,maxAngle,angleIncrement,pathSegment);
},"Direction at idx: " + i++ + " has invalid direction");
}
}
public static void assertIntersectPath(Deque<PathSegment> path, Obstacle obstacle,boolean intersects){
for (PathSegment pathSegment : path) {
var ls = TestUtilities.gf.createLineString(
new Coordinate[]{pathSegment.getStartPoint(),pathSegment.getEndPoint()});
assertTrue(intersects==!obstacle.getShape().disjoint(ls), "obstacle intersects path:" + obstacle);
assertTrue(intersects==obstacle.getShape().intersects(ls)
|| intersects==obstacle.getShape().touches(ls),"obstacle intersects path" + obstacle);
}
}
public static Sensor constructSensor(Coordinate point, float reading, float battery){
Point p = Point.fromLngLat(point.x, point.y);
return new AQSensor(
new SensorData("", battery, reading),
new W3WAddressData("country", new W3WSquareData(), "nearestPlace", p, "w.o.rds", "language", "map"));
}
}
|
package com.e.jobkwetu.Model;
public class Subcounty {
public static final String TABLE_NAME = "subcounty";
public static final String COLUMN_ID = "id";
public static final String COLUMN_SUBCOUNTY = "subcounty";
public static final String COLUMN_TIMESTAMP = "timestamp";
private int id;
private String subcounty;
private String timestamp;
// Create table SQL query
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_SUBCOUNTY + " TEXT,"
+ COLUMN_TIMESTAMP + " DATETIME DEFAULT CURRENT_TIMESTAMP"
+ ")";
public Subcounty() {
}
public Subcounty(int id, String subcounty, String timestamp) {
this.id = id;
this.subcounty = subcounty;
this.timestamp = timestamp;
}
public int getId() {
return id;
}
public String getSubcounty() {
return subcounty;
}
public void setSubcounty(String subcounty) {
this.subcounty = subcounty;
}
public String getTimestamp() {
return timestamp;
}
public void setId(int id) {
this.id = id;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
|
package com.davemorrissey.labs.subscaleview.view;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
class SubsamplingScaleImageView$4 extends SimpleOnGestureListener {
final /* synthetic */ SubsamplingScaleImageView abb;
SubsamplingScaleImageView$4(SubsamplingScaleImageView subsamplingScaleImageView) {
this.abb = subsamplingScaleImageView;
}
public final boolean onSingleTapConfirmed(MotionEvent motionEvent) {
this.abb.performClick();
return true;
}
}
|
package zad1;
public class Point {
private double[] coords;
public Point(double[] coords) {
setCoords(coords);
}
public Point() {
this(new double[2]);//new double[]{0, 0}
}
public Point(Point p) {
this(p.coords);
}
public double[] getCoords() {
double[] temp;
temp = new double[2];
for (int i = 0; i < coords.length; i++) {
temp[i] = coords[i];
}
return temp;
}
public void setCoords(double[] coords) {
if (coords != null && coords.length == 2) {
this.coords = new double[2];
for (int i = 0; i < coords.length; i++){
this.coords[i] = coords[i];
//възможна валидация за положителни стойности
}
} else {
this.coords = new double[2];
}
}
@Override
public String toString() {
return String.format("(%.2f; %.2f)",
coords[0], coords[1]); //(x; y)
}
}
|
package com.mrhan.console;
/**
* 在控制台页面
*/
public class Console {
/**
* 创建一个Dos窗体
* @return
*/
private long createDos(){
return 1;
}
}
|
package sc.water.ustc.action;
import sc.water.ustc.utils.CommonUtils;
public class RegisterAction {
private String userName;
private String password;
public String handleRegister(){
if (CommonUtils.isNotEmpty(this.userName) && CommonUtils.isNotEmpty(this.password)) {
return "success";
} else {
return "failure";
}
}
}
|
package NiuKe;
public class 矩阵路径 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
if(matrix==null||rows<1||cols<1||str==null||matrix.length==0||str.length==0){
return false;
}
boolean [] flagArr = new boolean[rows*cols];
int pathIndex=0;
for(int row = 0;row<rows;row++){
for(int col = 0;col<cols;col++){
if(findPath(matrix, rows, cols, str,pathIndex,row,col,flagArr)){
return true;
}
}
}
return false;
}
public boolean findPath(char[] matrix, int rows, int cols, char[] str,int pathIndex,int row,int col,boolean[] flagArr){
if(pathIndex==str.length){
return true;
}
if(row<rows&&row>=0&&col>=0&&col<cols&&matrix[row*cols+col]==str[pathIndex]&&flagArr[row*cols+col]==false){
pathIndex++;
flagArr[row*cols+col]=true;
boolean result = findPath(matrix, rows, cols, str,pathIndex,row-1,col,flagArr)||
findPath(matrix, rows, cols, str,pathIndex,row+1,col,flagArr)||
findPath(matrix, rows, cols, str,pathIndex,row,col-1,flagArr)||
findPath(matrix, rows, cols, str,pathIndex,row,col+1,flagArr);
if(!result) {//如果在下一个没有找到正确的路径,则要将当前步往回退(即当前这个标志已经访问过的节点要重新标记为没有访问过)
flagArr[row*cols+col]=false;
}
return result;
}else{
return false;
}
}
}
|
package p05.redesign.domain;
import static org.junit.Assert.*;
import java.util.*;
import java.util.concurrent.atomic.*;
import org.junit.*;
import static org.hamcrest.CoreMatchers.*;
public class StatCompilerTest {
@Test
public void responsesByQuestionAnswersCountsByQuestionText() {
StatCompiler stats = new StatCompiler();
List<BooleanAnswer> answers = new ArrayList<>();
answers.add(new BooleanAnswer(1, true));
answers.add(new BooleanAnswer(1, true));
answers.add(new BooleanAnswer(1, true));
answers.add(new BooleanAnswer(1, false));
answers.add(new BooleanAnswer(2, true));
answers.add(new BooleanAnswer(2, true));
Map<Integer,String> questions = new HashMap<>();
questions.put(1, "Tuition reimbursement?");
questions.put(2, "Relocation package?");
Map<String, Map<Boolean,AtomicInteger>> responses =
stats.responsesByQuestion(answers, questions);
assertThat(responses.get("Tuition reimbursement?").
get(Boolean.TRUE).get(), equalTo(3));
assertThat(responses.get("Tuition reimbursement?").
get(Boolean.FALSE).get(), equalTo(1));
assertThat(responses.get("Relocation package?").
get(Boolean.TRUE).get(), equalTo(2));
assertThat(responses.get("Relocation package?").
get(Boolean.FALSE).get(), equalTo(0));
}
}
|
public abstract class Mensagem {
private String login;
private String descricao;
public Mensagem(String login, String descricao) {
this.login = login;
this.descricao = descricao;
}
public String getLogin(){
return this.login;
}
public String getDescricao(){
return this.descricao;
}
protected void setLogin(String login){
this.login = login;
}
@Override
public String toString(){
return String.format("Mensagem de %s %n"
+ "Conteudo: %s %n"
+ "------------- %n", this.login,
this.descricao);
}
}
|
package software.design.consulate.model.dto;
public class StatusChangeDto {
protected String manage;
public StatusChangeDto() {
}
public StatusChangeDto(String manage) {
this.manage = manage;
}
public String getManage() {
return manage;
}
public void setManage(String manage) {
this.manage = manage;
}
}
|
package com.dzz.user.service.config.exception;
import com.dzz.util.response.ResponsePack;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 统一异常处理
* @author dzz
* @version 1.0.0
* @since 2019年07月30 11:40
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 设置响应头信息
* @param response response
*/
private void setResponse(HttpServletResponse response) {
response.setContentType("application/json;charset=UTF-8");
response.setHeader("Content-Type","application/json;charset=UTF-8");
}
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponsePack defaultErrorHandler(HttpServletRequest req, HttpServletResponse response, Exception e) {
setResponse(response);
log.error("出现异常了", e);
ResponsePack responsePack;
if(e instanceof BusinessException) {
responsePack = ResponsePack.fail(e.getMessage());
}else{
responsePack = ResponsePack.fail("系统开小差了,请稍候再试");
}
return responsePack;
}
@ExceptionHandler(AccessDeniedException.class)
public ResponsePack handleAccessDeniedException(HttpServletResponse response) {
setResponse(response);
return ResponsePack.fail("无权限访问");
}
}
|
import com.baizhi.entity.Person;
import com.baizhi.service.PersonService;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* service
* Created by gjp06 on 17.5.17.
*/
class PersonServiceTest {
private ApplicationContext ctx = new ClassPathXmlApplicationContext("/spring.xml");
@Test
void findPerson() {
PersonService service = (PersonService) ctx.getBean("personService");
List<Person> people = service.findPerson(new Person());
for (Person p : people) {
System.out.println(p);
}
}
}
|
/**
*
*/
package de.tixus.eopac.client;
/**
* @author TSP
*
*/
public class Isbn13Validator {
/*
* stolen
* fromhttp://svn.apache.org/viewvc/jakarta/commons/proper/validator/trunk
* /src
* /share/org/apache/commons/validator/routines/ISBNValidator.java?revision
* =487479&view=markup&pathrev=488896
*/
private static final String SEP = "(?:\\-|\\s)";
private static final String GROUP = "(\\d{1,5})";
private static final String PUBLISHER = "(\\d{1,7})";
private static final String TITLE = "(\\d{1,6})";
/**
* ISBN-13 consists of 5 groups of numbers separated by either dashes (-) or
* spaces. The first group is 978 or 979, the second group is 1-5
* characters, third 1-7, fourth 1-6, and fifth is 1 digit.
*/
static final String ISBN13_REGEX = "^(978|979)(?:(\\d{10})|(?:" + SEP
+ GROUP + SEP + PUBLISHER + SEP + TITLE + SEP + "([0-9])))$";
public boolean isValid(final String isbn) {
return !"".equals(isbn) && isbn.matches(ISBN13_REGEX);
}
}
|
package vanadis.core.jmx;
public class JmxException extends RuntimeException {
public JmxException(String message) {
super(message);
}
public JmxException(String message, Throwable cause) {
super(message, cause);
}
private static final long serialVersionUID = -7634021168508883181L;
}
|
package com.lin.paper.pojo;
import java.util.Date;
public class PColumn {
private String columnid;
private String columnname;
private String parentcolumn;
private Integer columnstate;
private Integer type;
private String url;
private Integer orderby;
private Integer isparent;
private Date createtime;
private Date updatetime;
public String getColumnid() {
return columnid;
}
public void setColumnid(String columnid) {
this.columnid = columnid == null ? null : columnid.trim();
}
public String getColumnname() {
return columnname;
}
public void setColumnname(String columnname) {
this.columnname = columnname == null ? null : columnname.trim();
}
public String getParentcolumn() {
return parentcolumn;
}
public void setParentcolumn(String parentcolumn) {
this.parentcolumn = parentcolumn == null ? null : parentcolumn.trim();
}
public Integer getColumnstate() {
return columnstate;
}
public void setColumnstate(Integer columnstate) {
this.columnstate = columnstate;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url == null ? null : url.trim();
}
public Integer getOrderby() {
return orderby;
}
public void setOrderby(Integer orderby) {
this.orderby = orderby;
}
public Integer getIsparent() {
return isparent;
}
public void setIsparent(Integer isparent) {
this.isparent = isparent;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
}
|
package cn.edu.zucc.web.json;
/**
* Created by zxy on 3/31/2017.
*/
public class AddRunRequest {
private String no;
private String meter;
private String starttime;
private String endtime;
private String phoneuid;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getMeter() {
return meter;
}
public void setMeter(String meter) {
this.meter = meter;
}
public String getStarttime() {
return starttime;
}
public void setStarttime(String starttime) {
this.starttime = starttime;
}
public String getEndtime() {
return endtime;
}
public void setEndtime(String endtime) {
this.endtime = endtime;
}
public String getPhoneuid() {
return phoneuid;
}
public void setPhoneuid(String phoneuid) {
this.phoneuid = phoneuid;
}
}
|
package com.pengyifan.pubtator.eval;
public class DetailedTextDisplay extends EvalDisplay {
public DetailedTextDisplay() {
super(27);
}
@Override
protected void get(Mode mode, ResultPrinter resultPrinter, PubTatorEval eval) {
switch (mode) {
case Disease:
resultPrinter.printRow("Disease");
resultPrinter.printRow(" Concept id matching", eval.getDiseaseIdStats());
resultPrinter.printRow(" Mention (Strict matching)", eval.getDiseaseMentionStats());
resultPrinter.printRow(" Mention (Appro. matching)", eval.getDiseaseApproMentionStats());
break;
case Chemical:
resultPrinter.printRow("Chemical");
resultPrinter.printRow(" Concept id matching", eval.getChemicalIdStats());
resultPrinter.printRow(" Mention (Strict matching)", eval.getChemicalMentionStats());
resultPrinter.printRow(" Mention (Appro. matching)", eval.getChemicalApproMentionStats());
break;
case CID:
resultPrinter.printRow("CID");
resultPrinter.printRow(" Concept id matching", eval.getCdrStats());
resultPrinter.printRow(" Mention (Strict matching)", eval.getCdrWithMentionStats());
resultPrinter.printRow(" Mention (Appro matching)", eval.getCdrWithApproMentionStats());
break;
}
}
}
|
package sort;
import java.util.Arrays;
import static sort.NetherLandFlag.swap;
public class HeapSort {
public static void heapSort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
for (int i = 0; i < arr.length; i++) {
heapInsert(arr, i);
}
int size = arr.length;
swap(arr, 0, --size);
while (size > 0) {
heapify(arr, 0, size);
swap(arr, 0, --size);
}
}
private static void heapify(int[] arr, int i, int size) {
int left = 2 * i + 1;
while (left < size) {
int large = left + 1 < size && arr[left + 1] > arr[left] ? left + 1 : left;
large = arr[i] > arr[large]? i: large;
if(large == i){
break;
}
swap(arr,i,large);
i = large;
left = 2 * i + 1;
}
}
private static void heapInsert(int[] arr, int i) {
while (arr[i] > arr[(i-1)/2]){
swap(arr,i,(i-1)/2);
i = (i-1)/2;
}
}
public static void main(String[] args) {
int[] arr = new int[]{7,2,9,3,5,8,8,5,1,6,6,4};
heapSort(arr);
System.out.println(Arrays.toString(arr));
}
}
|
import java.util.Comparator;
import java.util.Hashtable;
import javax.naming.ldap.SortResponseControl;
import com.sun.corba.se.impl.encoding.OSFCodeSetRegistry.Entry;
public class Google{
private double[] rank;
Hashtable<String,Inte> hashedPages;
String[] sortedRank;
public Google() {}
private void rankFilter(BigMatrix dataMatrix){
String[] tempRank = new String[sortedRank.length];
Boolean isEqual = true;
//迭代计算,直到数据收敛或计算次数达到50次
for(int i=0;i<50;i++){
rank = dataMatrix.multiply(rank);
//拷贝当前的数组值到临时数组
for(int j=0;j < sortedRank.length;j++){
tempRank[j] = sortedRank[j];
}
//排序
Arrays.sort(sortedRank,new compareByRank());
//计算是否收敛
for(int j=0;j < sortedRank.length;j++){
if(sortedRank[j].compareTo(tempRank[j])!=0){
isEqual = false;
break;
}
}
if(isEqual == true){
break;
}
else{
isEqual = true;
}
}
}
class compareByRank implements Comparator<String>{
public int compare(String a,String b){
int indexA=hashedPages.get(a);
int indexB=hashedPages.get(b);
if(rank[indexA] == rank[indexB]){
return(0);
}else if(rank[indexA]>rank[indexB]){
return(-1);
}else{
return(1);
}
}
}
public java.lang.String[] pageRank(java.lang.String[] s){
//height of data
int theSize = Math.max(4 * s.length/3 + 1, 16);
//initialization
hashedPages = new Hashtable<String,Integer>(theSize);
String[] pages = new String[s.length];
int[] nLinks = new int[s.length];
rank = new double[s.length];
sortedRank = new String[s.length];
String[] dataEntry = new String[s.length];
//获取数据
for(int i=0;i<s.length;i++){
String[] temp = s[i].split(" ");
pages[i] = temp[0];
nLinks[i] = temp.length - 1;
sortedRank[i] = temp[0];
rank[i] =1;
dataEntry[i] = "";
hashedPages.put(pages[i], i);
}
int tRow,tCol;
//初始化矩阵
for(int i=0;i<s.length;i++){
String[] temp = s[i].split(" ");
for(int j=1;j<temp.length;j++){
tCol = hashedPages.get(temp[0]);
tRow = hashedPages.get(temp[j]);
dataEntry[tRow] += "{" + tCol + "," + (1/(double)nLinks[i]) + "}";
}
}
//创建矩阵数据
BigMatrix dataMatrix = new BigMatrix(dataEntry);
//排序
rankFilter(dataMatrix);
//返回排序后的URL列表
return(sortedRank);
}
}
class BigMatrix {
public int nCols, nRows;
EntryList[] theRows;
//构造函数采用String数组作为输入
//每个字符串能够初始化一行数据
public BigMatrix(java.lang.String[] x) {
nRows = x.length;
nCols = 0;
theRows = new EntryList[nRows];
for(int i=0;i<nRows;i++){
theRows[i] = new EntryList();
if(x[i] != null){
String[] tempArr = x[i].split(";");
if(tempArr[0] != null){
for(int j=0;j<tempArr.length;j++){
Entry instance = new Entry(tempArr[j]);
theRows[i].add(instance);
if(nCols <= instance.col){
nCols = instance.col + 1;
}
}
}
}
}
}
//乘以一维向量
public double[] multiply(double[] x){
double[] result = new double[nRows];
int count;
for(int i=0;i<nRows;i++){
EntryList temp = theRows[i];
count=0;
while ((temp != null) && (temp.data != null)){
result[i] += (temp.data.value * x[temp.data.col]);
temp.temp.next;
count++;
}
}
return(result);
}
}
//矩阵的元素
class Entry{
int col; //元素所在列
double value;//元素值
public Entry(java.lang.String x){
String[] temp = x.split(",");
if(temp[0].compareTo("") != 0){
col = Integer.parseInt(temp[0].trim().substring(1));
value = Double.parseDouble(temp[1].trim().substring(0,temp[1].trim().length()-1);
}
}
}
//元素列表
class EntryList {
Entry data;
EntryList next, tail;
public EntryList(){
next = null;
tail = null;
data = null;
}
//添加数据
void add(Entry x){
if(tail = null){
data=x;
tail=this;
}else{
tail.next = new EntryList();
tail.next.data = x;
tail = tail.next;
}
}
}
|
package com.bridgeit.ObjectOrientedPrograms;
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONObject;
import com.bridgeit.utility.Utility;
public class Json {
public static void main(String[] args) throws IOException {
JSONObject obj1 = new JSONObject();
obj1.put("name", "rice");
obj1.put("weight", "10kg");
obj1.put("price", "55");
JSONObject obj2 = new JSONObject();
obj2.put("name", "pulse");
obj2.put("weight", "10kg");
obj2.put("price", "45");
JSONObject obj3 = new JSONObject();
obj3.put("name", "wheat");
obj3.put("weight", "10kg");
obj3.put("price", "55");
try (FileWriter file = new FileWriter("jsonoutput.json")) {
file.write(obj1.toJSONString());
file.write(obj2.toJSONString());
file.write(obj3.toJSONString());
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + obj1);
System.out.println(obj2);
System.out.println(obj3);
}
// Utility.jsonDataManagement();
}
}
|
public interface BalStreetLegal {
void getstreetSignalStop();
void getstreetSingalLeftTurn();
void getstreetSignalRightTurn();
}
|
package com.nearsoft.upiita.api.repository;
import com.nearsoft.upiita.api.model.Loan;
import org.springframework.data.repository.CrudRepository;
public interface LoanRepository extends CrudRepository<Loan, Long> {
}
|
package com.sunteam.library.activity;
import android.app.Activity;
import android.content.Intent;
import com.sunteam.common.menu.MenuActivity;
import com.sunteam.common.menu.MenuConstant;
import com.sunteam.common.tts.TtsUtils;
import com.sunteam.library.R;
import com.sunteam.library.utils.TTSUtils;
/**
* @Destryption 电子图书中朗读界面需要设置文本朗读的一些设置,如:中文角色、语速、语调、语音音效
* @Author Jerry
* @Date 2017-2-7 上午9:55:09
* @Note
*/
public class VoiceSettings extends MenuActivity {
@Override
protected void onResume() {
TtsUtils.getInstance().restoreSettingParameters();
super.onResume();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
TtsUtils.getInstance().restoreSettingParameters(); // 在菜单界面使用系统设置朗读
if (Activity.RESULT_OK != resultCode || null == data) { // 在子菜单中回传的标志
return;
}
// 设置成功后,销毁当前界面,返回到父窗口
super.setResultCode(Activity.RESULT_OK, requestCode, getSelectItemContent());
}
@Override
public void setResultCode(int resultCode, int selectItem, String menuItem) {
String[] list;
int defaultItem = 0;
switch(selectItem){
case 0: // 中文角色
list = getResources().getStringArray(R.array.library_array_menu_voice_china);
defaultItem = TTSUtils.getInstance().getRoleIndex();
startNextActivity(VoiceSpeaker.class, selectItem, menuItem, list, defaultItem);
break;
case 1: // 语速
defaultItem = TTSUtils.getInstance().getSpeed();
startNextActivity(VoiceSpeed.class, selectItem, menuItem, null, defaultItem);
break;
case 2: // 语调
defaultItem = TTSUtils.getInstance().getPitch();
startNextActivity(VoiceTone.class, selectItem, menuItem, null, defaultItem);
break;
case 3: // 语音音效
list = getResources().getStringArray(R.array.library_array_menu_voice_effect);
defaultItem = TTSUtils.getInstance().getCurEffectIndex();
startNextActivity(VoiceEffect.class, selectItem, menuItem, list, defaultItem);
break;
default:
break;
}
}
private void startNextActivity(Class<?> cls, int selectItem, String title, String[] list, int defaultItem) {
Intent intent = new Intent();
intent.putExtra(MenuConstant.INTENT_KEY_TITLE, title); // 菜单名称
intent.putExtra(MenuConstant.INTENT_KEY_LIST, list); // 菜单列表
intent.putExtra(MenuConstant.INTENT_KEY_SELECTEDITEM, defaultItem); // 子菜单默认值
intent.setClass(this, cls);
// 如果希望启动另一个Activity,并且希望有返回值,则需要使用startActivityForResult这个方法,
// 第一个参数是Intent对象,第二个参数是一个requestCode值,如果有多个按钮都要启动Activity,则requestCode标志着每个按钮所启动的Activity
startActivityForResult(intent, selectItem);
}
}
|
//Servlet do edytowania pliku
package vs.api.serlvets;
import vs.api.helpers.FoldersController;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
@WebServlet("/EditTextServlet")
public class EditTextServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String user = String.valueOf((int) session.getAttribute("id"));
String filePath = request.getParameter("fileName") + ".txt";
List<String> fileContent = Arrays.asList(request.getParameter("fileTextArea").split("\n"));
FoldersController foldersController = new FoldersController(user, null);
String userPath = foldersController.getUserPath();
String fileFullPath = userPath + "\\" + filePath;
File file = new File(fileFullPath);
try(PrintWriter out = new PrintWriter(file)){
for(String line : fileContent){
out.println(line);
}
out.println(fileContent);
}
response.sendRedirect("/mainpage.jsp");
}
}
|
package com.snkit.resiliencechaosmonkey;
public class ResponseDTO {
private long duration;
private String msg;
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
|
package com.github.manage.jwt;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.github.manage.common.util.CommonConstants;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
/**
* @ProjectName: spring-cloud-examples
* @Package: com.github.manage.jwt
* @Description: JWT用户实现类
* @Author: Vayne.Luo
* @date 2018/12/20
*/
@Data
public class JwtUser extends User{
private String remoteAddress;
private String theme;
private String avatar;
private Long userId;
private String email;
private String mobile;
private String ssex;
private String password;
private String loginTime;
public JwtUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
}
|
package com.ahmetkizilay.yatlib4j.accounts;
import com.ahmetkizilay.yatlib4j.oauthhelper.OAuthHolder;
public class UpdateProfileBanner {
private static final String BASE_URL = "https://api.twitter.com/1.1/account/update_profile_banner.json";
private static final String HTTP_METHOD = "POST";
public static UpdateProfileBanner.Response sendRequest(UpdateProfileBanner.Parameters params, OAuthHolder oauthHolder) {
throw new UnsupportedOperationException();
}
public static class Response {
}
public static class Parameters {
}
}
|
package com.ece.pfe.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ece.pfe.R;
import com.ece.pfe.model.Patient;
import java.util.List;
/**
* Created by Jerry on 10/10/2017.
*/
public class PatientAdapter extends ArrayAdapter<Patient> {
public PatientAdapter(Context context, List<Patient> patients) {
super(context, 0, patients);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.row_patient, parent, false);
}
PatientViewHolder viewHolder = (PatientViewHolder) convertView.getTag();
if (viewHolder == null) {
viewHolder = new PatientViewHolder();
viewHolder.icon = (ImageView) convertView.findViewById(R.id.ic_people);
viewHolder.name = (TextView) convertView.findViewById(R.id.rowName);
viewHolder.room = (TextView) convertView.findViewById(R.id.rowRoom);
convertView.setTag(viewHolder);
}
Patient patient = getItem(position);
viewHolder.name.setText(patient.getFirstName() + "" + patient.getLastName());
viewHolder.room.setText(patient.getRoom());
return convertView;
}
private class PatientViewHolder {
public ImageView icon;
public TextView name;
public TextView room;
}
}
|
package com.blackvelvet.cybos.bridge.cpforetrade ;
import com4j.*;
/**
*/
public enum CPE_ACC_GOODS implements ComEnum {
/**
* <p>
* 전체
* </p>
* <p>
* The value of this constant is -1
* </p>
*/
CPC_ALL_ACC(-1),
/**
* <p>
* 주식계좌
* </p>
* <p>
* The value of this constant is 1
* </p>
*/
CPC_STOCK_ACC(1),
/**
* <p>
* 선물계좌
* </p>
* <p>
* The value of this constant is 2
* </p>
*/
CPC_FUTURE_ACC(2),
;
private final int value;
CPE_ACC_GOODS(int value) { this.value=value; }
public int comEnumValue() { return value; }
}
|
package com.ssafy.web.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//import com.ssafy.web.dto.Favorite;
import com.ssafy.web.dto.Member;
import com.ssafy.web.repository.MemberRepository;
@Service
public class MemberServiceImpl implements MemberService{
@Autowired
MemberRepository repo;
@Override
public Member login(String id, String pw) throws Exception {
Member member = repo.login(id, pw);
if(member == null) return null;
return member;
}
@Override
public String check(String id, String name) throws Exception {
String password = repo.check(id, name);
if(password==null) return null;
return password;
}
@Override
public void signUp(Member member) throws Exception {
repo.signUp(member);
}
@Override
public void modify(Member member) throws Exception {
repo.modify(member);
}
@Override
public void delete(String id) throws Exception {
repo.delete(id);
}
@Override
public List<Member> search() throws Exception {
return repo.search();
}
}
|
/*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.company.cubavisionclinic.web.invoicedetails;
import com.company.cubavisionclinic.entity.InvoiceDetails;
import com.company.cubavisionclinic.entity.Product;
import com.haulmont.cuba.gui.components.AbstractEditor;
import com.haulmont.cuba.gui.components.PickerField;
import com.haulmont.cuba.gui.data.DataSupplier;
import javax.inject.Inject;
import javax.inject.Named;
public class InvoiceDetailsEdit extends AbstractEditor<InvoiceDetails> {
@Named("fieldGroup.productProductid")
private PickerField productProductidField;
@Override
protected void postInit() {
super.postInit();
/**
* Adding {@link com.haulmont.cuba.gui.components.Component.ValueChangeListener} for {@link productProductidField}
* to set initial value of the {@link InvoiceDetails#unitPrice} field in correspondence to {@link Product#getCurrentPrice()}
*/
productProductidField.addValueChangeListener(e -> {
Product selectedProduct = getItem().getProductProductid();
if (selectedProduct != null) {
getItem().setUnitPrice(selectedProduct.getCurrentPrice());
} else
getItem().setUnitPrice(null);
});
}
}
|
package com.espendwise.manta.web.forms;
import com.espendwise.manta.model.data.OrderPropertyData;
import com.espendwise.manta.model.view.OrderItemIdentView;
import com.espendwise.manta.spi.Initializable;
import com.espendwise.manta.spi.Resetable;
import com.espendwise.manta.util.validation.Validation;
import com.espendwise.manta.web.validator.OrderItemNoteFilterFormValidator;
import java.util.List;
@Validation(OrderItemNoteFilterFormValidator.class)
public class OrderItemNoteFilterForm extends WebForm implements Resetable, Initializable {
private String orderItemNoteField;
private String type;
private List<OrderPropertyData> orderNotes;
private List<OrderItemIdentView> orderItemViews;
private Long orderId;
private Long orderItemId;
private boolean init;
private boolean view;
public OrderItemNoteFilterForm() {
super();
}
public String getOrderItemNoteField() {
return orderItemNoteField;
}
public void setOrderItemNoteField(String orderItemNoteField) {
this.orderItemNoteField = orderItemNoteField;
}
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public Long getOrderItemId() {
return orderItemId;
}
public void setOrderItemId(Long orderItemId) {
this.orderItemId = orderItemId;
}
@Override
public void reset() {
this.orderItemNoteField = null;
}
@Override
public void initialize() {
this.init = true;
}
@Override
public boolean isInitialized() {
return this.init;
}
public boolean getView() {
return view;
}
public void setView(boolean view) {
this.view = view;
}
public List<OrderPropertyData> getOrderNotes() {
return orderNotes;
}
public void setOrderNotes(List<OrderPropertyData> orderNotes) {
this.orderNotes = orderNotes;
}
public List<OrderItemIdentView> getOrderItemViews() {
return orderItemViews;
}
public void setOrderItemViews(List<OrderItemIdentView> orderItemViews) {
this.orderItemViews = orderItemViews;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
package com.module.controllers.excel;
import com.module.controllers.ProgressController;
import com.module.database.DatabaseWorker;
import com.module.helpers.ExcelTableGenerator;
import com.module.helpers.FileLoader;
import com.module.model.entity.VeteranEntity;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import lombok.Data;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
@Data
@Component
public class ExportInExcelDialogController {
@FXML
private CheckBox caseNumber;
@FXML
private CheckBox militaryRank;
@FXML
private CheckBox firstName;
@FXML
private CheckBox secondName;
@FXML
private CheckBox middleName;
@FXML
private CheckBox dateOfBirth;
@FXML
private CheckBox category;
@FXML
private CheckBox subcategory;
@FXML
private CheckBox position;
@FXML
private CheckBox militarySubdivision;
@FXML
private CheckBox district;
@FXML
private CheckBox registrationAddress;
@FXML
private CheckBox address;
@FXML
private CheckBox phoneNumber;
@FXML
private CheckBox regionalExecutiveCommittee;
@FXML
private CheckBox villageExecutiveCommittee;
@FXML
private CheckBox marchingOrganization;
@FXML
private Button exportButton;
@FXML
private Button closeButton;
@FXML
private AnchorPane excelDialogRoot;
private Stage dialogStage;
private DatabaseWorker databaseWorker;
private List<VeteranEntity> filtersEntities;
private File file;
@FXML
public void handleExportButton() throws IOException {
if (!getExportColumnNames().isEmpty()) {
file = FileLoader.saveExcel();
if (file != null) {
final Task task = new Task() {
@Override
protected Object call() throws Exception {
ExcelTableGenerator tableGenerator = new ExcelTableGenerator();
List<List<String>> dataToExportInExcel = excelDateGenerator();
tableGenerator.writeIntoExcel(dataToExportInExcel, file);
return null;
}
};
ProgressController progressController = new ProgressController();
progressController.showProgressBar(dialogStage, task);
}
}
}
@FXML
public void initialize() {
}
private List<List<String>> excelDateGenerator() {
List<List<String>> dataToExportInExcel = new LinkedList<>();
if (!getExportColumnNames().isEmpty()) {
dataToExportInExcel.add(getExportColumnNames());
for (VeteranEntity entity : filtersEntities) {
List<String> data = new ArrayList<>();
if (caseNumber.isSelected())//
data.add(entity.getCaseNumber());
if (militaryRank.isSelected())//
if (entity.getMilitaryRank() != null)
data.add(entity.getMilitaryRank().getName());
else data.add("-");
if (firstName.isSelected())//
data.add(entity.getFirstName());
if (secondName.isSelected())//
data.add(entity.getSecondName());
if (middleName.isSelected())//
data.add(entity.getMiddleName());
if (dateOfBirth.isSelected())
if (entity.getDateOfBirth() != null)
data.add(entity.getDateOfBirth().toString());
else data.add("-");
if (category.isSelected())//
data.add(entity.getCategory().getName());
if (subcategory.isSelected())
if (entity.getSubcategory() != null)
data.add(entity.getSubcategory().getName());
else data.add("-");
if (position.isSelected())
if (entity.getPosition() != null)
data.add(entity.getPosition());
else data.add("-");
if (militarySubdivision.isSelected())
if (entity.getSubdivision() != null)
data.add(entity.getSubdivision());
else data.add("-");
if (district.isSelected())//
data.add(entity.getDistrict().getName());
if (registrationAddress.isSelected())
if (entity.getRegistrationAddress() != null)
data.add(entity.getRegistrationAddress());
else data.add("-");
if (address.isSelected())
if (entity.getAddress() != null)
data.add(entity.getAddress());
else data.add("-");
if (phoneNumber.isSelected())
if (entity.getPhoneNumber() != null)
data.add(entity.getPhoneNumber());
else data.add("-");
if (regionalExecutiveCommittee.isSelected())
if (entity.getRegionalExecutiveCommittee() != null)
data.add(entity.getRegionalExecutiveCommittee());
else data.add("-");
if (villageExecutiveCommittee.isSelected())
if (entity.getVillageExecutiveCommittee() != null)
data.add(entity.getVillageExecutiveCommittee());
if (marchingOrganization.isSelected())
if (entity.getMarchingOrganization() != null)
data.add(entity.getMarchingOrganization());
else data.add("-");
dataToExportInExcel.add(data);
}
}
return dataToExportInExcel;
}
private List<String> getExportColumnNames() {
List<String> columnNames = new ArrayList<>();
if (caseNumber.isSelected())//
columnNames.add(caseNumber.getText());
if (militaryRank.isSelected())//
columnNames.add(militaryRank.getText());
if (firstName.isSelected())//
columnNames.add(firstName.getText());
if (secondName.isSelected())//
columnNames.add(secondName.getText());
if (middleName.isSelected())//
columnNames.add(middleName.getText());
if (dateOfBirth.isSelected())
columnNames.add(dateOfBirth.getText());
if (category.isSelected())//
columnNames.add(category.getText());
if (subcategory.isSelected())
columnNames.add(subcategory.getText());
if (position.isSelected())
columnNames.add(position.getText());
if (militarySubdivision.isSelected())
columnNames.add(militarySubdivision.getText());
if (district.isSelected())//
columnNames.add(district.getText());
if (registrationAddress.isSelected())
columnNames.add(registrationAddress.getText());
if (address.isSelected())
columnNames.add(address.getText());
if (phoneNumber.isSelected())
columnNames.add(phoneNumber.getText());
if (regionalExecutiveCommittee.isSelected())
columnNames.add(regionalExecutiveCommittee.getText());
if (villageExecutiveCommittee.isSelected())
columnNames.add(villageExecutiveCommittee.getText());
if (marchingOrganization.isSelected())
columnNames.add(marchingOrganization.getText());
return columnNames;
}
@FXML
private void handleCloseButton() {
dialogStage.close();
}
}
|
/*
Problem from Topcoder practice problems (http://www.topcoder.com)
https://arena.topcoder.com/#/u/practiceCode/16319/46378/13642/1/325040
Problem Statement
You are given two s: N and K. Lun the dog is interested in strings that satisfy the following conditions:
The string has exactly N characters, each of which is either 'A' or 'B'.
The string s has exactly K pairs (i, j) (0 <= i < j <= N-1) such that s[i] = 'A' and s[j] = 'B'.
If there exists a string that satisfies the conditions, find and return any such string. Otherwise, return an empty string.
*/
public class ABComputed {
public static String createString(int i,int k){
int noA =i;
int noB =0;
int curK = 0;
int bPos =-1;
boolean found=false;
while(noA >= noB && !found){
if( k-curK <noA){
found=true;
bPos= k-curK;
} else {
curK = --noA * ++noB;
if (curK == k) {
found = true;
}else{
curK=curK-noB;
}
}
}
if (!found) {
return "";
}else{
StringBuffer stringBuffer= new StringBuffer();
for(int j=0; j<i; j++){
if (j<noA) {
stringBuffer.append("A");
}else{
stringBuffer.append("B");
}
}
if(bPos >-1){
stringBuffer.replace(bPos,bPos+1,"B");
}
return stringBuffer.toString();
}
}
public static void main(String[] args) {
for (int i = 1; i < 50; i++){
System.out.println("8:"+i+" = "+createString(8, i));
}
}
}
|
package top.kylewang.bos.service.transit.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.kylewang.bos.dao.transit.InOutStorageInfoRepository;
import top.kylewang.bos.dao.transit.TransitRepository;
import top.kylewang.bos.domain.transit.InOutStorageInfo;
import top.kylewang.bos.domain.transit.TransitInfo;
import top.kylewang.bos.service.transit.InOutStorageInfoService;
/**
* @author Kyle.Wang
* 2018/1/13 0013 16:21
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class InOutStorageInfoServiceImpl implements InOutStorageInfoService {
@Autowired
private InOutStorageInfoRepository inOutStorageInfoRepository;
@Autowired
private TransitRepository transitRepository;
@Override
public void save(String transitInfoId, InOutStorageInfo inOutStorageInfo) {
// 保存出入库信息
inOutStorageInfoRepository.save(inOutStorageInfo);
// 保存运单信息
TransitInfo transitInfo = transitRepository.findOne(Integer.parseInt(transitInfoId));
transitInfo.getInOutStorageInfos().add(inOutStorageInfo);
// 修改状态
if(inOutStorageInfo.getOperation().equals("到达网点")){
// 更新网点地址
transitInfo.setStatus("到达网点");
transitInfo.setOutletAddress(inOutStorageInfo.getAddress());
}
}
}
|
package server.by.epam.fullparser.service.parser;
import entity.Book;
import java.util.List;
/**
* Service interface for all parser types.
*/
public interface Parser {
List<Book> parse(String fileName) throws ParserException;
}
|
package leecode.Array;
import java.util.ArrayList;
import java.util.List;
public class 子集_组合_排列_回溯框架模板 {
//result = []
//def backtrack(路径, 选择列表):
// if 满足结束条件:
// result.add(路径)
// return
// for 选择 in 选择列表:
// 做选择
// backtrack(路径, 选择列表)
// 撤销选择
List<List<Integer>> listall=new ArrayList<>();
List<Integer>track=new ArrayList<>();//track就是路径
//子集
// []
// / | \
// [1] [2] [3]
// / \ \
// [1,2] [1,3] [2,3]
// /
// [1,2,3]
public void subsets(int[]nums,int index,List<Integer>track){
listall.add(new ArrayList<>(track));//树上每个节点都要加上
//没有return
for (int i = index; i <nums.length ; i++) {//从index开始,如果是1,选择列表2,3;如果是2选择列表只有3
track.add(nums[i]);//做选择
//回溯函数相当于一个指针,i+1 走到下一层 ,每层track里面的个数不一样
subsets(nums,i+1,track);//i不断在循环中增加,如果写成index,则会重复回溯(例如下次循环i为index+1,但还是从index回溯)
track.remove(track.size()-1);//撤销
}
}
//组合
// 典型的回溯算法,k(2) 限制了树的高度,n(4) 限制了树的宽度,直接套我们以前讲过的回溯算法模板框架就行了:
// []
// / / \ \
// [1] [2] [3] [4]
// / | \ / \ \
// 1.2 1.3 1.4 2.3 2.4 3.4
public void backtrack(int n,int k,int index,List<Integer>list){
if(list.size()==k){//注意这个条件,list中有k个数时就输出,子集几个数都可以,所以不写条件
listall.add(new ArrayList<>(list));
return;//这个不写return也可以,建议写上
}
for (int i = index; i <n ; i++) {
list.add(i);
backtrack(n,k,i+1,list);
list.remove(list.size()-1);
}
}
//排列
// []
//
// 1 2 3
//
// 1,2 1,3 2,1 2,3 3,1 3,2
//
// 1,2,3 1,3,2 2,1,3 2,3,1 3,1,2 3,2,1
//排列问题的树比较对称,而组合问题的树越靠右节点越少。
// 在代码中的体现就是,
// 排列问题每次通过 contains 方法来排除在 track 中已经选择过的数字;
// 而组合问题通过传入一个 start 参数,
// 来排除 start 索引之前的数字。
public void huisu(List<Integer>trace,int[]nums,int index) {//全排列下标没有用
if (trace.size() == nums.length) {//满足三个数了
listall.add(new ArrayList<>(trace));
return;//打印一个字符串的全部排列不需要写return
}
for (int i = 0; i < nums.length; i++) {//从0开始,因为全排列所有的数都要包含,不是说你到了3就不能选1了,每步都有三个选择
// 但是访问过就不能访问了,子集是从begin开始,所以排除了访问过的
if (trace.contains(nums[i])) {//排除不合法的选择,也可以使用visit排除,全排列_46
continue;
}
//做选择
trace.add(nums[i]);//路径.add(选择)
huisu(trace, nums, index);//backtrack(路径, 选择列表) index没有用
trace.remove(trace.size() - 1);
}
}
}
|
package com.mrice.txl.appthree.view.dialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.mrice.txl.appthree.R;
/**
* Created by wangchao on 14/11/30.
*/
public class AlertDialog extends ThreeRowDialog {
protected View top,
middle,
bottom;
protected FrameLayout middle_layout;//中间布局
protected View middle_root;//中间布局根布局
protected ViewGroup.LayoutParams middleParams;//中间的布局参数
protected ImageView imageView;
protected TextView titleView,
messageView;
protected Button[] buttons;
protected String title,
message;
protected int topIcon;
protected String[] buttonsText;
protected View divider;
private int dividerVisibility = View.GONE;
private boolean versionMode;
public AlertDialog setDividerVisibility(int dividerVisibility) {
this.dividerVisibility = dividerVisibility;
return this;
}
public String getMessage() {
if (messageView != null) {
return messageView.getText().toString();
}
return message;
}
@Override
public void onStart() {
super.onStart();
if (getDialog() == null) return;
}
@Override
View topView() {
if (TextUtils.isEmpty(title) && topIcon == 0) {
return null;
}
if (top != null) {
return top;
}
top = View.inflate(getActivity(), R.layout.ui_alert_top_dialog, null);
divider = top.findViewById(R.id.divider);
divider.setVisibility(dividerVisibility);
imageView = (ImageView) top.findViewById(R.id.dialog_top_image);
titleView = (TextView) top.findViewById(R.id.dialog_top_text);
if (versionMode) {
titleView.setTextSize(22);
titleView.setTextColor(getResources().getColor(R.color.black));
}
if (topIcon != 0) {
imageView.setBackgroundResource(topIcon);
imageView.setVisibility(View.VISIBLE);
}
if (title != null && !title.equals("")) {
titleView.setText(title);
}
return top;
}
@Override
int theme() {
return R.style.dialog_normal;
}
@Override
View middleView() {
if (middle != null) {
return middle;
}
LayoutInflater inflater = LayoutInflater.from(getActivity());
if (versionMode)
middle_root = inflater.inflate(R.layout.ui_alert_middle_dialog_version, null);
else
middle_root = inflater.inflate(R.layout.ui_alert_middle_dialog, null);
middle_layout = (FrameLayout) middle_root.findViewById(R.id.middle_layout);
messageView = (TextView) middle_root.findViewById(R.id.dialog_middle_text);
if (linkMark != null) {
messageView.setAutoLinkMask(linkMark);
}
if (message != null && !message.equals("")) {
messageView.setText(message);
}
return middle_root;
}
private Integer linkMark;
public void setMessageAutoLinkMask(int mark) {
linkMark = mark;
}
@Override
View bottomView() {
if (bottom != null) {
return bottom;
}
bottom = View.inflate(getActivity(), R.layout.ui_alert_bottom_dialog, null);
if (buttons != null && buttons.length != 0) {
if (((ViewGroup) bottom).getChildCount() == buttons.length) {
return bottom;
}
int btnLength = buttons.length;
if (btnLength == 1) {
View btn = getOnlyOneButton(buttonsText[0], 0);
addButton2Bottom(btn);
return bottom;
}
for (int i = 0; i < btnLength; i++) {
if (i > 0) {
View divider = new View(getActivity());
divider.setBackgroundColor(getResources().getColor(R.color.gray));
((ViewGroup) bottom).addView(divider);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(1,
ViewGroup.LayoutParams.MATCH_PARENT);
divider.setLayoutParams(params);
}
View btn = null;
if (i == 0) {
btn = getLeftButton(buttonsText[i], i);
} else if (i == btnLength - 1) {
btn = getRightButton(buttonsText[i], i);
} else {
btn = getButton(buttonsText[i], i);
}
addButton2Bottom(btn);
}
}
return bottom;
}
public void setMode(boolean mode) {
this.versionMode = mode;
}
private void addButton2Bottom(View btn) {
((ViewGroup) bottom).addView(btn);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) btn.getLayoutParams();
params.width = 0;
params.weight = 1;
btn.setLayoutParams(params);
}
private View getOnlyOneButton(String text, int index) {
View button = getButton(text, index);
button.setBackgroundResource(R.drawable.ui_selector_dialog_common_onebtn);
return button;
}
private View getRightButton(String text, int index) {
View button = getButton(text, index);
button.setBackgroundResource(R.drawable.ui_selector_dialog_common_rightbtn);
return button;
}
private View getLeftButton(String text, final int index) {
View button = getButton(text, index);
button.setBackgroundResource(R.drawable.ui_selector_dialog_common_leftbtn);
return button;
}
/**
* get button with text
*
* @param text button text
* @param index index
* @return me
*/
private View getButton(String text, final int index) {
View view = View.inflate(getActivity(), R.layout.ui_alert_bottom_button_dialog, null);
final AlertDialog dialog = this;
buttons[index] = (Button) view.findViewById(R.id.dialog_bottom_button);
buttons[index].setText(text);
buttons[index].setTag(text);
if (versionMode) {
buttons[index].setTextSize(20);
}
buttons[index].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (dialogDelegate != null && dialogDelegate instanceof AlertDialogDelegate) {
((AlertDialogDelegate) dialogDelegate).onButtonClick(dialog, v, index);
}
}
});
return view;
}
/**
* set title
*
* @param title title
* @return me
*/
public AlertDialog setTitle(String title) {
if (titleView != null) {
titleView.setText(title);
} else {
this.title = title;
}
return this;
}
/**
* set icon
*
* @param resourceId id
* @return me
*/
public AlertDialog setIcon(int resourceId) {
if (imageView != null) {
imageView.setBackgroundResource(resourceId);
} else {
this.topIcon = resourceId;
}
return this;
}
/**
* set middle message
*
* @param message message
* @return me
*/
public AlertDialog setMessage(String message) {
if (messageView != null) {
messageView.setText(message);
} else {
this.message = message;
}
return this;
}
public void setMessageViewSize() {
if (messageView != null) {
messageView.setTextSize(getResources().getDimension(R.dimen.font_size_normal));
}
}
/**
* set buttons
*
* @param buttonsText button array
* @return me
*/
public AlertDialog setButtons(String[] buttonsText) {
this.buttonsText = buttonsText;
this.buttons = new Button[buttonsText.length];
return this;
}
/**
* 获取 Button
*
* @param index Button index
* @return View
*/
public Button getButton(int index) {
if (index < buttons.length && index > -1) {
return buttons[index];
}
return null;
}
/**
* 设置中间的布局
*
* @param view
* @return
*/
public AlertDialog setMiddleView(View view) {
this.middle = view;
this.middleParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
if (null != middle_root) {
removeMiddleView();
initMiddleView();
}
return this;
}
/**
* 设置AlertDialog中间view
*
* @param view
*/
public void setMiddleView(View view, ViewGroup.LayoutParams params) {
this.middle = view;
this.middleParams = params;
if (null != middle_root) {
removeMiddleView();
initMiddleView();
}
}
/**
* 初始化中间布局
*/
public void initMiddleView() {
if (middle != null) {
removeMiddleView();
middle_layout.addView(middle, middleParams);
if (title == null || title.equals("") || title.equals("null")) {
middle_layout.setPadding(5, (int) this.getActivity().getResources().getDimension(R.dimen.common_size_10), 5, 0);
}
middle_layout.bringChildToFront(middle);
middle_layout.postInvalidate();
}
}
/**
* 删除中间的布局
*/
public void removeMiddleView() {
if (null != middle_root && middle_layout.getChildCount() > 1) {
if (null != middle.getParent()) {
((ViewGroup) middle.getParent()).removeView(middle);
}
middle_layout.removeView(middle);
}
}
/**
* 设置索引为 index 的 button 的文本
*
* @param text 文本
* @param index 索引
* @return me
*/
public AlertDialog setButtonText(String text, int index) {
if (buttons != null && buttons.length > index) {
buttons[index].setText(text);
} else if (dialogDelegate != null && dialogDelegate instanceof AlertDialogDelegate) {
((AlertDialogDelegate) dialogDelegate).onError(index + "", "您设置的按钮文本,索引越界!");
}
return this;
}
//alert dialog delegate
public static class AlertDialogDelegate extends ThreeRowDialogDelegate {
/**
* button click
*
* @param dialog dialog
* @param view button
* @param index index
*/
public void onButtonClick(AlertDialog dialog, View view, int index) {
}
/**
* 发生异常时候会调用这个方法
*
* @param id 异常 id
* @param data 异常数据
*/
public void onError(String id, Object data) {
}
}
@Override
public void dismiss() {
dismissAllowingStateLoss();
}
}
|
package pl.codewars.kata7;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Vowels {
private static final Pattern VOVEL_PATTERN = Pattern.compile("[aeiouyAEIOUY]");
/**
* Return the number (count) of vowels in the given string.
*
* We will consider a, e, i, o, and u as vowels for this Kata.
*
* The input string will only consist of lower case letters and/or spaces.
*
* @param str
* @return
*/
public static int getCount(String str) {
Matcher matcher = VOVEL_PATTERN.matcher(str);
int count = 0;
while(matcher.find()){
count++;
}
return count;
}
}
|
package preprocess.dbclasses;
import java.io.Serializable;
import java.util.HashMap;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(
name = "DEMOGRAPHICS"
)
public class Demographics implements Serializable{
@Id
@GeneratedValue
@Column (
name = "DEMOGRAPHICS_ID"
)
private int demographicsID;
@Column(
name = "PRECINCT_ID"
)
private int precinctID;
@Column(
name = "ASIAN"
)
private int asian;
@Column(
name = "CAUCASIAN"
)
private int caucasian;
@Column(
name = "HISPANIC"
)
private int hispanic;
@Column(
name = "AFRICAN_AMERICAN"
)
private int african_american;
@Column(
name = "NATIVE_AMERICAN"
)
private int native_american;
@Column(
name = "OTHER"
)
private int other;
@Column(
name="DISTRICT_ID"
)
private int districtId;
public Demographics(int precinctID, int asian, int caucasian, int hispanic, int african_american, int native_american, int other, int district_id){
this.precinctID = precinctID;
this.asian = asian;
this.caucasian = caucasian;
this.hispanic = hispanic;
this.african_american = african_american;
this.native_american = native_american;
this.other = other;
this.districtId = district_id;
}
public Demographics(){
}
public int getDemographicsID(){
return this.demographicsID;
}
public int getPrecinctID(){
return this.precinctID;
}
public int getDistrictID() { return this.districtId; }
public HashMap<String, Integer> getDemographicMap(){
HashMap<String, Integer> hm = new HashMap<>();
hm.put("Asian", this.asian);
hm.put("Caucasian", this.caucasian);
hm.put("Hispanic", this.hispanic);
hm.put("African-American", this.african_american);
hm.put("Native-American", this.native_american);
hm.put("Other", this.other);
return hm;
}
}
|
package com.tencent.mm.plugin.game.gamewebview.ui;
import com.tencent.mm.sdk.platformtools.bi;
class d$23 implements Runnable {
final /* synthetic */ String dEt;
final /* synthetic */ int fdh;
final /* synthetic */ d jJO;
public d$23(d dVar, String str, int i) {
this.jJO = dVar;
this.dEt = str;
this.fdh = i;
}
public final void run() {
if (d.e(this.jJO) != null) {
if (!bi.oW(this.dEt)) {
d.e(this.jJO).setTitleText(this.dEt);
}
d.e(this.jJO).setTitleColor(this.fdh);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.