text
stringlengths 10
2.72M
|
|---|
class Solution {
public String intToRoman(int num) {
/*
1. example
2. data structure / algo
Map each digit to Roman, use array
3. logic
thousand: num / 1000
hundresds: 4800 - > num % 1000 = 800, 800 / 100 = 8
tens: 4810 -> num % 100 = 10, 10 / 10 = 1
ones: 4871 -> num % 10 = 1
4. reuslt
5. analysis : TimeO(1), num operation is same, Space: O(1), fixed array size
============================
3 III
12: 12 % 10 = 1, 2 % 1 = 2 , XII
9: IX
58: LVIII
============================
*/
String[] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
String[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String[] thousands = {"", "M", "MM", "MMM"};
String[] hundreds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
return thousands[num / 1000] + hundreds[num % 1000 / 100] + tens[num % 100 / 10] + ones[num % 10];
}
}
|
package com.example.leosauvaget.channelmessaging.message;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.example.leosauvaget.channelmessaging.R;
import com.example.leosauvaget.channelmessaging.gps.GPSActivity;
import com.example.leosauvaget.channelmessaging.gps.OnGpsReceiveLocation;
public class MessageActivity extends GPSActivity {
String channelId;
MessageFragment messageFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
recoverUserInfos();
messageFragment = (MessageFragment) getSupportFragmentManager().findFragmentById(R.id.fMessages);
messageFragment.setChannelID(channelId);
setOnGpsReceiveLocation(new OnGpsReceiveLocation() {
@Override
public void onReceiveNewLocation(Location location) {
if(location != null ){
Log.wtf("Location in Message Activity", String.format("%f %f", location.getLongitude(), location.getLatitude()));
messageFragment.setLocation(location);
}
}
});
}
private void recoverUserInfos(){
Intent intent = getIntent();
channelId = (String) intent.getSerializableExtra("channelId");
}
public static void go(String channelID, Context cxt) {
Intent intent = new Intent(cxt, MessageActivity.class);
intent.putExtra("channelId", channelID);
cxt.startActivity(intent);
}
}
|
/*
* Copyright 2014, Stratio.
*
* 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.stratio.cassandra.index.schema.mapping;
import com.stratio.cassandra.index.schema.Schema;
import org.apache.lucene.document.Field;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;
public class ColumnMapperInetTest {
@Test()
public void testValueNull() {
ColumnMapperInet mapper = new ColumnMapperInet();
String parsed = mapper.indexValue("test", null);
Assert.assertNull(parsed);
}
@Test(expected = IllegalArgumentException.class)
public void testValueInteger() {
ColumnMapperInet mapper = new ColumnMapperInet();
mapper.indexValue("test", 3);
}
@Test(expected = IllegalArgumentException.class)
public void testValueLong() {
ColumnMapperInet mapper = new ColumnMapperInet();
mapper.indexValue("test", 3l);
}
@Test(expected = IllegalArgumentException.class)
public void testValueFloat() {
ColumnMapperInet mapper = new ColumnMapperInet();
mapper.indexValue("test", 3.5f);
}
@Test(expected = IllegalArgumentException.class)
public void testValueDouble() {
ColumnMapperInet mapper = new ColumnMapperInet();
mapper.indexValue("test", 3.6d);
}
@Test(expected = IllegalArgumentException.class)
public void testValueUUID() {
ColumnMapperInet mapper = new ColumnMapperInet();
mapper.indexValue("test", UUID.randomUUID());
}
@Test(expected = IllegalArgumentException.class)
public void testValueStringInvalid() {
ColumnMapperInet mapper = new ColumnMapperInet();
mapper.indexValue("test", "Hello");
}
@Test
public void testValueStringV4WithoutZeros() {
ColumnMapperInet mapper = new ColumnMapperInet();
String parsed = mapper.indexValue("test", "192.168.0.1");
Assert.assertEquals("192.168.0.1", parsed);
}
@Test
public void testValueStringV4WithZeros() {
ColumnMapperInet mapper = new ColumnMapperInet();
String parsed = mapper.indexValue("test", "192.168.000.001");
Assert.assertEquals("192.168.0.1", parsed);
}
@Test
public void testValueStringV6WithoutZeros() {
ColumnMapperInet mapper = new ColumnMapperInet();
String parsed = mapper.indexValue("test", "2001:db8:2de:0:0:0:0:e13");
Assert.assertEquals("2001:db8:2de:0:0:0:0:e13", parsed);
}
@Test
public void testValueStringV6WithZeros() {
ColumnMapperInet mapper = new ColumnMapperInet();
String parsed = mapper.indexValue("test", "2001:0db8:02de:0000:0000:0000:0000:0e13");
Assert.assertEquals("2001:db8:2de:0:0:0:0:e13", parsed);
}
@Test
public void testValueStringV6Compact() {
ColumnMapperInet mapper = new ColumnMapperInet();
String parsed = mapper.indexValue("test", "2001:DB8:2de::0e13");
Assert.assertEquals("2001:db8:2de:0:0:0:0:e13", parsed);
}
@Test
public void testValueInetV4() throws UnknownHostException {
ColumnMapperInet mapper = new ColumnMapperInet();
InetAddress inet = InetAddress.getByName("192.168.0.13");
String parsed = mapper.indexValue("test", inet);
Assert.assertEquals("192.168.0.13", parsed);
}
@Test
public void testValueInetV6() throws UnknownHostException {
ColumnMapperInet mapper = new ColumnMapperInet();
InetAddress inet = InetAddress.getByName("2001:db8:2de:0:0:0:0:e13");
String parsed = mapper.indexValue("test", inet);
Assert.assertEquals("2001:db8:2de:0:0:0:0:e13", parsed);
}
@Test
public void testField() {
ColumnMapperInet mapper = new ColumnMapperInet();
Field field = mapper.field("name", "192.168.0.13");
Assert.assertNotNull(field);
Assert.assertEquals("192.168.0.13", field.stringValue());
Assert.assertEquals("name", field.name());
Assert.assertEquals(false, field.fieldType().stored());
}
@Test
public void testExtractAnalyzers() {
ColumnMapperInet mapper = new ColumnMapperInet();
String analyzer = mapper.analyzer();
Assert.assertEquals(ColumnMapper.KEYWORD_ANALYZER, analyzer);
}
@Test
public void testParseJSON() throws IOException {
String json = "{fields:{age:{type:\"inet\"}}}";
Schema schema = Schema.fromJson(json);
ColumnMapper columnMapper = schema.getMapper("age");
Assert.assertNotNull(columnMapper);
Assert.assertEquals(ColumnMapperInet.class, columnMapper.getClass());
}
@Test
public void testParseJSONEmpty() throws IOException {
String json = "{fields:{}}";
Schema schema = Schema.fromJson(json);
ColumnMapper columnMapper = schema.getMapper("age");
Assert.assertNull(columnMapper);
}
@Test(expected = IOException.class)
public void testParseJSONInvalid() throws IOException {
String json = "{fields:{age:{}}";
Schema.fromJson(json);
}
}
|
package cc.apoc.rccvm.qemu;
import java.io.*;
import java.net.Socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MonitorClient {
private static final Logger logger = LoggerFactory.getLogger("rccvm.qemu");
private int port;
private Socket socket;
private BufferedReader inputStream;
private BufferedWriter outputStream;
public MonitorClient(int port) {
this.port = port;
}
public boolean connect() {
try {
if (port <= 0) {
return false;
}
socket = new Socket("127.0.0.1", port);
outputStream = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
handshake();
return true;
} catch (java.net.ConnectException e) {
return false;
} catch (IOException e) {
return false;
}
}
private void handshake() throws IOException {
readLine(); // ignore the welcome banner
}
public boolean isConnected() {
return socket.isConnected();
}
private String execute(String command) {
return execute(command, false);
}
private String execute(String command, boolean noResponse) {
String response = "";
try {
writeLine(command);
readLine(); // the monitor echos the command
String buffer = "";
String line = "";
do {
buffer += line;
line = readLine();
// break when prompt read:
if (line.contains("(qemu)")) {
if (!buffer.equals("") || noResponse)
break;
else
line = "";
}
} while (line != null);
response = buffer;
} catch (IOException e) {
e.printStackTrace();
logger.info("IOException in execute for " + command);
}
return response;
}
private void writeLine(String line) throws IOException {
logger.debug(String.format("send to monitor port %d: %s", port, line));
outputStream.write(line + "\r\n");
outputStream.flush();
}
private String readLine() throws IOException {
return inputStream.readLine();
}
public void close() {
if (socket != null && socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
logger.info("IOException: " + e.toString());
}
}
}
public String status() {
return execute("info status");
}
public void sendSaveVM(String tag) {
execute("savevm " + tag, true);
}
public void sendLoadVM(String tag) {
execute("loadvm " + tag, true);
}
public void sendPowerdown() {
execute("system_powerdown", true);
}
public void sendReset() {
execute("system_reset", true);
}
public void sendStop() {
execute("stop", true);
}
public void sendCont() {
execute("cont", true);
}
}
|
package com.root.mssm.List.List.suggestionlist;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class SearchCat {
@SerializedName("cat_name")
@Expose
private String catName;
@SerializedName("photo")
@Expose
private Object photo;
@SerializedName("catid")
@Expose
private String catid;
public String getCatName() {
return catName;
}
public void setCatName(String catName) {
this.catName = catName;
}
public Object getPhoto() {
return photo;
}
public void setPhoto(Object photo) {
this.photo = photo;
}
public String getCatid() {
return catid;
}
public void setCatid(String catid) {
this.catid = catid;
}
}
|
/**
* Copyright 2007 Jens Dietrich 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 nz.org.take.mandarax_migration_kit;
import java.beans.XMLEncoder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Map;
import org.apache.log4j.Category;
/**
* Constant handlers are used to deal with the constants found in the
* mandarax kb. These objects are represented by strings in the script
* generated. This handler serialises these objects using standard JDK XML
* serialization (for beans) and also generates a script that can be used
* to read these objects.
* @author Jens Dietrich
*/
public class XMLConstantHandler implements ConstantHandler {
public void generateScript(File folder, Map<String, Object> constants,Category logger) throws Exception {
// write objects
logger.info("Serializing objects found in mandarax kb using XML serialization to objects.xml");
File f = new File(folder.getAbsolutePath() + File.separatorChar + "objects.xml");
FileOutputStream fout = new FileOutputStream(f);
XMLEncoder encoder = new XMLEncoder(fout);
boolean generateScript = true;
try {
encoder.writeObject(constants);
}
catch (Exception t) {
generateScript = false;
logger.error("Error serializing oject references found in knowledge base - use alternative constant handler", t);
}
finally {
encoder.close();
}
if (!generateScript)
return;
// generate script to recover objects
logger.info("Creating script to load objects: recoverobjectsscript.txt");
f = new File(folder.getAbsolutePath() + File.separatorChar + "recoverobjectsscript.txt");
PrintStream out = new PrintStream(new FileOutputStream(f));
out.println("// script that can be used to recover the objects found in the (mandarax) knowledge base");
out.println("// applications should initialise the Constants class generated by the TAKE compiler with these objects ");
out.println("FileInputStream in = new FileInputStream(\"objects.xml\")");
out.println("XMLDecoder decoder = new XMLDecoder(in);");
out.println("Map<String, Object> r = (Map<String, Object>)decoder.readObject();");
out.println("out.close();");
out.close();
}
}
|
package cn.edu.zucc.web.controller;
import cn.edu.zucc.web.json.UpdateUserDataRequest;
import cn.edu.zucc.web.json.UserPwdPojo;
import cn.edu.zucc.web.security.PermissionSign;
import cn.edu.zucc.web.security.RoleSign;
import cn.edu.zucc.web.service.PhoneUIDService;
import cn.edu.zucc.web.service.UserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
/**
* 用户界面处理
* Created by zxy on 2016/7/6.
*
* @author zxyAnkh
* @since 2016-07-06
*/
@Controller("userController")
@RequestMapping("/user")
public class UserController {
private static final Log logger = LogFactory.getLog(UserController.class);
@Resource
private UserService userService;
@Resource
private PhoneUIDService phoneUIDService;
/**
* 用户首页
*/
@RequestMapping(value = "/main", method = {RequestMethod.POST, RequestMethod.GET})
@RequiresRoles(value = RoleSign.USER)
@ResponseBody
public String main() {
logger.info("User logined.");
return "{\"logined\":true}";
}
/**
* 用户更新个人密码
*
* @return
*/
@RequestMapping(value = "/update", method = RequestMethod.POST)
@RequiresRoles(value = RoleSign.USER)
@RequiresPermissions(value = PermissionSign.USER_UPDATE)
@ResponseBody
public String update(@RequestBody UpdateUserDataRequest json, HttpSession session) {
if (json.getNo() == null || "".equals(json.getNo())) {
return "{\"result\":false}";
}
if (json.getOldpwd() == null || "".equals(json.getOldpwd())) {
return "{\"result\":false}";
}
if (json.getNewpwd() == null || "".equals(json.getNewpwd())) {
return "{\"result\":false}";
}
String phoneuid = phoneUIDService.getPhoneUID(json.getNo());
if (phoneuid != null && json.getPhoneuid() != null && phoneuid.equals(json.getPhoneuid())) {
UserPwdPojo user = new UserPwdPojo(json.getNo(), json.getOldpwd(), json.getNewpwd());
logger.info("Receive update user personal information request, user = " + user.toString());
if (userService.updateUserPassword(user) == 1) {
session.removeAttribute("userInfo");
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "{\"result\":true}";
}
}
return "{\"result\":false}";
}
}
|
package util;
public enum TipoLog {
DEBUG, ERROR, FATAL, INFO, WARNING
}
|
package epamlab;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class StartManager {
public static ConcurrentMap<String, Long> competitors;
public static CountDownLatch latch;
private static final long MAX_RUNNING_TIME = 5000;
public static void startRase(Car... cars) {
latch = new CountDownLatch(1);
competitors = new ConcurrentHashMap<>();
List<Thread> threadsList = new ArrayList<>();
for (Car car : cars) {
threadsList.add(new Thread(car));
}
for (Thread thread : threadsList) {
thread.start();
}
latch.countDown();
try {
Thread.sleep(MAX_RUNNING_TIME);
for (Thread thread : threadsList) {
if (thread.isAlive()) {
thread.interrupt();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static String getWinner() {
Long minTime = null;
String nameWinner = null;
for (String name : competitors.keySet()) {
Long currentTime = competitors.get(name);
if (minTime == null || (minTime.compareTo(currentTime) > 0)) {
nameWinner = name;
minTime = currentTime;
}
}
return ("Winner is " + nameWinner);
}
}
|
package main.java.kashiish.autotext.autocorrect;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import main.java.kashiish.autotext.Lexicon;
import main.java.kashiish.autotext.Tree;
/**
* BKTree data structure.
* @author kashish
*
*/
public class BKTree implements Tree {
/* The maximum edit distance a word can have from input word to be considered a similar word/autocorrect word. */
private static final int TOLERANCE = 3;
/* The maximum number of matches to get while searching for similar words. */
private static final int MAX_MATCHES = 10;
/* The maximum number of suggestions to return when {@link #getClosestWords(String)} is called. */
private int maxSuggestions = 3;
/* Root of tree. */
private TreeNode root;
/* The number of words in the tree. */
private int size = 0;
/**
* Creates a new BKTree.
* @param lexicon Lexicon, words to add to the BKTree
* @throws IOException
*/
public BKTree(Lexicon lexicon) throws IOException {
createTree(lexicon);
}
/**
* Creates a new BKTree object with specified file of words to add to the tree.
* @throws IOException
*/
public BKTree(String fileName) throws IOException {
createTree(new Lexicon(fileName));
}
/**
* Inserts a new word into the BKTree.
* @param word String
*/
@Override
public void insertWord(String word) {
if(word == null || word.length() == 0)
throw new IllegalArgumentException("String is not valid.");
//remove everthing except letters
word = word.toLowerCase().replaceAll("[^a-z]", "");
if(root == null) {
root = new TreeNode(word);
this.size++;
return;
}
TreeNode current = root;
int distance = getDistance(word, current.getValue());
while(current.getChild(distance) != null && distance != 0) {
current = current.getChild(distance);
distance = getDistance(word, current.getValue());
}
current.addChild(new TreeNode(word, distance));
this.size++;
}
@Override
public int getNumWords() {
return this.size;
}
/**
* Sets the maximum number of autocorrected words to return.
* @param matches int
*/
@Override
public void setMaxMatches(int matches) {
this.maxSuggestions = matches;
}
/**
* Gets a list of words from the BKTree that have the shortest edit distance from
* the input word.
* @param word String
* @return ArrayList<String>
*/
public ArrayList<String> getClosestWords(String word) {
//Get closest words (edit distance within TOLERANCE)
HashSet<CloseWord> closeWords = getCloseWords(word);
//The shortest distance found within `closeWords`
int shortestDistance = Integer.MAX_VALUE;
//All the words with the `shortestDistance`
ArrayList<String> closestWords = new ArrayList<String>();
//find the shortest edit distance within `closeWords`
for(CloseWord closeWord : closeWords) {
if(closeWord.distance < shortestDistance)
shortestDistance = closeWord.distance;
}
//Get all the words with the `shortestDistance`
for(CloseWord closeWord : closeWords) {
if(closeWord.distance == shortestDistance) closestWords.add(closeWord.word);
if(closestWords.size() == maxSuggestions) break;
}
return closestWords;
}
/* CloseWord class contains a word and its distance from the queried word. */
private class CloseWord {
String word;
int distance;
public CloseWord(String word, int distance) {
this.word = word;
this.distance = distance;
}
}
/*
* Gets a set of the words that have edit distance within the specified tolerance (static variable)
* from the input word.
* @param word String
* @return HashSet<String>
*/
private HashSet<CloseWord> getCloseWords(String word) {
HashSet<CloseWord> closeWords = new HashSet<CloseWord>();
if(word.equals("")) return closeWords;
getCloseWords(closeWords, root, word.toLowerCase().replaceAll("[^a-z]", ""));
return closeWords;
}
/*
* Recursive helper function that traverses the root's children that have edit distance
* within the range of `TOLERANCE` from the input `word`. Adds root value to
* `closeWords` if edit distance is less than or equal to <TOLERANCE>.
* @param closeWords HashSet<String>
* @param root TreeNode
* @param word String
*/
private void getCloseWords(HashSet<CloseWord> closeWords, TreeNode root, String word) {
if(root == null) return;
if(closeWords.size() == MAX_MATCHES) return;
int distance = getDistance(word, root.getValue());
int minDist = (distance - TOLERANCE);
int maxDist = (distance + TOLERANCE);
if(distance <= TOLERANCE)
closeWords.add(new CloseWord(root.getValue(), distance));
for(int i = minDist; i <= maxDist; i++) {
TreeNode node = root.getChild(i);
if(node != null)
getCloseWords(closeWords, node, word);
}
}
/*
* Calculates the edit distance between two strings using Damerau-Levenshtein's Distance weighted for
* QWERTY keyboard.
* @param wordA String
* @param wordB String
* @return double Edit distance between input strings
*/
private int getDistance(String wordA, String wordB) {
if(wordA.length() == 0 || wordB.length() == 0) return Math.max(wordA.length(), wordB.length());
int m = wordA.length();
int n = wordB.length();
int[][] memo = new int[m + 1][n + 1];
getDistanceUtil(wordA, wordB, m, n, memo);
return memo[m][n];
}
/*
* Helper recursive function for {@link #getDistance(String, String)}.
* @param wordA String
* @param wordB String
* @param i int, index of current character in wordA
* @param j int, index of current character in wordB
* @param memo double[][], used to store previously calculated results
* @return double edit distance between substrings wordA[i:m] and wordB[j:n]
*/
private int getDistanceUtil(String wordA, String wordB, int i, int j, int[][] memo) {
if(i == 0 && j == 0) return 0;
if(i == 0 || j == 0) return Math.max(i, j) + 2;
if(memo[i][j] != 0) return memo[i][j];
if(wordA.charAt(i - 1) == wordB.charAt(j - 1))
return memo[i][j] = getDistanceUtil(wordA, wordB, i - 1, j - 1, memo);
boolean keysAreClose = keysAreClose(wordA.charAt(i - 1), wordB.charAt(j - 1));
boolean isTransposed = isTransposed(wordA, wordB, i, j);
int substitutionWeight = !keysAreClose && isTransposed ? -2 : (keysAreClose ? 0 : 1) + (isTransposed ? 0 : 1);
int substitute = getDistanceUtil(wordA, wordB, i - 1, j - 1, memo) + substitutionWeight;
/*
* Adds one to the value if the previous character is not the same as current character and
* subtracts one if it is the same.
* Helps decrease the edit distance if a character is typed consecutively or is missing a repeated letter.
* For example "catle" -> "cattle" or "mapple" -> "maple"
*/
int insert = getDistanceUtil(wordA, wordB, i, j - 1, memo) + (samePreviousChar(wordB, j) ? -1 : 1);
int delete = getDistanceUtil(wordA, wordB, i - 1, j, memo) + (samePreviousChar(wordA, i) ? -1 : 1);
return memo[i][j] = Math.min(substitute, Math.min(insert, delete)) + 1;
}
/*
* Checks if the previous character before index k in the word is the same as
* the character at index k.
* @param word String
* @param k int, index of current character
* @return boolean
*/
private boolean samePreviousChar(String word, int k) {
if(word.length() < 3) return false;
if(k == word.length()) {
return word.charAt(k - 1) == word.charAt(k - 2);
} else {
return word.charAt(k) == word.charAt(k - 1);
}
}
/*
* Determines if a character from one string is transposed in the other.
* @param wordA String
* @param wordB String
* @param i int, index of wordA character
* @param j int, index of wordB character
* @return boolean
*/
private boolean isTransposed(String wordA, String wordB, int i, int j) {
return i > 1 && j > 1 && wordA.charAt(i - 2) == wordB.charAt(j - 1) && wordA.charAt(i - 1) == wordB.charAt(j - 2);
}
/*
* This function determines if two keys (chars) are close to each other on a QWERTY
* keyboard.
* Thank you to @scott @StackOverflow https://stackoverflow.com/questions/7079183/how-to-check-efficiently-if-two-characters-are-neighbours-on-the-keyboard
* @param a char
* @param b char
* @return boolean
*/
private boolean keysAreClose(char a, char b) {
/*
* Assign numbers to each character determined by the key position on qwerty keyboard.
* The first row has 10 letters and middle row has 9. 10 - 9 = 1, so the middle row characters have an additional 0.1 added.
* The last row has 7 letters, so last row characters have an additional 0.3 added.
*/
double[] chars = new double[]{10.1, 24.3, 22.3, 12.1, 2, 13.1, 14.1, 15.1, 7, 16.1, 17.1, 18.1,
26.3, 25.3, 8, 9, 0, 3, 11.1, 4, 6, 23.3, 1, 21.3, 5, 20.3};
double one = chars[a - 97];
double two = chars[b - 97];
double val = Math.abs(one - two);
return ((double) Math.round(val * 10) / 10 == 1 || val > 9 && val <= 11);
}
}
|
package events;
import java.lang.reflect.Method;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import fwk.ControllerFactory;
import fwk.XMLMappingLoader;
/**
* Processing events from button of the view
*
* @author Yuliya
*/
public class EventHandler implements ActionListener {
// object of ControllerFactory for creating controller object
private ControllerFactory factory;
// loads mapping of pair view - controller from xml file
private XMLMappingLoader loader = XMLMappingLoader.getLoader();
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
factory = ControllerFactory.getFactory();
// getting component that generated the event
JButton comp = (JButton) e.getSource();
// retrieve class of the view from object that generated the event
Class<?> view_class = comp.getParent().getParent().getParent().getParent().getClass();
String button_name = e.getActionCommand();
// using reflection for getting controller class
try {
// getting controller class from manager by the view class
Class<?> controller_class = loader.getControllerClass(view_class);
Method method = controller_class.getMethod(button_name);
// getting controller object from controller factory
Object object = factory.getControllerObject(controller_class);
// invoking controller method through reflection
method.invoke(object);
} catch (Exception ex2) {
ex2.printStackTrace();
}
}
}
|
/*
* 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.jorgeivanmeza.oasimple.elements;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author educacion
*/
public class Entry
{
public String name;
public String path;
public String title;
public EntryType type;
public String icon;
protected String content;
protected transient List<Entry> entries;
public Entry()
{
entries = new ArrayList<Entry>();
type = EntryType.PAGE;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public EntryType getType() {
return type;
}
public void setType(EntryType type) {
this.type = type;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public List<Entry> getEntries() {
return entries;
}
public void setEntries(List<Entry> entries) {
this.entries = entries;
}
public void addEntry(Entry e)
{
entries.add(e);
}
public Entry getEntry(int index)
{
return entries.get(index);
}
public int entriesCount()
{
return entries.size();
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
|
package com.github.vinja.util;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class SystemJob extends Thread {
private int jobId;
private String[] cmdArray;
private String workDir;
private String vimServerName;
private boolean runInShell = false;
private String uuid;
private String bufname;
private String origCmdLine;
//private Preference pref = Preference.getInstance();
private ScheduledExecutorService exec = null;
private StringBuffer buffer = new StringBuffer();
private Process process ;
private StreamGobbler stdOut = null;
private StreamGobbler stdErr = null;
private OutputStream stdIn = null;
public SystemJob(int jobId,String cmd,String vimServerName,String cmdShell,
String bufname,String workDir,String origCmdLine) {
this.jobId = jobId;
this.cmdArray = cmd.split("::");
this.vimServerName = vimServerName;
this.uuid = IdGenerator.getUniqueId();
this.bufname = bufname;
this.workDir = workDir;
this.origCmdLine = origCmdLine;
if (cmdShell !=null && cmdShell.equalsIgnoreCase("true")) {
runInShell = true;
}
BufferStore.put(uuid, buffer);
}
public void feedInput(String input) {
try {
byte[] bytes = input.getBytes();
stdIn.write(bytes);
stdIn.flush();
//feeded string also goes to output
buffer.append(new String(bytes));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
if (runInShell) {
String[] newCmdArray = new String[4];
newCmdArray[0] = "cmd.exe";
newCmdArray[1] = "/s";
newCmdArray[2] = "/c";
StringBuffer resolvedCmdLine = new StringBuffer();
for (int i=0; i<cmdArray.length; i++) {
resolvedCmdLine.append(cmdArray[i]).append(" ");
}
newCmdArray[3] = resolvedCmdLine.toString();
process = Runtime.getRuntime().exec(newCmdArray,null, new File(workDir));
} else {
process = Runtime.getRuntime().exec(cmdArray,null, new File(workDir));
}
stdOut=new StreamGobbler(buffer, process.getInputStream());
stdErr=new StreamGobbler(buffer, process.getErrorStream());
stdIn = process.getOutputStream();
stdOut.start();
stdErr.start();
/*
int timeOut = 60 * 10 ;
String timeOutStr = pref.getValue(Preference.JDE_RUN_TIMEOUT);
try {
timeOut = Integer.parseInt(timeOutStr);
} catch (NumberFormatException e) {
}
*/
exec = Executors.newScheduledThreadPool(1);
exec.scheduleAtFixedRate(new BufferChecker(this.jobId), 1, 100, TimeUnit.MILLISECONDS);
/*
exec.schedule(new Runnable() {
public void run() {
process.destroy();
exec.shutdown();
}
}, timeOut, TimeUnit.SECONDS);
*/
process.waitFor();
exec.shutdown();
} catch (Exception err) {
buffer.append(err.getMessage());
} finally {
if (exec !=null ) { exec.shutdown(); }
//wait max 3 seconds till stdout gobbler finished.
int count = 0;
while (true) {
if (stdOut == null || !stdOut.isAlive()) break;
if (count > 30 ) break;
try {
sleep(100);
count++;
} catch (Exception e) {
}
}
buffer.append("\n");
buffer.append( "(" + origCmdLine + " finished.)");
//run buffer checker last time
new BufferChecker(this.jobId).run();
SystemJobManager.finishJob(this.jobId);
}
}
class BufferChecker implements Runnable {
private int jobId;
public BufferChecker(int jobId) {
this.jobId = jobId;
}
public void run() {
synchronized (buffer) {
if ( ! (buffer.length() > 0)) return;
String[] args = new String[] { uuid,bufname };
VjdeUtil.callVimFunc(vimServerName, "FetchResult", args);
SystemJobManager.setLastJobId(jobId);
}
}
}
}
|
package Cargame;
import java.util.*;
import java.io.*;
public class CarBL {
public static void main(String [] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Press Enter to start");
String readString = scanner.nextLine();
while(readString!=null) {
System.out.println(readString);
}
}
}
|
package com.tencent.mm.plugin.honey_pay.model;
import com.tencent.mm.sdk.e.e;
import com.tencent.mm.sdk.e.i;
public final class b extends i<a> {
public static final String[] diD = new String[]{i.a(a.dhO, "HoneyPayMsgRecord")};
private static final String[] eBa = new String[]{"*", "rowid"};
private e diF;
public b(e eVar) {
super(eVar, a.dhO, "HoneyPayMsgRecord", null);
this.diF = eVar;
}
}
|
package com.erpambudi.moviecatalogue.ui.tvshow;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.erpambudi.moviecatalogue.BuildConfig;
import com.erpambudi.moviecatalogue.R;
import com.erpambudi.moviecatalogue.adapter.MoviesAdapter;
import com.erpambudi.moviecatalogue.model.Movies;
import com.erpambudi.moviecatalogue.model.MoviesItems;
import com.erpambudi.moviecatalogue.rest.ApiClient;
import com.erpambudi.moviecatalogue.rest.ApiInterface;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class TvShowFragment extends Fragment {
public static final String TV_SHOW_KEY = "tv_show_key";
private RecyclerView rvTvSow;
private List<Movies> list;
private MoviesAdapter tvShowAdapter;
private ProgressBar progressBar;
private ApiInterface apiServise = ApiClient.getClient().create(ApiInterface.class);
public TvShowFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_tvshow, container, false);
rvTvSow = root.findViewById(R.id.rv_tv_show);
rvTvSow.setHasFixedSize(true);
progressBar = root.findViewById(R.id.progressBar);
showRecyclerList();
if (savedInstanceState == null){
getDataTvShow();
}else {
onActivityCreated(savedInstanceState);
}
return root;
}
private void showRecyclerList(){
rvTvSow.setLayoutManager(new LinearLayoutManager(getActivity()));
tvShowAdapter = new MoviesAdapter(getActivity());
}
private void getDataTvShow(){
showLoading(true);
Call<MoviesItems> call = apiServise.getMovie("tv", BuildConfig.API_KEY, getActivity().getResources().getString(R.string.language));
list = new ArrayList<>();
call.enqueue(new Callback<MoviesItems>() {
@Override
public void onResponse(Call<MoviesItems> call, Response<MoviesItems> response) {
if (response.body() != null){
list = response.body().getMoviesList();
}
tvShowAdapter.setListFilm(list);
rvTvSow.setAdapter(tvShowAdapter);
showLoading(false);
}
@Override
public void onFailure(Call<MoviesItems> call, Throwable t) {
Toast.makeText(getContext(), "Can't Load Data", Toast.LENGTH_SHORT).show();
}
});
}
private void showLoading(Boolean state){
if (state){
progressBar.setVisibility(View.VISIBLE);
}else{
progressBar.setVisibility(View.GONE);
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(TV_SHOW_KEY, new ArrayList<>(tvShowAdapter.getListFilm()));
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null){
ArrayList<Movies> list;
list = savedInstanceState.getParcelableArrayList(TV_SHOW_KEY);
tvShowAdapter.setListFilm(list);
rvTvSow.setAdapter(tvShowAdapter);
}
}
}
|
package com.example.libroapp.ui.home;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.ViewModelProviders;
import com.example.libroapp.ConnectionSql;
import com.example.libroapp.ItemAdapter;
import com.example.libroapp.R;
import com.example.libroapp.detailAct;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
Resources res = getResources();
String[] Libros;
final String[] ISVarray;
final String[] Autor;
ArrayList<String> titulos = new ArrayList<>();
ArrayList<String> ISBN = new ArrayList<>();
ArrayList<String> autor = new ArrayList<>();
String sql = "select libro.nombre,libro.isbn, group_concat(autor.nombre) as autores from libro join autor_libro on libro.idlibro = autor_libro.idlibro join autor on autor.idautor = autor_libro.idautor group by libro.idlibro, libro.nombre;";
try {
ConnectionSql con = new ConnectionSql(sql, 1);
Thread threadQuery = new Thread(con);
threadQuery.start();
threadQuery.join();
ResultSet output = con.getOutput();
while (output.next()) {
titulos.add(output.getString(1));
ISBN.add(output.getString(2));
autor.add(output.getString(3));
}
con.desconectar();
} catch (InterruptedException | SQLException e) {
e.printStackTrace();
}
ListView listview = root.findViewById(R.id.myListView);
Libros = titulos.toArray(new String[0]);
ISVarray = ISBN.toArray(new String[0]);
Autor = autor.toArray(new String[0]);
ItemAdapter itemadapter = new ItemAdapter(requireActivity(), Libros, ISVarray,Autor);
listview.setAdapter(itemadapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager manager = getFragmentManager();
String autor=ISVarray[position];
detailAct nuevo=new detailAct();
Bundle Arguments=new Bundle();
Arguments.putInt("INDEX",position);
Arguments.putString("ISV",autor);
nuevo.setArguments(Arguments);
manager.beginTransaction().replace(R.id.nav_host_fragment, nuevo).commit();
}
});
return root;
}
}
|
package com.rofour.baseball.controller.model;
import java.io.Serializable;
/**
* @ClassName: Ztree
* @Description: ztree Model
* @author ZhangLei
* @date 2016年5月11日 下午7:24:11
*
*/
public class SimpleZtree implements Serializable {
private static final long serialVersionUID = -1476850311068162763L;
private String id;
private String name;
private String pId;
private boolean isParent;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getpId() {
return pId;
}
public void setpId(String pId) {
this.pId = pId;
}
public boolean getIsParent() {
return isParent;
}
public void setIsParent(boolean isParent) {
this.isParent = isParent;
}
public SimpleZtree(){}
public SimpleZtree(String id, String name) {
super();
this.id = id;
this.name = name;
}
}
|
package com.zhonghuilv.shouyin.controller;
import com.zhonghuilv.shouyin.common.BasicController;
import com.zhonghuilv.shouyin.mapper.StockinDetailsMapper;
import com.zhonghuilv.shouyin.pojo.OrderDetails;
import com.zhonghuilv.shouyin.pojo.StockinDetails;
import com.zhonghuilv.shouyin.result.ApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by llk2014 on 2018-07-04 17:13:48
*/
@RestController
@RequestMapping("/stockin_details")
@Api(value = "StockinDetailsController", description = "库存入库详情表")
public class StockinDetailsController extends BasicController<StockinDetails> {
private StockinDetailsMapper stockinDetailsMapper;
@Autowired
public StockinDetailsController(StockinDetailsMapper stockinDetailsMapper) {
super(stockinDetailsMapper);
this.stockinDetailsMapper =stockinDetailsMapper;
}
@Override
@ApiOperation(value = "新增入库详情",notes = "新增入库详情",tags = "库存管理",response = StockinDetails.class)
@PostMapping(value = "")
public ApiResult<StockinDetails> save(@RequestBody StockinDetails model){
return super.save(model);
}
}
|
package lesson5;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Movie movie1 = new Movie("The one living boy in new york", new Time(65, 200));
Movie movie2 = new Movie("The hunt", new Time(1, 40));
Movie movie3 = new Movie("The Call of the Wild", new Time(2, 0));
Movie movie4 = new Movie("Dolittle", new Time(1, 35));
Movie movie5 = new Movie("Extraction", new Time(1, 56));
Movie movie6 = new Movie("1917", new Time(2, 25));
Seance seance1 = new Seance(movie1, new Time(20, 0));
Seance seance2 = new Seance(movie2, new Time(9, 0));
Seance seance3 = new Seance(movie3, new Time(17, 0));
Seance seance4 = new Seance(movie4, new Time(10, 1));
Seance seance5 = new Seance(movie5, new Time(14, 20));
Seance seance6 = new Seance(movie6, new Time(16, 0));
Schedule schedule1 = new Schedule();
Schedule schedule2 = new Schedule();
schedule1.addSeance(seance1);
schedule1.addSeance(seance2);
schedule1.addSeance(seance3);
TreeMap<Days, Schedule> scheduleForCinema1 = new TreeMap<>();
scheduleForCinema1.put(Days.MONDAY, schedule1);
Cinema cinema1 = new Cinema(scheduleForCinema1,
new Time(8, 20), new Time(22, 30));
TreeMap<Days, Schedule> scheduleForCinema2 = new TreeMap<>();
scheduleForCinema2.put(Days.TUESDAY, schedule2);
Cinema cinema2 = new Cinema(scheduleForCinema2, new Time(7, 30),
new Time(20, 40));
cinema1.addSeances("MONDAY", seance1, seance2, seance3);
System.out.println("========Added Seances or Seance. Cinema1==========");
System.out.println(cinema1);
cinema2.addSeances("TUESDAY", seance4, seance5, seance6);
System.out.println("========Added Seances or Seance. Cinema2==========");
System.out.println(cinema2);
cinema1.removeMovie(movie1);
System.out.println("=========Removed Movie1=========");
System.out.println(cinema1);
cinema1.removeSeance(seance2, Days.MONDAY);
System.out.println("=========Removed Seance2=========");
System.out.println(cinema1);
}
}
// 1. Розібратись як працює compareTo в String
// 2. Розібратись як загалом працює compareTo :)
//
// Даний проект має такі сутності: Days, Time, Movie, Seance, Schedule, Cinema.
// enum Days:
// - прописати дні тижня;
// Time:
// - int min, int hour;
// - передбачити межі для цих полів (для min 0..59, для hour 0..23);
// Movie:
// - String title, Time duration;
// Seance:
// - Movie movie, Time startTime, Time endTime;
// - в конструктор має надходити параметрами значення для перших двох полів,
// третє поле повинне обчислюватись (start + duration);
// Schedule:
// - TreeSet <Seance> (в полі пишемо Set <Seance>, а в конструкторі вже =new TreeSet <Seance>() );
// - Сортування по startTime.
// - методи: addSeance (Seance), removeSeance (Seance);
// Cinema:
// - TreeMap<Days, Schedule>, Time open, Time close;
// - врахувати час відкриття і закриття при формуванні сеансів!
// - методи: addSeances (String day, Seance...seance) (додає набір сеансів в конкретний день),
// addSeance (Seance, String) (додає один сеанс в конкретний день), removeMovie(Movie)
// (повністю видаляє усі сеанси вказаного фільму з розкладу), removeSeance (Seance, String)
// (видаляє конкретний сеанс фільму в конкретний день, який задається параметром String).
//
// Main class:
// - створення об'єкту Cinema;
// - викликаємо всі методи Cinema
//
// Для кожного класу зробити адекватний toString, щоб все було читабельно і доступно.
// Там де потрібно, зробити compareTo(). Маєте якісь власні ідеї для розробки - будь-ласка.
// Це моделювання роботи кінотеатру, тому все що наблизить програму до реальності вітається.
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.frontend.client.widget.properties;
import java.util.Collection;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HasAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.openkm.frontend.client.Main;
import com.openkm.frontend.client.bean.GWTDocument;
import com.openkm.frontend.client.bean.GWTFolder;
import com.openkm.frontend.client.bean.GWTPermission;
import com.openkm.frontend.client.bean.GWTUser;
import com.openkm.frontend.client.constants.ui.UIDesktopConstants;
import com.openkm.frontend.client.service.OKMDocumentService;
import com.openkm.frontend.client.service.OKMDocumentServiceAsync;
import com.openkm.frontend.client.util.Util;
import com.openkm.frontend.client.widget.properties.CategoryManager.CategoryToRemove;
import com.openkm.frontend.client.widget.properties.KeywordManager.KeywordToRemove;
import com.openkm.frontend.client.widget.thesaurus.ThesaurusSelectPopup;
/**
* Document
*
* @author jllort
*
*/
public class Document extends Composite {
private final OKMDocumentServiceAsync documentService = (OKMDocumentServiceAsync) GWT.create(OKMDocumentService.class);
private FlexTable tableProperties;
private FlexTable tableSubscribedUsers;
private FlexTable table;
private GWTDocument document;
private HTML subcribedUsersText;
private HorizontalPanel hPanelSubscribedUsers;
private CategoryManager categoryManager;
private KeywordManager keywordManager;
private ScrollPanel scrollPanel;
private boolean remove = true;
/**
* Document
*/
public Document() {
categoryManager = new CategoryManager(CategoryManager.ORIGIN_DOCUMENT);
keywordManager = new KeywordManager(ThesaurusSelectPopup.DOCUMENT_PROPERTIES);
document = new GWTDocument();
table = new FlexTable();
tableProperties = new FlexTable();
tableSubscribedUsers = new FlexTable();
scrollPanel = new ScrollPanel(table);
tableProperties.setHTML(0, 0, "<b>"+Main.i18n("document.uuid")+"</b>");
tableProperties.setHTML(0, 1, "");
tableProperties.setHTML(1, 0, "<b>"+Main.i18n("document.name")+"</b>");
tableProperties.setHTML(1, 1, "");
tableProperties.setHTML(2, 0, "<b>"+Main.i18n("document.folder")+"</b>");
tableProperties.setHTML(3, 1, "");
tableProperties.setHTML(3, 0, "<b>"+Main.i18n("document.size")+"</b>");
tableProperties.setHTML(4, 1, "");
tableProperties.setHTML(4, 0, "<b>"+Main.i18n("document.created")+"</b>");
tableProperties.setHTML(5, 1, "");
tableProperties.setHTML(5, 0, "<b>"+Main.i18n("document.lastmodified")+"</b>");
tableProperties.setHTML(5, 1, "");
tableProperties.setHTML(6, 0, "<b>"+Main.i18n("document.mimetype")+"</b>");
tableProperties.setHTML(6, 1, "");
tableProperties.setHTML(7, 0, "<b>"+Main.i18n("document.keywords")+"</b>");
tableProperties.setHTML(7, 1, "");
tableProperties.setHTML(8, 0, "<b>"+Main.i18n("document.status")+"</b>");
tableProperties.setHTML(8, 1, "");
tableProperties.setHTML(9, 0, "<b>"+Main.i18n("document.subscribed")+"</b>");
tableProperties.setHTML(9, 1, "");
tableProperties.setHTML(10, 0, "<b>"+Main.i18n("document.history.size")+"</b>");
tableProperties.setHTML(10, 1, "");
tableProperties.setHTML(11, 0, "<b>"+Main.i18n("document.url")+"</b>");
tableProperties.setWidget(11, 1, new HTML(""));
tableProperties.setHTML(12, 0, "<b>"+Main.i18n("document.webdav")+"</b>");
tableProperties.setWidget(12, 1, new HTML(""));
tableProperties.getCellFormatter().setVerticalAlignment(7, 0, HasAlignment.ALIGN_TOP);
// Sets the tagcloud
keywordManager.getKeywordCloud().setWidth("350px");
VerticalPanel vPanel2 = new VerticalPanel();
hPanelSubscribedUsers = new HorizontalPanel();
subcribedUsersText = new HTML("<b>"+Main.i18n("document.subscribed.users")+"<b>");
hPanelSubscribedUsers.add(subcribedUsersText);
hPanelSubscribedUsers.add(new HTML(" "));
hPanelSubscribedUsers.setCellVerticalAlignment(subcribedUsersText, HasAlignment.ALIGN_MIDDLE);
vPanel2.add(hPanelSubscribedUsers);
vPanel2.add(tableSubscribedUsers);
HTML space2 = new HTML("");
vPanel2.add(space2);
vPanel2.add(keywordManager.getKeywordCloudText());
vPanel2.add(keywordManager.getKeywordCloud());
HTML space3 = new HTML("");
vPanel2.add(space3);
vPanel2.add(categoryManager.getPanelCategories());
vPanel2.add(categoryManager.getSubscribedCategoriesTable());
vPanel2.setCellHeight(space2, "10px");
vPanel2.setCellHeight(space3, "10px");
table.setWidget(0, 0, tableProperties);
table.setHTML(0, 1, "");
table.setWidget(0, 2, vPanel2);
// The hidden column extends table to 100% width
CellFormatter cellFormatter = table.getCellFormatter();
cellFormatter.setWidth(0, 1, "25px");
cellFormatter.setVerticalAlignment(0, 0, HasAlignment.ALIGN_TOP);
cellFormatter.setVerticalAlignment(0, 2, HasAlignment.ALIGN_TOP);
// Sets wordWrap for al rows
for (int i=0; i<11; i++) {
setRowWordWarp(i, 0, true, tableProperties);
}
setRowWordWarp(0, 0, true, tableSubscribedUsers);
tableProperties.setStyleName("okm-DisableSelect");
tableSubscribedUsers.setStyleName("okm-DisableSelect");
initWidget(scrollPanel);
}
/**
* Set the WordWarp for all the row cells
*
* @param row The row cell
* @param columns Number of row columns
* @param warp
* @param table The table to change word wrap
*/
private void setRowWordWarp(int row, int columns, boolean warp, FlexTable table) {
CellFormatter cellFormatter = table.getCellFormatter();
for (int i=0; i<columns; i++) {
cellFormatter.setWordWrap(row, i, warp);
}
}
/**
* Sets the document values
*
* @param doc The document object
*/
public void set(GWTDocument doc) {
this.document = doc;
// URL clipboard button
String url = Main.get().workspaceUserProperties.getApplicationURL();
url += "?uuid=" + URL.encodeQueryString(URL.encodeQueryString(document.getUuid()));
tableProperties.setWidget(11, 1, new HTML("<div id=\"urlClipboard\"></div>\n"));
Util.createClipboardButton("urlClipboard", url);
// Webdav button
String webdavUrl = Main.get().workspaceUserProperties.getApplicationURL();
String webdavPath = document.getPath();
// Replace only in case webdav fix is enabled
if (Main.get().workspaceUserProperties.getWorkspace() != null && Main.get().workspaceUserProperties.getWorkspace().isWebdavFix()) {
webdavPath = webdavPath.replace("okm:", "okm_");
}
// Login case write empty folder
if (!webdavUrl.isEmpty()) {
webdavPath = Util.encodePathElements(webdavPath);
webdavUrl = webdavUrl.substring(0, webdavUrl.lastIndexOf('/')) + "/webdav" + webdavPath;
}
tableProperties.setWidget(12, 1, new HTML("<div id=\"webdavClipboard\"></div>\n"));
Util.createClipboardButton("webdavClipboard", webdavUrl);
tableProperties.setHTML(0, 1, doc.getUuid());
tableProperties.setHTML(1, 1, doc.getName());
tableProperties.setHTML(2, 1, doc.getParentPath());
tableProperties.setHTML(3, 1, Util.formatSize(doc.getActualVersion().getSize()));
DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.date.pattern"));
tableProperties.setHTML(4, 1, dtf.format(doc.getCreated())+" "+Main.i18n("document.by")+" " + doc.getUser().getUsername());
tableProperties.setHTML(5, 1, dtf.format(doc.getLastModified())+" "+Main.i18n("document.by")+" " + doc.getActualVersion().getUser().getUsername());
tableProperties.setHTML(6, 1, doc.getMimeType());
tableProperties.setWidget(7, 1, keywordManager.getKeywordPanel());
// Enable select
tableProperties.getFlexCellFormatter().setStyleName(0, 1, "okm-EnableSelect");
tableProperties.getFlexCellFormatter().setStyleName(1, 1, "okm-EnableSelect");
tableProperties.getFlexCellFormatter().setStyleName(2, 1, "okm-EnableSelect");
remove = ((doc.getPermissions() & GWTPermission.WRITE) == GWTPermission.WRITE && !doc.isCheckedOut() &&
!(doc.isLocked() && !doc.getLockInfo().getOwner().equals(Main.get().workspaceUserProperties.getUser())));
if (doc.isCheckedOut()) {
tableProperties.setHTML(8, 1, Main.i18n("document.status.checkout")+" " + doc.getLockInfo().getUser().getUsername());
} else if (doc.isLocked()) {
tableProperties.setHTML(8, 1, Main.i18n("document.status.locked")+" " + doc.getLockInfo().getUser().getUsername());
} else {
tableProperties.setHTML(8, 1, Main.i18n("document.status.normal"));
}
if (doc.isSubscribed()) {
tableProperties.setHTML(9, 1, Main.i18n("document.subscribed.yes"));
} else {
tableProperties.setHTML(9, 1, Main.i18n("document.subscribed.no"));
}
// Enables or disables change keywords with user permissions and document is not check-out or locked
if (remove) {
keywordManager.setVisible(true);
categoryManager.setVisible(true);
} else {
keywordManager.setVisible(false);
categoryManager.setVisible(false);
}
getVersionHistorySize();
// Sets wordWrap for al rows
for (int i=0; i<11; i++) {
setRowWordWarp(i, 1, true, tableProperties);
}
// Remove all table rows
tableSubscribedUsers.removeAllRows();
// Sets the document subscribers
for (GWTUser subscriptor : doc.getSubscriptors() ) {
tableSubscribedUsers.setHTML(tableSubscribedUsers.getRowCount(), 0, subscriptor.getUsername());
setRowWordWarp(tableSubscribedUsers.getRowCount()-1, 0, true, tableSubscribedUsers);
}
int actualView = Main.get().mainPanel.desktop.navigator.getStackIndex();
// Some data must not be visible on personal view
if (actualView == UIDesktopConstants.NAVIGATOR_PERSONAL) {
subcribedUsersText.setVisible(false);
tableSubscribedUsers.setVisible(false);
} else {
subcribedUsersText.setVisible(true);
tableSubscribedUsers.setVisible(true);
}
// keywords
keywordManager.reset();
keywordManager.setObject(doc, remove);
keywordManager.drawAll();
// Categories
categoryManager.removeAllRows();
categoryManager.setObject(doc, remove);
categoryManager.drawAll();
}
/**
* Lang refresh
*/
public void langRefresh() {
tableProperties.setHTML(0, 0, "<b>"+Main.i18n("document.uuid")+"</b>");
tableProperties.setHTML(1, 0, "<b>"+Main.i18n("document.name")+"</b>");
tableProperties.setHTML(2, 0, "<b>"+Main.i18n("document.folder")+"</b>");
tableProperties.setHTML(3, 0, "<b>"+Main.i18n("document.size")+"</b>");
tableProperties.setHTML(4, 0, "<b>"+Main.i18n("document.created")+"</b>");
tableProperties.setHTML(5, 0, "<b>"+Main.i18n("document.lastmodified")+"</b>");
tableProperties.setHTML(6, 0, "<b>"+Main.i18n("document.mimetype")+"</b>");
tableProperties.setHTML(7, 0, "<b>"+Main.i18n("document.keywords")+"</b>");
tableProperties.setHTML(8, 0, "<b>"+Main.i18n("document.status")+"</b>");
tableProperties.setHTML(9, 0, "<b>"+Main.i18n("document.subscribed")+"</b>");
tableProperties.setHTML(10, 0, "<b>"+Main.i18n("document.history.size")+"</b>");
tableProperties.setHTML(11, 0, "<b>"+Main.i18n("document.url")+"</b>");
tableProperties.setHTML(12, 0, "<b>"+Main.i18n("document.webdav")+"</b>");
subcribedUsersText.setHTML("<b>"+Main.i18n("document.subscribed.users")+"<b>");
keywordManager.langRefresh();
categoryManager.langRefresh();
if (document != null) {
DateTimeFormat dtf = DateTimeFormat.getFormat(Main.i18n("general.date.pattern"));
if (document.getCreated() != null) {
tableProperties.setHTML(4, 1, dtf.format(document.getCreated())+" "+Main.i18n("document.by")+" " + document.getUser().getUsername());
}
if (document.getLastModified() != null) {
tableProperties.setHTML(5, 1, dtf.format(document.getLastModified())+" "+Main.i18n("document.by")+" " + document.getActualVersion().getUser().getUsername());
}
if (document.isCheckedOut()) {
tableProperties.setHTML(8, 1, Main.i18n("document.status.checkout")+" " + document.getLockInfo().getUser().getUsername());
} else if (document.isLocked()) {
tableProperties.setHTML(8, 1, Main.i18n("document.status.locked")+" " + document.getLockInfo().getUser().getUsername());
} else {
tableProperties.setHTML(8, 1, Main.i18n("document.status.normal"));
}
if (document.isSubscribed()) {
tableProperties.setHTML(9, 1, Main.i18n("document.subscribed.yes"));
} else {
tableProperties.setHTML(9, 1, Main.i18n("document.subscribed.no"));
}
}
}
/**
* Callback GetVersionHistorySize document
*/
final AsyncCallback<Long> callbackGetVersionHistorySize = new AsyncCallback<Long>() {
public void onSuccess(Long result) {
tableProperties.setHTML(10, 1, Util.formatSize(result.longValue()));
Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetGetVersionHistorySize();
}
public void onFailure(Throwable caught) {
Main.get().mainPanel.desktop.browser.tabMultiple.status.unsetGetVersionHistorySize();
Main.get().showError("GetVersionHistorySize", caught);
}
};
/**
* getVersionHistorySize document
*/
public void getVersionHistorySize() {
Main.get().mainPanel.desktop.browser.tabMultiple.status.setGetVersionHistorySize();
documentService.getVersionHistorySize(document.getUuid(), callbackGetVersionHistorySize);
}
/**
* addKeyword document
*/
public void addKeyword(String keyword) {
keywordManager.addKeyword(keyword);
}
/**
* removeKeyword document
*/
public void removeKeyword(String keyword) {
keywordManager.removeKeyword(keyword);
}
/**
* addCategory document
*/
public void addCategory(GWTFolder category) {
categoryManager.addCategory(category);
}
/**
* removeCategory document
*/
public void removeCategory(String UUID) {
categoryManager.removeCategory(UUID);
}
/**
* removeCategory
*
* @param category
*/
public void removeCategory(CategoryToRemove obj) {
categoryManager.removeCategory(obj);
}
/**
* Sets visibility to buttons ( true / false )
*
* @param visible The visible value
*/
public void setVisibleButtons(boolean visible) {
keywordManager.setVisible(visible);
categoryManager.setVisible(visible);
}
/**
* Removes a key
*
* @param keyword The key to be removed
*/
public void removeKey(String keyword) {
keywordManager.removeKey(keyword);
}
/**
* removeKeyword
*
* @param ktr
*/
public void removeKeyword(KeywordToRemove ktr) {
keywordManager.removeKeyword(ktr);
}
/**
* addKeywordToPendinList
*
* @param key
*/
public void addKeywordToPendinList(String key) {
keywordManager.addKeywordToPendinList(key);
}
/**
* Adds keywords sequentially
*
*/
public void addPendingKeyWordsList() {
keywordManager.addPendingKeyWordsList();
}
/**
* getKeywords
*
* @return
*/
public Collection<String> getKeywords() {
return document.getKeywords();
}
/**
* @param enabled
*/
public void setKeywordEnabled(boolean enabled) {
keywordManager.setKeywordEnabled(enabled);
}
/**
* showAddCategory
*/
public void showAddCategory() {
categoryManager.showAddCategory();
}
/**
* showRemoveCategory
*/
public void showRemoveCategory() {
categoryManager.showRemoveCategory();
}
/**
* showAddKeyword
*/
public void showAddKeyword() {
keywordManager.showAddKeyword();
}
/**
* showRemoveKeyword
*/
public void showRemoveKeyword() {
keywordManager.showRemoveKeyword();
}
}
|
/**
* @author throwable
* @version v1.0
* @description jsr-303 hibernate-validator implement
* @since 2017/6/16 12:26
*/
package org.throwable.validators;
|
package pl.cwanix.opensun.agentserver.packets.s2c.connection;
import org.apache.commons.lang3.ArrayUtils;
import pl.cwanix.opensun.agentserver.packets.AgentServerPacketOPCode;
import pl.cwanix.opensun.model.character.CharacterModel;
import pl.cwanix.opensun.agentserver.packets.structures.ClientCharacterPartPacketStructure;
import pl.cwanix.opensun.commonserver.packets.Packet;
import pl.cwanix.opensun.commonserver.packets.annotations.OutgoingPacket;
import pl.cwanix.opensun.utils.datatypes.FixedLengthField;
import java.util.List;
import java.util.stream.Collectors;
@SuppressWarnings("checkstyle:MagicNumber")
@OutgoingPacket(category = AgentServerPacketOPCode.Connection.CATEGORY, operation = AgentServerPacketOPCode.Connection.Ans.ENTER_SERVER)
public class S2CAnsEnterServerPacket implements Packet {
private final FixedLengthField userId;
private final FixedLengthField charCount;
private final FixedLengthField unknown;
private final List<ClientCharacterPartPacketStructure> charactersList;
public S2CAnsEnterServerPacket(final int userId, final List<CharacterModel> characterModelList) {
this.userId = new FixedLengthField(4, userId);
this.charCount = new FixedLengthField(1, characterModelList.size());
this.unknown = new FixedLengthField(1, characterModelList.size()); //TODO: ???
this.charactersList = convertCharacterEntityListToClientCharacterPartPacketStructureList(characterModelList);
}
private List<ClientCharacterPartPacketStructure> convertCharacterEntityListToClientCharacterPartPacketStructureList(final List<CharacterModel> characterModelList) {
return characterModelList
.stream()
.map(ClientCharacterPartPacketStructure::new)
.collect(Collectors.toList());
}
@Override
public Object[] getOrderedFields() {
return ArrayUtils.toArray(userId, charCount, unknown, charactersList);
}
}
|
package ru.mmk.okpposad.server.dao;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import ru.mmk.okpposad.server.domain.Posad;
@Repository
public class PosadDaoImpl implements PosadDao {
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public List<Posad> listByDate(String dateFrom, String dateTo) {
List<Posad> result = new ArrayList<Posad>();
// String sql = "select * from posad_plav";
// List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
// String sql = "select * from posad_plav where date between ? and ?";
String sql = "gwt_posad.report_data ?, ?";
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, new Object[] { dateFrom, dateTo });
int rowNumber = 1;
for (Map<String, Object> row : rows) {
Posad posad1 = new Posad();
Posad posad2 = new Posad();
posad1.setId(((BigDecimal) row.get("ID")).intValueExact());
posad2.setId(((BigDecimal) row.get("ID")).intValueExact());
posad1.setRowNumber(rowNumber);
posad2.setRowNumber(rowNumber);
posad1.setDate((Date) row.get("DATE"));
posad2.setDate((Date) row.get("DATE"));
int convNum1 = (Integer) row.get("CONV_NUM1");
int convNum2 = (Integer) row.get("CONV_NUM2");
int meltNum1 = (Integer) row.get("MELT_NUM1");
int meltNum2 = (Integer) row.get("MELT_NUM2");
int longMeltNum1 = convNum1 * 100000 + meltNum1;
int longMeltNum2 = convNum2 * 100000 + meltNum2;
posad1.setMeltNum(longMeltNum1);
posad2.setMeltNum(longMeltNum2);
posad1.setMark(row.get("MARK1") + "");
posad2.setMark(row.get("MARK2") + "");
posad1.setMnlzNum((Integer) row.get("MNLZ_NUM"));
posad2.setMnlzNum((Integer) row.get("MNLZ_NUM"));
posad1.setSection(row.get("THICK") + " x " + row.get("WIDTH"));
posad2.setSection(row.get("THICK") + " x " + row.get("WIDTH"));
posad1.setTechWaste(((BigDecimal) row.get("TECH_WASTE1")).doubleValue());
posad2.setTechWaste(((BigDecimal) row.get("TECH_WASTE2")).doubleValue());
posad1.setBrak(((BigDecimal) row.get("BRAK1")).doubleValue());
posad2.setBrak(((BigDecimal) row.get("BRAK2")).doubleValue());
posad1.setNpCount((int) row.get("NP_COUNT1"));
posad2.setNpCount((int) row.get("NP_COUNT2"));
posad1.setNpWeight(((BigDecimal) row.get("NP_WEIGHT1")).doubleValue());
posad2.setNpWeight(((BigDecimal) row.get("NP_WEIGHT2")).doubleValue());
posad1.setLgCount((int) row.get("LG_COUNT1"));
posad2.setLgCount((int) row.get("LG_COUNT2"));
posad1.setLgWeight(((BigDecimal) row.get("LG_WEIGHT1")).doubleValue());
posad2.setLgWeight(((BigDecimal) row.get("LG_WEIGHT2")).doubleValue());
posad1.setReason((String) row.get("REASON"));
posad2.setReason((String) row.get("REASON"));
result.add(posad1);
result.add(posad2);
rowNumber++;
}
return result;
}
@Override
public void updateReasonById(Integer id, String userName, String reason) {
String sql = "update gwt_posad.posad_plav set upd_date=getdate(), upd_name=?, reason=? where id = ?";
jdbcTemplate.update(sql, new Object[] { userName, reason, id });
}
@Override
public void removeById(Integer id, String userName) {
String sql = "gwt_posad.remove_posad @id=?, @user_name=?";
jdbcTemplate.update(sql, new Object[] { id, userName });
}
}
|
package com.rekoe.test.client;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import com.rekoe.msg.BaseIoMessage;
import com.rekoe.msg.cs.CSLoginMessage;
/**
* @author 科技㊣²º¹³
* Feb 16, 2013 2:35:33 PM
* http://www.rekoe.com
* QQ:5382211
*/
public class SimpleClientHandler extends SimpleChannelUpstreamHandler {
private final static Log log = Logs.get();
@Override
public void messageReceived(ChannelHandlerContext ctx, org.jboss.netty.channel.MessageEvent e)
throws Exception {
Object message = e.getMessage();
if(message == null || !(message instanceof BaseIoMessage)) {
return;
}
//if(e.getMessage() instanceof LoginResult)
{
//LoginResult loginReslut = (LoginResult)e.getMessage();
//log.info(loginReslut.getResult());
}
log.info(e.getMessage());
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
//模拟登录
CSLoginMessage loginMessage = new CSLoginMessage("iwan", "?name=rekoe", (byte)1);
e.getChannel().write(loginMessage);
}
}
|
package extra_Practices;
public abstract class home {
String omr="Omer";
public home(String omr) {
this.omr=omr;
System.out.println("Hello from parent"+ omr);
}
static{
System.out.println("Static block in home");
}
{
System.out.println("Initilaztion block in home");
}
public abstract void balcony();
}
|
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.EbenheitType;
import java.io.StringWriter;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
public class EbenheitTypeBuilder
{
public static String marshal(EbenheitType ebenheitType)
throws JAXBException
{
JAXBElement<EbenheitType> jaxbElement = new JAXBElement<>(new QName("TESTING"), EbenheitType.class , ebenheitType);
StringWriter stringWriter = new StringWriter();
return stringWriter.toString();
}
private String ebenheit;
private Double ebenheitAmplitudeMitte;
private Double ebenheitAmplitudeRand;
public EbenheitTypeBuilder setEbenheit(String value)
{
this.ebenheit = value;
return this;
}
public EbenheitTypeBuilder setEbenheitAmplitudeMitte(Double value)
{
this.ebenheitAmplitudeMitte = value;
return this;
}
public EbenheitTypeBuilder setEbenheitAmplitudeRand(Double value)
{
this.ebenheitAmplitudeRand = value;
return this;
}
public EbenheitType build()
{
EbenheitType result = new EbenheitType();
result.setEbenheit(ebenheit);
result.setEbenheitAmplitudeMitte(ebenheitAmplitudeMitte);
result.setEbenheitAmplitudeRand(ebenheitAmplitudeRand);
return result;
}
}
|
package chc;
/** used to test the bitmask during development of chc.
*/
public class TestBitMask {
/** Constructed a new bit mask and then printed out the
* size and the values of all the masks. The values should
* correspond to those found in the MLJ-Options.file.
*/
public static void main(String[] args) {
BitMask bm = new BitMask();
System.out.println(bm.size());
System.out.println(bm.getDisplayString());
}
}
|
/*
* 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 pastesitessearch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author utente
*/
public abstract class SiteParserCommon implements SiteParser {
/**
* The url of the Paste site
*/
protected final String pasteSiteUrl;
/**
* The url of the Paste site that return the raw content instead of the html
* page
*/
protected final String rawUrlString;
SearchingPattern searchingPattern;
String lastContentPage;
String remoteID;
// Pattern che sono stati matchati
private Set<String> patterns_matched;
SiteParserCommon(String site, String rawContentUrl, SearchingPattern searchingPattern) {
this.searchingPattern = searchingPattern;
this.pasteSiteUrl = site;
this.rawUrlString = rawContentUrl;
}
/**
* Get the content of the Paste sited addressed by remoteUrl
*
* @param remoteUrl The url of the page to be downloaded
* @return The content page or throws an exception in case of error (the
* return value is null).
* @throws MalformedURLException
* @throws IOException
*/
protected String getPage(String remoteUrl) throws MalformedURLException, IOException {
URL url = new URL(remoteUrl);
URLConnection conn = url.openConnection();
String retval = null;
InputStream remoteData = null;
BufferedReader br = null;
try {
remoteData = conn.getInputStream();
br = new BufferedReader(new InputStreamReader(remoteData, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
retval = sb.toString();
} catch (IOException ioe) {
if (conn instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection) conn;
int statusCode = httpConn.getResponseCode();
if (statusCode != 200) {
remoteData = httpConn.getErrorStream(); // Future use
}
}
} finally {
if (br != null) {
br.close();
}
}
return (retval);
}
@Override
public abstract Set<String> getAndParsedArchivePage() throws IOException;
@Override
public String getRemoteContent(String remoteID) throws IOException {
this.remoteID = remoteID;
String urlString = rawUrlString + remoteID;
lastContentPage = getPage(urlString);
return (lastContentPage);
}
@Override
public boolean parseContentPage(String remoteID) throws IOException {
Set<Pattern> patterns = searchingPattern.getPattern().keySet();
patterns_matched = new HashSet<>();
boolean retval = false;
getRemoteContent(remoteID);
for (Pattern p : patterns) {
Matcher m = p.matcher(lastContentPage);
while (m.find()) {
// TODO: Tenere conto dei match per formare un indice rappresentativo di cosa è stato trovato
// Ad esempio numero matches/tot matches
patterns_matched.add(p.toString());
retval = true;
}
}
return (retval);
}
@Override
public String getLastContent() {
return (lastContentPage);
}
@Override
public String getLastRemoteIdParsed() {
return (remoteID);
}
@Override
public Set<String> getMatchedPatterns() {
return patterns_matched;
}
@Override
public String pasteSiteUrl() {
return pasteSiteUrl;
}
@Override
public String pastSiteRawContentUrl() {
return rawUrlString;
}
}
|
package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BOJ_7490_0만들기 {
private static int N;
private static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for (int i = 0; i < T; i++) {
N = Integer.parseInt(br.readLine());
dfs(2,12, new StringBuilder("1 2"));
dfs(1,1, new StringBuilder("1"));
sb.append("\n");
}
System.out.println(sb);
}
private static void dfs(int i ,int sum, StringBuilder str) {
if(i == N) {
if(sum == 0)
sb.append(str).append("\n");
return;
}
if(i+2 <= N) {
// 붙어있는 수
int num = ((i+1)*10+(i+2));
dfs(i+2,sum+num,str.append("+").append(i+1).append(" " +(i+2)));
str.setLength(str.length()-4);
}
dfs(i+1,sum+(i+1),str.append("+").append(i+1));
str.setLength(str.length()-2);
if(i+2 <= N) {
// 붙어있는 수
int num = ((i+1)*10+(i+2));
dfs(i+2,sum-num,str.append("-").append(i+1).append(" " +(i+2)));
str.setLength(str.length()-4);
}
dfs(i+1,sum-(i+1),str.append("-").append(i+1));
str.setLength(str.length()-2);
}
}
|
package model.persistence;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.List;
import model.interfaces.IShapeDraw;
import model.shapes.Shape;
public class ShapeDrawer implements IShapeDraw{
@Override
public void drawAllShapes(Graphics2D graphics2d, List<Shape> shapeList) {
for (Shape shape : shapeList) {
if(shape.getName().equals("Rectangle")) {
graphics2d.fillRect(shape.getPointX(), shape.getPointY(), shape.getWidth(), shape.getHeight());
}else if(shape.getName().equals("Triangle")){
}else {
}
}
}
@Override
public void clearCanvais(Graphics2D graphics2d) {
graphics2d.setColor(Color.white);
graphics2d.fillRect(0, 0, 100000, 100000);
graphics2d.setColor(Color.black);
}
}
|
package com.anydecisions.controller.register;
import java.sql.SQLException;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.anydecisions.bean.WebUser;
import com.anydecisions.bean.register.UserData;
import com.anydecisions.service.register.RegistrationService;
@Controller
@RequestMapping(value = "/register")
public class RegistrationController {
@Autowired
RegistrationService regService;
@RequestMapping(method = RequestMethod.POST)
public ModelAndView registerUser(
@RequestParam(value = "firstName") String firstName,
@RequestParam(value = "lastName") String lastName,
@RequestParam(value = "emailId") String emailId,
@RequestParam(value = "userName") String userName,
@RequestParam(value = "password") String password,
@RequestParam(value = "webUsertype", required = false, defaultValue = "ROLE_USER") String webUserTypeName,
@RequestParam(value = "isActivated", required = false, defaultValue = "Y") String isActivated,
HttpServletRequest request, @Valid WebUser webUser, BindingResult result) {
ModelAndView model;
if (result.hasErrors()) {
model = new ModelAndView("register");
} else {
model = new ModelAndView("registerSuccess");
try {
webUser.setWebUserTypeName(webUserTypeName);
webUser.setIsActivated(isActivated);
regService.registerUser(webUser);
} catch (SQLException e) {
e.printStackTrace();
} catch (NamingException e) {
e.printStackTrace();
}
model.addObject("firstName", firstName);
model.addObject("lastName", lastName);
model.addObject("emailId", emailId);
}
return model;
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public static ModelAndView showLogin(ModelMap model) {
model.addAttribute("webUser", new WebUser());
return new ModelAndView("register");
}
}
|
package com.mwj.bean;
import java.util.Date;
public class Employees {
private Integer employeeId;
private String empName;
private String email;
private String phoneNumber;
private Date hireDate;
private String jobId;
private Integer salary;
private Integer departmentId;
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName == null ? null : empName.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber == null ? null : phoneNumber.trim();
}
public Date getHireDate() {
return hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
public String getJobId() {
return jobId;
}
public void setJobId(String jobId) {
this.jobId = jobId == null ? null : jobId.trim();
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
@Override
public String toString() {
return "Employees{" +
"employeeId=" + employeeId +
", empName='" + empName + '\'' +
", email='" + email + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", hireDate=" + hireDate +
", jobId='" + jobId + '\'' +
", salary=" + salary +
", departmentId=" + departmentId +
'}';
}
}
|
package com.example.davidmacak.etzen;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class Score extends AppCompatActivity {
Context context;
String[][] list = new String[20][3];
LinearLayout[] linearLayout = new LinearLayout[26];
LinearLayout[] linearLayoutDruhy = new LinearLayout[26];
LinearLayout[] linearLayoutTreti = new LinearLayout[26];
LinearLayout linearLayoutScoreMain;
TableRow[] tableRowPrvni = new TableRow[26];
TableRow[] tableRowDruhy = new TableRow[26];
Button[] buttonPrvni = new Button[26];
Button[] buttonDruhy = new Button[26];
Button[] buttonTreti = new Button[26];
LinearLayout.LayoutParams layoutParams;
int poradi = 0;
int control = 1;
FirebaseDatabase database;
FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.score);
context = this;
linearLayoutScoreMain = findViewById(R.id.layoutScoreMainScroll);
mAuth = FirebaseAuth.getInstance();
mAuth.signInAnonymously();
database= FirebaseDatabase.getInstance();
for(int q=1;q<11;q++){
getScore(q);
}
}
private void getScore(final int level){
final DatabaseReference myRef = database.getReference(String.valueOf(level));
final Query query = myRef.orderByValue();
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
control++;
if(dataSnapshot.getValue()!=null){
for(DataSnapshot snapshot:dataSnapshot.getChildren()){
if(poradi<3 && snapshot.getValue()!=null){
list[level][poradi] = snapshot.getKey()+" - "+ snapshot.getValue();
poradi++;
}
}
}
if(control==11){
vykresliSkore();
}
poradi = 0;
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void vykresliSkore(){
for(int level=1;level<11;level++) {
layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TableRow.LayoutParams paramsButton = new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams paramsNextRow = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
linearLayout[level] = new LinearLayout(context);
linearLayout[level].setLayoutParams(layoutParams);
linearLayout[level].setOrientation(LinearLayout.VERTICAL);
linearLayoutDruhy[level] = new LinearLayout(context);
linearLayoutTreti[level] = new LinearLayout(context);
tableRowPrvni[level] = new TableRow(context);
tableRowPrvni[level].setGravity(Gravity.CENTER);
tableRowPrvni[level].setLayoutParams(layoutParams);
tableRowPrvni[level].setPadding(0, 50, 0, 0);
tableRowDruhy[level] = new TableRow(context);
tableRowDruhy[level] = new TableRow(context);
tableRowDruhy[level].setGravity(Gravity.CENTER);
tableRowDruhy[level].setLayoutParams(layoutParams);
linearLayoutDruhy[level].setLayoutParams(paramsNextRow);
linearLayoutTreti[level].setLayoutParams(paramsNextRow);
linearLayoutTreti[level].setPadding(0, 50, 0, 0);
buttonPrvni[level] = new Button(context);
buttonPrvni[level].setBackground(getDrawable(R.drawable.border_skore));
buttonPrvni[level].setElevation(4);
buttonPrvni[level].setText(list[level][0]);
buttonPrvni[level].setLayoutParams(paramsButton);
buttonDruhy[level] = new Button(context);
buttonDruhy[level].setBackground(getDrawable(R.drawable.border_silver));
buttonDruhy[level].setElevation(4);
buttonDruhy[level].setText(list[level][1]);
buttonDruhy[level].setLayoutParams(paramsButton);
buttonTreti[level] = new Button(context);
buttonTreti[level].setBackground(getDrawable(R.drawable.border_bronze));
buttonTreti[level].setElevation(4);
buttonTreti[level].setText(list[level][2]);
buttonTreti[level].setLayoutParams(paramsButton);
tableRowPrvni[level].addView(buttonPrvni[level]);
tableRowDruhy[level].addView(buttonDruhy[level]);
tableRowDruhy[level].addView(buttonTreti[level]);
linearLayout[level].addView(tableRowPrvni[level]);
linearLayout[level].addView(tableRowDruhy[level]);
linearLayoutScoreMain.addView(linearLayout[level]);
}
}
}
|
package it.polimi.ingsw.GC_21.VIEW;
import java.util.Scanner;
import javax.naming.TimeLimitExceededException;
import javax.net.ssl.SSLException;
import javax.print.attribute.standard.Copies;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import it.polimi.ingsw.GC_21.ACTION.Action;
import it.polimi.ingsw.GC_21.ACTION.Pass;
import it.polimi.ingsw.GC_21.CLIENT.Connections;
import it.polimi.ingsw.GC_21.CLIENT.TimerThread;
import it.polimi.ingsw.GC_21.GAMECOMPONENTS.Possession;
import it.polimi.ingsw.GC_21.PLAYER.Color;
import it.polimi.ingsw.GC_21.PLAYER.Player;
public class ActionInput extends InputForm {
protected Player player;
public InputForm chooseAction(Player player, TimerThread timerThread) throws ExecutionException, InterruptedException {
System.out.println("Choose your action: " + "\n 1: Tower placement" + "\n 2: Craft placement "
+ "\n 3: Market placement " + "\n 4: Council placement" + "\n 5: Pass" + "\n 6: Play Leader Card" + "\n 7: Discard Leader Card");
boolean blackPlayer = false;
if (player.getPlayerColor() == Color.Black) {
blackPlayer = true;
}
String choice = takeInput(this);
switch (choice) {
case "1":
TowerPlacementInput towerPlacementInput = new TowerPlacementInput(this, input, blackPlayer);
towerPlacementInput.inputFromCli();
return towerPlacementInput;
case "2":
CraftPlacementInput craftPlacementInput = new CraftPlacementInput(this, input, blackPlayer);
craftPlacementInput.inputFromCli();
return craftPlacementInput;
case "3":
MarketPlacementInput marketPlacementInput = new MarketPlacementInput(this, input,blackPlayer);
marketPlacementInput.inputFromCli();
return marketPlacementInput;
case "4":
CouncilPlacementInput councilPlacementInput = new CouncilPlacementInput(this, input, blackPlayer);
councilPlacementInput.inputFromCli();
return councilPlacementInput;
case "5":
PassInput passInput = new PassInput();
passInput.inputFromCli();
return passInput;
case "6":
if (player.getPlayerColor() == Color.Black) {
System.out.println("Invalid input, try again!");
return this.chooseAction(player, timerThread);
}
LeaderInput leaderInput = new LeaderInput(this, input, player);
leaderInput.inputFromCli();
return leaderInput;
case "7":
if (player.getPlayerColor() == Color.Black) {
System.out.println("Invalid input, try again!");
return this.chooseAction(player, timerThread);
}
DiscardInput discardInput = new DiscardInput(this, input, player);
discardInput.inputFromCli();
return discardInput;
default:
System.out.println("Invalid input, try again!");
return this.chooseAction(player, timerThread);
}
}
}
|
package SprESRepo;
import org.elasticsearch.common.collect.Tuple;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by dekorate on 06/03/17.
*/
public class Graph {
Map<Long, ProfileUser> userProfileMap;
Map<Long, Message> messages;
List<Tuple<Long, Long>> links;
public Graph() {
this.userProfileMap = new HashMap<>();
this.messages = new HashMap<>();
this.links = new ArrayList<>();
}
public Graph(Map<Long, ProfileUser> userProfileMap, Map<Long, Message> messages, List<Tuple<Long, Long>> edges) {
this.userProfileMap = userProfileMap;
this.messages = messages;
this.links = edges;
}
public void addLink(Message message) {
ProfileUser user = message.getUser();
this.userProfileMap.put(user.getId(), user);
this.messages.put(message.getId(), message);
this.links.add(Tuple.tuple(user.getId(), message.getId()));
}
public Map<Long, ProfileUser> getUserProfileMap() {
return userProfileMap;
}
public void setUserProfileMap(Map<Long, ProfileUser> userProfileMap) {
this.userProfileMap = userProfileMap;
}
public Map<Long, Message> getMessages() {
return messages;
}
public void setMessages(Map<Long, Message> messages) {
this.messages = messages;
}
public List<Tuple<Long, Long>> getLinks() {
return links;
}
public void setLinks(List<Tuple<Long, Long>> links) {
this.links = links;
}
}
|
package com.demo.total;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
public class SplashScreen extends Activity {
public class SplashView extends View {
private Context mContext;
public SplashView(Context context) {
super(context);
mContext = context;
}
public boolean onTouchEvent(MotionEvent event) {
try {
mContext.startActivity(new Intent("com.demo.total.CLEARSPLASH"));
return (super.onTouchEvent(event));
} finally {
finish();
}
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: if current game is paused then don't display this screen,
// simply start game activity
requestWindowFeature(Window.FEATURE_NO_TITLE);
SplashView mainView = new SplashView(this);
mainView.setBackgroundResource(R.drawable.background);
// setContentView(R.layout.splash);
setContentView(mainView);
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* 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 vanadis.extrt;
import vanadis.core.reflection.Invoker;
import vanadis.core.properties.PropertySet;
import vanadis.ext.Expose;
import vanadis.jmx.ManagedDynamicMBeans;
import java.lang.reflect.Field;
final class FieldExposer<T> extends Exposer<T> {
private final Field field;
FieldExposer(FeatureAnchor<T> featureAnchor, Field field, Expose annotation, ManagedDynamicMBeans mbeans) {
super(featureAnchor, annotation, mbeans);
this.field = field;
}
@Override
protected Object resolveExposedObject(PropertySet runtimePropertySet) {
Object managed = getObjectManager().getManagedObject();
return field == null ? managed : Invoker.getByForce(this, managed, field);
}
}
|
package com.family.model;
import org.springframework.data.mongodb.core.mapping.Document;
@Document
public class Family {
private String familyinitial;
public String getFamilyinitial() {
return familyinitial;
}
public void setFamilyinitial(String familyinitial) {
this.familyinitial = familyinitial;
}
public String getFamilyproper() {
return familyproper;
}
public void setFamilyproper(String familyproper) {
this.familyproper = familyproper;
}
public int getNumberofmember() {
return numberofmember;
}
public void setNumberofmember(int numberofmember) {
this.numberofmember = numberofmember;
}
private String familyproper;
private int numberofmember;
}
|
/*
* 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.condition;
import java.util.List;
import org.apache.commons.lang3.tuple.Pair;
import edu.umich.verdict.VerdictContext;
import edu.umich.verdict.relation.AggregatedRelation;
import edu.umich.verdict.relation.ExactRelation;
import edu.umich.verdict.relation.JoinedRelation;
import edu.umich.verdict.relation.ProjectedRelation;
import edu.umich.verdict.relation.Relation;
import edu.umich.verdict.relation.SingleRelation;
import edu.umich.verdict.relation.expr.ColNameExpr;
import edu.umich.verdict.relation.expr.Expr;
import edu.umich.verdict.relation.expr.SubqueryExpr;
public class CompCond extends Cond {
private Expr left;
private Expr right;
private String compOp;
public CompCond(Expr left, String compOp, Expr right) {
this.left = left;
this.right = right;
this.compOp = compOp;
}
public static CompCond from(VerdictContext vc, Expr left, String compOp, Expr right) {
return new CompCond(left, compOp, right);
}
public static CompCond from(VerdictContext vc, Expr left, String compOp, Relation r) {
return from(vc, left, compOp, SubqueryExpr.from(vc, r));
}
public static CompCond from(VerdictContext vc, String left, String compOp, Relation r) {
return from(vc, Expr.from(vc, left), compOp, SubqueryExpr.from(vc, r));
}
public Expr getLeft() {
return left;
}
public Expr getRight() {
return right;
}
public String getOp() {
return compOp;
}
@Override
public Cond accept(CondModifier v) {
return v.call(this);
}
@Override
public String toString() {
return String.format("%s %s %s", left, compOp, right);
}
@Override
public Pair<Cond, Pair<ExactRelation, ExactRelation>> searchForJoinCondition(List<ExactRelation> tableSources) {
if (compOp.equals("=")) {
if (left instanceof ColNameExpr && right instanceof ColNameExpr) {
String leftTab = ((ColNameExpr) left).getTab();
String rightTab = ((ColNameExpr) right).getTab();
ExactRelation r1 = tableSources.get(0);
ExactRelation r2 = null;
if (doesRelationContain(r1, leftTab)) {
r2 = findSourceContaining(tableSources, rightTab);
} else if (doesRelationContain(r1, rightTab)) {
r2 = findSourceContaining(tableSources, leftTab);
}
if (r2 != null && r1 != r2) {
return Pair.of((Cond) this, Pair.of(r1, r2));
}
// if (!joinedTableAliases.contains(leftTab) &&
// !joinedTableAliases.contains(rightTab)) {
// // the condition does not contain any pre-joined tables.
// if (leftTab != rightTab) {
// return Triple.of((Cond) this, Pair.of(leftTab, rightTab), true);
// }
// } else {
// // if there are some tables that are already joined, a new table must be a
// new table.
// if (joinedTableAliases.contains(leftTab) &&
// !joinedTableAliases.contains(rightTab)) {
// return Triple.of((Cond) this, Pair.of(leftTab, rightTab));
// } else if (!joinedTableAliases.contains(leftTab) &&
// joinedTableAliases.contains(rightTab)) {
// return Triple.of((Cond) this, Pair.of(rightTab, leftTab));
// }
// }
}
}
return null;
}
private ExactRelation findSourceContaining(List<ExactRelation> tableSources, String tab) {
for (ExactRelation r : tableSources) {
if (doesRelationContain(r, tab)) {
return r;
}
}
return null;
}
private boolean doesRelationContain(ExactRelation r, String tab) {
if (r instanceof SingleRelation || r instanceof ProjectedRelation || r instanceof AggregatedRelation) {
if (r.getAlias().equals(tab)) {
return true;
}
} else if (r instanceof JoinedRelation) {
return doesRelationContain(((JoinedRelation) r).getLeftSource(), tab)
|| doesRelationContain(((JoinedRelation) r).getRightSource(), tab);
}
return false;
}
// private String searchForTableName(VerdictContext vc, ColNameExpr col,
// List<TableUniqueName> among) {
// if (col.getTab() != null) {
// return col.getTab();
// } else {
// for (TableUniqueName t : among) {
// Set<String> cols = vc.getMeta().getColumns(t);
// if (cols.contains(col.getCol())) {
// return t.
// }
// }
// }
// }
@Override
public boolean equals(Object a) {
if (a instanceof CompCond) {
if (((CompCond) a).getLeft().equals(left) && ((CompCond) a).getRight().equals(right)
&& ((CompCond) a).getOp().equals(compOp)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public Cond remove(Cond j) {
if (equals(j)) {
return null;
} else {
return this;
}
}
@Override
public Cond withTableSubstituted(String newTab) {
return new CompCond(left.withTableSubstituted(newTab), compOp, right.withTableSubstituted(newTab));
}
@Override
public String toSql() {
return String.format("%s %s %s", left.toSql(), compOp, right.toSql());
}
@Override
public boolean equals(Cond o) {
if (o instanceof CompCond) {
return getOp().equals(((CompCond) o).getOp()) && getLeft().equals(((CompCond) o).getLeft())
&& getRight().equals(((CompCond) o).getRight());
}
return false;
}
}
|
// **********************************************************************
// This file was generated by a TAF parser!
// TAF version 3.2.1.6 by WSRD Tencent.
// Generated from `/data/jcetool/taf//upload/opalli/pitu_meta_protocol.jce'
// **********************************************************************
package NS_PITU_META_PROTOCOL;
public final class eMaterialFeedItemType implements java.io.Serializable
{
public static final int _eMaterialFeedItemTypeImage = 0;
public static final int _eMaterialFeedItemTypeVideo = 1;
}
|
package net.asurovenko.netexam.ui.teacher_screen.exam_results;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.h6ah4i.android.widget.advrecyclerview.expandable.RecyclerViewExpandableItemManager;
import net.asurovenko.netexam.R;
import net.asurovenko.netexam.network.models.Exam;
import net.asurovenko.netexam.network.models.ExamResults;
import net.asurovenko.netexam.ui.base.BaseFragment;
import net.asurovenko.netexam.ui.teacher_screen.MainTeacherFragment;
import net.asurovenko.netexam.utils.ServerUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
public class ExamResultsFragment extends BaseFragment {
@Bind(R.id.recycler_view)
RecyclerView examResultsRecyclerView;
@Bind(R.id.exam_title)
TextView examTitle;
@Bind(R.id.exam_semester)
TextView examSemester;
@Bind(R.id.progress_bar)
ProgressBar progressBar;
@Bind(R.id.error_text)
TextView errorText;
private String token;
private int examId;
public static ExamResultsFragment newInstance(Exam exam, String token) {
Bundle args = new Bundle();
args.putString(MainTeacherFragment.TOKEN_KEY, token);
args.putInt(MainTeacherFragment.EXAM_ID_KEY, exam.getId());
args.putString(MainTeacherFragment.EXAM_TITLE_KEY, exam.getName());
args.putInt(MainTeacherFragment.SEMESTER_KEY, exam.getSemester());
ExamResultsFragment fragment = new ExamResultsFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_exam_results, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final Bundle bundle = getArguments();
if (bundle != null) {
token = bundle.getString(MainTeacherFragment.TOKEN_KEY);
examId = bundle.getInt(MainTeacherFragment.EXAM_ID_KEY);
examTitle.setText(bundle.getString(MainTeacherFragment.EXAM_TITLE_KEY));
examSemester.setText(String.valueOf(bundle.getInt(MainTeacherFragment.SEMESTER_KEY))
+ getString(R.string.semester_little_char));
loadExamResults();
}
}
private void loadExamResults() {
getNetExamApi().getExamResults(token, examId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::completeLoadExamResults, this::errorLoad);
}
private void errorLoad(Throwable error) {
showSnackBar(ServerUtils.getMsgId(error));
progressBar.setVisibility(View.GONE);
errorText.setVisibility(View.VISIBLE);
}
private void completeLoadExamResults(ExamResults examResults) {
List<List<ExamResults.Student>> groups = new ArrayList<>();
List<String> groupsTitle = new ArrayList<>();
for (Map.Entry<String, ExamResults.Group> entry : examResults.getGroups().entrySet()) {
groupsTitle.add(entry.getKey());
List<ExamResults.Student> item = new ArrayList<>();
item.addAll(entry.getValue().getStudents());
groups.add(item);
}
progressBar.setVisibility(View.GONE);
setupExpandableRecyclerView(groups, groupsTitle);
}
private void setupExpandableRecyclerView(List<List<ExamResults.Student>> groups, List<String> groupsTitle) {
RecyclerViewExpandableItemManager expMgr = new RecyclerViewExpandableItemManager(null);
examResultsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
examResultsRecyclerView.setAdapter(expMgr.createWrappedAdapter(new ExamResultsAdapter(groups, groupsTitle)));
((SimpleItemAnimator) examResultsRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
expMgr.attachRecyclerView(examResultsRecyclerView);
}
}
|
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.niubimq.dao;
import java.util.List;
import com.niubimq.pojo.Producer;
/**
* 生产者Dao服务
* @author junjin4838
*
*/
public interface ProducerManageDao {
/**
* 查询生产者信息
* */
List<Producer> selectProducer(String producerSign);
/**
* 新增生产者信息
* */
void insertProducer(Producer producer);
/**
* 删除生产者信息
* */
void deleteProducer(Producer p);
/**
* 修改生产者信息
* */
void updateProducer(Producer producer);
}
|
package com.example.myreadproject8.ui.adapter.booksource;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.myreadproject8.R;
import com.example.myreadproject8.greendao.entity.Book;
import com.example.myreadproject8.ui.adapter.holder.ViewHolderImpl;
import com.example.myreadproject8.util.source.BookSourceManager;
/**
* @author fengyue
* @date 2020/9/30 18:43
*/
public class SourceExchangeHolder extends ViewHolderImpl<Book> {
//书源标题
TextView sourceTvTitle;
//书源最新章节
TextView sourceTvChapter;
//是否选中
ImageView sourceIv;
//获取布局
@Override
protected int getItemLayoutId() {
return R.layout.item_change_source;
}
@Override
public void initView() {
sourceTvTitle = findById(R.id.tv_source_name);
sourceTvChapter = findById(R.id.tv_lastChapter);
sourceIv = findById(R.id.iv_checked);
}
//设置表项
@Override
public void onBind(Book data, int pos) {
sourceTvTitle.setText(BookSourceManager.getSourceNameByStr(data.getSource()));
sourceTvChapter.setText(data.getNewestChapterTitle());
if (Boolean.parseBoolean(data.getNewestChapterId()))
sourceIv.setVisibility(View.VISIBLE);
else
sourceIv.setVisibility(View.GONE);
}
}
|
package com.elepy.annotations;
import com.elepy.auth.Permissions;
import com.elepy.handlers.DefaultDelete;
import com.elepy.handlers.DeleteHandler;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation used to change the way Elepy handles deletes.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Delete {
/**
* The class that handles the functionality of deletes on this Resource.
*
* @return the route deleteHandler
* @see DefaultDelete
* @see com.elepy.handlers.DeleteHandler
*/
Class<? extends DeleteHandler> handler() default DefaultDelete.class;
/**
* A list of required permissions to execute this A
*/
String[] requiredPermissions() default Permissions.AUTHENTICATED;
}
|
package com.zhao.leetcode;
//17.12
public class TreeToLinkList2 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(){}
TreeNode(int x) { val = x; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
private TreeNode dummyHead =new TreeNode();
private TreeNode tail = dummyHead;
public TreeNode convertBiNode(TreeNode root) {
inorder(root);
return dummyHead.right;
}
private void inorder(TreeNode root){
if (root==null) return;
TreeNode left =root.left;
TreeNode right = root.right;
inorder(left);
tail.right =root;
tail=root;
root.left =null;
inorder(right);
}
}
|
/**
*
*/
/**
* @author jinweizhang
*
*/
public class LengthOfLastWord {
/**
* @param args
*
* Given a string s consists of upper/lower-case alphabets and empty
* space characters ' ', return the length of last word in the
* string.
*
* If the last word does not exist, return 0.
*
* Note: A word is defined as a character sequence consists of
* non-space characters only.
*
* Example:
*
* Input: "Hello World" Output: 5
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
class SolutionLengthOfLastWord {
public int lengthOfLastWord(String s) {
String[] outcome = s.split(" ");
return outcome.length > 0 ? outcome[outcome.length - 1].length() : 0;
}
}
|
package dao;
import java.util.ArrayList;
import entity.Order;
import exception.DAOException;
public interface IOrderDAO {
public ArrayList<Order> queryAll() throws DAOException;
public Order queryById(int orderId) throws DAOException;
public void insert(Order order) throws DAOException;
public void update(Order order) throws DAOException;
public void delete(int id) throws DAOException;
public int getMaxId() throws DAOException;
public ArrayList<Order> queryByUserId(int userId) throws DAOException;
}
|
package com.example.appBack.Tablas.Student.application;
import com.example.appBack.Tablas.Student.application.port.CreateStudentPort;
import com.example.appBack.Tablas.Student.domain.Student;
import com.example.appBack.Tablas.Student.infrastructure.repositorio.port.SaveCreateStudentPort;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@AllArgsConstructor
public class CreateStudentUseCase implements CreateStudentPort {
private SaveCreateStudentPort saveCreateStudentPort;
@Override
public Student create(Student student) throws Exception{
return saveCreateStudentPort.addStudent(student);
}
}
|
package com.takshine.wxcrm.base.util;
import java.util.Random;
import java.util.UUID;
import org.neo4j.cypher.internal.compiler.v2_1.docbuilders.internalDocBuilder;
public class Get32Primarykey {
/***
* 随机产生32位16进制字符串
* @return
*/
public static String getRandom32PK(){
return UUID.randomUUID().toString().replaceAll("-", "");
}
/***
* 随机产生32位16进制字符串,以时间开头
* @return
*/
public static String getRandom32BeginTimePK(){
String timeStr = DateTime.currentDateTime("yyyyMMddHHmmssSSS");
String random32 = getRandom32PK();
return timeStr+random32.substring(17,random32.length());
}
/***
* 随机产生32位16进制字符串,以时间结尾
* @return
*/
public static String getRandom32EndTimePK(){
String timeStr = DateTime.currentDateTime("yyyyMMddHHmmssSSS");
String random32 = getRandom32PK();
return random32.substring(0,random32.length()-17)+timeStr;
}
/**
* 获取随机的验证码
* @return
*/
public static String getRandomValiteCode(int size){
if(size <= 0) size = 6;//默认6位
String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
Random random = new Random();//随机种子
String rst = "";//返回值
for (int i = 0; i < size; i++) {
rst += randString.charAt(random.nextInt(36));
}
return rst;
}
/**
* 获取8位随机字符串
* @return
*/
public static String get8RandomValiteCode(int size){
if(size <= 0) size = 8;//默认8位
String randString = "0123456789";//随机产生的字符串
Random random = new Random();//随机种子
String rst = "";//返回值
for (int i = 0; i < size; i++) {
rst += randString.charAt(random.nextInt(10));
}
return rst;
}
public static void main(String[] args) {
System.out.println("随机验证码6位:"+getRandomValiteCode(6));
System.out.println("随机"+Get32Primarykey.getRandom32PK().length()+"位:"+Get32Primarykey.getRandom32PK());
System.out.println("随机"+Get32Primarykey.getRandom32BeginTimePK().length()+"位以时间打头:"+Get32Primarykey.getRandom32BeginTimePK());
System.out.println("随机"+Get32Primarykey.getRandom32EndTimePK().length()+"位以时间结尾:"+Get32Primarykey.getRandom32EndTimePK());
System.out.println(get8RandomValiteCode(8));
}
}
|
/*
* 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 SCBGerenciamento;
import java.sql.*;
import java.util.ArrayList;
/**
*
* @author silvi
*/
public class Container {
private String container;
private String cliente;
private int tipo;
private int status;
private int categoria;
public Container(String container, String cliente, int tipo, int status, int categoria) {
this.container = container;
this.cliente = cliente;
this.tipo = tipo;
this.status = status;
this.categoria = categoria;
}
public static ArrayList<Container> listar(){
ArrayList<Container> list = new ArrayList<>();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
con = DBListener.connection();
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM containers;");
while(rs.next()){
list.add(new Container(
rs.getString("cd_container"),
rs.getString("cliente"),
rs.getInt("tipo"),
rs.getInt("status"),
rs.getInt("categoria")
));
}
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
try{
con.close();
stmt.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
return list;
}
public static void inseir(String container, String cliente, int tipo, int status, int categoria) throws SQLException{
Connection con = null;
PreparedStatement stmt = null;
try{
con = DBListener.connection();
stmt = con.prepareStatement("INSERT INTO containers VALUES (?,?,?,?,?);");
stmt.setString(1, container);
stmt.setString(2, cliente);
stmt.setInt(3, tipo);
stmt.setInt(4, status);
stmt.setInt(5, categoria);
stmt.execute();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
try{
con.close();
stmt.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
public static void deletar(String container) throws SQLException{
Connection con = null;
PreparedStatement stmt = null;
try{
con = DBListener.connection();
stmt = con.prepareStatement("DELETE FROM containers WHERE cd_container = ?;");
stmt.setString(1, container);
stmt.execute();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
try{
con.close();
stmt.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
public String getContainer() {
return container;
}
public void setContainer(String container) {
this.container = container;
}
public String getCliente() {
return cliente;
}
public void setCliente(String cliente) {
this.cliente = cliente;
}
public int getTipo() {
return tipo;
}
public void setTipo(int tipo) {
this.tipo = tipo;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getCategoria() {
return categoria;
}
public void setCategoria(int categoria) {
this.categoria = categoria;
}
}
|
import java.util.Scanner;
import java.io.*;
public class Over_avg{
public static int average(int[] arr){
int avg=0;
int count=0;
for(int i=0;i<arr.length;i++){
avg=avg+arr[i];
count++;
}
avg=avg/count;
return avg;
}
public static double average(double[] arr){
double avg=0.0;
double count=0.0;
for(int i=0;i<arr.length;i++){
avg=avg+arr[i];
count++;
}
avg=avg/count;
return avg;
}
public static void main(String[] args) {
int[] iarr = { 1,2,3,4,5};
double[] darr = { 1.1,2.1,3.5 };
System.out.println(average(iarr));
System.out.println(average(darr));
}
}
|
package com.behzad.spring5webapp.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class Guid {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String guidDescription;
@OneToMany(cascade = CascadeType.ALL , mappedBy = "guid")
private Set<Student> students = new HashSet<Student>();
public String getGuidDescription() {
return guidDescription;
}
public void setGuidDescription(String guidDescription) {
this.guidDescription = guidDescription;
}
@Override
public String toString() {
return "Guid{" +
"id=" + id +
", guidDescription='" + guidDescription + '\'' +
", students=" + students +
'}';
}
public Set<Student> getStudents() {
return students;
}
}
|
package graphics;
import listeners.DownButtonListener;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Created by Brian on 16/3/24.
*/
public class DownButton extends JButton {
private String image = "images/SmallDownArrow.png";
private int column;
private Board board;
// Constructor
public DownButton(int column, Board board) {
this.column = column;
this.board = board;
setImage();
this.setSize(50, 50);
this.addActionListener(new DownButtonListener(board, this));
}
public void setImage() {
// JLabel pic;
//
// BufferedImage myPicture = null;
// try {
// myPicture = ImageIO.read(new File(image));
// } catch (IOException e) {
// System.out.println(image);
// e.printStackTrace();
// }
// pic = new JLabel(new ImageIcon(myPicture));
// this.add(pic);
this.add(new JLabel("X"));
}
public int getColumn() {
return column;
}
}
|
package com.tencent.tencentmap.mapsdk.a;
import com.qq.jutil.string.StringUtil;
import java.util.ArrayList;
public class al {
String a;
int b;
int c;
int d;
int e;
ay f;
int g;
public au h;
int i;
int j;
boolean k;
long l;
String m;
String n;
String o;
String p;
private int q;
public int a() {
return this.c;
}
public String toString() {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(c() + "@");
for (bb d : this.h.c()) {
stringBuffer.append(d.d() + ":");
}
String stringBuffer2 = stringBuffer.toString();
if (stringBuffer2.endsWith(":")) {
return stringBuffer2.substring(0, stringBuffer2.length() - 1);
}
return stringBuffer2;
}
public void a(au auVar) {
this.h = auVar;
}
public String b() {
StringBuffer stringBuffer = new StringBuffer();
for (bb c : this.h.c()) {
stringBuffer.append(c.c() + ":");
}
String stringBuffer2 = stringBuffer.toString();
if (stringBuffer2.endsWith(":")) {
return stringBuffer2.substring(0, stringBuffer2.length() - 1);
}
return stringBuffer2;
}
public static ai<ArrayList<bb>, ArrayList<bb>> a(String str, int i, int i2, int i3, String str2) {
ArrayList arrayList = new ArrayList();
ArrayList arrayList2 = new ArrayList();
for (String a : StringUtil.split(str2, ":")) {
bb a2 = bb.a(str, a, i, i2, i3);
if (a2.g()) {
arrayList.add(a2);
} else {
arrayList2.add(a2);
}
}
ai<ArrayList<bb>, ArrayList<bb>> aiVar = new ai();
aiVar.a = arrayList;
aiVar.b = arrayList2;
return aiVar;
}
public boolean equals(Object obj) {
return (obj instanceof al) && ((al) obj).q == this.q;
}
public int hashCode() {
return this.q;
}
public String c() {
return this.a;
}
public int d() {
return this.e;
}
public ay e() {
return this.f;
}
public String f() {
return this.n;
}
public String g() {
return this.o;
}
public String h() {
return this.p;
}
}
|
package eu.lsem.bakalarka.filetypeprocess.archives;
import java.io.File;
import java.io.IOException;
public interface ArchiveDecompressor {
public void unpackFiles(File archive, File path) throws IOException;
}
|
package com.tencent.mm.plugin.exdevice.model;
import android.os.Looper;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.exdevice.h.a;
import com.tencent.mm.plugin.exdevice.j.b;
import com.tencent.mm.plugin.exdevice.service.c;
import com.tencent.mm.plugin.exdevice.service.f$a;
import com.tencent.mm.plugin.exdevice.service.j;
import com.tencent.mm.plugin.exdevice.service.u;
import com.tencent.mm.plugin.exdevice.service.w;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.al;
import com.tencent.mm.sdk.platformtools.x;
import java.util.HashMap;
public final class d {
private static int iti = 0;
public c itd;
private w ite;
HashMap<Long, al> itf;
HashMap<Long, al> itg;
HashMap<Long, Integer> ith;
j itj;
private Object itk;
public d() {
this.itj = null;
this.itk = new Object();
u.aHG().isZ = new 1(this);
if (this.ite == null) {
this.ite = new 10(this);
}
this.itf = new HashMap();
this.itg = new HashMap();
this.ith = new HashMap();
}
public static int aGM() {
return iti;
}
public final synchronized void oZ(int i) {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "setConnectMode, mode = %d", new Object[]{Integer.valueOf(i)});
iti = i;
}
public final synchronized void a(Long l, int i) {
this.ith.put(l, Integer.valueOf(i));
}
public final void a(String str, long j, int i) {
a(str, j, i, false);
}
public final void a(String str, long j, int i, boolean z) {
a.B("shut_down_device", j);
if (this.itd == null) {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "Bind exdeviceService");
this.itd = new c();
this.itd.iyE = new 6(this, i, str, j, z);
this.itd.dd(ad.getContext());
} else if (this.itd == null || this.itd.iyF) {
b(str, j, i, z);
} else {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "ExdeviceService setConnected");
this.itd.iyE = new 7(this, i, str, j, z);
this.itd.dd(ad.getContext());
}
}
public final void b(String str, long j, int i, boolean z) {
boolean b;
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "doConnect");
if (z) {
b = b(str, j, i);
} else if (au.DF().Lg() != 4) {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "now network is not avaiable, notify directly");
b = false;
} else {
if (this.itf.containsKey(Long.valueOf(j))) {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "now the device is connecting, reset timer : brand name = %s, deviceid = %d, bluetooth version = %d", new Object[]{str, Long.valueOf(j), Integer.valueOf(i)});
al alVar = (al) this.itf.get(Long.valueOf(j));
alVar.SO();
alVar.J(30000, 30000);
} else {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "the device is not connecting, brand name = %s, deviceid = %d, bluetooth version = %d", new Object[]{str, Long.valueOf(j), Integer.valueOf(i)});
al alVar2 = new al(Looper.getMainLooper(), new 9(this, j, str, i), false);
alVar2.J(30000, 30000);
this.itf.put(Long.valueOf(j), alVar2);
}
if (u.aHG().isY == null) {
x.w("MicroMsg.exdevice.ExdeviceConnectManager", "MMExDeviceCore.getTaskQueue().getDispatcher() == null, Just leave, brand name is %s, device id is %d, bluetooth version is %d", new Object[]{str, Long.valueOf(j), Integer.valueOf(i)});
b = false;
} else {
f$a cN = u.aHF().cN(j);
if (cN == null) {
x.w("MicroMsg.exdevice.ExdeviceConnectManager", "Device unbond: %s", new Object[]{Long.valueOf(j)});
b = false;
} else {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "onStateChange, connectState = %d ", new Object[]{Integer.valueOf(cN.bLv)});
if (!(cN.bLv == 2 || cN.bLv == 1)) {
u.aHG().isY.a(j, i, this.ite);
}
b = true;
}
}
}
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "startChannel Ret = %s", new Object[]{Boolean.valueOf(b)});
}
public static void cB(long j) {
if (u.aHG().isY != null) {
boolean cT = u.aHG().isY.cT(j);
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "now stop the devide channel : %d, result : %b", new Object[]{Long.valueOf(j), Boolean.valueOf(cT)});
}
}
public final void aGN() {
if (this.itd != null && this.itd.iyF) {
try {
ad.getContext().unbindService(this.itd);
} catch (Exception e) {
}
}
}
private synchronized boolean b(String str, long j, int i) {
boolean z;
int Lg = au.DF().Lg();
if (Lg != 4 && Lg != 6) {
x.e("MicroMsg.exdevice.ExdeviceConnectManager", "now network is not avaiable, notify directly");
z = false;
} else if (this.itg.containsKey(Long.valueOf(j))) {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "now the device is syncing data : %s, %d, Just leave!!!", new Object[]{str, Long.valueOf(j)});
z = false;
} else {
al alVar = new al(Looper.getMainLooper(), new 8(this, j, str, i), false);
long aIs = b.aIs();
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "now sync time out is : %d", new Object[]{Long.valueOf(aIs)});
alVar.J(aIs, aIs);
this.itg.put(Long.valueOf(j), alVar);
if (u.aHG().isY != null) {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "start channel now : %s, %d", new Object[]{str, Long.valueOf(j)});
z = u.aHG().isY.a(j, i, this.ite);
} else {
x.e("MicroMsg.exdevice.ExdeviceConnectManager", "MMExDeviceCore.getTaskQueue().getDispatcher() == null");
z = false;
}
}
return z;
}
public static boolean ev(boolean z) {
if (u.aHG().isY != null) {
long[] aHt = u.aHG().isY.aHt();
if (aHt == null || aHt.length <= 0) {
x.w("MicroMsg.exdevice.ExdeviceConnectManager", "connectedDevices = null or connectedDevices.length = 0");
return false;
}
for (long j : aHt) {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "deviceId = %s", new Object[]{Long.valueOf(j)});
com.tencent.mm.plugin.exdevice.h.b cX = ad.aHe().cX(j);
if (cX == null) {
x.w("MicroMsg.exdevice.ExdeviceConnectManager", "Get device info failed, deviceId = %s", new Object[]{Long.valueOf(j)});
} else if (z && (cX.field_closeStrategy & 1) == 0) {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "Device is not close after exit chatting, deviceId = %s", new Object[]{Long.valueOf(j)});
} else {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "Stop channel, deviceId = %s", new Object[]{Long.valueOf(j)});
u.aHG().isY.cT(j);
}
}
return true;
}
x.w("MicroMsg.exdevice.ExdeviceConnectManager", "MMExDeviceCore.getTaskQueue().getDispatcher is null!");
return false;
}
public final void a(int i, j jVar) {
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "scanLogic, bluetooth version = %d", new Object[]{Integer.valueOf(i)});
if (jVar == null) {
x.e("MicroMsg.exdevice.ExdeviceConnectManager", "null == aCallback");
return;
}
this.itj = jVar;
if (this.itd == null) {
this.itd = new c();
this.itd.iyE = new 12(this, i, i);
this.itd.dd(ad.getContext());
return;
}
x.i("MicroMsg.exdevice.ExdeviceConnectManager", "try start scan");
if (u.aHG().isY == null) {
x.e("MicroMsg.exdevice.ExdeviceConnectManager", "dispatcher is null.");
} else if (!u.aHG().isY.b(i, this.itj)) {
x.e("MicroMsg.exdevice.ExdeviceConnectManager", "scan failed!!!");
}
}
}
|
package au.com.pactera.sampledownloader.adapters;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import java.util.Iterator;
import java.util.List;
import au.com.pactera.sampledownloader.R;
import au.com.pactera.sampledownloader.dto.Rows;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by priju.jacobpaul on 3/05/15.
*/
public class DownloadItemAdapter extends BaseAdapter {
Context mContext;
List<Rows> mRowItems;
public DownloadItemAdapter(Context context, List<Rows> rowItems){
mContext = context;
mRowItems = rowItems;
}
public void setRows(List<Rows> rowItems){
mRowItems = rowItems;
}
/**
* Remove the unwanted items
*/
public void parseAndRemoveItems(){
Iterator<Rows> rowsIterator = mRowItems.listIterator();
while (rowsIterator.hasNext()){
Rows rows =rowsIterator.next();
if(rows.getImageHref() == null && rows.getDescription() == null){
rowsIterator.remove();
}
}
}
@Override
public int getCount() {
return mRowItems.size();
}
@Override
public long getItemId(int position) {
return mRowItems.indexOf(getItem(position));
}
@Override
public Object getItem(int position) {
return mRowItems.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
View vi = null;
if(vi == null){
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_item, null);
viewHolder = new ViewHolder(convertView );
convertView.setTag(viewHolder);
}
else{
viewHolder = (ViewHolder)convertView.getTag();
}
vi = convertView;
String title = mRowItems.get(position).getTitle();
final String description = mRowItems.get(position).getDescription();
viewHolder.mTitle.setText(title);
if(description!=null) {
viewHolder.mDescriptionOnly.setText(description);
}
viewHolder.mDescriptionOnly.setVisibility(View.VISIBLE);
loadImage(viewHolder,position);
return vi;
}
/**
* loadImage using Picasso library
* @param viewHolder
* @param view
* @param position
*/
private void loadImage(final ViewHolder viewHolder,int position){
String imageUrl = mRowItems.get(position).getImageHref();
final String description = mRowItems.get(position).getDescription();
Picasso.with(mContext)
.load(imageUrl)
.placeholder(R.drawable.abc_item_background_holo_dark)
.transform(new TransformImage(viewHolder.mImageView))
.into(viewHolder.mImageView, new Callback() {
@Override
public void onSuccess() {
viewHolder.mDescriptionOnly.setVisibility(View.GONE);
viewHolder.mLLTextImageView.setVisibility(View.VISIBLE);
viewHolder.mDescription.setText(description);
}
@Override
public void onError() {
// Failed to download image
}
});
}
public static class ViewHolder{
@InjectView(R.id.title)
TextView mTitle;
@InjectView(R.id.icon)
ImageView mImageView;
@InjectView(R.id.description)
TextView mDescription;
@InjectView(R.id.layout_with_text_imageView)
LinearLayout mLLTextImageView;
@InjectView(R.id.descriptionOnly)
TextView mDescriptionOnly;
public ViewHolder(View view) {
ButterKnife.inject(this, view);
}
}
public class TransformImage implements Transformation {
private ImageView mImageView;
public TransformImage(ImageView imageView){
mImageView = imageView;
}
/**
* Transform the image to the required size
* @param source source bitmap
* @return scaled bitmap
*/
@Override public Bitmap transform(Bitmap source) {
int width = source.getWidth();
int height = source.getHeight();
float currentWidth = mImageView.getWidth() == 0 ? mContext.getResources().getInteger(R.integer.default_image_width) : mImageView.getWidth();
float currentHeight = mImageView.getHeight() == 0 ? mContext.getResources().getInteger(R.integer.default_image_height) :mImageView.getHeight();
float scaleWidth = (currentWidth) / width;
float scaleHeight = (currentHeight) / height;
Matrix matrix = new Matrix();
// resize the new bitmap.
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(source, 0, 0, width, height, matrix, false);
if (resizedBitmap != source) {
source.recycle();
}
return resizedBitmap;
}
@Override public String key() { return mContext.getString(R.string.app_name); }
}
}
|
package com.template.data.local.preferences;
public interface PreferencesHelper {
String getAccessToken();
void setAccessToken(String accessToken);
}
|
package com.example.osiris.testapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class EmployeeCreate extends AppCompatActivity {
// private Button button = (Button) findViewById(R.id.buttonCompanyCreate);
private FirebaseAuth mAuth;
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef1;
private DatabaseReference myRef2;
private Button button;
private User employeeToSave;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employee_add);
getSupportActionBar().hide();
mAuth = FirebaseAuth.getInstance();
}
public void addEmployee(View view) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference().child("Users");
final String id = getIntent().getStringExtra("companyKey");
final EditText et = (EditText) findViewById(R.id.editFieldAddEmployee);
myRef2 = database.getReference().child("Users").child(mAuth.getCurrentUser().getUid()).child(id).child("Employees");
final String key = String.valueOf(et.getText());
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> children = dataSnapshot.getChildren();
DataSnapshot ds;
for (DataSnapshot child : children) {
//User user = new User(dataSnapshot.child("name").getValue(String.class), dataSnapshot.child("email").getValue(String.class));
User user = child.getValue(User.class);
if (user.getEmail().equals(String.valueOf(et.getText()))) {
if(user.getCompanyOwner()!= null){
Toast.makeText(EmployeeCreate.this, "This user is already part of a company!", Toast.LENGTH_LONG).show();
return;
}
user.setCompanyOwner(mAuth.getCurrentUser().getUid());
user.employTo(id);
myRef.child(user.getKey()).setValue(user);
String id2 = user.getKey();
DatabaseReference myRef = database.getReference();
myRef.child("Users").child(id2).setValue(user);
myRef2.push();
myRef2.child(id2).setValue(user);
Toast.makeText(EmployeeCreate.this, "User added!", Toast.LENGTH_LONG).show();
Log.d("Look here", "Anotherone");
finish();
return;
}
}
Toast.makeText(EmployeeCreate.this, "No such user!", Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
// // Log.d("Company check", company.getName() + " NAME" + company.getOwner().getEmail() + " OWNER");
// Intent intent = new Intent(this, CompanyO_Account.class);
// // intent.putExtra("MyCompany", company);
// finish();
// startActivity(intent);
}
}
|
package com.enat.sharemanagement.security.role;
import com.enat.sharemanagement.security.privilage.Privilege;
import com.enat.sharemanagement.utils.Auditable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.enat.sharemanagement.security.user.User;
import lombok.Data;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
@Entity(name = "roles")
@Data
@EntityListeners(AuditingEntityListener.class)
public class Role extends Auditable implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(mappedBy = "roles")
private List<User> users;
@JsonIgnoreProperties(value = {"roles","users"})
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "roles_privileges",
joinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id"))
private Set<Privilege> privileges;
@Column(unique = true, updatable = false)
private String name;
}
|
package org.skunion.smallru8.util;
public class RegularExpression {
public static boolean isDigitOnly(String str) {
return str.matches("[0-9]*");
}
public static boolean isUpperOnly(String str) {
return str.matches("[A-Z]*");
}
public static boolean isLowerOnly(String str) {
return str.matches("[a-z]*");
}
public static boolean isLetterOnly(String str) {
return str.matches("[A-Za-z]*");
}
public static boolean isLetterDigitOnly(String str) {
return str.matches("[A-Za-z0-9]*");
}
public static boolean isIPAddress(String str) {
String[] ip4 = str.split("\\.");
if(ip4.length!=4)
return false;
for(int i=0;i<4;i++) {
if(!isDigitOnly(ip4[i]))
return false;
if(Integer.parseInt(ip4[i])>255||Integer.parseInt(ip4[i])<0)
return false;
}
return true;
}
}
|
package risk.game.strategy;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Random;
import risk.game.Cards;
import risk.game.Player;
import risk.game.Territory;
/**
* An Aggressive Strategy that implements strategy and serializable operation
*/
public class AggressiveStrategy implements Strategy , Serializable{
private Player player;
private Behavior behavior;
/**
* Constructor of AggressiveStratege
* @param player
* the player to use strategy
*/
public AggressiveStrategy(Player player) {
this.player = player;
behavior = Behavior.AGGRESSIVE;
}
/**
* Method to startup
*/
@Override
public void startup() {
for (Territory territory : player.getTerritoryMap().values()) {
for (Territory adj : territory.getAdjacent().values()) {
if (adj.getOwner() != player) {
player.placeUnassignedArmy(territory, player.getUnassignedArmy());
return;
}
}
}
}
/**
* Method to reinforce.
*/
@Override
public void reinforce() {
Territory strongestTerritory = player.getStrongestTerritory();
Cards handCard = player.getCardSet();
if (handCard.getSize() == 5) {
LinkedList<Integer> exchangeCards = new LinkedList<Integer>();
for (int i = 0; i < 3; i++) {
exchangeCards.add(handCard.getAllCards().get(i));
}
player.exchangeCards(exchangeCards, Cards.exchangeArmy);
Cards.exchangeArmy += 5;
}
player.getReinforcement();
try {
player.placeUnassignedArmy(strongestTerritory, player.getUnassignedArmy());
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Method to attack.
*/
@Override
public void attack() {
Territory strongestTerritory = player.getStrongestTerritory();
player.updateAttackableMap();
while (!player.getAttackableMap().get(strongestTerritory).isEmpty()) {
Random r = new Random();
LinkedList<Territory>attackableList = player.getAttackableMap().get(strongestTerritory);
Territory targetTerritory = attackableList.get(r.nextInt(attackableList.size()));
while (targetTerritory.getOwner() != player && strongestTerritory.getArmy() > 1) {
int attackerDiceNum = Math.min(3, strongestTerritory.getArmy() - 1);
int defenderDiceNum = Math.min(2, targetTerritory.getArmy());
player.attack(strongestTerritory, targetTerritory, attackerDiceNum, defenderDiceNum);
if (targetTerritory.getArmy() == 0) {
player.moveArmy(strongestTerritory, targetTerritory, strongestTerritory.getArmy() - 1);
strongestTerritory = targetTerritory;
}
}
player.updateAttackableMap();
}
}
/**
* Method to fortify
*/
@Override
public void fortify() {
player.updateReachableMap();
HashMap<Territory, LinkedList<Territory>> reachableMap = player.getReachableMap();
Territory strongestTerritory = player.getStrongestTerritory();
Territory fortificationTerritory = null;
for (Territory territory : reachableMap.keySet()) {
if (reachableMap.get(territory).contains(strongestTerritory)) {
if (fortificationTerritory == null) {
fortificationTerritory = territory;
}
if (fortificationTerritory.getArmy() < territory.getArmy()) {
fortificationTerritory = territory;
}
}
}
if (fortificationTerritory != null) {
player.moveArmy(fortificationTerritory, strongestTerritory, fortificationTerritory.getArmy() - 1);
}
}
/**
* Method to get its behavior
*
* @return the behavior that got which is Behavior type
*/
@Override
public Behavior getBehavior() {
return behavior;
}
}
|
package VSMSerialization;
import java.io.Serializable;
import no.uib.cipr.matrix.DenseVector;
public class VSMWordEmbeddingSyn implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4497064505074068848L;
private DenseVector wordEmbeddingSyn;
public DenseVector getWordEmbeddingSyn() {
return wordEmbeddingSyn;
}
public void setWordEmbeddingSem(DenseVector wordEmbeddingSyn) {
this.wordEmbeddingSyn = wordEmbeddingSyn;
}
}
|
package cn.itsite.abase.mvvm.view.base;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import com.gyf.barlibrary.ImmersionBar;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import cn.itsite.abase.mvvm.contract.base.BaseContract;
import cn.itsite.abase.mvvm.viewmodel.base.BaseViewModel;
import cn.itsite.adialog.dialog.LoadingDialog;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment;
import retrofit2.Response;
/**
* Author:leguang on 2016/10/9 0009 15:49
* Email:langmanleguang@qq.com
* <p>
* 所有Fragment的基类。将Fragment作为View层对象,专职处理View的试图渲染和事件。
*/
public abstract class BaseFragment<VM extends BaseViewModel> extends SwipeBackFragment implements BaseContract.View {
public final String TAG = this.getClass().getSimpleName();
protected VM mViewModel;
protected ImmersionBar mImmersionBar;
protected Dialog loadingDialog;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initViewModel();
}
private void initViewModel() {
mViewModel = onCreateViewModel();
if (mViewModel == null) {
createViewModel();
}
if (mViewModel != null) {
getLifecycle().addObserver(mViewModel);
mViewModel.loading.observe(this, o -> {
onLoading(o);
});
mViewModel.complete.observe(this, o -> {
onComplete(o);
});
mViewModel.error.observe(this, o -> {
onError(o);
});
}
}
/**
* 借助泛型来自动生成对应的ViewModel对象
*
* @return
*/
private VM createViewModel() {
Type type = getClass().getGenericSuperclass();
if (type instanceof ParameterizedType) {
Type[] types = ((ParameterizedType) type).getActualTypeArguments();
Class<VM> vmClass = (Class<VM>) types[0];
mViewModel = ViewModelProviders.of(this).get(vmClass);
}
return mViewModel;
}
protected VM onCreateViewModel() {
return onBindViewModel() != null ? ViewModelProviders.of(this).get(onBindViewModel()) : null;
}
protected Class<VM> onBindViewModel() {
return null;
}
@Override
public void onDestroyView() {
super.onDestroyView();
if (mImmersionBar != null) {
mImmersionBar.destroy();
}
hideSoftInput();
}
@Override
public void onDestroy() {
super.onDestroy();
getLifecycle().removeObserver(mViewModel);
}
public VM getViewModel() {
return mViewModel;
}
public void setViewModel(@NonNull VM viewModel) {
this.mViewModel = viewModel;
}
@Override
public FragmentAnimator onCreateFragmentAnimator() {
return new DefaultHorizontalAnimator();
}
public void initStateBar(@NonNull View view) {
ImmersionBar.setTitleBar(_mActivity, view);
}
/**
* 用于被P层调用的通用函数。
*
* @param response
*/
@Override
public void onLoading(Object... response) {
showLoading();
}
public void showLoading() {
if (loadingDialog == null) {
loadingDialog = new LoadingDialog(_mActivity)
.setDimAmount(0);
}
loadingDialog.show();
}
@Override
public void onError(Object... error) {
dismissLoading();
}
public void dismissLoading() {
if (loadingDialog != null) {
loadingDialog.dismiss();
}
}
@Override
@CallSuper
public void onComplete(Object... response) {
dismissLoading();
}
@Override
public void onLazyInitView(@Nullable Bundle savedInstanceState) {
super.onLazyInitView(savedInstanceState);
if (mViewModel != null) {
mViewModel.onInitialize();
}
}
@Override
public void onSupportVisible() {
super.onSupportVisible();
if (mViewModel != null) {
mViewModel.onVisible();
}
}
@Override
public void onSupportInvisible() {
super.onSupportInvisible();
if (mViewModel != null) {
mViewModel.onInvisible();
}
}
public abstract class BaseObserver<T> implements Observer<T> {
@Override
public void onSubscribe(Disposable disposable) {
onLoading();
}
@Override
public void onNext(T response) {
onSuccess(response);
}
@Override
public void onError(Throwable throwable) {
BaseFragment.this.onError(throwable);
}
@Override
public void onComplete() {
BaseFragment.this.onComplete();
}
public abstract void onSuccess(T response);
}
public abstract class ResponseObserver<T extends Response> implements Observer<T> {
@Override
public void onSubscribe(Disposable disposable) {
onLoading();
}
@Override
public void onNext(T response) {
if (response.isSuccessful()) {
onSuccess(response);
} else {
BaseFragment.this.onError(response);
}
}
@Override
public void onError(Throwable throwable) {
BaseFragment.this.onError(throwable);
}
@Override
public void onComplete() {
BaseFragment.this.onComplete("");
}
public abstract void onSuccess(T t);
}
public abstract class ResponseConsumer<T extends Response> implements Consumer<T> {
@Override
public void accept(T response) {
if (response.isSuccessful()) {
onSuccess(response);
} else {
BaseFragment.this.onError(response);
}
}
public abstract void onSuccess(T t);
}
}
|
/**
*
*/
package org.ashah.sbcloudpayrollservice;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* @author avish
*
*/
@Repository
public interface EmployeePayrollRepository extends JpaRepository<EmployeePayroll, Long> {
}
|
package com.lingnet.vocs.service.monit;
import java.util.List;
import com.lingnet.common.service.BaseService;
import com.lingnet.util.Pager;
import com.lingnet.vocs.entity.Annals;
public interface AnnalsService extends BaseService<Annals, String> {
public String getTemperatureData(Pager pager, String eqCode,String startdate,String enddate);
public List<Object[]> getTemperatureChart(String eqCode, String string,String startdate,String enddate);
}
|
package com.accp.dong.vo;
import java.util.List;
import com.accp.pub.pojo.Grade;
import com.accp.pub.pojo.Studentinfo;
public class GradeorganizationuserVo {
private Grade grade;
private String graderName;
private String banzhuren;
private String jiaoyuan;
private Integer stucount;
private String zengbanzhuren;
private String zengjaoyuan;
private String banwei;
private String shusequyu;
private List<Studentinfo> list;
public String getGraderName() {
return graderName;
}
public void setGraderName(String graderName) {
this.graderName = graderName;
}
public List<Studentinfo> getList() {
return list;
}
public void setList(List<Studentinfo> list) {
this.list = list;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
public String getBanzhuren() {
return banzhuren;
}
public void setBanzhuren(String banzhuren) {
this.banzhuren = banzhuren;
}
public String getJiaoyuan() {
return jiaoyuan;
}
public void setJiaoyuan(String jiaoyuan) {
this.jiaoyuan = jiaoyuan;
}
public Integer getStucount() {
return stucount;
}
public void setStucount(Integer stucount) {
this.stucount = stucount;
}
public String getZengbanzhuren() {
return zengbanzhuren;
}
public void setZengbanzhuren(String zengbanzhuren) {
this.zengbanzhuren = zengbanzhuren;
}
public String getZengjaoyuan() {
return zengjaoyuan;
}
public void setZengjaoyuan(String zengjaoyuan) {
this.zengjaoyuan = zengjaoyuan;
}
public String getBanwei() {
return banwei;
}
public void setBanwei(String banwei) {
this.banwei = banwei;
}
public String getShusequyu() {
return shusequyu;
}
public void setShusequyu(String shusequyu) {
this.shusequyu = shusequyu;
}
}
|
package io.github.wickhamwei.wessential.eventlistener;
import io.github.wickhamwei.wessential.WEssentialMain;
import org.bukkit.GameRule;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.WorldInitEvent;
public class KeepInventoryListener implements Listener {
@EventHandler
public void keepInventory(WorldInitEvent event) {
World world = event.getWorld();
if (world.setGameRule(GameRule.KEEP_INVENTORY, true)) {
WEssentialMain.wEssentialMain.getLogger().info("死亡是否保留背包内的物品在 " + world.getName() + " 设置为 " + true);
}
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.order.hook.impl;
import de.hybris.platform.commerceservices.event.QuoteBuyerOrderPlacedEvent;
import de.hybris.platform.commerceservices.order.hook.CommercePlaceOrderMethodHook;
import de.hybris.platform.commerceservices.service.data.CommerceCheckoutParameter;
import de.hybris.platform.commerceservices.service.data.CommerceOrderResult;
import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.core.model.order.QuoteModel;
import de.hybris.platform.servicelayer.event.EventService;
import de.hybris.platform.servicelayer.util.ServicesUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Required;
/**
* Hook for updating quote's state if the placed order was based on a quote
*/
public class CommercePlaceQuoteOrderMethodHook implements CommercePlaceOrderMethodHook
{
private static final Logger LOG = Logger.getLogger(CommercePlaceQuoteOrderMethodHook.class);
private EventService eventService;
@Override
public void afterPlaceOrder(final CommerceCheckoutParameter commerceCheckoutParameter,
final CommerceOrderResult commerceOrderResult)
{
final OrderModel order = commerceOrderResult.getOrder();
ServicesUtil.validateParameterNotNullStandardMessage("order", order);
// Set quote state for quote order
final QuoteModel quoteModel = order.getQuoteReference();
if (quoteModel != null)
{
if (LOG.isDebugEnabled())
{
LOG.debug(String.format("Quote Order has been placed. Quote Code : [%s] , Order Code : [%s]", quoteModel.getCode(),
order.getCode()));
}
final QuoteBuyerOrderPlacedEvent quoteBuyerOrderPlacedEvent = new QuoteBuyerOrderPlacedEvent(order, quoteModel);
getEventService().publishEvent(quoteBuyerOrderPlacedEvent);
}
}
@Override
public void beforePlaceOrder(final CommerceCheckoutParameter commerceCheckoutParameter)
{
// not implemented
}
@Override
public void beforeSubmitOrder(final CommerceCheckoutParameter commerceCheckoutParameter,
final CommerceOrderResult commerceOrderResult)
{
// not implemented
}
protected EventService getEventService()
{
return eventService;
}
@Required
public void setEventService(final EventService eventService)
{
this.eventService = eventService;
}
}
|
package com.company.phoneNum;
public class Main {
public static void main(String[] args) {
Main main = new Main();
String phoneNum = "027778888";
System.out.println(main.solution(phoneNum));
}
public String solution(String phone_number) {
StringBuilder sb = new StringBuilder();
int size = phone_number.length();
String str = "";
for(int i=0; i<size-4; i++){
sb.append("*");
}
sb.append(str);
sb.append(phone_number.substring(size-4));
return sb.toString();
}
}
|
package com.shopping.li.shopping.Fragment.Mall;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.shopping.li.shopping.Adapter.EleAdapter;
import com.shopping.li.shopping.Entity.GoodsInfo;
import com.shopping.li.shopping.Fragment.BaseFragment;
import com.shopping.li.shopping.R;
import java.util.ArrayList;
/**
* Created by li on 2018/2/24.
* 电子界面
*/
public class EleFragment extends BaseFragment {
private EleAdapter eleAdapter;
private ListView listView;
private View view;
private GoodsInfo goodsInfo ,ipad ,iphone,xianshiqi,jianpan,bijiben;
private ArrayList<GoodsInfo> goodsInfoArrayList;
private GoodsInfo.Builder builder;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.elefragment_main_layout,container,false);
listView = view.findViewById(R.id.eleListView);
goodsInfoArrayList = new ArrayList<>();
ipad = new GoodsInfo("1","name", "desc",200, 100,
"color", "size", R.drawable.ipad,1000 ,1);
iphone = new GoodsInfo("1","name", "desc",200, 100,
"color", "size", R.drawable.iphone,1000 ,1);
xianshiqi = new GoodsInfo("1","name", "desc",200, 100,
"color", "size", R.drawable.xianshiqi,1000 ,1);
jianpan = new GoodsInfo("1","name", "desc",200, 100,
"color", "size", R.drawable.jianpan,1000 ,1);
bijiben = new GoodsInfo("1","name", "desc",200, 100,
"color", "size", R.drawable.bijiben,1000 ,1);
goodsInfoArrayList.add(ipad);
goodsInfoArrayList.add(iphone);
goodsInfoArrayList.add(xianshiqi);
goodsInfoArrayList.add(jianpan);
goodsInfoArrayList.add(bijiben);
if (goodsInfoArrayList != null)
{
eleAdapter = new EleAdapter(getContext(),goodsInfoArrayList);
listView.setAdapter(eleAdapter);
}else
{
Toast.makeText(getContext(),"goodsInfoArrayList = null",Toast.LENGTH_LONG).show();
}
return view;
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.models;
import static edu.tsinghua.lumaqq.resource.Messages.*;
import java.io.File;
import java.io.IOException;
import edu.tsinghua.lumaqq.ecore.EcoreFactory;
import edu.tsinghua.lumaqq.ecore.LoginOption;
import edu.tsinghua.lumaqq.ecore.ProxyType;
import edu.tsinghua.lumaqq.ecore.face.FaceConstant;
import edu.tsinghua.lumaqq.ecore.face.FaceFactory;
import edu.tsinghua.lumaqq.ecore.face.FaceGroup;
import edu.tsinghua.lumaqq.ecore.face.Faces;
import edu.tsinghua.lumaqq.ecore.group.GroupFactory;
import edu.tsinghua.lumaqq.ecore.group.XCluster;
import edu.tsinghua.lumaqq.ecore.group.XGroup;
import edu.tsinghua.lumaqq.ecore.group.XGroups;
import edu.tsinghua.lumaqq.ecore.group.XOrganization;
import edu.tsinghua.lumaqq.ecore.group.XUser;
import edu.tsinghua.lumaqq.ecore.login.LoginFactory;
import edu.tsinghua.lumaqq.ecore.login.Logins;
import edu.tsinghua.lumaqq.ecore.option.GUIOption;
import edu.tsinghua.lumaqq.ecore.option.KeyOption;
import edu.tsinghua.lumaqq.ecore.option.MessageOption;
import edu.tsinghua.lumaqq.ecore.option.OpType;
import edu.tsinghua.lumaqq.ecore.option.OptionFactory;
import edu.tsinghua.lumaqq.ecore.option.Options;
import edu.tsinghua.lumaqq.ecore.option.OtherOption;
import edu.tsinghua.lumaqq.ecore.option.SyncOption;
import edu.tsinghua.lumaqq.eutil.FaceUtil;
import edu.tsinghua.lumaqq.eutil.GroupUtil;
import edu.tsinghua.lumaqq.eutil.LoginUtil;
import edu.tsinghua.lumaqq.eutil.OptionUtil;
import edu.tsinghua.lumaqq.qq.beans.ContactInfo;
import edu.tsinghua.lumaqq.qq.beans.QQFriend;
/**
* 这个类负责提供一些创建数据的方法,纯粹是为了免得个别的文件行数太多,
* 所以把这些集中操作底层数据的方法抽出来放在一个工具类里
*
* @author luma
*/
public class ModelUtils {
/**
* 从QQFriend类创建一个contact info结构
* @param friend QQFriend
* @return ContactInfo
*/
public static ContactInfo createContact(QQFriend friend) {
ContactInfo ret = new ContactInfo();
ret.nick = friend.nick;
ret.qq = friend.qqNum;
ret.age = friend.age;
if(friend.isGG())
ret.gender = gender_gg;
else
ret.gender = gender_mm;
return ret;
}
/**
* 从User创建一个ContactInfo
*
* @param u
* User对象
* @return
* ContactInfo对象
*/
public static ContactInfo createContact(User u) {
ContactInfo ret = new ContactInfo();
ret.nick = u.nick;
ret.qq = u.qq;
ret.head = u.headId;
return ret;
}
/**
* 从Friend元素创建一个ContactInfo对象
*
* @param user
* Friend元素对象
* @return
* ContactInfo
*/
public static ContactInfo createContact(XUser user) {
ContactInfo ret = new ContactInfo();
ret.qq = user.getQq();
ret.nick = user.getNick();
ret.head = user.getHeadId();
return ret;
}
/**
* 从XML元素中创建Group
*
* @param group
* XGroup元素对象
* @return
* Group对象
*/
public static Group createGroup(XGroup group) {
Group ret = new Group();
ret.name = group.getName();
return ret;
}
/**
* 从XUser元素创建一个User
*
* @param user
* XUser
* @return
* User
*/
public static User createUser(XUser user) {
User ret = new User();
ret.qq = user.getQq();
if(ret.qq == 0)
return null;
ret.nick = user.getNick();
ret.cardName = user.getCardName();
ret.displayName = ret.nick;
ret.headId = user.getHeadId();
ret.windowX = user.getWindowX();
ret.windowY = user.getWindowY();
ret.member = user.isMember();
ret.status = Status.OFFLINE;
ret.pinned = user.isPinned();
ret.userFlag = user.getUserFlag();
ret.organizationId = user.getOrganizationId();
ret.info = createContact(user);
ret.talkMode = user.isTalkMode();
ret.lastMessageTime = user.getLastMessageTime();
ret.signature = user.getSignature();
ret.level = user.getLevel();
ret.female = user.isFemale();
ret.hasCustomHead = user.isHasCustomHead();
ret.customHeadId = user.getCustomHeadId();
ret.customHeadTimestamp = user.getCustomHeadTimestamp();
return ret;
}
/**
* 从User对象创建一个XUser元素对象
*
* @param u
* User
* @return
* XUser
*/
public static XUser createXUser(User u) {
XUser ret = GroupFactory.eINSTANCE.createXUser();
ret.setQq(u.qq);
ret.setNick(u.nick);
ret.setHeadId(u.headId);
ret.setWindowX(u.windowX);
ret.setWindowY(u.windowY);
ret.setMember(u.member);
ret.setTalkMode(u.talkMode);
ret.setOrganizationId(u.organizationId);
ret.setPinned(u.pinned);
ret.setCardName(u.cardName);
ret.setUserFlag(u.userFlag);
ret.setLastMessageTime(u.lastMessageTime);
ret.setSignature(u.signature);
ret.setLevel(u.level);
ret.setFemale(u.female);
ret.setHasCustomHead(u.hasCustomHead);
ret.setCustomHeadId(u.customHeadId);
ret.setCustomHeadTimestamp(u.customHeadTimestamp);
return ret;
}
/**
* 创建XOrganization元素对象
*
* @param org
* @return
*/
public static XOrganization createXOrganization(Organization org) {
XOrganization ret = GroupFactory.eINSTANCE.createXOrganization();
ret.setId(org.id);
ret.setName(org.name);
ret.setPath(org.path);
return ret;
}
/**
* 创建Organization对象
*
* @param org
* @return
*/
public static Organization createOrganization(XOrganization org) {
Organization ret = new Organization();
ret.id = org.getId();
ret.path = org.getPath();
ret.name = org.getName();
return ret;
}
/**
* 从QQFriend类创建一个User
*
* @param friend
* QQFriend对象
* @return
* User
*/
public static User createUser(QQFriend friend) {
User ret = new User();
ret.headId = friend.head;
ret.status = Status.OFFLINE;
ret.qq = friend.qqNum;
ret.nick = friend.nick;
ret.displayName = ret.nick;
ret.member = friend.isMember();
ret.info = createContact(friend);
ret.userFlag = friend.userFlag;
ret.female = !friend.isGG();
return ret;
}
/**
* 创建群的Model
*
* @param cluster
* XCluster
* @return
* Cluster
*/
public static Cluster createCluster(XCluster cluster) {
Cluster ret = new Cluster();
ret.clusterId = cluster.getClusterId();
if(ret.clusterId == -1)
return null;
ret.externalId = cluster.getExternalId();
if(ret.externalId == -1)
return null;
ret.parentClusterId = cluster.getParentClusterId();
ret.headId = cluster.getHeadId();
ret.name = cluster.getName();
ret.creator = cluster.getCreator();
ret.clusterType = ClusterType.valueOf(cluster.getType());
ret.messageSetting = MessageSetting.valueOf(cluster.getMessageSetting());
ret.authType = (byte)cluster.getAuthType();
ret.category = cluster.getCategory();
ret.oldCategory = cluster.getOldCategory();
ret.description = cluster.getDescription();
ret.notice = cluster.getNotice();
ret.lastMessageTime = cluster.getLastMessageTime();
ret.parseAdminQQString(cluster.getAdmins());
ret.parseStockholderQQString(cluster.getStockholders());
return ret;
}
/**
* 创建缺省组文件
* @param file 目的文件
* @throws IOException 创建失败
*/
@SuppressWarnings("unchecked")
public static void createDefaultGroupXmlFile(File file) throws IOException {
file.getParentFile().mkdirs();
file.createNewFile();
XGroups groups = GroupFactory.eINSTANCE.createXGroups();
// 我的好友
XGroup group = GroupFactory.eINSTANCE.createXGroup();
group.setName(group_default_friend);
group.setType(GroupType.DEFAULT_FRIEND_GROUP.toString());
groups.getGroup().add(group);
// 群/校友录
group = GroupFactory.eINSTANCE.createXGroup();
group.setName(group_default_cluster);
group.setType(GroupType.CLUSTER_GROUP.toString());
groups.getGroup().add(group);
// 陌生人
group = GroupFactory.eINSTANCE.createXGroup();
group.setName(group_default_stranger);
group.setType(GroupType.STRANGER_GROUP.toString());
groups.getGroup().add(group);
// 黑名单
group = GroupFactory.eINSTANCE.createXGroup();
group.setName(group_default_blacklist);
group.setType(GroupType.BLACKLIST_GROUP.toString());
groups.getGroup().add(group);
// 最近联系人
group = GroupFactory.eINSTANCE.createXGroup();
group.setName(group_default_latest);
group.setType(GroupType.LATEST_GROUP.toString());
groups.getGroup().add(group);
// 保存
GroupUtil.save(file, groups);
}
/**
* 创建缺省登陆历史信息文件
* @param file
*/
public static void createDefaultLoginXmlFile(File file){
Logins logins = createDefaultLogins();
LoginUtil.save(file, logins);
}
/**
* 创建缺省的Logins对象
*
* @return
*/
public static Logins createDefaultLogins() {
Logins logins = LoginFactory.eINSTANCE.createLogins();
logins.setLastLogin("");
LoginOption lo = EcoreFactory.eINSTANCE.createLoginOption();
lo.setUseTcp(true);
lo.setAutoSelect(true);
lo.setServer("");
lo.setProxyType(ProxyType.NONE_LITERAL);
lo.setProxyServer("");
lo.setProxyPort(0);
lo.setProxyUsername("");
lo.setProxyPassword("");
lo.setTcpPort(80);
logins.setNetwork(lo);
return logins;
}
/**
* 从Group创建一个XGroup元素对象,这相当于createGroup的反方法
*
* @param group
* Group
* @return
* XGroup元素对象
*/
public static XGroup createXGroup(Group group) {
XGroup ret = GroupFactory.eINSTANCE.createXGroup();
ret.setName(group.name);
ret.setType(group.groupType.toString());
return ret;
}
/**
* 从User创建XUser元素,相当于createUser的反方法
*
* @param user
* User
* @return
* XUser元素对象
*/
public static XUser createFriendElement(User user) {
XUser ret = GroupFactory.eINSTANCE.createXUser();
ContactInfo info = user.info;
if(info == null)
info = new ContactInfo();
ret.setQq(user.qq);
ret.setNick(user.nick);
ret.setHeadId(user.headId);
ret.setMember(user.member);
ret.setWindowX(user.windowX);
ret.setWindowY(user.windowY);
ret.setTalkMode(user.talkMode);
return ret;
}
/**
* 从Cluster对象创建一个XCluster元素
*
* @param c
*/
public static XCluster createXCluster(Cluster c) {
XCluster ret = GroupFactory.eINSTANCE.createXCluster();
ret.setClusterId(c.clusterId);
ret.setExternalId(c.externalId);
ret.setParentClusterId(c.parentClusterId);
ret.setName(c.name);
ret.setHeadId(c.headId);
ret.setMessageSetting(c.messageSetting.toString());
ret.setType(c.clusterType.toString());
ret.setCreator(c.creator);
ret.setAuthType(c.authType);
ret.setCategory(c.category);
ret.setOldCategory(c.oldCategory);
ret.setDescription(c.description);
ret.setNotice(c.notice);
ret.setAdmins(c.getAdminQQString());
ret.setStockholders(c.getStockholderQQString());
ret.setLastMessageTime(c.lastMessageTime);
return ret;
}
/**
* 创建一个缺省的表情配置文件
*
* @param file
* @throws IOException
*/
@SuppressWarnings("unchecked")
public static void createDefaultFaceFile(File file) throws IOException {
Faces faces = FaceFactory.eINSTANCE.createFaces();
faces.setNextId(33);
faces.setNextGroupId(3);
FaceGroup defaultGroup = FaceFactory.eINSTANCE.createFaceGroup();
defaultGroup.setName(face_group_default);
defaultGroup.setId(FaceConstant.DEFAULT_GROUP_ID);
faces.getGroup().add(defaultGroup);
FaceGroup recvGroup = FaceFactory.eINSTANCE.createFaceGroup();
recvGroup.setName(face_group_recv);
recvGroup.setId(FaceConstant.RECEIVED_GROUP_ID);
faces.getGroup().add(recvGroup);
FaceGroup chGroup = FaceFactory.eINSTANCE.createFaceGroup();
chGroup.setName(face_group_custom_head);
chGroup.setId(FaceConstant.CUSTOM_HEAD_GROUP_ID);
faces.getGroup().add(chGroup);
FaceUtil.save(file, faces);
}
/**
* 创建一个缺省的系统设置文件
* @param file
*/
public static void createDefaultSysOptFile(File file) throws IOException {
Options options = OptionFactory.eINSTANCE.createOptions();
// 登陆设置
LoginOption lo = EcoreFactory.eINSTANCE.createLoginOption();
lo.setUseTcp(true);
lo.setAutoSelect(true);
lo.setServer("");
lo.setProxyType(ProxyType.NONE_LITERAL);
lo.setProxyServer("");
lo.setProxyPort(0);
lo.setProxyUsername("");
lo.setProxyPassword("");
lo.setTcpPort(80);
options.setLoginOption(lo);
// 界面设置
GUIOption go = OptionFactory.eINSTANCE.createGUIOption();
go.setLocationX(50);
go.setLocationY(50);
go.setWidth(-1);
go.setHeight(-1);
go.setShowNick(false);
go.setShowSmallHead(false);
go.setShowFriendTip(true);
go.setShowOnlineOnly(false);
go.setShowOnlineTip(true);
go.setShowLastLoginTip(true);
go.setTreeMode(true);
go.setOnlineTipLocationX(-1);
go.setOnlineTipLocationY(-1);
go.setFontName(default_font);
go.setFontSize(9);
go.setBold(false);
go.setItalic(false);
go.setFontColor(0);
go.setGroupBackground(0xFFFFFF);
go.setShowBlacklist(true);
go.setAutoDock(true);
go.setUseTabIMWindow(false);
go.setShowSignature(true);
go.setShowCustomHead(true);
go.setMinimizeWhenClose(false);
go.setOnTop(true);
go.setImOnTop(false);
go.setHideWhenMinimize(false);
go.setBarExpanded(false);
options.setGuiOption(go);
// 消息设置
MessageOption mo = OptionFactory.eINSTANCE.createMessageOption();
mo.setAutoEject(false);
mo.setEnableSound(true);
mo.setRejectStranger(false);
mo.setRejectTempSessionIM(false);
mo.setUseEnterInMessageMode(false);
mo.setUseEnterInTalkMode(false);
options.setMessageOption(mo);
// 热键设置
KeyOption ko = OptionFactory.eINSTANCE.createKeyOption();
ko.setMessageKey("<Ctrl><Alt>Z");
options.setKeyOption(ko);
// 同步设置
SyncOption so = OptionFactory.eINSTANCE.createSyncOption();
so.setAutoDownloadGroup(true);
so.setAutoUploadGroup(OpType.PROMPT_LITERAL);
so.setAutoDownloadFriendRemark(true);
so.setAutoCheckUpdate(false);
options.setSyncOption(so);
// 其他设置
OtherOption oo = OptionFactory.eINSTANCE.createOtherOption();
oo.setBrowser("");
oo.setKeepStrangerInLatest(false);
oo.setLatestSize(20);
oo.setEnableLatest(true);
oo.setShowFakeCam(false);
options.setOtherOption(oo);
// 写入文件
OptionUtil.save(file, options);
}
}
|
package alg;
import impl.BasicHashSet;
import impl.HeapPriorityQueue;
import adt.PriorityQueue;
import adt.Set;
import adt.WeightedGraph;
import adt.WeightedGraph.WeightedEdge;
/**
* PrimMinSpanTree
*
* Implementation of Prim's algorithm for computing
* the minimum spanning tree of a graph.
*
* @author Thomas VanDrunen
* CSCI 345, Wheaton College
* June 24, 2015
*/
public class PrimMinSpanTree implements MinSpanTree {
/**
* Compute the minimum spanning tree of a given graph.
* @param g The given graph
* @return A set of the edges in the minimum spanning tree
*/
public Set<WeightedEdge> minSpanTree(WeightedGraph g) {
VertexRecord[] records = new VertexRecord[g.numVertices()];
for (int i = 0; i < g.numVertices(); i++)
records[i] = new VertexRecord(i, Double.POSITIVE_INFINITY);
PriorityQueue<VertexRecord> pq =
new HeapPriorityQueue<VertexRecord>(records, new VertexRecord.VRComparator());
Set<WeightedEdge> mstEdges = new BasicHashSet<WeightedEdge>(g.numVertices());
int[] parents = new int[g.numVertices()];
for (int i = 0; i < g.numVertices(); i++)
parents[i] = -1;
while(!pq.isEmpty()){
VertexRecord u = pq.extractMax();
if(parents[u.id] != -1){
//add (u.p, u) to A
WeightedEdge item = new WeightedEdge(parents[u.id], u.id, u.getDistance());
mstEdges.add(item);
}
//for each v in u.adj
for(int v : g.adjacents(u.id)){
VertexRecord vRecord = records[v];
VertexRecord uRecord = records[u.id];
double w = g.weight(u.id, v);
if(pq.contains(vRecord) && w < vRecord.getDistance()){
parents[v] = u.id;
vRecord.setDistance(w);
pq.increaseKey(vRecord);
}
}
}
return mstEdges;
}
}
|
package com.stem.service;
import com.stem.core.interfaces.BasicService;
import com.stem.entity.WxMenu;
import com.stem.entity.WxMenuExample;
public interface WxMenuService extends BasicService<WxMenuExample, WxMenu> {
}
|
package com.basis.cg.xtarefas.repository;
import com.basis.cg.xtarefas.domain.Tarefa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface TarefaRepository extends JpaRepository<Tarefa, Long> {
@Query("SELECT t from Tarefa t WHERE" +
":status IS NULL OR t.status LIKE :status")
List<Tarefa> listar(@Param("status") String status);
}
|
package test.down;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Created by maguoqiang on 2018/1/30.
*/
public class DownloadByThread {
/**
* 自营资质下载--多线程
*
* @param outZipName 外层zip包名称
* @param imgUrls 图片地址集合 key:图片名称-按需求规则生成
* value:imgUrls-图片地址集合
* @return File 压缩包
*/
public static File downLoadZip4SelfByThread(String outZipName, Map<String, List<String>> imgUrls) {
if (null == imgUrls) {
return null;
}
long startTime = System.currentTimeMillis();
//商品目录集合
File[] files = new File[imgUrls.keySet().size()];
//压缩成zip文件
File zipfile = new File(outZipName);
File resZipfile = new File(outZipName);
ExecutorService pool;
try {
List<Feature4Download<HttpURLConnection>> combList = new ArrayList<Feature4Download<HttpURLConnection>>();
pool = Executors.newCachedThreadPool();
int i = 0;
//获取远程图片
for (String key : imgUrls.keySet()) {
//商品的资质集合
List<String> urls = imgUrls.get(key);
/*files[i] = new File(key);
files[i].mkdir();*/
for (final String url : urls) {//根据商品图片url获取图片文件
Future<HttpURLConnection> future = pool.submit(new Callable<HttpURLConnection>() {
@Override
public HttpURLConnection call() throws Exception {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(50000);//连接超时时间
connection.setReadTimeout(10000);//读取超时时间
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.connect();
return connection;
}
});
Feature4Download<HttpURLConnection> download = new Feature4Download<HttpURLConnection>();
download.setPath(key);
download.setUrl(url);
download.setFeatureData(future);
combList.add(download);
}
//i++;
}
//下载保存图片
final CountDownLatch latch = new CountDownLatch(combList.size());
for (Feature4Download<HttpURLConnection> feature4Download : combList) {
Future<HttpURLConnection> featureData = feature4Download.getFeatureData();
String path = feature4Download.getPath();
String url = feature4Download.getUrl();
//阿里云上图片地址 http://*..*/**.**?**&**
String[] splitBy = url.split("\\?");
String front = splitBy[0];
String[] split;
if (StringUtils.isNotBlank(front)) {
split = front.split("\\/");
} else {
split = url.split("\\/");
}
HttpURLConnection connectionF = featureData.get();
final InputStream inputStream = connectionF.getInputStream();
String fileName = split[split.length - 1];
String suffix = fileName.split("\\.")[1];
final File file = new File(path + "." + suffix);
pool.submit(new Runnable() {
@Override
public void run() {
try {
HttpURLConnectionUtil.saveData(inputStream, file);
} catch (Exception e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
});
files[i] = file;
i++;
}
latch.await();
//将商品文件夹压缩成zip文件
resZipfile = ZipUtils.doCompressByEncode(files, zipfile);
for (File file : files) {
deleteDir(file);
}
long endTime = System.currentTimeMillis();
} catch (Exception e) {
e.printStackTrace();
}
return resZipfile;
}
private static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
public static void main(String[] args) {
String zipName = "商品首营资质(广东壹号药业有限公司).zip";
Map<String, List<String>> req = new HashMap<String, List<String>>();
/*List<String> img_1 = new ArrayList<String>();
img_1.add("http://test-111-images.oss-cn-shanghai.aliyuncs.com/product/firstBattalion/0009716954.zip?Expires=1519272984&OSSAccessKeyId=T2cz8IRvSwIRIIoZ&Signature=NeZFBPKWl3LdpIbuH3Ma0yjDFxY%3D");
req.put("龙虎_人丹_30s100包", img_1);*/
List<String> img_2 = new ArrayList<String>();
img_2.add("http://test-111-images.oss-cn-shanghai.aliyuncs.com/product/firstBattalion/1701064806.zip?Expires=1519373327&OSSAccessKeyId=T2cz8IRvSwIRIIoZ&Signature=fUQk%2BK0P/ayVIrsuMXauJ2FbilI%3D");
req.put("龙虎_人丹_30s100包2", img_2);
downLoadZip4SelfByThread(zipName, req);
}
}
|
package edu.byu.cs.tweeter.model.service;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
import edu.byu.cs.tweeter.model.domain.User;
import edu.byu.cs.tweeter.model.net.ServerFacade;
import edu.byu.cs.tweeter.model.service.request.MakeUnfollowRequest;
import edu.byu.cs.tweeter.model.service.response.MakeUnfollowResponse;
public class MakeUnfollowServiceTest
{
private MakeUnfollowRequest validRequest;
private MakeUnfollowRequest invalidRequest;
private MakeUnfollowResponse successResponse;
private MakeUnfollowResponse failureResponse;
private MakeUnfollowService makeUnfollowServiceSpy;
/**
* Create a MakeUnfollowService spy that uses a mock ServerFacade to return known responses to
* requests.
*/
@BeforeEach
public void setup() {
User currentUser = new User("FirstName", "LastName", null);
User resultUser1 = new User("FirstName1", "LastName1",
"https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/donald_duck.png");
User resultUser2 = new User("FirstName2", "LastName2",
"https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/daisy_duck.png");
User resultUser3 = new User("FirstName3", "LastName3",
"https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/daisy_duck.png");
// Setup request objects to use in the tests
validRequest = new MakeUnfollowRequest(resultUser1.getAlias(), resultUser2.getAlias());
invalidRequest = new MakeUnfollowRequest(null, null);
// Setup a mock ServerFacade that will return known responses
successResponse = new MakeUnfollowResponse(true);
ServerFacade mockServerFacade = Mockito.mock(ServerFacade.class);
Mockito.when(mockServerFacade.updateUnfollowServer(validRequest)).thenReturn(successResponse);
failureResponse = new MakeUnfollowResponse(false);
Mockito.when(mockServerFacade.updateUnfollowServer(invalidRequest)).thenReturn(failureResponse);
// Create a MakeUnfollowService instance and wrap it with a spy that will use the mock service
makeUnfollowServiceSpy = Mockito.spy(new MakeUnfollowService());
Mockito.when(makeUnfollowServiceSpy.getServerFacade()).thenReturn(mockServerFacade);
}
/**
* Verify that for successful requests the {@link MakeUnfollowService#sendUnfollowRequest(MakeUnfollowRequest)}
* method returns the same result as the {@link ServerFacade}.
* .
*
* @throws IOException if an IO error occurs.
*/
@Test
public void testGetUnfollowees_validRequest_correctResponse() throws IOException {
MakeUnfollowResponse response = makeUnfollowServiceSpy.sendUnfollowRequest(validRequest);
Assertions.assertEquals(successResponse, response);
}
/**
* Verify that the {@link MakeUnfollowService#sendUnfollowRequest(MakeUnfollowRequest)} method loads the
* profile image of each user included in the result.
*
* @throws IOException if an IO error occurs.
*/
/*@Test
public void testGetUnfollowees_validRequest_loadsProfileImages() throws IOException {
MakeUnfollowResponse response = makeUnfollowServiceSpy.sendUnfollowRequest(validRequest);
response.
for(User user : response.sendUnfollowRequest()) {
Assertions.assertNotNull(user.getImageBytes());
}
}*/
/**
* Verify that for failed requests the {@link MakeUnfollowService#sendUnfollowRequest(MakeUnfollowRequest)}
* method returns the same result as the {@link ServerFacade}.
*
* @throws IOException if an IO error occurs.
*/
@Test
public void testGetUnfollow_invalidRequest_returnsUnfollow() throws IOException {
MakeUnfollowResponse response = makeUnfollowServiceSpy.sendUnfollowRequest(invalidRequest);
Assertions.assertEquals(failureResponse, response);
}
}
|
/*
* Copyright 2019 iserge.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cleanlogic.rsc4j.format.primitives;
import com.google.gson.annotations.Expose;
import org.cleanlogic.rsc4j.format.enums.PrimitiveType;
import java.nio.ByteBuffer;
/**
* @author Serge Silaev aka iSergio <s.serge.b@gmail.com>
*/
public class HatchSquarePrimitive extends Primitive {
/**
* Угол наклона штриховки в градусах (0,45,90,135) против часовой стрелки от горизонтали.
*/
private int angle;
/**
* Расстояние между осями линий штриховки.
*/
private int step;
/**
* {@link LinePrimitive} or {@link DottedLinePrimitive}
*/
private Primitive desc;
private int length;
public HatchSquarePrimitive(int incode) {
super(PrimitiveType.HATCHSQUARE, null, incode);
}
@Override
public int getLength() {
return this.length;
}
public int getAngle() {
return angle;
}
public void setAngle(int angle) {
this.angle = angle;
}
public int getStep() {
return step;
}
public void setStep(int step) {
this.step = step;
}
public Primitive getDesc() {
return desc;
}
public void setDesc(Primitive desc) {
this.desc = desc;
}
// @Override
// public void setLength(int length) {
// super.setLength(length);
// }
@Override
public HatchSquarePrimitive read(ByteBuffer buffer, boolean strict) {
// Buffer position before begin read
int pos = buffer.position();
this.length = buffer.getInt();
angle = buffer.getInt();
step = buffer.getInt();
PrimitiveType type = PrimitiveType.fromValue(buffer.getInt());
if (type == PrimitiveType.LINE) {
desc = new LinePrimitive(super.getIncode()).read(buffer, strict);
} else if (type == PrimitiveType.DOTTEDLINE) {
desc = new DottedLinePrimitive(super.getIncode()).read(buffer, strict);
}
int length = buffer.position() - pos;
if (length != this.length) {
System.err.println(String.format("%s[%d]: something wrong with read primitive. Aspect/Actual: %d/%d", PrimitiveType.HATCHSQUARE, incode, this.length, length));
}
return this;
}
}
|
package com.cnk.travelogix.jalo;
import com.cnk.travelogix.constants.PaymentgatewaysConstants;
import de.hybris.platform.jalo.JaloSession;
import de.hybris.platform.jalo.extension.ExtensionManager;
import org.apache.log4j.Logger;
@SuppressWarnings("PMD")
public class PaymentgatewaysManager extends GeneratedPaymentgatewaysManager
{
@SuppressWarnings("unused")
private static Logger log = Logger.getLogger( PaymentgatewaysManager.class.getName() );
public static final PaymentgatewaysManager getInstance()
{
ExtensionManager em = JaloSession.getCurrentSession().getExtensionManager();
return (PaymentgatewaysManager) em.getExtension(PaymentgatewaysConstants.EXTENSIONNAME);
}
}
|
package io.swagger.client.api;
import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.model.*;
import java.util.*;
import io.swagger.client.model.FundingSourceListResponse;
import io.swagger.client.model.FundingSource;
import io.swagger.client.model.CreateFundingSourceRequest;
import io.swagger.client.model.Unit$;
import io.swagger.client.model.RemoveBankRequest;
import io.swagger.client.model.FundingSourceBalance;
import io.swagger.client.model.MicroDepositsInitiated;
import io.swagger.client.model.MicroDeposits;
import io.swagger.client.model.VerifyMicroDepositsRequest;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.util.Map;
import java.util.HashMap;
import java.net.URL;
import java.net.MalformedURLException;
public class FundingsourcesApi {
private ApiClient apiClient;
private String[] authNames = new String[] { "oauth2" };
public FundingsourcesApi() {
this(Configuration.getDefaultApiClient());
}
public FundingsourcesApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Get an account's funding sources.
*
* @param id Account id to get funding sources for.
* @param removed Filter funding sources by this value.
* @return FundingSourceListResponse
*/
public FundingSourceListResponse getAccountFundingSources (String id, Boolean removed) throws ApiException {
Object postBody = null;
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException(400, "Missing the required parameter 'id' when calling getAccountFundingSources");
}
// if a URL is provided, extract the ID
URL u;
try {
u = new URL(id);
id = id.substring(id.lastIndexOf('/') + 1);
}
catch (MalformedURLException mue) {
u = null;
}
// create path and map variables
String path = "/accounts/{id}/funding-sources".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
if (removed != null)
queryParams.put("removed", apiClient.parameterToString(removed));
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/vnd.dwolla.v1.hal+json"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (FundingSourceListResponse) apiClient.deserialize(response, "", FundingSourceListResponse.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Get a customer's funding sources.
*
* @param id Customer id to get funding sources for.
* @param removed Filter funding sources by this value.
* @return FundingSourceListResponse
*/
public FundingSourceListResponse getCustomerFundingSources (String id, Boolean removed) throws ApiException {
Object postBody = null;
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException(400, "Missing the required parameter 'id' when calling getCustomerFundingSources");
}
// if a URL is provided, extract the ID
URL u;
try {
u = new URL(id);
id = id.substring(id.lastIndexOf('/') + 1);
}
catch (MalformedURLException mue) {
u = null;
}
// create path and map variables
String path = "/customers/{id}/funding-sources".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
if (removed != null)
queryParams.put("removed", apiClient.parameterToString(removed));
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/vnd.dwolla.v1.hal+json"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (FundingSourceListResponse) apiClient.deserialize(response, "", FundingSourceListResponse.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Create a new funding source.
*
* @param body Funding source to create.
* @param id Customer id to create funding source for.
* @return FundingSource
*/
public FundingSource createCustomerFundingSource (CreateFundingSourceRequest body, String id) throws ApiException {
Object postBody = body;
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException(400, "Missing the required parameter 'id' when calling createCustomerFundingSource");
}
// if a URL is provided, extract the ID
URL u;
try {
u = new URL(id);
id = id.substring(id.lastIndexOf('/') + 1);
}
catch (MalformedURLException mue) {
u = null;
}
// create path and map variables
String path = "/customers/{id}/funding-sources".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/vnd.dwolla.v1.hal+json"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (FundingSource) apiClient.deserialize(response, "", FundingSource.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Create a new funding source.
*
* @param body Funding source to create.
* @return FundingSource
*/
public FundingSource createFundingSource (CreateFundingSourceRequest body) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/funding-sources".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/vnd.dwolla.v1.hal+json"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (FundingSource) apiClient.deserialize(response, "", FundingSource.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Get a funding source by id.
*
* @param id Funding source ID to get.
* @return FundingSource
*/
public FundingSource id (String id) throws ApiException {
Object postBody = null;
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException(400, "Missing the required parameter 'id' when calling id");
}
// if a URL is provided, extract the ID
URL u;
try {
u = new URL(id);
id = id.substring(id.lastIndexOf('/') + 1);
}
catch (MalformedURLException mue) {
u = null;
}
// create path and map variables
String path = "/funding-sources/{id}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (FundingSource) apiClient.deserialize(response, "", FundingSource.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Remove a funding source.
*
* @param body request body to remove a funding source
* @param id Funding source ID to remove.
* @return FundingSource
*/
public FundingSource softDelete (RemoveBankRequest body, String id) throws ApiException {
Object postBody = body;
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException(400, "Missing the required parameter 'id' when calling softDelete");
}
// if a URL is provided, extract the ID
URL u;
try {
u = new URL(id);
id = id.substring(id.lastIndexOf('/') + 1);
}
catch (MalformedURLException mue) {
u = null;
}
// create path and map variables
String path = "/funding-sources/{id}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (FundingSource) apiClient.deserialize(response, "", FundingSource.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Get the balance of a funding source.
*
* @param id Funding source ID to get the balance for.
* @return FundingSourceBalance
*/
public FundingSourceBalance getBalance (String id) throws ApiException {
Object postBody = null;
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException(400, "Missing the required parameter 'id' when calling getBalance");
}
// if a URL is provided, extract the ID
URL u;
try {
u = new URL(id);
id = id.substring(id.lastIndexOf('/') + 1);
}
catch (MalformedURLException mue) {
u = null;
}
// create path and map variables
String path = "/funding-sources/{id}/balance".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (FundingSourceBalance) apiClient.deserialize(response, "", FundingSourceBalance.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Verify pending verifications exist.
*
* @param id Funding source ID to check for pending validation deposits for.
* @return MicroDepositsInitiated
*/
public MicroDepositsInitiated verifyMicroDepositsExist (String id) throws ApiException {
Object postBody = null;
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException(400, "Missing the required parameter 'id' when calling verifyMicroDepositsExist");
}
// if a URL is provided, extract the ID
URL u;
try {
u = new URL(id);
id = id.substring(id.lastIndexOf('/') + 1);
}
catch (MalformedURLException mue) {
u = null;
}
// create path and map variables
String path = "/funding-sources/{id}/micro-deposits".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (MicroDepositsInitiated) apiClient.deserialize(response, "", MicroDepositsInitiated.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Initiate or verify micro deposits for bank verification.
*
* @param body Optional micro deposit amounts for verification
* @param id Funding source ID to initiate or verify micro deposits for.
* @return MicroDeposits
*/
public MicroDeposits microDeposits (VerifyMicroDepositsRequest body, String id) throws ApiException {
Object postBody = body;
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException(400, "Missing the required parameter 'id' when calling microDeposits");
}
// if a URL is provided, extract the ID
URL u;
try {
u = new URL(id);
id = id.substring(id.lastIndexOf('/') + 1);
}
catch (MalformedURLException mue) {
u = null;
}
// create path and map variables
String path = "/funding-sources/{id}/micro-deposits".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (MicroDeposits) apiClient.deserialize(response, "", MicroDeposits.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
}
|
package com.diwakar.theater.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.NOT_FOUND)
public class TheaterNotFoundException extends RuntimeException {
public TheaterNotFoundException(String message) {
super(message);
}
}
|
package com.aplicacion.guiaplayasgalicia.utils;
import java.util.List;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
public class MapUtils {
/**
* Method that retrieves the last current location
* @param context
* @return Location object with the last current location
*/
public static Location bestLastKnownLocation(Context context) {
Location bestResult = null;
float bestAccuracy = Float.MAX_VALUE;
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
List<String> providers = locationManager.getAllProviders();
for (String provider : providers) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
if (accuracy < bestAccuracy) {
bestResult = location;
bestAccuracy = accuracy;
}
}
}
return bestResult;
}
}
|
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.*;
public class QuestionWindow extends JFrame {
/**
*
*/
private static final long serialVersionUID = 38476236516135752L;
private JTextField entry;
private JLabel question, extra, ansLab, image;
private JButton submit, know, notKnow;
private ProblemSet currentSet;
private int qIndex, numRight, numWrong;
private JPanel panel;
private Question currentQu;
private StudyHelper sh;
private miniHUD mh;
private SingleQuestionEditor quEdit;
private ProblemStorage ps;
private ArrayList<Question> qStorage;
private User currentUser;
private Database db;
public QuestionWindow(StudyHelper s, miniHUD m, ProblemStorage p, Database d) {
setSize(800, 450);
setResizable(false);
setVisible(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mh = m;
sh = s;
db = d;
qIndex = 0;
ps = p;
quEdit = new SingleQuestionEditor(this, ps, db);
JMenuBar jmb = new JMenuBar();
question = new JLabel("");
extra = new JLabel("");
submit = new JButton("Submit Answer");
know = new JButton("I knew the answer");
notKnow = new JButton("I didn't know the answer");
ansLab = new JLabel("");
image = new JLabel();
panel = new JPanel();
entry = new JTextField();
JMenu m1 = new JMenu("Options");
JMenuItem toggleHUD = new JMenuItem("Toggle miniHUD");
JMenuItem exitDomain = new JMenuItem("Exit Domain");
JMenuItem editQuestion = new JMenuItem("Edit Question");
JMenuItem delQu = new JMenuItem("Delete Question");
panel.setLayout(null);
entry.setColumns(50);
entry.setBounds(75, 300, 650, 25);
question.setBounds(75, 25, 1000, 25);
extra.setBounds(75, 50, 1000, 25);
image.setBounds(75, 100, 600, 150);
submit.setBounds(300, 350, 200, 40);
know.setBounds(75, 350, 200, 40);
notKnow.setBounds(525, 350, 200, 40);
ansLab.setBounds(75, 310, 1000, 40);
jmb.setBackground(Color.BLACK);
m1.setForeground(Color.GREEN);
toggleHUD.setForeground(Color.GREEN);
exitDomain.setForeground(Color.GREEN);
editQuestion.setForeground(Color.GREEN);
delQu.setForeground(Color.GREEN);
toggleHUD.setBackground(Color.BLACK);
exitDomain.setBackground(Color.BLACK);
editQuestion.setBackground(Color.BLACK);
delQu.setBackground(Color.BLACK);
entry.setBackground(Color.BLACK);
entry.setForeground(Color.GREEN);
question.setForeground(Color.GREEN);
extra.setForeground(Color.GREEN);
submit.setForeground(Color.GREEN);
know.setForeground(Color.GREEN);
notKnow.setForeground(Color.GREEN);
ansLab.setForeground(Color.GREEN);
panel.setBackground(Color.BLACK);
submit.setBackground(Color.BLACK);
know.setForeground(Color.BLACK);
notKnow.setForeground(Color.BLACK);
this.add(panel);
panel.add(question);
panel.add(extra);
panel.add(submit);
panel.add(entry);
panel.add(ansLab);
panel.add(image);
panel.add(know);
panel.add(notKnow);
know.setVisible(false);
notKnow.setVisible(false);
this.setJMenuBar(jmb);
jmb.add(m1);
m1.add(exitDomain);
m1.add(editQuestion);
m1.add(delQu);
m1.add(toggleHUD);
toggleHUD.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sh.toggleMiniHUD();
}
});
submit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
submit();
}
});
know.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
know();
}
});
notKnow.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
notKnow();
}
});
exitDomain.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mh.emptyRight();
mh.emptyLeft();
currentQu = null;
question.setText("");
extra.setText("");
qIndex = 0;
sh.reload(currentSet);
}
});
editQuestion.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
editQuestion();
}
});
delQu.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
deleteCurrentQu();
}
});
}
public void loadWindow(ProblemSet ps, boolean randomize, User cU) {
mh.setVisible(true);
currentUser = cU;
numRight = 0;
numWrong = 0;
setLocation(0, 0);
setTitle("Quizzing on: " + ps.getName());
currentSet = ps;
setVisible(true);
mh.setRight(0);
mh.setWrong(0);
ansLab.setText("");
qStorage = new ArrayList<Question>(currentSet.getList());
if (randomize) {
randomizeOrder();
}
loadQu();
}
public void submit() {
submit.setVisible(false);
know.setVisible(true);
notKnow.setVisible(true);
entry.setText("");
ansLab.setText("The correct answer was: " + currentQu.getAns() + ".");
db.getData().get(currentUser.getName()).addAsked(currentSet, currentQu);
}
public void know() {
submit.setVisible(true);
know.setVisible(false);
notKnow.setVisible(false);
numRight++;
mh.setRight(numRight);
ansLab.setText("");
db.getData().get(currentUser.getName()).addRight(currentSet, currentQu);
qIndex++;
if (qIndex < qStorage.size()) {
loadQu();
} else {
close();
}
}
public void notKnow() {
submit.setVisible(true);
know.setVisible(false);
notKnow.setVisible(false);
numWrong++;
mh.setWrong(numWrong);
ansLab.setText("");
qIndex++;
if (qIndex < qStorage.size()) {
loadQu();
} else {
close();
}
}
public void loadQu() {
currentQu = qStorage.get(qIndex);
question.setText(currentQu.getPrompt());
extra.setText(currentQu.getExtra());
if (currentQu.getImage() != null) {
image.setIcon(currentQu.getImage());
} else {
image.setIcon(null);
}
}
public void randomizeOrder() {
ArrayList<Question> randQ = new ArrayList<Question>();
while (qStorage.size() > 0) {
int randInt = (int) (Math.random() * qStorage.size());
randQ.add(qStorage.remove(randInt));
}
qStorage = randQ;
qIndex = 0;
mh.setRight(0);
mh.setWrong(0);
numRight = 0;
numWrong = 0;
ansLab.setText("");
loadQu();
}
public void editQuestion() {
quEdit.getAUser(currentUser);
quEdit.loadWindow(currentSet, currentQu, qIndex);
this.setVisible(false);
}
public void reload() {
this.setVisible(true);
if (qIndex >= currentSet.getLength()) {
close();
} else {
this.loadQu();
}
}
public void close() {
mh.emptyRight();
mh.emptyLeft();
JOptionPane.showMessageDialog(null, "You knew " + numRight + " and did not know " + numWrong + ".", "Results",
JOptionPane.INFORMATION_MESSAGE);
currentQu = null;
question.setText("");
extra.setText("");
qIndex = 0;
sh.reload(currentSet);
}
public void deleteCurrentQu() {
String check = JOptionPane.showInputDialog("Are you sure?(Y/N)\nNumber of Attempts: "
+ db.getData().get(currentUser.getName()).getAsked(currentSet, currentQu)
+ "\nNumber of correct attempts: "
+ db.getData().get(currentUser.getName()).getAsked(currentSet, currentQu));
if (check == null) {
return;
}
check = check.toUpperCase();
if (check.equals("Y")) {
currentSet.deleteQuestion(qIndex, db);
ps.updateFile();
if (qIndex >= currentSet.getLength()) {
close();
} else {
currentQu = currentSet.getQuestionByIndex(qIndex);
this.loadQu();
}
}
}
}
|
package edu.sit.bancodedados.conexao;
public enum EErrosConexao {
ABRE_CONEXAO ("Erro de Conexão: Não foi possível estabelecer conexão com o Banco de Dados."),
FECHA_CONEXAO ("Erro de Conexão: Não foi possível fechar a conexão com o Banco de Dados.");
private String mensagem;
public String getMensagem() {
return mensagem;
}
private EErrosConexao(String mensagem) {
this.mensagem = mensagem;
}
}
|
package test;
import static org.junit.Assert.*;
import model.HeroDTO;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import dao.DAOException;
import dao.mysql.HeroDAOImpl;
public class TestHeroDAOImpl {
private HeroDAOImpl heroImpl;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
heroImpl = new HeroDAOImpl();
}
@After
public void tearDown() throws Exception {
}
@Test
public void testDeleteHero() {
fail("Not yet implemented");
}
@Test
public void testFindAllHero() {
fail("Not yet implemented");
}
@Test
public void testFindHero() throws DAOException {
HeroDTO hero = heroImpl.findHero("Ghandhi");
assertTrue(hero.getName().trim().equalsIgnoreCase("Ghandhi"));
}
@Test
public void testInsertHero() {
fail("Not yet implemented");
}
@Test
public void testUpdateHero() {
fail("Not yet implemented");
}
@Test
public void testFindHeroByCriteria() {
fail("Not yet implemented");
}
}
|
package com.romariogrohmann.sistemagestaodevisitas;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class login extends AppCompatActivity {
private Button btAcessar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
btAcessar = findViewById(R.id.btAcessar);
btAcessar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), telainicial.class);
startActivity( intent );
}
});
}
}
|
package modeltests;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.net.MalformedURLException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import server.httprequest.HttpRequester;
import utilities.Users;
public class UsersTest {
static HttpRequester requester;
/**
* Adds test data to database.
* @throws MalformedURLException Error
* @throws IOException Error
*/
@BeforeClass
public static void setUp() throws MalformedURLException, IOException {
requester = new HttpRequester();
String sqlCommand = "INSERT INTO staff "
+ "(username, email, pass, full_name, telephone_number, address, "
+ "job_position_id, permission_level) VALUES "
+ "('testUsername', 'testEmail', 'testPassword', 'testFullName',"
+ " 'testNumber', 'testAddress', 1, 1)";
requester.sendPost("/database/insertRow", sqlCommand);
}
/**
* Used to remove test data from db.
* @throws MalformedURLException Error
* @throws IOException Error
*/
@AfterClass
public static void tearDown() throws MalformedURLException, IOException {
requester = new HttpRequester();
String sqlCommand = "DELETE FROM staff WHERE username ='testUsername'";
requester.sendPost("/database/deleteRow", sqlCommand);
}
@Test
public void userNameIsThereTest() {
String[] dbNames = { "connor", "geoff", "bill", "tommy", "lilo", "stitch" };
String username = "connor";
assertEquals("Test to see if can tell if username is there", true,
Users.userNameIsThere(username, dbNames));
}
@Test
public void userNameIsNotThereTest() {
String[] dbNames = { "connor", "geoff", "bill", "tommy", "lilo", "stitch" };
String username = "reggie";
assertEquals("Test to see if can tell if username is there", false,
Users.userNameIsThere(username, dbNames));
}
@Test
public void getStaffUsernamesTest() {
String username = "testUsername";
assertEquals(
"Test that uses the usernameThere method with a call to the database",
true, Users.userNameIsThere(username, Users.getStaffUsernames()));
}
@Test
public void getStaffUsernamesNotThereTest() {
String username = "notPresent";
assertEquals(
"Test that uses the usernameThere method with a call to the database",
false, Users.userNameIsThere(username, Users.getStaffUsernames()));
}
@Test
public void staffObjectTest() {
String address = "testAddress";
assertEquals(
"This test is used to make sure the object is created from the database information",
true,
address.equals(Users.getStaffObject("testUsername").getAddress()));
}
@Test
public void staffObjectWrongTest() {
String address = "wrongAddress";
assertEquals(
"This test is used to make sure the object is created from the database information",
false,
address.equals(Users.getStaffObject("testUsername").getAddress()));
}
}
|
package de.dhbw.studientag.model;
import android.os.Parcel;
import android.os.Parcelable;
/**
* represents a comment / notes for a company
*
*/
public class Comment implements Parcelable {
private long id;
private Company company;
private String fullMessage;
public Comment(long id, Company company, String message) {
this(company);
this.id = id;
this.fullMessage = message;
}
public Comment(Company company){
this.company = company;
}
public long getId() {
return id;
}
public Company getCompany() {
return company;
}
public String getFullMessage() {
return fullMessage;
}
public String getShortMessage() {
final int LIMIT = 100;
if (fullMessage != null && !fullMessage.isEmpty()) {
// remove line breaks:
String shortMessage = this.fullMessage.replace("\n", " ").replace("\r", " ");
if (shortMessage.length() < LIMIT) {
return shortMessage;
} else {
return shortMessage.substring(0, LIMIT).concat("...");
}
} else {
return "";
}
}
@Override
public int describeContents() {
return this.hashCode();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeParcelable(company, flags);
dest.writeString(fullMessage);
}
private Comment(Parcel source){
this(source.readLong(), (Company) source.readParcelable(Company.class.getClassLoader()), source.readString());
}
public static final Parcelable.Creator<Comment> CREATOR =
new Parcelable.Creator<Comment>() {
public Comment createFromParcel(Parcel in) {
return new Comment(in);
}
public Comment[] newArray(int size) {
return new Comment[size];
}
};
}
|
package com.tencent.mm.plugin.appbrand.jsapi.file;
public final class r extends b<ao> {
private static final int CTRL_INDEX = -1;
private static final String NAME = "isdir";
public r() {
super(new ao());
}
}
|
package view.menuutil;
import descriptionfiles.DescSection;
import descriptionfiles.Description;
import descriptionfiles.DescriptionFiles;
import graphana.model.HelpSystem;
import graphana.operationsystem.Operation;
import view.argumentcomponents.ArgumentComponentManager;
import view.argumentcomponents.ArgumentsPanelSettings;
import view.guicomponents.mainmenu.GraphanaMainMenu;
import java.awt.event.ActionEvent;
/**
* A sub menu containing menu items for each section of a given section file. Each menu item leads to a sub menu with
* macro items of operations of the respective section.
*
* @author Andreas Fender
*/
public class OperationSectionMenu extends GraphanaMenu {
private static final long serialVersionUID = 1L;
private final static ArgumentsPanelSettings ARGUMENT_SETTINGS = new ArgumentsPanelSettings(true, true);
private DescriptionFiles descFiles;
private GraphanaMainMenu mainMenu;
/**
* Creates an instance
*
* @param title the caption of the item
* @param mainMenu the top level main menu
* @param argumentComponentManager the argument component manager to create argument components
*/
public OperationSectionMenu(String title, GraphanaMainMenu mainMenu, ArgumentComponentManager
argumentComponentManager) {
super(title, mainMenu.getMainControl(), argumentComponentManager);
this.mainMenu = mainMenu;
this.descFiles = mainControl.getOperationSet().getDescFiles();
}
/**
* Creates the sub menu.
*
* @param sectionFilename the filename of the section file.
*/
public void create(String sectionFilename) {
for (String sectionTitle : HelpSystem.iterateSections(sectionFilename)) {
MacroMenu subMenu = new MacroMenu(sectionTitle, mainMenu, argumentComponentManager, ARGUMENT_SETTINGS);
DescSection section = descFiles.getSection(sectionTitle);
for (Description desc : section.getDescriptions()) {
if (!desc.isTerm()) {
Operation operation = mainControl.getOperationSet().getOperation(desc.getKey());
if (operation == null) throw new RuntimeException("Operation not found: '" + desc.getKey() + "'");
subMenu.addOperationItem(desc.getKey(), operation, '\0');
}
}
this.add(subMenu);
}
}
@Override
public void actionPerformed(ActionEvent ev) {
}
}
|
package jpa.project.repository.board;
import jpa.project.model.dto.board.BoardDto;
import jpa.project.repository.search.BoardSearch;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
@Repository
public interface BoardRepositoryCustom {
Page<BoardDto> search(BoardSearch boardSearch, Pageable pageable);
}
|
package interfaz;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import logica.Controlador;
import otros.DAOException;
public class PanelPrincipal extends JFrame {
private JPanel contentPane;
private JButton btnLogIn;
private PanelFondo panelFondo;
private JButton btnNuevaPartida;
private JButton btnMisPartidas;
private static JButton btnInvitaciones;
private String nombreLogin;
private static int numInvitaciones;
private JButton btnLoguot;
private Controlador control;
private PanelCarga panelCarga;
private JButton btnNombreLogin;
private JButton btnAyuda;
/**
* Create the frame.
*/
public PanelPrincipal(String nombrelogin , final int numInvitaciones) {
try {
control = new Controlador();
} catch (DAOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.nombreLogin=nombrelogin;
this.numInvitaciones=numInvitaciones;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 637, 396);
setLocationRelativeTo(null);
setUndecorated(true);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
panelFondo = new PanelFondo("/imagenes/panelPrincipalFondo3.png");
panelFondo.setBounds(0, 0, 637, 396);
panelFondo.setFocusable(false);
contentPane.add(panelFondo);
btnLogIn = new JButton("Clasificacion");
btnLogIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clasificaciones();
}
});
btnLogIn.setFont(new Font("AR CHRISTY", Font.BOLD, 14));
btnLogIn.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
btnLogIn.setFont(new Font("AR CHRISTY", Font.BOLD, 16));
setCursor(Cursor.HAND_CURSOR);
}
@Override
public void mouseExited(MouseEvent e) {
btnLogIn.setFont(new Font("AR CHRISTY", Font.BOLD, 14));
setCursor(Cursor.DEFAULT_CURSOR);
}
});
btnLogIn.setForeground(Color.WHITE);
btnLogIn.setBounds(233, 218, 173, 23);
btnLogIn.setOpaque(false);
btnLogIn.setBorderPainted(false);
btnLogIn.setContentAreaFilled(false);
panelFondo.add(btnLogIn);
btnNuevaPartida = new JButton("Nueva Partida");
btnNuevaPartida.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
partidaNueva();
}
});
btnNuevaPartida.setOpaque(false);
btnNuevaPartida.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
btnNuevaPartida.setFont(new Font("AR CHRISTY", Font.BOLD, 16));
setCursor(Cursor.HAND_CURSOR);
}
@Override
public void mouseExited(MouseEvent e) {
btnNuevaPartida.setFont(new Font("AR CHRISTY", Font.BOLD, 14));
setCursor(Cursor.DEFAULT_CURSOR);
}
});
btnNuevaPartida.setForeground(Color.WHITE);
btnNuevaPartida.setFont(new Font("AR CHRISTY", Font.BOLD, 14));
btnNuevaPartida.setContentAreaFilled(false);
btnNuevaPartida.setBorderPainted(false);
btnNuevaPartida.setBounds(233, 150, 173, 23);
panelFondo.add(btnNuevaPartida);
btnMisPartidas = new JButton("Mis Partidas");
btnMisPartidas.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cargarPartida(nombreLogin);
panelCarga= new PanelCarga("/imagenes/PartidasGIF.gif");
setVisible(false);
panelCarga.setVisible(true);
}
});
btnMisPartidas.setOpaque(false);
btnMisPartidas.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
btnMisPartidas.setFont(new Font("AR CHRISTY", Font.BOLD, 16));
setCursor(Cursor.HAND_CURSOR);
}
@Override
public void mouseExited(MouseEvent e) {
btnMisPartidas.setFont(new Font("AR CHRISTY", Font.BOLD, 14));
setCursor(Cursor.DEFAULT_CURSOR);
}
});
btnMisPartidas.setForeground(Color.WHITE);
btnMisPartidas.setFont(new Font("AR CHRISTY", Font.BOLD, 14));
btnMisPartidas.setContentAreaFilled(false);
btnMisPartidas.setBorderPainted(false);
btnMisPartidas.setBounds(233, 184, 173, 23);
panelFondo.add(btnMisPartidas);
btnInvitaciones = new JButton();
btnInvitaciones.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(numInvitaciones>0){
PanelInvitaciones panelIn = new PanelInvitaciones(nombreLogin);
panelIn.setVisible(true);
}else JOptionPane.showMessageDialog(contentPane, "No tiene ninguna invitación", "", JOptionPane.INFORMATION_MESSAGE);
}
});
btnInvitaciones.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
btnInvitaciones.setIcon(new ImageIcon(PanelPrincipal.class.getResource("/imagenes/sobre40.png")));
btnInvitaciones.setFont(new Font("AR CHRISTY", Font.BOLD, 16));
setCursor(Cursor.HAND_CURSOR);
}
@Override
public void mouseExited(MouseEvent e) {
btnInvitaciones.setIcon(new ImageIcon(PanelPrincipal.class.getResource("/imagenes/sobre32.png")));
btnInvitaciones.setFont(new Font("AR CHRISTY", Font.BOLD, 14));
setCursor(Cursor.DEFAULT_CURSOR);
}
});
btnInvitaciones.setForeground(Color.WHITE);
btnInvitaciones.setFont(new Font("AR CHRISTY", Font.PLAIN, 14));
btnInvitaciones.setIcon(new ImageIcon(PanelPrincipal.class.getResource("/imagenes/sobre32.png")));
btnInvitaciones.setFont(new Font("AR CHRISTY", Font.BOLD, 14));
btnInvitaciones.setContentAreaFilled(false);
btnInvitaciones.setBorderPainted(false);
btnInvitaciones.setBounds(112, 113, 165, 41);
btnInvitaciones.setText("("+numInvitaciones+")");
btnInvitaciones.setFocusable(false);
panelFondo.add(btnInvitaciones);
btnAyuda = new JButton("Ayuda");
btnAyuda.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PanelAyuda pa = new PanelAyuda();
pa.setVisible(true);
}
});
btnAyuda.setForeground(Color.WHITE);
btnAyuda.setFont(new Font("AR CHRISTY", Font.PLAIN, 14));
btnAyuda.setFont(new Font("AR CHRISTY", Font.BOLD, 14));
btnAyuda.setContentAreaFilled(false);
btnAyuda.setBorderPainted(false);
btnAyuda.setBounds(233, 252, 173, 23);
btnAyuda.setOpaque(false);
btnAyuda.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
btnAyuda.setFont(new Font("AR CHRISTY", Font.BOLD, 16));
setCursor(Cursor.HAND_CURSOR);
}
@Override
public void mouseExited(MouseEvent e) {
btnAyuda.setFont(new Font("AR CHRISTY", Font.BOLD, 14));
setCursor(Cursor.DEFAULT_CURSOR);
}
});
panelFondo.add(btnAyuda);
btnLoguot = new JButton("");
btnLoguot.setToolTipText("Salir de la sesión");
btnLoguot.setIcon(new ImageIcon(PanelPrincipal.class.getResource("/imagenes/off25.png")));
btnLoguot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PanelInicio panelInicion= new PanelInicio();
panelInicion.setVisible(true);
dispose();
}
});
btnLoguot.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent arg0) {
btnLoguot.setIcon(new ImageIcon(PanelPrincipal.class.getResource("/imagenes/off32.png")));
setCursor(Cursor.HAND_CURSOR);
}
@Override
public void mouseExited(MouseEvent e) {
btnLoguot.setIcon(new ImageIcon(PanelPrincipal.class.getResource("/imagenes/off25.png")));
setCursor(Cursor.DEFAULT_CURSOR);
}
});
btnLoguot.setOpaque(false);
btnLoguot.setContentAreaFilled(false);
btnLoguot.setBorderPainted(false);
btnLoguot.setBounds(462, 240, 38, 41);
panelFondo.add(btnLoguot);
btnNombreLogin = new JButton();
btnNombreLogin.setForeground(Color.WHITE);
btnNombreLogin.setFont(new Font("Dialog", Font.PLAIN, 14));
btnNombreLogin.setContentAreaFilled(false);
btnNombreLogin.setBorderPainted(false);
btnNombreLogin.setBounds(387, 113, 165, 41);
btnNombreLogin.setText(nombreLogin);
btnNombreLogin.setFocusable(false);
panelFondo.add(btnNombreLogin);
}
public void partidaNueva(){
PanelNuevaPartida panelNuevaPartida= new PanelNuevaPartida(nombreLogin);
panelNuevaPartida.setVisible(true);
}
public static void setNumInvitaciones(int n){
numInvitaciones=n;
}
public static int getNumInvitaciones(){
return numInvitaciones;
}
public static void cambiarTextobtn(int numInvitaciones){
if(numInvitaciones>0){
btnInvitaciones.setText(numInvitaciones+"");
}else btnInvitaciones.setText("(0)");
}
public void cargarPartida(final String jugador){
Runnable miRunnable = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try{
control= new Controlador();
List<List<Integer>> listasIds = control.getIdsPartidasAceptadas(jugador);
List<Integer> listaIdsPartidas = listasIds.get(0);
List<Integer> listaIdsPartidasAceptadas = listasIds.get(1);
ArrayList<String[]> listaInfoPartidas = control.cargarInfoPartidas(jugador,listaIdsPartidas);
if (listaInfoPartidas.size() != 0){
PanelMisPartidas panel = new PanelMisPartidas(listaInfoPartidas,listaIdsPartidasAceptadas,jugador);
panelCarga.dispose();
//setVisible(true);
panel.setVisible(true);
}
else{
panelCarga.dispose();
setVisible(true);
JOptionPane.showMessageDialog(contentPane, "No tiene partidas en curso", "Partidas no encontradas", JOptionPane.INFORMATION_MESSAGE);
}
}catch(DAOException e){
}
}
};
Thread hilo = new Thread(miRunnable);
hilo.start();
}
protected void clasificaciones(){
Controlador control;
try {
control = new Controlador();
ArrayList<String[]> listaJugadores = control.getClasificacion();
PanelClasificacion panelClasificacion = new PanelClasificacion(listaJugadores);
panelClasificacion.setVisible(true);
} catch (DAOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.chris.projects.fx.ftp.fix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import quickfix.*;
public class FixSessionConnector implements SessionConnector {
private static final Logger LOG = LoggerFactory.getLogger(FixSessionConnector.class);
private Connector connector;
private FixConnectorFactory fixConnectorFactory;
private volatile boolean isFixSessionStarted;
public FixSessionConnector(String configFile, boolean isAcceptor, Application fixApplication, FixConnectorFactory fixConnectorFactory) {
this.fixConnectorFactory = fixConnectorFactory;
this.connector = createConnector(configFile, isAcceptor, fixApplication);
}
@Override
public void start() {
startFixSession();
}
@Override
public void stop() {
stopSession();
}
private void startFixSession() {
try {
connector.start();
isFixSessionStarted = true;
} catch (ConfigError configError) {
LOG.error("Fail to start FTP fix application {}, with exception", configError.getMessage(), configError);
}
}
private void stopSession() {
connector.stop();
isFixSessionStarted = false;
}
private Connector createConnector(String configFile, boolean isAcceptor, Application fixApplication) {
try {
SessionSettings sessionSettings = getSessionSettings(configFile);
MessageStoreFactory messageStoreFactory = new FileStoreFactory(sessionSettings);
MessageFactory messageFactory = new DefaultMessageFactory();
LogFactory logFactory = new SLF4JLogFactory(sessionSettings);
if (isAcceptor) {
return fixConnectorFactory.createSocketAcceptor(fixApplication, messageStoreFactory, sessionSettings, logFactory, messageFactory);
}else {
return fixConnectorFactory.createSocketInitiator(fixApplication, messageStoreFactory, sessionSettings, logFactory, messageFactory);
}
}catch (ConfigError | RuntimeException ex) {
LOG.error("Fail to create FTP fix application {}, with exception {}", ex.getMessage(), ex);
return null; // bad practice, show return some special case
}
}
private SessionSettings getSessionSettings(String configFile) throws ConfigError {
LOG.info("Loading fix configuration from: {}", configFile);
final SessionSettings fixSessionSettings = new FixSessionSettingsFactory(configFile).create();
LOG.info("Fix session {} created", fixSessionSettings);
return fixSessionSettings;
}
}
|
package com.buckstracksui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import com.buckstracksui.R;
/**
* Created by carmelo.iriti on 30/03/2015.
*/
public class FeedLayout extends LinearLayout {
public FeedLayout(Context context) {
super(context);
init();
}
public FeedLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
void init(){
setOrientation(LinearLayout.HORIZONTAL);
setWeightSum(2f);
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.compound_send_cancel, this, true);
setBackgroundResource(android.R.color.black);
}
}
|
import org.javacord.api.DiscordApi;
import org.javacord.api.DiscordApiBuilder;
import org.javacord.api.util.logging.ExceptionLogger;
public class Main {
public static void main(String[] args) {
DiscordApi api = new DiscordApiBuilder().setToken(args[0]).
login().exceptionally(ExceptionLogger.get()).join();
JavacordCommandListener registry = new JavacordCommandListener("!");
registry.registerCommand("ping", new Ping());
api.addMessageCreateListener(registry);
}
}
|
package Model.Set;
import org.junit.Test;
import java.util.HashSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.*;
/**
* Classe de test de SetStack
*/
public class SetStackTest {
private final SetStack stack = SetStack.generate();
/**
* Test de l'opération d'union des ensembles
*/
@Test
public void doOperationUnion() {
stack.push(Stream.of(1.0, 2.0, 3.0).collect(Collectors.toCollection(HashSet::new)));
stack.push(Stream.of(3.0, 4.0, 5.0).collect(Collectors.toCollection(HashSet::new)));
HashSet<Double> test = Stream.of(1.0, 2.0, 3.0, 4.0, 5.0).collect(Collectors.toCollection(HashSet::new));
assertEquals(test, stack.doOperation("UNION"));
}
/**
* Test de l'opération d'intersection des ensembles
*/
@Test
public void doOperationInter() {
stack.push(Stream.of(1.0, 2.0, 3.0).collect(Collectors.toCollection(HashSet::new)));
stack.push(Stream.of(3.0, 4.0, 5.0).collect(Collectors.toCollection(HashSet::new)));
HashSet<Double> test = Stream.of(3.0).collect(Collectors.toCollection(HashSet::new));
assertEquals(test, stack.doOperation("INTER"));
}
/**
* Test de l'opération de complémentaire des ensembles
*/
@Test
public void doOperationDiff() {
stack.push(Stream.of(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0).collect(Collectors.toCollection(HashSet::new)));
stack.push(Stream.of(5.0, 6.0, 7.0).collect(Collectors.toCollection(HashSet::new)));
HashSet<Double> test = Stream.of(0.0, 1.0, 2.0, 3.0, 4.0).collect(Collectors.toCollection(HashSet::new));
assertEquals(test, stack.doOperation("DIFFERENCE"));
}
/**
* Test de la reconnaissance de l'opérateur UNION
*/
@Test
public void isOperatorUnion() { assertTrue(stack.isOperator("UNION")); }
/**
* Test de la reconnaissance de l'opérateur INTER
*/
@Test
public void isOperatorInter() {
assertTrue(stack.isOperator("INTER"));
}
/**
* Test de la reconnaissance de l'opérateur DIFFERENCE
*/
@Test
public void isOperatorDiff() {
assertTrue(stack.isOperator("DIFFERENCE"));
}
/**
* Test de la conversion de la chaîne entrée en ensemble
*/
@Test
public void getValue() {
HashSet<Double> test = stack.getValue("[1,2,3]");
HashSet<Double> compare = Stream.of(1.0, 2.0, 3.0).collect(Collectors.toCollection(HashSet::new));
assertEquals(compare, test);
}
}
|
package com.zstu.util;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Map;
public class JdbcUtil{
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
final String URL="jdbc:mysql://localhost:3306/zstu-exam";
final String USERNAME="root";
final String PASSWORD="333";
PreparedStatement ps =null;
Connection con =null;
public Connection getCon(){
try {
con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
public Connection getCon(HttpServletRequest req){
ServletContext application =req.getServletContext();
Map map =(Map) application.getAttribute("key");
Iterator it =map.keySet().iterator();
while (it.hasNext()){
con =(Connection)it.next();
Boolean bl=(Boolean) map.get(con);
if(bl==true){
map.put(con,false);
break;
}
}
return con;
}
public PreparedStatement creatStatement(String sql){
con = getCon();
try {
ps=con.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
public PreparedStatement creatStatement(String sql,HttpServletRequest request){
con = getCon(request);
try {
ps=con.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
public void close(){
if (ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public void close(HttpServletRequest request){
if (ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
ServletContext application =request.getServletContext();
Map map=(Map) application.getAttribute("key");
map.put(con,false);
}
public void close(ResultSet rs){
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
close();
}
public void close(ResultSet rs,HttpServletRequest request){
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
close(request);
}
}
|
package cn.yami.wechat.demo.dao;
import cn.yami.wechat.demo.dto.OrderInfo;
import cn.yami.wechat.demo.dto.SpikeOrder;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
@Mapper
@Component
public interface OrderDao {
@Select("select * from spike_order where user_id = #{userId} and shops_id = #{shopId}")
SpikeOrder getSpikeOrderByUserId(@Param("userId") long id, @Param("shopId") long shopId);
@Insert("insert into order_info(user_id,shops_id,shops_name,shops_count,shops_price,order_channel,status,create_date)" +
" values(#{userId},#{shopId},#{shopName},#{shopCount},#{shopPrice},#{orderChannel},#{status},#{createDate})")
@SelectKey(keyColumn = "id",keyProperty = "id",resultType = long.class,before = false,statement = "select last_insert_id()")
long insertOrder(OrderInfo orderInfo);
@Insert("insert into spike_order(user_id,order_id,shops_id) values(#{userId},#{orderId},#{shopId})")
int insertSpikeOrder(SpikeOrder order);
}
|
package com.xj.base.service;
import com.xj.base.entity.Student;
import com.xj.base.entity.User;
import com.xj.base.service.support.IBaseService;
/**
* <p>
* 人员服务类
* </p>
*
* @author xj
* @since 2020-02-28
*/
public interface IStudentService extends IBaseService<Student, Integer>{
/**
* 根据用户名查找用户
* @param name 名字
* @return
*/
Student findByName(String name);
/**
*
* @param id id
* @return
*/
String findClassNameById(Integer id);
/**
* 增加或者修改用户
* @param user
*/
String saveOrUpdate(Student student);
/**
* 根据部门id查找数量
*/
int findCountByDeptId(Integer id);
void grant(Integer id, String[] roleIds);
String findDormitoryNameById(Integer id);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.