text
stringlengths
10
2.72M
package com.oneteam.graduationproject; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.oneteam.graduationproject.Utils.NetworkUtils; import java.io.IOException; import java.net.URL; import butterknife.Bind; import butterknife.ButterKnife; public class LoginActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Boolean> { public int LOGIN_LOADER_ID = 22; @Bind(R.id.input_email) EditText _emailText; @Bind(R.id.input_password) EditText _passwordText; @Bind(R.id.btn_login) Button _loginButton; @Bind(R.id.link_signup) TextView _signupLink; ProgressDialog progressDialog; private UserSession zUserSession; private String zEmail; private String zPassword; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); ButterKnife.bind(this); zUserSession = new UserSession(this); // checking if the user already has email and password //if there is no data this func will launch the login activity && if not it does nothing zUserSession.checkLogin(); _loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { login(); } }); _signupLink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Start the Signup activity Intent intent = new Intent(getApplicationContext(), SignUpActivity.class); startActivity(intent); overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); finish(); } }); } public void login() { if (!validate()) { onLoginFailed(); return; } progressDialog = new ProgressDialog(LoginActivity.this, R.style.AppTheme_Dark_Dialog); progressDialog.setIndeterminate(true); progressDialog.setMessage("Authenticating..."); progressDialog.show(); getSupportLoaderManager().initLoader(LOGIN_LOADER_ID, null, this); } private void checkIfAuthorized(Boolean status) { if (status) { Toast.makeText(this, "Authorized !", Toast.LENGTH_SHORT).show(); zUserSession.createLoginSession(zEmail, zPassword, "",""); // Staring HomeActivity startActivity(new Intent(getApplicationContext(), HomeActivity.class)); progressDialog.dismiss(); finish(); } else { Toast.makeText(this, "Un Authorized !", Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); } } @Override public void onBackPressed() { moveTaskToBack(true); } public void onLoginFailed() { Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_SHORT).show(); } public boolean validate() { boolean valid = true; zEmail = _emailText.getText().toString(); zPassword = _passwordText.getText().toString(); // I disabled checking for email format to be able to send usernames if (zEmail.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(zEmail).matches()) { _emailText.setError("Enter a valid email address"); valid = false; } else { _emailText.setError(null); } if (zPassword.isEmpty() || zPassword.length() < 6) { _passwordText.setError("Password is too short !"); valid = false; } else { _passwordText.setError(null); } return valid; } @Override public Loader<Boolean> onCreateLoader(int id, final Bundle args) { return new AsyncTaskLoader<Boolean>(this) { @Override protected void onStartLoading() { forceLoad(); } @Override public Boolean loadInBackground() { URL url = NetworkUtils.buildLoginUrl(zEmail, zPassword); String jsonLoginResponse; try { jsonLoginResponse = NetworkUtils.getLoginResponse(url); return NetworkUtils.getStatus(jsonLoginResponse); } catch (IOException e) { Log.e("Error:", "Error making login request"); return null; } } }; } @Override public void onLoadFinished(Loader<Boolean> loader, Boolean data) { checkIfAuthorized(data); } @Override public void onLoaderReset(Loader<Boolean> loader) { } }
package interviews.offerup; import java.util.Arrays; public class Onsite { // 1. what is queue and stack, and how to implements them, how to implement // queue with stack? // 2. parking lot design, what does the interaction like when the API used // by other developer? // if else judgment, throw exception and design callback interface. // 3. design communication format alike Netflix between client and server // 4. FindCommon in two date range and sort an random a-z char array with // given swapWithA(int pos) method char[] arr; public static void main(String[] args) { Onsite app = new Onsite(); char[] arr2 = new char[]{'c', 'f', 'g', 'e', 'b', 'a', 'd'}; app.sort(arr2); System.out.println(Arrays.toString(arr2)); } public void sort(char[] arr) { this.arr = arr; swapWithA(0); for (int i = 1; i < 7; i++) { while (arr[i] - 'a' != i) { swapWithA(arr[i] - 'a'); swapWithA(i); swapWithA(0); } } } private void swapWithA(int i) { int p = 0; for (int j = 0; j < arr.length; j++) { if(arr[j] == 'a') { p = j; break; } } char temp = arr[i]; arr[i] = arr[p]; arr[p] = temp; } }
package push; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Query; public class SendPush extends HttpServlet { private final int MAXNUM = 500; private final String OLDBOOKKEY = "AIzaSyC5hoQ5DzZ1Qtj-sBzrpc6NYEbE8b9KTBM"; public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Sender sender = new Sender(OLDBOOKKEY); // 구글 코드에서 발급받은 서버 키 String GCMID = null; String sellerID = req.getParameter("sellerID"); String myID = req.getParameter("myID"); String title = req.getParameter("sellerTitle"); String phone = req.getParameter("phone"); Message msg = new Message.Builder() .addData("push", "제목:" + title + ", 구매자:" + myID + ", 번호:" + phone) .build(); DatastoreService datastore = DatastoreServiceFactory .getDatastoreService(); Query query = new Query("Member").addSort("date", Query.SortDirection.DESCENDING); List<Entity> entities = datastore.prepare(query).asList( FetchOptions.Builder.withLimit(MAXNUM)); if (entities.isEmpty()) { resp.getWriter().print("null"); } else { for (Entity entity : entities) { if (sellerID.equals(entity.getProperty("ID").toString())) { GCMID = entity.getProperty("GCMID").toString(); break; } } } // 푸시 전송. 파라미터는 푸시 내용, 보낼 단말의 id, 마지막은 잘 모르겠음 Result result = sender.send(msg, GCMID, 5); // 결과 처리 if (result.getMessageId() != null) { // 푸시 전송 성공 resp.getWriter().print("succeed push"); } else { String error = result.getErrorCodeName(); // 에러 내용 받기 // 에러 처리 if (Constants.ERROR_INTERNAL_SERVER_ERROR.equals(error)) { // 구글 푸시 서버 에러 resp.getWriter().print("google server error"); } else resp.getWriter().print(error); } // 정보 저장하기 } }
/* * 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 src; /** * * @author pller */ import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.BorderLayout; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.JPanel; import java.awt.Color; import javax.swing.JButton; import java.awt.FlowLayout; import javax.swing.JSeparator; import javax.swing.SwingConstants; import javax.swing.BoxLayout; import javax.swing.JCheckBox; import javax.swing.JList; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.AbstractListModel; import javax.swing.JScrollBar; import javax.swing.ListSelectionModel; import javax.swing.JScrollPane; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * * @author pller */ public class MainWindow2 { private JFrame frmProjetapplication; private JTextField txtNom; private JTextField txtAdresse; private JTextField txtAge; /** * Launch the application. */ public static void CreateWindow() { EventQueue.invokeLater(new Runnable() { public void run() { try { MainWindow window = new MainWindow(); window.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public MainWindow2() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frmProjetapplication = new JFrame(); frmProjetapplication.setTitle("Projet_Application"); frmProjetapplication.setBounds(100, 100, 700, 500); frmProjetapplication.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmProjetapplication.getContentPane().setLayout(null); JPanel panel = new JPanel(); panel.setBackground(Color.LIGHT_GRAY); panel.setBounds(10, 11, 266, 439); frmProjetapplication.getContentPane().add(panel); panel.setLayout(null); JLabel lblRsultat = new JLabel("R\u00E9sultat"); lblRsultat.setHorizontalAlignment(SwingConstants.CENTER); lblRsultat.setBounds(10, 0, 246, 40); panel.add(lblRsultat); txtNom = new JTextField(); txtNom.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { txtNom.setText(""); } }); txtNom.setText("Nom"); txtNom.setBounds(304, 113, 321, 37); frmProjetapplication.getContentPane().add(txtNom); txtNom.setColumns(10); txtAdresse = new JTextField(); txtAdresse.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { txtAdresse.setText(""); } }); txtAdresse.setText("Adresse "); txtAdresse.setBounds(304, 161, 321, 37); frmProjetapplication.getContentPane().add(txtAdresse); txtAdresse.setColumns(10); JLabel lblAjouterUneDonnee = new JLabel("Ajouter une donn\u00E9e"); lblAjouterUneDonnee.setHorizontalAlignment(SwingConstants.CENTER); lblAjouterUneDonnee.setBounds(304, 11, 321, 40); frmProjetapplication.getContentPane().add(lblAjouterUneDonnee); JButton btnNewButton = new JButton("Ajouter"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { //TODO Action quand on clique sur le bouton. } }); btnNewButton.setBounds(304, 386, 321, 43); frmProjetapplication.getContentPane().add(btnNewButton); JCheckBox chckbxPatient = new JCheckBox("Homme"); chckbxPatient.setBounds(304, 83, 97, 23); frmProjetapplication.getContentPane().add(chckbxPatient); JCheckBox chckbxHpital = new JCheckBox("Femme"); chckbxHpital.setBounds(528, 83, 97, 23); frmProjetapplication.getContentPane().add(chckbxHpital); JLabel lblSlectionnerLeType = new JLabel("S\u00E9lectionner le type de lit requis"); lblSlectionnerLeType.setBounds(304, 287, 321, 14); frmProjetapplication.getContentPane().add(lblSlectionnerLeType); txtAge = new JTextField(); txtAge.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { txtAge.setText(""); } }); txtAge.setText("Date de naissance (jj/mm/yyyy)"); txtAge.setBounds(304, 209, 321, 40); frmProjetapplication.getContentPane().add(txtAge); txtAge.setColumns(10); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(304, 312, 321, 43); frmProjetapplication.getContentPane().add(scrollPane); JList<String> list = new JList<String>(); scrollPane.setViewportView(list); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setModel(new AbstractListModel() { String[] values = new String[] {"Soins intensifs", "Soins paliatifs", "Traumatologie", "Autre"}; public int getSize() { return values.length; } public Object getElementAt(int index) { return values[index]; } }); } }
package LessonsJavaCore_8.Local.Eng; public enum MonthEng { JANUARY(31,"WINTER"), FEBRUARY(28,"WINTER"), MARCH(31,"SPRING"), APRIL(30,"SPRING"), MAY(31,"SPRING"), JUNE(30,"SUMMER"), JULY(31,"SUMMER"), AUGUST(31,"SUMMER"), SEPTEMBER(30,"AUTUMN"), OCTOBER(31,"AUTUMN"), NOVEMBER(30,"AUTUMN"), DECEMBER(31,"WINTER"); int inDays; String inSeasons; public int getInDays() { return inDays; } public void setInDays(int inDays) { this.inDays = inDays; } public String getInSeasons() { return inSeasons; } public void setInSeasons(String inSeasons) { this.inSeasons = inSeasons; } private MonthEng(int inDays, String inSeasons) { this.inDays = inDays; this.inSeasons = inSeasons; } }
package model; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; public class Client { private String username; private final ObjectInputStream objectInputStream; private final ObjectOutputStream objectOutputStream; public Client(Socket client) throws IOException { objectInputStream = new ObjectInputStream(client.getInputStream()); objectOutputStream = new ObjectOutputStream(client.getOutputStream()); } public void setUsername(String username) { this.username = username; } public String getUsername() { return username; } public ObjectInputStream getObjectInputStream() { return objectInputStream; } public ObjectOutputStream getObjectOutputStream() { return objectOutputStream; } }
package br.com.mbreno.banco; public class Endereco { String rua; int numero; int cep; String bairro; }
package com.example.walkerym.wym_ui_demo; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; /** * Created by walkerym on 2017/8/28. */ public class FruitAdapter extends ArrayAdapter<Fruit> { private int resourceId; class ViewHolder{ private ImageView imageView; private TextView textView; } public FruitAdapter(Context context, int textViewResourceId, List<Fruit> fruits){ super(context, textViewResourceId, fruits); resourceId = textViewResourceId; } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { Fruit fruit = getItem(position); View view; ViewHolder holder; if (convertView == null){ //注意:false 参数 view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false); holder = new ViewHolder(); holder.imageView = (ImageView) view.findViewById(R.id.image_view); holder.textView = (TextView) view.findViewById(R.id.text_view); view.setTag(holder); } else { view = convertView; holder = (ViewHolder) view.getTag(); } holder.imageView.setImageResource(fruit.getImageId()); holder.textView.setText(fruit.getFruitName()); return view; } }
/* * 2012-3 Red Hat Inc. and/or its affiliates and other contributors. * * 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.overlord.rtgov.activity.processor.mvel; import static org.junit.Assert.*; import javax.xml.parsers.DocumentBuilderFactory; import org.junit.Test; import org.overlord.rtgov.activity.processor.mvel.MVELInformationTransformer; public class MVELInformationTransformerTest { @Test public void testTransform() { MVELInformationTransformer transformer=new MVELInformationTransformer(); transformer.setExpression("information.value"); try { transformer.init(); } catch (Exception e) { fail("Evaluator should have initialized: "+e); } TestInfo info=new TestInfo(); String value=transformer.transform(info); if (value == null) { fail("Null value returned"); } if (!value.equals(info.value)) { fail("Value mismatch: "+value+" not equal "+info.value); } } @Test public void testTransformNonString1() { MVELInformationTransformer transformer=new MVELInformationTransformer(); transformer.setExpression("information.bool"); try { transformer.init(); } catch (Exception e) { fail("Evaluator should have initialized: "+e); } TestInfo info=new TestInfo(); String value=transformer.transform(info); if (value == null) { fail("Null value returned"); } if (!value.equals("true")) { fail("Value mismatch: "+value+" not equal true"); } } @Test public void testTransformNonString2() { MVELInformationTransformer transformer=new MVELInformationTransformer(); transformer.setExpression("information"); try { transformer.init(); } catch (Exception e) { fail("Evaluator should have initialized: "+e); } TestInfo info=new TestInfo(); String value=transformer.transform(info); if (value == null) { fail("Null value returned"); } if (!value.equals(info.toString())) { fail("Value mismatch: "+value+" not equal "+info.toString()); } } @Test public void testEvaluateBadExpression() { MVELInformationTransformer evaluator=new MVELInformationTransformer(); evaluator.setExpression("X X"); try { evaluator.init(); fail("Transformer should NOT have initialized"); } catch (Exception e) { } } @Test public void testTransformDOM() { org.w3c.dom.Document doc=null; try { doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); org.w3c.dom.Element elem=doc.createElement("test"); doc.appendChild(elem); elem.appendChild(doc.createTextNode("This is a test")); } catch (Exception e) { fail("Failed to build DOM: "+e); } MVELInformationTransformer transformer=new MVELInformationTransformer(); transformer.setExpression("import javax.xml.transform.TransformerFactory; "+ "import javax.xml.transform.Transformer; "+ "import javax.xml.transform.dom.DOMSource; "+ "import javax.xml.transform.stream.StreamResult; "+ "import java.io.ByteArrayOutputStream; "+ "ByteArrayOutputStream out = new ByteArrayOutputStream();"+ "DOMSource source = new DOMSource(information);"+ "StreamResult result = new StreamResult(out);"+ "TransformerFactory transFactory = TransformerFactory.newInstance();"+ "Transformer transformer = transFactory.newTransformer();"+ "transformer.transform(source, result);"+ "out.close();"+ "return new String(out.toByteArray());"); try { transformer.init(); } catch (Exception e) { e.printStackTrace(); fail("Evaluator should have initialized: "+e); } String value=transformer.transform(doc); if (value == null) { fail("Null value returned"); } if (!value.contains("<test>This is a test</test>")) { fail("Value does not contain original document information: "+value); } } public class TestInfo { public String value="Hello"; public boolean bool=true; public String toString() { return ("TestInfo"); } } }
package com.stickyblob.chords.utils; /** * Created by thisi on 5/24/2017. */ public class Chord { private double mSopranoNote; private double mAltoNote; private double mTenorNote; private double mBassNote; private int mIncrementInt; public Chord(double sopranoNote, double altoNote, double tenorNote, double bassNote, int incrementInt) { mSopranoNote = sopranoNote; mAltoNote = altoNote; mTenorNote = tenorNote; mBassNote = bassNote; mIncrementInt = incrementInt; } public Chord() { } public double getSopranoNote() { return mSopranoNote; } public void setSopranoNote(double sopranoNote) { mSopranoNote = sopranoNote; } public double getAltoNote() { return mAltoNote; } public void setAltoNote(double altoNote) { mAltoNote = altoNote; } public double getTenorNote() { return mTenorNote; } public void setTenorNote(double tenorNote) { mTenorNote = tenorNote; } public double getBassNote() { return mBassNote; } public void setBassNote(double bassNote) { mBassNote = bassNote; } public int getIncrementInt() { return mIncrementInt; } public void setIncrementInt(int incrementInt) { mIncrementInt = incrementInt; } }
package com.penzias.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.penzias.core.BasicServiceImpl; import com.penzias.core.interfaces.BasicMapper; import com.penzias.dao.ElectrocardiogramExamInfoMapper; import com.penzias.entity.ElectrocardiogramExamInfo; import com.penzias.entity.ElectrocardiogramExamInfoExample; import com.penzias.service.ElectrocardiogramExamInfoService; @Service("electrocardiogramExamInfoService") public class ElectrocardiogramExamInfoServiceImpl extends BasicServiceImpl<ElectrocardiogramExamInfoExample, ElectrocardiogramExamInfo> implements ElectrocardiogramExamInfoService { @Resource private ElectrocardiogramExamInfoMapper electrocardiogramExamInfoMapper; @Override public BasicMapper<ElectrocardiogramExamInfoExample, ElectrocardiogramExamInfo> getMapper(){ return electrocardiogramExamInfoMapper; } }
package kz.halyqteam.service; import edu.cmu.sphinx.api.Configuration; import edu.cmu.sphinx.api.SpeechResult; import edu.cmu.sphinx.api.StreamSpeechRecognizer; import edu.cmu.sphinx.decoder.adaptation.Stats; import edu.cmu.sphinx.decoder.adaptation.Transform; import edu.cmu.sphinx.result.WordResult; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; /** * @author Assylkhan * on 28.01.2019 * @project speech_rec_ee */ public class RecognizeService { public String recognize(InputStream stream ) throws Exception { System.out.println("Loading models..."); Configuration configuration = new Configuration(); configuration .setAcousticModelPath("cmusphinx-kz-5.2/model_parameters/kz.cd_cont_200"); configuration .setDictionaryPath("cmusphinx-kz-5.2/etc/kz.dic"); configuration .setLanguageModelPath("cmusphinx-kz-5.2/etc/kz.ug.lm"); System.out.println(System.getProperty("user.dir")); StreamSpeechRecognizer recognizer = new StreamSpeechRecognizer(configuration); stream.skip(44); recognizer.startRecognition(stream); SpeechResult result; while ((result = recognizer.getResult()) != null) { System.out.format("Hypothesis: %s\n", result.getHypothesis()); System.out.println("List of recognized words and their times:"); for (WordResult r : result.getWords()) { System.out.println(r); } System.out.println("Best 3 hypothesis:"); for (String s : result.getNbest(3)) System.out.println(s); } recognizer.stopRecognition(); stream.skip(44); Stats stats = recognizer.createStats(1); recognizer.startRecognition(stream); while ((result = recognizer.getResult()) != null) { stats.collect(result); } recognizer.stopRecognition(); Transform transform = stats.createTransform(); recognizer.setTransform(transform); // Decode again with updated transform stream.skip(44); recognizer.startRecognition(stream); String sentences = ""; while ((result = recognizer.getResult()) != null) { sentences += result.getHypothesis(); } recognizer.stopRecognition(); return "{ \"message\" : \"" + (sentences.length() > 0 ? sentences : "not recognized") + "\" , \"error\" : false} "; } }
package com.khaale.bigdatarampup.mapreduce.shared; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.Mapper; import java.nio.file.Path; public class ConfigurableFilePathProvider implements FilePathProvider { private final FilePathProvider localImpl; private final FilePathProvider distributedImpl; public ConfigurableFilePathProvider() { localImpl = new LocalFilePathProvider(); distributedImpl = new DistributedCacheFilePathProvider(); } @Override public Path getUserTagDictionaryPath(Mapper.Context context) { Configuration conf = context.getConfiguration(); String localFilePath = conf.get(LocalKey); if (localFilePath != null) { return localImpl.getUserTagDictionaryPath(context); } else { return distributedImpl.getUserTagDictionaryPath(context); } } }
package eu.clarin.cmdi.rasa.filters; import java.sql.Timestamp; public interface Filter<T>{ public T setUrlIs(String url); public T setUrlIn(String... urls); public T setSourceIs(String source); public T setProviderGroupIs(String providerGroup); public T setRecordIs(String record); public T setIngestionDateIs(Timestamp ingestionDate); public T setLimit(int offset, int limit); public T setIsActive(boolean active); public T setOrderByCheckingDate(boolean isAscending); }
package com.diozero.devices.sandpit.motor; /* * #%L * Organisation: diozero * Project: diozero - Core * Filename: StepperMotorInterface.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * 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. * #L% */ import com.diozero.api.DeviceInterface; /** * Common interface for stepper motors. The rotational speed is determined by the time allowed between steps and the * number of steps to complete a rotation. * <p> * Note that the {@link #getStrideAngle()} and {@link #getStepsPerRotation()} represent the same physical * characteristics of the motor. * <p> * <b>IMPORTANT NOTE!</b> Implementation/usage should not exceed the maximum rotational speed of the device, otherwise * bad things can happen. * * @author E. A. Graham Jr. * @see <a href="https://learn.adafruit.com/all-about-stepper-motors?view=all">What is a Stepper Motor?</a> */ public interface StepperMotorInterface extends DeviceInterface { /** * Which way to rotate: this is relative to observing the <i>face</i> of the motor - exactly like a clock. */ enum Direction { CLOCKWISE(1), COUNTERCLOCKWISE(-1), CW(1), CCW(-1), FORWARD(1), BACKWARD(-1); private final int direction; Direction(int d) { direction = d; } public int getDirection() { return direction; } } interface StepperMotorController extends DeviceInterface { /** * Should allow the spindle to move freely. */ void release(); } StepperMotorController getController(); /** * Get the stride-angle (degrees per step) for this motor. This <b>MUST</b> take into account any gearboxes. * * @return the angle */ float getStrideAngle(); /** * Get the number of full steps in a full rotation of the motor shaft. This <b>MUST</b> take into account any * gearboxes. * * @return the steps */ long getStepsPerRotation(); /** * Move a single step in the given direction at the default speed. No events are fired for this action. Not all * implementations support this. * * @param direction which way to rotate */ default void step(Direction direction) { throw new UnsupportedOperationException("Single-stepping is not implemented."); } /** * Releases the rotor (should allow free rotation). */ default void release() { getController().release(); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Methods { public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringBuffer sb=new StringBuffer(); String sn="Koshti"; String mn="Vijay"; String ln="Dineshbhai"; // System.out.println("Enter Surname: "); // String sur=br.readLine(); // System.out.println("Enter Middlename: "); // String mid=br.readLine(); // System.out.println("Enter Lastname: "); // String las=br.readLine(); sb.append(sn); sb.append(ln); System.out.println(sb); int n=sn.length(); sb.insert(n, mn); System.out.println("Full name: "+ sb); System.out.println("In reverse form: " +sb.reverse()); } }
package org.jasig.cas.me.dao.csswAccount; import org.jasig.cas.me.po.CsswAccount; public interface ICsswAccountDao { CsswAccount getAccountByNameAndPassword(String accountName,String accountPwd); CsswAccount getAccountByUid(String uid); CsswAccount getAccountByUid(Integer uid); }
package samples.jsr305.nullness; import java.io.IOException; import de.ruedigermoeller.heapoff.FSTCompressed; import de.ruedigermoeller.serialization.FSTConfiguration; public class UnannotatedExtendingLibClass extends FSTCompressed<String> { @Override public void set(String object) throws IOException { super.set(object); } @Override protected void storeArray(byte[] buffer, int written) { } @Override protected FSTConfiguration getConf() { return null; } @Override public byte[] getArray() { return null; } @Override public int getLen() { return 0; } @Override public int getOffset() { return 0; } }
package com.vilio.plms.pojo; import java.io.Serializable; import java.util.Date; /** * 公司表 */ public class PlmsCompany implements Serializable{ private int id; private String code; private String companyName; private String abbrName; private String companyType; private String status; private String bmsCode; private Date createDate; private Date modifyDate; public PlmsCompany() { } public PlmsCompany(int id, String code, String companyName, String abbrName, String companyType, String status, String bmsCode, Date createDate, Date modifyDate) { this.id = id; this.code = code; this.companyName = companyName; this.abbrName = abbrName; this.companyType = companyType; this.status = status; this.bmsCode = bmsCode; this.createDate = createDate; this.modifyDate = modifyDate; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getAbbrName() { return abbrName; } public void setAbbrName(String abbrName) { this.abbrName = abbrName; } public String getCompanyType() { return companyType; } public void setCompanyType(String companyType) { this.companyType = companyType; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getBmsCode() { return bmsCode; } public void setBmsCode(String bmsCode) { this.bmsCode = bmsCode; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } }
package com.tencent.mm.plugin.sns.abtest; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AbsoluteLayout; import com.tencent.mm.plugin.sns.abtest.NotInterestMenu.c; import com.tencent.mm.plugin.sns.i.a; import com.tencent.mm.sdk.platformtools.ad; public final class b { int JP = 0; int gwO = 0; int mScreenHeight = 0; NotInterestMenu nhD; ViewGroup nhE; NotInterestMenu$b nhF = new 1(this); Animation nhG = null; Animation nhH = null; private Animation nhI = null; private Animation nhJ = null; int nhK = 0; int nhL = 0; int nhM = 0; int nhN = 0; int nhO = 0; boolean nhP = false; AbsoluteLayout nhQ = null; boolean nhR = false; boolean nhS = false; c nhy; public b(ViewGroup viewGroup) { this.nhE = viewGroup; this.nhG = AnimationUtils.loadAnimation(ad.getContext(), a.dropdown_down); this.nhG.setFillAfter(true); this.nhG.setDuration(100); this.nhG.setAnimationListener(new 2(this)); this.nhH = AnimationUtils.loadAnimation(ad.getContext(), a.dropup_up); this.nhH.setFillAfter(true); this.nhH.setDuration(100); this.nhH.setAnimationListener(new 3(this)); this.nhI = AnimationUtils.loadAnimation(ad.getContext(), a.dropdown_up); this.nhI.setFillAfter(true); this.nhI.setDuration(100); this.nhI.setAnimationListener(new 4(this)); this.nhJ = AnimationUtils.loadAnimation(ad.getContext(), a.dropup_down); this.nhJ.setFillAfter(true); this.nhJ.setDuration(100); this.nhJ.setAnimationListener(new 5(this)); } public final void bwH() { if (this.nhQ != null && this.nhE != null && this.nhD != null) { this.nhQ.removeView(this.nhD); this.nhE.removeView(this.nhQ); this.nhQ = null; this.nhD = null; this.nhP = false; } } }
package hello.hellospring.controller; import hello.hellospring.damain.Member; import hello.hellospring.service.MemberService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @Controller public class MemberController { private static final Logger log = LogManager.getLogger(MemberController.class); private final MemberService memberService; public MemberController(final MemberService memberService) { this.memberService = memberService; } @GetMapping(value = "/members/new") public String createForm() { return "members/createMemberForm"; } @PostMapping(value = "/members/new") public String create(final MemberForm form) { log.info("form={}", form); final var member = new Member(); member.setName(form.name()); log.info("member={}", member); this.memberService.join(member); return "redirect:/"; } @GetMapping(value = "/members") public String list(final Model model) { final var members = this.memberService.findMembers(); model.addAttribute("members", members); return "members/memberList"; } }
package com.zhangyu.lock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockTest { public static void main(String[] args) { Ticket ticket = new Ticket(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 30; i++) { ticket.sale(); } } }, "aa").start(); new Thread(()->{for (int i = 0; i < 30; i++) ticket.sale();},"bb").start();//lambda表达式写法 } } //卖票实例 class Ticket { private int number = 30; private Lock lock = new ReentrantLock(); //卖票的方法 public void sale() { lock.lock(); try { System.out.println(); } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } }
package co.edu.banco.echo; import java.io.IOException; import java.net.Socket; public class EchoTCPClient { public static final int PORT = 12676; public static final String SERVER = "6.tcp.ngrok.io"; private Socket clientSideSocket; private EchoTCPClientProtocol clientProtocol; public EchoTCPClient() throws Exception { init(); } public void init() throws Exception { clientSideSocket = new Socket(SERVER, PORT); clientProtocol = new EchoTCPClientProtocol(); clientProtocol.protocol(clientSideSocket); } public String realizarTransaccion(String comando) throws IOException { String respuesta; if(comando.startsWith("CARGA")) respuesta = clientProtocol.cargaAutomatica(comando); else respuesta = clientProtocol.procesarTransaccion(comando); return respuesta; } public void cerrarConexion() throws IOException { clientSideSocket.close(); } }
package service; import java.util.HashMap; /** * Created by xheart on 2016/8/14. */ public interface RoleService { /** * 列出角色 * @return 角色列表 */ HashMap<String, Object> list(int pageNumber, int pageSize); }
/* * Copyright (C) 2015 Miquel Sas * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.library.trading.chart; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JPanel; import com.qtplaf.library.swing.ActionUtils; import com.qtplaf.library.swing.core.SwingUtils; import com.qtplaf.library.trading.chart.parameters.InformationPlotParameters; import com.qtplaf.library.util.Icons; /** * A panel located at the top of the container, aimed to contain an info panel and necessary controls like the close * button. * * @author Miquel Sas */ public class JChartInfo extends JPanel { /** * The info panel. */ class JPanelInfo extends JPanel { /** * Default constructor. */ JPanelInfo() { super(); } /** * Paint this info panel. * * @param g The graphics object. */ @Override public void paint(Graphics g) { super.paint(g); // If no info items to paint, do nothing. if (infoItems.isEmpty()) { return; } Graphics2D g2 = (Graphics2D) g; // Info plot params. InformationPlotParameters plotParameters = chartContainer.getChart().getInfoPlotParameters(); // Save the current color and font. Color saveColor = g2.getColor(); Font saveFont = g2.getFont(); // Set the font. g2.setFont(plotParameters.getInfoTextFont()); // Retrieve the font metrics to calculate the font total height. FontMetrics fm = g2.getFontMetrics(); // Starting X and Y int x = plotParameters.getInfoTextInsets().left; int y = plotParameters.getInfoTextInsets().top + fm.getMaxAscent(); // Separator control flag. boolean separator = false; // Iterate groups. Iterator<InfoItem> i = infoItems.iterator(); while (i.hasNext()) { InfoItem infoItem = i.next(); // If the item is not active skip it. if (!infoItem.isActive()) { continue; } // If the item is empty, skip it. if (infoItem.isEmpty()) { continue; } // If necessary paint the separator. if (separator) { g2.setColor(plotParameters.getInfoSeparatorColor()); String separatorStrings = plotParameters.getInfoSeparatorString(); g2.drawString(separatorStrings, x, y); x += fm.stringWidth(separatorStrings); } // Paint the item. String text = infoItem.getText(); Color color = infoItem.getColor(); if (infoItem.getStyle() != plotParameters.getInfoTextFont().getStyle()) { Font itemFont = new Font( plotParameters.getInfoTextFont().getName(), infoItem.getStyle(), plotParameters.getInfoTextFont().getSize()); g2.setFont(itemFont); } g2.setColor(color); g2.drawString(text, x, y); x += fm.stringWidth(text); // From now the separator is needed. separator = true; // Restore the working font if necessary. if (infoItem.getStyle() != plotParameters.getInfoTextFont().getStyle()) { g2.setFont(plotParameters.getInfoTextFont()); } } // Restore the color and font. g2.setColor(saveColor); g2.setFont(saveFont); } } /** * The action class for the close button. */ class ActionCloseButton extends AbstractAction { /** * Default constructor. */ ActionCloseButton() { super(); ActionUtils.setSmallIcon(this, Icons.chart_16x16_titlebar_close_tab); } /** * Perform the action, remove this chart container. * * @param e The action event. */ @Override public void actionPerformed(ActionEvent e) { chartContainer.getChart().removeChartContainer(chartContainer); } } /** * An information item that is a text with a color. */ class InfoItem { /** * The string identifier. */ private String id; /** * The info text. */ private String text; /** * The info color. */ private Color color; /** * The font style. */ private int style = Font.PLAIN; /** * A boolean that indicates if the info item is active. */ private boolean active = true; /** * Constructor assigning text, color and style. * * @param id The info identifier. */ InfoItem(String id) { super(); this.id = id; } /** * Returns the string identifier. * * @return The string identifier. */ public String getId() { return id; } /** * Returns the text. * * @return The text. */ public String getText() { return text; } /** * Sets the text. * * @param text The text. */ public void setText(String text) { this.text = text; } /** * Returns the color. * * @return The color. */ public Color getColor() { return color; } /** * Sets the color. * * @param color The color. */ public void setColor(Color color) { this.color = color; } /** * Returns the font style. * * @return The font style. */ public int getStyle() { return style; } /** * Sets the font style. * * @param style The font style. */ public void setStyle(int style) { this.style = style; } /** * Returns a boolean indicating if this info item is active. * * @return A boolean indicating if this info item is active. */ public boolean isActive() { return active; } /** * Sets a boolean indicating if this info item is active. * * @param active A boolean indicating if this info item is active. */ public void setActive(boolean active) { this.active = active; } /** * Check if this info item is empty. * * @return A boolean that indicates that the info is empty. */ public boolean isEmpty() { return text == null || text.isEmpty(); } /** * Check for equality. * * @param o The object to compare. */ @Override public boolean equals(Object o) { if (o instanceof InfoItem) { InfoItem item = (InfoItem) o; return getId().equals(item.getId()); } return false; } } /** * A set of info items indexed by a string identifier. */ class InfoItemSet { /** * The set of info items. */ private Set<InfoItem> set = new LinkedHashSet<>(); /** * The map to index them by identifier. */ private HashMap<String, InfoItem> map = new HashMap<>(); /** * Default constructor. */ InfoItemSet() { super(); } /** * Add an item indexed by id. * * @param item Theinfo item. */ public void add(InfoItem item) { set.add(item); map.put(item.getId(), item); } /** * Returns the info item with the give id or null if not exists. * * @param id The id. * @return The info item with the give id or null if not exists. */ public InfoItem get(String id) { return map.get(id); } /** * Removes the info item with the given id. * * @param id The id. */ public void remove(String id) { InfoItem item = get(id); if (item != null) { set.remove(item); map.remove(id); } } /** * Clear the info item set. */ public void clear() { set.clear(); map.clear(); } /** * Check for emptyness. * * @return A boolean. */ public boolean isEmpty() { return set.isEmpty(); } /** * Returns an iterator on the info items. * * @return The iterator. */ public Iterator<InfoItem> iterator() { return set.iterator(); } } /** * The parent chart container. */ private JChartContainer chartContainer; /** * An information JPanel. A panel is used instead of a label to have the hability to better control fonts and colors * for each part of the text. */ private JPanelInfo panelInfo; /** * Close button. */ private JButton buttonClose; /** * The set of info items indexes by id. */ private InfoItemSet infoItems = new InfoItemSet(); /** * Constructor assigning the parent chart container. * * @param chartContainer The parent chart container. */ public JChartInfo(JChartContainer chartContainer) { super(); this.chartContainer = chartContainer; // Info plot params. InformationPlotParameters parameters = chartContainer.getChart().getInfoPlotParameters(); // Set the backgroud color. setBackground(parameters.getInfoBackgroundColor()); // Layout setLayout(new GridBagLayout()); // Layout panels. layoutPanels(); } /** * Layout panels and buttons. */ private void layoutPanels() { removeAll(); // Constraints info panel. GridBagConstraints constraintsPanelInfo = new GridBagConstraints(); constraintsPanelInfo.anchor = GridBagConstraints.WEST; constraintsPanelInfo.fill = GridBagConstraints.HORIZONTAL; constraintsPanelInfo.gridheight = 1; constraintsPanelInfo.gridwidth = 1; constraintsPanelInfo.weightx = 1; constraintsPanelInfo.weighty = 1; constraintsPanelInfo.gridx = 0; constraintsPanelInfo.gridy = 0; constraintsPanelInfo.insets = new Insets(0, 0, 0, 0); // Info plot params. InformationPlotParameters plotParameters = chartContainer.getChart().getInfoPlotParameters(); // Calculate the size based on the desired font and insets. The graphics context needs to be that of the upper // level chart, because it is the only one displayed at this time. FontMetrics fm = SwingUtils.getFontMetrics(plotParameters.getInfoTextFont()); int size = plotParameters.getInfoTextInsets().top + fm.getMaxAscent() + fm.getMaxDescent() + plotParameters.getInfoTextInsets().bottom; // Define and add the info panel. panelInfo = new JPanelInfo(); panelInfo.setMinimumSize(new Dimension(0, size)); panelInfo.setMaximumSize(new Dimension(0, size)); panelInfo.setPreferredSize(new Dimension(0, size)); add(panelInfo, constraintsPanelInfo); // Constraints close button. GridBagConstraints constraintsButtonClose = new GridBagConstraints(); constraintsButtonClose.anchor = GridBagConstraints.EAST; constraintsPanelInfo.fill = GridBagConstraints.BOTH; constraintsButtonClose.gridheight = 1; constraintsButtonClose.gridwidth = 1; constraintsButtonClose.weightx = 0; constraintsButtonClose.weighty = 0; constraintsButtonClose.gridx = 1; constraintsButtonClose.gridy = 0; constraintsButtonClose.insets = new Insets(0, 0, 0, 0); // Defina and add the close button. buttonClose = new JButton(new ActionCloseButton()); buttonClose.setMinimumSize(new Dimension(size, size)); buttonClose.setMaximumSize(new Dimension(size, size)); buttonClose.setPreferredSize(new Dimension(size, size)); add(buttonClose, constraintsButtonClose); } /** * Sets the panel iinfo background color. * * @param color The color. */ public void setPanelInfoBackgorund(Color color) { panelInfo.setBackground(color); } /** * Set the properties to the info item. * * @param id The info item id. * @param text The text. * @param color The color. * @param repaint A boolean that idicates if the info panel should immediatly be repainted. */ public void setInfo(String id, String text, Color color, boolean repaint) { setInfo(id, text, color, -1, repaint); } /** * Set the properties to the info item. * * @param id The info item id. * @param text The text. * @param color The color. * @param style The font style. * @param repaint A boolean that idicates if the info panel should immediatly be repainted. */ public void setInfo(String id, String text, Color color, int style, boolean repaint) { InfoItem infoItem = infoItems.get(id); if (infoItem == null) { infoItem = new InfoItem(id); infoItems.add(infoItem); } if (text != null) { infoItem.setText(text); } if (color != null) { infoItem.setColor(color); } if (style >= 0) { infoItem.setStyle(style); } infoItem.setActive(true); if (repaint) { panelInfo.repaint(); } } /** * Returns the info item of the given identifier. * * @param id The identifier. * @return The corrsponding info item. */ public InfoItem getInfo(String id) { return infoItems.get(id); } /** * Activates the info. * * @param id The info id. */ public void activateInfo(String id) { if (getInfo(id) != null) { getInfo(id).setActive(true); } } /** * Dectivates the info. * * @param id The info id. */ public void deactivateInfo(String id) { if (getInfo(id) != null) { getInfo(id).setActive(false); } } /** * Repaint info items. */ public void repaintInfo() { panelInfo.repaint(); } /** * Remove the info item with the given id. * * @param id The id. */ public void removeInfo(String id) { infoItems.remove(id); } /** * Returns the parent container. * * @return The parent container. */ public JChartContainer getChartContainer() { return chartContainer; } }
package 笔试代码.list; import 笔试代码.list.ListNode; import java.util.List; public class 删除排序链表中的重复元素lee_83 { public void deleteDupNum(int[] num) { int slow = 0; int fast = 1; while (fast < num.length) { if (num[fast] != num[slow]) { num[++slow] = num[fast]; } fast++; } } public ListNode deleteDuplicates2(ListNode head){ ListNode slow=head; ListNode fast=head.next; while (fast!=null){ if(fast.val!=slow.val){//不相等 才后移 slow.next=fast; slow=slow.next; } fast=fast.next; } slow.next=null;//注意这个 return head; } public ListNode deleteDuplicates(ListNode head) { if(head==null){ return head; } ListNode cur=head.next; ListNode pre=head; while (cur!=null){ if(cur.val==pre.val){ pre.next=cur.next; cur=cur.next; }else { pre=pre.next; cur=cur.next; } } return head; } }
package codeclan.com.raymusicshop; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; /** * Created by user on 03/11/2017. */ public class MusicSheetTest { MusicSheet musicsheet; @Before public void before() { musicsheet = new MusicSheet(6, 3, "Living on a prayer"); } @Test public void canGetSellPrice() { assertEquals(6, musicsheet.getSellPrice()); } @Test public void canGetBuyValue() { assertEquals(3, musicsheet.getBuyPrice()); } @Test public void caGetTitle() { assertEquals("Living on a prayer", musicsheet.getTitle()); } }
package com.neo.solr; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery.ORDER; import org.apache.solr.client.solrj.SolrQuery.SortClause; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.impl.XMLResponseParser; import org.apache.solr.client.solrj.response.QueryResponse; /** * @Description: TODO * @author: wangyunpeng * @date: 2015年4月14日下午4:44:47 */ public class SolrSearch { /** * @Description: TODO * @author: wangyunpeng * @date: 2015年4月14日下午4:44:47 * @param args */ public static void main(String[] args) { /* * http://10.144.52.195:8080/solr/gome/select?q=*%3A*&wt=json&indent=true */ try { Map<String, String> map = new HashMap<String, String>(); map.put("q", "subject:山"); map.put("wt", "json"); map.put("indent", "true"); String content = HttpUtil.getRequestContent(map); String url_str = "http://10.144.52.195:8080/solr/gome/select"; String res = HttpUtil.doHttpPost(content, HttpUtil.CONTENTTYPE_WWWFROM, HttpUtil.CHARSET_UTF8, url_str); System.out.println(res); } catch (Exception e) { e.printStackTrace(); } } }
/** * @Copyright CopperMobile 2014. * */ package com.atn.app.component; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.widget.Button; import com.atn.app.R; import com.atn.app.utils.TypefaceUtils; //custom button handle different type of type face public class MyButton extends Button { public MyButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(context, attrs, defStyle); } public MyButton(Context context, AttributeSet attrs) { super(context, attrs); initView(context, attrs, 0); } public MyButton(Context context) { super(context); } private void initView(Context context, AttributeSet attrs, int defStyle) { //for eclipse preview xml if(isInEditMode()) return; //get type face and apply TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomFontStyle, 0, 0); try { setTypeface(TypefaceUtils.getTypeface(context, a.getInteger(R.styleable.CustomFontStyle_customFont, 0))); } catch(Exception e){}finally { a.recycle(); } } }
package com.tencent.mm.plugin.mmsight.segment; import android.media.MediaCodec; import android.media.MediaCodec.BufferInfo; import android.media.MediaExtractor; import android.media.MediaFormat; import android.os.HandlerThread; import com.tencent.mm.modelcontrol.VideoTransPara; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.x; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; public final class g { private long aBL; String ldm = null; private MediaExtractor ldo; private long lkn; MediaCodec llj; MediaCodec llk; MediaFormat lll; MediaFormat llm; VideoTransPara lln; boolean llo = true; List<byte[]> llp = null; private boolean llq = false; private boolean llr = false; private byte[] lls; private HandlerThread llt = null; private ag llu = null; public g(MediaExtractor mediaExtractor, MediaFormat mediaFormat, long j, long j2, VideoTransPara videoTransPara) { this.ldo = mediaExtractor; this.lll = mediaFormat; this.aBL = j; this.lkn = j2; this.lln = videoTransPara; this.ldm = mediaFormat.getString("mime"); this.llp = new ArrayList(); x.i("MicroMsg.MediaCodecAACTranscoder", "create MediaCodecAACTranscoder, startTimeMs: %s, endTimeMs: %s, mime: %s, srcMediaFormat: %s, para: %s", new Object[]{Long.valueOf(j), Long.valueOf(j2), this.ldm, mediaFormat, videoTransPara}); } public final void beT() { this.llq = false; this.llr = false; while (this.llj != null && this.ldo != null) { try { ByteBuffer[] inputBuffers = this.llj.getInputBuffers(); int dequeueInputBuffer = this.llj.dequeueInputBuffer(20000); if (dequeueInputBuffer < 0) { x.d("MicroMsg.MediaCodecAACTranscoder", "decoder no input buffer available, drain first"); beU(); } if (dequeueInputBuffer >= 0) { boolean z; x.d("MicroMsg.MediaCodecAACTranscoder", "decoderInputBufferIndex: %d", new Object[]{Integer.valueOf(dequeueInputBuffer)}); ByteBuffer byteBuffer = inputBuffers[dequeueInputBuffer]; byteBuffer.clear(); byteBuffer.position(0); int readSampleData = this.ldo.readSampleData(byteBuffer, 0); long sampleTime = this.ldo.getSampleTime(); this.ldo.advance(); x.d("MicroMsg.MediaCodecAACTranscoder", "sampleSize: %s, pts: %s", new Object[]{Integer.valueOf(readSampleData), Long.valueOf(sampleTime)}); if (sampleTime >= this.lkn * 1000 || sampleTime <= 0 || readSampleData <= 0) { x.i("MicroMsg.MediaCodecAACTranscoder", "reach end time, send EOS and try delay stop decoder"); this.llr = true; ah.i(new 1(this), 500); z = true; } else { z = false; } if (this.llj == null) { return; } if (z) { x.i("MicroMsg.MediaCodecAACTranscoder", "EOS received in sendAudioToEncoder"); this.llj.queueInputBuffer(dequeueInputBuffer, 0, readSampleData, sampleTime, 4); } else { this.llj.queueInputBuffer(dequeueInputBuffer, 0, readSampleData, sampleTime, 0); } } beU(); if (this.llr && this.llk == null) { return; } } catch (Throwable e) { x.printErrStackTrace("MicroMsg.MediaCodecAACTranscoder", e, "startTranscodeBlockLoop error: %s", new Object[]{e.getMessage()}); return; } } x.e("MicroMsg.MediaCodecAACTranscoder", "startTranscodeBlockLoop error"); } private void beU() { if (this.llj != null) { try { ByteBuffer[] outputBuffers = this.llj.getOutputBuffers(); BufferInfo bufferInfo = new BufferInfo(); ByteBuffer[] byteBufferArr = outputBuffers; while (true) { int dequeueOutputBuffer = this.llj.dequeueOutputBuffer(bufferInfo, 20000); x.d("MicroMsg.MediaCodecAACTranscoder", "decoderOutputBufferIndex: %s", new Object[]{Integer.valueOf(dequeueOutputBuffer)}); if (dequeueOutputBuffer == -1) { x.d("MicroMsg.MediaCodecAACTranscoder", "no output available, break"); return; } else if (dequeueOutputBuffer == -3) { byteBufferArr = this.llj.getOutputBuffers(); } else if (dequeueOutputBuffer == -2) { this.lll = this.llj.getOutputFormat(); x.i("MicroMsg.MediaCodecAACTranscoder", "srcMediaFormat change: %s", new Object[]{this.lll}); } else if (dequeueOutputBuffer < 0) { x.e("MicroMsg.MediaCodecAACTranscoder", "unexpected decoderOutputBufferIndex: %s", new Object[]{Integer.valueOf(dequeueOutputBuffer)}); } else { x.v("MicroMsg.MediaCodecAACTranscoder", "perform decoding"); ByteBuffer byteBuffer = byteBufferArr[dequeueOutputBuffer]; if (byteBuffer == null) { x.e("MicroMsg.MediaCodecAACTranscoder", "ERROR, retrieve decoderOutputBuffer is null!!"); return; } if ((bufferInfo.flags & 2) != 0) { x.e("MicroMsg.MediaCodecAACTranscoder", "ignore BUFFER_FLAG_CODEC_CONFIG"); bufferInfo.size = 0; } if (bufferInfo.size > 0) { byteBuffer.position(bufferInfo.offset); byteBuffer.limit(bufferInfo.offset + bufferInfo.size); a(byteBuffer, bufferInfo, (bufferInfo.flags & 4) != 0); } this.llj.releaseOutputBuffer(dequeueOutputBuffer, false); if ((bufferInfo.flags & 4) != 0) { x.i("MicroMsg.MediaCodecAACTranscoder", "receive EOS!"); if (this.llj != null) { this.llj.stop(); this.llj.release(); this.llj = null; return; } return; } } } } catch (Throwable e) { x.printErrStackTrace("MicroMsg.MediaCodecAACTranscoder", e, "drainDecoder error: %s", new Object[]{e.getMessage()}); } } } private void a(ByteBuffer byteBuffer, BufferInfo bufferInfo, boolean z) { if (byteBuffer != null) { x.d("MicroMsg.MediaCodecAACTranscoder", "processDecodeBuffer, EOS: %s, finishGetAllInputAACData: %s", new Object[]{Boolean.valueOf(z), Boolean.valueOf(this.llr)}); if (this.llo) { if (!this.llq) { beV(); this.llq = true; } if (this.lls == null) { this.lls = new byte[byteBuffer.remaining()]; byteBuffer.get(this.lls, 0, byteBuffer.remaining()); } a(this.lls, bufferInfo.presentationTimeUs, z); return; } Object obj = new byte[byteBuffer.remaining()]; byteBuffer.get(obj, 0, byteBuffer.remaining()); this.llp.add(obj); if (this.llr || z) { try { this.llj.stop(); this.llj.release(); } catch (Throwable e) { x.printErrStackTrace("MicroMsg.MediaCodecAACTranscoder", e, "", new Object[0]); } beV(); this.llq = true; int i = 0; for (byte[] bArr : this.llp) { boolean z2; long j = bufferInfo.presentationTimeUs; if (i >= this.llp.size() - 1) { z2 = true; } else { z2 = false; } a(bArr, j, z2); i++; } } } } private void beV() { if (this.llk == null || !this.llo || this.llq) { try { this.llm = new MediaFormat(); this.llm.setString("mime", "audio/mp4a-latm"); this.llm.setInteger("aac-profile", 2); this.llm.setInteger("sample-rate", this.lln.audioSampleRate); this.llm.setInteger("channel-count", 1); this.llm.setInteger("bitrate", this.lln.dQF); this.llm.setInteger("max-input-size", 16384); this.llk = MediaCodec.createEncoderByType(this.ldm); this.llk.configure(this.llm, null, null, 1); this.llk.start(); x.i("MicroMsg.MediaCodecAACTranscoder", "checkInitAndStartEncoder, not canEncodeDecodeBothExist, create new encoder"); return; } catch (Exception e) { x.e("MicroMsg.MediaCodecAACTranscoder", "checkInitAndStartEncoder, not canEncodeDecodeBothExist, error: %s", new Object[]{e.getMessage()}); return; } } this.llj.start(); } private void a(byte[] bArr, long j, boolean z) { if (this.llk != null && bArr != null) { ByteBuffer[] inputBuffers = this.llk.getInputBuffers(); int dequeueInputBuffer = this.llk.dequeueInputBuffer(20000); if (dequeueInputBuffer < 0) { x.d("MicroMsg.MediaCodecAACTranscoder", "encoder no input buffer available, drain first"); beF(); } if (dequeueInputBuffer >= 0) { int i; ByteBuffer byteBuffer = inputBuffers[dequeueInputBuffer]; byteBuffer.clear(); byteBuffer.position(0); byteBuffer.put(bArr); if (z) { x.i("MicroMsg.MediaCodecAACTranscoder", "last, send EOS and try delay stop encoder"); i = 1; ah.i(new 2(this), 500); } else { i = 0; } if (this.llk == null) { return; } if (i != 0) { x.i("MicroMsg.MediaCodecAACTranscoder", "EOS received in sendAudioToEncoder"); this.llk.queueInputBuffer(dequeueInputBuffer, 0, bArr.length, j, 4); } else { this.llk.queueInputBuffer(dequeueInputBuffer, 0, bArr.length, j, 0); } } beF(); } } private void beF() { if (this.llk != null) { try { ByteBuffer[] outputBuffers = this.llk.getOutputBuffers(); BufferInfo bufferInfo = new BufferInfo(); while (true) { int dequeueOutputBuffer = this.llk.dequeueOutputBuffer(bufferInfo, 20000); x.d("MicroMsg.MediaCodecAACTranscoder", "encoderOutputBufferIndex: %s", new Object[]{Integer.valueOf(dequeueOutputBuffer)}); if (dequeueOutputBuffer == -1) { x.d("MicroMsg.MediaCodecAACTranscoder", "no output available, break"); return; } else if (dequeueOutputBuffer == -3) { outputBuffers = this.llk.getOutputBuffers(); } else if (dequeueOutputBuffer == -2) { this.llm = this.llk.getOutputFormat(); x.i("MicroMsg.MediaCodecAACTranscoder", "dstMediaFormat change: %s", new Object[]{this.llm}); } else if (dequeueOutputBuffer < 0) { x.e("MicroMsg.MediaCodecAACTranscoder", "unexpected encoderOutputBufferIndex: %s", new Object[]{Integer.valueOf(dequeueOutputBuffer)}); } else { x.v("MicroMsg.MediaCodecAACTranscoder", "perform encoding"); ByteBuffer byteBuffer = outputBuffers[dequeueOutputBuffer]; if (byteBuffer == null) { x.e("MicroMsg.MediaCodecAACTranscoder", "ERROR, retrieve encoderOutputBuffer is null!!"); return; } if (bufferInfo.size > 0) { byteBuffer.position(bufferInfo.offset); byteBuffer.limit(bufferInfo.offset + bufferInfo.size); if (byteBuffer != null) { MP4MuxerJNI.writeAACData(0, byteBuffer, bufferInfo.size); } } this.llk.releaseOutputBuffer(dequeueOutputBuffer, false); if ((bufferInfo.flags & 4) != 0) { x.i("MicroMsg.MediaCodecAACTranscoder", "receive EOS!"); if (this.llk != null) { this.llk.stop(); this.llk.release(); this.llk = null; return; } return; } } } } catch (Throwable e) { x.printErrStackTrace("MicroMsg.MediaCodecAACTranscoder", e, "drainEncoder error: %s", new Object[]{e.getMessage()}); } } } }
package com.spring.util; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SlopeInterceptor { private static Logger logger = LoggerFactory.getLogger(SlopeInterceptor.class); // private data fields of slope and intercept to be used throughout // the class private double slope; private double intercept; // Creates a new 2-D Line // @ s - the slope of the line // @ i - the intercept of the line public SlopeInterceptor(double s, double i) { slope = s; intercept = i; } public SlopeInterceptor(List<Double> rollingAvgTxn) { Double[] x_values =null; Double[] y_values =null; double slope1=1.0; double slope2=1.0; if(rollingAvgTxn!=null && rollingAvgTxn.size()>=4) { x_values =new Double[rollingAvgTxn.size()]; y_values =new Double[rollingAvgTxn.size()]; int val=0; for(Double value: rollingAvgTxn) { x_values[val]=Double.valueOf(val+1); y_values[val]=value; logger.info("x_values[val] :: "+x_values[val]); val++; } slope1=new SlopeInterceptor(1,y_values[0],rollingAvgTxn.size(),y_values[rollingAvgTxn.size()-1]).getSlope(); slope2=new SlopeInterceptor(2,y_values[1],rollingAvgTxn.size()-1,y_values[rollingAvgTxn.size()-2]).getSlope(); } //double slope3=new SlopeInterceptor(3,y_values[2],rollingAvgTxn.size(),y_values[rollingAvgTxn.size()-1]).getSlope(); // double slope4=new SlopeInterceptor(2,y_values[1],rollingAvgTxn.size()-1,y_values[rollingAvgTxn.size()-2]).getSlope(); logger.info("slope1 :: "+slope1); logger.info("slope2 :: "+slope2); logger.info("total :: "+(slope1+slope2-100)); slope= (slope1+slope2-100); } // Creates a new 2-D Line by calculating the slope an intercept // from the points // @ x1 - the x-value of point 1 // @ y1 - the y-value of point 1 // @ x2 - the x-value of point 2 // @ y2 - the y-value of point 2 public SlopeInterceptor(double x1, double y1, double x2, double y2) { logger.info("x1 :: "+x1); logger.info("y1 :: "+y1); logger.info("x2 :: "+x2); logger.info("y2 :: "+y2); slope = (y2-y1) / (x2/x1); intercept = y1 - x1*slope; } // Returns the slope of the line public double getSlope() { return slope; } public double getRollingAvg(List<Double> rollingAvgTxn) { double avgOfRollingAvg=0.0; if(rollingAvgTxn!=null && rollingAvgTxn.size()>=4) { avgOfRollingAvg = ((rollingAvgTxn.get(0)+rollingAvgTxn.get(1)+rollingAvgTxn.get(2)+rollingAvgTxn.get(3))/4); } return avgOfRollingAvg; } public double getSlopePercentile(List<Double> rollingAvgTxn) { double slopePercentile=0.0; slopePercentile=slope/getRollingAvg(rollingAvgTxn); return slopePercentile*100; } // Returns the intercept of the line public double getIntercept() { return intercept; } // Calculates the y value as the x value given // @ x - the x value public double calculateY(double x) { return x * slope + intercept; } }
package com.example.mvpdemo0602.ui.splash; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.example.mvpdemo0602.R; import com.example.mvpdemo0602.global.MyApplication; import com.example.mvpdemo0602.ui.login.LoginActivity; import com.example.mvpdemo0602.ui.splash.interactor.SplashInteractorImpl; import com.example.mvpdemo0602.ui.splash.presenter.SplashPresenter; import com.example.mvpdemo0602.ui.splash.presenter.SplashPresenterImpl; import com.example.mvpdemo0602.ui.splash.view.SplashView; import com.example.mvpdemo0602.view.MainActivity; import butterknife.Bind; import butterknife.ButterKnife; public class SplashActivity extends AppCompatActivity implements SplashView{ @Bind(R.id.tv_splash_app_version_code) TextView tvSplashAppVersionCode; @Bind(R.id.pb_splash_progress_1) ProgressBar mPb; private SplashPresenter splashPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); ButterKnife.bind(this); splashPresenter =new SplashPresenterImpl(this,new SplashInteractorImpl()); splashPresenter.compareVercode(); } @Override protected void onDestroy() { splashPresenter.onDestroy(); super.onDestroy(); } @Override public void showProgressbar() { mPb.setVisibility(View.VISIBLE); } @Override public void hindProgressbar() { mPb.setVisibility(View.GONE); } @Override public void setTextVerCode() { tvSplashAppVersionCode.setText(splashPresenter.getLocalVerCode()); } @Override public void showDialog(String desc, final String url) { String str="1、UI有局部增加;2、代码优化"; AlertDialog.Builder builder =new AlertDialog.Builder(this); builder.setTitle("更新APP"); builder.setMessage("更新内容:"+str); builder.setCancelable(false); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { splashPresenter.cancelDialog(); dialog.dismiss(); } }); builder.setPositiveButton("下载", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { splashPresenter.downloadAPK(dialog,url); } }); builder.show(); } @Override public void navigateToHome() { startActivity(new Intent(SplashActivity.this, MainActivity.class)); finish(); } @Override public void navigateToLogin() { startActivity(new Intent(SplashActivity.this, LoginActivity.class)); finish(); } }
package thread.synchronize;/** * Created by jiajia on 2018/9/12. */ import java.util.ArrayList; import java.util.List; /** * @author jiajia * @version V1.0 * @Description: synchronize 版生产者消费者 * @date 2018/9/12 22:44 */ public class Queue { private int size = 2; private List<Integer> queues = new ArrayList<>(size); private Object lock1 = new Object(); private Object lock2 = new Object(); public void push(Integer x) { synchronized (lock1) { while (queues.size() == size) { try { System.out.println(Thread.currentThread().getName() + " push wait"); lock1.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } queues.add(x); System.out.println(Thread.currentThread().getName() + " push " + x); lock1.notifyAll(); } } public Integer pop() { Integer x; synchronized (lock1) { while (queues.size() == 0) { try { System.out.println(Thread.currentThread().getName() + " pop wait"); lock1.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } x = queues.get(0); System.out.println(Thread.currentThread().getName() + " pop " + x); queues.remove(0); lock1.notifyAll(); } return x; } public static void main(String[] args) { Queue queue = new Queue(); Customer consumer = new Customer(queue); Provider provider = new Provider(queue); int size = 3; Thread[] consumerThreads = new Thread[size]; Thread[] providerThreads = new Thread[size]; for (int i = 0; i < size; i++) { consumerThreads[i] = new Thread(consumer); providerThreads[i] = new Thread(provider); } for (int i = 0; i < size; i++) { consumerThreads[i].start(); providerThreads[i].start(); } } } class Customer implements Runnable { private Queue queue; public Customer(Queue queue) { this.queue = queue; } @Override public void run() { for (int i = 0; i < Integer.MAX_VALUE; i++) { queue.pop(); } } } class Provider implements Runnable { private Queue queue; public Provider(Queue queue) { this.queue = queue; } @Override public void run() { for (int i = 0; i < Integer.MAX_VALUE; i++) { queue.push(i); } } }
/** * MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT * * Copyright (c) 2010-11 The Trustees of Columbia University in the City of * New York and Grameen Foundation USA. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Grameen Foundation USA, Columbia University, or * their respective contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY * 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 GRAMEEN FOUNDATION * USA, COLUMBIA UNIVERSITY 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 org.motechproject.server.omod.advice; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.motechproject.server.annotation.RunAsAdminUser; import org.motechproject.server.service.ContextService; import org.openmrs.User; import org.openmrs.api.AdministrationService; import org.openmrs.scheduler.SchedulerConstants; public class AuthenticateAdvice implements MethodInterceptor { private ContextService contextService; public Object invoke(MethodInvocation invocation) throws Throwable { if (hasAuthAnnotation(invocation.getMethod())) { Object returnValue = null; User user = contextService.getAuthenticatedUser(); boolean authenticated = authenticate(user); returnValue = invocation.proceed(); if (authenticated) { unauthenticate(user); } return returnValue; } else { return invocation.proceed(); } } private boolean authenticate(User currentUser) { String username = null; String password = null; AdministrationService adminService = contextService .getAdministrationService(); username = adminService .getGlobalProperty(SchedulerConstants.SCHEDULER_USERNAME_PROPERTY); password = adminService .getGlobalProperty(SchedulerConstants.SCHEDULER_PASSWORD_PROPERTY); if (currentUser == null || !currentUser.getSystemId().equals(username)) { contextService.authenticate(username, password); return true; } return false; } private void unauthenticate(User previousUser) { if (previousUser == null) { contextService.logout(); } else { contextService.becomeUser(previousUser.getSystemId()); } } private boolean hasAuthAnnotation(Method method) { for (Annotation annotation : method.getAnnotations()) { if (annotation instanceof RunAsAdminUser) { return true; } } return false; } public void setContextService(ContextService contextService) { this.contextService = contextService; } }
package com.tuitaking.dp; /** * 给定一个整数数组 nums,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 * * 示例: * * 输入: [-2,1,-3,4,-1,2,1,-5,4], * 输出: 6 * 解释:连续子数组[4,-1,2,1] 的和最大,为6。 * 进阶: * * 如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。 * * 来源:力扣(LeetCode) * 链接:https://leetcode-cn.com/problems/maximum-subarray * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class MaxSubArray_53 { public int maxSubArray(int[] nums) { if(nums.length==0){ return 0; } int preSum=nums[0],pre=0; for(int i :nums){ pre=Math.max(i,pre+i); preSum=Math.max(preSum,pre); } return preSum; } public int maxSubArray_v1(int[] nums){ if(nums==null){ return 0; } int sum=0,max=nums[0]; for(int i = 0 ; i < nums.length ; i++){ if(sum>0){ sum+=nums[i]; }else { sum=nums[i]; } max=Math.max(sum,max); } return max; } //error public int maxSubArray_v2(int[] nums){ if(nums.length==1){ return nums[0]; } int[] preSum=new int[nums.length]; preSum[0]=nums[0]; int min=Math.min(preSum[0],0); int max=0; for(int i=1;i<nums.length;i++){ preSum[i]=nums[i]+preSum[i-1]; max=Math.max(preSum[i]-min,max); min=Math.min(min,preSum[i]); } return max; } public int maxSubArray_pre(int[] nums) { int len = nums.length; int[] pf = new int[len+1]; for(int i = 1; i < len+1; i++) { pf[i] = nums[i-1] + pf[i-1]; } int min = Math.min(nums[0], 0); // int mind = 0; int ans = nums[0]; for(int i = 1; i < len; i++) { int pfs = pf[i+1] - min; ans = Math.max(ans, pfs); if(pf[i+1] < min) min = pf[i+1]; } return ans; } // 前缀后求 public int myPre(int[] nums){ int[] sumPre=new int[nums.length]; sumPre[0]=nums[0]; for(int i = 1; i < nums.length;i++){ sumPre[i]=nums[i]+sumPre[i-1]; } // 如果是0的话,可以不 int min=Math.min(nums[0], 0); int res=nums[0]; for(int i = 1 ; i < nums.length;i++){ res=Math.max(sumPre[i]-min,res); min=Math.min(sumPre[i],min); } return res; } }
package elaundry.domain; import java.io.Serializable; public class ItemDummy implements Serializable { private int orderId; private int itemId; private int laundryItemId; private int serviceId; private String serviceName; private String itemName; private int quantity; private double price; private double totalPrice; private int sumTotalQuantity; private double sumTotalPrice; public ItemDummy() { super(); } public ItemDummy(int orderId, int itemId, int serviceId, String serviceName, String itemName, int quantity) { this.orderId = orderId; this.itemId = itemId; this.serviceId = serviceId; this.serviceName = serviceName; this.itemName = itemName; this.quantity = quantity; } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public int getLaundryItemId() { return laundryItemId; } public void setLaundryItemId(int laundryItemId) { this.laundryItemId = laundryItemId; } public int getItemId() { return itemId; } public void setItemId(int itemId) { this.itemId = itemId; } public int getServiceId() { return serviceId; } public void setServiceId(int serviceId) { this.serviceId = serviceId; } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } public int getSumTotalQuantity() { return sumTotalQuantity; } public void setSumTotalQuantity(int sumTotalQuantity) { this.sumTotalQuantity = sumTotalQuantity; } public double getSumTotalPrice() { return sumTotalPrice; } public void setSumTotalPrice(double sumTotalPrice) { this.sumTotalPrice = sumTotalPrice; } }
package com.hqb.patshop.app.home.domain; import com.hqb.patshop.app.home.pojo.BidSalePOJO; import com.hqb.patshop.mbg.model.BidResultModel; import java.util.List; public class BidSaleResult { List<BidSalePOJO> bidResultList; public List<BidSalePOJO> getBidResultList() { return bidResultList; } public void setBidResultList(List<BidSalePOJO> bidResultList) { this.bidResultList = bidResultList; } @Override public String toString() { return "BidSaleResult{" + "bidResultList=" + bidResultList + '}'; } }
package Shapes; import util.Input; public class CircleApp { public static void main(String[] args) { boolean response = true; System.out.println("Please enter the circle radius."); Circle userCircle = new Circle(); } } //code continues to run and has to be manually stopped - why???
package com.guru.mplayer.helper; import android.content.Context; import android.database.Cursor; import android.provider.MediaStore; import android.util.Log; import com.guru.mplayer.data_model.MusicData; import java.util.ArrayList; /** * Created by Guru on 09-03-2018. */ public class MediaDataHelper { Cursor mCursor; public ArrayList<MusicData> queryMediaMeta(Context context) { mCursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{ MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ALBUM_ID }, null, null, MediaStore.Audio.Media.ALBUM+" ASC" ); ArrayList<MusicData> TracksList = new ArrayList<>(); Log.d("track list Size", String.valueOf(TracksList.size())); try { if (mCursor.moveToFirst()) { Log.d("cursorfirst", "moveto first"); //constructor signature public MusicData(String id,int length, String title, String albumName, String albumArt) do { MusicData music_data = new MusicData(mCursor.getString(mCursor.getColumnIndex(MediaStore.Audio.Media._ID)) , mCursor.getString(mCursor.getColumnIndex(MediaStore.Audio.Media.TITLE)) , mCursor.getInt(mCursor.getColumnIndex(MediaStore.Audio.Media.DURATION)) , mCursor.getString(mCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)) , mCursor.getString(mCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID))); // // music_data.setAlbumArt(mAlbumCursor.getString(mAlbumCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART))); // Log.d("albumArt",music_data.getAlbumArt()); Log.d("music cursor", mCursor.getString(mCursor.getColumnIndex(MediaStore.Audio.Media._ID))); TracksList.add(music_data); } while (mCursor.moveToNext()); } else { Log.d("cursor ", "cursor not moved to first"); // } } finally { Log.d("track list Size", String.valueOf(TracksList.size())); mCursor.close(); } return TracksList; } }
package com.example.lara.sing; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.facebook.login.LoginManager; import com.google.firebase.auth.FirebaseAuth; import java.util.ArrayList; public class MoreFragment extends Fragment { private FirebaseAuth mAuth; public MoreFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.settings_list, container, false); mAuth = FirebaseAuth.getInstance(); // Create a list of settings final ArrayList<Setting> settings = new ArrayList<Setting>(); settings.add(new Setting(R.string.edit_profile, R.drawable.edit_profile_pic)); settings.add(new Setting(R.string.my_files, R.drawable.my_files_pic)); settings.add(new Setting(R.string.my_messages, R.drawable.my_messages_pic)); settings.add(new Setting(R.string.my_favorite, R.drawable.my_favorites_pic)); settings.add(new Setting(R.string.my_community, R.drawable.my_community_pic)); settings.add(new Setting(R.string.log_out, R.drawable.log_out_pic)); // Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The // adapter knows how to create list items for each item in the list. SettingAdapter adapter = new SettingAdapter(getActivity(), settings); // Find the {@link ListView} object in the view hierarchy of the {@link Activity}. // There should be a {@link ListView} with the view ID called list, which is declared in the // word_list.xml layout file. ListView listView = (ListView) rootView.findViewById(R.id.list); // Make the {@link ListView} use the {@link WordAdapter} we created above, so that the // {@link ListView} will display list items for each {@link Word} in the list. listView.setAdapter(adapter); // Set a click listener to play the audio when the list item is clicked on listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { switch( position ) { case 0: startActivity(new Intent(getActivity(), SignUpProfileActivity.class)); break; case 1: // Intent intent = new Intent(this, youtube.class); // startActivity(newActivity); break; case 2: // Intent newActivity = new Intent(this, olympiakos.class); // startActivity(newActivity); // break; case 3: // Intent newActivity = new Intent(this, karaiskaki.class); // startActivity(newActivity); // break; case 4: // Intent newIntent = new Intent(this, reservetickets.class); // startActivity(newActivity); // break; case 5: mAuth.signOut(); LoginManager.getInstance().logOut(); startActivity(new Intent(getActivity(), MainActivity.class)); break; } // Setting setting = settings.get(position); //// // Release the media player if it currently exists because we are about to //// // play a different sound file //// releaseMediaPlayer(); // // // Get the {@link Word} object at the given position the user clicked on // Setting setting = settings.get(position); // // Request audio focus so in order to play the audio file. The app needs to play a // // short audio file, so we will request audio focus with a short amount of time // // with AUDIOFOCUS_GAIN_TRANSIENT. // int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, // AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); // // if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { // // We have audio focus now. // // // Create and setup the {@link MediaPlayer} for the audio resource associated // // with the current word // mMediaPlayer = MediaPlayer.create(getActivity(), word.getAudioResourceId()); // // // Start the audio file // mMediaPlayer.start(); // // // Setup a listener on the media player, so that we can stop and release the // // media player once the sound has finished playing. // mMediaPlayer.setOnCompletionListener(mCompletionListener); // } } }); return rootView; } }
import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.ProbeBuilder; import org.ops4j.pax.exam.TestProbeBuilder; import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; import org.ops4j.pax.exam.options.UrlProvisionOption; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.startlevel.BundleStartLevel; import javax.inject.Inject; import java.io.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.ops4j.pax.exam.CoreOptions.*; import static org.ops4j.pax.exam.OptionUtils.combine; public class TestSupport { @Inject protected BundleContext bundleContext; @ProbeBuilder protected TestProbeBuilder probeConfiguration(TestProbeBuilder probe) { probe.setHeader(Constants.DYNAMICIMPORT_PACKAGE, "*,org.apache.felix.service.*;status=provisional"); return probe; } protected Option[] configuration() { return options( //mavenBundle("org.eclipse.osgi", "org.eclipse.equinox.ds", "1.3.0"), bundle("file:/Users/sshelomentsev/Downloads/org.eclipse.equinox.ds-3.8.0.jar"), bundle("file:/Users/sshelomentsev/Downloads/org.eclipse.equinox.util-1.0.100.jar"), cleanCaches(), junitBundles()); } protected static Option[] getMavenDependencies(String groupId, String artifactId, String version) throws IOException { //The path is relative to the directory of integration test module File dependenciesFile = new File("../bundles/" + artifactId + "/target/audit/", "dependencies.txt"); Option[] bundles = null; BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(dependenciesFile)); String line = reader.readLine(); while (line != null) { line = line.replaceAll("\\s+", ""); Pattern p = Pattern.compile("\\s*?[\\w.]+:.*:.*:.*"); Matcher m = p.matcher(line); if (m.matches()) { /* options: 0: groupId 1: artifactId 2: type 3: scope 4: version 5: isFragmentHost */ String[] options = line.split(":"); if (options[5].equals("true")) { bundles = combine(bundles, bundleNoStart(options[0], options[1], options[2])); } else { bundles = combine(bundles, bundleStart(options[0], options[1], options[2])); } } line = reader.readLine(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { reader.close(); } bundles = combine(bundles, bundleStart(groupId, artifactId, version)); return bundles; } protected static Option[] bundleStart(String groupId, String artifactId, String version) { return new MavenArtifactProvisionOption[]{mavenBundle(groupId, artifactId).version(version).start()}; } protected static Option[] bundleStart(String url) { return new UrlProvisionOption[]{bundle("file:" + url).start()}; } protected static Option[] bundleNoStart(String groupId, String artifactId, String version) { return new MavenArtifactProvisionOption[]{ mavenBundle(groupId, artifactId).version(version).noStart()}; } protected static Option[] bundleNoStart(String url) { return new UrlProvisionOption[]{bundle("file:" + url).noStart()}; } protected static Option[] bundleStartLevel(String groupId, String artifactId, String version, int startLevel) { return new MavenArtifactProvisionOption[]{mavenBundle(groupId, artifactId).version(version).startLevel(Bundle.RESOLVED)}; } }
package com.utknl.katas; /** * https://www.codewars.com/kata/56269eb78ad2e4ced1000013/train/java * <p> * You might know some pretty large perfect squares. But what about the NEXT one? * <p> * Complete the findNextSquare method that finds the next integral perfect square after the one passed as a parameter. * Recall that an integral perfect square is an integer n such that sqrt(n) is also an integer. * <p> * If the parameter is itself not a perfect square, than -1 should be returned. You may assume the parameter is positive. */ public class FindTheNextPerfectSquare { public static long findNextSquare(long sq) { int x = (int) Math.sqrt(sq); if (Math.pow(x, 2) != sq) { return -1L; } return (long) Math.pow(Math.sqrt(sq) + 1, 2); } } /* Good ones: return Math.sqrt(sq) % 1 != 0 ? -1 : (long)Math.pow(Math.sqrt(sq)+1,2); */
package model; import utilities.Coord; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Random; /** * Class representing a floor in the haunted house. Holds a number of tiles which can be likened to rooms. */ public class Floor { private final int mapSize; private final int amountOfStairs = 4; private final int stairSpacing; private final Tile[][] tiles; private final Random rand = new Random(); /** * mapSize is the amount of tiles squared. * * @param eventList List of events from Board * @param floor which floor it is */ Floor(List<Event> eventList, int floor) { mapSize = 6; stairSpacing = mapSize / 3; tiles = new Tile[mapSize][mapSize]; generateTileMap(); generateStairs(floor); addEventsRandom(eventList); } /** * @param floor amount of floors * Method generates stairs, if floor 0 stair up, floor1 stair upDown, floor2 stair down */ private void generateStairs(int floor) { if (floor == 0) { setStairUp(0); } else if (floor == 1) { setStairDown(0); setStairUp(mapSize - 1); } else { setStairDown(mapSize - 1); } } /** * @param row Set stair down, int is row, i+1 is Col */ private void setStairUp(int row) { Tile tile; for (int i = 0; i < amountOfStairs / 2; i++) { tile = tiles[stairSpacing * (i + 1)][row]; tile.setStairUp(true); } } /** * @param row Set stair down, int is row, i+1 is Col */ private void setStairDown(int row) { Tile tile; for (int i = 0; i < amountOfStairs / 2; i++) { tile = tiles[stairSpacing * (i + 1)][row]; tile.setStairDown(true); } } /** * @param x * @param y * @return tile on position x,y */ Tile getTile(int x, int y) { return tiles[x][y]; } /** * adds event randomly and checks so that an event can only be places on empty tile * * @param eventList */ void addEventsRandom(List<Event> eventList) { int col; int row; for (Event event : eventList) { row = rand.nextInt(tiles.length); col = rand.nextInt(tiles[0].length); while (tiles[row][col].hasEvent() || tiles[row][col].hasStair()) { row = rand.nextInt(tiles.length); col = rand.nextInt(tiles[0].length); } tiles[row][col].setEvent(event); } } /** * @param x * @param y * @return returns hasmap of doors on tile on position x,y */ HashMap<Integer, Boolean> getDoorsOnTile(int x, int y) { return tiles[x][y].getDoors(); } /** * tries to activate event on tile on current player position * * @param player current active player * @return true if an event was activated, false if not */ boolean tryActivateEventOnTile(Player player) { Tile tile = tiles[player.getX()][player.getY()]; return tile.tryActivateEvent(); } /** * chains handleEvent method to tile * * @param currentPlayer */ void handleEvent(Player currentPlayer) { Tile tile = tiles[currentPlayer.getX()][currentPlayer.getY()]; tile.handleEvent(currentPlayer); } private void generateTileMap() { for (int i = 0; i < tiles.length; i++) { for (int j = 0; j < tiles[i].length; j++) { tiles[i][j] = new Tile(i, j, tiles.length, tiles[i].length); } } } /** * Chaining of a getter down to Event * * @param currentPlayer current Active player * @return String of text to be displayed on mainGameView. */ String getEventEffectText(Player currentPlayer) { Tile tile = tiles[currentPlayer.getX()][currentPlayer.getY()]; return tile.getEventEffectText(); } /** * Chaining of a getter down to Event * * @param currentPlayer current Active player * @return String of text to be displayed on eventButton. */ String getEventButtonText(Player currentPlayer) { Tile tile = tiles[currentPlayer.getX()][currentPlayer.getY()]; return tile.getEventButtonText(); } /** * Getter for where the stairs up are located. * * @param floor * @return List of coords where the stairs up are. */ List<Coord> getStairsUp(int floor) { List<Coord> coords = new ArrayList<>(); for (int x = 0; x < mapSize; x++) { for (int y = 0; y < mapSize; y++) { if (tiles[x][y].hasStairUp()) { coords.add(new Coord(x, y, floor)); } } } return coords; } /** * Getter for where the stairs are located. * * @param floor * @return List of coords where the stairs are. */ List<Coord> getStairsDown(int floor) { List<Coord> coords = new ArrayList<>(); for (int x = 0; x < mapSize; x++) { for (int y = 0; y < mapSize; y++) { if (tiles[x][y].hasStairDown()) { coords.add(new Coord(x, y, floor)); } } } return coords; } }
package parse.standalone; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.ParseException; import ru.hse.performance.PerformanceUtil; import util.JsonReadWriteUtils; import util.ParseMessage; import util.Util; public class AddTemplateComposite extends Composite { private Text messagesText; private Text templatesText; private Text statusText; private String jsonMessagesFileName; private String templatesFileName; private String parsedMessagesFileName; private int parsedMessagesCount; private int unparsedMessagesCount; private int totalMessagesCount; private Text parsedMessagesText; public AddTemplateComposite(Composite parent, int style) { super(parent, style); setLayout(new GridLayout(3, false)); Label lblParsedJsonMessages = new Label(this, SWT.NONE); lblParsedJsonMessages.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblParsedJsonMessages.setText("JSON Messages File"); messagesText = new Text(this, SWT.BORDER); messagesText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Button btnExplore = new Button(this, SWT.NONE); btnExplore.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); btnExplore.setText("Explore"); btnExplore.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { jsonMessagesFileName = new FileDialog(getShell()).open(); if (jsonMessagesFileName != null && !jsonMessagesFileName.trim().isEmpty()) { messagesText.setText(jsonMessagesFileName); } } }); Label lblResultsJsonFile = new Label(this, SWT.NONE); lblResultsJsonFile.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblResultsJsonFile.setText("Templates File"); templatesText = new Text(this, SWT.BORDER); templatesText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Button resultsSaveAs = new Button(this, SWT.NONE); resultsSaveAs.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1)); resultsSaveAs.setText("Explore"); resultsSaveAs.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { templatesFileName = new FileDialog(getShell()).open(); if (templatesFileName != null && !templatesFileName.trim().isEmpty()) { templatesText.setText(templatesFileName); } } }); Label lblParsedJsonMessages_1 = new Label(this, SWT.NONE); lblParsedJsonMessages_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); lblParsedJsonMessages_1.setText("Parsed JSON Messages File"); parsedMessagesText = new Text(this, SWT.BORDER); parsedMessagesText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1)); Button btnSaveAs = new Button(this, SWT.NONE); btnSaveAs.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { parsedMessagesFileName = new FileDialog(getShell(), SWT.SAVE).open(); if (parsedMessagesFileName != null && !parsedMessagesFileName.trim().isEmpty()) { parsedMessagesText.setText(parsedMessagesFileName); } } }); btnSaveAs.setText("Save As"); Button runComputation = new Button(this, SWT.NONE); runComputation.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { run(); } }); runComputation.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 3, 1)); runComputation.setText("Run message parsing"); Label lblNewLabel = new Label(this, SWT.NONE); lblNewLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1)); statusText = new Text(this, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL); statusText.setEditable(false); statusText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1)); } private void run() { if (jsonMessagesFileName == null || jsonMessagesFileName.trim().isEmpty() || templatesFileName == null || templatesFileName.trim().isEmpty() || parsedMessagesFileName == null || parsedMessagesFileName.trim().isEmpty()) { statusText.setText("Invalid file names. Check file paths and provide the correct ones, then restart computations"); } statusText.setText("Processing in progress..."); getShell().getDisplay().asyncExec(new Runnable() { @Override public void run() { try { PerformanceUtil.initialize(); JsonReadWriteUtils.readJsonLogFile(jsonMessagesFileName); List<String> templates=Files.readAllLines(Paths.get(templatesFileName)); parseMessagesAndAddTemplates(JsonReadWriteUtils.getJsonArray(), templates); JsonReadWriteUtils.saveJsonArrayToFile(JsonReadWriteUtils.getJsonArray(), parsedMessagesFileName); System.out.println("Total messages processed: " + totalMessagesCount + "\nParsed messages: " + parsedMessagesCount + "\nUnparsed Messages: " + unparsedMessagesCount); statusText.setText("Finished!\n"); PerformanceUtil.printTotalTime(); } catch (IOException e) { statusText.setText(Util.getStackTrace(e)); e.printStackTrace(); } catch (ParseException e) { statusText.setText(Util.getStackTrace(e)); e.printStackTrace(); } } }); } /** * Метод производит разбор переданного списка сообщений (как JSON-объектов) * с помощью переданных шаблонов. Если сообщение было разборано, то в его * JSON-объект добавляется ключ "template" в со значением равным * разобравшему шаблону. Если сообщение не разобрано, то ключ не добавляется. * * @param messages * @param templates */ private void parseMessagesAndAddTemplates(JSONArray messages, List<String> templates) { boolean parsed; String msg; Map<String, String> placeholderValueMap; JSONObject message; parsedMessagesCount = 0; unparsedMessagesCount = 0; totalMessagesCount = messages.size(); for (Object o : messages) { message = (JSONObject) o; parsed = false; msg = ((String)message.get("msg")); for (String template : templates) { placeholderValueMap = ParseMessage.parseMessageAgainstTemplate(msg, template); if (!placeholderValueMap.isEmpty()) { parsed = true; message.put("template", template); parsedMessagesCount++; break; } } if (!parsed) { unparsedMessagesCount++; } } } }
/* * UniTime 3.5 (University Timetabling Application) * Copyright (C) 2013, UniTime LLC, and individual contributors * as indicated by the @authors tag. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ package org.unitime.commons.jgroups; import java.util.Properties; import org.jgroups.Channel; import org.jgroups.JChannel; import org.jgroups.fork.ForkChannel; import org.jgroups.protocols.FRAG2; import org.jgroups.protocols.RSVP; import org.jgroups.stack.ProtocolStack; import org.unitime.commons.Debug; import org.unitime.timetable.defaults.ApplicationProperty; /** * @author Tomas Muller */ public class SectioningChannelLookup extends UniTimeChannelLookup { @Override public Channel getJGroupsChannel(Properties p) { try { if (ApplicationProperty.OnlineSchedulingClusterForkChannel.isTrue()) { return new ForkChannel(super.getJGroupsChannel(p), "forked-stack", "sectioning-channel", true, ProtocolStack.ABOVE, FRAG2.class, new RSVP().setValue("timeout", 60000).setValue("resend_interval", 500).setValue("ack_on_delivery", false)); } else { return new JChannel(JGroupsUtils.getConfigurator(ApplicationProperty.OnlineSchedulingClusterConfiguration.value())); } } catch (Exception e) { Debug.error(e.getMessage(), e); return null; } } }
package include.linguistics.english; import include.Tuple2; import include.linguistics.Word; import english.pos.ETag; public final class WordETag extends Tuple2<Word, ETag> { public WordETag() { super(); } public WordETag(final WordETag word_tag) { super(word_tag.m_object1, word_tag.m_object2); } public WordETag(final Word word, final ETag tag) { super(word, tag); } @Override public Word create_object1(final Word a) { return a; } @Override public ETag create_object2(final ETag b) { return b; } }
package it.unibz.testhunter; import it.unibz.testhunter.action.ActionAddProject; import it.unibz.testhunter.action.ActionCheckProject; import it.unibz.testhunter.action.ActionCommandHelp; import it.unibz.testhunter.action.ActionCreateTestSequence; import it.unibz.testhunter.action.ActionHelp; import it.unibz.testhunter.action.ActionListPlugins; import it.unibz.testhunter.action.ActionListProjects; import it.unibz.testhunter.action.ActionProject; import it.unibz.testhunter.action.ActionTestResults; import it.unibz.testhunter.action.ICommandAction; import it.unibz.testhunter.cmd.CmdAddProject; import it.unibz.testhunter.cmd.CmdCheckProject; import it.unibz.testhunter.cmd.CmdCreateTestSequence; import it.unibz.testhunter.cmd.CmdListCommands; import it.unibz.testhunter.cmd.CmdListPlugins; import it.unibz.testhunter.cmd.CmdListProjects; import it.unibz.testhunter.cmd.CmdProject; import it.unibz.testhunter.cmd.CmdTestResults; import com.google.inject.AbstractModule; import com.google.inject.name.Names; public class ModuleActions extends AbstractModule { @Override protected void configure() { bind(ICommandAction.class).annotatedWith(Names.named("cmd-help")).to(ActionCommandHelp.class); bind(ICommandAction.class).annotatedWith(Names.named(CmdListProjects.name)).to(ActionListProjects.class); bind(ICommandAction.class).annotatedWith(Names.named(CmdAddProject.name)).to(ActionAddProject.class); bind(ICommandAction.class).annotatedWith(Names.named(CmdListCommands.name)).to(ActionHelp.class); bind(ICommandAction.class).annotatedWith(Names.named(CmdCheckProject.name)).to(ActionCheckProject.class); bind(ICommandAction.class).annotatedWith(Names.named(CmdListPlugins.name)).to(ActionListPlugins.class); bind(ICommandAction.class).annotatedWith(Names.named(CmdProject.name)).to(ActionProject.class); bind(ICommandAction.class).annotatedWith(Names.named(CmdTestResults.name)).to(ActionTestResults.class); bind(ICommandAction.class).annotatedWith(Names.named(CmdCreateTestSequence.name)).to(ActionCreateTestSequence.class); } }
package com.example.fileupload; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.multipart.MultipartFile; @RestController public class FileUploadCleintController { @GetMapping("/upload") public ResponseEntity<byte[]> uploadFile(){ try { byte[] contents = uploadSingleFile().getBody(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); // Here you have to set the actual filename of your pdf String filename = "output.pdf"; headers.setContentDispositionFormData(filename, filename); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK); return response; } catch (IOException e) { e.printStackTrace(); } return null; } @PostMapping("/stub/multipart") public ResponseEntity<String> uploadFile(MultipartFile file) throws IOException { String result = new String(file.getBytes()); //File f = Files.write(Paths.get("/")) System.out.println("Result is "+result); return new ResponseEntity<>(result, HttpStatus.OK); } private static ResponseEntity<byte[]> uploadSingleFile() throws IOException { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); //headers.add("htmlString"); MultiValueMap<String, Object> body = new LinkedMultiValueMap<>(); body.add("htmlString", getTestFile()); HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers); //String serverUrl = "http://localhost:9595/stub/multipart"; String serverUrl = "http://localhost:8080/pdfsvc/pdfRequest/convert"; RestTemplate restTemplate = new RestTemplate(); ResponseEntity<byte[]> response = restTemplate.postForEntity(serverUrl, requestEntity,byte[].class); return ResponseEntity.ok(response.getBody()); // String pdfResponse = new String(response.getBody()); // System.out.println("Response code: " + response.getStatusCode()+" PDF Response "+pdfResponse); } public static Resource getTestFile() throws IOException { Path testFile = Files.createTempFile("test-file", ".html"); System.out.println("Creating and Uploading Test File: " + testFile); Files.write(testFile, "<html><head> THis is my HEAD </head> <body> Hello World !!, This is a test file.</body></html>".getBytes()); return new FileSystemResource(testFile.toFile()); } }
package main; public class Main { public static void main(String[] args) { Thread thread = new Thread(new BlackJackTCPClient("localhost", 3002)); thread.start(); } }
package com.mcf.base.dao; import com.mcf.base.common.dao.IBaseMapperDao; import com.mcf.base.exception.BaseException; import com.mcf.base.pojo.AdminUser; /** * Title. <br> * Description. * <p> * Copyright: Copyright (c) 2016年12月17日 下午2:34:10 * <p> * Author: 10003/sunaiqiang saq691@126.com * <p> * Version: 1.0 * <p> */ public interface IAdminUserDao extends IBaseMapperDao<AdminUser> { /** * 根据用户名获得对象 * * @param username * 用户名 * @return */ public AdminUser getByUsername(String username) throws BaseException; }
import java.util.Scanner; public class App { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Please enter the file name "); String fileName = s.nextLine(); char[][] grid = FileReader.readFile(fileName); System.out.println("Coordinates of Cameras:"); traverseDiagonally(grid); System.out.println("Bank's Map:"); printMatrix(grid); s.close(); } // assign cameras in diagonal order static void traverseDiagonally(char matrix[][]) { // grid size int n = matrix.length; int row = 0, column = 0; boolean row_increment = false; for (int len = 1; len <= n; ++len) { for (int i = 0; i < len; ++i) { if (matrix[row][column] == '-') { matrix[row][column] = 'c'; System.out.println(" " + (row+1) + " " + (1+column)); // set views in both directions vertically, horizontally and diagonally setDownViews(matrix, row + 1, column); setUpViews(matrix, row - 1, column); setLeftViews(matrix, row, column - 1); setRightViews(matrix, row, column + 1); setLeftUpViews(matrix, row - 1, column - 1); setLeftDownViews(matrix, row + 1, column - 1); setRightDownViews(matrix, row + 1, column + 1); setRightUpViews(matrix, row - 1, column + 1); } if (i + 1 == len) break; if (row_increment) { ++row; --column; } else { --row; ++column; } } if (len == n) break; if (row_increment) { ++row; row_increment = false; } else { ++column; row_increment = true; } } if (row == 0) { if (column == n - 1) ++row; else ++column; row_increment = true; } else { if (row == n - 1) ++column; else ++row; row_increment = false; } int MAX = n - 1; for (int len, diag = MAX; diag > 0; --diag) { if (diag > n) len = n; else len = diag; for (int i = 0; i < len; ++i) { if (matrix[row][column] == '-') { matrix[row][column] = 'c'; System.out.println(" " + (row+1) + " " + (1+column)); // set views in both directions vertically, horizontally and diagonally setDownViews(matrix, row + 1, column); setUpViews(matrix, row - 1, column); setLeftViews(matrix, row, column - 1); setRightViews(matrix, row, column + 1); setLeftUpViews(matrix, row - 1, column - 1); setLeftDownViews(matrix, row + 1, column - 1); setRightDownViews(matrix, row + 1, column + 1); setRightUpViews(matrix, row - 1, column + 1); } if (i + 1 == len) break; if (row_increment) { ++row; --column; } else { ++column; --row; } } if (row == 0 || column == n - 1) { if (column == n - 1) ++row; else ++column; row_increment = true; } else if (column == 0 || row == n - 1) { if (row == n - 1) ++column; else ++row; row_increment = false; } } } // prints the matrix values static void printMatrix(char matrix[][]) { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) System.out.print(matrix[i][j] + " "); System.out.print("\n"); } } // set views to the right down diagonal of an added camera static void setRightDownViews(char[][] grid, int i, int j) { if (i >= grid.length || j >= grid.length || i < 0 || j < 0) return; if (grid[i][j] == 'x') return; grid[i][j] = 'v'; setRightDownViews(grid, i + 1, j + 1); } // set views to the right up diagonal of an added camera static void setRightUpViews(char[][] grid, int i, int j) { if (i >= grid.length || j >= grid.length || i < 0 || j < 0) return; if (grid[i][j] == 'x') return; grid[i][j] = 'v'; setRightUpViews(grid, i - 1, j + 1); } // set views to the right side of an added camera static void setRightViews(char[][] grid, int i, int j) { if (i >= grid.length || j >= grid.length || i < 0 || j < 0) return; if (grid[i][j] == 'x') return; grid[i][j] = 'v'; setRightViews(grid, i, j + 1); } // set views to the left up diagonal of an added camera static void setLeftUpViews(char[][] grid, int i, int j) { if (i >= grid.length || j >= grid.length || i < 0 || j < 0) return; if (grid[i][j] == 'x') return; grid[i][j] = 'v'; setLeftUpViews(grid, i - 1, j - 1); } // set views to the left down diagonal of an added camera static void setLeftDownViews(char[][] grid, int i, int j) { if (i >= grid.length || j >= grid.length || i < 0 || j < 0) return; if (grid[i][j] == 'x') return; grid[i][j] = 'v'; setLeftDownViews(grid, i + 1, j - 1); } // set views to the left side of an added camera static void setLeftViews(char[][] grid, int i, int j) { if (i >= grid.length || j >= grid.length || i < 0 || j < 0) return; if (grid[i][j] == 'x') return; grid[i][j] = 'v'; setLeftViews(grid, i, j - 1); } // set views to the up side of an added camera static void setUpViews(char[][] grid, int i, int j) { if (i >= grid.length || j >= grid.length || i < 0 || j < 0) return; if (grid[i][j] == 'x') return; grid[i][j] = 'v'; setUpViews(grid, i - 1, j); } // set views to the down side of an added camera static void setDownViews(char[][] grid, int i, int j) { if (i >= grid.length || j >= grid.length || i < 0 || j < 0) return; if (grid[i][j] == 'x') return; grid[i][j] = 'v'; setDownViews(grid, i + 1, j); } // public static void DFS(char[][] grid) { // int l = grid[0].length; // boolean[][] visited = new boolean[h][l]; // Stack<Coordinate> stack = new Stack<>(); // stack.push(new Coordinate(0, 0)); // System.out.println("Depth-First Traversal: "); // while (!stack.empty()) { // Coordinate x = stack.pop(); // int row = x.i; // int col = x.j; // if (row < 0 || col < 0 || row >= h || col >= l || visited[row][col]) // continue; // visited[row][col] = true; // System.out.print(grid[row][col] + " "); // stack.push(new Coordinate(row, (col - 1))); // go left // stack.push(new Coordinate(row, (col + 1))); // go right // stack.push(new Coordinate(row - 1, col)); // go up // stack.push(new Coordinate(row + 1, col)); // go down // } // } }
package temakereso.helper; import com.fasterxml.jackson.annotation.JsonFormat; @JsonFormat(shape = JsonFormat.Shape.OBJECT) public enum TopicType { BSC_THESIS("Bsc. szakdolgozat"), MSC_THESIS("Msc. diplomamunka"), PHD_THESIS("PhD. disszertáció"), RESEARCH_TOPIC("Kutatási téma, TDK"); private String name; TopicType(String name) { this.name = name; } public String getId() { return name(); } public String getName() { return name; } }
package Home_Work; public class HomeWork_1 { // Типы целочисленные byte myNameByte = 25; short myNmeShort = 32000; int myNameint = 99999999; long myNamelong = 1000000; //Типы плавающей точкой float myNmamefloat = 130.0F; double myNamedouble = 140.0; //Логический тип boolean myNamebollean8bit = true; // false = ложь //Символьный тип char myNamechar = 'n'; //Строки String myNamestring = "Всем привет"; public static void main(String[] args) { System.out.println(args[0]); String endresult; endresult = "" + test3(22.2F, 34.8F, 32.6F, 6.24F); System.out.println(endresult); test4(6, 8); System.out.println(test4()); } public static float test3(float a, float b, float c, float d) { float result = a * (b + (c / d)); return result; } public static int test4(int c, int d) { int a = 10; int b = 20; int vol = (c + d) ; if (a < (c + d) < b) { return 1; } else { return 0; } } } }
package com.tencent.mm.ui.chatting.gallery; import android.animation.TimeInterpolator; import android.os.Build.VERSION; import android.view.View; class ImageGalleryGridUI$7 implements Runnable { final /* synthetic */ ImageGalleryGridUI tUJ; final /* synthetic */ View tUM; final /* synthetic */ TimeInterpolator tUN; ImageGalleryGridUI$7(ImageGalleryGridUI imageGalleryGridUI, View view, TimeInterpolator timeInterpolator) { this.tUJ = imageGalleryGridUI; this.tUM = view; this.tUN = timeInterpolator; } public final void run() { if (VERSION.SDK_INT >= 16) { this.tUM.animate().setDuration(500).alpha(0.0f).withEndAction(this.tUJ.tUB).withLayer().setInterpolator(this.tUN); } else if (this.tUJ.handler != null) { this.tUM.animate().setDuration(500).alpha(0.0f).setInterpolator(this.tUN); this.tUJ.handler.postDelayed(this.tUJ.tUB, 500); } } }
package pe.egcc.cartesiano.dto; public class CartesianoDto { // Input private int puntoX1; private int puntoY1; private int puntoX2; private int puntoY2; // Output private String cuadrante1; private String cuadrante2; private Double distancia; public CartesianoDto(){ } public CartesianoDto(int puntoX1, int puntoY1, int puntoX2, int puntoY2){ this.puntoX1 = puntoX1; this.puntoY1 = puntoY1; this.puntoX2 = puntoX2; this.puntoY2 = puntoY2; } /** * @return the puntoX1 */ public int getPuntoX1() { return puntoX1; } /** * @param puntoX1 the puntoX1 to set */ public void setPuntoX1(int puntoX1) { this.puntoX1 = puntoX1; } /** * @return the puntoY1 */ public int getPuntoY1() { return puntoY1; } /** * @param puntoY1 the puntoY1 to set */ public void setPuntoY1(int puntoY1) { this.puntoY1 = puntoY1; } /** * @return the puntoX2 */ public int getPuntoX2() { return puntoX2; } /** * @param puntoX2 the puntoX2 to set */ public void setPuntoX2(int puntoX2) { this.puntoX2 = puntoX2; } /** * @return the puntoY2 */ public int getPuntoY2() { return puntoY2; } /** * @param puntoY2 the puntoY2 to set */ public void setPuntoY2(int puntoY2) { this.puntoY2 = puntoY2; } /** * @return the distancia */ public Double getDistancia() { return distancia; } /** * @param distancia the distancia to set */ public void setDistancia(Double distancia) { this.distancia = distancia; } /** * @return the cuadrante2 */ public String getCuadrante2() { return cuadrante2; } /** * @param cuadrante2 the cuadrante2 to set */ public void setCuadrante2(String cuadrante2) { this.cuadrante2 = cuadrante2; } /** * @return the cuadrante1 */ public String getCuadrante1() { return cuadrante1; } /** * @param cuadrante1 the cuadrante1 to set */ public void setCuadrante1(String cuadrante1) { this.cuadrante1 = cuadrante1; } }
package car.adroid.service; import android.Manifest; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.IBinder; import android.support.v4.app.ActivityCompat; import car.adroid.config.AppConfig; import car.adroid.data.AppData; import car.adroid.util.SimpleLogger; public class LocationService extends Service { public Context mContext = this; private LocationManager mLocMan; private String mProvider; public LocationService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return null; } @Override public void onCreate() { super.onCreate(); mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mProvider = mLocMan.getBestProvider(new Criteria(), true); } @Override public int onStartCommand(Intent intent, int flags, int startId) { int superRtn = super.onStartCommand(intent, flags, startId); SimpleLogger.debug(mContext , "start Location service"); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. //return START_NOT_STICKY; return superRtn; } mLocMan.requestLocationUpdates(mProvider, AppConfig.LOCATION_RECIVE_MILISECONDS , AppConfig.LOCATION_RECEIVE_DISTANCE , mListener); // AppData data = AppData.getInstance(getApplicationContext()); // Location loc = mLocMan.getLastKnownLocation(mProvider); // data.updateLocalLocation(loc.getLatitude() , loc.getLongitude()); //return START_STICKY; return superRtn; } @Override public void onDestroy() { super.onDestroy(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } SimpleLogger.debug(mContext , "stop service"); mLocMan.removeUpdates(mListener); } LocationListener mListener = new LocationListener() { public void onLocationChanged(Location location) { AppData data = AppData.getInstance(getApplicationContext()); // data.setLatitude(location.getLatitude()); // data.setLongitude(location.getLongitude()); data.updateLocalLocation(location.getLatitude() , location.getLongitude()); data.setSpeed(location.getSpeed()); SimpleLogger.debug(mContext , "lat : " + location.getLatitude() + ", lot : " + location.getLongitude() + "speed : " + location.getSpeed()); } public void onProviderDisabled(String provider) { //서비스사용불가 } public void onProviderEnabled(String provider) { //서비스 사용 가능 } public void onStatusChanged(String provider, int status, Bundle extras) { String sStatus = ""; switch (status) { case LocationProvider.OUT_OF_SERVICE: //범위 벗어남 break; case LocationProvider.TEMPORARILY_UNAVAILABLE: //일시적 불능 break; case LocationProvider.AVAILABLE: //사용 가능 break; } } }; }
package example; import beans.Mocode; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import mapper.MoCodeMapper; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.builder.fluent.Configurations; import org.apache.ibatis.jdbc.SQL; import org.apache.ibatis.session.SqlSession; import util.Default; import util.SqlMapper; import util.Tool; import util.WorkFlowSqlSessionFactory; import wrapper.MoCodeOperate; import wrapper.Operate; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.stream.Stream; public class Usage { /** * Use synchronous blocking basic method * Includes basic implementation of Select Insert Update Delete * Basically means relatively low efficiency * Opera is the operation object passed in according to the dependency inversion principle * Operate is actually a packaging object * Can accept all types of objects under the "mapper" package * Use reflection * */ public void example1(){ Operate<Mocode> operate = new Operate<>(MoCodeMapper.class); System.out.println(operate.getById("1106")); } /** * Use asynchronous methods * Should print Get 1 / 2 first * Then print out the database results * This is completely different from the synchronization method * * Sleep is to wait for an asynchronous call to return or the program will end * * You can use custom thread pools in asynchronous operations * newFixedThreadPool * newCachedThreadPool * newSingleThreadExecutor * newScheduleThreadPool * FixedThreadPool * CachedThreadPool */ public void example2(){ Operate<Mocode> operate = new Operate<>(MoCodeMapper.class); CompletableFuture<Mocode> fu1 = operate.getByIdAsync("107").thenApplyAsync(x->{ if(x == null){ return x; } x.setId("666"); System.out.println(x); return x;}); System.out.println("Get 1 "); CompletableFuture<Mocode> fu2 = operate.getByIdAsync("108").thenApplyAsync(x->{ if(x == null){ return x; } x.setId("666"); System.out.println(x); return x;}); System.out.println("Get 2 "); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Use Optional as the return value * Simple example of using Optional * If you previously had experience * with Haskell (Maybe Type) or Swift (`?` optional operator, `!` forcing unwrapping operators) * This is easy to understand */ public void example3(){ Operate<Mocode> operate = new Operate<>(MoCodeMapper.class); System.out.println(operate.getByIdOptional("107") .map(mocode -> mocode.getMocode()) .orElse("UnKnown")); /* //Consider the following program //We now have the results of a competition set //Now we want to get the name of the person who won the championship. //If there is no, return "UnKnown" : String //If we use the traditional method, we should check whether the object is NULL at each step. //If you use the most common nested if : x = c.getResult(); if (x != null) { y = x.getChampion() if (y != null) { z = y.getName() if (z != null){ return z; } } } return "UnKnown"; //If you use a method that returns in advance will be like this: final String result = "UnKnown"; if (...){ return } if (...){ return } if (...){ return } return //But if you use Optional : Optional.ofNullable(comp) .map(c->c.getResult()) .map(r->r.getChampion()) .map(u->u.getName()) .orElseThrow(()->new IllegalArgumentException("The value of param comp isn't available.")); */ } /** * Return Stream object to manipulate Stream in a functional way * Several simple examples of functional */ public void example4(){ } /** * More flexible API 1 * Call a functional method */ public void example5(){ System.out.println(selectMoCodeSql()); Tool.consumeSession((session)->{ SqlMapper sqlMapper = new SqlMapper(session); sqlMapper.selectList(selectMoCodeSql()).forEach(System.out::println); }); Tool.consumeSession((session)->{ MoCodeMapper moCodeMapper = session.getMapper(MoCodeMapper.class); Mocode moCode = moCodeMapper.getById("107"); List<Mocode> moCodeList = moCodeMapper.getAll(); if (moCode == null) { System.out.println("The result is null."); } else { System.out.println(moCode.toString()); for (Mocode e : moCodeList) { System.out.println(e.toString()); } } }); } /** * Lower level API primitives */ public void example6(){ try { SqlSession session = WorkFlowSqlSessionFactory.getInstance().openSession(); try { MoCodeMapper moCodeMapper = session.getMapper(MoCodeMapper.class); //moCodeMapper.InsertDemo(); Mocode moCode = moCodeMapper.getById("107"); List<Mocode> moCodeList = moCodeMapper.getAll(); if (moCode == null) { System.out.println("The result is null."); } else { System.out.println(moCode.toString()); for (Mocode e : moCodeList) { System.out.println(e.toString()); } } session.commit(); } catch (Exception e){ e.printStackTrace(); session.rollback(); } finally { if(session != null) { session.close(); } } } catch (Exception ex) { ex.printStackTrace(); } } /** * More flexible API SQL statement builder classes */ public void example7(){ System.out.println(selectPersonSql()); } private String selectPersonSql() { return new SQL() {{ SELECT("P.ID, P.USERNAME, P.PASSWORD, P.FULL_NAME"); SELECT("P.LAST_NAME, P.CREATED_ON, P.UPDATED_ON"); FROM("PERSON P"); FROM("ACCOUNT A"); INNER_JOIN("DEPARTMENT D on D.ID = P.DEPARTMENT_ID"); INNER_JOIN("COMPANY C on D.COMPANY_ID = C.ID"); WHERE("P.ID = A.ID"); WHERE("P.FIRST_NAME like ?"); OR(); WHERE("P.LAST_NAME like ?"); GROUP_BY("P.ID"); HAVING("P.LAST_NAME like ?"); OR(); HAVING("P.FIRST_NAME like ?"); ORDER_BY("P.ID"); ORDER_BY("P.FULL_NAME"); }}.toString(); } private String selectMoCodeSql() { return new SQL() {{ SELECT("*"); FROM("MOCODE"); //WHERE("ID = '107'"); }}.toString(); } /** * How to use paging query * Divide large-scale data into multiple pages * Solving Problems at the Database Level Using Physical Paging */ public void example8(){ Page<Mocode> page = PageHelper.startPage(1, 10).doSelectPage(()->{ Operate<Mocode> operate = new Operate<>(MoCodeMapper.class); operate.getAll(); }); page.getResult().stream().forEach(System.out::println); } /** * Using the traditional method */ public void example9(){ } /** * Use Operate objects * If you like the more intuitive use of semantics */ public void example10(){ MoCodeOperate moCodeOperate = new MoCodeOperate(); moCodeOperate.getByIdAsync("107").thenAccept(System.out::println); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Insert Example */ public void example11(){ Operate<Mocode> operate = new Operate<>(MoCodeMapper.class); Mocode mocode = new Mocode(); mocode.setAmountPerMonth("3"); mocode.setIsactive("1"); mocode.setMocode("hd985"); mocode.setRowstamp("bbss7"); mocode.setPercentage("3"); mocode.setTablename("Mocode"); mocode.setSubmitted(new Timestamp(System.currentTimeMillis())); mocode.setSubmittedBy("hd945"); mocode.setTablenameId("hsytc"); operate.insert(mocode); } /** * Update Example */ public void example12(){ Operate<Mocode> operate = new Operate<>(MoCodeMapper.class); Mocode mocode = new Mocode(); mocode.setId("5"); mocode.setAmountPerMonth("3"); mocode.setIsactive("1"); mocode.setMocode("hd985"); mocode.setRowstamp("bbss7"); mocode.setPercentage("3"); mocode.setTablename("Mocode"); mocode.setSubmitted(new Timestamp(System.currentTimeMillis())); mocode.setSubmittedBy("hd945"); mocode.setTablenameId("hsytc"); operate.updateById(mocode); } /** * Force Delete Example */ public void example13(){ Operate<Mocode> operate = new Operate<>(MoCodeMapper.class); operate.forceDeleteById("6"); } /** * Insert 100 Rows to DataBase * It's Slow * Cost 20374933551 (nano) / 100 Insert */ public void example14(){ Usage usage = new Usage(); long timeStart = System.nanoTime(); Stream.generate(()-> 1) .limit(100) .forEach(e -> usage.example11()); long timeFinish = System.nanoTime(); System.out.println(timeFinish - timeStart); } /** * Insert By Batch Mode * Cost 2225984012 (nano) / 100 Insert * 20374933551 / 2225984012 ~= 9 (9 Times Faster !) */ public void example15(){ Usage usage = new Usage(); Mocode mocode = new Mocode(); mocode.setAmountPerMonth("3"); mocode.setIsactive("1"); mocode.setMocode("hd985"); mocode.setRowstamp("bbss7"); mocode.setPercentage("3"); mocode.setTablename("Mocode"); mocode.setSubmitted(new Timestamp(System.currentTimeMillis())); mocode.setSubmittedBy("hd945"); mocode.setTablenameId("hsytc"); long timeStart = System.nanoTime(); Tool.consumeBatchSession((session)->{ MoCodeMapper moCodeMapper = session.getMapper(MoCodeMapper.class); Stream.generate(()-> 1) .limit(100) .forEach(e -> moCodeMapper.insert(mocode)); }); long timeFinish = System.nanoTime(); System.out.println(timeFinish - timeStart); } public void example16(){ List<Mocode> mocodeList = new ArrayList<>(); Tool.consumeSession((session)->{ SqlMapper sqlMapper = new SqlMapper(session); sqlMapper.selectList(selectMoCodeSql()).forEach((x)->{ Mocode temp = new Mocode(); temp.setMocode((String) x.get("MOCODE")); mocodeList.add(temp); }); }); mocodeList.forEach(System.out::println); } public void example17(){ Configurations configs = new Configurations(); try { Configuration config = configs.properties("workflow.properties"); String defaultRawstramp = config.getString("default.rawstramp"); Integer defaultIsActive = config.getInteger("default.isactive",1); System.out.println(defaultRawstramp); System.out.println(defaultIsActive); } catch (org.apache.commons.configuration2.ex.ConfigurationException e) { e.printStackTrace(); } } public void example18(){ Mocode mocode = new Mocode(); System.out.println(mocode.getIsactive()); System.out.println(mocode.getRowstamp()); System.out.println(Default.getInstance().getDefaultRawstramp()); System.out.println(Default.getInstance().getDefaultIsActive()); } }
package com.tencent.mm.plugin.account.security.ui; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.kernel.g; import com.tencent.mm.modelfriend.a; import com.tencent.mm.plugin.account.a.j; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.h; class SecurityAccountVerifyUI$3 implements OnClickListener { final /* synthetic */ SecurityAccountVerifyUI ePi; SecurityAccountVerifyUI$3(SecurityAccountVerifyUI securityAccountVerifyUI) { this.ePi = securityAccountVerifyUI; } public final void onClick(View view) { x.v("MicroMsg.SecurityAccountVerifyUI", "on resend verify code button click"); SecurityAccountVerifyUI.b(this.ePi).setVisibility(8); SecurityAccountVerifyUI.a(this.ePi).setTag(Integer.valueOf(60)); SecurityAccountVerifyUI.c(this.ePi).SO(); SecurityAccountVerifyUI.c(this.ePi).J(1000, 1000); a aVar = new a(SecurityAccountVerifyUI.d(this.ePi), 10, "", "", SecurityAccountVerifyUI.e(this.ePi)); g.DF().a(aVar, 0); SecurityAccountVerifyUI securityAccountVerifyUI = this.ePi; ActionBarActivity actionBarActivity = this.ePi.mController.tml; this.ePi.getString(j.app_tip); SecurityAccountVerifyUI.a(securityAccountVerifyUI, h.a(actionBarActivity, this.ePi.getString(j.safe_device_sending_verify_code), true, new 1(this, aVar))); } }
package com.tencent.mm.plugin.emoji.ui; import android.graphics.Bitmap; import com.tencent.mm.a.e; import com.tencent.mm.ak.a.c.l; import com.tencent.mm.plugin.gif.g; class EmojiCustomUI$16 implements l { final /* synthetic */ EmojiCustomUI ilG; EmojiCustomUI$16(EmojiCustomUI emojiCustomUI) { this.ilG = emojiCustomUI; } public final Bitmap K(byte[] bArr) { return g.ay(bArr); } public final Bitmap mf(String str) { return g.ay(e.e(str, 0, e.cm(str))); } }
package main; import java.awt.BorderLayout; import java.awt.Color; import javax.swing.*; import javax.swing.table.DefaultTableModel; import BreezySwing.*; public class AddDlg extends GBDialog { JLabel nameLbl = addLabel("Name", 1,1,1,1); JTextField name = addTextField("", 2,1,1,1); JLabel testLbl = addLabel("Test Score", 1,2,1,1); JTextField test = addTextField("", 2,2,1,1); JButton addTest = addButton("Add Test", 3,2,1,1); JLabel quizLbl = addLabel("Quiz Score", 1,3,1,1); JTextField quiz = addTextField("", 2,3,1,1); JButton addQuiz = addButton("Add Quiz", 3,3,1,1); JLabel hwLbl = addLabel("Homework Average", 1,4,1,1); JTextField hw = addTextField("", 2,4,1,1); JButton add = addButton("Add Student", 10,3,2,1); JButton exit = addButton("Exit", 10,1,2,1); AllStudents all; int testCount; int quizCount; double[] tests; double[] quizzes; double hwAvg; public AddDlg(JFrame frm, AllStudents a) throws FormatException { super(frm); all = a; testCount = 0; quizCount = 0; tests = new double[5]; quizzes = new double[8]; addTest.setEnabled(true); addQuiz.setEnabled(true); test.setEditable(true); quiz.setEditable(true); getContentPane().setBackground(new Color(217, 130, 176)); setSize(800, 250); setTitle("Add Students"); setVisible(true); } public void buttonClicked(JButton button) { if(button==exit) { dispose(); } if(button==add) { try { if(testCount==0) { throw new FormatException("Please enter at least one test score."); } if(quizCount==0) { throw new FormatException("Please enter at least one quiz score."); } setHwAvg(hw.getText()); StudentInfo s = new StudentInfo(name.getText().trim(), tests, testCount, quizzes, quizCount, hwAvg); clearFields(); all.addStudent(s); dispose(); } catch(FormatException e) { messageBox(e.getMessage()); } } if(button==addTest) { try { addTest(test.getText()); testLbl.setText(print(tests, testCount)); if(testCount==5) { addTest.setEnabled(false); test.setEditable(false); quiz.grabFocus(); } else { test.grabFocus(); } } catch(FormatException e) { messageBox(e.getMessage()); } } if(button==addQuiz) { try { addQuiz(quiz.getText()); quizLbl.setText(print(quizzes, quizCount)); if(quizCount==8) { addQuiz.setEnabled(false); quiz.setEditable(false); hw.grabFocus(); } else { quiz.grabFocus(); } } catch(FormatException e) { messageBox(e.getMessage()); } } } private void addTest(String str) throws FormatException { try { if(!str.trim().equals("")) { if(Double.parseDouble(str.trim())<0 || Double.parseDouble(str.trim())>100) { throw new FormatException("Test grade must be between 0-100."); } tests[testCount] = Double.parseDouble(str.trim()); testCount++; test.setText(""); } } catch(NumberFormatException e) { throw new FormatException("Invalid test input."); } } private void addQuiz(String str) throws FormatException { try { if(!str.trim().equals("")) { if(Double.parseDouble(str.trim())<0 || Double.parseDouble(str.trim())>100) { throw new FormatException("Quiz grade must be between 0-100."); } quizzes[quizCount] = Double.parseDouble(str.trim()); quizCount++; quiz.setText(""); } } catch(NumberFormatException e) { throw new FormatException("Invalid quiz input."); } } private void setHwAvg(String str) throws FormatException { try { if(str.trim().equals("")) { throw new FormatException("Invalid homework average."); } if(Double.parseDouble(str.trim())<0 || Double.parseDouble(str.trim())>100) { throw new FormatException("Homework average must be between 0-100."); } hwAvg = Double.parseDouble(str.trim()); } catch(NumberFormatException e) { throw new FormatException("Invalid homework average."); } } private void clearFields() { name.setText(""); test.setText(""); quiz.setText(""); hw.setText(""); } private String print(double[] arr, int length) { String out = String.format("%.1f", arr[0]); for(int i=1; i<length; i++) { out += ", " + String.format("%.1f", arr[i]); } return out; } }
package de.zarncke.lib.test; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import junit.framework.Assert; import junit.framework.Test; import junit.framework.TestSuite; import org.joda.time.DateTime; import org.junit.Assume; import org.junit.experimental.categories.Category; public class Tests { public static void assumeTimeIsAfter(final int year, final int month, final int day) { Assume.assumeTrue(new DateTime().isAfter(new DateTime(year, month, day, 0, 0, 0, 0))); } public static void assertContentEquals(final List<?> a, final List<?> b) { Assert.assertEquals(new ArrayList<Object>(a), new ArrayList<Object>(b)); } public static void assertContentEquals(final Set<?> a, final Set<?> b) { Assert.assertEquals(new HashSet<Object>(a), new HashSet<Object>(b)); } public static void assertContentEquals(final Collection<?> a, final Collection<?> b) { Assert.assertTrue("a containsAll b", a.containsAll(b)); Assert.assertTrue("b containsAll a", b.containsAll(a)); } public static void addTestsFromTestCase(final TestSuite suite, final Class<?> theClass, final Class<?>... categories) { addTestsFromTestCase(suite, true, theClass, categories); } public static void addTestsFromTestCase(final TestSuite suite, final boolean onlyClassesImplementingTest, final Class<?> theClass, final Class<?>... categories) { try { TestSuite.getTestConstructor(theClass); // Avoid generating multiple error messages } catch (NoSuchMethodException e) { suite.addTest(TestSuite.warning("Class " + theClass.getName() + " has no public constructor TestCase(String name) or TestCase()")); return; } if (!Modifier.isPublic(theClass.getModifiers())) { suite.addTest(TestSuite.warning("Class " + theClass.getName() + " is not public")); return; } Class<?> superClass = theClass; List<String> names = new ArrayList<String>(); while (onlyClassesImplementingTest ? Test.class.isAssignableFrom(superClass) : superClass != null) { for (Method each : superClass.getDeclaredMethods()) { if (hasMethodMatchingCategory(each, categories) || hasClassMatchingCategory(superClass, categories)) { addTestMethod(suite, each, names, theClass); } } superClass = superClass.getSuperclass(); } } public static boolean hasMethodMatchingCategory(final Method testMethod, final Class<?>[] categories) { Category category = testMethod.getAnnotation(Category.class); return isCategoryMatching(category, categories); } public static boolean hasClassMatchingCategory(final Class<?> testClass, final Class<?>[] categories) { Category category = testClass.getAnnotation(Category.class); return isCategoryMatching(category, categories); } private static boolean isCategoryMatching(final Category category, final Class<?>[] categories) { boolean ok; if (categories.length == 0) { ok = category == null; } else { ok = false; if (category != null) { findCategory: for (Class<?> requiredCategory : categories) { for (Class<?> annotatedCategory : category.value()) { if (requiredCategory.isAssignableFrom(annotatedCategory)) { ok = true; break findCategory; } } } } } return ok; } private static void addTestMethod(final TestSuite suite, final Method m, final List<String> names, final Class<?> theClass) { String name = m.getName(); if (names.contains(name)) { return; } if (!isPublicTestMethod(m)) { if (isTestMethod(m)) { suite.addTest(TestSuite.warning("Test method isn't public: " + m.getName() + "(" + theClass.getCanonicalName() + ")")); } return; } names.add(name); suite.addTest(TestSuite.createTest(theClass, name)); } private static boolean isPublicTestMethod(final Method m) { return isTestMethod(m) && Modifier.isPublic(m.getModifiers()); } private static boolean isTestMethod(final Method m) { return m.getParameterTypes().length == 0 && m.getName().startsWith("test") && m.getReturnType().equals(Void.TYPE); } }
package com.mx.profuturo.bolsa.service.common; public abstract class OpenHrServiceBase implements OpenHrService { }
package com.example.carwash; import androidx.annotation.Dimension; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class SummaryActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_summary); TextView txt = findViewById(R.id.txtViewSummary); String outString = "Conversion Summary\n"; txt.setTextSize(Dimension.SP,24); if(getIntent() != null){ Bundle myBundle = getIntent().getExtras(); outString += String.format("Input Weight = %2f %s\n", myBundle.getDouble("INPUTWT")); } txt.setText(outString); setContentView(txt); getActionBar().setDisplayHomeAsUpEnabled(true); } }
package com.example.radio.Adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.example.radio.Activity.ProfileActivity; import com.example.radio.Interface.ShowAllDataInterfsce; import com.example.radio.Model.AllData; import com.example.radio.R; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; public class EmployessAdapter extends RecyclerView.Adapter<EmployessAdapter.Custom_emp> { Context context; ArrayList<AllData> arrayList; ShowAllDataInterfsce showAllDataInterfsce; public EmployessAdapter(Context context, ArrayList<AllData> arrayList, ShowAllDataInterfsce showAllDataInterfsce) { this.context= context; this.arrayList= arrayList; this.showAllDataInterfsce= showAllDataInterfsce; } @NonNull @Override public Custom_emp onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.emp_layout_custom, null, true); view.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)); return new Custom_emp(view); } @Override public void onBindViewHolder(@NonNull Custom_emp holder, int position) { AllData allData= arrayList.get(position); Glide.with(context).load(arrayList.get(position).getImgUrl()).into(holder.circleImageView); holder.textView_name.setText(arrayList.get(position).getmName()); holder.textView_name.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent= new Intent(context, ProfileActivity.class); intent.putExtra("data", allData); context.startActivity(intent); } }); } @Override public int getItemCount() { return arrayList.size(); } class Custom_emp extends RecyclerView.ViewHolder{ CircleImageView circleImageView; TextView textView_name; public Custom_emp(@NonNull View itemView) { super(itemView); circleImageView= itemView.findViewById(R.id.profile_img11); textView_name = itemView.findViewById(R.id.userTextView); } } }
package ro.redeul.google.go.lang.parser; import java.io.File; import java.io.IOException; import java.util.List; import com.intellij.openapi.application.PluginPathManager; import com.intellij.openapi.util.io.FileUtil; import com.intellij.psi.PsiFile; import com.intellij.psi.impl.DebugUtil; import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; import ro.redeul.google.go.util.TestUtils; public abstract class GoParsingTestCase extends LightCodeInsightFixtureTestCase { @Override protected String getBasePath() { String base = FileUtil.toSystemIndependentName(PluginPathManager.getPluginHomePathRelative("google-go-language")) + "/testdata/"; return base + File.separator + "parsing" + File.separator + "go"; } protected String getLocalTestDataPath() { return getBasePath(); } public void doTest() throws IOException { doTest(getTestName(true).replace('$', '/') + ".test"); } private void doTest(String fileName) throws IOException { final List<String> list = TestUtils.readInput(getTestDataPath() + "/" + fileName); final String input = list.get(0); if ( list.size() != 2 || list.get(1).trim().length() == 0 ) { dumpParsingTree(input, getTestDataPath() + "/" + fileName); } else { checkParsing(input, list.get(1).trim()); } } protected void dumpParsingTree(String input, String fileName) throws IOException { final PsiFile psiFile = TestUtils.createPseudoPhysicalGoFile(getProject(), input); String psiTree = DebugUtil.psiToString(psiFile, false); TestUtils.writeTestFile(input, psiTree.trim(), fileName); } protected void checkParsing(String input, String output) { final PsiFile psiFile = TestUtils.createPseudoPhysicalGoFile(getProject(), input); String psiTree = DebugUtil.psiToString(psiFile, false); org.testng.Assert.assertEquals(psiTree.trim(), output.trim()); } }
/* * FileTest.java * * Created on 2016年3月26日, 下午9:16 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package view; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Label; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; /** * * @author xubo */ public class FileTest { /** Creates a new instance of FileTest */ public FileTest() { } public static void main(String[] args){ final Frame f1=new Frame("QQ"); f1.setBounds(200,200,500,300); final String title1=f1.getTitle(); MenuBar m1=new MenuBar(); Menu m2=new Menu("文件"); Menu m3=new Menu("更改名称"); // MenuItem i1=new MenuItem("更改名称"); MenuItem i2=new MenuItem("打开记事本"); final MenuItem i3=new MenuItem("推出系统"); final MenuItem i11=new MenuItem("好好学习"); final MenuItem i12=new MenuItem("天天向上"); final MenuItem i13=new MenuItem("恢复标题"); m2.add(m3); m3.add(i11); m3.add(i12); m3.add(i13); m2.add(i2); m2.add(i3); m1.add(m2); // f1.add(m1); f1.setMenuBar(m1); i2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Runtime r1=Runtime.getRuntime(); try { r1.exec("notepad"); } catch (IOException ex) { ex.printStackTrace(); } } }); i11.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f1.setTitle(i11.getLabel()); } }); i12.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f1.setTitle(i12.getLabel()); } }); i13.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { f1.setTitle(title1); } }); f1.setLayout(new FlowLayout()); f1.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); i3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); f1.setVisible(true); } }
package pack1; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.opera.OperaDriver; import org.openqa.selenium.support.ui.WebDriverWait; public class Vtiger1 { public static void main(String[] args) throws Exception { WebDriver driver=null; FileInputStream fsi=new FileInputStream("./commonData.properties"); Properties pobj= new Properties(); pobj.load(fsi); String BROWSER=pobj.getProperty("browser"); String URL=pobj.getProperty("url"); String USERNAME=pobj.getProperty("username"); String PASSWORD=pobj.getProperty("password"); String OrgName=pobj.getProperty("organization"); String WEBSITE=pobj.getProperty("website"); String TICKER=pobj.getProperty("tickersymbol"); String EMPLOYEES=pobj.getProperty("Employees"); if(BROWSER.equals("chrome")) { driver=new ChromeDriver(); } else if(BROWSER.equals("firefox")) { driver=new FirefoxDriver(); } else if(BROWSER.equals("ie")) { driver=new InternetExplorerDriver(); } else if(BROWSER.equals("opera")) { driver=new OperaDriver(); } driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); WebDriverWait wait=new WebDriverWait(driver,10); driver.get(URL); driver.findElement(By.name("user_name")).sendKeys(USERNAME); driver.findElement(By.name("user_password")).sendKeys(PASSWORD); driver.findElement(By.id("submitButton")).click(); driver.findElement(By.linkText("Organizations")).click(); driver.findElement(By.cssSelector("img[title='Create Organization...']")).click(); driver.findElement(By.name("accountname")).sendKeys(OrgName); driver.findElement(By.name("website")).sendKeys(WEBSITE); driver.findElement(By.id("tickersymbol")).sendKeys(TICKER); driver.findElement(By.id("employees")).sendKeys(EMPLOYEES); driver.findElement(By.cssSelector("input[title='Save [Alt+S]']")).click(); WebElement orgverify = driver.findElement(By.xpath("//span[contains(text(),'Organization Information')]")); System.out.println(orgverify.getText()); if(orgverify.getText().contains(OrgName)){ System.out.println("Pass::organization hasbeen created sucessfully"); }else System.out.println("Fail::organization is not created"); Actions actions=new Actions(driver); WebElement signoutmenu = driver.findElement(By.cssSelector("img[src='themes/softed/images/user.PNG']")); actions.moveToElement(signoutmenu).perform(); driver.findElement(By.linkText("Sign Out")).click(); driver.quit(); } }
package jp.personal.server.domain.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import jp.personal.server.domain.entity.base.BaseEntity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * The persistent class for the message_read database table. */ @AllArgsConstructor @NoArgsConstructor @Data @Entity @Table(name = "message_read") @NamedQueries({// @NamedQuery(name = "MessageRead.findAll", query = "SELECT m FROM MessageRead m"), // @NamedQuery(// name = "MessageRead.findByMsgId",// query = "SELECT m FROM MessageRead m WHERE m.messageId = :messageId AND m.deleted = :deleted ORDER BY m.id DESC"), @NamedQuery(// name = "MessageRead.findByMsgListAndUserId",// query = "SELECT m FROM MessageRead m WHERE m.messageId in (:messageIdList) AND m.userId = :userId AND m.deleted in (:deletedList) ORDER BY m.id DESC"), @NamedQuery(// name = "MessageRead.findByUnique",// query = "SELECT m FROM MessageRead m WHERE m.messageId = :messageId AND m.userId = :userId AND m.deleted in (:deletedList) ORDER BY m.id DESC")}) public class MessageRead extends BaseEntity { private static final long serialVersionUID = 2377932200497420692L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Temporal(TemporalType.TIMESTAMP) private Date date; @Column(name = "message_id") private Long messageId; @Column(name = "user_id") private int userId; }
package com.netcracker.financeapp.mapping; public class Agent implements java.io.Serializable { private int idAgent; private String accountNumber; private String name; public Agent() { } public Agent(int idAgent) { this.idAgent = idAgent; } public Agent(int idAgent, String accountNumber, String name) { this.idAgent = idAgent; this.accountNumber = accountNumber; this.name = name; } public void setIdAgent(int idAgent) { this.idAgent = idAgent; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public void setName(String name) { this.name = name; } public int getIdAgent() { return idAgent; } public String getAccountNumber() { return accountNumber; } public String getName() { return name; } }
import java.util.Collections; import java.util.Hashtable; import java.util.Map; import java.util.stream.Collectors; public class readonlymap { public static void main(String[] args) { Hashtable<String,Integer> ha = new Hashtable<>(); ha.put("p", 79); ha.put("o", 78); ha.put("t", 77); Map<String, Integer> um = Collections.unmodifiableMap(ha); um.put("s", 76); System.out.println(um); } }
/* * Purpose:-Read .a List of Numbers from a file and arrange it * ascending Order in a Linked List. Take user input for a number, * if found then pop the number out of the list else insert * the number in appropriate position * *@Author:-Arpana Kumari *Version:-1.0 *@Since:-25 April,2017 */ package com.bridgeit.dataStructurePrograms; import java.io.BufferedReader; import java.io.FileReader; import com.bridgeit.utility.Utility; public class OrderedList { public static void main(String[] args) throws Exception { OrderedLinkedList<Integer> list = new OrderedLinkedList<Integer>(); FileReader read = new FileReader("ordered"); BufferedReader br = new BufferedReader(read); String file = br.readLine(); System.out.println("File contains :"); System.out.println(file); br.close(); String[] stringArray = file.split("\\s",0); Object[] array = list.SortInt(stringArray); int i, j; //System.out.println("The sorted array is:"); for (i = 0; i < stringArray.length; i++) { //System.out.println(array[i]); } for (j = 0; j < i; j++) { list.add(array[j]); } System.out.println("Enter the value to be search:"); String value = Utility.inputString(); int index = list.search(value); if (index == 0) { list.sortedAdd(value); } else { list.remove(value, index); } System.out.println("After searching:"); list.show(); list.printOrdered(); } }
package net.trejj.talk.activities; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import net.trejj.talk.R; import org.json.JSONException; import org.json.JSONObject; import co.paystack.android.Paystack; import co.paystack.android.PaystackSdk; import co.paystack.android.Transaction; import co.paystack.android.model.Card; import co.paystack.android.model.Charge; public class ChargePaystack extends Activity { private Card card; private Charge charge; private ProgressDialog pDialog; // private BalanceActivity balance; private EditText emailField; private EditText cardNumberField; private EditText expiryMonthField; private EditText expiryYearField; private EditText cvvField; private String USD,NGN,finalNGN; // IabHelper mHelper; private Boolean loading = false; private String SKU; private Integer custom_amount =0; private String credits; private String title; private String price; private String email, cardNumber, cvv; private int expiryMonth, expiryYear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //init paystack sdk PaystackSdk.initialize(getApplicationContext()); setContentView(R.layout.content_charge_paystack); initpDialog(); // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); // setSupportActionBar(toolbar); if (savedInstanceState != null) { loading = savedInstanceState.getBoolean("loading"); } else { loading = false; } // balance = new BalanceActivity(); //init view Intent intent = getIntent(); Button payBtn = (Button) findViewById(R.id.pay_button); if (intent != null){ // SKU = bundle.getString("paystack_sku"); price = intent.getStringExtra("price"); title = intent.getStringExtra("title"); credits = intent.getStringExtra("credits"); previousPoints = intent.getStringExtra("points"); } else{ Toast.makeText(getApplicationContext(),"Bundle Error!", Toast.LENGTH_LONG).show(); return; } emailField = (EditText) findViewById(R.id.edit_email_address); cardNumberField = (EditText) findViewById(R.id.edit_card_number); expiryMonthField = (EditText) findViewById(R.id.edit_expiry_month); expiryYearField = (EditText) findViewById(R.id.edit_expiry_year); cvvField = (EditText) findViewById(R.id.edit_cvv); payBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!validateForm()) { return; } try { showpDialog(); email = emailField.getText().toString().trim(); cardNumber = cardNumberField.getText().toString().trim(); expiryMonth = Integer.parseInt(expiryMonthField.getText().toString().trim()); expiryYear = Integer.parseInt(expiryYearField.getText().toString().trim()); cvv = cvvField.getText().toString().trim(); // String cardNumber = "4084084084084081"; // int expiryMonth = 11; //any month in the future // int expiryYear = 18; // any year in the future // String cvv = "408"; emailField.setText(email); card = new Card(cardNumber, expiryMonth, expiryYear, cvv); if (card.isValid()) { // Toast.makeText(ChargePaystack.this, "Card is Valid", Toast.LENGTH_LONG).show(); // performCharge(); getFreshRates(); } else { hidepDialog(); Toast.makeText(ChargePaystack.this, "Card is not Valid", Toast.LENGTH_LONG).show(); } } catch (Exception e) { hidepDialog(); e.printStackTrace(); } } }); } private void getFreshRates() { NGN="";USD="";finalNGN =""; RequestQueue queue = Volley.newRequestQueue(this); final String url = "https://radius.trejj.net/convert.php?from=USD&to=NGN&amount=1"; // prepare the Request JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // display response Log.e("Response:",response.toString()); // Log.e("Found:",response.getString("rate")); try { finalNGN = response.getString("rate"); } catch (JSONException e) { e.printStackTrace(); } performCharge(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("Error.Response", error.getMessage()); } } ); // add it to the RequestQueue queue.add(getRequest); } /** * Method to perform the charging of the card */ private void performCharge() { //create a Charge object charge = new Charge(); Log.e("Gonna","Chagggggggghghghghg"); Integer amount_to_charge=0; Integer amount_in_KOBO=0; if(finalNGN.equals("")){ Toast.makeText(ChargePaystack.this, "finalNGN is null", Toast.LENGTH_SHORT).show(); return; } double temp =(Double.parseDouble(price)* Double.parseDouble(finalNGN))*100; /*amount_to_charge = custom_amount; amount_in_KOBO = amount_to_charge * 100; //converting NGN to KOBO */ amount_in_KOBO = Integer.parseInt(String.valueOf(Math.round(temp))); //set the card to charge charge.setCard(card); //call this method if you set a plan //charge.setPlan("PLN_yourplan"); charge.setEmail(email); //dummy email address // if(SKU.equals("custom")) { // amount_to_charge = custom_amount; // amount_in_KOBO = amount_to_charge * 100; //converting NGN to KOBO // // // } // else // { // // amount_to_charge = get_amount_(SKU); // amount_in_KOBO = amount_to_charge * 100; //converting NGN to KOBO // // // } charge.setAmount(amount_in_KOBO); // amount to Charge, accepts in KOBO, (1NGN * 100) = 1 KOBO Log.e("amount_in_kobooo","koboo"+amount_in_KOBO); PaystackSdk.chargeCard(ChargePaystack.this, charge, new Paystack.TransactionCallback() { @Override public void onSuccess(Transaction transaction) { // This is called only after transaction is deemed successful. // Retrieve the transaction, and send its reference to your server // for verification. chargeFinished(transaction); } @Override public void beforeValidate(Transaction transaction) { // This is called only before requesting OTP. // Save reference so you may send to server. If // error occurs with OTP, you should still verify on server. Log.e("OTOp","Reuired"); } @Override public void onError(Throwable error, Transaction transaction) { Log.e("OTOp","Reuired2"); //handle error here } }); // PaystackSdk.chargeCard(ChargePaystack.this, charge, new Paystack.TransactionCallback() { // @Override // public void onSuccess(Transaction transaction) { // // // This is called only after transaction is deemed successful. // // Retrieve the transaction, and send its reference to your server // // for verification. // String paymentReference = transaction.getReference(); //// Toast.makeText(ChargePaystack.this, "Transaction Successful! payment reference: " //// + paymentReference, Toast.LENGTH_LONG).show(); // // // chargeFinished(transaction); // } // // @Override // public void beforeValidate(Transaction transaction) { // // // // // // This is called only before requesting OTP. // // Save reference so you may send to server. If // // error occurs with OTP, you should still verify on server. // } // // @Override // public void onError(Throwable error, Transaction transaction) { // hidepDialog(); //// Log.e("PaymentUndone",transaction.toString()); // customDialog("Payment error","Payment was unsuccessful, Please try later "+error.getMessage()); // // //handle error here // } // }); } private String previousPoints; public void chargeFinished(Transaction transaction) { hidepDialog(); double newPoints = Double.parseDouble(previousPoints) + Double.parseDouble(credits); DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("users") .child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("credits"); reference.setValue(newPoints).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()){ AlertDialog.Builder builder = new AlertDialog.Builder(ChargePaystack.this); builder.setMessage("Congratulations, you have successfully purchased "+ credits + " credits!") .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); ChargePaystack.super.onBackPressed(); } }).show(); } } }); } private boolean validateForm() { boolean valid = true; String email = emailField.getText().toString(); if (TextUtils.isEmpty(email)) { emailField.setError("Required."); valid = false; } else { emailField.setError(null); } String cardNumber = cardNumberField.getText().toString(); if (TextUtils.isEmpty(cardNumber)) { cardNumberField.setError("Required."); valid = false; } else { cardNumberField.setError(null); } String expiryMonth = expiryMonthField.getText().toString(); if (TextUtils.isEmpty(expiryMonth)) { expiryMonthField.setError("Required."); valid = false; } else { expiryMonthField.setError(null); } String expiryYear = expiryYearField.getText().toString(); if (TextUtils.isEmpty(expiryYear)) { expiryYearField.setError("Required."); valid = false; } else { expiryYearField.setError(null); } String cvv = cvvField.getText().toString(); if (TextUtils.isEmpty(cvv)) { cvvField.setError("Required."); valid = false; } else { cvvField.setError(null); } return valid; } private void cancelMethod1(){ return; } @RequiresApi(api = Build.VERSION_CODES.KITKAT) private void okMethod1(){ } /** * Custom alert dialog that will execute method in the class * @param title * @param message */ public void customDialog(String title, String message){ AlertDialog.Builder builder = new AlertDialog.Builder(ChargePaystack.this); builder.setMessage(message) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }).show(); } public void show_msg(String message){ AlertDialog.Builder builder = new AlertDialog.Builder(ChargePaystack.this); builder.setMessage(message) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }).show(); } protected void initpDialog() { pDialog = new ProgressDialog(ChargePaystack.this); pDialog.setMessage(getString(R.string.please_wait)); pDialog.setCancelable(false); } protected void showpDialog() { if (!pDialog.isShowing()) pDialog.show(); } protected void hidepDialog() { if (pDialog.isShowing()) pDialog.dismiss(); } }
package multipath; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; /*********************************************************************************************************************** * This class provides helper methods needed for various MultipathOSCARSClient methods to work appropriately. * This class exists solely to provide a higher layer of modularity and keep MultipathOSCARSClient.java clean. * * @author Jeremy ***********************************************************************************************************************/ public class HelperMiscellaneous { public static final String mpQueryOut = MultipathOSCARSClient.mpQueryOut; // File containing subrequest statuses for queried MP reservations. public static final String mpLookupGRI = MultipathOSCARSClient.mpLookupGRI; // File which acts as the MP-GRI lookup table public static final String mpTrackerGRI = MultipathOSCARSClient.mpTrackerGRI; // File containing tracker for next MP-GRI number /********************************************************************************************************************************************************* * Inspects the MP-GRI lookup table (file) to determine if the given groupGRI exists. * IF the GRI exists, THEN the corresponding regular-format MP-GRI will be returned. * ELSE will return the unaltered groupGRI. * * @param groupGRI * @return regular-format MP-GRI corresponding to input parameter groupGRI, or the original groupGRI if no such correspondence exists. *********************************************************************************************************************************************************/ protected String getRegularMPGri(String groupGRI) { String originalGRI = groupGRI; // MP-GRI simple-format: "MP-ID" // MP-GRI regular-format: "MP-ID:_K_:<gri1>:<gri2>:<griK>" // K = Destination Set size // MP-GRI long-format: "MP-ID_=_MP-ID:_K_:<gri1>:<gri2>:<griK>" if(groupGRI.startsWith("MP")) { // MP-GRI is in short-format --> Open up mp_gri_lookup.txt and lookup the corresponding long-format MP-GRI. // if(!groupGRI.contains(":_")) { try { FileInputStream griStream = new FileInputStream(mpLookupGRI); DataInputStream griIn = new DataInputStream(griStream); BufferedReader griBr = new BufferedReader(new InputStreamReader(griIn)); String strGriLine; while(true) { strGriLine = griBr.readLine(); if(strGriLine == null) break; // If MP-GRI is valid, convert short-format to corresponding long-format MP-GRI. // if(strGriLine.substring(0, strGriLine.indexOf("_=_")).equals(groupGRI)) { groupGRI = strGriLine;; break; } } griBr.close(); griIn.close(); griStream.close(); } catch(Exception e) { System.err.println("Problem looking up MP-GRI in \'mp_gri_lookup.txt\'"); System.err.println(originalGRI + " is not a valid MP-GRI, cannot Query."); System.exit(-1); } } // MP-GRI is in long-format --> convert to corresponding regular-format MP-GRI. // if(groupGRI.contains("_=_")) { groupGRI = groupGRI.substring(groupGRI.indexOf("_=_")+3); } } return groupGRI; // If unicast, gri will be returned unaltered. } /********************************************************************************************************************************************************* * Truncates the given groupGRI from long-format and/or regular-format. * * @param groupGRI * @return short-format MP-GRI corresponding to input parameter groupGRI, or the original groupGRI if no such correspondence exists. *********************************************************************************************************************************************************/ protected String getShortMPGri(String groupGRI) { // MP-GRI simple-format: "MP-ID" // MP-GRI regular-format: "MP-ID:_K_:<gri1>:<gri2>:<griK>" // K = Destination Set size // MP-GRI long-format: "MP-ID_=_MP-ID:_K_:<gri1>:<gri2>:<griK>" // MP-GRI is in regular-format or long-format --> truncate to the corresponding short-format MP-GRI. // if(groupGRI.contains(":_")) { groupGRI = groupGRI.substring(0, groupGRI.indexOf(":_")); } // MP-GRI was originally in long-format --> convert to corresponding short-format MP-GRI. // if(groupGRI.contains("_=_")) { groupGRI = groupGRI.substring(0, groupGRI.indexOf("_=_")); } return groupGRI; // If already in short-form, gri will be returned unaltered. } /********************************************************************************************************************************************************* * Inspects the MP-GRI lookup table (file) to determine if the given groupGRI exists. * IF the GRI exists, THEN the corresponding long-format MP-GRI will be returned. * ELSE will return a newly created long-format MP-GRI. * * @param groupGRI * @return long-format MP-GRI corresponding to input parameter gri, or a new long-format MP-GRI if no such correspondence exists. *********************************************************************************************************************************************************/ protected String getLongMPGri(String gri) { String shortGRI; // MP-GRI simple-format: "MP-ID" // MP-GRI regular-format: "MP-ID:_K_:<gri1>:<gri2>:<griK>" // K = Destination Set size // MP-GRI long-format: "MP-ID_=_MP-ID:_K_:<gri1>:<gri2>:<griK>" if(!gri.startsWith("MP")) { return null; // All group IDs must start with "MP" } else { try { gri = getShortMPGri(gri); shortGRI = gri; FileInputStream griStream = new FileInputStream(mpLookupGRI); DataInputStream griIn = new DataInputStream(griStream); BufferedReader griBr = new BufferedReader(new InputStreamReader(griIn)); String strGriLine; while(true) { strGriLine = griBr.readLine(); if(strGriLine == null) break; // If short-format GRI is in lookup table, convert to corresponding long-format GRI // if(strGriLine.substring(0, strGriLine.indexOf("_=_")).equals(shortGRI)) { gri = strGriLine; break; } } griBr.close(); griIn.close(); griStream.close(); if(shortGRI.equals(gri)) // MP-GRI not in lookup table, make new long-form GRI { gri += "_=_" + gri + ":_0_:"; } } catch(Exception e) { System.err.println("Problem looking up MP-GRI in \'mp_gri_lookup.txt\'"); e.printStackTrace(); System.exit(-1); } return gri; } } /********************************************************************************************************************************************************* * Inspects the MP-GRI lookup tracker (file) to determine what the next default MP-GRI should be, and updates the file accordingly. * IF the GRI exists, THEN the corresponding long-format MP-GRI will be returned. *********************************************************************************************************************************************************/ protected Integer getMPGri(Integer thisMPGri) { try { int thisGri; FileInputStream fstream = new FileInputStream(mpTrackerGRI); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); thisMPGri = new Integer(strLine.trim()); thisGri = thisMPGri.intValue() + 1; // increment the GRI counter for the next request FileWriter fstream_out = new FileWriter(mpTrackerGRI); BufferedWriter out = new BufferedWriter(fstream_out); Integer nextMcGri = new Integer(thisGri); out.write(nextMcGri.toString()); in.close(); fstream.close(); out.close(); fstream_out.close(); } catch(Exception e) //mp_gri_tracker.txt doesn't exist { try { FileWriter fstream_out = new FileWriter(mpTrackerGRI); BufferedWriter out = new BufferedWriter(fstream_out); out.write("1"); out.close(); thisMPGri = new Integer(0); } catch(Exception e2){e2.printStackTrace();} } return thisMPGri + 1; } }
package com.rc.utils.notification; import com.rc.panels.NotificationPopup; import javax.swing.*; import java.awt.*; import java.util.*; /** * @author song * @date 19-9-29 09:25 * @description * @since */ public class NotificationUtil { private static Stack<NotificationPopup> idles = new Stack<>(); private static Stack<NotificationPopup> showns = new Stack<>(); private static NotificationEventListener eventListener; private static Dimension windowDimension = Toolkit.getDefaultToolkit().getScreenSize(); /** * 等待中的消息队列 */ public static Queue<MsgItem> waitingItems = new ArrayDeque<>(); private static int initCapacity = 5; static { eventListener = new NotificationEventListener() { @Override public void onShown(NotificationPopup src) { } @Override public void onClosed(NotificationPopup src) { idles.push(src); showns.remove(src); adjustAfterPopup(); // 从等待队列获取一条消息 MsgItem item = waitingItems.poll(); if (item != null) { show(item.roomId, item.icon, item.title, item.brief, item.message); } } }; for (int i = 0; i < initCapacity; i++) { NotificationPopup pop = new NotificationPopup(); pop.setListener(eventListener); idles.push(pop); } } public static synchronized void show(String roomId, ImageIcon icon, String title, String brief, String message) { try { NotificationPopup popup = idles.pop(); popup.show(roomId, icon, title, brief, message, calcLocation()); showns.push(popup); } catch (EmptyStackException e) { waitingItems.add(new MsgItem(roomId, icon, title, brief, message)); System.out.println("通知队列已满"); } } private static Point calcLocation() { Point location; int gap = 50; int height = NotificationPopup.HEIGHT + 20; if (showns.size() == 0) { location = new Point((int) (windowDimension.getWidth() - 320), gap); } else { location = new Point((int) (windowDimension.getWidth() - 320), gap + height * showns.size()); } return location; } private static void adjustAfterPopup() { int height = NotificationPopup.HEIGHT + 20; int gap = 50; for (int i = 0; i < showns.size(); i++) { NotificationPopup pop = showns.get(i); Point p = pop.getLocation(); /* int y = p.y - height; if (showns.size() == 1) { y = gap; }*/ int y; if (i == 0) { y = gap; } else { y = gap + height * i; } int destY = y; /*Point newP = null; newP = new Point(p.x, destY); pop.setLocation(newP); System.out.println(newP);*/ new Thread(() -> { Point newP = null; int cy = p.y; while (cy >= destY) { newP = new Point(p.x, cy); pop.setLocation(newP); cy -= 10; try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } } class MsgItem { public String roomId; public ImageIcon icon; public String title; public String brief; public String message; public MsgItem() { } public MsgItem(String roomId, ImageIcon icon, String title, String brief, String message) { this.roomId = roomId; this.icon = icon; this.title = title; this.brief = brief; this.message = message; } }
package com.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.bean.Product; import com.dao.ProductDao; import com.sun.org.apache.regexp.internal.RE; /** * Servlet implementation class AServlet */ @WebServlet("/AServlet") public class AServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // System.out.println("!!!!!!!!"); // request.setCharacterEncoding("UTF-8"); // ProductDao dao = new ProductDao(); // List<Product> ps=dao.getProduct(); // request.setAttribute("ps", ps); // request.getRequestDispatcher("cart.jsp").forward(request,response); // return; request.setCharacterEncoding("11111"); String username=request.getParameter("userName"); String password = request.getParameter("password"); String Agent = request.getHeader("User-Agent"); System.out.println(Agent); if(!"cat".equals(username)){ String msg="错误"; request.setAttribute("msg", msg); RequestDispatcher re=request.getRequestDispatcher("login.jsp"); re.forward(request, response); } else{ HttpSession session = request.getSession(); session.setAttribute("username", username); response.sendRedirect("/test1/suss.jsp"); } } }
package advance; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; public class Map01 { // Map /* Mapとは、「キー」と「値」の組み合わせで要素を管理するコレクションです。Mapは、1つの「キー」に対して、1つの「値」が存在します。そのため、「キー」は重複して保持することができません。「値」は、重複して保持することができます。追加した要素の順番は保証されません。MapもList同様にインターフェースのため、HashMapやTreeMapなどのMapを実装したクラスを使用する必要があります。 */ public static void main(String[] args) { // Mapの生成 /* 実装したいクラスによって異なりますが、生成は次のように行います */ // HashMapを生成する場合 Map<Integer, String> map1 = new HashMap<Integer, String>(); // TreeMapを生成する場合 Map<String, String> map2 = new TreeMap<String, String>(); // Mapの操作 /* Listと同様、使えるメソッドの一部を紹介します。例として、HashMap map1 を捜査対象としていますが、どのクラスを実装していても使えるメソッドは同じです。 */ // 要素の追加 // 要素を追加するにはputメソッドを使います。既に追加済みのキーを用いると、あとから追加した値で上書きされます。 // 要素を追加する map1.put(0, "ぶどう"); map1.put(3, "もも"); // 要素の取得 System.out.println(map1.get(0)); System.out.println(map1.get(3)); // 登録済みのキーで追加すると上書きされる map1.put(0, "マスカット"); System.out.println(map1.get(0)); // マスカットを返す // 存在しないキーを指定した場合は戻り値がnullとなるので注意 System.out.println(map1.get(1)); // nullを返す // 要素の存在チェック // ある要素が含まれるか確認するにはcontainsKeyやcontainsValueを使います。名前の通り、それぞれキーと値のチェックができるメソッドで、戻り値はbooleanです。 // キーの存在チェック (trueを返す) System.out.println(map1.containsKey(0)); // 値の存在チェック (falseを返す) System.out.println(map1.containsValue("ぶどう")); // 要素数の取得 // コレクションの要素数の合計を取得するには、 size メソッドを使います System.out.println(map1.size()); // 2を返す // 要素の削除 // 要素を削除するにはremoveメソッドを使います。キーのみか、キーと値の両方の指定ができます。キーを指定するとそれで特定される要素が削除され、両方を指定した場合はキーも値もともに一致する要素が削除されます。いずれも、該当する要素が存在しなければ何もせず、エラーも発生しません。 // キーを指定して要素を削除する map1.remove(0); map1.remove(1); // 何もしない // キーと値を指定して要素を削除する map1.remove(3, "もも"); map1.remove(3, "なし"); // 何もしない System.out.println(map1.get(1)); // removeした後なので、出力結果はnullになる // 拡張for文 /* キーのみ 値のみ キーと値のペア のいずれかをループの対象とすることができます。 */ Map<Integer, String> classmates = new HashMap<>(); classmates.put(1, "青木"); classmates.put(2, "石坂"); classmates.put(3, "小野田"); // キーのみ for (Integer key : classmates.keySet()) { System.out.println(key); // 1, 2, 3の順に表示 } // 値のみ for (String name : classmates.values()) { System.out.println(name); // 青木、石坂、小野田の順に表示 } // キーと値のペア for (Map.Entry<Integer, String> classmate : classmates.entrySet()) { System.out.println(classmate.getKey() + "番は" + classmate.getValue() + "さん"); // 1番は青木さん、2番は石坂さん、3番は小野田さんの順に表示 } } }
package com.mta.vengage.leisuretime; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.ImageView; import android.widget.TextView; import com.mta.vengage.leisuretime.data.TablesContract; import com.squareup.picasso.Picasso; public class MovieDetailActivity extends ActionBarActivity implements LoaderManager.LoaderCallbacks<Cursor>{ private static final String LOG_TAG = MovieDetailActivity.class.getSimpleName(); private static final int DETAIL_LOADER = 0; private static final String[] PROGRAM_COLUMNS = { TablesContract.ProgramEntry.COLUMN_MOVIE_ID, TablesContract.ProgramEntry.COLUMN_HOUR }; private static final String[] MOVIES_COLUMNS = { TablesContract.MoviesEntry.COLUMN_MOVIE_ID, TablesContract.MoviesEntry.COLUMN_NAME, TablesContract.MoviesEntry.COLUMN_DURATION, TablesContract.MoviesEntry.COLUMN_GENRE, TablesContract.MoviesEntry.COLUMN_MIN_AGE, TablesContract.MoviesEntry.COLUMN_TYPE, TablesContract.MoviesEntry.COLUMN_POSTER, TablesContract.MoviesEntry.COLUMN_SYNOPSIS }; static final int COL_NAME = 1; static final int COL_DURATION = 2; static final int COL_GENRE = 3; static final int COL_MIN_AGE = 4; static final int COL_TYPE = 5; static final int COL_POSTER = 6; static final int COL_SYNOPSIS = 7; private static final int COL_MOVIE_ID = 0; private static final int COL_HOUR = 1; private TextView title; private TextView duration; private TextView genre; private TextView type; private TextView synopsis; private TextView min_age; private ImageView poster; private TextView programView; private String movie_id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_detail); getLoaderManager().initLoader(DETAIL_LOADER, null, this); title = (TextView) findViewById(R.id.title_movie); duration = (TextView) findViewById(R.id.duration); genre = (TextView) findViewById(R.id.genre); type = (TextView) findViewById(R.id.type); synopsis = (TextView) findViewById(R.id.synopsis); min_age = (TextView) findViewById(R.id.min_age); poster = (ImageView) findViewById(R.id.poster); programView = (TextView) findViewById(R.id.program); programView.setText(""); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { Intent intent = getIntent(); movie_id = intent.getExtras().getString("movie_id"); if(intent == null) return null; CursorLoader cursorLoader = new CursorLoader( getApplicationContext(), TablesContract.MoviesEntry.buildMoviesMovieUri(movie_id), MOVIES_COLUMNS, TablesContract.MoviesEntry.COLUMN_MOVIE_ID + "=?", new String[]{movie_id}, null ); return cursorLoader; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if(!data.moveToFirst()){return;} title.setText(data.getString(COL_NAME)); duration.setText(data.getString(COL_DURATION) + " min"); genre.setText(data.getString(COL_GENRE)); type.setText(data.getString(COL_TYPE)); min_age.setText(data.getString(COL_MIN_AGE) + " ani"); synopsis.setText(data.getString(COL_SYNOPSIS)); Picasso .with(getApplicationContext()) .load(data.getString(data.getColumnIndexOrThrow("poster"))) .resize(175,271) .into(poster); Cursor cursor = getContentResolver().query( TablesContract.ProgramEntry.buildMovieProgramUri(movie_id), PROGRAM_COLUMNS, "movie_id=?", new String[]{movie_id}, null); while(cursor.moveToNext()){ programView.append(cursor.getString(COL_HOUR) + " "); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } }
package edu.wayne.cs.severe.redress2.entity.refactoring.formulas.puf; import edu.wayne.cs.severe.redress2.controller.metric.LOCMetric; import edu.wayne.cs.severe.redress2.entity.TypeDeclaration; import edu.wayne.cs.severe.redress2.entity.refactoring.RefactoringOperation; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; public class LOCPullUpFieldPF extends PullUpFieldPredFormula { @Override public HashMap<String, Double> predictMetrVal(RefactoringOperation ref, LinkedHashMap<String, LinkedHashMap<String, Double>> prevMetrics) { List<TypeDeclaration> srcClses = getSourceClasses(ref); HashMap<String, Double> predMetrs = new HashMap<String, Double>(); for (TypeDeclaration cls : srcClses) { Double prevMetr = prevMetrics.get(cls.getQualifiedName()).get( getMetric().getMetricAcronym()); predMetrs.put(cls.getQualifiedName(), prevMetr - 1); } TypeDeclaration tgtCls = getTargetClass(ref); predMetrs.put( tgtCls.getQualifiedName(), prevMetrics.get(tgtCls.getQualifiedName()).get( getMetric().getMetricAcronym()) + 1); return predMetrs; } public LOCMetric getMetric() { return new LOCMetric(); } }
package server.models; import at.rennweg.htl.sew.autoconfig.UserInfo; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.Set; @Entity public class Person extends Persistent implements UserInfo { @Column(unique = true) private String username; private String displayName; @OneToMany(mappedBy = "person", fetch = FetchType.EAGER, cascade = CascadeType.MERGE) private Set<Qualifikation> qualifikationen; @NotNull private String role; @Transient private String password; @ManyToOne private Projekt projekt; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Projekt getProjekt() { return projekt; } @Override public String getDisplayName() { return displayName; } @Override public void setDisplayName(String displayName) { this.displayName = displayName; } public Set<Qualifikation> getQualifikationen() { return qualifikationen; } /** * Aktualisiert beide Seiten der @OneToMany-Beziehung. */ public void setProjekt(Projekt projekt) { this.projekt = setManyToOne(projekt, Projekt::getPersonas, Person::getProjekt); } /** * Aktualisiert beide Seiten der @OneToMany-Beziehung. */ public void setQualifikationen(Set<Qualifikation> qualifikationen) { this.qualifikationen = setOneToMany(qualifikationen, Qualifikation::setPerson, Person::getQualifikationen); } @Override public String getRole() { return role; } @Override public void setRole(String role) { this.role = role; } }
package br.inf.ufg.mddsm.broker.manager.actions; import java.util.Collection; import java.util.Map; import br.inf.ufg.mddsm.broker.expression.ContextProviderParams; import br.inf.ufg.mddsm.broker.expression.ValueEvaluator; import br.inf.ufg.mddsm.broker.manager.ManagerContext; public class SequenceActionInstance implements ActionInstance { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SequenceActionInstance.class); private Collection<ActionCaller> callers; public SequenceActionInstance(Collection<ActionCaller> callers) { log.trace("new SequenceActionInstance(callers:{})", callers); this.callers = callers; } public Object execute(ManagerContext ctx, Map<String, Object> params) { log.trace("execute(ctx:{}, params:{})", ctx, params); Object result = null; ValueEvaluator eval = ctx.getMainManager().getEvaluator(); for (ActionCaller caller : callers) { result = caller.execute(ctx, new ContextProviderParams(params), eval); } log.trace("execute() = {})", result); return result; } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.common.validator.impl; import de.hybris.platform.cmsfacades.common.validator.ValidationErrors; import de.hybris.platform.cmsfacades.common.validator.ValidationErrorsProvider; import de.hybris.platform.cmsfacades.constants.CmsfacadesConstants; import de.hybris.platform.cmsfacades.exception.ValidationException; import de.hybris.platform.servicelayer.session.SessionService; import java.util.Deque; import java.util.LinkedList; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Required; /** * Default implementation of {@link ValidationErrorsProvider}. * Stores the {@link ValidationErrors} instance on the current Session. */ public class DefaultValidationErrorsProvider implements ValidationErrorsProvider { private ObjectFactory<ValidationErrors> validationErrorsObjectFactory; private SessionService sessionService; private final ReentrantLock lock = new ReentrantLock(); @Override public ValidationErrors initializeValidationErrors() { final ValidationErrors validationErrors = getValidationErrorsObjectFactory().getObject(); lock.lock(); try { Object value = getSessionService().getAttribute(CmsfacadesConstants.SESSION_VALIDATION_ERRORS_OBJ); if (value == null) { final Deque<ValidationErrors> stack = new LinkedList<>(); value = new AtomicReference<>(stack); } else { final Deque<ValidationErrors> stack = getWrappedStack(value); if (stack.size() > 0) { validationErrors.pushField(stack.peek().parseFieldStack()); } } getWrappedStack(value).push(validationErrors); // Lists stored in the session service are serialized and modified. When they are retrieved, the result is a // Collections$UnmodifiableRandomAccessList. To prevent this from happening the collection is wrapped in the AtomicReference. getSessionService().setAttribute(CmsfacadesConstants.SESSION_VALIDATION_ERRORS_OBJ, value); } finally { lock.unlock(); } return validationErrors; } @Override public ValidationErrors getCurrentValidationErrors() { lock.lock(); try { final Object value = getSessionService().getAttribute(CmsfacadesConstants.SESSION_VALIDATION_ERRORS_OBJ); if (value == null) { throw new IllegalStateException("There is no current validation error context. Please Initialize with #initializeValidationErrors before using this method."); } else { return getWrappedStack(value).peek(); } } finally { lock.unlock(); } } @Override public void finalizeValidationErrors() { lock.lock(); try { final Object value = getSessionService().getAttribute(CmsfacadesConstants.SESSION_VALIDATION_ERRORS_OBJ); if (value == null) { throw new IllegalStateException("There is no current validation error context. Please Initialize with #initializeValidationErrors before using this method."); } else { getWrappedStack(value).pop(); } } finally { lock.unlock(); } } @Override public void collectValidationErrors(ValidationException e, Optional<String> language, Optional<Integer> position) { e.getValidationErrors().getValidationErrors().forEach(validationError -> { language.ifPresent(validationError::setLanguage); position.ifPresent(validationError::setPosition); this.getCurrentValidationErrors().add(validationError); }); } /** * Values stored in the session service must be wrapped in AtomicReference objects to protect them from being altered during serialization. When values are * read from the session service, they must be unwrapped. Thus, this method is used to retrieve the original value (stack) stored in the AtomicReference wrapper. * * @param rawValue Object retrieved from the session service. The object must be an AtomicReference. Otherwise, an IllegalStateException is thrown. * @return stack stored within the AtomicReference. */ protected Deque<ValidationErrors> getWrappedStack(Object rawValue) { if(rawValue instanceof AtomicReference) { final AtomicReference<Deque<ValidationErrors>> originalValue = (AtomicReference<Deque<ValidationErrors>>) rawValue; return originalValue.get(); } throw new IllegalStateException("Session object for SESSION_VALIDATION_ERRORS_OBJ should hold a reference of AtomicReference object."); } protected SessionService getSessionService() { return sessionService; } @Required public void setSessionService(final SessionService sessionService) { this.sessionService = sessionService; } protected ObjectFactory<ValidationErrors> getValidationErrorsObjectFactory() { return validationErrorsObjectFactory; } @Required public void setValidationErrorsObjectFactory(final ObjectFactory<ValidationErrors> validationErrorsObjectFactory) { this.validationErrorsObjectFactory = validationErrorsObjectFactory; } }
package com.wuyr.rippleanimationtest; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import com.wuyr.rippleanimation.RippleAnimation; /** * Created by wuyr on 3/15/18 5:21 PM. */ public class MainActivity extends AppCompatActivity { private View mLeftNavigationView, mRightNavigationView; private View[] mChildViews; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_main_view); initStatusBar(); mLeftNavigationView = findViewById(R.id.navigation_left); mRightNavigationView = findViewById(R.id.navigation_right); ViewGroup viewGroup = findViewById(R.id.root_view); mChildViews = new View[viewGroup.getChildCount()]; for (int i = 0; i < mChildViews.length; i++) { mChildViews[i] = viewGroup.getChildAt(i); } } public void onClick(View view) { //RippleAnimation.create(view).setDuration(200).start().setOnAnimationEndListener(); //关键代码 RippleAnimation.create(view).setDuration(250).start(); int color; switch (view.getId()) { case R.id.red: color = Color.RED; break; case R.id.green: color = Color.GREEN; break; case R.id.blue: color = Color.BLUE; break; case R.id.yellow: color = Color.YELLOW; break; case R.id.black: color = Color.DKGRAY; break; case R.id.cyan: color = Color.CYAN; break; default: color = Color.TRANSPARENT; break; } updateColor(color); } private void updateColor(int color) { mLeftNavigationView.setBackgroundColor(color); mRightNavigationView.setBackgroundColor(color); for (View view : mChildViews) { if (view instanceof TextView) { ((TextView) view).setTextColor(color); } else { view.setBackgroundColor(color); } } } private void initStatusBar() { Window window = getWindow(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(Color.TRANSPARENT); window.setNavigationBarColor(Color.TRANSPARENT); } } } }
package com.kute.webflux.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomUtils; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; import java.io.Serializable; import java.sql.Timestamp; /** * created by bailong001 on 2019/02/22 17:21 */ @Data @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor @Document(collection = "test") public class User implements Serializable { @Id private String id; private Long ucId; /** * 若mongo不存在此索引会自动创建 */ @Indexed(unique = true) private String name; private int age; /** * spring data mongo 会内置一个 org.bson.BsonTimestamp -> java.time.Instant 的converter, * 可以替换为 Instant就不必注册新的convert,这里为了演示 新添加 convert */ private Timestamp birthday; public static User randomUser(String id) { return new User(id, RandomUtils.nextLong(1L, 1000L), RandomStringUtils.random(11), RandomUtils.nextInt(10, 100), new Timestamp(System.currentTimeMillis())); } }
package org.team3128.compbot.autonomous; import edu.wpi.first.wpilibj.command.CommandGroup; import org.team3128.common.utility.math.Pose2D; import org.team3128.common.utility.math.Rotation2D; import org.team3128.common.drive.Drive; import org.team3128.common.hardware.limelight.Limelight; import org.team3128.common.drive.DriveCommandRunning; import org.team3128.compbot.autonomous.*; import org.team3128.compbot.commands.*; import org.team3128.compbot.subsystems.Constants.VisionConstants; import org.team3128.compbot.subsystems.*; import com.kauailabs.navx.frc.AHRS; public class AutoPriority extends CommandGroup { public AutoPriority(FalconDrive drive, Shooter shooter, Arm arm, Hopper hopper, AHRS ahrs, Limelight limelight, DriveCommandRunning cmdRunning, double timeoutMs) { addSequential(new CmdAlignShoot(drive, shooter, arm, hopper, ahrs, limelight, cmdRunning, Constants.VisionConstants.TX_OFFSET, 3)); addSequential(new CmdAutoTrajectory(drive, 120, 0.5, 10000, new Pose2D(0, 0, Rotation2D.fromDegrees(0)), new Pose2D(194 * Constants.MechanismConstants.inchesToMeters, 27 * Constants.MechanismConstants.inchesToMeters, Rotation2D.fromDegrees(180)))); // 194.63 inches length and 27.75 inches width // for (int i = 0; i < 3; i++) { // run three times because we are picking up three balls // addSequential(new CmdBallIntake(ahrs, limelight, hopper, arm, cmdRunning, Constants.VisionConstants.BALL_PID, Constants.VisionConstants.BLIND_BALL_PID, 0.472441 * Constants.MechanismConstants.inchesToMeters, Constants.VisionConstants.TX_OFFSET)); // } addSequential(new CmdAutoTrajectory(drive, 120, 0.5, 10000, new Pose2D(0, 0, Rotation2D.fromDegrees(0)), new Pose2D(0, 0, Rotation2D.fromDegrees(180)))); // TODO: check if this rotate in place addSequential(new CmdAlignShoot(drive, shooter, arm, hopper, ahrs, limelight, cmdRunning, Constants.VisionConstants.TX_OFFSET, 3)); } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ArbeitsvorgangKorrekturListeType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class ArbeitsvorgangKorrekturListeTypeBuilder { public static String marshal(ArbeitsvorgangKorrekturListeType arbeitsvorgangKorrekturListeType) throws JAXBException { JAXBElement<ArbeitsvorgangKorrekturListeType> jaxbElement = new JAXBElement<>(new QName("TESTING"), ArbeitsvorgangKorrekturListeType.class , arbeitsvorgangKorrekturListeType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } public ArbeitsvorgangKorrekturListeType build() { ArbeitsvorgangKorrekturListeType result = new ArbeitsvorgangKorrekturListeType(); return result; } }
package com.tencent.mm.g.a; public final class tc$a { public String ceD; }
package org.jcarvajal.webapp.server.impl; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.io.IOException; import org.junit.Before; import org.junit.Test; public class HttpServerFacadeTest { private static int PORT = 100; private HttpServerFacade serverFacade; private boolean actualStarted; @Before public void setup() throws IOException { HttpServerFacade realServerFacade = new HttpServerFacade(); serverFacade = spy(realServerFacade); doNothing().when(serverFacade).startInternal(anyInt()); } @Test public void start_whenNotStarted_thenServerStarts() throws IOException { whenStart(); thenIsStarted(); thenStartInternalInvoked(); } @Test public void start_whenExceptionAtStart_thenServerDidNotStart() throws IOException { givenExceptionAtStartServer(); whenStart(); thenIsNotStarted(); } private void givenExceptionAtStartServer() throws IOException { doThrow(new IOException()).when(serverFacade).startInternal(anyInt()); } private void whenStart() { actualStarted = serverFacade.start(PORT); } private void thenIsStarted() { assertTrue(actualStarted); } private void thenIsNotStarted() { assertFalse(actualStarted); } private void thenStartInternalInvoked() throws IOException { verify(serverFacade, times(1)).startInternal(PORT); } }
package com.mango.leo.zsproject.industrialservice.createrequirements.carditems.bean; import java.util.List; /** * Created by admin on 2018/5/16. */ public class CardNinthItemBean { private String moshi; private String money; private List<String> why; private List<String> type; private String qita; public CardNinthItemBean(String moshi, String money, List<String> why, List<String> type, String qita) { this.moshi = moshi; this.money = money; this.why = why; this.type = type; this.qita = qita; } public CardNinthItemBean() { } public String getMoshi() { return moshi; } public void setMoshi(String moshi) { this.moshi = moshi; } public String getMoney() { return money; } public void setMoney(String money) { this.money = money; } public List<String> getWhy() { return why; } public void setWhy(List<String> why) { this.why = why; } public List<String> getType() { return type; } public void setType(List<String> type) { this.type = type; } public String getQita() { return qita; } public void setQita(String qita) { this.qita = qita; } @Override public String toString() { return "CardNinthItemBean{" + "moshi='" + moshi + '\'' + ", money='" + money + '\'' + ", why=" + why + ", type=" + type + ", qita='" + qita + '\'' + '}'; } }
package wx.realware.grp.pt.pb.start.job; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import wx.realware.grp.pt.pb.respority.service.JobService; import java.io.Serializable; /** * 服务启动时,自动执行order执行顺序 * editby liufengqiang * time 20180901 */ @Component @Order(value = 1) public class StartJobService implements ApplicationRunner,Serializable { Logger logger = LoggerFactory.getLogger(StartJobService.class); @Autowired JobService jobService; @Override public void run(ApplicationArguments applicationArguments) throws Exception { /** * 启动自动任务 * */ logger.info("开始加载自动任务........"); jobService.start(); logger.info("完成加载自动任务........"); } }
package com.ibeiliao.pay.web.open.notify; import com.ibeiliao.pay.api.ApiResultBase; import com.ibeiliao.pay.api.dto.request.PaymentNotifyRequest; import com.ibeiliao.pay.api.dto.response.PaymentNotifyResponse; import com.ibeiliao.pay.api.provider.PaymentNotifyProvider; import com.ibeiliao.pay.common.utils.IpAddressUtils; import com.ibeiliao.pay.common.utils.JsonUtil; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.OutputStream; /** * 功能:处理金惠家的通知回调 * 详细:支付成功异步回调、绑卡回调 * * @author linyi 2016/8/17 */ @Controller @RequestMapping("/open/jhj") public class JhjNotifyController { private static final Logger logger = LoggerFactory.getLogger(JhjNotifyController.class); @Autowired private PaymentNotifyProvider paymentNotifyProvider; /** * 处理支付成功的异步通知。 * 如果成功,需要返回布尔值true;失败返回其他。 * * @param msg 金惠家返回的信息 * @param data 金惠家返回的数据 * @param request * @param response * @throws IOException */ @RequestMapping(value = "asyncNotify.do", method = RequestMethod.POST) public void asyncNotify(String msg, String data, HttpServletRequest request, HttpServletResponse response) throws IOException { String clientIp = IpAddressUtils.getClientIpAddr(request); logger.info("金惠家支付成功异步通知 | clientIp: {}, msg: {}, data: {}", clientIp, msg, data); String result = "false"; if (StringUtils.isNotBlank(data)) { try { PaymentNotifyRequest req = new PaymentNotifyRequest(data, null ,clientIp); PaymentNotifyResponse notifyResponse = paymentNotifyProvider.jhjAsyncNotify(req); logger.info("金惠家支付回调服务返回内容 | response: {}", JsonUtil.toJSONString(notifyResponse)); if (ApiResultBase.isSuccess(notifyResponse)) { result = "true"; } } catch (Exception e) { logger.error("出错", e); } } else { logger.error("data为空!"); } OutputStream out = response.getOutputStream(); out.write(result.getBytes()); out.flush(); out.close(); } /** * 处理绑卡成功的异步通知。 * 如果成功,需要返回布尔值true;失败返回其他。 * * @param msg 金惠家返回的信息 * @param data 金惠家返回的数据 * @param request * @param response * @throws IOException */ @RequestMapping(value = "bindCardNotify.do", method = RequestMethod.POST) public void bindCardNotify(String msg, String data, HttpServletRequest request, HttpServletResponse response) throws IOException { String clientIp = IpAddressUtils.getClientIpAddr(request); logger.info("金惠家绑卡成功异步通知 | clientIp: {}, msg: {}, data: {}", clientIp, msg, data); String result = "false"; if (StringUtils.isNotBlank(data)) { try { PaymentNotifyRequest req = new PaymentNotifyRequest(data, null, clientIp); PaymentNotifyResponse notifyResponse = paymentNotifyProvider.jhjContractNotify(req); logger.info("绑卡服务返回内容 | response: {}", JsonUtil.toJSONString(notifyResponse)); if (ApiResultBase.isSuccess(notifyResponse)) { result = "true"; } } catch (Exception e) { logger.error("出错", e); } } else { logger.error("data为空!"); } OutputStream out = response.getOutputStream(); out.write(result.getBytes()); out.flush(); out.close(); } /** * 功能:处理支付成功的同步通知 * 详细:这是一个HTTP GET 请求, * 成功处理后跳转到展示结果页面(HTML5)。 * 失败输出 ERROR 信息。 * * @param data 金惠家返回的数据,加密 * @param request * @param response */ @RequestMapping("syncNotify") public void syncNotify(String data, HttpServletRequest request, HttpServletResponse response) throws IOException { String clientIp = IpAddressUtils.getClientIpAddr(request); logger.info("金惠家支付成功同步通知 | clientIp: {}, data: {}", clientIp, data); if (StringUtils.isNotBlank(data)) { try { PaymentNotifyRequest req = new PaymentNotifyRequest(data, null, clientIp); PaymentNotifyResponse notifyResponse = paymentNotifyProvider.jhjSyncNotify(req); logger.info("金惠家支付回调服务返回内容 | response: {}", JsonUtil.toJSONString(notifyResponse)); if (ApiResultBase.isSuccess(notifyResponse)) { response.sendRedirect(notifyResponse.getResult()); return; } } catch (Exception e) { logger.error("出错", e); } } else { logger.error("数据为空!"); } // 错误,不跳转任何页面 OutputStream out = response.getOutputStream(); out.write("Error, Please contact administrator.".getBytes()); out.flush(); out.close(); } }
package clasearchivo; import java.util.Date; import java.util.GregorianCalendar; public class ClaseArchivo { //Atributos private String nombre; private String tipo; private Date fecha_creacion; private String contenido; //Constructor 1 public ClaseArchivo(String nombre, int año, int mes, int dia){ this.nombre=nombre; GregorianCalendar calendario = new GregorianCalendar (año, mes-1, dia); fecha_creacion=calendario.getTime(); } //Constructor 2 public ClaseArchivo(String nombre, String tipo, int año, int mes, int dia){ this.nombre=nombre; this.tipo=tipo; GregorianCalendar calendario = new GregorianCalendar (año, mes-1, dia); fecha_creacion=calendario.getTime(); } //Constructor 3 public ClaseArchivo(String nombre, String tipo, int año, int mes, int dia, String contenido){ this.nombre=nombre; this.tipo=tipo; GregorianCalendar calendario = new GregorianCalendar (año, mes-1, dia); fecha_creacion=calendario.getTime(); this.contenido=contenido; } public String getNombre(){ return "El nombre del archivo es: "+nombre; } public String getTipo(){ return "El tipo de archivo es: "+tipo; } public String getFechaCreacion(){ return "La fecha de creacion del archivo es: "+fecha_creacion; } public void setContenido(String contenido){ this.contenido=contenido; } public String getContenido(){ return "El contenido es: "+contenido; } public static void main(String[] args) { ClaseArchivo objeto1 = new ClaseArchivo("Deber",2018,05,07); System.out.println("\tBienvenido a mi Programa\n"); System.out.println(" Objeto 1\n"); System.out.println(objeto1.getNombre()); System.out.println(objeto1.getFechaCreacion()); ClaseArchivo objeto2 = new ClaseArchivo("Proyecto",".pdf",2018,02,25); System.out.println("\n Objeto 2\n"); System.out.println(objeto2.getNombre()); System.out.println(objeto2.getTipo()); System.out.println(objeto2.getFechaCreacion()); ClaseArchivo objeto3 = new ClaseArchivo("Programa",".java",2018,05,07,"Vacio"); System.out.println("\n Objeto 3\n"); objeto3.setContenido("Hola mundo"); System.out.println(objeto3.getNombre()); System.out.println(objeto3.getTipo()); System.out.println(objeto3.getContenido()); } }
package com.sunteam.library.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import org.wlf.filedownloader.DownloadFileInfo; import org.wlf.filedownloader.FileDownloader; import org.wlf.filedownloader.listener.OnDeleteDownloadFilesListener; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.text.TextUtils; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.TextView; import com.sunteam.common.tts.TtsUtils; import com.sunteam.common.utils.PromptDialog; import com.sunteam.common.utils.dialog.PromptListener; import com.sunteam.dict.utils.DBUtil; import com.sunteam.jni.SunteamJni; import com.sunteam.library.R; import com.sunteam.library.activity.WordSearchResultActivity; import com.sunteam.library.db.DownloadChapterDBDao; import com.sunteam.library.db.DownloadResourceDBDao; import com.sunteam.library.entity.DownloadChapterEntity; import com.sunteam.library.entity.DownloadResourceEntity; /** * 可重用的方法工具类。 * * @author wzp */ public class PublicUtils { private static ProgressDialog progress; private static int mColorSchemeIndex = 0; //配色方案索引 //从系统配置文件中得到配色方案索引 public static int getSysColorSchemeIndex() { return (int)(System.currentTimeMillis()%7); } //设置配色方案 public static void setColorSchemeIndex( int index ) { mColorSchemeIndex = index; } //得到配色方案 public static int getColorSchemeIndex() { return mColorSchemeIndex; } //dip转px public static int dip2px( Context context, float dipValue ) { final float scale = context.getResources().getDisplayMetrics().density; return (int)(dipValue * scale + 0.5f); } //px转dip public static int px2dip( Context context, float pxValue ) { final float scale = context.getResources().getDisplayMetrics().density; return (int)(pxValue / scale + 0.5f); } //byte转char public static char byte2char( byte[] buffer, int offset ) { if( buffer[offset] >= 0 ) { return (char)buffer[offset]; } int hi = (int)(256+buffer[offset]); int li = (int)(256+buffer[offset+1]); return (char)((hi<<8)+li); } //byte转int public static int byte2int( byte[] buffer, int offset ) { int[] temp = new int[4]; for( int i = offset, j = 0; i < offset+4; i++, j++ ) { if( buffer[i] < 0 ) { temp[j] = 256+buffer[i]; } else { temp[j] = buffer[i]; } } int result = 0; for( int i = 0; i < 4; i++ ) { result += (temp[i]<<(8*(i))); } return result; } /** * 加载提示 * * @param context */ public static void showProgress(final Context context, String info, final AsyncTask<?, ?, ?> asyncTask) { cancelProgress(); progress = new ProgressDialog(context, R.style.progress_dialog); progress.setIndeterminate(false); progress.setCancelable(true); progress.setCanceledOnTouchOutside(false); progress.show(); progress.setContentView(R.layout.progress_layout); TextView tvInfo = (TextView) progress.findViewById(R.id.tv_info); tvInfo.setText(info); TTSUtils.getInstance().speakMenu(info); progress.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO Auto-generated method stub asyncTask.cancel(true); PublicUtils.showToast( context, context.getString(R.string.library_cancel_loading) ); //执行异步线程取消操作   } }); } /** * 加载提示 * * @param context */ public static void showProgress(final Context context, final AsyncTask<?, ?, ?> asyncTask) { cancelProgress(); progress = new ProgressDialog(context, R.style.progress_dialog); progress.setIndeterminate(false); progress.setCancelable(true); progress.setCanceledOnTouchOutside(false); progress.show(); progress.setContentView(R.layout.progress_layout); progress.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // TODO Auto-generated method stub asyncTask.cancel(true); PublicUtils.showToast( context, context.getString(R.string.library_cancel_loading) ); //执行异步线程取消操作   } }); } public static void cancelProgress() { if (null != progress) { if (progress.isShowing()) { progress.dismiss(); } progress = null; } } //显示提示信息并朗读(不需要接收TTS结束回调) public static void showToast( final Context context, String tips,final boolean isFinish ) { //用后鼎提供的系统提示对话框 TTSUtils.getInstance().stop(); PromptDialog pd = new PromptDialog(context, tips); pd.setPromptListener( new PromptListener() { public void onComplete() { ((Activity)context).finish(); } }); pd.show(); } //显示提示信息并朗读(不需要接收TTS结束回调) public static void showToast( Context context, String tips ) { /* TTSUtils.getInstance().speakMenu(tips, listener); CustomToast.showToast(context, tips, Toast.LENGTH_SHORT); */ TTSUtils.getInstance().stop(); //用后鼎提供的系统提示对话框 PromptDialog pd = new PromptDialog(context, tips); pd.setPromptListener( new PromptListener() { public void onComplete() { } }); pd.show(); } //显示提示信息并朗读(需要接收TTS结束回调) public static void showToast( Context context, String tips, PromptListener listener ) { showToast(context, tips, listener, TtsUtils.TTS_QUEUE_FLUSH); } // 显示提示信息并朗读(需要接收TTS结束回调) public static void showToast(Context context, String tips, PromptListener listener, int mode) { PromptDialog pd = new PromptDialog(context, tips); if (null != listener) { pd.setPromptListener(listener); } pd.setTtsMode(mode); pd.show(); } // 显示提示信息并朗读(不需要接收TTS结束回调), 以追加方式朗读 public static void showToast(Context context, String tips, int mode) { showToast(context, tips, null, mode); } //检查讯飞语音服务是否安装 public static boolean checkSpeechServiceInstalled(Context context) { return true; //SpeechUtility.getUtility().checkServiceInstalled(); } //跳到反查 public static void jumpFanCha(final Context context, final String content) { if( TextUtils.isEmpty(content) ) { PublicUtils.showToast( context, context.getString(R.string.library_search_fail) ); } else { DBUtil dbUtils = new DBUtil(); final String result = dbUtils.search(content); if( TextUtils.isEmpty(result) ) { PublicUtils.showToast( context, context.getString(R.string.library_search_fail) ); } else { TTSUtils.getInstance().stop(); TTSUtils.getInstance().OnTTSListener(null); PublicUtils.showToast( context, context.getString(R.string.library_dict_search_success), new PromptListener() { @Override public void onComplete() { // TODO Auto-generated method stub Intent intent = new Intent( context, WordSearchResultActivity.class ); intent.putExtra("word", content); intent.putExtra("explain", result); context.startActivity(intent); } }); } } } //判断一个文件是否为纯文本文件 public static boolean checkIsTextFile(byte[] buffer) { boolean isTextFile = true; try { int i = 0; int length = (int)buffer.length; byte data; while (i < length && isTextFile) { data = (byte)buffer[i]; isTextFile = (data != 0); i++; } return isTextFile; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 方法(创建缓存目录) * * @param parentPath * 父路径 * @param dirName * 目录名 * @return * @author wzp * @Created 2017/01/29 */ public static String createCacheDir( String parentPath, String dirName ) { String dirPath = parentPath+dirName+"/"; try { File f = new File(dirPath); if( !f.exists() ) { f.mkdirs(); } } catch( Exception e ) { e.printStackTrace(); } return dirPath; } /** * 方法(加载下载Content) * * @param filepath * 文件路径 * @param filaname * 文件名 * @return * @author wzp * @Created 2017/01/31 */ public static String readDownloadContent( String filepath, String filename ) { try { File file = new File(filepath+filename); if( file.exists() ) { int len = (int) file.length(); byte[] buffer = new byte[len]; FileInputStream inStream = new FileInputStream(file); inStream.read(buffer); inStream.close(); return new String(buffer); } } catch( Exception e ) { e.printStackTrace(); } return ""; } /** * 方法(加载Content) * * @param filepath * 文件路径 * @param filaname * 文件名 * @return * @author wzp * @Created 2017/01/31 */ public static String readContent( String filepath, String filename ) { try { File file = new File(filepath+filename); if( file.exists() ) { SunteamJni mSunteamJni = new SunteamJni(); mSunteamJni.decryptFile(filepath+filename); //解密文件 int len = (int) file.length(); byte[] buffer = new byte[len-LibraryConstant.ENCRYPT_FLAGS_LENGTH]; FileInputStream inStream = new FileInputStream(file); inStream.read(buffer); inStream.close(); return new String(buffer); } } catch( Exception e ) { e.printStackTrace(); } return ""; } /** * 方法(保存Content) * * @param filepath * 文件路径 * @param filaname * 文件名 * @param content * 文件内容 * @return * @author wzp * @Created 2017/01/29 */ public static void saveContent( String filepath, String filename, String content ) { if( !TextUtils.isEmpty(content) ) { try { File f = new File(filepath); if( !f.exists() ) { f.mkdirs(); } File file = new File(filepath+filename); if( !file.exists() ) { byte[] flags = new byte[LibraryConstant.ENCRYPT_FLAGS_LENGTH]; FileOutputStream outStream = new FileOutputStream(file); outStream.write(content.getBytes("GB18030")); outStream.write(flags); //加密标记 outStream.close(); SunteamJni mSunteamJni = new SunteamJni(); mSunteamJni.encryptFile(filepath+filename); //加密文件 } } catch( Exception e ) { e.printStackTrace(); } } } //加密文件 public static void encryptFile( String fullpath ) { try { File file = new File(fullpath); if( file.exists() ) { byte[] flags = new byte[LibraryConstant.ENCRYPT_FLAGS_LENGTH]; // 打开一个随机访问文件流,按读写方式 RandomAccessFile randomFile = new RandomAccessFile(fullpath, "rw"); // 文件长度,字节数 long fileLength = randomFile.length(); // 将写文件指针移到文件尾。 randomFile.seek(fileLength); randomFile.write(flags); //加密标记 randomFile.close(); SunteamJni mSunteamJni = new SunteamJni(); mSunteamJni.encryptFile(fullpath); //加密文件 } } catch( Exception e ) { e.printStackTrace(); } } //去掉一个字符串中的标点符号 public static String format(String s) { String str = s.replaceAll("[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……& amp;*()——+|{}【】‘;:”“’。,、?|-]", ""); return str.replaceAll("//", ""); } /** * 方法(解析Html) * * @param html * @return * @author wzp * @Created 2017/01/29 */ public static String parseHtml( String html ) { if( TextUtils.isEmpty(html) ) { return ""; } String txtcontent = html.replaceAll("</?[^>]+>", ""); //剔出<html>的标签 txtcontent = txtcontent.replaceAll("&nbsp;", ""); //替换空格 txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", ""); //去除字符串中的空格,回车,换行符,制表符 return txtcontent; } //删除目录 public static void deleteFiles(File file) { if( file.exists() == false ) { return; } if( file.isFile() && !file.getName().contains(".temp") ) { file.delete(); return; } if( file.isDirectory() ) { File[] childFiles = file.listFiles(); if( childFiles == null || childFiles.length == 0 ) { //file.delete(); //不删除目录了 return; } for( int i = 0; i < childFiles.length; i++ ) { deleteFiles(childFiles[i]); } //file.delete(); //不删除目录了 } } //得到用户名 public static String getUserName( Context context ) { SharedPreferences spf = context.getSharedPreferences(LibraryConstant.USER_INFO, Activity.MODE_PRIVATE); return spf.getString(LibraryConstant.USER_NAME, ""); } //得到分类名称 public static String getCategoryName( Context context, int type ) { String[] list = context.getResources().getStringArray(R.array.library_category_list); return list[type]; } //得到子分类名称 public static String getSubCategoryName( String categoryFullName ) { String[] str = categoryFullName.split("-"); return str[1]; } //得到网络是否连接 public static boolean isNetworkConnect() { try { Process p = Runtime.getRuntime().exec( "ping -c 1 -w 5 www.baidu.com"); int status = p.waitFor(); if (status == 0) { return true; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch( InterruptedException e ) { e.printStackTrace(); } return false; } //保存用户信息 public static void saveUserInfo( Context context, String username, String password ) { SharedPreferences spf = context.getSharedPreferences(LibraryConstant.USER_INFO, Activity.MODE_PRIVATE); Editor editor = spf.edit(); editor.putString( LibraryConstant.USER_NAME, username ); editor.putString( LibraryConstant.USER_PASSWORD, password ); editor.commit(); } // 隐藏输入法 public static void hideMsgIputKeyboard(Activity activity) { if (activity.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) { if (activity.getCurrentFocus() != null) { InputMethodManager inputKeyBoard = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); inputKeyBoard.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } } //删除下载任务 public static void deleteDownloadTask( final Context context, final DownloadResourceEntity entity ) { DownloadChapterDBDao dcDao = new DownloadChapterDBDao( context ); ArrayList<DownloadChapterEntity> list = dcDao.findAll(entity._id); //得到所有的章节信息 dcDao.closeDb(); if( list != null ) { ArrayList<String> urls = new ArrayList<String>(); int size = list.size(); for( int i = 0; i < size; i++ ) { urls.add(list.get(i).chapterUrl); } if( urls.size() > 0 ) { //删除所有的章节任务,不论下载状态 FileDownloader.delete(urls, false, new OnDeleteDownloadFilesListener() { @Override public void onDeleteDownloadFilesCompleted( List<DownloadFileInfo> arg0, List<DownloadFileInfo> arg1) { // TODO Auto-generated method stub DownloadChapterDBDao dcDao = new DownloadChapterDBDao( context ); dcDao.deleteAll(entity._id); dcDao.closeDb(); DownloadResourceDBDao drDao = new DownloadResourceDBDao( context ); drDao.delete(entity); drDao.closeDb(); } @Override public void onDeleteDownloadFilesPrepared( List<DownloadFileInfo> arg0) { // TODO Auto-generated method stub } @Override public void onDeletingDownloadFiles( List<DownloadFileInfo> arg0, List<DownloadFileInfo> arg1, List<DownloadFileInfo> arg2, DownloadFileInfo arg3) { // TODO Auto-generated method stub } }); } else { DownloadResourceDBDao drDao = new DownloadResourceDBDao( context ); drDao.delete(entity); drDao.closeDb(); } } else { DownloadResourceDBDao drDao = new DownloadResourceDBDao( context ); drDao.delete(entity); drDao.closeDb(); } } //清空下载任务 public static void clearDownloadTask( final Context context, final boolean isFinished ) { final String userName = PublicUtils.getUserName(context); DownloadResourceDBDao drDao = new DownloadResourceDBDao( context ); ArrayList<DownloadResourceEntity> allResourceList = null; if( isFinished ) //删除已完成任务 { allResourceList = drDao.findAllCompleted(userName); } else //删除未完成任务 { allResourceList = drDao.findAllUnCompleted(userName); } //得到所有的资源信息 drDao.closeDb(); if( ( null == allResourceList ) || ( 0 == allResourceList.size() ) ) { return; } DownloadChapterDBDao dcDao = new DownloadChapterDBDao( context ); final ArrayList<DownloadChapterEntity> allChapterList = new ArrayList<DownloadChapterEntity>(); //所有章节信息 int size = allResourceList.size(); for( int i = 0; i < size; i++ ) { ArrayList<DownloadChapterEntity> chapterList = dcDao.findAll(allResourceList.get(i)._id); //得到所有的章节信息 if( ( chapterList != null ) && ( chapterList.size() > 0 ) ) { allChapterList.addAll(chapterList); } } dcDao.closeDb(); ArrayList<String> urls = new ArrayList<String>(); size = allChapterList.size(); for( int i = 0; i < size; i++ ) { urls.add(allChapterList.get(i).chapterUrl); } if( urls.size() > 0 ) { //删除所有的章节任务,不论下载状态 FileDownloader.delete(urls, false, new OnDeleteDownloadFilesListener() { @Override public void onDeleteDownloadFilesCompleted( List<DownloadFileInfo> arg0, List<DownloadFileInfo> arg1) { // TODO Auto-generated method stub DownloadChapterDBDao dcDao = new DownloadChapterDBDao( context ); int size = allChapterList.size(); for( int i = 0; i < size; i++ ) { dcDao.deleteAll(allChapterList.get(i).recorcdId); } dcDao.closeDb(); DownloadResourceDBDao drDao = new DownloadResourceDBDao( context ); if( isFinished ) //删除已完成任务 { drDao.deleteAllCompleted(userName); } else //删除未完成任务 { drDao.deleteAllUnCompleted(userName); } //得到所有的资源信息 drDao.closeDb(); } @Override public void onDeleteDownloadFilesPrepared( List<DownloadFileInfo> arg0) { // TODO Auto-generated method stub } @Override public void onDeletingDownloadFiles( List<DownloadFileInfo> arg0, List<DownloadFileInfo> arg1, List<DownloadFileInfo> arg2, DownloadFileInfo arg3) { // TODO Auto-generated method stub } }); } else { drDao = new DownloadResourceDBDao( context ); if( isFinished ) //删除已完成任务 { drDao.deleteAllCompleted(userName); } else //删除未完成任务 { drDao.deleteAllUnCompleted(userName); } //得到所有的资源信息 drDao.closeDb(); } } //检测下载文件是否加密,没有加密的需要先加密 public static void checkEncryptFile( File file ) { if( file.exists() == false ) { return; } if( file.isFile() ) { if( file.getName().contains(".temp") ) //如果是临时下载文件 { return; } String fullpath = file.getPath(); //需要判断此文件是否加密,如果没有加密,这需要加密 SunteamJni mSunteamJni = new SunteamJni(); int state = mSunteamJni.getFileEncryptedState(fullpath); //0 原始数据;1加密数据;2数据损坏,表示状态无法确定 if( state != 1 ) { mSunteamJni.encryptFile(fullpath); } } if( file.isDirectory() ) { File[] childFiles = file.listFiles(); if( childFiles == null || childFiles.length == 0 ) { return; } for( int i = 0; i < childFiles.length; i++ ) { checkEncryptFile(childFiles[i]); } } } /** * 执行shell命令 * * @param cmd */ public static void execShellCmd(String cmd) { try { Runtime.getRuntime().exec( cmd ); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.nazmul.dp.designpattern.prototype; public class AppDemoShape { public static void main(String[] args) { ShapeCache.loadData(); Shape newShape = (Shape)ShapeCache.getShape("1"); newShape.draw(); Shape newShape2 = (Shape)ShapeCache.getShape("2"); newShape2.draw(); } }
package com.guevara.crud.conf; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger.web.ApiKeyVehicle; import springfox.documentation.swagger.web.SecurityConfiguration; import springfox.documentation.swagger2.annotations.EnableSwagger2; import static springfox.documentation.builders.PathSelectors.regex; @Configuration @EnableSwagger2 @PropertySource("classpath:swagger.properties") public class SwaggerConfiguration { @Autowired private Environment env; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .enable(true) //colocar FALSE si no se quiere mostrar el API Swagger .select() .apis(RequestHandlerSelectors.basePackage("com.guevara")) .paths(regex(env.getProperty("swagger.path.regex"))) .build(); } @Bean public SecurityConfiguration securityInfo() { return new SecurityConfiguration("client", "secret", "realm", "api", "api_key", ApiKeyVehicle.HEADER, "api-key", ","); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title(env.getProperty("swagger.api.title")) .description(env.getProperty("swagger.api.description")) .termsOfServiceUrl(env.getProperty("swagger.api.termsOfServiceUrl")) .license(env.getProperty("swagger.api.licence")) .licenseUrl(env.getProperty("swagger.api.licence.url")) .version(env.getProperty("swagger.api.version")) .build(); } }
package api.longpoll.bots.model.objects.additional.buttons; import com.google.gson.JsonElement; import com.google.gson.annotations.SerializedName; /** * A button to open VK App. */ public class VKAppsButton extends Button { public VKAppsButton(Action action) { super(action); } /** * Describes action for button type of VK Apps. */ public static class Action extends Button.Action { /** * ID of the launched VK Apps application. */ @SerializedName("app_id") private int appId; /** * ID of the community in which the app is installed, if it needs to be opened in that community context. */ @SerializedName("owner_id") private int ownerId; /** * The name of the app, specified on the button. */ @SerializedName("label") private String label; /** * Hash for navigation inside the app; is sent inside the launch parameters string after the # symbol. */ @SerializedName("hash") private String hash; public Action(int appId, int ownerId, String label, String hash) { this(appId, ownerId, label, hash, null); } public Action(int appId, int ownerId, String label, String hash, JsonElement payload) { super("open_app", payload); this.appId = appId; this.ownerId = ownerId; this.label = label; this.hash = hash; } public int getAppId() { return appId; } public void setAppId(int appId) { this.appId = appId; } public int getOwnerId() { return ownerId; } public void setOwnerId(int ownerId) { this.ownerId = ownerId; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getHash() { return hash; } public void setHash(String hash) { this.hash = hash; } @Override public String toString() { return "Action{" + "appId=" + appId + ", ownerId=" + ownerId + ", label='" + label + '\'' + ", hash='" + hash + '\'' + "} " + super.toString(); } } }
package com.lanltn.homestay.modules.tabbar; import android.content.Context; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.lanltn.homestay.R; public class CustomTab extends TabLayout { public static final int TAB_HOME = 0; public static final int TAB_LINEUP = 1; public static final int TAB_TIMETABLE = 2; public static final int TAB_MAP = 3; public static final int TAB_SNS = 4; private Context mContext; public CustomTab(Context context) { super(context); this.mContext = context; } public CustomTab(Context context, AttributeSet attrs) { super(context, attrs); this.mContext = context; } public CustomTab(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.mContext = context; } @Override public void setupWithViewPager(@Nullable ViewPager viewPager) { super.setupWithViewPager(viewPager); if (viewPager.getAdapter() == null) { return; } setupTab(); } private void setupTab() { // setTabGravity(TabLayout.GRAVITY_CENTER); //this.setSelectedTabIndicatorHeight(0); this.setSelectedTabIndicatorColor(mContext.getResources().getColor(android.R.color.transparent)); this.addOnTabSelectedListener(new OnTabSelectedListener() { @Override public void onTabSelected(Tab tab) { ((TextView) tab.getCustomView().findViewById(R.id.item_tabbar_text)) .setTextColor(mContext.getResources().getColor(R.color.main_tab_text_active)); switch (tab.getPosition()) { case TAB_HOME: ((ImageView) tab.getCustomView().findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_discover); break; case TAB_LINEUP: ((ImageView) tab.getCustomView().findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_map); break; case TAB_TIMETABLE: ((ImageView) tab.getCustomView().findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_favorite); break; case TAB_MAP: ((ImageView) tab.getCustomView().findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_notification); break; case TAB_SNS: ((ImageView) tab.getCustomView().findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_profile); break; } } @Override public void onTabUnselected(Tab tab) { ((TextView) tab.getCustomView().findViewById(R.id.item_tabbar_text)) .setTextColor(mContext.getResources().getColor(R.color.main_tab_text_inactive)); switch (tab.getPosition()) { case 0: ((ImageView) tab.getCustomView().findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_discover); break; case 1: ((ImageView) tab.getCustomView().findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_map); break; case 2: ((ImageView) tab.getCustomView().findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_favorite); break; case 3: ((ImageView) tab.getCustomView().findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_notification); break; case 4: ((ImageView) tab.getCustomView().findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_profile); break; } } @Override public void onTabReselected(Tab tab) { } }); RelativeLayout tabHome = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.item_tabbar, null); ((TextView) tabHome.findViewById(R.id.item_tabbar_text)) .setText(mContext.getText(R.string.main_tab_discover)); ((TextView) tabHome.findViewById(R.id.item_tabbar_text)) .setTextColor(mContext.getResources().getColor(R.color.main_tab_text_active)); ((ImageView) tabHome.findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_discover); this.getTabAt(0).setCustomView(tabHome); RelativeLayout tabLineup = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.item_tabbar, null); ((TextView) tabLineup.findViewById(R.id.item_tabbar_text)) .setText(mContext.getText(R.string.main_tab_map)); ((TextView) tabLineup.findViewById(R.id.item_tabbar_text)) .setTextColor(mContext.getResources().getColor(R.color.main_tab_text_inactive)); ((ImageView) tabLineup.findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_map); this.getTabAt(1).setCustomView(tabLineup); RelativeLayout tabTimeTable = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.item_tabbar, null); ((TextView) tabTimeTable.findViewById(R.id.item_tabbar_text)) .setText(mContext.getText(R.string.main_tab_favorite)); ((TextView) tabTimeTable.findViewById(R.id.item_tabbar_text)) .setTextColor(mContext.getResources().getColor(R.color.main_tab_text_inactive)); ((ImageView) tabTimeTable.findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_favorite); this.getTabAt(2).setCustomView(tabTimeTable); RelativeLayout tabMapArea = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.item_tabbar, null); ((TextView) tabMapArea.findViewById(R.id.item_tabbar_text)) .setText(mContext.getText(R.string.main_tab_notification)); ((TextView) tabMapArea.findViewById(R.id.item_tabbar_text)) .setTextColor(mContext.getResources().getColor(R.color.main_tab_text_inactive)); ((ImageView) tabMapArea.findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_notification); this.getTabAt(3).setCustomView(tabMapArea); RelativeLayout tabSNS = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.item_tabbar, null); ((TextView) tabSNS.findViewById(R.id.item_tabbar_text)) .setText(mContext.getText(R.string.main_tab_profile)); ((TextView) tabSNS.findViewById(R.id.item_tabbar_text)) .setTextColor(mContext.getResources().getColor(R.color.main_tab_text_inactive)); ((ImageView) tabSNS.findViewById(R.id.item_tabbar_icon)) .setImageResource(R.drawable.ic_profile); this.getTabAt(4).setCustomView(tabSNS); } }
package com.cimcssc.chaojilanling.entity.user; /** * Created by cimcssc on 2017/2/15. */ public class SendSMSResultVo { private boolean result; private String message; public SendSMSResultVo(){ } public SendSMSResultVo(boolean result, String message) { this.result = result; this.message = message; } public boolean isResult() { return result; } public void setResult(boolean result) { this.result = result; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
package nelsys.modelo; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Funcao { @Id private String idfuncao; private String cdchamada; private String nmfuncao; private String tpfuncao; private String cdclassificacao; public void setCdclassificacao(String cdclassificacao) { this.cdclassificacao = cdclassificacao; } public String getCdclassificacao() { return cdclassificacao; } public String getIdfuncao() { return idfuncao; } public void setIdfuncao(String idfuncao) { this.idfuncao = idfuncao; } public String getCdchamada() { return cdchamada; } public void setCdchamada(String cdchamada) { this.cdchamada = cdchamada; } public String getNmfuncao() { return nmfuncao; } public void setNmfuncao(String nmfuncao) { this.nmfuncao = nmfuncao; } public String getTpfuncao() { return tpfuncao; } public void setTpfuncao(String tpfuncao) { this.tpfuncao = tpfuncao; } }
package com.karlnosworthy.examples.daggerv1.activity; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; import com.karlnosworthy.examples.daggerv1.ApplicationImpl; import com.karlnosworthy.examples.daggerv1.R; import com.karlnosworthy.examples.daggerv1.reporting.ActivityEntryReporter; import javax.inject.Inject; public class OtherActivity extends Activity { @Inject ActivityEntryReporter activityEntryReporter; private TextView entryCountTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_other); // Inject our required instances from the centralised Dagger // object graph ApplicationImpl.using(this).inject(this); // now that we've had our instances injected, we can use them activityEntryReporter.reportActivityEntry(this); // Never do this, use ButterKnife! but for the purposes of keeping this // example simple.. entryCountTextView = (TextView) findViewById(R.id.other_entry_count_text_view); } @Override protected void onResume() { super.onResume(); int entryCount = activityEntryReporter.getEntryCount(this); String entryCountText = getResources().getQuantityString(R.plurals.other_activity_has_been_entered, entryCount, entryCount); entryCountTextView.setText(entryCountText); } }
package ctci.LinkedList; import java.util.HashSet; /** * Created by joetomjob on 7/15/17. */ public class removeDuplicate { public void removeDuplicate(List newList) { HashSet<Integer> h = new HashSet<>(); Node n = newList.head; Node prev = n; while (n != null) { if (h.contains(n.a)) { prev.next = n.next; } h.add(n.a); prev = n; n = n.next; } } public static void main(String[] args) { Node a = new Node(1); Node b = new Node(2); Node c = new Node(2); Node d = new Node(4); Node e = new Node(5); Node f = new Node(1); Node g = new Node(7); Node h = new Node(8); Node i = new Node(9); List newList = new List(); newList.addFirst(a); newList.addFirst(b); newList.addFirst(c); newList.addLast(d); newList.addLast(e); newList.insert(f, 2); newList.printList(); System.out.print('\n'); removeDuplicate r = new removeDuplicate(); r.removeDuplicate(newList); newList.printList(); } }