hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
3e13469eef9ae88d201dd4aefd102084b69d4d1b
746
java
Java
biz/src/main/java/ctone/rap/component/LabelComponent.java
c-tone/rap
11724032131239ed23a3f6df8c004f8be83d6c9d
[ "MIT" ]
null
null
null
biz/src/main/java/ctone/rap/component/LabelComponent.java
c-tone/rap
11724032131239ed23a3f6df8c004f8be83d6c9d
[ "MIT" ]
1
2022-03-31T18:41:29.000Z
2022-03-31T18:41:29.000Z
biz/src/main/java/ctone/rap/component/LabelComponent.java
c-tone/rap
11724032131239ed23a3f6df8c004f8be83d6c9d
[ "MIT" ]
null
null
null
15.541667
61
0.565684
8,136
package ctone.rap.component; import ctone.rap.db.module.Label; import java.util.List; import java.util.Map; /** * Created by ouyi on 2017/2/26. */ public class LabelComponent implements Component<Label>{ public long add(){ return 0; } public int edit(){ return 0; } public int delete(){ return 0; } //帖标 public int attach(){ return 0; } //去标 public int remove(){ return 0; } @Override public Label load(long id) { return null; } @Override public List<Label> list(Map<String, Object> conditions) { return null; } @Override public int count(Map<String, Object> conditions) { return 0; } }
3e1346f4e906966da509c8a10cfe88288f3131f9
1,893
java
Java
permission-entity/src/main/java/com/nepxion/permission/entity/RolePermissionEntity.java
Nepxion/Permission
be651d8247217f91a1022016680f18437ffb1833
[ "Apache-2.0" ]
83
2018-01-18T09:56:19.000Z
2022-03-11T15:32:51.000Z
permission-entity/src/main/java/com/nepxion/permission/entity/RolePermissionEntity.java
Nepxion/Permission
be651d8247217f91a1022016680f18437ffb1833
[ "Apache-2.0" ]
null
null
null
permission-entity/src/main/java/com/nepxion/permission/entity/RolePermissionEntity.java
Nepxion/Permission
be651d8247217f91a1022016680f18437ffb1833
[ "Apache-2.0" ]
31
2018-05-04T02:48:06.000Z
2021-07-01T14:17:26.000Z
23.37037
72
0.676175
8,137
package com.nepxion.permission.entity; /** * <p>Title: Nepxion Permission</p> * <p>Description: Nepxion Permission</p> * <p>Copyright: Copyright (c) 2017-2050</p> * <p>Company: Nepxion</p> * @author Haojun Ren * @version 1.0 */ public class RolePermissionEntity extends BasicEntity { private static final long serialVersionUID = -8798208584420759097L; // 做一定的冗余设计,避免多表查询 private Long roleId; private String roleName; private RoleEntity roleEntity; // 做一定的冗余设计,避免多表查询 private Long permissionId; private String permissionName; private String permissionType; private PermissionEntity permissionEntity; public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public RoleEntity getRoleEntity() { return roleEntity; } public void setRoleEntity(RoleEntity roleEntity) { this.roleEntity = roleEntity; } public Long getPermissionId() { return permissionId; } public void setPermissionId(Long permissionId) { this.permissionId = permissionId; } public String getPermissionName() { return permissionName; } public void setPermissionName(String permissionName) { this.permissionName = permissionName; } public String getPermissionType() { return permissionType; } public void setPermissionType(String permissionType) { this.permissionType = permissionType; } public PermissionEntity getPermissionEntity() { return permissionEntity; } public void setPermissionEntity(PermissionEntity permissionEntity) { this.permissionEntity = permissionEntity; } }
3e134868cf46b5df25cceec7628288881c7f8311
5,345
java
Java
src/com/company/AccountSettings/AccountSettingsController.java
RickardA/Swedenbank
3c31300c9596de659d07f0630b4be964856fdd0a
[ "MIT" ]
null
null
null
src/com/company/AccountSettings/AccountSettingsController.java
RickardA/Swedenbank
3c31300c9596de659d07f0630b4be964856fdd0a
[ "MIT" ]
null
null
null
src/com/company/AccountSettings/AccountSettingsController.java
RickardA/Swedenbank
3c31300c9596de659d07f0630b4be964856fdd0a
[ "MIT" ]
null
null
null
33.40625
94
0.579233
8,138
package com.company.AccountSettings; import com.company.Account; import com.company.Database.DB; import com.company.Helpers.Messsage; import com.company.Interfaces.ParentController; import com.company.Navigation.NavController; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.text.Text; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AccountSettingsController implements ParentController { private NavController navController; @FXML private Button applyButton; @FXML private Button createAccountButton; @FXML private TextField accountNameField; @FXML private Text accountNumberText; @FXML private RadioButton savingsButton; @FXML private RadioButton cardButton; @FXML private RadioButton salaryButton; @FXML private RadioButton undefinedButton; @FXML private RadioButton companyButton; @FXML private Button deleteButton; @FXML private Text saldoText; private Account account; private ToggleGroup toggleGroup = new ToggleGroup(); private boolean isTypeChanged = false; private boolean isNameChanged = false; @FXML private void initialize(){ setup(); } private void setup(){ if (account.getType().matches("Företagskonto")){ savingsButton.setVisible(false); cardButton.setVisible(false); salaryButton.setVisible(false); undefinedButton.setVisible(false); companyButton.setVisible(true); companyButton.fire(); deleteButton.setVisible(false); accountNameField.setText(account.getAccount_name()); }else { companyButton.setVisible(false); accountNameField.setText(account.getAccount_name()); accountNumberText.setText(account.getAccount_number()); saldoText.setText("" + account.getBalance()); savingsButton.setToggleGroup(toggleGroup); cardButton.setToggleGroup(toggleGroup); salaryButton.setToggleGroup(toggleGroup); undefinedButton.setToggleGroup(toggleGroup); switch (account.getType()) { case "Sparkonto": savingsButton.fire(); break; case "Lönekonto": salaryButton.fire(); break; case "Kortkonto": cardButton.fire(); break; case "Ingen Koppling": undefinedButton.fire(); break; } deleteButton.setOnMousePressed(event -> deleteAccount()); applyButton.setOnMousePressed(event -> applyChanges()); toggleGroup.selectedToggleProperty().addListener((observable, oldVal, newVal) -> { if (newVal.toString().contains(account.getType())) { isTypeChanged = false; } else { isTypeChanged = true; } checkIfChangesIsMade(); }); accountNameField.textProperty().addListener((observable, oldVal, newVal) -> { if (newVal.equals(account.getAccount_name())) { isNameChanged = false; } else { isNameChanged = true; } checkIfChangesIsMade(); }); } } private void checkIfChangesIsMade(){ if (isTypeChanged == true || isNameChanged == true){ applyButton.setDisable(false); }else { applyButton.setDisable(true); } } private void applyChanges(){ int success = 0; String type = ""; Pattern pattern = Pattern.compile("(?:^|)'([^']*?)'(?:|$)"); Matcher matcher = pattern.matcher(toggleGroup.getSelectedToggle().toString()); if (matcher.find()){ type = matcher.group(1); System.out.println(type); if(!type.equals(account.getType()) || !type.equals("Ingen Koppling")) { Boolean result = account.setType(type); System.out.println(result); if (result == false) { Messsage.printError("Det finns redan ett konto med denna typen!"); applyButton.setDisable(false); }else success++; }else{ success++; } }else{ System.out.println("Something went wrong"); } if (success == 1){ account.setAccount_name(accountNameField.getText()); applyButton.setDisable(true); Messsage.printSuccess("Ändringar genomförda"); } } public void setAccount(Account account){ this.account = account; } private void deleteAccount(){ boolean result = DB.deleteAccount(account.getAccount_number()); if (result == true){ Messsage.printSuccess("Konto raderat"); navController.displayHomePage(); }else { Messsage.printError("Kan inte radera konto, får inte inehålla pengar!"); } } @Override public void setParent(Object parent) { navController = (NavController)parent; } }
3e1349e58cb1330a18b83f070abd694df320f8c5
293
java
Java
Aug9-Springboot/mod-spring-boot-angular5/user-portal/src/main/java/com/devglan/userportal/UserRepository.java
gupta-ji6/IIHT-Assignments
492c2122b52c2da938b46fcb6a8e9dc3ef0c833d
[ "MIT" ]
1
2021-04-02T21:43:57.000Z
2021-04-02T21:43:57.000Z
Aug8-SpringBoot/spring-boot-angular5/user-portal/src/main/java/com/devglan/userportal/UserRepository.java
gupta-ji6/IIHT-Assignments
492c2122b52c2da938b46fcb6a8e9dc3ef0c833d
[ "MIT" ]
null
null
null
Aug8-SpringBoot/spring-boot-angular5/user-portal/src/main/java/com/devglan/userportal/UserRepository.java
gupta-ji6/IIHT-Assignments
492c2122b52c2da938b46fcb6a8e9dc3ef0c833d
[ "MIT" ]
1
2022-02-16T14:56:11.000Z
2022-02-16T14:56:11.000Z
17.235294
67
0.733788
8,139
package com.devglan.userportal; import org.springframework.data.repository.Repository; import java.util.List; public interface UserRepository extends Repository<User, Integer> { void delete(User user); List<User> findAll(); User findOne(int id); User save(User user); }
3e134a23b35c8ef4b0e45c904db47ced00dabdc4
2,099
java
Java
src/main/java/io/bdrc/lucene/sa/CommonHelpers.java
drupchen/lucene-sa-pi
568d9f02fb856156c0db8838012a91494ca36f33
[ "Apache-2.0" ]
1
2020-08-28T01:28:17.000Z
2020-08-28T01:28:17.000Z
src/main/java/io/bdrc/lucene/sa/CommonHelpers.java
drupchen/lucene-sa-pi
568d9f02fb856156c0db8838012a91494ca36f33
[ "Apache-2.0" ]
16
2017-10-30T13:47:28.000Z
2018-11-19T14:50:51.000Z
src/main/java/io/bdrc/lucene/sa/CommonHelpers.java
drupchen/lucene-sa-pi
568d9f02fb856156c0db8838012a91494ca36f33
[ "Apache-2.0" ]
2
2019-02-05T09:32:12.000Z
2021-07-18T06:32:46.000Z
34.983333
98
0.634111
8,140
package io.bdrc.lucene.sa; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.InputStream; import java.util.Comparator; import java.util.MissingResourceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CommonHelpers { static final Logger logger = LoggerFactory.getLogger(CommonHelpers.class); public static final String baseDir = "src/main/resources/"; public static InputStream getResourceOrFile(final String baseName) { InputStream stream = null; stream = CommonHelpers.class.getClassLoader().getResourceAsStream("/"+baseName); if (stream != null) { logger.info("found resource /{} through regular classloader", baseName); return stream; } stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("/"+baseName); if (stream != null) { logger.info("found resource /{} through thread context classloader", baseName); return stream; } final String fileBaseName = baseDir+baseName; try { stream = new FileInputStream(fileBaseName); logger.info("found file {}", fileBaseName); return stream; } catch (FileNotFoundException e) { logger.info("could not find file {}", fileBaseName); return null; } } public static final BufferedReader getFileContent (final String baseName) { try { return new BufferedReader(new FileReader(baseName)); } catch (FileNotFoundException e) { throw new MissingResourceException("cannot find file " + baseName, "", ""); } } public static class LengthComp implements Comparator<String> { @Override public int compare(String s1, String s2) { final int lenComp = s2.length() - s1.length(); if (lenComp != 0) { return lenComp; } return s1.compareTo(s2); } } }
3e134ad37a68daee4dcc3b4cf4ae82942cc99c88
18,203
java
Java
components/src/main/java/ca/phon/ui/ipa/DefaultSyllabificationDisplayUI.java
phon-ca/phon
a6ad9ed772aded438602a010deacf02883d35ade
[ "Apache-2.0" ]
27
2016-12-04T19:46:48.000Z
2022-01-22T18:49:40.000Z
components/src/main/java/ca/phon/ui/ipa/DefaultSyllabificationDisplayUI.java
ghedlund/phon
2a8e4e2c9954604123748e17d611385e41e6357e
[ "Apache-2.0" ]
196
2016-02-10T16:43:02.000Z
2022-03-23T16:56:28.000Z
components/src/main/java/ca/phon/ui/ipa/DefaultSyllabificationDisplayUI.java
ghedlund/phon
2a8e4e2c9954604123748e17d611385e41e6357e
[ "Apache-2.0" ]
2
2021-03-31T22:09:58.000Z
2022-03-09T07:13:42.000Z
31.823427
108
0.698731
8,141
/* * Copyright (C) 2005-2020 Gregory Hedlund & Yvan Rose * * 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 ca.phon.ui.ipa; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.event.*; import org.jdesktop.swingx.painter.effects.*; import ca.phon.ipa.*; import ca.phon.syllable.*; import ca.phon.ui.action.*; /** * */ public class DefaultSyllabificationDisplayUI extends SyllabificationDisplayUI { /* Action IDs */ private static final String FOCUS_PREVIOUS = "_FOCUS_PREV_PHONE_"; private static final String FOCUS_NEXT = "_FOCUS_NEXT_PHONE_"; private static final String TOGGLE_HIATUS = "_TOGGLE_HIATUS_"; private static final String SET_SCTYPE_PREFIX = "_SET_SCTYPE_"; private static final String BACKSPACE = "_backspace_"; private static final int insetSize = 2; private Insets phoneBoxInsets = new Insets(insetSize, insetSize, insetSize, insetSize); private Dimension phoneBoxSize = new Dimension(18, 20); /** Display we are installed on */ private SyllabificationDisplay display; public DefaultSyllabificationDisplayUI(SyllabificationDisplay display) { super(); this.display = display; } @Override public void installUI(JComponent c) { display = (SyllabificationDisplay) c; setupActions(); installMouseListener(); display.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent fe) { display.repaint(); } @Override public void focusLost(FocusEvent fe) { display.repaint(); } }); display.addPropertyChangeListener("showDiacritics", (e) -> display.repaint() ); display.setRequestFocusEnabled(true); } /** Setup actions for component */ private void setupActions() { ActionMap actionMap = display.getActionMap(); InputMap inputMap = display.getInputMap(JComponent.WHEN_FOCUSED); PhonUIAction focusNextAct = new PhonUIAction(this, "focusNextPhone"); actionMap.put(FOCUS_NEXT, focusNextAct); KeyStroke focusNextKs = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0); inputMap.put(focusNextKs, FOCUS_NEXT); PhonUIAction focusPrevAct = new PhonUIAction(this, "focusPrevPhone"); actionMap.put(FOCUS_PREVIOUS, focusPrevAct); KeyStroke focusPrevKs = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0); inputMap.put(focusPrevKs, FOCUS_PREVIOUS); PhonUIAction backSpaceAct = new PhonUIAction(this, "onBackspace", SyllableConstituentType.UNKNOWN); actionMap.put(BACKSPACE, backSpaceAct); KeyStroke delKs = KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0); inputMap.put(delKs, BACKSPACE); PhonUIAction toggleHiatusAct = new PhonUIAction(this, "toggleHiatus"); actionMap.put(TOGGLE_HIATUS, toggleHiatusAct); KeyStroke toggleHiatusKs1 = KeyStroke.getKeyStroke('h'); KeyStroke toggleHiatusKs2 = KeyStroke.getKeyStroke('H'); inputMap.put(toggleHiatusKs1, TOGGLE_HIATUS); inputMap.put(toggleHiatusKs2, TOGGLE_HIATUS); // sc type identifiers for (int scTypeIdx = 0; scTypeIdx < SyllableConstituentType.values().length; scTypeIdx++) { SyllableConstituentType scType = SyllableConstituentType.values()[scTypeIdx]; String scChar1 = (scType.getIdChar() + "").toUpperCase(); String scChar2 = (scType.getIdChar() + "").toLowerCase(); String scTypeActID = SET_SCTYPE_PREFIX + "_" + scType.getIdentifier().toUpperCase() + "_"; PhonUIAction scTypeAct = new PhonUIAction(this, "setScType", scType); actionMap.put(scTypeActID, scTypeAct); KeyStroke scKs1 = KeyStroke.getKeyStroke(scChar1.charAt(0)); inputMap.put(scKs1, scTypeActID); KeyStroke scKs2 = KeyStroke.getKeyStroke(scChar2.charAt(0)); inputMap.put(scKs2, scTypeActID); } String removeSyllabificationID = SET_SCTYPE_PREFIX + "_" + SyllableConstituentType.UNKNOWN.getIdentifier().toUpperCase() + "_"; PhonUIAction removeSyllabificationAct = new PhonUIAction(this, "setScType", SyllableConstituentType.UNKNOWN); actionMap.put(removeSyllabificationID, removeSyllabificationAct); KeyStroke removeSyllabificationKs = KeyStroke.getKeyStroke( KeyEvent.VK_DELETE, 0); inputMap.put(removeSyllabificationKs, removeSyllabificationID); } /** UI Actions */ public void onBackspace(PhonActionEvent pae) { int pIdx = display.getFocusedPhone(); display.setSyllabificationAtIndex(pIdx, (SyllableConstituentType) pae.getData()); int prevFocus = pIdx - 1; if (prevFocus >= 0) { display.setFocusedPhone(prevFocus); } } public void focusNextPhone(PhonActionEvent pae) { int currentFocus = display.getFocusedPhone(); int nextFocus = currentFocus + 1; if (nextFocus < display.getNumberOfDisplayedPhones()) { display.setFocusedPhone(nextFocus); } } public void focusPrevPhone(PhonActionEvent pae) { int currentFocus = display.getFocusedPhone(); int prevFocus = currentFocus - 1; if (prevFocus >= 0) { display.setFocusedPhone(prevFocus); } } public void toggleHiatus(PhonActionEvent pae) { int pIdx = (pae.getData() != null ? (int)pae.getData() : display.getFocusedPhone()); display.toggleHiatus(pIdx); } public void setScType(PhonActionEvent pae) { int pIdx = display.getFocusedPhone(); display.setSyllabificationAtIndex(pIdx, (SyllableConstituentType) pae.getData()); display.setFocusedPhone(pIdx + 1); } public void menuSetScType(PhonActionEvent pae) { int pIdx = display.getFocusedPhone(); display.setSyllabificationAtIndex(pIdx, (SyllableConstituentType) pae.getData()); } /** * Get the context menu for the specified phone */ private JPopupMenu getContextMenu(int pIdx) { final JPopupMenu retVal = new JPopupMenu(); // final IPATranscript ipa = display.getContextMenuTranscript(); IPAElement phone = display.getPhoneAtIndex(pIdx); if (phone != null) { for (int i = 0; i < SyllableConstituentType.values().length; i++) { SyllableConstituentType scType = SyllableConstituentType .values()[i]; String itemText = "<html>"; if (scType == SyllableConstituentType.ONSET) { itemText += "<u><b>O</b></u>nset"; } else if (scType == SyllableConstituentType.NUCLEUS) { itemText += "<u><b>N</b></u>ucleus"; } else if (scType == SyllableConstituentType.CODA) { itemText += "<u><b>C</b></u>oda"; } else if (scType == SyllableConstituentType.LEFTAPPENDIX) { itemText += "<u><b>L</b></u>eft Appendix"; } else if (scType == SyllableConstituentType.RIGHTAPPENDIX) { itemText += "<u><b>R</b></u>ight Appendix"; } else if (scType == SyllableConstituentType.OEHS) { itemText += "O<u><b>E</b></u>HS"; } else if (scType == SyllableConstituentType.AMBISYLLABIC) { itemText += "<u><b>A</b></u>mbisyllabic"; } else if (scType == SyllableConstituentType.UNKNOWN) { itemText += "<u><b>U</b></u>nknown"; } else { continue; } itemText += "</html>"; final JMenuItem constituentItem = new JMenuItem(itemText); PhonUIAction constituentAction = new PhonUIAction(this, "menuSetScType", scType); constituentAction.putValue(Action.NAME, itemText); constituentItem.setAction(constituentAction); retVal.add(constituentItem); } if(pIdx < display.getNumberOfDisplayedPhones()-1 && phone.getScType() == SyllableConstituentType.NUCLEUS) { IPAElement nextPhone = display.getPhoneAtIndex(pIdx+1); if(nextPhone.getScType() == SyllableConstituentType.NUCLEUS) { String itemText = "<html>Toggle Hiatus with " + nextPhone.getText(); JMenuItem item = new JMenuItem(); PhonUIAction toggleHiatusAct = new PhonUIAction(this, "toggleHiatus", pIdx+1); toggleHiatusAct.putValue(Action.NAME, itemText); item.setAction(toggleHiatusAct); retVal.addSeparator(); retVal.add(item); } } if (pIdx > 0 && phone.getScType() == SyllableConstituentType.NUCLEUS) { IPAElement prevPhone = display.getPhoneAtIndex(pIdx - 1); if (prevPhone.getScType() == SyllableConstituentType.NUCLEUS) { String itemText = "<html>Toggle <u><b>H</b></u>iatus with " + prevPhone.getText(); JMenuItem item = new JMenuItem(); PhonUIAction toggleHiatusAct = new PhonUIAction(this, "toggleHiatus", pIdx); toggleHiatusAct.putValue(Action.NAME, itemText); item.setAction(toggleHiatusAct); retVal.addSeparator(); retVal.add(item); } } } return retVal; } /** Install mouse listener for component */ private void installMouseListener() { MouseListener mouseListener = new MouseInputAdapter() { @Override public void mouseClicked(MouseEvent me) { } @Override public void mousePressed(MouseEvent me) { // System.out.println(me); display.requestFocusInWindow(); int pIdx = locationToPhoneIndex(me.getPoint()); if (pIdx >= 0) { display.setFocusedPhone(pIdx); if (me.isPopupTrigger()) { JPopupMenu menu = getContextMenu(pIdx); menu.show(display, me.getPoint().x, me.getPoint().y); } } } @Override public void mouseReleased(MouseEvent me) { if (me.isPopupTrigger()) { JPopupMenu menu = getContextMenu(display.getFocusedPhone()); menu.show(display, me.getPoint().x, me.getPoint().y); } } }; display.addMouseListener(mouseListener); } /** * Paint phones */ @Override public void paint(Graphics g, JComponent c) { Graphics2D g2d = (Graphics2D) g; // Enable antialiasing for shapes g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // Enable antialiasing for text g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); Dimension size = display.getSize(); if (display.isOpaque()) { g2d.setColor(display.getBackground()); g2d.fillRect(0, 0, size.width, size.height); } // setup phone rect int pX = c.getInsets().left + insetSize; int pY = c.getInsets().top + insetSize; int pW = phoneBoxInsets.left + phoneBoxInsets.right + phoneBoxSize.width; int pH = phoneBoxInsets.top + phoneBoxInsets.bottom + phoneBoxSize.height; Font displayFont = display.getFont(); Rectangle phoneRect = new Rectangle(pX, pY, pW, pH); double dArcLengthFill = Math.min(phoneRect.width / 1.8, phoneRect.height / 1.8); double dOffsetFill = dArcLengthFill / 2; // draw syllable background first List<Area> syllAreas = new ArrayList<Area>(); List<Area> phoneAreas = new ArrayList<Area>(); int syllCurrentX = phoneRect.x; IPATranscript grpPhones = (display.getTranscript() == null ? new IPATranscript() : display.getTranscript()); List<IPATranscript> syllables = grpPhones.syllables(); for (int sIdx = 0; sIdx < syllables.size(); sIdx++) { final IPATranscript s = syllables.get(sIdx); IPATranscript syllablePhones = s.removePunctuation(); int sX = syllCurrentX; int sY = phoneRect.y; int sW = syllablePhones.length() * phoneRect.width; int sH = phoneRect.height; syllCurrentX += sW; if((sIdx+1) < syllables.size()) { final IPATranscript nextSyll = syllables.get(sIdx+1); if(nextSyll.length() > 0 && nextSyll.elementAt(0).getScType() == SyllableConstituentType.AMBISYLLABIC) { sW += phoneRect.width; } } Rectangle sR = new Rectangle(sX, sY, sW, sH); // outer area RoundRectangle2D.Double rrect2dFill = new RoundRectangle2D.Double( sR.x, sR.y, sR.width, sR.height, dArcLengthFill, dArcLengthFill); Area fillArea = new Area(rrect2dFill); syllAreas.add(fillArea); Rectangle savedPhoneRect = new Rectangle(phoneRect); for (int pIdx = 0; pIdx < syllablePhones.length(); pIdx++) { IPAElement p = syllablePhones.elementAt(pIdx); // calculate fill area Rectangle2D.Double phoneRect2d = new Rectangle2D.Double( phoneRect.x, phoneRect.y, phoneRect.width, phoneRect.height); Area phoneArea = new Area(phoneRect2d); if (pIdx == 0) { RoundRectangle2D.Double roundPhoneRect2d = new RoundRectangle2D.Double( phoneRect.x, phoneRect.y, phoneRect.width, phoneRect.height, dArcLengthFill, dArcLengthFill); Rectangle2D.Double fillRect = new Rectangle2D.Double( phoneRect.x + phoneRect.width - dOffsetFill, phoneRect.y, dOffsetFill, phoneRect.height); phoneArea = new Area(roundPhoneRect2d); if (syllablePhones.length() > 1) phoneArea.add(new Area(fillRect)); } else if (pIdx == syllablePhones.length() - 1) { RoundRectangle2D.Double roundPhoneRect2d = new RoundRectangle2D.Double( phoneRect.x, phoneRect.y, phoneRect.width, phoneRect.height, dArcLengthFill, dArcLengthFill); Rectangle2D.Double fillRect = new Rectangle2D.Double( phoneRect.x, phoneRect.y, dOffsetFill, phoneRect.height); phoneArea = new Area(roundPhoneRect2d); phoneArea.add(new Area(fillRect)); } Color grad_top = p.getScType().getColor().brighter(); Color grad_btm = p.getScType().getColor().darker(); GradientPaint gp = new GradientPaint(new Point(phoneRect.x, phoneRect.y), grad_top, new Point(phoneRect.x, phoneRect.y + phoneRect.height), grad_btm); Paint oldPaiont = g2d.getPaint(); g2d.setPaint(gp); g2d.fill(phoneArea); g2d.setPaint(oldPaiont); phoneAreas.add(phoneArea); g2d.setColor(Color.gray); g2d.setStroke(new BasicStroke(0.5f)); g2d.draw(phoneArea); phoneRect.translate(phoneRect.width, 0); } // draw bottom syllable highlight Color grad_top = new Color(150, 150, 150, 0); Color grad_btm = new Color(150, 150, 150, 100); GradientPaint gp = new GradientPaint(new Point(sR.x + (2 * insetSize), (sR.y + sR.height) - 3 * insetSize), grad_top, new Point(sR.x + (2 * insetSize), (sR.y + sR.height) - insetSize), grad_btm); Paint oldPaint = g2d.getPaint(); g2d.setPaint(gp); g2d.setPaint(oldPaint); phoneRect = new Rectangle(savedPhoneRect); for (int pIdx = 0; pIdx < syllablePhones.length(); pIdx++) { IPAElement p = syllablePhones.elementAt(pIdx); // draw phone string Rectangle pBox = new Rectangle(phoneRect.x + phoneBoxInsets.left, phoneRect.y + phoneBoxInsets.top, phoneBoxSize.width, phoneBoxSize.height); IPATranscriptBuilder builder = new IPATranscriptBuilder(); builder.append(p); IPATranscript trans = builder.toIPATranscript(); if(!display.isShowDiacritics()) trans = trans.stripDiacritics(); String txt = trans.toString(); Font f = displayFont; FontMetrics fm = g.getFontMetrics(f); Rectangle2D stringBounds = fm.getStringBounds(txt, g); while ((stringBounds.getWidth() > pBox.width) || (stringBounds.getHeight() > pBox.height)) { f = f.deriveFont(f.getSize2D() - 0.2f); fm = g.getFontMetrics(f); stringBounds = fm.getStringBounds(txt, g); } float phoneX = pBox.x + (pBox.width / 2.0f) - ((float) stringBounds.getWidth() / 2.0f); float phoneY = (float) pBox.y + (float) pBox.height - fm.getDescent(); g2d.setFont(f); g2d.setColor(c.getForeground()); g2d.drawString(txt, phoneX, phoneY); phoneRect.translate(phoneRect.width, 0); } // draw top highlight grad_top = new Color(255, 255, 255, 80); grad_btm = new Color(255, 255, 255, 0); gp = new GradientPaint(new Point(sR.x, sR.y), grad_top, new Point( sR.x, sR.y + 3 * insetSize), grad_btm); oldPaint = g2d.getPaint(); g2d.setPaint(gp); g2d.fillRoundRect(sR.x, sR.y, sR.width, 3 * insetSize, (int) dArcLengthFill, (int) dArcLengthFill); g2d.setPaint(oldPaint); } // draw syllable outlines for (Area syllArea : syllAreas) { g2d.setStroke(new BasicStroke(1.5f)); g2d.setColor(Color.darkGray); g2d.draw(syllArea); } if (display.hasFocus() && display.getNumberOfDisplayedPhones() > 0 && display.getFocusedPhone() < display.getNumberOfDisplayedPhones() && display.getFocusedPhone() >= 0) { Area phoneArea = phoneAreas.get(display.getFocusedPhone()); GlowPathEffect gpe = new GlowPathEffect(); gpe.setRenderInsideShape(true); gpe.setBrushColor(Color.yellow); gpe.apply(g2d, phoneArea, 0, 0); } } @Override public Dimension getPreferredSize(JComponent c) { Dimension retVal = new Dimension(0, 0); int widthPerPhone = phoneBoxInsets.right + phoneBoxInsets.left + phoneBoxSize.width; int height = phoneBoxInsets.top + phoneBoxInsets.bottom + phoneBoxSize.height; retVal.width = widthPerPhone * (display.getNumberOfDisplayedPhones()) + 2 * insetSize + c.getInsets().right + c.getInsets().left; retVal.height = height + c.getInsets().top + c.getInsets().bottom + /* padding */2 * insetSize; return retVal; } @Override public Rectangle rectForPhone(int pidx) { int pX = display.getInsets().left + insetSize; int pY = display.getInsets().top + insetSize; int pW = phoneBoxInsets.left + phoneBoxInsets.right + phoneBoxSize.width; int pH = phoneBoxInsets.top + phoneBoxInsets.bottom + phoneBoxSize.height; Rectangle phoneRect = new Rectangle(pX, pY, pW, pH); phoneRect.translate(pidx * pW, 0); return phoneRect; } @Override public int locationToPhoneIndex(Point p) { int widthPerPhone = phoneBoxInsets.right + phoneBoxInsets.left + phoneBoxSize.width; int currentX = display.getInsets().left + insetSize; int pIdx = 0; IPATranscript grpPhones = display.getDisplayedPhones(); int grpSize = widthPerPhone * grpPhones.length(); if ((currentX + grpSize) >= p.x) { for (int grpPIdx = 0; grpPIdx < grpPhones.length(); grpPIdx++) { currentX += widthPerPhone; if (currentX >= p.x) { break; } pIdx++; } } return pIdx; } }
3e134bc0aae1de5701e689e136e2a0a999fbf511
110
java
Java
Week3/Day2/src/main/java/gradleTest/Calculator.java
f10re/Prep-Work---Full-Stack-Development
2cbee91cdea5d88d18b1e4cf525687c580719278
[ "MIT" ]
6
2018-03-17T14:32:59.000Z
2021-05-14T02:00:19.000Z
Week3/Day2/src/main/java/gradleTest/Calculator.java
f10re/Prep-Work---Full-Stack-Development
2cbee91cdea5d88d18b1e4cf525687c580719278
[ "MIT" ]
null
null
null
Week3/Day2/src/main/java/gradleTest/Calculator.java
f10re/Prep-Work---Full-Stack-Development
2cbee91cdea5d88d18b1e4cf525687c580719278
[ "MIT" ]
2
2018-02-07T20:14:42.000Z
2018-06-03T17:37:26.000Z
12.222222
41
0.681818
8,142
package gradleTest; public class Calculator { public double add (double x, double y) { return x+y; } }
3e134bc507a0276d09aadae43a6c4619a6f90fd4
227
java
Java
src/zajecia11bootcamp/OldDog.java
Konrad-code/NaukaCD
1f08750d65767bdb1a39f6369b1809a7159abfa9
[ "Unlicense" ]
null
null
null
src/zajecia11bootcamp/OldDog.java
Konrad-code/NaukaCD
1f08750d65767bdb1a39f6369b1809a7159abfa9
[ "Unlicense" ]
null
null
null
src/zajecia11bootcamp/OldDog.java
Konrad-code/NaukaCD
1f08750d65767bdb1a39f6369b1809a7159abfa9
[ "Unlicense" ]
null
null
null
17.461538
44
0.678414
8,143
package zajecia11bootcamp; public class OldDog implements Dog{ @Override public void bark(int iloscSzczekniec) { for(int i = 0; i < iloscSzczekniec; i++) { System.out.print("hauuu "); } System.out.println(); } }
3e134d1d6cdac32296f183b911f536780a1e4672
4,136
java
Java
src/test/java/ch/admin/bag/covidcode/authcodegeneration/web/controller/AuthCodeVerificationControllerV2SecurityTest.java
admin-ch/CovidCode-Service
d45c3f3522904ff6121709009459ed168dae73e7
[ "MIT" ]
14
2020-05-13T12:51:09.000Z
2021-09-11T08:45:20.000Z
src/test/java/ch/admin/bag/covidcode/authcodegeneration/web/controller/AuthCodeVerificationControllerV2SecurityTest.java
admin-ch/CovidCode-Service
d45c3f3522904ff6121709009459ed168dae73e7
[ "MIT" ]
15
2020-05-05T09:29:03.000Z
2021-05-25T12:37:27.000Z
src/test/java/ch/admin/bag/covidcode/authcodegeneration/web/controller/AuthCodeVerificationControllerV2SecurityTest.java
admin-ch/CovidCode-Service
d45c3f3522904ff6121709009459ed168dae73e7
[ "MIT" ]
5
2020-05-06T22:34:39.000Z
2021-11-29T16:54:13.000Z
49.238095
127
0.786509
8,144
package ch.admin.bag.covidcode.authcodegeneration.web.controller; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import ch.admin.bag.covidcode.authcodegeneration.api.AuthorizationCodeVerificationDto; import ch.admin.bag.covidcode.authcodegeneration.api.AuthorizationCodeVerifyResponseDto; import ch.admin.bag.covidcode.authcodegeneration.api.AuthorizationCodeVerifyResponseDtoWrapper; import ch.admin.bag.covidcode.authcodegeneration.config.security.OAuth2SecuredWebConfiguration; import ch.admin.bag.covidcode.authcodegeneration.service.AuthCodeVerificationService; import ch.admin.bag.covidcode.authcodegeneration.testutil.LocalDateSerializer; import ch.admin.bag.covidcode.authcodegeneration.web.security.WebSecurityConfig; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import java.time.LocalDate; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; @WebMvcTest(value = {AuthCodeVerificationControllerV2.class, OAuth2SecuredWebConfiguration.class, WebSecurityConfig.class}) @ActiveProfiles("local") class AuthCodeVerificationControllerV2SecurityTest { private static final String URL = "/v2/onset"; private static final String TEST_AUTHORIZATION_CODE = "123456789"; private static final String FAKE = "0"; private static final String DUMMY_FOO = "foo"; private static final String DUMMY_BAR = "bar"; @Autowired private MockMvc mockMvc; @MockBean private AuthCodeVerificationService service; private static final ObjectMapper MAPPER = new ObjectMapper(); @BeforeAll static void setup() { SimpleModule module = new SimpleModule(); module.addSerializer(LocalDate.class, new LocalDateSerializer()); MAPPER.registerModule(module); } @Test void test_verify_authorization_without_token_is_permitted() throws Exception { AuthorizationCodeVerificationDto verificationDto = new AuthorizationCodeVerificationDto(TEST_AUTHORIZATION_CODE, FAKE); AuthorizationCodeVerifyResponseDto dp3tResponseDto = new AuthorizationCodeVerifyResponseDto(DUMMY_FOO); AuthorizationCodeVerifyResponseDto checkInResponseDto = new AuthorizationCodeVerifyResponseDto(DUMMY_BAR); final var expectedWrapper = new AuthorizationCodeVerifyResponseDtoWrapper(dp3tResponseDto, checkInResponseDto); when(service.verify(anyString(), anyString(), anyBoolean())).thenReturn(expectedWrapper); mockMvc.perform(post(URL) .accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(MAPPER.writeValueAsString(verificationDto))) .andExpect(status().isOk()); verify(service, times(1)).verify(anyString(), anyString(), anyBoolean()); } @Test void test_verify_authorization_without_token_is_permitted_return_404() throws Exception { AuthorizationCodeVerificationDto verificationDto = new AuthorizationCodeVerificationDto(TEST_AUTHORIZATION_CODE, FAKE); mockMvc.perform(post(URL) .accept(MediaType.APPLICATION_JSON_VALUE) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(MAPPER.writeValueAsString(verificationDto))) .andExpect(status().is(404)); verify(service, times(1)).verify(anyString(), anyString(), anyBoolean()); } }
3e134d7f65c0ce3f2c85ce690da79a6f2d030234
663
java
Java
src/integration-test/java/org/webtree/social/stackexchange/AbstractStackObjectFetcherIntegrationTest.java
Max-Levicky/spring-social-stackexchange
6e51cd1235fbffc48980b89424bbdb1589960dca
[ "MIT" ]
2
2018-10-04T19:01:12.000Z
2018-10-04T19:01:14.000Z
src/integration-test/java/org/webtree/social/stackexchange/AbstractStackObjectFetcherIntegrationTest.java
Max-Levicky/spring-social-stackexchange
6e51cd1235fbffc48980b89424bbdb1589960dca
[ "MIT" ]
3
2018-09-26T16:19:57.000Z
2019-04-25T05:53:43.000Z
src/integration-test/java/org/webtree/social/stackexchange/AbstractStackObjectFetcherIntegrationTest.java
Web-tree/spring-social-stackexchange
6e51cd1235fbffc48980b89424bbdb1589960dca
[ "MIT" ]
null
null
null
28.826087
71
0.75264
8,145
package org.webtree.social.stackexchange; import org.junit.jupiter.api.BeforeEach; import org.webtree.social.stackexchange.api.StackExchange; import org.webtree.social.stackexchange.api.impl.StackExchangeTemplate; /** * Created by Udjin Skobelev on 06.10.2018. */ public abstract class AbstractStackObjectFetcherIntegrationTest { static String TOKEN; static String APP_KEY; StackExchange stackExchange; @BeforeEach public void setUp() throws Exception { TOKEN = System.getenv("stackexchange_token"); APP_KEY = System.getenv("stackexchange_key"); stackExchange = new StackExchangeTemplate(TOKEN, APP_KEY); } }
3e134dd550c18b37c330ffebb8d40f8192a1f124
2,467
java
Java
wicket/src/main/java/org/apache/wicket/protocol/http/servlet/AbortWithWebErrorCodeException.java
astubbs/wicket.get-portals2
6ceca0773ab057880643ba2bd87eb18855e04082
[ "Apache-2.0" ]
2
2015-11-23T16:52:11.000Z
2016-05-08T14:37:42.000Z
wicket/src/main/java/org/apache/wicket/protocol/http/servlet/AbortWithWebErrorCodeException.java
astubbs/wicket.get-portals2
6ceca0773ab057880643ba2bd87eb18855e04082
[ "Apache-2.0" ]
null
null
null
wicket/src/main/java/org/apache/wicket/protocol/http/servlet/AbortWithWebErrorCodeException.java
astubbs/wicket.get-portals2
6ceca0773ab057880643ba2bd87eb18855e04082
[ "Apache-2.0" ]
null
null
null
30.45679
93
0.738143
8,146
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.protocol.http.servlet; import javax.servlet.http.HttpServletResponse; import org.apache.wicket.AbortException; import org.apache.wicket.AbstractRestartResponseException; import org.apache.wicket.RequestCycle; import org.apache.wicket.protocol.http.request.WebErrorCodeResponseTarget; /** * Causes Wicket to abort processing and set the specified HTTP error code, with the provided * message if provided. * * @author Eelco Hillenius * * @see AbortException * @see WebErrorCodeResponseTarget */ public final class AbortWithWebErrorCodeException extends AbstractRestartResponseException { private static final long serialVersionUID = 1L; private final int errorCode; /** * Construct. * * @param errorCode * the servlet error code; use one of the * {@link javax.servlet.http.HttpServletResponse} constants * @see javax.servlet.http.HttpServletResponse */ public AbortWithWebErrorCodeException(int errorCode) { this(errorCode, null); } /** * Construct. * * @param errorCode * the servlet error code; use one of the * {@link javax.servlet.http.HttpServletResponse} constants * @param message * the optional message to send to the client * @see javax.servlet.http.HttpServletResponse */ public AbortWithWebErrorCodeException(int errorCode, String message) { this.errorCode = errorCode; RequestCycle.get().setRequestTarget(new WebErrorCodeResponseTarget(errorCode, message)); } /** * Gets the error code. * * @return errorCode * @see HttpServletResponse */ public int getErrorCode() { return errorCode; } }
3e134e141bad286009c78f5f7ae44670ba240349
697
java
Java
ms-limiter-client/src/main/java/com/sailfish/limiter/Application.java
xiaxinyu/ms-limiter
1295f87d1959a0bcc2dc95987a7b1f4b2e87ea25
[ "Apache-2.0" ]
null
null
null
ms-limiter-client/src/main/java/com/sailfish/limiter/Application.java
xiaxinyu/ms-limiter
1295f87d1959a0bcc2dc95987a7b1f4b2e87ea25
[ "Apache-2.0" ]
null
null
null
ms-limiter-client/src/main/java/com/sailfish/limiter/Application.java
xiaxinyu/ms-limiter
1295f87d1959a0bcc2dc95987a7b1f4b2e87ea25
[ "Apache-2.0" ]
null
null
null
29.041667
72
0.807747
8,147
package com.sailfish.limiter; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import static org.springframework.web.bind.annotation.RequestMethod.GET; /** * @author XIAXINYU3 * @date 2020/10/27 */ @SpringBootApplication @RestController public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
3e134ecbe5ffe395f4728ca7715e80b87e9cc942
251
java
Java
src/Signal.java
g40st/Relaissteuerung-Raspberry-PI
6bffa372463c5493197bfae74e99a60cc4b6eaa7
[ "MIT" ]
null
null
null
src/Signal.java
g40st/Relaissteuerung-Raspberry-PI
6bffa372463c5493197bfae74e99a60cc4b6eaa7
[ "MIT" ]
null
null
null
src/Signal.java
g40st/Relaissteuerung-Raspberry-PI
6bffa372463c5493197bfae74e99a60cc4b6eaa7
[ "MIT" ]
null
null
null
16.733333
35
0.438247
8,148
class Signal { boolean green = true; public boolean getState() { return green; } public void changeState() { if(green) { green = false; } else { green = true; } } }
3e1350e9b2b83f1af7241eadf3590dbaf80455dc
903
java
Java
dbblog-backend/dbblog-portal/src/main/java/cn/dblearn/blog/portal/timeline/controller/TimelineController.java
awenaw/dbblog
7839b2b88825f181da5642b9ff73d630c86fd091
[ "Apache-2.0" ]
1,251
2018-10-08T06:43:37.000Z
2022-03-30T10:32:33.000Z
dbblog-backend/dbblog-portal/src/main/java/cn/dblearn/blog/portal/timeline/controller/TimelineController.java
awenaw/dbblog
7839b2b88825f181da5642b9ff73d630c86fd091
[ "Apache-2.0" ]
24
2019-04-20T13:47:18.000Z
2022-02-27T21:16:26.000Z
dbblog-backend/dbblog-portal/src/main/java/cn/dblearn/blog/portal/timeline/controller/TimelineController.java
awenaw/dbblog
7839b2b88825f181da5642b9ff73d630c86fd091
[ "Apache-2.0" ]
483
2019-04-07T14:29:48.000Z
2022-03-17T09:16:31.000Z
25.771429
69
0.764967
8,149
package cn.dblearn.blog.portal.timeline.controller; import cn.dblearn.blog.common.Result; import cn.dblearn.blog.entity.timeline.Timeline; import cn.dblearn.blog.portal.timeline.service.TimelineService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.List; /** * TimeLineController * * @author bobbi * @date 2019/02/24 20:46 * @email hzdkv@example.com * @description */ @RestController @RequestMapping("/timeline") public class TimelineController { @Resource private TimelineService timelineService; @GetMapping("") public Result listTimeline() { List<Timeline> timelineList = timelineService.listTimeLine(); return Result.ok().put("timelineList",timelineList); } }
3e1351087723975b079e0f59b4fdbd50b4eb37d0
873
java
Java
algorithms/search/SherlockAndArray.java
praveen-rgukt/Hackerrank-Solutions
5bb040de06dca0c16dba854923fdbd2b802c52ba
[ "MIT" ]
1
2019-09-10T18:19:12.000Z
2019-09-10T18:19:12.000Z
algorithms/search/SherlockAndArray.java
praveen-rgukt/Hackerrank-Solutions
5bb040de06dca0c16dba854923fdbd2b802c52ba
[ "MIT" ]
null
null
null
algorithms/search/SherlockAndArray.java
praveen-rgukt/Hackerrank-Solutions
5bb040de06dca0c16dba854923fdbd2b802c52ba
[ "MIT" ]
null
null
null
17.816327
90
0.549828
8,150
/** * * Problem Statement- * [Sherlock and Array](https://www.hackerrank.com/challenges/sherlock-and-array/problem) */ import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * @author nagasai praveen * */ public class SherlockAndArray { static String balancedSums(List<Integer> arr) { int x = 0; int sum = 0; for (int a : arr) { sum += a; } for (int y : arr) { if (2 * x == sum - y) { return "YES"; } x = x + y; } return "NO"; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while (T-- > 0) { int n = sc.nextInt(); List<Integer> list = new ArrayList(); for (int i = 0; i < n; i++) { list.add(sc.nextInt()); } System.out.println(balancedSums(list)); } sc.close(); } }
3e135248650d51e00699ea401933e5ef5dbcea8e
2,463
java
Java
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/core/org/gradle/logging/internal/logback/LogLevelConverter.java
bit-man/pushfish-android
5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc
[ "BSD-2-Clause" ]
158
2015-04-18T23:39:02.000Z
2021-07-01T18:28:29.000Z
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/core/org/gradle/logging/internal/logback/LogLevelConverter.java
bit-man/pushfish-android
5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc
[ "BSD-2-Clause" ]
31
2015-04-29T18:52:40.000Z
2020-06-29T19:25:24.000Z
gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/core/org/gradle/logging/internal/logback/LogLevelConverter.java
bit-man/pushfish-android
5f4fcf56adf5a8cdb6f31d91c315bcd3b3dc93bc
[ "BSD-2-Clause" ]
32
2016-01-05T21:58:24.000Z
2021-06-21T21:56:34.000Z
34.690141
132
0.601299
8,151
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.logging.internal.logback; import ch.qos.logback.classic.Level; import org.gradle.api.Nullable; import org.gradle.api.logging.LogLevel; import org.gradle.api.logging.Logging; import org.slf4j.Marker; public class LogLevelConverter { /** * Maps a Logback log level and optional marker to a Gradle log level. * Returns null if there is no equivalent Gradle log level (such as for TRACE). */ @Nullable public static LogLevel toGradleLogLevel(Level level, @Nullable Marker marker) { switch(level.toInt()) { case Level.TRACE_INT: return null; case Level.DEBUG_INT: return LogLevel.DEBUG; case Level.INFO_INT: if (marker == Logging.LIFECYCLE) { return LogLevel.LIFECYCLE; } if (marker == Logging.QUIET) { return LogLevel.QUIET; } return LogLevel.INFO; case Level.WARN_INT: return LogLevel.WARN; case Level.ERROR_INT: return LogLevel.ERROR; default: throw new IllegalArgumentException("Don't know how to map Logback log level '" + level + "' to a Gradle log level"); } } public static Level toLogbackLevel(LogLevel level) { switch (level) { case DEBUG: return Level.DEBUG; case INFO: case LIFECYCLE: case QUIET: return Level.INFO; case WARN: return Level.WARN; case ERROR: return Level.ERROR; default: throw new IllegalArgumentException("Don't know how to map Gradle log level '" + level + "' to a Logback log level"); } } }
3e135274852d9047e268d0b42bfcfe903f695a00
6,207
java
Java
server/src/internalClusterTest/java/org/elasticsearch/search/functionscore/FunctionScoreFieldValueIT.java
diwasjoshi/elasticsearch
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
[ "Apache-2.0" ]
null
null
null
server/src/internalClusterTest/java/org/elasticsearch/search/functionscore/FunctionScoreFieldValueIT.java
diwasjoshi/elasticsearch
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
[ "Apache-2.0" ]
null
null
null
server/src/internalClusterTest/java/org/elasticsearch/search/functionscore/FunctionScoreFieldValueIT.java
diwasjoshi/elasticsearch
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
[ "Apache-2.0" ]
null
null
null
43.711268
125
0.610923
8,152
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.search.functionscore; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction; import org.elasticsearch.test.ESIntegTestCase; import java.io.IOException; import static org.elasticsearch.index.query.QueryBuilders.functionScoreQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.simpleQueryStringQuery; import static org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders.fieldValueFactorFunction; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFailures; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertOrderedSearchHits; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; /** * Tests for the {@code field_value_factor} function in a function_score query. */ public class FunctionScoreFieldValueIT extends ESIntegTestCase { public void testFieldValueFactor() throws IOException { assertAcked( prepareCreate("test").setMapping( jsonBuilder().startObject() .startObject("_doc") .startObject("properties") .startObject("test") .field("type", randomFrom(new String[] { "short", "float", "long", "integer", "double" })) .endObject() .startObject("body") .field("type", "text") .endObject() .endObject() .endObject() .endObject() ).get() ); client().prepareIndex("test").setId("1").setSource("test", 5, "body", "foo").get(); client().prepareIndex("test").setId("2").setSource("test", 17, "body", "foo").get(); client().prepareIndex("test").setId("3").setSource("body", "bar").get(); refresh(); // document 2 scores higher because 17 > 5 SearchResponse response = client().prepareSearch("test") .setExplain(randomBoolean()) .setQuery(functionScoreQuery(simpleQueryStringQuery("foo"), fieldValueFactorFunction("test"))) .get(); assertOrderedSearchHits(response, "2", "1"); // try again, but this time explicitly use the do-nothing modifier response = client().prepareSearch("test") .setExplain(randomBoolean()) .setQuery( functionScoreQuery( simpleQueryStringQuery("foo"), fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.NONE) ) ) .get(); assertOrderedSearchHits(response, "2", "1"); // document 1 scores higher because 1/5 > 1/17 response = client().prepareSearch("test") .setExplain(randomBoolean()) .setQuery( functionScoreQuery( simpleQueryStringQuery("foo"), fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL) ) ) .get(); assertOrderedSearchHits(response, "1", "2"); // doc 3 doesn't have a "test" field, so an exception will be thrown try { response = client().prepareSearch("test") .setExplain(randomBoolean()) .setQuery(functionScoreQuery(matchAllQuery(), fieldValueFactorFunction("test"))) .get(); assertFailures(response); } catch (SearchPhaseExecutionException e) { // We are expecting an exception, because 3 has no field } // doc 3 doesn't have a "test" field but we're defaulting it to 100 so it should be last response = client().prepareSearch("test") .setExplain(randomBoolean()) .setQuery( functionScoreQuery( matchAllQuery(), fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).missing(100) ) ) .get(); assertOrderedSearchHits(response, "1", "2", "3"); // field is not mapped but we're defaulting it to 100 so all documents should have the same score response = client().prepareSearch("test") .setExplain(randomBoolean()) .setQuery( functionScoreQuery( matchAllQuery(), fieldValueFactorFunction("notmapped").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).missing(100) ) ) .get(); assertEquals(response.getHits().getAt(0).getScore(), response.getHits().getAt(2).getScore(), 0); client().prepareIndex("test").setId("2").setSource("test", -1, "body", "foo").get(); refresh(); // -1 divided by 0 is infinity, which should provoke an exception. try { response = client().prepareSearch("test") .setExplain(randomBoolean()) .setQuery( functionScoreQuery( simpleQueryStringQuery("foo"), fieldValueFactorFunction("test").modifier(FieldValueFactorFunction.Modifier.RECIPROCAL).factor(0) ) ) .get(); assertFailures(response); } catch (SearchPhaseExecutionException e) { // This is fine, the query will throw an exception if executed // locally, instead of just having failures } } }
3e1352f09cc5b9d4b5b321365ee572591c1dca0d
174
java
Java
pet-clinic-data/src/main/java/io/github/slawomirr/petclinicspring/services/PetService.java
SlawomirR/PetClinic--Spring
46ef92ee59fce6d030c68c3c24256aa2e84fb8a0
[ "MIT" ]
1
2018-08-18T14:12:10.000Z
2018-08-18T14:12:10.000Z
pet-clinic-data/src/main/java/io/github/slawomirr/petclinicspring/services/PetService.java
SlawomirR/PetClinic--Spring
46ef92ee59fce6d030c68c3c24256aa2e84fb8a0
[ "MIT" ]
44
2018-08-09T10:25:44.000Z
2018-08-17T08:55:56.000Z
pet-clinic-data/src/main/java/io/github/slawomirr/petclinicspring/services/PetService.java
SlawomirR/PetClinic--Spring
46ef92ee59fce6d030c68c3c24256aa2e84fb8a0
[ "MIT" ]
null
null
null
21.75
60
0.821839
8,153
package io.github.slawomirr.petclinicspring.services; import io.github.slawomirr.petclinicspring.model.Pet; public interface PetService extends CrudService<Pet, Long> { }
3e13530f9368c9fafeee5ba3f554404e92a7342d
869
java
Java
microservice-caelum-course/monolith/fj33-eats-monolito-modular/eats-restaurante/src/main/java/br/com/caelum/eats/restaurante/HorarioDeFuncionamento.java
jether2011/alura-classes
09ab8d39d948688a4e6962a59c5ddc3494806974
[ "MIT" ]
1
2022-01-14T23:18:54.000Z
2022-01-14T23:18:54.000Z
microservice-caelum-course/monolith/fj33-eats-monolito-modular/eats-restaurante/src/main/java/br/com/caelum/eats/restaurante/HorarioDeFuncionamento.java
jether2011/alura-classes
09ab8d39d948688a4e6962a59c5ddc3494806974
[ "MIT" ]
7
2021-03-09T13:16:54.000Z
2022-03-09T13:44:26.000Z
microservice-caelum-course/monolith/fj33-eats-monolito-modular/eats-restaurante/src/main/java/br/com/caelum/eats/restaurante/HorarioDeFuncionamento.java
jether2011/alura-classes
09ab8d39d948688a4e6962a59c5ddc3494806974
[ "MIT" ]
null
null
null
19.75
52
0.827388
8,154
package br.com.caelum.eats.restaurante; import java.time.DayOfWeek; import java.time.LocalTime; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Entity @NoArgsConstructor @AllArgsConstructor @Data class HorarioDeFuncionamento { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Enumerated(EnumType.STRING) private DayOfWeek diaDaSemana; @NotNull private LocalTime horarioDeAbertura; @NotNull private LocalTime horarioDeFechamento; @ManyToOne private Restaurante restaurante; }
3e1353be7ac52ecdbbb0a210a63a5912d39a8db2
160
java
Java
org.povworld.collection/src/org/povworld/collection/tree/ImmutableAvlTreeNode.java
iquadrat/collection
058db58dd225c3886c075d973e359ac99ca536b9
[ "MIT" ]
3
2018-11-07T13:53:51.000Z
2020-04-28T07:15:36.000Z
org.povworld.collection/src/org/povworld/collection/tree/ImmutableAvlTreeNode.java
iquadrat/collection
058db58dd225c3886c075d973e359ac99ca536b9
[ "MIT" ]
null
null
null
org.povworld.collection/src/org/povworld/collection/tree/ImmutableAvlTreeNode.java
iquadrat/collection
058db58dd225c3886c075d973e359ac99ca536b9
[ "MIT" ]
null
null
null
40
119
0.83125
8,155
package org.povworld.collection.tree; public interface ImmutableAvlTreeNode<N extends ImmutableAvlTreeNode<N>> extends ImmutableTreeNode<N>, AvlTreeNode<N> { }
3e1353dc44dbca93e2f035813d71e5facaff1765
863
java
Java
Lucene/src/com/hwh/utils/Atc2DocConv.java
andrewv587/j2ee
cfafe9cb9f61d2cbd2ceb6098bbd7ff670cf2014
[ "Apache-2.0" ]
null
null
null
Lucene/src/com/hwh/utils/Atc2DocConv.java
andrewv587/j2ee
cfafe9cb9f61d2cbd2ceb6098bbd7ff670cf2014
[ "Apache-2.0" ]
null
null
null
Lucene/src/com/hwh/utils/Atc2DocConv.java
andrewv587/j2ee
cfafe9cb9f61d2cbd2ceb6098bbd7ff670cf2014
[ "Apache-2.0" ]
null
null
null
28.766667
76
0.711472
8,156
package com.hwh.utils; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; import org.apache.lucene.document.TextField; import com.hwh.model.Article; public class Atc2DocConv { public static Document atc2Doc(Article article) { Document doc = new Document(); doc.add(new StringField("id", String.valueOf(article.getId()), Field.Store.YES)); doc.add(new StringField("name", article.getName(), Field.Store.YES)); doc.add(new TextField("context", article.getContext(), Field.Store.YES)); return doc; } public static Article doc2Atc(Document doc){ Article article = new Article(); article.setId(Integer.parseInt(doc.get("id"))); article.setName(doc.get("name")); article.setContext(doc.get("context")); return article; } }
3e13541fd31dcb38ca9c07dd4da6fa966941983c
2,440
java
Java
aliyun-java-sdk-dts-v5/src/main/java/com/aliyuncs/v5/dts/model/v20200101/StopMigrationJobRequest.java
aliyun/aliyun-openapi-java-sdk-v5
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
[ "Apache-2.0" ]
4
2020-05-14T05:04:30.000Z
2021-08-20T11:08:46.000Z
aliyun-java-sdk-dts-v5/src/main/java/com/aliyuncs/v5/dts/model/v20200101/StopMigrationJobRequest.java
aliyun/aliyun-openapi-java-sdk-v5
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
[ "Apache-2.0" ]
2
2020-10-13T07:47:10.000Z
2021-06-04T02:42:57.000Z
aliyun-java-sdk-dts-v5/src/main/java/com/aliyuncs/v5/dts/model/v20200101/StopMigrationJobRequest.java
aliyun/aliyun-openapi-java-sdk-v5
0ece7a0ba3730796e7a7ce4970a23865cd11b57c
[ "Apache-2.0" ]
null
null
null
25.957447
121
0.731148
8,157
/* * 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.aliyuncs.v5.dts.model.v20200101; import com.aliyuncs.v5.RpcAcsRequest; import com.aliyuncs.v5.http.MethodType; import com.aliyuncs.v5.dts.Endpoint; /** * @author auto create * @version */ public class StopMigrationJobRequest extends RpcAcsRequest<StopMigrationJobResponse> { private String clientToken; private String migrationJobId; private String ownerId; private String accountId; public StopMigrationJobRequest() { super("Dts", "2020-01-01", "StopMigrationJob", "dts"); setMethod(MethodType.POST); try { com.aliyuncs.v5.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.v5.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getClientToken() { return this.clientToken; } public void setClientToken(String clientToken) { this.clientToken = clientToken; if(clientToken != null){ putQueryParameter("ClientToken", clientToken); } } public String getMigrationJobId() { return this.migrationJobId; } public void setMigrationJobId(String migrationJobId) { this.migrationJobId = migrationJobId; if(migrationJobId != null){ putQueryParameter("MigrationJobId", migrationJobId); } } public String getOwnerId() { return this.ownerId; } public void setOwnerId(String ownerId) { this.ownerId = ownerId; if(ownerId != null){ putQueryParameter("OwnerId", ownerId); } } public String getAccountId() { return this.accountId; } public void setAccountId(String accountId) { this.accountId = accountId; if(accountId != null){ putQueryParameter("AccountId", accountId); } } @Override public Class<StopMigrationJobResponse> getResponseClass() { return StopMigrationJobResponse.class; } }
3e1354b1a3ec301bc1274acb2acee59eabb09155
2,150
java
Java
src/main/java/com/arzio/pixelexprates/RatesCommand.java
Arzio/PixelEXPRates
4191ee3fae4a940aaa12a10ee4c8b63bcfc333fc
[ "Unlicense" ]
3
2020-08-18T23:00:43.000Z
2021-09-04T09:31:09.000Z
src/main/java/com/arzio/pixelexprates/RatesCommand.java
Arzio/PixelEXPRates
4191ee3fae4a940aaa12a10ee4c8b63bcfc333fc
[ "Unlicense" ]
null
null
null
src/main/java/com/arzio/pixelexprates/RatesCommand.java
Arzio/PixelEXPRates
4191ee3fae4a940aaa12a10ee4c8b63bcfc333fc
[ "Unlicense" ]
1
2020-10-10T02:31:37.000Z
2020-10-10T02:31:37.000Z
37.719298
149
0.654419
8,158
package com.arzio.pixelexprates; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import com.google.inject.Inject; public class RatesCommand implements CommandExecutor { @Inject private PixelEXPRates plugin; @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { if (!(src instanceof Player)) { src.sendMessage(Text.of("Somente players podem usar este comando")); return CommandResult.empty(); } src.sendMessage(Text.builder("Ganho de EXP pelo nivel de seu Pokémon:").color(TextColors.GREEN).build()); plugin.getRates().stream().forEach(s -> src.sendMessage( Text.builder(" Nivel "+s.getMinLevel()+" a "+s.getMaxLevel()).color(TextColors.GRAY) .append(Text.builder(": ").color(TextColors.DARK_GRAY).build()) .append(Text.builder(String.format("%.1f", s.getExpMultiplier())+"x EXP em batalhas").color(TextColors.GOLD).build()) .build() ) ); return CommandResult.success(); } public static class ReloadSubcommand implements CommandExecutor { @Inject private PixelEXPRates plugin; @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { try { plugin.reloadConfig(); } catch (Exception e) { throw new CommandException(Text.of("Falha ao recarregar config"), e); } src.sendMessage(Text.builder("Configurações recarregadas!").color(TextColors.GREEN).build()); return CommandResult.success(); } } }
3e1355201aaaab618397f2f3e2d2702c090566f4
886
java
Java
support/cas-server-support-token-core/src/test/java/org/apereo/cas/token/cipher/TokenTicketCipherExecutorTests.java
yauheni-sidarenka/apereo-cas
0cb298645b92777e1dcceffb27b0c388123cc29a
[ "Apache-2.0" ]
3
2018-10-10T09:05:29.000Z
2021-02-23T02:29:49.000Z
support/cas-server-support-token-core/src/test/java/org/apereo/cas/token/cipher/TokenTicketCipherExecutorTests.java
yauheni-sidarenka/apereo-cas
0cb298645b92777e1dcceffb27b0c388123cc29a
[ "Apache-2.0" ]
null
null
null
support/cas-server-support-token-core/src/test/java/org/apereo/cas/token/cipher/TokenTicketCipherExecutorTests.java
yauheni-sidarenka/apereo-cas
0cb298645b92777e1dcceffb27b0c388123cc29a
[ "Apache-2.0" ]
null
null
null
30.121212
113
0.71328
8,159
package org.apereo.cas.token.cipher; import org.junit.Test; import static org.junit.Assert.*; /** * This is {@link TokenTicketCipherExecutorTests}. * * @author Misagh Moayyed * @since 5.2.0 */ public class TokenTicketCipherExecutorTests { public static final String ST = "ST-1234567890"; @Test public void verifyCipheredToken() { final TokenTicketCipherExecutor c = new TokenTicketCipherExecutor(null, "caf86f4uutaoxfysmf7anj01xl6sv3ps", true); final String token = c.encode(ST); assertEquals(ST, c.decode(token)); } @Test public void verifyCipheredTokenWithoutEncryption() { final TokenTicketCipherExecutor c = new TokenTicketCipherExecutor(null, "caf86f4uutaoxfysmf7anj01xl6sv3ps", false); final String token = c.encode(ST); assertEquals(ST, c.decode(token)); } }
3e1355a8d8c1245219bbd52b433e8524dea8f8bf
2,328
java
Java
src/main/java/me/rosskelso/utilities_remastered/enchantment/SmeltingEnchantment.java
RossRKK/Utilities-Remastered
3467004312b1a8d882daf91a4fd3c0a6eef143ec
[ "MIT" ]
null
null
null
src/main/java/me/rosskelso/utilities_remastered/enchantment/SmeltingEnchantment.java
RossRKK/Utilities-Remastered
3467004312b1a8d882daf91a4fd3c0a6eef143ec
[ "MIT" ]
null
null
null
src/main/java/me/rosskelso/utilities_remastered/enchantment/SmeltingEnchantment.java
RossRKK/Utilities-Remastered
3467004312b1a8d882daf91a4fd3c0a6eef143ec
[ "MIT" ]
null
null
null
36.375
131
0.766753
8,160
package me.rosskelso.utilities_remastered.enchantment; import java.util.ArrayList; import java.util.List; import java.util.Optional; import me.rosskelso.utilities_remastered.UtilitiesRemasteredMod; import net.minecraft.block.BlockState; import net.minecraft.block.entity.BlockEntity; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentTarget; import net.minecraft.enchantment.Enchantments; import net.minecraft.entity.Entity; import net.minecraft.entity.EquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.recipe.Recipe; import net.minecraft.recipe.RecipeType; import net.minecraft.server.world.ServerWorld; import net.minecraft.util.math.BlockPos; /** * An enchantment that replaces block drops with the smelted version of themselves. * @author rossrkk * */ public class SmeltingEnchantment extends DropReplaceEnchantment { //TODO configure rarity and level public SmeltingEnchantment(Weight enchantment$Weight_1, EnchantmentTarget enchantmentTarget_1, EquipmentSlot[] equipmentSlots_1, int priority) { super(enchantment$Weight_1, enchantmentTarget_1, equipmentSlots_1, priority); } @Override public List<ItemStack> replaceDrops(BlockState blockState, ServerWorld world, BlockPos blockPos, BlockEntity blockEntity, Entity entity, List<ItemStack> normalDrops, int level) { List<ItemStack> list = new ArrayList<ItemStack>(); for (ItemStack drop:normalDrops) { //lookup the result of smelting the current item Optional<Recipe<?>> recipe = world.getRecipeManager().values().parallelStream().filter((recipe_1) -> { return recipe_1.getType() == RecipeType.SMELTING && recipe_1.getPreviewInputs().parallelStream().anyMatch((i) -> i.test(drop)); }).findFirst(); if (recipe.isPresent()) { list.add(recipe.get().getOutput()); } } //let's not punish the player too much, drop the item if the list is empty if (!list.isEmpty()) { return list; } else { return normalDrops; } } //should not be allowed with silk touch, fortune or void, should chain with pulverize (i.e. stone becomes glass) @Override public boolean differs(Enchantment enchantment) { return super.differs(enchantment) && enchantment != Enchantments.SILK_TOUCH && enchantment != UtilitiesRemasteredMod.VOID; } }
3e13564c2068cc369b714b2ef8cee53d5dce7b9f
894
java
Java
src/main/java/edu/cmu/team029/termproj/Review.java
automotua/645-project
c2c4176a619514d3dfb7bb63f2b73b753ba989be
[ "MIT" ]
null
null
null
src/main/java/edu/cmu/team029/termproj/Review.java
automotua/645-project
c2c4176a619514d3dfb7bb63f2b73b753ba989be
[ "MIT" ]
null
null
null
src/main/java/edu/cmu/team029/termproj/Review.java
automotua/645-project
c2c4176a619514d3dfb7bb63f2b73b753ba989be
[ "MIT" ]
null
null
null
16.254545
101
0.659955
8,161
package edu.cmu.team029.termproj; /** * Created by auta on 24/4/16. */ public class Review { public Review() { } private int stars; private String date; private String content; private String userName; public void setContent(String content) { this.content = content; } public String getContent() { return content; } public void setDate(String date) { this.date = date; } public String getDate() { return date; } public void setStars(int stars) { this.stars = stars; } public int getStars() { return stars; } public void setUserName(String userName) { this.userName = userName; } public String getUserName() { return userName; } @Override public String toString() { String retStr = "User name: " + this.userName + "\nDate: " + this.date + "\nStars: " + this.stars + "\nContent: " + this.content; retStr += "\n"; return retStr; } }
3e13568a7659304681bbd8110c3a93f7cbe4f2cc
821
java
Java
BM_src/WayofTime/alchemicalWizardry/common/spell/complex/effect/impactEffects/wind/SelfDefaultWind.java
Vexatos/BloodMagic
30e18429eca8f64609c81b63d5690ec80bcddcad
[ "CC-BY-4.0" ]
null
null
null
BM_src/WayofTime/alchemicalWizardry/common/spell/complex/effect/impactEffects/wind/SelfDefaultWind.java
Vexatos/BloodMagic
30e18429eca8f64609c81b63d5690ec80bcddcad
[ "CC-BY-4.0" ]
null
null
null
BM_src/WayofTime/alchemicalWizardry/common/spell/complex/effect/impactEffects/wind/SelfDefaultWind.java
Vexatos/BloodMagic
30e18429eca8f64609c81b63d5690ec80bcddcad
[ "CC-BY-4.0" ]
null
null
null
29.321429
94
0.82095
8,162
package WayofTime.alchemicalWizardry.common.spell.complex.effect.impactEffects.wind; import java.util.List; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; import WayofTime.alchemicalWizardry.AlchemicalWizardry; import WayofTime.alchemicalWizardry.common.spell.complex.effect.SpellHelper; import WayofTime.alchemicalWizardry.common.spell.complex.effect.impactEffects.SelfSpellEffect; public class SelfDefaultWind extends SelfSpellEffect { public SelfDefaultWind(int power, int potency, int cost) { super(power, potency, cost); } @Override public void onSelfUse(World world, EntityPlayer player) { player.extinguish(); player.fallDistance = 0; } }
3e13570978d8b13e5b0a3b0f04939f057b746438
4,892
java
Java
cdap-data-fabric/src/main/java/co/cask/cdap/data/stream/StreamDataFileSplitter.java
pa-mahe/cdap
17e80b38a17215bced088d7c1c7ee58386d0ae59
[ "Apache-2.0" ]
3
2018-03-22T23:25:54.000Z
2018-03-22T23:36:44.000Z
cdap-data-fabric/src/main/java/co/cask/cdap/data/stream/StreamDataFileSplitter.java
pa-mahe/cdap
17e80b38a17215bced088d7c1c7ee58386d0ae59
[ "Apache-2.0" ]
21
2018-10-31T10:19:47.000Z
2020-02-06T12:06:05.000Z
cdap-data-fabric/src/main/java/co/cask/cdap/data/stream/StreamDataFileSplitter.java
pa-mahe/cdap
17e80b38a17215bced088d7c1c7ee58386d0ae59
[ "Apache-2.0" ]
5
2019-09-04T19:09:50.000Z
2020-04-22T16:06:50.000Z
37.630769
113
0.697465
8,163
/* * Copyright © 2014 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.data.stream; import org.apache.hadoop.fs.BlockLocation; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.InputSplit; import java.io.IOException; import java.net.URI; import java.util.List; /** * Helper class for computing {@link InputSplit} for a stream data file. * * It splits a stream event file into equal size blocks (except the last block). The split size is computed by * * <br/><br/> * {@code Math.min(minSplitSize, Math.max(maxSplitSize, fileBlockSize)) } * <br/><br/> * * Each split produced will also carries {@code startTime} and {@code endTime} so that only stream events within * the given time range will get processed. */ final class StreamDataFileSplitter { private final FileStatus eventFileStatus; StreamDataFileSplitter(FileStatus eventFileStatus) { this.eventFileStatus = eventFileStatus; } /** * Computes splits for the event file. */ <T> void computeSplits(FileSystem fs, long minSplitSize, long maxSplitSize, long startTime, long endTime, List<T> splits, StreamInputSplitFactory<T> splitFactory) throws IOException { // Compute the splits based on the min/max size Path eventFile = eventFileStatus.getPath(); Path indexFile = getIndexFile(eventFile); BlockLocation[] blockLocations = fs.getFileBlockLocations(eventFile, 0, eventFileStatus.getLen()); long length = eventFileStatus.getLen(); long offset = 0; int blockIndex = 0; while (offset < length) { blockIndex = getBlockIndex(blockLocations, offset, blockIndex); String[] hosts = null; if (blockIndex >= 0) { hosts = blockLocations[blockIndex].getHosts(); } else { blockIndex = 0; } long splitSize = computeSplitSize(eventFileStatus, offset, minSplitSize, maxSplitSize); splits.add(splitFactory.createSplit(eventFile, indexFile, startTime, endTime, offset, splitSize, hosts)); offset += splitSize; } // One extra split for the tail of the file. splits.add(splitFactory.createSplit(eventFile, indexFile, startTime, endTime, offset, Long.MAX_VALUE, null)); } /** * Returns the array index of the given blockLocations that contains the given offset. * * @param blockLocations Array of {@link BlockLocation} to search for. * @param offset File offset. * @param startIdx Starting index for the search in the array. * @return The array index of the {@link BlockLocation} that contains the given offset. */ private int getBlockIndex(BlockLocation[] blockLocations, long offset, int startIdx) { if (blockLocations == null) { return -1; } for (int i = startIdx; i < blockLocations.length; i++) { BlockLocation blockLocation = blockLocations[i]; long endOffset = blockLocation.getOffset() + blockLocation.getLength(); if (blockLocation.getOffset() <= offset && offset < endOffset) { return i; } } return -1; } /** * Compute the actual split size. The split size compute would be no larger than the given max split size. * The split size would be no smaller than the given min split size, except if number of bytes between * offset and file length is smaller than min split size. * * @param fileStatus The FileStatus of the file to split on. * @param offset Starting offset for the split. * @param minSplitSize Minimum size for the split. * @param maxSplitSize Maximum size for the split. * @return */ private long computeSplitSize(FileStatus fileStatus, long offset, long minSplitSize, long maxSplitSize) { long blockSize = fileStatus.getBlockSize(); long splitSize = Math.max(minSplitSize, Math.min(maxSplitSize, blockSize)); return Math.min(splitSize, fileStatus.getLen() - offset); } private Path getIndexFile(Path eventFile) { String eventPath = eventFile.toUri().toString(); int extLength = StreamFileType.EVENT.getSuffix().length(); return new Path(URI.create(String.format("%s%s", eventPath.substring(0, eventPath.length() - extLength), StreamFileType.INDEX.getSuffix()))); } }
3e13578054f8ad4c1630513c9965bbc31f43fd74
3,270
java
Java
src/main/java/ai/arcblroth/projectInception/client/taterwebz/TaterwebzControlScreen.java
Motschen/ProjectInception
5cc4313da52bb3e55c5f3347c2fcdc9bbb155b97
[ "MIT" ]
13
2020-08-17T10:01:29.000Z
2022-02-11T16:06:44.000Z
src/main/java/ai/arcblroth/projectInception/client/taterwebz/TaterwebzControlScreen.java
Motschen/ProjectInception
5cc4313da52bb3e55c5f3347c2fcdc9bbb155b97
[ "MIT" ]
9
2020-09-29T13:17:19.000Z
2021-05-31T02:16:44.000Z
src/main/java/ai/arcblroth/projectInception/client/taterwebz/TaterwebzControlScreen.java
Motschen/ProjectInception
5cc4313da52bb3e55c5f3347c2fcdc9bbb155b97
[ "MIT" ]
1
2021-02-21T07:58:57.000Z
2021-02-21T07:58:57.000Z
39.878049
175
0.649847
8,164
package ai.arcblroth.projectInception.client.taterwebz; import ai.arcblroth.projectInception.block.TaterwebzBlockEntity; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.gui.widget.TextFieldWidget; import net.minecraft.client.util.NarratorManager; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.text.LiteralText; import net.minecraft.text.TranslatableText; import static org.lwjgl.glfw.GLFW.GLFW_KEY_ENTER; import static org.lwjgl.glfw.GLFW.GLFW_KEY_KP_ENTER; public class TaterwebzControlScreen extends Screen { private final TaterwebzBlockEntity blockEntity; private ButtonWidget backButton, forwardButton, reloadButton, goButton; private TextFieldWidget urlField; public TaterwebzControlScreen(TaterwebzBlockEntity blockEntity) { super(NarratorManager.EMPTY); this.blockEntity = blockEntity; } @Override public void init() { client.keyboard.setRepeatEvents(true); backButton = addButton(new ButtonWidget(this.width / 6 - 10, this.height / 2 - 10, 20, 20, new LiteralText("←"), (buttonWidget) -> { blockEntity.getGameInstance().goBack(); this.onClose(); })); forwardButton = addButton(new ButtonWidget(this.width / 6 + 11, this.height / 2 - 10, 20, 20, new LiteralText("→"), (buttonWidget) -> { blockEntity.getGameInstance().goForward(); this.onClose(); })); reloadButton = addButton(new ButtonWidget(this.width / 6 + 32, this.height / 2 - 10, 20, 20, new LiteralText("⟳"), (buttonWidget) -> { blockEntity.getGameInstance().reload(); this.onClose(); })); goButton = addButton(new ButtonWidget(this.width * 5 / 6 + 10, this.height / 2 - 10, 20, 20, new TranslatableText("gui.project_inception.go"), (buttonWidget) -> { gotoUrl(urlField.getText()); })); urlField = new TextFieldWidget(this.textRenderer, this.width / 6 + 55, this.height / 2 - 10, this.width * 2 / 3 - 48, 20, NarratorManager.EMPTY); urlField.setMaxLength(16000); urlField.setEditable(true); urlField.setText(blockEntity.getGameInstance().getCurrentURL()); this.children.add(urlField); } @Override public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) { this.renderBackground(matrices); super.render(matrices, mouseX, mouseY, delta); this.urlField.render(matrices, mouseX, mouseY, delta); } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { if (super.keyPressed(keyCode, scanCode, modifiers)) { return true; } else if (keyCode != GLFW_KEY_ENTER && keyCode != GLFW_KEY_KP_ENTER) { return false; } else { if(!this.urlField.getText().isEmpty()) { this.gotoUrl(this.urlField.getText()); return true; } else { return false; } } } private void gotoUrl(String url) { if(!url.isEmpty()) { blockEntity.getGameInstance().gotoUrl(url); this.onClose(); } } }
3e13579bc33c4ddf674f8ffc5b5009ba662bf9d4
743
java
Java
android/src/main/java/com/flutter_webview_plugin/jsapi/JsApiModuleEx.java
whitekyo/pa_webview_plugin
bf43961ceff6dec817d1db02fb10ae9fcb25a1ed
[ "BSD-3-Clause" ]
4
2019-01-16T09:41:28.000Z
2019-09-21T13:14:09.000Z
android/src/main/java/com/flutter_webview_plugin/jsapi/JsApiModuleEx.java
whitekyo/pa_webview_plugin
bf43961ceff6dec817d1db02fb10ae9fcb25a1ed
[ "BSD-3-Clause" ]
null
null
null
android/src/main/java/com/flutter_webview_plugin/jsapi/JsApiModuleEx.java
whitekyo/pa_webview_plugin
bf43961ceff6dec817d1db02fb10ae9fcb25a1ed
[ "BSD-3-Clause" ]
null
null
null
21.228571
70
0.701211
8,165
package com.flutter_webview_plugin.jsapi; import android.widget.ProgressBar; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * created by jyk on 2019/1/10. */ public class JsApiModuleEx { private static final JsApiModuleEx INSTANCE = new JsApiModuleEx(); private List<String> modules = new ArrayList<>(); private JsApiModuleEx() { } public static JsApiModuleEx getInstance() { return INSTANCE; } public List<String> getModules(){ return modules; } public void addJsApiModule(String iJsApiModule) { modules.remove(iJsApiModule); modules.add(iJsApiModule); } }
3e1357c4ead6f041179b6282fe6fb3901c2492b4
10,927
java
Java
thrift/compiler/test/fixtures/basic-annotations/gen-android/MyServicePrioChild.java
killight98/fbthrift
c28d5036f96f7eab67c30abadc5ddbe627a11ee3
[ "Apache-2.0" ]
2,112
2015-01-02T11:34:27.000Z
2022-03-31T16:30:42.000Z
thrift/compiler/test/fixtures/basic-annotations/gen-android/MyServicePrioChild.java
killight98/fbthrift
c28d5036f96f7eab67c30abadc5ddbe627a11ee3
[ "Apache-2.0" ]
372
2015-01-05T10:40:09.000Z
2022-03-31T20:45:11.000Z
thrift/compiler/test/fixtures/basic-annotations/gen-android/MyServicePrioChild.java
killight98/fbthrift
c28d5036f96f7eab67c30abadc5ddbe627a11ee3
[ "Apache-2.0" ]
582
2015-01-03T01:51:56.000Z
2022-03-31T02:01:09.000Z
29.216578
173
0.667338
8,166
/** * Autogenerated by Thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.Collections; import java.util.BitSet; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.facebook.thrift.*; import com.facebook.thrift.annotations.*; import com.facebook.thrift.async.*; import com.facebook.thrift.meta_data.*; import com.facebook.thrift.server.*; import com.facebook.thrift.transport.*; import com.facebook.thrift.protocol.*; @SuppressWarnings({ "unused", "serial" }) public class MyServicePrioChild { public interface Iface extends MyServicePrioParent.Iface { public void pang() throws TException; } public interface AsyncIface extends MyServicePrioParent.AsyncIface { public void pang(AsyncMethodCallback resultHandler) throws TException; } public static class Client extends MyServicePrioParent.Client implements Iface, TClientIf { public Client(TProtocol prot) { this(prot, prot); } public Client(TProtocol iprot, TProtocol oprot) { super(iprot, oprot); } public void pang() throws TException { ContextStack ctx = getContextStack("MyServicePrioChild.pang", null); this.setContextStack(ctx); send_pang(); recv_pang(); } public void send_pang() throws TException { ContextStack ctx = this.getContextStack(); super.preWrite(ctx, "MyServicePrioChild.pang", null); oprot_.writeMessageBegin(new TMessage("pang", TMessageType.CALL, seqid_)); pang_args args = new pang_args(); args.write(oprot_); oprot_.writeMessageEnd(); oprot_.getTransport().flush(); super.postWrite(ctx, "MyServicePrioChild.pang", args); return; } public void recv_pang() throws TException { ContextStack ctx = super.getContextStack(); long bytes; TMessageType mtype; super.preRead(ctx, "MyServicePrioChild.pang"); TMessage msg = iprot_.readMessageBegin(); if (msg.type == TMessageType.EXCEPTION) { TApplicationException x = TApplicationException.read(iprot_); iprot_.readMessageEnd(); throw x; } pang_result result = pang_result.deserialize(iprot_); iprot_.readMessageEnd(); super.postRead(ctx, "MyServicePrioChild.pang", result); return; } } public static class AsyncClient extends MyServicePrioParent.AsyncClient implements AsyncIface { public static class Factory implements TAsyncClientFactory<AsyncClient> { private TAsyncClientManager clientManager; private TProtocolFactory protocolFactory; public Factory(TAsyncClientManager clientManager, TProtocolFactory protocolFactory) { this.clientManager = clientManager; this.protocolFactory = protocolFactory; } public AsyncClient getAsyncClient(TNonblockingTransport transport) { return new AsyncClient(protocolFactory, clientManager, transport); } } public AsyncClient(TProtocolFactory protocolFactory, TAsyncClientManager clientManager, TNonblockingTransport transport) { super(protocolFactory, clientManager, transport); } public void pang(AsyncMethodCallback resultHandler58) throws TException { checkReady(); pang_call method_call = new pang_call(resultHandler58, this, ___protocolFactory, ___transport); this.___currentMethod = method_call; ___manager.call(method_call); } public static class pang_call extends TAsyncMethodCall { public pang_call(AsyncMethodCallback resultHandler59, TAsyncClient client55, TProtocolFactory protocolFactory56, TNonblockingTransport transport57) throws TException { super(client55, protocolFactory56, transport57, resultHandler59, false); } public void write_args(TProtocol prot) throws TException { prot.writeMessageBegin(new TMessage("pang", TMessageType.CALL, 0)); pang_args args = new pang_args(); args.write(prot); prot.writeMessageEnd(); } public void getResult() throws TException { if (getState() != State.RESPONSE_READ) { throw new IllegalStateException("Method call not finished!"); } TMemoryInputTransport memoryTransport = new TMemoryInputTransport(getFrameBuffer().array()); TProtocol prot = super.client.getProtocolFactory().getProtocol(memoryTransport); (new Client(prot)).recv_pang(); } } } public static class Processor extends MyServicePrioParent.Processor implements TProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName()); public Processor(Iface iface) { super(iface); iface_ = iface; processMap_.put("pang", new pang()); } private Iface iface_; public boolean process(TProtocol iprot, TProtocol oprot, TConnectionContext server_ctx) throws TException { TMessage msg = iprot.readMessageBegin(); ProcessFunction fn = processMap_.get(msg.name); if (fn == null) { TProtocolUtil.skip(iprot, TType.STRUCT); iprot.readMessageEnd(); TApplicationException x = new TApplicationException(TApplicationException.UNKNOWN_METHOD, "Invalid method name: '"+msg.name+"'"); oprot.writeMessageBegin(new TMessage(msg.name, TMessageType.EXCEPTION, msg.seqid)); x.write(oprot); oprot.writeMessageEnd(); oprot.getTransport().flush(); return true; } fn.process(msg.seqid, iprot, oprot, server_ctx); return true; } private class pang implements ProcessFunction { public void process(int seqid, TProtocol iprot, TProtocol oprot, TConnectionContext server_ctx) throws TException { Object handler_ctx = event_handler_.getContext("MyServicePrioChild.pang", server_ctx); pang_args args = new pang_args(); event_handler_.preRead(handler_ctx, "MyServicePrioChild.pang"); args.read(iprot); iprot.readMessageEnd(); event_handler_.postRead(handler_ctx, "MyServicePrioChild.pang", args); pang_result result = new pang_result(); iface_.pang(); event_handler_.preWrite(handler_ctx, "MyServicePrioChild.pang", result); oprot.writeMessageBegin(new TMessage("pang", TMessageType.REPLY, seqid)); result.write(oprot); oprot.writeMessageEnd(); oprot.getTransport().flush(); event_handler_.postWrite(handler_ctx, "MyServicePrioChild.pang", result); } } } public static class pang_args implements TBase, java.io.Serializable, Cloneable { private static final TStruct STRUCT_DESC = new TStruct("pang_args"); public pang_args() { } /** * Performs a deep copy on <i>other</i>. */ public pang_args(pang_args other) { } public pang_args deepCopy() { return new pang_args(this); } @Override public boolean equals(Object _that) { if (_that == null) return false; if (this == _that) return true; if (!(_that instanceof pang_args)) return false; pang_args that = (pang_args)_that; return true; } @Override public int hashCode() { return Arrays.deepHashCode(new Object[] {}); } // This is required to satisfy the TBase interface, but can't be implemented on immutable struture. public void read(TProtocol iprot) throws TException { throw new TException("unimplemented in android immutable structure"); } public static pang_args deserialize(TProtocol iprot) throws TException { TField __field; iprot.readStructBegin(); while (true) { __field = iprot.readFieldBegin(); if (__field.type == TType.STOP) { break; } switch (__field.id) { default: TProtocolUtil.skip(iprot, __field.type); break; } iprot.readFieldEnd(); } iprot.readStructEnd(); pang_args _that; _that = new pang_args( ); _that.validate(); return _that; } public void write(TProtocol oprot) throws TException { validate(); oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } @Override public String toString() { return toString(1, true); } @Override public String toString(int indent, boolean prettyPrint) { return TBaseHelper.toStringHelper(this, indent, prettyPrint); } public void validate() throws TException { // check for required fields } } public static class pang_result implements TBase, java.io.Serializable, Cloneable { private static final TStruct STRUCT_DESC = new TStruct("pang_result"); public pang_result() { } /** * Performs a deep copy on <i>other</i>. */ public pang_result(pang_result other) { } public pang_result deepCopy() { return new pang_result(this); } @Override public boolean equals(Object _that) { if (_that == null) return false; if (this == _that) return true; if (!(_that instanceof pang_result)) return false; pang_result that = (pang_result)_that; return true; } @Override public int hashCode() { return Arrays.deepHashCode(new Object[] {}); } // This is required to satisfy the TBase interface, but can't be implemented on immutable struture. public void read(TProtocol iprot) throws TException { throw new TException("unimplemented in android immutable structure"); } public static pang_result deserialize(TProtocol iprot) throws TException { TField __field; iprot.readStructBegin(); while (true) { __field = iprot.readFieldBegin(); if (__field.type == TType.STOP) { break; } switch (__field.id) { default: TProtocolUtil.skip(iprot, __field.type); break; } iprot.readFieldEnd(); } iprot.readStructEnd(); pang_result _that; _that = new pang_result( ); _that.validate(); return _that; } public void write(TProtocol oprot) throws TException { oprot.writeStructBegin(STRUCT_DESC); oprot.writeFieldStop(); oprot.writeStructEnd(); } @Override public String toString() { return toString(1, true); } @Override public String toString(int indent, boolean prettyPrint) { return TBaseHelper.toStringHelper(this, indent, prettyPrint); } public void validate() throws TException { // check for required fields } } }
3e135869e5963988438d041b78d8ddf3d5a4f17a
15,924
java
Java
core/src/com/dokkaebistudio/tacticaljourney/rendering/MapRenderer.java
Callilf/tactical-journey
c4025f6401b5254eccad0e23dc63fbebc745cc2a
[ "Apache-2.0" ]
2
2018-08-18T10:51:59.000Z
2019-03-13T14:18:17.000Z
core/src/com/dokkaebistudio/tacticaljourney/rendering/MapRenderer.java
Callilf/tactical-journey
c4025f6401b5254eccad0e23dc63fbebc745cc2a
[ "Apache-2.0" ]
43
2019-01-01T09:44:10.000Z
2019-07-03T08:21:17.000Z
core/src/com/dokkaebistudio/tacticaljourney/rendering/MapRenderer.java
Callilf/tactical-journey
c4025f6401b5254eccad0e23dc63fbebc745cc2a
[ "Apache-2.0" ]
null
null
null
30.216319
200
0.683371
8,167
/** * */ package com.dokkaebistudio.tacticaljourney.rendering; import java.util.Map.Entry; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Cell; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.SnapshotArray; import com.dokkaebistudio.tacticaljourney.Assets; import com.dokkaebistudio.tacticaljourney.assets.SceneAssets; import com.dokkaebistudio.tacticaljourney.gamescreen.GameScreen; import com.dokkaebistudio.tacticaljourney.rendering.interfaces.Renderer; import com.dokkaebistudio.tacticaljourney.rendering.service.PopinService; import com.dokkaebistudio.tacticaljourney.room.Floor; import com.dokkaebistudio.tacticaljourney.room.Room; /** * This class allows rendering the map of the current floor. * @author Callil * */ public class MapRenderer implements Renderer { float offsetX = GameScreen.SCREEN_W - GameScreen.SCREEN_W/8; float offsetY = GameScreen.SCREEN_H - GameScreen.SCREEN_H/5; // TEST to debug floor layout public static boolean FULL_MAP = false; private Stage stage; /** Whether the map is displayed on screen or not. */ private boolean mapDisplayed; /** The floor to render. */ private Floor floor; /** The button to open the map. */ private TextButton noMapBtn; private TextButton smallMapBtn; private TextButton fullMapBtn; /** The main table. */ private ScrollPane scrollPane; private Table roomsTable; /** The background of the map. */ private Image smallBackground; private Image fullBackground; private Image player; private static boolean needRefresh; //*************************** // Current floor attributes private Integer minX; private Integer maxX; private Integer minY; private Integer maxY; private int xRange; private int yRange; /** * Instanciate a Map Renderer. * @param sr the shaperenderer * @param f the floor which map we want to render */ public MapRenderer(Stage s, Floor f) { this.stage = s; this.mapDisplayed = true; smallBackground = new Image(Assets.map_background.getRegion()); smallBackground.setPosition(GameScreen.SCREEN_W - Assets.map_background.getRegionWidth() - 5, GameScreen.SCREEN_H - Assets.map_background.getRegionHeight() - Assets.map_panel.getRegionHeight() - 5); smallBackground.addAction(Actions.alpha(0.5f)); stage.addActor(smallBackground); fullBackground = new Image(Assets.menuBackground.getRegion()); fullBackground.setPosition(0, 0); fullBackground.addAction(Actions.alpha(0.5f)); Table mapTable = new Table(); mapTable.setPosition(GameScreen.SCREEN_W - Assets.map_panel.getRegionWidth() - 5, GameScreen.SCREEN_H - Assets.map_panel.getRegionHeight() - 5); mapTable.setTouchable(Touchable.childrenOnly); NinePatchDrawable ninePatchDrawable = new NinePatchDrawable(SceneAssets.popinNinePatch); ninePatchDrawable.setMinWidth(444); ninePatchDrawable.setMinHeight(68); mapTable.setBackground(ninePatchDrawable); noMapBtn = new TextButton("None", PopinService.checkedButtonStyle()); smallMapBtn = new TextButton("Small", PopinService.checkedButtonStyle()); fullMapBtn = new TextButton("Full", PopinService.checkedButtonStyle()); noMapBtn.setProgrammaticChangeEvents(false); noMapBtn.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { if (noMapBtn.isChecked()) { mapDisplayed = false; smallBackground.remove(); fullBackground.remove(); scrollPane.remove(); smallMapBtn.setChecked(false); fullMapBtn.setChecked(false); } else { noMapBtn.setChecked(true); } } }); smallMapBtn.setProgrammaticChangeEvents(false); smallMapBtn.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { if (smallMapBtn.isChecked()) { mapDisplayed = true; if (mapDisplayed) { fullBackground.remove(); stage.addActor(smallBackground); smallBackground.toBack(); if (!scrollPane.hasParent()) { stage.addActor(scrollPane); } scrollPane.setBounds(smallBackground.getX() + 5, smallBackground.getY() + 5, Assets.map_background.getRegionWidth() - 10, Assets.map_background.getRegionHeight() - 10); scrollToCurrentRoom(); noMapBtn.setChecked(false); fullMapBtn.setChecked(false); } } else { smallMapBtn.setChecked(true); } } }); smallMapBtn.setChecked(true); fullMapBtn.setProgrammaticChangeEvents(false); fullMapBtn.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { if (fullMapBtn.isChecked()) { mapDisplayed = true; if (mapDisplayed) { smallBackground.remove(); stage.addActor(fullBackground); fullBackground.toBack(); if (!scrollPane.hasParent()) { stage.addActor(scrollPane); } scrollPane.setBounds(0, 0, GameScreen.SCREEN_W, GameScreen.SCREEN_H); scrollToCurrentRoom(); noMapBtn.setChecked(false); smallMapBtn.setChecked(false); } } else { fullMapBtn.setChecked(true); } } }); Label mapTitle = new Label("MAP", PopinService.hudStyle()); mapTable.add(mapTitle).width(65).pad(-5, 0, -5, 10); mapTable.add(noMapBtn).width(100).height(50).pad(-5, 0, -5, 10); mapTable.add(smallMapBtn).width(100).height(50).pad(-5, 0, -5, 10); mapTable.add(fullMapBtn).width(100).height(50).pad(-5, 0, -5, 0); mapTable.pack(); stage.addActor(mapTable); roomsTable = new Table(); roomsTable.pad(2000, 2000, 2000, 2000); // roomsTable.setDebug(true); scrollPane = new ScrollPane(roomsTable); scrollPane.setTouchable(Touchable.disabled); scrollPane.setSmoothScrolling(false); scrollPane.setBounds(smallBackground.getX() + 12, smallBackground.getY() + 12, Assets.map_background.getRegionWidth() - 24, Assets.map_background.getRegionHeight() - 24); // scrollPane.addAction(Actions.alpha(0.5f)); stage.addActor(scrollPane); enterFloor(f); } /** * Render the map of the floor. */ public void render(float deltaTime) { if (needRefresh) { buildRooms(); scrollToCurrentRoom(); needRefresh = false; } stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); } /** * Change floor. * @param newFloor the new floor */ public void enterFloor(Floor newFloor) { this.floor = newFloor; // Create the table containing rooms and corridors images for (Vector2 coord : floor.getRoomPositions().keySet()) { if (minX == null || coord.x < minX.intValue()) { minX = (int) coord.x; } if (maxX == null || coord.x > maxX.intValue()) { maxX = (int) coord.x; } if (minY == null || coord.y < minY.intValue()) { minY = (int) coord.y; } if (maxY == null || coord.y > maxY.intValue()) { maxY = (int) coord.y; } } xRange = maxX - minX + 1; yRange = maxY - minY + 1; createTableLayout(xRange, yRange); needRefresh = true; } /** * Build the table of rooms and corridors. */ private void buildRooms() { Array<Cell> cells = roomsTable.getCells(); for (int y=0 ; y<(yRange*2) ; y++) { for (int x=0 ; x<(xRange*2) ; x++) { Cell c = findCell(x, y, cells); if (c != null && c.getActor() instanceof Image) { Image corridorImg = (Image) c.getActor(); corridorImg.setVisible(false); } } } for (Entry<Vector2, Room> entry : floor.getRoomPositions().entrySet()) { Vector2 coord = entry.getKey(); int tableX = (int) ((coord.x + Math.abs(minX)) * 2); int tableY = (int) (((yRange - (coord.y + Math.abs(minY))) * 2) - 2); Cell c = findCell(tableX, tableY, cells); if (c != null) { Room room = entry.getValue(); Stack stack = (Stack) c.getActor(); SnapshotArray<Actor> children = stack.getChildren(); Image roomImage = (Image) children.get(0); Image playerImage = (Image) children.get(1); if (room.isDisplayedOnMap() || FULL_MAP) { roomImage.setVisible(true); switch(room.type) { case START_FLOOR_ROOM: roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_start.getRegion())); break; case END_FLOOR_ROOM: roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_exit.getRegion())); break; case SHOP_ROOM: roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_shop.getRegion())); break; case STATUE_ROOM: if (room.hasEnemies()) { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_statue_enemy.getRegion())); } else { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_statue.getRegion())); } break; case KEY_ROOM: if (room.hasEnemies()) { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_key_enemy.getRegion())); } else { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_key.getRegion())); } break; case ITEM_ROOM: if (room.hasEnemies()) { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_item_enemy.getRegion())); } else { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_item.getRegion())); } break; case GIFT_ROOM: if (room.hasEnemies()) { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_gift_enemy.getRegion())); } else { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_gift.getRegion())); } break; case CHALICE_ROOM: if (room.hasEnemies()) { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_chalice_enemy.getRegion())); } else { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_chalice.getRegion())); } break; case MINI_BOSS_ROOM: if (room.hasEnemies()) { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_mini_boss_enemy.getRegion())); } else { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_mini_boss.getRegion())); } break; case BOSS_ROOM: if (room.hasEnemies()) { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_boss_enemy.getRegion())); } else { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_boss.getRegion())); } break; case COMMON_ENEMY_ROOM: case EMPTY_ROOM: case TREASURE_ROOM: default: if (room.hasEnemies()) { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_enemy.getRegion())); } else { roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room.getRegion())); } break; } if (floor.getActiveRoom() == room) { playerImage.setDrawable(new TextureRegionDrawable(Assets.map_player.getRegion())); player = playerImage; } else { playerImage.setDrawable(null); } drawEastCorridor(tableX, tableY, cells, room); drawSouthCorridor(tableX, tableY, cells, room); } else { roomImage.setVisible(true); if( (room.getSouthNeighbor() != null && room.getSouthNeighbor().isVisited()) || (room.getNorthNeighbor() != null && room.getNorthNeighbor().isVisited()) || (room.getWestNeighbor() != null && room.getWestNeighbor().isVisited()) || (room.getEastNeighbor() != null && room.getEastNeighbor().isVisited())) { // Draw unknown room roomImage.setDrawable(new TextureRegionDrawable(Assets.map_room_unknown.getRegion())); if (room.getSouthNeighbor() != null && room.getSouthNeighbor().isVisited()) { // Draw corridor drawSouthCorridor(tableX, tableY, cells, room); } if (room.getEastNeighbor() != null && room.getEastNeighbor().isVisited()) { // Draw corridor drawEastCorridor(tableX, tableY, cells, room); } } else { // Room too far and unvisited, do not display it roomImage.setVisible(false); } } } else { System.out.println("no cell"); } } roomsTable.pack(); } private void createTableLayout(int xRange, int yRange) { roomsTable.clear(); for (int y=0 ; y<yRange; y++) { if (y != 0) { // Add the room row roomsTable.row(); } // Add the columns for the current row for (int x=0 ; x<xRange ; x++) { Stack s = new Stack(); // Room image s.add(new Image()); // Player image s.add(new Image()); roomsTable.add(s).width(Assets.map_room.getRegionWidth()).height(Assets.map_room.getRegionHeight()); if (x != xRange - 1) { roomsTable.add(new Image()).width(Assets.map_corridor.getRegionWidth()).height(Assets.map_corridor.getRegionHeight()); } } // Add the corridor row if (y != yRange - 1) { roomsTable.row(); // Add the columns for the current row for (int x=0 ; x<xRange ; x++) { roomsTable.add(new Image()).width(Assets.map_room.getRegionWidth()).height(Assets.map_corridor.getRegionHeight()); if (x != xRange - 1) { roomsTable.add(new Image()).width(Assets.map_corridor.getRegionWidth()).height(Assets.map_corridor.getRegionHeight()); } } } } } private void drawSouthCorridor(int tableX, int tableY, Array<Cell> cells, Room room) { if (room.getSouthNeighbor() != null) { Cell result = findCell(tableX, tableY + 1, cells); Image corridorImg = (Image) result.getActor(); corridorImg.setVisible(true); corridorImg.setDrawable(new TextureRegionDrawable(Assets.map_corridor.getRegion())); result.setActor(corridorImg); result.width(Assets.map_corridor.getRegionWidth()); } } private void drawEastCorridor(int tableX, int tableY, Array<Cell> cells, Room room) { if (room.getEastNeighbor() != null) { Cell result = findCell(tableX + 1, tableY, cells); Image corridorImg = (Image) result.getActor(); corridorImg.setVisible(true); corridorImg.setDrawable(new TextureRegionDrawable(Assets.map_corridor.getRegion())); result.setActor(corridorImg); } } /** * Find a cell in the table given a coordinate. * @param tableX the x * @param tableY the y * @param cells the array of cells to search from * @return the cell. Null if no cell at this coordinates. */ private Cell findCell(int tableX, int tableY, Array<Cell> cells) { Cell result = null; for (Cell c : cells) { if (c.getRow() == tableY && c.getColumn() == tableX) { result = c; } } return result; } /** * Scroll to center on the current room. */ private void scrollToCurrentRoom() { if (player != null) { Group scrollPos = player.getParent(); scrollPane.layout(); scrollPane.scrollTo(scrollPos.getX(), scrollPos.getY(), player.getImageWidth(), player.getImageHeight(), true, true); } } // getters and setters public boolean isMapDisplayed() { return mapDisplayed; } public void setMapDisplayed(boolean mapDisplayed) { this.mapDisplayed = mapDisplayed; } public boolean isNeedRefresh() { return needRefresh; } public static void requireRefresh() { needRefresh = true; } }
3e1358c6a27202e9041d22fc7b5741f78e2807fb
3,195
java
Java
Hangman/HangmanLv2Class.java
billykurniawanh/100MinigamesProject
a1f90a8233aab339c323d27a3020da3a7d202066
[ "MIT" ]
null
null
null
Hangman/HangmanLv2Class.java
billykurniawanh/100MinigamesProject
a1f90a8233aab339c323d27a3020da3a7d202066
[ "MIT" ]
null
null
null
Hangman/HangmanLv2Class.java
billykurniawanh/100MinigamesProject
a1f90a8233aab339c323d27a3020da3a7d202066
[ "MIT" ]
null
null
null
25.97561
85
0.52144
8,168
import java.util.*; public class HangmanLv2Class{ private Set<String> wordList; private SortedSet<Character> guesses; private int guessesLeft; private String pattern; public HangmanLv2Class(Collection<String> dictionary, int length, int max){ if (length < 1 || max < 0) throw new IllegalArgumentException(); wordList = new TreeSet<>(); guesses = new TreeSet<>(); pattern = ""; Iterator<String> iterator = dictionary.iterator(); while (iterator.hasNext()){ String s = iterator.next(); if (s.length() == length) wordList.add(s); } for (int i = 0; i < length; i++){ pattern += "- "; } guessesLeft = max; } public Set<String> words(){ return wordList; } public int guessesLeft(){ return guessesLeft; } public SortedSet<Character> guesses(){ return guesses; } public String pattern(){ if (wordList.size() == 0) throw new IllegalStateException(); return pattern; } public int record(char guess){ if (wordList.size() == 0 || guessesLeft < 1) throw new IllegalStateException(); else if (guesses.contains(guess)) throw new IllegalArgumentException(); guesses.add(guess); ArrayList<String> patternArray = new ArrayList<String>(); Iterator<String> iterator = wordList.iterator(); while (iterator.hasNext()){ String word = iterator.next(); String patternForWord = createPattern(word,guess); patternArray.add(patternForWord); } int count1 = 0; int best = 0; int index = 0; for(int i = 0; i < patternArray.size(); i++){ for(int j = i; j < patternArray.size(); j++){ if (patternArray.get(i).equals(patternArray.get(j))) count1++; } if (best < count1){ index = i; best = count1; } count1 = 0; } String pickedPattern = patternArray.get(index); for(int i = 0; i < pattern.length(); i++){ if(pattern.substring(i,i+1).equals("-") && pickedPattern.charAt(i) == guess) pattern = pattern.substring(0,i) + guess + pattern.substring(i+1); } Iterator<String> iterator2 = wordList.iterator(); while (iterator2.hasNext()){ if (!createPattern(iterator2.next(),guess).equals(pickedPattern)){ iterator2.remove(); } } int count2 = 0; for (int i = 0; i < pickedPattern.length(); i++){ if(pickedPattern.charAt(i) == guess) count2++; } if (count2 == 0) guessesLeft--; return count2; } public String createPattern(String word, char guess){ String output = ""; for(int i = 0; i < word.length(); i++){ if (word.charAt(i) != guess) output += "- "; else output += Character.toString(guess) + " "; } return output; } }
3e1359fbc1c6101f2a8555a3fd418cec5ade873d
2,313
java
Java
sparkybe-onap-service/src/main/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntry.java
onap/aai-sparky-be
9e320c44e397071c100c5e7728a0a89ee3ebe485
[ "Apache-2.0" ]
null
null
null
sparkybe-onap-service/src/main/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntry.java
onap/aai-sparky-be
9e320c44e397071c100c5e7728a0a89ee3ebe485
[ "Apache-2.0" ]
null
null
null
sparkybe-onap-service/src/main/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntry.java
onap/aai-sparky-be
9e320c44e397071c100c5e7728a0a89ee3ebe485
[ "Apache-2.0" ]
null
null
null
30.038961
98
0.602248
8,169
/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. * Copyright © 2017-2018 Amdocs * ================================================================================ * 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. * ============LICENSE_END========================================================= */ package org.onap.aai.sparky.viewandinspect.entity; /** * The Class EntityEntry. */ public class EntityEntry { private String entityType; private String entityPrimaryKeyValue; private String searchTags; private String entityId; public String getEntityId() { return entityId; } public void setEntityId(String entityId) { this.entityId = entityId; } public String getEntityType() { return entityType; } public void setEntityType(String entityType) { this.entityType = entityType; } public String getEntityPrimaryKeyValue() { return entityPrimaryKeyValue; } public void setEntityPrimaryKeyValue(String entityPrimaryKeyValue) { this.entityPrimaryKeyValue = entityPrimaryKeyValue; } public String getSearchTags() { return searchTags; } public void setSearchTags(String searchTags) { this.searchTags = searchTags; } @Override public String toString() { return "EntityEntry [" + (entityType != null ? "entityType=" + entityType + ", " : "") + (entityPrimaryKeyValue != null ? "entityPrimaryKeyValue=" + entityPrimaryKeyValue + ", " : "") + (searchTags != null ? "searchTags=" + searchTags + ", " : "") + (entityId != null ? "entityId=" + entityId : "") + "]"; } }
3e135a11a0a19f52c72625fee306fdb3ed97b1d6
1,207
java
Java
Minecraft/build/tmp/recompileMc/sources/net/minecraftforge/fml/common/versioning/ArtifactVersion.java
QinxiWang/Mincraft-Agent-Learn-to-Fight-Zombies-and-Slimes
019deb0b37674289d077fb69800ee97e5fdb47d1
[ "MIT" ]
22
2021-01-10T20:58:45.000Z
2021-12-19T18:11:35.000Z
Minecraft/build/tmp/recompileMc/sources/net/minecraftforge/fml/common/versioning/ArtifactVersion.java
QinxiWang/Mincraft-Agent-Learn-to-Fight-Zombies-and-Slimes
019deb0b37674289d077fb69800ee97e5fdb47d1
[ "MIT" ]
3
2021-01-10T20:59:19.000Z
2021-01-13T14:00:58.000Z
Minecraft/build/tmp/recompileMc/sources/net/minecraftforge/fml/common/versioning/ArtifactVersion.java
QinxiWang/Mincraft-Agent-Learn-to-Fight-Zombies-and-Slimes
019deb0b37674289d077fb69800ee97e5fdb47d1
[ "MIT" ]
4
2020-12-20T02:10:44.000Z
2022-01-25T19:38:53.000Z
31.736842
93
0.742123
8,170
/* * Minecraft Forge * Copyright (c) 2016. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation version 2.1 * of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.minecraftforge.fml.common.versioning; /** * Describes an artifact version in terms of its components, converts it to/from a string and * compares two versions. * * @author <a href="mailto:anpch@example.com">Brett Porter</a> */ public interface ArtifactVersion extends Comparable<ArtifactVersion> { String getLabel(); String getVersionString(); boolean containsVersion(ArtifactVersion source); String getRangeString(); }
3e135b956eb083cefaea5bcc3a14de8df61f9a4c
5,930
java
Java
src/main/java/org/dynalang/dynalink/support/ClassMap.java
YunLemon/dynalink
f524803f1c3e88bba274295329d6ff879769b501
[ "Apache-2.0", "BSD-3-Clause" ]
71
2015-01-07T21:08:50.000Z
2022-03-01T11:47:58.000Z
src/main/java/org/dynalang/dynalink/support/ClassMap.java
YunLemon/dynalink
f524803f1c3e88bba274295329d6ff879769b501
[ "Apache-2.0", "BSD-3-Clause" ]
3
2015-01-23T10:02:35.000Z
2016-07-31T21:27:47.000Z
src/main/java/org/dynalang/dynalink/support/ClassMap.java
YunLemon/dynalink
f524803f1c3e88bba274295329d6ff879769b501
[ "Apache-2.0", "BSD-3-Clause" ]
19
2015-01-07T21:09:08.000Z
2021-08-17T13:49:23.000Z
40.340136
119
0.667622
8,171
/* Copyright 2009-2013 Attila Szegedi Licensed under both the Apache License, Version 2.0 (the "Apache License") and the BSD License (the "BSD License"), with licensee being free to choose either of the two at their discretion. You may not use this file except in compliance with either the Apache License or the BSD License. If you choose to use this file in compliance with the Apache License, the following notice applies to you: You may obtain a copy of the Apache 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. If you choose to use this file in compliance with the BSD License, the following notice applies to you: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.dynalang.dynalink.support; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Map; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * A dual map that can either strongly or weakly reference a given class depending on whether the class is visible from * a class loader or not. * * @author Attila Szegedi * @param <T> the type of the values in the map */ public abstract class ClassMap<T> { private final ConcurrentMap<Class<?>, T> map = new ConcurrentHashMap<>(); private final Map<Class<?>, Reference<T>> weakMap = new WeakHashMap<>(); private final ClassLoader classLoader; /** * Creates a new class map. It will use strong references for all keys and values where the key is a class visible * from the class loader, and will use weak keys and soft values for all other classes. * * @param classLoader the classloader that determines strong referenceability. */ protected ClassMap(final ClassLoader classLoader) { this.classLoader = classLoader; } /** * Compute the value associated with the given class. It is possible that the method will be invoked several times * (or even concurrently) for the same class parameter. * * @param clazz the class to compute the value for * @return the return value. Must not be null. */ protected abstract T computeValue(Class<?> clazz); /** * Returns the value associated with the class * * @param clazz the class * @return the value associated with the class */ public T get(final Class<?> clazz) { // Check in fastest first - objects we're allowed to strongly reference final T v = map.get(clazz); if(v != null) { return v; } // Check objects we're not allowed to strongly reference Reference<T> ref; synchronized(weakMap) { ref = weakMap.get(clazz); } if(ref != null) { final T refv = ref.get(); if(refv != null) { return refv; } } // Not found in either place; create a new value final T newV = computeValue(clazz); assert newV != null; final ClassLoader clazzLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return clazz.getClassLoader(); } }, ClassLoaderGetterContextProvider.GET_CLASS_LOADER_CONTEXT); // If allowed to strongly reference, put it in the fast map if(Guards.canReferenceDirectly(classLoader, clazzLoader)) { final T oldV = map.putIfAbsent(clazz, newV); return oldV != null ? oldV : newV; } // Otherwise, put it into the weak map synchronized(weakMap) { ref = weakMap.get(clazz); if(ref != null) { final T oldV = ref.get(); if(oldV != null) { return oldV; } } weakMap.put(clazz, new SoftReference<>(newV)); return newV; } } }
3e135c1173b1aee691a705e0ebb1b723ed3f9b76
5,548
java
Java
saminda/cipres-airavata/cipres-portal/portal2/src/main/java/org/ngbw/web/model/impl/tool/clustalw_profileValidator.java
SciGaP/DEPRECATED-Cipres-Airavata-POC
a2f3dce75ce6c8e23c8cdde14ece708b5a0ad4ab
[ "Apache-2.0" ]
null
null
null
saminda/cipres-airavata/cipres-portal/portal2/src/main/java/org/ngbw/web/model/impl/tool/clustalw_profileValidator.java
SciGaP/DEPRECATED-Cipres-Airavata-POC
a2f3dce75ce6c8e23c8cdde14ece708b5a0ad4ab
[ "Apache-2.0" ]
null
null
null
saminda/cipres-airavata/cipres-portal/portal2/src/main/java/org/ngbw/web/model/impl/tool/clustalw_profileValidator.java
SciGaP/DEPRECATED-Cipres-Airavata-POC
a2f3dce75ce6c8e23c8cdde14ece708b5a0ad4ab
[ "Apache-2.0" ]
null
null
null
33.421687
94
0.69881
8,172
package org.ngbw.web.model.impl.tool; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.ngbw.sdk.api.tool.ParameterValidator; import org.ngbw.sdk.common.util.BaseValidator; import org.ngbw.sdk.database.TaskInputSourceDocument; public class clustalw_profileValidator implements ParameterValidator { private Set<String> requiredParameters; private Set<String> requiredInput; public clustalw_profileValidator() { requiredParameters = new HashSet<String>(); requiredInput = new HashSet<String>(); requiredParameters.add("actions_"); } public Map<String, String> validateParameters(Map<String, String> parameters) { Map<String, String> errors = new HashMap<String, String>(); Set<String> missingRequired = validateRequiredParameters(parameters); for (String missing : missingRequired) { errors.put(missing, "You must enter a value for \"" + missing + "\""); } for (String param : parameters.keySet()) { String error = validate(param, parameters.get(param)); if (error != null) errors.put(param, error); } return errors; } public Map<String, String> validateInput(Map<String, List<TaskInputSourceDocument>> input) { Map<String, String> errors = new HashMap<String, String>(); Set<String> missingRequired = validateRequiredInput(input); for (String missing : missingRequired) { errors.put(missing, "You must enter a value for \"" + missing + "\""); } for (String param : input.keySet()) { String error = validate(param, input.get(param)); if (error != null) errors.put(param, error); } return errors; } public String validate(String parameter, Object value) { if (parameter.equals("actions_")) { if (BaseValidator.validateString(value) == false) return "You must enter a value for \"" + parameter + "\""; return null; } if (parameter.equals("gapopen_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("gapext_")) { if (BaseValidator.validateDouble(value) == false) return "\"" + parameter + "\" must be a Double."; return null; } if (parameter.equals("gapdist_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("maxdiv_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("transweight_")) { if (BaseValidator.validateDouble(value) == false) return "\"" + parameter + "\" must be a Double."; return null; } if (parameter.equals("ktuple_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("topdiags_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("window_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("pairgap_")) { if (BaseValidator.validateDouble(value) == false) return "\"" + parameter + "\" must be a Double."; return null; } if (parameter.equals("pwgapopen_")) { if (BaseValidator.validateDouble(value) == false) return "\"" + parameter + "\" must be a Double."; return null; } if (parameter.equals("pwgapext_")) { if (BaseValidator.validateDouble(value) == false) return "\"" + parameter + "\" must be a Double."; return null; } if (parameter.equals("helixgap_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("strandgap_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("loopgap_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("terminalgap_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("helixendin_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("helixendout_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("strandendin_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } if (parameter.equals("strandendout_")) { if (BaseValidator.validateInteger(value) == false) return "\"" + parameter + "\" must be an integer."; return null; } return null; } private Set<String> validateRequiredParameters(Map<String, String> parameters) { Set<String> required = new HashSet<String>(requiredParameters.size()); required.addAll(requiredParameters); for (String parameter : parameters.keySet()) { if (required.contains(parameter)) required.remove(parameter); } return required; } private Set<String> validateRequiredInput(Map<String, List<TaskInputSourceDocument>> input) { Set<String> required = new HashSet<String>(requiredInput.size()); required.addAll(requiredInput); for (String parameter : input.keySet()) { if (required.contains(parameter)) required.remove(parameter); } return required; } }
3e135c59c45e8db7172ffa21b3778a8365e9c3f0
246
java
Java
CodingBat/Recursion-1/Recursion1count11.java
wizardassassin/Fun-Coding
56b9f338b27fc8fca01fa8f7c0ed4d47f697eb5d
[ "MIT" ]
null
null
null
CodingBat/Recursion-1/Recursion1count11.java
wizardassassin/Fun-Coding
56b9f338b27fc8fca01fa8f7c0ed4d47f697eb5d
[ "MIT" ]
null
null
null
CodingBat/Recursion-1/Recursion1count11.java
wizardassassin/Fun-Coding
56b9f338b27fc8fca01fa8f7c0ed4d47f697eb5d
[ "MIT" ]
null
null
null
30.75
114
0.577236
8,173
public class Recursion1count11 { public int count11(String str) { if (str.length() <= 1) return 0; return (str.substring(0, 2).equals("11")) ? 1 + count11(str.substring(2)) : 0 + count11(str.substring(1)); } }
3e135c628174530a25b5fdd0500551e260a61253
6,157
java
Java
src/main/java/uk/ac/ebi/intact/editor/controller/dashboard/DashboardController.java
EBI-IntAct/editor
8bd0c1412aa9ac8ae66835c841b1a79f19fafa33
[ "CC-BY-4.0" ]
null
null
null
src/main/java/uk/ac/ebi/intact/editor/controller/dashboard/DashboardController.java
EBI-IntAct/editor
8bd0c1412aa9ac8ae66835c841b1a79f19fafa33
[ "CC-BY-4.0" ]
1
2016-06-28T13:36:20.000Z
2016-06-28T13:36:20.000Z
src/main/java/uk/ac/ebi/intact/editor/controller/dashboard/DashboardController.java
EBI-IntAct/Editor
8bd0c1412aa9ac8ae66835c841b1a79f19fafa33
[ "CC-BY-4.0" ]
null
null
null
34.982955
136
0.712197
8,174
/** * Copyright 2010 The European Bioinformatics Institute, and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.ac.ebi.intact.editor.controller.dashboard; import org.primefaces.model.LazyDataModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import uk.ac.ebi.intact.editor.controller.BaseController; import uk.ac.ebi.intact.editor.controller.UserSessionController; import uk.ac.ebi.intact.editor.services.dashboard.DashboardQueryService; import uk.ac.ebi.intact.editor.services.summary.ComplexSummary; import uk.ac.ebi.intact.editor.services.summary.PublicationSummary; import uk.ac.ebi.intact.jami.ApplicationContextProvider; import uk.ac.ebi.intact.jami.model.user.Role; import javax.annotation.Resource; import javax.faces.context.FacesContext; import javax.faces.event.ComponentSystemEvent; /** * @author Bruno Aranda (envkt@example.com) * @version $Id$ */ @Controller @Scope( "session" ) public class DashboardController extends BaseController { public static final String[] DEFAULT_STATUS_SHOWN = new String[]{"new", "curation in progress", "ready for checking"}; private LazyDataModel<PublicationSummary> allPublications; private LazyDataModel<PublicationSummary> ownedByUser; private LazyDataModel<PublicationSummary> reviewedByUser; private LazyDataModel<ComplexSummary> allComplexes; private LazyDataModel<ComplexSummary> complexesOwnedByUser; private LazyDataModel<ComplexSummary> complexesReviewedByUser; private boolean hideAcceptedAndReleased; private String[] statusToShow; private boolean isPublicationTableEnabled = false; private boolean isComplexTableEnabled = false; @Resource(name = "dashboardQueryService") private transient DashboardQueryService queryService; @Autowired private UserSessionController userSessionController; public DashboardController() { hideAcceptedAndReleased = true; statusToShow = DEFAULT_STATUS_SHOWN; } public void loadData( ComponentSystemEvent event ) { if (!FacesContext.getCurrentInstance().isPostback()) { if (userSessionController.hasRole(Role.ROLE_CURATOR) || userSessionController.hasRole(Role.ROLE_REVIEWER) ){ isPublicationTableEnabled = true; } else{ isPublicationTableEnabled = false; } if (userSessionController.hasRole(Role.ROLE_COMPLEX_CURATOR) || userSessionController.hasRole(Role.ROLE_COMPLEX_REVIEWER) ){ isComplexTableEnabled = true; } else{ isComplexTableEnabled = false; } refreshAllTables(); } } public void refreshAllTables() { final String userId = userSessionController.getCurrentUser().getLogin().toUpperCase(); if (statusToShow.length == 0) { addWarningMessage("No statuses selected", "Using default status selection"); statusToShow = DEFAULT_STATUS_SHOWN; } StringBuilder statusToShowSql = new StringBuilder(); for (int i=0; i<statusToShow.length; i++) { if (i>0) { statusToShowSql.append(" or"); } statusToShowSql.append(" p.cvStatus.shortName = '").append(statusToShow[i]).append("'"); } String additionalSql = statusToShowSql.toString(); if (isPublicationTableEnabled){ allPublications = getQueryService().loadAllPublications(additionalSql); ownedByUser = getQueryService().loadPublicationsOwnedBy(userId, additionalSql); reviewedByUser = getQueryService().loadPublicationsReviewedBy(userId, additionalSql); } if (isComplexTableEnabled){ allComplexes = getQueryService().loadAllComplexes(additionalSql); complexesOwnedByUser = getQueryService().loadComplexesOwnedBy(userId, additionalSql); complexesReviewedByUser = getQueryService().loadComplexesReviewedBy(userId, additionalSql); } } public LazyDataModel<PublicationSummary> getAllPublications() { return allPublications; } public LazyDataModel<PublicationSummary> getOwnedByUser() { return ownedByUser; } public LazyDataModel<PublicationSummary> getReviewedByUser() { return reviewedByUser; } public boolean isHideAcceptedAndReleased() { return hideAcceptedAndReleased; } public void setHideAcceptedAndReleased(boolean hideAcceptedAndReleased) { this.hideAcceptedAndReleased = hideAcceptedAndReleased; } public String[] getStatusToShow() { return statusToShow; } public void setStatusToShow(String[] statusToShow) { this.statusToShow = statusToShow; } public LazyDataModel<ComplexSummary> getAllComplexes() { return allComplexes; } public LazyDataModel<ComplexSummary> getComplexesOwnedByUser() { return complexesOwnedByUser; } public LazyDataModel<ComplexSummary> getComplexesReviewedByUser() { return complexesReviewedByUser; } public boolean isPublicationTableEnabled() { return isPublicationTableEnabled; } public boolean isComplexTableEnabled() { return isComplexTableEnabled; } public DashboardQueryService getQueryService() { if (this.queryService == null){ this.queryService = ApplicationContextProvider.getBean("dashboardQueryService"); } return queryService; } }
3e135cf19fcce5f0259a83f6239ab5b2c0e313eb
996
java
Java
app/auth/AdminAuthenticator.java
yuhuanxi/play2
d1691abd44d9a253de1a3376a2b42e8faefb495c
[ "Apache-2.0" ]
1
2016-09-09T10:00:11.000Z
2016-09-09T10:00:11.000Z
app/auth/AdminAuthenticator.java
yuhuanxi/play2
d1691abd44d9a253de1a3376a2b42e8faefb495c
[ "Apache-2.0" ]
null
null
null
app/auth/AdminAuthenticator.java
yuhuanxi/play2
d1691abd44d9a253de1a3376a2b42e8faefb495c
[ "Apache-2.0" ]
null
null
null
25.538462
64
0.572289
8,175
package auth; import models.User; import play.mvc.Http; import play.mvc.Result; import play.mvc.Security; import play.twirl.api.Content; /** * Created by yuhuanxi on 16/6/18. */ public class AdminAuthenticator extends Security.Authenticator { public String getUsername(Http.Context ctx) { String uid = ctx.request().getQueryString("uid"); if (uid != null) { User user = User.finder.byId(Long.parseLong(uid)); if (user != null) { if ("abc".equals(user.nick)) { return user.nick; } } } return null; // 自定义验证逻辑,这里是看看session中的username是否为yhx,如果是,则通过验证 // String username = ctx.session().get("username"); // if (username != null && username.equals("yhx")) { // return ctx.session().get("username"); // } // return null; } public Result onUnauthorized(Http.Context ctx) { return unauthorized("未授权"); } }
3e135d0de70dd667e1d818c1ed21609904373e16
2,179
java
Java
USACOContest/2018Dec/Silver/convention2/convention2.java
UlyssesZh/AlgorithmTraining
a3d3c95cf60f0b73a13d297ef699617a19d0b80e
[ "CC0-1.0" ]
null
null
null
USACOContest/2018Dec/Silver/convention2/convention2.java
UlyssesZh/AlgorithmTraining
a3d3c95cf60f0b73a13d297ef699617a19d0b80e
[ "CC0-1.0" ]
null
null
null
USACOContest/2018Dec/Silver/convention2/convention2.java
UlyssesZh/AlgorithmTraining
a3d3c95cf60f0b73a13d297ef699617a19d0b80e
[ "CC0-1.0" ]
null
null
null
25.337209
70
0.65397
8,176
import java.io.*; import java.util.*; public class convention2 { private static final String PROG = "convention2"; private static int n; private static int[] arrivals; private static int[] eatTime; private static boolean[] waiting; private static Integer[] approaching; private static int approachingI; private static int now; private static int eating; private static int[] startTime; private static int result; private static void init() { n = scanner.nextInt(); arrivals = new int[n]; eatTime = new int[n]; waiting = new boolean[n]; approaching = new Integer[n]; startTime = new int[n]; for (int i = 0; i < n; i++) { arrivals[i] = scanner.nextInt(); eatTime[i] = scanner.nextInt(); approaching[i] = i; startTime[i] = -1; } Arrays.sort(approaching, Comparator.comparingInt(i -> arrivals[i])); result = 0; approachingI = 0; eating = -1; } private static int nextArriveTime() { return arrivals[approaching[approachingI]]; } private static int nextFinishEatingTime() { return eating == -1 ? -1 : startTime[eating] + eatTime[eating]; } private static int findQueueTop() { for (int i = 0; i < n; i++) if (waiting[i]) return i; return -1; } private static void eat() { int next = findQueueTop(); if (next != -1) { waiting[next] = false; startTime[next] = now; eating = next; result = Math.max(result, now - arrivals[next]); } } private static void emulate() { while (approachingI < n) { if (eating == -1) eat(); int arrive = nextArriveTime(); int finishing = nextFinishEatingTime(); if (finishing == -1 || arrive < finishing) { now = arrive; waiting[approaching[approachingI++]] = true; } else { now = finishing; eating = -1; } } } private static void actualMain() { init(); emulate(); out.println(result); } private static InputStream in; private static PrintStream out; private static Scanner scanner; public static void main(String[] args) throws IOException { in = new FileInputStream(PROG + ".in"); out = new PrintStream(PROG + ".out"); scanner = new Scanner(in); actualMain(); in.close(); out.close(); scanner.close(); } }
3e135efd00460d0b07014547a221fddde053e421
1,539
java
Java
platform-common/src/test/java/com/softicar/platform/common/testing/AssertionErrorMessageCollectorTest.java
softicar/platform
d4cf99f3e3537272af23bf60f6b088891bd271ff
[ "MIT" ]
1
2021-11-25T09:58:31.000Z
2021-11-25T09:58:31.000Z
platform-common/src/test/java/com/softicar/platform/common/testing/AssertionErrorMessageCollectorTest.java
softicar/platform
d4cf99f3e3537272af23bf60f6b088891bd271ff
[ "MIT" ]
22
2021-11-10T13:59:22.000Z
2022-03-04T16:38:33.000Z
platform-common/src/test/java/com/softicar/platform/common/testing/AssertionErrorMessageCollectorTest.java
softicar/platform
d4cf99f3e3537272af23bf60f6b088891bd271ff
[ "MIT" ]
null
null
null
26.534483
93
0.77193
8,177
package com.softicar.platform.common.testing; import com.softicar.platform.common.string.formatting.StackTraceFormatting; import org.junit.Test; public class AssertionErrorMessageCollectorTest extends AbstractTest { private final AssertionErrorMessageCollector collector; public AssertionErrorMessageCollectorTest() { this.collector = new AssertionErrorMessageCollector(); } @Test public void testThrowIfNecessaryWithoutMessages() { collector.throwIfNecessary(); } @Test public void testThrowIfNecessaryWithSimpleMessage() { collector.add("foo"); try { collector.throwIfNecessary(); } catch (Throwable throwable) { assertTrue(StackTraceFormatting.getStackTraceAsString(throwable).contains("1 error")); assertTrue(AssertionError.class.isAssignableFrom(throwable.getClass())); } } @Test public void testThrowIfNecessaryWithSimpleMessages() { collector.add("foo"); collector.add("bar"); try { collector.throwIfNecessary(); } catch (Throwable throwable) { assertTrue(StackTraceFormatting.getStackTraceAsString(throwable).contains("2 errors")); assertTrue(AssertionError.class.isAssignableFrom(throwable.getClass())); } } @Test public void testThrowIfNecessaryWithFormattedMessage() { collector.add("foo %s bar", "xxx"); try { collector.throwIfNecessary(); } catch (Throwable throwable) { assertTrue(StackTraceFormatting.getStackTraceAsString(throwable).contains("foo xxx bar")); assertTrue(AssertionError.class.isAssignableFrom(throwable.getClass())); } } }
3e135f02a47de88eea5d719bce7f5eb8a9dcdfdd
1,890
java
Java
src/main/java/org/pokowaka/hanabi/ai/rl4j/HanabiState.java
pokowaka/hanabi
3ff26fa082ed3fb00b6cf08e12d9702725a688d7
[ "MIT" ]
1
2020-03-05T16:56:57.000Z
2020-03-05T16:56:57.000Z
src/main/java/org/pokowaka/hanabi/ai/rl4j/HanabiState.java
pokowaka/hanabi
3ff26fa082ed3fb00b6cf08e12d9702725a688d7
[ "MIT" ]
null
null
null
src/main/java/org/pokowaka/hanabi/ai/rl4j/HanabiState.java
pokowaka/hanabi
3ff26fa082ed3fb00b6cf08e12d9702725a688d7
[ "MIT" ]
null
null
null
30.983607
84
0.564021
8,178
package org.pokowaka.hanabi.ai.rl4j; import org.pokowaka.hanabi.Card; import org.pokowaka.hanabi.Game; import org.pokowaka.hanabi.Player; import org.deeplearning4j.rl4j.space.Encodable; import java.util.Vector; public class HanabiState implements Encodable { static final int PILES = 2 * (Card.Color.values().length - 1); private final Game game; double encoded[]; public HanabiState(Game g) { this.game = g; this.encoded = new double[stateSize(g.getPlayerCount())]; } public static int stateSize(int playerCount) { return 4 + PILES + playerCount * 8; } @Override public double[] toArray() { int i = 0; int currentPlayer = this.game.getPlayerIdx(); this.encoded[i++] = this.game.getHints(); this.encoded[i++] = this.game.getFireworks(); this.encoded[i++] = currentPlayer; this.encoded[i++] = this.game.getDeck().size(); for (Card.Color c : this.game.getPiles().keySet()) { this.encoded[i++] = c.getValue(); this.encoded[i++] = this.game.getPiles().get(c); } Vector<Player> players = this.game.getPlayers(); for (int j = 1; j < players.size(); j++) { Player p = players.elementAt((currentPlayer + j) % players.size()); for (int k = 0; k < 4; k++) { Card c = p.getCard(k); this.encoded[i++] = c.getColor().getValue(); this.encoded[i++] = c.getNumber(); } } Player current = this.game.getCurrent(); for (int k = 0; k < 4; k++) { Card c = current.getCard(k); this.encoded[i++] = current.knowsColor(k) ? c.getColor().getValue() : 0; this.encoded[i++] = current.knowsNumber(k) ? c.getNumber() : 0; } assert i == encoded.length; return encoded; } }
3e135f85b4973aa7ce571d2c5f2f07933fceaff5
1,577
java
Java
instrument-simulator/system-modules/instrument-simulator-logger-module/src/main/java/com/shulie/instrument/simulator/module/logger/common/LoggerHelper.java
vinzhangya/LinkAgent
3e58956a4bb3a251767de058e98a3170a897f90d
[ "Apache-2.0" ]
104
2021-06-24T09:39:13.000Z
2022-03-31T14:33:27.000Z
instrument-simulator/system-modules/instrument-simulator-logger-module/src/main/java/com/shulie/instrument/simulator/module/logger/common/LoggerHelper.java
vinzhangya/LinkAgent
3e58956a4bb3a251767de058e98a3170a897f90d
[ "Apache-2.0" ]
38
2021-06-25T09:32:27.000Z
2022-03-31T18:33:36.000Z
instrument-simulator/system-modules/instrument-simulator-logger-module/src/main/java/com/shulie/instrument/simulator/module/logger/common/LoggerHelper.java
vinzhangya/LinkAgent
3e58956a4bb3a251767de058e98a3170a897f90d
[ "Apache-2.0" ]
81
2021-06-24T09:52:35.000Z
2022-02-27T13:22:17.000Z
32.833333
70
0.715736
8,179
/** * Copyright 2021 Shulie Technology, Co.Ltd * Email: lyhxr@example.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * See the License for the specific language governing permissions and * limitations under the License. */ package com.shulie.instrument.simulator.module.logger.common; /** * * @author hengyunabc 2019-09-06 * */ public interface LoggerHelper { public static final String clazz = "class"; public static final String classLoader = "classLoader"; public static final String classLoaderHash = "classLoaderHash"; public static final String codeSource = "codeSource"; // logger info public static final String level = "level"; public static final String effectiveLevel = "effectiveLevel"; // log4j2 only public static final String config = "config"; // type boolean public static final String additivity = "additivity"; public static final String appenders = "appenders"; // appender info public static final String name = "name"; public static final String file = "file"; public static final String blocking = "blocking"; // type List<String> public static final String appenderRef = "appenderRef"; public static final String target = "target"; }
3e136029cd281ac3bfd1c8e0542aced01c8ef8d5
352
java
Java
L02.2.3-JavaInstrumentation/src/com/javapapers/java/instrumentation/DurationAgent.java
lanaflonPerso/otus_java_2018_04
13f91ab3dc08e34cea1e859d234f87ec47e4ab08
[ "MIT" ]
9
2018-04-13T18:51:49.000Z
2021-12-16T22:58:57.000Z
L02.2.3-JavaInstrumentation/src/com/javapapers/java/instrumentation/DurationAgent.java
myluckagain/otus_java_2018_04
13f91ab3dc08e34cea1e859d234f87ec47e4ab08
[ "MIT" ]
null
null
null
L02.2.3-JavaInstrumentation/src/com/javapapers/java/instrumentation/DurationAgent.java
myluckagain/otus_java_2018_04
13f91ab3dc08e34cea1e859d234f87ec47e4ab08
[ "MIT" ]
17
2018-04-12T13:40:08.000Z
2021-12-16T22:58:47.000Z
27.076923
69
0.767045
8,180
package com.javapapers.java.instrumentation; import java.lang.instrument.Instrumentation; public class DurationAgent { // for all the class loaded, premain will be called public static void premain(String agentArgs, Instrumentation inst) { System.out.println("Executing premain........."); inst.addTransformer(new DurationTransformer()); } }
3e13603020988572ab217cd3aa614cddcb29834f
3,222
java
Java
src/cn/tzm/oa/domain/User.java
spacestime/TZMOA
6ac95efb5d57857cced27260fbd1798b7b94713f
[ "Apache-2.0" ]
null
null
null
src/cn/tzm/oa/domain/User.java
spacestime/TZMOA
6ac95efb5d57857cced27260fbd1798b7b94713f
[ "Apache-2.0" ]
null
null
null
src/cn/tzm/oa/domain/User.java
spacestime/TZMOA
6ac95efb5d57857cced27260fbd1798b7b94713f
[ "Apache-2.0" ]
null
null
null
17.606557
74
0.664494
8,181
package cn.tzm.oa.domain; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Set; import com.opensymphony.xwork2.ActionContext; /** * 用户 * * @author tyg * */ public class User implements Serializable { private Long id; private Department department; private Set<Role> roles = new HashSet<Role>(); private String loginName; // 登录名 private String password; // 密码 private String name; // 真实姓名 private String gender; // 性别 private String phoneNumber; // 电话号码 private String email; // 电子邮件 private String description; // 说明 /** * 判断当前用户是否有指定的名称权限 * * @param privName * 权限的名称 */ public boolean hasPrivilegeByName(String privName) { // 如果是超级管理员。默认所以权限 if (isAdmin()) { return true; } for (Role role : roles) { for (Privilege p : role.getPrivileges()) { if (p.getName().equals(privName)) { return true; } } } return false; } /** * 判断当前url是否有指定的名称权限 * * @param privUrl * 权限的url地址 * @return */ public boolean hasPrivilegeByUrl(String privUrl) { // 如果是超级管理员。默认所以权限 if (isAdmin()) { return true; } // a去掉后面的参数字符串(如果有) int pos = privUrl.indexOf("?"); if (pos > -1) { privUrl = privUrl.substring(0, pos); } // b去掉后面的UI后缀(如果有) if (privUrl.endsWith("UI")) { privUrl = privUrl.substring(0, privUrl.length() - 2); } // 如果是普通用户,就需要判断权限 // a.如果这个URL是不需要控制的功能(登录后直接使用的),这时应该直接返回true Collection<String> allPrivilegeUrls = (Collection<String>) ActionContext .getContext().getApplication().get("allPrivilegeUrls"); if (!allPrivilegeUrls.contains(privUrl)) { return true; } // b.如果这个URL是需要控制的功能(登录后,还要有对应的权限才能使用的),这时应该判断权限 else { for (Role role : roles) { for (Privilege p : role.getPrivileges()) { if (privUrl.equals(p.getUrl())) { return true; } } } } return false; } public boolean isAdmin() { return "admin".equals(loginName); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
3e1361184ae601a036fe20073ea7454ed2a32fc6
11,364
java
Java
ext/platforms/android/app/src/java/com/jamar/penengine/PenBitmap.java
fentacoder/NanoEngine
9c4e27b7b7b1d8335d21aa02385afc96a7ea8188
[ "Apache-2.0" ]
null
null
null
ext/platforms/android/app/src/java/com/jamar/penengine/PenBitmap.java
fentacoder/NanoEngine
9c4e27b7b7b1d8335d21aa02385afc96a7ea8188
[ "Apache-2.0" ]
null
null
null
ext/platforms/android/app/src/java/com/jamar/penengine/PenBitmap.java
fentacoder/NanoEngine
9c4e27b7b7b1d8335d21aa02385afc96a7ea8188
[ "Apache-2.0" ]
null
null
null
34.858896
173
0.549102
8,182
/************************************************************************************************* Copyright 2021 Jamar Phillip Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *************************************************************************************************/ package com.jamar.penengine; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.text.BoringLayout; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.text.TextUtils; import android.util.Log; import java.nio.ByteBuffer; import java.nio.ByteOrder; public final class PenBitmap { // =========================================================== // Constants // =========================================================== private static final int HORIZONTAL_ALIGN_LEFT = 1; private static final int HORIZONTAL_ALIGN_RIGHT = 2; private static final int HORIZONTAL_ALIGN_CENTER = 3; private static final int VERTICAL_ALIGN_TOP = 1; private static final int VERTICAL_ALIGN_BOTTOM = 2; private static final int VERTICAL_ALIGN_CENTER = 3; // =========================================================== // Fields // =========================================================== private static Context sContext; // =========================================================== // Getter & Setter // =========================================================== public static void setContext(final Context context) { PenBitmap.sContext = context; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== private static native void nativeInitBitmapDC(final int width, final int height, final byte[] pixels); //http://egoco.de/post/19077604048/calculating-the-height-of-text-in-android public static int getTextHeight(String text, int maxWidth, float textSize, Typeface typeface) { TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG); paint.setTextSize(textSize); paint.setTypeface(typeface); int lineCount = 0; int index = 0; int length = text.length(); while(index < length) { final int charsToAdvance = paint.breakText(text, index, length, true, maxWidth, null); if(charsToAdvance == 0) { index++; } else { index += charsToAdvance; lineCount++; } } float actualHeight = (Math.abs(paint.ascent()) + Math.abs(paint.descent())); return (int)Math.floor(lineCount * actualHeight); } public static Typeface calculateShrinkTypeFace(String text, int width, int height, Layout.Alignment hAlignment, float textSize, TextPaint paint, boolean enableWrap) { if (width == 0 || height == 0) { return paint.getTypeface(); } float actualWidth = width + 1; float actualHeight = height + 1; float fontSize = textSize + 1; if (!enableWrap) { while (actualWidth > width || actualHeight > height) { fontSize = fontSize - 1; actualWidth = (int)Math.ceil( StaticLayout.getDesiredWidth(text, paint)); actualHeight = getTextHeight(text, (int)actualWidth, fontSize, paint.getTypeface()); paint.setTextSize(fontSize); if (fontSize <= 0) { paint.setTextSize(textSize); break; } } } else { while (actualHeight > height || actualWidth > width) { fontSize = fontSize - 1; Layout layout = new StaticLayout(text, paint, (int) width, hAlignment,1.0f,0.0f,false); actualWidth = layout.getWidth(); actualHeight = layout.getLineTop(layout.getLineCount()); paint.setTextSize(fontSize); if (fontSize <= 0) { paint.setTextSize(textSize); break; } } } return paint.getTypeface(); } public static boolean createTextBitmapShadowStroke(byte[] bytes, final String fontName, int fontSize, int fontTintR, int fontTintG, int fontTintB, int fontTintA, int alignment, int width, int height, boolean shadow, float shadowDX, float shadowDY, float shadowBlur, float shadowOpacity, boolean stroke, int strokeR, int strokeG, int strokeB, int strokeA, float strokeSize, boolean enableWrap, int overflow) { String string; if (bytes == null || bytes.length == 0) { return false; } else { string = new String(bytes); } Layout.Alignment hAlignment = Layout.Alignment.ALIGN_NORMAL; int horizontalAlignment = alignment & 0x0F; switch (horizontalAlignment) { case HORIZONTAL_ALIGN_CENTER: hAlignment = Layout.Alignment.ALIGN_CENTER; break; case HORIZONTAL_ALIGN_RIGHT: hAlignment = Layout.Alignment.ALIGN_OPPOSITE; break; case HORIZONTAL_ALIGN_LEFT: break; default: break; } TextPaint paint = PenBitmap.newPaint(fontName, fontSize); if (stroke) { paint.setStyle(TextPaint.Style.STROKE); paint.setStrokeWidth(strokeSize); } int maxWidth = width; if (maxWidth <= 0) { maxWidth = (int)Math.ceil( StaticLayout.getDesiredWidth(string, paint)); } Layout layout = null; int layoutWidth = 0; int layoutHeight = 0; if (overflow == 1 && !enableWrap){ int widthBoundary = (int)Math.ceil( StaticLayout.getDesiredWidth(string, paint)); layout = new StaticLayout(string, paint, widthBoundary , hAlignment,1.0f,0.0f,false); }else { if (overflow == 2) { calculateShrinkTypeFace(string, width, height, hAlignment, fontSize, paint, enableWrap); } layout = new StaticLayout(string, paint, maxWidth , hAlignment,1.0f,0.0f,false); } layoutWidth = layout.getWidth(); layoutHeight = layout.getLineTop(layout.getLineCount()); int bitmapWidth = Math.max(layoutWidth, width); int bitmapHeight = layoutHeight; if (height > 0) { bitmapHeight = height; } if (overflow == 1 && !enableWrap) { if (width > 0) { bitmapWidth = width; } } if (bitmapWidth == 0 || bitmapHeight == 0) { return false; } int offsetX = 0; if (horizontalAlignment == HORIZONTAL_ALIGN_CENTER) { offsetX = (bitmapWidth - layoutWidth) / 2; } else if (horizontalAlignment == HORIZONTAL_ALIGN_RIGHT) { offsetX = bitmapWidth - layoutWidth; } int offsetY = 0; int verticalAlignment = (alignment >> 4) & 0x0F; switch (verticalAlignment) { case VERTICAL_ALIGN_CENTER: offsetY = (bitmapHeight - layoutHeight) / 2; break; case VERTICAL_ALIGN_BOTTOM: offsetY = bitmapHeight - layoutHeight; break; } Bitmap bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.translate(offsetX, offsetY); if ( stroke ) { paint.setARGB(strokeA, strokeR, strokeG, strokeB); layout.draw(canvas); } paint.setStyle(TextPaint.Style.FILL); paint.setARGB(fontTintA, fontTintR, fontTintG, fontTintB); layout.draw(canvas); PenBitmap.initNativeObject(bitmap); return true; } private static TextPaint newPaint(final String fontName, final int fontSize) { final TextPaint paint = new TextPaint(); paint.setTextSize(fontSize); paint.setAntiAlias(true); paint.setTypeface(Typeface.create(fontName, Typeface.NORMAL)); return paint; } private static void initNativeObject(final Bitmap bitmap) { final byte[] pixels = PenBitmap.getPixels(bitmap); if (pixels == null) { return; } PenBitmap.nativeInitBitmapDC(bitmap.getWidth(), bitmap.getHeight(), pixels); } private static byte[] getPixels(final Bitmap bitmap) { if (bitmap != null) { final byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight() * 4]; final ByteBuffer buf = ByteBuffer.wrap(pixels); buf.order(ByteOrder.nativeOrder()); bitmap.copyPixelsToBuffer(buf); return pixels; } return null; } public static int getFontSizeAccordingHeight(int height) { TextPaint paint = new TextPaint(); Rect bounds = new Rect(); paint.setTypeface(Typeface.DEFAULT); int text_size = 1; boolean found_desired_size = false; while (!found_desired_size) { paint.setTextSize(text_size); String text = "SghMNy"; paint.getTextBounds(text, 0, text.length(), bounds); text_size++; if (height - bounds.height() <= 2) { found_desired_size = true; } } return text_size; } private static String getStringWithEllipsis(String string, float width, float fontSize) { if (TextUtils.isEmpty(string)) { return ""; } TextPaint paint = new TextPaint(); paint.setTypeface(Typeface.DEFAULT); paint.setTextSize(fontSize); return TextUtils.ellipsize(string, paint, width, TextUtils.TruncateAt.END).toString(); } }
3e136216fc65fa864046cf903d729718ee68ab6a
1,560
java
Java
src/main/java/io/dgraph/client/ValueDecoders.java
windoze/dgraph4j
77dff62155381de7ccabea6b1eba809570220360
[ "Apache-2.0" ]
null
null
null
src/main/java/io/dgraph/client/ValueDecoders.java
windoze/dgraph4j
77dff62155381de7ccabea6b1eba809570220360
[ "Apache-2.0" ]
null
null
null
src/main/java/io/dgraph/client/ValueDecoders.java
windoze/dgraph4j
77dff62155381de7ccabea6b1eba809570220360
[ "Apache-2.0" ]
1
2021-11-01T17:34:03.000Z
2021-11-01T17:34:03.000Z
34.666667
112
0.728205
8,183
/* * Copyright 2016 DGraph Labs, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.dgraph.client; import java.nio.ByteBuffer; import java.nio.charset.Charset; /** * Definition of a set of decoders that could be used oto converting value bytes to a required type. * * @author Edgar Rodriguez-Diaz * @version 0.0.1 */ public final class ValueDecoders { public static ValueDecoder<String> STRING_UTF8 = theBytes -> new String(theBytes, Charset.forName("utf-8")); public static ValueDecoder<Integer> INTEGER = theBytes -> { final ByteBuffer wrapped = ByteBuffer.wrap(theBytes); return wrapped.getInt(); }; public static ValueDecoder<Short> SHORT = theBytes -> ByteBuffer.wrap(theBytes).getShort(); public static ValueDecoder<Long> LONG = theBytes -> ByteBuffer.wrap(theBytes).getLong(); public static ValueDecoder<Float> FLOAT = theBytes -> ByteBuffer.wrap(theBytes).getFloat(); public static ValueDecoder<Double> DOUBLE = theBytes -> ByteBuffer.wrap(theBytes).getDouble(); }
3e13633c66b543b2ee9665b5435d6d0db20dcce9
3,943
java
Java
jadx-plugins/jadx-dex-input/src/main/java/jadx/plugins/input/dex/insns/DexInsnData.java
xdnice/jadx
7a93d0d93c68083bb7e5f72bbc8a9a00d7916e49
[ "Apache-2.0" ]
1
2021-03-05T11:36:06.000Z
2021-03-05T11:36:06.000Z
jadx-plugins/jadx-dex-input/src/main/java/jadx/plugins/input/dex/insns/DexInsnData.java
decodelove/jadx
9f684937c666609082612278aa1cab146d49b7c0
[ "Apache-2.0" ]
1
2020-11-05T18:02:35.000Z
2020-11-05T18:02:35.000Z
jadx-plugins/jadx-dex-input/src/main/java/jadx/plugins/input/dex/insns/DexInsnData.java
decodelove/jadx
9f684937c666609082612278aa1cab146d49b7c0
[ "Apache-2.0" ]
1
2021-03-05T11:36:08.000Z
2021-03-05T11:36:08.000Z
18.866029
75
0.709358
8,184
package jadx.plugins.input.dex.insns; import org.jetbrains.annotations.Nullable; import jadx.api.plugins.input.data.IFieldData; import jadx.api.plugins.input.data.IMethodRef; import jadx.api.plugins.input.insns.InsnData; import jadx.api.plugins.input.insns.InsnIndexType; import jadx.api.plugins.input.insns.Opcode; import jadx.api.plugins.input.insns.custom.ICustomPayload; import jadx.plugins.input.dex.sections.DexCodeReader; import jadx.plugins.input.dex.sections.SectionReader; public class DexInsnData implements InsnData { private final DexCodeReader codeData; private final SectionReader externalReader; private DexInsnInfo insnInfo; private boolean decoded; private int opcodeUnit; private int length; private int offset; private int[] argsReg = new int[5]; private int regsCount; private long literal; private int target; private int index; @Nullable private ICustomPayload payload; public DexInsnData(DexCodeReader codeData, SectionReader externalReader) { this.codeData = codeData; this.externalReader = externalReader; } @Override public void decode() { if (insnInfo != null && !decoded) { codeData.decode(this); } } @Override public int getOffset() { return offset; } @Override public Opcode getOpcode() { DexInsnInfo info = this.insnInfo; if (info == null) { return Opcode.UNKNOWN; } return info.getApiOpcode(); } @Override public int getRawOpcodeUnit() { return opcodeUnit; } @Override public int getRegsCount() { return regsCount; } @Override public int getReg(int argNum) { return argsReg[argNum]; } @Override public long getLiteral() { return literal; } @Override public int getTarget() { return target; } @Override public int getIndex() { return index; } @Override public InsnIndexType getIndexType() { return insnInfo.getIndexType(); } @Override public String getIndexAsString() { return externalReader.getString(index); } @Override public String getIndexAsType() { return externalReader.getType(index); } @Override public IFieldData getIndexAsField() { return externalReader.getFieldData(index); } @Override public IMethodRef getIndexAsMethod() { return externalReader.getMethodRef(index); } @Nullable @Override public ICustomPayload getPayload() { return payload; } public int[] getArgsReg() { return argsReg; } public void setArgsReg(int[] argsReg) { this.argsReg = argsReg; } public void setRegsCount(int regsCount) { this.regsCount = regsCount; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public void setLiteral(long literal) { this.literal = literal; } public void setTarget(int target) { this.target = target; } public void setIndex(int index) { this.index = index; } public boolean isDecoded() { return decoded; } public void setDecoded(boolean decoded) { this.decoded = decoded; } public void setOffset(int offset) { this.offset = offset; } public DexInsnInfo getInsnInfo() { return insnInfo; } public void setInsnInfo(DexInsnInfo insnInfo) { this.insnInfo = insnInfo; } public DexCodeReader getCodeData() { return codeData; } public int getOpcodeUnit() { return opcodeUnit; } public void setOpcodeUnit(int opcodeUnit) { this.opcodeUnit = opcodeUnit; } public void setPayload(ICustomPayload payload) { this.payload = payload; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("0x%04X", offset)); sb.append(": ").append(getOpcode()); if (insnInfo == null) { sb.append(String.format("(0x%04X)", opcodeUnit)); } else { int regsCount = getRegsCount(); if (isDecoded()) { sb.append(' '); for (int i = 0; i < regsCount; i++) { if (i != 0) { sb.append(", "); } sb.append("r").append(argsReg[i]); } } } return sb.toString(); } }
3e13638410116f8d5aaa1bde8fd7847689aa56ae
541
java
Java
maja-web/src/main/java/de/mwvb/maja/web/ActionBase.java
SoltauFintel/maja-web
618d9b9b9f60dc2c4e7ef6fbb15f9c16353757ab
[ "Apache-2.0" ]
null
null
null
maja-web/src/main/java/de/mwvb/maja/web/ActionBase.java
SoltauFintel/maja-web
618d9b9b9f60dc2c4e7ef6fbb15f9c16353757ab
[ "Apache-2.0" ]
null
null
null
maja-web/src/main/java/de/mwvb/maja/web/ActionBase.java
SoltauFintel/maja-web
618d9b9b9f60dc2c4e7ef6fbb15f9c16353757ab
[ "Apache-2.0" ]
null
null
null
23.521739
119
0.687616
8,185
package de.mwvb.maja.web; import spark.Request; import spark.Response; /** * Pageless Action * * You can access Request (req) and Response (res) within run(). Prefer the Action class if the action has got a page. * Use this class for pageless actions, e.g. save actions that redirect to another page. */ public abstract class ActionBase { protected Request req; protected Response res; public void init(Request req, Response res) { this.req = req; this.res = res; } public abstract String run(); }
3e13640f6bbec93bb6bddc3ff7fbeec66cce6d0d
103
java
Java
src/main/java/br/com/zupacademy/haline/proposta/carteira/TipoCarteira.java
Haline26/orange-talents-04-template-proposta
88dbc13b5107821666f2b9750d7d655c5879e4fe
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zupacademy/haline/proposta/carteira/TipoCarteira.java
Haline26/orange-talents-04-template-proposta
88dbc13b5107821666f2b9750d7d655c5879e4fe
[ "Apache-2.0" ]
null
null
null
src/main/java/br/com/zupacademy/haline/proposta/carteira/TipoCarteira.java
Haline26/orange-talents-04-template-proposta
88dbc13b5107821666f2b9750d7d655c5879e4fe
[ "Apache-2.0" ]
null
null
null
14.714286
51
0.796117
8,186
package br.com.zupacademy.haline.proposta.carteira; public enum TipoCarteira { PAYPAL, SAMSUNGPAY }
3e13646c5afe9b1dc2163f4045f4014a11411661
11,559
java
Java
plugins/mps-kotlin/languages/kotlin/source_gen/jetbrains/mps/kotlin/editor/SuperClassSpecifier_EditorBuilder_a.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
plugins/mps-kotlin/languages/kotlin/source_gen/jetbrains/mps/kotlin/editor/SuperClassSpecifier_EditorBuilder_a.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
plugins/mps-kotlin/languages/kotlin/source_gen/jetbrains/mps/kotlin/editor/SuperClassSpecifier_EditorBuilder_a.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
55.042857
278
0.791418
8,187
package jetbrains.mps.kotlin.editor; /*Generated by MPS */ import jetbrains.mps.editor.runtime.descriptor.AbstractEditorBuilder; import org.jetbrains.annotations.NotNull; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.openapi.editor.EditorContext; import jetbrains.mps.openapi.editor.cells.EditorCell; import jetbrains.mps.nodeEditor.cells.EditorCell_Collection; import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Indent; import org.jetbrains.mps.openapi.language.SReferenceLink; import jetbrains.mps.lang.editor.cellProviders.SReferenceCellProvider; import jetbrains.mps.editor.runtime.impl.CellUtil; import jetbrains.mps.nodeEditor.cells.EditorCell_Error; import jetbrains.mps.openapi.editor.cells.CellActionType; import jetbrains.mps.nodeEditor.cellActions.CellAction_DeleteNode; import jetbrains.mps.lang.editor.menus.transformation.NamedTransformationMenuLookup; import jetbrains.mps.smodel.language.LanguageRegistry; import jetbrains.mps.nodeEditor.cellMenu.CompositeSubstituteInfo; import jetbrains.mps.lang.editor.cellProviders.ReferenceCellContext; import jetbrains.mps.nodeEditor.cellMenu.SubstituteInfoPartExt; import jetbrains.mps.nodeEditor.cellMenu.SChildSubstituteInfoPartEx; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.lang.smodel.generator.smodelAdapter.IAttributeDescriptor; import jetbrains.mps.internal.collections.runtime.Sequence; import jetbrains.mps.internal.collections.runtime.IWhereFilter; import java.util.Objects; import jetbrains.mps.lang.core.behavior.LinkAttribute__BehaviorDescriptor; import jetbrains.mps.nodeEditor.EditorManager; import jetbrains.mps.openapi.editor.update.AttributeKind; import org.jetbrains.mps.openapi.language.SProperty; import jetbrains.mps.openapi.editor.menus.transformation.SPropertyInfo; import jetbrains.mps.nodeEditor.cells.EditorCell_Property; import jetbrains.mps.nodeEditor.cells.SPropertyAccessor; import jetbrains.mps.lang.editor.cellProviders.PropertyCellContext; import jetbrains.mps.lang.core.behavior.PropertyAttribute__BehaviorDescriptor; import jetbrains.mps.lang.editor.generator.internal.AbstractCellMenuPart_ReplaceNode_CustomNodeConcept; import org.jetbrains.mps.openapi.language.SAbstractConcept; import jetbrains.mps.openapi.editor.menus.EditorMenuDescriptor; import jetbrains.mps.nodeEditor.cellMenu.CellContext; import jetbrains.mps.lang.editor.menus.EditorMenuDescriptorBase; import jetbrains.mps.smodel.SNodePointer; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import org.jetbrains.mps.openapi.language.SConcept; import org.jetbrains.mps.openapi.language.SInterfaceConcept; /*package*/ class SuperClassSpecifier_EditorBuilder_a extends AbstractEditorBuilder { @NotNull private SNode myNode; public SuperClassSpecifier_EditorBuilder_a(@NotNull EditorContext context, @NotNull SNode node) { super(context); myNode = node; } @NotNull @Override public SNode getNode() { return myNode; } /*package*/ EditorCell createCell() { return createCollection_0(); } private EditorCell createCollection_0() { EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent()); editorCell.setCellId("Collection_9efcph_a"); editorCell.setBig(true); setCellContext(editorCell); editorCell.addEditorCell(createRefCell_0()); editorCell.addEditorCell(createComponent_0()); editorCell.addEditorCell(createComponent_1()); return editorCell; } private EditorCell createRefCell_0() { final SReferenceLink referenceLink = LINKS.target$mYQV; SReferenceCellProvider provider = new SReferenceCellProvider(getNode(), referenceLink, getEditorContext()) { protected EditorCell createReferenceCell(final SNode targetNode) { EditorCell cell = getUpdateSession().updateReferencedNodeCell(() -> new Inline_Builder0(getEditorContext(), getNode(), targetNode).createCell(), targetNode, LINKS.target$mYQV); CellUtil.setupIDeprecatableStyles(targetNode, cell); setSemanticNodeToCells(cell, getNode()); installDeleteActions_notnull_smartReference(cell); return cell; } @Override protected EditorCell createErrorCell(String error) { EditorCell_Error cell = new EditorCell_Error(getEditorContext(), getNode(), error, true); cell.setAction(CellActionType.DELETE, new CellAction_DeleteNode(getNode(), CellAction_DeleteNode.DeleteDirection.FORWARD)); cell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteNode(getNode(), CellAction_DeleteNode.DeleteDirection.BACKWARD)); return cell; } }; provider.setNoTargetText("<no target>"); EditorCell editorCell = provider.createCell(); if (editorCell.getSRole() == null) { editorCell.setReferenceCell(true); editorCell.setSRole(LINKS.target$mYQV); } editorCell.setTransformationMenuLookup(new NamedTransformationMenuLookup(LanguageRegistry.getInstance(getEditorContext().getRepository()), CONCEPTS.SuperClassSpecifier$ZV, "jetbrains.mps.kotlin.editor.SuperInterface_Specify_Transform")); editorCell.setSubstituteInfo(new CompositeSubstituteInfo(getEditorContext(), new ReferenceCellContext(getNode(), getNode(), referenceLink), new SubstituteInfoPartExt[]{new ReplaceWith_ISuperTypeSpecifier_cellMenu_9efcph_a0a0(), new SChildSubstituteInfoPartEx(editorCell)})); Iterable<SNode> referenceAttributes = SNodeOperations.ofConcept(new IAttributeDescriptor.AllAttributes().list(myNode), CONCEPTS.LinkAttribute$v_); Iterable<SNode> currentReferenceAttributes = Sequence.fromIterable(referenceAttributes).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return Objects.equals(LinkAttribute__BehaviorDescriptor.getLink_id1avfQ4BEFo6.invoke(it), referenceLink); } }); if (Sequence.fromIterable(currentReferenceAttributes).isNotEmpty()) { EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext()); return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentReferenceAttributes).first(), AttributeKind.REFERENCE, editorCell); } else return editorCell; } /*package*/ static class Inline_Builder0 extends AbstractEditorBuilder { @NotNull private SNode myNode; private SNode myReferencingNode; /*package*/ Inline_Builder0(@NotNull EditorContext context, SNode referencingNode, @NotNull SNode node) { super(context); myReferencingNode = referencingNode; myNode = node; } /*package*/ EditorCell createCell() { return createProperty_0(); } @NotNull @Override public SNode getNode() { return myNode; } private EditorCell createProperty_0() { getCellFactory().pushCellContext(); try { final SProperty property = PROPS.name$MnvL; getCellFactory().setPropertyInfo(new SPropertyInfo(myNode, property)); EditorCell_Property editorCell = EditorCell_Property.create(getEditorContext(), new SPropertyAccessor(myNode, property, true, false), myNode); editorCell.setDefaultText("<no name>"); editorCell.setCellId("property_name"); editorCell.setSubstituteInfo(new CompositeSubstituteInfo(getEditorContext(), new PropertyCellContext(myNode, property), new SubstituteInfoPartExt[]{new ReplaceWith_ISuperTypeSpecifier_cellMenu_9efcph_a0a0a0(), new SChildSubstituteInfoPartEx(editorCell)})); setCellContext(editorCell); Iterable<SNode> propertyAttributes = SNodeOperations.ofConcept(new IAttributeDescriptor.AllAttributes().list(myNode), CONCEPTS.PropertyAttribute$Gb); Iterable<SNode> currentPropertyAttributes = Sequence.fromIterable(propertyAttributes).where(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return Objects.equals(PropertyAttribute__BehaviorDescriptor.getProperty_id1avfQ4BBzOo.invoke(it), property); } }); if (Sequence.fromIterable(currentPropertyAttributes).isNotEmpty()) { EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext()); return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentPropertyAttributes).first(), AttributeKind.PROPERTY, editorCell); } else return editorCell; } finally { getCellFactory().popCellContext(); } } public static class ReplaceWith_ISuperTypeSpecifier_cellMenu_9efcph_a0a0a0 extends AbstractCellMenuPart_ReplaceNode_CustomNodeConcept { public ReplaceWith_ISuperTypeSpecifier_cellMenu_9efcph_a0a0a0() { } public SAbstractConcept getReplacementConcept() { return CONCEPTS.ISuperTypeSpecifier$PQ; } @Override protected EditorMenuDescriptor createEditorMenuDescriptor(CellContext cellContext, EditorContext editorContext) { return new EditorMenuDescriptorBase("replace node (custom node concept: " + "ISuperTypeSpecifier" + ")", new SNodePointer("r:5e60d3fe-71b1-4c17-b38e-424792223875(jetbrains.mps.kotlin.editor)", "1806979145073018437")); } } } public static class ReplaceWith_ISuperTypeSpecifier_cellMenu_9efcph_a0a0 extends AbstractCellMenuPart_ReplaceNode_CustomNodeConcept { public ReplaceWith_ISuperTypeSpecifier_cellMenu_9efcph_a0a0() { } public SAbstractConcept getReplacementConcept() { return CONCEPTS.ISuperTypeSpecifier$PQ; } @Override protected EditorMenuDescriptor createEditorMenuDescriptor(CellContext cellContext, EditorContext editorContext) { return new EditorMenuDescriptorBase("replace node (custom node concept: " + "ISuperTypeSpecifier" + ")", new SNodePointer("r:5e60d3fe-71b1-4c17-b38e-424792223875(jetbrains.mps.kotlin.editor)", "1752885245462907936")); } } private EditorCell createComponent_0() { EditorCell editorCell = getCellFactory().createEditorComponentCell(myNode, "jetbrains.mps.kotlin.editor.TypeArguments_Component"); return editorCell; } private EditorCell createComponent_1() { EditorCell editorCell = getCellFactory().createEditorComponentCell(myNode, "jetbrains.mps.kotlin.editor.DelegateComponent"); return editorCell; } private static final class LINKS { /*package*/ static final SReferenceLink target$mYQV = MetaAdapterFactory.getReferenceLink(0x6b3888c1980244d8L, 0x8baff8e6c33ed689L, 0x2043bc8310b9b194L, 0x2043bc8310b9b195L, "target"); } private static final class CONCEPTS { /*package*/ static final SConcept SuperClassSpecifier$ZV = MetaAdapterFactory.getConcept(0x6b3888c1980244d8L, 0x8baff8e6c33ed689L, 0x2043bc8310b9b194L, "jetbrains.mps.kotlin.structure.SuperClassSpecifier"); /*package*/ static final SConcept LinkAttribute$v_ = MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da51L, "jetbrains.mps.lang.core.structure.LinkAttribute"); /*package*/ static final SConcept PropertyAttribute$Gb = MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, "jetbrains.mps.lang.core.structure.PropertyAttribute"); /*package*/ static final SInterfaceConcept ISuperTypeSpecifier$PQ = MetaAdapterFactory.getInterfaceConcept(0x6b3888c1980244d8L, 0x8baff8e6c33ed689L, 0x2043bc8310c1c80cL, "jetbrains.mps.kotlin.structure.ISuperTypeSpecifier"); } private static final class PROPS { /*package*/ static final SProperty name$MnvL = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name"); } }
3e1364a04c2b9fb5e6d6a32d6e660c8dbf32afef
538
java
Java
src/main/java/com/stevezero/aws/api/exceptions/InvalidApiInvocation.java
fitzcairn/GoalTenderAWS
362faf6b1dd7da71a11a7913a4472c25f5812cca
[ "MIT" ]
1
2018-07-25T19:43:09.000Z
2018-07-25T19:43:09.000Z
src/main/java/com/stevezero/aws/api/exceptions/InvalidApiInvocation.java
fitzcairn/GoalTenderAWS
362faf6b1dd7da71a11a7913a4472c25f5812cca
[ "MIT" ]
null
null
null
src/main/java/com/stevezero/aws/api/exceptions/InvalidApiInvocation.java
fitzcairn/GoalTenderAWS
362faf6b1dd7da71a11a7913a4472c25f5812cca
[ "MIT" ]
null
null
null
28.315789
61
0.710037
8,188
package com.stevezero.aws.api.exceptions; import com.stevezero.aws.api.http.StatusCode; /** * Thrown when the invocation path is malformed. * Checked exception by design. */ public class InvalidApiInvocation extends ApiException { public InvalidApiInvocation() { this.message = "Malformed API call."; this.returnCode = StatusCode.BAD_REQUEST; } public InvalidApiInvocation(String path) { this.message = path + " is not a well-formed API call."; this.returnCode = StatusCode.BAD_REQUEST; } }
3e136574ad68e9f76e6cdcfcf1f2adc117f4c3f9
4,298
java
Java
src/main/java/org/orecruncher/dsurround/registry/acoustics/SimpleAcoustic.java
Tsoccerguy3/DynamicSurroundings
93040490bef8591a99c25aa154098a97ab271edd
[ "MIT" ]
125
2016-12-06T06:04:18.000Z
2022-03-21T00:47:23.000Z
src/main/java/org/orecruncher/dsurround/registry/acoustics/SimpleAcoustic.java
Tsoccerguy3/DynamicSurroundings
93040490bef8591a99c25aa154098a97ab271edd
[ "MIT" ]
762
2016-12-05T22:11:58.000Z
2022-03-27T16:27:52.000Z
src/main/java/org/orecruncher/dsurround/registry/acoustics/SimpleAcoustic.java
Tsoccerguy3/DynamicSurroundings
93040490bef8591a99c25aa154098a97ab271edd
[ "MIT" ]
78
2016-12-11T09:44:31.000Z
2022-03-27T16:44:55.000Z
31.372263
93
0.732434
8,189
/* * This file is part of Dynamic Surroundings, licensed under the MIT License (MIT). * * Copyright (c) OreCruncher * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.orecruncher.dsurround.registry.acoustics; import java.util.Random; import javax.annotation.Nonnull; import javax.annotation.Nullable; import net.minecraft.util.SoundEvent; import net.minecraft.util.math.Vec3d; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /* * A simple acoustic is one that is backed by a singular sound event. Most sounds * that are played in Minecraft can be considered a simple acoustic. */ @SideOnly(Side.CLIENT) public class SimpleAcoustic implements IAcoustic { protected SoundEvent sound; protected float volMin = 1f; protected float volMax = 1f; protected float pitchMin = 1f; protected float pitchMax = 1f; protected IOptions outputOptions; public SimpleAcoustic() { // Used in various builders } public SimpleAcoustic(@Nonnull final SoundEvent evt) { this.sound = evt; } @Override @Nonnull public String getName() { return this.sound != null ? this.sound.getSoundName().toString() : "<UNKNOWN>"; } @Override public void playSound(@Nonnull final ISoundPlayer player, @Nonnull final Vec3d location, @Nullable final EventType event, @Nullable final IOptions inputOptions) { // Special case for intentionally empty sounds (as opposed to fall back // sounds) if (this.sound == null) return; float volume = generateVolume(player.getRNG()); float pitch = generatePitch(player.getRNG()); if (inputOptions != null) { if (inputOptions.getGlidingVolume() > 0) { volume = this.volMin + (this.volMax - this.volMin) * inputOptions.getGlidingVolume(); } if (inputOptions.getGlidingPitch() > 0) { pitch = this.pitchMin + (this.pitchMax - this.pitchMin) * inputOptions.getGlidingPitch(); } volume *= inputOptions.getVolumeScale(); pitch *= inputOptions.getPitchScale(); } player.playSound(location, this.sound, volume, pitch, this.outputOptions); } private float generateVolume(@Nonnull final Random rng) { return randAB(rng, this.volMin, this.volMax); } private float generatePitch(@Nonnull final Random rng) { return randAB(rng, this.pitchMin, this.pitchMax); } private float randAB(@Nonnull final Random rng, final float a, final float b) { if (a >= b) return a; return a + rng.nextFloat() * (b - a); } public void setSound(@Nullable final SoundEvent sound) { this.sound = sound; } public void setVolMin(final float volMin) { this.volMin = volMin; } public void setVolMax(final float volMax) { this.volMax = volMax; } public void setPitchMin(final float pitchMin) { this.pitchMin = pitchMin; } public void setPitchMax(final float pitchMax) { this.pitchMax = pitchMax; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append(getName()).append('['); builder.append("vMin:").append(this.volMin).append(','); builder.append("vMax:").append(this.volMax).append(','); builder.append("pMin:").append(this.pitchMax).append(','); builder.append("pMax:").append(this.pitchMax); builder.append(']'); return builder.toString(); } }
3e1365a12b4e53110483aad976b030e9dcfd1d84
1,030
java
Java
origin-product/origin-product-dao/src/main/java/tech/aegean/next/origin/product/model/product/ProductLog.java
aegean-next/aegean-next-origin
0e540b2e33daeb005106153632ee65324914d425
[ "Apache-2.0" ]
null
null
null
origin-product/origin-product-dao/src/main/java/tech/aegean/next/origin/product/model/product/ProductLog.java
aegean-next/aegean-next-origin
0e540b2e33daeb005106153632ee65324914d425
[ "Apache-2.0" ]
null
null
null
origin-product/origin-product-dao/src/main/java/tech/aegean/next/origin/product/model/product/ProductLog.java
aegean-next/aegean-next-origin
0e540b2e33daeb005106153632ee65324914d425
[ "Apache-2.0" ]
null
null
null
35.517241
136
0.720388
8,190
/* * Copyright (c) 2021. Aegean Next OpenSource FrameWork * * Licensed under the Apache License, Version 2.0 (the "License"): you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. * * ----- ----- ----- ----- ----- * * Visit the project homepage for more information at https://next.aegean.tech, * Or see the code warehouse at https://github.com/aegean-next, https://gitee.com/aegean-next. */ package tech.aegean.next.origin.product.model.product; import tech.aegean.next.origin.base.model.BaseModel; /** * 商品变更日志 * @author RainyBlossom */ public class ProductLog extends BaseModel { }
3e13662abe9034e6872f316db90a81788625b6d8
834
java
Java
Corpus/birt/4906.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
1
2022-01-15T02:47:45.000Z
2022-01-15T02:47:45.000Z
Corpus/birt/4906.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
null
null
null
Corpus/birt/4906.java
JamesCao2048/BlizzardData
a524bec4f0d297bb748234eeb1c2fcdee3dce7d7
[ "MIT" ]
null
null
null
33.36
81
0.6247
8,191
/******************************************************************************* * Copyright (c) 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.model.simpleapi; import org.eclipse.birt.report.model.api.ListGroupHandle; import org.eclipse.birt.report.model.api.simpleapi.IListGroup; public class ListGroup extends Group implements IListGroup { public ListGroup( ListGroupHandle group ) { super( group ); } }
3e136890c79638007405aeb14cc0657e803e5b88
655
java
Java
microservicios-spring-distributed/microservicio-usuarios/src/main/java/co/jdti/example/microserviciousuarios/app/services/IStudentServices.java
jdavidtorres/spring-practice
7ef4c8d0c0a459d85d9ef5106b303534637309d5
[ "MIT" ]
null
null
null
microservicios-spring-distributed/microservicio-usuarios/src/main/java/co/jdti/example/microserviciousuarios/app/services/IStudentServices.java
jdavidtorres/spring-practice
7ef4c8d0c0a459d85d9ef5106b303534637309d5
[ "MIT" ]
null
null
null
microservicios-spring-distributed/microservicio-usuarios/src/main/java/co/jdti/example/microserviciousuarios/app/services/IStudentServices.java
jdavidtorres/spring-practice
7ef4c8d0c0a459d85d9ef5106b303534637309d5
[ "MIT" ]
3
2021-08-06T20:21:04.000Z
2022-02-07T14:47:24.000Z
26.2
74
0.792366
8,192
package co.jdti.example.microserviciousuarios.app.services; import co.jdti.example.commons.student.models.entities.StudentEntity; import co.jdti.example.microserviciocommons.services.ICommonServices; import java.util.List; import java.util.Optional; public interface IStudentServices extends ICommonServices<StudentEntity> { List<StudentEntity> findAll(); Optional<StudentEntity> findById(Long id); StudentEntity save(StudentEntity newStudent); void deleteById(Long id); List<StudentEntity> findByNameOrLastname(String term); List<StudentEntity> findAllByIds(List<Long> ids); void deleteCourseStudentById(Long id); }
3e13695f43758d39f3d383f607e666c38f269d31
8,264
java
Java
src/main/java/com/google/location/suplclient/asn1/supl2/supl_triggered_start/WLANAreaId.java
RogerioDoCarmo/supl-client
4ccc275f42a5894dd03f1acea8667fddbe021617
[ "Apache-2.0" ]
45
2019-01-16T23:49:27.000Z
2022-03-31T14:52:23.000Z
src/main/java/com/google/location/suplclient/asn1/supl2/supl_triggered_start/WLANAreaId.java
RogerioDoCarmo/supl-client
4ccc275f42a5894dd03f1acea8667fddbe021617
[ "Apache-2.0" ]
5
2019-04-11T18:38:28.000Z
2021-04-08T15:56:44.000Z
src/main/java/com/google/location/suplclient/asn1/supl2/supl_triggered_start/WLANAreaId.java
RogerioDoCarmo/supl-client
4ccc275f42a5894dd03f1acea8667fddbe021617
[ "Apache-2.0" ]
25
2019-04-10T22:16:10.000Z
2022-02-24T08:50:17.000Z
25.744548
108
0.682599
8,193
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.location.suplclient.asn1.supl2.supl_triggered_start; // Copyright 2008 Google Inc. All Rights Reserved. /* * This class is AUTOMATICALLY GENERATED. Do NOT EDIT. */ // // import com.google.location.suplclient.asn1.base.Asn1BitString; import com.google.location.suplclient.asn1.base.Asn1Object; import com.google.location.suplclient.asn1.base.Asn1Sequence; import com.google.location.suplclient.asn1.base.Asn1Tag; import com.google.location.suplclient.asn1.base.BitStream; import com.google.location.suplclient.asn1.base.BitStreamReader; import com.google.location.suplclient.asn1.base.SequenceComponent; import com.google.common.collect.ImmutableList; import java.util.Collection; import javax.annotation.Nullable; /** * */ public class WLANAreaId extends Asn1Sequence { // private static final Asn1Tag TAG_WLANAreaId = Asn1Tag.fromClassAndNumber(-1, -1); public WLANAreaId() { super(); } @Override @Nullable protected Asn1Tag getTag() { return TAG_WLANAreaId; } @Override protected boolean isTagImplicit() { return true; } public static Collection<Asn1Tag> getPossibleFirstTags() { if (TAG_WLANAreaId != null) { return ImmutableList.of(TAG_WLANAreaId); } else { return Asn1Sequence.getPossibleFirstTags(); } } /** * Creates a new WLANAreaId from encoded stream. */ public static WLANAreaId fromPerUnaligned(byte[] encodedBytes) { WLANAreaId result = new WLANAreaId(); result.decodePerUnaligned(new BitStreamReader(encodedBytes)); return result; } /** * Creates a new WLANAreaId from encoded stream. */ public static WLANAreaId fromPerAligned(byte[] encodedBytes) { WLANAreaId result = new WLANAreaId(); result.decodePerAligned(new BitStreamReader(encodedBytes)); return result; } @Override protected boolean isExtensible() { return true; } @Override public boolean containsExtensionValues() { for (SequenceComponent extensionComponent : getExtensionComponents()) { if (extensionComponent.isExplicitlySet()) return true; } return false; } private WLANAreaId.apMACAddressType apMACAddress_; public WLANAreaId.apMACAddressType getApMACAddress() { return apMACAddress_; } /** * @throws ClassCastException if value is not a WLANAreaId.apMACAddressType */ public void setApMACAddress(Asn1Object value) { this.apMACAddress_ = (WLANAreaId.apMACAddressType) value; } public WLANAreaId.apMACAddressType setApMACAddressToNewInstance() { apMACAddress_ = new WLANAreaId.apMACAddressType(); return apMACAddress_; } @Override public Iterable<? extends SequenceComponent> getComponents() { ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder(); builder.add(new SequenceComponent() { Asn1Tag tag = Asn1Tag.fromClassAndNumber(2, 0); @Override public boolean isExplicitlySet() { return getApMACAddress() != null; } @Override public boolean hasDefaultValue() { return false; } @Override public boolean isOptional() { return false; } @Override public Asn1Object getComponentValue() { return getApMACAddress(); } @Override public void setToNewInstance() { setApMACAddressToNewInstance(); } @Override public Collection<Asn1Tag> getPossibleFirstTags() { return tag == null ? WLANAreaId.apMACAddressType.getPossibleFirstTags() : ImmutableList.of(tag); } @Override public Asn1Tag getTag() { return tag; } @Override public boolean isImplicitTagging() { return true; } @Override public String toIndentedString(String indent) { return "apMACAddress : " + getApMACAddress().toIndentedString(indent); } }); return builder.build(); } @Override public Iterable<? extends SequenceComponent> getExtensionComponents() { ImmutableList.Builder<SequenceComponent> builder = ImmutableList.builder(); return builder.build(); } // Copyright 2008 Google Inc. All Rights Reserved. /* * This class is AUTOMATICALLY GENERATED. Do NOT EDIT. */ // /** * */ public static class apMACAddressType extends Asn1BitString { // // defined bit positions, if any // setters // clearers private static final Asn1Tag TAG_apMACAddressType = Asn1Tag.fromClassAndNumber(-1, -1); public apMACAddressType() { super(); setMinSize(48); setMaxSize(48); } @Override @Nullable protected Asn1Tag getTag() { return TAG_apMACAddressType; } @Override protected boolean isTagImplicit() { return true; } public static Collection<Asn1Tag> getPossibleFirstTags() { if (TAG_apMACAddressType != null) { return ImmutableList.of(TAG_apMACAddressType); } else { return Asn1BitString.getPossibleFirstTags(); } } /** * Creates a new apMACAddressType from encoded stream. */ public static apMACAddressType fromPerUnaligned(byte[] encodedBytes) { apMACAddressType result = new apMACAddressType(); result.decodePerUnaligned(new BitStreamReader(encodedBytes)); return result; } /** * Creates a new apMACAddressType from encoded stream. */ public static apMACAddressType fromPerAligned(byte[] encodedBytes) { apMACAddressType result = new apMACAddressType(); result.decodePerAligned(new BitStreamReader(encodedBytes)); return result; } @Override public Iterable<BitStream> encodePerUnaligned() { return super.encodePerUnaligned(); } @Override public Iterable<BitStream> encodePerAligned() { return super.encodePerAligned(); } @Override public void decodePerUnaligned(BitStreamReader reader) { super.decodePerUnaligned(reader); } @Override public void decodePerAligned(BitStreamReader reader) { super.decodePerAligned(reader); } @Override public String toString() { return toIndentedString(""); } public String toIndentedString(String indent) { return "apMACAddressType = " + getValue() + ";\n"; } } @Override public Iterable<BitStream> encodePerUnaligned() { return super.encodePerUnaligned(); } @Override public Iterable<BitStream> encodePerAligned() { return super.encodePerAligned(); } @Override public void decodePerUnaligned(BitStreamReader reader) { super.decodePerUnaligned(reader); } @Override public void decodePerAligned(BitStreamReader reader) { super.decodePerAligned(reader); } @Override public String toString() { return toIndentedString(""); } public String toIndentedString(String indent) { StringBuilder builder = new StringBuilder(); builder.append("WLANAreaId = {\n"); final String internalIndent = indent + " "; for (SequenceComponent component : getComponents()) { if (component.isExplicitlySet()) { builder.append(internalIndent) .append(component.toIndentedString(internalIndent)); } } if (isExtensible()) { builder.append(internalIndent).append("...\n"); for (SequenceComponent component : getExtensionComponents()) { if (component.isExplicitlySet()) { builder.append(internalIndent) .append(component.toIndentedString(internalIndent)); } } } builder.append(indent).append("};\n"); return builder.toString(); } }
3e136b5293506f1584090ff263b1efcf0461a3c2
8,231
java
Java
eu.scasefp7.eclipse.servicecomposition/src/eu/scasefp7/eclipse/servicecomposition/importer/PythonImporter.java
s-case/web-service-composition
4af1baa98af96c034082e36d751ad33e711c3348
[ "Apache-2.0" ]
1
2016-08-13T06:57:40.000Z
2016-08-13T06:57:40.000Z
eu.scasefp7.eclipse.servicecomposition/src/eu/scasefp7/eclipse/servicecomposition/importer/PythonImporter.java
s-case/web-service-composition
4af1baa98af96c034082e36d751ad33e711c3348
[ "Apache-2.0" ]
null
null
null
eu.scasefp7.eclipse.servicecomposition/src/eu/scasefp7/eclipse/servicecomposition/importer/PythonImporter.java
s-case/web-service-composition
4af1baa98af96c034082e36d751ad33e711c3348
[ "Apache-2.0" ]
null
null
null
33.595918
97
0.658243
8,194
package eu.scasefp7.eclipse.servicecomposition.importer; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Platform; import org.osgi.framework.Bundle; import eu.scasefp7.eclipse.servicecomposition.Activator; import eu.scasefp7.eclipse.servicecomposition.transformer.Similarity.ComparableName; /** * <h1>PythonImporter</h1> * This class can be used to import services from Python files. * @author Manios Krasanakis */ public class PythonImporter extends Importer{ /** * <h1>PythonOperation</h1> * This class basically implements a different constructor to <code>Operation</code> * that allows variable generation from a Python function body */ public static class PythonOperation extends Operation{ /** * Generates an operation from the contents of Python function inside a file. * @param pythonImplementation * @param pythonFileName * @param domainList */ public PythonOperation(String pythonImplementation, String pythonFileName) { super(); domain = domainList.get(pythonFileName); if(!pythonFileName.isEmpty() && domain==null){ //throw new Exception("Domain "+domainName+" has not been declared"); domainList.put(pythonFileName, domain = new ApplicationDomain(pythonFileName)); } String retVariable = ""; for(String line : pythonImplementation.split("\n")){ if(line.trim().startsWith("def ")){ name = new ComparableName(line.substring(4, line.indexOf("(")).trim()); String args = line.substring(line.indexOf("(")+1, line.lastIndexOf(")")); for(String arg : args.split(",")){ if(!arg.trim().isEmpty()) try { inputs.add(new Argument(arg.trim(), "", "pythonParameter", false, false, null)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } int retIndex = line.indexOf("return "); if(retIndex!=-1){ retIndex += 6; int end = line.indexOf(";", retIndex); if(end==-1) retVariable = line.substring(retIndex).trim(); else retVariable = line.substring(retIndex, end).trim(); } int retIndex2 = line.indexOf("cost"); if(retIndex2!=-1){ retIndex2 += 8; int end = line.length()-2; if(end==-1){ float cost=Float.parseFloat(line.substring(retIndex2).trim()); accessInfo.getCommercialCostSchema().setCommercialCost(cost); } else{ float cost=Float.parseFloat(line.substring(retIndex2, end).trim()); accessInfo.getCommercialCostSchema().setCommercialCost(cost); } } int retIndex3 = line.indexOf("charge_type"); if(retIndex3!=-1){ retIndex3 += 15; int end = line.length()-2; if(end==-1){ String chargeType=line.substring(retIndex3).trim(); accessInfo.getCommercialCostSchema().setCostPaymentChargeType(chargeType); } else{ String chargeType=line.substring(retIndex3, end).trim(); accessInfo.getCommercialCostSchema().setCostPaymentChargeType(chargeType); } } int retIndex4 = line.indexOf("currency"); if(retIndex4!=-1){ retIndex4 += 12; int end = line.length()-2; if(end==-1){ String currency=line.substring(retIndex4).trim(); accessInfo.getCommercialCostSchema().setCommercialCostCurrency(currency); } else{ String currency=line.substring(retIndex4, end).trim(); accessInfo.getCommercialCostSchema().setCommercialCostCurrency(currency); } } int retIndex5 = line.indexOf("duration_in_days"); if(retIndex5!=-1){ retIndex5 += 20; int end = line.length()-2; if(end==-1){ int duration=Integer.parseInt(line.substring(retIndex5).trim()); accessInfo.getCommercialCostSchema().getTrialSchema().setDurationInDays(duration); } else{ int duration=Integer.parseInt(line.substring(retIndex5, end).trim()); accessInfo.getCommercialCostSchema().getTrialSchema().setDurationInDays(duration); } } int retIndex6 = line.indexOf("duration_in_usages"); if(retIndex6!=-1){ retIndex6 += 22; int end = line.length()-2; if(end==-1){ int duration=Integer.parseInt(line.substring(retIndex6).trim()); accessInfo.getCommercialCostSchema().getTrialSchema().setDurationInUsages(duration); } else{ int duration=Integer.parseInt(line.substring(retIndex6, end).trim()); accessInfo.getCommercialCostSchema().getTrialSchema().setDurationInUsages(duration); } } int retIndex7 = line.indexOf("license_name"); if(retIndex7!=-1){ retIndex7 += 16; int end = line.length()-2; if(end==-1){ String licence=line.substring(retIndex7).trim(); accessInfo.getLicense().setLicenseName(licence); } else{ String licence=line.substring(retIndex7, end).trim(); accessInfo.getLicense().setLicenseName(licence); } } } for(String var : retVariable.split(",")) try { outputs.add(new Argument(var.trim(), "", "pythonParameter", false, false,null)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(outputs.isEmpty()) try { outputs.add(new Argument(name+"Result", "", "pythonParameter", false, false,null)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * <h1>importPath</h1> * Traverses all folder contents (including sub-folders) and uses <code>importPythonAsOwl</code> * to import all Python functions from detected <i>.py</i> files. * @param path * @return * @throws Exception */ public static ArrayList<Operation> importPath(String path) throws Exception{ Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID); URL fileURL = bundle.getEntry(path); File file1=new File(FileLocator.resolve(fileURL).toURI()); File folder = new File(file1.getAbsolutePath()); if(folder.isFile()) return importPythonAsOwl(path); ArrayList<Operation> operations = new ArrayList<Operation>(); if(path.isEmpty()) return operations; File[] listOfFiles = folder.listFiles(); Arrays.sort(listOfFiles); for (File file : listOfFiles) if (file.isFile() && (file.getName().contains(".py"))) operations.addAll(importPath(path+file.getName())); for (File file : listOfFiles) if(file.isDirectory() && (file.getName()!=".") && (file.getName()!="..")) operations.addAll(importPath(path+file.getName()+"/")); return operations; } /** * <h1>importPythonAsOwl</h1> * Imports all Python file functions as operations. This function uses the appropriate * <code>Importer.OwlOperation</code> constructor for code and comments detected. * @param pythonPath : the path of the Python file * @return a list of operations that match the functions detected in the file * @throws Exception */ public static ArrayList<Operation> importPythonAsOwl(String pythonPath) throws Exception{ ArrayList<Operation> allOperations = new ArrayList<Operation>(); Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID); URL fileURL = bundle.getEntry(pythonPath); File file=new File(FileLocator.resolve(fileURL).toURI()); BufferedReader br = new BufferedReader(new FileReader(file.getAbsoluteFile())); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { if(line.startsWith("def ")){ String code = sb.toString(); sb = new StringBuilder(); if(!code.isEmpty()) allOperations.add(new PythonOperation(code, pythonPath)); } sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String code = sb.toString(); if(code!=null && code.contains("def ")) allOperations.add(new PythonOperation(code, pythonPath)); } finally { br.close(); } return allOperations; } }
3e136b697c1c8a17bf3131f092a6bd296fad85f9
2,631
java
Java
tools-common/src/main/java/cn/gjing/tools/common/result/PageResult.java
sybcnlh/tools
1e4801f7db81fc5030d46358c7347e685e3a604c
[ "MIT" ]
2
2020-06-23T07:23:35.000Z
2020-06-23T07:23:38.000Z
tools-common/src/main/java/cn/gjing/tools/common/result/PageResult.java
jiangxd0716/tools
e52e7218d177b1c8172dcfc1ea9899e8814ff263
[ "MIT" ]
null
null
null
tools-common/src/main/java/cn/gjing/tools/common/result/PageResult.java
jiangxd0716/tools
e52e7218d177b1c8172dcfc1ea9899e8814ff263
[ "MIT" ]
null
null
null
23.702703
119
0.59065
8,195
package cn.gjing.tools.common.result; import lombok.Data; import java.io.Serializable; import java.util.List; /** * 分页结果集 * @author Gjing **/ @Data public class PageResult<T> implements Serializable { /** * 数据 */ private List<T> data; /** * 总页数 */ private long totalPages; /** * 当前页数 */ private long currentPage; /** * 总条数 */ private long totalRows; /** * 每页条数 */ private long pageRows; private PageResult() { } /** * 构建分页结果 * * @param data page数据 * @param totalPages 总页数 * @param currentPage 当前页数 * @return PageResult * @param <T> 返回结果泛型 */ public static <T> PageResult<T> of(List<T> data, long totalPages, long currentPage) { PageResult<T> pageResult = new PageResult<>(); pageResult.setData(data); pageResult.setTotalPages(totalPages); pageResult.setCurrentPage(currentPage); return pageResult; } /** * 构建分页结果 * * @param data page数据 * @param totalPages 总页数 * @return PageResult * @param <T> 返回结果泛型 */ public static <T> PageResult<T> of(List<T> data, long totalPages) { PageResult<T> pageResult = new PageResult<>(); pageResult.setData(data); pageResult.setTotalPages(totalPages); return pageResult; } /** * 构建分页结果 * * @param data page数据 * @param totalPages 总页数 * @param currentPage 当前页数 * @param totalRows 总条数 * @param <T> 返回结果泛型 * @return PageResult */ public static <T> PageResult<T> of(List<T> data, long totalPages, long currentPage, long totalRows) { PageResult<T> pageResult = new PageResult<>(); pageResult.setData(data); pageResult.setTotalPages(totalPages); pageResult.setCurrentPage(currentPage); pageResult.setTotalRows(totalRows); return pageResult; } /** * 构建分页结果 * * @param data page数据 * @param totalPages 总页数 * @param currentPage 当前页数 * @param totalRows 总条数 * @param pageRows 每页条数 * @param <T> 返回结果泛型 * @return PageResult */ public static <T> PageResult<T> of(List<T> data, long totalPages, long currentPage, long totalRows,long pageRows) { PageResult<T> pageResult = new PageResult<>(); pageResult.setData(data); pageResult.setTotalPages(totalPages); pageResult.setCurrentPage(currentPage); pageResult.setTotalRows(totalRows); pageResult.setPageRows(pageRows); return pageResult; } }
3e136c7a14d4b1d7e61932a51d998318800efa21
7,886
java
Java
plugins/ldapservers/src/main/java/org/apache/directory/studio/ldapservers/wizards/NewServerWizard.java
mrod0101/directory-studio
37d3378f38d8347647a1402b560960a21e4dbbc7
[ "Apache-2.0" ]
89
2015-04-21T15:07:03.000Z
2022-03-19T11:45:14.000Z
plugins/ldapservers/src/main/java/org/apache/directory/studio/ldapservers/wizards/NewServerWizard.java
Munins-eye/directory-studio
5cbde8abeb04db2354a0c23ed4f92e92d97f9574
[ "Apache-2.0" ]
3
2018-04-16T19:45:33.000Z
2018-08-21T18:01:12.000Z
plugins/ldapservers/src/main/java/org/apache/directory/studio/ldapservers/wizards/NewServerWizard.java
Munins-eye/directory-studio
5cbde8abeb04db2354a0c23ed4f92e92d97f9574
[ "Apache-2.0" ]
54
2015-03-27T16:28:45.000Z
2022-02-25T16:54:28.000Z
34.467249
136
0.630179
8,196
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.directory.studio.ldapservers.wizards; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.directory.studio.common.core.jobs.StudioProgressMonitor; import org.apache.directory.studio.ldapservers.LdapServerAdapterExtensionsManager; import org.apache.directory.studio.ldapservers.LdapServersManager; import org.apache.directory.studio.ldapservers.model.LdapServer; import org.apache.directory.studio.ldapservers.model.LdapServerAdapterConfigurationPage; import org.apache.directory.studio.ldapservers.model.LdapServerAdapterExtension; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; /** * This class implements the new server wizard. * * @author <a href="mailto:nnheo@example.com">Apache Directory Project</a> */ public class NewServerWizard extends Wizard implements INewWizard { /** The wizard page */ private NewServerWizardSelectionPage adapterSelectionPage; private Map<String, NewServerWizardConfigurationPage> configurationPages = new HashMap<String, NewServerWizardConfigurationPage>(); /** * {@inheritDoc} */ public void addPages() { adapterSelectionPage = new NewServerWizardSelectionPage(); addPage( adapterSelectionPage ); List<LdapServerAdapterExtension> ldapServerAdapterExtensions = LdapServerAdapterExtensionsManager.getDefault() .getLdapServerAdapterExtensions(); for ( LdapServerAdapterExtension ldapServerAdapterExtension : ldapServerAdapterExtensions ) { String configurationPageClassName = ldapServerAdapterExtension.getConfigurationPageClassName(); if ( ( configurationPageClassName != null ) && ( !"".equals( configurationPageClassName ) ) ) //$NON-NLS-1$ { try { LdapServerAdapterConfigurationPage configurationPage = ldapServerAdapterExtension .getNewConfigurationPageInstance(); NewServerWizardConfigurationPage configurationWizardPage = new NewServerWizardConfigurationPage( configurationPage ); configurationPages.put( ldapServerAdapterExtension.getId(), configurationWizardPage ); addPage( configurationWizardPage ); } catch ( Exception e ) { e.printStackTrace(); } } } } /** * {@inheritDoc} */ public boolean performFinish() { // Getting server name and adapter extension final String serverName = adapterSelectionPage.getServerName(); final LdapServerAdapterExtension adapterExtension = adapterSelectionPage.getLdapServerAdapterExtension(); // Getting the configuration page (in any NewServerWizardConfigurationPage configurationPage = getConfigurationPage(); // Creating the new server final LdapServer server = new LdapServer(); server.setName( serverName ); server.setLdapServerAdapterExtension( adapterExtension ); // Saving the configuration page (is any) if ( configurationPage != null ) { configurationPage.saveConfiguration( server ); } try { getContainer().run( true, false, new IRunnableWithProgress() { public void run( IProgressMonitor monitor ) { // Creating a StudioProgressMonitor StudioProgressMonitor spm = new StudioProgressMonitor( monitor ); // Setting the title spm.beginTask( Messages.getString( "NewServerWizard.CreatingLdapServer" ), IProgressMonitor.UNKNOWN ); //$NON-NLS-1$ spm.subTask( Messages.getString( "NewServerWizard.CreatingServerFolder" ) ); //$NON-NLS-1$ // Adding the new server to the servers handler LdapServersManager.getDefault().addServer( server ); // Creating the folder for the new server LdapServersManager.createNewServerFolder( server ); try { // Letting the LDAP Server Adapter finish the creation of the server adapterExtension.getInstance().add( server, spm ); } catch ( Exception e ) { // Reporting the error to the progress monitor spm.reportError( e ); } // Reporting to the monitors that we're done spm.done(); } } ); } catch ( Exception e ) { // Will never occur } return true; } /** * {@inheritDoc} */ public void init( IWorkbench workbench, IStructuredSelection selection ) { setWindowTitle( Messages.getString( "NewServerWizard.NewLdapServer" ) ); //$NON-NLS-1$ setNeedsProgressMonitor( true ); } /** * {@inheritDoc} */ public IWizardPage getNextPage( IWizardPage page ) { IWizardPage configurationPage = getConfigurationPage(); if ( adapterSelectionPage.equals( page ) ) { return configurationPage; } return null; } /** * {@inheritDoc} */ public boolean canFinish() { if ( adapterSelectionPage.isPageComplete() ) { IWizardPage configurationPage = getConfigurationPage(); if ( configurationPage != null ) { return configurationPage.isPageComplete(); } else { return true; } } return false; } /** * Gets the configuration page corresponding to the currently * selected LDAP Server Adapter Extension. * * @return the configuration page corresponding to the currently * selected LDAP Server Adapter Extension. */ private NewServerWizardConfigurationPage getConfigurationPage() { LdapServerAdapterExtension ldapServerAdapterExtension = adapterSelectionPage .getLdapServerAdapterExtension(); if ( ldapServerAdapterExtension != null ) { String configurationPageClassName = ldapServerAdapterExtension.getConfigurationPageClassName(); if ( ( configurationPageClassName != null ) && ( !"".equals( configurationPageClassName ) ) ) //$NON-NLS-1$ { return configurationPages.get( ldapServerAdapterExtension.getId() ); } } return null; } }
3e136cf46f1679dc71ad9d73e686ef32635d8a38
779
java
Java
ogham-test-utils/src/main/java/fr/sii/ogham/testing/sms/simulator/bean/SimpleAddress.java
groupe-sii/ogham
cb303d2168a5f2a0bca69b4b5b92bdb3de90cfab
[ "Apache-2.0" ]
18
2016-04-28T10:19:30.000Z
2021-10-05T12:04:39.000Z
ogham-test-utils/src/main/java/fr/sii/ogham/testing/sms/simulator/bean/SimpleAddress.java
groupe-sii/ogham
cb303d2168a5f2a0bca69b4b5b92bdb3de90cfab
[ "Apache-2.0" ]
99
2015-08-13T13:24:27.000Z
2021-09-24T06:45:57.000Z
ogham-test-utils/src/main/java/fr/sii/ogham/testing/sms/simulator/bean/SimpleAddress.java
groupe-sii/ogham
cb303d2168a5f2a0bca69b4b5b92bdb3de90cfab
[ "Apache-2.0" ]
16
2015-09-08T09:21:22.000Z
2022-03-04T10:43:20.000Z
17.311111
70
0.646983
8,197
package fr.sii.ogham.testing.sms.simulator.bean; /** * Just provide field values * * @author Aurélien Baudet * */ public class SimpleAddress implements Address { private final String address; private final byte ton; private final byte npi; /** * @param address * the address (phone number, IP address or anything else) * @param ton * the {@link TypeOfNumber} * @param npi * the {@link NumberingPlanIndicator} */ public SimpleAddress(String address, byte ton, byte npi) { super(); this.address = address; this.ton = ton; this.npi = npi; } @Override public byte getTon() { return ton; } @Override public byte getNpi() { return npi; } @Override public String getAddress() { return address; } }
3e136d21110d521efb715492c9f85573c0ae2718
1,700
java
Java
sharding-proxy/src/test/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/text/TextResultSetRowPacketTest.java
hadoop835/sharding-jdbc
04571e42870e0447021605efdd0de70c8ae0ebce
[ "Apache-2.0" ]
1
2018-09-06T09:15:09.000Z
2018-09-06T09:15:09.000Z
sharding-proxy/src/test/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/text/TextResultSetRowPacketTest.java
zhongshan0525/sharding-sphere
399f92d68e22588365dfecb545cc0f645e59ca18
[ "Apache-2.0" ]
null
null
null
sharding-proxy/src/test/java/io/shardingsphere/proxy/transport/mysql/packet/command/query/text/TextResultSetRowPacketTest.java
zhongshan0525/sharding-sphere
399f92d68e22588365dfecb545cc0f645e59ca18
[ "Apache-2.0" ]
null
null
null
34.693878
80
0.737647
8,198
/* * Copyright 2016-2018 shardingsphere.io. * <p> * 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. * </p> */ package io.shardingsphere.proxy.transport.mysql.packet.command.query.text; import io.shardingsphere.proxy.transport.mysql.packet.MySQLPacketPayload; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public final class TextResultSetRowPacketTest { @Mock private MySQLPacketPayload payload; @Test public void assertWrite() { when(payload.readInt1()).thenReturn(1); when(payload.readStringLenenc()).thenReturn("value_a", null, "value_c"); TextResultSetRowPacket actual = new TextResultSetRowPacket(payload, 3); assertThat(actual.getSequenceId(), is(1)); actual.write(payload); verify(payload).writeStringLenenc("value_a"); verify(payload).writeStringLenenc("value_c"); verify(payload).writeInt1(0xfb); } }
3e136d355f9d7ac6e871e8a8e16ccc2fee6efbff
18,501
java
Java
services/core/java/com/android/server/wm/VrController.java
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
164
2015-01-05T16:49:11.000Z
2022-03-29T20:40:27.000Z
services/core/java/com/android/server/wm/VrController.java
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
127
2015-01-12T12:02:32.000Z
2021-11-28T08:46:25.000Z
services/core/java/com/android/server/wm/VrController.java
rio-31/android_frameworks_base-1
091a068a3288d27d77636708679dde58b7b7fd25
[ "Apache-2.0" ]
1,141
2015-01-01T22:54:40.000Z
2022-02-09T22:08:26.000Z
40.931416
100
0.650451
8,199
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.server.wm; import android.content.ComponentName; import android.os.Process; import android.service.vr.IPersistentVrStateCallbacks; import android.util.Slog; import android.util.proto.ProtoOutputStream; import android.util.proto.ProtoUtils; import com.android.server.LocalServices; import com.android.server.am.ActivityManagerService; import com.android.server.am.ProcessList; import com.android.server.am.VrControllerProto; import com.android.server.vr.VrManagerInternal; /** * Helper class for {@link ActivityManagerService} responsible for VrMode-related ActivityManager * functionality. * * <p>Specifically, this class is responsible for: * <ul> * <li>Adjusting the scheduling of VR render threads while in VR mode. * <li>Handling ActivityManager calls to set a VR or a 'persistent' VR thread. * <li>Tracking the state of ActivityManagerService's view of VR-related behavior flags. * </ul> * * <p>This is NOT the class that manages the system VR mode lifecycle. The class responsible for * handling everything related to VR mode state changes (e.g. the lifecycles of the associated * VrListenerService, VrStateCallbacks, VR HAL etc.) is VrManagerService. * * <p>This class is exclusively for use by ActivityManagerService. Do not add callbacks or other * functionality to this for things that belong in VrManagerService. */ final class VrController { private static final String TAG = "VrController"; // VR state flags. private static final int FLAG_NON_VR_MODE = 0; private static final int FLAG_VR_MODE = 1; private static final int FLAG_PERSISTENT_VR_MODE = 2; // Keep the enum lists in sync private static int[] ORIG_ENUMS = new int[] { FLAG_NON_VR_MODE, FLAG_VR_MODE, FLAG_PERSISTENT_VR_MODE, }; private static int[] PROTO_ENUMS = new int[] { VrControllerProto.FLAG_NON_VR_MODE, VrControllerProto.FLAG_VR_MODE, VrControllerProto.FLAG_PERSISTENT_VR_MODE, }; // Invariants maintained for mVrState // // Always true: // - Only a single VR-related thread will have elevated scheduling priorities at a time // across all threads in all processes (and for all possible running modes). // // Always true while FLAG_PERSISTENT_VR_MODE is set: // - An application has set a flag to run in persistent VR mode the next time VR mode is // entered. The device may or may not be in VR mode. // - mVrState will contain FLAG_PERSISTENT_VR_MODE // - An application may set a persistent VR thread that gains elevated scheduling // priorities via a call to setPersistentVrThread. // - Calls to set a regular (non-persistent) VR thread via setVrThread will fail, and // thread that had previously elevated its scheduling priority in this way is returned // to its normal scheduling priority. // // Always true while FLAG_VR_MODE is set: // - The current top application is running in VR mode. // - mVrState will contain FLAG_VR_MODE // // While FLAG_VR_MODE is set without FLAG_PERSISTENT_VR_MODE: // - The current top application may set one of its threads to run at an elevated // scheduling priority via a call to setVrThread. // // While FLAG_VR_MODE is set with FLAG_PERSISTENT_VR_MODE: // - The current top application may NOT set one of its threads to run at an elevated // scheduling priority via a call to setVrThread (instead, the persistent VR thread will // be kept if an application has set one). // // While mVrState == FLAG_NON_VR_MODE: // - Calls to setVrThread will fail. // - Calls to setPersistentVrThread will fail. // - No threads will have elevated scheduling priority for VR. // private int mVrState = FLAG_NON_VR_MODE; // The single VR render thread on the device that is given elevated scheduling priority. private int mVrRenderThreadTid = 0; private final Object mGlobalAmLock; private final IPersistentVrStateCallbacks mPersistentVrModeListener = new IPersistentVrStateCallbacks.Stub() { @Override public void onPersistentVrStateChanged(boolean enabled) { synchronized(mGlobalAmLock) { // Note: This is the only place where mVrState should have its // FLAG_PERSISTENT_VR_MODE setting changed. if (enabled) { setVrRenderThreadLocked(0, ProcessList.SCHED_GROUP_TOP_APP, true); mVrState |= FLAG_PERSISTENT_VR_MODE; } else { setPersistentVrRenderThreadLocked(0, true); mVrState &= ~FLAG_PERSISTENT_VR_MODE; } } } }; /** * Create new VrController instance. * * @param globalAmLock the global ActivityManagerService lock. */ public VrController(final Object globalAmLock) { mGlobalAmLock = globalAmLock; } /** * Called when ActivityManagerService receives its systemReady call during boot. */ public void onSystemReady() { VrManagerInternal vrManagerInternal = LocalServices.getService(VrManagerInternal.class); if (vrManagerInternal != null) { vrManagerInternal.addPersistentVrModeStateListener(mPersistentVrModeListener); } } /** * Called when ActivityManagerService's TOP_APP process has changed. * * <p>Note: This must be called with the global ActivityManagerService lock held. * * @param proc is the WindowProcessController of the process that entered or left the TOP_APP * scheduling group. */ public void onTopProcChangedLocked(WindowProcessController proc) { final int curSchedGroup = proc.getCurrentSchedulingGroup(); if (curSchedGroup == ProcessList.SCHED_GROUP_TOP_APP) { setVrRenderThreadLocked(proc.mVrThreadTid, curSchedGroup, true); } else { if (proc.mVrThreadTid == mVrRenderThreadTid) { clearVrRenderThreadLocked(true); } } } /** * Called when ActivityManagerService is switching VR mode for the TOP_APP process. * * @param record the ActivityRecord of the activity changing the system VR mode. * @return {@code true} if the VR state changed. */ public boolean onVrModeChanged(ActivityRecord record) { // This message means that the top focused activity enabled VR mode (or an activity // that previously set this has become focused). VrManagerInternal vrService = LocalServices.getService(VrManagerInternal.class); if (vrService == null) { // VR mode isn't supported on this device. return false; } boolean vrMode; ComponentName requestedPackage; ComponentName callingPackage; int userId; int processId = -1; boolean changed = false; synchronized (mGlobalAmLock) { vrMode = record.requestedVrComponent != null; requestedPackage = record.requestedVrComponent; userId = record.mUserId; callingPackage = record.info.getComponentName(); // Tell the VrController that a VR mode change is requested. changed = changeVrModeLocked(vrMode, record.app); if (record.app != null) { processId = record.app.getPid(); } } // Tell VrManager that a VR mode changed is requested, VrManager will handle // notifying all non-AM dependencies if needed. vrService.setVrMode(vrMode, requestedPackage, userId, processId, callingPackage); return changed; } /** * Called to set an application's VR thread. * * <p>This will fail if the system is not in VR mode, the system has the persistent VR flag set, * or the scheduling group of the thread is not for the current top app. If this succeeds, any * previous VR thread will be returned to a normal sheduling priority; if this fails, the * scheduling for the previous thread will be unaffected. * * <p>Note: This must be called with the global ActivityManagerService lock and the * mPidsSelfLocked object locks held. * * @param tid the tid of the thread to set, or 0 to unset the current thread. * @param pid the pid of the process owning the thread to set. * @param proc the WindowProcessController of the process owning the thread to set. */ public void setVrThreadLocked(int tid, int pid, WindowProcessController proc) { if (hasPersistentVrFlagSet()) { Slog.w(TAG, "VR thread cannot be set in persistent VR mode!"); return; } if (proc == null) { Slog.w(TAG, "Persistent VR thread not set, calling process doesn't exist!"); return; } if (tid != 0) { enforceThreadInProcess(tid, pid); } if (!inVrMode()) { Slog.w(TAG, "VR thread cannot be set when not in VR mode!"); } else { setVrRenderThreadLocked(tid, proc.getCurrentSchedulingGroup(), false); } proc.mVrThreadTid = (tid > 0) ? tid : 0; } /** * Called to set an application's persistent VR thread. * * <p>This will fail if the system does not have the persistent VR flag set. If this succeeds, * any previous VR thread will be returned to a normal sheduling priority; if this fails, * the scheduling for the previous thread will be unaffected. * * <p>Note: This must be called with the global ActivityManagerService lock and the * mPidsSelfLocked object locks held. * * @param tid the tid of the thread to set, or 0 to unset the current thread. * @param pid the pid of the process owning the thread to set. * @param proc the process owning the thread to set. */ public void setPersistentVrThreadLocked(int tid, int pid, WindowProcessController proc) { if (!hasPersistentVrFlagSet()) { Slog.w(TAG, "Persistent VR thread may only be set in persistent VR mode!"); return; } if (proc == null) { Slog.w(TAG, "Persistent VR thread not set, calling process doesn't exist!"); return; } if (tid != 0) { enforceThreadInProcess(tid, pid); } setPersistentVrRenderThreadLocked(tid, false); } /** * Return {@code true} when UI features incompatible with VR mode should be disabled. * * <p>Note: This must be called with the global ActivityManagerService lock held. */ public boolean shouldDisableNonVrUiLocked() { return mVrState != FLAG_NON_VR_MODE; } /** * Called when to update this VrController instance's state when the system VR mode is being * changed. * * <p>Note: This must be called with the global ActivityManagerService lock held. * * @param vrMode {@code true} if the system VR mode is being enabled. * @param proc the WindowProcessController of the process enabling the system VR mode. * * @return {@code true} if our state changed. */ private boolean changeVrModeLocked(boolean vrMode, WindowProcessController proc) { final int oldVrState = mVrState; // This is the only place where mVrState should have its FLAG_VR_MODE setting // changed. if (vrMode) { mVrState |= FLAG_VR_MODE; } else { mVrState &= ~FLAG_VR_MODE; } boolean changed = (oldVrState != mVrState); if (changed) { if (proc != null) { if (proc.mVrThreadTid > 0) { setVrRenderThreadLocked( proc.mVrThreadTid, proc.getCurrentSchedulingGroup(), false); } } else { clearVrRenderThreadLocked(false); } } return changed; } /** * Set the given thread as the new VR thread, and give it special scheduling priority. * * <p>If the current thread is this thread, do nothing. If the current thread is different from * the given thread, the current thread will be returned to a normal scheduling priority. * * @param newTid the tid of the thread to set, or 0 to unset the current thread. * @param suppressLogs {@code true} if any error logging should be disabled. * * @return the tid of the thread configured to run at the scheduling priority for VR * mode after this call completes (this may be the previous thread). */ private int updateVrRenderThreadLocked(int newTid, boolean suppressLogs) { if (mVrRenderThreadTid == newTid) { return mVrRenderThreadTid; } if (mVrRenderThreadTid > 0) { ActivityManagerService.scheduleAsRegularPriority(mVrRenderThreadTid, suppressLogs); mVrRenderThreadTid = 0; } if (newTid > 0) { mVrRenderThreadTid = newTid; ActivityManagerService.scheduleAsFifoPriority(mVrRenderThreadTid, suppressLogs); } return mVrRenderThreadTid; } /** * Set special scheduling for the given application persistent VR thread, if allowed. * * <p>This will fail if the system does not have the persistent VR flag set. If this succeeds, * any previous VR thread will be returned to a normal sheduling priority; if this fails, * the scheduling for the previous thread will be unaffected. * * @param newTid the tid of the thread to set, or 0 to unset the current thread. * @param suppressLogs {@code true} if any error logging should be disabled. * * @return the tid of the thread configured to run at the scheduling priority for VR * mode after this call completes (this may be the previous thread). */ private int setPersistentVrRenderThreadLocked(int newTid, boolean suppressLogs) { if (!hasPersistentVrFlagSet()) { if (!suppressLogs) { Slog.w(TAG, "Failed to set persistent VR thread, " + "system not in persistent VR mode."); } return mVrRenderThreadTid; } return updateVrRenderThreadLocked(newTid, suppressLogs); } /** * Set special scheduling for the given application VR thread, if allowed. * * <p>This will fail if the system is not in VR mode, the system has the persistent VR flag set, * or the scheduling group of the thread is not for the current top app. If this succeeds, any * previous VR thread will be returned to a normal sheduling priority; if this fails, the * scheduling for the previous thread will be unaffected. * * @param newTid the tid of the thread to set, or 0 to unset the current thread. * @param schedGroup the current scheduling group of the thread to set. * @param suppressLogs {@code true} if any error logging should be disabled. * * @return the tid of the thread configured to run at the scheduling priority for VR * mode after this call completes (this may be the previous thread). */ private int setVrRenderThreadLocked(int newTid, int schedGroup, boolean suppressLogs) { boolean inVr = inVrMode(); boolean inPersistentVr = hasPersistentVrFlagSet(); if (!inVr || inPersistentVr || schedGroup != ProcessList.SCHED_GROUP_TOP_APP) { if (!suppressLogs) { String reason = "caller is not the current top application."; if (!inVr) { reason = "system not in VR mode."; } else if (inPersistentVr) { reason = "system in persistent VR mode."; } Slog.w(TAG, "Failed to set VR thread, " + reason); } return mVrRenderThreadTid; } return updateVrRenderThreadLocked(newTid, suppressLogs); } /** * Unset any special scheduling used for the current VR render thread, and return it to normal * scheduling priority. * * @param suppressLogs {@code true} if any error logging should be disabled. */ private void clearVrRenderThreadLocked(boolean suppressLogs) { updateVrRenderThreadLocked(0, suppressLogs); } /** * Check that the given tid is running in the process for the given pid, and throw an exception * if not. */ private void enforceThreadInProcess(int tid, int pid) { if (!Process.isThreadInProcess(pid, tid)) { throw new IllegalArgumentException("VR thread does not belong to process"); } } /** * True when the system is in VR mode. */ private boolean inVrMode() { return (mVrState & FLAG_VR_MODE) != 0; } /** * True when the persistent VR mode flag has been set. * * Note: Currently this does not necessarily mean that the system is in VR mode. */ private boolean hasPersistentVrFlagSet() { return (mVrState & FLAG_PERSISTENT_VR_MODE) != 0; } @Override public String toString() { return String.format("[VrState=0x%x,VrRenderThreadTid=%d]", mVrState, mVrRenderThreadTid); } void writeToProto(ProtoOutputStream proto, long fieldId) { final long token = proto.start(fieldId); ProtoUtils.writeBitWiseFlagsToProtoEnum(proto, VrControllerProto.VR_MODE, mVrState, ORIG_ENUMS, PROTO_ENUMS); proto.write(VrControllerProto.RENDER_THREAD_ID, mVrRenderThreadTid); proto.end(token); } }
3e136eefdbafa71eec51c57a6b4b31bbf6401c36
373
java
Java
shiva-etl-ibatis/src/main/java/com/reizes/shiva/etl/ibatis/helper/QueryExecuteType.java
reizes/shiva
c0cb2f6080e2ce01b240bf812fd816932bfeb71e
[ "MIT" ]
null
null
null
shiva-etl-ibatis/src/main/java/com/reizes/shiva/etl/ibatis/helper/QueryExecuteType.java
reizes/shiva
c0cb2f6080e2ce01b240bf812fd816932bfeb71e
[ "MIT" ]
null
null
null
shiva-etl-ibatis/src/main/java/com/reizes/shiva/etl/ibatis/helper/QueryExecuteType.java
reizes/shiva
c0cb2f6080e2ce01b240bf812fd816932bfeb71e
[ "MIT" ]
null
null
null
14.92
45
0.587131
8,200
package com.reizes.shiva.etl.ibatis.helper; /** * Query 실행 타입 * @author reizes * @since 2009.9.24 */ public enum QueryExecuteType { SELECT(0), INSERT(1), UPDATE(2), DELETE(3); private final int type; QueryExecuteType(int type) { this.type = type; } /** * int값 반환 * @return - int */ public int intValue() { return type; } }
3e1371599d81ba437962351b61b9e7ca11deebf2
5,294
java
Java
app/src/main/java/com/beyond/popscience/widget/MenuManagerPop.java
sunhaiteng2016/iknow-android
b1aeec07a70953b776d0c113384b04cef3b36869
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/beyond/popscience/widget/MenuManagerPop.java
sunhaiteng2016/iknow-android
b1aeec07a70953b776d0c113384b04cef3b36869
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/beyond/popscience/widget/MenuManagerPop.java
sunhaiteng2016/iknow-android
b1aeec07a70953b776d0c113384b04cef3b36869
[ "Apache-2.0" ]
null
null
null
29.248619
123
0.673782
8,201
package com.beyond.popscience.widget; import android.content.Context; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import com.beyond.popscience.R; import com.beyond.popscience.frame.pojo.NavObj; import com.beyond.popscience.module.home.adapter.DragAdapter; import com.beyond.popscience.module.home.adapter.UnSubAdapter; import com.beyond.popscience.widget.draggridview.DragGridView; import java.util.ArrayList; import java.util.List; /** * Created by yao.cui on 2017/6/10. */ public class MenuManagerPop extends PopupWindow implements DragAdapter.IChangeListener,UnSubAdapter.IUnSubListener{ private Context mContext; private Fragment mFragment; private DragGridView mDgvSub; private GridView mGvNoSub;//为订阅 private DragAdapter mDragAdapter; private UnSubAdapter unSubAdapter; private IManagerLitener mManagerListener; private int canDragIndex;//设置从哪个位置可以拖拽 private List<NavObj> navSub = new ArrayList<>();//订阅 private List<NavObj> navUnSub = new ArrayList<>();//为订阅 private LinearLayout llPopTitle; private TextView tvOrderDelete; private ImageView ivClose; public MenuManagerPop(Fragment fragment,Context context, List<NavObj> navSub, List<NavObj> navUnSub, int canDragIndex){ init(context); this.mFragment = fragment; this.navSub = navSub; this.navUnSub = navUnSub; this.canDragIndex = canDragIndex; initMenuManager(); } private void init(Context context) { this.mContext = context; View rootView = LayoutInflater.from(context).inflate(R.layout.menu_manager_pop_layout, null); this.setContentView(rootView); this.setWidth(WindowManager.LayoutParams.MATCH_PARENT); this.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); this.setOutsideTouchable(false); this.setTouchable(true); mDgvSub = (DragGridView) rootView.findViewById(R.id.dgvSubscribe); mGvNoSub = (GridView) rootView.findViewById(R.id.gvNoSubscribe); llPopTitle=(LinearLayout)rootView.findViewById(R.id.llPopTitle); tvOrderDelete=(TextView)rootView.findViewById(R.id.tvOrderDelete); tvOrderDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { canOrder(); } }); ivClose=(ImageView)rootView.findViewById(R.id.ivClose); ivClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dismiss(); } }); } /** * 初始化已订阅标签 未订阅标签 */ private void initMenuManager(){ mDragAdapter = new DragAdapter(mFragment,navSub,canDragIndex); mDragAdapter.setDeleteListener(this); mDgvSub.setAdapter(mDragAdapter); mDgvSub.setCanDragIndex(canDragIndex);//从第6个开始可以拖拽 从0 开始 unSubAdapter = new UnSubAdapter(mFragment,navUnSub); mGvNoSub.setAdapter(unSubAdapter); unSubAdapter.setUnSubListener(this); } @Override public void onDelete(int position) { mDgvSub.removeDragImage(); unSubAdapter.add(navSub.get(position)); mDragAdapter.remove(position); mDragAdapter.notifyDataSetChanged(); //在操作数据之后调用 if (mManagerListener!= null){ mManagerListener.onChange(navSub); } } @Override public void onLongClick() { mDragAdapter.setIsShowDelete(true); mDragAdapter.notifyDataSetChanged(); if (mManagerListener != null){ mManagerListener.canManager(true); } } @Override public void onPositionChange(int oldPosition, int newPosition) { if (mManagerListener!= null){ mManagerListener.onChange(navSub); } } @Override public void onUnSubItemClick(int position) { mDragAdapter.add(unSubAdapter.getItem(position));//添加到已订阅 unSubAdapter.remove(position);//从为订阅中删除 //在移动数据之后调用 if (mManagerListener!= null){ mManagerListener.onChange(navSub); } } /** * 设置可排序删除 */ public void canOrder(){ DragGridView.dragResponseMS = 10; mDragAdapter.setIsShowDelete(true); mDragAdapter.notifyDataSetChanged(); } /** * 完成 * 不可拖拽排序 */ public void confirm(){ DragGridView.dragResponseMS = 700; mDragAdapter.setIsShowDelete(false); mDragAdapter.notifyDataSetChanged(); mDgvSub.removeDragImage(); } public void show(View parent) { this.showAsDropDown(parent); } public void setManagerListener(IManagerLitener listener){ this.mManagerListener = listener; } public interface IManagerLitener{ /** * 当前状态是否可编辑 * @param isEditable */ void canManager(boolean isEditable); void onChange(List<NavObj> navs); } }
3e137228749a16d3d1e3650d91a7b4c5609ab4af
9,557
java
Java
modules/runtime-info/src/main/java/org/opencastproject/runtimeinfo/rest/StatusData.java
LinqLover/opencast
f803d6fa3cd805619c934a6d35b1306b1a9b3c4b
[ "ECL-2.0" ]
300
2017-06-19T09:49:57.000Z
2022-03-15T09:23:32.000Z
modules/runtime-info/src/main/java/org/opencastproject/runtimeinfo/rest/StatusData.java
LinqLover/opencast
f803d6fa3cd805619c934a6d35b1306b1a9b3c4b
[ "ECL-2.0" ]
1,907
2017-06-22T13:16:39.000Z
2022-03-31T22:34:24.000Z
modules/runtime-info/src/main/java/org/opencastproject/runtimeinfo/rest/StatusData.java
LinqLover/opencast
f803d6fa3cd805619c934a6d35b1306b1a9b3c4b
[ "ECL-2.0" ]
228
2017-06-19T12:57:09.000Z
2022-03-29T11:29:17.000Z
31.750831
114
0.651878
8,202
/** * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * * The Apereo Foundation licenses this file to you under the Educational * Community License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License * at: * * http://opensource.org/licenses/ecl2.txt * * 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.opencastproject.runtimeinfo.rest; import org.opencastproject.util.doc.rest.RestResponse; import javax.servlet.http.HttpServletResponse; /** * Represents a possible status result for an endpoint */ public class StatusData { /** * The HTTP response code. */ private int code; /** * The name of this status. */ private String name; /** * The description for this HTTP response. */ private String description; /** * The XML schema for the response, if applicable. */ private String xmlSchema; /** * A constructor that takes a RestResponse annotation type object and constructs a StatusData object. * * @param restResponse * a RestResponse annotation type object that stores a response code and its description * @throws IllegalArgumentException * if the response code is out of range (e.g. &lt;100 or &gt;1100) */ public StatusData(RestResponse restResponse) throws IllegalArgumentException { this(restResponse.responseCode(), restResponse.description()); } /** * A constructor that takes a HTTP response code and a description for this response, and an XML schema for the * response and constructs a StatusData object. A reference of response code constants can be found in <a * href="http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html" * >javax.servlet.http.HttpServletResponse</a>. * * @param code * a HTTP response code * @param description * a description of the response * @throws IllegalArgumentException * if code is out of range (e.g. &lt;100 or &gt;1100) */ public StatusData(int code, String description, String xmlSchema) throws IllegalArgumentException { if (code < 100 || code > 1100) { throw new IllegalArgumentException("Code (" + code + ") is outside of the valid range: 100-1100."); } this.code = code; name = findName(code); if (description.isEmpty()) { this.description = null; } else { this.description = description; } this.xmlSchema = xmlSchema; } /** * A constructor that takes a HTTP response code and a description for this response and constructs a StatusData * object. A reference of response code constants can be found in <a * href="http://download.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html" * >javax.servlet.http.HttpServletResponse</a>. * * @param code * a HTTP response code * @param description * a description of the response * @throws IllegalArgumentException * if code is out of range (e.g. &lt;100 or &gt; 1100) */ public StatusData(int code, String description) throws IllegalArgumentException { this(code, description, null); } @Override /** * @return a string representation of this object */ public String toString() { return "SC:" + code + ":" + name; } /** * @return the response code of this status */ public int getCode() { return code; } /** * @return a string name of this status */ public String getName() { return name; } /** * @return a description of this status */ public String getDescription() { return description; } /** * This will resolve a human readable name for all known status codes. * * @param code * the status code * @return the name OR UNKNOWN if none found * @throws IllegalArgumentException * if the code is outside the valid range */ public static String findName(int code) throws IllegalArgumentException { if (code < 100 || code > 1100) { throw new IllegalArgumentException("Code (" + code + ") is outside of the valid range: 100-1100."); } // list from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes String result; switch (code) { // 1xx Informational case HttpServletResponse.SC_CONTINUE: // 100 result = "Continue"; break; case HttpServletResponse.SC_SWITCHING_PROTOCOLS: // 101 result = "Switching Protocols"; break; // 2xx Success case HttpServletResponse.SC_OK: // 200 result = "OK"; break; case HttpServletResponse.SC_CREATED: // 201 result = "Created"; break; case HttpServletResponse.SC_ACCEPTED: // 202 result = "Accepted"; break; case HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION: // 203 result = "Non-Authoritative Information"; break; case HttpServletResponse.SC_NO_CONTENT: // 204 result = "No Content"; break; case HttpServletResponse.SC_RESET_CONTENT: // 205 result = "Reset Content"; break; case HttpServletResponse.SC_PARTIAL_CONTENT: // 206 result = "Partial Content"; break; // 3xx Redirection case HttpServletResponse.SC_MULTIPLE_CHOICES: // 300 result = "Multiple Choices"; break; case HttpServletResponse.SC_MOVED_PERMANENTLY: // 301 result = "Moved Permanently"; break; case HttpServletResponse.SC_MOVED_TEMPORARILY: // 302 result = "Found"; break; case HttpServletResponse.SC_SEE_OTHER: // 303 result = "See Other"; break; case HttpServletResponse.SC_NOT_MODIFIED: // 304 result = "Not Modified"; break; case HttpServletResponse.SC_USE_PROXY: // 305 result = "Use Proxy"; break; case HttpServletResponse.SC_TEMPORARY_REDIRECT: // 307 result = "Temporary Redirect"; break; // 4xx Client Error case HttpServletResponse.SC_BAD_REQUEST: // 400 result = "Bad Request"; break; case HttpServletResponse.SC_UNAUTHORIZED: // 401 result = "Unauthorized"; break; case HttpServletResponse.SC_PAYMENT_REQUIRED: // 402 result = "Payment Required"; break; case HttpServletResponse.SC_FORBIDDEN: // 403 result = "Forbidden"; break; case HttpServletResponse.SC_NOT_FOUND: // 404 result = "Not Found"; break; case HttpServletResponse.SC_METHOD_NOT_ALLOWED: // 405 result = "Method Not Allowed"; break; case HttpServletResponse.SC_NOT_ACCEPTABLE: // 406 result = "Not Acceptable"; break; case HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED: // 407 result = "Proxy Authentication Required"; break; case HttpServletResponse.SC_REQUEST_TIMEOUT: // 408 result = "Request Timeout"; break; case HttpServletResponse.SC_CONFLICT: // 409 result = "Conflict"; break; case HttpServletResponse.SC_GONE: // 410 result = "Gone"; break; case HttpServletResponse.SC_LENGTH_REQUIRED: // 411 result = "Length Required"; break; case HttpServletResponse.SC_PRECONDITION_FAILED: // 412 result = "Precondition Failed"; break; case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE: // 413 result = "Request Entity Too Large"; break; case HttpServletResponse.SC_REQUEST_URI_TOO_LONG: // 414 result = "Request URI Too Long"; break; case HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE: // 415 result = "Unsupported Media Type"; break; case HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE: // 416 result = "Requested Range Not Satisfiable"; break; case HttpServletResponse.SC_EXPECTATION_FAILED: // 417 result = "Expectation Failed"; break; // 5xx Server Error case HttpServletResponse.SC_INTERNAL_SERVER_ERROR: // 500 result = "Internal Server Error"; break; case HttpServletResponse.SC_NOT_IMPLEMENTED: // 501 result = "Not Implemented"; break; case HttpServletResponse.SC_BAD_GATEWAY: // 502 result = "Bad Gateway"; break; case HttpServletResponse.SC_SERVICE_UNAVAILABLE: // 503 result = "Service Unavailable"; break; case HttpServletResponse.SC_GATEWAY_TIMEOUT: // 504 result = "Gateway Timeout"; break; case HttpServletResponse.SC_HTTP_VERSION_NOT_SUPPORTED: // 505 result = "Version Not Supported"; break; default: result = "UNKNOWN"; } return result; } /** * @return the xmlSchema */ public String getXmlSchema() { return xmlSchema; } /** * @param xmlSchema * the xmlSchema to set */ public void setXmlSchema(String xmlSchema) { this.xmlSchema = xmlSchema; } }
3e13727caa49119e0c62a3aeaa253be64a72b151
5,138
java
Java
src/test/java/loghub/senders/TestFile.java
asyd/LogHub
df98b281d31a59428f1ca499dd41d40090441a43
[ "Apache-2.0" ]
null
null
null
src/test/java/loghub/senders/TestFile.java
asyd/LogHub
df98b281d31a59428f1ca499dd41d40090441a43
[ "Apache-2.0" ]
null
null
null
src/test/java/loghub/senders/TestFile.java
asyd/LogHub
df98b281d31a59428f1ca499dd41d40090441a43
[ "Apache-2.0" ]
null
null
null
30.951807
130
0.645971
8,203
package loghub.senders; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collections; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Semaphore; import java.util.function.Consumer; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import loghub.ConnectionContext; import loghub.Event; import loghub.LogUtils; import loghub.Stats; import loghub.Tools; import loghub.configuration.Properties; import loghub.encoders.StringField; import lombok.var; public class TestFile { /** * Allows to check that asynchronous acknowledge is indeed being called * @author Fabrice Bacchella * */ private class BlockingConnectionContext extends ConnectionContext<Semaphore> { Semaphore lock = new Semaphore(1); BlockingConnectionContext() { lock.drainPermits(); } @Override public Semaphore getLocalAddress() { return lock; } @Override public Semaphore getRemoteAddress() { return lock; } @Override public void acknowledge() { lock.release(); } } private static Logger logger = LogManager.getLogger(); @BeforeClass static public void configure() throws IOException { Tools.configure(); logger = LogManager.getLogger(); LogUtils.setLevel(logger, Level.TRACE, "loghub.senders.File", "loghub.encoders.StringField"); } @Rule public TemporaryFolder folder; { try { folder = new TemporaryFolder(); } catch (Exception e) { e.printStackTrace(); throw e; } } private String outFile; private final ArrayBlockingQueue<Event> queue = new ArrayBlockingQueue<>(10); @Before public void reset() { Stats.reset(); } private File send(Consumer<File.Builder> prepare, long expectedSize, boolean close) throws IOException, InterruptedException { outFile = Paths.get(folder.getRoot().getCanonicalPath(), "file1").toAbsolutePath().toString(); StringField.Builder builder1 = StringField.getBuilder(); builder1.setFormat("${message%s}"); StringField sf = builder1.build(); File.Builder fb = File.getBuilder(); fb.setFileName(outFile); fb.setEncoder(sf); prepare.accept(fb); File fsend = fb.build(); fsend.setInQueue(queue); Assert.assertTrue(fsend.configure(new Properties(Collections.emptyMap()))); fsend.start(); Event ev = Event.emptyEvent(new BlockingConnectionContext()); ev.put("message", 1); queue.add(ev); ConnectionContext<Semaphore> ctxt = ev.getConnectionContext(); ctxt.getLocalAddress().acquire(); if (close) { fsend.stopSending(); Assert.assertEquals(expectedSize, new java.io.File(outFile).length()); } return fsend; } @Test(timeout=2000) public void testOk() throws IOException, InterruptedException { send(i -> i.setTruncate(true), 1, true); send(i -> i.setTruncate(true), 1, true); Assert.assertEquals(2L, Stats.sent.get()); } @Test(timeout=2000) public void testOkAppend() throws IOException, InterruptedException { send(i -> i.setTruncate(false), 1, true); send(i -> i.setTruncate(false), 2, true); Assert.assertEquals(2L, Stats.sent.get()); } @Test(timeout=2000) public void testOkSeparator() throws IOException, InterruptedException { send(i -> {i.setTruncate(true) ; i.setSeparator("\n");}, 2, true); send(i -> i.setTruncate(true), 1, true); Assert.assertEquals(2L, Stats.sent.get()); } @Test public void testBrokenFormatter() throws IOException, InterruptedException { outFile = Paths.get(folder.getRoot().getCanonicalPath(), "file1").toAbsolutePath().toString(); StringField.Builder builder1 = StringField.getBuilder(); builder1.setFormat("${"); StringField sf = builder1.build(); var builder = File.getBuilder(); builder.setFileName(outFile); builder.setEncoder(sf); File fsend = builder.build(); fsend.setInQueue(queue); Assert.assertFalse(fsend.configure(new Properties(Collections.emptyMap()))); } @Test() public void testFailing() throws IOException, InterruptedException { File fsend = send(i -> {}, -1, false); new java.io.File(fsend.getName()).setWritable(false, false); Files.setPosixFilePermissions(Paths.get(fsend.getFileName()), Collections.emptySet()); Event ev = Tools.getEvent(); ev.put("message", 2); fsend.close(); fsend.send(ev); Thread.sleep(100); Assert.assertEquals(1L, Stats.failed.get()); } }
3e137303b9ba51e5a606a304a52f3585c10e3ce7
8,835
java
Java
src/main/java/net/bither/viewsystem/froms/SignMessagePanel.java
bitcoinboy/bither
2d0931586cde6df84142c7f3225e3ad410955541
[ "Apache-2.0" ]
66
2015-01-07T05:35:58.000Z
2022-03-05T07:00:48.000Z
src/main/java/net/bither/viewsystem/froms/SignMessagePanel.java
bitcoinboy/bither
2d0931586cde6df84142c7f3225e3ad410955541
[ "Apache-2.0" ]
11
2015-02-18T10:34:19.000Z
2020-05-10T14:42:08.000Z
src/main/java/net/bither/viewsystem/froms/SignMessagePanel.java
bitcoinboy/bither
2d0931586cde6df84142c7f3225e3ad410955541
[ "Apache-2.0" ]
59
2015-01-07T05:36:05.000Z
2021-12-11T11:19:47.000Z
32.127273
109
0.634182
8,204
/* * * Copyright 2014 http://Bither.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * / */ package net.bither.viewsystem.froms; import com.google.common.base.Optional; import net.bither.BitherUI; import net.bither.bitherj.core.Address; import net.bither.bitherj.crypto.SecureCharSequence; import net.bither.fonts.AwesomeIcon; import net.bither.languages.MessageKey; import net.bither.viewsystem.TextBoxes; import net.bither.viewsystem.action.TextTransfer; import net.bither.viewsystem.base.AccessibilityDecorator; import net.bither.viewsystem.base.Buttons; import net.bither.viewsystem.base.Labels; import net.bither.viewsystem.base.Panels; import net.bither.viewsystem.components.ScrollBarUIDecorator; import net.bither.viewsystem.components.borders.TextBubbleBorder; import net.bither.viewsystem.themes.Themes; import net.miginfocom.swing.MigLayout; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.event.ActionEvent; public class SignMessagePanel extends WizardPanel { private Address address; private JLabel signingAddressLabel; private JLabel messageLabel; private JLabel signatureLabel; private JTextField signingAddress; private JTextArea signature; private JTextArea messageTextArea; private JPasswordField currentPassword; private JLabel spinner; JLabel reportLabel; public SignMessagePanel(Address address) { super(MessageKey.SIGN_MESSAGE_TITLE, AwesomeIcon.PENCIL); this.address = address; } @Override public void initialiseContent(JPanel panel) { panel.setLayout(new MigLayout( Panels.migXYLayout(), "[][][][]", // Column constraints "[][80][][30][30][20]" // Row constraints )); // Labels (also used in clipboard) signingAddressLabel = Labels.newBitcoinAddress(); messageLabel = Labels.newMessage(); signatureLabel = Labels.newSignature(); signingAddress = TextBoxes.newTextField(43); signingAddress.setText(address.getAddress()); messageTextArea = TextBoxes.newEnterMessage(); // The message is a wall of text so needs scroll bars in many cases messageTextArea.setBorder(null); // Message requires its own scroll pane JScrollPane messageScrollPane = new JScrollPane(); messageScrollPane.setOpaque(true); messageScrollPane.setBackground(Themes.currentTheme.dataEntryBackground()); messageScrollPane.setBorder(null); messageScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); messageScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); // View port requires special handling messageScrollPane.setViewportView(messageTextArea); messageScrollPane.getViewport().setBackground(Themes.currentTheme.dataEntryBackground()); messageScrollPane.setViewportBorder(new TextBubbleBorder(Themes.currentTheme.dataEntryBorder())); // Ensure we maintain the overall theme ScrollBarUIDecorator.apply(messageScrollPane, true); signature = TextBoxes.newReadOnlyLengthLimitedTextArea(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { } @Override public void removeUpdate(DocumentEvent e) { } @Override public void changedUpdate(DocumentEvent e) { } }, 5, 40); AccessibilityDecorator.apply(signature, MessageKey.SIGNATURE); // Add them to the panel panel.add(signingAddressLabel); panel.add(signingAddress, "growx,span 3,push,wrap"); panel.add(messageLabel); panel.add(messageScrollPane, "grow,span 3,push,wrap"); panel.add(Labels.newEnterPassword()); panel.add(getenterPasswordMaV(), "growx,span 3,wrap"); panel.add(Buttons.newSignMessageButton(getSignMessageAction()), "cell 1 3,align right"); // panel.add(Buttons.newCopyAllButton(getCopyClipboardAction()), "cell 2 3"); panel.add(Buttons.newClearAllButton(getClearAllAction()), "cell 3 3,wrap"); panel.add(signatureLabel); panel.add(signature, "grow,span 3,push,wrap"); reportLabel = Labels.newStatusLabel(Optional.<MessageKey>absent(), null, Optional.<Boolean>absent()); AccessibilityDecorator.apply(reportLabel, MessageKey.NOTES); panel.add(reportLabel, "growx,span 4"); } /** * @return A new action for signing the message */ private Action getSignMessageAction() { // Sign the message return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { signMessage(); } }; } /** * @return A new action for clearing the signing address, message text and signature */ private Action getClearAllAction() { // Clear the fields and set focus return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { signingAddress.setText(""); messageTextArea.setText(""); currentPassword.setText(""); signature.setText(""); reportLabel.setText(""); reportLabel.setIcon(null); // Reset focus signingAddress.requestFocusInWindow(); } }; } private JPanel getenterPasswordMaV() { JPanel panel = Panels.newPanel( new MigLayout( Panels.migXLayout(), // Layout "[][][][]", // Columns "[]" // Rows )); // Keep track of the credentials fields currentPassword = TextBoxes.newPassword(); // Provide an invisible tar pit spinner spinner = Labels.newSpinner(Themes.currentTheme.fadedText(), BitherUI.NORMAL_PLUS_ICON_SIZE); spinner.setVisible(false); // Bind a document listener to allow instant update of UI to matched passwords currentPassword.getDocument().addDocumentListener( new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { updateModel(); } @Override public void removeUpdate(DocumentEvent e) { updateModel(); } @Override public void changedUpdate(DocumentEvent e) { updateModel(); } /** * Trigger any UI updates */ private void updateModel() { // Reset the credentials background currentPassword.setBackground(Themes.currentTheme.dataEntryBackground()); } }); panel.add(currentPassword, "growx,h 32,push"); //panel.add(showButton, "shrink"); // Ensure the icon label is a size suitable for rotation panel.add(spinner, BitherUI.NORMAL_PLUS_ICON_SIZE_MIG + ",wrap"); return panel; } /** * Sign the message text with the address specified and update UI */ private void signMessage() { String messageText = messageTextArea.getText(); SecureCharSequence secureCharSequence = new SecureCharSequence(currentPassword.getPassword()); String signMessage = this.address.signMessage(messageText, secureCharSequence); signature.setText(signMessage); } /** * @return A new action for copying the view contents to the clipboard */ private Action getCopyClipboardAction() { return new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { TextTransfer textTransfer = new TextTransfer(); //getReceiveAddress textTransfer.setClipboardContents(signature.getText()); } }; } }
3e1373fd446224d41e86dbd26c48545e2eb8ae26
1,403
java
Java
src/edu/rosehulman/serg/smellbuster/app/SmellBuster.java
RhitSerg/SmellBuster
6fc7f885b6ea07f333645e049527668c826bd0b6
[ "MIT" ]
null
null
null
src/edu/rosehulman/serg/smellbuster/app/SmellBuster.java
RhitSerg/SmellBuster
6fc7f885b6ea07f333645e049527668c826bd0b6
[ "MIT" ]
null
null
null
src/edu/rosehulman/serg/smellbuster/app/SmellBuster.java
RhitSerg/SmellBuster
6fc7f885b6ea07f333645e049527668c826bd0b6
[ "MIT" ]
null
null
null
32.627907
84
0.717748
8,205
package edu.rosehulman.serg.smellbuster.app; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.WindowConstants; import edu.rosehulman.serg.smellbuster.gui.VersionInputScreenGUI; public class SmellBuster { public static void main(String[] args) throws Exception { try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } // // UIManager.setLookAndFeel("com.jtattoo.plaf.graphite.GraphiteLookAndFeel"); // // UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel"); // // UIManager.setLookAndFeel("com.jtattoo.plaf.acryl.AcrylLookAndFeel"); // // UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel"); // // UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel"); // // UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel"); // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } VersionInputScreenGUI frame = new VersionInputScreenGUI(); frame.setVisible(true); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); } }
3e1374444c07c5611b1e1489ce83a942dfaf8909
1,768
java
Java
common/src/main/java/io/openapitools/sample/time/CurrentTime.java
openapi-tools/seed-rest-server-jee7
6298df0255ea2a1e9ed2711908d68437ebf75ad1
[ "MIT" ]
3
2018-09-22T17:59:06.000Z
2020-12-17T13:54:10.000Z
common/src/main/java/io/openapitools/sample/time/CurrentTime.java
openapi-tools/seed-rest-server-jee7
6298df0255ea2a1e9ed2711908d68437ebf75ad1
[ "MIT" ]
8
2017-10-28T20:50:31.000Z
2019-05-20T04:46:23.000Z
common/src/main/java/io/openapitools/sample/time/CurrentTime.java
openapi-tools/seed-rest-server-jee7
6298df0255ea2a1e9ed2711908d68437ebf75ad1
[ "MIT" ]
null
null
null
26.38806
108
0.639706
8,206
package io.openapitools.sample.time; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; /** * A very simple way of controlling current time. * * can be used in tests for avoiding time related challenges and thus remove false positives in test. * to be used remotely the remote instance must expose an endpoint which allows the support of this feature. */ public class CurrentTime { private static ZonedDateTime time = ZonedDateTime.now(ZoneId.of("UTC")); private static boolean stopped; protected CurrentTime() { // no construction necessary except from derived usages } /** * @return current time to in UTC time, the time can be real or set as "virtual" current time */ public static ZonedDateTime nowAsZonedDateTime() { if (stopped) { return time; } return ZonedDateTime.now(ZoneId.of("UTC")); } /** * @return current time to in UTC time, the time can be real or set as "virtual" current time */ public static Instant now() { if (stopped) { return time.toInstant(); } return Instant.now(); } protected static void setTime(Instant instant) { time = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC")); stopped = false; } protected static void setTime(Instant instant, boolean stopTime) { time = ZonedDateTime.ofInstant(instant, ZoneId.of("UTC")); stopped = stopTime; } protected static void startTime() { stopped = false; } protected static void stopTime() { stopped = true; } protected static void reset() { time = ZonedDateTime.now(ZoneId.of("UTC")); stopped = false; } }
3e13745c026d9ea548c716dad976bca0c38946d5
533
java
Java
src/main/java/io/github/harha/rest/service/api/IOPCUASubscriptionService.java
Harha/IoT_Project_REST
da1d0f6d5587f13c7c323db0f3887cccb61905b8
[ "MIT" ]
1
2020-01-22T03:41:58.000Z
2020-01-22T03:41:58.000Z
src/main/java/io/github/harha/rest/service/api/IOPCUASubscriptionService.java
Harha/IoT_Project_REST
da1d0f6d5587f13c7c323db0f3887cccb61905b8
[ "MIT" ]
1
2020-09-02T06:37:51.000Z
2020-09-23T07:51:34.000Z
src/main/java/io/github/harha/rest/service/api/IOPCUASubscriptionService.java
Harha/IoT_Project_REST
da1d0f6d5587f13c7c323db0f3887cccb61905b8
[ "MIT" ]
2
2019-05-17T09:08:03.000Z
2020-06-07T09:39:26.000Z
35.533333
113
0.842402
8,207
package io.github.harha.rest.service.api; import java.util.List; import io.github.harha.rest.model.OPCUASubscription; public interface IOPCUASubscriptionService { List<OPCUASubscription> getSubscriptions(Integer nsIndex, String identifier, Integer serverId) throws Exception; void deleteSubscriptions(Integer nsIndex, String identifier, Integer serverId) throws Exception; void insertSubscription(OPCUASubscription subscription) throws Exception; void updateSubscription(OPCUASubscription subscription) throws Exception; }
3e13749360ab3ade1d1fc8441a1c0a6f0dcd32c1
1,739
java
Java
src/chapter04/section01/thread_4_1_6/project_1_MustUseMoreCondition_OK/MyService.java
yzrds/untitled
7c8759c2e1bfb409b5871ad88c30a7e8865953d6
[ "MIT" ]
266
2019-03-21T13:16:54.000Z
2022-03-30T03:24:46.000Z
src/chapter04/section01/thread_4_1_6/project_1_MustUseMoreCondition_OK/MyService.java
yzrds/untitled
7c8759c2e1bfb409b5871ad88c30a7e8865953d6
[ "MIT" ]
1
2019-02-02T09:15:15.000Z
2019-02-02T09:15:15.000Z
src/chapter04/section01/thread_4_1_6/project_1_MustUseMoreCondition_OK/MyService.java
yzrds/untitled
7c8759c2e1bfb409b5871ad88c30a7e8865953d6
[ "MIT" ]
92
2019-03-21T07:55:17.000Z
2021-12-17T02:35:54.000Z
27.171875
75
0.680851
8,208
package chapter04.section01.thread_4_1_6.project_1_MustUseMoreCondition_OK; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class MyService { private Lock lock = new ReentrantLock(); public Condition conditionA = lock.newCondition(); public Condition conditionB = lock.newCondition(); public void awaitA() { try { lock.lock(); System.out.println("begin awaitA时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); conditionA.await(); System.out.println(" end awaitA时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void awaitB() { try { lock.lock(); System.out.println("begin awaitB时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); conditionB.await(); System.out.println(" end awaitB时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } public void signalAll_A() { try { lock.lock(); System.out.println(" signalAll_A时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); conditionA.signalAll(); } finally { lock.unlock(); } } public void signalAll_B() { try { lock.lock(); System.out.println(" signalAll_B时间为" + System.currentTimeMillis() + " ThreadName=" + Thread.currentThread().getName()); conditionB.signalAll(); } finally { lock.unlock(); } } }
3e1374d32c5e6563ebd633d67fc02d55131354e2
12,749
java
Java
src/main/java/com/t3c/anchel/client/ui/FileInformation.java
t3ctechnologies/Anchel_Client
43582680bacf7e440c53be592caaa7c959a8a104
[ "MIT" ]
null
null
null
src/main/java/com/t3c/anchel/client/ui/FileInformation.java
t3ctechnologies/Anchel_Client
43582680bacf7e440c53be592caaa7c959a8a104
[ "MIT" ]
null
null
null
src/main/java/com/t3c/anchel/client/ui/FileInformation.java
t3ctechnologies/Anchel_Client
43582680bacf7e440c53be592caaa7c959a8a104
[ "MIT" ]
null
null
null
35.315789
108
0.665307
8,209
package com.t3c.anchel.client.ui; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.sql.Date; import java.sql.Timestamp; import java.util.List; import javax.swing.BoxLayout; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTabbedPane; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.tree.DefaultMutableTreeNode; import com.fasterxml.jackson.databind.JsonNode; import com.t3c.anchel.client.model.common.ResponseObject; import com.t3c.anchel.client.model.dashboard.FileDetailsDTO; import com.t3c.anchel.client.model.dashboard.JTableDto; import com.t3c.anchel.client.model.dashboard.SharedDetailsDto; import com.t3c.anchel.client.utils.consts.ApplicationConstants; import com.t3c.anchel.client.wsclient.controller.dashboard.DashboardController; import com.t3c.anchel.client.wsclient.controller.dashboard.ShareFileController; public class FileInformation { private JDialog frame; private JScrollPane scroll; private JPanel pane; private String username; private ResponseObject resp = null; private List<FileDetailsDTO> fileList = null; private List<SharedDetailsDto> shareList = null; private JTableDto tableDto; public FileInformation(String username, DefaultMutableTreeNode selectedNode, JTableDto tableDto) { this.username = username; this.tableDto = tableDto; initialize(selectedNode); } public void initialize(DefaultMutableTreeNode selectedNode) { frame = new JDialog(frame, "FILE INFO", true); frame.setIconImage( Toolkit.getDefaultToolkit().getImage(FileInformation.class.getResource(ApplicationConstants.ICON_IMG))); frame.setResizable(false); JTabbedPane tp = new JTabbedPane(); tp.setBounds(10, 29, 410, 287); frame.setSize(372, 353); frame.getContentPane().setLayout(null); JPanel pane1 = new JPanel(); tp.add("DETAILS", pane1); // FILE SHARED INFO START------------------ if (selectedNode.toString().equals("My Files")) { resp = new ShareFileController().shareFileDetails(username, tableDto.getUuid()); fileList = (List<FileDetailsDTO>) resp.getResponseObject(); if (fileList != null) { FileDetailsDTO dto1 = fileList.get(0); shareList = dto1.getShares(); pane = new JPanel(); pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS)); for (int i = 0; i < shareList.size(); i++) { SharedDetailsDto dto = shareList.get(i); JLabel label1 = new JLabel("FILENAME : " + dto.getName()); label1.setAlignmentX(frame.CENTER_ALIGNMENT); pane.add(label1); JLabel label2 = new JLabel("SHARED WITH : " + dto.getRecipient().getFirstName() + " " + dto.getRecipient().getLastName()); label2.setAlignmentX(frame.CENTER_ALIGNMENT); pane.add(label2); JLabel label3 = (new JLabel("EMAIL-ID : " + dto.getRecipient().getMail())); label3.setAlignmentX(frame.CENTER_ALIGNMENT); pane.add(label3); JLabel label4 = (new JLabel("SHARED ON : " + dto.getCreationDate())); label4.setAlignmentX(frame.CENTER_ALIGNMENT); pane.add(label4); JLabel label5 = (new JLabel("EXPIRE ON THE : " + dto.getExpirationDate())); label5.setAlignmentX(frame.CENTER_ALIGNMENT); pane.add(label5); JLabel label6 = (new JLabel("DOWNLOADED : " + dto.getDownloaded() + " Times")); label6.setAlignmentX(frame.CENTER_ALIGNMENT); pane.add(label6); JSeparator sep = new JSeparator(); pane.add(sep); } } scroll = new JScrollPane(pane); tp.add("SHARES", scroll); } // FILE SHARED INFO END------------------ // FILE DETAILS INFO START------------------ pane1.setLayout(new BoxLayout(pane1, BoxLayout.PAGE_AXIS)); JLabel emptyLabel4 = new JLabel(" "); emptyLabel4.setAlignmentX(pane1.CENTER_ALIGNMENT); pane1.add(emptyLabel4); JLabel emptyLabel5 = new JLabel(" "); emptyLabel5.setAlignmentX(pane1.CENTER_ALIGNMENT); pane1.add(emptyLabel5); JLabel emptyLabel6 = new JLabel(" "); emptyLabel6.setAlignmentX(pane1.CENTER_ALIGNMENT); pane1.add(emptyLabel6); JLabel label1 = new JLabel("FILENAME : " + tableDto.getName()); label1.setAlignmentX(frame.CENTER_ALIGNMENT); pane1.add(label1); JLabel emptyLabel = new JLabel(" "); emptyLabel.setAlignmentX(pane1.CENTER_ALIGNMENT); pane1.add(emptyLabel); JLabel label2 = new JLabel("FILE SIZE : " + tableDto.getSize()); label2.setAlignmentX(frame.CENTER_ALIGNMENT); pane1.add(label2); JLabel emptyLabel1 = new JLabel(" "); emptyLabel1.setAlignmentX(pane1.CENTER_ALIGNMENT); pane1.add(emptyLabel1); JLabel label3 = (new JLabel("FILE TYPE : " + tableDto.getType())); label3.setAlignmentX(frame.CENTER_ALIGNMENT); pane1.add(label3); JLabel emptyLabel2 = new JLabel(" "); emptyLabel2.setAlignmentX(pane1.CENTER_ALIGNMENT); pane1.add(emptyLabel2); JLabel label4 = (new JLabel("MODIFIED ON : " + tableDto.getModificationDate())); label4.setAlignmentX(frame.CENTER_ALIGNMENT); pane1.add(label4); // FILE DETAILS INFO END------------------ // FILE ACTIVITY INFO END------------------ JPanel pane2 = new JPanel(); pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS)); resp = new DashboardController().getFileActivity(tableDto, username); JsonNode rootNode = (JsonNode) resp.getResponseObject(); if (rootNode.isArray()) { scroll = new JScrollPane(pane2); tp.addTab("ACTIVITY", scroll); for (final JsonNode objNode : rootNode) { String type = objNode.get("type").textValue(); String activity = null; String dateInfo = null; String action = objNode.get("action").textValue(); long date11 = objNode.get("creationDate").asLong(); Timestamp ts = new Timestamp(date11); Date date = new Date(ts.getTime()); if (type.equals("DOCUMENT_ENTRY")) { if (action.equals("CREATE")) { activity = "You have uploaded a new file into your Personal Space."; dateInfo = "On : " + date.toString() + " | by You"; JLabel label9 = (new JLabel("FILE UPLOAD")); pane2.add(label9); JLabel label10 = (new JLabel(activity)); pane2.add(label10); JLabel label11 = (new JLabel(dateInfo)); pane2.add(label11); JSeparator sep = new JSeparator(); pane2.add(sep); } if (action.equals("UPDATE")) { activity = "You have edited this file from your Personal Space."; dateInfo = "On : " + date.toString() + " | by You"; JsonNode res = objNode.get("resource"); String oldNmae = res.get("name").textValue().toString(); JsonNode upres = objNode.get("resourceUpdated"); String newNmae = upres.get("name").textValue().toString(); JLabel label8 = (new JLabel("FILE UPDATE")); pane2.add(label8); JLabel label10 = (new JLabel(activity)); pane2.add(label10); JLabel label9 = (new JLabel( "FILE from " + oldNmae.toUpperCase() + " to " + newNmae.toUpperCase())); pane2.add(label9); JLabel label11 = (new JLabel(dateInfo)); pane2.add(label11); JLabel empty1 = new JLabel(" "); pane2.add(empty1); JSeparator sep = new JSeparator(); pane2.add(sep); } } if (type.equals("SHARE_ENTRY")) { JsonNode res = objNode.get("resource"); JsonNode rec = res.get("recipient"); String firstName = rec.get("firstName").textValue().toString(); String lastName = rec.get("lastName").textValue().toString(); if (action.equals("CREATE")) { activity = "You have shared this file with '" + firstName + " " + lastName + "'"; dateInfo = "On : " + date.toString() + " | by You"; JLabel label9 = (new JLabel("FILE SHARED")); pane2.add(label9); JLabel label10 = (new JLabel(activity)); pane2.add(label10); JLabel label11 = (new JLabel(dateInfo)); pane2.add(label11); JSeparator sep = new JSeparator(); pane2.add(sep); } if (action.equals("DOWNLOAD")) { activity = "Your shared file has downloaded by '" + firstName + " " + lastName + "'"; dateInfo = "On : " + date.toString() + " | '" + firstName + " " + lastName + "'"; JLabel label9 = (new JLabel("FILE DOWNLOAD")); pane2.add(label9); JLabel label10 = (new JLabel(activity)); pane2.add(label10); JLabel label11 = (new JLabel(dateInfo)); pane2.add(label11); JLabel empty1 = new JLabel(" "); pane2.add(empty1); JSeparator sep = new JSeparator(); pane2.add(sep); } if (action.equals("DELETE")) { activity = "Your shared file has deleted by '" + firstName + " " + lastName + "'"; dateInfo = "On : " + date.toString() + " | '" + firstName + " " + lastName + "'"; JLabel label9 = (new JLabel("FILE DELETION")); pane2.add(label9); JLabel label10 = (new JLabel(activity)); pane2.add(label10); JLabel label11 = (new JLabel(dateInfo)); pane2.add(label11); JLabel empty1 = new JLabel(" "); pane2.add(empty1); JSeparator sep = new JSeparator(); pane2.add(sep); } } if (type.equals("WORKGROUP_DOCUMENT")) { JsonNode grp = objNode.get("workGroup"); String name = grp.get("name").textValue().toString(); if (action.equals("CREATE")) { activity = "You have uploaded a new file into the Workgroup '" + name + "'."; dateInfo = "On : " + date.toString() + " | by You"; JLabel label9 = (new JLabel("FILE UPLOAD")); pane2.add(label9); JLabel label10 = (new JLabel(activity)); pane2.add(label10); JLabel label11 = (new JLabel(dateInfo)); pane2.add(label11); JSeparator sep = new JSeparator(); pane2.add(sep); } if (action.equals("UPDATE")) { activity = "You have edited this file from the Workgroup '" + name + "'."; dateInfo = "On : " + date.toString() + " | by You"; JsonNode res = objNode.get("resource"); String oldNmae = res.get("name").textValue().toString(); JsonNode upres = objNode.get("resourceUpdated"); String newNmae = upres.get("name").textValue().toString(); JLabel label9 = (new JLabel("FILE UPDATE")); pane2.add(label9); JLabel label10 = (new JLabel(activity)); pane2.add(label10); JLabel label8 = (new JLabel( "FILE from " + oldNmae.toUpperCase() + " to " + newNmae.toUpperCase())); pane2.add(label8); JLabel label11 = (new JLabel(dateInfo)); pane2.add(label11); JLabel empty1 = new JLabel(" "); pane2.add(empty1); JSeparator sep = new JSeparator(); pane2.add(sep); } if (action.equals("DOWNLOAD")) { activity = "You have downloaded this file from the Workgroup '" + name + "'."; dateInfo = "On : " + date.toString() + " | by You"; JLabel label9 = (new JLabel("FILE DOWNLOAD")); pane2.add(label9); JLabel label10 = (new JLabel(activity)); pane2.add(label10); JLabel label11 = (new JLabel(dateInfo)); pane2.add(label11); JLabel empty1 = new JLabel(" "); pane2.add(empty1); JSeparator sep = new JSeparator(); pane2.add(sep); } } } } JPanel panel = new JPanel(); panel.setBounds(0, 0, 367, 319); frame.getContentPane().add(panel); JLabel nameLable = new JLabel(tableDto.getName().toUpperCase()); nameLable.setFont(new Font("Times New Roman", Font.PLAIN, 15)); // nameLable.setAlignmentX(panel.RIGHT_ALIGNMENT); GroupLayout gl_panel = new GroupLayout(panel); gl_panel.setHorizontalGroup(gl_panel.createParallelGroup(Alignment.LEADING) .addGroup(gl_panel.createSequentialGroup().addContainerGap() .addGroup(gl_panel.createParallelGroup(Alignment.LEADING) .addComponent(tp, GroupLayout.DEFAULT_SIZE, 347, Short.MAX_VALUE) .addComponent(nameLable, GroupLayout.DEFAULT_SIZE, 347, Short.MAX_VALUE)) .addContainerGap())); gl_panel.setVerticalGroup(gl_panel.createParallelGroup(Alignment.TRAILING) .addGroup(gl_panel.createSequentialGroup().addContainerGap() .addComponent(nameLable, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(tp, GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE).addGap(2))); panel.setLayout(gl_panel); final Toolkit toolkit = Toolkit.getDefaultToolkit(); final Dimension screenSize = toolkit.getScreenSize(); final int x = (screenSize.width - frame.getWidth()) / 2; final int y = (screenSize.height - frame.getHeight()) / 2; frame.setLocation(x, y); frame.setVisible(true); frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE); } }
3e1375f24c978c3dc4b00b4880842770cdb37cc8
1,219
java
Java
src/java/com/echothree/control/user/item/common/form/CreateItemAliasChecksumTypeForm.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-09-01T08:39:01.000Z
2020-09-01T08:39:01.000Z
src/java/com/echothree/control/user/item/common/form/CreateItemAliasChecksumTypeForm.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
null
null
null
src/java/com/echothree/control/user/item/common/form/CreateItemAliasChecksumTypeForm.java
echothreellc/echothree
1744df7654097cc000e5eca32de127b5dc745302
[ "Apache-2.0" ]
1
2020-05-31T08:34:46.000Z
2020-05-31T08:34:46.000Z
35.852941
83
0.64397
8,210
// -------------------------------------------------------------------------------- // Copyright 2002-2021 Echo Three, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // -------------------------------------------------------------------------------- package com.echothree.control.user.item.common.form; import com.echothree.util.common.form.BaseForm; public interface CreateItemAliasChecksumTypeForm extends BaseForm { String getItemAliasChecksumTypeName(); void setItemAliasChecksumTypeName(String itemAliasChecksumTypeName); String getIsDefault(); void setIsDefault(String isDefault); String getSortOrder(); void setSortOrder(String sortOrder); }
3e13760e1e0dd666481f425b39f9ef755eca514c
540
java
Java
sso-client-core/src/main/java/io/github/byference/sso/client/authentication/OAuth2AuthenticationResult.java
byference/spring-security-sso
380aab6312130501b94f2d7e94aafac9fc9702d8
[ "MIT" ]
5
2019-03-18T01:16:59.000Z
2021-03-19T10:48:53.000Z
tiny-sso/tiny-sso-core/src/main/java/io/github/byference/sso/client/authentication/OAuth2AuthenticationResult.java
byference/tiny-frameworks
547f9f62a701b5709532356af055dafe4957e7b1
[ "Apache-2.0" ]
2
2020-07-06T13:56:08.000Z
2021-03-19T10:45:03.000Z
sso-client-core/src/main/java/io/github/byference/sso/client/authentication/OAuth2AuthenticationResult.java
byference/spring-security-sso
380aab6312130501b94f2d7e94aafac9fc9702d8
[ "MIT" ]
2
2019-05-08T06:41:30.000Z
2020-10-16T09:55:39.000Z
13.846154
54
0.598148
8,211
package io.github.byference.sso.client.authentication; import lombok.Data; /** * OAuth2AuthenticationResult * * @author byference * @since 2019/11/21 */ @Data public class OAuth2AuthenticationResult { /** * access_token */ private String access_token; /** * token_type */ private String token_type; /** * refresh_token */ private String refresh_token; /** * expires_in */ private String expires_in; /** * scope */ private String scope; }
3e137662baee5f3ed60db5b8d61f08a3a96ba6a4
260
java
Java
shadowsocks4j-common/src/main/java/io/github/zhenbianshu/shadowsocks4j/verify/method/Verifier.java
zhenbianshu/shadowSockz
2fae75a0f0fffc7c04d74077639d988b3cd28afd
[ "Apache-2.0" ]
2
2018-12-11T07:51:58.000Z
2018-12-11T22:55:27.000Z
shadowsocks4j-common/src/main/java/io/github/zhenbianshu/shadowsocks4j/verify/method/Verifier.java
zhenbianshu/shadowsocks4j
2fae75a0f0fffc7c04d74077639d988b3cd28afd
[ "Apache-2.0" ]
null
null
null
shadowsocks4j-common/src/main/java/io/github/zhenbianshu/shadowsocks4j/verify/method/Verifier.java
zhenbianshu/shadowsocks4j
2fae75a0f0fffc7c04d74077639d988b3cd28afd
[ "Apache-2.0" ]
1
2018-12-11T07:51:59.000Z
2018-12-11T07:51:59.000Z
23.636364
72
0.792308
8,212
package io.github.zhenbianshu.shadowsocks4j.verify.method; import io.github.zhenbianshu.shadowsocks4j.verify.request.VerifyContent; /** * created by zhenbianshu on 2018/12/1 */ public interface Verifier { boolean verify(VerifyContent verifyContent); }
3e1376f0a6cc9d058212a7a35c32345a850881d9
2,072
java
Java
src/main/java/org/jetbrains/plugins/template/api/data/BitbucketErrorMessage.java
arthas-choi/intellij-bitbucket
8f5821fdaf4c933abab1b4c7fb62f4fd58f72138
[ "Apache-2.0" ]
null
null
null
src/main/java/org/jetbrains/plugins/template/api/data/BitbucketErrorMessage.java
arthas-choi/intellij-bitbucket
8f5821fdaf4c933abab1b4c7fb62f4fd58f72138
[ "Apache-2.0" ]
null
null
null
src/main/java/org/jetbrains/plugins/template/api/data/BitbucketErrorMessage.java
arthas-choi/intellij-bitbucket
8f5821fdaf4c933abab1b4c7fb62f4fd58f72138
[ "Apache-2.0" ]
null
null
null
23.022222
140
0.653475
8,213
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.template.api.data; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; @SuppressWarnings("UnusedDeclaration") public class BitbucketErrorMessage { private String message; private List<Error> errors; @NotNull public String getMessage() { return message; } @NotNull public List<Error> getErrors() { if (errors == null) return Collections.emptyList(); return errors; } @NotNull public String getPresentableError() { if (errors == null) { return message; } else { StringBuilder s = new StringBuilder(); s.append(message); for (Error e : errors) { s.append(String.format("<br/>[%s; %s]%s: %s", e.resource, e.field, e.code, e.message)); } return s.toString(); } } public boolean containsReasonMessage(@NotNull String reason) { if (message == null) return false; return message.contains(reason); } public boolean containsErrorCode(@NotNull String code) { if (errors == null) return false; for (Error error : errors) { if (error.code != null && error.code.contains(code)) return true; } return false; } public boolean containsErrorMessage(@NotNull String message) { if (errors == null) return false; for (Error error : errors) { if (error.code != null && error.code.contains(message)) return true; } return false; } public static class Error { private String resource; private String field; private String code; private String message; @NotNull public String getResource() { return resource; } @Nullable public String getField() { return field; } @NotNull public String getCode() { return code; } @Nullable public String getMessage() { return message; } } }
3e1377053d7ae8cc18d3f6fb8b8b60bb401a80e2
204
java
Java
src/main/java/io/choerodon/notify/api/service/FileService.java
readme1988/notify-service
2aae0de7a04aacf859fbba9b5dc9f447bcdf0d6a
[ "Apache-2.0" ]
null
null
null
src/main/java/io/choerodon/notify/api/service/FileService.java
readme1988/notify-service
2aae0de7a04aacf859fbba9b5dc9f447bcdf0d6a
[ "Apache-2.0" ]
null
null
null
src/main/java/io/choerodon/notify/api/service/FileService.java
readme1988/notify-service
2aae0de7a04aacf859fbba9b5dc9f447bcdf0d6a
[ "Apache-2.0" ]
null
null
null
18.545455
56
0.79902
8,214
package io.choerodon.notify.api.service; import javax.servlet.http.HttpServletRequest; import java.util.List; public interface FileService { List<String> uploadFile(HttpServletRequest request); }
3e1377123c15816a3793e69dc9e034251da83ca6
644
java
Java
mod/pattern/src/main/com/thaiopensource/relaxng/pattern/BuiltinDatatypeBuilder.java
brand/jing-trang
7221c0290a90de8f6093aaebc7acf6e5ec28fd32
[ "BSD-3-Clause" ]
192
2015-04-12T01:10:52.000Z
2022-02-03T15:46:34.000Z
mod/pattern/src/main/com/thaiopensource/relaxng/pattern/BuiltinDatatypeBuilder.java
brand/jing-trang
7221c0290a90de8f6093aaebc7acf6e5ec28fd32
[ "BSD-3-Clause" ]
70
2015-06-23T04:17:54.000Z
2021-09-17T22:18:37.000Z
mod/pattern/src/main/com/thaiopensource/relaxng/pattern/BuiltinDatatypeBuilder.java
brand/jing-trang
7221c0290a90de8f6093aaebc7acf6e5ec28fd32
[ "BSD-3-Clause" ]
71
2015-04-13T10:30:15.000Z
2022-02-10T23:21:49.000Z
25.76
86
0.779503
8,215
package com.thaiopensource.relaxng.pattern; import org.relaxng.datatype.Datatype; import org.relaxng.datatype.DatatypeBuilder; import org.relaxng.datatype.DatatypeException; import org.relaxng.datatype.ValidationContext; class BuiltinDatatypeBuilder implements DatatypeBuilder { private final Datatype dt; BuiltinDatatypeBuilder(Datatype dt) { this.dt = dt; } public void addParameter(String name, String value, ValidationContext context) throws DatatypeException { throw new DatatypeException(SchemaBuilderImpl.localizer.message("builtin_param")); } public Datatype createDatatype() { return dt; } }
3e1377d61f08b2c8a48216c06f3f07a207bfc0d6
8,175
java
Java
src/main/java/DuelistMetrics/Server/models/tierScore/ScoredCard.java
adambennett/StS-Metrics-Server
36d56f1ea7b1950cd60b865283299e7d8e392e81
[ "MIT" ]
null
null
null
src/main/java/DuelistMetrics/Server/models/tierScore/ScoredCard.java
adambennett/StS-Metrics-Server
36d56f1ea7b1950cd60b865283299e7d8e392e81
[ "MIT" ]
1
2020-12-26T21:24:04.000Z
2020-12-26T21:24:04.000Z
src/main/java/DuelistMetrics/Server/models/tierScore/ScoredCard.java
adambennett/StS-Metrics-Server
36d56f1ea7b1950cd60b865283299e7d8e392e81
[ "MIT" ]
null
null
null
21.513158
80
0.63682
8,216
package DuelistMetrics.Server.models.tierScore; import javax.persistence.*; import java.util.*; @Entity @IdClass(ScoredCardKey.class) public class ScoredCard { @Id public String card_id; @Id public String pool_name; public String card_name; public Date lastUpdated; private float act0_delta; private float act1_delta; private float act2_delta; private float act3_delta; private float act0_win_rate; private float act1_win_rate; private float act2_win_rate; private float act3_win_rate; private int act0_wins; private int act1_wins; private int act2_wins; private int act3_wins; private int act0_losses; private int act1_losses; private int act2_losses; private int act3_losses; private int act0_score; private int act1_score; private int act2_score; private int act3_score; private int overall_score; private int position; private int a0_position; private int a1_position; private int a2_position; private int a3_position; private float percentile; private float a0_percentile; private float a1_percentile; private float a2_percentile; private float a3_percentile; public ScoredCard() {} public ScoredCard(String card_id, String pool_name) { this.card_id = card_id; this.pool_name = pool_name; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ScoredCard)) return false; ScoredCard that = (ScoredCard) o; return card_id.equals(that.card_id) && pool_name.equals(that.pool_name); } @Override public int hashCode() { return Objects.hash(card_id, pool_name); } public String getCard_id() { return card_id; } public void setCard_id(String card_id) { this.card_id = card_id; } public String getPool_name() { return pool_name; } public void setPool_name(String pool_name) { this.pool_name = pool_name; } public float getAct0_delta() { return act0_delta; } public void setAct0_delta(float act0_delta) { this.act0_delta = act0_delta; } public float getAct1_delta() { return act1_delta; } public void setAct1_delta(float act1_delta) { this.act1_delta = act1_delta; } public float getAct2_delta() { return act2_delta; } public void setAct2_delta(float act2_delta) { this.act2_delta = act2_delta; } public float getAct3_delta() { return act3_delta; } public void setAct3_delta(float act3_delta) { this.act3_delta = act3_delta; } public float getAct0_win_rate() { return act0_win_rate; } public void setAct0_win_rate(float act0_win_rate) { this.act0_win_rate = act0_win_rate; } public float getAct1_win_rate() { return act1_win_rate; } public void setAct1_win_rate(float act1_win_rate) { this.act1_win_rate = act1_win_rate; } public float getAct2_win_rate() { return act2_win_rate; } public void setAct2_win_rate(float act2_win_rate) { this.act2_win_rate = act2_win_rate; } public float getAct3_win_rate() { return act3_win_rate; } public void setAct3_win_rate(float act3_win_rate) { this.act3_win_rate = act3_win_rate; } public int getAct0_wins() { return act0_wins; } public void setAct0_wins(int act0_wins) { this.act0_wins = act0_wins; } public int getAct1_wins() { return act1_wins; } public void setAct1_wins(int act1_wins) { this.act1_wins = act1_wins; } public int getAct2_wins() { return act2_wins; } public void setAct2_wins(int act2_wins) { this.act2_wins = act2_wins; } public int getAct3_wins() { return act3_wins; } public void setAct3_wins(int act3_wins) { this.act3_wins = act3_wins; } public int getAct0_losses() { return act0_losses; } public void setAct0_losses(int act0_losses) { this.act0_losses = act0_losses; } public int getAct1_losses() { return act1_losses; } public void setAct1_losses(int act1_losses) { this.act1_losses = act1_losses; } public int getAct2_losses() { return act2_losses; } public void setAct2_losses(int act2_losses) { this.act2_losses = act2_losses; } public int getAct3_losses() { return act3_losses; } public void setAct3_losses(int act3_losses) { this.act3_losses = act3_losses; } public int getAct0_score() { return act0_score; } public void setAct0_score(int act0_score) { this.act0_score = act0_score; } public int getAct1_score() { return act1_score; } public void setAct1_score(int act1_score) { this.act1_score = act1_score; } public int getAct2_score() { return act2_score; } public void setAct2_score(int act2_score) { this.act2_score = act2_score; } public int getAct3_score() { return act3_score; } public void setAct3_score(int act3_score) { this.act3_score = act3_score; } public int getOverall_score() { return overall_score; } public void setOverall_score(int overall_score) { this.overall_score = overall_score; } public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public int getA0_position() { return a0_position; } public void setA0_position(int a0_position) { this.a0_position = a0_position; } public int getA1_position() { return a1_position; } public void setA1_position(int a1_position) { this.a1_position = a1_position; } public int getA2_position() { return a2_position; } public void setA2_position(int a2_position) { this.a2_position = a2_position; } public int getA3_position() { return a3_position; } public void setA3_position(int a3_position) { this.a3_position = a3_position; } public float getPercentile() { return percentile; } public void setPercentile(float percentile) { this.percentile = percentile; } public float getA0_percentile() { return a0_percentile; } public void setA0_percentile(float a0_percentile) { this.a0_percentile = a0_percentile; } public float getA1_percentile() { return a1_percentile; } public void setA1_percentile(float a1_percentile) { this.a1_percentile = a1_percentile; } public float getA2_percentile() { return a2_percentile; } public void setA2_percentile(float a2_percentile) { this.a2_percentile = a2_percentile; } public float getA3_percentile() { return a3_percentile; } public void setA3_percentile(float a3_percentile) { this.a3_percentile = a3_percentile; } public String getCard_name() { return card_name; } public void setCard_name(String card_name) { this.card_name = card_name; } public Date getLastUpdated() { return lastUpdated; } public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } public void multOverall(float multi) { this.overall_score *= multi; } public void multA0(float multi) { this.act0_score *= multi; } public void multA1(float multi) { this.act1_score *= multi; } public void multA2(float multi) { this.act2_score *= multi; } public void multA3(float multi) { this.act3_score *= multi; } public void inc100() { this.overall_score += 100; this.act0_score += 100; this.act1_score += 100; this.act2_score += 100; this.act3_score += 100; } }
3e13780edb76c37c016c89921afbb98037e470db
873
java
Java
StrategyPattern/src/strategypattern/Abstraction/EST.java
rednax1994/A2BDesignPatterns
d17047b6906ca34623be073e83710e92a2b6d9e1
[ "Apache-2.0" ]
null
null
null
StrategyPattern/src/strategypattern/Abstraction/EST.java
rednax1994/A2BDesignPatterns
d17047b6906ca34623be073e83710e92a2b6d9e1
[ "Apache-2.0" ]
null
null
null
StrategyPattern/src/strategypattern/Abstraction/EST.java
rednax1994/A2BDesignPatterns
d17047b6906ca34623be073e83710e92a2b6d9e1
[ "Apache-2.0" ]
null
null
null
22.384615
79
0.656357
8,217
/* * 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 strategypattern.Abstraction; import java.util.Calendar; import java.util.Date; /** * * @author xandergerreman */ public class EST extends TimeZone { private final long HOUR = 3600 * 1000; private final int timeDiff = -5; TimeZone timeZone; public EST(TimeZone timeZone) { this.timeZone = timeZone; } public String getDescription() { return timeZone.getDescription() + " " + timeDiff; } @Override public Date dateNow() { Calendar cal = Calendar.getInstance(); cal.setTime(timeZone.dateNow()); cal.add(Calendar.HOUR_OF_DAY, timeDiff); cal.getTime(); return cal.getTime(); } }
3e137885a9c60f99006179bec739f7b66224b76e
1,340
java
Java
vertigo-influxdb-connector/src/main/java/io/vertigo/connectors/influxdb/InfluxDbFeatures.java
KleeGroup/vertigo-connectors
d67d6d541c11810ca9af1333141342596441f085
[ "Apache-2.0" ]
null
null
null
vertigo-influxdb-connector/src/main/java/io/vertigo/connectors/influxdb/InfluxDbFeatures.java
KleeGroup/vertigo-connectors
d67d6d541c11810ca9af1333141342596441f085
[ "Apache-2.0" ]
null
null
null
vertigo-influxdb-connector/src/main/java/io/vertigo/connectors/influxdb/InfluxDbFeatures.java
KleeGroup/vertigo-connectors
d67d6d541c11810ca9af1333141342596441f085
[ "Apache-2.0" ]
null
null
null
26.235294
75
0.733931
8,218
/** * vertigo - application development platform * * Copyright (C) 2013-2020, Vertigo.io, lyhxr@example.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.vertigo.connectors.influxdb; import io.vertigo.core.node.config.Feature; import io.vertigo.core.node.config.Features; import io.vertigo.core.param.Param; /** * Defines the influxdb connector module. * @author mlaroche */ public final class InfluxDbFeatures extends Features<InfluxDbFeatures> { /** * Constructor. */ public InfluxDbFeatures() { super("vertigo-influxdb-connector"); } @Feature("influxdb") public InfluxDbFeatures withInfluxDb(final Param... params) { getModuleConfigBuilder() .addConnector(InfluxDbConnector.class, params); return this; } /** {@inheritDoc} */ @Override protected void buildFeatures() { // } }
3e1378ff380b78cdedf8fb19a8076843c990d60c
5,321
java
Java
java/src/main/java/com/vmware/nsx/examples/basics/Vmc.java
raymonddejong/nsx-t
bd5f892dd14c9c00c08a7a28d947e78639ab2848
[ "BSD-2-Clause" ]
32
2019-04-25T11:06:27.000Z
2022-03-23T02:50:30.000Z
java/src/main/java/com/vmware/nsx/examples/basics/Vmc.java
raymonddejong/nsx-t
bd5f892dd14c9c00c08a7a28d947e78639ab2848
[ "BSD-2-Clause" ]
14
2019-05-03T17:41:15.000Z
2022-03-20T11:20:35.000Z
java/src/main/java/com/vmware/nsx/examples/basics/Vmc.java
raymonddejong/nsx-t
bd5f892dd14c9c00c08a7a28d947e78639ab2848
[ "BSD-2-Clause" ]
17
2019-04-08T20:37:05.000Z
2022-02-25T11:00:55.000Z
43.614754
120
0.712084
8,219
/* * NSX-T SDK Sample Code * * Copyright 2018 VMware, Inc. All rights reserved * * The BSD-2 license (the "License") set forth below applies to all parts of the * NSX-T SDK Sample Code project. You may not use this file except in compliance * with the License. * * BSD-2 License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.vmware.nsx.examples.basics; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import com.vmware.nsx.examples.authentication.VmcNsxAuthenticationHelper; import com.vmware.nsx_policy.Infra; import com.vmware.nsx_policy.infra.Domains; import com.vmware.nsx_policy.infra.domains.CommunicationMaps; import com.vmware.nsx_policy.model.CommunicationMapListResult; import com.vmware.nsx_policy.model.DomainListResult; import com.vmware.nsx_vmc_app.infra.LinkedVpcs; import com.vmware.nsx_vmc_app.model.LinkedVpcsListResult; import com.vmware.vapi.client.ApiClient; /*- * This example shows how to authenticate to the VMC (VMware Cloud on AWS) * service, using a VMC refresh token to obtain an authentication token that * can then be used to authenticate to the NSX-T instance in a Software * Defined Data Center (SDDC). */ public class Vmc { public static String VMC_SERVER = "vmc.vmware.com"; public static String CSP_SERVER = "console.cloud.vmware.com"; public static void main(String[] args) { Options options = new Options(); Option option; option = new Option("o", "organization_id", true, "ID of the VMC organization"); option.setRequired(true); options.addOption(option); option = new Option("s", "sddc_id", true, "ID of the Software Defined Data Center (SDDC)"); option.setRequired(true); options.addOption(option); option = new Option("r", "refresh_token", true, "Refresh token"); option.setRequired(true); options.addOption(option); option = new Option("h", "help", false, "Get help"); options.addOption(option); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); formatter.printHelp("VMC Authentication Demo", options); System.exit(1); } // Create the API client. This client will automatically obtain // and use an authentication token from the VMC CSP service, // and will automatically refresh it when it expires. ApiClient apiClient = new VmcNsxAuthenticationHelper() .newVmcNsxPolicyClient(cmd.getOptionValue("organization_id"), cmd.getOptionValue("sddc_id"), cmd.getOptionValue("refresh_token"), false, false); // The API client can be used to call the NSX-T policy API... Infra infraService = apiClient.createStub(Infra.class); com.vmware.nsx_policy.model.Infra infra = infraService.get(null); System.out.println(infra); Domains domains = apiClient.createStub(Domains.class); DomainListResult domainsList = domains.list(null, false, null, 1000L, false, null); System.out.println(domainsList); // ...as well as the NSX-T VMC app APIs. LinkedVpcs lvpcSvc = apiClient.createStub(LinkedVpcs.class); LinkedVpcsListResult results = lvpcSvc.list(); System.out.println(results); CommunicationMaps communicationMaps = apiClient.createStub(CommunicationMaps.class); CommunicationMapListResult mapListResult = communicationMaps.list("mgw", null, false, null, 1000L, false, null); System.out.println(mapListResult); } }
3e137925266c3ee40e7b59d08c247997e0b91a94
22,620
java
Java
src/java/org/apache/cassandra/db/commitlog/CommitLog.java
tadeegan/eiger-application-aware
0c1faf6ed2de35d6913dfce7cb1badcc555cbef8
[ "Apache-2.0" ]
42
2015-01-08T06:48:30.000Z
2021-11-08T09:01:57.000Z
src/java/org/apache/cassandra/db/commitlog/CommitLog.java
tadeegan/eiger-application-aware
0c1faf6ed2de35d6913dfce7cb1badcc555cbef8
[ "Apache-2.0" ]
6
2015-02-25T18:38:18.000Z
2015-12-10T11:29:58.000Z
src/java/org/apache/cassandra/db/commitlog/CommitLog.java
tadeegan/eiger-application-aware
0c1faf6ed2de35d6913dfce7cb1badcc555cbef8
[ "Apache-2.0" ]
15
2015-02-19T05:32:33.000Z
2021-06-07T23:21:19.000Z
38.799314
154
0.556057
8,220
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.db.commitlog; import java.io.*; import java.lang.management.ManagementFactory; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.CRC32; import java.util.zip.Checksum; import com.google.common.collect.Ordering; import org.apache.cassandra.config.Schema; import org.apache.cassandra.db.*; import org.apache.cassandra.io.IColumnSerializer; import org.apache.cassandra.io.util.*; import org.apache.cassandra.net.MessagingService; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.concurrent.Stage; import org.apache.cassandra.concurrent.StageManager; import org.apache.cassandra.config.Config; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.io.util.FastByteArrayInputStream; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.WrappedRunnable; import javax.management.MBeanServer; import javax.management.ObjectName; /* * Commit Log tracks every write operation into the system. The aim of the commit log is to be able to * successfully recover data that was not stored to disk via the Memtable. */ public class CommitLog implements CommitLogMBean { private static final int MAX_OUTSTANDING_REPLAY_COUNT = 1024; static final Logger logger = LoggerFactory.getLogger(CommitLog.class); public static final CommitLog instance = new CommitLog(); private final ICommitLogExecutorService executor; public final CommitLogAllocator allocator; public static final int END_OF_SEGMENT_MARKER = 0; // this is written out at the end of a segment public static final int END_OF_SEGMENT_MARKER_SIZE = 4; // number of bytes of ^^^ /** size of commitlog segments to allocate */ public static final int SEGMENT_SIZE = 128 * 1024 * 1024; public CommitLogSegment activeSegment; private CommitLog() { try { DatabaseDescriptor.createAllDirectories(); allocator = new CommitLogAllocator(); activateNextSegment(); } catch (IOException e) { throw new IOError(e); } executor = DatabaseDescriptor.getCommitLogSync() == Config.CommitLogSync.batch ? new BatchCommitLogExecutorService() : new PeriodicCommitLogExecutorService(this); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { mbs.registerMBean(this, new ObjectName("org.apache.cassandra.db:type=Commitlog")); } catch (Exception e) { throw new RuntimeException(e); } } /** * FOR TESTING PURPOSES. See CommitLogAllocator. */ public void resetUnsafe() throws IOException { allocator.resetUnsafe(); activateNextSegment(); } /** * Perform recovery on commit logs located in the directory specified by the config file. * * @return the number of mutations replayed */ public int recover() throws IOException { File[] files = new File(DatabaseDescriptor.getCommitLogLocation()).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { // we used to try to avoid instantiating commitlog (thus creating an empty segment ready for writes) // until after recover was finished. this turns out to be fragile; it is less error-prone to go // ahead and allow writes before recover(), and just skip active segments when we do. return CommitLogSegment.possibleCommitLogFile(name) && !instance.allocator.manages(name); } }); int replayed = 0; if (files.length == 0) { logger.info("No commitlog files found; skipping replay"); } else { Arrays.sort(files, new FileUtils.FileComparator()); logger.info("Replaying " + StringUtils.join(files, ", ")); replayed = recover(files); logger.info("Log replay complete, " + replayed + " replayed mutations"); for (File f : files) CommitLog.instance.allocator.recycleSegment(f); } allocator.enableReserveSegmentCreation(); return replayed; } /** * Perform recovery on a list of commit log files. * * @param clogs the list of commit log files to replay * @return the number of mutations replayed */ public int recover(File[] clogs) throws IOException { final Set<Table> tablesRecovered = new HashSet<Table>(); List<Future<?>> futures = new ArrayList<Future<?>>(); byte[] bytes = new byte[4096]; Map<Integer, AtomicInteger> invalidMutations = new HashMap<Integer, AtomicInteger>(); // count the number of replayed mutation. We don't really care about atomicity, but we need it to be a reference. final AtomicInteger replayedCount = new AtomicInteger(); // compute per-CF and global replay positions final Map<Integer, ReplayPosition> cfPositions = new HashMap<Integer, ReplayPosition>(); for (ColumnFamilyStore cfs : ColumnFamilyStore.all()) { // it's important to call RP.gRP per-cf, before aggregating all the positions w/ the Ordering.min call // below: gRP will return NONE if there are no flushed sstables, which is important to have in the // list (otherwise we'll just start replay from the first flush position that we do have, which is not correct). ReplayPosition rp = ReplayPosition.getReplayPosition(cfs.getSSTables()); cfPositions.put(cfs.metadata.cfId, rp); } final ReplayPosition globalPosition = Ordering.from(ReplayPosition.comparator).min(cfPositions.values()); Checksum checksum = new CRC32(); for (final File file : clogs) { logger.info("Replaying " + file.getPath()); final long segment = CommitLogSegment.idFromFilename(file.getName()); RandomAccessReader reader = RandomAccessReader.open(new File(file.getAbsolutePath()), true); assert reader.length() <= Integer.MAX_VALUE; try { int replayPosition; if (globalPosition.segment < segment) replayPosition = 0; else if (globalPosition.segment == segment) replayPosition = globalPosition.position; else replayPosition = (int) reader.length(); if (replayPosition < 0 || replayPosition >= reader.length()) { // replayPosition > reader.length() can happen if some data gets flushed before it is written to the commitlog // (see https://issues.apache.org/jira/browse/CASSANDRA-2285) logger.debug("skipping replay of fully-flushed {}", file); continue; } reader.seek(replayPosition); if (logger.isDebugEnabled()) logger.debug("Replaying " + file + " starting at " + reader.getFilePointer()); /* read the logs populate RowMutation and apply */ while (!reader.isEOF()) { if (logger.isDebugEnabled()) logger.debug("Reading mutation at " + reader.getFilePointer()); long claimedCRC32; int serializedSize; try { // any of the reads may hit EOF serializedSize = reader.readInt(); if (serializedSize == CommitLog.END_OF_SEGMENT_MARKER) { logger.debug("Encountered end of segment marker at " + reader.getFilePointer()); break; } // RowMutation must be at LEAST 10 bytes: // 3 each for a non-empty Table and Key (including the 2-byte length from // writeUTF/writeWithShortLength) and 4 bytes for column count. // This prevents CRC by being fooled by special-case garbage in the file; see CASSANDRA-2128 if (serializedSize < 10) break; long claimedSizeChecksum = reader.readLong(); checksum.reset(); checksum.update(serializedSize); if (checksum.getValue() != claimedSizeChecksum) break; // entry wasn't synced correctly/fully. that's ok. if (serializedSize > bytes.length) bytes = new byte[(int) (1.2 * serializedSize)]; reader.readFully(bytes, 0, serializedSize); claimedCRC32 = reader.readLong(); } catch(EOFException eof) { break; // last CL entry didn't get completely written. that's ok. } checksum.update(bytes, 0, serializedSize); if (claimedCRC32 != checksum.getValue()) { // this entry must not have been fsynced. probably the rest is bad too, // but just in case there is no harm in trying them (since we still read on an entry boundary) continue; } /* deserialize the commit log entry */ FastByteArrayInputStream bufIn = new FastByteArrayInputStream(bytes, 0, serializedSize); RowMutation rm = null; try { // assuming version here. We've gone to lengths to make sure what gets written to the CL is in // the current version. so do make sure the CL is drained prior to upgrading a node. rm = RowMutation.serializer().deserialize(new DataInputStream(bufIn), MessagingService.version_, IColumnSerializer.Flag.LOCAL); } catch (UnserializableColumnFamilyException ex) { AtomicInteger i = invalidMutations.get(ex.cfId); if (i == null) { i = new AtomicInteger(1); invalidMutations.put(ex.cfId, i); } else i.incrementAndGet(); continue; } if (logger.isDebugEnabled()) logger.debug(String.format("replaying mutation for %s.%s: %s", rm.getTable(), ByteBufferUtil.bytesToHex(rm.key()), "{" + StringUtils.join(rm.getColumnFamilies().iterator(), ", ") + "}")); final long entryLocation = reader.getFilePointer(); final RowMutation frm = rm; Runnable runnable = new WrappedRunnable() { public void runMayThrow() throws IOException { if (Schema.instance.getKSMetaData(frm.getTable()) == null) return; final Table table = Table.open(frm.getTable()); RowMutation newRm = new RowMutation(frm.getTable(), frm.key()); // Rebuild the row mutation, omitting column families that a) have already been flushed, // b) are part of a cf that was dropped. Keep in mind that the cf.name() is suspect. do every // thing based on the cfid instead. for (ColumnFamily columnFamily : frm.getColumnFamilies()) { if (Schema.instance.getCF(columnFamily.id()) == null) // null means the cf has been dropped continue; ReplayPosition rp = cfPositions.get(columnFamily.id()); // replay if current segment is newer than last flushed one or, if it is the last known // segment, if we are after the replay position if (segment > rp.segment || (segment == rp.segment && entryLocation > rp.position)) { newRm.add(columnFamily); replayedCount.incrementAndGet(); } } if (!newRm.isEmpty()) { Table.open(newRm.getTable()).apply(newRm, false); tablesRecovered.add(table); } } }; futures.add(StageManager.getStage(Stage.MUTATION).submit(runnable)); if (futures.size() > MAX_OUTSTANDING_REPLAY_COUNT) { FBUtilities.waitOnFutures(futures); futures.clear(); } } } finally { FileUtils.closeQuietly(reader); logger.info("Finished reading " + file); } } for (Map.Entry<Integer, AtomicInteger> entry : invalidMutations.entrySet()) logger.info(String.format("Skipped %d mutations from unknown (probably removed) CF with id %d", entry.getValue().intValue(), entry.getKey())); // wait for all the writes to finish on the mutation stage FBUtilities.waitOnFutures(futures); logger.debug("Finished waiting on mutations from recovery"); // flush replayed tables futures.clear(); for (Table table : tablesRecovered) futures.addAll(table.flush()); FBUtilities.waitOnFutures(futures); return replayedCount.get(); } /** * @return the current ReplayPosition of the current segment file */ public ReplayPosition getContext() { Callable<ReplayPosition> task = new Callable<ReplayPosition>() { public ReplayPosition call() throws Exception { return activeSegment.getContext(); } }; try { return executor.submit(task).get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } /** * Used by tests. * * @return the number of active segments (segments with unflushed data in them) */ public int activeSegments() { return allocator.getActiveSegments().size(); } /** * Add a RowMutation to the commit log. * * @param rm the RowMutation to add to the log */ public void add(RowMutation rm) throws IOException { long totalSize = RowMutation.serializer().serializedSize(rm, MessagingService.version_) + CommitLogSegment.ENTRY_OVERHEAD_SIZE; if (totalSize > CommitLog.SEGMENT_SIZE) { logger.warn("Skipping commitlog append of extremely large mutation ({} bytes)", totalSize); return; } executor.add(new LogRecordAdder(rm)); } /** * Modifies the per-CF dirty cursors of any commit log segments for the column family according to the position * given. Discards any commit log segments that are no longer used. * * @param cfId the column family ID that was flushed * @param context the replay position of the flush */ public void discardCompletedSegments(final Integer cfId, final ReplayPosition context) throws IOException { Callable task = new Callable() { public Object call() throws IOException { logger.debug("discard completed log segments for {}, column family {}", context, cfId); // Go thru the active segment files, which are ordered oldest to newest, marking the // flushed CF as clean, until we reach the segment file containing the ReplayPosition passed // in the arguments. Any segments that become unused after they are marked clean will be // recycled or discarded. for (Iterator<CommitLogSegment> iter = allocator.getActiveSegments().iterator(); iter.hasNext();) { CommitLogSegment segment = iter.next(); segment.markClean(cfId, context); // If the segment is no longer needed, and we have another spare segment in the hopper // (to keep the last segment from getting discarded), pursue either recycling or deleting // this segment file. if (segment.isUnused() && iter.hasNext()) { logger.debug("Commit log segment {} is unused", segment); allocator.recycleSegment(segment); } else { if (logger.isDebugEnabled()) logger.debug(String.format("Not safe to delete commit log %s; dirty is %s; hasNext: %s", segment, segment.dirtyString(), iter.hasNext())); } // Don't mark or try to delete any newer segments once we've reached the one containing the // position of the flush. if (segment.contains(context)) break; } return null; } }; try { executor.submit(task).get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } } /** * Forces a disk flush on the commit log files that need it. */ public void sync() throws IOException { for (CommitLogSegment segment : allocator.getActiveSegments()) { segment.sync(); } } /** * @return the number of tasks completed by the commit log executor */ public long getCompletedTasks() { return executor.getCompletedTasks(); } /** * @return the depth of pending commit log executor queue */ public long getPendingTasks() { return executor.getPendingTasks(); } /** * @return the total size occupied by commitlo segments expressed in bytes. (used by MBean) */ public long getTotalCommitlogSize() { return allocator.bytesUsed(); } /** * Forces a new segment file to be allocated and activated. Used mainly by truncate. */ public void forceNewSegment() throws ExecutionException, InterruptedException { logger.debug("Forcing new segment creation"); Callable<?> task = new Callable() { public Object call() throws IOException { if (activeSegment.position() > 0) activateNextSegment(); return null; } }; executor.submit(task).get(); } /** * Fetches a new segment file from the allocator and activates it. * * @return the newly activated segment */ private void activateNextSegment() throws IOException { activeSegment = allocator.fetchSegment(); } /** * Shuts down the threads used by the commit log, blocking until completion. */ public void shutdownBlocking() throws InterruptedException { executor.shutdown(); executor.awaitTermination(); allocator.shutdown(); allocator.awaitTermination(); } // TODO this should be a Runnable since it doesn't actually return anything, but it's difficult to do that // without breaking the fragile CheaterFutureTask in BatchCLES. class LogRecordAdder implements Callable, Runnable { final RowMutation rowMutation; LogRecordAdder(RowMutation rm) { this.rowMutation = rm; } public void run() { try { if (!activeSegment.hasCapacityFor(rowMutation)) activateNextSegment(); activeSegment.write(rowMutation); } catch (IOException e) { throw new IOError(e); } } public Object call() throws Exception { run(); return null; } } }
3e13793da1e9fdefec73943eb4227ba7153b5fb9
1,561
java
Java
diablo-server/src/test/java/me/hao0/diablo/server/PushLogServiceTests.java
fnet123/diablo
23c83a1e57bc1c8edd69ed2d9d8f6aa3017961d8
[ "MIT" ]
374
2016-10-09T03:48:49.000Z
2022-03-15T05:40:10.000Z
diablo-server/src/test/java/me/hao0/diablo/server/PushLogServiceTests.java
micezhao/diablo
d3b75a888c11390960c3620ea15415542cd199db
[ "MIT" ]
9
2016-10-10T08:25:55.000Z
2017-05-26T08:24:10.000Z
diablo-server/src/test/java/me/hao0/diablo/server/PushLogServiceTests.java
micezhao/diablo
d3b75a888c11390960c3620ea15415542cd199db
[ "MIT" ]
166
2016-10-09T08:58:05.000Z
2022-02-03T05:46:29.000Z
31.897959
91
0.695457
8,221
package me.hao0.diablo.server; import me.hao0.common.model.Page; import me.hao0.diablo.server.model.PushLog; import me.hao0.diablo.server.model.Response; import me.hao0.diablo.server.service.PushLogService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; /** * Author: haolin * Email: anpch@example.com */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = DiabloServerTest.class) public class PushLogServiceTests { @Autowired(required = false) private PushLogService pushLogService; @Test public void testAddPushLog(){ PushLog log; for (int i=0; i<26; i++){ log = new PushLog(); log.setAppId(1L); log.setServer("127.0.0.1:12345"); log.setClient("127.0.0.1:3311"); log.setConfig("test_config"+i); pushLogService.add(log); } } @Test public void testPagingPushLog(){ Response<Page<PushLog>> pagingResp = pushLogService.pagingConfigPushLog(1L, 1, 10); assertTrue(pagingResp.isSuccess()); assertEquals(10, pagingResp.getData().getData().size()); pagingResp = pushLogService.pagingConfigPushLog(1L, 3, 10); assertTrue(pagingResp.isSuccess()); assertEquals(6, pagingResp.getData().getData().size()); } }
3e137a291d9c75fb643c399d3c84264f52d330a0
1,293
java
Java
src/main/java/io/github/talelin/latticy/service/BannerItemService.java
13840170832/lin-cms-spring-boot
95647639fff1972a3493bab81cfbe84aa0b46182
[ "MIT" ]
1
2020-05-25T02:18:12.000Z
2020-05-25T02:18:12.000Z
src/main/java/io/github/talelin/latticy/service/BannerItemService.java
13840170832/lin-cms-spring-boot
95647639fff1972a3493bab81cfbe84aa0b46182
[ "MIT" ]
null
null
null
src/main/java/io/github/talelin/latticy/service/BannerItemService.java
13840170832/lin-cms-spring-boot
95647639fff1972a3493bab81cfbe84aa0b46182
[ "MIT" ]
null
null
null
30.785714
83
0.731632
8,222
package io.github.talelin.latticy.service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import io.github.talelin.autoconfigure.exception.NotFoundException; import io.github.talelin.latticy.dto.BannerItemDTO; import io.github.talelin.latticy.mapper.BannerItemMapper; import io.github.talelin.latticy.mapper.BannerMapper; import io.github.talelin.latticy.model.BannerItemDO; import com.baomidou.mybatisplus.extension.service.IService; import io.github.talelin.latticy.vo.UpdatedVO; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; /** * <p> * 服务类 * </p> * * @author generator@TaleLin * @since 2020-05-31 */ @Service public class BannerItemService extends ServiceImpl<BannerItemMapper,BannerItemDO> { public void update(BannerItemDTO dto,Long id){ BannerItemDO bannerItem = this.getById(id); if(null == bannerItem){ throw new NotFoundException(20001); } BeanUtils.copyProperties(dto,bannerItem); this.updateById(bannerItem); } public void delete(Long id){ BannerItemDO bannerItemDO = this.getById(id); if(null == bannerItemDO){ throw new NotFoundException(20001); } this.getBaseMapper().deleteById(id); } }
3e137a978083de79e673c1e8b85e0cde104607c0
4,897
java
Java
src/main/java/bio/ferlab/fhir/app/service/QueryService.java
joelplourde3/fhavro-rest-server
9c5084ed0aaa4d251ce46e83a7d7d8795d0586ad
[ "Apache-2.0" ]
null
null
null
src/main/java/bio/ferlab/fhir/app/service/QueryService.java
joelplourde3/fhavro-rest-server
9c5084ed0aaa4d251ce46e83a7d7d8795d0586ad
[ "Apache-2.0" ]
null
null
null
src/main/java/bio/ferlab/fhir/app/service/QueryService.java
joelplourde3/fhavro-rest-server
9c5084ed0aaa4d251ce46e83a7d7d8795d0586ad
[ "Apache-2.0" ]
null
null
null
43.723214
128
0.684092
8,223
package bio.ferlab.fhir.app.service; import bio.ferlab.fhir.FhavroConverter; import bio.ferlab.fhir.app.Response; import bio.ferlab.fhir.converter.ConverterUtils; import bio.ferlab.fhir.converter.exception.BadRequestException; import bio.ferlab.fhir.schema.repository.SchemaMode; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.r4.model.BaseResource; import org.hl7.fhir.r4.model.Bundle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.stream.Collectors; @Service public class QueryService { @Autowired private IGenericClient genericClient; @Autowired private FhirContext fhirContext; public void serialize(OutputStream outputStream, String resource, SchemaMode schemaMode, int count) { Schema schema = FhavroConverter.loadSchema(resource, schemaMode); List<GenericRecord> genericRecords = genericClient.search() .forResource(resource) .count(count) .returnBundle(Bundle.class) .execute() .getEntry() .stream() .map(x -> FhavroConverter.convertResourceToGenericRecord(x.getResource(), schema)) .collect(Collectors.toList()); FhavroConverter.serializeGenericRecords(schema, genericRecords, outputStream); } public List<String> deserialize(MultipartFile file, String resource, SchemaMode schemaMode) { Schema schema = FhavroConverter.loadSchema(resource, schemaMode); List<GenericRecord> genericRecords = FhavroConverter.deserializeGenericRecords(schema, multipartFileToFile(file)); return genericRecords.stream() .map(x -> FhavroConverter.convertGenericRecordToResource(x, schema, resource)) .map(x -> ConverterUtils.standardizeDate(fhirContext.newJsonParser().encodeResourceToString((IBaseResource) x))) .collect(Collectors.toList()); } public List<Response> query(String resource, SchemaMode schemaMode, int count) { Schema schema = FhavroConverter.loadSchema(resource, schemaMode); return genericClient.search() .forResource(resource) .count(count) .returnBundle(Bundle.class) .execute() .getEntry() .stream() .map(x -> convert(schema, x.getResource(), resource)) .collect(Collectors.toList()); } public Response queryById(String resource, SchemaMode schemaMode, String id) { Schema schema = FhavroConverter.loadSchema(resource, schemaMode); try { BaseResource baseResource = (BaseResource) genericClient.read() .resource(resource) .withId(id) .execute(); return convert(schema, baseResource, resource); } catch (ResourceNotFoundException ex) { throw new BadRequestException(String.format("Unknown Resource %s/%s is not found.", resource, id)); } } private <T extends BaseResource> Response convert(Schema schema, BaseResource baseResource, String name) { String inputString = ConverterUtils.standardizeDate(fhirContext.newJsonParser().encodeResourceToString(baseResource)); Response queryResult = new Response(inputString); try { GenericRecord input = FhavroConverter.convertResourceToGenericRecord(baseResource, schema); T resource = FhavroConverter.convertGenericRecordToResource(input, schema, name); String outputString = ConverterUtils.standardizeDate(fhirContext.newJsonParser().encodeResourceToString(resource)); boolean valid = queryResult.getInput().equals(outputString); if (!valid) { queryResult.setOutput(outputString); } return queryResult.returnValid(valid); } catch (Exception ex) { return queryResult.returnError(ex.getMessage()); } } public File multipartFileToFile(MultipartFile multipartFile) { File file = new File(multipartFile.getOriginalFilename()); try (OutputStream os = new FileOutputStream(file)) { os.write(multipartFile.getBytes()); } catch (IOException ex) { throw new BadRequestException("Please verify the provided file."); } return file; } }
3e137ad1d7a948f16476f17fbb1130dec8d0f2f6
588
java
Java
Codec/app/src/main/java/io/kvh/media/sound/Supporter.java
kevinho/opencore-amr-android
888937a78a67d47c9f2437744214f45d13e85dec
[ "Apache-2.0" ]
181
2015-08-31T00:43:41.000Z
2022-03-26T09:13:38.000Z
Codec/app/src/main/java/io/kvh/media/sound/Supporter.java
xpemail/opencore-amr-android
b320d7f1f8d13c24b996b51ff15f37b30f8ceee5
[ "Apache-2.0" ]
19
2016-03-22T10:14:14.000Z
2021-09-04T02:40:20.000Z
Codec/app/src/main/java/io/kvh/media/sound/Supporter.java
xpemail/opencore-amr-android
b320d7f1f8d13c24b996b51ff15f37b30f8ceee5
[ "Apache-2.0" ]
71
2015-08-31T02:31:29.000Z
2022-03-08T10:18:07.000Z
20.275862
58
0.653061
8,224
package io.kvh.media.sound; import java.io.File; /** * Created by changbinhe on 14/11/22. */ public class Supporter { public static final int SLICE_SECOND = 20; public static interface PcmConsumer { public void onPcmFeed(short[] buffer, int length); } public static interface AmrConsumer { public void onAmrFeed(byte[] buffer, int length); } public static interface FileConsumer { public void onFileFeed(File file); } public static interface OnOffSwitcher { public void start(); public void stop(); } }
3e137cf387c01d08ca5a9e66f29d8415780ad07b
615
java
Java
src/main/java/com/lisaxdevelopment/lisax/commands/misc/MiscCommands.java
AstelonM/Lisa
127e090a0342e9f3e10fc638a537ea7dc4e720c2
[ "Apache-2.0" ]
3
2019-06-26T06:01:15.000Z
2019-06-26T18:01:29.000Z
src/main/java/com/lisaxdevelopment/lisax/commands/misc/MiscCommands.java
AstelonM/Lisa
127e090a0342e9f3e10fc638a537ea7dc4e720c2
[ "Apache-2.0" ]
1
2019-06-25T13:38:20.000Z
2019-06-27T19:55:26.000Z
src/main/java/com/lisaxdevelopment/lisax/commands/misc/MiscCommands.java
AstelonM/Lisa
127e090a0342e9f3e10fc638a537ea7dc4e720c2
[ "Apache-2.0" ]
1
2019-06-27T17:04:39.000Z
2019-06-27T17:04:39.000Z
34.166667
77
0.721951
8,225
package com.lisaxdevelopment.lisax.commands.misc; import com.lisaxdevelopment.lisax.ChatListener; import com.lisaxdevelopment.lisax.commands.CommandGroup; public class MiscCommands extends CommandGroup { public MiscCommands(ChatListener listener) { super(listener); name = "MiscCommands"; description = "Group of commands providing miscellaneous utilities."; addCommand(new CharCount(listener)); addCommand(new Namemc(listener)); addCommand(new Currency(listener)); addCommand(new EmbedDissect(listener)); addCommand(new OCR(listener)); } }
3e137df40d18d78ee3340885807da24179dbc678
2,037
java
Java
src/test/java/io/evident/api/UserAttributionsApiTest.java
EvidentSecurity/esp-sdk-java
02c5573424b36d570aad7779bedf2ce0736e6ad3
[ "MIT" ]
1
2018-07-31T07:58:57.000Z
2018-07-31T07:58:57.000Z
src/test/java/io/evident/api/UserAttributionsApiTest.java
EvidentSecurity/esp-sdk-java
02c5573424b36d570aad7779bedf2ce0736e6ad3
[ "MIT" ]
null
null
null
src/test/java/io/evident/api/UserAttributionsApiTest.java
EvidentSecurity/esp-sdk-java
02c5573424b36d570aad7779bedf2ce0736e6ad3
[ "MIT" ]
3
2020-11-04T03:07:30.000Z
2020-11-17T02:10:18.000Z
24.542169
95
0.658812
8,226
package io.evident.api; import io.evident.EspSdk.ApiClient; import io.evident.models.ExternalAccount; import io.evident.models.ExternalAccountUserAttributionChannel; import io.evident.models.Meta; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for UserAttributionsApi */ public class UserAttributionsApiTest { private UserAttributionsApi api; @Before public void setup() { api = new ApiClient().createService(UserAttributionsApi.class); } /** * Create a User Attribution Channel for an external account * * URL will only be returned in this response and will not be accessible again. */ @Test public void addChannelTest() { Integer externalAccountId = null; // ExternalAccountUserAttributionChannel response = api.addChannel(externalAccountId); // TODO: test validations } /** * Remove the User Attribution Channel for an external account * * */ @Test public void removeChannelTest() { Integer externalAccountId = null; // Meta response = api.removeChannel(externalAccountId); // TODO: test validations } /** * Show the User Attribution Channel of an external account * * The channel url will not be returned. */ @Test public void showChannelTest() { Integer externalAccountId = null; // ExternalAccountUserAttributionChannel response = api.showChannel(externalAccountId); // TODO: test validations } /** * Update the user attributions on an external account * * */ @Test public void updateTest() { Integer externalAccountId = null; String include = null; String cloudtrailName = null; // ExternalAccount response = api.update(externalAccountId, include, cloudtrailName); // TODO: test validations } }
3e137e575a6429c75bce7e4a7f90434016c10218
19,379
java
Java
novel-gen/src/main/java/com/java2nb/novel/book/mapper/BookMapper.java
13377006021/novel-cloud
44bcd1c25f9d06602be2fac204bef88b0d1fef23
[ "Apache-2.0" ]
704
2020-05-28T10:55:18.000Z
2022-03-31T08:29:58.000Z
novel-gen/src/main/java/com/java2nb/novel/book/mapper/BookMapper.java
13377006021/novel-cloud
44bcd1c25f9d06602be2fac204bef88b0d1fef23
[ "Apache-2.0" ]
6
2020-08-14T10:26:52.000Z
2021-08-01T04:21:15.000Z
novel-gen/src/main/java/com/java2nb/novel/book/mapper/BookMapper.java
13377006021/novel-cloud
44bcd1c25f9d06602be2fac204bef88b0d1fef23
[ "Apache-2.0" ]
325
2020-05-28T17:02:05.000Z
2022-03-25T00:14:06.000Z
61.325949
352
0.68115
8,227
package com.java2nb.novel.book.mapper; import static com.java2nb.novel.book.mapper.BookDynamicSqlSupport.*; import static org.mybatis.dynamic.sql.SqlBuilder.*; import com.java2nb.novel.book.entity.Book; import java.util.List; import javax.annotation.Generated; import org.apache.ibatis.annotations.DeleteProvider; import org.apache.ibatis.annotations.InsertProvider; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.ResultMap; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.annotations.UpdateProvider; import org.apache.ibatis.type.JdbcType; import org.mybatis.dynamic.sql.SqlBuilder; import org.mybatis.dynamic.sql.delete.DeleteDSL; import org.mybatis.dynamic.sql.delete.MyBatis3DeleteModelAdapter; import org.mybatis.dynamic.sql.delete.render.DeleteStatementProvider; import org.mybatis.dynamic.sql.insert.render.InsertStatementProvider; import org.mybatis.dynamic.sql.render.RenderingStrategy; import org.mybatis.dynamic.sql.select.MyBatis3SelectModelAdapter; import org.mybatis.dynamic.sql.select.QueryExpressionDSL; import org.mybatis.dynamic.sql.select.SelectDSL; import org.mybatis.dynamic.sql.select.render.SelectStatementProvider; import org.mybatis.dynamic.sql.update.MyBatis3UpdateModelAdapter; import org.mybatis.dynamic.sql.update.UpdateDSL; import org.mybatis.dynamic.sql.update.render.UpdateStatementProvider; import org.mybatis.dynamic.sql.util.SqlProviderAdapter; @Mapper public interface BookMapper { @Generated("org.mybatis.generator.api.MyBatisGenerator") @SelectProvider(type=SqlProviderAdapter.class, method="select") long count(SelectStatementProvider selectStatement); @Generated("org.mybatis.generator.api.MyBatisGenerator") @DeleteProvider(type=SqlProviderAdapter.class, method="delete") int delete(DeleteStatementProvider deleteStatement); @Generated("org.mybatis.generator.api.MyBatisGenerator") @InsertProvider(type=SqlProviderAdapter.class, method="insert") int insert(InsertStatementProvider<Book> insertStatement); @Generated("org.mybatis.generator.api.MyBatisGenerator") @SelectProvider(type=SqlProviderAdapter.class, method="select") @ResultMap("BookResult") Book selectOne(SelectStatementProvider selectStatement); @Generated("org.mybatis.generator.api.MyBatisGenerator") @SelectProvider(type=SqlProviderAdapter.class, method="select") @Results(id="BookResult", value = { @Result(column="id", property="id", jdbcType=JdbcType.BIGINT, id=true), @Result(column="work_direction", property="workDirection", jdbcType=JdbcType.TINYINT), @Result(column="cat_id", property="catId", jdbcType=JdbcType.INTEGER), @Result(column="cat_name", property="catName", jdbcType=JdbcType.VARCHAR), @Result(column="pic_url", property="picUrl", jdbcType=JdbcType.VARCHAR), @Result(column="book_name", property="bookName", jdbcType=JdbcType.VARCHAR), @Result(column="author_id", property="authorId", jdbcType=JdbcType.BIGINT), @Result(column="author_name", property="authorName", jdbcType=JdbcType.VARCHAR), @Result(column="book_desc", property="bookDesc", jdbcType=JdbcType.VARCHAR), @Result(column="score", property="score", jdbcType=JdbcType.REAL), @Result(column="book_status", property="bookStatus", jdbcType=JdbcType.TINYINT), @Result(column="visit_count", property="visitCount", jdbcType=JdbcType.BIGINT), @Result(column="word_count", property="wordCount", jdbcType=JdbcType.INTEGER), @Result(column="comment_count", property="commentCount", jdbcType=JdbcType.INTEGER), @Result(column="last_index_id", property="lastIndexId", jdbcType=JdbcType.BIGINT), @Result(column="last_index_name", property="lastIndexName", jdbcType=JdbcType.VARCHAR), @Result(column="last_index_update_time", property="lastIndexUpdateTime", jdbcType=JdbcType.TIMESTAMP), @Result(column="is_vip", property="isVip", jdbcType=JdbcType.TINYINT), @Result(column="status", property="status", jdbcType=JdbcType.TINYINT), @Result(column="update_time", property="updateTime", jdbcType=JdbcType.TIMESTAMP), @Result(column="create_time", property="createTime", jdbcType=JdbcType.TIMESTAMP), @Result(column="crawl_source_id", property="crawlSourceId", jdbcType=JdbcType.INTEGER), @Result(column="crawl_book_id", property="crawlBookId", jdbcType=JdbcType.VARCHAR), @Result(column="crawl_last_time", property="crawlLastTime", jdbcType=JdbcType.TIMESTAMP), @Result(column="crawl_is_stop", property="crawlIsStop", jdbcType=JdbcType.TINYINT) }) List<Book> selectMany(SelectStatementProvider selectStatement); @Generated("org.mybatis.generator.api.MyBatisGenerator") @UpdateProvider(type=SqlProviderAdapter.class, method="update") int update(UpdateStatementProvider updateStatement); @Generated("org.mybatis.generator.api.MyBatisGenerator") default QueryExpressionDSL<MyBatis3SelectModelAdapter<Long>> countByExample() { return SelectDSL.selectWithMapper(this::count, SqlBuilder.count()) .from(book); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default DeleteDSL<MyBatis3DeleteModelAdapter<Integer>> deleteByExample() { return DeleteDSL.deleteFromWithMapper(this::delete, book); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default int deleteByPrimaryKey(Long id_) { return DeleteDSL.deleteFromWithMapper(this::delete, book) .where(id, isEqualTo(id_)) .build() .execute(); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default int insert(Book record) { return insert(SqlBuilder.insert(record) .into(book) .map(id).toProperty("id") .map(workDirection).toProperty("workDirection") .map(catId).toProperty("catId") .map(catName).toProperty("catName") .map(picUrl).toProperty("picUrl") .map(bookName).toProperty("bookName") .map(authorId).toProperty("authorId") .map(authorName).toProperty("authorName") .map(bookDesc).toProperty("bookDesc") .map(score).toProperty("score") .map(bookStatus).toProperty("bookStatus") .map(visitCount).toProperty("visitCount") .map(wordCount).toProperty("wordCount") .map(commentCount).toProperty("commentCount") .map(lastIndexId).toProperty("lastIndexId") .map(lastIndexName).toProperty("lastIndexName") .map(lastIndexUpdateTime).toProperty("lastIndexUpdateTime") .map(isVip).toProperty("isVip") .map(status).toProperty("status") .map(updateTime).toProperty("updateTime") .map(createTime).toProperty("createTime") .map(crawlSourceId).toProperty("crawlSourceId") .map(crawlBookId).toProperty("crawlBookId") .map(crawlLastTime).toProperty("crawlLastTime") .map(crawlIsStop).toProperty("crawlIsStop") .build() .render(RenderingStrategy.MYBATIS3)); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default int insertSelective(Book record) { return insert(SqlBuilder.insert(record) .into(book) .map(id).toPropertyWhenPresent("id", record::getId) .map(workDirection).toPropertyWhenPresent("workDirection", record::getWorkDirection) .map(catId).toPropertyWhenPresent("catId", record::getCatId) .map(catName).toPropertyWhenPresent("catName", record::getCatName) .map(picUrl).toPropertyWhenPresent("picUrl", record::getPicUrl) .map(bookName).toPropertyWhenPresent("bookName", record::getBookName) .map(authorId).toPropertyWhenPresent("authorId", record::getAuthorId) .map(authorName).toPropertyWhenPresent("authorName", record::getAuthorName) .map(bookDesc).toPropertyWhenPresent("bookDesc", record::getBookDesc) .map(score).toPropertyWhenPresent("score", record::getScore) .map(bookStatus).toPropertyWhenPresent("bookStatus", record::getBookStatus) .map(visitCount).toPropertyWhenPresent("visitCount", record::getVisitCount) .map(wordCount).toPropertyWhenPresent("wordCount", record::getWordCount) .map(commentCount).toPropertyWhenPresent("commentCount", record::getCommentCount) .map(lastIndexId).toPropertyWhenPresent("lastIndexId", record::getLastIndexId) .map(lastIndexName).toPropertyWhenPresent("lastIndexName", record::getLastIndexName) .map(lastIndexUpdateTime).toPropertyWhenPresent("lastIndexUpdateTime", record::getLastIndexUpdateTime) .map(isVip).toPropertyWhenPresent("isVip", record::getIsVip) .map(status).toPropertyWhenPresent("status", record::getStatus) .map(updateTime).toPropertyWhenPresent("updateTime", record::getUpdateTime) .map(createTime).toPropertyWhenPresent("createTime", record::getCreateTime) .map(crawlSourceId).toPropertyWhenPresent("crawlSourceId", record::getCrawlSourceId) .map(crawlBookId).toPropertyWhenPresent("crawlBookId", record::getCrawlBookId) .map(crawlLastTime).toPropertyWhenPresent("crawlLastTime", record::getCrawlLastTime) .map(crawlIsStop).toPropertyWhenPresent("crawlIsStop", record::getCrawlIsStop) .build() .render(RenderingStrategy.MYBATIS3)); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default QueryExpressionDSL<MyBatis3SelectModelAdapter<List<Book>>> selectByExample() { return SelectDSL.selectWithMapper(this::selectMany, id, workDirection, catId, catName, picUrl, bookName, authorId, authorName, bookDesc, score, bookStatus, visitCount, wordCount, commentCount, lastIndexId, lastIndexName, lastIndexUpdateTime, isVip, status, updateTime, createTime, crawlSourceId, crawlBookId, crawlLastTime, crawlIsStop) .from(book); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default QueryExpressionDSL<MyBatis3SelectModelAdapter<List<Book>>> selectDistinctByExample() { return SelectDSL.selectDistinctWithMapper(this::selectMany, id, workDirection, catId, catName, picUrl, bookName, authorId, authorName, bookDesc, score, bookStatus, visitCount, wordCount, commentCount, lastIndexId, lastIndexName, lastIndexUpdateTime, isVip, status, updateTime, createTime, crawlSourceId, crawlBookId, crawlLastTime, crawlIsStop) .from(book); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default Book selectByPrimaryKey(Long id_) { return SelectDSL.selectWithMapper(this::selectOne, id, workDirection, catId, catName, picUrl, bookName, authorId, authorName, bookDesc, score, bookStatus, visitCount, wordCount, commentCount, lastIndexId, lastIndexName, lastIndexUpdateTime, isVip, status, updateTime, createTime, crawlSourceId, crawlBookId, crawlLastTime, crawlIsStop) .from(book) .where(id, isEqualTo(id_)) .build() .execute(); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default UpdateDSL<MyBatis3UpdateModelAdapter<Integer>> updateByExample(Book record) { return UpdateDSL.updateWithMapper(this::update, book) .set(id).equalTo(record::getId) .set(workDirection).equalTo(record::getWorkDirection) .set(catId).equalTo(record::getCatId) .set(catName).equalTo(record::getCatName) .set(picUrl).equalTo(record::getPicUrl) .set(bookName).equalTo(record::getBookName) .set(authorId).equalTo(record::getAuthorId) .set(authorName).equalTo(record::getAuthorName) .set(bookDesc).equalTo(record::getBookDesc) .set(score).equalTo(record::getScore) .set(bookStatus).equalTo(record::getBookStatus) .set(visitCount).equalTo(record::getVisitCount) .set(wordCount).equalTo(record::getWordCount) .set(commentCount).equalTo(record::getCommentCount) .set(lastIndexId).equalTo(record::getLastIndexId) .set(lastIndexName).equalTo(record::getLastIndexName) .set(lastIndexUpdateTime).equalTo(record::getLastIndexUpdateTime) .set(isVip).equalTo(record::getIsVip) .set(status).equalTo(record::getStatus) .set(updateTime).equalTo(record::getUpdateTime) .set(createTime).equalTo(record::getCreateTime) .set(crawlSourceId).equalTo(record::getCrawlSourceId) .set(crawlBookId).equalTo(record::getCrawlBookId) .set(crawlLastTime).equalTo(record::getCrawlLastTime) .set(crawlIsStop).equalTo(record::getCrawlIsStop); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default UpdateDSL<MyBatis3UpdateModelAdapter<Integer>> updateByExampleSelective(Book record) { return UpdateDSL.updateWithMapper(this::update, book) .set(id).equalToWhenPresent(record::getId) .set(workDirection).equalToWhenPresent(record::getWorkDirection) .set(catId).equalToWhenPresent(record::getCatId) .set(catName).equalToWhenPresent(record::getCatName) .set(picUrl).equalToWhenPresent(record::getPicUrl) .set(bookName).equalToWhenPresent(record::getBookName) .set(authorId).equalToWhenPresent(record::getAuthorId) .set(authorName).equalToWhenPresent(record::getAuthorName) .set(bookDesc).equalToWhenPresent(record::getBookDesc) .set(score).equalToWhenPresent(record::getScore) .set(bookStatus).equalToWhenPresent(record::getBookStatus) .set(visitCount).equalToWhenPresent(record::getVisitCount) .set(wordCount).equalToWhenPresent(record::getWordCount) .set(commentCount).equalToWhenPresent(record::getCommentCount) .set(lastIndexId).equalToWhenPresent(record::getLastIndexId) .set(lastIndexName).equalToWhenPresent(record::getLastIndexName) .set(lastIndexUpdateTime).equalToWhenPresent(record::getLastIndexUpdateTime) .set(isVip).equalToWhenPresent(record::getIsVip) .set(status).equalToWhenPresent(record::getStatus) .set(updateTime).equalToWhenPresent(record::getUpdateTime) .set(createTime).equalToWhenPresent(record::getCreateTime) .set(crawlSourceId).equalToWhenPresent(record::getCrawlSourceId) .set(crawlBookId).equalToWhenPresent(record::getCrawlBookId) .set(crawlLastTime).equalToWhenPresent(record::getCrawlLastTime) .set(crawlIsStop).equalToWhenPresent(record::getCrawlIsStop); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default int updateByPrimaryKey(Book record) { return UpdateDSL.updateWithMapper(this::update, book) .set(workDirection).equalTo(record::getWorkDirection) .set(catId).equalTo(record::getCatId) .set(catName).equalTo(record::getCatName) .set(picUrl).equalTo(record::getPicUrl) .set(bookName).equalTo(record::getBookName) .set(authorId).equalTo(record::getAuthorId) .set(authorName).equalTo(record::getAuthorName) .set(bookDesc).equalTo(record::getBookDesc) .set(score).equalTo(record::getScore) .set(bookStatus).equalTo(record::getBookStatus) .set(visitCount).equalTo(record::getVisitCount) .set(wordCount).equalTo(record::getWordCount) .set(commentCount).equalTo(record::getCommentCount) .set(lastIndexId).equalTo(record::getLastIndexId) .set(lastIndexName).equalTo(record::getLastIndexName) .set(lastIndexUpdateTime).equalTo(record::getLastIndexUpdateTime) .set(isVip).equalTo(record::getIsVip) .set(status).equalTo(record::getStatus) .set(updateTime).equalTo(record::getUpdateTime) .set(createTime).equalTo(record::getCreateTime) .set(crawlSourceId).equalTo(record::getCrawlSourceId) .set(crawlBookId).equalTo(record::getCrawlBookId) .set(crawlLastTime).equalTo(record::getCrawlLastTime) .set(crawlIsStop).equalTo(record::getCrawlIsStop) .where(id, isEqualTo(record::getId)) .build() .execute(); } @Generated("org.mybatis.generator.api.MyBatisGenerator") default int updateByPrimaryKeySelective(Book record) { return UpdateDSL.updateWithMapper(this::update, book) .set(workDirection).equalToWhenPresent(record::getWorkDirection) .set(catId).equalToWhenPresent(record::getCatId) .set(catName).equalToWhenPresent(record::getCatName) .set(picUrl).equalToWhenPresent(record::getPicUrl) .set(bookName).equalToWhenPresent(record::getBookName) .set(authorId).equalToWhenPresent(record::getAuthorId) .set(authorName).equalToWhenPresent(record::getAuthorName) .set(bookDesc).equalToWhenPresent(record::getBookDesc) .set(score).equalToWhenPresent(record::getScore) .set(bookStatus).equalToWhenPresent(record::getBookStatus) .set(visitCount).equalToWhenPresent(record::getVisitCount) .set(wordCount).equalToWhenPresent(record::getWordCount) .set(commentCount).equalToWhenPresent(record::getCommentCount) .set(lastIndexId).equalToWhenPresent(record::getLastIndexId) .set(lastIndexName).equalToWhenPresent(record::getLastIndexName) .set(lastIndexUpdateTime).equalToWhenPresent(record::getLastIndexUpdateTime) .set(isVip).equalToWhenPresent(record::getIsVip) .set(status).equalToWhenPresent(record::getStatus) .set(updateTime).equalToWhenPresent(record::getUpdateTime) .set(createTime).equalToWhenPresent(record::getCreateTime) .set(crawlSourceId).equalToWhenPresent(record::getCrawlSourceId) .set(crawlBookId).equalToWhenPresent(record::getCrawlBookId) .set(crawlLastTime).equalToWhenPresent(record::getCrawlLastTime) .set(crawlIsStop).equalToWhenPresent(record::getCrawlIsStop) .where(id, isEqualTo(record::getId)) .build() .execute(); } }
3e137e583acb7aa09cbbcd742454f325e11b1efd
316
java
Java
nsf/Code/Java/dk/majkilde/logreader/files/IFile.java
cubeteam/LogFileReader
20bf77d580664eb6b945bed90fc7aedaed9288b7
[ "Apache-2.0" ]
null
null
null
nsf/Code/Java/dk/majkilde/logreader/files/IFile.java
cubeteam/LogFileReader
20bf77d580664eb6b945bed90fc7aedaed9288b7
[ "Apache-2.0" ]
null
null
null
nsf/Code/Java/dk/majkilde/logreader/files/IFile.java
cubeteam/LogFileReader
20bf77d580664eb6b945bed90fc7aedaed9288b7
[ "Apache-2.0" ]
null
null
null
15.047619
50
0.743671
8,228
package dk.majkilde.logreader.files; import java.util.Date; public interface IFile extends Comparable<IFile> { public String getHtml(); public String getFilename(); public String getPath(); public Date getDate(); public long getSize(); public abstract void download(); public Filters getFilters(); }
3e137ef985eeecad95cd81ad38e6bce73acacf29
1,015
java
Java
S04.02-Exercise-DisplayDayForecast/app/src/main/java/com/example/android/sunshine/DetailActivity.java
aberdean/ud851-Sunshine
c94b43b7b9d4c4672880cf1b45fe38a2576d4a4e
[ "Apache-2.0" ]
null
null
null
S04.02-Exercise-DisplayDayForecast/app/src/main/java/com/example/android/sunshine/DetailActivity.java
aberdean/ud851-Sunshine
c94b43b7b9d4c4672880cf1b45fe38a2576d4a4e
[ "Apache-2.0" ]
null
null
null
S04.02-Exercise-DisplayDayForecast/app/src/main/java/com/example/android/sunshine/DetailActivity.java
aberdean/ud851-Sunshine
c94b43b7b9d4c4672880cf1b45fe38a2576d4a4e
[ "Apache-2.0" ]
null
null
null
30.757576
92
0.723153
8,229
package com.example.android.sunshine; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import org.w3c.dom.Text; public class DetailActivity extends AppCompatActivity { private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp"; private String mForecast; private TextView mWeatherDisplay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); mWeatherDisplay = (TextView) findViewById(R.id.tv_display_weather); Intent intentThatStartedThisActivity = getIntent(); if (intentThatStartedThisActivity != null) { if (intentThatStartedThisActivity.hasExtra(Intent.EXTRA_TEXT)) { mForecast = intentThatStartedThisActivity.getStringExtra(Intent.EXTRA_TEXT); mWeatherDisplay.setText(mForecast); } } } }
3e137fa526fb8dbc5a09fb8ffcae88e6323691fc
337
java
Java
src/main/java/ua/logos/service/CategoryService.java
iloveyoulviv/spring-boot-app
d82d53d8f4e75b05a3884c480dd57aa913b4498a
[ "Apache-2.0" ]
null
null
null
src/main/java/ua/logos/service/CategoryService.java
iloveyoulviv/spring-boot-app
d82d53d8f4e75b05a3884c480dd57aa913b4498a
[ "Apache-2.0" ]
null
null
null
src/main/java/ua/logos/service/CategoryService.java
iloveyoulviv/spring-boot-app
d82d53d8f4e75b05a3884c480dd57aa913b4498a
[ "Apache-2.0" ]
null
null
null
18.722222
48
0.771513
8,230
package ua.logos.service; import ua.logos.domain.CategoryDTO; import ua.logos.entity.CategoryEntity; import java.util.List; public interface CategoryService { CategoryDTO save(CategoryDTO category); List<CategoryDTO> findAll(); CategoryDTO findByCategoryId(Long id); CategoryDTO findByCategoryName(String name); }
3e137ffe6314d73753cbe43d9885dc677024f4cc
472
java
Java
src/LeetcodeTemplate/_1359CountAllValidPickupAndDeliveryOptions.java
darshanhs90/Java-HackerRank
da76ccd7851f102712f7d8dfa4659901c5de7a76
[ "MIT" ]
3
2017-03-04T19:21:28.000Z
2019-08-09T07:31:34.000Z
src/LeetcodeTemplate/_1359CountAllValidPickupAndDeliveryOptions.java
darshanhs90/Java-HackerRank
da76ccd7851f102712f7d8dfa4659901c5de7a76
[ "MIT" ]
null
null
null
src/LeetcodeTemplate/_1359CountAllValidPickupAndDeliveryOptions.java
darshanhs90/Java-HackerRank
da76ccd7851f102712f7d8dfa4659901c5de7a76
[ "MIT" ]
3
2017-12-17T10:36:07.000Z
2022-01-19T19:08:35.000Z
19.666667
57
0.735169
8,231
package LeetcodeTemplate; import java.util.List; public class _1359CountAllValidPickupAndDeliveryOptions { public static void main(String[] args) { System.out.println(countOrders(1)); System.out.println(countOrders(2)); System.out.println(countOrders(3)); System.out.println(generate(1)); System.out.println(generate(2)); System.out.println(generate(3)); } public static int countOrders(int n) { } public static List<String> generate(int n) { } }
3e138020e532343a84b7c56e84f6bd1ba4783d1a
7,127
java
Java
src/net/minecraft/util/IntHashMap.java
ExistDev/EXIST
52e87cc048b5fe1c9c708844c59c11a1be34e2ea
[ "Apache-2.0" ]
6
2018-11-14T19:01:09.000Z
2021-08-23T10:52:32.000Z
src/net/minecraft/util/IntHashMap.java
ExistDev/EXIST
52e87cc048b5fe1c9c708844c59c11a1be34e2ea
[ "Apache-2.0" ]
null
null
null
src/net/minecraft/util/IntHashMap.java
ExistDev/EXIST
52e87cc048b5fe1c9c708844c59c11a1be34e2ea
[ "Apache-2.0" ]
null
null
null
28.394422
126
0.538095
8,232
package net.minecraft.util; public class IntHashMap { /** * An array of HashEntries representing the heads of hash slot lists */ private transient IntHashMap.Entry[] slots = new IntHashMap.Entry[16]; /** * The number of items stored in this map */ private transient int count; /** * The grow threshold */ private int threshold = 12; /** * The scale factor used to determine when to grow the table */ private final float growFactor = 0.75F; /** * Makes the passed in integer suitable for hashing by a number of shifts */ private static int computeHash(int p_76044_0_) { p_76044_0_ ^= p_76044_0_ >>> 20 ^ p_76044_0_ >>> 12; return p_76044_0_ ^ p_76044_0_ >>> 7 ^ p_76044_0_ >>> 4; } /** * Computes the index of the slot for the hash and slot count passed in. */ private static int getSlotIndex(int p_76043_0_, int p_76043_1_) { return p_76043_0_ & p_76043_1_ - 1; } /** * Returns the object associated to a key */ public Object lookup(int p_76041_1_) { int var2 = computeHash(p_76041_1_); for (IntHashMap.Entry var3 = this.slots[getSlotIndex(var2, this.slots.length)]; var3 != null; var3 = var3.nextEntry) { if (var3.hashEntry == p_76041_1_) { return var3.valueEntry; } } return null; } /** * Returns true if this hash table contains the specified item. */ public boolean containsItem(int p_76037_1_) { return this.lookupEntry(p_76037_1_) != null; } /** * Returns the internal entry for a key */ final IntHashMap.Entry lookupEntry(int p_76045_1_) { int var2 = computeHash(p_76045_1_); for (IntHashMap.Entry var3 = this.slots[getSlotIndex(var2, this.slots.length)]; var3 != null; var3 = var3.nextEntry) { if (var3.hashEntry == p_76045_1_) { return var3; } } return null; } /** * Adds a key and associated value to this map */ public void addKey(int p_76038_1_, Object p_76038_2_) { int var3 = computeHash(p_76038_1_); int var4 = getSlotIndex(var3, this.slots.length); for (IntHashMap.Entry var5 = this.slots[var4]; var5 != null; var5 = var5.nextEntry) { if (var5.hashEntry == p_76038_1_) { var5.valueEntry = p_76038_2_; return; } } this.insert(var3, p_76038_1_, p_76038_2_, var4); } /** * Increases the number of hash slots */ private void grow(int p_76047_1_) { IntHashMap.Entry[] var2 = this.slots; int var3 = var2.length; if (var3 == 1073741824) { this.threshold = Integer.MAX_VALUE; } else { IntHashMap.Entry[] var4 = new IntHashMap.Entry[p_76047_1_]; this.copyTo(var4); this.slots = var4; this.threshold = (int) ((float) p_76047_1_ * this.growFactor); } } /** * Copies the hash slots to a new array */ private void copyTo(IntHashMap.Entry[] p_76048_1_) { IntHashMap.Entry[] var2 = this.slots; int var3 = p_76048_1_.length; for (int var4 = 0; var4 < var2.length; ++var4) { IntHashMap.Entry var5 = var2[var4]; if (var5 != null) { var2[var4] = null; IntHashMap.Entry var6; do { var6 = var5.nextEntry; int var7 = getSlotIndex(var5.slotHash, var3); var5.nextEntry = p_76048_1_[var7]; p_76048_1_[var7] = var5; var5 = var6; } while (var6 != null); } } } /** * Removes the specified object from the map and returns it */ public Object removeObject(int p_76049_1_) { IntHashMap.Entry var2 = this.removeEntry(p_76049_1_); return var2 == null ? null : var2.valueEntry; } /** * Removes the specified entry from the map and returns it */ final IntHashMap.Entry removeEntry(int p_76036_1_) { int var2 = computeHash(p_76036_1_); int var3 = getSlotIndex(var2, this.slots.length); IntHashMap.Entry var4 = this.slots[var3]; IntHashMap.Entry var5; IntHashMap.Entry var6; for (var5 = var4; var5 != null; var5 = var6) { var6 = var5.nextEntry; if (var5.hashEntry == p_76036_1_) { --this.count; if (var4 == var5) { this.slots[var3] = var6; } else { var4.nextEntry = var6; } return var5; } var4 = var5; } return var5; } /** * Removes all entries from the map */ public void clearMap() { IntHashMap.Entry[] var1 = this.slots; for (int var2 = 0; var2 < var1.length; ++var2) { var1[var2] = null; } this.count = 0; } /** * Adds an object to a slot */ private void insert(int p_76040_1_, int p_76040_2_, Object p_76040_3_, int p_76040_4_) { IntHashMap.Entry var5 = this.slots[p_76040_4_]; this.slots[p_76040_4_] = new IntHashMap.Entry(p_76040_1_, p_76040_2_, p_76040_3_, var5); if (this.count++ >= this.threshold) { this.grow(2 * this.slots.length); } } static class Entry { final int hashEntry; Object valueEntry; IntHashMap.Entry nextEntry; final int slotHash; Entry(int p_i1552_1_, int p_i1552_2_, Object p_i1552_3_, IntHashMap.Entry p_i1552_4_) { this.valueEntry = p_i1552_3_; this.nextEntry = p_i1552_4_; this.hashEntry = p_i1552_2_; this.slotHash = p_i1552_1_; } public final int getHash() { return this.hashEntry; } public final Object getValue() { return this.valueEntry; } public final boolean equals(Object p_equals_1_) { if (!(p_equals_1_ instanceof IntHashMap.Entry)) { return false; } else { IntHashMap.Entry var2 = (IntHashMap.Entry) p_equals_1_; Integer var3 = Integer.valueOf(this.getHash()); Integer var4 = Integer.valueOf(var2.getHash()); if (var3 == var4 || var3 != null && var3.equals(var4)) { Object var5 = this.getValue(); Object var6 = var2.getValue(); if (var5 == var6 || var5 != null && var5.equals(var6)) { return true; } } return false; } } public final int hashCode() { return IntHashMap.computeHash(this.hashEntry); } public final String toString() { return this.getHash() + "=" + this.getValue(); } } }
3e138083e3efd327d6660fc6169b1e6b1d1209a3
6,388
java
Java
web/KoreanAir/src/main/java/com/ke/css/cimp/fwb/fwb9/Rule_IATA_CARGO_AGENT_CODE.java
ganzijo/portfolio
a31834b23308be7b3a992451ab8140bef5a61728
[ "Apache-2.0" ]
null
null
null
web/KoreanAir/src/main/java/com/ke/css/cimp/fwb/fwb9/Rule_IATA_CARGO_AGENT_CODE.java
ganzijo/portfolio
a31834b23308be7b3a992451ab8140bef5a61728
[ "Apache-2.0" ]
null
null
null
web/KoreanAir/src/main/java/com/ke/css/cimp/fwb/fwb9/Rule_IATA_CARGO_AGENT_CODE.java
ganzijo/portfolio
a31834b23308be7b3a992451ab8140bef5a61728
[ "Apache-2.0" ]
null
null
null
27.895197
98
0.386036
8,233
package com.ke.css.cimp.fwb.fwb9; /* ----------------------------------------------------------------------------- * Rule_IATA_CARGO_AGENT_CODE.java * ----------------------------------------------------------------------------- * * Producer : com.parse2.aparse.Parser 2.5 * Produced : Tue Mar 06 10:38:42 KST 2018 * * ----------------------------------------------------------------------------- */ import java.util.ArrayList; final public class Rule_IATA_CARGO_AGENT_CODE extends Rule { public Rule_IATA_CARGO_AGENT_CODE(String spelling, ArrayList<Rule> rules) { super(spelling, rules); } public Object accept(Visitor visitor) { return visitor.visit(this); } public static Rule_IATA_CARGO_AGENT_CODE parse(ParserContext context) { context.push("IATA_CARGO_AGENT_CODE"); boolean parsed = true; int s0 = context.index; ParserAlternative a0 = new ParserAlternative(s0); ArrayList<ParserAlternative> as1 = new ArrayList<ParserAlternative>(); parsed = false; { int s1 = context.index; ParserAlternative a1 = new ParserAlternative(s1); parsed = true; if (parsed) { boolean f1 = true; int c1 = 0; for (int i1 = 0; i1 < 1 && f1; i1++) { int g1 = context.index; ArrayList<ParserAlternative> as2 = new ArrayList<ParserAlternative>(); parsed = false; { int s2 = context.index; ParserAlternative a2 = new ParserAlternative(s2); parsed = true; if (parsed) { boolean f2 = true; int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { Rule rule = Rule_Sub_IATA_CARGO_AGENT_CODE.parse(context); if ((f2 = rule != null)) { a2.add(rule, context.index); c2++; } } parsed = c2 == 1; } if (parsed) { boolean f2 = true; @SuppressWarnings("unused") int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { int g2 = context.index; ArrayList<ParserAlternative> as3 = new ArrayList<ParserAlternative>(); parsed = false; { int s3 = context.index; ParserAlternative a3 = new ParserAlternative(s3); parsed = true; if (parsed) { boolean f3 = true; int c3 = 0; for (int i3 = 0; i3 < 1 && f3; i3++) { Rule rule = Rule_Sep_Slant.parse(context); if ((f3 = rule != null)) { a3.add(rule, context.index); c3++; } } parsed = c3 == 1; } if (parsed) { as3.add(a3); } context.index = s3; } ParserAlternative b = ParserAlternative.getBest(as3); parsed = b != null; if (parsed) { a2.add(b.rules, b.end); context.index = b.end; } f2 = context.index > g2; if (parsed) c2++; } parsed = true; } if (parsed) { boolean f2 = true; @SuppressWarnings("unused") int c2 = 0; for (int i2 = 0; i2 < 1 && f2; i2++) { int g2 = context.index; ArrayList<ParserAlternative> as3 = new ArrayList<ParserAlternative>(); parsed = false; { int s3 = context.index; ParserAlternative a3 = new ParserAlternative(s3); parsed = true; if (parsed) { boolean f3 = true; int c3 = 0; for (int i3 = 0; i3 < 1 && f3; i3++) { Rule rule = Rule_Sub_IATA_Cargo_Agent_CASS_Address.parse(context); if ((f3 = rule != null)) { a3.add(rule, context.index); c3++; } } parsed = c3 == 1; } if (parsed) { as3.add(a3); } context.index = s3; } ParserAlternative b = ParserAlternative.getBest(as3); parsed = b != null; if (parsed) { a2.add(b.rules, b.end); context.index = b.end; } f2 = context.index > g2; if (parsed) c2++; } parsed = true; } if (parsed) { as2.add(a2); } context.index = s2; } ParserAlternative b = ParserAlternative.getBest(as2); parsed = b != null; if (parsed) { a1.add(b.rules, b.end); context.index = b.end; } f1 = context.index > g1; if (parsed) c1++; } parsed = c1 == 1; } if (parsed) { as1.add(a1); } context.index = s1; } ParserAlternative b = ParserAlternative.getBest(as1); parsed = b != null; if (parsed) { a0.add(b.rules, b.end); context.index = b.end; } Rule rule = null; if (parsed) { rule = new Rule_IATA_CARGO_AGENT_CODE(context.text.substring(a0.start, a0.end), a0.rules); } else { context.index = s0; } context.pop("IATA_CARGO_AGENT_CODE", parsed); return (Rule_IATA_CARGO_AGENT_CODE)rule; } } /* ----------------------------------------------------------------------------- * eof * ----------------------------------------------------------------------------- */
3e1380a3b180fc3dca2f98eeae3e2132adb0f69a
7,089
java
Java
javolution-serializer/src/test/java/de/javakaffee/web/msm/serializer/javolution/CGLibProxyFormatTest.java
mosoft521/memcached-session-manager
716e147c9840ab10298c4d2b9edd0662058331e6
[ "Apache-2.0" ]
619
2015-01-04T07:41:22.000Z
2022-03-30T07:58:45.000Z
javolution-serializer/src/test/java/de/javakaffee/web/msm/serializer/javolution/CGLibProxyFormatTest.java
bingli-borland/memcached-session-manager
f17f42863f6685c0adc988e3e3ccfce3a2e0d327
[ "Apache-2.0" ]
376
2015-03-19T11:33:48.000Z
2022-02-14T13:58:01.000Z
javolution-serializer/src/test/java/de/javakaffee/web/msm/serializer/javolution/CGLibProxyFormatTest.java
bingli-borland/memcached-session-manager
f17f42863f6685c0adc988e3e3ccfce3a2e0d327
[ "Apache-2.0" ]
307
2015-01-10T19:50:00.000Z
2022-03-28T05:46:17.000Z
36.040609
109
0.644648
8,234
/* * Copyright 2010 Martin Grotzke * * 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 &quot;AS IS&quot; 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 de.javakaffee.web.msm.serializer.javolution; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Serializable; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import javolution.xml.XMLBinding; import javolution.xml.XMLObjectReader; import javolution.xml.XMLObjectWriter; import javolution.xml.XMLReferenceResolver; import javolution.xml.stream.XMLStreamException; import net.sf.cglib.core.DefaultNamingPolicy; import net.sf.cglib.core.Predicate; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.InvocationHandler; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; /** * Test for {@link CGLibProxyFormat}. * * @author <a href="mailto:kenaa@example.com">Martin Grotzke</a> */ public class CGLibProxyFormatTest { private static final Log LOG = LogFactory.getLog( CGLibProxyFormatTest.class ); private ReflectionBinding _binding; @BeforeTest protected void beforeTest() { _binding = new ReflectionBinding( getClass().getClassLoader(), false, new CGLibProxyFormat() ); } @Test( enabled = true ) public void testCGLibProxy() throws XMLStreamException { final ClassToProxy proxy = createProxy( new ClassToProxy() ); proxy.setValue( "foo" ); final byte[] serialized = serialize( proxy, _binding ); System.out.println( new String( serialized ) ); final ClassToProxy deserialized = deserialize( serialized, _binding ); Assert.assertEquals( deserialized.getValue(), proxy.getValue() ); } /** * Test that a proxy for another existing xmlformat is handled correctly. * * @throws XMLStreamException */ @Test( enabled = true ) public void testCGLibProxyForExistingFormat() throws XMLStreamException { final Map<String, String> proxy = createProxy( new HashMap<String, String>() ); proxy.put( "foo", "bar" ); Assert.assertEquals( proxy.get( "foo" ), "bar" ); final byte[] serialized = serialize( proxy, _binding ); System.out.println( new String( serialized ) ); final Map<String, String> deserialized = deserialize( serialized, _binding ); Assert.assertEquals( deserialized.get( "foo" ), proxy.get( "foo" ) ); } @SuppressWarnings( "unchecked" ) private <T> T createProxy( final T obj ) { final Enhancer e = new Enhancer(); e.setInterfaces( new Class[] { Serializable.class } ); final Class<? extends Object> class1 = obj.getClass(); e.setSuperclass( class1 ); e.setCallback( new DelegatingHandler( obj ) ); e.setNamingPolicy( new DefaultNamingPolicy() { @Override public String getClassName(final String prefix, final String source, final Object key, final Predicate names) { return super.getClassName( "MSM_" + prefix, source, key, names ); } } ); return (T) e.create(); } protected byte[] serialize( final Object o, final XMLBinding binding ) { if ( o == null ) { throw new NullPointerException( "Can't serialize null" ); } XMLObjectWriter writer = null; try { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); writer = XMLObjectWriter.newInstance( bos ); final XMLReferenceResolver xmlReferenceResolver = new XMLReferenceResolver(); xmlReferenceResolver.setIdentifierAttribute( JavolutionTranscoder.REFERENCE_ATTRIBUTE_ID ); xmlReferenceResolver.setReferenceAttribute( JavolutionTranscoder.REFERENCE_ATTRIBUTE_REF_ID ); writer.setReferenceResolver( xmlReferenceResolver ); writer.setBinding( binding ); writer.write( o, "root" ); writer.flush(); return bos.toByteArray(); } catch ( final Exception e ) { throw new IllegalArgumentException( "Non-serializable object", e ); } finally { try { writer.close(); } catch ( final XMLStreamException e ) { // fail silently } } } protected <T> T deserialize( final byte[] in, final XMLBinding binding ) { XMLObjectReader reader = null; try { final ByteArrayInputStream bis = new ByteArrayInputStream( in ); reader = XMLObjectReader.newInstance( bis ); final XMLReferenceResolver xmlReferenceResolver = new XMLReferenceResolver(); xmlReferenceResolver.setIdentifierAttribute( JavolutionTranscoder.REFERENCE_ATTRIBUTE_ID ); xmlReferenceResolver.setReferenceAttribute( JavolutionTranscoder.REFERENCE_ATTRIBUTE_REF_ID ); reader.setReferenceResolver( xmlReferenceResolver ); reader.setBinding( binding ); if ( !reader.hasNext() ) { throw new IllegalStateException( "reader has no input" ); } return reader.<T> read( "root" ); } catch ( final RuntimeException e ) { LOG.error( "Could not deserialize.", e ); throw e; } catch ( final javolution.xml.stream.XMLStreamException e ) { LOG.error( "Could not deserialize.", e ); throw new RuntimeException( e ); } finally { try { reader.close(); } catch ( final XMLStreamException e ) { // fail silently } } } public static class DelegatingHandler implements InvocationHandler, Serializable { private static final long serialVersionUID = 1L; private final Object _delegate; public DelegatingHandler( final Object delegate ) { _delegate = delegate; } public Object invoke( final Object obj, final Method method, final Object[] args ) throws Throwable { return method.invoke( _delegate, args ); } } public static class ClassToProxy { private String _value; /** * @param value the value to set */ public void setValue( final String value ) { _value = value; } /** * @return the value */ public String getValue() { return _value; } } }
3e1380a990edb1d40f1574fd3b6c1b05c6d17374
548
java
Java
TDList Android App/TDList/app/src/main/java/com/sk/tdlist/TaskViewActivity.java
kartik2112/TDList
218461a0c5bc2828d5dde7adc13f6ff9c3a976aa
[ "MIT" ]
5
2017-02-02T20:01:42.000Z
2019-02-19T14:29:43.000Z
TDList Android App/TDList/app/src/main/java/com/sk/tdlist/TaskViewActivity.java
kartik2112/TDList
218461a0c5bc2828d5dde7adc13f6ff9c3a976aa
[ "MIT" ]
5
2017-02-04T17:38:01.000Z
2017-04-02T18:02:27.000Z
TDList Android App/TDList/app/src/main/java/com/sk/tdlist/TaskViewActivity.java
kartik2112/TDList
218461a0c5bc2828d5dde7adc13f6ff9c3a976aa
[ "MIT" ]
3
2019-02-14T13:38:30.000Z
2019-04-30T14:58:58.000Z
21.92
73
0.671533
8,235
package com.sk.tdlist; import android.app.Activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; public class TaskViewActivity extends AppCompatActivity { @Override public void onCreate(Bundle state) { super.onCreate(state); String word=getIntent().getStringExtra(WidgetHandler.EXTRA_WORD); if (word==null) { word="We did not get a word!"; } Toast.makeText(this, word, Toast.LENGTH_LONG).show(); finish(); } }