branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep><?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use AppBundle\Entity\Advert; class DefaultController extends Controller { public function indexAction(Request $request) { return $this->render('default/index.html.twig', [ 'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR, ]); } public function viewAction() { $stop = true; $advert = new Advert; $advert->setContent("Recherche développeur Symfony3."); $advert->setTitle("Developpeur Symfony"); $advert->setAuthor("Brice"); $advert->setPublished(true); $em = $this->getDoctrine()->getManager(); $advertRepository = $em->getRepository('AppBundle:Advert'); if($stop){ $em->persist($advert); $em->flush(); } return $this->render('default/view.html.twig', array( 'advert' => $advert )); } } <file_sep><?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use AppBundle\Entity\Advert; class AdvertController extends Controller { public function setAdvertAction() { $advert = new Advert(); $advert->setTitle('Recherche développeur Symfony.'); $advert->setAuthor('Alexandre'); $advert->setContent("Nous recherchons un développeur Symfony débutant sur Lyon. Blabla…"); $em = $this->getDoctrine()->getManager(); $em->persist($advert); $em->flush(); return $this->render('default/advert.html.twig', array('advert' => $advert)); } public function getAdvertAction() { $repository = $this->getDoctrine() ->getManager() ->getRepository('AppBundle:Advert'); $advert = $repository->find(5); if($advert === null) { throw new NotFoundHttpException("L'annonce d'id 5 n'existe pas."); } return $this->render('default/advert.html.twig', array('advert' => $advert)); } } <file_sep>my_project_name =============== A Symfony project created on November 11, 2018, 6:35 pm.
f6e63311f7e5ef0c51c8b24cdf766329b0e149dd
[ "Markdown", "PHP" ]
3
PHP
Burdy777/symfony-
86558caf19ab662917686021d73712842173378d
07db272c03943b65558c18509548cf1e4c9f30aa
refs/heads/main
<file_sep>import { Route, Switch } from 'react-router-dom'; import Account from './pages/Account'; import AuthRoute from './pages/AuthRoute'; import ForgotPassword from './pages/ForgotPassword'; import Home from './pages/Home'; import Invite from './pages/Invite'; import Landing from './pages/Landing'; import Login from './pages/Login'; import Register from './pages/Register'; import ResetPassword from './pages/ResetPassword'; import ViewGuild from './pages/ViewGuild'; export default function App() { return ( <Switch> <Route exact component={Landing} path="/" /> <Route component={Login} path="/login" /> <Route component={Register} path="/register" /> <Route component={ForgotPassword} path="/forgot-password" /> <Route component={ResetPassword} path="/reset-password/:token" /> <AuthRoute exact path="/channels/me" component={Home} /> <AuthRoute exact path="/channels/me/:channelId" component={Home} /> <AuthRoute exact path="/channels/:guildId/:channelId" component={ViewGuild} /> <AuthRoute exact path="/account" component={Account} /> <AuthRoute exact path="/:link" component={Invite} /> </Switch> ); } <file_sep>export const fake_user = { email: '<EMAIL>', username: 'UniQue', image: 'https://png.pngtree.com/png-clipart/20190516/original/pngtree-users-vector-icon-png-image_3725294.jpg', id: '7898780055454559745100', }; export const fake_pending = [ { id: 1, type: 2 }, { id: 2, type: 1 }, ]; export const fake_friends = [ { id: 1, username: 'ahmad' }, { id: 2, username: 'asghar', isOnline: true }, ]; export const fake_dms = [ { id: 1, user: { id: 1, username: 'ahmad', }, }, { id: 2, user: { id: 3, username: 'asghar', isOnline: true, }, }, ]; export const fake_messages = [ { id: 1, text: 'this is a test message and i am test user', user: { id: 12, username: 'asghar', isOnline: true, }, createdAt: new Date(), // updatedAt, }, { id: 2, text: 'this is a test message and i am test user', user: { id: 3, username: 'ahmad', isOnline: true, }, createdAt: new Date(), // updatedAt, }, { id: 1, text: 'this is a test message and i am test user', user: { id: 4, username: 'hosein', isOnline: true, }, createdAt: new Date(), // updatedAt, }, { id: 1, text: 'this is a test message and i am test user', user: { id: 6, username: 'hamid', isOnline: true, }, createdAt: new Date(), updatedAt: new Date(), }, ]; <file_sep>import { Flex, Text, UnorderedList } from '@chakra-ui/react'; import { getFriends } from 'api/handler/account'; import useFriendSocket from 'api/ws/useFriendSocket'; import FriendsListItem from 'components/items/FriendsListItem'; import OnlineLabel from 'components/sections/OnlineLabel'; import React from 'react'; import { useQuery } from 'react-query'; import { fKey } from 'utils/querykeys'; // fake import { fake_friends as data } from 'utils/fake'; export default function FriendsList() { // const { data } = useQuery(fKey, () => getFriends); // useFriendSocket(); if (data?.length === 0) { return ( <Flex justify={'center'} align={'center'} w={'full'}> <Text textColor={'brandGray.accent'}>No one here yet</Text> </Flex> ); } return ( <> <UnorderedList listStyleType="none" ml="0" w="full" mt="2"> <OnlineLabel label={`friends — ${data.length || 0}`} /> {data.map((frnd) => ( <FriendsListItem key={frnd.id} friend={frnd} /> ))} </UnorderedList> </> ); }
ae6fd5bd21d5240e278c06567b779f4cd7570b65
[ "JavaScript" ]
3
JavaScript
hoseinABH98/discord-client
e1a073454e089352150d1f0f7fd6a6051e10a050
373c43dc9865bd0703b4a8b798ce19d48c9a6eb8
refs/heads/master
<repo_name>ashrafemp/smartlearningdesktop<file_sep>/src/app/Home.java /* 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 app; import Decoder.BASE64Decoder; import Decoder.BASE64Encoder; import java.awt.Container; import java.awt.Font; import java.awt.Image; import java.awt.List; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.net.URL; import java.security.Key; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import net.proteanit.sql.DbUtils; import org.w3c.dom.Document; import org.w3c.dom.*; /** * * @author <NAME> */ public class Home extends javax.swing.JFrame { Connection con; Statement stmt; ResultSet rs, rs1, rs2; PreparedStatement pst, pst1, pst2; String nm = null; String subject = null; String selectedlesson = null; String selectedUserid = null; String selectedUsername = null; String selectedUserEmail = null; String selectedUserPassword = null; String selectedQuestionId = null; String selectedQuestion = null; String selectedlessonPicture = null; Boolean login = false; String userLoginName = ""; String EMAIL_PATTERN = ""; Boolean userEmailCheck = false; String lessonImage = null; String LessonImageUrl = null; String selectedId = null; int pictureIndex; int checkIndex = 1; int pictureId = 0; int rowcount = 0; long StartTime, EndTime; ArrayList<String> wordList = new ArrayList<String>(); ArrayList<String> subjectList = new ArrayList<String>(); static JFrame progressFrame; JLabel progressLabel; static Container pane; private static final String ALGORITHM = "AES"; private static final String KEY = "<KEY>"; String servername, serveraddress, databasename, databaseusername, databasepassword=""; String servernameDecrypt, serveraddressDecrypt, databasenameDecrypt, databaseusernameDecrypt, databasepasswordDecrypt,url=""; /** * Creates new form Home */ public Home() { initComponents(); readXML(); con = mysqlconnect.ConnectDb(url,databaseusernameDecrypt,databasepasswordDecrypt); closeAllFrames(); if(con==null) { SettingsFrame.setVisible(true); Settings_Home_Btn.setVisible(false); } else { buttonGroup11.clearSelection(); English_lang.setSelected(true); UserLoginFrame.setLocation(200, 200); UserLoginFrame.setVisible(true); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); buttonGroup2 = new javax.swing.ButtonGroup(); buttonGroup3 = new javax.swing.ButtonGroup(); buttonGroup4 = new javax.swing.ButtonGroup(); buttonGroup5 = new javax.swing.ButtonGroup(); buttonGroup6 = new javax.swing.ButtonGroup(); buttonGroup7 = new javax.swing.ButtonGroup(); buttonGroup8 = new javax.swing.ButtonGroup(); buttonGroup9 = new javax.swing.ButtonGroup(); buttonGroup10 = new javax.swing.ButtonGroup(); buttonGroup11 = new javax.swing.ButtonGroup(); desktopPane = new javax.swing.JDesktopPane(); LessonsFrame = new javax.swing.JInternalFrame(); Ls_Label = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); Ls_Table = new javax.swing.JTable(); Ls_Add_Btn = new javax.swing.JButton(); Ls_Delete_Btn = new javax.swing.JButton(); Ls_Enter_Btn = new javax.swing.JButton(); Ls_Back_Btn = new javax.swing.JButton(); Ls_Marks_Btn = new javax.swing.JButton(); AddLessonFrame = new javax.swing.JInternalFrame(); AddLs_Name_Label = new javax.swing.JLabel(); AddLs_Submit_Btn = new javax.swing.JButton(); AddLs_Label = new javax.swing.JLabel(); AddLs_Back_Btn = new javax.swing.JButton(); AddLs_Name_TextArea = new javax.swing.JTextField(); LessonsImageFrame = new javax.swing.JInternalFrame(); LsImage_AddImage_Btn = new javax.swing.JButton(); LsImage_label = new javax.swing.JLabel(); LsImage_Questions_Btn = new javax.swing.JButton(); Ls_Image_Back_Btn = new javax.swing.JButton(); LsImage_PictureLabel = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); Ls_Image_Table = new javax.swing.JTable(); LsImage_Delete_Btn = new javax.swing.JButton(); SubjectFrame = new javax.swing.JInternalFrame(); Sub_Label = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); Sub_Table = new javax.swing.JTable(); Sub_Add_Btn = new javax.swing.JButton(); Sub_Delete_Btn = new javax.swing.JButton(); Sub_Enter_Btn = new javax.swing.JButton(); Sub_Home_Btn = new javax.swing.JButton(); Sub_Status_Btn = new javax.swing.JButton(); active = new javax.swing.JRadioButton(); inactive = new javax.swing.JRadioButton(); AddSubjectFrame = new javax.swing.JInternalFrame(); AddSub_Name_Label = new javax.swing.JLabel(); AddSub_Add_Btn = new javax.swing.JButton(); AddSub_Label = new javax.swing.JLabel(); AddSub_Back_Btn = new javax.swing.JButton(); AddSub_Name_Textfield = new javax.swing.JTextField(); UserManagementFrame = new javax.swing.JInternalFrame(); UsMng_label = new javax.swing.JLabel(); UsMng_Name_Textfield = new javax.swing.JTextField(); UsMng_Email_Textfield = new javax.swing.JTextField(); jScrollPane6 = new javax.swing.JScrollPane(); User_Table = new javax.swing.JTable(); UsMng_Delete_Btn = new javax.swing.JButton(); UsMng_Update_Btn = new javax.swing.JButton(); UsMng_Name_Label = new javax.swing.JLabel(); UsMng_Email_Label = new javax.swing.JLabel(); UsMng_Home_Btn = new javax.swing.JButton(); QuestionsFrame = new javax.swing.JInternalFrame(); Qst_Label = new javax.swing.JLabel(); jScrollPane7 = new javax.swing.JScrollPane(); Qst_Table = new javax.swing.JTable(); jScrollPane8 = new javax.swing.JScrollPane(); Qst_Textarea = new javax.swing.JTextArea(); Qst_Opt1_Textfield = new javax.swing.JTextField(); Qst_Opt2_Textfield = new javax.swing.JTextField(); Qst_Opt3_Textfield = new javax.swing.JTextField(); Qst_Update_Btn = new javax.swing.JButton(); Qst_Opt1_Btn = new javax.swing.JRadioButton(); Qst_Opt2_Btn = new javax.swing.JRadioButton(); Qst_Opt3_Btn = new javax.swing.JRadioButton(); Qst_Add_Btn = new javax.swing.JButton(); Qst_Back_Btn = new javax.swing.JButton(); Qst_Delete_Btn = new javax.swing.JButton(); UserLoginFrame = new javax.swing.JInternalFrame(); UserLogin_Label = new javax.swing.JLabel(); UserLogin_Name_Label = new javax.swing.JLabel(); UserLogin_Password_Label = new javax.swing.JLabel(); UserLogin_Login_Btn = new javax.swing.JButton(); UserLogin_Name_Textfield = new javax.swing.JTextField(); UserLogin_ForgetPwd_Btn = new javax.swing.JButton(); UserLogin_Password_Textfield = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); English_lang = new javax.swing.JRadioButton(); Arabic_lang = new javax.swing.JRadioButton(); ChangePasswordFrame = new javax.swing.JInternalFrame(); ChangePwd_Label = new javax.swing.JLabel(); ChangePwd_NewPwd_Label = new javax.swing.JLabel(); ChangePwd_ConfPwd_Label = new javax.swing.JLabel(); ChangePwd_NewPwd_Textfield = new javax.swing.JTextField(); ChangePwd_ConfPwd_Textfield = new javax.swing.JTextField(); ChangePwd_Submit_Btn = new javax.swing.JButton(); ChangePwd_Home_Btn = new javax.swing.JButton(); StudentManagementFrame = new javax.swing.JInternalFrame(); StDetails_Label = new javax.swing.JLabel(); jScrollPane9 = new javax.swing.JScrollPane(); St_Table = new javax.swing.JTable(); StDetails_Back_Btn = new javax.swing.JButton(); HomeFrame = new javax.swing.JInternalFrame(); Home_Subject_Btn = new javax.swing.JButton(); Home_UsrMngt_Btn = new javax.swing.JButton(); Home_ChangePwd_Btn = new javax.swing.JButton(); Home_Logout_Btn = new javax.swing.JButton(); Home_label = new javax.swing.JLabel(); Home_ViewSugg_Btn = new javax.swing.JButton(); Home_EmployeeFeedback_Btn = new javax.swing.JButton(); Home_Results_Btn = new javax.swing.JButton(); Home_Dictionary_Btn = new javax.swing.JButton(); Home_Settings_Btn = new javax.swing.JButton(); ViewSuggestionsFrame = new javax.swing.JInternalFrame(); ViewSug_Label = new javax.swing.JLabel(); jScrollPane10 = new javax.swing.JScrollPane(); Suggestions_Table = new javax.swing.JTable(); ViewSug_Home_Btn = new javax.swing.JButton(); jScrollPane11 = new javax.swing.JScrollPane(); ViewSug_Suggestion_Textarea = new javax.swing.JTextArea(); ViewSug_Suggestion_Label = new javax.swing.JLabel(); ViewSug_Subject_Label = new javax.swing.JLabel(); ViewSug_Subject_Textfield = new javax.swing.JTextField(); FeedbackFrame = new javax.swing.JInternalFrame(); jScrollPane12 = new javax.swing.JScrollPane(); feedbackTable = new javax.swing.JTable(); jScrollPane13 = new javax.swing.JScrollPane(); jPanel1 = new javax.swing.JPanel(); Question2_Label = new javax.swing.JLabel(); Question3_Label = new javax.swing.JLabel(); Question4_Label = new javax.swing.JLabel(); Question5_Label = new javax.swing.JLabel(); Question6_Label = new javax.swing.JLabel(); Question7_Label = new javax.swing.JLabel(); Question1 = new javax.swing.JLabel(); Question2 = new javax.swing.JLabel(); Question3 = new javax.swing.JLabel(); Question4 = new javax.swing.JLabel(); Question5 = new javax.swing.JLabel(); Question6 = new javax.swing.JLabel(); Question7 = new javax.swing.JLabel(); Question1_Label = new javax.swing.JLabel(); Question8_Label = new javax.swing.JLabel(); Question8 = new javax.swing.JLabel(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); jRadioButton4 = new javax.swing.JRadioButton(); jRadioButton5 = new javax.swing.JRadioButton(); jRadioButton6 = new javax.swing.JRadioButton(); jRadioButton7 = new javax.swing.JRadioButton(); jRadioButton8 = new javax.swing.JRadioButton(); jRadioButton9 = new javax.swing.JRadioButton(); jRadioButton10 = new javax.swing.JRadioButton(); jRadioButton11 = new javax.swing.JRadioButton(); jRadioButton12 = new javax.swing.JRadioButton(); jRadioButton13 = new javax.swing.JRadioButton(); jRadioButton14 = new javax.swing.JRadioButton(); jRadioButton15 = new javax.swing.JRadioButton(); jRadioButton16 = new javax.swing.JRadioButton(); jRadioButton17 = new javax.swing.JRadioButton(); jRadioButton18 = new javax.swing.JRadioButton(); jRadioButton19 = new javax.swing.JRadioButton(); jRadioButton20 = new javax.swing.JRadioButton(); jRadioButton21 = new javax.swing.JRadioButton(); jRadioButton22 = new javax.swing.JRadioButton(); jRadioButton23 = new javax.swing.JRadioButton(); jRadioButton24 = new javax.swing.JRadioButton(); jRadioButton25 = new javax.swing.JRadioButton(); jRadioButton26 = new javax.swing.JRadioButton(); jRadioButton27 = new javax.swing.JRadioButton(); jRadioButton28 = new javax.swing.JRadioButton(); jRadioButton29 = new javax.swing.JRadioButton(); jRadioButton30 = new javax.swing.JRadioButton(); jRadioButton31 = new javax.swing.JRadioButton(); jRadioButton32 = new javax.swing.JRadioButton(); jRadioButton33 = new javax.swing.JRadioButton(); jRadioButton34 = new javax.swing.JRadioButton(); jRadioButton35 = new javax.swing.JRadioButton(); jRadioButton36 = new javax.swing.JRadioButton(); jRadioButton37 = new javax.swing.JRadioButton(); jRadioButton38 = new javax.swing.JRadioButton(); jRadioButton39 = new javax.swing.JRadioButton(); jRadioButton40 = new javax.swing.JRadioButton(); EmpFeedback_Home_Btn = new javax.swing.JButton(); EmpFeedback_Label = new javax.swing.JLabel(); ResultFrame = new javax.swing.JInternalFrame(); jScrollPane14 = new javax.swing.JScrollPane(); Result_Table = new javax.swing.JTable(); Results_label = new javax.swing.JLabel(); Results_Home_Btn = new javax.swing.JButton(); jComboBox1 = new javax.swing.JComboBox<>(); Results_StudentName_Lbl = new javax.swing.JLabel(); Results_Subject_Lbl = new javax.swing.JLabel(); jComboBox2 = new javax.swing.JComboBox<>(); Results_Search_Btn = new javax.swing.JButton(); AddLessonPictureFrame = new javax.swing.JInternalFrame(); AddLessonPicture_Label = new javax.swing.JLabel(); AddLessonPicture_Add_Btn = new javax.swing.JButton(); AddLessonPicture_Back_Btn = new javax.swing.JButton(); AddLessonPicture_Upload_Btn = new javax.swing.JButton(); DictionaryFrame = new javax.swing.JInternalFrame(); Dictionary_Word_Label = new javax.swing.JLabel(); Dictionary_Word_Textfield = new javax.swing.JTextField(); Dictionary_Meaning_Label = new javax.swing.JLabel(); jScrollPane4 = new javax.swing.JScrollPane(); Dictionary_Meaning_Textarea = new javax.swing.JTextArea(); Dictionary_Add_Btn = new javax.swing.JButton(); Dictionary_Update_Btn = new javax.swing.JButton(); Dictionary_Delete_Btn = new javax.swing.JButton(); jScrollPane5 = new javax.swing.JScrollPane(); Dictionary_Table = new javax.swing.JTable(); Dictionary_Label = new javax.swing.JLabel(); Dictionary_Home_Btn = new javax.swing.JButton(); SettingsFrame = new javax.swing.JInternalFrame(); Settings_Label = new javax.swing.JLabel(); Settings_DBUserName = new javax.swing.JLabel(); Settings_DBPassword = new <PASSWORD>(); Settings_DBUserName_Textfield = new javax.swing.JTextField(); Settings_DBPassword_Textfield = new javax.swing.JTextField(); Settings_Save_Btn = new javax.swing.JButton(); Settings_ServerName = new javax.swing.JLabel(); Settings_DatabaseName = new javax.swing.JLabel(); Settings_ServerAddress = new javax.swing.JLabel(); Settings_ServerName_Textfield = new javax.swing.JTextField(); Settings_ServerAddress_Textfield = new javax.swing.JTextField(); Settings_DatabaseName_Textfield = new javax.swing.JTextField(); Settings_Home_Btn = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); LessonsFrame.setPreferredSize(new java.awt.Dimension(600, 400)); LessonsFrame.setVisible(true); Ls_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N Ls_Label.setText("LESSONS"); Ls_Table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Sl.No.", "Lesson" } )); Ls_Table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Ls_TableMouseClicked(evt); } }); Ls_Table.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Ls_TableKeyReleased(evt); } }); jScrollPane3.setViewportView(Ls_Table); Ls_Add_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Ls_Add_Btn.setText("Add"); Ls_Add_Btn.setPreferredSize(new java.awt.Dimension(125, 30)); Ls_Add_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Ls_Add_BtnActionPerformed(evt); } }); Ls_Add_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Ls_Add_BtnKeyReleased(evt); } }); Ls_Delete_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Ls_Delete_Btn.setText("Delete"); Ls_Delete_Btn.setPreferredSize(new java.awt.Dimension(125, 30)); Ls_Delete_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Ls_Delete_BtnActionPerformed(evt); } }); Ls_Delete_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Ls_Delete_BtnKeyReleased(evt); } }); Ls_Enter_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Ls_Enter_Btn.setText("Enter"); Ls_Enter_Btn.setPreferredSize(new java.awt.Dimension(125, 30)); Ls_Enter_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Ls_Enter_BtnActionPerformed(evt); } }); Ls_Enter_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Ls_Enter_BtnKeyReleased(evt); } }); Ls_Back_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Ls_Back_Btn.setText("Back"); Ls_Back_Btn.setPreferredSize(new java.awt.Dimension(70, 30)); Ls_Back_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Ls_Back_BtnActionPerformed(evt); } }); Ls_Back_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Ls_Back_BtnKeyReleased(evt); } }); Ls_Marks_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Ls_Marks_Btn.setText("Students Marks"); Ls_Marks_Btn.setPreferredSize(new java.awt.Dimension(125, 30)); Ls_Marks_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Ls_Marks_BtnActionPerformed(evt); } }); Ls_Marks_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Ls_Marks_BtnKeyReleased(evt); } }); javax.swing.GroupLayout LessonsFrameLayout = new javax.swing.GroupLayout(LessonsFrame.getContentPane()); LessonsFrame.getContentPane().setLayout(LessonsFrameLayout); LessonsFrameLayout.setHorizontalGroup( LessonsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(LessonsFrameLayout.createSequentialGroup() .addComponent(Ls_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(175, 175, 175) .addComponent(Ls_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, LessonsFrameLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(87, 87, 87)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, LessonsFrameLayout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(Ls_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 78, Short.MAX_VALUE) .addGroup(LessonsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Ls_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Ls_Marks_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(69, 69, 69) .addComponent(Ls_Enter_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(22, 22, 22)) ); LessonsFrameLayout.setVerticalGroup( LessonsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(LessonsFrameLayout.createSequentialGroup() .addGroup(LessonsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Ls_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Ls_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(34, 34, 34) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(35, 35, 35) .addGroup(LessonsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Ls_Enter_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Ls_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Ls_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE) .addComponent(Ls_Marks_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) ); desktopPane.add(LessonsFrame); LessonsFrame.setBounds(0, 0, 600, 400); AddLessonFrame.setPreferredSize(new java.awt.Dimension(500, 300)); AddLessonFrame.setVisible(true); AddLs_Name_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N AddLs_Name_Label.setText("LESSON NAME"); AddLs_Submit_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N AddLs_Submit_Btn.setText("Submit"); AddLs_Submit_Btn.setPreferredSize(new java.awt.Dimension(80, 30)); AddLs_Submit_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddLs_Submit_BtnActionPerformed(evt); } }); AddLs_Submit_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { AddLs_Submit_BtnKeyReleased(evt); } }); AddLs_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N AddLs_Label.setText("ADD LESSON"); AddLs_Back_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N AddLs_Back_Btn.setText("Back"); AddLs_Back_Btn.setPreferredSize(new java.awt.Dimension(80, 30)); AddLs_Back_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddLs_Back_BtnActionPerformed(evt); } }); AddLs_Back_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { AddLs_Back_BtnKeyReleased(evt); } }); javax.swing.GroupLayout AddLessonFrameLayout = new javax.swing.GroupLayout(AddLessonFrame.getContentPane()); AddLessonFrame.getContentPane().setLayout(AddLessonFrameLayout); AddLessonFrameLayout.setHorizontalGroup( AddLessonFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AddLessonFrameLayout.createSequentialGroup() .addGroup(AddLessonFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AddLessonFrameLayout.createSequentialGroup() .addComponent(AddLs_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(84, 84, 84) .addComponent(AddLs_Label)) .addGroup(AddLessonFrameLayout.createSequentialGroup() .addGap(69, 69, 69) .addComponent(AddLs_Name_Label) .addGap(65, 65, 65) .addGroup(AddLessonFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(AddLs_Name_TextArea, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(AddLs_Submit_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(68, Short.MAX_VALUE)) ); AddLessonFrameLayout.setVerticalGroup( AddLessonFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AddLessonFrameLayout.createSequentialGroup() .addGroup(AddLessonFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(AddLs_Label) .addComponent(AddLs_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(73, 73, 73) .addGroup(AddLessonFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(AddLs_Name_Label) .addComponent(AddLs_Name_TextArea, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(74, 74, 74) .addComponent(AddLs_Submit_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(35, Short.MAX_VALUE)) ); desktopPane.add(AddLessonFrame); AddLessonFrame.setBounds(0, 0, 500, 300); LessonsImageFrame.setPreferredSize(new java.awt.Dimension(1000, 600)); LessonsImageFrame.setVisible(true); LsImage_AddImage_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N LsImage_AddImage_Btn.setText("Add Image"); LsImage_AddImage_Btn.setPreferredSize(new java.awt.Dimension(100, 30)); LsImage_AddImage_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LsImage_AddImage_BtnActionPerformed(evt); } }); LsImage_AddImage_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { LsImage_AddImage_BtnKeyReleased(evt); } }); LsImage_label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N LsImage_label.setText("jLabel5"); LsImage_Questions_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N LsImage_Questions_Btn.setText("Questions"); LsImage_Questions_Btn.setPreferredSize(new java.awt.Dimension(100, 30)); LsImage_Questions_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LsImage_Questions_BtnActionPerformed(evt); } }); LsImage_Questions_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { LsImage_Questions_BtnKeyReleased(evt); } }); Ls_Image_Back_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Ls_Image_Back_Btn.setText("Back"); Ls_Image_Back_Btn.setPreferredSize(new java.awt.Dimension(60, 30)); Ls_Image_Back_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Ls_Image_Back_BtnActionPerformed(evt); } }); Ls_Image_Back_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Ls_Image_Back_BtnKeyReleased(evt); } }); LsImage_PictureLabel.setPreferredSize(new java.awt.Dimension(525, 350)); Ls_Image_Table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null}, {null}, {null}, {null}, {null}, {null}, {null}, {null}, {null}, {null} }, new String [] { "Title 1" } )); Ls_Image_Table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Ls_Image_TableMouseClicked(evt); } }); Ls_Image_Table.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Ls_Image_TableKeyReleased(evt); } }); jScrollPane2.setViewportView(Ls_Image_Table); LsImage_Delete_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N LsImage_Delete_Btn.setText("Delete Image"); LsImage_Delete_Btn.setPreferredSize(new java.awt.Dimension(100, 30)); LsImage_Delete_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { LsImage_Delete_BtnActionPerformed(evt); } }); LsImage_Delete_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { LsImage_Delete_BtnKeyReleased(evt); } }); javax.swing.GroupLayout LessonsImageFrameLayout = new javax.swing.GroupLayout(LessonsImageFrame.getContentPane()); LessonsImageFrame.getContentPane().setLayout(LessonsImageFrameLayout); LessonsImageFrameLayout.setHorizontalGroup( LessonsImageFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(LessonsImageFrameLayout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(LessonsImageFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(LessonsImageFrameLayout.createSequentialGroup() .addComponent(Ls_Image_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(326, 326, 326) .addComponent(LsImage_label)) .addGroup(LessonsImageFrameLayout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(71, 71, 71) .addGroup(LessonsImageFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(LsImage_PictureLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(LessonsImageFrameLayout.createSequentialGroup() .addComponent(LsImage_AddImage_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(107, 107, 107) .addComponent(LsImage_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(LsImage_Questions_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); LessonsImageFrameLayout.setVerticalGroup( LessonsImageFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(LessonsImageFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(LessonsImageFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Ls_Image_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(LsImage_label)) .addGap(18, 18, 18) .addGroup(LessonsImageFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(LsImage_PictureLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 98, Short.MAX_VALUE) .addGroup(LessonsImageFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(LsImage_AddImage_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(LsImage_Questions_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(LsImage_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(31, 31, 31)) ); desktopPane.add(LessonsImageFrame); LessonsImageFrame.setBounds(0, 0, 1000, 600); SubjectFrame.setNormalBounds(new java.awt.Rectangle(0, 0, 800, 550)); SubjectFrame.setPreferredSize(new java.awt.Dimension(600, 475)); SubjectFrame.setVisible(true); Sub_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N Sub_Label.setText("SUBJECTS"); Sub_Table.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N Sub_Table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null}, {null}, {null}, {null}, {null}, {null}, {null}, {null}, {null}, {null} }, new String [] { "Subject" } ) { boolean[] canEdit = new boolean [] { false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); Sub_Table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Sub_TableMouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { Sub_TableMousePressed(evt); } }); Sub_Table.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { Sub_TableKeyPressed(evt); } public void keyReleased(java.awt.event.KeyEvent evt) { Sub_TableKeyReleased(evt); } }); jScrollPane1.setViewportView(Sub_Table); if (Sub_Table.getColumnModel().getColumnCount() > 0) { Sub_Table.getColumnModel().getColumn(0).setResizable(false); } Sub_Add_Btn.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N Sub_Add_Btn.setText("Add"); Sub_Add_Btn.setMaximumSize(new java.awt.Dimension(75, 50)); Sub_Add_Btn.setPreferredSize(new java.awt.Dimension(90, 30)); Sub_Add_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Sub_Add_BtnActionPerformed(evt); } }); Sub_Add_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Sub_Add_BtnKeyReleased(evt); } }); Sub_Delete_Btn.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N Sub_Delete_Btn.setText("Delete"); Sub_Delete_Btn.setPreferredSize(new java.awt.Dimension(90, 30)); Sub_Delete_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Sub_Delete_BtnActionPerformed(evt); } }); Sub_Delete_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Sub_Delete_BtnKeyReleased(evt); } }); Sub_Enter_Btn.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N Sub_Enter_Btn.setText("Enter"); Sub_Enter_Btn.setNextFocusableComponent(Sub_Table); Sub_Enter_Btn.setPreferredSize(new java.awt.Dimension(90, 30)); Sub_Enter_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Sub_Enter_BtnActionPerformed(evt); } }); Sub_Enter_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Sub_Enter_BtnKeyReleased(evt); } }); Sub_Home_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Sub_Home_Btn.setText("Home"); Sub_Home_Btn.setPreferredSize(new java.awt.Dimension(65, 30)); Sub_Home_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Sub_Home_BtnMouseClicked(evt); } }); Sub_Home_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Sub_Home_BtnActionPerformed(evt); } }); Sub_Home_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Sub_Home_BtnKeyReleased(evt); } }); Sub_Status_Btn.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N Sub_Status_Btn.setText("Update Status"); Sub_Status_Btn.setPreferredSize(new java.awt.Dimension(90, 30)); Sub_Status_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Sub_Status_BtnActionPerformed(evt); } }); Sub_Status_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Sub_Status_BtnKeyReleased(evt); } }); buttonGroup10.add(active); active.setText("Active"); buttonGroup10.add(inactive); inactive.setText("Inactive"); javax.swing.GroupLayout SubjectFrameLayout = new javax.swing.GroupLayout(SubjectFrame.getContentPane()); SubjectFrame.getContentPane().setLayout(SubjectFrameLayout); SubjectFrameLayout.setHorizontalGroup( SubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SubjectFrameLayout.createSequentialGroup() .addContainerGap() .addComponent(Sub_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(126, 126, 126) .addComponent(Sub_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SubjectFrameLayout.createSequentialGroup() .addGap(0, 67, Short.MAX_VALUE) .addGroup(SubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SubjectFrameLayout.createSequentialGroup() .addGroup(SubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(SubjectFrameLayout.createSequentialGroup() .addComponent(Sub_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE) .addComponent(Sub_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(70, 70, 70) .addComponent(Sub_Enter_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(SubjectFrameLayout.createSequentialGroup() .addComponent(active) .addGap(66, 66, 66) .addComponent(inactive) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Sub_Status_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(113, 113, 113)))) ); SubjectFrameLayout.setVerticalGroup( SubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SubjectFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(SubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Sub_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Sub_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(35, 35, 35) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(31, 31, 31) .addGroup(SubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(active) .addComponent(inactive) .addComponent(Sub_Status_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE) .addGroup(SubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Sub_Enter_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Sub_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Sub_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(76, 76, 76)) ); desktopPane.add(SubjectFrame); SubjectFrame.setBounds(0, 0, 600, 475); AddSubjectFrame.setPreferredSize(new java.awt.Dimension(500, 300)); AddSubjectFrame.setVisible(true); AddSub_Name_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N AddSub_Name_Label.setText("SUBJECT NAME"); AddSub_Add_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N AddSub_Add_Btn.setText("Add"); AddSub_Add_Btn.setPreferredSize(new java.awt.Dimension(60, 30)); AddSub_Add_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddSub_Add_BtnActionPerformed(evt); } }); AddSub_Add_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { AddSub_Add_BtnKeyReleased(evt); } }); AddSub_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N AddSub_Label.setText("ADD SUBJECT"); AddSub_Back_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N AddSub_Back_Btn.setText("Back"); AddSub_Back_Btn.setPreferredSize(new java.awt.Dimension(60, 30)); AddSub_Back_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddSub_Back_BtnActionPerformed(evt); } }); AddSub_Back_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { AddSub_Back_BtnKeyReleased(evt); } }); javax.swing.GroupLayout AddSubjectFrameLayout = new javax.swing.GroupLayout(AddSubjectFrame.getContentPane()); AddSubjectFrame.getContentPane().setLayout(AddSubjectFrameLayout); AddSubjectFrameLayout.setHorizontalGroup( AddSubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AddSubjectFrameLayout.createSequentialGroup() .addGroup(AddSubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(AddSub_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(AddSubjectFrameLayout.createSequentialGroup() .addGap(32, 32, 32) .addComponent(AddSub_Name_Label))) .addGroup(AddSubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AddSubjectFrameLayout.createSequentialGroup() .addGap(35, 35, 35) .addComponent(AddSub_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(AddSubjectFrameLayout.createSequentialGroup() .addGap(50, 50, 50) .addGroup(AddSubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(AddSub_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(AddSub_Name_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(111, Short.MAX_VALUE)) ); AddSubjectFrameLayout.setVerticalGroup( AddSubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AddSubjectFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(AddSubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(AddSub_Label) .addGroup(AddSubjectFrameLayout.createSequentialGroup() .addComponent(AddSub_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(80, 80, 80) .addGroup(AddSubjectFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(AddSub_Name_Label) .addComponent(AddSub_Name_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE) .addComponent(AddSub_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(49, 49, 49)) ); desktopPane.add(AddSubjectFrame); AddSubjectFrame.setBounds(0, 0, 500, 300); UserManagementFrame.setPreferredSize(new java.awt.Dimension(725, 525)); UserManagementFrame.setVisible(true); UsMng_label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N UsMng_label.setText("USER MANAGEMENT"); User_Table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "User name", "Email Address" } )); User_Table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { User_TableMouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { User_TableMousePressed(evt); } }); User_Table.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { User_TableKeyReleased(evt); } }); jScrollPane6.setViewportView(User_Table); UsMng_Delete_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N UsMng_Delete_Btn.setText("Delete"); UsMng_Delete_Btn.setPreferredSize(new java.awt.Dimension(100, 30)); UsMng_Delete_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { UsMng_Delete_BtnActionPerformed(evt); } }); UsMng_Delete_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { UsMng_Delete_BtnKeyReleased(evt); } }); UsMng_Update_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N UsMng_Update_Btn.setText("Update"); UsMng_Update_Btn.setPreferredSize(new java.awt.Dimension(100, 30)); UsMng_Update_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { UsMng_Update_BtnActionPerformed(evt); } }); UsMng_Update_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { UsMng_Update_BtnKeyReleased(evt); } }); UsMng_Name_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N UsMng_Name_Label.setText("<NAME>"); UsMng_Email_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N UsMng_Email_Label.setText("EMAIL"); UsMng_Home_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N UsMng_Home_Btn.setText("Home"); UsMng_Home_Btn.setPreferredSize(new java.awt.Dimension(65, 30)); UsMng_Home_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { UsMng_Home_BtnMouseClicked(evt); } }); UsMng_Home_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { UsMng_Home_BtnActionPerformed(evt); } }); UsMng_Home_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { UsMng_Home_BtnKeyReleased(evt); } }); javax.swing.GroupLayout UserManagementFrameLayout = new javax.swing.GroupLayout(UserManagementFrame.getContentPane()); UserManagementFrame.getContentPane().setLayout(UserManagementFrameLayout); UserManagementFrameLayout.setHorizontalGroup( UserManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(UserManagementFrameLayout.createSequentialGroup() .addGroup(UserManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(UserManagementFrameLayout.createSequentialGroup() .addGap(0, 65, Short.MAX_VALUE) .addGroup(UserManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(UserManagementFrameLayout.createSequentialGroup() .addGap(106, 106, 106) .addComponent(UsMng_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(161, 161, 161) .addComponent(UsMng_Update_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(UserManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(UserManagementFrameLayout.createSequentialGroup() .addComponent(UsMng_Name_Label) .addGap(37, 37, 37) .addComponent(UsMng_Name_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(UsMng_Email_Label) .addGap(37, 37, 37) .addComponent(UsMng_Email_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 570, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(UserManagementFrameLayout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(UsMng_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(150, 150, 150) .addComponent(UsMng_label, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 74, Short.MAX_VALUE)) ); UserManagementFrameLayout.setVerticalGroup( UserManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(UserManagementFrameLayout.createSequentialGroup() .addGap(13, 13, 13) .addGroup(UserManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(UsMng_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(UsMng_label)) .addGap(76, 76, 76) .addGroup(UserManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(UsMng_Email_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(UsMng_Name_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(UsMng_Name_Label) .addComponent(UsMng_Email_Label)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 41, Short.MAX_VALUE) .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(29, 29, 29) .addGroup(UserManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(UsMng_Update_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(UsMng_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(66, 66, 66)) ); desktopPane.add(UserManagementFrame); UserManagementFrame.setBounds(0, 0, 725, 525); QuestionsFrame.setPreferredSize(new java.awt.Dimension(800, 600)); QuestionsFrame.setVisible(true); Qst_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N Qst_Label.setText("QUESTIONS"); Qst_Table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null}, {null, null, null, null, null, null, null} }, new String [] { "Question id", "Lesson Id", "Question", "opt 1", "opt 2", "opt 3", "Answer" } )); Qst_Table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Qst_TableMouseClicked(evt); } }); Qst_Table.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Qst_TableKeyReleased(evt); } }); jScrollPane7.setViewportView(Qst_Table); Qst_Textarea.setColumns(20); Qst_Textarea.setRows(5); jScrollPane8.setViewportView(Qst_Textarea); Qst_Opt3_Textfield.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Qst_Opt3_TextfieldKeyReleased(evt); } }); Qst_Update_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Qst_Update_Btn.setText("Update"); Qst_Update_Btn.setPreferredSize(new java.awt.Dimension(90, 30)); Qst_Update_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Qst_Update_BtnActionPerformed(evt); } }); Qst_Update_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Qst_Update_BtnKeyReleased(evt); } }); buttonGroup1.add(Qst_Opt1_Btn); buttonGroup1.add(Qst_Opt2_Btn); Qst_Opt2_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Qst_Opt2_BtnActionPerformed(evt); } }); buttonGroup1.add(Qst_Opt3_Btn); Qst_Add_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Qst_Add_Btn.setText("Add"); Qst_Add_Btn.setPreferredSize(new java.awt.Dimension(90, 30)); Qst_Add_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Qst_Add_BtnActionPerformed(evt); } }); Qst_Add_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Qst_Add_BtnKeyReleased(evt); } }); Qst_Back_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Qst_Back_Btn.setText("Back"); Qst_Back_Btn.setPreferredSize(new java.awt.Dimension(90, 30)); Qst_Back_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Qst_Back_BtnMouseClicked(evt); } }); Qst_Back_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Qst_Back_BtnActionPerformed(evt); } }); Qst_Back_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Qst_Back_BtnKeyReleased(evt); } }); Qst_Delete_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Qst_Delete_Btn.setText("Delete"); Qst_Delete_Btn.setPreferredSize(new java.awt.Dimension(90, 30)); Qst_Delete_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Qst_Delete_BtnActionPerformed(evt); } }); Qst_Delete_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Qst_Delete_BtnKeyReleased(evt); } }); javax.swing.GroupLayout QuestionsFrameLayout = new javax.swing.GroupLayout(QuestionsFrame.getContentPane()); QuestionsFrame.getContentPane().setLayout(QuestionsFrameLayout); QuestionsFrameLayout.setHorizontalGroup( QuestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(QuestionsFrameLayout.createSequentialGroup() .addGroup(QuestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(QuestionsFrameLayout.createSequentialGroup() .addComponent(Qst_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(230, 230, 230) .addComponent(Qst_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(QuestionsFrameLayout.createSequentialGroup() .addGap(73, 73, 73) .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 565, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(QuestionsFrameLayout.createSequentialGroup() .addGap(262, 262, 262) .addGroup(QuestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Qst_Opt1_Btn) .addComponent(Qst_Opt3_Btn) .addComponent(Qst_Opt2_Btn)) .addGap(18, 18, 18) .addGroup(QuestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Qst_Opt2_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Qst_Opt3_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Qst_Opt1_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(QuestionsFrameLayout.createSequentialGroup() .addGap(194, 194, 194) .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(QuestionsFrameLayout.createSequentialGroup() .addGap(142, 142, 142) .addComponent(Qst_Update_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(107, 107, 107) .addComponent(Qst_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(79, 79, 79) .addComponent(Qst_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(146, Short.MAX_VALUE)) ); QuestionsFrameLayout.setVerticalGroup( QuestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(QuestionsFrameLayout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(QuestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Qst_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Qst_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(38, 38, 38) .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addGroup(QuestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(Qst_Opt1_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Qst_Opt1_Btn)) .addGap(25, 25, 25) .addGroup(QuestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Qst_Opt2_Textfield, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Qst_Opt2_Btn, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(27, 27, 27) .addGroup(QuestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Qst_Opt3_Btn) .addComponent(Qst_Opt3_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(37, 37, 37) .addGroup(QuestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Qst_Update_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Qst_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Qst_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(39, Short.MAX_VALUE)) ); desktopPane.add(QuestionsFrame); QuestionsFrame.setBounds(0, 0, 800, 600); UserLoginFrame.setVisible(true); UserLogin_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N UserLogin_Label.setText("LOGIN"); UserLogin_Name_Label.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N UserLogin_Name_Label.setText("<NAME>"); UserLogin_Password_Label.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N UserLogin_Password_Label.setText("<PASSWORD>"); UserLogin_Login_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N UserLogin_Login_Btn.setText("Login"); UserLogin_Login_Btn.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); UserLogin_Login_Btn.setPreferredSize(new java.awt.Dimension(127, 30)); UserLogin_Login_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { UserLogin_Login_BtnActionPerformed(evt); } }); UserLogin_Login_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { UserLogin_Login_BtnKeyReleased(evt); } }); UserLogin_ForgetPwd_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N UserLogin_ForgetPwd_Btn.setText("Forget Password"); UserLogin_ForgetPwd_Btn.setPreferredSize(new java.awt.Dimension(127, 30)); UserLogin_ForgetPwd_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { UserLogin_ForgetPwd_BtnActionPerformed(evt); } }); UserLogin_ForgetPwd_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { UserLogin_ForgetPwd_BtnKeyReleased(evt); } }); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1.setText("Select Language"); buttonGroup11.add(English_lang); English_lang.setText("English"); English_lang.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { English_langActionPerformed(evt); } }); English_lang.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { English_langKeyReleased(evt); } }); buttonGroup11.add(Arabic_lang); Arabic_lang.setText("Arabic"); Arabic_lang.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Arabic_langActionPerformed(evt); } }); Arabic_lang.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Arabic_langKeyReleased(evt); } }); javax.swing.GroupLayout UserLoginFrameLayout = new javax.swing.GroupLayout(UserLoginFrame.getContentPane()); UserLoginFrame.getContentPane().setLayout(UserLoginFrameLayout); UserLoginFrameLayout.setHorizontalGroup( UserLoginFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, UserLoginFrameLayout.createSequentialGroup() .addContainerGap(218, Short.MAX_VALUE) .addComponent(UserLogin_Label) .addGap(136, 136, 136) .addGroup(UserLoginFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(UserLoginFrameLayout.createSequentialGroup() .addComponent(English_lang) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Arabic_lang) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, UserLoginFrameLayout.createSequentialGroup() .addComponent(jLabel1) .addGap(22, 22, 22)))) .addGroup(UserLoginFrameLayout.createSequentialGroup() .addGap(97, 97, 97) .addGroup(UserLoginFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(UserLoginFrameLayout.createSequentialGroup() .addComponent(UserLogin_Login_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(UserLogin_ForgetPwd_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(UserLoginFrameLayout.createSequentialGroup() .addGroup(UserLoginFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(UserLogin_Name_Label) .addComponent(UserLogin_Password_Label)) .addGap(125, 125, 125) .addGroup(UserLoginFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(UserLogin_Name_Textfield) .addComponent(UserLogin_Password_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 0, Short.MAX_VALUE)) ); UserLoginFrameLayout.setVerticalGroup( UserLoginFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(UserLoginFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(UserLoginFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(UserLogin_Label)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(UserLoginFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(English_lang) .addComponent(Arabic_lang)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE) .addGroup(UserLoginFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(UserLoginFrameLayout.createSequentialGroup() .addComponent(UserLogin_Name_Label) .addGap(30, 30, 30) .addComponent(UserLogin_Password_Label) .addGap(50, 50, 50) .addGroup(UserLoginFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(UserLogin_Login_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(UserLogin_ForgetPwd_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(UserLoginFrameLayout.createSequentialGroup() .addComponent(UserLogin_Name_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(25, 25, 25) .addComponent(UserLogin_Password_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(52, 52, 52)) ); desktopPane.add(UserLoginFrame); UserLoginFrame.setBounds(0, 0, 572, 340); ChangePasswordFrame.setPreferredSize(new java.awt.Dimension(500, 300)); ChangePasswordFrame.setVisible(true); ChangePwd_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N ChangePwd_Label.setText("CHANGE PASSWORD"); ChangePwd_NewPwd_Label.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N ChangePwd_NewPwd_Label.setText("<PASSWORD>"); ChangePwd_ConfPwd_Label.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N ChangePwd_ConfPwd_Label.setText("CONFIRM PASSWORD"); ChangePwd_ConfPwd_Textfield.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { ChangePwd_ConfPwd_TextfieldKeyReleased(evt); } }); ChangePwd_Submit_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N ChangePwd_Submit_Btn.setText("Submit"); ChangePwd_Submit_Btn.setPreferredSize(new java.awt.Dimension(90, 30)); ChangePwd_Submit_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ChangePwd_Submit_BtnActionPerformed(evt); } }); ChangePwd_Submit_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { ChangePwd_Submit_BtnKeyReleased(evt); } }); ChangePwd_Home_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N ChangePwd_Home_Btn.setText("Home"); ChangePwd_Home_Btn.setPreferredSize(new java.awt.Dimension(65, 30)); ChangePwd_Home_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ChangePwd_Home_BtnMouseClicked(evt); } }); ChangePwd_Home_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ChangePwd_Home_BtnActionPerformed(evt); } }); ChangePwd_Home_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { ChangePwd_Home_BtnKeyReleased(evt); } }); javax.swing.GroupLayout ChangePasswordFrameLayout = new javax.swing.GroupLayout(ChangePasswordFrame.getContentPane()); ChangePasswordFrame.getContentPane().setLayout(ChangePasswordFrameLayout); ChangePasswordFrameLayout.setHorizontalGroup( ChangePasswordFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ChangePasswordFrameLayout.createSequentialGroup() .addComponent(ChangePwd_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(71, 71, 71) .addComponent(ChangePwd_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(ChangePasswordFrameLayout.createSequentialGroup() .addGroup(ChangePasswordFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(ChangePwd_NewPwd_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(ChangePasswordFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ChangePasswordFrameLayout.createSequentialGroup() .addGap(99, 99, 99) .addGroup(ChangePasswordFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ChangePwd_NewPwd_Label) .addComponent(ChangePwd_ConfPwd_Label))) .addGroup(ChangePasswordFrameLayout.createSequentialGroup() .addGap(279, 279, 279) .addGroup(ChangePasswordFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ChangePwd_Submit_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ChangePwd_ConfPwd_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(35, Short.MAX_VALUE)) ); ChangePasswordFrameLayout.setVerticalGroup( ChangePasswordFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ChangePasswordFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(ChangePasswordFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChangePwd_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ChangePwd_Label)) .addGap(38, 38, 38) .addGroup(ChangePasswordFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChangePwd_NewPwd_Label) .addComponent(ChangePwd_NewPwd_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(ChangePasswordFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ChangePwd_ConfPwd_Label) .addComponent(ChangePwd_ConfPwd_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(50, 50, 50) .addComponent(ChangePwd_Submit_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(40, Short.MAX_VALUE)) ); desktopPane.add(ChangePasswordFrame); ChangePasswordFrame.setBounds(0, 0, 500, 300); StudentManagementFrame.setVisible(true); StDetails_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N StDetails_Label.setText("STUDENTS DETAILS"); St_Table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane9.setViewportView(St_Table); StDetails_Back_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N StDetails_Back_Btn.setText("Back"); StDetails_Back_Btn.setPreferredSize(new java.awt.Dimension(60, 30)); StDetails_Back_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { StDetails_Back_BtnActionPerformed(evt); } }); StDetails_Back_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { StDetails_Back_BtnKeyReleased(evt); } }); javax.swing.GroupLayout StudentManagementFrameLayout = new javax.swing.GroupLayout(StudentManagementFrame.getContentPane()); StudentManagementFrame.getContentPane().setLayout(StudentManagementFrameLayout); StudentManagementFrameLayout.setHorizontalGroup( StudentManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(StudentManagementFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(StudentManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(StudentManagementFrameLayout.createSequentialGroup() .addComponent(StDetails_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(172, 172, 172) .addComponent(StDetails_Label) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane9, javax.swing.GroupLayout.DEFAULT_SIZE, 647, Short.MAX_VALUE)) .addContainerGap()) ); StudentManagementFrameLayout.setVerticalGroup( StudentManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(StudentManagementFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(StudentManagementFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(StDetails_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(StDetails_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(54, 54, 54) .addComponent(jScrollPane9, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(26, Short.MAX_VALUE)) ); desktopPane.add(StudentManagementFrame); StudentManagementFrame.setBounds(0, 0, 683, 358); HomeFrame.setVisible(true); Home_Subject_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Home_Subject_Btn.setText("SUBJECTS"); Home_Subject_Btn.setPreferredSize(new java.awt.Dimension(160, 30)); Home_Subject_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Home_Subject_BtnMouseClicked(evt); } }); Home_Subject_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Home_Subject_BtnActionPerformed(evt); } }); Home_Subject_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Home_Subject_BtnKeyReleased(evt); } }); Home_UsrMngt_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Home_UsrMngt_Btn.setText("USER MANAGEMENT"); Home_UsrMngt_Btn.setPreferredSize(new java.awt.Dimension(160, 30)); Home_UsrMngt_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Home_UsrMngt_BtnMouseClicked(evt); } }); Home_UsrMngt_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Home_UsrMngt_BtnActionPerformed(evt); } }); Home_UsrMngt_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Home_UsrMngt_BtnKeyReleased(evt); } }); Home_ChangePwd_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Home_ChangePwd_Btn.setText("CHANGE PASSWORD"); Home_ChangePwd_Btn.setPreferredSize(new java.awt.Dimension(160, 30)); Home_ChangePwd_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Home_ChangePwd_BtnMouseClicked(evt); } }); Home_ChangePwd_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Home_ChangePwd_BtnActionPerformed(evt); } }); Home_ChangePwd_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Home_ChangePwd_BtnKeyReleased(evt); } }); Home_Logout_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Home_Logout_Btn.setText("LOGOUT"); Home_Logout_Btn.setPreferredSize(new java.awt.Dimension(160, 30)); Home_Logout_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Home_Logout_BtnMouseClicked(evt); } }); Home_Logout_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Home_Logout_BtnActionPerformed(evt); } }); Home_Logout_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Home_Logout_BtnKeyReleased(evt); } }); Home_label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N Home_label.setText("HOME"); Home_label.setPreferredSize(new java.awt.Dimension(35, 30)); Home_ViewSugg_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Home_ViewSugg_Btn.setText("VIEW SUGGESTIONS"); Home_ViewSugg_Btn.setPreferredSize(new java.awt.Dimension(160, 30)); Home_ViewSugg_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Home_ViewSugg_BtnMouseClicked(evt); } }); Home_ViewSugg_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Home_ViewSugg_BtnActionPerformed(evt); } }); Home_ViewSugg_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Home_ViewSugg_BtnKeyReleased(evt); } }); Home_EmployeeFeedback_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Home_EmployeeFeedback_Btn.setText("EMPLOYEE FEEDBACK"); Home_EmployeeFeedback_Btn.setPreferredSize(new java.awt.Dimension(160, 30)); Home_EmployeeFeedback_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Home_EmployeeFeedback_BtnMouseClicked(evt); } }); Home_EmployeeFeedback_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Home_EmployeeFeedback_BtnActionPerformed(evt); } }); Home_EmployeeFeedback_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Home_EmployeeFeedback_BtnKeyReleased(evt); } }); Home_Results_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Home_Results_Btn.setText("RESULTS"); Home_Results_Btn.setPreferredSize(new java.awt.Dimension(160, 30)); Home_Results_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Home_Results_BtnActionPerformed(evt); } }); Home_Results_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Home_Results_BtnKeyReleased(evt); } }); Home_Dictionary_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Home_Dictionary_Btn.setText("DICTIONARY"); Home_Dictionary_Btn.setPreferredSize(new java.awt.Dimension(160, 30)); Home_Dictionary_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Home_Dictionary_BtnActionPerformed(evt); } }); Home_Dictionary_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Home_Dictionary_BtnKeyReleased(evt); } }); Home_Settings_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Home_Settings_Btn.setText("SETTINGS"); Home_Settings_Btn.setPreferredSize(new java.awt.Dimension(160, 30)); Home_Settings_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Home_Settings_BtnActionPerformed(evt); } }); Home_Settings_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Home_Settings_BtnKeyReleased(evt); } }); javax.swing.GroupLayout HomeFrameLayout = new javax.swing.GroupLayout(HomeFrame.getContentPane()); HomeFrame.getContentPane().setLayout(HomeFrameLayout); HomeFrameLayout.setHorizontalGroup( HomeFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, HomeFrameLayout.createSequentialGroup() .addGap(112, 112, 112) .addGroup(HomeFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Home_ViewSugg_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Home_ChangePwd_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Home_UsrMngt_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Home_EmployeeFeedback_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE) .addGroup(HomeFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HomeFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Home_Subject_Btn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Home_Results_Btn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(Home_Dictionary_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Home_Settings_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(90, 90, 90)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, HomeFrameLayout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(HomeFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, HomeFrameLayout.createSequentialGroup() .addComponent(Home_label, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(227, 227, 227)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, HomeFrameLayout.createSequentialGroup() .addComponent(Home_Logout_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(197, 197, 197)))) ); HomeFrameLayout.setVerticalGroup( HomeFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HomeFrameLayout.createSequentialGroup() .addContainerGap() .addComponent(Home_label, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(44, 44, 44) .addGroup(HomeFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Home_UsrMngt_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Home_Subject_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(50, 50, 50) .addGroup(HomeFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Home_ChangePwd_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Home_Results_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(50, 50, 50) .addGroup(HomeFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Home_ViewSugg_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Home_Dictionary_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(51, 51, 51) .addGroup(HomeFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Home_EmployeeFeedback_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Home_Settings_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 50, Short.MAX_VALUE) .addComponent(Home_Logout_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(62, 62, 62)) ); desktopPane.add(HomeFrame); HomeFrame.setBounds(0, 0, 597, 531); ViewSuggestionsFrame.setVisible(true); ViewSug_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N ViewSug_Label.setText("SUGGESTIONS"); ViewSug_Label.setPreferredSize(new java.awt.Dimension(145, 30)); Suggestions_Table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); Suggestions_Table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Suggestions_TableMouseClicked(evt); } }); Suggestions_Table.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Suggestions_TableKeyReleased(evt); } }); jScrollPane10.setViewportView(Suggestions_Table); ViewSug_Home_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N ViewSug_Home_Btn.setText("Home"); ViewSug_Home_Btn.setPreferredSize(new java.awt.Dimension(60, 30)); ViewSug_Home_Btn.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ViewSug_Home_BtnMouseClicked(evt); } }); ViewSug_Home_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ViewSug_Home_BtnActionPerformed(evt); } }); ViewSug_Home_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { ViewSug_Home_BtnKeyReleased(evt); } }); ViewSug_Suggestion_Textarea.setColumns(20); ViewSug_Suggestion_Textarea.setRows(5); jScrollPane11.setViewportView(ViewSug_Suggestion_Textarea); ViewSug_Suggestion_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N ViewSug_Suggestion_Label.setText("SUGGESTION"); ViewSug_Suggestion_Label.setPreferredSize(new java.awt.Dimension(70, 20)); ViewSug_Subject_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N ViewSug_Subject_Label.setText("SUBJECT"); javax.swing.GroupLayout ViewSuggestionsFrameLayout = new javax.swing.GroupLayout(ViewSuggestionsFrame.getContentPane()); ViewSuggestionsFrame.getContentPane().setLayout(ViewSuggestionsFrameLayout); ViewSuggestionsFrameLayout.setHorizontalGroup( ViewSuggestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ViewSuggestionsFrameLayout.createSequentialGroup() .addGroup(ViewSuggestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ViewSuggestionsFrameLayout.createSequentialGroup() .addContainerGap() .addComponent(ViewSug_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(121, 121, 121) .addComponent(ViewSug_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(ViewSuggestionsFrameLayout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 523, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(29, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ViewSuggestionsFrameLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(ViewSuggestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ViewSug_Suggestion_Label, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ViewSug_Subject_Label)) .addGap(51, 51, 51) .addGroup(ViewSuggestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane11, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE) .addComponent(ViewSug_Subject_Textfield)) .addGap(115, 115, 115)) ); ViewSuggestionsFrameLayout.setVerticalGroup( ViewSuggestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ViewSuggestionsFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(ViewSuggestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ViewSug_Label, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(ViewSug_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(57, 57, 57) .addComponent(jScrollPane10, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(49, 49, 49) .addGroup(ViewSuggestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ViewSug_Subject_Label) .addComponent(ViewSug_Subject_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE) .addGroup(ViewSuggestionsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ViewSuggestionsFrameLayout.createSequentialGroup() .addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(22, 22, 22)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ViewSuggestionsFrameLayout.createSequentialGroup() .addComponent(ViewSug_Suggestion_Label, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(62, 62, 62)))) ); desktopPane.add(ViewSuggestionsFrame); ViewSuggestionsFrame.setBounds(0, 0, 613, 569); FeedbackFrame.setPreferredSize(new java.awt.Dimension(1300, 900)); FeedbackFrame.setVisible(true); feedbackTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Title 1", "Title 2" } )); feedbackTable.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { feedbackTableMouseClicked(evt); } }); feedbackTable.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { feedbackTableKeyReleased(evt); } }); jScrollPane12.setViewportView(feedbackTable); jPanel1.setPreferredSize(new java.awt.Dimension(1000, 700)); Question2_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Question2_Label.setText("Question 2"); Question3_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Question3_Label.setText("Question 3"); Question4_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Question4_Label.setText("Question 4"); Question5_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Question5_Label.setText("Question 5"); Question6_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Question6_Label.setText("Question 6"); Question7_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Question7_Label.setText("Question 7"); Question1.setText("Question1"); Question1.setPreferredSize(new java.awt.Dimension(500, 15)); Question2.setText("Question 2"); Question2.setPreferredSize(new java.awt.Dimension(600, 15)); Question3.setText("Question 3"); Question3.setPreferredSize(new java.awt.Dimension(600, 15)); Question4.setText("Question 4"); Question4.setPreferredSize(new java.awt.Dimension(600, 15)); Question5.setText("Question 5"); Question5.setPreferredSize(new java.awt.Dimension(600, 15)); Question6.setText("Question 6"); Question6.setPreferredSize(new java.awt.Dimension(600, 15)); Question7.setText("Question 7"); Question7.setPreferredSize(new java.awt.Dimension(600, 15)); Question1_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Question1_Label.setText("Question 1"); Question8_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Question8_Label.setText("Question 8"); Question8.setText("Question 8"); Question8.setPreferredSize(new java.awt.Dimension(600, 15)); buttonGroup2.add(jRadioButton1); jRadioButton1.setText("jRadioButton1"); jRadioButton1.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup2.add(jRadioButton2); jRadioButton2.setText("jRadioButton2"); jRadioButton2.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup2.add(jRadioButton3); jRadioButton3.setText("jRadioButton3"); jRadioButton3.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup2.add(jRadioButton4); jRadioButton4.setText("jRadioButton4"); jRadioButton4.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup2.add(jRadioButton5); jRadioButton5.setText("jRadioButton5"); jRadioButton5.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup3.add(jRadioButton6); jRadioButton6.setText("jRadioButton6"); jRadioButton6.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup3.add(jRadioButton7); jRadioButton7.setText("jRadioButton7"); jRadioButton7.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup3.add(jRadioButton8); jRadioButton8.setText("jRadioButton8"); jRadioButton8.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup3.add(jRadioButton9); jRadioButton9.setText("jRadioButton9"); jRadioButton9.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup3.add(jRadioButton10); jRadioButton10.setText("jRadioButton10"); jRadioButton10.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup4.add(jRadioButton11); jRadioButton11.setText("jRadioButton11"); buttonGroup4.add(jRadioButton12); jRadioButton12.setText("jRadioButton12"); jRadioButton12.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup4.add(jRadioButton13); jRadioButton13.setText("jRadioButton13"); buttonGroup4.add(jRadioButton14); jRadioButton14.setText("jRadioButton14"); buttonGroup4.add(jRadioButton15); jRadioButton15.setText("jRadioButton15"); buttonGroup5.add(jRadioButton16); jRadioButton16.setText("jRadioButton16"); buttonGroup5.add(jRadioButton17); jRadioButton17.setText("jRadioButton17"); buttonGroup5.add(jRadioButton18); jRadioButton18.setText("jRadioButton18"); buttonGroup5.add(jRadioButton19); jRadioButton19.setText("jRadioButton19"); buttonGroup5.add(jRadioButton20); jRadioButton20.setText("jRadioButton20"); buttonGroup6.add(jRadioButton21); jRadioButton21.setText("jRadioButton21"); jRadioButton21.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup6.add(jRadioButton22); jRadioButton22.setText("jRadioButton22"); jRadioButton22.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup6.add(jRadioButton23); jRadioButton23.setText("jRadioButton23"); jRadioButton23.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup6.add(jRadioButton24); jRadioButton24.setText("jRadioButton24"); buttonGroup6.add(jRadioButton25); jRadioButton25.setText("jRadioButton25"); buttonGroup7.add(jRadioButton26); jRadioButton26.setText("jRadioButton26"); jRadioButton26.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup7.add(jRadioButton27); jRadioButton27.setText("jRadioButton27"); buttonGroup7.add(jRadioButton28); jRadioButton28.setText("jRadioButton28"); buttonGroup7.add(jRadioButton29); jRadioButton29.setText("jRadioButton29"); buttonGroup7.add(jRadioButton30); jRadioButton30.setText("jRadioButton30"); buttonGroup8.add(jRadioButton31); jRadioButton31.setText("jRadioButton31"); jRadioButton31.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup8.add(jRadioButton32); jRadioButton32.setText("jRadioButton32"); buttonGroup8.add(jRadioButton33); jRadioButton33.setText("jRadioButton33"); buttonGroup8.add(jRadioButton34); jRadioButton34.setText("jRadioButton34"); buttonGroup8.add(jRadioButton35); jRadioButton35.setText("jRadioButton35"); buttonGroup9.add(jRadioButton36); jRadioButton36.setText("jRadioButton36"); jRadioButton36.setPreferredSize(new java.awt.Dimension(100, 23)); buttonGroup9.add(jRadioButton37); jRadioButton37.setText("jRadioButton37"); buttonGroup9.add(jRadioButton38); jRadioButton38.setText("jRadioButton38"); buttonGroup9.add(jRadioButton39); jRadioButton39.setText("jRadioButton39"); buttonGroup9.add(jRadioButton40); jRadioButton40.setText("jRadioButton40"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Question1_Label) .addComponent(Question3_Label) .addComponent(Question4_Label) .addComponent(Question2_Label) .addComponent(Question7_Label) .addComponent(Question8_Label)) .addGap(75, 75, 75) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Question8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Question7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Question6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Question5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Question4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Question3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Question2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Question1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(1, 1, 1)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jRadioButton6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(54, 54, 54) .addComponent(jRadioButton7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jRadioButton26, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton31, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(jRadioButton27)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(jRadioButton32)))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jRadioButton36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(53, 53, 53) .addComponent(jRadioButton37)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jRadioButton21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(53, 53, 53) .addComponent(jRadioButton22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(53, 53, 53) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton33, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jRadioButton38, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(54, 54, 54) .addComponent(jRadioButton23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(54, 54, 54) .addComponent(jRadioButton28)))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton16) .addComponent(jRadioButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton11)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(jRadioButton17)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(jRadioButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(52, 52, 52) .addComponent(jRadioButton12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(53, 53, 53) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton18) .addComponent(jRadioButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton13)))) .addGap(53, 53, 53) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton14) .addComponent(jRadioButton9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton19) .addComponent(jRadioButton24) .addComponent(jRadioButton29) .addComponent(jRadioButton34) .addComponent(jRadioButton39) .addComponent(jRadioButton4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(52, 52, 52))) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Question5_Label) .addComponent(Question6_Label)) .addGap(42, 42, 42))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton25) .addComponent(jRadioButton20) .addComponent(jRadioButton30) .addComponent(jRadioButton35) .addComponent(jRadioButton40) .addComponent(jRadioButton15) .addComponent(jRadioButton10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(139, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(29, 29, 29) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Question1_Label) .addComponent(Question1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Question2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Question2_Label)) .addGap(19, 19, 19) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton10, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Question3_Label) .addComponent(Question3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton11) .addComponent(jRadioButton12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton13) .addComponent(jRadioButton14) .addComponent(jRadioButton15)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Question4_Label) .addComponent(Question4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton16) .addComponent(jRadioButton17) .addComponent(jRadioButton18) .addComponent(jRadioButton19) .addComponent(jRadioButton20)) .addGap(17, 17, 17) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Question5_Label) .addComponent(Question5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton21, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton22, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton23, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton24) .addComponent(jRadioButton25)) .addGap(19, 19, 19) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Question6_Label) .addComponent(Question6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton26, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton27) .addComponent(jRadioButton28) .addComponent(jRadioButton29) .addComponent(jRadioButton30)) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(Question7_Label) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton33) .addComponent(jRadioButton34) .addComponent(jRadioButton35))) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(Question7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton31, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton32)))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(Question8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton36, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jRadioButton37) .addComponent(jRadioButton38) .addComponent(jRadioButton39) .addComponent(jRadioButton40))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(Question8_Label))) .addContainerGap(54, Short.MAX_VALUE)) ); jScrollPane13.setViewportView(jPanel1); EmpFeedback_Home_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N EmpFeedback_Home_Btn.setText("Home"); EmpFeedback_Home_Btn.setPreferredSize(new java.awt.Dimension(65, 30)); EmpFeedback_Home_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EmpFeedback_Home_BtnActionPerformed(evt); } }); EmpFeedback_Home_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { EmpFeedback_Home_BtnKeyReleased(evt); } }); EmpFeedback_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N EmpFeedback_Label.setText("EMPLOYEE FEEDBACK"); javax.swing.GroupLayout FeedbackFrameLayout = new javax.swing.GroupLayout(FeedbackFrame.getContentPane()); FeedbackFrame.getContentPane().setLayout(FeedbackFrameLayout); FeedbackFrameLayout.setHorizontalGroup( FeedbackFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(FeedbackFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(FeedbackFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EmpFeedback_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane12, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(FeedbackFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(FeedbackFrameLayout.createSequentialGroup() .addGap(277, 277, 277) .addComponent(EmpFeedback_Label)) .addGroup(FeedbackFrameLayout.createSequentialGroup() .addGap(57, 57, 57) .addComponent(jScrollPane13, javax.swing.GroupLayout.PREFERRED_SIZE, 910, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(86, Short.MAX_VALUE)) ); FeedbackFrameLayout.setVerticalGroup( FeedbackFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(FeedbackFrameLayout.createSequentialGroup() .addGroup(FeedbackFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(EmpFeedback_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(EmpFeedback_Label)) .addGap(29, 29, 29) .addGroup(FeedbackFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane12, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane13, javax.swing.GroupLayout.PREFERRED_SIZE, 670, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(142, Short.MAX_VALUE)) ); desktopPane.add(FeedbackFrame); FeedbackFrame.setBounds(0, 0, 1300, 900); ResultFrame.setPreferredSize(new java.awt.Dimension(1000, 400)); ResultFrame.setVisible(true); Result_Table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null}, {null, null, null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4", "Title 5", "Title 6" } )); jScrollPane14.setViewportView(Result_Table); Results_label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N Results_label.setText("RESULTS"); Results_Home_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Results_Home_Btn.setText("Home"); Results_Home_Btn.setPreferredSize(new java.awt.Dimension(70, 30)); Results_Home_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Results_Home_BtnActionPerformed(evt); } }); Results_Home_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Results_Home_BtnKeyReleased(evt); } }); Results_StudentName_Lbl.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N Results_StudentName_Lbl.setText("STUDENT NAME"); Results_Subject_Lbl.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N Results_Subject_Lbl.setText("SUBJECT"); jComboBox2.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBox2ItemStateChanged(evt); } }); Results_Search_Btn.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N Results_Search_Btn.setText("Search"); Results_Search_Btn.setPreferredSize(new java.awt.Dimension(75, 30)); Results_Search_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Results_Search_BtnActionPerformed(evt); } }); Results_Search_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Results_Search_BtnKeyReleased(evt); } }); javax.swing.GroupLayout ResultFrameLayout = new javax.swing.GroupLayout(ResultFrame.getContentPane()); ResultFrame.getContentPane().setLayout(ResultFrameLayout); ResultFrameLayout.setHorizontalGroup( ResultFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ResultFrameLayout.createSequentialGroup() .addGroup(ResultFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(ResultFrameLayout.createSequentialGroup() .addContainerGap() .addComponent(Results_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(297, 297, 297) .addComponent(Results_label) .addGap(0, 490, Short.MAX_VALUE)) .addComponent(jScrollPane14)) .addContainerGap()) .addGroup(ResultFrameLayout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(Results_StudentName_Lbl, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(77, 77, 77) .addComponent(Results_Subject_Lbl) .addGap(18, 18, 18) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Results_Search_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(128, 128, 128)) ); ResultFrameLayout.setVerticalGroup( ResultFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ResultFrameLayout.createSequentialGroup() .addGroup(ResultFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Results_label) .addComponent(Results_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(41, 41, 41) .addGroup(ResultFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Results_StudentName_Lbl) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Results_Subject_Lbl) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Results_Search_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane14, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE) .addGap(31, 31, 31)) ); desktopPane.add(ResultFrame); ResultFrame.setBounds(0, 0, 1000, 400); AddLessonPictureFrame.setVisible(true); AddLessonPicture_Label.setBorder(javax.swing.BorderFactory.createEtchedBorder()); AddLessonPicture_Label.setPreferredSize(new java.awt.Dimension(600, 400)); AddLessonPicture_Add_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N AddLessonPicture_Add_Btn.setText("Add"); AddLessonPicture_Add_Btn.setPreferredSize(new java.awt.Dimension(70, 30)); AddLessonPicture_Add_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddLessonPicture_Add_BtnActionPerformed(evt); } }); AddLessonPicture_Add_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { AddLessonPicture_Add_BtnKeyReleased(evt); } }); AddLessonPicture_Back_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N AddLessonPicture_Back_Btn.setText("Back"); AddLessonPicture_Back_Btn.setPreferredSize(new java.awt.Dimension(70, 30)); AddLessonPicture_Back_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddLessonPicture_Back_BtnActionPerformed(evt); } }); AddLessonPicture_Back_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { AddLessonPicture_Back_BtnKeyReleased(evt); } }); AddLessonPicture_Upload_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N AddLessonPicture_Upload_Btn.setText("Upload"); AddLessonPicture_Upload_Btn.setPreferredSize(new java.awt.Dimension(71, 30)); AddLessonPicture_Upload_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AddLessonPicture_Upload_BtnActionPerformed(evt); } }); AddLessonPicture_Upload_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { AddLessonPicture_Upload_BtnKeyReleased(evt); } }); javax.swing.GroupLayout AddLessonPictureFrameLayout = new javax.swing.GroupLayout(AddLessonPictureFrame.getContentPane()); AddLessonPictureFrame.getContentPane().setLayout(AddLessonPictureFrameLayout); AddLessonPictureFrameLayout.setHorizontalGroup( AddLessonPictureFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AddLessonPictureFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(AddLessonPictureFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, AddLessonPictureFrameLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(AddLessonPicture_Label, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(AddLessonPictureFrameLayout.createSequentialGroup() .addComponent(AddLessonPicture_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) .addGroup(AddLessonPictureFrameLayout.createSequentialGroup() .addGap(140, 140, 140) .addComponent(AddLessonPicture_Upload_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(AddLessonPicture_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(113, 113, 113)) ); AddLessonPictureFrameLayout.setVerticalGroup( AddLessonPictureFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(AddLessonPictureFrameLayout.createSequentialGroup() .addContainerGap() .addComponent(AddLessonPicture_Back_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(27, 27, 27) .addComponent(AddLessonPicture_Label, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(46, 46, 46) .addGroup(AddLessonPictureFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(AddLessonPicture_Upload_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(AddLessonPicture_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(54, Short.MAX_VALUE)) ); desktopPane.add(AddLessonPictureFrame); AddLessonPictureFrame.setBounds(0, 0, 636, 631); DictionaryFrame.setPreferredSize(new java.awt.Dimension(780, 470)); DictionaryFrame.setVisible(true); Dictionary_Word_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Dictionary_Word_Label.setText("WORD"); Dictionary_Meaning_Label.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N Dictionary_Meaning_Label.setText("MEANING"); Dictionary_Meaning_Textarea.setColumns(20); Dictionary_Meaning_Textarea.setRows(5); Dictionary_Meaning_Textarea.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Dictionary_Meaning_TextareaKeyReleased(evt); } }); jScrollPane4.setViewportView(Dictionary_Meaning_Textarea); Dictionary_Add_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Dictionary_Add_Btn.setText("Add"); Dictionary_Add_Btn.setPreferredSize(new java.awt.Dimension(80, 30)); Dictionary_Add_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Dictionary_Add_BtnActionPerformed(evt); } }); Dictionary_Add_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Dictionary_Add_BtnKeyReleased(evt); } }); Dictionary_Update_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Dictionary_Update_Btn.setText("Update"); Dictionary_Update_Btn.setPreferredSize(new java.awt.Dimension(80, 30)); Dictionary_Update_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Dictionary_Update_BtnActionPerformed(evt); } }); Dictionary_Update_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Dictionary_Update_BtnKeyReleased(evt); } }); Dictionary_Delete_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Dictionary_Delete_Btn.setText("Delete"); Dictionary_Delete_Btn.setPreferredSize(new java.awt.Dimension(80, 30)); Dictionary_Delete_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Dictionary_Delete_BtnActionPerformed(evt); } }); Dictionary_Delete_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Dictionary_Delete_BtnKeyReleased(evt); } }); Dictionary_Table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null} }, new String [] { "Title 1", "Title 2" } )); Dictionary_Table.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { Dictionary_TableMouseClicked(evt); } }); Dictionary_Table.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Dictionary_TableKeyReleased(evt); } }); jScrollPane5.setViewportView(Dictionary_Table); Dictionary_Label.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N Dictionary_Label.setText("DICTIONARY"); Dictionary_Home_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Dictionary_Home_Btn.setText("Home"); Dictionary_Home_Btn.setPreferredSize(new java.awt.Dimension(80, 30)); Dictionary_Home_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Dictionary_Home_BtnActionPerformed(evt); } }); Dictionary_Home_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Dictionary_Home_BtnKeyReleased(evt); } }); javax.swing.GroupLayout DictionaryFrameLayout = new javax.swing.GroupLayout(DictionaryFrame.getContentPane()); DictionaryFrame.getContentPane().setLayout(DictionaryFrameLayout); DictionaryFrameLayout.setHorizontalGroup( DictionaryFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(DictionaryFrameLayout.createSequentialGroup() .addGroup(DictionaryFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(DictionaryFrameLayout.createSequentialGroup() .addGap(25, 25, 25) .addGroup(DictionaryFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(DictionaryFrameLayout.createSequentialGroup() .addComponent(Dictionary_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(58, 58, 58) .addComponent(Dictionary_Update_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(Dictionary_Word_Label) .addComponent(Dictionary_Meaning_Label) .addComponent(Dictionary_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane4) .addComponent(Dictionary_Word_Textfield))) .addGroup(DictionaryFrameLayout.createSequentialGroup() .addGap(89, 89, 89) .addComponent(Dictionary_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE) .addGroup(DictionaryFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Dictionary_Label)) .addContainerGap()) ); DictionaryFrameLayout.setVerticalGroup( DictionaryFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(DictionaryFrameLayout.createSequentialGroup() .addContainerGap() .addGroup(DictionaryFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Dictionary_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Dictionary_Label)) .addGap(26, 26, 26) .addGroup(DictionaryFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(DictionaryFrameLayout.createSequentialGroup() .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 6, Short.MAX_VALUE)) .addGroup(DictionaryFrameLayout.createSequentialGroup() .addGap(11, 11, 11) .addComponent(Dictionary_Word_Label) .addGap(18, 18, 18) .addComponent(Dictionary_Word_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Dictionary_Meaning_Label) .addGap(18, 18, 18) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(36, 36, 36) .addGroup(DictionaryFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Dictionary_Add_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Dictionary_Update_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(33, 33, 33) .addComponent(Dictionary_Delete_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); desktopPane.add(DictionaryFrame); DictionaryFrame.setBounds(0, 0, 780, 470); SettingsFrame.setPreferredSize(new java.awt.Dimension(550, 525)); SettingsFrame.setVisible(true); Settings_Label.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N Settings_Label.setText("SETTINGS"); Settings_DBUserName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Settings_DBUserName.setText("DATABASE USER NAME "); Settings_DBPassword.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Settings_DBPassword.setText("<PASSWORD>"); Settings_DBUserName_Textfield.setPreferredSize(new java.awt.Dimension(164, 25)); Settings_DBPassword_Textfield.setPreferredSize(new java.awt.Dimension(164, 25)); Settings_Save_Btn.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N Settings_Save_Btn.setText("Save"); Settings_Save_Btn.setPreferredSize(new java.awt.Dimension(60, 30)); Settings_Save_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Settings_Save_BtnActionPerformed(evt); } }); Settings_Save_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Settings_Save_BtnKeyReleased(evt); } }); Settings_ServerName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Settings_ServerName.setText("SERVER NAME"); Settings_DatabaseName.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Settings_DatabaseName.setText("DATABASE NAME "); Settings_ServerAddress.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Settings_ServerAddress.setText("SERVER ADDRESS "); Settings_ServerName_Textfield.setPreferredSize(new java.awt.Dimension(164, 25)); Settings_ServerAddress_Textfield.setPreferredSize(new java.awt.Dimension(164, 25)); Settings_DatabaseName_Textfield.setPreferredSize(new java.awt.Dimension(164, 25)); Settings_Home_Btn.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N Settings_Home_Btn.setText("Home"); Settings_Home_Btn.setPreferredSize(new java.awt.Dimension(65, 30)); Settings_Home_Btn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { Settings_Home_BtnActionPerformed(evt); } }); Settings_Home_Btn.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { Settings_Home_BtnKeyReleased(evt); } }); javax.swing.GroupLayout SettingsFrameLayout = new javax.swing.GroupLayout(SettingsFrame.getContentPane()); SettingsFrame.getContentPane().setLayout(SettingsFrameLayout); SettingsFrameLayout.setHorizontalGroup( SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SettingsFrameLayout.createSequentialGroup() .addGroup(SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SettingsFrameLayout.createSequentialGroup() .addComponent(Settings_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(122, 122, 122) .addComponent(Settings_Label)) .addGroup(SettingsFrameLayout.createSequentialGroup() .addGap(64, 64, 64) .addGroup(SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Settings_ServerName) .addComponent(Settings_DatabaseName) .addComponent(Settings_ServerAddress) .addComponent(Settings_DBUserName) .addComponent(Settings_DBPassword)) .addGap(120, 120, 120) .addGroup(SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Settings_DBPassword_Textfield, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(Settings_DBUserName_Textfield, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Settings_Save_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Settings_DatabaseName_Textfield, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Settings_ServerAddress_Textfield, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Settings_ServerName_Textfield, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); SettingsFrameLayout.setVerticalGroup( SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(SettingsFrameLayout.createSequentialGroup() .addGroup(SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Settings_Home_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Settings_Label)) .addGap(32, 32, 32) .addGroup(SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Settings_ServerName) .addComponent(Settings_ServerName_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(44, 44, 44) .addGroup(SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Settings_ServerAddress_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Settings_ServerAddress)) .addGap(45, 45, 45) .addGroup(SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Settings_DatabaseName) .addComponent(Settings_DatabaseName_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE) .addGroup(SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Settings_DBUserName) .addComponent(Settings_DBUserName_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(60, 60, 60) .addGroup(SettingsFrameLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Settings_DBPassword) .addComponent(Settings_DBPassword_Textfield, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(50, 50, 50) .addComponent(Settings_Save_Btn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(28, 28, 28)) ); desktopPane.add(SettingsFrame); SettingsFrame.setBounds(0, 0, 550, 525); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1253, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1172, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void ArabicAllText() { //Login Screen UserLogin_Label.setText("الدخول"); UserLogin_Name_Label.setText("<NAME>"); UserLogin_Password_Label.setText("<PASSWORD>"); UserLogin_Login_Btn.setText("الدخول"); UserLogin_ForgetPwd_Btn.setText("نسيت كلمة"); //Home screen Home_label.setText("منزل"); Home_UsrMngt_Btn.setText("إدارةالمستخدم"); Home_Subject_Btn.setText("مواضيع"); Home_ChangePwd_Btn.setText("<PASSWORD>"); Home_Results_Btn.setText("النتيجة"); Home_ViewSugg_Btn.setText("عرض الاقتراحات"); Home_Dictionary_Btn.setText("المصطلحات"); Home_EmployeeFeedback_Btn.setText("آراء الموظفين"); Home_Settings_Btn.setText("إعدادات"); Home_Logout_Btn.setText("خروج"); //User Management screen UsMng_label.setText("إدارةالمستخدم"); UsMng_Home_Btn.setText("منزل"); UsMng_Name_Label.setText("<NAME>"); UsMng_Email_Label.setText("البريد الالكتروني"); UsMng_Delete_Btn.setText("حذف"); UsMng_Update_Btn.setText("تحديث"); //Subject Screen Sub_Label.setText("الموضوع"); Sub_Home_Btn.setText("الرئيسية"); active.setText("نشط"); inactive.setText("غير نشط"); Sub_Status_Btn.setText("حالة التحديث"); Sub_Add_Btn.setText("إضافة"); Sub_Delete_Btn.setText("حذف"); Sub_Enter_Btn.setText("أدخل"); //Add Subject screen AddSub_Label.setText("إضافة الموضوع"); AddSub_Back_Btn.setText("الى الخلف"); AddSub_Name_Label.setText("اسم الموضوع"); AddSub_Add_Btn.setText("إضافة"); //lessons screen Ls_Label.setText("الى الخلف"); Ls_Back_Btn.setText("الى الخلف"); Ls_Add_Btn.setText("إضافة"); Ls_Delete_Btn.setText("حذف"); Ls_Enter_Btn.setText("أدخل"); Ls_Marks_Btn.setText("علامات الطلاب"); //Add lesson screen AddLs_Label.setText("إضافة الدرس"); AddLs_Back_Btn.setText("الى الخلف"); AddLs_Name_Label.setText("إضافة الدرس"); AddLs_Submit_Btn.setText("تقديم"); //Marks details screen StDetails_Label.setText("تفاصيل طالب"); StDetails_Back_Btn.setText("الى الخلف"); //Lesson Image screen Ls_Image_Back_Btn.setText("الى الخلف"); LsImage_AddImage_Btn.setText("إضافة صورة"); LsImage_Delete_Btn.setText("حذف صورة"); LsImage_Questions_Btn.setText("الأسئلة"); //Add Lesson Image screen AddLessonPicture_Back_Btn.setText("الى الخلف"); AddLessonPicture_Upload_Btn.setText("تحميل"); AddLessonPicture_Add_Btn.setText("إضافة"); //Questions screen Qst_Label.setText("الأسئلة "); Qst_Back_Btn.setText("الى الخلف"); Qst_Update_Btn.setText("تحديث"); Qst_Add_Btn.setText("إضافة"); Qst_Delete_Btn.setText("حذف"); //Change Password screen ChangePwd_Label.setText("تغيير كلمة السر"); ChangePwd_Home_Btn.setText("الرئيسية"); ChangePwd_NewPwd_Label.setText("كلمة السر الجديدة"); ChangePwd_ConfPwd_Label.setText("تاكيد الرقم السري"); ChangePwd_Submit_Btn.setText("تقديم"); //Results screen Results_label.setText("النتائج"); Results_Home_Btn.setText("الرئيسية"); Results_StudentName_Lbl.setText("أ<NAME>"); Results_Subject_Lbl.setText("مواضيع"); Results_Search_Btn.setText("بحث"); //Suggestions screen ViewSug_Label.setText("ملاحظاتكم تهمنا"); ViewSug_Home_Btn.setText("الرئيسية"); ViewSug_Subject_Label.setText("الموضوع"); ViewSug_Suggestion_Label.setText("ملاحظاتكم تهمنا"); //Dictionary screen Dictionary_Label.setText("المصطلحات"); Dictionary_Home_Btn.setText("الرئيسية"); Dictionary_Word_Label.setText("كلمة"); Dictionary_Meaning_Label.setText("معنى"); Dictionary_Add_Btn.setText("إضافة"); Dictionary_Update_Btn.setText("تحديث"); Dictionary_Delete_Btn.setText("حذف"); //Feedback screen EmpFeedback_Label.setText("آراء الموظفين"); EmpFeedback_Home_Btn.setText("الرئيسية"); Question1_Label.setText("1 سؤال"); Question2_Label.setText("2 سؤال"); Question3_Label.setText("3 سؤال"); Question4_Label.setText("4 سؤال"); Question5_Label.setText("5 سؤال"); Question6_Label.setText("6 سؤال"); Question7_Label.setText("7 سؤال"); Question8_Label.setText("8 سؤال"); Question1.setText("8 سؤال"); Question2.setText("8 سؤال"); Question3.setText("8 سؤال"); Question4.setText("8 سؤال"); Question5.setText("8 سؤال"); Question6.setText("8 سؤال"); Question7.setText("8 سؤال"); Question8.setText("8 سؤال"); //Answer 1 options jRadioButton1.setText("8 سؤال"); jRadioButton2.setText("7 سؤال"); jRadioButton3.setText("6 سؤال"); jRadioButton4.setText("5 سؤال"); jRadioButton5.setText("4سؤال "); //Answer 2 options jRadioButton6.setText("سؤال"); jRadioButton7.setText("سؤال"); jRadioButton8.setText("سؤال"); jRadioButton9.setText("سؤال"); jRadioButton10.setText("سؤال"); //Answer 3 options jRadioButton11.setText("سؤال"); jRadioButton12.setText("سؤال"); jRadioButton13.setText("سؤال"); jRadioButton14.setText("سؤال"); jRadioButton15.setText("سؤال"); //Answer 4 options jRadioButton16.setText("سؤال"); jRadioButton17.setText("سؤال"); jRadioButton18.setText("سؤال"); jRadioButton19.setText("سؤال"); jRadioButton20.setText("سؤال"); //Answer 5 options jRadioButton21.setText("سؤال"); jRadioButton22.setText("سؤال"); jRadioButton23.setText("سؤال"); jRadioButton24.setText("سؤال"); jRadioButton25.setText("سؤال"); //Answer 6 options jRadioButton26.setText("سؤال"); jRadioButton27.setText("سؤال"); jRadioButton28.setText("سؤال"); jRadioButton29.setText("سؤال"); jRadioButton30.setText("سؤال"); //Answer 7 options jRadioButton31.setText("سؤال"); jRadioButton32.setText("سؤال"); jRadioButton33.setText("سؤال"); jRadioButton34.setText("سؤال"); jRadioButton35.setText("سؤال"); //Answer 8 options jRadioButton36.setText("سؤال"); jRadioButton37.setText("سؤال"); jRadioButton38.setText("سؤال"); jRadioButton39.setText("سؤال"); jRadioButton40.setText("سؤال"); //Settings screen Settings_Label.setText("إعدادات"); Settings_Home_Btn.setText("الرئيسية"); Settings_ServerName.setText("اسم الخادم"); Settings_ServerAddress.setText("عنوان المستقبل"); Settings_DatabaseName.setText("اسم قاعدة البيانات"); Settings_DBUserName.setText("اسم المستخدم قاعدة البيانات "); Settings_DBPassword.setText("<PASSWORD>"); Settings_Save_Btn.setText("حفظ"); } private void EnglishAllText() { //Login Screen UserLogin_Label.setText("LOGIN"); UserLogin_Name_Label.setText("USER NAME"); UserLogin_Password_Label.setText("<PASSWORD>"); UserLogin_Login_Btn.setText("Login"); UserLogin_ForgetPwd_Btn.setText("Forget Password"); //Home screen Home_label.setText("HOME"); Home_UsrMngt_Btn.setText("USER MANAGEMENT"); Home_Subject_Btn.setText("SUBJECT"); Home_ChangePwd_Btn.setText("CHANGE PASSWORD"); Home_Results_Btn.setText("RESULTS"); Home_ViewSugg_Btn.setText("VIEW SUGGESTIONS"); Home_Dictionary_Btn.setText("DICTIONARY"); Home_EmployeeFeedback_Btn.setText("EMPLOYEE FEEDBACK"); Home_Settings_Btn.setText("SETTINGS"); Home_Logout_Btn.setText("LOGOUT"); //User Management screen UsMng_label.setText("USER MANAGEMENT"); UsMng_Home_Btn.setText("Home"); UsMng_Name_Label.setText("<NAME>"); UsMng_Email_Label.setText("EMAIL"); UsMng_Delete_Btn.setText("Delete"); UsMng_Update_Btn.setText("Update"); //Subject Screen Sub_Label.setText("SUBJECTS"); Sub_Home_Btn.setText("Home"); active.setText("active"); inactive.setText("inactive"); Sub_Status_Btn.setText("Update Status"); Sub_Add_Btn.setText("Add"); Sub_Delete_Btn.setText("Delete"); Sub_Enter_Btn.setText("Enter"); //Add Subject screen AddSub_Label.setText("ADD SUBJECTS"); AddSub_Back_Btn.setText("Back"); AddSub_Name_Label.setText("SUBJECT NAME"); AddSub_Add_Btn.setText("Add"); //lessons screen Ls_Label.setText("LESSONS"); Ls_Back_Btn.setText("Back"); Ls_Add_Btn.setText("Add"); Ls_Delete_Btn.setText("Delete"); Ls_Enter_Btn.setText("Enter"); Ls_Marks_Btn.setText("Students Marks"); //Add lesson screen AddLs_Label.setText("ADD LESSONS"); AddLs_Back_Btn.setText("Back"); AddLs_Name_Label.setText("LESSON NAME"); AddLs_Submit_Btn.setText("Submit"); //Marks details screen StDetails_Label.setText("STUDENT DETAILS"); StDetails_Back_Btn.setText("Back"); //Lesson Image screen Ls_Image_Back_Btn.setText("Back"); LsImage_AddImage_Btn.setText("Add Image"); LsImage_Delete_Btn.setText("Delete Image"); LsImage_Questions_Btn.setText("Questions"); //Add Lesson Image screen AddLessonPicture_Back_Btn.setText("Back"); AddLessonPicture_Upload_Btn.setText("Upload"); AddLessonPicture_Add_Btn.setText("Add"); //Questions screen Qst_Label.setText("QUESTIONS"); Qst_Back_Btn.setText("Back"); Qst_Update_Btn.setText("Update"); Qst_Add_Btn.setText("Add"); Qst_Delete_Btn.setText("Delete"); //Change Password screen ChangePwd_Label.setText("CHANGE PASSWORD"); ChangePwd_Home_Btn.setText("Home"); ChangePwd_NewPwd_Label.setText("NEW PASSWORD"); ChangePwd_ConfPwd_Label.setText("CONFIRM PASSWORD"); ChangePwd_Submit_Btn.setText("Submit"); //Results screen Results_label.setText("RESULTS"); Results_Home_Btn.setText("Home"); Results_StudentName_Lbl.setText("STUDENT NAME"); Results_Subject_Lbl.setText("SUBJECT"); Results_Search_Btn.setText("Search"); //Suggestions screen ViewSug_Label.setText("SUGGESTIONS"); ViewSug_Home_Btn.setText("Home"); ViewSug_Subject_Label.setText("SUBJECT"); ViewSug_Suggestion_Label.setText("SUGGESTION"); //Dictionary screen Dictionary_Label.setText("DICTIONARY"); Dictionary_Home_Btn.setText("Home"); Dictionary_Word_Label.setText("WORD"); Dictionary_Meaning_Label.setText("MEANING"); Dictionary_Add_Btn.setText("Add"); Dictionary_Update_Btn.setText("Update"); Dictionary_Delete_Btn.setText("Delete"); //Feedback screen EmpFeedback_Label.setText("EMPLOYEE FEEDBACK"); EmpFeedback_Home_Btn.setText("Home"); Question1_Label.setText("Question 1"); Question2_Label.setText("Question 2"); Question3_Label.setText("Question 3"); Question4_Label.setText("Question 4"); Question5_Label.setText("Question 5"); Question6_Label.setText("Question 6"); Question7_Label.setText("Question 7"); Question8_Label.setText("Question 8"); Question1.setText("Question 1"); Question2.setText("Question 2"); Question3.setText("Question 3"); Question4.setText("Question 4"); Question5.setText("Question 5"); Question6.setText("Question 6"); Question7.setText("Question 7"); Question8.setText("Question 8"); //Answer 1 options jRadioButton1.setText("Excellent"); jRadioButton2.setText("Good"); jRadioButton3.setText("Average"); jRadioButton4.setText("Below Average"); jRadioButton5.setText("Poor"); //Answer 2 options jRadioButton6.setText("Excellent"); jRadioButton7.setText("Good"); jRadioButton8.setText("Average"); jRadioButton9.setText("Below Average"); jRadioButton10.setText("Poor"); //Answer 3 options jRadioButton11.setText("Excellent"); jRadioButton12.setText("Good"); jRadioButton13.setText("Average"); jRadioButton14.setText("Below Average"); jRadioButton15.setText("Poor"); //Answer 4 options jRadioButton16.setText("Excellent"); jRadioButton17.setText("Good"); jRadioButton18.setText("Average"); jRadioButton19.setText("Below Average"); jRadioButton20.setText("Poor"); //Answer 5 options jRadioButton21.setText("Excellent"); jRadioButton22.setText("Good"); jRadioButton23.setText("Average"); jRadioButton24.setText("Below Average"); jRadioButton25.setText("Poor"); //Answer 6 options jRadioButton26.setText("Excellent"); jRadioButton27.setText("Good"); jRadioButton28.setText("Average"); jRadioButton29.setText("Below Average"); jRadioButton30.setText("Poor"); //Answer 7 options jRadioButton31.setText("Excellent"); jRadioButton32.setText("Good"); jRadioButton33.setText("Average"); jRadioButton34.setText("Below Average"); jRadioButton35.setText("Poor"); //Answer 8 options jRadioButton36.setText("Excellent"); jRadioButton37.setText("Good"); jRadioButton38.setText("Average"); jRadioButton39.setText("Below Average"); jRadioButton40.setText("poor"); //Settings screen Settings_Label.setText("SETTINGS"); Settings_Home_Btn.setText("Home"); Settings_ServerName.setText("SERVER NAME"); Settings_ServerAddress.setText("SERVER ADDRESS "); Settings_DatabaseName.setText("DATABASE NAME "); Settings_DBUserName.setText("DATABASE USERNAME "); Settings_DBPassword.setText("<PASSWORD>"); Settings_Save_Btn.setText("Save"); } private void Populate_FeedbackDetails() { try { pst = con.prepareStatement("select employee_id as ID,employee_name as 'Employee Name',examination_date,answer1,answer2,answer3,answer4,answer5,answer6,answer7,answer8 from feedbacktable"); createComponents(); rs = pst.executeQuery(); feedbackTable.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); feedbackTable.setModel(DbUtils.resultSetToTableModel(rs)); for (int a = 2; a <= 10; a++) { feedbackTable.getColumnModel().getColumn(a).setMinWidth(0); feedbackTable.getColumnModel().getColumn(a).setMaxWidth(0); } if (Arabic_lang.isSelected()) { feedbackTable.getColumnModel().getColumn(0).setHeaderValue("هوية شخصية"); feedbackTable.getColumnModel().getColumn(1).setHeaderValue("اسم الموظف"); } } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } killDialog(); } private void Populate_LessonPictures() { try { createComponents(); pst = con.prepareStatement("select id as Id,lesson_id as 'Lesson Id' ,image as Images from lesson_image where lesson_id=" + selectedlesson); rs = pst.executeQuery(); try { Ls_Image_Table.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); Ls_Image_Table.setModel(DbUtils.resultSetToTableModel(rs)); for (int i = 0; i < 2; i++) { Ls_Image_Table.getColumnModel().getColumn(i).setMinWidth(0); Ls_Image_Table.getColumnModel().getColumn(i).setMaxWidth(0); } if (Arabic_lang.isSelected()) { Ls_Image_Table.getColumnModel().getColumn(2).setHeaderValue("صور"); } } catch (Exception ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } killDialog(); } private void Populate_Checkboxes() { String sqlStudent = "select student_name from students"; String sqlSubject = "select subject_name from subject"; jComboBox1.removeAllItems(); jComboBox2.removeAllItems(); jComboBox1.addItem(""); jComboBox2.addItem(""); try { pst = con.prepareStatement(sqlStudent); rs = pst.executeQuery(sqlStudent); while (rs.next()) { jComboBox1.addItem(rs.getString("student_name")); } pst1 = con.prepareStatement(sqlSubject); rs1 = pst1.executeQuery(sqlSubject); while (rs1.next()) { jComboBox2.addItem(rs1.getString("subject_name")); } } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } } private void Populate_Results() { try { createComponents(); String wquery = ""; if (jComboBox1.getSelectedItem() != null && jComboBox1.getSelectedItem() != "") { if (jComboBox2.getSelectedItem() != null && jComboBox2.getSelectedItem() != "") { wquery = " where st.student_name='" + jComboBox1.getSelectedItem() + "' and sub.subject_name='" + jComboBox2.getSelectedItem() + "'"; } else { wquery = " where st.student_name='" + jComboBox1.getSelectedItem() + "'"; } } else if (jComboBox2.getSelectedItem() != null && jComboBox2.getSelectedItem() != "") { wquery = " where sub.subject_name='" + jComboBox2.getSelectedItem() + "'"; } String sql = "select st.student_name as 'Student Name',sub.subject_name as Subject, ls.lesson_name as Lesson,rlt.marks as Marks, rlt.passing_date as Date, rlt.result as Result from results rlt " + "INNER JOIN students st ON rlt.student_id=st.student_id " + "INNER JOIN subject sub ON rlt.subject_id=sub.subject_id " + "INNER JOIN lessons ls ON rlt.lesson_id=ls.lesson_id " + wquery; pst = con.prepareStatement(sql); rs = pst.executeQuery(sql); Result_Table.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); Result_Table.setModel(DbUtils.resultSetToTableModel(rs)); if (Arabic_lang.isSelected()) { Result_Table.getColumnModel().getColumn(0).setHeaderValue("أسم الطالب"); Result_Table.getColumnModel().getColumn(1).setHeaderValue("الموضوع"); Result_Table.getColumnModel().getColumn(2).setHeaderValue("الى الخلف"); Result_Table.getColumnModel().getColumn(3).setHeaderValue("علامات"); Result_Table.getColumnModel().getColumn(4).setHeaderValue("تاريخ"); Result_Table.getColumnModel().getColumn(5).setHeaderValue("النتيجة"); } killDialog(); Populate_Checkboxes(); } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } } private void Populate_Dictionary() { try { wordList.clear(); pst = con.prepareStatement("select id as Id ,word as Word,meaning as Meaning from worddictionary"); pst1 = con.prepareStatement("select word from worddictionary"); createComponents(); rs = pst.executeQuery(); Dictionary_Table.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); Dictionary_Table.setModel(DbUtils.resultSetToTableModel(rs)); Dictionary_Table.getColumnModel().getColumn(0).setMinWidth(0); Dictionary_Table.getColumnModel().getColumn(0).setMaxWidth(0); if (Arabic_lang.isSelected()) { Dictionary_Table.getColumnModel().getColumn(1).setHeaderValue("كلمة"); Dictionary_Table.getColumnModel().getColumn(2).setHeaderValue("معنى"); } rs.close(); rs1 = pst.executeQuery(); while (rs1.next()) { wordList.add(rs1.getString("word")); } rs1.close(); killDialog(); } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } } private void Populate_Subject() { try { createComponents(); pst = con.prepareStatement("select subject_id as Id,subject_name as Subject,status as Status from subject"); rs = pst.executeQuery(); Sub_Table.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); Sub_Table.setModel(DbUtils.resultSetToTableModel(rs)); Sub_Table.getColumnModel().getColumn(0).setMinWidth(0); Sub_Table.getColumnModel().getColumn(0).setMaxWidth(0); Sub_Table.getColumnModel().getColumn(2).setMinWidth(0); Sub_Table.getColumnModel().getColumn(2).setMaxWidth(0); if (Arabic_lang.isSelected()) { Sub_Table.getColumnModel().getColumn(1).setHeaderValue("الموضوع"); } buttonGroup10.clearSelection(); } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } killDialog(); } private void Populate_Lessons() { try { createComponents(); pst = con.prepareStatement("select lesson_id as Id,lesson_name as Lessons from lessons where subject_id=" + subject); rs = pst.executeQuery(); Ls_Table.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); Ls_Table.setModel(DbUtils.resultSetToTableModel(rs)); Ls_Table.getColumnModel().getColumn(0).setMinWidth(0); Ls_Table.getColumnModel().getColumn(0).setMaxWidth(0); if (Arabic_lang.isSelected()) { Ls_Table.getColumnModel().getColumn(1).setHeaderValue("الى الخلف"); } } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } killDialog(); } private void Populate_Students() { try { createComponents(); pst = con.prepareStatement("select st.student_name as 'Student Name' ,sub.subject_name as Subject, ls.lesson_name as Lesson ,stdt.marks as 'Marks' from studentmarkdetails stdt INNER JOIN students st ON stdt.student_id=st.student_id INNER JOIN subject sub ON stdt.subject_id=sub.subject_id INNER JOIN lessons ls ON stdt.lesson_id=ls.lesson_id where stdt.subject_id=" + subject + " and stdt.lesson_id=" + selectedlesson); rs = pst.executeQuery(); St_Table.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); St_Table.setModel(DbUtils.resultSetToTableModel(rs)); if (Arabic_lang.isSelected()) { St_Table.getColumnModel().getColumn(0).setHeaderValue("أسم الطالب"); St_Table.getColumnModel().getColumn(1).setHeaderValue("اسم الموضوع"); St_Table.getColumnModel().getColumn(2).setHeaderValue("الى الخلف"); St_Table.getColumnModel().getColumn(3).setHeaderValue("علامات"); } } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } killDialog(); } private void Populate_Suggestions() { try { createComponents(); pst = con.prepareStatement("select id as Id ,username as 'User Name', subject as Subject ,message as Suggestions from suggestions"); rs = pst.executeQuery(); Suggestions_Table.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); Suggestions_Table.setModel(DbUtils.resultSetToTableModel(rs)); if (Arabic_lang.isSelected()) { Suggestions_Table.getColumnModel().getColumn(0).setHeaderValue("هوية شخصية"); Suggestions_Table.getColumnModel().getColumn(1).setHeaderValue("اسم المستخدم"); Suggestions_Table.getColumnModel().getColumn(2).setHeaderValue("مواضيع"); Suggestions_Table.getColumnModel().getColumn(3).setHeaderValue("ملاحظاتكم تهمنا"); } } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } killDialog(); } // private void updateSubjectIndex() { // String str = "Select * from subject"; // String index = ""; // int i = 1; // try { // pst = con.prepareStatement(str); // rs = pst.executeQuery(); // while (rs.next()) { // index = rs.getString("subject_id"); // pst2 = con.prepareStatement("Update subject set subject_no=" + i + " where subject_id=" + index); // pst2.executeUpdate(); // i++; // } // } catch (Exception e) { // Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); // } // } // private void updateLessonIndex() { // String str = "Select * from lessons where subject_id=" + subject; // String index = ""; // int i = 1; // try { // pst = con.prepareStatement(str); // rs = pst.executeQuery(); // while (rs.next()) { // index = rs.getString("lesson_id"); // pst2 = con.prepareStatement("Update lessons set lesson_no=" + i + " where lesson_id=" + index); // pst2.executeUpdate(); // i++; // } // } catch (Exception e) { // Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); // } // } // private void updateQuestionsIndex() { // String str = "Select * from questions where lesson_id=" + selectedlesson; // String index = ""; // int i = 1; // try { // pst = con.prepareStatement(str); // rs = pst.executeQuery(); // while (rs.next()) { // index = rs.getString("id"); // pst2 = con.prepareStatement("Update questions set question_no=" + i + " where id=" + index); // pst2.executeUpdate(); // i++; // } // } catch (Exception e) { // Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); // } // } // private void updateUsersIndex() { // String str = "Select * from users"; // String index = ""; // int i = 1; // try { // pst = con.prepareStatement(str); // rs = pst.executeQuery(); // while (rs.next()) { // index = rs.getString("user_id"); // pst2 = con.prepareStatement("Update users set user_no=" + i + " where user_id=" + index); // pst2.executeUpdate(); // i++; // } // } catch (Exception e) { // Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); // } // } private Boolean userCheck(String emailCheck) { userEmailCheck = false; ArrayList<String> emailList = new ArrayList<String>(); String str = "Select email from user"; try { pst = con.prepareStatement(str); rs = pst.executeQuery(); while (rs.next()) { int i = 1; emailList.add(rs.getString(i++)); } for (int a = 1; a < emailList.size(); a++) { if (emailCheck.equalsIgnoreCase(emailList.get(a))) { userEmailCheck = true; } } } catch (Exception e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } return userEmailCheck; } private void closeAllFrames() { SubjectFrame.setVisible(false); AddSubjectFrame.setVisible(false); LessonsFrame.setVisible(false); AddLessonFrame.setVisible(false); LessonsImageFrame.setVisible(false); UserManagementFrame.setVisible(false); QuestionsFrame.setVisible(false); UserLoginFrame.setVisible(false); ChangePasswordFrame.setVisible(false); StudentManagementFrame.setVisible(false); HomeFrame.setVisible(false); SettingsFrame.setVisible(false); ViewSuggestionsFrame.setVisible(false); FeedbackFrame.setVisible(false); ResultFrame.setVisible(false); AddLessonPictureFrame.setVisible(false); DictionaryFrame.setVisible(false); SettingsFrame.setVisible(false); } private void Populate_Users() { try { createComponents(); pst = con.prepareStatement("select id as Id,username as '<NAME>', email as 'Email Id' from user"); rs = pst.executeQuery(); User_Table.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); User_Table.setModel(DbUtils.resultSetToTableModel(rs)); User_Table.getColumnModel().getColumn(0).setMinWidth(0); User_Table.getColumnModel().getColumn(0).setMaxWidth(0); if (Arabic_lang.isSelected()) { User_Table.getColumnModel().getColumn(1).setHeaderValue("اسم المستخدم"); User_Table.getColumnModel().getColumn(2).setHeaderValue("البريد الإلكتروني معرف"); } } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } killDialog(); } private void Populate_Questions() { try { createComponents(); pst = con.prepareStatement("select id as Id, questions as Questions, option1 as 'First Option', option2 as 'Second Option',option3 as 'Third Option',answer as Anwser from questions where lesson_id=" + selectedlesson); rs = pst.executeQuery(); Qst_Table.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); Qst_Table.setModel(DbUtils.resultSetToTableModel(rs)); Qst_Table.getColumnModel().getColumn(0).setMinWidth(0); Qst_Table.getColumnModel().getColumn(0).setMaxWidth(0); if (Arabic_lang.isSelected()) { Qst_Table.getColumnModel().getColumn(1).setHeaderValue("الأسئلة "); Qst_Table.getColumnModel().getColumn(2).setHeaderValue("الخيار الأول"); Qst_Table.getColumnModel().getColumn(3).setHeaderValue("الخيار الثاني"); Qst_Table.getColumnModel().getColumn(4).setHeaderValue("الخيار الثالث"); Qst_Table.getColumnModel().getColumn(5).setHeaderValue("الأجوبة"); } } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } killDialog(); } private void Delete_Lesson(String selected) { List results = new List(); String lessonquery = ""; int i = 0; try { lessonquery = "select lesson_id from lessons where subject_id=" + selected; pst = con.prepareStatement(lessonquery); rs = pst.executeQuery(lessonquery); while (rs.next()) { results.add(rs.getString("lesson_id")); i++; } for (int a = 0; a < results.getItemCount(); a++) { Delete_Questions(results.getItem(a)); pst2 = con.prepareStatement("delete from lessons where lesson_id=" + results.getItem(a)); pst2.executeUpdate(); } } catch (Exception e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } } private void Delete_Questions(String lessonStr) { List results = new List(); String lessonquery = ""; int j = 0; try { lessonquery = "select id from questions where lesson_id=" + lessonStr; pst = con.prepareStatement(lessonquery); rs = pst.executeQuery(lessonquery); while (rs.next()) { results.add(rs.getString("id")); j++; } for (int b = 0; b < results.getItemCount(); b++) { pst2 = con.prepareStatement("delete from questions where id=" + results.getItem(b)); pst2.executeUpdate(); } } catch (Exception e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } } private void Sub_Add_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Sub_Add_BtnActionPerformed closeAllFrames(); AddSubjectFrame.setVisible(true); }//GEN-LAST:event_Sub_Add_BtnActionPerformed private void subject_delete_fn() { int viewIndex = Sub_Table.getSelectedRow(); rowcount = Sub_Table.getSelectedRowCount(); if (rowcount > 1 || rowcount == 0) { JOptionPane.showMessageDialog(null, "Please select one subject at a time", "Alert", JOptionPane.ERROR_MESSAGE); } else { DefaultTableModel model = (DefaultTableModel) Sub_Table.getModel(); String selected = model.getValueAt(viewIndex, 0).toString(); if (viewIndex != -1) { model.removeRow(viewIndex); try { Delete_Lesson(selected); pst = con.prepareStatement("delete from subject where subject_id='" + selected + "' "); pst.executeUpdate(); //updateSubjectIndex(); Populate_Subject(); } catch (Exception w) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, w); } } } } private void Sub_Delete_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Sub_Delete_BtnActionPerformed subject_delete_fn(); }//GEN-LAST:event_Sub_Delete_BtnActionPerformed private void SubjectCheck() { subjectList.clear(); try { pst = con.prepareStatement("select subject_name from subject"); rs = pst.executeQuery(); while (rs.next()) { subjectList.add(rs.getString("subject_name")); } } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } } private void AddSub_Add_Btn_fun() { SubjectCheck(); if (!(AddSub_Name_Textfield.getText().trim()).equals("") && !subjectList.contains(AddSub_Name_Textfield.getText().trim())) { String insertsubject = "INSERT INTO Subject(subject_name) VALUES(?)"; try { pst = con.prepareStatement(insertsubject); pst.setString(1, AddSub_Name_Textfield.getText().trim()); createComponents(); pst.executeUpdate(); killDialog(); } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } AddSub_Name_Textfield.setText(""); Populate_Subject(); closeAllFrames(); SubjectFrame.setVisible(true); } else { JOptionPane.showMessageDialog(null, "Please enter a new Subject", "Alert", JOptionPane.ERROR_MESSAGE); AddSubjectFrame.setVisible(true); AddSub_Name_Textfield.setText(""); } } public void createComponents() { SwingUtilities.invokeLater(new Runnable() { public void run() { //Create all components progressFrame = new JFrame("Progress Status"); progressFrame.setSize(300, 100); progressFrame.setBounds(300, 300, 300, 100); pane = progressFrame.getContentPane(); pane.setLayout(null); progressFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); JLabel progressLabel = new JLabel(); pane.add(progressLabel); progressLabel.setText("Processing..."); progressLabel.setBounds(80, 5, 280, 70); progressFrame.setResizable(false); progressFrame.setVisible(true); } }); } private void killDialog() { SwingUtilities.invokeLater(new Runnable() { public void run() { progressFrame.setVisible(false); } }); } private void AddSub_Add_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddSub_Add_BtnActionPerformed AddSub_Add_Btn_fun(); }//GEN-LAST:event_AddSub_Add_BtnActionPerformed private void Sub_Table_fun() { String subjectStatus = ""; buttonGroup10.clearSelection(); if (Sub_Table.getSelectedRowCount() > 0) { subject = Sub_Table.getModel().getValueAt(Sub_Table.getSelectedRow(), 0).toString(); subjectStatus = Sub_Table.getModel().getValueAt(Sub_Table.getSelectedRow(), 2).toString(); if (subjectStatus != "active") { inactive.setSelected(true); } if (subjectStatus.equalsIgnoreCase("active")) { active.setSelected(true); } } } private void Sub_TableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Sub_TableMouseClicked Sub_Table_fun(); }//GEN-LAST:event_Sub_TableMouseClicked private void Sub_Enter_Btn_fun() { String lessonsid = ""; rowcount = Sub_Table.getSelectedRowCount(); if (rowcount > 1) { JOptionPane.showMessageDialog(null, "Please select one subject at a time", "Alert", JOptionPane.ERROR_MESSAGE); } else { try { subject = Sub_Table.getModel().getValueAt(Sub_Table.getSelectedRow(), 0).toString(); lessonsid = "select lesson_id as Id,lesson_name as Lesson from lessons where subject_id=" + subject; pst = con.prepareStatement(lessonsid); rs = pst.executeQuery(lessonsid); Ls_Table.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 12)); Ls_Table.setModel(DbUtils.resultSetToTableModel(rs)); Ls_Table.getColumnModel().getColumn(0).setMinWidth(0); Ls_Table.getColumnModel().getColumn(0).setMaxWidth(0); closeAllFrames(); LessonsFrame.setVisible(true); Populate_Lessons(); } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } } } private void Sub_Enter_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Sub_Enter_BtnActionPerformed if (Sub_Table.getSelectedRowCount() == 1) { Sub_Enter_Btn_fun(); } else if (Sub_Table.getSelectedRowCount() > 1) { JOptionPane.showMessageDialog(null, "Please select one subject at a time", "Alert", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Please select one subject", "Alert", JOptionPane.ERROR_MESSAGE); } }//GEN-LAST:event_Sub_Enter_BtnActionPerformed private void Ls_Enter_Btn_fun() { String lessonsLabel = ""; rowcount = Ls_Table.getSelectedRowCount(); if (rowcount > 1 || rowcount == 0) { JOptionPane.showMessageDialog(null, "Please select one lesson at a time", "Alert", JOptionPane.ERROR_MESSAGE); LessonsFrame.requestFocus(); } else { try { selectedlesson = Ls_Table.getModel().getValueAt(Ls_Table.getSelectedRow(), 0).toString(); lessonsLabel = "select lesson_name from lessons where lesson_id=" + selectedlesson; pst = con.prepareStatement(lessonsLabel); rs = pst.executeQuery(lessonsLabel); while (rs.next()) { LsImage_label.setText(rs.getString(1)); } closeAllFrames(); LessonsImageFrame.setVisible(true); Populate_LessonPictures(); } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } } } private void Ls_Enter_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Ls_Enter_BtnActionPerformed Ls_Enter_Btn_fun(); }//GEN-LAST:event_Ls_Enter_BtnActionPerformed private void LsContent_Update_Btn_fun() { String updatelessoncontent = "Update lessons set lesson_picture=? where lesson_id=" + selectedlesson; try { pst = con.prepareStatement(updatelessoncontent); //pst.setString(1, LsContent_PictureLabel.get()); pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } closeAllFrames(); LessonsFrame.setVisible(true); Populate_Lessons(); } private void LsImage_AddImage_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LsImage_AddImage_BtnActionPerformed closeAllFrames(); AddLessonPictureFrame.setVisible(true); }//GEN-LAST:event_LsImage_AddImage_BtnActionPerformed private void Ls_Delete_Btn_fun() { int row = Ls_Table.getSelectedRow(); rowcount = Ls_Table.getSelectedRowCount(); if (rowcount > 1 || rowcount == 0) { JOptionPane.showMessageDialog(null, "Please select one lesson at a time", "Alert", JOptionPane.ERROR_MESSAGE); LessonsFrame.requestFocus(); } else { DefaultTableModel model = (DefaultTableModel) Ls_Table.getModel(); String selected = model.getValueAt(row, 0).toString(); if (row >= 0) { model.removeRow(row); try { pst = con.prepareStatement("delete from lessons where lesson_id='" + selected + "' "); pst.executeUpdate(); // updateLessonIndex(); Populate_Lessons(); } catch (Exception w) { JOptionPane.showMessageDialog(this, "Connection Error!"); } } } } private void Ls_Delete_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Ls_Delete_BtnActionPerformed Ls_Delete_Btn_fun(); }//GEN-LAST:event_Ls_Delete_BtnActionPerformed private void Ls_Add_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Ls_Add_BtnActionPerformed closeAllFrames(); AddLessonFrame.setVisible(true); }//GEN-LAST:event_Ls_Add_BtnActionPerformed private void AddLs_Submit_Btn_fun() { String insertlesson = "INSERT INTO lessons(lesson_name,subject_id) VALUES(?,?)"; if (!AddLs_Name_TextArea.getText().equalsIgnoreCase("")) { try { pst = con.prepareStatement(insertlesson); pst.setString(1, AddLs_Name_TextArea.getText()); pst.setString(2, subject); pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } //updateLessonIndex(); Populate_Lessons(); closeAllFrames(); LessonsFrame.setVisible(true); AddLs_Name_TextArea.setText(""); } else { JOptionPane.showMessageDialog(null, "Please enter the lesson information", "Alert", JOptionPane.ERROR_MESSAGE); AddLessonFrame.requestFocus(); } } private void AddLs_Submit_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddLs_Submit_BtnActionPerformed AddLs_Submit_Btn_fun(); }//GEN-LAST:event_AddLs_Submit_BtnActionPerformed private void UsMng_Delete_Btn_fun() { int row = User_Table.getSelectedRow(); rowcount = User_Table.getSelectedRowCount(); if (rowcount > 1 || rowcount == 0) { JOptionPane.showMessageDialog(null, "Please select a user to delete at a time", "Alert", JOptionPane.ERROR_MESSAGE); UserManagementFrame.requestFocus(); } else { DefaultTableModel model = (DefaultTableModel) User_Table.getModel(); String selected = model.getValueAt(row, 0).toString(); model.removeRow(row); try { pst = con.prepareStatement("delete from user where id='" + selected + "' "); pst.executeUpdate(); } catch (Exception w) { JOptionPane.showMessageDialog(this, "Connection Error!"); } UsMng_Name_Textfield.setText(""); UsMng_Email_Textfield.setText(""); Populate_Users(); } } private void UsMng_Delete_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UsMng_Delete_BtnActionPerformed UsMng_Delete_Btn_fun(); }//GEN-LAST:event_UsMng_Delete_BtnActionPerformed private void UserTable_fun() { int row = User_Table.getSelectedRow(); DefaultTableModel model = (DefaultTableModel) User_Table.getModel(); selectedUserid = model.getValueAt(row, 0).toString(); selectedUsername = model.getValueAt(row, 1).toString(); selectedUserEmail = model.getValueAt(row, 2).toString(); if (row >= 0) { UsMng_Name_Textfield.setText(selectedUsername); UsMng_Email_Textfield.setText(selectedUserEmail); } } private void User_TableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_User_TableMouseClicked UserTable_fun(); }//GEN-LAST:event_User_TableMouseClicked private Boolean EmailValidator(String emailIdString) { Pattern patternString; Matcher matcherString; Boolean ValidEmailId = false; EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; patternString = Pattern.compile(EMAIL_PATTERN); matcherString = patternString.matcher(emailIdString); if (!matcherString.matches()) { ValidEmailId = false; } else { ValidEmailId = true; } return ValidEmailId; } // private void UsMng_Add_Btn_fun() { // rowcount = User_Table.getSelectedRowCount(); // if (!UsMng_Name_Textfield.getText().trim().equalsIgnoreCase("") && !UsMng_Email_Textfield.getText().trim().equalsIgnoreCase("") && !UsMng_Password_Textfield.getText().equalsIgnoreCase("") && rowcount == 0) { // if (userCheck(UsMng_Email_Textfield.getText())) { // JOptionPane.showMessageDialog(null, "Email Id already exist", "Alert", JOptionPane.ERROR_MESSAGE); // UsMng_Email_Textfield.setText(""); // } else if (!EmailValidator(UsMng_Email_Textfield.getText().trim())) { // JOptionPane.showMessageDialog(null, "Please enter valid Email Id", "Alert", JOptionPane.ERROR_MESSAGE); // UsMng_Email_Textfield.setText(""); // } else { // try { // String insertuser = "INSERT INTO user(username,email,password,gender,image) VALUES(?,?,?,?,?)"; // pst = con.prepareStatement(insertuser); // pst.setString(1, UsMng_Name_Textfield.getText()); // pst.setString(2, UsMng_Email_Textfield.getText()); // pst.setString(3, UsMng_Password_Textfield.getText()); // pst.setString(4, "None"); // pst.setString(5, "http://www.research.cmru.ac.th/2014/ris/researcher/blank-person.jpg"); // pst.executeUpdate(); // UsMng_Name_Textfield.setText(""); // UsMng_Email_Textfield.setText(""); // UsMng_Password_Textfield.setText(""); // //updateUsersIndex(); // } catch (SQLException ex) { // Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); // } // } // } else { // JOptionPane.showMessageDialog(null, "Please enter new user information", "Alert", JOptionPane.ERROR_MESSAGE); // UserManagementFrame.requestFocus(); // UsMng_Name_Textfield.setText(""); // UsMng_Email_Textfield.setText(""); // UsMng_Password_Textfield.setText(""); // } // Populate_Users(); // } private void UsMng_Update_Btn_fun() { rowcount = User_Table.getSelectedRowCount(); if (rowcount > 1 || rowcount == 0) { JOptionPane.showMessageDialog(null, "Please select a user to update at a time", "Alert", JOptionPane.ERROR_MESSAGE); UserManagementFrame.requestFocus(); } else { try { if (!EmailValidator(UsMng_Email_Textfield.getText().trim())) { JOptionPane.showMessageDialog(null, "Please enter valid Email Id", "Alert", JOptionPane.ERROR_MESSAGE); UsMng_Email_Textfield.setText(""); UserManagementFrame.requestFocus(); } else { pst = con.prepareStatement("Update user set username=?,email=? where id=" + selectedUserid); pst.setString(1, UsMng_Name_Textfield.getText()); pst.setString(2, UsMng_Email_Textfield.getText()); pst.executeUpdate(); UsMng_Name_Textfield.setText(""); UsMng_Email_Textfield.setText(""); } } catch (Exception w) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, w); } Populate_Users(); } } private void UsMng_Update_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UsMng_Update_BtnActionPerformed UsMng_Update_Btn_fun(); }//GEN-LAST:event_UsMng_Update_BtnActionPerformed private void Sub_TableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Sub_TableMousePressed }//GEN-LAST:event_Sub_TableMousePressed private void User_TableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_User_TableMousePressed // TODO add your handling code here: }//GEN-LAST:event_User_TableMousePressed private void LsImage_Questions_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LsImage_Questions_BtnActionPerformed closeAllFrames(); QuestionsFrame.setVisible(true); Populate_Questions(); }//GEN-LAST:event_LsImage_Questions_BtnActionPerformed private void Qst_Table_fun() { rowcount = Qst_Table.getSelectedRowCount(); int row = Qst_Table.getSelectedRow(); if (rowcount > 1 || rowcount == 0) { JOptionPane.showMessageDialog(null, "Please select one question at a time", "Alert", JOptionPane.ERROR_MESSAGE); QuestionsFrame.requestFocus(); } else { DefaultTableModel model = (DefaultTableModel) Qst_Table.getModel(); selectedQuestionId = model.getValueAt(row, 0).toString(); selectedQuestion = model.getValueAt(row, 1).toString(); String option1 = model.getValueAt(row, 2).toString(); String option2 = model.getValueAt(row, 3).toString(); String option3 = model.getValueAt(row, 4).toString(); String correctanswer = model.getValueAt(row, 5).toString(); if (row >= 0) { Qst_Textarea.setText(selectedQuestion); Qst_Opt1_Textfield.setText(option1); Qst_Opt2_Textfield.setText(option2); Qst_Opt3_Textfield.setText(option3); if (correctanswer.equalsIgnoreCase("option1")) { Qst_Opt1_Btn.setSelected(true); } else if (correctanswer.equalsIgnoreCase("option2")) { Qst_Opt2_Btn.setSelected(true); } else { Qst_Opt3_Btn.setSelected(true); } } } } private void Qst_TableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Qst_TableMouseClicked Qst_Table_fun(); }//GEN-LAST:event_Qst_TableMouseClicked private void Qst_Update_Btn_fun() { rowcount = Qst_Table.getSelectedRowCount(); if (rowcount > 1 || rowcount == 0) { JOptionPane.showMessageDialog(null, "Please select a question to update at a time", "Alert", JOptionPane.ERROR_MESSAGE); QuestionsFrame.requestFocus(); } else { String option = null; if (Qst_Opt1_Btn.isSelected()) { option = "option1"; } else if (Qst_Opt2_Btn.isSelected()) { option = "option2"; } else { option = "option3"; } try { pst = con.prepareStatement("Update questions set questions=?,option1=?,option2=?,option3=? ,answer=? where id=" + selectedQuestionId); pst.setString(1, Qst_Textarea.getText()); pst.setString(2, Qst_Opt1_Textfield.getText()); pst.setString(3, Qst_Opt2_Textfield.getText()); pst.setString(4, Qst_Opt3_Textfield.getText()); pst.setString(5, option); pst.executeUpdate(); Qst_Textarea.setText(""); Qst_Opt1_Textfield.setText(""); Qst_Opt2_Textfield.setText(""); Qst_Opt3_Textfield.setText(""); buttonGroup1.clearSelection(); Populate_Questions(); } catch (Exception w) { JOptionPane.showMessageDialog(this, "Connection Error!"); } } } private void Qst_Update_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Qst_Update_BtnActionPerformed Qst_Update_Btn_fun(); }//GEN-LAST:event_Qst_Update_BtnActionPerformed private void Qst_Add_Btn_fun() { String insertquestion = "INSERT INTO questions(questions,option1,option2,option3,answer,lesson_id) VALUES(?,?,?,?,?,?)"; String correctoption = ""; rowcount = Qst_Table.getSelectedRowCount(); try { if ((!Qst_Textarea.getText().trim().equals("") && rowcount == 0) || !Qst_Textarea.getText().trim().equals(selectedQuestion)) { pst = con.prepareStatement(insertquestion); pst.setString(1, Qst_Textarea.getText()); pst.setString(2, Qst_Opt1_Textfield.getText()); pst.setString(3, Qst_Opt2_Textfield.getText()); pst.setString(4, Qst_Opt3_Textfield.getText()); if (Qst_Opt1_Btn.isSelected()) { correctoption = "option1"; } else if (Qst_Opt2_Btn.isSelected()) { correctoption = "option2"; } else { correctoption = "option3"; } pst.setString(5, correctoption); pst.setString(6, selectedlesson); if (buttonGroup1.getSelection() == null) { JOptionPane.showMessageDialog(null, "Please select an answer", "Alert", JOptionPane.ERROR_MESSAGE); QuestionsFrame.requestFocus(); } else { pst.execute(); Qst_Textarea.setText(""); Qst_Opt1_Textfield.setText(""); Qst_Opt2_Textfield.setText(""); Qst_Opt3_Textfield.setText(""); buttonGroup1.clearSelection(); //updateQuestionsIndex(); } } else { JOptionPane.showMessageDialog(null, "Please enter a new question", "Alert", JOptionPane.ERROR_MESSAGE); QuestionsFrame.requestFocus(); Qst_Textarea.setText(""); Qst_Opt1_Textfield.setText(""); Qst_Opt2_Textfield.setText(""); Qst_Opt3_Textfield.setText(""); buttonGroup1.clearSelection(); } } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } Populate_Questions(); } private void Qst_Add_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Qst_Add_BtnActionPerformed Qst_Add_Btn_fun(); }//GEN-LAST:event_Qst_Add_BtnActionPerformed private void AddLs_Back_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddLs_Back_BtnActionPerformed closeAllFrames(); LessonsFrame.setVisible(true); Populate_Lessons(); }//GEN-LAST:event_AddLs_Back_BtnActionPerformed private void Qst_Back_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Qst_Back_BtnActionPerformed closeAllFrames(); LessonsFrame.setVisible(true); Populate_Lessons(); }//GEN-LAST:event_Qst_Back_BtnActionPerformed private void Qst_Back_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Qst_Back_BtnMouseClicked }//GEN-LAST:event_Qst_Back_BtnMouseClicked private void Qst_Opt2_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Qst_Opt2_BtnActionPerformed // TODO add your handling code here: }//GEN-LAST:event_Qst_Opt2_BtnActionPerformed private void Ls_Back_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Ls_Back_BtnActionPerformed closeAllFrames(); SubjectFrame.setVisible(true); Populate_Subject(); }//GEN-LAST:event_Ls_Back_BtnActionPerformed private void UserLogin_fun() { String sql = "Select * from user where username=? and password=?"; try { pst = con.prepareStatement(sql); pst.setString(1, UserLogin_Name_Textfield.getText()); pst.setString(2, UserLogin_Password_Textfield.getText()); rs = pst.executeQuery(); if (rs.next()) { UserLoginFrame.setVisible(false); JOptionPane.showMessageDialog(null, "Logged in successfully.."); login = true; userLoginName = rs.getString("username"); HomeFrame.setVisible(true); HomeFrame.setLocation(250, 200); Home_label.requestFocus(); } else { JOptionPane.showMessageDialog(null, "Username or Password is incorrect"); login = false; UserLoginFrame.requestFocus(); } UserLogin_Name_Textfield.setText(""); UserLogin_Password_Textfield.setText(""); } catch (SQLException e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } } private void UserLogin_Login_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UserLogin_Login_BtnActionPerformed UserLogin_fun(); }//GEN-LAST:event_UserLogin_Login_BtnActionPerformed private void ChangedPwd_Submit_Btn_fun() { try { pst = con.prepareStatement("Update user set password=? where username='" + userLoginName + "'"); if ((ChangePwd_NewPwd_Textfield.getText()).equals(ChangePwd_ConfPwd_Textfield.getText()) && !ChangePwd_NewPwd_Textfield.getText().trim().equals("") && !ChangePwd_ConfPwd_Textfield.getText().trim().equals("")) { pst.setString(1, ChangePwd_NewPwd_Textfield.getText()); pst.executeUpdate(); ChangePasswordFrame.setVisible(false); JOptionPane.showMessageDialog(null, "Password Changed Successfully", "Alert", JOptionPane.ERROR_MESSAGE); HomeFrame.setVisible(true); HomeFrame.requestFocus(); } else { ChangePasswordFrame.setVisible(true); JOptionPane.showMessageDialog(null, "Password and Confirm Password Mismatched", "Alert", JOptionPane.ERROR_MESSAGE); ChangePasswordFrame.requestFocus(); } ChangePwd_NewPwd_Textfield.setText(""); ChangePwd_ConfPwd_Textfield.setText(""); } catch (Exception w) { JOptionPane.showMessageDialog(this, "Connection Error!"); } } private void ChangePwd_Submit_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ChangePwd_Submit_BtnActionPerformed ChangedPwd_Submit_Btn_fun(); }//GEN-LAST:event_ChangePwd_Submit_BtnActionPerformed private void UserLogin_ForgetPwd() { if (!UserLogin_Name_Textfield.getText().trim().equals("")) { String messageBody = null; String[] recipients = new String[1]; String[] bccRecipients = new String[]{""}; String subject = "Forget Password Mail"; StringBuffer messageBodyBuffer = new StringBuffer(); String user = UserLogin_Name_Textfield.getText(); String sql = "select password,email from user where username='" + user + "'"; messageBodyBuffer.append("Hi ").append(user); try { pst = con.prepareStatement(sql); rs = pst.executeQuery(); if (rs.next()) { recipients[0] = rs.getString("email"); messageBodyBuffer.append("</br>"); messageBodyBuffer.append("</br>"); messageBodyBuffer.append("Your password is ").append(rs.getString("password")); messageBodyBuffer.append("</br>"); messageBodyBuffer.append("</br>"); messageBodyBuffer.append("Regards,"); messageBodyBuffer.append("</br>"); messageBodyBuffer.append("Team"); messageBody = messageBodyBuffer.toString(); new MailUtil().sendMail(recipients, bccRecipients, subject, messageBody); } else { JOptionPane.showMessageDialog(null, "User does not exist", "Alert", JOptionPane.ERROR_MESSAGE); UserLoginFrame.requestFocus(); } } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } } else { JOptionPane.showMessageDialog(null, "Please enter your User Name", "Alert", JOptionPane.ERROR_MESSAGE); UserLoginFrame.requestFocus(); } } private void UserLogin_ForgetPwd_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UserLogin_ForgetPwd_BtnActionPerformed UserLogin_ForgetPwd(); }//GEN-LAST:event_UserLogin_ForgetPwd_BtnActionPerformed private void Qst_Delete_Btn_fun() { int row = Qst_Table.getSelectedRow(); rowcount = Qst_Table.getSelectedRowCount(); if (rowcount > 1 || rowcount == 0) { JOptionPane.showMessageDialog(null, "Please select one question at a time", "Alert", JOptionPane.ERROR_MESSAGE); QuestionsFrame.requestFocus(); } else { DefaultTableModel model = (DefaultTableModel) Qst_Table.getModel(); String selected = model.getValueAt(row, 0).toString(); model.removeRow(row); try { pst = con.prepareStatement("delete from questions where id='" + selected + "' "); pst.executeUpdate(); } catch (Exception w) { JOptionPane.showMessageDialog(this, "Connection Error!"); } //updateQuestionsIndex(); Populate_Questions(); Qst_Textarea.setText(""); Qst_Opt1_Textfield.setText(""); Qst_Opt2_Textfield.setText(""); Qst_Opt3_Textfield.setText(""); buttonGroup1.clearSelection(); } } private void Qst_Delete_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Qst_Delete_BtnActionPerformed Qst_Delete_Btn_fun(); }//GEN-LAST:event_Qst_Delete_BtnActionPerformed private void Ls_Marks_Btn_fun() { if (Ls_Table.getSelectedRowCount() > 0) { closeAllFrames(); Populate_Students(); StudentManagementFrame.setVisible(true); } else { JOptionPane.showMessageDialog(null, "Please select a lesson to check the students marks", "Alert", JOptionPane.ERROR_MESSAGE); LessonsFrame.requestFocus(); } } private void Ls_Marks_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Ls_Marks_BtnActionPerformed Ls_Marks_Btn_fun(); }//GEN-LAST:event_Ls_Marks_BtnActionPerformed private void Ls_Table_fun() { if (Ls_Table.getSelectedRowCount() > 0) { selectedlesson = Ls_Table.getModel().getValueAt(Ls_Table.getSelectedRow(), 0).toString(); } } private void Ls_TableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Ls_TableMouseClicked Ls_Table_fun(); }//GEN-LAST:event_Ls_TableMouseClicked private void Ls_Image_Back_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Ls_Image_Back_BtnActionPerformed closeAllFrames(); LessonsFrame.setVisible(true); Populate_Lessons(); LsImage_PictureLabel.setIcon(null); }//GEN-LAST:event_Ls_Image_Back_BtnActionPerformed private void StDetails_Back_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StDetails_Back_BtnActionPerformed closeAllFrames(); LessonsFrame.setVisible(true); Populate_Lessons(); }//GEN-LAST:event_StDetails_Back_BtnActionPerformed private void Sub_Delete_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Sub_Delete_BtnKeyReleased rowcount = Sub_Table.getSelectedRowCount(); if (evt.getKeyCode() == KeyEvent.VK_ENTER && rowcount == 1) { subject_delete_fn(); } else if (evt.getKeyCode() == KeyEvent.VK_ENTER && rowcount > 1) { JOptionPane.showMessageDialog(this, "Please select one subject to delete"); Sub_Table.requestFocus(); } else if (evt.getKeyCode() == KeyEvent.VK_ENTER && rowcount == 0) { JOptionPane.showMessageDialog(this, "Please select one subject to delete"); Sub_Table.requestFocus(); } }//GEN-LAST:event_Sub_Delete_BtnKeyReleased private void UserLogin_Login_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_UserLogin_Login_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { UserLogin_fun(); } else { //UserLoginFrame.requestFocus(); UserLogin_ForgetPwd_Btn.requestFocus(); } }//GEN-LAST:event_UserLogin_Login_BtnKeyReleased private void UserLogin_ForgetPwd_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_UserLogin_ForgetPwd_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { UserLogin_ForgetPwd(); } }//GEN-LAST:event_UserLogin_ForgetPwd_BtnKeyReleased private void Sub_Add_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Sub_Add_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); AddSubjectFrame.setVisible(true); AddSub_Name_Textfield.requestFocus(); } }//GEN-LAST:event_Sub_Add_BtnKeyReleased private void Sub_Enter_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Sub_Enter_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_TAB) { SubjectFrame.requestFocus(); } if (evt.getKeyCode() == KeyEvent.VK_ENTER) { if (Sub_Table.getSelectedRowCount() == 1) { Sub_Enter_Btn_fun(); } else if (Sub_Table.getSelectedRowCount() > 1) { JOptionPane.showMessageDialog(null, "Please select one subject at a time", "Alert", JOptionPane.ERROR_MESSAGE); Sub_Table.requestFocus(); } else { JOptionPane.showMessageDialog(null, "Please select a subject", "Alert", JOptionPane.ERROR_MESSAGE); Sub_Table.requestFocus(); } } }//GEN-LAST:event_Sub_Enter_BtnKeyReleased private void Sub_TableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Sub_TableKeyReleased if (evt.getKeyCode() == KeyEvent.VK_TAB) { Sub_Add_Btn.requestFocus(); } if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN) { Sub_Table_fun(); } }//GEN-LAST:event_Sub_TableKeyReleased private void Ls_TableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Ls_TableKeyReleased if (evt.getKeyCode() == KeyEvent.VK_TAB) { Ls_Add_Btn.requestFocus(); } if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN) { } }//GEN-LAST:event_Ls_TableKeyReleased private void AddSub_Add_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AddSub_Add_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { AddSub_Add_Btn_fun(); } }//GEN-LAST:event_AddSub_Add_BtnKeyReleased private void AddSub_Back_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddSub_Back_BtnActionPerformed AddSub_Name_Textfield.setText(""); closeAllFrames(); SubjectFrame.setVisible(true); Populate_Subject(); }//GEN-LAST:event_AddSub_Back_BtnActionPerformed private void AddSub_Back_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AddSub_Back_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); SubjectFrame.setVisible(true); Populate_Subject(); } if (evt.getKeyCode() == KeyEvent.VK_TAB) { AddSub_Name_Textfield.requestFocus(); } }//GEN-LAST:event_AddSub_Back_BtnKeyReleased private void Sub_TableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Sub_TableKeyPressed // TODO add your handling code here: }//GEN-LAST:event_Sub_TableKeyPressed private void Ls_Back_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Ls_Back_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); SubjectFrame.setVisible(true); Populate_Subject(); } }//GEN-LAST:event_Ls_Back_BtnKeyReleased private void Ls_Add_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Ls_Add_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); AddLessonFrame.setVisible(true); } }//GEN-LAST:event_Ls_Add_BtnKeyReleased private void Ls_Delete_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Ls_Delete_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Ls_Delete_Btn_fun(); LessonsFrame.setVisible(true); Populate_Lessons(); } }//GEN-LAST:event_Ls_Delete_BtnKeyReleased private void Ls_Enter_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Ls_Enter_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Ls_Enter_Btn_fun(); } }//GEN-LAST:event_Ls_Enter_BtnKeyReleased private void AddLs_Back_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AddLs_Back_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); LessonsFrame.setVisible(true); Populate_Lessons(); } }//GEN-LAST:event_AddLs_Back_BtnKeyReleased private void AddLs_Submit_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AddLs_Submit_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { AddLs_Submit_Btn_fun(); } }//GEN-LAST:event_AddLs_Submit_BtnKeyReleased private void Ls_Image_Back_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Ls_Image_Back_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); LessonsFrame.setVisible(true); Populate_Lessons(); LsImage_PictureLabel.setIcon(null); } }//GEN-LAST:event_Ls_Image_Back_BtnKeyReleased private void LsImage_AddImage_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LsImage_AddImage_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { //LsContent_Update_Btn_fun(); closeAllFrames(); AddLessonPictureFrame.setVisible(true); } }//GEN-LAST:event_LsImage_AddImage_BtnKeyReleased private void LsImage_Questions_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LsImage_Questions_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); QuestionsFrame.setVisible(true); Populate_Questions(); } }//GEN-LAST:event_LsImage_Questions_BtnKeyReleased private void Qst_Back_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Qst_Back_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); LessonsFrame.setVisible(true); Populate_Lessons(); } }//GEN-LAST:event_Qst_Back_BtnKeyReleased private void Qst_Update_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Qst_Update_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Qst_Update_Btn_fun(); } }//GEN-LAST:event_Qst_Update_BtnKeyReleased private void Qst_Add_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Qst_Add_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Qst_Add_Btn_fun(); } }//GEN-LAST:event_Qst_Add_BtnKeyReleased private void Qst_Delete_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Qst_Delete_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Qst_Delete_Btn_fun(); } }//GEN-LAST:event_Qst_Delete_BtnKeyReleased private void Qst_TableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Qst_TableKeyReleased if (evt.getKeyCode() == KeyEvent.VK_TAB) { Qst_Textarea.requestFocus(); } if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN) { Qst_Table_fun(); } }//GEN-LAST:event_Qst_TableKeyReleased private void Qst_Opt3_TextfieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Qst_Opt3_TextfieldKeyReleased if (evt.getKeyCode() == KeyEvent.VK_TAB) { Qst_Update_Btn.requestFocus(); } }//GEN-LAST:event_Qst_Opt3_TextfieldKeyReleased private void Ls_Marks_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Ls_Marks_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Ls_Marks_Btn_fun(); } }//GEN-LAST:event_Ls_Marks_BtnKeyReleased private void StDetails_Back_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_StDetails_Back_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); LessonsFrame.setVisible(true); Populate_Lessons(); } }//GEN-LAST:event_StDetails_Back_BtnKeyReleased private void ChangePwd_ConfPwd_TextfieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ChangePwd_ConfPwd_TextfieldKeyReleased if (evt.getKeyCode() == KeyEvent.VK_TAB) { ChangePwd_Submit_Btn.requestFocus(); } }//GEN-LAST:event_ChangePwd_ConfPwd_TextfieldKeyReleased private void ChangePwd_Submit_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ChangePwd_Submit_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { ChangedPwd_Submit_Btn_fun(); } }//GEN-LAST:event_ChangePwd_Submit_BtnKeyReleased private void UsMng_Delete_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_UsMng_Delete_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { UsMng_Delete_Btn_fun(); } }//GEN-LAST:event_UsMng_Delete_BtnKeyReleased private void UsMng_Update_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_UsMng_Update_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { UsMng_Update_Btn_fun(); } }//GEN-LAST:event_UsMng_Update_BtnKeyReleased private void User_TableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_User_TableKeyReleased // if (evt.getKeyCode() == KeyEvent.VK_TAB) { // UsMng_Add_Btn.requestFocus(); // } // if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN ) // { // UserTable_fun(); // } }//GEN-LAST:event_User_TableKeyReleased private void Home_UsrMngt_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Home_UsrMngt_BtnMouseClicked closeAllFrames(); UserManagementFrame.setVisible(true); Populate_Users(); UsMng_Name_Textfield.setText(""); UsMng_Email_Textfield.setText(""); }//GEN-LAST:event_Home_UsrMngt_BtnMouseClicked private void Home_UsrMngt_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Home_UsrMngt_BtnActionPerformed closeAllFrames(); UserManagementFrame.setVisible(true); Populate_Users(); UsMng_Name_Textfield.setText(""); UsMng_Email_Textfield.setText(""); }//GEN-LAST:event_Home_UsrMngt_BtnActionPerformed private void Home_UsrMngt_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Home_UsrMngt_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); UserManagementFrame.setVisible(true); Populate_Users(); UsMng_Name_Textfield.setText(""); UsMng_Email_Textfield.setText(""); } }//GEN-LAST:event_Home_UsrMngt_BtnKeyReleased private void Home_Subject_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Home_Subject_BtnMouseClicked closeAllFrames(); SubjectFrame.setVisible(true); Populate_Subject(); }//GEN-LAST:event_Home_Subject_BtnMouseClicked private void Home_Subject_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Home_Subject_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); SubjectFrame.setVisible(true); Populate_Subject(); } }//GEN-LAST:event_Home_Subject_BtnKeyReleased private void Home_ChangePwd_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Home_ChangePwd_BtnMouseClicked closeAllFrames(); ChangePasswordFrame.setVisible(true); }//GEN-LAST:event_Home_ChangePwd_BtnMouseClicked private void Home_ChangePwd_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Home_ChangePwd_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); ChangePasswordFrame.setVisible(true); } }//GEN-LAST:event_Home_ChangePwd_BtnKeyReleased private void Home_Logout_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Home_Logout_BtnMouseClicked closeAllFrames(); login = false; UserLoginFrame.setVisible(true); buttonGroup11.clearSelection(); English_lang.setSelected(true); EnglishAllText(); }//GEN-LAST:event_Home_Logout_BtnMouseClicked private void Home_Logout_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Home_Logout_BtnActionPerformed closeAllFrames(); login = false; UserLoginFrame.setVisible(true); buttonGroup11.clearSelection(); English_lang.setSelected(true); EnglishAllText(); }//GEN-LAST:event_Home_Logout_BtnActionPerformed private void Home_Logout_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Home_Logout_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); login = false; UserLoginFrame.setVisible(true); buttonGroup11.clearSelection(); English_lang.setSelected(true); EnglishAllText(); } }//GEN-LAST:event_Home_Logout_BtnKeyReleased private void UsMng_Home_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UsMng_Home_BtnActionPerformed closeAllFrames(); HomeFrame.setVisible(true); }//GEN-LAST:event_UsMng_Home_BtnActionPerformed private void UsMng_Home_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_UsMng_Home_BtnMouseClicked closeAllFrames(); HomeFrame.setVisible(true); }//GEN-LAST:event_UsMng_Home_BtnMouseClicked private void UsMng_Home_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_UsMng_Home_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); HomeFrame.setVisible(true); } }//GEN-LAST:event_UsMng_Home_BtnKeyReleased private void Sub_Home_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Sub_Home_BtnActionPerformed closeAllFrames(); HomeFrame.setVisible(true); }//GEN-LAST:event_Sub_Home_BtnActionPerformed private void Sub_Home_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Sub_Home_BtnMouseClicked closeAllFrames(); HomeFrame.setVisible(true); }//GEN-LAST:event_Sub_Home_BtnMouseClicked private void Sub_Home_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Sub_Home_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); HomeFrame.setVisible(true); } if (evt.getKeyCode() == KeyEvent.VK_TAB) { Sub_Status_Btn.requestFocus(); } }//GEN-LAST:event_Sub_Home_BtnKeyReleased private void ChangePwd_Home_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ChangePwd_Home_BtnActionPerformed closeAllFrames(); HomeFrame.setVisible(true); }//GEN-LAST:event_ChangePwd_Home_BtnActionPerformed private void ChangePwd_Home_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ChangePwd_Home_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); HomeFrame.setVisible(true); } }//GEN-LAST:event_ChangePwd_Home_BtnKeyReleased private void ChangePwd_Home_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ChangePwd_Home_BtnMouseClicked closeAllFrames(); HomeFrame.setVisible(true); }//GEN-LAST:event_ChangePwd_Home_BtnMouseClicked // private void UsMng_ViewProfile_Btn_fun() { // String sql = ""; // String userimage = ""; // rowcount = User_Table.getSelectedRowCount(); // //createComponents(); // closeAllFrames(); // UsersProfileFrame.setVisible(true); // if (rowcount > 1 || rowcount == 0) { // JOptionPane.showMessageDialog(null, "Please select a user", "Alert", JOptionPane.ERROR_MESSAGE); // UserManagementFrame.requestFocus(); // } else { // // try { // sql = "SELECT image FROM user where id=" + selectedUserid; // pst = con.prepareStatement(sql); // createComponents(); // rs = pst.executeQuery(); // //System.out.println("end time"+System.currentTimeMillis()); // // UserProfile_Name_Textfield.setText(selectedUsername); // UserProfile_Email_Textfield.setText(selectedUserEmail); // UserProfile_Pwd_Textfield.setText(selectedUserPassword); // // if (rs.next()) { // userimage = rs.getString("image"); // try { // ImageIcon icon = new ImageIcon(ImageIO.read(new URL(userimage))); // Image resizeImage = icon.getImage(); // Image newimg = resizeImage.getScaledInstance(180, 150, java.awt.Image.SCALE_SMOOTH); // ImageIcon newIcon = new ImageIcon(newimg); // UserProfile_Picture_Label.setIcon(newIcon); // // // } catch (IOException ex) { // Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); // } // } // //killDialog(); // } catch (SQLException ex) { // Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); // } // } // // } private void Home_ChangePwd_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Home_ChangePwd_BtnActionPerformed closeAllFrames(); ChangePasswordFrame.setVisible(true); }//GEN-LAST:event_Home_ChangePwd_BtnActionPerformed private void Home_Subject_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Home_Subject_BtnActionPerformed closeAllFrames(); SubjectFrame.setVisible(true); Populate_Subject(); }//GEN-LAST:event_Home_Subject_BtnActionPerformed private void Home_ViewSugg_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Home_ViewSugg_BtnActionPerformed closeAllFrames(); ViewSuggestionsFrame.setVisible(true); Populate_Suggestions(); }//GEN-LAST:event_Home_ViewSugg_BtnActionPerformed private void Home_ViewSugg_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Home_ViewSugg_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); ViewSuggestionsFrame.setVisible(true); Populate_Suggestions(); } }//GEN-LAST:event_Home_ViewSugg_BtnKeyReleased private void Home_ViewSugg_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Home_ViewSugg_BtnMouseClicked closeAllFrames(); ViewSuggestionsFrame.setVisible(true); Populate_Suggestions(); }//GEN-LAST:event_Home_ViewSugg_BtnMouseClicked private void ViewSug_Home_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ViewSug_Home_BtnActionPerformed closeAllFrames(); ViewSug_Suggestion_Textarea.setText(""); HomeFrame.setVisible(true); ViewSug_Subject_Textfield.setText(""); ViewSug_Suggestion_Textarea.setText(""); }//GEN-LAST:event_ViewSug_Home_BtnActionPerformed private void ViewSug_Home_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ViewSug_Home_BtnMouseClicked closeAllFrames(); ViewSug_Suggestion_Textarea.setText(""); HomeFrame.setVisible(true); ViewSug_Subject_Textfield.setText(""); ViewSug_Suggestion_Textarea.setText(""); }//GEN-LAST:event_ViewSug_Home_BtnMouseClicked private void ViewSug_Home_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_ViewSug_Home_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); ViewSug_Suggestion_Textarea.setText(""); HomeFrame.setVisible(true); ViewSug_Subject_Textfield.setText(""); ViewSug_Suggestion_Textarea.setText(""); } }//GEN-LAST:event_ViewSug_Home_BtnKeyReleased private void Suggestions_table_selection() { String selectedSuggestion = ""; String selectedSubject = ""; int row = 0; ViewSug_Suggestion_Textarea.setText(""); ViewSug_Subject_Textfield.setText(""); row = Suggestions_Table.getSelectedRow(); DefaultTableModel model = (DefaultTableModel) Suggestions_Table.getModel(); selectedSubject = model.getValueAt(row, 2).toString(); selectedSuggestion = model.getValueAt(row, 3).toString(); ViewSug_Suggestion_Textarea.setText(selectedSuggestion); ViewSug_Subject_Textfield.setText(selectedSubject); } private void Suggestions_TableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Suggestions_TableMouseClicked Suggestions_table_selection(); }//GEN-LAST:event_Suggestions_TableMouseClicked private void Suggestions_TableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Suggestions_TableKeyReleased if (evt.getKeyCode() == KeyEvent.VK_TAB) { Suggestions_table_selection(); } if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN) { Suggestions_table_selection(); } }//GEN-LAST:event_Suggestions_TableKeyReleased private void buttonGroupClearSelection() { buttonGroup2.clearSelection(); buttonGroup3.clearSelection(); buttonGroup4.clearSelection(); buttonGroup5.clearSelection(); buttonGroup6.clearSelection(); buttonGroup7.clearSelection(); buttonGroup8.clearSelection(); buttonGroup9.clearSelection(); } private void feedbackTable_fun() { int row = 0; buttonGroupClearSelection(); String selectedFirstAns, selectedSecondAns, selectedThirdAns, selectedFourthAns, selectedFifthAns, selectedSixthAns, selectedSeventhAns, selectedEigthAns; rowcount = feedbackTable.getSelectedRowCount(); if (rowcount > 1 || rowcount == 0) { //JOptionPane.showMessageDialog(null, "Please select one question", "Alert", JOptionPane.ERROR_MESSAGE); FeedbackFrame.requestFocus(); } else { row = feedbackTable.getSelectedRow(); DefaultTableModel model = (DefaultTableModel) feedbackTable.getModel(); selectedFirstAns = model.getValueAt(row, 3).toString(); selectedSecondAns = model.getValueAt(row, 4).toString(); selectedThirdAns = model.getValueAt(row, 5).toString(); selectedFourthAns = model.getValueAt(row, 6).toString(); selectedFifthAns = model.getValueAt(row, 7).toString(); selectedSixthAns = model.getValueAt(row, 8).toString(); selectedSeventhAns = model.getValueAt(row, 9).toString(); selectedEigthAns = model.getValueAt(row, 10).toString(); if (selectedFirstAns.equals("1")) { jRadioButton1.setSelected(true); } else if (selectedFirstAns.equals("2")) { jRadioButton2.setSelected(true); } else if (selectedFirstAns.equals("3")) { jRadioButton3.setSelected(true); } else if (selectedFirstAns.equals("4")) { jRadioButton4.setSelected(true); } else if (selectedFirstAns.equals("5")) { jRadioButton5.setSelected(true); } if (selectedSecondAns.equals("1")) { jRadioButton6.setSelected(true); } else if (selectedSecondAns.equals("2")) { jRadioButton7.setSelected(true); } else if (selectedSecondAns.equals("3")) { jRadioButton8.setSelected(true); } else if (selectedSecondAns.equals("4")) { jRadioButton9.setSelected(true); } else if (selectedSecondAns.equals("5")) { jRadioButton10.setSelected(true); } if (selectedThirdAns.equals("1")) { jRadioButton11.setSelected(true); } else if (selectedThirdAns.equals("2")) { jRadioButton12.setSelected(true); } else if (selectedThirdAns.equals("3")) { jRadioButton13.setSelected(true); } else if (selectedThirdAns.equals("4")) { jRadioButton14.setSelected(true); } else if (selectedThirdAns.equals("5")) { jRadioButton15.setSelected(true); } if (selectedFourthAns.equals("1")) { jRadioButton16.setSelected(true); } else if (selectedFourthAns.equals("2")) { jRadioButton17.setSelected(true); } else if (selectedFourthAns.equals("3")) { jRadioButton18.setSelected(true); } else if (selectedFourthAns.equals("4")) { jRadioButton19.setSelected(true); } else if (selectedFourthAns.equals("5")) { jRadioButton20.setSelected(true); } if (selectedFifthAns.equals("1")) { jRadioButton21.setSelected(true); } else if (selectedFifthAns.equals("2")) { jRadioButton22.setSelected(true); } else if (selectedFifthAns.equals("3")) { jRadioButton23.setSelected(true); } else if (selectedFifthAns.equals("4")) { jRadioButton24.setSelected(true); } else if (selectedFifthAns.equals("5")) { jRadioButton25.setSelected(true); } if (selectedSixthAns.equals("1")) { jRadioButton26.setSelected(true); } else if (selectedSixthAns.equals("2")) { jRadioButton27.setSelected(true); } else if (selectedSixthAns.equals("3")) { jRadioButton28.setSelected(true); } else if (selectedSixthAns.equals("4")) { jRadioButton29.setSelected(true); } else if (selectedSixthAns.equals("5")) { jRadioButton30.setSelected(true); } if (selectedSeventhAns.equals("1")) { jRadioButton31.setSelected(true); } else if (selectedSeventhAns.equals("2")) { jRadioButton32.setSelected(true); } else if (selectedSeventhAns.equals("3")) { jRadioButton33.setSelected(true); } else if (selectedSeventhAns.equals("4")) { jRadioButton34.setSelected(true); } else if (selectedSeventhAns.equals("5")) { jRadioButton35.setSelected(true); } if (selectedEigthAns.equals("1")) { jRadioButton36.setSelected(true); } else if (selectedEigthAns.equals("2")) { jRadioButton37.setSelected(true); } else if (selectedEigthAns.equals("3")) { jRadioButton38.setSelected(true); } else if (selectedEigthAns.equals("4")) { jRadioButton39.setSelected(true); } else if (selectedEigthAns.equals("5")) { jRadioButton40.setSelected(true); } } } private void feedbackTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_feedbackTableMouseClicked feedbackTable_fun(); }//GEN-LAST:event_feedbackTableMouseClicked private void feedbackTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_feedbackTableKeyReleased if (evt.getKeyCode() == KeyEvent.VK_TAB || evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN) { feedbackTable_fun(); } }//GEN-LAST:event_feedbackTableKeyReleased private void Home_EmployeeFeedback_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Home_EmployeeFeedback_BtnActionPerformed closeAllFrames(); FeedbackFrame.setVisible(true); Populate_FeedbackDetails(); jPanel1.setEnabled(false); }//GEN-LAST:event_Home_EmployeeFeedback_BtnActionPerformed private void Home_EmployeeFeedback_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Home_EmployeeFeedback_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); FeedbackFrame.setVisible(true); Populate_FeedbackDetails(); } }//GEN-LAST:event_Home_EmployeeFeedback_BtnKeyReleased private void Home_EmployeeFeedback_BtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Home_EmployeeFeedback_BtnMouseClicked closeAllFrames(); FeedbackFrame.setVisible(true); Populate_FeedbackDetails(); }//GEN-LAST:event_Home_EmployeeFeedback_BtnMouseClicked private void clearButtonGroup() { buttonGroup2.clearSelection(); buttonGroup3.clearSelection(); buttonGroup4.clearSelection(); buttonGroup5.clearSelection(); buttonGroup6.clearSelection(); buttonGroup7.clearSelection(); buttonGroup8.clearSelection(); buttonGroup9.clearSelection(); } private void EmpFeedback_Home_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EmpFeedback_Home_BtnActionPerformed closeAllFrames(); HomeFrame.setVisible(true); clearButtonGroup(); }//GEN-LAST:event_EmpFeedback_Home_BtnActionPerformed private void EmpFeedback_Home_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_EmpFeedback_Home_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); HomeFrame.setVisible(true); buttonGroup2.clearSelection(); clearButtonGroup(); } }//GEN-LAST:event_EmpFeedback_Home_BtnKeyReleased private void Home_Results_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Home_Results_BtnActionPerformed closeAllFrames(); ResultFrame.setVisible(true); Populate_Results(); }//GEN-LAST:event_Home_Results_BtnActionPerformed private void Results_Home_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Results_Home_BtnActionPerformed closeAllFrames(); HomeFrame.setVisible(true); }//GEN-LAST:event_Results_Home_BtnActionPerformed private void Results_Home_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Results_Home_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); HomeFrame.setVisible(true); } }//GEN-LAST:event_Results_Home_BtnKeyReleased private void Home_Results_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Home_Results_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); ResultFrame.setVisible(true); Populate_Results(); } }//GEN-LAST:event_Home_Results_BtnKeyReleased private void Results_Search_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Results_Search_BtnActionPerformed Populate_Results(); }//GEN-LAST:event_Results_Search_BtnActionPerformed private void jComboBox2ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox2ItemStateChanged }//GEN-LAST:event_jComboBox2ItemStateChanged private void Results_Search_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Results_Search_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Populate_Results(); } }//GEN-LAST:event_Results_Search_BtnKeyReleased private void AddLessonPicture_Back_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddLessonPicture_Back_BtnActionPerformed closeAllFrames(); LessonsImageFrame.setVisible(true); Populate_LessonPictures(); }//GEN-LAST:event_AddLessonPicture_Back_BtnActionPerformed private void AddLessonPicture_Back_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AddLessonPicture_Back_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); LessonsImageFrame.setVisible(true); Populate_LessonPictures(); } }//GEN-LAST:event_AddLessonPicture_Back_BtnKeyReleased private void AddLessonPicture_Add_Btn_fun() { String str = ""; String sql = "insert into lesson_image(lesson_id,image) values (?,?)"; if (lessonImage == null) { JOptionPane.showMessageDialog(null, "No picture is selected", "Alert", JOptionPane.ERROR_MESSAGE); } else { LessonImageUrl = selectedlesson + "_" + pictureId + "_" + lessonImage; AddLessonPicture_Label.setIcon(null); try { pst = con.prepareStatement(sql); pst.setString(1, selectedlesson); pst.setString(2, LessonImageUrl); pst.executeUpdate(); LessonsImageFrame.setVisible(true); Populate_LessonPictures(); } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } } } private void AddLessonPicture_Add_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddLessonPicture_Add_BtnActionPerformed AddLessonPicture_Add_Btn_fun(); }//GEN-LAST:event_AddLessonPicture_Add_BtnActionPerformed private void AddLessonPicture_Upload_Btn_fun() { String sql = "Select id from lesson_image order by id desc"; JFileChooser filechooser = new JFileChooser(); filechooser.setDialogTitle("Choose the File to upload"); filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnval = filechooser.showOpenDialog(this); if (returnval == JFileChooser.APPROVE_OPTION) { File file = filechooser.getSelectedFile(); BufferedImage bi; try { bi = ImageIO.read(file); bi = scale(bi, 600, 400); AddLessonPicture_Label.setIcon(new ImageIcon(bi)); lessonImage = file.getName(); if (!lessonImage.endsWith("jpg")) { lessonImage = lessonImage.substring(0, lessonImage.lastIndexOf(".") + 1).concat("jpg"); } pst = con.prepareStatement(sql); rs = pst.executeQuery(sql); if (rs.next()) { pictureId++; } File f = new File("c:\\wamp\\www\\images\\" + selectedlesson + "_" + pictureId + "_" + lessonImage); ImageIO.write(bi, "jpg", f); } catch (Exception e) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, e); } } } private BufferedImage scale(BufferedImage src, int w, int h) { BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); int x, y; int ww = src.getWidth(); int hh = src.getHeight(); for (x = 0; x < w; x++) { for (y = 0; y < h; y++) { int col = src.getRGB(x * ww / w, y * hh / h); img.setRGB(x, y, col); } } return img; } private void AddLessonPicture_Upload_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddLessonPicture_Upload_BtnActionPerformed AddLessonPicture_Upload_Btn_fun(); }//GEN-LAST:event_AddLessonPicture_Upload_BtnActionPerformed private void AddLessonPicture_Upload_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AddLessonPicture_Upload_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { AddLessonPicture_Upload_Btn_fun(); } }//GEN-LAST:event_AddLessonPicture_Upload_BtnKeyReleased private void AddLessonPicture_Add_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_AddLessonPicture_Add_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { AddLessonPicture_Add_Btn_fun(); AddLessonPictureFrame.requestFocus(); } }//GEN-LAST:event_AddLessonPicture_Add_BtnKeyReleased private void Ls_Content_Table_fun() { rowcount = Ls_Image_Table.getSelectedRowCount(); int row; if (rowcount > 1 || rowcount == 0) { //AddLessonPictureFrame.requestFocus(); } else { row = Ls_Image_Table.getSelectedRow(); DefaultTableModel model = (DefaultTableModel) Ls_Image_Table.getModel(); selectedlessonPicture = model.getValueAt(row, 2).toString(); ImageIcon icon; try { icon = new ImageIcon(ImageIO.read(new URL("file:/C:/wamp/www/images/" + selectedlessonPicture))); Image resizeImage = icon.getImage(); Image newimg = resizeImage.getScaledInstance(525, 350, java.awt.Image.SCALE_SMOOTH); ImageIcon newIcon = new ImageIcon(newimg); LsImage_PictureLabel.setIcon(newIcon); } catch (IOException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } } } private void Ls_Image_TableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Ls_Image_TableMouseClicked Ls_Content_Table_fun(); }//GEN-LAST:event_Ls_Image_TableMouseClicked private void Ls_Image_TableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Ls_Image_TableKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER || evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN) { Ls_Content_Table_fun(); } if (evt.getKeyCode() == KeyEvent.VK_TAB) { LsImage_AddImage_Btn.requestFocus(); } }//GEN-LAST:event_Ls_Image_TableKeyReleased private void LsContent_Delete_Btn_fun() { int row = Ls_Image_Table.getSelectedRow(); rowcount = Ls_Image_Table.getSelectedRowCount(); if (rowcount > 1 || rowcount == 0) { JOptionPane.showMessageDialog(null, "Please select a picture to delete", "Alert", JOptionPane.ERROR_MESSAGE); AddLessonPictureFrame.requestFocus(); } else { DefaultTableModel model = (DefaultTableModel) Ls_Image_Table.getModel(); String selected = model.getValueAt(row, 0).toString(); model.removeRow(row); try { pst = con.prepareStatement("delete from lesson_image where id='" + selected + "'"); pst.executeUpdate(); } catch (Exception w) { JOptionPane.showMessageDialog(this, "Connection Error!"); } Populate_LessonPictures(); LsImage_PictureLabel.setIcon(null); } } private void LsImage_Delete_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LsImage_Delete_BtnActionPerformed LsContent_Delete_Btn_fun(); }//GEN-LAST:event_LsImage_Delete_BtnActionPerformed private void LsImage_Delete_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_LsImage_Delete_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { LsContent_Delete_Btn_fun(); } }//GEN-LAST:event_LsImage_Delete_BtnKeyReleased private void Home_Dictionary_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Home_Dictionary_BtnActionPerformed closeAllFrames(); DictionaryFrame.setVisible(true); Populate_Dictionary(); }//GEN-LAST:event_Home_Dictionary_BtnActionPerformed private void Home_Dictionary_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Home_Dictionary_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); DictionaryFrame.setVisible(true); Populate_Dictionary(); } }//GEN-LAST:event_Home_Dictionary_BtnKeyReleased private void Dictionary_Home_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Dictionary_Home_BtnActionPerformed closeAllFrames(); HomeFrame.setVisible(true); Dictionary_Word_Textfield.setText(""); Dictionary_Meaning_Textarea.setText(""); }//GEN-LAST:event_Dictionary_Home_BtnActionPerformed private void Dictionary_Home_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Dictionary_Home_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); HomeFrame.setVisible(true); Dictionary_Word_Textfield.setText(""); Dictionary_Meaning_Textarea.setText(""); } }//GEN-LAST:event_Dictionary_Home_BtnKeyReleased private void Dictionary_Add_Btn_fun() { Boolean sameword = false; String selectdWord = ""; if (!(Dictionary_Word_Textfield.getText().trim()).equals("") && !(Dictionary_Meaning_Textarea.getText()).equals("")) { String insertword = "INSERT INTO worddictionary(word,meaning) VALUES(?,?)"; selectdWord = Dictionary_Word_Textfield.getText().trim(); try { if (wordList.contains(selectdWord)) { sameword = true; } if (sameword) { JOptionPane.showMessageDialog(null, "The word already exists", "Alert", JOptionPane.ERROR_MESSAGE); DictionaryFrame.requestFocus(); } else { pst = con.prepareStatement(insertword); pst.setString(1, Dictionary_Word_Textfield.getText().trim()); pst.setString(2, Dictionary_Meaning_Textarea.getText()); pst.executeUpdate(); } } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } Dictionary_Word_Textfield.setText(""); Dictionary_Meaning_Textarea.setText(""); Populate_Dictionary(); } else { JOptionPane.showMessageDialog(null, "Please enter a Word", "Alert", JOptionPane.ERROR_MESSAGE); DictionaryFrame.requestFocus(); } } private void Dictionary_Add_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Dictionary_Add_BtnActionPerformed Dictionary_Add_Btn_fun(); }//GEN-LAST:event_Dictionary_Add_BtnActionPerformed private void Dictionary_Add_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Dictionary_Add_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Dictionary_Add_Btn_fun(); } }//GEN-LAST:event_Dictionary_Add_BtnKeyReleased private void Dictionary_Table_fun() { int row = Dictionary_Table.getSelectedRow(); DefaultTableModel model = (DefaultTableModel) Dictionary_Table.getModel(); if (row >= 0) { Dictionary_Word_Textfield.setText(model.getValueAt(row, 1).toString()); Dictionary_Meaning_Textarea.setText(model.getValueAt(row, 2).toString()); selectedId = model.getValueAt(row, 0).toString(); } } private void Dictionary_TableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Dictionary_TableMouseClicked Dictionary_Table_fun(); }//GEN-LAST:event_Dictionary_TableMouseClicked private void Dictionary_Update_Btn_fun() { int row = Dictionary_Table.getSelectedRow(); rowcount = Dictionary_Table.getSelectedRowCount(); try { if (!(Dictionary_Word_Textfield.getText().trim()).equals("") && !(Dictionary_Meaning_Textarea.getText()).equals("") && wordList.contains(Dictionary_Word_Textfield.getText().trim())) { pst = con.prepareStatement("Update worddictionary set word='" + Dictionary_Word_Textfield.getText() + "', meaning ='" + Dictionary_Meaning_Textarea.getText() + "' where id='" + selectedId + "'"); pst.executeUpdate(); Dictionary_Word_Textfield.setText(""); Dictionary_Meaning_Textarea.setText(""); Populate_Dictionary(); } else { JOptionPane.showMessageDialog(null, "Please select a Word to Update from the dictionary", "Alert", JOptionPane.ERROR_MESSAGE); DictionaryFrame.requestFocus(); } } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } } private void Dictionary_Update_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Dictionary_Update_BtnActionPerformed Dictionary_Update_Btn_fun(); }//GEN-LAST:event_Dictionary_Update_BtnActionPerformed private void Dictionary_Delete_Btn_fun() { int row = Dictionary_Table.getSelectedRow(); rowcount = Dictionary_Table.getSelectedRowCount(); if (rowcount > 1 || rowcount == 0) { JOptionPane.showMessageDialog(null, "Please select a word from the table to delete at a time", "Alert", JOptionPane.ERROR_MESSAGE); DictionaryFrame.requestFocus(); } else if (wordList.contains(Dictionary_Word_Textfield.getText().trim())) { DefaultTableModel model = (DefaultTableModel) Dictionary_Table.getModel(); if (row >= 0) { model.removeRow(row); try { pst = con.prepareStatement("delete from worddictionary where id='" + selectedId + "'"); pst.executeUpdate(); Populate_Dictionary(); Dictionary_Word_Textfield.setText(""); Dictionary_Meaning_Textarea.setText(""); } catch (Exception w) { JOptionPane.showMessageDialog(this, "Connection Error!"); } } } else { JOptionPane.showMessageDialog(null, "Please select a word to delete", "Alert", JOptionPane.ERROR_MESSAGE); } DictionaryFrame.requestFocus(); } private void Dictionary_Delete_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Dictionary_Delete_BtnActionPerformed Dictionary_Delete_Btn_fun(); }//GEN-LAST:event_Dictionary_Delete_BtnActionPerformed private void Dictionary_Update_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Dictionary_Update_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Dictionary_Update_Btn_fun(); } }//GEN-LAST:event_Dictionary_Update_BtnKeyReleased private void Dictionary_Delete_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Dictionary_Delete_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Dictionary_Delete_Btn_fun(); } }//GEN-LAST:event_Dictionary_Delete_BtnKeyReleased private void Dictionary_TableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Dictionary_TableKeyReleased if (evt.getKeyCode() == KeyEvent.VK_TAB) { Dictionary_Word_Textfield.requestFocus(); } if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN) { Dictionary_Table_fun(); } }//GEN-LAST:event_Dictionary_TableKeyReleased private void Dictionary_Meaning_TextareaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Dictionary_Meaning_TextareaKeyReleased if (evt.getKeyCode() == KeyEvent.VK_TAB) { Dictionary_Add_Btn.requestFocus(); } }//GEN-LAST:event_Dictionary_Meaning_TextareaKeyReleased private void Sub_Status_Btn_fun() { rowcount = Sub_Table.getSelectedRowCount(); if (rowcount == 1) { String UpdatedStatus = ""; if (active.isSelected()) { UpdatedStatus = "active"; } if (inactive.isSelected()) { UpdatedStatus = "inactive"; } String sql = "Update subject set status='" + UpdatedStatus + "' where subject_id=" + subject; try { pst = con.prepareStatement(sql); pst.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex); } } else { JOptionPane.showMessageDialog(null, "Please select a single subject to update status", "Alert", JOptionPane.ERROR_MESSAGE); } Populate_Subject(); } private void Sub_Status_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Sub_Status_BtnActionPerformed Sub_Status_Btn_fun(); }//GEN-LAST:event_Sub_Status_BtnActionPerformed private void Sub_Status_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Sub_Status_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Sub_Status_Btn_fun(); } }//GEN-LAST:event_Sub_Status_BtnKeyReleased private void Arabic_langActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Arabic_langActionPerformed ArabicAllText(); }//GEN-LAST:event_Arabic_langActionPerformed private void English_langActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_English_langActionPerformed EnglishAllText(); }//GEN-LAST:event_English_langActionPerformed private void Arabic_langKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Arabic_langKeyReleased ArabicAllText(); }//GEN-LAST:event_Arabic_langKeyReleased private void English_langKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_English_langKeyReleased EnglishAllText(); }//GEN-LAST:event_English_langKeyReleased private void Home_Settings_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Home_Settings_BtnActionPerformed closeAllFrames(); SettingsFrame.setVisible(true); }//GEN-LAST:event_Home_Settings_BtnActionPerformed private void Home_Settings_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Home_Settings_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); SettingsFrame.setVisible(true); } }//GEN-LAST:event_Home_Settings_BtnKeyReleased private void Settings_Save_Btn_fun() { try { servername = Settings_ServerName_Textfield.getText(); serveraddress = Settings_ServerAddress_Textfield.getText(); databasename = Settings_DatabaseName_Textfield.getText(); databaseusername = Settings_DBUserName_Textfield.getText(); databasepassword = Settings_DBPassword_Textfield.getText(); if(!Settings_ServerAddress_Textfield.getText().trim().equals("") && !Settings_DatabaseName_Textfield.getText().trim().equals("") && !Settings_DBUserName_Textfield.getText().trim().equals("")) { saveToXML(encrypt(servername), encrypt(serveraddress), encrypt(databasename), encrypt(databaseusername), encrypt(databasepassword)); } else { JOptionPane.showMessageDialog(null, "Please fill server settings"); } } catch (Exception e) { } Settings_ServerName_Textfield.setText(""); Settings_ServerAddress_Textfield.setText(""); Settings_DatabaseName_Textfield.setText(""); Settings_DBUserName_Textfield.setText(""); Settings_DBPassword_Textfield.setText(""); } private void Settings_Save_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Settings_Save_BtnActionPerformed Settings_Save_Btn_fun(); }//GEN-LAST:event_Settings_Save_BtnActionPerformed private void Settings_Home_BtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Settings_Home_BtnActionPerformed closeAllFrames(); HomeFrame.setVisible(true); }//GEN-LAST:event_Settings_Home_BtnActionPerformed private void Settings_Home_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Settings_Home_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { closeAllFrames(); HomeFrame.setVisible(true); } }//GEN-LAST:event_Settings_Home_BtnKeyReleased private void Settings_Save_BtnKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Settings_Save_BtnKeyReleased if (evt.getKeyCode() == KeyEvent.VK_ENTER) { Settings_Save_Btn_fun(); } }//GEN-LAST:event_Settings_Save_BtnKeyReleased public void saveToXML(String servername, String serveraddress, String databasename, String databaseusername, String databasepassword) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); org.w3c.dom.Element rootElement = doc.createElement("DatabaseConnection"); doc.appendChild(rootElement); // connection elements org.w3c.dom.Element Connection = doc.createElement("Connection"); rootElement.appendChild(Connection); // ServerName elements org.w3c.dom.Element ServerName = doc.createElement("ServerName"); ServerName.appendChild(doc.createTextNode(servername)); Connection.appendChild(ServerName); // ServerAddress elements org.w3c.dom.Element ServerAddress = doc.createElement("ServerAddress"); ServerAddress.appendChild(doc.createTextNode(serveraddress)); Connection.appendChild(ServerAddress); // DatabaseName elements org.w3c.dom.Element DatabaseName = doc.createElement("DatabaseName"); DatabaseName.appendChild(doc.createTextNode(databasename)); Connection.appendChild(DatabaseName); // DatabaseUserName elements org.w3c.dom.Element DatabaseUserName = doc.createElement("DatabaseUserName"); DatabaseUserName.appendChild(doc.createTextNode(databaseusername)); Connection.appendChild(DatabaseUserName); // DatabasePassword elements org.w3c.dom.Element DatabasePassword = doc.createElement("DatabasePassword"); DatabasePassword.appendChild(doc.createTextNode(databasepassword)); Connection.appendChild(DatabasePassword); // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("C:\\wamp\\www\\serverFile\\server.xml")); // Output to console for testing transformer.transform(source, result); JOptionPane.showMessageDialog(null, "Server Settings saved.Please Log in again"); readXML(); con = mysqlconnect.ConnectDb(url,databaseusernameDecrypt,databasepasswordDecrypt); closeAllFrames(); login = false; UserLoginFrame.setVisible(true); UserLoginFrame.setLocation(200, 200); buttonGroup11.clearSelection(); English_lang.setSelected(true); Settings_Home_Btn.setVisible(true); EnglishAllText(); //System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } } public static String encrypt(String value) throws Exception { Key key = generateKey(); Cipher cipher = Cipher.getInstance(Home.ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encryptedByteValue = cipher.doFinal(value.getBytes("utf-8")); String encryptedValue64 = new BASE64Encoder().encode(encryptedByteValue); return encryptedValue64; } public static String decrypt(String value) throws Exception { Key key = generateKey(); Cipher cipher = Cipher.getInstance(Home.ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decryptedValue64 = new BASE64Decoder().decodeBuffer(value); byte[] decryptedByteValue = cipher.doFinal(decryptedValue64); String decryptedValue = new String(decryptedByteValue, "utf-8"); return decryptedValue; } private static Key generateKey() throws Exception { Key key = new SecretKeySpec(Home.KEY.getBytes(), Home.ALGORITHM); return key; } public void readXML() { try { File fXmlFile = new File("C:\\wamp\\www\\serverFile\\server.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); doc.getDocumentElement().normalize(); //System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("Connection"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { org.w3c.dom.Element eElement = (org.w3c.dom.Element) nNode; servernameDecrypt = decrypt(eElement.getElementsByTagName("ServerName").item(0).getTextContent()); serveraddressDecrypt = decrypt(eElement.getElementsByTagName("ServerAddress").item(0).getTextContent()); databasenameDecrypt = decrypt(eElement.getElementsByTagName("DatabaseName").item(0).getTextContent()); databaseusernameDecrypt = decrypt(eElement.getElementsByTagName("DatabaseUserName").item(0).getTextContent()); databasepasswordDecrypt = decrypt(eElement.getElementsByTagName("DatabasePassword").item(0).getTextContent()); url=serveraddressDecrypt+"/"+databasenameDecrypt+"?useUnicode=yes&characterEncoding=UTF-8"; } } } catch (Exception e) { SettingsFrame.setVisible(true); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Home().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JInternalFrame AddLessonFrame; private javax.swing.JInternalFrame AddLessonPictureFrame; private javax.swing.JButton AddLessonPicture_Add_Btn; private javax.swing.JButton AddLessonPicture_Back_Btn; private javax.swing.JLabel AddLessonPicture_Label; private javax.swing.JButton AddLessonPicture_Upload_Btn; private javax.swing.JButton AddLs_Back_Btn; private javax.swing.JLabel AddLs_Label; private javax.swing.JLabel AddLs_Name_Label; private javax.swing.JTextField AddLs_Name_TextArea; private javax.swing.JButton AddLs_Submit_Btn; private javax.swing.JButton AddSub_Add_Btn; private javax.swing.JButton AddSub_Back_Btn; private javax.swing.JLabel AddSub_Label; private javax.swing.JLabel AddSub_Name_Label; private javax.swing.JTextField AddSub_Name_Textfield; private javax.swing.JInternalFrame AddSubjectFrame; private javax.swing.JRadioButton Arabic_lang; private javax.swing.JInternalFrame ChangePasswordFrame; private javax.swing.JLabel ChangePwd_ConfPwd_Label; private javax.swing.JTextField ChangePwd_ConfPwd_Textfield; private javax.swing.JButton ChangePwd_Home_Btn; private javax.swing.JLabel ChangePwd_Label; private javax.swing.JLabel ChangePwd_NewPwd_Label; private javax.swing.JTextField ChangePwd_NewPwd_Textfield; private javax.swing.JButton ChangePwd_Submit_Btn; private javax.swing.JInternalFrame DictionaryFrame; private javax.swing.JButton Dictionary_Add_Btn; private javax.swing.JButton Dictionary_Delete_Btn; private javax.swing.JButton Dictionary_Home_Btn; private javax.swing.JLabel Dictionary_Label; private javax.swing.JLabel Dictionary_Meaning_Label; private javax.swing.JTextArea Dictionary_Meaning_Textarea; private javax.swing.JTable Dictionary_Table; private javax.swing.JButton Dictionary_Update_Btn; private javax.swing.JLabel Dictionary_Word_Label; private javax.swing.JTextField Dictionary_Word_Textfield; private javax.swing.JButton EmpFeedback_Home_Btn; private javax.swing.JLabel EmpFeedback_Label; private javax.swing.JRadioButton English_lang; private javax.swing.JInternalFrame FeedbackFrame; private javax.swing.JInternalFrame HomeFrame; private javax.swing.JButton Home_ChangePwd_Btn; private javax.swing.JButton Home_Dictionary_Btn; private javax.swing.JButton Home_EmployeeFeedback_Btn; private javax.swing.JButton Home_Logout_Btn; private javax.swing.JButton Home_Results_Btn; private javax.swing.JButton Home_Settings_Btn; private javax.swing.JButton Home_Subject_Btn; private javax.swing.JButton Home_UsrMngt_Btn; private javax.swing.JButton Home_ViewSugg_Btn; private javax.swing.JLabel Home_label; private javax.swing.JInternalFrame LessonsFrame; private javax.swing.JInternalFrame LessonsImageFrame; private javax.swing.JButton LsImage_AddImage_Btn; private javax.swing.JButton LsImage_Delete_Btn; private javax.swing.JLabel LsImage_PictureLabel; private javax.swing.JButton LsImage_Questions_Btn; private javax.swing.JLabel LsImage_label; private javax.swing.JButton Ls_Add_Btn; private javax.swing.JButton Ls_Back_Btn; private javax.swing.JButton Ls_Delete_Btn; private javax.swing.JButton Ls_Enter_Btn; private javax.swing.JButton Ls_Image_Back_Btn; private javax.swing.JTable Ls_Image_Table; private javax.swing.JLabel Ls_Label; private javax.swing.JButton Ls_Marks_Btn; private javax.swing.JTable Ls_Table; private javax.swing.JButton Qst_Add_Btn; private javax.swing.JButton Qst_Back_Btn; private javax.swing.JButton Qst_Delete_Btn; private javax.swing.JLabel Qst_Label; private javax.swing.JRadioButton Qst_Opt1_Btn; private javax.swing.JTextField Qst_Opt1_Textfield; private javax.swing.JRadioButton Qst_Opt2_Btn; private javax.swing.JTextField Qst_Opt2_Textfield; private javax.swing.JRadioButton Qst_Opt3_Btn; private javax.swing.JTextField Qst_Opt3_Textfield; private javax.swing.JTable Qst_Table; private javax.swing.JTextArea Qst_Textarea; private javax.swing.JButton Qst_Update_Btn; private javax.swing.JLabel Question1; private javax.swing.JLabel Question1_Label; private javax.swing.JLabel Question2; private javax.swing.JLabel Question2_Label; private javax.swing.JLabel Question3; private javax.swing.JLabel Question3_Label; private javax.swing.JLabel Question4; private javax.swing.JLabel Question4_Label; private javax.swing.JLabel Question5; private javax.swing.JLabel Question5_Label; private javax.swing.JLabel Question6; private javax.swing.JLabel Question6_Label; private javax.swing.JLabel Question7; private javax.swing.JLabel Question7_Label; private javax.swing.JLabel Question8; private javax.swing.JLabel Question8_Label; private javax.swing.JInternalFrame QuestionsFrame; private javax.swing.JInternalFrame ResultFrame; private javax.swing.JTable Result_Table; private javax.swing.JButton Results_Home_Btn; private javax.swing.JButton Results_Search_Btn; private javax.swing.JLabel Results_StudentName_Lbl; private javax.swing.JLabel Results_Subject_Lbl; private javax.swing.JLabel Results_label; private javax.swing.JInternalFrame SettingsFrame; private javax.swing.JLabel Settings_DBPassword; private javax.swing.JTextField Settings_DBPassword_Textfield; private javax.swing.JLabel Settings_DBUserName; private javax.swing.JTextField Settings_DBUserName_Textfield; private javax.swing.JLabel Settings_DatabaseName; private javax.swing.JTextField Settings_DatabaseName_Textfield; private javax.swing.JButton Settings_Home_Btn; private javax.swing.JLabel Settings_Label; private javax.swing.JButton Settings_Save_Btn; private javax.swing.JLabel Settings_ServerAddress; private javax.swing.JTextField Settings_ServerAddress_Textfield; private javax.swing.JLabel Settings_ServerName; private javax.swing.JTextField Settings_ServerName_Textfield; private javax.swing.JButton StDetails_Back_Btn; private javax.swing.JLabel StDetails_Label; private javax.swing.JTable St_Table; private javax.swing.JInternalFrame StudentManagementFrame; private javax.swing.JButton Sub_Add_Btn; private javax.swing.JButton Sub_Delete_Btn; private javax.swing.JButton Sub_Enter_Btn; private javax.swing.JButton Sub_Home_Btn; private javax.swing.JLabel Sub_Label; private javax.swing.JButton Sub_Status_Btn; private javax.swing.JTable Sub_Table; private javax.swing.JInternalFrame SubjectFrame; private javax.swing.JTable Suggestions_Table; private javax.swing.JButton UsMng_Delete_Btn; private javax.swing.JLabel UsMng_Email_Label; private javax.swing.JTextField UsMng_Email_Textfield; private javax.swing.JButton UsMng_Home_Btn; private javax.swing.JLabel UsMng_Name_Label; private javax.swing.JTextField UsMng_Name_Textfield; private javax.swing.JButton UsMng_Update_Btn; private javax.swing.JLabel UsMng_label; private javax.swing.JInternalFrame UserLoginFrame; private javax.swing.JButton UserLogin_ForgetPwd_Btn; private javax.swing.JLabel UserLogin_Label; private javax.swing.JButton UserLogin_Login_Btn; private javax.swing.JLabel UserLogin_Name_Label; private javax.swing.JTextField UserLogin_Name_Textfield; private javax.swing.JLabel UserLogin_Password_Label; private javax.swing.JTextField UserLogin_Password_Textfield; private javax.swing.JInternalFrame UserManagementFrame; private javax.swing.JTable User_Table; private javax.swing.JButton ViewSug_Home_Btn; private javax.swing.JLabel ViewSug_Label; private javax.swing.JLabel ViewSug_Subject_Label; private javax.swing.JTextField ViewSug_Subject_Textfield; private javax.swing.JLabel ViewSug_Suggestion_Label; private javax.swing.JTextArea ViewSug_Suggestion_Textarea; private javax.swing.JInternalFrame ViewSuggestionsFrame; private javax.swing.JRadioButton active; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.ButtonGroup buttonGroup10; private javax.swing.ButtonGroup buttonGroup11; private javax.swing.ButtonGroup buttonGroup2; private javax.swing.ButtonGroup buttonGroup3; private javax.swing.ButtonGroup buttonGroup4; private javax.swing.ButtonGroup buttonGroup5; private javax.swing.ButtonGroup buttonGroup6; private javax.swing.ButtonGroup buttonGroup7; private javax.swing.ButtonGroup buttonGroup8; private javax.swing.ButtonGroup buttonGroup9; private javax.swing.JDesktopPane desktopPane; private javax.swing.JTable feedbackTable; private javax.swing.JRadioButton inactive; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JComboBox<String> jComboBox2; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton10; private javax.swing.JRadioButton jRadioButton11; private javax.swing.JRadioButton jRadioButton12; private javax.swing.JRadioButton jRadioButton13; private javax.swing.JRadioButton jRadioButton14; private javax.swing.JRadioButton jRadioButton15; private javax.swing.JRadioButton jRadioButton16; private javax.swing.JRadioButton jRadioButton17; private javax.swing.JRadioButton jRadioButton18; private javax.swing.JRadioButton jRadioButton19; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JRadioButton jRadioButton20; private javax.swing.JRadioButton jRadioButton21; private javax.swing.JRadioButton jRadioButton22; private javax.swing.JRadioButton jRadioButton23; private javax.swing.JRadioButton jRadioButton24; private javax.swing.JRadioButton jRadioButton25; private javax.swing.JRadioButton jRadioButton26; private javax.swing.JRadioButton jRadioButton27; private javax.swing.JRadioButton jRadioButton28; private javax.swing.JRadioButton jRadioButton29; private javax.swing.JRadioButton jRadioButton3; private javax.swing.JRadioButton jRadioButton30; private javax.swing.JRadioButton jRadioButton31; private javax.swing.JRadioButton jRadioButton32; private javax.swing.JRadioButton jRadioButton33; private javax.swing.JRadioButton jRadioButton34; private javax.swing.JRadioButton jRadioButton35; private javax.swing.JRadioButton jRadioButton36; private javax.swing.JRadioButton jRadioButton37; private javax.swing.JRadioButton jRadioButton38; private javax.swing.JRadioButton jRadioButton39; private javax.swing.JRadioButton jRadioButton4; private javax.swing.JRadioButton jRadioButton40; private javax.swing.JRadioButton jRadioButton5; private javax.swing.JRadioButton jRadioButton6; private javax.swing.JRadioButton jRadioButton7; private javax.swing.JRadioButton jRadioButton8; private javax.swing.JRadioButton jRadioButton9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane10; private javax.swing.JScrollPane jScrollPane11; private javax.swing.JScrollPane jScrollPane12; private javax.swing.JScrollPane jScrollPane13; private javax.swing.JScrollPane jScrollPane14; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JScrollPane jScrollPane7; private javax.swing.JScrollPane jScrollPane8; private javax.swing.JScrollPane jScrollPane9; // End of variables declaration//GEN-END:variables }
c22b0c27b72c5291bfc6ddfcaeb1f00a7789409f
[ "Java" ]
1
Java
ashrafemp/smartlearningdesktop
24aa1b695b6093ee3922190d93ab45d98d2f8776
f3c979251a451f38149fef079abd7ab3fc416b46
refs/heads/master
<file_sep>package com.practice; import java.util.Scanner; public class Evenorodd { public static void main(String[] args) { int n; System.out.print("enter any number"); Scanner sc=new Scanner(System.in); n=sc.nextInt(); if(n%2==0) { System.out.println("enter number is even"+n); } else { System.out.println("enter number is odd"+n); } } } <file_sep>package com.practice; import java.util.Scanner; public class LeftPyramid { public static void main(String[] args) { int i,j,rows,c; System.out.print("enter no of rows"); Scanner sc=new Scanner(System.in); rows=sc.nextInt(); for(i=1;rows>=1;i++) { for(j=rows-i;j<=i;j++) { for(c=1;c<=i;c++) { System.out.println(" "); } } System.out.println("*"); } } } <file_sep>package com.practice; public class Addfor { public static void main(String[] args) { // TODO Auto-generated method stub //byte b=10; // System.out.println("enter even numbers from 1and"+10); //for(int i=1;i<=10;i++) //for(int i=10;i>=1;i--) for(int i=1;i<=20;i++) { //if(i%2==0) if(i%2!=0) System.out.println(" odd number"+i ); else System.out.println(" even number"+i); } } } <file_sep>package com.practice; import java.util.Scanner; public class Aggregatemarks { public static void main(String[] args) { int s1,s2,s3,s4,s5; float agr,per; System.out.print("\nenter marks of student in s1"); System.out.print("\nenter marks of student in s2"); System.out.print("\nenter marks of student in s3"); System.out.print("\nenter marks of student in s4"); System.out.print("\nenter marks of student in s5"); Scanner sc=new Scanner(System.in); s1=sc.nextInt(); s2=sc.nextInt(); s3=sc.nextInt(); s4=sc.nextInt(); s5=sc.nextInt(); agr=s1+s2+s3+s4+s5; per=agr/500*100; System.out.println("aggregate marks of student"+agr); System.out.println("percentage marks of student"+per); } } <file_sep>package com.practice; import java.util.Scanner; public class Grossalary { public static void main(String[] args) { float bs,hra,da,gs; System.out.print("enter ramesh basicsalary"); Scanner sc=new Scanner(System.in); bs=sc.nextFloat(); da=40/100*bs; hra=20/100*bs; gs=bs-da-hra; System.out.println("gross salary of ramesh is"+gs); } } <file_sep>package com.practice; import java.util.Scanner; public class Displaynumbers { public static void main(String[] args) { int n; System.out.print("enter numbers" ); Scanner sc=new Scanner(System.in); n=sc.nextInt(); for(int i=0;i<=n;i++) { System.out.println("print numbers"+i); } } } <file_sep>package com.practice; import java.util.Scanner; public class Javafactorial { public static void main(String[] args) { // TODO Auto-generated method stub int n,i,fact=1; System.out.println("enter a value to calculate factorial"); Scanner sc=new Scanner(System.in); n =sc.nextInt(); if(n<0) System.out.println("number non-negative"); else { for(i=1;i<=n;i++) fact=fact*i; System.out.println("factorial of "+n+" is:"+fact); } } } <file_sep>package com.practice; import java.util.Scanner; public class Reverse { public static void main(String[] args) { int rev=0 ,n,res; System.out.print("enter rev of a num"); Scanner sc=new Scanner(System.in); n = sc.nextInt(); while(n!=0) { res=n%10; rev=rev*10+res; n=n/10; } System.out.println("enter reverse of a number="+rev); } } <file_sep>package com.practice; import java.nio.channels.ScatteringByteChannel; import java.util.Scanner; import java.util.concurrent.ScheduledExecutorService; public class Farenheittemp { public static void main(String[] args) { float celcius=0,farenheit=0; System.out.print("enter temperature in farenheit degree"); Scanner sc=new Scanner(System.in); celcius=sc.nextFloat(); celcius = (50/100*(farenheit-32))/90/100; System.out.println("calculate temperature in fareheit"+farenheit); } }
80459faffd7ec5340b56e8ce0d2cee2a39a90741
[ "Java" ]
9
Java
pranitha-mandadi/pran
cc923be999efe935776143df72af9a58ff0194e8
8616331c4431c4b9c33d98e5e7973c7b58228771
refs/heads/master
<repo_name>esthercuan/cssi-3-javascript-warmup<file_sep>/answer_key.js // -- DAY 3 ANSWER KEY: Code Writing -- // 1. Write a function called myName that simply returns your name as a string. // -- Store that string in a variable called thisIsMyName // -- Log the value of that variable to the console. function myName() { return "Victoria"; } var thisIsMyName = myName(); console.log(thisIsMyName); // 2. Write a function called greeting that: // -- Takes 1 argument: the hour of the day (24 hour time) // -- Logs to the console "Good day" if the hour is less than 18, or "Good evening" otherwise. // -- For example, greeting(10) should log "Good day", and greeting(20) should log "Good evening". function greeting(hour) { if (hour < 18) { console.log("Good day"); } else { console.log("Good evening"); } } // Extra credit solution: function greeting2(hour) { if (typeof hour === 'number' && hour >= 0 && hour < 24) { if (hour < 18) { console.log("Good day"); } else { console.log("Good evening"); } } } // Alternative EC solution (another way to write the same thing as above): function greeting3(hour) { if (typeof hour !== 'number' || hour < 0 || hour >= 24) { return; } var message = "Good "; if (hour < 18) { message += "day"; } else { message += "evening"; } console.log(message); } // 3. Write a function called receipt that: // -- Takes 1 argument, the subtotal (total cost of the meal, without tax or tip) // -- Returns the total cost, based on a 9% tax and a 15% tip. // -- For example, receipt(20) should return 24.8. function receipt(subtotal) { var tax = subtotal * 0.09; var tip = subtotal * 0.15; var total = subtotal + tax + tip; return total; } // 4. Modify your receipt function to take an additional argument, tip, to specify the percentage of tip to leave. For example, receipt(20, 10) should return 23.8. function receipt2(subtotal, percentTip) { var tax = subtotal * 0.09; var tip = subtotal * (percentTip / 100); var total = subtotal + tax + tip; return total; } // 5. Modify your receipt function to replace the subtotal argument with an array called costsPerItem, which is an array containing the prices for each item ordered in the meal. Compute the subtotal from the costsPerItem array and calculate the total cost with tax and tip. For example, receipt([10, 9, 25], 20) should return 56.76. function receipt3(costsPerItem, percentTip) { var subtotal = 0; for (var i = 0; i < costsPerItem.length; i++) { subtotal += costsPerItem[i]; } var tax = subtotal * 0.09; var tip = subtotal * (percentTip / 100); var total = subtotal + tax + tip; return total.toFixed(2); } // 6. Write a function called splitTheBill that: // -- Takes 2 arguments, the total cost (i.e. with tax and tip included), and an array of string names (e.g. ["Victoria", "Jessie", "Joseph"]) // -- For each person, logs to the console the amount that they owe in the form of "[name] owes $[money]" // -- Splits the amount owed per person as evenly as possible among the number of people. // -- Note that money cannot exceed 2 decimal places (e.g. you cannot have $12.255) and the sum of each part should still add exactly up to the total cost. // -- For example, splitTheBill(122.27, ["Victoria", "Joseph", "Jessie"]) should print: // "Victoria owes $40.76" // "Joseph owes $40.76" // "Jessie owes $40.75" function splitTheBill(totalCost, names) { var approximateCostPerPerson = totalCost / names.length; // Get an even dollar amount. approximateCostPerPerson = Math.floor(approximateCostPerPerson * 100) / 100; var costsPerPerson = []; var costSoFar = approximateCostPerPerson * names.length; for (var i = 0; i < names.length; i++) { costsPerPerson[i] = approximateCostPerPerson; } var i = 0; while (costSoFar < totalCost) { costsPerPerson[i] += 0.01; costSoFar += 0.01; // Note: This should never exceed (costsPerPerson.length - 1), but adding // the mod anyway just for safety. i = (i + 1) % costsPerPerson.length; } for (var i = 0; i < names.length; i++) { console.log(names[i] + " owes $" + costsPerPerson[i].toFixed(2)); } } // A more concise solution. function splitTheBill2(totalCost, names) { var approximateCostPerPerson = Math.floor(totalCost / names.length * 100) / 100; var penniesRemaining = totalCost * 100 - (approximateCostPerPerson * names.length * 100); for (var i = 0; i < names.length; i++) { var cost = approximateCostPerPerson; if (penniesRemaining > 0) { cost += 0.01; } console.log(names[i] + " owes $" + cost.toFixed(2)); penniesRemaining--; } }
44140f173f080641576669a947ccc6394747e768
[ "JavaScript" ]
1
JavaScript
esthercuan/cssi-3-javascript-warmup
ce5eebb6753fa7cead8acc5306e8d343264e3d14
f0c9af06ea3eb4c22385289a4bff538e2b4dc908
refs/heads/master
<file_sep>package gui; import javax.swing.*; public class ComboBoxEditor extends DefaultCellEditor { JComboBox box; public ComboBoxEditor(DefaultComboBoxModel comboModel) { super(new JComboBox(comboModel)); } }<file_sep>package helper; import DAOHibernateModel.DAOCity; import DAOHibernateModel.DAOUser; import gui.Gui; import hibernateModel.City; import hibernateModel.User; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.Session; import org.hibernate.Query; import org.hibernate.cfg.Configuration; import org.hibernate.metadata.ClassMetadata; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import javax.swing.*; import java.sql.SQLException; import java.util.List; import java.util.Map; public class Main { private static final SessionFactory ourSessionFactory; private static final ServiceRegistry serviceRegistry; static { try { Configuration configuration = new Configuration(); configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); ourSessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } public static Session getSession() throws HibernateException { return ourSessionFactory.openSession(); } public static void main(final String[] args) throws Exception { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Gui(); } }); } } <file_sep>package DAOHibernateModel; import helper.Main; import hibernateModel.User; import org.hibernate.Session; import org.hibernate.criterion.Expression; import javax.swing.*; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class DAOUser { public void addUser(User user) { Session session = null; try { session = Main.getSession(); session.beginTransaction(); session.save(user); session.getTransaction().commit(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка I/O", JOptionPane.OK_OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } } public void updateUser(User user) throws SQLException { Session session = null; try { session = Main.getSession(); session.beginTransaction(); session.update(user); session.getTransaction().commit(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка I/O", JOptionPane.OK_OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } } public User getUserById(int id) throws SQLException { Session session = null; User user = null; try { session = Main.getSession(); user = (User) session.createQuery("from User where id=" + id).list().get(0); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка I/O", JOptionPane.OK_OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } return user; } public List<User> getAllUsers() throws SQLException { Session session = null; List<User> users = new ArrayList<User>(); try { session = Main.getSession(); users = session.createCriteria(User.class).list(); } catch (Exception e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка I/O", JOptionPane.OK_OPTION); } finally { if (session != null && session.isOpen()) { session.close(); } } return users; } public void deleteUser(User user) throws RuntimeException { Session session = null; try { session = Main.getSession(); session.beginTransaction(); session.delete(user); session.getTransaction().commit(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (session != null && session.isOpen()) { session.close(); } } } }<file_sep>package gui; import DAOHibernateModel.DAOCity; import hibernateModel.City; import hibernateModel.User; import model.CityModel; import model.UserModel; import javax.swing.*; import javax.swing.table.TableColumn; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.Observer; public class Gui extends JFrame { List<City> cities = new ArrayList<City>(); List<User> users = new ArrayList<User>(); class ComboModel extends DefaultComboBoxModel implements Observer { ComboModel(String[] list) { super(list); } @Override public void update(Observable observable, Object o) { this.removeAllElements(); for (City c : ((CityModel)observable).getCitiesList()) { this.addElement(c.getName()); } } } public Gui() { super("СУБ<NAME>, Брюханов"); UserModel userModel = null; CityModel cityModel = null; try { userModel = new UserModel(); cityModel = new CityModel(); } catch (SQLException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } if (userModel == null || cityModel == null) return; JPanel panel = new JPanel(); panel.setLayout(null); final JTable userTable = new JTable(userModel); List<City> ls = null; try { ls = new DAOCity().getAllCities(); } catch (SQLException e) { e.printStackTrace(); } String[] items = new String[ls.size()]; for (int i=0; i<ls.size(); i++) { items[i] = ls.get(i).getName(); } ComboModel comboModel = new ComboModel(items); cityModel.addObserver(comboModel); TableColumn col = userTable.getColumnModel().getColumn(2); col.setCellEditor(new ComboBoxEditor(comboModel)); JScrollPane userTablePane= new JScrollPane(userTable); userTablePane.setBounds(10,10,450,500); panel.add(userTablePane); final JTable cityTable = new JTable(cityModel); JScrollPane cityTablePane= new JScrollPane(cityTable); cityTablePane.setBounds(500,10,450,500); panel.add(cityTablePane); JButton btnAddCity = new JButton("Add city"); btnAddCity.setBounds(550,520,140,30); final CityModel finalCityModel = cityModel; btnAddCity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { finalCityModel.addRow(); cityTable.revalidate(); cityTable.repaint(); } }); panel.add(btnAddCity); JButton btnDeleteCity = new JButton("Delete city"); btnDeleteCity.setBounds(720,520,140,30); btnDeleteCity.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { finalCityModel.deleteRow(cityTable.getSelectedRow()); cityTable.revalidate(); cityTable.repaint(); } }); panel.add(btnDeleteCity); JButton btnAddUser = new JButton("Add user"); btnAddUser.setBounds(50,520,140,30); final UserModel finalUserModel = userModel; final CityModel finalCityModel1 = cityModel; btnAddUser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (finalCityModel1.getRowCount() != 0) { finalUserModel.addRow(); userTable.revalidate(); userTable.repaint(); } } }); panel.add(btnAddUser); JButton btnDeleteUser = new JButton("Delete user"); btnDeleteUser.setBounds(220,520,140,30); btnDeleteUser.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { finalUserModel.deleteRow(userTable.getSelectedRow()); userTable.revalidate(); userTable.repaint(); } }); panel.add(btnDeleteUser); getContentPane().add(new JScrollPane(panel)); setPreferredSize(new Dimension(1000, 600)); pack(); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } } <file_sep>package hibernateModel; import javax.persistence.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; @Entity public class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String firstName; private String lastName; @ManyToOne(optional = false) private City city; public User() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } }
90b91ecd03273b58dde283ac0339ea575d5f3fe3
[ "Java" ]
5
Java
blitz156/SUBD
98d0364eaac00f7046014367e84efcb264cc7b8e
16ec45819322c1db019d18b379417660a61f085b
refs/heads/master
<file_sep>package operations import ( middleware "github.com/go-openapi/runtime/middleware" //"cassandragenrest/models" "github.com/stevef1uk/cassandragenrest/models" "github.com/gocql/gocql" "fmt" "os" "log" ) /** func Search(params GetAccountsParams) middleware.Responder { payload1 := new(models.GetAccountsOKBodyItems) num := int64(params.ID) payload1.ID = &num //name := "me" payload1.Name = &params.Name var ret models.GetAccountsOKBody ret = make(models.GetAccountsOKBody,2) ret[0] = payload1 return NewGetAccountsOK().WithPayload(ret) }*/ /*func retRow( id int, name string ) (local_id int, local_name string) { local_id = id; local_name = name return }*/ var session *gocql.Session func SetUp() { var err error fmt.Println("Connecting to Cassandra on ", os.Getenv("CASSANDRA_SERVICE_HOST")) cluster := gocql.NewCluster(os.Getenv("CASSANDRA_SERVICE_HOST")) cluster.Keyspace = "demo" cluster.Consistency = gocql.One session, err = cluster.CreateSession() if ( err != nil ) { log.Fatal("Connection to Cannandra failed", err) } else { fmt.Println("Connection to Cannandra established") } } func Stop() { fmt.Println("Stopping Cassandra") session.Close() } func Search(params GetAccountsParams) middleware.Responder { var id int = 0 var name string = "" fmt.Println("Id = ", params.ID) fmt.Println("Name = ", params.Name) if err := session.Query(`SELECT id, name FROM accounts WHERE id = ? and name = ?`, params.ID, params.Name).Consistency(gocql.One).Scan(&id, &name); err != nil { fmt.Println("No data? ", err) } var ret models.GetAccountsOKBody fmt.Println("Row = ", id, name ) num := int64(id) payload1 := new(models.GetAccountsOKBodyItems) payload1.ID = &num payload1.Name = &name ret = make(models.GetAccountsOKBody,1) ret[0] = payload1 /*Code to retrive more than one row iter := session.Query(`SELECT id, name FROM accounts WHERE id = ?`, params.ID).Consistency(gocql.One).Iter(); var ret models.GetAccountsOKBody ret = make(models.GetAccountsOKBody,iter.NumRows()) fmt.Println("Retried rows count = ", iter.NumRows() ) for i := 0; iter.Scan(&id, &name); i++ { fmt.Println("Rows = ", id, name ) payload1 := new(models.GetAccountsOKBodyItems) //var id, name = retRow( id, name ) var id = id var name = name num := int64(id) payload1.ID = &num payload1.Name = &name ret[i] = payload1 }*/ return NewGetAccountsOK().WithPayload(ret) }
dfe510c2b08321699c5354059afc75496d1a55d3
[ "Go" ]
1
Go
stevef1uk/cassandragenrest
aa4cbb24812d450bdf231de2da6acde30e199039
9e20e62ecde28a6bd1b4739e12d99dc92b8c8971
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Task; class TodoController extends Controller { // public function __construct(){ return $this->middleware(['auth']); } public function index(){ $tasks=Task::latest()->get(); return view('todos.index', [ 'tasks'=>$tasks, ]); } public function store(Request $request){ $this->validate($request, [ 'title'=>'required', 'body'=>'required', ]); $request->user()->tasks()->create([ //user_id meret automatikisht 'title'=>$request->title, 'body'=>$request->body ]); return back(); } //delete a task public function destroy(Task $task){ $task->delete(); return back(); } //update a task public function update(Request $request, Task $task){ if($task->status== 0){ $request->user()->tasks()->update([ //user_id meret automatikisht 'status'=>1, ]); } else{ $request->user()->tasks()->update([ //user_id meret automatikisht 'status'=>0, ]); } return back(); } public function viewProgress(){ $tasks=Task::latest()->get(); return view('todos.progress', [ 'tasks'=>$tasks, ]); } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use App\Models\User; class Task extends Model { use HasFactory; protected $fillable = [ 'title', 'body', 'status', ]; public function user(){ return $this->belongsTo(User::class); } //kjo kontrollon nese id e userit te kyqur osht enjejt me id e userit qe e ka bo qt postim public function ownedBy(User $user){ return $user->id === $this->user_id; } public function status(){ if( $this->status == 1) { return "Completed"; } else { return "Not completed"; } } } <file_sep><?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class LoginController extends Controller { // //perderisa je i logum mos me mjt mu as me pa loginin(formen) public function __construct(){ $this->middleware(['guest']); } public function index(){ return view('auth.login'); } public function store(Request $request){ //valido te dhenat $this->validate($request, [ 'email'=>'required|email', 'password'=>'<PASSWORD>' ]); //bone sign in userin edhe jepja mundesin me bo remember me if(!auth()->attempt($request->only('email', 'password'), $request->remember)){ return back()->with('status', 'Invalid login details'); //nese kyqja deshton kjo e kthe nje sesio me qet mesazh } return redirect()->route('todos'); } }
f7d29933e9a52e220080b322b0f2b46d1f94c3c6
[ "PHP" ]
3
PHP
BlertaAhmeti/todo_app
d6fa43363906e42c8ebcf24a13b5f17390e81b2a
b6b15d5d2ab9bd542b3f7383673c1e7f9e1dcfcb
refs/heads/master
<file_sep>server.port=9003 spring.cloud.stream.bindings.input.destination=usage-cost<file_sep>server.port=9001 spring.cloud.stream.bindings.output.destination=product_details_search <file_sep>package com.cliq.sample.productsender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.messaging.Source; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity.BodyBuilder; import org.springframework.messaging.support.MessageBuilder; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cliq.sample.product.Product; @RestController @EnableBinding(Source.class) @RequestMapping(path = "/product") public class ProductDetailSender { private static final Logger logger = LoggerFactory.getLogger(ProductDetailSenderApplication.class); @Autowired private Source source; @PostMapping(path= "/", consumes = "application/json") public BodyBuilder addProduct(@RequestBody Product product) throws Exception { logger.info(product.toString()); this.source.output().send(MessageBuilder.withPayload(product).build()); return ResponseEntity.status(HttpStatus.CREATED); } @PutMapping(path= "/", consumes = "application/json") public BodyBuilder updateProduct(@RequestBody Product product) throws Exception { this.source.output().send(MessageBuilder.withPayload(product).build()); return ResponseEntity.status(HttpStatus.ACCEPTED); } } <file_sep>server.port=9002 spring.cloud.stream.bindings.input.destination=product_details_search spring.cloud.stream.bindings.output.destination=usage-cost<file_sep># Standalone Stream Samples ## Building the apps
ef24bd3e0ff72ec08e206ca046c3baa73e9135c4
[ "Markdown", "Java", "INI" ]
5
INI
contact2amit/EventDrivenSearch
ab9e7aba345b3eea7e88ac4bae56adc52a15ec62
e29eb70d900b783de96dff5f37d5a5ce90cd08d4
refs/heads/main
<repo_name>ndY0/torrjs-server<file_sep>/src/interfaces/genchannel.ts import { GenServer } from "torrjs-core/src/interfaces/genserver"; import { keyForBaseMiddlewares, keyForNamespace, keyForGateMap, } from "../utils/symbols"; import { SocketIoMiddleware, SocketMiddleware } from "../utils/types"; abstract class GenChannel extends GenServer { public static [keyForGateMap]: Map< string, { event: string; middlewares: SocketMiddleware[] } >; public static [keyForNamespace]: string; public static [keyForBaseMiddlewares]: SocketIoMiddleware[]; } export { GenChannel }; <file_sep>/src/utils/symbols.ts const keyForRouteMap = Symbol("key_for_route_map"); const keyForMetadataRouteMap = Symbol("key_for_metadata_route_map"); const keyForBasePath = Symbol("key_for_base_path"); const keyForServer = Symbol("key_for_server"); const keyForBaseMiddlewares = Symbol("key_for_base_middlewares"); const keyForServerPort = Symbol("key_for_server_port"); const keyForSocketServerPort = Symbol("key_for_socket_server_port"); const keyForSocketServer = Symbol("key_for_socket_server"); const keyForNamespace = Symbol("key_for_namespace"); const keyForMetadataGateMap = Symbol("key_for_metadata_gate_map"); const keyForGateMap = Symbol("key_for_gate_map"); export { keyForRouteMap, keyForMetadataRouteMap, keyForBasePath, keyForServer, keyForSocketServer, keyForBaseMiddlewares, keyForServerPort, keyForSocketServerPort, keyForNamespace, keyForMetadataGateMap, keyForGateMap, }; <file_sep>/src/annotations/channel.ts import { InMemoryEmitter } from "torrjs-core/src/transports/in-memory-emitter"; import { SocketIoMiddleware } from "../utils/types"; import { GenChannel } from "../interfaces/genchannel"; import { keyForMetadataMapSymbol, keyForMapSymbol, } from "torrjs-core/src/utils/symbols"; import { keyForNamespace, keyForBaseMiddlewares, keyForMetadataGateMap, keyForGateMap, } from "../utils/symbols"; function Channel( transport: InMemoryEmitter, namespace: string, middlewares?: SocketIoMiddleware[] ) { return <T extends typeof GenChannel>(constructor: T) => { const map: Map<string, string> = Reflect.getOwnMetadata(keyForMetadataMapSymbol, constructor.prototype) || new Map(); Reflect.defineProperty(constructor, keyForMapSymbol, { configurable: false, enumerable: true, value: map, writable: false, }); Reflect.deleteMetadata(keyForMetadataMapSymbol, constructor.prototype); const mapGate: Map< string, { event: string; middlewares: SocketIoMiddleware[] } > = Reflect.getOwnMetadata(keyForMetadataGateMap, constructor.prototype) || new Map(); Reflect.defineProperty(constructor, keyForGateMap, { configurable: false, enumerable: true, value: mapGate, writable: false, }); Reflect.deleteMetadata(keyForMetadataGateMap, constructor.prototype); Reflect.defineProperty(constructor, keyForNamespace, { configurable: false, enumerable: true, value: namespace, writable: false, }); Reflect.defineProperty(constructor, keyForBaseMiddlewares, { configurable: false, enumerable: true, value: middlewares || [], writable: false, }); Reflect.defineProperty(constructor, "eventEmitter", { configurable: false, enumerable: false, value: transport, writable: false, }); }; } export { Channel }; <file_sep>/src/interfaces/genrouter.ts import { GenServer } from "torrjs-core/src/interfaces/genserver"; import { keyForRouteMap, keyForBasePath, keyForBaseMiddlewares, } from "../utils/symbols"; import { ExpressMiddleware, HttpVerb } from "../utils/types"; abstract class GenRouter extends GenServer { public static [keyForRouteMap]: Map< string, { verb: HttpVerb; route: string; middlewares: ExpressMiddleware[] } >; public static [keyForBasePath]: string; public static [keyForBaseMiddlewares]: ExpressMiddleware[]; } export { GenRouter }; <file_sep>/src/interfaces/genendpoint.ts import { Server } from "http"; import { Server as SocketServer } from "socket.io"; import { GenServer } from "torrjs-core/src/interfaces/genserver"; import { GenSupervisor } from "torrjs-core/src/interfaces/gensupervisor"; import EventEmitter from "events"; import { GenRouter } from "./genrouter"; import { keyForCombinedSelfReadable, keyForCombinedAdministrationSelfReadable, keyForSupervisedChidren, keyForIdSymbol, } from "torrjs-core/src/utils/symbols"; import { CombineEmitter } from "torrjs-core/src/transports/combine-emitter"; import { memo, combineMemos, getMemoPromise, tail, putMemoValue, } from "torrjs-core/src/utils"; import { ChildSpec, RestartStrategy } from "torrjs-core/src/supervision/types"; import { keyForServer, keyForServerPort, keyForSocketServer, keyForSocketServerPort, } from "../utils/symbols"; import { buildExpressApp, buildSocketServer } from "../utils"; import { GenChannel } from "./genchannel"; abstract class GenEndpoint extends GenSupervisor { public [keyForServer]: Server; public [keyForSocketServer]: Server; public static [keyForServerPort]: number; public static [keyForSocketServerPort]: number; protected abstract children(): AsyncGenerator< unknown, ( | (typeof GenRouter & (new () => GenRouter)) | (typeof GenChannel & (new () => GenChannel)) )[], unknown >; public async *start<U extends typeof GenServer, V extends typeof GenEndpoint>( startArgs: [RestartStrategy], context: U, canceler: Generator<[boolean, EventEmitter], never, boolean>, _cancelerPromise: Promise<boolean> ) { [ context.eventEmitter, ...context.externalEventEmitters.values(), ].forEach((emitter) => emitter.resetInternalStreams()); const combinableStreams = [ context.eventEmitter, ...context.externalEventEmitters.values(), ].map((emitter) => { const stream = new (emitter.getInternalStreamType())(); emitter.setStream(context.name, stream); return stream; }); const combinableAdministrationStreams = [ context.eventEmitter, ...context.externalEventEmitters.values(), ].map((emitter) => { const administrationStream = new (emitter.getInternalStreamType())(); emitter.setStream(`${context.name}_management`, administrationStream); return administrationStream; }); this[keyForCombinedSelfReadable] = new CombineEmitter(combinableStreams); this[keyForCombinedAdministrationSelfReadable] = new CombineEmitter( combinableAdministrationStreams ); const managementCanceler = memo(true); const combinedCanceler = combineMemos( (...states) => states.reduce((acc, curr) => acc && curr, true), managementCanceler, canceler ); const combinedCancelerPromise = getMemoPromise(combinedCanceler); const childSpecs = yield* this.init(); const httpServers = childSpecs.filter( ( spec: [ typeof GenRouter | typeof GenChannel, GenRouter | GenChannel, ChildSpec, Generator<[boolean, EventEmitter], never, boolean> ] ) => spec[1] instanceof GenRouter ); const socketServers = childSpecs.filter( ( spec: [ typeof GenRouter | typeof GenChannel, GenRouter | GenChannel, ChildSpec, Generator<[boolean, EventEmitter], never, boolean> ] ) => spec[1] instanceof GenChannel ); if (httpServers.length > 0) { this[keyForServer] = buildExpressApp(httpServers).listen( (<V>(<unknown>context))[keyForServerPort] ); combinedCancelerPromise.then((_) => { this[keyForServer].close(); }); } if (socketServers.length > 0) { this[keyForSocketServer] = buildSocketServer(socketServers).listen( (<V>(<unknown>context))[keyForSocketServerPort] ); combinedCancelerPromise.then((_) => { this[keyForSocketServer].close(); }); } this[keyForSupervisedChidren] = childSpecs.map( ( childSpecs: [ typeof GenRouter | typeof GenChannel, GenRouter | GenChannel, ChildSpec, Generator<[boolean, EventEmitter], never, boolean> ] ) => ({ id: childSpecs[1][keyForIdSymbol], canceler: childSpecs[3], }) ); await Promise.all([ tail( (specs) => this.run( combinedCanceler, combinedCancelerPromise, context, this[keyForSupervisedChidren], specs ), canceler, { childSpecs, strategy: startArgs[0], }, (specs) => specs.childSpecs.length === 0 ).then((value) => (putMemoValue(managementCanceler, false), value)), tail( () => this.runManagement( managementCanceler, combinedCancelerPromise, context ), combinedCanceler, null, (exitValue) => exitValue === undefined ), ]); } } export { GenEndpoint }; <file_sep>/src/utils/index.ts import express, { Request, Response } from "express"; import { Server, createServer } from "http"; import { Server as SocketServer, ServerOptions, Socket } from "socket.io"; import { GenRouter } from "../interfaces/genrouter"; import { keyForBaseMiddlewares, keyForBasePath, keyForRouteMap, keyForNamespace, keyForGateMap, } from "./symbols"; import { HttpVerb } from "./types"; import { keyForIdSymbol } from "torrjs-core/src/utils/symbols"; import { GenChannel } from "../interfaces/genchannel"; function mapEnumToExpressFuncName( verb: HttpVerb ): | "get" | "post" | "put" | "patch" | "delete" | "options" | "head" | "connect" | "trace" { switch (verb) { case HttpVerb.GET: return "get"; case HttpVerb.POST: return "post"; case HttpVerb.PUT: return "put"; case HttpVerb.DELETE: return "delete"; case HttpVerb.OPTIONS: return "options"; case HttpVerb.CONNECT: return "connect"; case HttpVerb.HEAD: return "head"; case HttpVerb.PATCH: return "patch"; case HttpVerb.TRACE: return "trace"; default: return "get"; } } async function runSync<Treturn, Tyield>( fn: (...args: any[]) => Generator<Tyield, Treturn, any>, ...args: any[] ): Promise<Treturn> { const iterable = fn(...args); let state: IteratorResult<Tyield, Treturn>; do { state = iterable.next(); } while (!state.done); return state.value; } function buildExpressApp(routers: [typeof GenRouter, GenRouter][]): Server { const app = express(); routers.forEach(([router, instance]: [typeof GenRouter, GenRouter]) => { const expressRouter = express.Router(); expressRouter.use(...router[keyForBaseMiddlewares]); router[keyForRouteMap].forEach((route) => { expressRouter[mapEnumToExpressFuncName(route.verb)]( route.route, route.middlewares, (req: Request, res: Response) => runSync( (req, res) => router.cast( [router, instance[keyForIdSymbol]], route.verb + route.route, [req, res] ), req, res ) ); }); app.use(router[keyForBasePath], expressRouter); }); const server = createServer(app); return server; } function buildSocketServer( channels: [typeof GenChannel, GenChannel][], serverOpt?: Partial<ServerOptions> ): Server { const io = new SocketServer(serverOpt); const server = require("http").createServer(); channels.forEach(([channel, instance]: [typeof GenChannel, GenChannel]) => { const namespace = io.of(channel[keyForNamespace]); channel[keyForBaseMiddlewares].forEach((middleware) => namespace.use(middleware) ); namespace.on("connection", (socket: Socket) => { channel[keyForGateMap].forEach((gate) => { gate.middlewares.forEach((middleware) => socket.use(middleware)); socket.on(gate.event, (...args: any[]) => { runSync( (io, namespace, socket, data) => channel.cast([channel, instance[keyForIdSymbol]], gate.event, [ io, namespace, socket, data, ]), io, namespace, socket, args ); }); }); }); }); io.attach(server); return server; } export { buildExpressApp, buildSocketServer, runSync }; <file_sep>/src/annotations/endpoint.ts import { GenEndpoint } from "../interfaces/genendpoint"; import { keyForServerPort, keyForSocketServerPort } from "../utils/symbols"; import { TransportEmitter } from "torrjs-core/src/transports/interface"; function Endpoint( transport: TransportEmitter, port?: number, socketPort?: number, externalTransports?: { [key: string]: TransportEmitter } & { internal?: never; } ) { return <T extends typeof GenEndpoint>(constructor: T) => { Reflect.defineProperty(constructor, keyForServerPort, { configurable: false, enumerable: true, value: port || 80, writable: false, }); Reflect.defineProperty(constructor, keyForSocketServerPort, { configurable: false, enumerable: true, value: socketPort || 3000, writable: false, }); Reflect.defineProperty(constructor, "eventEmitter", { configurable: false, enumerable: false, value: transport, writable: false, }); const externalTransportsMap: Map<string, TransportEmitter> = new Map(); if (externalTransports) { Object.keys(externalTransports).forEach((key) => { externalTransportsMap.set(key, externalTransports[key]); }); } Reflect.defineProperty(constructor, "externalEventEmitters", { configurable: false, enumerable: false, value: externalTransportsMap, writable: false, }); }; } export { Endpoint }; <file_sep>/src/annotations/route.ts import "reflect-metadata"; import { GenRouter } from "../interfaces/genrouter"; import { keyForMetadataMapSymbol } from "torrjs-core/src/utils/symbols"; import { HttpVerb, ExpressMiddleware } from "../utils/types"; import { keyForMetadataRouteMap } from "../utils/symbols"; function route( verb: HttpVerb, route: string, middlewares: ExpressMiddleware[] ) { return <T extends GenRouter, U extends string>( target: T, propertyKey: U & (U extends "init" ? never : U), _descriptor: PropertyDescriptor ) => { let map: Map<string, string> = Reflect.getOwnMetadata(keyForMetadataMapSymbol, target) || new Map<string, string>(); map.set(verb + route, propertyKey); Reflect.defineMetadata(keyForMetadataMapSymbol, map, target); let mapRoute: Map< string, { verb: HttpVerb; route: string; middlewares: ExpressMiddleware[] } > = Reflect.getOwnMetadata(keyForMetadataRouteMap, target) || new Map<string, string>(); mapRoute.set(route, { verb, route, middlewares: middlewares || [] }); Reflect.defineMetadata(keyForMetadataRouteMap, mapRoute, target); }; } export { route }; <file_sep>/src/utils/types.ts import { Request, Response, NextFunction } from "express"; import { Socket } from "socket.io"; type ExpressMiddleware = ( req: Request, res: Response, next: NextFunction ) => void; type SocketIoMiddleware = (socket: Socket, next: Function) => void; type SocketMiddleware = (events: any[], next: Function) => void; enum HttpVerb { GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH, CONNECT, TRACE, } export { ExpressMiddleware, HttpVerb, SocketIoMiddleware, SocketMiddleware }; <file_sep>/src/annotations/router.ts import { keyForMetadataMapSymbol, keyForMapSymbol, } from "torrjs-core/src/utils/symbols"; import { InMemoryEmitter } from "torrjs-core/src/transports/in-memory-emitter"; import { GenRouter } from "../interfaces/genrouter"; import { ExpressMiddleware, HttpVerb } from "../utils/types"; import { keyForMetadataRouteMap, keyForRouteMap, keyForBasePath, keyForBaseMiddlewares, } from "../utils/symbols"; function Router( transport: InMemoryEmitter, basePath: string, middlewares?: ExpressMiddleware[] ) { return <T extends typeof GenRouter>(constructor: T) => { const map: Map<string, string> = Reflect.getOwnMetadata(keyForMetadataMapSymbol, constructor.prototype) || new Map(); Reflect.defineProperty(constructor, keyForMapSymbol, { configurable: false, enumerable: true, value: map, writable: false, }); Reflect.deleteMetadata(keyForMetadataMapSymbol, constructor.prototype); const mapRoute: Map< string, { verb: HttpVerb; route: string; middlewares: ExpressMiddleware[] } > = Reflect.getOwnMetadata(keyForMetadataRouteMap, constructor.prototype) || new Map(); Reflect.defineProperty(constructor, keyForRouteMap, { configurable: false, enumerable: true, value: mapRoute, writable: false, }); Reflect.deleteMetadata(keyForMetadataRouteMap, constructor.prototype); Reflect.defineProperty(constructor, keyForBasePath, { configurable: false, enumerable: true, value: basePath, writable: false, }); Reflect.defineProperty(constructor, keyForBaseMiddlewares, { configurable: false, enumerable: true, value: middlewares || [], writable: false, }); Reflect.defineProperty(constructor, "eventEmitter", { configurable: false, enumerable: false, value: transport, writable: false, }); }; } export { Router }; <file_sep>/src/annotations/gate.ts import "reflect-metadata"; import { GenRouter } from "../interfaces/genrouter"; import { keyForMetadataMapSymbol } from "torrjs-core/src/utils/symbols"; import { SocketMiddleware } from "../utils/types"; import { keyForMetadataGateMap } from "../utils/symbols"; function gate(event: string, middlewares?: SocketMiddleware[]) { return <T extends GenRouter, U extends string>( target: T, propertyKey: U & (U extends "init" ? never : U), _descriptor: PropertyDescriptor ) => { let map: Map<string, string> = Reflect.getOwnMetadata(keyForMetadataMapSymbol, target) || new Map<string, string>(); map.set(event, propertyKey); Reflect.defineMetadata(keyForMetadataMapSymbol, map, target); let mapGate: Map< string, { event: string; middlewares: SocketMiddleware[] } > = Reflect.getOwnMetadata(keyForMetadataGateMap, target) || new Map<string, string>(); mapGate.set(event, { event, middlewares: middlewares || [] }); Reflect.defineMetadata(keyForMetadataGateMap, mapGate, target); }; } export { gate }; <file_sep>/README.md # torrjs-server torrjs http and socket server adapter
b1722847a423d3f6544191944f94e7b24c0a8f06
[ "Markdown", "TypeScript" ]
12
TypeScript
ndY0/torrjs-server
49354bac10b5d8f0e0c39fc7330e0c569c3d52d9
e09f474374e265163b8de21fc91e6de4818fc4f3
refs/heads/master
<file_sep>package controller import "github.com/gin-gonic/gin" func Index(c *gin.Context) { c.String(400, "post to /push") }
6062da38e108a8d6e47f503e47c1f910cfa55065
[ "Go" ]
1
Go
ttys3/wechat-work-message-push-go
d955f65c5f3a48fb4ccbdac6cbc8a8a2070f3cf5
c4ba7237c380e4d98213210052382aaa06480b4b
refs/heads/master
<file_sep>var http = require('http'); var cheerio = require('cheerio'); var endpoint = 'http://www.mollymoon.com/flavors/seasonal'; http.get(endpoint, function (res) { var noaaResponseString = ''; console.log('Status Code: ' + res.statusCode); if (res.statusCode != 200) { // tideResponseCallback(new Error("Non 200 Response")); } res.on('data', function (data) { noaaResponseString += data; }); res.on('end', function () { $ = cheerio.load(noaaResponseString); flavors = $('.product > strong'); flavs = flavors.text().split(' '); flavs = flavs.filter(String); flavs = flavs.filter(function(n){ return n != "\n" }); flavs = flavs.join(' '); console.log(flavs); response.tell(flavs, "MollyMoon", flavs); }); }).on('error', function (e) { console.log("Communications error: " + e.message); }); <file_sep>/** Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * This sample shows how to create a Lambda function for handling Alexa Skill requests that: * - Web service: communicate with an external web service to get tide data from NOAA CO-OPS API (http://tidesandcurrents.noaa.gov/api/) * - Multiple optional slots: has 2 slots (city and date), where the user can provide 0, 1, or 2 values, and assumes defaults for the unprovided values * - DATE slot: demonstrates date handling and formatted date responses appropriate for speech * - Custom slot type: demonstrates using custom slot types to handle a finite set of known values * - Dialog and Session state: Handles two models, both a one-shot ask and tell model, and a multi-turn dialog model. * If the user provides an incorrect slot in a one-shot model, it will direct to the dialog model. See the * examples section for sample interactions of these models. * - Pre-recorded audio: Uses the SSML 'audio' tag to include an ocean wave sound in the welcome response. * * Examples: * One-shot model: * User: "Alexa, ask Tide Pooler when is the high tide in Seattle on Saturday" * Alexa: "Saturday June 20th in Seattle the first high tide will be around 7:18 am, * and will peak at ..."" * Dialog model: * User: "Alexa, open Tide Pooler" * Alexa: "Welcome to Tide Pooler. Which city would you like tide information for?" * User: "Seattle" * Alexa: "For which date?" * User: "this Saturday" * Alexa: "Saturday June 20th in Seattle the first high tide will be around 7:18 am, * and will peak at ..."" */ /** * App ID for the skill */ var APP_ID = undefined;//replace with 'amzn1.echo-sdk-ams.app.[your-unique-value-here]'; var http = require('http'), alexaDateUtil = require('./alexaDateUtil'); cheerio = require('cheerio'); /** * The AlexaSkill prototype and helper functions */ var AlexaSkill = require('./AlexaSkill'); /** * TidePooler is a child of AlexaSkill. * To read more about inheritance in JavaScript, see the link below. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance */ var MollyMoon = function () { AlexaSkill.call(this, APP_ID); }; // Extend AlexaSkill MollyMoon.prototype = Object.create(AlexaSkill.prototype); MollyMoon.prototype.constructor = MollyMoon; // ----------------------- Override AlexaSkill request and intent handlers ----------------------- // MollyMoon.prototype.eventHandlers.onSessionStarted = function (sessionStartedRequest, session) { // console.log("onSessionStarted requestId: " + sessionStartedRequest.requestId // + ", sessionId: " + session.sessionId); // // any initialization logic goes here // }; // MollyMoon.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) { // console.log("onLaunch requestId: " + launchRequest.requestId + ", sessionId: " + session.sessionId); // handleWelcomeRequest(response); // }; // MollyMoon.prototype.eventHandlers.onSessionEnded = function (sessionEndedRequest, session) { // console.log("onSessionEnded requestId: " + sessionEndedRequest.requestId // + ", sessionId: " + session.sessionId); // // any cleanup logic goes here // }; /** * override intentHandlers to map intent handling functions. */ MollyMoon.prototype.intentHandlers = { "OneshotMollyMoonIntent": function (intent, session, response) { handleOneshotMollyMoonRequest(intent, session, response); }, "AMAZON.HelpIntent": function (intent, session, response) { handleHelpRequest(response); }, "AMAZON.StopIntent": function (intent, session, response) { var speechOutput = "Goodbye"; response.tell(speechOutput); }, "AMAZON.CancelIntent": function (intent, session, response) { var speechOutput = "Goodbye"; response.tell(speechOutput); } }; // -------------------------- TidePooler Domain Specific Business Logic -------------------------- // example city to NOAA station mapping. Can be found on: http://tidesandcurrents.noaa.gov/map/ function handleHelpRequest(response) { var repromptText = "Which city would you like tide information for?"; var speechOutput = "I can lead you through providing a city and " + "day of the week to get tide information, " + "or you can simply open Tide Pooler and ask a question like, " + "get tide information for Seattle on Saturday. " + "For a list of supported cities, ask what cities are supported. " + "Or you can say exit. " + repromptText; response.ask(speechOutput, repromptText); } /** * This handles the one-shot interaction, where the user utters a phrase like: * 'Alexa, open Tide Pooler and get tide information for Seattle on Saturday'. * If there is an error in a slot, this will guide the user to the dialog approach. */ function handleOneshotMollyMoonRequest(intent, session, response) { var endpoint = 'http://www.mollymoon.com/flavors/seasonal'; http.get(endpoint, function (res) { var noaaResponseString = ''; console.log('Status Code: ' + res.statusCode); if (res.statusCode != 200) { // tideResponseCallback(new Error("Non 200 Response")); } res.on('data', function (data) { noaaResponseString += data; }); res.on('end', function () { $ = cheerio.load(noaaResponseString); flavors = $('.product > strong'); flavs = flavors.text().split(' '); flavs = flavs.filter(String); flavs = flavs.filter(function(n){ return n != "\n" }); flavs = flavs.join(' '); console.log(flavs); response.tell(flavs, "MollyMoon", flavs); }); }).on('error', function (e) { console.log("Communications error: " + e.message); }); } // Create the handler that responds to the Alexa Request. exports.handler = function (event, context) { var mollyMoon = new MollyMoon(); mollyMoon.execute(event, context); };
ededaa9060a15719c1b6313a643305f6d9d2ef20
[ "JavaScript" ]
2
JavaScript
hsuhanooi/molly-moon-alexa
e6c461c4a942db0ff1ea3f97480b03232eebe200
fbd78b89bbbf587140ca61acd4af692a637d7009
refs/heads/master
<file_sep>export const SET_USER = "SET_USER"; export type SET_USER_ACTION = { type: typeof SET_USER, user: TUser, }; export type TUserAction = SET_USER_ACTION; export type TUser = { name: string, }; export type TUserState = { user?: TUser, }; <file_sep>import { TBoard } from "../../views/desktop/board/board.types"; import { ADD_CARD_TO_COLUMN, CHANGE_ALL_CARD_STATUS, CHANGE_BOARD_STATE, CHANGE_CARD, INIT_BOARD, TBoardAction, } from "./types"; import _ from "lodash"; import { UPDATE_USERS } from "./types"; export const initialBoardState: TBoard = { state: "hidden", columns: [ {id: "1", title: "Continue", cards: []}, {id: "2", title: "Improvments", cards: []}, {id: "3", title: "Idea", cards: []}, {id: "4", title: "Flower", cards: []}, ], users: [], }; export const boardReducer = (state: TBoard = initialBoardState, action: TBoardAction) => { switch (action.type) { case ADD_CARD_TO_COLUMN: { const newColumns = state.columns.map((c) => { if (c.id !== action.columnId) { return c; } return { ...c, cards: [...c.cards, action.card], }; }); return { ...state, columns: newColumns, }; } case CHANGE_ALL_CARD_STATUS: { const newColumns = state.columns.map((c) => { const newCards = c.cards.map((card) => { return { ...card, status: {...action.status}, }; }); return { ...c, cards: newCards, }; }); return { ...state, columns: newColumns, }; } case CHANGE_CARD: { const {card: changedCard} = action; const newColumns = state.columns.map((col) => { const newCards = col.cards.map((card) => { if (card.id !== changedCard.id) { return card; } return changedCard; }); return { ...col, cards: newCards, }; }); return { ...state, columns: newColumns, }; } case CHANGE_BOARD_STATE: { const boardState = action.state; return { ...state, state: boardState, }; } case INIT_BOARD: { const cards = action.board.cards; const newColumns = state.columns.map((col) => { const newColCards = cards .filter(card => card.columnId === col.id) .map(card => card.card); return { ...col, state: action.board.state, cards: _.uniqBy([...col.cards, ...newColCards], "id"), }; }); return { ...state, state: action.board.state, columns: newColumns, users: action.board.users, }; } case UPDATE_USERS: { return { ...state, users: action.users, }; } default: return state; } }; <file_sep>import { createStore, applyMiddleware, compose, combineReducers, Reducer } from "redux"; import { createEpicMiddleware } from "redux-observable"; import logger from "redux-logger"; import { boardReducer } from "./board/reducer"; import { TBoardAction } from "./board/types"; import { TBoard } from "../views/desktop/board/board.types"; import { errorHandlerReducer } from "./errorHandler/reducer"; import { TErrorHandlerState, TErrorAction } from "./errorHandler/types"; import { userReducer } from "./user/reducer"; import { TUserState, TUserAction } from "./user/types"; import { TShowingCardState, TShowingCardAction } from "./mobile/types"; import { mobileShowingCardReducer } from "./mobile/reducer"; import rootEpic from "./epics/index"; const isDev = process.env.NODE_ENV === "development"; export type RootState = { board: TBoard, errorHandler: TErrorHandlerState, user: TUserState, mobile: TShowingCardState, }; export type RootAction = TBoardAction | TErrorAction | TUserAction | TShowingCardAction | {type: "NOOP"}; const rootReducer: Reducer<RootState> = combineReducers({ board: boardReducer, errorHandler: errorHandlerReducer, user: userReducer, mobile: mobileShowingCardReducer, }); const epicMiddleware = createEpicMiddleware(rootEpic); const configureStore = (initialState?: RootState) => { // compose enhancers const enhancer = isDev ? compose( applyMiddleware( logger, epicMiddleware, ), ) : compose( applyMiddleware( epicMiddleware, ), ); // create store return createStore<RootState>( rootReducer, initialState!, enhancer, ); }; // pass an optional param to rehydrate state on app start const store = configureStore(); // export store singleton instance export default store; <file_sep>// export type TCardStatus = "unread" | "read" | "edit" | "resolved" | "error"; export type TCardStatusUnread = {type: "unread"}; export type TCardStatusRead = {type: "read"}; export type TCardStatusEdit = {type: "edit"}; export type TCardStatusResolving = {type: "resolving", message: string}; export type TCardStatusResolved = {type: "resolved", message: string}; export type TCardStatusError = {type: "error", error: Error}; export type TCardStatus = TCardStatusEdit | TCardStatusError | TCardStatusRead | TCardStatusResolving | TCardStatusResolved | TCardStatusUnread; export type TCard = { id: string, author: string, description: string, status: TCardStatus, }; <file_sep>import { TError } from "../../views/common/errorHandlers/error.types"; export const THROW_ERROR = "THROW_ERROR"; export type THROW_ERROR_ACTION = { type: typeof THROW_ERROR, error: TError, }; export const RESOLVE_ERROR = "RESOLVE_ERROR"; export type RESOLVE_ERROR_ACTION = { type: typeof RESOLVE_ERROR, }; export type TErrorAction = THROW_ERROR_ACTION | RESOLVE_ERROR_ACTION; export type TErrorHandlerState = { error?: TError, }; <file_sep>import { TCard, TCardStatus } from "../../views/desktop/card/card.types"; import { TUser } from "../../views/desktop/board/board.types"; export const ADD_CARD_TO_COLUMN = "ADD_CARD_TO_COLUMN"; export type ADD_CARD_TO_COLUMN_ACTION = { type: typeof ADD_CARD_TO_COLUMN, columnId: string, card: TCard, }; export const CHANGE_ALL_CARD_STATUS = "CHANGE_ALL_CARD_STATUS"; export type CHANGE_ALL_CARD_STATUS_ACTION = { type: typeof CHANGE_ALL_CARD_STATUS, status: TCardStatus, }; export const CHANGE_CARD = "CHANGE_CARD"; export type CHANGE_CARD_ACTION = { type: typeof CHANGE_CARD, card: TCard, }; export const CHANGE_BOARD_STATE = "CHANGE_BOARD_STATE"; export type CHANGE_BOARD_STATE_ACTION = { type: typeof CHANGE_BOARD_STATE, state: string, }; export const INIT_BOARD = "INIT_BOARD"; export type INIT_BOARD_ACTION = { type: typeof INIT_BOARD, board: { state: string, cards: Array<{columnId: string, card: TCard}>, users: TUser[], }, }; export const UPDATE_USERS = "UPDATE_USERS"; export type UPDATE_USERS_ACTION = { type: typeof UPDATE_USERS, users: TUser[], }; export type TBoardAction = ADD_CARD_TO_COLUMN_ACTION | CHANGE_ALL_CARD_STATUS_ACTION | CHANGE_CARD_ACTION | CHANGE_BOARD_STATE_ACTION | INIT_BOARD_ACTION | UPDATE_USERS_ACTION; <file_sep>import "rxjs"; import { combineEpics, ActionsObservable } from "redux-observable"; // tslint:disable-next-line import { Observable, Subject } from "rxjs"; import { MiddlewareAPI } from "redux"; import { RootState, RootAction } from "../store"; import { TCard } from "../../views/desktop/card/card.types"; import { TBoardState } from "../../views/desktop/board/board.types"; export const SOCKET_ADD_CARD = "SOCKET_ADD_CARD"; export type SOCKET_ADD_CARD_ACTION = { type: typeof SOCKET_ADD_CARD, }; export const SOCKET_CARD_SUB = "SOCKET_CARD_SUB"; export type SOCKET_CARD_SUB_ACTION = { type: typeof SOCKET_CARD_SUB, }; export const SOCKET_ADD_CARD_COLUMN = "SOCKET_ADD_CARD_COLUMN"; export type SOCKET_ADD_CARD_COLUMN_ACTION = { type: typeof SOCKET_ADD_CARD_COLUMN, columnId: string, card: TCard, }; export const SOCKET_CHANGE_BOARD_STATE = "SOCKET_CHANGE_BOARD_STATE"; export type SOCKET_CHANGE_BOARD_STATE_ACTION = { type: typeof SOCKET_CHANGE_BOARD_STATE, boardState: TBoardState, }; export const SOCKET_CHANGE_CARD = "SOCKET_CHANGE_CARD"; export type SOCKET_CHANGE_CARD_ACTION = { type: typeof SOCKET_CHANGE_CARD, card: TCard, }; export const SOCKET_LIVE_CHANGE_CARD = "SOCKET_LIVE_CHANGE_CARD"; export type SOCKET_LIVE_CHANGE_CARD_ACTION = { type: typeof SOCKET_LIVE_CHANGE_CARD, card: TCard, }; export const SOCKET_MOBILE_SHOW_CARD = "SOCKET_MOBILE_SHOW_CARD"; export type SOCKET_MOBILE_SHOW_CARD_ACTION = { type: typeof SOCKET_MOBILE_SHOW_CARD, card: TCard, }; type TSocketActions = SOCKET_ADD_CARD_ACTION | SOCKET_CARD_SUB_ACTION | SOCKET_CHANGE_BOARD_STATE_ACTION | SOCKET_CHANGE_CARD_ACTION | SOCKET_LIVE_CHANGE_CARD_ACTION | SOCKET_ADD_CARD_COLUMN_ACTION | SOCKET_MOBILE_SHOW_CARD_ACTION; type TActions = TSocketActions | RootAction; export const actionCreators = { socketAddCard: (): SOCKET_ADD_CARD_ACTION => ({type: SOCKET_ADD_CARD}), socketCardSub: (): SOCKET_CARD_SUB_ACTION => ({type: SOCKET_CARD_SUB}), socketAddCardToColumn: (columnId: string, card: TCard): SOCKET_ADD_CARD_COLUMN_ACTION => ({ type: SOCKET_ADD_CARD_COLUMN, columnId: columnId, card: card, }), socketChangeBoardState: (boardState: TBoardState): SOCKET_CHANGE_BOARD_STATE_ACTION => ({ type: SOCKET_CHANGE_BOARD_STATE, boardState: boardState, }), socketChangeCard: (card: TCard): SOCKET_CHANGE_CARD_ACTION => ({ type: SOCKET_CHANGE_CARD, card: card, }), socketMobileShowCard: (card: TCard): SOCKET_MOBILE_SHOW_CARD_ACTION => ({ type: SOCKET_MOBILE_SHOW_CARD, card: card, }), socketLiveChangeCard: (card: TCard): SOCKET_LIVE_CHANGE_CARD_ACTION => ({ type: SOCKET_LIVE_CHANGE_CARD, card: card, }), }; const openSubject = new Subject(); const wsPath = process.env.WS_PATH || "ws://localhost:3000/socket"; export const socket$ = Observable.webSocket({ url: wsPath, openObserver: openSubject, closeObserver: { next: (val: any) => console.info("closing", val)}, }); const wsEpic = (action$: ActionsObservable<TSocketActions>, store: MiddlewareAPI<RootState>): Observable<TActions> => action$.ofType(SOCKET_CARD_SUB) .mergeMap((action: TSocketActions) => socket$ .retry(20) // .takeUntil( // action$.ofType("CLOSE_TICKER_STREAM") // .filter(closeAction => closeAction.ticker === action.ticker), // ) .filter((serverAction: RootAction) => [ "ADD_CARD_TO_COLUMN", "INIT_BOARD", "CHANGE_BOARD_STATE", "CHANGE_CARD", "MOBILE_SHOW_CARD", "UPDATE_USERS", ].includes(serverAction.type)) .map((serverAction: RootAction) => serverAction) .catch((error) => { const errorAction: RootAction = {type: "THROW_ERROR", error: { message: "error", type: "error"}}; return Observable.of(errorAction); }), ); const wsActionsEpic = (action$: ActionsObservable<TSocketActions>, store: MiddlewareAPI<RootState>): Observable<TActions> => action$.ofType( SOCKET_ADD_CARD_COLUMN, SOCKET_CHANGE_BOARD_STATE, SOCKET_CHANGE_CARD, SOCKET_MOBILE_SHOW_CARD, ) .map((action: TSocketActions) => socket$.next(JSON.stringify(action))) .mapTo({type: "NOOP"} as RootAction); const wsLiveEpic = (action$: ActionsObservable<TSocketActions>, store: MiddlewareAPI<RootState>): Observable<TActions> => action$.ofType( SOCKET_LIVE_CHANGE_CARD, ) .debounceTime(250) .map((action: TSocketActions) => socket$.next(JSON.stringify(action))) .mapTo({type: "NOOP"} as RootAction); const testEpic = (action$: ActionsObservable<TSocketActions>, store: MiddlewareAPI<RootState>): Observable<TActions> => action$.ofType(SOCKET_CARD_SUB) .switchMap((action: TSocketActions) => openSubject .do(() => socket$.next(JSON.stringify({ type: "SOCKET_USER_JOIN", user: store.getState().user, }))), ).mapTo({type: "NOOP"} as RootAction); const rootEpic = combineEpics( wsEpic, wsActionsEpic, wsLiveEpic, testEpic, ); export default rootEpic; <file_sep>import { TError } from "../../views/common/errorHandlers/error.types"; import { THROW_ERROR, THROW_ERROR_ACTION, RESOLVE_ERROR, RESOLVE_ERROR_ACTION, } from "./types"; // Action Creators export const actionCreators = { throwError: (error: TError): THROW_ERROR_ACTION => ({ type: THROW_ERROR, error: error, }), resolveError: (): RESOLVE_ERROR_ACTION => ({ type: RESOLVE_ERROR, }), }; <file_sep>import { THROW_ERROR, RESOLVE_ERROR, TErrorAction, TErrorHandlerState, } from "./types"; export const initialErrorState: TErrorHandlerState = { error: undefined, }; export const errorHandlerReducer = (state: TErrorHandlerState = initialErrorState, action: TErrorAction) => { switch (action.type) { case THROW_ERROR: { return { ...state, error: action.error, }; } case RESOLVE_ERROR: { return { ...state, error: undefined, }; } default: return state; } }; <file_sep>import { TColumn } from "../column/column.types"; export type TBoardState = "hidden" | "showing" | "resolving"; export type TUser = { name: string }; export type TBoard = { state: TBoardState, columns: TColumn[], users: TUser[], }; <file_sep>const express = require("express"); const WebSocket = require("ws"); const _ = require("lodash"); const isDev = process.env.NODE_ENV !== "production"; const port = isDev ? 3001 : process.env.PORT; const app = express(); if (!isDev) { app.use(express.static("build")); app.get("/*", (req, res) => { res.sendFile(path.join(__dirname, "build/index.html")); res.end(); }); } const server = app.listen(port, "0.0.0.0", (err, res) => { if (err) { return console.log(err); } console.log(`Environment: ${process.env.NODE_ENV}`) console.log(`Listening on port ${port}`); }); let webSockets = {}; let users = []; let board = { state: "hidden", cards: [], } const getBoard = () => { return { ...board, users: [...Object.values(webSockets)], } } const handleWSMessages = (wss, ws, req, msg) => { console.log(msg); switch (msg.type) { case "SOCKET_CHANGE_BOARD_STATE": { board.state = msg.boardState; wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({type: "CHANGE_BOARD_STATE", state: board.state})); } }); break; } case "SOCKET_GET_BOARD_STATE": { ws.send(JSON.stringify({ type: "INIT_BOARD", board: getBoard(), })); break; } case "SOCKET_ADD_CARD_COLUMN": { const data = { columnId: msg.columnId, card: { ...msg.card, id: _.uniqueId("card"), } } board.cards = [...board.cards, data]; wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ type: "ADD_CARD_TO_COLUMN", ...data })); } }); break; } case "SOCKET_CHANGE_CARD": { const data = { card: msg.card } board.cards = board.cards.map((card) => { if (card.card.id === data.card.id) { return { ...card, card: data.card } } return card; }); wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ type: "CHANGE_CARD", ...data })); } }); break; } case "SOCKET_MOBILE_SHOW_CARD": { const data = { card: msg.card } wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ type: "MOBILE_SHOW_CARD", ...data })); } }); break; } case "SOCKET_LIVE_CHANGE_CARD": { const data = { card: msg.card } wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ type: "MOBILE_SHOW_CARD", ...data })); } }); break; } case "SOCKET_USER_JOIN": { webSockets[ws.id] = msg.user.user; wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ type: "UPDATE_USERS", users: [...Object.values(webSockets)], })); } }); break; } default: console.log("Something else called", msg.type); break; } } const wss = new WebSocket.Server({server: server}); wss.on("connection", (ws, req) => { console.log("connected"); ws.id = _.uniqueId(); ws.send(JSON.stringify({ type: "INIT_BOARD", board: getBoard(), })); ws.on("message", (msg) => { handleWSMessages(wss, ws, req, JSON.parse(msg)); }); ws.on("close", () => { console.log("close"); delete webSockets[ws.id]; wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify({ type: "UPDATE_USERS", users: [...Object.values(webSockets)], })); } }); }); ws.on("open", () => { console.log("open"); }); ws.on("ping", () => { console.log("ping") }); ws.on("pong", () => { console.log("pong") }); ws.on("error", (e) => { console.log("error", e) }); }); <file_sep>import { TCard } from "../card/card.types"; export type TColumn = { id: string, title: string, cards: TCard[], }; <file_sep>import { MOBILE_SHOW_CARD, TShowingCardState, TShowingCardAction, } from "./types"; export const initialErrorState: TShowingCardState = { card: undefined, }; export const mobileShowingCardReducer = (state: TShowingCardState = initialErrorState, action: TShowingCardAction) => { switch (action.type) { case MOBILE_SHOW_CARD: { return { ...state, card: action.card, }; } default: return state; } }; <file_sep>import { TCard } from "../../views/desktop/card/card.types"; import { MOBILE_SHOW_CARD, MOBILE_SHOW_CARD_ACTION, } from "./types"; // Action Creators export const actionCreators = { mobileShowCard: (card?: TCard): MOBILE_SHOW_CARD_ACTION => ({ type: MOBILE_SHOW_CARD, card: card, }), }; <file_sep>import { SemanticCOLORS } from "semantic-ui-react"; import { TCardStatus } from "../views/desktop/card/card.types"; /** * @export returntypeof() - extract return type of an "expression" * @template RT - Generic Type * @param expression: (...params: any[]) => RT * @returns RT */ export function returntypeof<RT>(expression: (...params: any[]) => RT): RT { const returnValue: any = {}; return returnValue; } /** * Returns a Semantic color depending on the column id * * @export * @param {string} columnId * @returns {SemanticCOLORS} */ export function getColumnColor(columnId: string): SemanticCOLORS { switch (columnId) { case "1": return "green"; case "2": return "teal"; case "3": return "blue"; case "4": return "purple"; default: return "black"; } } export function getCardColor({type: cardStatusType}: TCardStatus): SemanticCOLORS { switch (cardStatusType) { case "unread": return "yellow"; case "read": return "green"; case "error": return "red"; case "resolving": case "resolved": return "purple"; default: return "orange"; } } <file_sep>import { TCard, TCardStatus } from "../../views/desktop/card/card.types"; import { TBoardState } from "../../views/desktop/board/board.types"; import { ADD_CARD_TO_COLUMN, ADD_CARD_TO_COLUMN_ACTION, CHANGE_ALL_CARD_STATUS, CHANGE_ALL_CARD_STATUS_ACTION, CHANGE_CARD, CHANGE_CARD_ACTION, CHANGE_BOARD_STATE, CHANGE_BOARD_STATE_ACTION, } from "./types"; // Action Creators export const actionCreators = { addCardToColumn: (columnId: string, card: TCard): ADD_CARD_TO_COLUMN_ACTION => ({ type: ADD_CARD_TO_COLUMN, columnId: columnId, card: card, }), changeAllCardsStatus: (status: TCardStatus): CHANGE_ALL_CARD_STATUS_ACTION => ({ type: CHANGE_ALL_CARD_STATUS, status: status, }), changeCard: (card: TCard): CHANGE_CARD_ACTION => ({ type: CHANGE_CARD, card: card, }), changeBoardState: (boardState: TBoardState): CHANGE_BOARD_STATE_ACTION => ({ type: CHANGE_BOARD_STATE, state: boardState, }), }; <file_sep>import { TUserAction, TUserState, SET_USER, } from "./types"; export const initialUserState: TUserState = { user: undefined, }; export const userReducer = (state: TUserState = initialUserState, action: TUserAction) => { switch (action.type) { case SET_USER: { return { ...state, user: action.user, }; } default: return state; } }; <file_sep>export type TController = { }; <file_sep>import { TCard } from "../../views/desktop/card/card.types"; export const MOBILE_SHOW_CARD = "MOBILE_SHOW_CARD"; export type MOBILE_SHOW_CARD_ACTION = { type: typeof MOBILE_SHOW_CARD, card?: TCard, }; export type TShowingCardAction = MOBILE_SHOW_CARD_ACTION; export type TShowingCardState = { card?: TCard, }; <file_sep>export type TErrorSeverity = "warning" | "error"; export type TError = { message: string, type: TErrorSeverity, };<file_sep>import { SET_USER, SET_USER_ACTION, TUser, } from "./types"; // Action Creators export const actionCreators = { setUser: (user: TUser): SET_USER_ACTION => ({ type: SET_USER, user: user, }), };
783228b79d353d98d96081735c30b256c86182f2
[ "JavaScript", "TypeScript" ]
21
TypeScript
proProbe/retropoker
e4131b91c7576ce5d658c3b528ab0f08fb952c17
1034e23b575943ec5dfcf84f341f55a85a2a834f
refs/heads/master
<file_sep>import networkx as nx def noedges(): noedges = nx.DiGraph() noedges.add_nodes_from(range(3)) return noedges def directed(): directed = nx.DiGraph() directed.add_nodes_from(range(4)) directed.add_edges_from([ (0, 3), (1, 0), (2, 0), (2, 1), (3, 0) ]) return directed def selfloops(): selfloops = nx.MultiDiGraph() selfloops.add_nodes_from(range(3)) selfloops.add_edges_from([ (0, 0), (0, 1), (0, 2), (0, 2), (1, 0) ]) return selfloops def complete(): return nx.complete_graph(3, create_using=nx.DiGraph) def nonconnected(): """Non connected + nodes with no edges at all""" nonconnected = nx.MultiDiGraph() nonconnected.add_nodes_from(range(6)) nonconnected.add_edges_from([ (0, 1), (1, 2), (2, 3), (3, 0), (1, 0), (1, 0), (3, 2), (3, 3), (4, 4), (4, 4) ]) return nonconnected def karate(): karate = nx.Graph() karate.add_nodes_from(range(34)) karate.add_edges_from([ (1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (5, 0), (6, 0), (6, 4), (6, 5), (7, 0), (7, 1), (7, 2), (7, 3), (8, 0), (8, 2), (9, 2), (10, 0), (10, 4), (10, 5), (11, 0), (12, 0), (12, 3), (13, 0), (13, 1), (13, 2), (13, 3), (16, 5), (16, 6), (17, 0), (17, 1), (19, 0), (19, 1), (21, 0), (21, 1), (25, 23), (25, 24), (27, 2), (27, 23), (27, 24), (28, 2), (29, 23), (29, 26), (30, 1), (30, 8), (31, 0), (31, 24), (31, 25), (31, 28), (32, 2), (32, 8), (32, 14), (32, 15), (32, 18), (32, 20), (32, 22), (32, 23), (32, 29), (32, 30), (32, 31), (33, 8), (33, 9), (33, 13), (33, 14), (33, 15), (33, 18), (33, 19), (33, 20), (33, 22), (33, 23), (33, 26), (33, 27), (33, 28), (33, 29), (33, 30), (33, 31), (33, 32) ]) karate = karate.to_directed() return karate def graphs_for_test(): return { 'empty': nx.MultiDiGraph(), 'noedges': noedges(), 'directed': directed(), 'selfloops': selfloops(), 'complete': complete(), 'nonconnected': nonconnected(), 'karate': karate() } if __name__ == '__main__': for name, graph in graphs_for_test().items(): nx.nx_pydot.to_pydot(graph).write(f'{name}.png', format='png') <file_sep>import pytest import torch from torchgraphs import Graph def test_empty(): graph = Graph() validate_graph(graph) assert graph.num_nodes == 0 assert graph.node_features is None assert graph.node_features_shape is None assert graph.num_edges == len(graph.senders) == len(graph.receivers) == 0 assert graph.edge_features is None assert graph.edge_features_shape is None assert graph.global_features is None assert graph.global_features_shape is None def test_nodes(): graph = Graph(num_nodes=0) validate_graph(graph) assert graph.num_nodes == 0 graph = Graph(num_nodes=10) validate_graph(graph) assert graph.num_nodes == 10 graph = Graph(node_features=torch.rand(15, 2)) validate_graph(graph) assert graph.num_nodes == 15 assert graph.node_features_shape == (2,) with pytest.raises(ValueError): Graph(num_nodes=-1) with pytest.raises(ValueError): Graph(num_nodes=0, node_features=torch.rand(15, 2)) def test_edges(): graph = Graph(num_nodes=6, senders=torch.tensor([0, 1, 2, 5, 5]), receivers=torch.tensor([3, 4, 5, 5, 5])) validate_graph(graph) assert graph.num_edges == len(graph.senders) == len(graph.receivers) == 5 graph = Graph(num_nodes=6, edge_features=torch.rand(5, 2), senders=torch.tensor([0, 1, 2, 5, 5]), receivers=torch.tensor([3, 4, 5, 5, 5])) validate_graph(graph) assert graph.num_edges == len(graph.senders) == len(graph.receivers) == len(graph.edge_features) == 5 assert graph.edge_features_shape == (2,) # Negative number of edges with pytest.raises(ValueError): Graph(num_edges=-1) # Senders and receivers not given with pytest.raises(ValueError): Graph(num_edges=3) # Senders not given with pytest.raises(ValueError): Graph(num_edges=3, receivers=torch.arange(10)) # Receivers not given with pytest.raises(ValueError): Graph(num_edges=3, senders=torch.arange(10)) # Senders and receivers given, but not matching number of edges with pytest.raises(ValueError): Graph(num_edges=3, senders=torch.arange(10), receivers=torch.arange(10)) # Edges on a graph with no nodes with pytest.raises(ValueError): Graph(senders=torch.tensor([0, 1, 2]), receivers=torch.tensor([3, 4, 5])) # Different number of senders and receivers with pytest.raises(ValueError): Graph(num_nodes=6, senders=torch.tensor([0]), receivers=torch.tensor([3, 4, 5])) # Indexes out-of-bounds with pytest.raises(ValueError): Graph(num_nodes=6, senders=torch.tensor([0, 1, 1000]), receivers=torch.tensor([3, 4, 5])) # Indexes out-of-bounds with pytest.raises(ValueError): Graph(num_nodes=6, senders=torch.tensor([0, 1, 2]), receivers=torch.tensor([3, 4, 1000])) # Indexes out-of-bounds with pytest.raises(ValueError): Graph(num_nodes=6, senders=torch.tensor([-1000, 1, 2]), receivers=torch.tensor([3, 4, 5])) # Indexes out-of-bounds with pytest.raises(ValueError): Graph(num_nodes=6, senders=torch.tensor([0, 1, 2]), receivers=torch.tensor([-1000, 4, 5])) # Senders, receivers and number of edges given, but not matching features with pytest.raises(ValueError): Graph(num_nodes=6, senders=torch.tensor([0, 1]), receivers=torch.tensor([3, 4]), edge_features=torch.rand(9, 2)) def test_globals(): graph = Graph(global_features=torch.rand(3)) validate_graph(graph) graph = Graph(node_features=torch.rand(6, 2), edge_features=torch.rand(5, 2), global_features=torch.rand(3), senders=torch.tensor([0, 0, 1, 1, 2]), receivers=torch.tensor([0, 0, 3, 4, 5])) validate_graph(graph) def validate_graph(graph: Graph): assert graph.num_nodes >= 0 assert graph.num_edges >= 0 assert graph.node_features is None or graph.num_nodes == len(graph.node_features) assert graph.num_edges == len(graph.senders) == len(graph.receivers) assert (graph.senders < graph.num_nodes).all() and (graph.senders >= 0).all() assert (graph.receivers < graph.num_nodes).all() and (graph.receivers >= 0).all() assert graph.edge_features is None or graph.num_edges == len(graph.edge_features) assert graph.global_features is None or graph.global_features.shape == graph.global_features_shape <file_sep>import dataclasses from typing import Optional, Iterator import torch import torch_scatter @dataclasses.dataclass class _BaseGraph(object): num_nodes: int = None num_edges: int = None node_features: Optional[torch.Tensor] = None edge_features: Optional[torch.Tensor] = None senders: torch.LongTensor = None receivers: torch.LongTensor = None _feature_fields = ('node_features', 'edge_features') _index_fields = ('senders', 'receivers') def __post_init__(self): # Try filling in missing info if self.num_nodes is None: self.num_nodes = len(self.node_features) if self.node_features is not None else 0 if self.num_edges is None or self.num_edges == 0: if self.senders is None: self.senders = torch.LongTensor() if self.receivers is None: self.receivers = torch.LongTensor() self.num_edges = len(self.senders) self._validate() def _validate(self): # Check nodes if self.num_nodes is None or self.num_nodes < 0: raise ValueError(f"`num_nodes` cannot be None or negative, got {self.num_nodes}") if self.node_features is not None and len(self.node_features) != self.num_nodes: raise ValueError(f"`num_nodes`, `len(node_features)` must match, " f"got {self.num_nodes}, {len(self.node_features)}") # Check edges if self.num_edges is None or self.num_nodes < 0: raise ValueError(f"`num_edges` cannot be None or negative, got {self.num_edges}") if self.senders is None or self.receivers is None: raise ValueError(f"`senders`, `receivers` cannot be None") if not (self.num_edges == len(self.senders) == len(self.receivers)): raise ValueError(f"`num_edges`, `len(senders)`, `len(receivers)` must match, " f"got {self.num_edges}, {len(self.senders)}, {len(self.receivers)}") if self.edge_features is not None and len(self.edge_features) != self.num_edges: raise ValueError(f"`num_edges`, `len(edge_features)` must match, " f"got {self.num_edges}, {len(self.edge_features)}") # Check out-of-bounds edge indexes send_oob = (self.senders < 0) | (self.senders >= self.num_nodes) recv_oob = (self.receivers < 0) | (self.receivers >= self.num_nodes) if send_oob.any(): wrongs = [f'{s.item()} -> {r.item()}' for s, r in zip(self.senders[send_oob], self.receivers[send_oob])] raise ValueError(f"Edge sender out of bounds for: {wrongs}") if recv_oob.any(): wrongs = [f'{s.item()} -> {r.item()}' for s, r in zip(self.senders[recv_oob], self.receivers[recv_oob])] raise ValueError(f"Edge receiver out of bounds for: {wrongs}") @property def sender_features(self): """For every edge, the features of the sender node. Examples: * Access the sender's features of a single edge >>> graph.sender_features[node_index] * Iterate over the the sender's features of every edge >>> iter(graph.sender_features) * Get a tensor of sender features with shape (num_edges, *node_features_shape) >>> graph.sender_features() """ return _SenderNodeView(self) @property def receiver_features(self): """For every edge, the features of the receiver node. Examples: * Access the receiver's features of a single edge >>> graph.receiver_features[node_index] * Iterate over the the receiver's features of every edge >>> iter(graph.receiver_features) * Get a tensor of receivers' features with shape (num_edges, *node_features_shape) >>> graph.receiver_features() """ return _ReceiverNodeView(self) @property def out_edge_features(self): """For every node, the features of the outgoing edges i.e. the features of the edges that have that node as sender Examples: * Access the features of the outgoing edges of a single node >>> graph.out_edge_features[node_index] * Iterate node by node over the features of the outgoing edges >>> iter(graph.out_edge_features) * Get a tensor of aggregated edge features with shape (num_nodes, *edge_features_shape) >>> graph.out_edge_features(aggregation='sum') """ return _OutEdgeView(self) edge_features_by_sender = out_edge_features @property def in_edge_features(self): """For every node, the features of the incoming edges, i.e. the features of the edges that have that node as receiver. Examples: * Access the features of the incoming edges of a single node >>> graph.in_edge_features[node_index] * Iterate node by node over the features of the incoming edges >>> iter(graph.in_edge_features) * Get a tensor of aggregated edge features with shape (num_nodes, *edge_features_shape) >>> graph.in_edge_features(aggregation='sum') """ return _InEdgeView(self) edge_features_by_receiver = in_edge_features @property def successor_features(self): """For every node, the features of the successor nodes. Examples: * Access the features of the successor nodes of a single node as a tensor of shape (num_successors, *node_features_shape) >>> graph.successor_features[node_index] * Iterate over the successors of every node >>> iter(graph.successor_features) * Get a tensor of aggregated successor features with shape (num_nodes, *node_features_shape) >>> graph.successor_features(aggregation='sum') """ return _SuccessorView(self) @property def predecessor_features(self): """For every node, the features of the predecessor nodes. Examples: * Access the features of the predecessor nodes of a single node as a tensor of shape (num_predecessors, *node_features_shape) >>> graph.predecessor_features[node_index] * Iterate over the predecessors of every node >>> iter(graph.predecessor_features) * Get a tensor of aggregated predecessor features with shape (num_nodes, *node_features_shape) >>> graph.predecessor_features(aggregation='sum') """ return _PredecessorView(self) def neighbors(self, node_index): """The indexes of the nodes that are directly reachable from the node `node_index`. """ return self.receivers[self.senders == node_index] def neighbors_features(self, node_index): """The features of the nodes that are directly reachable from the node `node_index`. """ return self.node_features.index_select(index=self.neighbors(node_index), dim=0) @property def degree(self) -> torch.LongTensor: """For every node, the number of edges adjacent to that node. If an edge is a self connection it is counted twice, both as outgoing and as incoming. """ return self.in_degree + self.out_degree @property def out_degree(self) -> torch.LongTensor: """For every node, the number edges pointing out from that node. I.e. the number of edges that have that node as a sender. """ # TODO still buggy return self.senders.new_zeros(self.num_nodes).index_add_( dim=0, index=self.senders, source=self.senders.new_ones(self.num_edges)) @property def in_degree(self) -> torch.LongTensor: """For every node, the number edges pointing in to that node. I.e. the number of edges that have that node as a receiver. """ return self.receivers.new_zeros(self.num_nodes).index_add_( dim=0, index=self.receivers, source=self.receivers.new_ones(self.num_edges)) @property def node_features_shape(self): return self.node_features.shape[1:] if self.node_features is not None else None @property def edge_features_shape(self): return self.edge_features.shape[1:] if self.edge_features is not None else None def cpu(self): return self.to('cpu') def cuda(self, device=None, non_blocking=False): if device is None: device = torch.cuda.current_device() return self.to(device, non_blocking) def to(self, device, non_blocking=False): feature_fields = { field_name: getattr(self, field_name).to(device=device, non_blocking=non_blocking) for field_name in self._feature_fields if getattr(self, field_name) is not None } index_fields = { field_name: getattr(self, field_name).to(device=device, non_blocking=non_blocking) for field_name in self._index_fields } return self.evolve(**index_fields, **feature_fields) def pin_memory(self): for field_name in self._index_fields + self._feature_fields: if getattr(self, field_name) is not None: setattr(self, field_name, getattr(self, field_name).pin_memory()) return self def requires_grad_(self, requires_grad=True): for field_name in self._feature_fields: if getattr(self, field_name) is not None: getattr(self, field_name).requires_grad_(requires_grad) return self def zero_grad_(self): for field_name in self._feature_fields: if getattr(self, field_name) is not None: getattr(self, field_name).grad = None return self def evolve(self, **updates): return dataclasses.replace(self, **updates) class _InOutEdgeView(object): def __init__(self, graph: _BaseGraph): self._graph = graph # TODO move these to the class definition or somewhere else self._pooling_functions = { 'mean': lambda src, idx: torch_scatter.scatter_mean(src, idx, dim=0, dim_size=graph.num_nodes), 'sum': lambda src, idx: torch_scatter.scatter_add(src, idx, dim=0, dim_size=graph.num_nodes), 'max': lambda src, idx: torch_scatter.scatter_max(src, idx, dim=0, dim_size=graph.num_nodes)[0], } def __len__(self): return self._graph.num_nodes def __getitem__(self, node_index) -> torch.Tensor: raise NotImplemented def __iter__(self) -> Iterator[torch.Tensor]: for node_index in range(self._graph.num_nodes): yield self[node_index] class _InEdgeView(_InOutEdgeView): def __call__(self, aggregation, *args, **kwargs) -> torch.Tensor: if isinstance(aggregation, str): aggregation = self._pooling_functions[aggregation] return aggregation(self._graph.edge_features, self._graph.receivers, *args, **kwargs) def __getitem__(self, node_index) -> torch.Tensor: return self._graph.edge_features[self._graph.receivers == node_index] class _OutEdgeView(_InOutEdgeView): def __call__(self, aggregation, *args, **kwargs) -> torch.Tensor: if isinstance(aggregation, str): aggregation = self._pooling_functions[aggregation] return aggregation(self._graph.edge_features, self._graph.senders, *args, **kwargs) def __getitem__(self, node_index) -> torch.Tensor: return self._graph.edge_features[self._graph.senders == node_index] class _NodeView(object): def __init__(self, graph: _BaseGraph): self._graph = graph def __len__(self): return self._graph.num_edges def __getitem__(self, edge_index) -> torch.Tensor: raise NotImplemented def __iter__(self) -> Iterator[torch.Tensor]: for edge_index in range(self._graph.num_edges): yield self[edge_index] class _ReceiverNodeView(_NodeView): def __call__(self) -> torch.Tensor: return self._graph.node_features.index_select(index=self._graph.receivers, dim=0) def __getitem__(self, edge_index) -> torch.Tensor: return self._graph.node_features[self._graph.receivers[edge_index]] class _SenderNodeView(_NodeView): def __call__(self) -> torch.Tensor: return self._graph.node_features.index_select(index=self._graph.senders, dim=0) def __getitem__(self, edge_index) -> torch.Tensor: return self._graph.node_features[self._graph.senders[edge_index]] class _SuccessorPredecessorView(object): def __init__(self, graph: _BaseGraph): self._graph = graph # TODO move these to the class definition or somewhere else self._pooling_functions = { 'mean': lambda src, idx: torch_scatter.scatter_mean(src, idx, dim=0, dim_size=graph.num_nodes), 'sum': lambda src, idx: torch_scatter.scatter_add(src, idx, dim=0, dim_size=graph.num_nodes), 'max': lambda src, idx: torch_scatter.scatter_max(src, idx, dim=0, dim_size=graph.num_nodes)[0], } def __len__(self): return self._graph.num_nodes def __getitem__(self, edge_index) -> torch.Tensor: raise NotImplemented def __iter__(self) -> Iterator[torch.Tensor]: for node_index in range(self._graph.num_nodes): yield self[node_index] class _SuccessorView(_SuccessorPredecessorView): def __call__(self, aggregation, *args, **kwargs) -> torch.Tensor: # For every edge get the features of the receiving node successors = self._graph.node_features.index_select(index=self._graph.receivers, dim=0) # Aggregate the features of the receiving nodes according to the sender fn = self._pooling_functions.get(aggregation, aggregation) return fn(successors, self._graph.senders) def __getitem__(self, node_index) -> torch.Tensor: successors = self._graph.receivers[self._graph.senders == node_index] return self._graph.node_features.index_select(index=successors, dim=0) class _PredecessorView(_SuccessorPredecessorView): def __call__(self, aggregation, *args, **kwargs) -> torch.Tensor: # For every edge get the features of the sender node predecessors = self._graph.node_features.index_select(index=self._graph.senders, dim=0) # Aggregate the features of the sender nodes according to the receiver fn = self._pooling_functions.get(aggregation, aggregation) return fn(predecessors, self._graph.receivers) def __getitem__(self, node_index) -> torch.Tensor: predecessors = self._graph.receivers[self._graph.senders == node_index] return self._graph.node_features.index_select(index=predecessors, dim=0) <file_sep>from torchgraphs import Graph from torchgraphs.data.features import add_random_features from data.utils import assert_graphs_equal def test_from_networkx(graph_nx, features_shapes): graph_nx = add_random_features(graph_nx, **features_shapes) graph = Graph.from_networkx(graph_nx) assert_graphs_equal(graph_nx, graph) def test_to_networkx(graph, features_shapes): graph = add_random_features(graph, **features_shapes) graph_nx = graph.to_networkx() assert_graphs_equal(graph, graph_nx) def test_device(graph, features_shapes, device): graph = add_random_features(graph, **features_shapes) other_graph = graph.to(device) for k in other_graph._feature_fields: assert (getattr(other_graph, k) is None) or (getattr(other_graph, k).device == device) assert_graphs_equal(graph, other_graph.cpu()) <file_sep>import torch from ..data import GraphBatch class _FeatureFunction(torch.nn.Module): def __init__(self, function): super().__init__() self.function = function class EdgeFunction(_FeatureFunction): def forward(self, graphs: GraphBatch) -> GraphBatch: return graphs.evolve(edge_features=self.function(graphs.edge_features)) class NodeFunction(_FeatureFunction): def forward(self, graphs: GraphBatch) -> GraphBatch: return graphs.evolve(node_features=self.function(graphs.node_features)) class GlobalFunction(_FeatureFunction): def forward(self, graphs: GraphBatch) -> GraphBatch: return graphs.evolve(global_features=self.function(graphs.global_features)) class NodeReLU(NodeFunction): def __init__(self): super(NodeReLU, self).__init__(torch.nn.functional.relu) class EdgeReLU(EdgeFunction): def __init__(self): super(EdgeReLU, self).__init__(torch.nn.functional.relu) class GlobalReLU(GlobalFunction): def __init__(self): super(GlobalReLU, self).__init__(torch.nn.functional.relu) class NodeSigmoid(NodeFunction): def __init__(self): super(NodeSigmoid, self).__init__(torch.sigmoid) class EdgeSigmoid(EdgeFunction): def __init__(self): super(EdgeSigmoid, self).__init__(torch.sigmoid) class GlobalSigmoid(GlobalFunction): def __init__(self): super(GlobalSigmoid, self).__init__(torch.sigmoid) class EdgeDropout(EdgeFunction): def __init__(self, p=0.5, inplace=False): super(EdgeDropout, self).__init__(torch.nn.Dropout(p, inplace)) class NodeDropout(NodeFunction): def __init__(self, p=0.5, inplace=False): super(NodeDropout, self).__init__(torch.nn.Dropout(p, inplace)) class GlobalDropout(GlobalFunction): def __init__(self, p=0.5, inplace=False): super(GlobalDropout, self).__init__(torch.nn.Dropout(p, inplace)) <file_sep>import torch from torchgraphs import Graph, GraphBatch from torchgraphs.data.features import add_random_features from data.utils import assert_graphs_equal def test_collate_tuples(graphs_nx, features_shapes, device): graphs_in = [add_random_features(Graph.from_networkx(g), **features_shapes).to(device) for g in graphs_nx] graphs_out = list(reversed(graphs_in)) xs = torch.rand(len(graphs_in), 10, 32) ys = torch.rand(len(graphs_in), 7) samples = list(zip(graphs_in, xs, ys, graphs_out)) batch = GraphBatch.collate(samples) for g1, g2 in zip(graphs_in, batch[0]): assert_graphs_equal(g1, g2) torch.testing.assert_allclose(xs, batch[1]) torch.testing.assert_allclose(ys, batch[2]) for g1, g2 in zip(graphs_out, batch[3]): assert_graphs_equal(g1, g2) def test_collate_dicts(graphs_nx, features_shapes, device): graphs_in = [add_random_features(Graph.from_networkx(g), **features_shapes).to(device) for g in graphs_nx] graphs_out = list(reversed(graphs_in)) xs = torch.rand(len(graphs_in), 10, 32) ys = torch.rand(len(graphs_in), 7) samples = [{'in': gi, 'x': x, 'y': y, 'out': go} for gi, x, y, go in zip(graphs_in, xs, ys, graphs_out)] batch = GraphBatch.collate(samples) for g1, g2 in zip(graphs_in, batch['in']): assert_graphs_equal(g1, g2) torch.testing.assert_allclose(xs, batch['x']) torch.testing.assert_allclose(ys, batch['y']) for g1, g2 in zip(graphs_out, batch['out']): assert_graphs_equal(g1, g2) <file_sep>from collections import OrderedDict import torch from torchgraphs import GraphBatch from torchgraphs.network import NodeLinear, EdgeLinear, GlobalLinear, EdgeReLU, NodeReLU, GlobalReLU from features_shapes import linear_features from torchgraphs.data.features import add_random_features def test_linear_graph_network(graphbatch: GraphBatch, device): graphbatch = add_random_features(graphbatch, **linear_features).to(device) node_linear = NodeLinear( out_features=linear_features['node_features_shape'], incoming_features=linear_features['edge_features_shape'], node_features=linear_features['node_features_shape'], global_features=linear_features['global_features_shape'], aggregation='mean' ) edge_linear = EdgeLinear( out_features=linear_features['edge_features_shape'], edge_features=linear_features['edge_features_shape'], sender_features=linear_features['node_features_shape'], receiver_features=linear_features['node_features_shape'], global_features=linear_features['global_features_shape'] ) global_linear = GlobalLinear( out_features=linear_features['global_features_shape'], edge_features=linear_features['edge_features_shape'], node_features=linear_features['node_features_shape'], global_features=linear_features['global_features_shape'], aggregation='mean' ) net = torch.nn.Sequential(OrderedDict([ ('edge', edge_linear), ('edge_relu', EdgeReLU()), ('node', node_linear), ('node_relu', NodeReLU()), ('global', global_linear), ('global_relu', GlobalReLU()), ])) net.to(device) result = net.forward(graphbatch) assert graphbatch.num_graphs == result.num_graphs assert graphbatch.num_nodes == result.num_nodes assert graphbatch.num_edges == result.num_edges assert (graphbatch.num_nodes_by_graph == result.num_nodes_by_graph).all() assert (graphbatch.num_edges_by_graph == result.num_edges_by_graph).all() assert (graphbatch.senders == result.senders).all() assert (graphbatch.receivers == result.receivers).all() <file_sep>import typing import torch import numpy as np def repeat_tensor(input: torch.Tensor, repeats: torch.LongTensor, dim: int = 0) -> torch.Tensor: """ Repeats each entry of a tensor along a given dimension according to a tensor of repetitions, gradients can be computed w.r.t. `tensor`, but not w.r.t. `repeats` Args: input: a tensor to repeat, e.g. [x, y, z] repeats: the non-negative number of repetition of each entry of the tensor, e.g. [2, 3, 1] dim: the dimension used to repeat the tensor Returns: A tensor with repeated entries that has the same type and placement as `tensor` Examples: Each element of `x` is repeated according to the corresponding number of repetitions in `repeats` >>> x = torch.tensor([a, b, c, d]) >>> repeats = torch.tensor([2, 3, 0, 1]) >>> repeat_tensor(x, repeats, dim=0) tensor([a, a, b, b, b, d]) Gradient information can be propagated through the repetition >>> x = torch.tensor([a, b, c, d], requires_grad=True) >>> repeats = torch.tensor([2, 3, 0, 1]) >>> repeat_tensor(x, repeats, dim=0).sum().backward() >>> x.grad tensor([2., 3., 0., 1.]) """ import warnings warnings.warn('Use torch.repeat_interleave instead of torchgraphs.utils.repeat_tensor', DeprecationWarning) if repeats.dim() != 1: raise ValueError(f'`repeats` should have a single dimension, got shape {repeats.shape}') if (repeats < 0).any(): raise ValueError(f'All entries in `repeats` should be non-negative') if len(repeats) != input.shape[dim]: raise ValueError(f'`input.shape[dim]` should match `len(repeats)`, got {input.shape[dim]} and {len(repeats)}') index = input.new_tensor(np.arange(len(repeats)).repeat(repeats.cpu().numpy()), dtype=torch.long) return torch.index_select(input, index=index, dim=dim) def segment_lengths_to_ids(segment_lengths: torch.LongTensor) -> torch.LongTensor: """ Args: segment_lengths: Non-negative lengths of the tensor segments Returns: A tensor containing ids for every element in the tensor to be segmented Examples: >>> segments = torch.tensor([2, 4, 3, 1]) >>> segment_lengths_to_slices(segments) tensor([0, 0, 1, 1, 1, 1, 2, 2, 2, 3]) """ return torch.repeat_interleave(torch.arange(len(segment_lengths), device=segment_lengths.device), segment_lengths) def segment_lengths_to_slices(segment_lengths: torch.LongTensor) -> typing.Iterator[slice]: """ Args: segment_lengths: Non-negative lengths of the tensor segments Yields: Slices to slice the tensor according to the segments Examples: >>> segments = torch.tensor([2, 4, 3, 1]) >>> list(segment_lengths_to_slices(segments)) [0:2, 2:6, 6:9, 9:10] """ assert segment_lengths.dim() == 1 assert (segment_lengths >= 0).all() indexes = segment_lengths.cumsum(dim=0) yield slice(indexes.new_tensor(0), indexes[0]) for start, end in zip(indexes[:-1], indexes[1:]): yield slice(start, end) <file_sep>networkx>=2.3 numpy>=1.16 torch>=1.1.0 torch-scatter>=1.2 <file_sep>from setuptools import setup, find_packages with open('requirements.txt') as f: requirements = f.read().splitlines() setup( name='torchgraphs', version='0.0.1', packages=find_packages(where='src'), package_dir={"": "src"}, license='Creative Commons Attribution-Noncommercial-Share Alike license', long_description=open('README.md').read(), python_requires='>=3.7', install_requires=requirements ) <file_sep>from __future__ import annotations from typing import Optional import dataclasses import torch import networkx as nx from .base import _BaseGraph @dataclasses.dataclass class Graph(_BaseGraph): global_features: Optional[torch.Tensor] = None _feature_fields = _BaseGraph._feature_fields + ('global_features',) @property def global_features_shape(self): return self.global_features.shape if self.global_features is not None else None @property def global_features_as_edges(self) -> torch.Tensor: """Broadcast `global_features` along the the first dimension to match the first dimension of `edge_features`, therefore the shape of the returned tensor is `(num_edges,) + self.global_features.shape` """ return self.global_features.expand(self.num_edges, *self.global_features.shape) @property def global_features_as_nodes(self): """Broadcast `global_features` along the the first dimension to match the first dimension of `node_features`, therefore the shape of the returned tensor is `(num_nodes,) + self.global_features.shape` """ return self.global_features.expand(self.num_nodes, *self.global_features.shape) def __repr__(self): return (f"{self.__class__.__name__}(" f"n={self.num_nodes}, " f"e={self.num_edges}, " f"n_shape={self.node_features_shape}, " f"e_shape={self.edge_features_shape}, " f"g_shape={self.global_features_shape})") def to_networkx(self, cls=nx.MultiDiGraph): g = cls() if self.node_features is not None: g.add_nodes_from([(i, {'features': f}) for i, f in enumerate(self.node_features)]) else: g.add_nodes_from(range(self.num_nodes)) if self.edge_features is None: g.add_edges_from([(s.item(), r.item()) for s, r in zip(self.senders, self.receivers)]) else: g.add_edges_from([(s.item(), r.item(), {'features': f}) for s, r, f in zip(self.senders, self.receivers, self.edge_features)]) if self.global_features is not None: g.graph['features'] = self.global_features return g @classmethod def from_networkx(cls, graph_nx: nx.Graph) -> Graph: # Handle node features if graph_nx.number_of_nodes() > 0 and 'features' in graph_nx.nodes[0]: node_features = torch.stack([features for node_id, features in graph_nx.nodes(data='features')]) else: node_features = None # Handle edge features if graph_nx.number_of_edges() > 0: senders, receivers, edge_features = zip(*graph_nx.edges(data='features')) senders = torch.tensor(senders, dtype=torch.long) receivers = torch.tensor(receivers, dtype=torch.long) if edge_features[0] is not None: edge_features = torch.stack(edge_features) else: edge_features = None else: senders = torch.tensor([], dtype=torch.long) receivers = torch.tensor([], dtype=torch.long) edge_features = None # Handle global features global_features = graph_nx.graph.get('features', None) return cls( num_nodes=graph_nx.number_of_nodes(), num_edges=graph_nx.number_of_edges(), node_features=node_features, edge_features=edge_features, senders=senders, receivers=receivers, global_features=global_features, ) <file_sep>import torch_scatter import torch.nn as nn from ..data import GraphBatch from ..utils import segment_lengths_to_ids def get_aggregation(name): if name in ('add', 'sum'): return torch_scatter.scatter_add elif name in ('mean', 'avg'): return torch_scatter.scatter_mean elif name == 'max': from functools import wraps @wraps(torch_scatter.scatter_max) def wrapper(*args, **kwargs): return torch_scatter.scatter_max(*args, **kwargs)[0] return wrapper class _BatchAggregator(nn.Module): def __init__(self, aggregation): super().__init__() if isinstance(aggregation, str): aggregation = get_aggregation(aggregation) self.aggregation = aggregation def forward(self, graphs: GraphBatch): raise NotImplementedError class EdgesToSender(_BatchAggregator): def forward(self, graphs: GraphBatch): # It's necessary to specify the shape of the output dimension, otherwise when max(receivers) != num_nodes # the pooling operation would output a minimal tensor with shape (max(receivers), *edge_features_shape) # instead of (num_nodes, *edge_features_shape), same would happen for senders return self.aggregation( graphs.edge_features, index=graphs.senders, dim=0, dim_size=graphs.num_nodes) class EdgesToReceiver(_BatchAggregator): def forward(self, graphs: GraphBatch): return self.aggregation( graphs.edge_features, index=graphs.receivers, dim=0, dim_size=graphs.num_nodes) class EdgesToGlobal(_BatchAggregator): def forward(self, graphs: GraphBatch): return self.aggregation( graphs.edge_features, index=graphs.node_index_by_graph, dim=0, dim_size=graphs.num_graphs) class NodesToGlobal(_BatchAggregator): def forward(self, graphs: GraphBatch): return self.aggregation( graphs.node_features, index=graphs.edge_index_by_graph, dim=0, dim_size=graphs.num_graphs) <file_sep>import math import torch import torch.nn as nn from .aggregation import get_aggregation from ..data import GraphBatch class EdgeLinear(nn.Module): def __init__(self, out_features, edge_features=None, sender_features=None, receiver_features=None, global_features=None, bias=True): super(EdgeLinear, self).__init__() self.out_features = out_features self.W_edge = nn.Parameter(torch.Tensor(out_features, edge_features)) \ if edge_features is not None else None self.W_sender = nn.Parameter(torch.Tensor(out_features, sender_features)) \ if sender_features is not None else None self.W_receiver = nn.Parameter(torch.Tensor(out_features, receiver_features)) \ if receiver_features is not None else None self.W_global = nn.Parameter(torch.Tensor(out_features, global_features)) \ if global_features is not None else None self.bias = nn.Parameter(torch.Tensor(out_features)) if bias else None _reset_parameters(self) def forward(self, graphs: GraphBatch) -> GraphBatch: new_edges = 0 if self.W_edge is not None: new_edges += graphs.edge_features @ self.W_edge.t() if self.W_sender is not None: new_edges += torch.index_select( graphs.node_features @ self.W_sender.t(), dim=0, index=graphs.senders) if self.W_receiver is not None: new_edges += torch.index_select( graphs.node_features @ self.W_receiver.t(), dim=0, index=graphs.receivers) if self.W_global is not None: new_edges += torch.repeat_interleave( graphs.global_features @ self.W_global.t(), dim=0, repeats=graphs.num_edges_by_graph) if self.bias is not None: new_edges = new_edges + self.bias.expand(graphs.num_edges, -1) return graphs.evolve(edge_features=new_edges) class NodeLinear(nn.Module): def __init__(self, out_features, node_features=None, incoming_features=None, outgoing_features=None, global_features=None, aggregation=None, bias=True): super(NodeLinear, self).__init__() self.out_features = out_features if isinstance(aggregation, str): aggregation = get_aggregation(aggregation) self.aggregation = aggregation self.W_node = nn.Parameter(torch.Tensor(out_features, node_features)) \ if node_features is not None else None self.W_incoming = nn.Parameter(torch.Tensor(out_features, incoming_features)) \ if incoming_features is not None else None self.W_outgoing = nn.Parameter(torch.Tensor(out_features, outgoing_features)) \ if outgoing_features is not None else None self.W_global = nn.Parameter(torch.Tensor(out_features, global_features)) \ if global_features is not None else None self.bias = nn.Parameter(torch.Tensor(out_features)) if bias else None if incoming_features is not None and aggregation is None: raise ValueError('An aggregation function is needed to process incoming edges') if outgoing_features is not None and aggregation is None: raise ValueError('An aggregation function is needed to process outgoing edges') _reset_parameters(self) def forward(self, graphs: GraphBatch) -> GraphBatch: new_nodes = 0 if self.W_node is not None: new_nodes += graphs.node_features @ self.W_node.t() if self.W_incoming is not None: new_nodes += self.aggregation( graphs.edge_features, dim=0, index=graphs.receivers, dim_size=graphs.num_nodes) @ self.W_incoming.t() if self.W_outgoing is not None: new_nodes += self.aggregation( graphs.edge_features, dim=0, index=graphs.senders, dim_size=graphs.num_nodes) @ self.W_outgoing.t() if self.W_global is not None: new_nodes += torch.repeat_interleave( graphs.global_features @ self.W_global.t(), dim=0, repeats=graphs.num_nodes_by_graph) if self.bias is not None: new_nodes = new_nodes + self.bias.expand(graphs.num_nodes, -1) return graphs.evolve(node_features=new_nodes) class GlobalLinear(nn.Module): def __init__(self, out_features, node_features=None, edge_features=None, global_features=None, aggregation=None, bias=True): super(GlobalLinear, self).__init__() self.W_node = nn.Parameter(torch.Tensor(out_features, node_features)) \ if node_features is not None else None self.W_edges = nn.Parameter(torch.Tensor(out_features, edge_features)) \ if edge_features is not None else None self.W_global = nn.Parameter(torch.Tensor(out_features, global_features)) \ if global_features is not None else None self.bias = nn.Parameter(torch.Tensor(out_features)) if bias else None if isinstance(aggregation, str): aggregation = get_aggregation(aggregation) self.aggregation = aggregation if node_features is not None and aggregation is None: raise ValueError('An aggregation function is needed to process node features') if edge_features is not None and aggregation is None: raise ValueError('An aggregation function is needed to process edge features') _reset_parameters(self) def forward(self, graphs: GraphBatch) -> GraphBatch: new_globals = 0 if self.W_node is not None: new_globals = new_globals + self.aggregation(graphs.node_features, index=graphs.node_index_by_graph, dim=0, dim_size=graphs.num_graphs) @ self.W_node.t() if self.W_edges is not None: new_globals = new_globals + self.aggregation(graphs.edge_features, index=graphs.edge_index_by_graph, dim=0, dim_size=graphs.num_graphs) @ self.W_edges.t() if self.W_global is not None: new_globals = new_globals + graphs.global_features @ self.W_global.t() if self.bias is not None: new_globals = new_globals + self.bias.expand(graphs.num_graphs, -1) return graphs.evolve(global_features=new_globals) def _reset_parameters(module): for name, param in module.named_parameters(): if 'bias' in name: bound = 1 / math.sqrt(param.numel()) nn.init.uniform_(param, -bound, bound) else: nn.init.kaiming_uniform_(param, a=math.sqrt(5)) <file_sep>from __future__ import annotations import dataclasses import collections.abc from typing import Iterator, Sequence, Iterable, Optional, Tuple import networkx as nx import torch import torch_scatter from torch.utils.data._utils.collate import default_collate from .base import _BaseGraph from .graph import Graph from ..utils import segment_lengths_to_slices, segment_lengths_to_ids @dataclasses.dataclass class GraphBatch(_BaseGraph): num_graphs: int = None global_features: Optional[torch.Tensor] = None num_nodes_by_graph: torch.LongTensor = None num_edges_by_graph: torch.LongTensor = None node_index_by_graph: torch.LongTensor = dataclasses.field(init=False) edge_index_by_graph: torch.LongTensor = dataclasses.field(init=False) _feature_fields = _BaseGraph._feature_fields + ('global_features',) _index_fields = _BaseGraph._index_fields + ('num_nodes_by_graph', 'num_edges_by_graph') def __post_init__(self): # super().__post_init__() will also validate the instance using the _validate methods, # so we first fill in missing values that are will be used in self._validate() if self.num_graphs is None: if self.num_nodes_by_graph is not None: self.num_graphs = len(self.num_nodes_by_graph) elif self.num_nodes_by_graph is not None: self.num_graphs = len(self.num_nodes_by_graph) elif self.global_features is not None: self.num_graphs = len(self.global_features) else: raise ValueError('Could not infer number of graphs from batch fields') if self.num_nodes_by_graph is None and self.num_nodes == 0: self.num_nodes_by_graph = torch.zeros(self.num_graphs, dtype=torch.long) if self.num_edges_by_graph is None and self.num_edges == 0: self.num_edges_by_graph = torch.zeros(self.num_graphs, dtype=torch.long) self.node_index_by_graph = segment_lengths_to_ids(self.num_nodes_by_graph) self.edge_index_by_graph = segment_lengths_to_ids(self.num_edges_by_graph) super(GraphBatch, self).__post_init__() def _validate(self): super(GraphBatch, self)._validate() if self.global_features is not None and self.num_graphs != len(self.global_features): raise ValueError(f'Total number of graphs and length of global features must correspond: ' f'`num_graphs`={self.num_graphs} ' f'`len(self.global_features)`={len(self.global_features)}') if self.num_graphs != len(self.num_nodes_by_graph): raise ValueError(f'Total number of graphs and length of nodes by graph must correspond: ' f'`num_graphs`={self.num_graphs} ' f'`len(self.num_nodes_by_graph)`={len(self.num_nodes_by_graph)}') if self.num_graphs != len(self.num_edges_by_graph): raise ValueError(f'Total number of graphs and length of edges by graph must correspond: ' f'`num_graphs`={self.num_graphs} ' f'`len(self.num_edges_by_graph)`={len(self.num_edges_by_graph)}') if self.num_nodes != self.num_nodes_by_graph.sum(): raise ValueError(f'Total number of nodes and number of nodes by graph must correspond: ' f'`num_nodes`={self.num_nodes} ' f'`sum(self.num_nodes_by_graph)`={self.num_nodes_by_graph.sum().item()}') if self.num_edges != self.num_edges_by_graph.sum(): raise ValueError(f'Total number of edges and number of edges by graph must correspond: ' f'`num_edges`={self.num_edges} ' f'`sum(self.num_edges_by_graph)`={self.num_edges_by_graph.sum().item()}') def __len__(self): return self.num_graphs @property def node_features_by_graph(self): """For every graph in the batch, the features of their nodes Examples: * Access the node features of a single graph >>> batch.node_features_by_graph[graph_index] * Iterate over the node features of every graph in the batch >>> iter(batch.node_features_by_graph) * Get a tuple of tensors containing the node features of every graph >>> batch.node_features_by_graph.astuple() * Get a tensor of aggregated node features with shape (num_graphs, *node_features_shape) >>> batch.node_features_by_graph(aggregation='sum') """ return _BatchNodeView(self) @property def edge_features_by_graph(self): """For every graph in the batch, the features of their edges Examples: * Access the edge features of a single graph >>> batch.edge_features_by_graph[graph_index] * Iterate over the edge features of every graph in the batch >>> iter(batch.edge_features_by_graph) * Get a tuple of tensors containing the edge features of every graph >>> batch.edge_features_by_graph.astuple() * Get a tensor of aggregated edge features with shape (num_graphs, *edge_features_shape) >>> batch.edge_features_by_graph(aggregation='sum') """ return _BatchEdgeView(self) @property def global_features_shape(self): return self.global_features.shape[1:] if self.global_features is not None else None def global_features_as_edges(self) -> torch.Tensor: """Broadcast `global_features` along the the first dimension to match `edge_features`, respecting the edge-to-graph assignment Returns: a tensor of shape `(num_edges, *global_features_shape)` """ return torch.repeat_interleave(self.global_features, self.num_edges_by_graph) def global_features_as_nodes(self) -> torch.Tensor: """Broadcast `global_features` along the the first dimension to match `node_features`, respecting the node-to-graph assignment Returns: a tensor of shape `(num_nodes, *global_features_shape)` """ return torch.repeat_interleave(self.global_features, self.num_nodes_by_graph) def __getitem__(self, graph_index): """Use for random access, as in `batch[i]`. For sequential access use `iter(batch)` or `for g in batch` """ node_offset = self.num_nodes_by_graph[:graph_index].sum() edge_offset = self.num_edges_by_graph[:graph_index].sum() n_nodes = self.num_nodes_by_graph[graph_index] n_edges = self.num_edges_by_graph[graph_index] return Graph( num_nodes=n_nodes.item(), num_edges=n_edges.item(), node_features=None if self.node_features is None else self.node_features[node_offset:node_offset + n_nodes], edge_features=None if self.edge_features is None else self.edge_features[edge_offset:edge_offset + n_edges], global_features=self.global_features[graph_index] if self.global_features is not None else None, senders=self.senders[edge_offset:edge_offset + n_edges] - node_offset, receivers=self.receivers[edge_offset:edge_offset + n_edges] - node_offset ) def __iter__(self): """Use for sequential access, as in `iter(batch)` or `for g in batch`. For random access use `batch[i].` """ node_slices = segment_lengths_to_slices(self.num_nodes_by_graph) edge_slices = segment_lengths_to_slices(self.num_edges_by_graph) for graph_index, node_slice, edge_slice in zip(range(self.num_graphs), node_slices, edge_slices): yield Graph( num_nodes=self.num_nodes_by_graph[graph_index].item(), num_edges=self.num_edges_by_graph[graph_index].item(), node_features=self.node_features[node_slice] if self.node_features is not None else None, edge_features=self.edge_features[edge_slice] if self.edge_features is not None else None, global_features=self.global_features[graph_index] if self.global_features is not None else None, senders=self.senders[edge_slice] - node_slice.start, receivers=self.receivers[edge_slice] - node_slice.start ) def __repr__(self): return (f"{self.__class__.__name__}(" f"#{self.num_graphs}, " f"n={self.num_nodes_by_graph}, " f"e={self.num_edges_by_graph}, " f"n_shape={self.node_features_shape}, " f"e_shape={self.edge_features_shape}, " f"g_shape={self.global_features_shape})") def to_networkxs(self): return [g.to_networkx() for g in self] def to_graphs(self): return list(self) @classmethod def from_graphs(cls, graphs: Sequence[Graph]) -> GraphBatch: """Merges multiple graphs in a batch. All node, edge and graph features must have the same shape if present. If some graph of the sequence have values for `node_features`, `edge_features`, but some of the others don't (maybe they were created with `num_nodes = 0` or `num_edges = 0` and None as node/edge features), this method will still try to correctly batch the graphs together. It is however advised to replace the None values on those graphs with empty tensors of shape `(0, *node_features_shape)` and `(0, *edge_features_shape)`. The field `global_features` is instead required to be either present on all graphs or absent from all graphs. """ # TODO if the graphs in `graphs` require grad the resulting batch should require grad too if len(graphs) == 0: raise ValueError('Graphs list can not be empty') node_features = [] edge_features = [] global_features = [] num_nodes_by_graph = [] num_edges_by_graph = [] senders = [] receivers = [] node_offset = 0 for i, g in enumerate(graphs): if g.node_features is not None: node_features.append(g.node_features) if g.edge_features is not None: edge_features.append(g.edge_features) if g.global_features is not None: global_features.append(g.global_features) num_nodes_by_graph.append(g.num_nodes) num_edges_by_graph.append(g.num_edges) senders.append(g.senders + node_offset) receivers.append(g.receivers + node_offset) node_offset += g.num_nodes from torch.utils.data._utils.collate import _use_shared_memory if len(node_features) > 0: out = None if _use_shared_memory: numel = sum([x.numel() for x in node_features]) storage = node_features[0].storage()._new_shared(numel) out = node_features[0].new(storage) node_features = torch.cat(node_features, out=out) else: node_features = None if len(edge_features) > 0: out = None if _use_shared_memory: numel = sum([x.numel() for x in edge_features]) storage = edge_features[0].storage()._new_shared(numel) out = edge_features[0].new(storage) edge_features = torch.cat(edge_features, out=out) else: edge_features = None if len(global_features) == len(graphs): out = None if _use_shared_memory: numel = sum([x.numel() for x in global_features]) storage = global_features[0].storage()._new_shared(numel) out = global_features[0].new(storage) global_features = torch.stack(global_features, out=out) elif len(global_features) == 0: global_features = None else: raise ValueError('The field `global_features` must either be None on all graphs or present on all graphs') out = None if _use_shared_memory: numel = sum([x.numel() for x in senders]) storage = graphs[0].senders.storage()._new_shared(numel) out = senders[0].new(storage) senders = torch.cat(senders, out=out) out = None if _use_shared_memory: numel = sum([x.numel() for x in receivers]) storage = graphs[0].receivers.storage()._new_shared(numel) out = receivers[0].new(storage) receivers = torch.cat(receivers, out=out) return cls( num_nodes=node_offset, num_edges=len(senders), num_nodes_by_graph=senders.new_tensor(num_nodes_by_graph), num_edges_by_graph=senders.new_tensor(num_edges_by_graph), node_features=node_features, edge_features=edge_features, global_features=global_features, senders=senders, receivers=receivers ) @classmethod def from_networkxs(cls, networkxs: Iterable[nx.Graph]) -> GraphBatch: return cls.from_graphs([Graph.from_networkx(graph_nx) for graph_nx in networkxs]) @classmethod def collate(cls, samples): """Collates a sequence of samples containing graphs into a batch The samples in the sequence can contain multiple types of inputs, such as: >>> [ >>> (input_graph, tensor, other_tensor, output_graph), >>> (input_graph, tensor, other_tensor, output_graph), >>> ... >>> ] """ if isinstance(samples[0], Graph): return cls.from_graphs(samples) elif isinstance(samples[0], (str, bytes)): return samples elif isinstance(samples[0], collections.abc.Mapping): return {key: cls.collate([d[key] for d in samples]) for key in samples[0]} elif isinstance(samples[0], collections.abc.Sequence): transposed = zip(*samples) return [cls.collate(samples) for samples in transposed] else: return default_collate(samples) class _BatchView(object): def __init__(self, batch: GraphBatch): self._batch = batch self._pooling_functions = { 'mean': lambda src, idx: torch_scatter.scatter_mean(src, idx, dim=0, dim_size=batch.num_graphs), 'sum': lambda src, idx: torch_scatter.scatter_add(src, idx, dim=0, dim_size=batch.num_graphs), 'max': lambda src, idx: torch_scatter.scatter_max(src, idx, dim=0, dim_size=batch.num_graphs)[0], } def __len__(self): return self._batch.num_graphs class _BatchNodeView(_BatchView): def __getitem__(self, graph_index) -> torch.Tensor: node_offset = self._batch.num_nodes_by_graph[:graph_index].sum() num_nodes = self._batch.num_nodes_by_graph[graph_index] return self._batch.node_features[node_offset:node_offset + num_nodes] def __iter__(self) -> Iterator[torch.Tensor]: for slice_ in segment_lengths_to_slices(self._batch.num_nodes_by_graph): yield self._batch.node_features[slice_] def as_tuple(self) -> Tuple[torch.Tensor]: """Convenience method to get a tuple of non-aggregated node features. Better than building a tuple from the iterator: `tuple(batch.node_features_by_graph)`""" return torch.split_with_sizes(self._batch.node_features, self._batch.num_nodes_by_graph.tolist(), dim=0) def __call__(self, aggregation) -> torch.Tensor: aggregation = self._pooling_functions[aggregation] return aggregation(self._batch.node_features, self._batch.node_index_by_graph) class _BatchEdgeView(_BatchView): def __getitem__(self, graph_index) -> torch.Tensor: edge_offset = self._batch.num_edges_by_graph[:graph_index].sum() num_edges = self._batch.num_edges_by_graph[graph_index] return self._batch.edge_features[edge_offset:edge_offset + num_edges] def __iter__(self) -> Iterator[torch.Tensor]: for slice_ in segment_lengths_to_slices(self._batch.num_edges_by_graph): yield self._batch.edge_features[slice_] def as_tuple(self) -> Tuple[torch.Tensor]: """Convenience method to get a tuple of non-aggregated edge features. Better than building a tuple from the iterator: `tuple(batch.edge_features_by_graph)`""" return torch.split_with_sizes(self._batch.edge_features, self._batch.num_edges_by_graph.tolist(), dim=0) def __call__(self, aggregation) -> torch.Tensor: aggregation = self._pooling_functions[aggregation] return aggregation(self._batch.edge_features, self._batch.edge_index_by_graph) <file_sep>import warnings import torch.nn as nn from ..data import GraphBatch class GraphNetwork(nn.Module): def __init__(self, node_fn, edge_fn, global_fn, edges_to_sender, edges_to_receiver, nodes_to_global, edges_to_global): super(GraphNetwork, self).__init__() self.node_fn = node_fn self.edge_fn = edge_fn self.global_fn = global_fn self.edges_to_sender = edges_to_sender self.edges_to_receiver = edges_to_receiver self.nodes_to_global = nodes_to_global self.edges_to_global = edges_to_global def forward(self, graphs: GraphBatch) -> GraphBatch: edge_features = self.edge_fn(graphs) edges_to_sender = self.edges_to_sender(graphs, edge_features) edges_to_receiver = self.edges_to_receiver(graphs, edge_features) node_features = self.node_fn(graphs, edges_to_sender, edges_to_receiver) edge_to_global = self.edges_to_global(graphs, edge_features) node_to_global = self.nodes_to_global(graphs, node_features) global_features = self.global_fn(graphs, node_to_global, edge_to_global) return graphs.evolve( node_features=node_features, edge_features=edge_features, global_features=global_features ) class GraphLayer(nn.Module): def __init__(self, edge_fn=None, node_fn=None, global_fn=None): super(GraphLayer, self).__init__() self.node_fn = node_fn self.edge_fn = edge_fn self.global_fn = global_fn def forward(self, graphs: GraphBatch) -> GraphBatch: if self.edge_fn is not None: new_edge_features = self.edge_fn(graphs) graphs.evolve(edge_features=new_edge_features) if self.node_fn is not None: new_node_features = self.node_fn(graphs) graphs.evolve(node_features=new_node_features) if self.global_fn is not None: new_global_features = self.global_fn(graphs) graphs.evolve(global_features=new_global_features) return graphs <file_sep>from typing import overload import torch import networkx as nx from .graph import Graph from .graphbatch import GraphBatch @overload def add_random_features(graph: nx.Graph, *, node_features_shape=None, edge_features_shape=None, global_features_shape=None) -> nx.Graph: ... @overload def add_random_features(graph: Graph, *, node_features_shape=None, edge_features_shape=None, global_features_shape=None) -> Graph: ... @overload def add_random_features(graph: GraphBatch, *, node_features_shape=None, edge_features_shape=None, global_features_shape=None) -> GraphBatch: ... def add_random_features(graph, *, node_features_shape=None, edge_features_shape=None, global_features_shape=None): if isinstance(node_features_shape, int): node_features_shape = (node_features_shape,) if isinstance(edge_features_shape, int): edge_features_shape = (edge_features_shape,) if isinstance(global_features_shape, int): global_features_shape = (global_features_shape,) if isinstance(graph, nx.Graph): if node_features_shape is not None: for node, data in graph.nodes(data=True): data['features'] = torch.rand(*node_features_shape) if edge_features_shape is not None: for start, end, data in graph.edges(data=True): data['features'] = torch.rand(*edge_features_shape) if global_features_shape is not None: graph.graph['features'] = torch.rand(*global_features_shape) return graph elif isinstance(graph, Graph): return graph.evolve( node_features=None if node_features_shape is None else torch.rand(graph.num_nodes, *node_features_shape), edge_features=None if edge_features_shape is None else torch.rand(graph.num_edges, *edge_features_shape), global_features=None if global_features_shape is None else torch.rand(*global_features_shape) ) elif isinstance(graph, GraphBatch): return graph.evolve( node_features=None if node_features_shape is None else torch.rand(graph.num_nodes, *node_features_shape), edge_features=None if edge_features_shape is None else torch.rand(graph.num_edges, *edge_features_shape), global_features=None if global_features_shape is None else torch.rand( graph.num_graphs, *global_features_shape) ) raise ValueError( f'`graph` must be instance of `networkx.Graph`, `torchgraphs.data.Graph` or ' f'`torchgraphs.data.GraphBatch`, found {type(graph)}') @overload def add_dummy_features(graph: nx.Graph) -> nx.Graph: ... @overload def add_dummy_features(graph: Graph) -> Graph: ... def add_dummy_features(graph): if isinstance(graph, nx.Graph): for node, data in graph.nodes(data=True): data['features'] = torch.empty(3).fill_(node) for start, end, data in graph.edges(data=True): data['features'] = torch.tensor([start, start, end, end]).float() graph.graph['features'] = torch.ones(5) return graph elif isinstance(graph, Graph): return graph.evolve( node_features=torch.arange(graph.num_nodes).expand(3, -1).t().float(), edge_features=torch.tensor([[s, s, r, r] for s, r in zip(graph.senders, graph.receivers)]).float(), global_features=torch.ones(5) ) raise ValueError(f'`graph` must be instance of `networkx.Graph` or `torchgraphs.data.Graph`, found {type(graph)}') <file_sep>import pytest import networkx as nx from torchgraphs import Graph from torchgraphs.data.features import add_dummy_features from graphs_for_test import graphs_for_test @pytest.fixture(params=[g for g in graphs_for_test().values() if g.number_of_edges() > 0], ids=[n for n, g in graphs_for_test().items() if g.number_of_edges() > 0]) def graph_nx(request) -> nx.Graph: return request.param def test_graph_properties(graph_nx): graph_nx = add_dummy_features(graph_nx) graph = Graph.from_networkx(graph_nx) assert list(graph.degree) == [d for _, d in graph_nx.degree] assert list(graph.in_degree) == [d for _, d in graph_nx.in_degree] assert list(graph.out_degree) == [d for _, d in graph_nx.out_degree] def test_edge_functions(graph_nx): graph_nx = add_dummy_features(graph_nx) graph = Graph.from_networkx(graph_nx) # Edge features # By edge index for edge_index in range(graph.num_edges): assert graph.edge_features[edge_index].shape == graph.edge_features_shape # Iterator for edge_features in iter(graph.edge_features): assert edge_features.shape == graph.edge_features_shape # As tensor assert graph.edge_features.shape == (graph.num_edges, *graph.edge_features_shape) # Features of the sender nodes # By edge index for edge_index in range(graph.num_edges): assert graph.sender_features[edge_index].shape == graph.node_features_shape # Iterator for edge_features in graph.sender_features: assert edge_features.shape == graph.node_features_shape # As tensor assert graph.sender_features().shape == (graph.num_edges, *graph.node_features_shape) # Features of the receiver nodes # By edge index for edge_index in range(graph.num_edges): assert graph.receiver_features[edge_index].shape == graph.node_features_shape # Iterator for edge_features in graph.receiver_features: assert edge_features.shape == graph.node_features_shape # As tensor assert graph.receiver_features().shape == (graph.num_edges, *graph.node_features_shape) def test_node_functions(graph_nx): graph_nx = add_dummy_features(graph_nx) graph = Graph.from_networkx(graph_nx) # Features of the outgoing edges # By node index for node_index in range(graph.num_nodes): assert graph.out_edge_features[node_index].shape[1:] == graph.edge_features_shape # Iterator for out_edges in iter(graph.out_edge_features): assert out_edges.shape[1:] == graph.edge_features_shape # As tensor assert graph.out_edge_features(aggregation='sum').shape == (graph.num_nodes, *graph.edge_features_shape) # Features of the incoming edges # By node index for node_index in range(graph.num_nodes): assert graph.in_edge_features[node_index].shape[1:] == graph.edge_features_shape # Iterator for in_edges in iter(graph.in_edge_features): assert in_edges.shape[1:] == graph.edge_features_shape # As tensor assert graph.in_edge_features(aggregation='sum').shape == (graph.num_nodes, *graph.edge_features_shape) # Features of the successor nodes # By node index for node_index in range(graph.num_nodes): assert graph.successor_features[node_index].shape[1:] == graph.node_features_shape # Iterator for in_edges in iter(graph.successor_features): assert in_edges.shape[1:] == graph.node_features_shape # As tensor assert graph.successor_features(aggregation='sum').shape == (graph.num_nodes, *graph.node_features_shape) # Features of the predecessor nodes # By node index for node_index in range(graph.num_nodes): assert graph.predecessor_features[node_index].shape[1:] == graph.node_features_shape # Iterator for in_edges in iter(graph.predecessor_features): assert in_edges.shape[1:] == graph.node_features_shape # As tensor assert graph.predecessor_features(aggregation='sum').shape == (graph.num_nodes, *graph.node_features_shape) def test_global_functions(graph_nx): graph_nx = add_dummy_features(graph_nx) graph = Graph.from_networkx(graph_nx) assert graph.global_features.shape == graph.global_features_shape assert graph.global_features_as_nodes.shape == (graph.num_nodes, *graph.global_features_shape) assert graph.global_features_as_edges.shape == (graph.num_edges, *graph.global_features_shape) <file_sep>import pytest import torch from torchgraphs import Graph, GraphBatch from torchgraphs.data.features import add_random_features from data.utils import assert_graphs_equal def test_from_to_networkxs(graphs_nx, features_shapes, device): graphs_nx = [add_random_features(g, **features_shapes) for g in graphs_nx] graphbatch = GraphBatch.from_networkxs(graphs_nx).to(device) validate_batch(graphbatch) assert len(graphs_nx) == len(graphbatch) == graphbatch.num_graphs assert [g.number_of_nodes() for g in graphs_nx] == graphbatch.num_nodes_by_graph.tolist() assert [g.number_of_edges() for g in graphs_nx] == graphbatch.num_edges_by_graph.tolist() # Test sequential access (__iter__) for g_nx, g in zip(graphs_nx, graphbatch): assert_graphs_equal(g_nx, g.cpu()) # Test random access (__getitem__) for i in range(len(graphbatch)): assert_graphs_equal(graphs_nx[i], graphbatch[i].cpu()) # Test back conversion graphs_nx_back = graphbatch.cpu().to_networkxs() for g1, g2 in zip(graphs_nx, graphs_nx_back): assert_graphs_equal(g1, g2) def test_corner_cases(features_shapes, device): # Only some graphs have node/edge features, global features are either present on all of them or absent from all gfs = features_shapes['global_features_shape'] graphs = [ add_random_features(Graph(num_nodes=0, num_edges=0), global_features_shape=gfs), add_random_features(Graph(num_nodes=0, num_edges=0), global_features_shape=gfs), add_random_features(Graph(num_nodes=3, num_edges=0), **features_shapes), add_random_features(Graph(num_nodes=0, num_edges=0), **features_shapes), add_random_features( Graph(num_nodes=2, senders=torch.tensor([0, 1]), receivers=torch.tensor([1, 0])), **features_shapes) ] graphbatch = GraphBatch.from_graphs(graphs).to(device) validate_batch(graphbatch) for g_orig, g_batch in zip(graphs, graphbatch): assert_graphs_equal(g_orig, g_batch.cpu()) # Global features should be either present on all graphs or absent from all graphs with pytest.raises(ValueError): GraphBatch.from_graphs([ Graph(num_nodes=0, num_edges=0), add_random_features(Graph(num_nodes=0, num_edges=0), global_features_shape=10) ]) with pytest.raises(ValueError): GraphBatch.from_graphs([ add_random_features(Graph(num_nodes=0, num_edges=0), global_features_shape=10), Graph(num_nodes=0, num_edges=0) ]) def test_from_graphs(graphs, features_shapes, device): graphs = [add_random_features(g, **features_shapes).to(device) for g in graphs] graphbatch = GraphBatch.from_graphs(graphs) validate_batch(graphbatch) assert len(graphs) == len(graphbatch) == graphbatch.num_graphs assert [g.num_nodes for g in graphs] == graphbatch.num_nodes_by_graph.tolist() assert [g.num_edges for g in graphs] == graphbatch.num_edges_by_graph.tolist() # Test sequential access (__iter__) for g, gb in zip(graphs, graphbatch): assert_graphs_equal(g, gb) # Test random access (__getitem__) for i in range(len(graphbatch)): assert_graphs_equal(graphs[i], graphbatch[i]) def validate_batch(graphbatch): assert len(graphbatch) == graphbatch.num_graphs assert (graphbatch.senders < graphbatch.num_nodes).all() assert (graphbatch.receivers < graphbatch.num_nodes).all() assert (graphbatch.degree == graphbatch.in_degree + graphbatch.out_degree).all() <file_sep>import pytest from torchgraphs import GraphBatch from graphs_for_test import graphs_for_test @pytest.fixture def graphbatch() -> GraphBatch: return GraphBatch.from_networkxs(graphs_for_test().values()) <file_sep>from . import utils from .data import Graph, GraphBatch from .network import GraphNetwork, \ EdgeLinear, NodeLinear, GlobalLinear, \ EdgesToSender, EdgesToReceiver, EdgesToGlobal, NodesToGlobal, \ EdgeFunction, NodeFunction, GlobalFunction, \ EdgeReLU, NodeReLU, GlobalReLU, \ EdgeSigmoid, NodeSigmoid, GlobalSigmoid, \ EdgeDropout, NodeDropout, GlobalDropout <file_sep>from .graph import Graph from .graphbatch import GraphBatch <file_sep># Torchgraphs A PyTorch library for Graph Convolutional Networks. ## Requirements and installation Torchgraphs is developed in Python 3.7 and depende on PyTorch 1.1. It is suggested but not required to install PyTorch beforehand, to correctly match the hardware capabilities, see the official installation [instruction](https://pytorch.org/). All requirements listed in [requirements.txt](./requirements.txt) will be installed automatically when running: ```bash pip install https://github.com/baldassarreFe/torchgraphs ``` To develop the library itself, a conda environment with additional dependencies is provided, as well as a test suite for [pytest](https://pytest.org): ```bash git clone https://github.com/baldassarreFe/torchgraphs cd torchgraphs ENV_NAME=torchgraphs_env conda env create -n "${ENV_NAME}" -f conda.yaml conda activate "${ENV_NAME}" pip install --editable . pytest ```<file_sep>from typing import Union import torch import networkx as nx import torchgraphs as tg def assert_graphs_equal(graph1: Union[tg.Graph, nx.Graph], graph2: Union[tg.Graph, nx.Graph]): if isinstance(graph1, tg.Graph) and isinstance(graph2, tg.Graph): _assert_graphs_equals(graph1, graph2) elif isinstance(graph1, nx.Graph) and isinstance(graph2, nx.Graph): _assert_graphs_nx_equal(graph1, graph2) elif isinstance(graph1, nx.Graph) and isinstance(graph2, tg.Graph): _assert_graph_and_graph_nx_equals(graph_nx=graph1, graph=graph2) elif isinstance(graph1, tg.Graph) and isinstance(graph2, nx.Graph): _assert_graph_and_graph_nx_equals(graph_nx=graph2, graph=graph1) def has_node_features(graph: Union[tg.Graph, nx.Graph]): if isinstance(graph, tg.Graph): return graph.node_features is not None and graph.node_features.shape[0] != 0 if isinstance(graph, nx.Graph): return graph.number_of_nodes() > 0 and graph.nodes(data='features')[0] is not None raise ValueError(f'Wrong type: {type(graph)}') def has_edge_features(graph: Union[tg.Graph, nx.Graph]): if isinstance(graph, tg.Graph): return graph.edge_features is not None and graph.edge_features.shape[0] != 0 if isinstance(graph, nx.Graph): return graph.number_of_edges() > 0 and list(graph.edges(data='features'))[0][-1] is not None raise ValueError(f'Wrong type: {type(graph)}') def has_global_features(graph: Union[tg.Graph, nx.Graph]): if isinstance(graph, tg.Graph): return graph.global_features is not None if isinstance(graph, nx.Graph): return 'features' in graph.graph raise ValueError(f'Wrong type: {type(graph)}') def _assert_graphs_nx_equal(g1: nx.Graph, g2: nx.Graph): # Check number of nodes and edges assert g1.number_of_nodes() == g2.number_of_nodes() assert g1.number_of_edges() == g2.number_of_edges() # Check node features for (node_id_1, node_features_1), (node_id_2, node_features_2) in \ zip(g1.nodes(data='features'), g2.nodes(data='features')): assert node_id_1 == node_id_2 assert (node_features_1 is not None) == (node_features_2 is not None) if node_features_1 is not None and node_features_2 is not None: torch.testing.assert_allclose(node_features_1, node_features_2) # Check edge features for (sender_id_1, receiver_id_1, edge_features_1), (sender_id_2, receiver_id_2, edge_features_2) in \ zip(g1.edges(data='features'), g2.edges(data='features')): assert sender_id_1 == sender_id_2 assert receiver_id_1 == receiver_id_2 assert (edge_features_1 is not None) == (edge_features_2 is not None) if edge_features_1 is not None and edge_features_2 is not None: torch.testing.assert_allclose(edge_features_1, edge_features_2) # Check graph features assert has_global_features(g1) == has_global_features(g2) if has_global_features(g1) and has_global_features(g2): torch.testing.assert_allclose(g1.graph['features'], g2.graph['features']) def _assert_graphs_equals(g1: tg.Graph, g2: tg.Graph): # Check number of nodes and edges assert g1.num_nodes == g2.num_nodes assert g1.num_edges == g2.num_edges # Check node features assert has_node_features(g1) == has_node_features(g2) if has_node_features(g1) and has_node_features(g2): torch.testing.assert_allclose(g1.node_features, g2.node_features) # Check edge indexes for sender_id_1, receiver_id_1, sender_id_2, receiver_id_2 in \ zip(g1.senders, g1.receivers, g2.senders, g2.receivers): assert sender_id_1 == sender_id_2 assert receiver_id_1 == receiver_id_2 # Check edge features assert has_edge_features(g1) == has_edge_features(g2) if has_edge_features(g1) and has_edge_features(g2): torch.testing.assert_allclose(g1.edge_features, g2.edge_features) # Check graph features assert has_global_features(g1) == has_global_features(g2) if has_global_features(g1) and has_global_features(g2): torch.testing.assert_allclose(g1.global_features, g2.global_features) def _assert_graph_and_graph_nx_equals(graph: tg.Graph, graph_nx: nx.Graph): # Check number of nodes and edges assert graph_nx.number_of_nodes() == graph.num_nodes assert graph_nx.number_of_edges() == graph.num_edges # Check node features assert has_node_features(graph) == has_node_features(graph_nx) if has_node_features(graph) and has_node_features(graph_nx): for node_features_nx, node_features in zip(graph_nx.nodes(data='features'), graph.node_features): torch.testing.assert_allclose(node_features_nx[1], node_features) # Check edge indexes for (sender_id_nx, receiver_id_nx, *_), sender_id, receiver_id in \ zip(graph_nx.edges, graph.senders, graph.receivers): assert sender_id_nx == sender_id assert receiver_id_nx == receiver_id assert has_edge_features(graph) == has_edge_features(graph_nx) if has_edge_features(graph) and has_edge_features(graph_nx): for (*_, edge_features_nx), edge_features in zip(graph_nx.edges(data='features'), graph.edge_features): torch.testing.assert_allclose(edge_features_nx, edge_features) # Check graph features assert has_global_features(graph) == has_global_features(graph_nx) if has_global_features(graph) and has_global_features(graph_nx): torch.testing.assert_allclose(graph_nx.graph['features'], graph.global_features) <file_sep>conv_features = { 'node_features_shape': (3, 32, 32), 'edge_features_shape': (4, 32, 32), 'global_features_shape': (1, 32, 32) } linear_features = { 'node_features_shape': 100, 'edge_features_shape': 7, 'global_features_shape': 2 } no_node_features = { 'node_features_shape': None, 'edge_features_shape': 7, 'global_features_shape': 2 } no_edge_features = { 'node_features_shape': 100, 'edge_features_shape': None, 'global_features_shape': 2 } no_global_features = { 'node_features_shape': 100, 'edge_features_shape': 7, 'global_features_shape': None } all_features = { 'conv_features': conv_features, 'linear_features': linear_features, 'no_node_features': no_node_features, 'no_edge_features': no_edge_features, 'no_global_features': no_global_features } <file_sep>from .network import GraphNetwork from .linear import EdgeLinear, NodeLinear, GlobalLinear from .aggregation import EdgesToSender, EdgesToReceiver, EdgesToGlobal, NodesToGlobal from .functions import \ EdgeFunction, NodeFunction, GlobalFunction, \ EdgeReLU, NodeReLU, GlobalReLU, \ EdgeSigmoid, NodeSigmoid, GlobalSigmoid, \ EdgeDropout, NodeDropout, GlobalDropout <file_sep>from typing import Sequence import pytest import networkx as nx from torchgraphs import Graph from graphs_for_test import graphs_for_test from features_shapes import all_features @pytest.fixture(params=all_features.values(), ids=all_features.keys()) def features_shapes(request): return request.param @pytest.fixture(params=graphs_for_test().values(), ids=graphs_for_test().keys()) def graph_nx(request) -> nx.Graph: return request.param @pytest.fixture(params=graphs_for_test().values(), ids=graphs_for_test().keys()) def graph(request) -> Graph: return Graph.from_networkx(request.param) @pytest.fixture def graphs_nx() -> Sequence[nx.Graph]: return list(graphs_for_test().values()) @pytest.fixture def graphs() -> Sequence[Graph]: return [Graph.from_networkx(g) for g in graphs_for_test().values()]
4fc09244c93d0b56f056477d5c274a8d35d41561
[ "Markdown", "Python", "Text" ]
26
Python
baldassarreFe/torchgraphs
ae42b917c0494c2201743f9c420cff466156e132
4cae6a6e2831e49c9b0f327faf3710ab553c43e2
refs/heads/main
<file_sep># Google Software Product Sprint This repo contains <NAME>'s portfolio and SPS projects. <file_sep>package com.google.sps.servlets; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; /** Handles requests sent to the /hello URL. Try running a server and navigating to /hello! */ @WebServlet("/hello") public class HelloWorldServlet extends HttpServlet { List<String> facts = Arrays.asList("My name is Tyler.", "I play guitar.", "I go to Georgia Tech."); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { Gson gson = new Gson(); String json = gson.toJson(facts); response.setContentType("application/json;"); response.getWriter().println(json); } }
adf5230f721191077835feb7bf0ca6fa216419a4
[ "Markdown", "Java" ]
2
Markdown
tyjedz/my-portfolio
a0962fbede149a704cf90a4bfa601df7e9b5f55f
2b9bd5d9bee6ca854a0d8461898b0c7e9dfdca08
refs/heads/master
<file_sep>vti_encoding:SR|utf8-nl vti_timelastmodified:TR|14 Mar 2016 12:57:02 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|STUDENTS\\itjblund592 vti_modifiedby:SR|STUDENTS\\itdomara586 vti_timecreated:TR|01 Mar 2016 11:35:58 -0000 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|08 Mar 2016 11:14:04 -0000 vti_cacheddtm:TX|14 Mar 2016 12:57:02 -0000 vti_filesize:IR|1043 vti_cachedbodystyle:SR|<body> vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 <file_sep>vti_encoding:SR|utf8-nl vti_author:SR|STUDENTS\\itdomara586 vti_modifiedby:SR|STUDENTS\\itdomara586 vti_timelastmodified:TR|14 Mar 2016 12:54:17 -0000 vti_timecreated:TR|14 Mar 2016 12:54:17 -0000 vti_cacheddtm:TX|14 Mar 2016 12:54:17 -0000 vti_filesize:IR|459 vti_cachedbodystyle:SR|<body> vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 vti_extenderversion:SR|12.0.0.0 vti_backlinkinfo:VX| <file_sep>vti_encoding:SR|utf8-nl vti_author:SR|STUDENTS\\itjblund592 vti_modifiedby:SR|STUDENTS\\itdomara586 vti_timelastmodified:TR|14 Mar 2016 12:50:46 -0000 vti_timecreated:TR|26 Feb 2016 09:18:51 -0000 vti_extenderversion:SR|12.0.0.0 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|10 Mar 2016 14:52:26 -0000 vti_cacheddtm:TX|14 Mar 2016 12:50:46 -0000 vti_filesize:IR|2095 vti_cachedbodystyle:SR|<body> vti_cachedlinkinfo:VX|S|https://www.google.com/maps/embed vti_cachedsvcrellinks:VX|NSSS|https://www.google.com/maps/embed vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_metatags:VR|HTTP-EQUIV=Content-Language en-gb vti_charset:SR|utf-8 vti_language:SR|en-gb <file_sep>vti_encoding:SR|utf8-nl vti_author:SR|STUDENTS\\itjblund592 vti_modifiedby:SR|STUDENTS\\itdomara586 vti_timelastmodified:TR|14 Mar 2016 12:50:46 -0000 vti_timecreated:TR|26 Feb 2016 09:20:29 -0000 vti_extenderversion:SR|12.0.0.0 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|11 Mar 2016 09:57:20 -0000 vti_cacheddtm:TX|14 Mar 2016 12:50:46 -0000 vti_filesize:IR|1467 vti_cachedbodystyle:SR|<body> vti_cachedlinkinfo:VX|H|Menu_Food.php H|Menu_Drinks.php H|Reservations.php H|Events.php H|Find_us.php S|http://free.timeanddate.com/clock/i53mwibw/n1364/szw110/szh110/hoc000/hbw2/hfcf1dca7/cf100/hnce1ead6/hwcf1dca7/hccf1dca7/hcw2/hcd100/fav0/fiv0/mqc000/mqs3/mql25/mqw2/mqd96/mhc000/mhs3/mhl20/mhw2/mhd96/mmc000/mms3/mml5/mmw2/mmd96/hhs2/hhw8/hms2/hmw8/hmr4/hss3/hsl90 vti_cachedsvcrellinks:VX|NHUS|commonMods/Menu_Food.php NHUS|commonMods/Menu_Drinks.php NHUS|commonMods/Reservations.php NHUS|commonMods/Events.php NHUS|commonMods/Find_us.php NSHS|http://free.timeanddate.com/clock/i53mwibw/n1364/szw110/szh110/hoc000/hbw2/hfcf1dca7/cf100/hnce1ead6/hwcf1dca7/hccf1dca7/hcw2/hcd100/fav0/fiv0/mqc000/mqs3/mql25/mqw2/mqd96/mhc000/mhs3/mhl20/mhw2/mhd96/mmc000/mms3/mml5/mmw2/mmd96/hhs2/hhw8/hms2/hmw8/hmr4/hss3/hsl90 vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 <file_sep>vti_encoding:SR|utf8-nl vti_timelastmodified:TR|14 Mar 2016 11:31:58 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|STUDENTS\\itjblund592 vti_modifiedby:SR|STUDENTS\\itjblund592 vti_timecreated:TR|01 Mar 2016 11:35:58 -0000 vti_backlinkinfo:VX| vti_cacheddtm:TX|14 Mar 2016 11:31:58 -0000 vti_filesize:IR|1041 vti_cachedbodystyle:SR|<body> vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 <file_sep>vti_encoding:SR|utf8-nl vti_author:SR|STUDENTS\\itjblund592 vti_modifiedby:SR|STUDENTS\\itdomara586 vti_timelastmodified:TR|14 Mar 2016 12:57:02 -0000 vti_timecreated:TR|11 Mar 2016 09:18:28 -0000 vti_extenderversion:SR|12.0.0.0 vti_nexttolasttimemodified:TW|14 Mar 2016 12:56:53 -0000 vti_backlinkinfo:VX| vti_cacheddtm:TX|14 Mar 2016 12:57:02 -0000 vti_filesize:IR|467 vti_cachedbodystyle:SR|<body> vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 <file_sep>vti_encoding:SR|utf8-nl vti_author:SR|STUDENTS\\itdomara586 vti_modifiedby:SR|STUDENTS\\itdomara586 vti_timelastmodified:TR|14 Mar 2016 12:54:17 -0000 vti_timecreated:TR|14 Mar 2016 12:54:17 -0000 vti_cacheddtm:TX|14 Mar 2016 12:54:17 -0000 vti_filesize:IR|1589 vti_cachedbodystyle:SR|<body> vti_cachedlinkinfo:VX|S|https://www.google.com/maps/embed S|images/find_us.jpg vti_cachedsvcrellinks:VX|NSSS|https://www.google.com/maps/embed NSUS|commonMods/images/find_us.jpg vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 vti_extenderversion:SR|12.0.0.0 vti_backlinkinfo:VX| <file_sep><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head><!--start main style--> <style type="text/css">.mainContainer { font-family: Arial, Helvetica, sans-serif; font-size: medium; } body{ background-color:#4d4d4d; } </style><!--end main style--> </head> <body> <div class="mainContainer"> <!-- start mainContainer--> <div class="header"> <!--banner class--> <?php include "commonMods/header.php";?> <!--mod import--> </div> <div class="menu"> <!--menu class--> <?php include "commonMods/menu.php"; ?> <!--mod import--> </div> <div class="content_Index"> <!--content class--> <?php include "commonMods/content_Menu_Food.php"; ?> <!--mod import--> </div> <div class="footer"> <!--footer class--> <?php include "commonMods/footer.php";?> <!--mod import--> </div> </div> <!--end mainContainer--> </body> </html> <file_sep>vti_encoding:SR|utf8-nl vti_author:SR|STUDENTS\\itjblund592 vti_modifiedby:SR|STUDENTS\\itdomara586 vti_timelastmodified:TR|14 Mar 2016 12:50:46 -0000 vti_timecreated:TR|26 Feb 2016 09:19:25 -0000 vti_extenderversion:SR|12.0.0.0 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|14 Mar 2016 12:28:34 -0000 vti_cacheddtm:TX|14 Mar 2016 12:50:46 -0000 vti_filesize:IR|824 vti_cachedbodystyle:SR|<body> vti_cachedlinkinfo:VX|S|images/home.jpg vti_cachedsvcrellinks:VX|NSUS|commonMods/images/home.jpg vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 <file_sep>vti_encoding:SR|utf8-nl <<<<<<< HEAD vti_timelastmodified:TR|11 Mar 2016 09:23:49 -0000 ======= vti_timelastmodified:TR|08 Mar 2016 11:14:04 -0000 >>>>>>> origin/master vti_extenderversion:SR|12.0.0.0 vti_author:SR|STUDENTS\\itjblund592 vti_modifiedby:SR|STUDENTS\\itjblund592 vti_timecreated:TR|01 Mar 2016 11:35:58 -0000 vti_backlinkinfo:VX| <<<<<<< HEAD vti_nexttolasttimemodified:TW|01 Mar 2016 11:35:58 -0000 vti_cacheddtm:TX|11 Mar 2016 09:23:52 -0000 vti_filesize:IR|1037 ======= vti_cacheddtm:TX|08 Mar 2016 11:14:04 -0000 vti_filesize:IR|1036 >>>>>>> origin/master vti_cachedbodystyle:SR|<body> vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 <file_sep>vti_encoding:SR|utf8-nl vti_author:SR|STUDENTS\\itjblund592 vti_modifiedby:SR|STUDENTS\\itdomara586 vti_timelastmodified:TR|14 Mar 2016 12:50:46 -0000 vti_timecreated:TR|11 Mar 2016 09:18:28 -0000 vti_extenderversion:SR|12.0.0.0 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|11 Mar 2016 10:20:13 -0000 vti_cacheddtm:TX|14 Mar 2016 12:50:46 -0000 vti_filesize:IR|1125 vti_cachedbodystyle:SR|<body> vti_cachedlinkinfo:VX|S|images/events.jpg vti_cachedsvcrellinks:VX|NSUS|commonMods/images/events.jpg vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 <file_sep>vti_encoding:SR|utf8-nl vti_author:SR|STUDENTS\\itjblund592 vti_modifiedby:SR|STUDENTS\\itdomara586 vti_timelastmodified:TR|14 Mar 2016 12:50:46 -0000 vti_timecreated:TR|26 Feb 2016 09:18:37 -0000 vti_extenderversion:SR|12.0.0.0 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TW|26 Feb 2016 10:58:31 -0000 vti_cacheddtm:TX|14 Mar 2016 12:50:46 -0000 vti_filesize:IR|499 vti_cachedbodystyle:SR|<body> vti_cachedlinkinfo:VX|H|Home.php vti_cachedsvcrellinks:VX|NHUS|commonMods/Home.php vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8 <file_sep>vti_encoding:SR|utf8-nl vti_timelastmodified:TR|14 Mar 2016 12:54:46 -0000 vti_extenderversion:SR|12.0.0.0 vti_author:SR|STUDENTS\\itjblund592 vti_modifiedby:SR|STUDENTS\\itdomara586 vti_timecreated:TR|01 Mar 2016 11:35:58 -0000 vti_backlinkinfo:VX| vti_nexttolasttimemodified:TR|14 Mar 2016 12:46:03 -0000 vti_cacheddtm:TX|14 Mar 2016 12:54:46 -0000 vti_filesize:IR|1040 vti_cachedbodystyle:SR|<body> vti_cachedneedsrewrite:BR|false vti_cachedhasbots:BR|false vti_cachedhastheme:BR|false vti_cachedhasborder:BR|false vti_charset:SR|utf-8
5616a401b274998f5622c5adb21e4e3505b612f2
[ "PHP" ]
13
PHP
thecraicbear/TheRestaurantProject
8af2ce46d14dfed0de0e7c36e25680df3acab796
4b3c6068f0cad5ed2c6ff19f43b395766f59bcb8
refs/heads/master
<file_sep>(function ($) { "use strict"; Drupal.behaviors.customBehavior = { // perform jQuery as normal in here attach: function (context, settings) { if (!(context instanceof HTMLDocument)) return; $(function () { $(".feedback-slider").responsiveSlides({ auto: false, nav: true, prevText: " ", nextText: " ", pager: true, speed: 800 }); ////////////////Sticky header on scroll/////////////////////////////// $(window).scroll(function() { if($(this).scrollTop() >= 70) { $('#navbar').addClass('stickytop'); $('.topcontrol').addClass('visible'); } else{ $('#navbar').removeClass('stickytop'); $('.topcontrol').removeClass('visible'); } }); ///////////////////////////////////// $(document).ready(function(){ $(".topcontrol").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); //return false; }); //$('.dropdown-toggle').prop('disabled', true); function setMobileMenuHeight() { var wh = $(window).height(), hh = $('.navbar-header').outerHeight(), $am = $('#toolbar-bar'), ah = $am.length ? $am.outerHeight() : 0; $('.region-navigation-collapsible').css('max-height', wh - hh - ah + 'px'); } $('.navbar-toggle').on('click', setMobileMenuHeight); $(window).on('resize', function (event) { setMobileMenuHeight(); }); $('.dropdown-toggle').on('click', function(e) { if ( $('.navbar-toggle').css('display') !== 'none' ) { var aria_expanded = $(this).attr('aria-expanded'), $dm = $(this).next('.dropdown-menu'), dm_li = $dm.find('li'), h = 0; for(var i=0; i < dm_li.length; i++) { h += +$(dm_li[i]).outerHeight(); } $dm.height( aria_expanded === 'true' ? 0 : h ); } else{ $(this).prop('disabled', true); } }); function lockScroll() { if ($('body').hasClass('lock-scroll')) { $('body').removeClass('lock-scroll'); } else { $('body').addClass('lock-scroll'); } } $('.navbar-toggle').on('click', function (event) { lockScroll(); //disabling body scroll when menu opened }); ///////////////////////////////////// $(document).on('click', '.navbar-collapse.in', function (e) { console.log(e); if ($(e.target).is('a') && $(e.target).attr('class') != 'dropdown-toggle' ) { $(this).collapse('hide'); } }); }); ///////////////////////////////////////////// new WOW().init(); }); } }; })(jQuery);
4f290d4ca62973cebe0d4991271456888d1d3b26
[ "JavaScript" ]
1
JavaScript
Svetlana712/plastic
127b18f37bfbcf51d5b2220af6e2d5b5fbb44cfc
98b534804814380d1dd9f25d8d2cabb24c95f472
refs/heads/master
<file_sep>"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from app.views import RegisterView,LoginView,LogoutView,IndexView,MainView,Person_info from django.contrib import admin from django.conf.urls import url from app import views import app from django.conf import settings from django.views.static import serve urlpatterns = [ # 基于函数 的 View 映射 URL 方法 #path('register/',RegisterView.as_view(),name='register'), url(r'^admin/', admin.site.urls), url(r'^login/$', LoginView.as_view(),name='login'), url(r'^register/$',RegisterView.as_view(),name='register'), url(r'^main/$',MainView.as_view(),name='main'), url(r'^person_info/$',Person_info.as_view(),name='person_info'), url(r'^logout/',LogoutView.as_view(),name='logout'), url(r'^save_todo/$',views.save_todo), url(r'^save_memo/$',views.save_memo), url(r'^save_hide_todo/$',views.save_hide_todo), url(r'^$',IndexView.as_view(),name='index'), url(r'^page_not_found',views.page_not_found), url(r'^not_open', views.not_open,name='not_open'), ] # 全局 404 页面配置(django 会自动调用这个变量) handler404 = 'app.views.page_not_found' """ if settings.DEBUG: # debug_toolbar 插件配置 import debug_toolbar urlpatterns.append(url(r'^__debug__/', include(debug_toolbar.urls))) else: # 项目部署上线时使用 from mysite.settings import STATIC_ROOT # 配置静态文件访问处理 urlpatterns.append(url(r'^static/(?P<path>.*)$', serve, {'document_root': STATIC_ROOT})) """<file_sep># Python+Django+SQLite 制作TO-DO list Python Django SQLite --- ## **ToDo List** ![todo-logo](http://172.16.31.10/static/images/main_page/logo_small.png) > 利用Django及SQLite制作的一个小型的TodoList,目的在于熟悉Django的编程以及SQLite数据库的一些简单操作,并不具备真正的生产功能。我将其部署在服务器中是也可以熟悉一下服务器的部署,增加对服务器的一些了解 **功能包括** - [x] 用户注册与登陆 - [x] 用户创建自己的memo - [x] 用户添加ToDolist - [ ] 利用其他平台(微信、QQ等)的账户进行登陆 - [ ] 在微信上利用服务号进行任务推 **环境** > * Django 2.0.6 > * SQLite(Django内置) <file_sep>// JavaScript Document function register(){ var password1 = document.getElementById("password1"); var password2 = document.getElementById("<PASSWORD>"); if (password1.value.length <6){ alert("密码长度至少为6个字符"); }else if (password1.value!==password2.value){ alert("两次输入的密码长度不一致,请重新输入"); } }<file_sep># !usr/bin/env python # -*- coding:utf-8 -*- # 生成图片验证码 import string import random from PIL import Image,ImageDraw,ImageFont,ImageFilter class Picture(object): ''' 生成图片验证码 ''' def __init__(self,size,background): ''' :param text: 图片验证码上的文字 :param size: 图片验证码的大小 :param background: 图片验证码的北京图片 ''' self.size = size self.background = background def create_pic(self): # 定义使用Image类实例化基于RGB的(255,255,255)颜色的图片 self.width,self.height=self.size self.img = Image.new("RGB",self.size,background) # 实例化画笔 self.draw = ImageDraw.Draw(self.img, mode="RGB") def create_text(self,font_type,font_size,font_num): ''' 画验证码的文字 :param self: :param font_type:字体格式 :param font_size: 字体大小 :param font_num: 文字的数量 :param start_xy: 第一个字左上角坐标,元组类型,如(5,5) :return: ''' font = ImageFont.truetype(font_type,font_size) letterto_test=[] for i in range(font_num): # 每循环一次生成一个随机字母或数字 letter=random.choice([random.choice(string.ascii_letters), str(random.randint(0, 9))]) # 每循环一次生成随机颜色, #color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 把生成的字母或数字添加到图片上 # 图片长度为100px,要生成几个数字或字母则每添加一个,其位置就要向后移动24px letterto_test.append(letter) print(letter) self.draw.text((20 * i + 10, 5),letter,fill=(random.randint(32,127),random.randint(32,127),random.randint(32,127)),font=font) letterto_test = ''.join(letterto_test) return letterto_test def draw_point(self): ''' 画点 :param num: 画点的数量 :return: ''' for y in range(self.height): for x in range(self.width): self.draw.point((x,y),fill=(random.randint(64,255),random.randint(64,255),random.randint(64,255))) def draw_line(self,num,color): ''' 画随机线条 :param num: :return: ''' for i in range(num): self.draw.line( [ (random.randint(0,self.width),random.randint(0,self.height)), (random.randint(0, self.width), random.randint(0, self.height)) ], fill=color ) def opera(self): ''' 对生成的对象进行相关操作,比如:旋转,缩放等 目的是让图片不太好识别 :return: ''' parms = [ 1 - float(random.randint(1,2))/100, 0, 0, 0, 1 - float(random.randint(1,10))/100, float(random.randint(1, 2)) / 500, 0.001, float(random.randint(1, 2)) / 500 ] self.img = self.img.transform(self.size,Image.PERSPECTIVE,parms) self.img = self.img.filter(ImageFilter.EDGE_ENHANCE_MORE) def save_pic(self): # 把生成的图片保存为“pic.png”格式 filename = "pic.png" with open(filename, "wb") as f: self.img.save(f, format("png")) def test(self,letterto_test): def toverify(): code = input('请输入验证码:') if code==letterto_test: print('通过') pass else: print('请重新输入') toverify() return toverify() if __name__ == '__main__': size = (150,50) num_point=150*50 background = 'white' pic = Picture(size,background) pic.create_pic() pic.draw_point() letterto_test=pic.create_text("times.ttf", 30, 5) #pic.draw_line(5, (30, 40, 210)) pic.opera() pic.img.filter(ImageFilter.BLUR) #pic.img.show() pic.save_pic() pic.test(letterto_test)<file_sep># Generated by Django 2.0.5 on 2018-06-01 07:49 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('app', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='usertodo', name='created_time', ), migrations.AddField( model_name='usertodo', name='deadline', field=models.DateTimeField(default=datetime.datetime(2018, 6, 1, 7, 49, 18, 623084, tzinfo=utc), verbose_name='截至时间'), ), ] <file_sep># Generated by Django 2.0.5 on 2018-06-03 15:32 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0004_auto_20180601_2030'), ] operations = [ migrations.AlterField( model_name='usertodo', name='deadline', field=models.DateTimeField(default=datetime.datetime(2018, 6, 3, 15, 32, 20, 756344), verbose_name='截至时间'), ), ] <file_sep>from django.db.models import Q from django.contrib.auth.backends import ModelBackend from django.shortcuts import render from django.views.generic.base import View from .models import UserProfile,UserTodo,UserMessage from .forms import RegisterForm,LoginForm from django.views.decorators.csrf import csrf_exempt from django.contrib.auth.hashers import make_password from django.contrib.auth import authenticate,login,logout from django.urls import reverse from django.http import HttpResponse,HttpResponseRedirect import re from datetime import datetime # Create your views here. #业务处理逻辑的编写 #自定义用户验证函数,实现邮箱或用户名都能登陆 class MyBackend(ModelBackend): def authenticate(self,username=None,password=None,**kwargs): try: user = UserProfile.objects.get(Q(username=username)|Q(email=username)) if user.check_password(password): return user except Exception as e: return None #用户注册 class RegisterView(View): def get(self,request): #get 请求,可以将验证码等html render到register.html中 register_form = RegisterForm() return render(request,'register.html',{'register_form':register_form}) def post(self,request): register_form = RegisterForm(request.POST) if register_form.is_valid(): email = request.POST.get('user_email','') #否则为空 username = request.POST.get('user_name','') if UserProfile.objects.filter(username=username): return render(request,'register.html',{'register_form':register_form,'msg_user':'用户已存在!'}) if UserProfile.objects.filter(email=email): return render(request,'register.html',{'register_form':register_form,'msg_email':'该邮箱已经注册!'}) password = request.POST.get('<PASSWORD>1','') user_profile = UserProfile() user_profile.username = username user_profile.email = email user_profile.password = <PASSWORD>(<PASSWORD>) user_profile.is_active = True #判断用户是否激活 user_profile.save() return render(request,'success.html') return render(request,'register.html',{'register_form':register_form}) #用户登陆 class LoginView(View): def get(self,request): return render(request, 'login.html') def post(self,request): login_form = LoginForm(request.POST) if login_form.is_valid(): user_name = request.POST.get('username','') password = request.POST.get('password','') #与数据库中的用户进行比对 #上面已经对authenticate进行了重写 若成功则返回user user = authenticate(request,username=user_name,password=password) if user is not None: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('main')) return render(request, 'login.html', {'msg': '用户名或密码错误!'}) return render(request,'login.html',{'msg':'用户名或密码错误!'}) #用户退出登陆 class LogoutView(View): def get(self,request): logout(request) return HttpResponseRedirect(reverse('index')) #用户打开网页首先显示的部分即index页面 class IndexView(View): def get(self,request): return render(request, 'index.html') #用户登陆以后显示的main页面 class MainView(View): def get(self,request): user_email = UserProfile.objects.get(username=request.user) #注意打印出的是用户名 user_memo = user_email.memo todo_query = UserTodo.objects.filter(user_email=user_email,done=False) todo_query = todo_query.order_by("deadline") #按照截至日期按照从小到大的顺序进行筛选 # todo_query = todo_query.order_by("-deadline") 按照截至日期按照从大到小的顺序进行筛选 todo_dict = todo_query.values("ToDolist").values("ToDolist") todo_list = [] for todo in todo_dict: todo_list.append(todo["ToDolist"]) para = {'todo_list':todo_list,'memo':user_memo} #para_time = {'time0':time_list[0],'time1':time_list[1],'time2':time_list[2],'time3':time_list[3],'memo':user_memo} #para = dict(para_todo,**para_time) #将两个字典连接到一块 return render(request,'main2.html',para) def post(self,request): return render(request, 'main2.html') #用户自己更改信息,此功能未完善 class Person_info(View): def get(self,request): return render(request,'person_info.html') def post(self,request): ''' 用户提交修改个人信息 :param request: :return: ''' pass #用于提示该功能还未开放的界面 def not_open(request): return render(request,'not_open.html') #全局404 函数 def page_not_found(request): from django.shortcuts import render_to_response response = render_to_response('404.html', {}) response.status_code = 404 return response #全局500 函数 def page_error(request): from django.shortcuts import render_to_response response = render_to_response('500.html', {}) response.status_code = 500 return response #将用户添加的todo保存到数据库中,加装饰符为了防止csrf对其进行拦截 @csrf_exempt def save_todo(request): if request.method == 'POST': user_email = UserProfile.objects.get(username=request.user) print(user_email) memo = '' done = False try: todo = request.POST.get('todo')#获取从后端返回的数据 if todo is not None: user_todo = UserTodo(ToDolist=todo,done=done,user_email=user_email,deadline=datetime.now()) user_todo.save() except Exception as e: print(e) #用户点击右侧的X号,对todo进行隐藏 @csrf_exempt def save_hide_todo(request): if request.method == 'POST': user_email = UserProfile.objects.get(username=request.user) #获取当前登陆用户的todo id time_query = UserTodo.objects.filter(user_email=user_email, done=False) time_query = time_query.order_by("deadline") # 按照截至日期按照从小到大的顺序进行筛选 print(type(time_query)) time_dict = time_query.values("deadline") print(type(time_dict)) print(time_dict) try: id = int(request.POST.get('id')) time_index = time_dict[id]['deadline'] #获取用户点击隐藏的那一条的deadline,一般来讲用户的deadline是不可能有重复的 User = UserTodo.objects.get(user_email=user_email,deadline=time_index) #User = User.filter(deadline=time_index) User.done = True User.save() except Exception as e: print(e) #将用户添加的memo保存到数据库中,加装饰符为了防止csrf对其进行拦截 @csrf_exempt def save_memo(request): if request.method == 'POST': try: memo = request.POST.get('memo')#获取从后端返回的数据 user_profile = UserProfile.objects.get(username=request.user) user_profile.memo = memo user_profile.save() except Exception as e: print(e)<file_sep>function open_page() { startTime(); add_close(); } function openNav() { document.getElementById("mySidenav").style.width = "80px"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; } function OpenOrClose() { state = document.getElementById("mySidenav").style.width; if (state === "80px"){ closeNav() } else{ openNav() } } //将todo数据添加到数据库中 function save_todo(){ $.ajax({ type:"post", url:"/save_todo/", cache:false , data:{ 'todo':$("#myInput").val(), }, dataType: "text", success: function() { //console.log("over.."); //alert(data); //就将返回的数据显示出来 //window.location.href="跳转页面" }, }); } //将todo数据添加到数据库中 function save_memo(){ $.ajax({ type:"post", url:"/save_memo/", cache:false, data:{ 'memo':$("#memo").val(), }, dataType: "text", success: function() { //console.log("over.."); //alert(data); //就将返回的数据显示出来 //window.location.href="跳转页面" }, }); } // Create a "close" button and append it to each list item var container = document.getElementById("myUL"); var myNodelist = container.getElementsByTagName("LI"); var i; for (i = 0; i < myNodelist.length; i++) { var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.className = "close"; span.appendChild(txt); myNodelist[i].appendChild(span); } // Click on a close button to hide the current list item function add_close() { var close = document.getElementsByClassName("close"); var i; for (i = 0; i < close.length; i++) { (function(i){ close[i].onclick = function() { this.parentElement.style.display = "none"; console.log(i) save_hide_todo(i) }; }(i)); } } // 当点击”新增“按钮时,增加新的元素,并保存在数据库中 function newElement() { var li = document.createElement("li"); var inputValue = document.getElementById("myInput").value; var t = document.createTextNode(inputValue); li.appendChild(t); if (inputValue === '') { alert("你还木有添加To Do..."); } else { document.getElementById("myUL").appendChild(li);//将新添加的list加入到后续的队列中 save_todo(); //调用数据库保存函数 } document.getElementById("myInput").value = ""; //将input框置空,以便下次输入 var span = document.createElement("SPAN"); //创建新的span标签 var txt = document.createTextNode("\u00D7");//创建X号 span.className = "close"; span.appendChild(txt); li.appendChild(span); add_close() } //用户点击X号,设置完成状态 function save_hide_todo(id) { $.ajax({ type:"post", url:"/save_hide_todo/", cache:false, data:{ 'id':id, }, success: function(data) { //console.log("over.."); //alert(data); //就将返回的数据显示出来 //window.location.href="跳转页面" }, error: function(data) { //console.log(data); // alert("Connection error"); } }); } function startTime() { var today=new Date();//定义日期对象 var yyyy = today.getFullYear();//通过日期对象的getFullYear()方法返回年 var MM = today.getMonth()+1;//通过日期对象的getMonth()方法返回年 var dd = today.getDate();//通过日期对象的getDate()方法返回年 var hh=today.getHours();//通过日期对象的getHours方法返回小时 var mm=today.getMinutes();//通过日期对象的getMinutes方法返回分钟 var ss=today.getSeconds();//通过日期对象的getSeconds方法返回秒 // 如果分钟或小时的值小于10,则在其值前加0,比如如果时间是下午3点20分9秒的话,则显示15:20:09 MM=checkTime(MM); dd=checkTime(dd); mm=checkTime(mm); ss=checkTime(ss); var day; //用于保存星期(getDay()方法得到星期编号) if(today.getDay()==0) day = "星期日 " if(today.getDay()==1) day = "星期一 " if(today.getDay()==2) day = "星期二 " if(today.getDay()==3) day = "星期三 " if(today.getDay()==4) day = "星期四 " if(today.getDay()==5) day = "星期五 " if(today.getDay()==6) day = "星期六 " document.getElementById('clock_date').innerHTML=yyyy+"-"+MM +"-"+ dd +" "; document.getElementById('clock_time').innerHTML=hh+":"+mm+":"+ss+" " + day; setTimeout('startTime()',1000);//每一秒重新加载startTime()方法 } function checkTime(i) { if (i<10){ i="0" + i; } return i; }<file_sep># Generated by Django 2.0.5 on 2018-06-01 20:27 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0002_auto_20180601_1549'), ] operations = [ migrations.RemoveField( model_name='usertodo', name='memo', ), migrations.AddField( model_name='userprofile', name='memo', field=models.TextField(blank=True, null=True, verbose_name='便签'), ), migrations.AlterField( model_name='usertodo', name='deadline', field=models.DateTimeField(default=datetime.datetime(2018, 6, 1, 20, 27, 54, 114938), verbose_name='截至时间'), ), ] <file_sep>// JavaScript Document function login(){ var username = document.getElementById("username"); var password = document.getElementById("password"); if (username.value ==""){ alert("请输入用户名"); }else if (password.value==""){ alert("请输入密码"); }else if (username.value =="adminbylht"&&password.value =="<PASSWORD>"){ window.location.href="welcome.html"; }else{ alert("请输入正确的用户名和密码!") } }<file_sep>from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import UserProfile,UserTodo # Register your models here. admin.site.register(UserProfile,UserAdmin)#用UserAdmin去注册UserProfile admin.site.register(UserTodo) <file_sep>// JavaScript Document /*以下是函数*/ // Create a "close" button and append it to each list item var container = document.getElementById("myUL"); var myNodelist = container.getElementsByTagName("LI"); var i; for (i = 0; i < myNodelist.length; i++) { var span = document.createElement("SPAN"); var txt = document.createTextNode("\u00D7"); span.className = "close"; span.appendChild(txt); myNodelist[i].appendChild(span); } / //对目标标签进行隐藏 function hide_ele(div) { div.style.display = "none"; } // Add a "checked" symbol when clicking on a list item var list = document.querySelector('ul'); list.addEventListener('click', function(ev) { if (ev.target.Tagname=== 'LI') { ev.target.classList.toggle('checked'); } }, false); // 当点击”新增“按钮时,增加新的元素,并保存在数据库中 function newElement() { var li = document.createElement("li"); var inputValue = document.getElementById("myInput").value; console.log(inputValue) var t = document.createTextNode(inputValue); li.appendChild(t); if (inputValue === '') { alert("你还木有添加To Do..."); } else { document.getElementById("myUL").appendChild(li);//将新添加的list加入到后续的队列中 save_todo(); //调用数据库保存函数 } document.getElementById("myInput").value = ""; //将input框置空,以便下次输入 document.getElementById("myUL"); var span = document.createElement("SPAN"); //创建新的span标签 var txt = document.createTextNode("\u00D7");//创建X号 span.className = "close"; span.appendChild(txt); li.appendChild(span); for (i = 0; i < close.length; i++) { close[i].onclick = function(i) { var div = this.parentElement; div.style.display = "none"; } } } / Click on a close button to hide the current list item var close = document.getElementsByClassName("close"); var i; for (i = 0; i < close.length; i++) { (function(i){ close[i].onclick = function() { this.parentElement.style.display = "none"; console.log(i) save_hide_todo(i) }; }(i)); } /* 点击按钮,下拉菜单在 显示/隐藏 之间切换 */ function choose_important() { document.getElementById("myDropdown").classList.toggle("show"); } // 点击下拉菜单 以外区域隐藏 window.onclick = function(event) { if (!event.target.matches('.addBtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } //将数据添加到数据库中 function save_todo(){ $.ajax({ type:"post", url:"/save_info/", cache:false, data:{ 'todo':$("#myInput").val(), }, dataType: "text", success: function(data) { //console.log("over.."); //alert(data); //就将返回的数据显示出来 //window.location.href="跳转页面" }, error: function(data) { //console.log(data); alert("Connection error"); } }); } //用户点击X号,设置完成状态 function save_hide_todo(id) { $.ajax({ type:"post", url:"/save_hide_todo/", cache:false, data:{ 'id':id, }, success: function(data) { //console.log("over.."); //alert(data); //就将返回的数据显示出来 //window.location.href="跳转页面" }, error: function(data) { //console.log(data); // alert("Connection error"); } }); }<file_sep># !usr/bin/env python # -*- coding:utf-8 -*- from django import forms class RegisterForm(forms.Form): user_email = forms.EmailField(required=True) password1 = forms.CharField(required=True,min_length=6) password2 = forms.CharField(required=True, min_length=6) user_name = forms.CharField(required=True) class LoginForm(forms.Form): username = forms.CharField(required=True,error_messages={'required':'用户名不能为空',}) password = forms.CharField(required=True,error_messages={'required':'密码不能为空',})<file_sep># Generated by Django 2.0.6 on 2018-06-07 00:48 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0005_auto_20180603_1532'), ] operations = [ migrations.AlterField( model_name='usertodo', name='deadline', field=models.DateTimeField(default=datetime.datetime(2018, 6, 7, 8, 48, 20, 434546), verbose_name='截至时间'), ), ] <file_sep>from django.db import models from django.contrib.auth.models import AbstractUser from datetime import datetime #导入AbstractUser class UserProfile(AbstractUser): ''' 继承Django的AbstractUser 并向里面添加数据内容 ''' gender = models.CharField(max_length=6,choices=(('male','男'),('female','女')),default='female',verbose_name='性别') memo = models.TextField(null=True, blank=True,verbose_name='便签') class Meta: verbose_name = '用户信息' verbose_name_plural = verbose_name #指定模型的复数形式是什么,如果不指定Django会自动在模型名称后加一个’s’ class UserTodo(models.Model): deadline = models.DateTimeField(default=datetime.now(),verbose_name='截至时间') user_email = models.ForeignKey(UserProfile,on_delete=models.CASCADE) #设置外键,关联到UserProfile表 ToDolist = models.CharField(max_length=255,verbose_name='todo') done = models.BooleanField(default=False,verbose_name='完成状态') class Meta: verbose_name = '用户自增信息' verbose_name_plural = verbose_name class EmailVerifyRecord(models.Model): code = models.CharField(max_length=20,verbose_name='验证码') email = models.EmailField(max_length=50, verbose_name='邮箱') send_type = models.CharField(max_length=18, choices=(('register', '邮箱'), ('forget', '修改密码'), ('update_email', '修改邮箱')), verbose_name='验证码类型') send_time = models.DateField(default=datetime.now, verbose_name='发送时间') class Meta: verbose_name = '邮箱验证码' verbose_name_plural = '邮箱验证码' #当启用邮件系统时用到下面的models class UserMessage(models.Model): # 如果 为 0 代表全局消息,否则就是用户的 ID user = models.IntegerField(default=0, verbose_name='接受用户') message = models.CharField(max_length=500, verbose_name='消息内容') has_read = models.BooleanField(default=False, verbose_name='是否已读') add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间') class Meta: verbose_name = '用户消息' verbose_name_plural = verbose_name
d4be93ba250fde9295292591157c287cc7c758f5
[ "Markdown", "Python", "JavaScript" ]
15
Python
Prolht/mysite-todo-list
bc2611bba14e2a2bc2648b11e367d2449c6df65d
151abb86d566300e49110aa51693be97e20ebd50
refs/heads/master
<repo_name>beingmartinbmc/Employee-Full-Stack<file_sep>/frontend/employee-manager-app/src/app/components/create-employee/create-employee.component.ts import { HttpErrorResponse } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { EmployeeService } from 'src/app/services/employee.service'; @Component({ selector: 'app-create-employee', templateUrl: './create-employee.component.html', styleUrls: ['./create-employee.component.css'] }) export class CreateEmployeeComponent implements OnInit { public firstName: string public lastName: string public email: string constructor(private employeeService: EmployeeService, private router: Router) { } ngOnInit(): void { } private addEmployee(): void { const employee = { "firstName": this.firstName, "lastName": this.lastName, "email": this.email } this.employeeService.addEmployee(employee).subscribe((emp) => { this.router.navigate(['/employee']) }, (error: HttpErrorResponse) => { alert(error.message) }) } public onSubmit(): void { this.addEmployee(); } } <file_sep>/frontend/employee-manager-app/src/app/components/employee-list/employee-list.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Employee } from 'src/app/Employee'; import { EmployeeService } from 'src/app/services/employee.service'; @Component({ selector: 'app-employee-list', templateUrl: './employee-list.component.html', styleUrls: ['./employee-list.component.css'] }) export class EmployeeListComponent implements OnInit { constructor(private employeeService: EmployeeService, private router: Router) { } ngOnInit(): void { this.getEmployees(); } employees: Employee[]; private getEmployees(): void { this.employeeService.getAllEmployees() .subscribe( (emp) => { this.employees = emp; }, (error) => { alert(error.message); } ) } public onDelete(employee: Employee) { this.employeeService.deleteEmployee(employee).subscribe(() => { this.employees = this.employees.filter(i => i.id !== employee.id) }) } public onUpdate(employee: Employee) { this.router.navigate(['/update-employee'], { queryParams: employee}) } }<file_sep>/frontend/employee-manager-app/src/app/components/update-employee/update-employee.component.ts import { HttpErrorResponse } from '@angular/common/http'; import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Employee } from 'src/app/Employee'; import { EmployeeService } from 'src/app/services/employee.service'; @Component({ selector: 'app-update-employee', templateUrl: './update-employee.component.html', styleUrls: ['./update-employee.component.css'] }) export class UpdateEmployeeComponent implements OnInit { public firstName: string public lastName: string public email: string constructor( private employeeService: EmployeeService, private router: Router, private route: ActivatedRoute ) { } ngOnInit(): void { } private updateEmployee(employee: Employee): void { const newEmployee = { "firstName": this.firstName, "lastName": this.lastName, "email": this.email, "id": employee.id } this.employeeService.updateEmployee(newEmployee).subscribe((emp) => { this.router.navigate(['/employee']) }, (error: HttpErrorResponse) => { alert(error.message) }) } public onSubmit(): void { const emp = this.route.snapshot.queryParams const employee: Employee = emp as Employee; this.updateEmployee(employee); } } <file_sep>/frontend/employee-manager-app/src/app/services/employee.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { EmptyError, Observable } from 'rxjs'; import { Employee } from '../Employee'; @Injectable({ providedIn: 'root' }) export class EmployeeService { private baseURL: string = "http://localhost:9999/employee" constructor(private http: HttpClient) {} public getAllEmployees(): Observable<Employee[]> { const url = `${this.baseURL}/all` return this.http.get<Employee[]>(url); } public addEmployee(employee: Employee): Observable<Employee> { const url = `${this.baseURL}/add` return this.http.post<Employee>(url, employee); } public deleteEmployee(employee: Employee): Observable<Employee> { const url = `${this.baseURL}/delete/${employee.id}` return this.http.delete<Employee>(url); } public updateEmployee(employee: Employee): Observable<Employee> { const url = `${this.baseURL}/update` return this.http.put<Employee>(url, employee); } } <file_sep>/backend/employee-manager/src/main/java/com/example/employeemanager/entity/Employee.java package com.example.employeemanager.entity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; @Data @NoArgsConstructor @Builder @AllArgsConstructor @Entity public class Employee implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(nullable = false, updatable = false) private Long id; private String firstName; private String lastName; private String email; }
71c6c165a4301340ae9e07b71d0834482efa8d11
[ "Java", "TypeScript" ]
5
TypeScript
beingmartinbmc/Employee-Full-Stack
e7b4acc058d2f989be0dacdfa18ed2dd05ce5751
ad210308e8526a946588ec48cbc0043c3f8efa6f
refs/heads/master
<file_sep>Magento 2.x support: ===================== The repo for Magento 2 version of our module is available in the new repository of the module : [https://github.com/onilab/magento-2-google-api-chart-fix/](https://github.com/onilab/magento-2-google-api-chart-fix/). About this module: =================== https://onilab.com/blog/chart-broken-in-magento-1-2-admin-dashboard-reasons-hotfix/ Installation: =============== 1. Copy files to your Magento root path 2. Clear all caches 3. Go to the dashboard 4. Enjoy What Magento version is supported? ----------------------------------- The module has been successfully deployed and tested against the following Magento versions: * Magento EE 1.14 * Magento CE 1.9 Bugs / RFC ---------- Don't hesitate to: * Submit a bug, RFC, idea of new feature * Submit a merge request <file_sep><?php class Onilab_GoogleCharts_Block_Adminhtml_Dashboard_Tab_Orders extends Onilab_GoogleCharts_Block_Adminhtml_Dashboard_Graph { /** * Initialize object * * @return void */ public function __construct() { $this->setHtmlId('orders'); parent::__construct(); } /** * Prepare chart data * * @return void */ protected function _prepareData() { $this->setDataHelperName('adminhtml/dashboard_order'); $this->getDataHelper()->setParam('store', $this->getRequest()->getParam('store')); $this->getDataHelper()->setParam('website', $this->getRequest()->getParam('website')); $this->getDataHelper()->setParam('group', $this->getRequest()->getParam('group')); $this->setDataRows('quantity'); $this->_axisMaps = array( 'x' => 'range', 'y' => 'quantity' ); parent::_prepareData(); } public function getTitle() { return $this->__('Orders'); } }<file_sep><?php class Onilab_GoogleCharts_Block_Adminhtml_Dashboard_Graph extends Mage_Adminhtml_Block_Dashboard_Graph { // protected $_width = '700'; // protected $_height = '300'; public function __construct() { parent::__construct(); $this->setTemplate($this->_getTabTemplate()); } /** * Get tab template * * @return string */ protected function _getTabTemplate() { return 'onilab/google_charts/dashboard/graph.phtml'; } public function getChartData() { $this->_allSeries = $this->getRowsData($this->_dataRows); foreach ($this->_axisMaps as $axis => $attr) { $this->setAxisLabels($axis, $this->getRowsData($attr, true)); } $timezoneLocal = Mage::app()->getStore()->getConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_TIMEZONE); list ($dateStart, $dateEnd) = Mage::getResourceModel('reports/order_collection') ->getDateRange($this->getDataHelper()->getParam('period'), '', '', true); $dateStart->setTimezone($timezoneLocal); $dateEnd->setTimezone($timezoneLocal); $dates = array(); $datas = array(); while ($dateStart->compare($dateEnd) < 0) { switch ($this->getDataHelper()->getParam('period')) { case '24h': $d = $dateStart->toString('yyyy-MM-dd HH:00'); $dateStart->addHour(1); break; case '7d': case '1m': $d = $dateStart->toString('yyyy-MM-dd'); $dateStart->addDay(1); break; case '1y': case '2y': $d = $dateStart->toString('yyyy-MM'); $dateStart->addMonth(1); break; } foreach ($this->getAllSeries() as $index => $serie) { if (in_array($d, $this->_axisLabels['x'])) { $datas[$index][] = (float)array_shift($this->_allSeries[$index]); } else { $datas[$index][] = 0; } } $dates[] = strtotime($d); } return [$datas, $dates]; } }<file_sep><?php class Onilab_GoogleCharts_Helper_Data extends Mage_Core_Helper_Abstract { }
806be494131ec712fa9b61f09c2a159aa80da92a
[ "Markdown", "PHP" ]
4
Markdown
onilab/magento-1-google-api-chart-fix
a6ecc00f34df3a8c5a06b7e046725b0f0a121997
7f538752119fe9d7cf00ea6aaa6f6b03e11e9805
refs/heads/master
<repo_name>tduboys/beamium<file_sep>/src/lib/mod.rs use std::error::Error; pub mod transcompiler; pub fn add_labels(line: &str, labels: &str) -> Result<String, Box<Error>> { if labels.is_empty() { return Ok(String::from(line)); } let mut parts = line.splitn(2, '{'); let class = parts.next().ok_or("no_class")?; let class = String::from(class); let plabels = parts.next().ok_or("no_labels")?; let plabels = String::from(plabels); let sep = if plabels.trim().starts_with('}') { "" } else { "," }; Ok(format!("{}{{{}{}{}", class, labels, sep, plabels)) } <file_sep>/src/lib/transcompiler.rs use std::error::Error; use time; use config; pub struct Transcompiler<'a> { format: &'a config::ScraperFormat, now: i64, } impl<'a> Transcompiler<'a> { pub fn new(format: &config::ScraperFormat) -> Transcompiler { let start = time::now_utc(); let now = start.to_timespec().sec * 1000 * 1000 + (i64::from(start.to_timespec().nsec) as i64 / 1000); Transcompiler { format, now } } pub fn format(&self, line: &str) -> Result<String, Box<Error>> { match *self.format { config::ScraperFormat::Sensision => format_warp10(line), config::ScraperFormat::Prometheus => format_prometheus(line, self.now), } } } /// Format Warp10 metrics from Prometheus one. fn format_warp10(line: &str) -> Result<String, Box<Error>> { Ok(String::from(line.trim())) } /// Format Warp10 metrics from Prometheus one. fn format_prometheus(line: &str, now: i64) -> Result<String, Box<Error>> { let line = line.trim(); // Skip comments if line.starts_with('#') { return Ok(String::new()); } // Extract Prometheus metric let index = if line.contains('{') { line.rfind('}').ok_or("bad class")? } else { line.find(' ').ok_or("bad class")? }; let (class, v) = line.split_at(index + 1); let mut tokens = v.split_whitespace(); let value = tokens.next().ok_or("no value")?; // Prometheus value can be '-Inf' or '+Inf', skipping if so if value == "+Inf" || value == "-Inf" { return Ok(String::new()); } let timestamp = tokens .next() .map(|v| i64::from_str_radix(v, 10).map(|v| v * 1000).unwrap_or(now)) .unwrap_or(now); // Format class let mut parts = class.splitn(2, '{'); let class = String::from(parts.next().ok_or("no_class")?); let class = class.trim(); let plabels = parts.next(); let slabels = if plabels.is_some() { let mut labels = plabels.unwrap().split("\",") .map(|v| v.replace("=", "%3D")) // escape .map(|v| v.replace("%3D\"", "=")) // remove left double quote .map(|v| v.replace("\"}", "")) // remove right double quote .map(|v| v.replace(",", "%2C")) // escape .map(|v| v.replace("}", "%7D")) // escape .map(|v| v.replace(r"\\", r"\")) // unescape .map(|v| v.replace("\\\"", "\"")) // unescape .map(|v| v.replace(r"\n", "%0A")) // unescape .fold(String::new(), |acc, x| { // skip invalid values if !x.contains('=') { return acc } acc + &x + "," }); labels.pop(); labels } else { String::new() }; let class = format!("{}{{{}}}", class, slabels); Ok(format!("{}// {} {}", timestamp, class, value)) } #[cfg(test)] mod tests { use super::*; #[test] fn prometheus_skip_infinity() { let line = "f{job_id=\"123\"} +Inf"; let expected: Result<String, Box<Error>> = Ok(String::new()); let result = super::format_prometheus(line, 1); assert_eq!(expected.is_ok(), result.is_ok()); assert_eq!(expected.unwrap(), result.unwrap()); let line = "f{job_id=\"123\"} -Inf"; let expected: Result<String, Box<Error>> = Ok(String::new()); let result = super::format_prometheus(line, 1); assert_eq!(expected.is_ok(), result.is_ok()); assert_eq!(expected.unwrap(), result.unwrap()); } } <file_sep>/Cargo.toml [package] name = "beamium" version = "1.9.3" authors = [ "d33d33 <<EMAIL>>" ] build = "build.rs" [dependencies] backoff = "0.1.2" bytes = "0.4" clap = "2.29.0" humantime="1.1.1" yaml-rust = "0.4.0" cast = "0.2.2" nix = "0.7.0" time = "0.1.35" hyper = "0.11.25" hyper-tls = "0.1.2" hyper-timeout = "0.1" futures = "0.1" tokio-core = "0.1" regex = "0.2.5" slog-async = "2.2.0" slog-term = "2.3.0" slog-stream = "1.2.0" slog-scope = "4.0.1" slog-syslog = "0.11.0" flate2 = "1.0.1" ctrlc = "3.0" tokio-timer="0.2.6" [dependencies.slog] version = "2.1" features = ["release_max_level_debug", "max_level_debug"] <file_sep>/src/scraper.rs //! # Scraper module. //! //! The Scraper module fetch metrics from an HTTP endpoint. use futures::future::Future; use futures::Stream; use hyper; use hyper_timeout::TimeoutConnector; use hyper_tls::HttpsConnector; use std::cmp; use std::error::Error; use std::fs; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; use std::time::Duration; use time; use config; use lib; /// Thread sleeping time. const REST_TIME: u64 = 10; /// Scraper loop. pub fn scraper( scraper: &config::Scraper, parameters: &config::Parameters, sigint: &Arc<AtomicBool>, ) { let labels: String = scraper.labels.iter().fold(String::new(), |acc, (k, v)| { let sep = if acc.is_empty() { "" } else { "," }; acc + sep + k + "=" + v }); loop { let start = time::now_utc(); match fetch(scraper, &labels, parameters) { Err(err) => error!("fetch fail: {}", err), Ok(_) => info!("fetch success"), } let elapsed = (time::now_utc() - start).num_milliseconds() as u64; let sleep_time = if elapsed > scraper.period { REST_TIME } else { cmp::max(scraper.period - elapsed, REST_TIME) }; for _ in 0..sleep_time / REST_TIME { thread::sleep(Duration::from_millis(REST_TIME)); if sigint.load(Ordering::Relaxed) { return; } } } } /// Fetch retrieve metrics. fn fetch( scraper: &config::Scraper, labels: &str, parameters: &config::Parameters, ) -> Result<(), Box<Error>> { debug!("fetch {}", &scraper.url); // Fetch metrics let mut core = ::tokio_core::reactor::Core::new()?; let handle = core.handle(); let connector = HttpsConnector::new(4, &handle)?; let mut tm = TimeoutConnector::new(connector, &handle); tm.set_connect_timeout(Some(Duration::from_secs(parameters.timeout))); tm.set_read_timeout(Some(Duration::from_secs(parameters.timeout))); tm.set_write_timeout(Some(Duration::from_secs(parameters.timeout))); let client = hyper::Client::configure().connector(tm).build(&handle); let mut req = hyper::Request::new(hyper::Method::Get, scraper.url.clone()); for (key, value) in &scraper.headers { req.headers_mut() .set_raw(key.clone(), vec![value.clone().into_bytes()]); } let get = client .request(req) .and_then(|res| { if res.status().is_success() { Ok(res) } else { Err(hyper::error::Error::from(io::Error::new( io::ErrorKind::Other, format!("{}", res.status()), ))) } }) .and_then(|res| res.body().concat2()); let got = core.run(get)?; // Read body let body = String::from_utf8_lossy(&got); trace!("data {}", &body); // Get now as millis let start = time::now_utc(); let now = start.to_timespec().sec * 1000 * 1000 + (i64::from(start.to_timespec().nsec) / 1000); let dir = Path::new(&parameters.source_dir); let temp_file = dir.join(format!("{}.tmp", scraper.name)); let mut batch_size = 0; let mut batch_count = 0; debug!("write to tmp file {}", format!("{:?}", temp_file)); { // Open tmp file let mut file = File::create(&temp_file)?; let ts = lib::transcompiler::Transcompiler::new(&scraper.format); for line in body.lines() { let line = match ts.format(line) { Ok(v) => v, Err(_) => { warn!("fail to format line {}", &line); continue; } }; if line.is_empty() { continue; } let line = match lib::add_labels(&line, labels) { Ok(v) => v, Err(_) => { warn!("fail to add label on {}", &line); continue; } }; if scraper.metrics.is_some() && !scraper.metrics.as_ref().unwrap().is_match(&line) { continue; } batch_size += line.len(); if batch_size > parameters.batch_size as usize && !line.starts_with('=') { // Rotate scraped file file.flush()?; let dest_file = dir.join(format!("{}-{}-{}.metrics", scraper.name, now, batch_count)); debug!("rotate tmp file to {}", format!("{:?}", dest_file)); fs::rename(&temp_file, &dest_file)?; file = File::create(&temp_file)?; batch_size = 0; batch_count += 1; } file.write_all(line.as_bytes())?; file.write_all(b"\n")?; } file.flush()?; } // Rotate scraped file let dest_file = dir.join(format!("{}-{}-{}.metrics", scraper.name, now, batch_count)); debug!("rotate tmp file to {}", format!("{:?}", dest_file)); fs::rename(&temp_file, &dest_file)?; Ok(()) } <file_sep>/Dockerfile FROM debian:jessie ENV DEBIAN_FRONTEND=noninteractive ARG METRICS_APT_URL=http://last.public.ovh.metrics.snap.mirrors.ovh.net RUN apt-get update \ && apt-get install -y --no-install-recommends \ gnupg \ && echo "deb $METRICS_APT_URL/debian jessie main" >> /etc/apt/sources.list.d/metrics.list \ && apt-key adv \ --keyserver $METRICS_APT_URL/pub.key \ --recv-keys <KEY> \ && apt-get update \ && apt-get install -y --no-install-recommends \ libssl-dev \ beamium \ ca-certificates \ && rm -rf /var/lib/apt/lists/* CMD ["beamium"] <file_sep>/src/config.rs //! # Config module. //! //! The Config module provides the beamium configuration. //! It set defaults and then load config from '/etc', local dir and provided path. use cast; use humantime::parse_duration; use hyper; use regex; use slog; use std::collections::HashMap; use std::error; use std::error::Error; use std::fmt; use std::fs::File; use std::io; use std::io::Read; use std::path::Path; use std::string::String; use std::time::Duration; use yaml_rust::{ScanError, YamlLoader}; pub const REST_TIME: u64 = 10; pub const BACKOFF_WARN: Duration = Duration::from_millis(1000); pub const CHUNK_SIZE: usize = 1024 * 1024; #[derive(Debug, Clone)] /// Config root. pub struct Config { pub scrapers: Vec<Scraper>, pub sinks: Vec<Sink>, pub labels: HashMap<String, String>, pub parameters: Parameters, } #[derive(Debug, Clone)] /// Scraper config. pub struct Scraper { pub name: String, pub url: hyper::Uri, pub period: u64, pub format: ScraperFormat, pub metrics: Option<regex::RegexSet>, pub headers: HashMap<String, String>, pub labels: HashMap<String, String>, } #[derive(Debug, Clone)] /// Scraper format. pub enum ScraperFormat { Prometheus, Sensision, } #[derive(Debug, Clone)] /// Sink config. pub struct Sink { pub name: String, pub url: hyper::Uri, pub token: String, pub token_header: String, pub selector: Option<regex::Regex>, pub ttl: u64, pub size: u64, pub parallel: u64, pub keep_alive: bool, } #[derive(Debug, Clone)] /// Parameters config. pub struct Parameters { pub scan_period: u64, pub sink_dir: String, pub source_dir: String, pub batch_size: u64, pub batch_count: u64, pub log_file: String, pub log_level: slog::Level, pub syslog: bool, pub timeout: u64, pub router_parallel: u64, pub backoff: Backoff, } #[derive(Debug, Clone)] /// Backoff config. pub struct Backoff { pub initial: Duration, pub max: Duration, pub multiplier: f64, pub randomization: f64, } #[derive(Debug)] /// Config Error. pub enum ConfigError { Io(io::Error), Yaml(ScanError), Regex(regex::Error), Format(Box<Error>), Uri(hyper::error::UriError), } impl From<io::Error> for ConfigError { fn from(err: io::Error) -> ConfigError { ConfigError::Io(err) } } impl From<ScanError> for ConfigError { fn from(err: ScanError) -> ConfigError { ConfigError::Yaml(err) } } impl From<regex::Error> for ConfigError { fn from(err: regex::Error) -> ConfigError { ConfigError::Regex(err) } } impl From<Box<Error>> for ConfigError { fn from(err: Box<Error>) -> ConfigError { ConfigError::Format(err) } } impl<'a> From<&'a str> for ConfigError { fn from(err: &str) -> ConfigError { ConfigError::Format(From::from(err)) } } impl From<String> for ConfigError { fn from(err: String) -> ConfigError { ConfigError::Format(From::from(err)) } } impl From<hyper::error::UriError> for ConfigError { fn from(err: hyper::error::UriError) -> ConfigError { ConfigError::Uri(err) } } impl fmt::Display for ConfigError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ConfigError::Io(ref err) => err.fmt(f), ConfigError::Yaml(ref err) => err.fmt(f), ConfigError::Regex(ref err) => err.fmt(f), ConfigError::Format(ref err) => err.fmt(f), ConfigError::Uri(ref err) => err.fmt(f), } } } impl error::Error for ConfigError { fn description(&self) -> &str { match *self { ConfigError::Io(ref err) => err.description(), ConfigError::Yaml(ref err) => err.description(), ConfigError::Regex(ref err) => err.description(), ConfigError::Format(ref err) => err.description(), ConfigError::Uri(ref err) => err.description(), } } fn cause(&self) -> Option<&error::Error> { match *self { ConfigError::Io(ref err) => Some(err), ConfigError::Yaml(ref err) => Some(err), ConfigError::Regex(ref err) => Some(err), ConfigError::Format(ref err) => Some(err.as_ref()), ConfigError::Uri(ref err) => Some(err), } } } /// Load config. /// /// Setup a defaults config and then load config from '/etc', local dir and provided path. /// Return Err if provided path is not found or if config is unprocessable. pub fn load_config(config_path: &str) -> Result<Config, ConfigError> { // Defaults let mut config = Config { scrapers: Vec::new(), labels: HashMap::new(), sinks: Vec::new(), parameters: Parameters { scan_period: 1000, sink_dir: String::from("sinks"), source_dir: String::from("sources"), batch_size: 200_000, batch_count: 250, log_file: String::from(env!("CARGO_PKG_NAME")) + ".log", log_level: slog::Level::Info, syslog: false, timeout: 300, router_parallel: 1, backoff: Backoff { initial: Duration::from_millis(500), max: Duration::from_millis(60_000), multiplier: 1.5, randomization: 0.3, }, }, }; if config_path.is_empty() { // Load from etc if Path::new("/etc/beamium/config.yaml").exists() { load_path("/etc/beamium/config.yaml", &mut config)?; } else if Path::new("config.yaml").exists() { // Load local load_path("config.yaml", &mut config)?; } } else { // Load from provided path load_path(config_path, &mut config)?; } Ok(config) } /// Extend config from file. #[allow(unknown_lints, cyclomatic_complexity)] fn load_path<P: AsRef<Path>>(file_path: P, config: &mut Config) -> Result<(), ConfigError> { let mut file = File::open(file_path)?; let mut contents = String::new(); file.read_to_string(&mut contents)?; let docs = YamlLoader::load_from_str(&contents)?; let config_scraper_keys = ["sources", "scrapers"]; for doc in &docs { for config_scraper_key in &config_scraper_keys { let key = *config_scraper_key; if !doc[key].is_badvalue() { if "sources" == key { warn!( "'sources' is deprecated and will be removed in further revision. \ Please use 'scrapers' instead.", ) } let scrapers = doc[key] .as_hash() .ok_or_else(|| format!("{} should be a map", key))?; for (k, v) in scrapers { let name = k .as_str() .ok_or_else(|| format!("{} keys should be a string", key))?; let url = v["url"].as_str().ok_or_else(|| { format!("{}.{}.url is required and should be a string", key, name) })?; let url = url.parse::<hyper::Uri>()?; let period = v["period"].as_i64().ok_or_else(|| { format!("{}.{}.period is required and should be a number", key, name) })?; let period = cast::u64(period) .map_err(|_| format!("scrapers.{}.period is invalid", name))?; let format = if v["format"].is_badvalue() { ScraperFormat::Prometheus } else { let f = v["format"] .as_str() .ok_or_else(|| format!("scrapers.{}.format should be a string", name))?; if f == "prometheus" { ScraperFormat::Prometheus } else if f == "sensision" { ScraperFormat::Sensision } else { return Err(format!( "scrapers.{}.format should be 'prometheus' or \ 'sensision'", name ).into()); } }; let metrics = if v["metrics"].is_badvalue() { None } else { let mut metrics = Vec::new(); let values = v["metrics"].as_vec().ok_or_else(|| { format!("scrapers.{}.metrics should be an array", name) })?; for v in values { let value = regex::Regex::new(v.as_str().ok_or_else(|| { format!("scrapers.{}.metrics is invalid", name) })?)?; metrics.push(String::from(r"^(\S*)\s") + value.as_str()); } Some(regex::RegexSet::new(&metrics)?) }; // let headers = HashMap::new(); let headers = if v["headers"].is_badvalue() { HashMap::new() } else { let heads = v["headers"] .as_hash() .ok_or_else(|| format!("scrapers.{}.headers should be a map", name))?; let mut ret = HashMap::new(); for (k, v) in heads { let hname = k.as_str().ok_or_else(|| { format!("scrapers.{}.headers keys should be a string", name) })?; let value = v.as_str().ok_or_else(|| { format!( "scrapers.{}.headers.{} value should be a string", hname, name ) })?; ret.insert(String::from(hname), String::from(value)); } ret }; let mut labels = HashMap::new(); if !v["labels"].is_badvalue() { let slabels = v["labels"] .as_hash() .ok_or_else(|| "labels should be a map")?; for (k, v) in slabels { let lname = k.as_str().ok_or_else(|| { format!("scrapers.{}.labels keys should be a string", name) })?; let value = v.as_str().ok_or_else(|| { format!( "scrapers.{}.labels.{} value should be a string", name, lname ) })?; labels.insert(String::from(lname), String::from(value)); } } config.scrapers.push(Scraper { name: String::from(name), url, period, format, metrics, headers, labels, }) } } } if !doc["sinks"].is_badvalue() { let sinks = doc["sinks"] .as_hash() .ok_or_else(|| "sinks should be a map")?; for (k, v) in sinks { let name = k.as_str().ok_or_else(|| "sinks keys should be a string")?; let url = v["url"].as_str().ok_or_else(|| { format!("sinks.{}.url is required and should be a string", name) })?; let url = url.parse::<hyper::Uri>()?; let token = v["token"].as_str().ok_or_else(|| { format!("sinks.{}.token is required and should be a string", name) })?; let token_header = if v["token-header"].is_badvalue() { "X-Warp10-Token" } else { v["token-header"] .as_str() .ok_or_else(|| format!("sinks.{}.token-header should be a string", name))? }; let selector = if v["selector"].is_badvalue() { None } else { Some(regex::Regex::new( format!( "^{}", v["selector"].as_str().ok_or_else(|| format!( "sinks.{}.selector \ is invalid", name ))? ).as_str(), )?) }; let ttl = if v["ttl"].is_badvalue() { 3600 } else { let ttl = v["ttl"] .as_i64() .ok_or_else(|| format!("sinks.{}.ttl should be a number", name))?; cast::u64(ttl) .map_err(|_| format!("sinks.{}.ttl should be a positive number", name))? }; let size = if v["size"].is_badvalue() { 1_073_741_824 } else { let size = v["size"] .as_i64() .ok_or_else(|| format!("sinks.{}.size should be a number", name))?; cast::u64(size) .map_err(|_| format!("sinks.{}.size should be a positive number", name))? }; let parallel = if v["parallel"].is_badvalue() { 1 } else { let parallel = v["parallel"] .as_i64() .ok_or_else(|| format!("sinks.{}.parallel should be a number", name))?; cast::u64(parallel).map_err(|_| { format!("sinks.{}.parallel should be a positive number", name) })? }; let keep_alive = if v["keep-alive"].is_badvalue() { true } else { v["keep-alive"] .as_bool() .ok_or_else(|| format!("sinks.{}.keep-alive should be a boolean", name))? }; config.sinks.push(Sink { name: String::from(name), url, token: String::from(token), token_header: String::from(token_header), selector, ttl, size, parallel, keep_alive, }) } } if !doc["labels"].is_badvalue() { let labels = doc["labels"] .as_hash() .ok_or_else(|| "labels should be a map")?; for (k, v) in labels { let name = k.as_str().ok_or_else(|| "labels keys should be a string")?; let value = v .as_str() .ok_or_else(|| format!("labels.{} value should be a string", name))?; config .labels .insert(String::from(name), String::from(value)); } } if !doc["parameters"].is_badvalue() { if !doc["parameters"]["source-dir"].is_badvalue() { let source_dir = doc["parameters"]["source-dir"] .as_str() .ok_or_else(|| "parameters.source-dir should be a string".to_string())?; config.parameters.source_dir = String::from(source_dir); } if !doc["parameters"]["sink-dir"].is_badvalue() { let sink_dir = doc["parameters"]["sink-dir"] .as_str() .ok_or_else(|| "parameters.sink-dir should be a string".to_string())?; config.parameters.sink_dir = String::from(sink_dir); } if !doc["parameters"]["scan-period"].is_badvalue() { let scan_period = doc["parameters"]["scan-period"] .as_i64() .ok_or_else(|| "parameters.scan-period should be a number".to_string())?; let scan_period = cast::u64(scan_period) .map_err(|_| "parameters.scan-period is invalid".to_string())?; config.parameters.scan_period = scan_period; } if !doc["parameters"]["batch-size"].is_badvalue() { let batch_size = doc["parameters"]["batch-size"] .as_i64() .ok_or_else(|| "parameters.batch-size should be a number".to_string())?; let batch_size = cast::u64(batch_size) .map_err(|_| "parameters.batch-size is invalid".to_string())?; config.parameters.batch_size = batch_size; } if !doc["parameters"]["batch-count"].is_badvalue() { let batch_count = doc["parameters"]["batch-count"] .as_i64() .ok_or_else(|| "parameters.batch-count should be a number".to_string())?; let batch_count = cast::u64(batch_count) .map_err(|_| "parameters.batch-count is invalid".to_string())?; config.parameters.batch_count = batch_count; } if !doc["parameters"]["log-file"].is_badvalue() { let log_file = doc["parameters"]["log-file"] .as_str() .ok_or_else(|| "parameters.log-file should be a string".to_string())?; config.parameters.log_file = String::from(log_file); } if !doc["parameters"]["log-level"].is_badvalue() { let log_level = doc["parameters"]["log-level"] .as_i64() .ok_or_else(|| "parameters.log-level should be a number".to_string())?; let log_level = cast::u64(log_level) .map_err(|_| "parameters.log-level is invalid".to_string())?; let log_level = slog::Level::from_usize(log_level as usize) .ok_or_else(|| "parameters.log-level is invalid".to_string())?; config.parameters.log_level = log_level; } if !doc["parameters"]["syslog"].is_badvalue() { let syslog = doc["parameters"]["syslog"] .as_bool() .ok_or_else(|| "parameters.bool should be a boolean")?; config.parameters.syslog = syslog; } if !doc["parameters"]["timeout"].is_badvalue() { let timeout = doc["parameters"]["timeout"] .as_i64() .ok_or_else(|| "parameters.timeout should be a number")?; let timeout = cast::u64(timeout).map_err(|_| "parameters.timeout is invalid".to_string())?; config.parameters.timeout = timeout; } if !doc["parameters"]["router-parallel"].is_badvalue() { let router_parallel = doc["parameters"]["router-parallel"] .as_i64() .ok_or_else(|| "parameters.router-parallel should be a number")?; let router_parallel = cast::u64(router_parallel) .map_err(|_| "parameters.router-parallel is invalid".to_string())?; config.parameters.router_parallel = router_parallel; } if !doc["parameters"]["backoff"].is_badvalue() { if !doc["parameters"]["backoff"]["initial"].is_badvalue() { let v = &doc["parameters"]["backoff"]["initial"]; let initial = v .as_i64() .and_then(|initial| cast::u64(initial).ok()) .map(|initial| Duration::from_millis(initial)) .or_else(|| v.as_str().and_then(|initial| parse_duration(initial).ok())) .ok_or_else(|| { "parameters.backoff.initial should be a duration string".to_string() })?; config.parameters.backoff.initial = initial; } if !doc["parameters"]["backoff"]["max"].is_badvalue() { let v = &doc["parameters"]["backoff"]["max"]; let max = v .as_i64() .and_then(|max| cast::u64(max).ok()) .map(|max| Duration::from_millis(max)) .or_else(|| v.as_str().and_then(|max| parse_duration(max).ok())) .ok_or_else(|| { "parameters.backoff.max should be a duration string".to_string() })?; config.parameters.backoff.max = max; } if !doc["parameters"]["backoff"]["multiplier"].is_badvalue() { let v = &doc["parameters"]["backoff"]["multiplier"]; let multiplier = v.as_f64().ok_or_else(|| { "parameters.backoff.multiplier should be a number".to_string() })?; if multiplier < 0.0 { return Err(ConfigError::from( "parameters.backoff.multiplier is negative", )); } config.parameters.backoff.multiplier = multiplier; } if !doc["parameters"]["backoff"]["randomization"].is_badvalue() { let v = &doc["parameters"]["backoff"]["randomization"]; let randomization = v.as_f64().ok_or_else(|| { "parameters.backoff.randomization should be a number".to_string() })?; if randomization < 0.0 || randomization > 1.0 { return Err(ConfigError::from( "parameters.backoff.randomization should in [0-1]", )); } config.parameters.backoff.randomization = randomization; } } } } Ok(()) }
03ec7f90c44f91c38ed3aca792522035cb9c0b97
[ "TOML", "Rust", "Dockerfile" ]
6
Rust
tduboys/beamium
5bbb18471bde8a5182a5ace73bf8510ff1ffe6ad
0e17f1fbec010703c12fdb72dd7fe7db87b0333d
refs/heads/master
<repo_name>dbdoyle182/CodeVents<file_sep>/src/features/user/UserDetailed/UserDetailedPage.jsx import React, {Component} from 'react'; import {Button, Card, Grid, Header, Icon, Image, Item, List, Menu, Segment} from "semantic-ui-react"; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { firestoreConnect } from 'react-redux-firebase'; import { compose } from 'redux'; import { differenceInYears, format } from 'date-fns'; const query = ({auth}) => { return [ { collection: 'users', doc: auth.uid, subcollections: [{collection: 'photos'}], storeAs: 'photos' } ] } const mapState = (state) => ({ auth: state.firebase.auth, profile: state.firebase.profile, photos: state.firestore.ordered.photos }) class UserDetailedPage extends Component { render() { const { auth, profile, photos } = this.props let age; let profileCreated; if ( profile.dateOfBirth) { age = differenceInYears(Date.now(), profile.dateOfBirth.toDate()) } else { age = 'unknown age' } if (profile.createdAt) { profileCreated = format(profile.createdAt.toDate(), 'MMM DD, YYYY') } else { profileCreated = "Unknown" } return ( <Grid> <Grid.Column width={16}> <Segment> <Item.Group> <Item> <Item.Image avatar size='small' src={auth.photoURL || '/assets/user.png'}/> <Item.Content verticalAlign='bottom'> <Header as='h1'>{auth.displayName}</Header> <br/> <Header as='h3'>{profile.occupation || "unknown"}</Header> <br/> <Header as='h3'>{age}, Lives in {profile.city || "Unknown"}</Header> </Item.Content> </Item> </Item.Group> </Segment> </Grid.Column> <Grid.Column width={12}> <Segment> <Grid columns={2}> <Grid.Column width={10}> <Header icon='smile' content='About <NAME>'/> <p>I am a: <strong>{profile.occupation || "Unknown"}</strong></p> <p>Originally from <strong>{profile.city || "Unknown"}</strong></p> <p>Member Since: <strong>{profileCreated}</strong></p> <p>{profile.about || "There is no user biography yet"}</p> </Grid.Column> <Grid.Column width={6}> <Header icon='heart outline' content='Interests'/> <List> {profile.interests ? profile.interests.map((interest, iterator) => ( <Item key={iterator}> <Icon name='heart'/> <Item.Content>{interest}</Item.Content> </Item> )) : <p>The user has no selected interests</p> } </List> </Grid.Column> </Grid> </Segment> </Grid.Column> <Grid.Column width={4}> <Segment> <Button as={Link} to='/settings' color='teal' fluid basic content='Edit Profile'/> </Segment> </Grid.Column> <Grid.Column width={12}> <Segment attached> <Header icon='image' content='Photos'/> <Image.Group size='small'> {photos && photos.length > 0 ? photos.map(photo => ( <Image src={photo.url} alt={photo.name} key={photo.id}/> )) : <p>You currently have no photos! Add one <a as={Link} to='/settings/photos'>here</a></p> } </Image.Group> </Segment> </Grid.Column> <Grid.Column width={12}> <Segment attached> <Header icon='calendar' content='Events'/> <Menu secondary pointing> <Menu.Item name='All Events' active/> <Menu.Item name='Past Events'/> <Menu.Item name='Future Events'/> <Menu.Item name='Events Hosted'/> </Menu> <Card.Group itemsPerRow={5}> <Card> <Image src={'/assets/categoryImages/drinks.jpg'}/> <Card.Content> <Card.Header textAlign='center'> Event Title </Card.Header> <Card.Meta textAlign='center'> 28th March 2018 at 10:00 PM </Card.Meta> </Card.Content> </Card> <Card> <Image src={'/assets/categoryImages/drinks.jpg'}/> <Card.Content> <Card.Header textAlign='center'> Event Title </Card.Header> <Card.Meta textAlign='center'> 28th March 2018 at 10:00 PM </Card.Meta> </Card.Content> </Card> </Card.Group> </Segment> </Grid.Column> </Grid> ); } } export default compose( connect(mapState, null), firestoreConnect(auth => query(auth)) )(UserDetailedPage);
17deb588bbf31d6d0186c72c7655e3fecd9d722b
[ "JavaScript" ]
1
JavaScript
dbdoyle182/CodeVents
dd63cd5b9310fafe2ae0ab9acbbf7734ab4515fc
233cd5632283b11c91570986e7328d70988ef1e7
refs/heads/master
<file_sep>/* * Copyright (C) 2016, 2017 Computer Graphics Group, University of Siegen * Written by <NAME> <<EMAIL>> * * 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. */ #include <QDataStream> #include "event.hpp" QVREvent::QVREvent() : type(QVR_Event_KeyPress), context(), keyEvent(QEvent::None, 0, Qt::NoModifier), mouseEvent(QEvent::None, QPointF(), Qt::NoButton, Qt::NoButton, Qt::NoModifier), wheelEvent(QPointF(), QPointF(), QPoint(), QPoint(), 0, Qt::Horizontal, Qt::NoButton, Qt::NoModifier), deviceEvent(QVRDevice(), -1, -1) {} QVREvent::QVREvent(QVREventType t, const QVRRenderContext& c, const QKeyEvent& e) : type(t), context(c), keyEvent(e), mouseEvent(QEvent::None, QPointF(), Qt::NoButton, Qt::NoButton, Qt::NoModifier), wheelEvent(QPointF(), QPointF(), QPoint(), QPoint(), 0, Qt::Horizontal, Qt::NoButton, Qt::NoModifier), deviceEvent(QVRDevice(), -1, -1) {} QVREvent::QVREvent(QVREventType t, const QVRRenderContext& c, const QMouseEvent& e) : type(t), context(c), keyEvent(QEvent::None, 0, Qt::NoModifier), mouseEvent(e), wheelEvent(QPointF(), QPointF(), QPoint(), QPoint(), 0, Qt::Horizontal, Qt::NoButton, Qt::NoModifier), deviceEvent(QVRDevice(), -1, -1) {} QVREvent::QVREvent(QVREventType t, const QVRRenderContext& c, const QWheelEvent& e) : type(t), context(c), keyEvent(QEvent::None, 0, Qt::NoModifier), mouseEvent(QEvent::None, QPointF(), Qt::NoButton, Qt::NoButton, Qt::NoModifier), wheelEvent(e), deviceEvent(QVRDevice(), -1, -1) {} QVREvent::QVREvent(QVREventType t, const QVRDeviceEvent& e) : type(t), context(), keyEvent(QEvent::None, 0, Qt::NoModifier), mouseEvent(QEvent::None, QPointF(), Qt::NoButton, Qt::NoButton, Qt::NoModifier), wheelEvent(QPointF(), QPointF(), QPoint(), QPoint(), 0, Qt::Horizontal, Qt::NoButton, Qt::NoModifier), deviceEvent(e) {} QDataStream &operator<<(QDataStream& ds, const QVREvent& e) { ds << static_cast<int>(e.type); switch (e.type) { case QVR_Event_KeyPress: case QVR_Event_KeyRelease: ds << e.context << static_cast<int>(e.keyEvent.type()) << e.keyEvent.key() << static_cast<int>(e.keyEvent.modifiers()); break; case QVR_Event_MouseMove: case QVR_Event_MousePress: case QVR_Event_MouseRelease: case QVR_Event_MouseDoubleClick: ds << e.context << static_cast<int>(e.mouseEvent.type()) << e.mouseEvent.localPos() << static_cast<int>(e.mouseEvent.button()) << static_cast<int>(e.mouseEvent.buttons()) << static_cast<int>(e.mouseEvent.modifiers()); break; case QVR_Event_Wheel: ds << e.context << e.wheelEvent.posF() << e.wheelEvent.globalPosF() << e.wheelEvent.pixelDelta() << e.wheelEvent.angleDelta() << static_cast<int>(e.wheelEvent.buttons()) << static_cast<int>(e.wheelEvent.modifiers()); break; case QVR_Event_DeviceButtonPress: case QVR_Event_DeviceButtonRelease: case QVR_Event_DeviceAnalogChange: ds << e.deviceEvent.device() << e.deviceEvent.buttonIndex() << e.deviceEvent.analogIndex(); } return ds; } QDataStream &operator>>(QDataStream& ds, QVREvent& e) { int type; ds >> type; e.type = static_cast<QVREventType>(type); int ke[3]; int me[4]; QPointF mepf; QPointF wepf[2]; QPoint wep[2]; int we[2]; QVRDevice d; int de[2]; switch (e.type) { case QVR_Event_KeyPress: case QVR_Event_KeyRelease: ds >> e.context >> ke[0] >> ke[1] >> ke[2]; e.keyEvent = QKeyEvent(static_cast<QEvent::Type>(ke[0]), ke[1], static_cast<Qt::KeyboardModifier>(ke[2])); break; case QVR_Event_MouseMove: case QVR_Event_MousePress: case QVR_Event_MouseRelease: case QVR_Event_MouseDoubleClick: ds >> e.context >> me[0] >> mepf >> me[1] >> me[2] >> me[3]; e.mouseEvent = QMouseEvent(static_cast<QEvent::Type>(me[0]), mepf, static_cast<Qt::MouseButton>(me[1]), static_cast<Qt::MouseButtons>(me[2]), static_cast<Qt::KeyboardModifier>(me[3])); break; case QVR_Event_Wheel: ds >> e.context >> wepf[0] >> wepf[1] >> wep[0] >> wep[1] >> we[0] >> we[1]; e.wheelEvent = QWheelEvent(wepf[0], wepf[1], wep[0], wep[1], 0, Qt::Horizontal, static_cast<Qt::MouseButtons>(we[0]), static_cast<Qt::KeyboardModifier>(we[1])); break; case QVR_Event_DeviceButtonPress: case QVR_Event_DeviceButtonRelease: case QVR_Event_DeviceAnalogChange: ds >> d >> de[0] >> de[1]; e.deviceEvent = QVRDeviceEvent(d, de[0], de[1]); break; } return ds; } <file_sep>file(REMOVE_RECURSE "qvr-example-opengl_autogen" "CMakeFiles/qvr-example-opengl_autogen.dir/AutogenOldSettings.txt" "CMakeFiles/qvr-example-opengl_autogen" "qvr-example-opengl_autogen/mocs_compilation.cpp" ) # Per-language clean rules from dependency scanning. foreach(lang ) include(CMakeFiles/qvr-example-opengl_autogen.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>#include <bvec.hpp> #include <maze.h> #define DRAW_AABB true #define MAZE_SCALE 0.1f Maze::Maze(unsigned short width, unsigned short height) : Drawable("Maze"), _width(width), _height(height) { initMaze(); Drawable::loadShader( ":vertex-shader.glsl" , ":fragment-shader.glsl" ); Drawable::setMaterial( Material(0.5f, 0.5f, 0.5f, 1.0f, 0.2f, 0.1f, loadTexture(":floor-diff.jpg") , getGLES() ? 0 : loadTexture(":floor-norm.jpg"), 0, 10.0f ) ); } void Maze::initMaze() { std::cout << "initialise maze " << _width << "×" << _height << std::endl; _maze.assign(static_cast<unsigned short> (_width * _height + 1), false); generate(); generateGeometry(); printMaze(); generateAabb(); } void Maze::addRandomLoop() { unsigned short xa = static_cast<unsigned short> (rand()) % (_width / 2); unsigned short xb = static_cast<unsigned short> (rand()) % (_width - xa) + xa; unsigned short ya = static_cast<unsigned short> (rand()) % (_height / 2); unsigned short yb = static_cast<unsigned short> (rand()) % (_height - ya) + ya; for (unsigned short x = xa; x <= xb; x++) { mazeBlockAt(x, ya) = true; mazeBlockAt(x, yb) = true; } for (unsigned short y = ya; y <= yb; y++) { mazeBlockAt(xa, y) = true; mazeBlockAt(xb, y) = true; } } void Maze::printMaze() { for (unsigned short x = 0; x < _width; x++) { for (unsigned short y = 0; y < _height; y++) std::cout << (mazeBlockAt(x, y) ? "##" : " "); std::cout << std::endl; } } void Maze::generate() { int it = (_width + _height) / 6; for (int i = 0; i < it; i++) addRandomLoop(); } void Maze::generateAabb() { // Aabb(QVector3D(xa - 0.5f, -0.5f, ya - 0.5f), QVector3D(xa + 0.5f, 0.5f, yb + 0.5f)); /** horizontal boxes */ for (unsigned short y = 0; y < _height; y++) { std::vector<unsigned short> front; std::vector<unsigned short> back; for (unsigned short x = 0; x < _width; x++) { bool block = mazeBlockAt(x, y); bool fw = mazeBlockAt(x, y + 1); bool bk = mazeBlockAt(x, y - 1); if (!block && fw && front.size() == 0) { front = {x, y}; } if ((block || (!block && !fw)) && front.size() > 0) { addObstacle(std::make_shared<Aabb>( QVector3D(front.at(0) - 0.5f, -0.5f, front.at(1) - 0.5f) , QVector3D((x - 1) + 0.5f, 0.5f, y + 0.5f) , DRAW_AABB )); front.clear(); } if (!block && bk && back.size() == 0) { back = {x, y}; } if ((block || (!block && !bk)) && back.size() > 0) { addObstacle(std::make_shared<Aabb>( QVector3D(back.at(0) - 0.5f, -0.5f, back.at(1) - 0.5f) , QVector3D((x - 1) + 0.5f, 0.5f, y + 0.5f) , DRAW_AABB )); back.clear(); } } } /** vertical boxes */ for (unsigned short x = 0; x < _width; x++) { std::vector<unsigned short> front; std::vector<unsigned short> back; for (unsigned short y = 0; y < _height; y++) { bool block = mazeBlockAt(x, y); bool fw = mazeBlockAt(x + 1, y); bool bk = mazeBlockAt(x - 1, y); if (!block && fw && front.size() == 0) { front = {x, y}; } if ((block || (!block && !fw)) && front.size() > 0) { addObstacle(std::make_shared<Aabb>( QVector3D(front.at(0) - 0.5f, -0.5f, front.at(1) - 0.5f) , QVector3D(x + 0.5f, 0.5f, (y - 1) + 0.5f) , DRAW_AABB)); front.clear(); } if (!block && bk && back.size() == 0) { back = {x, y}; } if ((block || (!block && !bk)) && back.size() > 0) { addObstacle(std::make_shared<Aabb>( QVector3D(back.at(0) - 0.5f, -0.5f, back.at(1) - 0.5f) , QVector3D(x + 0.5f, 0.5f, (y - 1) + 0.5f) , DRAW_AABB)); back.clear(); } } } /** Outer Wall */// TODO: other sides addObstacle(std::make_shared<Aabb>( QVector3D(-1 - 0.5f, -0.5f, 0 - 0.5f) , QVector3D(- 0.5f, 0.5f, _height + 0.5f) , DRAW_AABB)); /** Floor */ addObstacle(std::make_shared<Aabb>( QVector3D(0 - 0.5f, -2.f, 0 - 0.5f) , QVector3D(_width + 0.5f, -0.5f, _height + 0.5f) , DRAW_AABB)); } void Maze::genFace( std::vector<QVector3D> *vertices, std::vector<QVector3D> *normals, std::vector<QVector2D> *texcoords, std::vector<unsigned short> *indices, QMatrix4x4 transform ) { // 1 2 // c(x, y) // 4 3 QVector3D a = (transform * QVector3D(+ 0.5f, - 0.5, - 0.5f)); QVector3D b = (transform * QVector3D(+ 0.5f, - 0.5, + 0.5f)); QVector3D c = (transform * QVector3D(- 0.5f, - 0.5, + 0.5f)); QVector3D d = (transform * QVector3D(- 0.5f, - 0.5, - 0.5f)); QVector2D ta = QVector2D(1.0f, 0.f); QVector2D tb = QVector2D(1.0f, 1.f); QVector2D tc = QVector2D(0.0f, 1.f); QVector2D td = QVector2D(0.0f, 0.f); QVector3D normal = (transform * QVector3D(0.f, 1.f, 0.f)); normal.normalize(); vertices->push_back(a);// 1 vertices->push_back(b);// 2 vertices->push_back(c);// 3 vertices->push_back(d);// 4 normals->push_back(normal); normals->push_back(normal); normals->push_back(normal); normals->push_back(normal); texcoords->push_back(ta); texcoords->push_back(tb); texcoords->push_back(tc); texcoords->push_back(td); unsigned short idx = static_cast<unsigned short> (vertices->size() - 1); indices->push_back(idx - 1); indices->push_back(idx - 2); indices->push_back(idx - 3); indices->push_back(idx - 1); indices->push_back(idx - 3); indices->push_back(idx - 0); } void Maze::generateGeometry() { std::vector<QVector3D> vertices; std::vector<QVector3D> normals; std::vector<QVector2D> texcoords; std::vector<unsigned short> indices; for (unsigned short x = 0; x < _width; x++) for (unsigned short y = 0; y < _height; y++) if (mazeBlockAt(x, y)) { /** Floor **/ QMatrix4x4 t0 = QMatrix4x4(); t0.translate(QVector3D(x, 0, y)); genFace(&vertices, &normals, &texcoords, &indices, t0); /** Walls **/ if (y + 1 > _height || !mazeBlockAt(x, y + 1)) { QMatrix4x4 t = QMatrix4x4(t0); t.rotate(-90.f, QVector3D(1, 0, 0)); genFace(&vertices, &normals, &texcoords, &indices, t); } if (int(y) - 1 < 0 || !mazeBlockAt(x, y - 1)) { QMatrix4x4 t = QMatrix4x4(t0); t.rotate(90.0f, QVector3D(1, 0, 0)); genFace(&vertices, &normals, &texcoords, &indices, t); } if (x + 1 > _width || !mazeBlockAt(x + 1, y)) { QMatrix4x4 t = QMatrix4x4(t0); t.rotate(90.0f, QVector3D(0, 0, 1)); genFace(&vertices, &normals, &texcoords, &indices, t); } if (int(x) - 1 < 0 || !mazeBlockAt(x - 1, y)) { QMatrix4x4 t = QMatrix4x4(t0); t.rotate(-90.0f, QVector3D(0, 0, 1)); genFace(&vertices, &normals, &texcoords, &indices, t); } // { // QMatrix4x4 t = QMatrix4x4(t0); // t.rotate(-180.0f, QVector3D(0, 1, 0)); // genFace(&vertices, &normals, &texcoords, &indices, t); // } } Drawable::initBuffers(&vertices, &normals, &texcoords, &indices); } std::vector<bool>::reference Maze::mazeBlockAt(unsigned short x, unsigned short y) { unsigned short idx = y * _width + x; if (idx < 0 || idx >= _maze.size()) return _maze.at(_maze.size() - 1); return _maze.at(idx); } QVector3D Maze::getRandomPos() const { unsigned int idx = 0; for (;_maze.at(idx) != true; idx = static_cast<unsigned int>(rand()) % _maze.size()) { } QVector3D position = QVector3D(idx % _width, 0, idx / _width); std::cout << "Random position: " << position.x() << ", " << position.y() << ", " << position.x() << std::endl; return position * getModelMatrix(); } QVector3D Maze::collision(QVector3D position, QVector3D _movement, BoundingBox observerBox) { QVector3D shift = QVector3D(_movement.x(), _movement.y(), _movement.z()); std::shared_ptr<Aabb> pos0_aabb = std::make_shared<Aabb>(observerBox.a, observerBox.b); std::shared_ptr<Aabb> pos1_aabb = std::make_shared<Aabb>(observerBox.a + shift, observerBox.b + shift); bool collides = false; std::vector<std::shared_ptr<Aabb>> aabb_collided; // std::cout << "observer box: " // << observerBox.b.x() << ", " // << observerBox.b.y() << ", " // << observerBox.b.z() << std::endl; for (std::shared_ptr<Aabb> box : _aabb_list) { bool overlaps = box->hasOverlap(*pos1_aabb); collides |= overlaps; box->setCollided(overlaps); if (overlaps && box->isObstacle()) aabb_collided.push_back(box); } if (!collides) return position + shift; BVec overlap = BVec(true); for (std::shared_ptr<Aabb> box : aabb_collided) { BVec b = box->getOverlap(*pos0_aabb); overlap &= b; } shift = QVector3D( (overlap.x ? shift.x() : -shift.x()) , (overlap.y ? shift.y() : -shift.y()) , (overlap.z ? shift.z() : -shift.z()) ); return position + shift; } void Maze::addObstacle(std::shared_ptr<Aabb> obstacle) { _aabb_list.push_back(obstacle); addChild(obstacle); } <file_sep># Meta set(AM_MULTI_CONFIG "FALSE") set(AM_PARALLEL "4") set(AM_VERBOSITY "") # Directories set(AM_CMAKE_SOURCE_DIR "/home/andrey/workspace/qvr/libqvr") set(AM_CMAKE_BINARY_DIR "/home/andrey/workspace/qvr/libqvr") set(AM_CMAKE_CURRENT_SOURCE_DIR "/home/andrey/workspace/qvr/libqvr") set(AM_CMAKE_CURRENT_BINARY_DIR "/home/andrey/workspace/qvr/libqvr") set(AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE "") set(AM_BUILD_DIR "/home/andrey/workspace/qvr/libqvr/libqvr_autogen") set(AM_INCLUDE_DIR "/home/andrey/workspace/qvr/libqvr/libqvr_autogen/include") # Files set(AM_SOURCES "/home/andrey/workspace/qvr/libqvr/config.cpp;/home/andrey/workspace/qvr/libqvr/device.cpp;/home/andrey/workspace/qvr/libqvr/event.cpp;/home/andrey/workspace/qvr/libqvr/frustum.cpp;/home/andrey/workspace/qvr/libqvr/internalglobals.cpp;/home/andrey/workspace/qvr/libqvr/ipc.cpp;/home/andrey/workspace/qvr/libqvr/logging.cpp;/home/andrey/workspace/qvr/libqvr/manager.cpp;/home/andrey/workspace/qvr/libqvr/observer.cpp;/home/andrey/workspace/qvr/libqvr/process.cpp;/home/andrey/workspace/qvr/libqvr/rendercontext.cpp;/home/andrey/workspace/qvr/libqvr/window.cpp") set(AM_HEADERS "/home/andrey/workspace/qvr/libqvr/config.hpp;/home/andrey/workspace/qvr/libqvr/device.hpp;/home/andrey/workspace/qvr/libqvr/event.hpp;/home/andrey/workspace/qvr/libqvr/frustum.hpp;/home/andrey/workspace/qvr/libqvr/internalglobals.hpp;/home/andrey/workspace/qvr/libqvr/ipc.hpp;/home/andrey/workspace/qvr/libqvr/logging.hpp;/home/andrey/workspace/qvr/libqvr/manager.hpp;/home/andrey/workspace/qvr/libqvr/observer.hpp;/home/andrey/workspace/qvr/libqvr/process.hpp;/home/andrey/workspace/qvr/libqvr/rendercontext.hpp;/home/andrey/workspace/qvr/libqvr/window.hpp") set(AM_SETTINGS_FILE "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr_autogen.dir/AutogenOldSettings.txt") # Qt set(AM_QT_VERSION_MAJOR 5) set(AM_QT_MOC_EXECUTABLE "/usr/bin/moc") set(AM_QT_UIC_EXECUTABLE "") # MOC settings set(AM_MOC_SKIP "/home/andrey/workspace/qvr/libqvr/qrc_qvr.cpp") set(AM_MOC_DEFINITIONS "QT_CORE_LIB;QT_GUI_LIB;QT_NETWORK_LIB;QT_NO_DEBUG;libqvr_EXPORTS") set(AM_MOC_INCLUDES "/home/andrey/workspace/qvr/libqvr;/usr/include/qt;/usr/include/qt/QtGui;/usr/include/qt/QtCore;/usr/lib/qt/mkspecs/linux-g++;/usr/include/qt/QtNetwork;/usr/include;/usr/include/c++/8.3.0;/usr/include/c++/8.3.0/x86_64-pc-linux-gnu;/usr/include/c++/8.3.0/backward;/usr/lib/gcc/x86_64-pc-linux-gnu/8.3.0/include;/usr/local/include;/usr/lib/gcc/x86_64-pc-linux-gnu/8.3.0/include-fixed") set(AM_MOC_OPTIONS "") set(AM_MOC_RELAXED_MODE "") set(AM_MOC_MACRO_NAMES "Q_OBJECT;Q_GADGET;Q_NAMESPACE") set(AM_MOC_DEPEND_FILTERS "") set(AM_MOC_PREDEFS_CMD "/usr/bin/c++;-dM;-E;-c;/usr/share/cmake-3.14/Modules/CMakeCXXCompilerABI.cpp") <file_sep>#ifndef AABB_H #define AABB_H #include <vector> #include <QOpenGLExtraFunctions> #include <QVector3D> #include <QMatrix4x4> #include <QObject> #include <box.h> #include <bvec.hpp> struct BoundingBox { QVector3D a; QVector3D b; BoundingBox(QVector3D a, QVector3D b): a(a), b(b) {} }; struct BoundAxis { bool bottom; bool top; BoundAxis(bool bottom, bool top): bottom(bottom), top(top) {} }; struct Bound { BoundAxis x; BoundAxis y; BoundAxis z; Bound(BoundAxis x, BoundAxis y, BoundAxis z): x(x), y(y), z(z) {} }; class Aabb : public QObject, public Drawable { Q_OBJECT public: Aabb(QVector3D a = QVector3D(0.f, 0.f, 0.f) , QVector3D b = QVector3D(0.f, 0.f, 0.f) , bool renderable = false , QVector3D color = QVector3D(1.f, 0, 1.f) , QString name = "" , QObject* _parent = nullptr ); BVec virtual getOverlap(Aabb &aabb) const; bool virtual hasOverlap(Aabb &aabb) const; BVec virtual getContain(Aabb &aabb) const; Bound virtual boundsPoint(QVector3D point) const; BoundingBox getBox() const; std::vector<QVector3D> getAB() const; bool isCollided() const; virtual void setCollided(bool collided); QString getName() const; bool isObstacle() const; private: virtual void glRender(QMatrix4x4 &vMarix, QMatrix4x4 &pMatrix); BoundingBox _ab; std::shared_ptr<Box> _box; bool _collided = false; QString _name; signals: void collided(); }; #endif // AABB_H <file_sep>#ifndef MAZE_H #define MAZE_H #include <vector> #include <iostream> #include <QOpenGLShaderProgram> #include <QOpenGLExtraFunctions> #include <QVector3D> #include <QVector4D> #include <QMatrix> #include <drawable.h> #include <aabb.h> #include <box.h> class Maze : public Drawable { public: Maze(unsigned short width = 32, unsigned short height = 32); QVector3D getRandomPos() const; QVector3D collision(QVector3D position, QVector3D movement, BoundingBox observerBox); void addObstacle(std::shared_ptr<Aabb> obstacle); void addButton(std::shared_ptr<Aabb> obstacle); private: std::vector<bool> _maze; unsigned short _width; unsigned short _height; std::vector<std::shared_ptr<Aabb>> _aabb_list; std::vector<std::shared_ptr<Aabb>> _btn_list; void initMaze(); std::vector<bool>::reference mazeBlockAt(unsigned short x, unsigned short y); void addRandomLoop(); void generate(); void generateGeometry(); void genFace( std::vector<QVector3D> *vertices, std::vector<QVector3D> *normals, std::vector<QVector2D> *texcoords, std::vector<unsigned short> *indices, QMatrix4x4 transform ); void generateAabb(); void printMaze(); signals: public slots: }; #endif // MAZE_H <file_sep>#ifndef MATERIAL_H #define MATERIAL_H class Material { public: float r, g, b; float kd, ks, shininess; unsigned int diffTex; unsigned int normTex; unsigned int specTex; float texCoordFactor; Material() {} Material(float r, float g, float b, float kd, float ks, float shininess, unsigned int diffTex = 0, unsigned int normTex = 0, unsigned int specTex = 0, float texCoordFactor = 1.0f) : r(r), g(g), b(b), kd(kd), ks(ks), shininess(shininess), diffTex(diffTex), normTex(normTex), specTex(specTex), texCoordFactor(texCoordFactor) {} }; #endif // MATERIAL_H <file_sep># CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.14 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/bin/cmake # The command to remove a file. RM = /usr/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/andrey/workspace/qvr/qvr-example-opengl # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/andrey/workspace/qvr/qvr-example-opengl #============================================================================= # Targets provided globally by CMake. # Special rule for the target install/strip install/strip: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip # Special rule for the target install/strip install/strip/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." /usr/bin/ccmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target list_install_components list_install_components: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\"" .PHONY : list_install_components # Special rule for the target list_install_components list_install_components/fast: list_install_components .PHONY : list_install_components/fast # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local # Special rule for the target install/local install/local/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local/fast # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install/fast # The main all target all: cmake_check_build_system $(CMAKE_COMMAND) -E cmake_progress_start /home/andrey/workspace/qvr/qvr-example-opengl/CMakeFiles /home/andrey/workspace/qvr/qvr-example-opengl/CMakeFiles/progress.marks $(MAKE) -f CMakeFiles/Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start /home/andrey/workspace/qvr/qvr-example-opengl/CMakeFiles 0 .PHONY : all # The main clean target clean: $(MAKE) -f CMakeFiles/Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named qvr-example-opengl # Build rule for target. qvr-example-opengl: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 qvr-example-opengl .PHONY : qvr-example-opengl # fast build rule for target. qvr-example-opengl/fast: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/build .PHONY : qvr-example-opengl/fast #============================================================================= # Target rules for targets named qvr-example-opengl_autogen # Build rule for target. qvr-example-opengl_autogen: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 qvr-example-opengl_autogen .PHONY : qvr-example-opengl_autogen # fast build rule for target. qvr-example-opengl_autogen/fast: $(MAKE) -f CMakeFiles/qvr-example-opengl_autogen.dir/build.make CMakeFiles/qvr-example-opengl_autogen.dir/build .PHONY : qvr-example-opengl_autogen/fast geometries.o: geometries.cpp.o .PHONY : geometries.o # target to build an object file geometries.cpp.o: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/geometries.cpp.o .PHONY : geometries.cpp.o geometries.i: geometries.cpp.i .PHONY : geometries.i # target to preprocess a source file geometries.cpp.i: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/geometries.cpp.i .PHONY : geometries.cpp.i geometries.s: geometries.cpp.s .PHONY : geometries.s # target to generate assembly for a file geometries.cpp.s: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/geometries.cpp.s .PHONY : geometries.cpp.s qrc_resources.o: qrc_resources.cpp.o .PHONY : qrc_resources.o # target to build an object file qrc_resources.cpp.o: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/qrc_resources.cpp.o .PHONY : qrc_resources.cpp.o qrc_resources.i: qrc_resources.cpp.i .PHONY : qrc_resources.i # target to preprocess a source file qrc_resources.cpp.i: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/qrc_resources.cpp.i .PHONY : qrc_resources.cpp.i qrc_resources.s: qrc_resources.cpp.s .PHONY : qrc_resources.s # target to generate assembly for a file qrc_resources.cpp.s: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/qrc_resources.cpp.s .PHONY : qrc_resources.cpp.s qvr-example-opengl.o: qvr-example-opengl.cpp.o .PHONY : qvr-example-opengl.o # target to build an object file qvr-example-opengl.cpp.o: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/qvr-example-opengl.cpp.o .PHONY : qvr-example-opengl.cpp.o qvr-example-opengl.i: qvr-example-opengl.cpp.i .PHONY : qvr-example-opengl.i # target to preprocess a source file qvr-example-opengl.cpp.i: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/qvr-example-opengl.cpp.i .PHONY : qvr-example-opengl.cpp.i qvr-example-opengl.s: qvr-example-opengl.cpp.s .PHONY : qvr-example-opengl.s # target to generate assembly for a file qvr-example-opengl.cpp.s: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/qvr-example-opengl.cpp.s .PHONY : qvr-example-opengl.cpp.s qvr-example-opengl_autogen/mocs_compilation.o: qvr-example-opengl_autogen/mocs_compilation.cpp.o .PHONY : qvr-example-opengl_autogen/mocs_compilation.o # target to build an object file qvr-example-opengl_autogen/mocs_compilation.cpp.o: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/qvr-example-opengl_autogen/mocs_compilation.cpp.o .PHONY : qvr-example-opengl_autogen/mocs_compilation.cpp.o qvr-example-opengl_autogen/mocs_compilation.i: qvr-example-opengl_autogen/mocs_compilation.cpp.i .PHONY : qvr-example-opengl_autogen/mocs_compilation.i # target to preprocess a source file qvr-example-opengl_autogen/mocs_compilation.cpp.i: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/qvr-example-opengl_autogen/mocs_compilation.cpp.i .PHONY : qvr-example-opengl_autogen/mocs_compilation.cpp.i qvr-example-opengl_autogen/mocs_compilation.s: qvr-example-opengl_autogen/mocs_compilation.cpp.s .PHONY : qvr-example-opengl_autogen/mocs_compilation.s # target to generate assembly for a file qvr-example-opengl_autogen/mocs_compilation.cpp.s: $(MAKE) -f CMakeFiles/qvr-example-opengl.dir/build.make CMakeFiles/qvr-example-opengl.dir/qvr-example-opengl_autogen/mocs_compilation.cpp.s .PHONY : qvr-example-opengl_autogen/mocs_compilation.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... install/strip" @echo "... edit_cache" @echo "... qvr-example-opengl" @echo "... rebuild_cache" @echo "... list_install_components" @echo "... install/local" @echo "... install" @echo "... qvr-example-opengl_autogen" @echo "... geometries.o" @echo "... geometries.i" @echo "... geometries.s" @echo "... qrc_resources.o" @echo "... qrc_resources.i" @echo "... qrc_resources.s" @echo "... qvr-example-opengl.o" @echo "... qvr-example-opengl.i" @echo "... qvr-example-opengl.s" @echo "... qvr-example-opengl_autogen/mocs_compilation.o" @echo "... qvr-example-opengl_autogen/mocs_compilation.i" @echo "... qvr-example-opengl_autogen/mocs_compilation.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep>#ifndef BOX_H #define BOX_H #include <vector> #include "drawable.h" #include <QVector3D> #include <QMatrix4x4> /** * @brief The Box class describes the absolute path a planet follows */ class Box : public Drawable { public: /** * @brief Box constructor * @param name the name of the path */ Box(std::string name = "UNKNOWN BOX", std::vector<QVector3D> box = { QVector3D(0.f, 0.f, 0.f) , QVector3D(0.f, 0.f, 0.f) } , QVector3D color = QVector3D(1.f, 1.f, 1.f)); virtual void glRender(QMatrix4x4 &vMatrix, QMatrix4x4 &pMatrix) override; void setLines(bool lines); private: virtual void initBuffers(); std::vector<QVector3D> _box; QVector3D _color; bool _drawLines = true; GLsizei _vertexCount; }; #endif // BOX_H <file_sep>file(REMOVE_RECURSE "flying-things_autogen" "CMakeFiles/flying-things_autogen.dir/AutogenOldSettings.txt" "qrc_resources.cpp" "CMakeFiles/flying-things.dir/flying-things_autogen/mocs_compilation.cpp.o" "CMakeFiles/flying-things.dir/flying-things.cpp.o" "CMakeFiles/flying-things.dir/geometries.cpp.o" "CMakeFiles/flying-things.dir/qrc_resources.cpp.o" "flying-things.pdb" "flying-things" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/flying-things.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>file(REMOVE_RECURSE "libqvr_autogen" "CMakeFiles/libqvr_autogen.dir/AutogenOldSettings.txt" "qrc_qvr.cpp" "CMakeFiles/libqvr.dir/libqvr_autogen/mocs_compilation.cpp.o" "CMakeFiles/libqvr.dir/manager.cpp.o" "CMakeFiles/libqvr.dir/config.cpp.o" "CMakeFiles/libqvr.dir/device.cpp.o" "CMakeFiles/libqvr.dir/observer.cpp.o" "CMakeFiles/libqvr.dir/window.cpp.o" "CMakeFiles/libqvr.dir/process.cpp.o" "CMakeFiles/libqvr.dir/ipc.cpp.o" "CMakeFiles/libqvr.dir/internalglobals.cpp.o" "CMakeFiles/libqvr.dir/logging.cpp.o" "CMakeFiles/libqvr.dir/event.cpp.o" "CMakeFiles/libqvr.dir/rendercontext.cpp.o" "CMakeFiles/libqvr.dir/frustum.cpp.o" "CMakeFiles/libqvr.dir/qrc_qvr.cpp.o" "libqvr.pdb" "libqvr.so.3.0.0" "libqvr.so" "libqvr.so.3" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/libqvr.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep># Copyright (C) 2017, 2018 # Computer Graphics Group, University of Siegen # Written by <NAME> <<EMAIL>> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and this # notice are preserved. This file is offered as-is, without any warranty. cmake_minimum_required(VERSION 3.4) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR} ${CMAKE_MODULE_PATH}) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) project(qvr-videoplayer) find_package(Qt5 5.6.0 COMPONENTS Gui Multimedia) find_package(QVR REQUIRED) include_directories(${QVR_INCLUDE_DIRS}) link_directories(${QVR_LIBRARY_DIRS}) qt5_add_resources(RESOURCES resources.qrc) add_executable(qvr-videoplayer qvr-videoplayer.cpp qvr-videoplayer.hpp screen.cpp screen.hpp tiny_obj_loader.cc tiny_obj_loader.h ${RESOURCES}) set_target_properties(qvr-videoplayer PROPERTIES WIN32_EXECUTABLE TRUE) target_link_libraries(qvr-videoplayer ${QVR_LIBRARIES} Qt5::Gui Qt5::Multimedia) install(TARGETS qvr-videoplayer RUNTIME DESTINATION bin) <file_sep>#ifndef BVEC_HPP #define BVEC_HPP struct BVec { bool x; bool y; bool z; BVec(bool x, bool y, bool z): x(x), y(y), z(z) {} BVec(bool x): x(x), y(x), z(x) {} BVec operator &=(BVec a) { this->x &= a.x; this->y &= a.y; this->z &= a.z; return *this; } friend BVec operator & (BVec a, BVec b) { return a &= b; } public: bool any() { return x || y || z; } bool all() { return x && y && z; } }; #endif // BVEC_HPP <file_sep># Copyright (C) 2016, 2017, 2018 # Computer Graphics Group, University of Siegen # Written by <NAME> <<EMAIL>> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and this # notice are preserved. This file is offered as-is, without any warranty. cmake_minimum_required(VERSION 3.4) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR} ${CMAKE_MODULE_PATH}) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) project(qvr-example-opengl) find_package(Qt5 5.6.0 COMPONENTS Gui) find_package(QVR REQUIRED) include_directories(${QVR_INCLUDE_DIRS}) link_directories(${QVR_LIBRARY_DIRS}) qt5_add_resources(RESOURCES resources.qrc) add_executable(qvr-example-opengl geometries.cpp geometries.hpp qvr-example-opengl.cpp qvr-example-opengl.hpp ${RESOURCES}) set_target_properties(qvr-example-opengl PROPERTIES WIN32_EXECUTABLE TRUE) target_link_libraries(qvr-example-opengl ${QVR_LIBRARIES} Qt5::Gui) install(TARGETS qvr-example-opengl RUNTIME DESTINATION bin) <file_sep># Copyright (C) 2016, 2017, 2018 # Computer Graphics Group, University of Siegen # Written by <NAME> <<EMAIL>> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and this # notice are preserved. This file is offered as-is, without any warranty. cmake_minimum_required(VERSION 3.4) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR} ${CMAKE_MODULE_PATH}) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) project(maze) find_package(Qt5 5.6.0 COMPONENTS Gui) find_package(QVR REQUIRED) include_directories(${QVR_INCLUDE_DIRS}) link_directories(${QVR_LIBRARY_DIRS}) qt5_add_resources(RESOURCES resources.qrc) add_executable(maze aabb.cpp box.cpp bvec.hpp geometries.cpp geometries.hpp main.cpp main.hpp drawable.cpp line.cpp maze.cpp material.h ${RESOURCES}) set_target_properties(maze PROPERTIES WIN32_EXECUTABLE TRUE) target_link_libraries(maze ${QVR_LIBRARIES} Qt5::Gui) install(TARGETS maze RUNTIME DESTINATION bin) <file_sep>/* * Copyright (C) 2016, 2017 Computer Graphics Group, University of Siegen * Written by <NAME> <<EMAIL>> * * 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. */ #if(1) #include <Windows.h> #endif #define MAZE 1 #define CUSTOM_NAV true #define WALK_SPEED .001f #define SIZE 0.1f #define LIFT_TIME 3 * 1000.f #ifdef _WIN32 #include <Windows.h> #endif #include <QGuiApplication> #include <QKeyEvent> #include <QImage> #include <QTimer> #include <qvr/observer.hpp> #include <qvr/manager.hpp> #include <qvr/window.hpp> #include <qvr/device.hpp> #include "main.hpp" #include "geometries.hpp" static QString BUTTON = QString("Button"); static QString GOAL = QString("Goal"); static bool isGLES = false; // is this OpenGL ES or plain OpenGL? const float ANIMATION_SPEED = 0.1f; Main::Main() : _wantExit(false) , _objectRotationAngle(0.0f) { _timer.start(); } unsigned int Main::setupTex(const QString& filename) { QImage img; img.load(filename); if (isGLES) img = img.scaledToWidth(img.width() / 2, Qt::SmoothTransformation); img = img.mirrored(false, true); img = img.convertToFormat(QImage::Format_RGBA8888); return setupTex(img); } unsigned int Main::setupTex(const QImage& img) { unsigned int tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, img.width(), img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.constBits()); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); if (!isGLES) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4.0f); return tex; } unsigned int Main::setupVao(int vertexCount, const float* positions, const float* normals, const float* texcoords, int indexCount, const unsigned short* indices) { GLuint vao; GLuint positionBuf, normalBuf, texcoordBuf, indexBuf; std::vector<QVector3D> v, n; std::vector<QVector2D> t; for (int i = 0; i < vertexCount; i++) { v.push_back(QVector3D( positions[i * 3 + 0] , positions[i * 3 + 1] , positions[i * 3 + 2] )); n.push_back(QVector3D( normals[i * 3 + 0] , normals[i * 3 + 1] , normals[i * 3 + 2] )); t.push_back(QVector2D( texcoords[i * 2 + 0] , texcoords[i * 2 + 1] )); } glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &positionBuf); glBindBuffer(GL_ARRAY_BUFFER, positionBuf); glBufferData(GL_ARRAY_BUFFER, v.size() * sizeof(QVector3D), v.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); glGenBuffers(1, &normalBuf); glBindBuffer(GL_ARRAY_BUFFER, normalBuf); glBufferData(GL_ARRAY_BUFFER, n.size() * sizeof(QVector3D), n.data(), GL_STATIC_DRAW); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); glGenBuffers(1, &texcoordBuf); glBindBuffer(GL_ARRAY_BUFFER, texcoordBuf); glBufferData(GL_ARRAY_BUFFER, t.size() * sizeof (QVector2D), t.data(), GL_STATIC_DRAW); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(2); glGenBuffers(1, &indexBuf); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuf); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexCount * sizeof(unsigned short), indices, GL_STATIC_DRAW); return vao; } void Main::setMaterial(const Material& m) { _prg.setUniformValue("material_color", m.r, m.g, m.b); _prg.setUniformValue("material_kd", m.kd); _prg.setUniformValue("material_ks", m.ks); _prg.setUniformValue("material_shininess", m.shininess); _prg.setUniformValue("material_has_diff_tex", m.diffTex == 0 ? 0 : 1); _prg.setUniformValue("material_diff_tex", 0); _prg.setUniformValue("material_has_norm_tex", m.normTex == 0 ? 0 : 1); _prg.setUniformValue("material_norm_tex", 1); _prg.setUniformValue("material_has_spec_tex", m.specTex == 0 ? 0 : 1); _prg.setUniformValue("material_spec_tex", 2); _prg.setUniformValue("material_tex_coord_factor", m.texCoordFactor); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m.diffTex); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, m.normTex); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, m.specTex); } void Main::renderVao(const QMatrix4x4& projectionMatrix, const QMatrix4x4& viewMatrix, const QMatrix4x4& modelMatrix, unsigned int vao, unsigned int indices) { QMatrix4x4 modelViewMatrix = viewMatrix * modelMatrix; _prg.setUniformValue("model_view_matrix", modelViewMatrix); _prg.setUniformValue("projection_model_view_matrix", projectionMatrix * modelViewMatrix); _prg.setUniformValue("normal_matrix", modelViewMatrix.normalMatrix()); glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, indices, GL_UNSIGNED_SHORT, nullptr); } void Main::serializeDynamicData(QDataStream& ds) const { ds << _objectRotationAngle; } void Main::deserializeDynamicData(QDataStream& ds) { ds >> _objectRotationAngle; } void Main::update(const QList<QVRObserver*>& observerList) { float millis = _timer.elapsed(); _timer.restart(); // Trigger a haptic pulse on devices that support it for (int i = 0; i < QVRManager::deviceCount(); i++) { const QVRDevice& device = QVRManager::device(i); if (device.supportsHapticPulse() && device.hasAnalog(QVR_Analog_Trigger) && device.analogValue(QVR_Analog_Trigger) > 0.0f) { int microseconds = device.analogValue(QVR_Analog_Trigger) * 3999; device.triggerHapticPulse(microseconds); } } QVRObserver* observer = observerList.first(); /** Initial observer placement and maze position adjustment */ if (!_mazeInited) { _position = _root->getRandomPos(); _mazeInited = true; } for (int i = 0; i < QVRManager::deviceCount(); i++) { const QVRDevice& device = QVRManager::device(i); _orientation = -device.orientation(); observer->setTracking(_position, _orientation); } QVector3D position = _root->collision( _position , _orientation.rotatedVector(QVector3D(WALK_SPEED * _moveXAxis * millis, 0, WALK_SPEED * _moveZAxis * millis)) , _observerBox->getBox() ); _position = QVector3D(position.x(), 0, position.z()); observer->setTracking(_position, _orientation); QMatrix4x4 translation; translation.translate(observer->trackingPosition()); _observerBox->setGlobalTransform(translation); for (std::shared_ptr<Aabb> obstacle : _obstacles) obstacle->update(QMatrix4x4(), millis); } bool Main::wantExit() { return _wantExit; } // Helper function: read a complete file into a QString (without error checking) static QString readFile(const char* fileName) { QFile f(fileName); f.open(QIODevice::ReadOnly); QTextStream in(&f); return in.readAll(); } #if(MAZE) bool Main::initProcess(QVRProcess* /* p */) { // Qt-based OpenGL function pointers initializeOpenGLFunctions(); // FBO glGenFramebuffers(1, &_fbo); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); glGenTextures(1, &_fboDepthTex); glBindTexture(GL_TEXTURE_2D, _fboDepthTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, 1, 1, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _fboDepthTex, 0); //// Device model data //for (int i = 0; i < QVRManager::deviceModelVertexDataCount(); i++) { // _devModelVaos.append(setupVao( // QVRManager::deviceModelVertexCount(i), // QVRManager::deviceModelVertexPositions(i), // QVRManager::deviceModelVertexNormals(i), // QVRManager::deviceModelVertexTexCoords(i), // QVRManager::deviceModelVertexIndexCount(i), // QVRManager::deviceModelVertexIndices(i))); // _devModelVaoIndices.append(QVRManager::deviceModelVertexIndexCount(i)); //} //for (int i = 0; i < QVRManager::deviceModelTextureCount(); i++) { // _devModelTextures.append(setupTex(QVRManager::deviceModelTexture(i))); //} std::shared_ptr<Maze> maze = std::make_shared<Maze>(32, 32); for (unsigned short i = 0; i < 10; i++) { QVector3D pos = maze->getRandomPos(); std::shared_ptr<Aabb> obstacle = std::make_shared<Aabb>( pos - QVector3D(0.2f, .8, 0.2f) , pos + QVector3D(0.2f, 0.2f, 0.5f) , true , QVector3D(0, 1, 1)); maze->addObstacle(obstacle); _obstacles.push_back(obstacle); pos = maze->getRandomPos(); std::shared_ptr<Aabb> button = std::make_shared<Aabb>( pos - QVector3D(0.2f, 0.5, 0.2f) , pos + QVector3D(0.2f, 0.3, 0.2f) , true , QVector3D(0.5, 0.5, 1) , BUTTON); maze->addObstacle(button); QObject::connect(button.get() , &Aabb::collided , this , &Main::buttonHit ); pos = maze->getRandomPos(); std::shared_ptr<Aabb> goal = std::make_shared<Aabb>( pos - QVector3D(0.2f, 0.5, 0.2f) , pos + QVector3D(0.2f, 0.2, 0.2f) , true , QVector3D(0, 1, 0) , GOAL); maze->addObstacle(goal); QObject::connect(goal.get() , &Aabb::collided , this , &Main::reachedGoal ); } _root = maze; _observerBox = std::make_shared<Aabb> ( QVector3D(-SIZE, -SIZE, -SIZE) , QVector3D(SIZE, SIZE, SIZE) , true , QVector3D(1, 0.8f, 0) ); _line = std::make_shared<Line> ("ray" , std::vector<QVector3D>({QVector3D(), QVector3D()}) , QVector3D(1, 1, 0) ); maze->addChild(_line); return true; } void Main::render(QVRWindow* /* w */, const QVRRenderContext& context, const unsigned int* textures) { for (int view = 0; view < context.viewCount(); view++) { // Get view dimensions int width = context.textureSize(view).width(); int height = context.textureSize(view).height(); // Set up framebuffer object to render into glBindTexture(GL_TEXTURE_2D, _fboDepthTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[view], 0); // Set up view glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); QMatrix4x4 projectionMatrix = context.frustum(view).toMatrix4x4(); QMatrix4x4 viewMatrix = context.viewMatrixPure(view); // Set up shader program glEnable(GL_DEPTH_TEST); // Render scene _observerBox->render(viewMatrix, projectionMatrix); _root->render(viewMatrix, projectionMatrix); QRect viewport = QRect(0, 0, width, height); QVector3D line_p0 = QVector3D(width / 2, height / 2, 0); QVector3D line_p1 = QVector3D(_mousePos.x(), _mousePos.y(), 1); line_p0.unproject(viewMatrix, projectionMatrix, viewport); line_p1.unproject(viewMatrix, projectionMatrix, viewport); _line->setLine(std::vector<QVector3D>({ line_p0 , line_p1 })); // Render device models (optional) #if 0 for (int i = 0; i < QVRManager::deviceCount(); i++) { const QVRDevice& device = QVRManager::device(i); for (int j = 0; j < device.modelNodeCount(); j++) { QMatrix4x4 nodeMatrix = device.matrix(); nodeMatrix.translate(device.modelNodePosition(j)); nodeMatrix.rotate(device.modelNodeOrientation(j)); int vertexDataIndex = device.modelNodeVertexDataIndex(j); int textureIndex = device.modelNodeTextureIndex(j); Material material(1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, _devModelTextures[textureIndex], 0, 0, 1.0f); setMaterial(material); renderVao(projectionMatrix, context.viewMatrixPure(view), nodeMatrix, _devModelVaos[vertexDataIndex], _devModelVaoIndices[vertexDataIndex]); } } #endif // Invalidate depth attachment (to help OpenGL ES performance) const GLenum fboInvalidations[] = { GL_DEPTH_ATTACHMENT }; glInvalidateFramebuffer(GL_FRAMEBUFFER, 1, fboInvalidations); } } #endif void Main::keyPressEvent(const QVRRenderContext& /* context */, QKeyEvent* event) { switch (event->key()) { case Qt::Key_Escape: _wantExit = true; break; case Qt::Key_W: _moveZAxis = -1; break; case Qt::Key_S: _moveZAxis = 1; break; case Qt::Key_D: _moveXAxis = 1; break; case Qt::Key_A: _moveXAxis = -1; break; } } void Main::keyReleaseEvent(const QVRRenderContext& /* context */, QKeyEvent* event) { _moveZAxis = 0; _moveXAxis = 0; } void Main::deviceAnalogChangeEvent(QVRDeviceEvent *event) { switch (event->analog()) { case QVR_Analog_Axis_Y: _moveZAxis = event->device().analogValue(QVR_Analog_Axis_Y); break; case QVR_Analog_Axis_X: _moveXAxis = event->device().analogValue(QVR_Analog_Axis_X); break; } } void Main::mouseMoveEvent(const QVRRenderContext &context, QMouseEvent *event) { QPointF current = event->pos(); float yaw = -current.x() / context.windowGeometry().width(); float pitch = -current.y() / context.windowGeometry().height(); _mousePos = current; _orientation = QQuaternion::fromEulerAngles(pitch * 90 + 45, yaw * 360, 0.f); } void Main::mousePressEvent(const QVRRenderContext &context, QMouseEvent *event) { switch (event->buttons()) { case Qt::LeftButton: _moveZAxis = -1; break; case Qt::RightButton: _moveZAxis = 1; break; } } void Main::mouseReleaseEvent(const QVRRenderContext &context, QMouseEvent *event) { _moveZAxis = 0; } void Main::buttonHit() { if (_obstaclesAnimated) return; _obstaclesAnimated = true; std::cout << "lifting" << std::endl; QTimer::singleShot(LIFT_TIME, this, &Main::drop); animateObstacles(QVector3D(0, 1, 0) * ANIMATION_SPEED); } void Main::reachedGoal() { _wantExit = true; } void Main::drop() { std::cout << "dropping" << std::endl; QTimer::singleShot(LIFT_TIME, this, &Main::stop); animateObstacles(QVector3D(0, -1, 0) * ANIMATION_SPEED); } void Main::stop() { animateObstacles(QVector3D(0, 0, 0)); _obstaclesAnimated = false; } void Main::animateObstacles(QVector3D offset) { for (std::shared_ptr<Aabb> obstacle : _obstacles) obstacle->move(offset); } #if(!MAZE) bool Main::initProcess(QVRProcess* /* p */) { /* Initialize per-process OpenGL resources and state here */ std::vector<float> positions; std::vector<float> normals; std::vector<float> texcoords; std::vector<unsigned short> indices; // Qt-based OpenGL function pointers initializeOpenGLFunctions(); // FBO glGenFramebuffers(1, &_fbo); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); glGenTextures(1, &_fboDepthTex); glBindTexture(GL_TEXTURE_2D, _fboDepthTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, 1, 1, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _fboDepthTex, 0); // Floor geom_quad(positions, normals, texcoords, indices); _floorVao = setupVao(positions.size() / 3, positions.data(), normals.data(), texcoords.data(), indices.size(), indices.data()); _floorIndices = indices.size(); _floorMaterial = Material(0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, setupTex(":floor-diff.jpg"), isGLES ? 0 : setupTex(":floor-norm.jpg"), 0, 10.0f); // Pillar geom_cylinder(positions, normals, texcoords, indices, isGLES ? 20 : 40); _pillarVaos[0] = setupVao(positions.size() / 3, positions.data(), normals.data(), texcoords.data(), indices.size(), indices.data()); _pillarIndices[0] = indices.size(); geom_disk(positions, normals, texcoords, indices, 0.0f, isGLES ? 20 : 40); _pillarVaos[1] = setupVao(positions.size() / 3, positions.data(), normals.data(), texcoords.data(), indices.size(), indices.data()); _pillarIndices[1] = indices.size(); _pillarMaterial = Material(0.5f, 0.5f, 0.3f, 0.5f, 0.5f, 100.0f, setupTex(":pillar-diff.jpg"), isGLES ? 0 : setupTex(":pillar-norm.jpg"), isGLES ? 0 : setupTex(":pillar-spec.jpg")); // Object geom_cube(positions, normals, texcoords, indices); _objectVaos[0] = setupVao(positions.size() / 3, positions.data(), normals.data(), texcoords.data(), indices.size(), indices.data()); _objectIndices[0] = indices.size(); _objectMaterials[0] = Material(0.8f, 0.3f, 0.3f, 0.8f, 0.2f, 20.0f); _objectMatrices[0].rotate(15.0f, 1.0f, 1.0f, 0.0f); _objectMatrices[0].scale(0.5f); geom_cone(positions, normals, texcoords, indices, isGLES ? 20 : 40, isGLES ? 10 : 20); _objectVaos[1] = setupVao(positions.size() / 3, positions.data(), normals.data(), texcoords.data(), indices.size(), indices.data()); _objectIndices[1] = indices.size(); _objectMaterials[1] = Material(0.8f, 0.6f, 0.3f, 0.8f, 0.2f, 20.0f); _objectMatrices[1].rotate(15.0f, 1.0f, 1.0f, 0.0f); _objectMatrices[1].scale(0.5f); geom_torus(positions, normals, texcoords, indices, 0.4f, isGLES ? 20 : 40, isGLES ? 20 : 40); _objectVaos[2] = setupVao(positions.size() / 3, positions.data(), normals.data(), texcoords.data(), indices.size(), indices.data()); _objectIndices[2] = indices.size(); _objectMaterials[2] = Material(0.4f, 0.8f, 0.3f, 0.8f, 0.2f, 20.0f); _objectMatrices[2].rotate(15.0f, 1.0f, 1.0f, 0.0f); _objectMatrices[2].scale(0.5f); geom_teapot(positions, normals, texcoords, indices); _objectVaos[3] = setupVao(positions.size() / 3, positions.data(), normals.data(), texcoords.data(), indices.size(), indices.data()); _objectIndices[3] = indices.size(); _objectMaterials[3] = Material(0.3f, 0.3f, 0.8f, 0.8f, 0.2f, 20.0f); _objectMatrices[3].rotate(15.0f, 1.0f, 1.0f, 0.0f); geom_cylinder(positions, normals, texcoords, indices, isGLES ? 20 : 40); _objectVaos[4] = setupVao(positions.size() / 3, positions.data(), normals.data(), texcoords.data(), indices.size(), indices.data()); _objectIndices[4] = indices.size(); _objectMaterials[4] = Material(0.3f, 0.8f, 0.8f, 0.8f, 0.2f, 20.0f); _objectMatrices[4].rotate(15.0f, 1.0f, 1.0f, 0.0f); _objectMatrices[4].scale(0.5f); glBindBuffer(GL_ARRAY_BUFFER, 0); // Shader program QString vertexShaderSource = readFile(":vertex-shader.glsl"); QString fragmentShaderSource = readFile(":fragment-shader.glsl"); if (isGLES) { vertexShaderSource.prepend("#version 300 es\n"); fragmentShaderSource.prepend("#version 300 es\n"); fragmentShaderSource.replace("$WITH_NORMAL_MAPS", "0"); fragmentShaderSource.replace("$WITH_SPEC_MAPS", "0"); } else { vertexShaderSource.prepend("#version 330\n"); fragmentShaderSource.prepend("#version 330\n"); fragmentShaderSource.replace("$WITH_NORMAL_MAPS", "1"); fragmentShaderSource.replace("$WITH_SPEC_MAPS", "1"); } _prg.addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource); _prg.addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource); _prg.link(); // Device model data for (int i = 0; i < QVRManager::deviceModelVertexDataCount(); i++) { _devModelVaos.append(setupVao( QVRManager::deviceModelVertexCount(i), QVRManager::deviceModelVertexPositions(i), QVRManager::deviceModelVertexNormals(i), QVRManager::deviceModelVertexTexCoords(i), QVRManager::deviceModelVertexIndexCount(i), QVRManager::deviceModelVertexIndices(i))); _devModelVaoIndices.append(QVRManager::deviceModelVertexIndexCount(i)); } for (int i = 0; i < QVRManager::deviceModelTextureCount(); i++) { _devModelTextures.append(setupTex(QVRManager::deviceModelTexture(i))); } return true; } void Main::render(QVRWindow* /* w */, const QVRRenderContext& context, const unsigned int* textures) { for (int view = 0; view < context.viewCount(); view++) { // Get view dimensions int width = context.textureSize(view).width(); int height = context.textureSize(view).height(); // Set up framebuffer object to render into glBindTexture(GL_TEXTURE_2D, _fboDepthTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[view], 0); // Set up view glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); QMatrix4x4 projectionMatrix = context.frustum(view).toMatrix4x4(); QMatrix4x4 viewMatrix = context.viewMatrix(view); // Set up shader program glUseProgram(_prg.programId()); glEnable(GL_DEPTH_TEST); // Render scene setMaterial(_floorMaterial); QMatrix4x4 groundMatrix; groundMatrix.scale(5.0f); groundMatrix.rotate(-90.0f, 1.0f, 0.0f, 0.0f); renderVao(projectionMatrix, viewMatrix, groundMatrix, _floorVao, _floorIndices); for (int i = 0; i < 5; i++) { setMaterial(_pillarMaterial); QMatrix4x4 pillarMatrix, pillarDiskMatrix, objectMatrix; pillarMatrix.rotate(18.0f + (i + 1) * 72.0f, 0.0f, 1.0f, 0.0f); pillarMatrix.translate(2.0f, 0.0f, 0.0f); pillarDiskMatrix = pillarMatrix; objectMatrix = pillarMatrix; pillarMatrix.translate(0.0f, 0.8f, 0.0f); pillarMatrix.scale(0.2f, 0.8f, 0.2f); renderVao(projectionMatrix, viewMatrix, pillarMatrix, _pillarVaos[0], _pillarIndices[0]); pillarDiskMatrix.translate(0.0f, 1.6f, 0.0f); pillarDiskMatrix.rotate(-90.0f, 1.0f, 0.0f, 0.0f); pillarDiskMatrix.scale(0.2f); renderVao(projectionMatrix, viewMatrix, pillarDiskMatrix, _pillarVaos[1], _pillarIndices[1]); setMaterial(_objectMaterials[i]); objectMatrix.translate(0.0f, 1.75f, 0.0f); objectMatrix.scale(0.2f); objectMatrix.rotate(_objectRotationAngle, 0.0f, 1.0f, 0.0f); objectMatrix *= _objectMatrices[i]; renderVao(projectionMatrix, viewMatrix, objectMatrix, _objectVaos[i], _objectIndices[i]); } // Render device models (optional) for (int i = 0; i < QVRManager::deviceCount(); i++) { const QVRDevice& device = QVRManager::device(i); for (int j = 0; j < device.modelNodeCount(); j++) { QMatrix4x4 nodeMatrix = device.matrix(); nodeMatrix.translate(device.modelNodePosition(j)); nodeMatrix.rotate(device.modelNodeOrientation(j)); int vertexDataIndex = device.modelNodeVertexDataIndex(j); int textureIndex = device.modelNodeTextureIndex(j); Material material(1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, _devModelTextures[textureIndex], 0, 0, 1.0f); setMaterial(material); renderVao(projectionMatrix, context.viewMatrixPure(view), nodeMatrix, _devModelVaos[vertexDataIndex], _devModelVaoIndices[vertexDataIndex]); } } // Invalidate depth attachment (to help OpenGL ES performance) const GLenum fboInvalidations[] = { GL_DEPTH_ATTACHMENT }; glInvalidateFramebuffer(GL_FRAMEBUFFER, 1, fboInvalidations); } } #endif int main(int argc, char* argv[]) { srand (time(NULL)); QGuiApplication app(argc, argv); QVRManager manager(argc, argv); isGLES = (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES); Drawable::setGLES(isGLES); /* First set the default surface format that all windows will use */ QSurfaceFormat format; if (isGLES) { format.setVersion(3, 0); } else { format.setProfile(QSurfaceFormat::CoreProfile); format.setVersion(3, 3); } format.setOption(QSurfaceFormat::DebugContext); QSurfaceFormat::setDefaultFormat(format); /* Then start QVR with your app */ Main qvrapp; if (!manager.init(&qvrapp, CUSTOM_NAV)) { qCritical("Cannot initialize QVR manager"); return 1; } /* Enter the standard Qt loop */ return app.exec(); } <file_sep># Copyright (C) 2016, 2017, 2018 # Computer Graphics Group, University of Siegen # Written by <NAME> <<EMAIL>> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and this # notice are preserved. This file is offered as-is, without any warranty. cmake_minimum_required(VERSION 3.4) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR} ${CMAKE_MODULE_PATH}) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) project(qvr-example-vtk) find_package(Qt5 5.6.0 COMPONENTS Gui) find_package(QVR REQUIRED) find_package(VTK 6.2 REQUIRED COMPONENTS vtkRenderingExternal NO_MODULE) include(${VTK_USE_FILE}) include_directories(${VTK_INCLUDE_DIRS} ${QVR_INCLUDE_DIRS}) link_directories(${VTK_LIBRARY_DIRS} ${QVR_LIBRARY_DIRS}) add_executable(qvr-example-vtk qvr-example-vtk.cpp qvr-example-vtk.hpp) set_target_properties(qvr-example-vtk PROPERTIES WIN32_EXECUTABLE TRUE) target_link_libraries(qvr-example-vtk ${VTK_LIBRARIES} ${QVR_LIBRARIES} Qt5::Gui) install(TARGETS qvr-example-vtk RUNTIME DESTINATION bin) <file_sep># Copyright (C) 2016, 2017, 2018 # Computer Graphics Group, University of Siegen # Written by <NAME> <<EMAIL>> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and this # notice are preserved. This file is offered as-is, without any warranty. cmake_minimum_required(VERSION 3.4) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR} ${CMAKE_MODULE_PATH}) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) # Project project(libqvr) set(QVR_VERSION 3.0.0) set(QVR_LIBVERSION 3.0.0) set(QVR_SOVERSION 3) # Build options option(QVR_BUILD_DOCUMENTATION "Build API reference documentation (requires Doxygen)" OFF) # Required libraries find_package(Qt5 5.6.0 COMPONENTS Gui Network OPTIONAL_COMPONENTS Gamepad) # Optional libraries find_package(VRPN QUIET) find_package(Oculus QUIET) find_package(OpenVR QUIET) # The QVR library qt5_add_resources(QVRRESOURCES qvr.qrc) add_library(libqvr SHARED manager.hpp manager.cpp config.hpp config.cpp device.hpp device.cpp observer.hpp observer.cpp window.hpp window.cpp process.hpp process.cpp ipc.hpp ipc.cpp internalglobals.hpp internalglobals.cpp logging.hpp logging.cpp event.hpp event.cpp rendercontext.hpp rendercontext.cpp frustum.hpp frustum.cpp ${QVRRESOURCES}) set_target_properties(libqvr PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS TRUE) set_target_properties(libqvr PROPERTIES OUTPUT_NAME qvr) set_target_properties(libqvr PROPERTIES VERSION ${QVR_LIBVERSION}) set_target_properties(libqvr PROPERTIES SOVERSION ${QVR_SOVERSION}) target_link_libraries(libqvr Qt5::Gui Qt5::Network) if(Qt5Gamepad_FOUND) add_definitions(-DHAVE_QGAMEPAD) target_link_libraries(libqvr Qt5::Gamepad) endif() if(VRPN_FOUND) add_definitions(-DHAVE_VRPN) include_directories(${VRPN_INCLUDE_DIRS}) target_link_libraries(libqvr ${VRPN_LIBRARIES}) endif() if(OCULUS_FOUND) add_definitions(-DHAVE_OCULUS) include_directories(${OCULUS_INCLUDE_DIRS}) target_link_libraries(libqvr ${OCULUS_LIBRARIES}) endif() if(OPENVR_FOUND) add_definitions(-DHAVE_OPENVR) include_directories(${OPENVR_INCLUDE_DIRS}) target_link_libraries(libqvr ${OPENVR_LIBRARIES}) endif() install(TARGETS libqvr RUNTIME DESTINATION bin LIBRARY DESTINATION lib${LIB_SUFFIX} ARCHIVE DESTINATION lib${LIB_SUFFIX} ) install(FILES app.hpp manager.hpp config.hpp device.hpp observer.hpp window.hpp process.hpp rendercontext.hpp outputplugin.hpp frustum.hpp DESTINATION include/qvr) include(CMakePackageConfigHelpers) set(INCLUDE_INSTALL_DIR ${CMAKE_INSTALL_PREFIX}/include) set(LIB_INSTALL_DIR ${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}) configure_package_config_file( QVRConfig.cmake.in ${CMAKE_BINARY_DIR}/QVRConfig.cmake INSTALL_DESTINATION lib${LIB_SUFFIX}/cmake/QVR-{QVR_VERSION} PATH_VARS INCLUDE_INSTALL_DIR LIB_INSTALL_DIR NO_CHECK_REQUIRED_COMPONENTS_MACRO ) write_basic_package_version_file( ${CMAKE_BINARY_DIR}/QVRConfigVersion.cmake VERSION ${QVR_VERSION} COMPATIBILITY SameMajorVersion ) install(FILES ${CMAKE_BINARY_DIR}/QVRConfig.cmake ${CMAKE_BINARY_DIR}/QVRConfigVersion.cmake DESTINATION ${LIB_INSTALL_DIR}/cmake/QVR-${QVR_VERSION} ) # Optional target: reference documentation if(QVR_BUILD_DOCUMENTATION) find_package(Doxygen REQUIRED) configure_file("${CMAKE_SOURCE_DIR}/Doxyfile.in" "${CMAKE_BINARY_DIR}/Doxyfile" @ONLY) file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/html") add_custom_command(OUTPUT "${CMAKE_BINARY_DIR}/html/index.html" COMMAND ${DOXYGEN_EXECUTABLE} "${CMAKE_BINARY_DIR}/Doxyfile" WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" DEPENDS "${CMAKE_SOURCE_DIR}/Doxyfile.in" "${CMAKE_SOURCE_DIR}/app.hpp" "${CMAKE_SOURCE_DIR}/manager.hpp" "${CMAKE_SOURCE_DIR}/config.hpp" "${CMAKE_SOURCE_DIR}/device.hpp" "${CMAKE_SOURCE_DIR}/observer.hpp" "${CMAKE_SOURCE_DIR}/window.hpp" "${CMAKE_SOURCE_DIR}/process.hpp" "${CMAKE_SOURCE_DIR}/rendercontext.hpp" "${CMAKE_SOURCE_DIR}/outputplugin.hpp" "${CMAKE_SOURCE_DIR}/frustum.hpp" COMMENT "Generating API documentation with Doxygen" VERBATIM ) add_custom_target(doc ALL DEPENDS "${CMAKE_BINARY_DIR}/html/index.html") install(DIRECTORY "${CMAKE_BINARY_DIR}/html" DESTINATION share/doc/libqvr) endif() <file_sep>/* * Copyright (C) 2016, 2017 Computer Graphics Group, University of Siegen * Written by <NAME> <<EMAIL>> * * 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. */ #ifndef QVR_EXAMPLE_OPENGL_HPP #define QVR_EXAMPLE_OPENGL_HPP #include <QObject> #include <QOpenGLExtraFunctions> #include <QOpenGLShaderProgram> #include <QElapsedTimer> class QImage; #include <qvr/app.hpp> #include <qvr/process.hpp> #include <aabb.h> #include <drawable.h> #include <maze.h> #include <line.h> class Main : public QObject, public QVRApp, protected QOpenGLExtraFunctions { Q_OBJECT public: Main(); private: /* Data not directly relevant for rendering */ bool _wantExit; // do we want to exit the app? QElapsedTimer _timer; // used for animation purposes /* Static data for rendering. Here, these are OpenGL resources that are * initialized per process, so there is no need to serialize them for * multi-process rendering support. */ unsigned int _fbo; // Framebuffer object to render into unsigned int _fboDepthTex; // Depth attachment for the FBO unsigned int _floorVao; // Vertex array object for the floor unsigned int _floorIndices; // Number of indices to render for the pl. Material _floorMaterial; // Material of the floor unsigned int _pillarVaos[2]; // Vertex array objects for the pillar unsigned int _pillarIndices[2]; // Number of indices to render for the pil. Material _pillarMaterial; // Material of the pillar unsigned int _objectVaos[5]; // Vertex array objects for the 5 objects unsigned int _objectIndices[5]; // Number of indices to render for the objs Material _objectMaterials[5]; // Materials of the objects QMatrix4x4 _objectMatrices[5]; // Base transformation matrices of the objs QOpenGLShaderProgram _prg; // GLSL program for rendering std::shared_ptr<Maze> _root; // Scene root // Data to render device models QVector<unsigned int> _devModelVaos; QVector<unsigned int> _devModelVaoIndices; QVector<unsigned int> _devModelTextures; bool _mazeInited = false; // Flag indicated whether we have already adjusted the maze position QPointF _mousePos = QPointF(0, 0); QQuaternion _orientation; QVector3D _position; float _moveZAxis = 0; // Move forward/backward float _moveXAxis = 0; // Move left/right std::shared_ptr<Aabb> _observerBox;// Box of the observer std::shared_ptr<Line> _line; std::vector<std::shared_ptr<Aabb>> _obstacles; bool _obstaclesAnimated = false; /* Dynamic data for rendering. This needs to be serialized for multi-process * rendering) */ float _objectRotationAngle; // animated object rotation /* Helper function for texture loading */ unsigned int setupTex(const QString& filename); unsigned int setupTex(const QImage& img); /* Helper function for VAO setup */ unsigned int setupVao(int vertexCount, const float* positions, const float* normals, const float* texcoords, int indexCount, const unsigned short* indices); /* Helper function to set materials */ void setMaterial(const Material& m); /* Helper function for GL VAO rendering */ void renderVao(const QMatrix4x4& projectionMatrix, const QMatrix4x4& viewMatrix, const QMatrix4x4& modelMatrix, unsigned int vao, unsigned int indices); QVector3D collisionAdjust(QVector3D position, QVector3D movement, float size = 0.5f); void animateObstacles(QVector3D transform); public: void serializeDynamicData(QDataStream& ds) const override; void deserializeDynamicData(QDataStream& ds) override; void update(const QList<QVRObserver*>& observers) override; bool wantExit() override; bool initProcess(QVRProcess* p) override; void render(QVRWindow* w, const QVRRenderContext& c, const unsigned int* textures) override; void keyPressEvent(const QVRRenderContext& context, QKeyEvent* event) override; void keyReleaseEvent(const QVRRenderContext &, QKeyEvent * event); void deviceAnalogChangeEvent(QVRDeviceEvent * event) override; void mouseMoveEvent(const QVRRenderContext &context, QMouseEvent *event) override; void mousePressEvent(const QVRRenderContext &context, QMouseEvent *event) override; void mouseReleaseEvent(const QVRRenderContext &context, QMouseEvent *event) override; public slots: void buttonHit(); void drop(); void reachedGoal(); void stop(); }; #endif <file_sep>#include "drawable.h" #define ANIMATION_SPEED 0.01f Drawable::Drawable(std::string name): _name(name) { } void Drawable::update(QMatrix4x4 transform, float elapsedMilli) { _globalTransform = transform; _localTransform.translate(_offset); for (std::shared_ptr<Drawable> child : _children) child->update(_localTransform * _globalTransform, elapsedMilli); } void Drawable::setLocalTransform(QMatrix4x4 m) { _localTransform = m; for (std::shared_ptr<Drawable> child : _children) child->setLocalTransform(m); } void Drawable::setGlobalTransform(QMatrix4x4 m) { _globalTransform = m; for (std::shared_ptr<Drawable> child : _children) child->setGlobalTransform(m); } void Drawable::render(QMatrix4x4 &vMatrix, QMatrix4x4 &pMatrix) { for (std::shared_ptr<Drawable> child : _children) child->render(vMatrix, pMatrix); glRender(vMatrix, pMatrix); } void Drawable::glRender(QMatrix4x4 &vMatrix, QMatrix4x4 &pMatrix) { QOpenGLExtraFunctions *f = QOpenGLContext::currentContext()->extraFunctions(); _prg.bind(); f->glActiveTexture(GL_TEXTURE0); f->glBindTexture(GL_TEXTURE_2D, _material.diffTex); f->glActiveTexture(GL_TEXTURE1); f->glBindTexture(GL_TEXTURE_2D, _material.normTex); f->glActiveTexture(GL_TEXTURE2); f->glBindTexture(GL_TEXTURE_2D, _material.specTex); // Projection QMatrix4x4 modelViewMatrix = vMatrix * _globalTransform * _localTransform; _prg.setUniformValue("model_view_matrix", modelViewMatrix); _prg.setUniformValue("projection_model_view_matrix", pMatrix * modelViewMatrix); _prg.setUniformValue("normal_matrix", modelViewMatrix.normalMatrix()); f->glBindVertexArray(_vao); f->glDrawElements(GL_TRIANGLES, _elementsCount, GL_UNSIGNED_SHORT, nullptr); _prg.release(); } void Drawable::initBuffers(std::vector<QVector3D> *vertices , std::vector<QVector3D> *normals , std::vector<QVector2D> *texcoords , std::vector<unsigned short> *indices) { QOpenGLExtraFunctions *f = QOpenGLContext::currentContext()->extraFunctions(); GLuint positionBuf, normalBuf, texcoordBuf, indexBuf; f->glGenVertexArrays(1, &_vao); f->glBindVertexArray(_vao); f->glGenBuffers(1, &positionBuf); f->glBindBuffer(GL_ARRAY_BUFFER, positionBuf); f->glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (vertices->size() * sizeof (QVector3D)), vertices->data(), GL_STATIC_DRAW); f->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); f->glEnableVertexAttribArray(0); f->glGenBuffers(1, &normalBuf); f->glBindBuffer(GL_ARRAY_BUFFER, normalBuf); f->glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (normals->size() * sizeof (QVector3D)), normals->data(), GL_STATIC_DRAW); f->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr); f->glEnableVertexAttribArray(1); f->glGenBuffers(1, &texcoordBuf); f->glBindBuffer(GL_ARRAY_BUFFER, texcoordBuf); f->glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (texcoords->size() * sizeof (QVector2D)), texcoords->data(), GL_STATIC_DRAW); f->glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr); f->glEnableVertexAttribArray(2); f->glGenBuffers(1, &indexBuf); f->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuf); f->glBufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast<GLsizeiptr> (indices->size() * sizeof(unsigned short)), indices->data(), GL_STATIC_DRAW); f->glBindVertexArray(0); f->glDeleteBuffers(1, &positionBuf); f->glDeleteBuffers(1, &normalBuf); f->glDeleteBuffers(1, &texcoordBuf); f->glDeleteBuffers(1, &indexBuf); _elementsCount = static_cast<GLsizei> (indices->size()); } void Drawable::addChild(std::shared_ptr<Drawable> child) { _children.push_back(child); } unsigned int Drawable::loadTexture(const QString& filename) { QImage img; img.load(filename); if (getGLES()) img = img.scaledToWidth(img.width() / 2, Qt::SmoothTransformation); img = img.mirrored(false, true); img = img.convertToFormat(QImage::Format_RGBA8888); return loadTexture(img); } unsigned int Drawable::loadTexture(const QImage& img) { QOpenGLExtraFunctions *f = QOpenGLContext::currentContext()->extraFunctions(); unsigned int tex; f->glGenTextures(1, &tex); f->glBindTexture(GL_TEXTURE_2D, tex); f->glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, img.width(), img.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.constBits()); f->glGenerateMipmap(GL_TEXTURE_2D); f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); f->glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); if (!getGLES()) f->glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4.0f); return tex; } void Drawable::setMaterial(const Material m) { _material = m; _prg.bind(); // Material _prg.setUniformValue("material_color", m.r, m.g, m.b); _prg.setUniformValue("material_kd", m.kd); _prg.setUniformValue("material_ks", m.ks); _prg.setUniformValue("material_shininess", m.shininess); _prg.setUniformValue("material_has_diff_tex", m.diffTex == 0 ? 0 : 1); _prg.setUniformValue("material_diff_tex", 0); _prg.setUniformValue("material_has_norm_tex", m.normTex == 0 ? 0 : 1); _prg.setUniformValue("material_norm_tex", 1); _prg.setUniformValue("material_has_spec_tex", m.specTex == 0 ? 0 : 1); _prg.setUniformValue("material_spec_tex", 2); _prg.setUniformValue("material_tex_coord_factor", m.texCoordFactor); _prg.release(); } QString Drawable::readFile(const char* fileName) { QFile f(fileName); f.open(QIODevice::ReadOnly); QTextStream in(&f); return in.readAll(); } void Drawable::loadShader(const char* vertShaderPath, const char* fragShaderPath) { QString vertexShaderSource = readFile(vertShaderPath); QString fragmentShaderSource = readFile(fragShaderPath); if (getGLES()) { vertexShaderSource.prepend("#version 300 es\n"); fragmentShaderSource.prepend("#version 300 es\n"); fragmentShaderSource.replace("$WITH_NORMAL_MAPS", "0"); fragmentShaderSource.replace("$WITH_SPEC_MAPS", "0"); } else { vertexShaderSource.prepend("#version 330\n"); fragmentShaderSource.prepend("#version 330\n"); fragmentShaderSource.replace("$WITH_NORMAL_MAPS", "1"); fragmentShaderSource.replace("$WITH_SPEC_MAPS", "1"); } _prg.addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource); _prg.addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource); _prg.link(); } QOpenGLShaderProgram& Drawable::getShader() { return _prg; } GLuint Drawable::getVao() { return _vao; } void Drawable::setVao(GLuint vao) { _vao = vao; } QMatrix4x4 Drawable::getModelMatrix() const { return _globalTransform * _localTransform; } QMatrix4x4 Drawable::getLocalTransform() const { return _localTransform; } void Drawable::setGLES(bool isGLES) { Drawable::isGLES = isGLES; } bool Drawable::getGLES() { return Drawable::isGLES; } bool Drawable::isGLES = false; void Drawable::move(QVector3D offset) { _offset = offset; } <file_sep>/* * Copyright (C) 2016, 2017, 2018 Computer Graphics Group, University of Siegen * Written by <NAME> <<EMAIL>> * * 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. */ #ifndef QVR_FLYING_THINGS_HPP #define QVR_FLYING_THINGS_HPP #include <QOpenGLFunctions_3_3_Core> #include <QOpenGLShaderProgram> #include <QElapsedTimer> #include <qvr/app.hpp> class FlyingThings : public QVRApp, protected QOpenGLFunctions_3_3_Core { private: /* Data not directly relevant for rendering */ bool _wantExit; // do we want to exit the app? bool _pause; // are we in pause mode? qint64 _elapsedTime; // used for rotating the box QElapsedTimer _timer; // used for rotating the box /* Static data for rendering, initialized per process. */ unsigned int _fbo; // Framebuffer object to render into unsigned int _fboDepthTex; // Depth attachment for the FBO unsigned int _vaos[4][18]; // Vertex array objects for 4 objects in 18 LODs unsigned int _vaoIndices[4][18];// Number of indices to render for each VAO QOpenGLShaderProgram _prg; // Shader program for rendering /* Dynamic data for rendering. Needs to be serialized. */ float _ringRotationAngle; // Ring rotation float _objectRotationAngle; // Object rotation angle int _objects; // Number of objects int _objectLOD; // Global LOD for object geometry (0-5) int _objectType; // Sphere, cylinder, cone, torus, random (0-4) bool _wireframe; // Render wireframe? bool _frustumCulling; // Render with frustum culling? bool _backfaceCulling; // Render with backface culling? bool _distanceLOD; // Render with distance-based LOD? public: FlyingThings(); bool initProcess(QVRProcess* p) override; void render(QVRWindow* w, const QVRRenderContext& context, const unsigned int* textures) override; void update(const QList<QVRObserver*>& observers) override; bool wantExit() override; void serializeDynamicData(QDataStream& ds) const override; void deserializeDynamicData(QDataStream& ds) override; void keyPressEvent(const QVRRenderContext& context, QKeyEvent* event) override; }; #endif <file_sep># Meta set(AM_MULTI_CONFIG "FALSE") set(AM_PARALLEL "4") set(AM_VERBOSITY "") # Directories set(AM_CMAKE_SOURCE_DIR "/home/andrey/workspace/qvr/qvr-example-opengl") set(AM_CMAKE_BINARY_DIR "/home/andrey/workspace/qvr/qvr-example-opengl") set(AM_CMAKE_CURRENT_SOURCE_DIR "/home/andrey/workspace/qvr/qvr-example-opengl") set(AM_CMAKE_CURRENT_BINARY_DIR "/home/andrey/workspace/qvr/qvr-example-opengl") set(AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE "") set(AM_BUILD_DIR "/home/andrey/workspace/qvr/qvr-example-opengl/qvr-example-opengl_autogen") set(AM_INCLUDE_DIR "/home/andrey/workspace/qvr/qvr-example-opengl/qvr-example-opengl_autogen/include") # Files set(AM_SOURCES "/home/andrey/workspace/qvr/qvr-example-opengl/geometries.cpp;/home/andrey/workspace/qvr/qvr-example-opengl/qvr-example-opengl.cpp") set(AM_HEADERS "/home/andrey/workspace/qvr/qvr-example-opengl/geometries.hpp;/home/andrey/workspace/qvr/qvr-example-opengl/qvr-example-opengl.hpp") set(AM_SETTINGS_FILE "/home/andrey/workspace/qvr/qvr-example-opengl/CMakeFiles/qvr-example-opengl_autogen.dir/AutogenOldSettings.txt") # Qt set(AM_QT_VERSION_MAJOR 5) set(AM_QT_MOC_EXECUTABLE "/usr/bin/moc") set(AM_QT_UIC_EXECUTABLE "") # MOC settings set(AM_MOC_SKIP "/home/andrey/workspace/qvr/qvr-example-opengl/qrc_resources.cpp") set(AM_MOC_DEFINITIONS "QT_CORE_LIB;QT_GUI_LIB;QT_NO_DEBUG") set(AM_MOC_INCLUDES "/home/andrey/workspace/qvr/qvr-example-opengl;/usr/include/qt;/usr/include/qt/QtGui;/usr/include/qt/QtCore;/usr/lib/qt/mkspecs/linux-g++;/usr/local/include;/usr/include;/usr/include/c++/8.3.0;/usr/include/c++/8.3.0/x86_64-pc-linux-gnu;/usr/include/c++/8.3.0/backward;/usr/lib/gcc/x86_64-pc-linux-gnu/8.3.0/include;/usr/lib/gcc/x86_64-pc-linux-gnu/8.3.0/include-fixed") set(AM_MOC_OPTIONS "") set(AM_MOC_RELAXED_MODE "") set(AM_MOC_MACRO_NAMES "Q_OBJECT;Q_GADGET;Q_NAMESPACE") set(AM_MOC_DEPEND_FILTERS "") set(AM_MOC_PREDEFS_CMD "/usr/bin/c++;-dM;-E;-c;/usr/share/cmake-3.14/Modules/CMakeCXXCompilerABI.cpp") <file_sep># CMAKE generated file: DO NOT EDIT! # Generated by "Unix Makefiles" Generator, CMake Version 3.14 # Default target executed when no arguments are given to make. default_target: all .PHONY : default_target # Allow only one "make -f Makefile2" at a time, but pass parallelism. .NOTPARALLEL: #============================================================================= # Special targets provided by cmake. # Disable implicit rules so canonical targets will work. .SUFFIXES: # Remove some rules from gmake that .SUFFIXES does not remove. SUFFIXES = .SUFFIXES: .hpux_make_needs_suffix_list # Suppress display of executed commands. $(VERBOSE).SILENT: # A target that is always out of date. cmake_force: .PHONY : cmake_force #============================================================================= # Set environment variables for the build. # The shell in which to execute make rules. SHELL = /bin/sh # The CMake executable. CMAKE_COMMAND = /usr/bin/cmake # The command to remove a file. RM = /usr/bin/cmake -E remove -f # Escaping for special characters. EQUALS = = # The top-level source directory on which CMake was run. CMAKE_SOURCE_DIR = /home/andrey/workspace/qvr/libqvr # The top-level build directory on which CMake was run. CMAKE_BINARY_DIR = /home/andrey/workspace/qvr/libqvr #============================================================================= # Targets provided globally by CMake. # Special rule for the target install/strip install/strip: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip # Special rule for the target install/strip install/strip/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..." /usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake .PHONY : install/strip/fast # Special rule for the target edit_cache edit_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." /usr/bin/ccmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : edit_cache # Special rule for the target edit_cache edit_cache/fast: edit_cache .PHONY : edit_cache/fast # Special rule for the target rebuild_cache rebuild_cache: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." /usr/bin/cmake -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) .PHONY : rebuild_cache # Special rule for the target rebuild_cache rebuild_cache/fast: rebuild_cache .PHONY : rebuild_cache/fast # Special rule for the target list_install_components list_install_components: @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Unspecified\"" .PHONY : list_install_components # Special rule for the target list_install_components list_install_components/fast: list_install_components .PHONY : list_install_components/fast # Special rule for the target install/local install/local: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local # Special rule for the target install/local install/local/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..." /usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake .PHONY : install/local/fast # Special rule for the target install install: preinstall @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install # Special rule for the target install install/fast: preinstall/fast @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..." /usr/bin/cmake -P cmake_install.cmake .PHONY : install/fast # The main all target all: cmake_check_build_system $(CMAKE_COMMAND) -E cmake_progress_start /home/andrey/workspace/qvr/libqvr/CMakeFiles /home/andrey/workspace/qvr/libqvr/CMakeFiles/progress.marks $(MAKE) -f CMakeFiles/Makefile2 all $(CMAKE_COMMAND) -E cmake_progress_start /home/andrey/workspace/qvr/libqvr/CMakeFiles 0 .PHONY : all # The main clean target clean: $(MAKE) -f CMakeFiles/Makefile2 clean .PHONY : clean # The main clean target clean/fast: clean .PHONY : clean/fast # Prepare targets for installation. preinstall: all $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall # Prepare targets for installation. preinstall/fast: $(MAKE) -f CMakeFiles/Makefile2 preinstall .PHONY : preinstall/fast # clear depends depend: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 .PHONY : depend #============================================================================= # Target rules for targets named libqvr # Build rule for target. libqvr: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 libqvr .PHONY : libqvr # fast build rule for target. libqvr/fast: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/build .PHONY : libqvr/fast #============================================================================= # Target rules for targets named libqvr_autogen # Build rule for target. libqvr_autogen: cmake_check_build_system $(MAKE) -f CMakeFiles/Makefile2 libqvr_autogen .PHONY : libqvr_autogen # fast build rule for target. libqvr_autogen/fast: $(MAKE) -f CMakeFiles/libqvr_autogen.dir/build.make CMakeFiles/libqvr_autogen.dir/build .PHONY : libqvr_autogen/fast config.o: config.cpp.o .PHONY : config.o # target to build an object file config.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/config.cpp.o .PHONY : config.cpp.o config.i: config.cpp.i .PHONY : config.i # target to preprocess a source file config.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/config.cpp.i .PHONY : config.cpp.i config.s: config.cpp.s .PHONY : config.s # target to generate assembly for a file config.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/config.cpp.s .PHONY : config.cpp.s device.o: device.cpp.o .PHONY : device.o # target to build an object file device.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/device.cpp.o .PHONY : device.cpp.o device.i: device.cpp.i .PHONY : device.i # target to preprocess a source file device.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/device.cpp.i .PHONY : device.cpp.i device.s: device.cpp.s .PHONY : device.s # target to generate assembly for a file device.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/device.cpp.s .PHONY : device.cpp.s event.o: event.cpp.o .PHONY : event.o # target to build an object file event.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/event.cpp.o .PHONY : event.cpp.o event.i: event.cpp.i .PHONY : event.i # target to preprocess a source file event.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/event.cpp.i .PHONY : event.cpp.i event.s: event.cpp.s .PHONY : event.s # target to generate assembly for a file event.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/event.cpp.s .PHONY : event.cpp.s frustum.o: frustum.cpp.o .PHONY : frustum.o # target to build an object file frustum.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/frustum.cpp.o .PHONY : frustum.cpp.o frustum.i: frustum.cpp.i .PHONY : frustum.i # target to preprocess a source file frustum.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/frustum.cpp.i .PHONY : frustum.cpp.i frustum.s: frustum.cpp.s .PHONY : frustum.s # target to generate assembly for a file frustum.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/frustum.cpp.s .PHONY : frustum.cpp.s internalglobals.o: internalglobals.cpp.o .PHONY : internalglobals.o # target to build an object file internalglobals.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/internalglobals.cpp.o .PHONY : internalglobals.cpp.o internalglobals.i: internalglobals.cpp.i .PHONY : internalglobals.i # target to preprocess a source file internalglobals.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/internalglobals.cpp.i .PHONY : internalglobals.cpp.i internalglobals.s: internalglobals.cpp.s .PHONY : internalglobals.s # target to generate assembly for a file internalglobals.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/internalglobals.cpp.s .PHONY : internalglobals.cpp.s ipc.o: ipc.cpp.o .PHONY : ipc.o # target to build an object file ipc.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/ipc.cpp.o .PHONY : ipc.cpp.o ipc.i: ipc.cpp.i .PHONY : ipc.i # target to preprocess a source file ipc.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/ipc.cpp.i .PHONY : ipc.cpp.i ipc.s: ipc.cpp.s .PHONY : ipc.s # target to generate assembly for a file ipc.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/ipc.cpp.s .PHONY : ipc.cpp.s libqvr_autogen/mocs_compilation.o: libqvr_autogen/mocs_compilation.cpp.o .PHONY : libqvr_autogen/mocs_compilation.o # target to build an object file libqvr_autogen/mocs_compilation.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/libqvr_autogen/mocs_compilation.cpp.o .PHONY : libqvr_autogen/mocs_compilation.cpp.o libqvr_autogen/mocs_compilation.i: libqvr_autogen/mocs_compilation.cpp.i .PHONY : libqvr_autogen/mocs_compilation.i # target to preprocess a source file libqvr_autogen/mocs_compilation.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/libqvr_autogen/mocs_compilation.cpp.i .PHONY : libqvr_autogen/mocs_compilation.cpp.i libqvr_autogen/mocs_compilation.s: libqvr_autogen/mocs_compilation.cpp.s .PHONY : libqvr_autogen/mocs_compilation.s # target to generate assembly for a file libqvr_autogen/mocs_compilation.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/libqvr_autogen/mocs_compilation.cpp.s .PHONY : libqvr_autogen/mocs_compilation.cpp.s logging.o: logging.cpp.o .PHONY : logging.o # target to build an object file logging.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/logging.cpp.o .PHONY : logging.cpp.o logging.i: logging.cpp.i .PHONY : logging.i # target to preprocess a source file logging.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/logging.cpp.i .PHONY : logging.cpp.i logging.s: logging.cpp.s .PHONY : logging.s # target to generate assembly for a file logging.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/logging.cpp.s .PHONY : logging.cpp.s manager.o: manager.cpp.o .PHONY : manager.o # target to build an object file manager.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/manager.cpp.o .PHONY : manager.cpp.o manager.i: manager.cpp.i .PHONY : manager.i # target to preprocess a source file manager.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/manager.cpp.i .PHONY : manager.cpp.i manager.s: manager.cpp.s .PHONY : manager.s # target to generate assembly for a file manager.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/manager.cpp.s .PHONY : manager.cpp.s observer.o: observer.cpp.o .PHONY : observer.o # target to build an object file observer.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/observer.cpp.o .PHONY : observer.cpp.o observer.i: observer.cpp.i .PHONY : observer.i # target to preprocess a source file observer.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/observer.cpp.i .PHONY : observer.cpp.i observer.s: observer.cpp.s .PHONY : observer.s # target to generate assembly for a file observer.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/observer.cpp.s .PHONY : observer.cpp.s process.o: process.cpp.o .PHONY : process.o # target to build an object file process.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/process.cpp.o .PHONY : process.cpp.o process.i: process.cpp.i .PHONY : process.i # target to preprocess a source file process.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/process.cpp.i .PHONY : process.cpp.i process.s: process.cpp.s .PHONY : process.s # target to generate assembly for a file process.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/process.cpp.s .PHONY : process.cpp.s qrc_qvr.o: qrc_qvr.cpp.o .PHONY : qrc_qvr.o # target to build an object file qrc_qvr.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/qrc_qvr.cpp.o .PHONY : qrc_qvr.cpp.o qrc_qvr.i: qrc_qvr.cpp.i .PHONY : qrc_qvr.i # target to preprocess a source file qrc_qvr.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/qrc_qvr.cpp.i .PHONY : qrc_qvr.cpp.i qrc_qvr.s: qrc_qvr.cpp.s .PHONY : qrc_qvr.s # target to generate assembly for a file qrc_qvr.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/qrc_qvr.cpp.s .PHONY : qrc_qvr.cpp.s rendercontext.o: rendercontext.cpp.o .PHONY : rendercontext.o # target to build an object file rendercontext.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/rendercontext.cpp.o .PHONY : rendercontext.cpp.o rendercontext.i: rendercontext.cpp.i .PHONY : rendercontext.i # target to preprocess a source file rendercontext.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/rendercontext.cpp.i .PHONY : rendercontext.cpp.i rendercontext.s: rendercontext.cpp.s .PHONY : rendercontext.s # target to generate assembly for a file rendercontext.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/rendercontext.cpp.s .PHONY : rendercontext.cpp.s window.o: window.cpp.o .PHONY : window.o # target to build an object file window.cpp.o: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/window.cpp.o .PHONY : window.cpp.o window.i: window.cpp.i .PHONY : window.i # target to preprocess a source file window.cpp.i: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/window.cpp.i .PHONY : window.cpp.i window.s: window.cpp.s .PHONY : window.s # target to generate assembly for a file window.cpp.s: $(MAKE) -f CMakeFiles/libqvr.dir/build.make CMakeFiles/libqvr.dir/window.cpp.s .PHONY : window.cpp.s # Help Target help: @echo "The following are some of the valid targets for this Makefile:" @echo "... all (the default if no target is provided)" @echo "... clean" @echo "... depend" @echo "... install/strip" @echo "... edit_cache" @echo "... libqvr" @echo "... rebuild_cache" @echo "... list_install_components" @echo "... install/local" @echo "... install" @echo "... libqvr_autogen" @echo "... config.o" @echo "... config.i" @echo "... config.s" @echo "... device.o" @echo "... device.i" @echo "... device.s" @echo "... event.o" @echo "... event.i" @echo "... event.s" @echo "... frustum.o" @echo "... frustum.i" @echo "... frustum.s" @echo "... internalglobals.o" @echo "... internalglobals.i" @echo "... internalglobals.s" @echo "... ipc.o" @echo "... ipc.i" @echo "... ipc.s" @echo "... libqvr_autogen/mocs_compilation.o" @echo "... libqvr_autogen/mocs_compilation.i" @echo "... libqvr_autogen/mocs_compilation.s" @echo "... logging.o" @echo "... logging.i" @echo "... logging.s" @echo "... manager.o" @echo "... manager.i" @echo "... manager.s" @echo "... observer.o" @echo "... observer.i" @echo "... observer.s" @echo "... process.o" @echo "... process.i" @echo "... process.s" @echo "... qrc_qvr.o" @echo "... qrc_qvr.i" @echo "... qrc_qvr.s" @echo "... rendercontext.o" @echo "... rendercontext.i" @echo "... rendercontext.s" @echo "... window.o" @echo "... window.i" @echo "... window.s" .PHONY : help #============================================================================= # Special targets to cleanup operation of make. # Special rule to run CMake to check the build system integrity. # No rule that depends on this can have commands that come from listfiles # because they might be regenerated. cmake_check_build_system: $(CMAKE_COMMAND) -S$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 .PHONY : cmake_check_build_system <file_sep># Copyright (C) 2016, 2017, 2018 # Computer Graphics Group, University of Siegen # Written by <NAME> <<EMAIL>> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and this # notice are preserved. This file is offered as-is, without any warranty. cmake_minimum_required(VERSION 3.4) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR} ${CMAKE_MODULE_PATH}) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) project(qvr-example-openscenegraph) find_package(Qt5 5.6.0 COMPONENTS Gui) find_package(QVR REQUIRED) set(OpenSceneGraph_MARK_AS_ADVANCED ON) find_package(OpenSceneGraph REQUIRED COMPONENTS osgViewer osgDB) include_directories(${OPENSCENEGRAPH_INCLUDE_DIRS} ${QVR_INCLUDE_DIRS}) link_directories(${OPENSCENEGRAPH_LIBRARY_DIRS} ${QVR_LIBRARY_DIRS}) add_executable(qvr-example-openscenegraph qvr-example-openscenegraph.cpp qvr-example-openscenegraph.hpp) set_target_properties(qvr-example-openscenegraph PROPERTIES WIN32_EXECUTABLE TRUE) target_link_libraries(qvr-example-openscenegraph ${OPENSCENEGRAPH_LIBRARIES} ${QVR_LIBRARIES} Qt5::Gui) install(TARGETS qvr-example-openscenegraph RUNTIME DESTINATION bin) <file_sep>#include <iostream> #include "line.h" Line::Line(std::string name, std::vector<QVector3D> line, QVector3D color): Drawable(name), _color(color) { setLine(line); Drawable::loadShader( ":vertex-shader.glsl" , ":fragment-shader_dbg.glsl" ); } void Line::initBuffers() { QOpenGLExtraFunctions *f = QOpenGLContext::currentContext()->extraFunctions(); GLuint vao = getVao(); if (vao == 0) f->glGenVertexArrays(1, &vao); f->glBindVertexArray(vao); GLuint vertexBuf; f->glGenBuffers(1, &vertexBuf); f->glBindBuffer(GL_ARRAY_BUFFER, vertexBuf); f->glBufferData(GL_ARRAY_BUFFER, GLsizeiptr (_line.size() * sizeof(QVector3D)), _line.data(), GL_DYNAMIC_DRAW); f->glEnableVertexAttribArray(0); f->glVertexAttribPointer( 0,// attribute position in buffer 3,// size (number of items per vertex) GL_FLOAT,// data type GL_FALSE,// is normalised? 0,// stride nullptr// array buffer offset ); f->glBindVertexArray(0); f->glDeleteBuffers(1, &vertexBuf); _vertexCount = _line.size(); setVao(vao); } void Line::glRender(QMatrix4x4 &vMatrix, QMatrix4x4 &pMatrix) { initBuffers(); QOpenGLExtraFunctions *f = QOpenGLContext::currentContext()->extraFunctions(); QMatrix4x4 modelViewMatrix = vMatrix * getModelMatrix(); QOpenGLShaderProgram& prg = getShader(); prg.bind(); prg.setUniformValue("color", _color.x(), _color.y(), _color.z()); prg.setUniformValue("model_view_matrix", modelViewMatrix); prg.setUniformValue("projection_model_view_matrix", pMatrix * modelViewMatrix); prg.setUniformValue("normal_matrix", modelViewMatrix.normalMatrix()); f->glBindVertexArray(getVao()); f->glDrawArrays(GL_LINES, 0, _vertexCount); prg.release(); } void Line::setLine(std::vector<QVector3D> line) { _line = line; } <file_sep>#ifndef DRAWABLE_H #define DRAWABLE_H #include <QOpenGLShaderProgram> #include <QOpenGLExtraFunctions> #include <QFile> #include <QImage> #include <QMatrix4x4> #include <vector> #include <memory> #include <iostream> #include <material.h> class Drawable : protected QOpenGLExtraFunctions { public: Drawable(std::string name); void update(QMatrix4x4 m, float elapsedMilli); void setGlobalTransform(QMatrix4x4 m); void setLocalTransform(QMatrix4x4 m); void render(QMatrix4x4 &vMatrix, QMatrix4x4 &pMatrix); void addChild(std::shared_ptr<Drawable> child); void setMaterial(const Material material); virtual void initBuffers( std::vector<QVector3D> *vertices , std::vector<QVector3D> *normals , std::vector<QVector2D> *texcoords , std::vector<unsigned short> *indices); QOpenGLShaderProgram& getShader(); GLuint getVao(); void setVao(GLuint vao); void loadShader(const char* vertShaderPath, const char* fragShaderPath); unsigned int loadTexture(const QString& filename); unsigned int loadTexture(const QImage& img); static QString readFile(const char* fileName); static void setGLES(bool isGLES); static bool getGLES(); static bool isGLES; void move(QVector3D offset); QMatrix4x4 getModelMatrix() const; QMatrix4x4 getLocalTransform() const; private: virtual void glRender(QMatrix4x4 &vMatrix, QMatrix4x4 &pMatrix); QOpenGLShaderProgram _prg; std::vector<std::shared_ptr<Drawable>> _children; std::string _name; Material _material; QMatrix4x4 _globalTransform; QMatrix4x4 _localTransform; float _a = 0.f; GLsizei _elementsCount; QVector3D _offset = QVector3D(); unsigned int _vao; }; #endif // DRAWABLE_H <file_sep>#ifndef LINE_H #define LINE_H #include <vector> #include "drawable.h" #include <QVector3D> #include <QMatrix4x4> /** * @brief The Line class describes the absolute path a planet follows */ class Line : public Drawable { public: /** * @brief Line constructor * @param name the name of the path */ Line(std::string name = "UNKNOWN LINE", std::vector<QVector3D> line = { QVector3D(0.f, 0.f, 0.f) , QVector3D(0.f, 0.f, 0.f) } , QVector3D color = QVector3D(1.f, 1.f, 1.f)); virtual void glRender(QMatrix4x4 &vMatrix, QMatrix4x4 &pMatrix) override; void setLine(std::vector<QVector3D> line); private: virtual void initBuffers(); std::vector<QVector3D> _line; QVector3D _color; GLsizei _vertexCount; }; #endif // LINE_H <file_sep># The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/andrey/workspace/qvr/libqvr/config.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/config.cpp.o" "/home/andrey/workspace/qvr/libqvr/device.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/device.cpp.o" "/home/andrey/workspace/qvr/libqvr/event.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/event.cpp.o" "/home/andrey/workspace/qvr/libqvr/frustum.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/frustum.cpp.o" "/home/andrey/workspace/qvr/libqvr/internalglobals.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/internalglobals.cpp.o" "/home/andrey/workspace/qvr/libqvr/ipc.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/ipc.cpp.o" "/home/andrey/workspace/qvr/libqvr/libqvr_autogen/mocs_compilation.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/libqvr_autogen/mocs_compilation.cpp.o" "/home/andrey/workspace/qvr/libqvr/logging.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/logging.cpp.o" "/home/andrey/workspace/qvr/libqvr/manager.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/manager.cpp.o" "/home/andrey/workspace/qvr/libqvr/observer.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/observer.cpp.o" "/home/andrey/workspace/qvr/libqvr/process.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/process.cpp.o" "/home/andrey/workspace/qvr/libqvr/qrc_qvr.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/qrc_qvr.cpp.o" "/home/andrey/workspace/qvr/libqvr/rendercontext.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/rendercontext.cpp.o" "/home/andrey/workspace/qvr/libqvr/window.cpp" "/home/andrey/workspace/qvr/libqvr/CMakeFiles/libqvr.dir/window.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. set(CMAKE_TARGET_DEFINITIONS_CXX "QT_CORE_LIB" "QT_GUI_LIB" "QT_NETWORK_LIB" "QT_NO_DEBUG" "libqvr_EXPORTS" ) # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "." "libqvr_autogen/include" "/usr/include/qt" "/usr/include/qt/QtGui" "/usr/include/qt/QtCore" "/usr/lib/qt/mkspecs/linux-g++" "/usr/include/qt/QtNetwork" ) # Pairs of files generated by the same build rule. set(CMAKE_MULTIPLE_OUTPUT_PAIRS "/home/andrey/workspace/qvr/libqvr/libqvr.so" "/home/andrey/workspace/qvr/libqvr/libqvr.so.3.0.0" "/home/andrey/workspace/qvr/libqvr/libqvr.so.3" "/home/andrey/workspace/qvr/libqvr/libqvr.so.3.0.0" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "") <file_sep># Copyright (C) 2016, 2017, 2018 # Computer Graphics Group, University of Siegen # Written by <NAME> <<EMAIL>> # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice and this # notice are preserved. This file is offered as-is, without any warranty. cmake_minimum_required(VERSION 3.4) set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR} ${CMAKE_MODULE_PATH}) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) project(qvr-example-outputplugin) find_package(Qt5 5.6.0 COMPONENTS Widgets) find_package(QVR REQUIRED) include_directories(${QVR_INCLUDE_DIRS}) link_directories(${QVR_LIBRARY_DIRS}) qt5_add_resources(RESOURCES qvr-example-outputplugin.qrc) add_library(libqvr-example-outputplugin SHARED qvr-example-outputplugin.cpp qvr-example-outputplugin.hpp ${RESOURCES}) set_target_properties(libqvr-example-outputplugin PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS TRUE) set_target_properties(libqvr-example-outputplugin PROPERTIES OUTPUT_NAME qvr-example-outputplugin) target_link_libraries(libqvr-example-outputplugin ${QVR_LIBRARIES} Qt5::Widgets) install(TARGETS libqvr-example-outputplugin LIBRARY DESTINATION "lib${LIB_SUFFIX}" ARCHIVE DESTINATION "lib${LIB_SUFFIX}" ) <file_sep>/* * Copyright (C) 2017 Computer Graphics Group, University of Siegen * Written by <NAME> <<EMAIL>> * * 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. */ #include <cstring> #include <QGuiApplication> #include <QCommandLineParser> #include <QKeyEvent> #include <QMediaPlayer> #include <QMediaPlaylist> #include <QAbstractVideoSurface> #include <QVideoSurfaceFormat> #include <QFileInfo> #include <QTemporaryFile> #include <qvr/manager.hpp> #include "qvr-videoplayer.hpp" /* * The VideoFrame class. * * This class represents one video frame, in a form that allows serialization * to a QDataStream (for multi-process support). * On the master process, copying the frame data is avoided. */ class VideoFrame { public: enum StereoLayout { Layout_Unknown, // unknown; needs to be guessed Layout_Mono, // monoscopic video Layout_Top_Bottom, // stereoscopic video, left eye top, right eye bottom Layout_Top_Bottom_Half, // stereoscopic video, left eye top, right eye bottom, both half height Layout_Bottom_Top, // stereoscopic video, left eye bottom, right eye top Layout_Bottom_Top_Half, // stereoscopic video, left eye bottom, right eye top, both half height Layout_Left_Right, // stereoscopic video, left eye left, right eye right Layout_Left_Right_Half, // stereoscopic video, left eye left, right eye right, both half width Layout_Right_Left, // stereoscopic video, left eye right, right eye left Layout_Right_Left_Half // stereoscopic video, left eye right, right eye left, both half width }; QVideoFrame::PixelFormat pixelFormat; QVideoSurfaceFormat::YCbCrColorSpace yCbCrColorSpace; QSize size; float aspectRatio; StereoLayout stereoLayout; QByteArray data; VideoFrame() : pixelFormat(QVideoFrame::Format_Invalid), yCbCrColorSpace(QVideoSurfaceFormat::YCbCr_Undefined), size(-1, -1), aspectRatio(0.0f), stereoLayout(Layout_Unknown), data() { } // Map a QVideoFrame to this video frame; see also unmap() void map(enum StereoLayout sl, const QVideoSurfaceFormat& format, const QVideoFrame& frame) { bool valid = (frame.pixelFormat() != QVideoFrame::Format_Invalid); if (valid) { // This assignment does not copy the frame data: _mapFrame = frame; if (!_mapFrame.map(QAbstractVideoBuffer::ReadOnly)) valid = false; } if (valid) { pixelFormat = frame.pixelFormat(); yCbCrColorSpace = format.yCbCrColorSpace(); size = frame.size(); aspectRatio = static_cast<float>(size.width() * format.pixelAspectRatio().width()) / static_cast<float>(size.height() * format.pixelAspectRatio().height()); stereoLayout = sl; // This assignment does not copy the frame data: data.setRawData(reinterpret_cast<const char*>(_mapFrame.bits()), _mapFrame.mappedBytes()); } else { // Synthesize a black frame pixelFormat = QVideoFrame::Format_ARGB32; yCbCrColorSpace = QVideoSurfaceFormat::YCbCr_Undefined; size = QSize(1, 1); aspectRatio = 1.0f; stereoLayout = Layout_Mono; static const char zeroes[4] = { 0, 0, 0, 0 }; data.setRawData(zeroes, 4); } } // Unmap this video frame (must be called if map() was called) void unmap() { if (_mapFrame.isMapped()) _mapFrame.unmap(); } private: QVideoFrame _mapFrame; }; QDataStream &operator<<(QDataStream& ds, const VideoFrame& f) { ds << static_cast<int>(f.pixelFormat); ds << static_cast<int>(f.yCbCrColorSpace); ds << f.size; ds << f.aspectRatio; ds << static_cast<int>(f.stereoLayout); ds << f.data; return ds; } QDataStream &operator>>(QDataStream& ds, VideoFrame& f) { int tmp; ds >> tmp; f.pixelFormat = static_cast<QVideoFrame::PixelFormat>(tmp); ds >> tmp; f.yCbCrColorSpace = static_cast<QVideoSurfaceFormat::YCbCrColorSpace>(tmp); ds >> f.size; ds >> f.aspectRatio; ds >> tmp; f.stereoLayout = static_cast<enum VideoFrame::StereoLayout>(tmp); ds >> f.data; return ds; } /* * The VideoSurface class. * * This class is used by QMediaPlayer as a video surface, i.e. to output video * frames. * It specifies the video frame formats we can handle, and maps the incoming * QVideoFrame data to our video frame representation. */ class VideoSurface : public QAbstractVideoSurface { private: VideoFrame* _frame; // target video frame bool *_frameIsNew; // flag to set when the target frame represents a new frame QVideoSurfaceFormat _format; // format with which playback is started enum VideoFrame::StereoLayout _stereoLayout; // stereo layout of current media public: VideoSurface(VideoFrame* frame, bool* frameIsNew) : _frame(frame), _frameIsNew(frameIsNew), _stereoLayout(VideoFrame::Layout_Unknown) { } virtual QList<QVideoFrame::PixelFormat> supportedPixelFormats( QAbstractVideoBuffer::HandleType type = QAbstractVideoBuffer::NoHandle) const { Q_UNUSED(type); QList<QVideoFrame::PixelFormat> pixelFormats; pixelFormats.append(QVideoFrame::Format_RGB24); pixelFormats.append(QVideoFrame::Format_ARGB32); pixelFormats.append(QVideoFrame::Format_RGB32); pixelFormats.append(QVideoFrame::Format_RGB565); pixelFormats.append(QVideoFrame::Format_BGRA32); pixelFormats.append(QVideoFrame::Format_BGR32); pixelFormats.append(QVideoFrame::Format_BGR24); pixelFormats.append(QVideoFrame::Format_BGR565); pixelFormats.append(QVideoFrame::Format_YUV420P); pixelFormats.append(QVideoFrame::Format_YUV444); pixelFormats.append(QVideoFrame::Format_AYUV444); pixelFormats.append(QVideoFrame::Format_YV12); // TODO: we could support more formats with a little bit more effort in // preRenderProcess(), but probably RGB24 and YUV420P are the only // ones that are really relevant. return pixelFormats; } virtual bool present(const QVideoFrame &frame) { _frame->unmap(); _frame->map(_stereoLayout, _format, frame); *_frameIsNew = true; return true; } virtual bool start(const QVideoSurfaceFormat &format) { _format = format; return QAbstractVideoSurface::start(format); } void newUrl(const QUrl& url) // called whenever a new media URL is played { // Reset stereo layout, then try to guess it from URL. // This should be compatible to these conventions: // http://bino3d.org/doc/bino.html#File-Name-Conventions-1 _stereoLayout = VideoFrame::Layout_Unknown; QString fileName = url.fileName(); QString marker = fileName.left(fileName.lastIndexOf('.')); marker = marker.right(marker.length() - marker.lastIndexOf('-') - 1); marker = marker.toLower(); if (marker == "lr") _stereoLayout = VideoFrame::Layout_Left_Right; else if (marker == "rl") _stereoLayout = VideoFrame::Layout_Right_Left; else if (marker == "lrh" || marker == "lrq") _stereoLayout = VideoFrame::Layout_Left_Right_Half; else if (marker == "rlh" || marker == "rlq") _stereoLayout = VideoFrame::Layout_Right_Left_Half; else if (marker == "tb" || marker == "ab") _stereoLayout = VideoFrame::Layout_Top_Bottom; else if (marker == "bt" || marker == "ba") _stereoLayout = VideoFrame::Layout_Bottom_Top; else if (marker == "tbh" || marker == "abq") _stereoLayout = VideoFrame::Layout_Top_Bottom_Half; else if (marker == "bth" || marker == "baq") _stereoLayout = VideoFrame::Layout_Bottom_Top_Half; else if (marker == "2d") _stereoLayout = VideoFrame::Layout_Mono; } void newMetaData(const QMediaObject* mediaObject) // called whenever new media is played { /* TODO: we should set the stereoscopic layout from media meta data, but unfortunately * Qt does not give us access to the full media meta data, only to a small subset * of predefined keys, which do not include information about stereoscopic layouts... */ Q_UNUSED(mediaObject); } }; static bool isGLES = false; // Is this OpenGL ES or plain OpenGL? Initialized in main(). QVRVideoPlayer::QVRVideoPlayer(const Screen& screen, QMediaPlaylist* playlist) : _wantExit(false), _playlist(playlist), _player(NULL), _surface(NULL), _screen(screen), _frame(NULL), _frameIsNew(false) { } void QVRVideoPlayer::serializeStaticData(QDataStream& ds) const { ds << _screen; } void QVRVideoPlayer::deserializeStaticData(QDataStream& ds) { ds >> _screen; } void QVRVideoPlayer::serializeDynamicData(QDataStream& ds) const { ds << _frameIsNew; if (_frameIsNew) ds << (*_frame); } void QVRVideoPlayer::deserializeDynamicData(QDataStream& ds) { ds >> _frameIsNew; if (_frameIsNew) ds >> (*_frame); } bool QVRVideoPlayer::wantExit() { return _wantExit; } // Helper function: read a complete file into a QString (without error checking) static QString readFile(const char* fileName) { QFile f(fileName); f.open(QIODevice::ReadOnly); QTextStream in(&f); return in.readAll(); } bool QVRVideoPlayer::initProcess(QVRProcess* /* p */) { // Qt-based OpenGL function pointers initializeOpenGLFunctions(); // FBO and PBO glGenFramebuffers(1, &_fbo); glGenBuffers(1, &_pbo); glGenFramebuffers(1, &_viewFbo); if (_screen.isPlanar) { _depthTex = 0; } else { glGenTextures(1, &_depthTex); glBindTexture(GL_TEXTURE_2D, _depthTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, 1, 1, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glBindFramebuffer(GL_FRAMEBUFFER, _viewFbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _depthTex, 0); } // Color data textures glGenTextures(1, &_rgbTex); glBindTexture(GL_TEXTURE_2D, _rgbTex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glGenTextures(3, _yuvTex); glBindTexture(GL_TEXTURE_2D, _yuvTex[0]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, _yuvTex[1]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, _yuvTex[2]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // Quad geometry const float quadPositions[] = { -1.0f, +1.0f, 0.0f, +1.0f, +1.0f, 0.0f, +1.0f, -1.0f, 0.0f, -1.0f, -1.0f, 0.0f }; const float quadTexCoords[] = { 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f }; static const unsigned short quadIndices[] = { 0, 3, 1, 1, 3, 2 }; glGenVertexArrays(1, &_quadVao); glBindVertexArray(_quadVao); GLuint quadPositionBuf; glGenBuffers(1, &quadPositionBuf); glBindBuffer(GL_ARRAY_BUFFER, quadPositionBuf); glBufferData(GL_ARRAY_BUFFER, sizeof(quadPositions), quadPositions, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); GLuint quadTexCoordBuf; glGenBuffers(1, &quadTexCoordBuf); glBindBuffer(GL_ARRAY_BUFFER, quadTexCoordBuf); glBufferData(GL_ARRAY_BUFFER, sizeof(quadTexCoords), quadTexCoords, GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); GLuint quadIndexBuf; glGenBuffers(1, &quadIndexBuf); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, quadIndexBuf); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quadIndices), quadIndices, GL_STATIC_DRAW); // Color conversion shader program QString colorConvVertexShaderSource = readFile(":colorconv-vs.glsl"); QString colorConvFragmentShaderSource = readFile(":colorconv-fs.glsl"); if (isGLES) { colorConvVertexShaderSource.prepend("#version 300 es\n"); colorConvFragmentShaderSource.prepend("#version 300 es\n"); } else { colorConvVertexShaderSource.prepend("#version 330\n"); colorConvFragmentShaderSource.prepend("#version 330\n"); } _colorConvPrg.addShaderFromSourceCode(QOpenGLShader::Vertex, colorConvVertexShaderSource); _colorConvPrg.addShaderFromSourceCode(QOpenGLShader::Fragment, colorConvFragmentShaderSource); _colorConvPrg.link(); // Frame texture glGenTextures(1, &_frameTex); glBindTexture(GL_TEXTURE_2D, _frameTex); unsigned int black = 0; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, &black); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (_screen.isPlanar) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); if (!isGLES) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4.0f); } // Screen geometry glGenVertexArrays(1, &_screenVao); glBindVertexArray(_screenVao); GLuint positionBuf; glGenBuffers(1, &positionBuf); glBindBuffer(GL_ARRAY_BUFFER, positionBuf); glBufferData(GL_ARRAY_BUFFER, _screen.positions.size() * sizeof(float), _screen.positions.constData(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); GLuint texcoordBuf; glGenBuffers(1, &texcoordBuf); glBindBuffer(GL_ARRAY_BUFFER, texcoordBuf); glBufferData(GL_ARRAY_BUFFER, _screen.texCoords.size() * sizeof(float), _screen.texCoords.constData(), GL_STATIC_DRAW); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); GLuint indexBuf; glGenBuffers(1, &indexBuf); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuf); glBufferData(GL_ELEMENT_ARRAY_BUFFER, _screen.indices.length() * sizeof(unsigned short), _screen.indices.constData(), GL_STATIC_DRAW); // Shader program QString vertexShaderSource = readFile(":vertex-shader.glsl"); QString fragmentShaderSource = readFile(":fragment-shader.glsl"); if (isGLES) { vertexShaderSource.prepend("#version 300 es\n"); fragmentShaderSource.prepend("#version 300 es\n"); } else { vertexShaderSource.prepend("#version 330\n"); fragmentShaderSource.prepend("#version 330\n"); } _prg.addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource); _prg.addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource); _prg.link(); // Media Player _frame = new VideoFrame; if (QVRManager::processIndex() == 0) { _surface = new VideoSurface(_frame, &_frameIsNew); _player = new QMediaPlayer(NULL, QMediaPlayer::VideoSurface); _player->connect(_player, static_cast<void(QMediaPlayer::*)(QMediaPlayer::Error)>(&QMediaPlayer::error), [=](QMediaPlayer::Error error) { if (error != QMediaPlayer::NoError) { //qCritical("Error: %s", qPrintable(_player->errorString())); _wantExit = true; } }); _player->connect(_player, &QMediaPlayer::stateChanged, [=](QMediaPlayer::State state) { if (state == QMediaPlayer::StoppedState) _wantExit = true; }); _player->connect(_player, &QMediaPlayer::currentMediaChanged, [=](const QMediaContent &content) { _surface->newUrl(content.canonicalUrl()); }); _player->connect(_player, &QMediaPlayer::metaDataAvailableChanged, [=](bool available) { if (available) _surface->newMetaData(_player); }); _player->setVideoOutput(_surface); _player->setPlaylist(_playlist); _player->play(); } return true; } void QVRVideoPlayer::preRenderProcess(QVRProcess* /* p */) { /* We need to get new frame data into a texture that is suitable for * rendering the screen: _frameTex. * On the way, we typically need to convert the color space with a fragment * shader. SRGB texture formats are not suitable since we cannot render * into them from OpenGL ES. Therefore we need to store linear RGB. This * means 8 bit per color is not enough since we would lose details in dark * regions. GL_RGB10_A2 seems to be a good choice for _frameTex: we can * render into that format, it is filterable, and 10 bit per color should be * enough. */ if (_frameIsNew && QVRManager::windowCount() > 0) { // First copy the frame data into a PBO and from there into textures. // This is faster than using glTexImage2D() directly on the frame data. glBindBuffer(GL_PIXEL_UNPACK_BUFFER, _pbo); glBufferData(GL_PIXEL_UNPACK_BUFFER, _frame->data.size(), NULL, GL_STREAM_DRAW); void* ptr = glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, 0, _frame->data.size(), GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT | GL_MAP_UNSYNCHRONIZED_BIT); Q_ASSERT(ptr); std::memcpy(ptr, _frame->data.constData(), _frame->data.size()); glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER); const int w = _frame->size.width(); const int h = _frame->size.height(); int shaderInput; // 0=rgbTex.rgb, 1=yuvTex.rgb, 2=vec3(yuvTex[0].r,yuvTex[1].r,yuvTex[2].r) switch (_frame->pixelFormat) { case QVideoFrame::Format_RGB24: glBindTexture(GL_TEXTURE_2D, _rgbTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); shaderInput = 0; break; case QVideoFrame::Format_BGR24: glBindTexture(GL_TEXTURE_2D, _rgbTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); shaderInput = 0; break; case QVideoFrame::Format_ARGB32: case QVideoFrame::Format_RGB32: glBindTexture(GL_TEXTURE_2D, _rgbTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_ALPHA); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); shaderInput = 0; break; case QVideoFrame::Format_BGRA32: case QVideoFrame::Format_BGR32: glBindTexture(GL_TEXTURE_2D, _rgbTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); shaderInput = 0; break; case QVideoFrame::Format_RGB565: glBindTexture(GL_TEXTURE_2D, _rgbTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB565, w, h, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); shaderInput = 0; break; case QVideoFrame::Format_BGR565: glBindTexture(GL_TEXTURE_2D, _rgbTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB565, w, h, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); shaderInput = 0; break; case QVideoFrame::Format_YUV444: glBindTexture(GL_TEXTURE_2D, _yuvTex[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); shaderInput = 1; break; case QVideoFrame::Format_AYUV444: glBindTexture(GL_TEXTURE_2D, _yuvTex[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_GREEN); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_BLUE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_ALPHA); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); shaderInput = 1; break; case QVideoFrame::Format_YUV420P: glBindTexture(GL_TEXTURE_2D, _yuvTex[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_ZERO); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_ZERO); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); glBindTexture(GL_TEXTURE_2D, _yuvTex[1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w / 2, h / 2, 0, GL_RED, GL_UNSIGNED_BYTE, reinterpret_cast<const GLvoid*>(w * h)); glBindTexture(GL_TEXTURE_2D, _yuvTex[2]); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w / 2, h / 2, 0, GL_RED, GL_UNSIGNED_BYTE, reinterpret_cast<const GLvoid*>(w * h + w * h / 4)); shaderInput = 2; break; case QVideoFrame::Format_YV12: glBindTexture(GL_TEXTURE_2D, _yuvTex[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_ZERO); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_ZERO); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ONE); glBindTexture(GL_TEXTURE_2D, _yuvTex[2]); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w / 2, h / 2, 0, GL_RED, GL_UNSIGNED_BYTE, reinterpret_cast<const GLvoid*>(w * h)); glBindTexture(GL_TEXTURE_2D, _yuvTex[1]); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, w / 2, h / 2, 0, GL_RED, GL_UNSIGNED_BYTE, reinterpret_cast<const GLvoid*>(w * h + w * h / 4)); shaderInput = 2; break; default: qFatal("unknown pixel format %d", _frame->pixelFormat); break; } glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0); glBindTexture(GL_TEXTURE_2D, _frameTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB10_A2, w, h, 0, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, NULL); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _frameTex, 0); glDisable(GL_DEPTH_TEST); glViewport(0, 0, w, h); glUseProgram(_colorConvPrg.programId()); _colorConvPrg.setUniformValue("rgb_tex", 0); _colorConvPrg.setUniformValue("yuv_tex0", 0); _colorConvPrg.setUniformValue("yuv_tex1", 0); _colorConvPrg.setUniformValue("yuv_tex2", 0); _colorConvPrg.setUniformValue("shader_input", shaderInput); if (shaderInput != 0) { switch (_frame->yCbCrColorSpace) { case QVideoSurfaceFormat::YCbCr_Undefined: // XXX: seems to be used when in doubt!? case QVideoSurfaceFormat::YCbCr_BT601: _colorConvPrg.setUniformValue("yuv_value_range_8bit_mpeg", true); _colorConvPrg.setUniformValue("yuv_709", false); break; case QVideoSurfaceFormat::YCbCr_BT709: _colorConvPrg.setUniformValue("yuv_value_range_8bit_mpeg", true); _colorConvPrg.setUniformValue("yuv_709", true); break; case QVideoSurfaceFormat::YCbCr_xvYCC601: _colorConvPrg.setUniformValue("yuv_value_range_8bit_mpeg", false); _colorConvPrg.setUniformValue("yuv_709", false); break; case QVideoSurfaceFormat::YCbCr_xvYCC709: _colorConvPrg.setUniformValue("yuv_value_range_8bit_mpeg", false); _colorConvPrg.setUniformValue("yuv_709", true); break; default: qFatal("unknown YCbCr color space"); break; } } glActiveTexture(GL_TEXTURE0); if (shaderInput == 0) { glBindTexture(GL_TEXTURE_2D, _rgbTex); } else { glBindTexture(GL_TEXTURE_2D, _yuvTex[0]); if (shaderInput == 2) { _colorConvPrg.setUniformValue("yuv_tex1", 1); _colorConvPrg.setUniformValue("yuv_tex2", 2); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, _yuvTex[1]); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, _yuvTex[2]); } } glBindVertexArray(_quadVao); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindTexture(GL_TEXTURE_2D, _frameTex); if (!_screen.isPlanar) glGenerateMipmap(GL_TEXTURE_2D); _frameIsNew = false; } } void QVRVideoPlayer::render(QVRWindow* /* w */, const QVRRenderContext& context, const unsigned int* textures) { for (int view = 0; view < context.viewCount(); view++) { // Get view dimensions int width = context.textureSize(view).width(); int height = context.textureSize(view).height(); // Set up framebuffer object to render into if (!_screen.isPlanar) { glBindTexture(GL_TEXTURE_2D, _depthTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } glBindFramebuffer(GL_FRAMEBUFFER, _viewFbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[view], 0); // Set up view glViewport(0, 0, width, height); glClear(_screen.isPlanar ? GL_COLOR_BUFFER_BIT : (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); QMatrix4x4 projectionMatrix = context.frustum(view).toMatrix4x4(); QMatrix4x4 viewMatrix = context.viewMatrix(view); // Set up stereo layout enum VideoFrame::StereoLayout stereoLayout = _frame->stereoLayout; if (stereoLayout == VideoFrame::Layout_Unknown) { if (_frame->aspectRatio > 3.0f) stereoLayout = VideoFrame::Layout_Left_Right; else if (_frame->aspectRatio < 1.0f) stereoLayout = VideoFrame::Layout_Top_Bottom; } float frameAspectRatio = _frame->aspectRatio; float viewOffsetX = 0.0f; float viewFactorX = 1.0f; float viewOffsetY = 0.0f; float viewFactorY = 1.0f; switch (stereoLayout) { case VideoFrame::Layout_Unknown: // assume it is Mono case VideoFrame::Layout_Mono: // nothing to do break; case VideoFrame::Layout_Top_Bottom: viewFactorY = 0.5f; viewOffsetY = (context.eye(view) == QVR_Eye_Right ? 0.5f : 0.0f); frameAspectRatio *= 2.0f; break; case VideoFrame::Layout_Top_Bottom_Half: viewFactorY = 0.5f; viewOffsetY = (context.eye(view) == QVR_Eye_Right ? 0.5f : 0.0f); break; case VideoFrame::Layout_Bottom_Top: viewFactorY = 0.5f; viewOffsetY = (context.eye(view) != QVR_Eye_Right ? 0.5f : 0.0f); frameAspectRatio *= 2.0f; break; case VideoFrame::Layout_Bottom_Top_Half: viewFactorY = 0.5f; viewOffsetY = (context.eye(view) != QVR_Eye_Right ? 0.5f : 0.0f); break; case VideoFrame::Layout_Left_Right: viewFactorX = 0.5f; viewOffsetX = (context.eye(view) == QVR_Eye_Right ? 0.5f : 0.0f); frameAspectRatio /= 2.0f; break; case VideoFrame::Layout_Left_Right_Half: viewFactorX = 0.5f; viewOffsetX = (context.eye(view) == QVR_Eye_Right ? 0.5f : 0.0f); break; case VideoFrame::Layout_Right_Left: viewFactorX = 0.5f; viewOffsetX = (context.eye(view) != QVR_Eye_Right ? 0.5f : 0.0f); frameAspectRatio /= 2.0f; break; case VideoFrame::Layout_Right_Left_Half: viewFactorX = 0.5f; viewOffsetX = (context.eye(view) != QVR_Eye_Right ? 0.5f : 0.0f); break; } // Set up correct aspect ratio on screen float relWidth = 1.0f; float relHeight = 1.0f; if (_screen.aspectRatio < frameAspectRatio) relHeight = _screen.aspectRatio / frameAspectRatio; else relWidth = frameAspectRatio / _screen.aspectRatio; // Set up shader program glUseProgram(_prg.programId()); _prg.setUniformValue("projection_model_view_matrix", projectionMatrix * viewMatrix); _prg.setUniformValue("view_offset_x", viewOffsetX); _prg.setUniformValue("view_factor_x", viewFactorX); _prg.setUniformValue("view_offset_y", viewOffsetY); _prg.setUniformValue("view_factor_y", viewFactorY); _prg.setUniformValue("relative_width", relWidth); _prg.setUniformValue("relative_height", relHeight); // Render scene glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, _frameTex); glBindVertexArray(_screenVao); glDrawElements(GL_TRIANGLES, _screen.indices.size(), GL_UNSIGNED_SHORT, 0); // Invalidate depth attachment (to help OpenGL ES performance) if (!_screen.isPlanar) { const GLenum fboInvalidations[] = { GL_DEPTH_ATTACHMENT }; glInvalidateFramebuffer(GL_FRAMEBUFFER, 1, fboInvalidations); } } } void QVRVideoPlayer::playlistNext() { if (_playlist->currentIndex() < _playlist->mediaCount() - 1) _playlist->next(); } void QVRVideoPlayer::playlistPrevious() { if (_playlist->currentIndex() > 0 && _player->position() < 5000) _playlist->previous(); else _playlist->setCurrentIndex(_playlist->currentIndex()); } void QVRVideoPlayer::seek(qint64 milliseconds) { _player->setPosition(_player->position() + milliseconds); } void QVRVideoPlayer::togglePause() { if (_player->state() == QMediaPlayer::PlayingState) _player->pause(); else if (_player->state() == QMediaPlayer::PausedState) _player->play(); } void QVRVideoPlayer::pause() { if (_player->state() == QMediaPlayer::PlayingState) _player->pause(); } void QVRVideoPlayer::play() { if (_player->state() == QMediaPlayer::PausedState) _player->play(); } void QVRVideoPlayer::toggleMute() { _player->setMuted(!_player->isMuted()); } void QVRVideoPlayer::changeVolume(int offset) { _player->setVolume(_player->volume() + offset); } void QVRVideoPlayer::stop() { _player->stop(); } void QVRVideoPlayer::keyPressEvent(const QVRRenderContext& /* context */, QKeyEvent* event) { switch (event->key()) { case Qt::Key_Escape: case Qt::Key_Q: case Qt::Key_MediaStop: stop(); break; case Qt::Key_Space: case Qt::Key_MediaTogglePlayPause: togglePause(); break; case Qt::Key_MediaPause: pause(); break; case Qt::Key_MediaPlay: play(); break; case Qt::Key_P: case Qt::Key_MediaPrevious: playlistPrevious(); break; case Qt::Key_N: case Qt::Key_MediaNext: playlistNext(); break; case Qt::Key_M: case Qt::Key_VolumeMute: toggleMute(); break; case Qt::Key_VolumeDown: changeVolume(-5); break; case Qt::Key_VolumeUp: changeVolume(+5); break; case Qt::Key_Left: seek(-10000); break; case Qt::Key_Right: seek(+10000); break; case Qt::Key_Down: seek(-60000); break; case Qt::Key_Up: seek(+60000); break; case Qt::Key_PageDown: seek(-600000); break; case Qt::Key_PageUp: seek(+600000); break; } } int main(int argc, char* argv[]) { QGuiApplication app(argc, argv); QGuiApplication::setApplicationName("qvr-videoplayer"); QVRManager manager(argc, argv); isGLES = (QOpenGLContext::openGLModuleType() == QOpenGLContext::LibGLES); /* Process command line */ Screen screen( QVector3D(-16.0f / 9.0f, -1.0f + QVRObserverConfig::defaultEyeHeight, -8.0f), QVector3D(+16.0f / 9.0f, -1.0f + QVRObserverConfig::defaultEyeHeight, -8.0f), QVector3D(-16.0f / 9.0f, +1.0f + QVRObserverConfig::defaultEyeHeight, -8.0f)); QMediaPlaylist playlist; if (QVRManager::processIndex() == 0) { QCommandLineParser parser; parser.setApplicationDescription("QVR video player"); parser.addHelpOption(); parser.addVersionOption(); parser.addPositionalArgument("video...", "Video file(s) to play."); parser.addOptions({ { { "l", "loop" }, "Loop playlist." }, { { "s", "screen" }, "Set screen geometry.", "screen" }, }); parser.process(app); QStringList posArgs = parser.positionalArguments(); if (posArgs.length() == 0) { QFile file(":logo.mp4"); QTemporaryFile* tmpFile = QTemporaryFile::createNativeFile(file); playlist.addMedia(QUrl::fromLocalFile(tmpFile->fileName())); playlist.setPlaybackMode(QMediaPlaylist::Loop); } else { for (int i = 0; i < posArgs.length(); i++) { QUrl url(posArgs[i]); if (url.isRelative()) { QFileInfo videoFileInfo(posArgs[i]); if (videoFileInfo.exists()) { url = QUrl::fromLocalFile(videoFileInfo.canonicalFilePath()); } else { qCritical("File does not exist: %s", qPrintable(posArgs[i])); return 1; } } qInfo("Adding to playlist: %s", qPrintable(url.toDisplayString())); playlist.addMedia(url); } } if (parser.isSet("loop")) { qInfo("Setting playlist to loop mode"); playlist.setPlaybackMode(QMediaPlaylist::Loop); } if (parser.isSet("screen")) { QStringList paramList = parser.value("screen").split(','); float values[9]; if (paramList.length() == 9 && 9 == std::sscanf(qPrintable(parser.value("screen")), "%f,%f,%f,%f,%f,%f,%f,%f,%f", values + 0, values + 1, values + 2, values + 3, values + 4, values + 5, values + 6, values + 7, values + 8)) { screen = Screen( QVector3D(values[0], values[1], values[2]), QVector3D(values[3], values[4], values[5]), QVector3D(values[6], values[7], values[8])); } else if (paramList.length() == 2) { float ar; float ar2[2]; if (2 == std::sscanf(qPrintable(paramList[0]), "%f:%f", ar2 + 0, ar2 + 1)) { ar = ar2[0] / ar2[1]; } else if (1 != std::sscanf(qPrintable(paramList[0]), "%f", &ar)) { qCritical("Invalid aspect ratio %s", qPrintable(paramList[0])); return 1; } screen = Screen(paramList[1], ar); if (screen.indices.size() == 0) return 1; } else { qCritical("Invalid screen definition: %s", qPrintable(parser.value("screen"))); return 1; } } else { qInfo("Using default video screen"); } } /* First set the default surface format that all windows will use */ QSurfaceFormat format; if (isGLES) { format.setVersion(3, 0); } else { format.setProfile(QSurfaceFormat::CoreProfile); format.setVersion(3, 3); } QSurfaceFormat::setDefaultFormat(format); /* Then start QVR with your app */ QVRVideoPlayer qvrapp(screen, &playlist); if (!manager.init(&qvrapp)) { qCritical("Cannot initialize QVR manager"); return 1; } /* Enter the standard Qt loop */ return app.exec(); } <file_sep>#include "aabb.h" Aabb::Aabb(QVector3D a , QVector3D b , bool renderable , QVector3D color , QString name , QObject* parent): Drawable("AABB " + name.toStdString()) , QObject(parent) , _ab(BoundingBox( b.lengthSquared() > a.lengthSquared() ? a : b , b.lengthSquared() > a.lengthSquared() ? b : a )) , _name(name) { if (renderable) { _box = std::make_shared<Box>("AABB", std::vector<QVector3D> {a, b}, color); addChild(_box); } } BoundingBox Aabb::getBox() const { return BoundingBox( getModelMatrix() * _ab.a , getModelMatrix() * _ab.b ); } std::vector<QVector3D> Aabb::getAB() const { return { getModelMatrix() * _ab.a , getModelMatrix() * _ab.b }; } BVec Aabb::getOverlap(Aabb &aabb) const { BoundingBox box0 = getBox(); BoundingBox box1 = aabb.getBox(); bool overlapX = box0.b.x() > box1.a.x() && box1.b.x() > box0.a.x(); bool overlapY = box0.b.y() > box1.a.y() && box1.b.y() > box0.a.y(); bool overlapZ = box0.b.z() > box1.a.z() && box1.b.z() > box0.a.z(); return BVec(overlapX, overlapY, overlapZ); } Bound Aabb::boundsPoint(QVector3D point) const { BoundingBox box = getBox(); BoundAxis x = BoundAxis(point.x() >= box.a.x(), point.x() <= box.b.x()); BoundAxis y = BoundAxis(point.y() >= box.a.y(), point.y() <= box.b.y()); BoundAxis z = BoundAxis(point.z() >= box.a.z(), point.z() <= box.b.z()); return Bound({x, y, z}); } BVec Aabb::getContain(Aabb &aabb) const { BoundingBox box = aabb.getBox(); Bound a = boundsPoint(box.a); Bound b = boundsPoint(box.b); return BVec( (a.x.top && a.x.bottom && b.x.top && b.x.bottom) , (a.y.top && a.y.bottom && b.y.top && b.y.bottom) , (a.z.top && a.z.bottom && b.z.top && b.z.bottom) ); } bool Aabb::hasOverlap(Aabb &aabb) const { return getOverlap(aabb).all(); } void Aabb::glRender(QMatrix4x4 &vMatrix, QMatrix4x4 &pMatrix) { } void Aabb::setCollided(bool collided) { if (collided && _collided != collided) emit this->collided(); _collided = collided; if (_box) _box->setLines(!collided); } bool Aabb::isCollided() const { return _collided; } QString Aabb::getName() const { return _name; } bool Aabb::isObstacle() const { return _name.isEmpty(); } <file_sep># Meta set(AM_MULTI_CONFIG "FALSE") set(AM_PARALLEL "4") set(AM_VERBOSITY "") # Directories set(AM_CMAKE_SOURCE_DIR "/home/andrey/workspace/qvr/flying-things") set(AM_CMAKE_BINARY_DIR "/home/andrey/workspace/qvr/flying-things") set(AM_CMAKE_CURRENT_SOURCE_DIR "/home/andrey/workspace/qvr/flying-things") set(AM_CMAKE_CURRENT_BINARY_DIR "/home/andrey/workspace/qvr/flying-things") set(AM_CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE "") set(AM_BUILD_DIR "/home/andrey/workspace/qvr/flying-things/flying-things_autogen") set(AM_INCLUDE_DIR "/home/andrey/workspace/qvr/flying-things/flying-things_autogen/include") # Files set(AM_SOURCES "/home/andrey/workspace/qvr/flying-things/flying-things.cpp;/home/andrey/workspace/qvr/flying-things/geometries.cpp") set(AM_HEADERS "/home/andrey/workspace/qvr/flying-things/flying-things.hpp;/home/andrey/workspace/qvr/flying-things/geometries.hpp") set(AM_SETTINGS_FILE "/home/andrey/workspace/qvr/flying-things/CMakeFiles/flying-things_autogen.dir/AutogenOldSettings.txt") # Qt set(AM_QT_VERSION_MAJOR 5) set(AM_QT_MOC_EXECUTABLE "/usr/bin/moc") set(AM_QT_UIC_EXECUTABLE "") # MOC settings set(AM_MOC_SKIP "/home/andrey/workspace/qvr/flying-things/qrc_resources.cpp") set(AM_MOC_DEFINITIONS "QT_CORE_LIB;QT_GUI_LIB;QT_NO_DEBUG;QT_WIDGETS_LIB") set(AM_MOC_INCLUDES "/home/andrey/workspace/qvr/flying-things;/usr/include/qt;/usr/include/qt/QtWidgets;/usr/include/qt/QtGui;/usr/include/qt/QtCore;/usr/lib/qt/mkspecs/linux-g++;/usr/local/include;/usr/include;/usr/include/c++/8.3.0;/usr/include/c++/8.3.0/x86_64-pc-linux-gnu;/usr/include/c++/8.3.0/backward;/usr/lib/gcc/x86_64-pc-linux-gnu/8.3.0/include;/usr/lib/gcc/x86_64-pc-linux-gnu/8.3.0/include-fixed") set(AM_MOC_OPTIONS "") set(AM_MOC_RELAXED_MODE "") set(AM_MOC_MACRO_NAMES "Q_OBJECT;Q_GADGET;Q_NAMESPACE") set(AM_MOC_DEPEND_FILTERS "") set(AM_MOC_PREDEFS_CMD "/usr/bin/c++;-dM;-E;-c;/usr/share/cmake-3.14/Modules/CMakeCXXCompilerABI.cpp") <file_sep>#include <iostream> #include "box.h" Box::Box(std::string name, std::vector<QVector3D> box, QVector3D color): Drawable(name), _box(box), _color(color) { initBuffers(); Drawable::loadShader( ":vertex-shader.glsl" , ":fragment-shader_dbg.glsl" ); } void Box::initBuffers() { QVector3D k = _box.at(0); QVector3D l = _box.at(1); QVector3D p1 = QVector3D(k.x(), k.y(), k.z()); QVector3D p2 = QVector3D(k.x(), k.y(), l.z()); QVector3D p3 = QVector3D(l.x(), k.y(), l.z()); QVector3D p4 = QVector3D(l.x(), k.y(), k.z()); QVector3D p5 = QVector3D(k.x(), l.y(), k.z()); QVector3D p6 = QVector3D(k.x(), l.y(), l.z()); QVector3D p7 = QVector3D(l.x(), l.y(), l.z()); QVector3D p8 = QVector3D(l.x(), l.y(), k.z()); std::vector<QVector3D> vertices = { p1, p2 , p2, p3 , p3, p4 , p4, p1 , p5, p6 , p6, p7 , p7, p8 , p8, p5 , p1, p5 , p2, p6 , p3, p7 , p4, p8 }; QOpenGLExtraFunctions *f = QOpenGLContext::currentContext()->extraFunctions(); GLuint vao; f->glGenVertexArrays(1, &vao); f->glBindVertexArray(vao); GLuint vertexBuf; f->glGenBuffers(1, &vertexBuf); f->glBindBuffer(GL_ARRAY_BUFFER, vertexBuf); f->glBufferData(GL_ARRAY_BUFFER, GLsizeiptr (vertices.size() * sizeof(QVector3D)), vertices.data(), GL_STATIC_DRAW); f->glEnableVertexAttribArray(0); f->glVertexAttribPointer( 0,// attribute position in buffer 3,// size (number of items per vertex) GL_FLOAT,// data type GL_FALSE,// is normalised? 0,// stride nullptr// array buffer offset ); f->glBindVertexArray(0); f->glDeleteBuffers(1, &vertexBuf); _vertexCount = vertices.size(); setVao(vao); } void Box::glRender(QMatrix4x4 &vMatrix, QMatrix4x4 &pMatrix) { QOpenGLExtraFunctions *f = QOpenGLContext::currentContext()->extraFunctions(); QMatrix4x4 modelViewMatrix = vMatrix * getModelMatrix(); QOpenGLShaderProgram& prg = getShader(); prg.bind(); prg.setUniformValue("color", _color.x(), _color.y(), _color.z()); prg.setUniformValue("model_view_matrix", modelViewMatrix); prg.setUniformValue("projection_model_view_matrix", pMatrix * modelViewMatrix); prg.setUniformValue("normal_matrix", modelViewMatrix.normalMatrix()); f->glBindVertexArray(getVao()); f->glDrawArrays(_drawLines ? GL_LINES : GL_TRIANGLE_STRIP, 0, _vertexCount); prg.release(); } void Box::setLines(bool lines) { _drawLines = lines; } <file_sep>file(REMOVE_RECURSE "qvr-example-opengl_autogen" "CMakeFiles/qvr-example-opengl_autogen.dir/AutogenOldSettings.txt" "qrc_resources.cpp" "CMakeFiles/qvr-example-opengl.dir/qvr-example-opengl_autogen/mocs_compilation.cpp.o" "CMakeFiles/qvr-example-opengl.dir/geometries.cpp.o" "CMakeFiles/qvr-example-opengl.dir/qvr-example-opengl.cpp.o" "CMakeFiles/qvr-example-opengl.dir/qrc_resources.cpp.o" "qvr-example-opengl.pdb" "qvr-example-opengl" ) # Per-language clean rules from dependency scanning. foreach(lang CXX) include(CMakeFiles/qvr-example-opengl.dir/cmake_clean_${lang}.cmake OPTIONAL) endforeach() <file_sep>/* * Copyright (C) 2016, 2017, 2018 Computer Graphics Group, University of Siegen * Written by <NAME> <<EMAIL>> * * 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. */ #include <QApplication> #include <QKeyEvent> #include <qvr/manager.hpp> #include "flying-things.hpp" #include "geometries.hpp" FlyingThings::FlyingThings() : _wantExit(false), _pause(false), _elapsedTime(0), _ringRotationAngle(0.0f), _objectRotationAngle(0.0f), _objects(400), _objectLOD(7), _objectType(3), _wireframe(false), _frustumCulling(false), _backfaceCulling(false), _distanceLOD(false) { _timer.start(); } bool FlyingThings::initProcess(QVRProcess* /* p */) { // Qt-based OpenGL function pointers initializeOpenGLFunctions(); // Framebuffer object glGenFramebuffers(1, &_fbo); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); glGenTextures(1, &_fboDepthTex); glBindTexture(GL_TEXTURE_2D, _fboDepthTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1, 1, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, _fboDepthTex, 0); // VAOs and associated buffers for (int i = 0; i < 4; i++) { glGenVertexArrays(18, _vaos[i]); for (int l = 0; l < 18; l++) { int objectLOD = 8 + l * 2; std::vector<float> positions; std::vector<float> normals; std::vector<float> texcoords; std::vector<unsigned int> indices; if (i == 0) geom_sphere(positions, normals, texcoords, indices, objectLOD, objectLOD / 2); else if (i == 1) geom_cylinder(positions, normals, texcoords, indices, objectLOD); else if (i == 2) geom_cone(positions, normals, texcoords, indices, objectLOD, objectLOD / 2); else geom_torus(positions, normals, texcoords, indices, 0.4f, objectLOD, objectLOD); glBindVertexArray(_vaos[i][l]); GLuint positionBuf; glGenBuffers(1, &positionBuf); glBindBuffer(GL_ARRAY_BUFFER, positionBuf); glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(float), positions.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); GLuint normalBuf; glGenBuffers(1, &normalBuf); glBindBuffer(GL_ARRAY_BUFFER, normalBuf); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(float), normals.data(), GL_STATIC_DRAW); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(1); GLuint indexBuf; glGenBuffers(1, &indexBuf); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuf); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), indices.data(), GL_STATIC_DRAW); _vaoIndices[i][l] = indices.size(); } } // Shader program _prg.addShaderFromSourceFile(QOpenGLShader::Vertex, ":vertex-shader.glsl"); _prg.addShaderFromSourceFile(QOpenGLShader::Fragment, ":fragment-shader.glsl"); _prg.link(); return true; } static float frand() // return random number in [0,1] { return qrand() / static_cast<float>(RAND_MAX); } void FlyingThings::render(QVRWindow* /* w */, const QVRRenderContext& context, const unsigned int* textures) { // Initialize random number generator to fixed value so that all processes // will generate the same pseudo random number sequence for all frames. qsrand(42); for (int view = 0; view < context.viewCount(); view++) { // Get view dimensions int width = context.textureSize(view).width(); int height = context.textureSize(view).height(); // Set up framebuffer object to render into glBindTexture(GL_TEXTURE_2D, _fboDepthTex); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glBindFramebuffer(GL_FRAMEBUFFER, _fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[view], 0); // Set up view glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); QMatrix4x4 projectionMatrix = context.frustum(view).toMatrix4x4(); QMatrix4x4 viewMatrix = context.viewMatrix(view); // Set up shader program glUseProgram(_prg.programId()); _prg.setUniformValue("projection_matrix", projectionMatrix); glEnable(GL_DEPTH_TEST); if (_backfaceCulling) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, _wireframe ? GL_LINE : GL_FILL); // TODO: Compute normals of view frustum for frustum culling const QVRFrustum& frustum = context.frustum(view); QVector3D nTop = QVector3D(0.0f, frustum.nearPlane(), frustum.topPlane()).normalized(); QVector3D nBottom = QVector3D(0.0f, 0.0f, 0.0f); // TODO QVector3D nRight = QVector3D(0.0f, 0.0f, 0.0f); // TODO QVector3D nLeft = QVector3D(0.0f, 0.0f, 0.0f); // TODO // Render for (int i = 0; i < _objects; i++) { // Compute model matrix QMatrix4x4 modelMatrix; modelMatrix.translate(-2.0f, 1.6f, 0.0f); modelMatrix.rotate(_ringRotationAngle + frand() * 360.0f, 0.0f, -1.0f, 0.0f); modelMatrix.translate(2.5f, 0.0f, 0.0f); modelMatrix.rotate(frand() * 360.0f, 0.0f, 0.0f, 1.0f); modelMatrix.translate(0.5f - frand(), 0.0f, 0.0f); modelMatrix.rotate(_objectRotationAngle + frand() * 360.0f, QVector3D(frand(), frand(), frand())); modelMatrix.scale(0.1f); // Computer Bounding Sphere IN VIEW COORDINATES QVector3D boundingSphereCenter = (viewMatrix * modelMatrix).column(3).toVector3D(); float boundingSphereRadius = 0.1f; // TODO: Apply culling bool cull = false; if (_frustumCulling) { if (boundingSphereCenter.z() > (-frustum.nearPlane() + boundingSphereRadius)) { // near plane cull = true; } else if (false /* TODO */) { // far plane cull = true; } else if (false /* TODO */) { // top plane cull = true; } else if (false /* TODO */) { // bottom plane cull = true; } else if (false /* TODO */) { // right plane cull = true; } else if (false /* TODO */) { // left plane cull = true; } } // TODO: Apply LOD int lod = _objectLOD; if (_distanceLOD) { float distance = boundingSphereCenter.length(); // TODO: lod = ...; } // Determine object type int type = _objectType; if (type == 4) type = i % 4; // Set color QVector3D color = QVector3D(0.2f + 0.8f * frand(), 0.2f + 0.8f * frand(), 0.2f + 0.8f * frand()); _prg.setUniformValue("color", color); // Render if (!cull) { QMatrix4x4 modelViewMatrix = viewMatrix * modelMatrix; _prg.setUniformValue("modelview_matrix", modelViewMatrix); _prg.setUniformValue("normal_matrix", modelViewMatrix.normalMatrix()); glBindVertexArray(_vaos[type][lod]); glDrawElements(GL_TRIANGLES, _vaoIndices[type][lod], GL_UNSIGNED_INT, 0); } } } } void FlyingThings::update(const QList<QVRObserver*>&) { if (_pause) { if (_timer.isValid()) { _elapsedTime += _timer.elapsed(); _timer.invalidate(); } } else { if (!_timer.isValid()) { _timer.start(); } float seconds = (_elapsedTime + _timer.elapsed()) / 1000.0f; _ringRotationAngle = seconds * 20.0f; _objectRotationAngle = seconds * 10.0f; } } bool FlyingThings::wantExit() { return _wantExit; } void FlyingThings::serializeDynamicData(QDataStream& ds) const { ds << _ringRotationAngle << _objectRotationAngle << _objects << _objectType << _wireframe << _frustumCulling << _backfaceCulling << _distanceLOD; } void FlyingThings::deserializeDynamicData(QDataStream& ds) { ds >> _ringRotationAngle >> _objectRotationAngle >> _objects >> _objectType >> _wireframe >> _frustumCulling >> _backfaceCulling >> _distanceLOD; } void FlyingThings::keyPressEvent(const QVRRenderContext& /* context */, QKeyEvent* event) { switch (event->key()) { case Qt::Key_Escape: _wantExit = true; break; case Qt::Key_Space: _pause = !_pause; break; case Qt::Key_Plus: if (_objects < 5120) _objects *= 2; break; case Qt::Key_Minus: if (_objects > 1) _objects /= 2; break; case Qt::Key_Greater: if (_objectLOD < 17) _objectLOD++; break; case Qt::Key_Less: if (_objectLOD > 0) _objectLOD--; break; case Qt::Key_T: _objectType++; if (_objectType > 4) _objectType = 0; break; case Qt::Key_P: _wireframe = !_wireframe; break; case Qt::Key_F: _frustumCulling = !_frustumCulling; break; case Qt::Key_B: _backfaceCulling = !_backfaceCulling; break; case Qt::Key_L: _distanceLOD = !_distanceLOD; break; } } int main(int argc, char* argv[]) { QApplication app(argc, argv); QVRManager manager(argc, argv); /* First set the default surface format that all windows will use */ QSurfaceFormat format; format.setProfile(QSurfaceFormat::CoreProfile); format.setVersion(3, 3); QSurfaceFormat::setDefaultFormat(format); /* Then start QVR with the app */ FlyingThings qvrapp; if (!manager.init(&qvrapp)) { qCritical("Cannot initialize QVR manager"); return 1; } /* Enter the standard Qt loop */ return app.exec(); } <file_sep>/* * Copyright (C) 2016, 2017 Computer Graphics Group, University of Siegen * Written by <NAME> <<EMAIL>> * * 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. */ #ifndef QVR_EVENT_HPP #define QVR_EVENT_HPP #include <QKeyEvent> #include <QMouseEvent> #include <QWheelEvent> #include <QMatrix4x4> #include "device.hpp" #include "rendercontext.hpp" class QDataStream; typedef enum { QVR_Event_KeyPress, QVR_Event_KeyRelease, QVR_Event_MouseMove, QVR_Event_MousePress, QVR_Event_MouseRelease, QVR_Event_MouseDoubleClick, QVR_Event_Wheel, QVR_Event_DeviceButtonPress, QVR_Event_DeviceButtonRelease, QVR_Event_DeviceAnalogChange } QVREventType; class QVREvent { public: QVREventType type; QVRRenderContext context; QKeyEvent keyEvent; QMouseEvent mouseEvent; QWheelEvent wheelEvent; QVRDeviceEvent deviceEvent; QVREvent(); QVREvent(QVREventType t, const QVRRenderContext& c, const QKeyEvent& e); QVREvent(QVREventType t, const QVRRenderContext& c, const QMouseEvent& e); QVREvent(QVREventType t, const QVRRenderContext& c, const QWheelEvent& e); QVREvent(QVREventType t, const QVRDeviceEvent& e); }; QDataStream &operator<<(QDataStream& ds, const QVREvent& e); QDataStream &operator>>(QDataStream& ds, QVREvent& e); #endif <file_sep>/* * Copyright (C) 2017 Computer Graphics Group, University of Siegen * Written by <NAME> <<EMAIL>> * * 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. */ #ifndef QVR_VIDEOPLAYER_HPP #define QVR_VIDEOPLAYER_HPP #include <QOpenGLExtraFunctions> #include <QOpenGLShaderProgram> class QMediaPlaylist; class QMediaPlayer; class VideoSurface; class VideoFrame; #include <qvr/app.hpp> #include "screen.hpp" class QVRVideoPlayer : public QVRApp, protected QOpenGLExtraFunctions { public: QVRVideoPlayer(const Screen& screen, QMediaPlaylist* playlist); private: /* Data not directly relevant for rendering */ bool _wantExit; QMediaPlaylist* _playlist; QMediaPlayer* _player; VideoSurface* _surface; /* Static data for rendering, initialized on the master process */ Screen _screen; /* Static data for rendering, initialized in initProcess() */ unsigned int _fbo; unsigned int _pbo; unsigned int _rgbTex; unsigned int _yuvTex[3]; unsigned int _quadVao; QOpenGLShaderProgram _colorConvPrg; unsigned int _viewFbo; unsigned int _depthTex; unsigned int _frameTex; unsigned int _screenVao; QOpenGLShaderProgram _prg; /* Dynamic data for rendering */ VideoFrame* _frame; bool _frameIsNew; /* Interaction functions */ void playlistNext(); void playlistPrevious(); void seek(qint64 milliseconds); void togglePause(); void pause(); void play(); void toggleMute(); void changeVolume(int offset); void stop(); public: void serializeStaticData(QDataStream& ds) const override; void deserializeStaticData(QDataStream& ds) override; void serializeDynamicData(QDataStream& ds) const override; void deserializeDynamicData(QDataStream& ds) override; bool wantExit() override; bool initProcess(QVRProcess* p) override; void preRenderProcess(QVRProcess* p) override; void render(QVRWindow* w, const QVRRenderContext& c, const unsigned int* textures) override; void keyPressEvent(const QVRRenderContext& context, QKeyEvent* event) override; }; #endif
83c97e8cde9e0cfd0ba13c7467fe62ec489da9fa
[ "Makefile", "CMake", "C++" ]
37
C++
insonifi/vr-maze
15093b4b3ff0e7df970cc83315c016b43f67b257
70a9f92a1cc6d0dc8e99e0892a7694dea51edadd
refs/heads/master
<repo_name>mpurohit88/express-uploader<file_sep>/build/precache-manifest.1619a51b3ba68be19578440bc5c10748.js self.__precacheManifest = [ { "revision": "c5a1ea7d33ba65bd928b9c578328518a", "url": "/static/media/logo2.c5a1ea7d.png" }, { "revision": "ff853f5222254ee75e5b", "url": "/static/css/main.1b0e070c.chunk.css" }, { "revision": "fdfcfda2d9b1bf31db52", "url": "/static/js/runtime~main.c5541365.js" }, { "revision": "99fd5c49f66aefe02908fffb0bc9d0e9", "url": "/static/media/digi.99fd5c49.jpg" }, { "revision": "e3125adfb9b03b6d611e", "url": "/static/js/2.25fe3926.chunk.js" }, { "revision": "f74005b6e0bd52003f6197e08726ea1e", "url": "/static/media/CALogo.f74005b6.png" }, { "revision": "02674537535001827ed67d83cf420aee", "url": "/static/media/banner-bg.02674537.jpg" }, { "revision": "ba3d8c2a29499e3690b16b1e31c7c8bd", "url": "/static/media/cta-bg-img.ba3d8c2a.jpg" }, { "revision": "8f4583673b91e580b0e4958b5d7a0196", "url": "/static/media/slide-bg-2.8f458367.jpg" }, { "revision": "956c4b1d7b2ee350663fcf01aaf4fefa", "url": "/static/media/slide-bg-3.956c4b1d.jpg" }, { "revision": "fa7d963f2f34aeb40dc09d208f00a8e8", "url": "/static/media/slide-bg-1.fa7d963f.jpg" }, { "revision": "5e21238dc532def29a390680c75636c0", "url": "/static/media/video.5e21238d.jpg" }, { "revision": "0e00b0022cd432171f67614319459460", "url": "/static/media/logo.0e00b002.png" }, { "revision": "ff853f5222254ee75e5b", "url": "/static/js/main.82faccb8.chunk.js" }, { "revision": "499bdb391a8e1f54dc0bc218b23a334f", "url": "/static/media/rakeshGupta.499bdb39.jpg" }, { "revision": "fd924c2c57d4b45fd5604d0dae9679e6", "url": "/static/media/sekharnigam.fd924c2c.jpg" }, { "revision": "26ade050dfb9966633e3888e241e9662", "url": "/static/media/ajaygupta.26ade050.jpg" }, { "revision": "2aaaa3643bea91fc4437a1e0a6405ed9", "url": "/static/media/PankajKumpawat.2aaaa364.jpg" }, { "revision": "8a047627d1df3f480f2b9812ab6817a6", "url": "/static/media/kcagarwal.8a047627.png" }, { "revision": "cc774255254ecea28bf470a871f48259", "url": "/static/media/founder11.cc774255.png" }, { "revision": "9d27f8849ec800c3a0e2c726106aa1f1", "url": "/static/media/founder22.9d27f884.png" }, { "revision": "0fd6505516102cc12101d5d0d571fcee", "url": "/static/media/efforts.0fd65055.jpg" }, { "revision": "a4dc1cb4f4b25253461b138dacbea51a", "url": "/static/media/enterpreniourship.a4dc1cb4.jpg" }, { "revision": "015f1e990102d4e6235e350f6d775a9f", "url": "/static/media/successful.015f1e99.jpg" }, { "revision": "e3125adfb9b03b6d611e", "url": "/static/css/2.3ad3650c.chunk.css" }, { "revision": "282a8586d4d37e708874839128430e0c", "url": "/index.html" } ];
170146699c72cf65ae550b618893bd005011e144
[ "JavaScript" ]
1
JavaScript
mpurohit88/express-uploader
9a6d41a0559a580e506f9ae27ff1a88770f7b67a
0d0a71e029532aabf09b38bbfe4d550858d83499
refs/heads/master
<file_sep>//Dependencies - default var express = require('express'); var bodyParser = require('body-parser'); var cors = require('cors'); var morgan = require('morgan'); var mongoose = require('mongoose'); var session = require('express-session'); var passport = require('passport'); var GoogleStrategy = require('passport-google-oauth20').Strategy; //controllers var userInfo = require('./controllers/userInfoCtrl.js'); //Express - default var app = express(); var port = 8080; require('./config/passport-google.js')(passport,app); //database var mongoUri = 'mongodb://admin:<EMAIL>:27145/mymoodwall'; mongoose.connect(mongoUri); mongoose.connection.once('open',function(){ console.log('Connection to mongoDB in mlab is successful'); }); //dataBase rules var User = require('./models/user.model.js'); //middleware - default app.use(express.static('public')); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(cors()); app.use(morgan('combined')); app.get('/success',function(req,res){ res.status(200).json(req.user); }); app.get('/failure',function(req,res){ res.status(500).json('error'); }); //endpoint app.get('/userInfo/:id', userInfo.read); //Connection app.listen(port,function(){ console.log('Node is looping on port ' + port); }); // s%3A9r7FCEiuWc1ZANdhjtkSjV9grkG7mhx7.qq7mP16UhrV%2FeVF2zZV7DSnL1RzSAoNeM7GIP5jgq%2Bc //s%3AE1pm_i0NTIYsuLYbinbGYUYFUK0A4Qz5.%2BONAAi2qw97rnKJB3ZYLbXovi%2Bk4M<KEY>Gik <file_sep>angular .module("myApp") .controller('wallCtrl',function($scope,wallService, $stateParams){ $scope.test = "angular is connected"; //get me data per product ID $scope.userId = function(){ console.log($stateParams.id); wallService.getUserInfo($stateParams.id) .then(function(response){ $scope.user = response; console.log( response); })// .then promise }//productsData function $scope.userId(); });// <file_sep>$(document).ready(function() { $( "p" ).hide() // setTimeout(function(){ // $('img').animateCss('bounceInDown') // }, 2000); });​ // $(function() { // // code here // }); <file_sep>angular .module('myApp') .service('natureServices',function($http){ this.getDataFromServer = function(search){ search = "earth + north america + clips"; var baseUrl = 'https://www.googleapis.com/youtube/v3'; return $http.get(baseUrl+'/search?part=snippet&key=<KEY>&maxResults=7&q='+search) .then(function(response){ console.log(response); return response.data.items.map(function(item){ return "http://www.youtube.com/embed/"+item.id.videoId; }); }); }; });//service <file_sep>angular .module("myApp") .service('wallService',function($http){ this.getUserInfo = function(id){ return $http.get('/userInfo/'+id) .then(function(response){ console.log(response); return response.data; }); } }); <file_sep>var User = require('../models/user.model.js'); module.exports= { read: function(req,res) { console.log(req.params); console.log(req.params.id); User.findById(req.params.id) .exec(function(err, result) { console.log(err, result); if (err) return res.status(500).send(err); res.send(result); }); },//get product ID }//exports
cd8c7c475d36dfbac9e5d3e6665afc882198386d
[ "JavaScript" ]
6
JavaScript
vijaypatha/mymoodwall
c69333dee7a65141a8d77a82825d0418e9bbb159
9aae11a62ada125b020008273a78e673dfbe1e0f
refs/heads/main
<repo_name>slteksystemsllc/logstash<file_sep>/automated_install.sh #!/bin/bash cd /opt/ sudo apt-get update -y && sudo apt-get upgrade -y sudo apt-get install -y wget sudo wget https://raw.githubusercontent.com/slteksystemsllc/logstash/main/scripts/prereq.sh && sudo bash prereq.sh sudo wget https://raw.githubusercontent.com/slteksystemsllc/logstash/main/scripts/initialize.sh && sudo bash initialize.sh cd /usr/share/logstash/ docker-compose up --no-start <file_sep>/README.md # Logstash Development and Test Enviroment Using Docker Container ## This is will install a Logstash docker container inside Ubuntu for configuration testing prior to moving configs into production. You can run this and test pipelines and configs to verify they work the way you expect prior to migrating into a rpoduction system. If you wish to just run a single container not utilizing he docker-compose.yml you can do so as well by doing something like this ``` sudo docker pull docker.elastic.co/logstash/logstash:7.9.2 ``` ``` sudo docker run -it --rm -v /opt/logstash.conf:/opt/logstash.conf docker.elastic.co/elasticsearch/elasticsearch:7.9.2 -f /opt/logstash.conf (replace logstash.conf with your logstash test config) ``` Example logstash.conf test file for pasting logs into logstash and seeing output on screen. Copy the following text into a file ``` sudo vi logstash.conf ``` paste the following into your text editor (vim in this case) ``` input { stdin { } } output { stdout { codec => rubydebug } } ``` Than run the config with logstash in the conatiner using the following command ``` sudo docker run -it --rm -v /opt/logstash.conf:/opt/logstash.conf docker.elastic.co/logstash/logstash:7.9.2 -f /opt/logstash.conf ``` This is really only for quick test etc. ### Initial Goal Make it simple to test and modify Logstash configurations and grok patterns as you test various logs using Docker to orchestrate. ## Prerequisites Assume you have a copy of Ubuntu 18.04 minimum insatalled. Have not tested this on other Linux distros but doesnt stop you from trying it out #Assumes you have downloaded and installed Ubuntu 18.04 minimum to start. Follow the rest of the steps below to configure and get up and running # Once Ubuntu is insalled run update and upgrade commands to update system ``` sudo apt-get update -y && sudo apt-get upgrade -y ``` # Install wget ``` sudo apt-get install -y wget ``` # Change to the working directory /opt ``` cd /opt ``` # Download the prerequisites script and run in bash ``` sudo wget https://raw.githubusercontent.com/slteksystemsllc/logstash/main/scripts/prereq.sh && sudo bash prereq.sh ``` # Download the initialization script and run in bash ``` sudo wget https://raw.githubusercontent.com/slteksystemsllc/logstash/main/scripts/initialize.sh && sudo bash initialize.sh ``` # Navigate to /usr/share/logstash/ and run the following command. This will start the stack in daemon mode. ``` cd /usr/share/logstash/ ``` ``` sudo docker-compose up -d ``` ## Or download this script and execute to do everything listed above in one shot ``` sudo wget https://raw.githubusercontent.com/slteksystemsllc/logstash/main/automated_install.sh ``` ``` sudo bash automated_install.sh ``` <file_sep>/scripts/initialize.sh #!/bin/bash cd /opt/ git clone https://github.com/slteksystemsllc/logstash.git ######################################################### # Logstash Pre-Config mkdir -p /usr/share/logstash/ mkdir -p /usr/share/logstash/bin/ mkdir -p /usr/share/logstash/config/ mkdir -p /usr/share/logstash/configs/ mkdir -p /usr/share/logstash/custom_patterns/ mkdir -p /usr/share/logstash/dictionaries/ mkdir -p /usr/share/logstash/persistent_data/ mkdir -p /usr/share/logstash/pipeline/ mkdir -p /usr/share/logstash/plugins/ mkdir -p /usr/share/logstash/rules/ sudo chown 1000:1000 -R /usr/share/logstash/ cp -r /opt/logstash/logstash/logstash_configs/* /usr/share/logstash/configs/ cp -r /opt/logstash/logstash/dictionaries/* /usr/share/logstash/dictionaries/ cp -f /opt/logstash/logstash/pipelines.yml.example /usr/share/logstash/config/pipelines.yml cp -r /opt/logstash/logstash/rules/* /usr/share/logstash/rules/ cp -f /opt/logstash/docker-compose.yml.example /usr/share/logstash/docker-compose.yml cd /usr/share/logstash/ docker-compose up --no-start
6776390be43002dfda7b702795be2db57660e410
[ "Markdown", "Shell" ]
3
Shell
slteksystemsllc/logstash
ae4cc5736f525baec4c50817792d63bdb6d8b13f
e7e59f6598c31ce17b1d1541b22203c1f413bf97
refs/heads/master
<file_sep># phalcon-test-helpers TestUnit base and mocking requests <file_sep><?php /** * Extends Phalcon's base class for functional tests * * @author <NAME> <<EMAIL>> * @since 1.0 */ namespace canis\phalcon\testing; use Phalcon\Test\FunctionalTestCase as BaseFunctionalTestCase; use Phalcon\Mvc\Application as PhApplication; class FunctionalTestCase extends BaseFunctionalTestCase { protected function setUp() { parent::setUp(); $this->di->setShared( 'router', function () { $router = new \Phalcon\Mvc\Router(); return $router; } ); $applicationClass = $this->getApplicationClass(); if (get_class($this->application) !== $applicationClass) { $this->application = new $applicationClass($this->di); } } protected function getApplicationClass() { return PhApplication::class; } protected function requestGet($path, $data = [], $additionalHeaders = []) { return $this->request('GET', $path, $data, $additionalHeaders); } protected function requestPost($path, $data = [], $additionalHeaders = []) { return $this->request('POST', $path, $data, $additionalHeaders); } protected function requestPut($path, $data = [], $additionalHeaders = []) { return $this->request('PUT', $path, $data, $additionalHeaders); } protected function requestPatch($path, $data = [], $additionalHeaders = []) { return $this->request('PATCH', $path, $data, $additionalHeaders); } protected function requestDelete($path, $data = [], $additionalHeaders = []) { return $this->request('DELETE', $path, $data, $additionalHeaders); } protected function requestHead($path, $data = [], $additionalHeaders = []) { return $this->request('HEAD', $path, $data, $additionalHeaders); } private function request($method, $path, $data = [], $additionalHeaders = []) { $headers = [ 'HTTP_HOST' => 'test.dev', 'REQUEST_METHOD' => strtoupper($method), 'REQUEST_URI' => $path ]; if ($method === 'GET') { $headers['QUERY_STRING'] = http_build_query($data); $_GET = $data; } elseif (is_array($data)) { $_POST = $data; } $_SERVER = array_merge($headers, $additionalHeaders); var_dump([$path, $headers]);exit; $this->dispatch($path); return $this->di->getShared('response'); } }
32e32df7e5a399e8926646553ac38482cf0ab4d3
[ "Markdown", "PHP" ]
2
Markdown
canis-io/phalcon-test-helpers
543d6777e1f6d4971a2f4291c14c4fe6b1728a3f
7c5a1c0475a2556ca2da3a9cc7a5b1c689ebc8fb
refs/heads/master
<file_sep>import sys import os curpath = os.path.abspath(os.path.dirname(__file__)) rootpath = os.path.split(curpath)[0] print(rootpath) sys.path.append(rootpath) import torch #import matplotlib import os #matplotlib.use('TkAgg') import matplotlib.pyplot as plt from PIL import Image import numpy as np import shutil import cv2 from src.models.resnext import make_model # we should change the txtpath get new classes list def getclasseslist(): classlist = [] txtpath = "/data/wujilong/datas/openImg/coarse_train_label.txt" with open(txtpath, "r") as f: lines = f.readlines() for line in lines: line = line.strip() classlist.append(line.split(":")[-1]) return classlist # to getmodel we shuold change the config/value_config numclass and pretrained # resulttxt, modelpath, picdir should change def main(): print('ASL Example Inference code on a single image') # parsing args resulttxt = "/data/wujilong/huangye/292_shinei.txt" modelpath = "/data/wujilong/model/ASL/model_292_9.pth" picdir = "/data/wujilong/huangye/室内/" if os.path.exists(resulttxt): os.remove(resulttxt) model = make_model("resnext50_32x4d") # setup model print('creating and loading the model...') state = torch.load(modelpath, map_location='cpu') model.load_state_dict(state) model.eval() model.cuda() classes_list = np.array(getclasseslist()) print('done\n') # doing inference names = os.listdir(picdir) for name in names: pic_path= os.path.join(picdir, name) print(pic_path) print('loading image and doing inference...') try: im = Image.open(pic_path).convert("RGB") im_resize = im.resize((224, 224)) np_img = np.array(im_resize, dtype=np.uint8) tensor_img = torch.from_numpy(np_img).permute(2, 0, 1).float() / 255.0 # HWC to CHW tensor_batch = torch.unsqueeze(tensor_img, 0).cuda() output = torch.squeeze(torch.sigmoid(model(tensor_batch))) np_output = output.cpu().detach().numpy() print(np_output.shape) detected_classes = classes_list[np_output > 0.5] print(detected_classes) except: os.remove(pic_path) continue objects = pic_path for object in detected_classes: objects += ",{}".format(object) with open(resulttxt, "a") as f4: f4.write(objects+"\n") print('done\n') print('showing image on screen...') print('done\n') if __name__ == '__main__': main()<file_sep>from .tresnet import TResnetM, TResnetL, TResnetXL,TResNet<file_sep>from torch.utils import data from config.value_config import * import os from src.helper_functions.helper_functions import CocoDetection import torchvision.transforms as transforms import torch key = LOADERNAME trainpath = os.path.join(DATAPATH, TRAINNAME) testpath = os.path.join(DATAPATH, TESTNAME) valpath = os.path.join(DATAPATH, VALNAME) num = CLSNUM def get_loader(): if key == "comslow": from dataloader.traindata import Traindata from dataloader.valdata import Testdata trainset = Traindata(trainpath, num) #testset = Traindata(trainpath, num) testset = Testdata(testpath, num) valset = Testdata(valpath, num) trainloader = data.DataLoader(trainset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=True, pin_memory=True) testloader = data.DataLoader(testset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=False, pin_memory=True) valloader = data.DataLoader(valset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=False, pin_memory=True) return trainloader, testloader, valloader if key == "coco": vpath = "/code/wujilong/coco/val2014_224x224" tpath = "/code/wujilong/coco/train2014_224x224" valfile = "/code/wujilong/coco/annotations/instances_val2014.json" tfile = "/code/wujilong/coco/annotations/instances_val2014.json" testset = CocoDetection(vpath, valfile, transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), # normalize, # no need, toTensor does normalization ])) valset = CocoDetection(vpath, valfile, transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), # normalize, # no need, toTensor does normalization ])) trainset = CocoDetection(tpath, tfile, transforms.Compose([ transforms.Resize((224, 224)), transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5), transforms.RandomHorizontalFlip(), transforms.RandomVerticalFlip(), # torchvision.transforms.RandomRotation(180, expand=False), transforms.RandomGrayscale(0.1), transforms.ToTensor(), # normalize, # no need, toTensor does normalization ])) trainloader = data.DataLoader(trainset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=True, pin_memory=True) testloader = data.DataLoader(testset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=False, pin_memory=False) valloader = data.DataLoader(valset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=False, pin_memory=False) return trainloader, testloader, valloader if key=="single": from dataloader.single_train import Traindata from dataloader.single_val import Testdata trainset = Traindata(trainpath) testset = Testdata(testpath) valset = Testdata(valpath) trainloader = data.DataLoader(trainset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=True, pin_memory=True) testloader = data.DataLoader(testset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=False, pin_memory=True) valloader = data.DataLoader(valset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=False, pin_memory=True) return trainloader, testloader, valloader if key=="multi_machine": from dataloader.traindata import Traindata from dataloader.valdata import Testdata trainset = Traindata(trainpath, num) testset = Testdata(testpath, num) valset = Testdata(valpath, num) trainsampler = torch.utils.data.distributed.DistributedSampler(trainset) trainloader = data.DataLoader(trainset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=False, pin_memory=True,sampler=trainsampler) testloader = data.DataLoader(testset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=False, pin_memory=True) valloader = data.DataLoader(valset, batch_size=BATCH_SIZE, num_workers=THREADS, shuffle=False, pin_memory=True) return trainsampler, trainloader, valloader else: print('[*]! the key error of dataloader!!!!!') if __name__ == "__main__": _, testloader,_ = get_loader() for i , data in enumerate(testloader): print(data[1]) <file_sep>import os from torch.nn import DataParallel from dataloader.loader_select import get_loader from config.value_config import * from src.models.model_select import getmodel import torch import time import numpy as np from torch.cuda.amp import GradScaler, autocast os.environ['CUDA_VISIBLE_DEVICES'] = GPUS os.makedirs(SAVEPATH, exist_ok=True) def eval_fuse(testloader, net, gpus): fuse_matrix = np.zeros((CLSNUM, CLSNUM)) net.eval() total_num = 0 acc = 0 for i, data in enumerate(testloader): with torch.no_grad(): if gpus>0: img, label = data[0].cuda(), data[1].cuda() else: img, label = data[0], data[1] total_num += img.size(0) #with autocast(): pre = net(img) _, prelabel = torch.max(pre, 1) for i in range(CLSNUM): for j in range(CLSNUM): fuse_matrix[i][j] += torch.sum((label.data==i)&(prelabel.data==j)).item() acc += torch.sum(prelabel.data == label.data) test_acc = float(acc)/total_num recalldic = {} precisiondic = {} for i in range(CLSNUM): t = fuse_matrix[i][i] prenum = np.sum(fuse_matrix[:, i]) num = np.sum(fuse_matrix[i,:]) recalldic[i] = t/num precisiondic[i] = t/prenum print(fuse_matrix) return test_acc, recalldic, precisiondic def displaymetric(recalldic, precisiondic): for key in recalldic.keys(): name = MAPLIST[key] print('[*]! {} recall is : {}'.format(name, recalldic[key])) for key in precisiondic.keys(): name = MAPLIST[key] print('[*]! {} precision is : {}'.format(name, precisiondic[key])) trainloader, testloader, valloader = get_loader() beg = time.time() net = getmodel() if LOADDING: net.load_state_dict(torch.load(WEIGHT, map_location='cpu')) net.cuda() if torch.cuda.device_count()>1: net = DataParallel(net) end = time.time() print('[*]! model load time is{}'.format(end-beg)) iters = len(trainloader) if not FINE: optimizer = torch.optim.SGD(net.parameters(), lr=LR, momentum=0.9, weight_decay=1e-4) for param in net.parameters(): print(param.requires_grad) print("User all param for optimizer") else: optimizer = torch.optim.SGD(filter(lambda p :p.requires_grad, net.parameters()), lr=LR, momentum=0.9, weight_decay=1e-4) print("User only param for optimizer") for param in net.parameters(): print(param.requires_grad) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 20, eta_min= 1e-8, last_epoch=-1) print('[*] train start !!!!!!!!!!!') best_acc = 0 best_epoch = 0 #scaler = GradScaler() for epoch in range(EPOCHS): net.train() train_loss = 0 total = 0 for i, data in enumerate(trainloader): img, label = data[0].cuda(non_blocking=True), data[1].cuda(non_blocking=True) batch_size = img.size(0) optimizer.zero_grad() pre = net(img) loss = torch.nn.CrossEntropyLoss()(pre, label) train_loss += loss * batch_size total += batch_size loss.backward() optimizer.step() scheduler.step() print('[*] epoch:{} - lr:{} - train loss: {:.3f}'.format(epoch, scheduler.get_last_lr()[0], train_loss/total)) acc, recalldic, precisiondic = eval_fuse(testloader, net, torch.cuda.device_count()) if acc > best_acc: best_acc = acc best_epoch = epoch os.makedirs(SAVEPATH, exist_ok=True) if torch.cuda.device_count() > 1: net_state_dict = net.module.state_dict() else: net_state_dict = net.state_dict() mdname = os.path.join(SAVEPATH, 'model_best.pth') if os.path.exists(mdname): os.remove(mdname) torch.save(net_state_dict, os.path.join(SAVEPATH, 'model_best.pth')) print('[*] change the best model') print('[*] epoch:{} - test acc: {:.3f} - best acc: {}_{}'.format(epoch, acc, best_epoch, best_acc)) displaymetric(recalldic, precisiondic) print('[*] training finished') <file_sep>python infer.py \ --dataset_type=OpenImages \ --model_name=tresnet_l \ --model_path=/data/wujilong/model/ASL/Open_ImagesV6_TRresNet_L_448.pth \ --pic_dir=/data/wujilong/buluo/运动 \ --input_size=448 \ --txt_path="/data/wujilong/datas/worddir/pretrain/buluo/运动.txt" \ --subdir="./ajukpics" <file_sep>from torch.utils import data import torchvision import os from PIL import Image import cv2 import torch class Testdata(data.Dataset): def __init__(self, txtpath, nclass): self.nclass = nclass self.txtpath = txtpath with open(txtpath, "r") as f: lines = f.readlines() self.picpaths = [] self.labels = [] for line in lines: line = line.strip() factors = line.split(',') self.picpaths.append(factors[0]) label = [] for j in range(1, len(factors)): label.append(int(factors[j])) self.labels.append(label) #self.picpaths = self.picpaths[:100] #self.labels = self.labels[:100] self.transforms = torchvision.transforms.Compose([ torchvision.transforms.Resize((224,224)), torchvision.transforms.ToTensor(), ]) def __len__(self): return len(self.picpaths) def __getitem__(self, index): picpath = self.picpaths[index] #label = self.labels[index] img = Image.open(picpath).convert('RGB') img = self.transforms(img) label = self.labels[index] target = torch.zeros(self.nclass, dtype=torch.long) for intx in label: target[intx] = 1 return img, target <file_sep># for data DATAPATH = "/data/wujilong/datas" TRAINNAME = "train_ajuke.txt" TESTNAME = "val_ajuke.txt" VALNAME = "val_ajuke.txt" LOADERNAME = "single" CLSNUM = 8 BATCH_SIZE = 64 THREADS = 16 # for model MODELNAME = "tres" #MODELNAME = "resnext50_32x4d" # for train LR=1e-4 LOADDING= False WEIGHT="" SAVEPATH="/data/wujilong/tres_nofine" SAVEFREQ = 1 THRESH = 0.8 STEPSAVEFREQ = 1 STEPDISFREQ = 1 EPOCHS = 100 DISFREQ = 1 GPUS='1' # for fintune PREMODEL = "/data/wujilong/model/ASL/Open_ImagesV6_TRresNet_L_448.pth" #PREMODEL = "/home/wujilong/.cache/torch/checkpoints/resnext50_32x4d-7cdf4587.pth" FINE = False MAPLIST=["写字楼-公共区", "写字楼-办公区", "卧室", "卫生间", "厨房", "客厅", "室外图", "阳台"] # for multi machine learning WORD_SIZE=2 RANK=0 DIST_URL = "tcp://localhost:10001" BACKEND="nccl" SEED=108 <file_sep>import torch from src.helper_functions.helper_functions import parse_args from src.loss_functions.losses import AsymmetricLoss, AsymmetricLossOptimized from src.models import create_model import argparse #import matplotlib import os #matplotlib.use('TkAgg') import matplotlib.pyplot as plt from PIL import Image import numpy as np import shutil import cv2 parser = argparse.ArgumentParser(description='ASL MS-COCO Inference on a single image') parser.add_argument('--model_path', type=str, default='./models_local/TRresNet_L_448_86.6.pth') parser.add_argument('--pic_dir', type=str, default='./pics/') parser.add_argument('--model_name', type=str, default='tresnet_l') parser.add_argument('--input_size', type=int, default=448) parser.add_argument('--dataset_type', type=str, default='MS-COCO') parser.add_argument('--th', type=float, default=0.95) parser.add_argument('--txt_path', type=str, default="./result.txt") parser.add_argument('--subdir', type=str, default="./pics") #parser.add_argument('--result_txt', type=str, default="./result.txt") def main(): print('ASL Example Inference code on a single image') # parsing args args = parse_args(parser) resulttxt = args.txt_path if os.path.exists(resulttxt): os.remove(resulttxt) # setup model print('creating and loading the model...') state = torch.load(args.model_path, map_location='cpu') args.num_classes = state['num_classes'] model = create_model(args).cuda() model.load_state_dict(state['model'], strict=True) model.eval() classes_list = np.array(list(state['idx_to_class'].values())) print('done\n') # doing inference os.makedirs(args.subdir, exist_ok=True) savedir = args.subdir dir = args.pic_dir if "jpg" not in os.listdir(dir)[0] and "jpeg" not in os.listdir(dir)[0] and "png" not in os.listdir(dir)[0]: subdirs = [] for subdir in os.listdir(dir): #if subdir not in ["单人","拍照","多人","其他","室内","无人","制图"]: subdirs.append(os.path.join(dir, subdir)) #subdirs = [os.path.join(dir, subdir) for subdir in os.listdir(dir)] else: subdirs = [dir] for subdir in subdirs: taglist = [] _, subdirname = os.path.split(subdir) names = os.listdir(subdir) for name in names: pic_path= os.path.join(subdir, name) print(pic_path) objects = pic_path os.makedirs(os.path.join(savedir, subdirname), exist_ok=True) savepath = os.path.join(savedir, subdirname, name) print('loading image and doing inference...') try: im = Image.open(pic_path).convert("RGB") im_resize = im.resize((args.input_size, args.input_size)) print(args.input_size) np_img = np.array(im_resize, dtype=np.uint8) tensor_img = torch.from_numpy(np_img).permute(2, 0, 1).float() / 255.0 # HWC to CHW tensor_batch = torch.unsqueeze(tensor_img, 0).cuda() output = torch.squeeze(torch.sigmoid(model(tensor_batch))) np_output = output.cpu().detach().numpy() detected_classes = classes_list[np_output > 0.95] except: os.remove(pic_path) continue print(len(classes_list)) for object in detected_classes: print(object) if object not in taglist: taglist.append(object) objects += ",{}".format(object) with open(resulttxt, "a") as f4: f4.write(objects+"\n") # img = cv2.imread(pic_path) # cv2.putText(img, objects, (25, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2) # cv2.imwrite(savepath, img) # savetxt = os.path.join(savedir, subdirname+".txt") # for obj in taglist: # with open(savetxt, "a") as f: # f.write("{}\n".format(obj)) print('done\n') print('showing image on screen...') print('done\n') if __name__ == '__main__': main() <file_sep>from .traindata import Traindata from .valdata import Testdata <file_sep># multi_label-classification- ### 工程环境 pytorch 环境 ### 工程入口 正常入口为 train.py文件 多机多卡入口为 train_multi_machine.py(超参LOADERNAME="multi_machine" 必须如此设置) coco标签数据入口 train_coco.py 单标签训练入口 train_single.py ### 超参定义 所有的超参定义在config/value_config文件中。 <file_sep>from config.value_config import MODELNAME, PREMODEL # import argparse # from src.models import create_model # from src.helper_functions.helper_functions import parse_args key = MODELNAME #key = "<KEY>" def getmodel(): if key == "<KEY>": from src.models.resnext import make_model model = make_model(key) return model if key == "finetun_tres": from src.models.finetun_tres import Tres if len(PREMODEL) == 0: print("Please add the premodel!!!!!!!!") model = Tres() for param in model.parameters(): param.requires_grad = False model.output.requires_grad_(True) return model if key == "tres": from src.models.finetun_tres import Tres if len(PREMODEL) == 0: print("Please add the premodel!!!!!!!!") model = Tres() return model else: print("[*]! model key is error!!!!!") if __name__ == "__main__": model = getmodel() for k , v in model.named_parameters(): print(v.requires_grad) <file_sep>import os import torch import torch.nn.parallel import torch.optim from torch.optim import lr_scheduler from src.helper_functions.helper_functions import mAP from src.models.model_select import getmodel from src.loss_functions.losses import AsymmetricLoss from config.value_config import * from dataloader.loader_select import get_loader from torch.cuda.amp import GradScaler, autocast from torch.nn import DataParallel os.environ["CUDA_VISIBLE_DEVICES"]=GPUS os.makedirs(SAVEPATH, exist_ok=True) def validate_multi(val_loader, model): print("starting validation") Sig = torch.nn.Sigmoid() preds_regular = [] targets = [] for i, (input, target) in enumerate(val_loader): target = target # compute output with torch.no_grad(): with autocast(): output_regular = Sig(model(input.cuda())).cpu() # for mAP calculation preds_regular.append(output_regular.cpu().detach()) targets.append(target.cpu().detach()) mAP_score_regular = mAP(torch.cat(targets).numpy(), torch.cat(preds_regular).numpy()) print("mAP score regular {:.2f}".format(mAP_score_regular)) return mAP_score_regular # Setup model print('creating model...') model = getmodel() if LOADDING: # make sure to load pretrained ImageNet model state = torch.load(WEIGHT, map_location='cpu') model.load_state_dict(state) print('done\n') # Data loading trainloader, testloader, valloader = get_loader() #ema = ModelEma(model, 0.9997) # 0.9997^641=0.82 if torch.cuda.device_count()>1: model = DataParallel(model) model.cuda() print("model is loadding!!!") # set optimizer steps_per_epoch = len(trainloader) criterion = AsymmetricLoss(gamma_neg=4, gamma_pos=1, clip=0.05, disable_torch_grad_focal_loss=True) if FINE: parameters = filter(lambda p :p.requires_grad, model.parameters()) else: parameters = model.parameters() optimizer = torch.optim.Adam(params=parameters, lr=LR, weight_decay=0) # true wd, filter_bias_and_bn scheduler = lr_scheduler.OneCycleLR(optimizer, max_lr=LR, steps_per_epoch=steps_per_epoch, epochs=EPOCHS, pct_start=0.2) highest_mAP = 0 #trainInfoList = [] scaler = GradScaler() print(len(trainloader)) print(len(testloader)) print("begin train ....") for epoch in range(EPOCHS): model.train() for i, (inputData, target) in enumerate(trainloader): inputData = inputData.cuda(non_blocking=True) target = target.cuda(non_blocking=True) # (batch,3,num_classes) # target = target.max(dim=1)[0] with autocast(): output = model(inputData) # sigmoid will be done in loss ! loss = criterion(output, target) model.zero_grad() #loss.backward() scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() #optimizer.step() scheduler.step() # store information if i%DISFREQ==0: print('Epoch [{}/{}], Step [{}/{}], LR {:.1e}, Loss: {:.1f}'.format(epoch, EPOCHS, str(i).zfill(3), str(steps_per_epoch).zfill(3), scheduler.get_last_lr()[0], loss.item())) if i%STEPSAVEFREQ == 0: try: torch.save(model.state_dict(), os.path.join(SAVEPATH, 'model-{}-{}.pth'.format(epoch + 1, i))) except: pass if i%STEPDISFREQ == 0: model.eval() mAP_score = validate_multi(valloader, model) print('ecpoch{} step {} current_mAP = {:.2f} '.format(epoch, i, mAP_score)) model.train() if epoch%SAVEFREQ == 0: try: torch.save(model.state_dict(), os.path.join(SAVEPATH, 'model-{}.pth'.format(epoch + 1))) except: pass model.eval() mAP_score = validate_multi(testloader, model) if mAP_score > highest_mAP: highest_mAP = mAP_score try: torch.save(model.state_dict(), os.path.join(SAVEPATH, 'model-highest.pth')) except: pass print('current_mAP = {:.2f}, highest_mAP = {:.2f}\n'.format(mAP_score, highest_mAP)) <file_sep>import torch import torchvision from config.value_config import * PREMODEL = "/home/wujilong/.cache/torch/checkpoints/resnext50_32x4d-7cdf4587.pth" def make_model(key): return ResNext(key) class ResNext(torch.nn.Module): def __init__(self, key): super(ResNext, self).__init__() backbone = torchvision.models.__dict__[key](pretrained=False) dict = torch.load(PREMODEL, map_location="cpu") backbone.load_state_dict(dict) self.layer0 = torch.nn.Sequential(backbone.conv1, backbone.bn1, backbone.relu, backbone.maxpool) self.layer1 = backbone.layer1 self.layer2 = backbone.layer2 self.layer3 = backbone.layer3 self.layer4 = backbone.layer4 self.avgpool = torch.nn.AdaptiveAvgPool2d(1) self.fc = torch.nn.Sequential( torch.nn.Dropout(p=0.5), torch.nn.Linear(in_features=self.layer4[-1].conv1.in_channels, out_features=8), ) pass def forward(self, x): x = self.layer0(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = self.avgpool(x) x = x.view(x.size(0), -1) x = self.fc(x) return x if __name__ == '__main__': from PIL import Image path = "/mnt/wfs/wujilong/mlabel_data/ajuke_224x224/ffff0771ea9d6af757a924f291c70ef5_600x600.jpg" img = Image.open(path).convert("RGB") img = torchvision.transforms.Resize((224, 224))(img) img = torchvision.transforms.ToTensor()(img) img = img.unsqueeze(0) model = make_model("resnext50_32x4d") pre = model(img) print(torch.nn.functional.softmax(pre, dim=1)) # print(model.layer3[0].conv1.weight.detach().numpy()[:,:,0,0])<file_sep>import torch import torch.nn as nn import torch.distributed as dist import torch.multiprocessing as mp from config.value_config import * import random from src.helper_functions.helper_functions import mAP from src.models.model_select import getmodel from src.loss_functions.losses import AsymmetricLoss from dataloader.loader_select import get_loader from torch.optim import lr_scheduler import os def main(): if SEED is not None: random.seed(SEED) torch.manual_seed(SEED) main_worker() # mp.spawn(main_worker, nprocs=torch.cuda.device_count()) def train(train_loader, model, criterion, optimizer, epoch): model.train() for i, (images, target) in enumerate(train_loader): images = images.cuda(non_blocking=True) target = target.cuda(non_blocking=True) output = model(images) loss = criterion(output, target) optimizer.zero_grad() loss.backward() optimizer.step() def validate_multi(val_loader, model): print("starting validation") Sig = torch.nn.Sigmoid() preds_regular = [] targets = [] for i, (input, target) in enumerate(val_loader): target = target # compute output with torch.no_grad(): output_regular = Sig(model(input.cuda())).cpu() # for mAP calculation preds_regular.append(output_regular.cpu().detach()) targets.append(target.cpu().detach()) mAP_score_regular = mAP(torch.cat(targets).numpy(), torch.cat(preds_regular).numpy()) print("mAP score regular {:.2f}".format(mAP_score_regular)) return mAP_score_regular def main_worker(): highest_MAP = 0 port = os.environ["MASTER_PORT"] addr = os.environ["MASTER_ADDR"] word_size = os.environ["WORLD_SIZE"] rank = os.environ["RANK"] dist.init_process_group(backend="nccl", init_method="tcp://"+addr+":"+port, world_size=word_size, rank=rank) model = getmodel() model.cuda() model = torch.nn.parallel.DistributedDataParallel(model) criterion = AsymmetricLoss(gamma_neg=4, gamma_pos=1, clip=0.05, disable_torch_grad_focal_loss=True) optimizer = torch.optim.Adam(params=model.parameters(), lr=LR, weight_decay=0) trainsampler, trainloader, valloader = get_loader() scheduler = lr_scheduler.CosineAnnealingLR(optimizer,T_max=20, eta_min=1e-8, last_epoch=-1) for epoch in range(EPOCHS): trainsampler.set_epoch(epoch) train(trainloader, model, criterion, optimizer, epoch) MAP = validate_multi(valloader, model) if MAP > highest_MAP: highest_MAP = MAP torch.save(model.state_dict(), os.path.join(SAVEPATH, "hightst_{:.2f}.pth".format(MAP))) torch.save(model.state_dict(), os.path.join(SAVEPATH, "epoch_{}_{:.2f}".format(epoch, MAP))) print("[*]! epoch:{} MAP:{:.2f}".format(epoch, MAP)) scheduler.step() if __name__ == "__main__": main()<file_sep>from torch.utils import data import torchvision import os from PIL import Image import cv2 import torch class Traindata(data.Dataset): def __init__(self, txtpath): self.txtpath = txtpath with open(txtpath, "r") as f: lines = f.readlines() self.picpaths = [] self.labels = [] for line in lines: line = line.strip() factors = line.split(',') self.picpaths.append(factors[0]) self.labels.append(int(factors[1])) # self.picpaths = self.picpaths[0:10] # self.labels = self.labels[0:10] self.transforms = torchvision.transforms.Compose([ torchvision.transforms.Resize((224, 224), interpolation=2), torchvision.transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.5), torchvision.transforms.RandomHorizontalFlip(), torchvision.transforms.RandomVerticalFlip(), torchvision.transforms.RandomGrayscale(0.1), torchvision.transforms.ToTensor(), ]) def __len__(self): return len(self.picpaths) def __getitem__(self, index): picpath = self.picpaths[index] picpath = picpath.replace("/code", "/mnt/wfs") img = Image.open(picpath).convert('RGB') # print(img.size()) img = self.transforms(img) label = self.labels[index] return img, label <file_sep>import torch.nn as nn import torch from config.value_config import CLSNUM, PREMODEL from src.models.tresnet import TResNet import argparse class Tres(nn.Module): def __init__(self): super(Tres, self).__init__() self.classnum = CLSNUM self.net = TResNet(layers=[4, 5, 18, 3], num_classes=9605, in_chans=3, width_factor=1.2, do_bottleneck_head=True) self.param = torch.load(PREMODEL, map_location="cpu") self.net.load_state_dict(self.param["model"]) self.relu = nn.ReLU() self.output = nn.Linear(in_features=9605, out_features=self.classnum) # self.body = self.net.body # self.global_pool = self.net.global_pool # self.fc = nn.Sequential(nn.Linear(in_features=2432, out_features=512, bias=True), # nn.BatchNorm1d(512), # nn.ReLU(inplace=True), # nn.Linear(in_features=512, out_features=self.classnum, bias=True)) def forward(self, x): x = self.net(x) x = self.relu(x) x = self.output(x) return x if __name__ == "__main__": # param = torch.load(PREMODEL, map_location="cpu") # for key in param["model"].keys(): # print(key) img = torch.randn(1,3, 224, 224).cuda() a = Tres().cuda() print(next(a.parameters()).is_cuda) print(a(img)) for name, i in a._modules.items(): print(name) # for param in a.parameters(): # print(param)
81a43dc312d177f9cb3ad4fc53e88843bce2613e
[ "Markdown", "Python", "Shell" ]
16
Python
1006927966/multi_label-classification-
dd8acfd7a65a4017dbf73267a7e5ec8dc64eb38e
055aec013b8e39da655d576df28ea1b54ac91baa
refs/heads/master
<file_sep># Name: <NAME> # Course: CPE 202 # Instructor: <NAME> # Assignment: Lab 8 # Term: Fall 2017 import unittest from sep_chain_ht import MyHashTable class TestLab8(unittest.TestCase): def test_insert(self): h = MyHashTable() h[12] = "dog" self.assertEqual(h[12], (12, "dog")) self.assertEqual(h.size(), 1) h[12] = "cat" self.assertEqual(h[12], (12, "cat")) self.assertEqual(h.size(), 1) def test_get(self): h = MyHashTable() h[12] = "dog" self.assertEqual(h[12], (12, "dog")) with self.assertRaises(LookupError): h[13] def test_remove(self): h = MyHashTable() h[12] = "dog" self.assertEqual(h.remove(12), (12, "dog")) self.assertEqual(h.size(), 0) with self.assertRaises(LookupError): h.remove(13) def test_size(self): h = MyHashTable() for i in range(1, 20): h[i] = "random" self.assertEqual(i, h.size()) def test_load_factor(self): h = MyHashTable() for i in range(1, 10): h[i] = "random" self.assertEqual(i / 11, h.load_factor()) def test_collisions(self): h = MyHashTable() h[1] = "cat" self.assertEqual(h.collisions(), 0) h[12] = "cat" self.assertEqual(h.collisions(), 1) h[2] = "cat" self.assertEqual(h.collisions(), 1) h[23] = "cat" self.assertEqual(h.collisions(), 1) h[2] = "dog" self.assertEqual(h.collisions(), 1) def test_grow_table(self): h = MyHashTable(5) for i in range(7): h[i] = "random" self.assertEqual(h.load_factor(), 7 / 5) h[7] = "random" self.assertEqual(h.load_factor(), 8 / 11) if __name__ == "__main__": unittest.main() <file_sep># Name: <NAME> # Course: CPE 202 # Instructor: <NAME> # Assignment: Lab 8 # Term: Fall 2017 class MyHashTable: def __init__(self, table_size = 11): self.table = [[] for _ in range(table_size)] self.num_items = 0 self.num_collisions = 0 def insert(self, key, item): table_idx = key % len(self.table) if len(self.table[table_idx]) == 1: self.num_collisions += 1 for entry_idx in range(len(self.table[table_idx])): if self.table[table_idx][entry_idx][0] == key: self.table[table_idx][entry_idx] = (key, item) self.num_collisions -= 1 return self.num_items += 1 if self.load_factor() > 1.5: self.grow_table() self.table[table_idx].append((key, item)) def grow_table(self): new_table = [[] for _ in range(2 * len(self.table) + 1)] for slot in self.table: for entry in slot: new_table[entry[0] % len(new_table)].append(entry) self.table = new_table def get(self, key): slot_idx = key % len(self.table) for entry in self.table[slot_idx]: if entry[0] == key: return entry raise LookupError def remove(self, key): slot_idx = key % len(self.table) for entry in self.table[slot_idx]: if entry[0] == key: self.table[slot_idx].remove(entry) self.num_items -= 1 return entry raise LookupError def size(self): return self.num_items def load_factor(self): return self.size() / len(self.table) def collisions(self): return self.num_collisions #Below are additional methods I was using to test def __setitem__(self, key, item): self.insert(key, item) def __getitem__(self, key): return self.get(key) def __contains__(self, key): try: self.get(key) return True except LookupError: return False def __iter__(self): for slot in self.table: for entry in slot: yield entry
133e5d33603ec662873527720b338ec3ee248af6
[ "Python" ]
2
Python
tylrdvs277/HashTable
b867d6cde5cc2db51be0c92ede48e1dab442c863
987e729e8803a55f29fc5ecece1cd334811ebf4b
refs/heads/master
<repo_name>abagali1/tictactoe<file_sep>/src/Driver15.java import javax.swing.*; public class Driver15{ public static void main(String[] args){ JFrame frame = new JFrame("TicTacToe"); String d = JOptionPane.showInputDialog("Choose difficulty: 0(less impossible), 1(impossible)"); if(d == null){ return; } while(!("0".equals(d) || "1".equals(d))){ JOptionPane.showMessageDialog(null,"Please enter a valid choice"); d = JOptionPane.showInputDialog("Choose difficulty: 0(less impossible), 1(impossible)"); if(d == null){ return; } } int diff = Integer.parseInt(d); frame.setSize(320,320); frame.setLocation(200,100); frame.getContentPane().add(new Panel15(diff)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }<file_sep>/README.md # TicTacToe ## Description TicTacToe implementation of the minmax algorithm.
b7812f2d3040f7c3b4b681e3d46077da000cc7c6
[ "Markdown", "Java" ]
2
Java
abagali1/tictactoe
ab55ecc12be9e683a4ffacf39e668aa3bfd23a84
c9f724c050a03854f371420687af1017541dc05d
refs/heads/master
<repo_name>cryptobuks/item-auction-auction-blockchain<file_sep>/decent-auction/addmoney.php <?php include("functions/functions.php"); $base_url="10.1.18.33:3000/api/"; $access_token="<KEY>"; // $urlitem="10.1.18.33:3000/api/Item/1?access_token=<KEY>"; // $getitem=callAPI('GET',$urlitem,false); // echo "$getitem"; // $itemlist=array( // "\$class" => "org.example.mynetwork.ItemListing", // "listingId" => "2", // "reservePrice" => 100, // "description" => "string", // "state" => "FOR_SALE", // "enddate" => "Sun May 05 2019 19:50:40 GMT+0530 (India Standard Time)", // "offers" => [], // "EncBids" => [], // "item" => "resource:org.example.mynetwork.Item#2" // ); // $iteml=json_encode($itemlist); // echo "$iteml"; // echo "\n"; // $url="10.1.18.33:3000/api/ItemListing/?access_token=<KEY>"; // echo callAPI('POST',$url,$iteml); // { // "$class": "org.example.mynetwork.Offer", // "bidPrice": "100", // "listing": "resource:org.example.mynetwork.ItemListing#2", // "member": "resource:org.example.mynetwork.Member#a@z" // } // $offer=array( // "\$class" => "org.example.mynetwork.Offer", // "bidPrice" => "200", // "listing" => "resource:org.example.mynetwork.ItemListing#2", // "member" => "resource:org.example.mynetwork.Member#a%40z" // ); // $offer=json_encode($offer); // $email= "<EMAIL>"; // $url="10.1.18.33:3000/api/Member/".$email."?access_token=<KEY>"; // // echo callAPI('GET',$url,false); // // $url="10.1.18.33:3000/api/ItemListing/2?access_token=<KEY>"; // $res= callAPI('GET',$url,false); // $res1=json_decode($res,true); // $email="harshk025"; // $add_mem=json_encode(array( // "\$class"=>"org.example.mynetwork.Member", // "balance"=>800, // "key"=>"1", // "email"=>"harshk025", // "password"=>"<PASSWORD>", // "firstName"=>"F", // "lastName"=>"L" // ) // ); // $add_url= $base_url."Member/".$email."?access_token=".$access_token; // $res=json_decode(CallAPI('PUT',$add_url,$add_mem), true); // print_r($res); // $list_url=$base_url."/ItemListing?access_token=".$access_token; // $get_list=json_decode(CallAPI('GET',$list_url,false), true); // print_r($get_list); // print_r(openssl_get_cipher_methods()); // $key="<KEY>"; // $dec=decryptAES( hex2bin($key),"key1"); // echo "\n"; // echo "$dec"; // $get_mem=$add_url= $base_url."Member/"."a@b"."?access_token=".$access_token; // $mem_detail=json_decode(CallAPI('GET',$add_url,false), true); // if (!array_key_exists("error", $mem_detail)) { // print_r($mem_detail['itembids']); // } $data="9688806666666666666666608878032gkhcghkkckhvcbvjhb"; $enc= RSAencrypt($data); echo RSAdecrypt($enc); ?><file_sep>/Readme.txt echo "GITHUB REPOSITORY http://www.github.com/prakhar171/item-auction" # How to Set up the network on your local host along with a rest server echo "Install the prereqs from https://hyperledger.github.io/composer/latest/installing/installing-prereqs" echo "Perform EVERY step mentioned on https://hyperledger.github.io/composer/latest/installing/development-tools" git clone https://www.github.com/prakhar171/item-auction cd item-auction/ composer archive create -t dir -n . composer network install --card PeerAdmin@hlfv1 --archiveFile tutorial-network@0.0.1.bna composer network start --networkName tutorial-network --networkVersion 0.0.1 --card PeerAdmin@hlfv1 --networkAdmin admin --networkAdminEnrollSecret adminpw --file networkadmin.card composer card import -f networkadmin.card composer network ping --card admin@tutorial-network composer-rest-server # Use the server using network admin card: admin@tutorial-network # Other than web sockets and explorer, choose all options as N echo 'Install a suitable XAMPP/WAMP/MAMP server and switch on Apache.' echo 'Place the decent-auction folder in the htdocs folder of your installation.' echo 'In the functions/functions.php file, replace base_url with your localhost url and access_token with your REST Server Access Token available at localhost:3000.' echo 'Navigate to localhost/[ht-docs-path]/decent-auction' <file_sep>/decent-auction/make_bid.php <?php session_start(); include("functions/functions.php"); if(!isset($_SESSION['user_email'])) { echo "<script>alert('Please Log In ');window.open('login.php','_self');</script>"; } ?> <!doctype html> <!--[if IE 9]> <html class="no-js ie9 fixed-layout" lang="en"> <![endif]--> <!--[if gt IE 9]><!--> <html class="no-js " lang="en"> <!--<![endif]--> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Mobile Meta --> <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <!-- Site Meta --> <title>Make Bid</title> <meta name="keywords" content=""> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,500,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,400i,700,700i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:800" rel="stylesheet"> <!-- Custom & Default Styles --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/carousel.css"> <link rel="stylesheet" href="css/animate.css"> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="css/prettyPhoto.css"> <script src="js/jquery.min.js"></script> <script src="js/aes.js"></script> <link rel="stylesheet" href="css/Google-Style-Login.css"> <link rel="stylesheet" href="css/Pretty-Registration-Form.css"> <!--[if lt IE 9]> <script src="js/vendor/html5shiv.min.js"></script> <script src="js/vendor/respond.min.js"></script> <![endif]--> </head> <body> <!-- LOADER --> <div id="preloader"> <img class="preloader" src="images/loader.gif" alt=""> </div><!-- end loader --> <!-- END LOADER --> <?php include 'navbar.php'; ?> <style type="text/css"> #dash { color: black; } @media screen and (max-width: 768px) { #app { display: block; } } @media screen and (min-width: 769px) { #app { display: none; } } </style> <section class="section wb"> <div class="container" style="padding: 30px;"> <div class="row"> <div class="col-md-12"> <h2 class="text-center" style="font-size: 50px; font-family: Open Sans;">Items For Sale</h2> </br></br> <?php $list_id=$_POST['listid']; ?> <script type="text/javascript"> function encBid(){ var bid=document.getElementById('bid').value; var key=document.getElementById('key').value; var enc= CryptoJS.AES.encrypt(bid, key); document.getElementById('enc').value =enc; document.forms["makebid"].submit(); } </script> <form class="login-card" method="post" id="makebid" enctype="multipart/form-data" onsubmit="encBid()" > <label class="control-label">Listing </label> <input class="form-control" type="text" readonly required name="listid" value='<?php echo $list_id; ?>' /> <label class="control-label">Your Bid </label> <input class="form-control" type="number" id='bid' required name="bid" /> <label class="control-label">Encryption Key (Please Remember It For Revealing Your Bid)</label> <input class="form-control" type="text" required id="key" name="key" /> <input type="hidden" value="" id="enc" name="encbid"> <br><br> <a href="#" onclick="encBid();"><button class="btn btn-primary btn-block" name="add_item">Make Bid!</button></a> </form> </div><!-- end col --> </div><!-- end row --> </div><!-- end container --> </section><!-- end section --> <!-- jQuery Files --> <script src="js/bootstrap.min.js"></script> <script src="js/animate.js"></script> <script src="js/bootstrap-select.min.js"></script> <script src="js/custom.js"></script> <script src="js/carousel.js"></script> </body> </html> <?php if (isset($_POST['add_item'])) { #Make Offer $encbid=$_POST['encbid'];; echo "<script>alert('$encbid');</script>"; $bid = $_POST['bid']; $key = $_POST['key']; $listid=$_POST['listid']; $mem= $_SESSION['user_email']; // $encbid=bin2hex(encryptAES($bid,$key)); // $encbid=$bid; $offer=json_encode(array( "\$class"=> "org.example.mynetwork.Offer", "bidPrice"=> $encbid, "listing"=> "resource:org.example.mynetwork.ItemListing#".$listid, "member"=> "resource:org.example.mynetwork.Member#".$mem, )); $add_url=$base_url."/Offer?access_token=".$access_token; $res=json_decode(CallAPI('POST',$add_url,$offer), true); if (!array_key_exists("error", $res)) { echo "<script>alert('Hurray')</script>"; } else{ print_r($res); } #Deduct Amount $get_mem=$add_url= $base_url."Member/".$mem."?access_token=".$access_token; $mem_detail=json_decode(CallAPI('GET',$add_url,false), true); if (!array_key_exists("error", $mem_detail)) { // echo "<script>alert('Hurray')</script>"; $new_bal=$mem_detail['balance']-$bid; array_push($mem_detail['itembids'], $listid); $itembids= $mem_detail['itembids']; $add_mem=json_encode(array( "\$class"=>$mem_detail["\$class"], "balance"=>$new_bal, "key"=>$mem_detail["key"], "email"=>$mem_detail["email"], "password"=>$mem_detail["<PASSWORD>"], "firstName"=>$mem_detail["firstName"], "lastName"=>$mem_detail["lastName"], "itembids"=>$itembids ) ); echo $add_mem; $add_url= $base_url."Member/".$mem."?access_token=".$access_token; $res=json_decode(CallAPI('PUT',$add_url,$add_mem), true); if (!array_key_exists("error", $res)) { echo "<script>alert('Hurray'); window.open('dashboard.php', '_self');</script>"; } else{ echo "<script>alert('ERROR LOL')</script>"; print_r($res); } } else{ echo "<script>alert('ERROR LOL')</script>"; print_r($res); } } ?><file_sep>/decent-auction/navbar.php <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous"> <header id="head" class="header header-normal"> <div class="topbar clearfix"> <div class="container"> <div class="row-fluid"> <div class="col-md-6 col-sm-6 text-left"> <p> <strong><i class="fa fa-phone"></i></strong> +91 93 69 21 77 24 &nbsp;&nbsp; <strong><i class="fa fa-envelope"></i></strong> <a href="mailto: <EMAIL>"><EMAIL></a> </p> </div><!-- end left --> </div><!-- end row --> </div><!-- end container --> </div><!-- end topbar --> <div class="container"> <nav class="navbar navbar-default yamm"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> </button> <div class="logo-normal"> <?php if(isset($_SESSION['user_email'])) { echo "<span style='color:white;'>Welcome back, ".$_SESSION['user_email']."</span>"; } ?> </div> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <?php if(!isset($_SESSION['user_email'])) { echo "<li><a href='login.php'>LOG IN</a></li> <li role='presentation'><a href='login.php' id='signin'>SIGN UP</a></li>"; } else{ echo " <li><a href='items.php'>Items</a></li> <li role='presentation'><a href='dashboard.php'>Dashboard</a></li> <li><a href='logout.php'>Logout</a></li> "; } ?> </ul> </div> </nav><!-- end navbar --> </div><!-- end container --> </header><file_sep>/decent-auction/items.php <?php session_start(); include("functions/functions.php"); if(!isset($_SESSION['user_email'])) { echo "<script>alert('Please Log In ');window.open('login.php','_self');</script>"; } ?> <!doctype html> <!--[if IE 9]> <html class="no-js ie9 fixed-layout" lang="en"> <![endif]--> <!--[if gt IE 9]><!--> <html class="no-js " lang="en"> <!--<![endif]--> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Mobile Meta --> <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <!-- Site Meta --> <title>Items For Sale</title> <meta name="keywords" content=""> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,500,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,400i,700,700i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:800" rel="stylesheet"> <!-- Custom & Default Styles --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/carousel.css"> <link rel="stylesheet" href="css/animate.css"> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="css/prettyPhoto.css"> <script src="js/jquery.min.js"></script> <!--[if lt IE 9]> <script src="js/vendor/html5shiv.min.js"></script> <script src="js/vendor/respond.min.js"></script> <![endif]--> </head> <body> <?php include 'navbar.php'; ?> <style type="text/css"> #dash { color: black; } @media screen and (max-width: 768px) { #app { display: block; } } @media screen and (min-width: 769px) { #app { display: none; } } </style> <section class="section wb"> <div class="container" style="padding: 30px;"> <div class="row"> <div class="col-md-12"> <h2 class="text-center" style="font-size: 50px; font-family: Open Sans;">Items For Sale</h2> </br></br> <?php $list_url=$base_url."/ItemListing?access_token=".$access_token; $get_list=json_decode(CallAPI('GET',$list_url,false), true); echo "<div class='table-responsive' id='dash' > <table class='table-bordered' style='margin-left: auto; margin-right: auto;'> <thead> <tr style='font-weight:bold;'> <th style='padding:8px;'>Item ID</th> <th style='padding:8px;'>Item Description</th> <th style='padding:8px;'>Reserve Price</th> <th style='padding:8px;'>Status</th> <th style='padding:8px;'>Make A Bid</th> </tr> </thead> <tbody> "; foreach ($get_list as $listing) { if ($listing['state']=="FOR_SALE") { $bid="<form method='post' action='make_bid.php'> <input type='hidden' value='".$listing['listingId']."' name=listid /> <button class='btn btn-success' type='submit' style='margin-top: 20px;'>Make A Bid</button> </form>"; } else{ $bid=$listing['state']; } echo "<tr> <td style='padding:8px;' class='dasht'>".$listing['listingId']."</td> <td style='padding:8px;' class='dasht'>".$listing['description']."</td> <td style='padding:8px;' class='dasht'>".$listing['reservePrice']."</td> <td style='padding:8px;' class='dasht'>".$listing['state']."</td> <td style='padding:8px;' class='dasht'>".$bid."</td> </tr>"; } ?> </tbody> </table> </div> </div><!-- end col --> </div><!-- end row --> </div><!-- end container --> </section><!-- end section --> <!-- jQuery Files --> <script src="js/bootstrap.min.js"></script> <script src="js/animate.js"></script> <script src="js/bootstrap-select.min.js"></script> <script src="js/custom.js"></script> <script src="js/carousel.js"></script> </body> </html> <?php if (isset($_POST['add_item'])) { $bid = $_POST['bid']; $key = $_POST['key']; $listid=$_POST['listid']; $mem= $_SESSION['user_email']; $encbid=encryptAES($bid,$key); $offer=json_encode(array( "$class"=> "org.example.mynetwork.Offer", "bidPrice"=> $encbid, "listing"=> "resource:org.example.mynetwork.ItemListing#".$listid, "member"=> "resource:org.example.mynetwork.Member#".$mem, )); $add_url=$base_url."/Offer?access_token=".$access_token; $res=json_decode(CallAPI('POST',$add_url,$offer), true); if (!array_key_exists("error", $res)) { echo "alert('Hurray')"; } else{ print_r($res); } } ?><file_sep>/decent-auction/js/validate.js function checkPassword(str) { var re = (?=.{6,}); return re.test(str); } function checkForm(form) { if(form.appl_pass.value != "" && form.appl_pass.value == form.appl_cpass.value) { if(!checkPassword(form.appl_pass.value)) { alert("The password you have entered is not valid!" + form.appl_pass.value); form.appl_pass.focus(); return false; } } else { alert("Error: Please check that you've entered and confirmed your password!"); form.appl_pass.focus(); return false; } return true; }<file_sep>/decent-auction/functions/functions.php <?php $base_url="10.1.18.33:3000/api/"; $access_token="<KEY>"; function callAPI($method, $url, $data){ $curl = curl_init(); switch ($method){ case "POST": curl_setopt($curl, CURLOPT_POST, 1); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; case "PUT": curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; default: if ($data) $url = sprintf("%s?%s", $url, http_build_query($data)); } // OPTIONS: curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'APIKEY: 111111111111111111111', 'Content-Type: application/json', )); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // EXECUTE: $result = curl_exec($curl); if(!$result){die("Connection Failure");} curl_close($curl); return $result; } use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'functions/PHPMailer/src/Exception.php'; require 'functions/PHPMailer/src/PHPMailer.php'; require 'functions/PHPMailer/src/SMTP.php'; function SendMail($subject,$email,$message){ $to_id1 = $email; $mail1 = new PHPMailer(); $mail1->isSMTP(); $mail1->Host = 'smtp.gmail.com'; $mail1->Port = 587; // $mail1->SMTPSecure = 'tls'; $mail1->SMTPAuth = true; $mail1->Username = '<EMAIL>'; $mail1->Password = '<PASSWORD>'; $mail1->addAddress($to_id1); $mail1->Subject = $subject; $mail1->msgHTML($message); $mail1->SetFrom('<EMAIL>','De<NAME>'); // $mail1->SMTPDebug = 2; if (!$mail1->send()) { $error = "Mailer Error: " . $mail1->ErrorInfo; echo '<p id="para">'.$error.'</p>'; return $error; } else { echo '<p id="para">Message sent!</p>'; return "Sent"; } } function encryptAES($plaintext, $password) { $method = "AES-256-CBC"; $key = hash('sha256', $password, true); $iv = openssl_random_pseudo_bytes(16); $ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv); $hash = hash_hmac('sha256', $ciphertext, $key, true); return $iv . $hash . $ciphertext; } function decryptAES($ivHashCiphertext, $password) { $method = "AES-256-CBC"; $iv = substr($ivHashCiphertext, 0, 16); $hash = substr($ivHashCiphertext, 16, 32); $ciphertext = substr($ivHashCiphertext, 48); $key = hash('sha256', $password, true); if (hash_hmac('sha256', $ciphertext, $key, true) !== $hash) return null; return openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv); } $configargs = array( "config" => "F:/xampp/php/extras/openssl/openssl.cnf", 'private_key_bits'=> 2048, 'default_md' => "sha256", ); // Create the private and public key $res = openssl_pkey_new($configargs); // Extract the private key from $res to $privKey openssl_pkey_export($res, $privKey,NULL,$configargs); // Extract the public key from $res to $pubKey $pubKey = openssl_pkey_get_details($res); $pubKey = $pubKey["key"]; function encryptRSA($data) { global $pubKey; $enc = openssl_public_encrypt($data, $encrypted, $pubKey); $b64_enc = base64_encode($encrypted); return $b64_enc; } function decryptRSA($data) { global $privKey; if (openssl_private_decrypt(base64_decode($data), $decrypted, $privKey)) $data = $decrypted; else $data = ''; return $data; } function caesarEncode( $message, $key ){ $plaintext = strtolower( $message ); $ciphertext = ""; $ascii_a = ord( 'a' ); $ascii_z = ord( 'z' ); while( strlen( $plaintext ) ){ $char = ord( $plaintext ); if( $char >= $ascii_a && $char <= $ascii_z ){ $char = ( ( $key + $char - $ascii_a ) % 26 ) + $ascii_a; } $plaintext = substr( $plaintext, 1 ); $ciphertext .= chr( $char ); } return $ciphertext; } ?><file_sep>/decent-auction/dashboard.php <?php session_start(); include("functions/functions.php"); if(!isset($_SESSION['user_email'])) { echo "<script>alert('Please Log In ');window.open('login.php','_self');</script>"; } $user_email=$_SESSION['user_email']; ?> <!doctype html> <!--[if IE 9]> <html class="no-js ie9 fixed-layout" lang="en"> <![endif]--> <!--[if gt IE 9]><!--> <html class="no-js " lang="en"> <!--<![endif]--> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Mobile Meta --> <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <!-- Site Meta --> <title>Member Dashboard</title> <meta name="keywords" content=""> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,500,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,400i,700,700i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:800" rel="stylesheet"> <!-- Custom & Default Styles --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/carousel.css"> <link rel="stylesheet" href="css/animate.css"> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="css/prettyPhoto.css"> <script src="js/jquery.min.js"></script> <!--[if lt IE 9]> <script src="js/vendor/html5shiv.min.js"></script> <script src="js/vendor/respond.min.js"></script> <![endif]--> </head> <body> <!-- LOADER --> <div id="preloader"> <img class="preloader" src="images/loader.gif" alt=""> </div><!-- end loader --> <!-- END LOADER --> <?php include 'navbar.php'; ?> <style type="text/css"> .dasht{ padding: 20px; } #dash { color: black; } @media screen and (max-width: 768px) { #app { display: block; } } @media screen and (min-width: 769px) { #app { display: none; } } </style> <section class="section wb"> <div class="container" style="padding: 30px;"> <div class="row"> <div class="text-center col-md-12"> <h2 class="text-center" style="font-size: 50px; font-family: Open Sans;">Your Item Listings</h2> <button class="btn btn-primary" data-toggle="modal" data-target="#ItemList" style="margin-top: 20px;">Add Item Listing</button> <br> <br> <?php $list_url=$base_url."/ItemListing?access_token=".$access_token; $get_list=json_decode(CallAPI('GET',$list_url,false), true); echo "<div class='table-responsive' id='dash' > <table class='table-bordered' style='margin-left: auto; margin-right: auto;'> <thead> <tr style='font-weight:bold;'> <th style='padding:12px;'>Listing ID</th> <th style='padding:12px;'>Item Description</th> <th style='padding:12px;'>Reserve Price</th> <th style='padding:12px;'>Status</th> <th style='padding:12px;'>Bid Count</th> <th style='padding:12px;'>Close Bidding</th> <th style='padding:12px;'>End Auction</th> </tr> </thead> <tbody> "; foreach ($get_list as $listing) { if ($listing['state']=='FOR_SALE') { $close_bid="<form method='post'> <input type='hidden' value='".$listing['listingId']."' name=listid /> <button class='btn btn-danger' name='close_bid' type='submit' style='margin-top: 20px;'>Close Bidding</button> </form>"; } else{ $close_bid="Already Closed"; } if ($listing['state']=='BIDDING_CLOSED') { $end_bid="<form method='post'> <input type='hidden' value='".$listing['listingId']."' name=listid /> <button class='btn btn-success' name='end_bid' type='submit' style='margin-top: 20px;'>End Auction</button> </form>"; } else{ $end_bid=""; } if ($listing['owner']=="resource:org.example.mynetwork.Member#".$_SESSION['user_email']) { echo "<tr> <td style='padding:55 px;' class='dasht'>".$listing['listingId']."</td> <td style='padding:55 px;' class='dasht'>".$listing['description']."</td> <td style='padding:55 px;' class='dasht'>".$listing['reservePrice']."</td> <td style='padding:55 px;' class='dasht'>".$listing['state']."</td> <td style='padding:55 px;' class='dasht'>".sizeof($listing['offers'])."</td> <td style='padding:55 px;' class='dasht'>".$close_bid."</td> <td style='padding:55 px;' class='dasht'>".$end_bid."</td> </tr>"; } } ?> </tbody> </table> </div> </div><!-- end row --> <div class="row"> <div class="text-center col-md-12"> <h2 class="text-center" style="font-size: 50px; font-family: Open Sans;">Your Bids</h2> <a href="items.php"><button class="btn btn-primary" style="margin-top: 20px;">Explore Items</button></a> <br> <br> <?php $mem_url=$base_url."/Member/".$user_email."?access_token=".$access_token; $item_list=json_decode(CallAPI('GET',$mem_url,false), true); $itembids=$item_list['itembids']; echo "<div class='table-responsive' id='dash' > <table class='table-bordered' style='margin-left: auto; margin-right: auto;'> <thead> <tr style='font-weight:bold;'> <th style='padding:12px;'>Listing ID</th> <th style='padding:12px;'>Item Description</th> <th style='padding:12px;'>Status</th> <th style='padding:12px;'>Reveal Bid</th> </tr> </thead> <tbody> "; foreach ($itembids as $item) { $list_url=$base_url."/ItemListing/".$item."?access_token=".$access_token; $listing=json_decode(CallAPI('GET',$list_url,false), true); if (!array_key_exists("error", $listing)) { if ($listing['state']=='BIDDING_CLOSED') { $rev_bid="<form method='post'> <input type='hidden' value='".$listing['listingId']."' name='listid' /> <input type='hidden' value='".$user_email."' name='member' /> <input type='text' class='form-control' name='key' /> <button class='btn btn-danger' name='reveal_bid' type='submit' style='margin-top: 20px;'>Reveal Bid</button> </form>"; } else{ $rev_bid="Bidding Still Open"; } echo "<tr> <td style='padding:55 px;' class='dasht'>".$listing['listingId']."</td> <td style='padding:55 px;' class='dasht'>".$listing['description']."</td> <td style='padding:55 px;' class='dasht'>".$listing['state']."</td> <td style='padding:55 px;' class='dasht'>".$rev_bid."</td> </tr>"; } else{ echo $listing; } } ?> </tbody> </table> </div> </div><!-- end row --> </div><!-- end container --> </section><!-- end section --> <div id="ItemList" class="modal fade" role="dialog"> <div class="modal-dialog"> <form method="post"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h3 class="modal-title" style="color: white;">Add Item Listing</h3> </div> <div class="modal-body"> <label class="mod_label">Unique Item Name:</label> <input type="text" name="vin"> <br><br> <label class="mod_label">Unique Listing ID:</label> <input type="text" name="listid"> <br><br> <label class="mod_label">Item Description</label> <input type="text" name="desc"> <br><br> <label class="mod_label">Reserve Bid:</label> <input type="number" name="rbid"> <br><br> <label class="mod_label">Bidding End Date:</label> <input type="datetime-local" name="enddt"> </div> <div class="modal-footer"> <button type="submit" class="btn btn-default" name="add_item">Submit</button> </div> </div> </div> </div> </form> <!-- jQuery Files --> <script src="js/bootstrap.min.js"></script> <script src="js/animate.js"></script> <script src="js/bootstrap-select.min.js"></script> <script src="js/custom.js"></script> <script src="js/carousel.js"></script> </body> </html> <?php if (isset($_POST['close_bid'])) { $listid = $_POST['listid']; $list=json_encode(array( "\$class"=> "org.example.mynetwork.CloseBidding", "listing"=> "resource:org.example.mynetwork.ItemListing#".$listid, )); $add_url=$base_url."/CloseBidding?access_token=".$access_token; $res=json_decode(CallAPI('POST',$add_url,$list), true); if (!array_key_exists("error", $res)) { echo "<script>window.location = window.location.href.split('#')[0];"; } else{ print_r($res); } } if (isset($_POST['add_item'])) { $vin = $_POST['vin']; $listid = $_POST['listid']; $desc = $_POST['desc']; $rbid = $_POST['rbid']; $enddt = $_POST['enddt']; $owner= $_SESSION['user_email']; $item=json_encode(array( "\$class"=> "org.example.mynetwork.Item", "vin"=> $vin, "owner"=> "resource:org.example.mynetwork.Member#".$owner )); $add_url=$base_url."/Item?access_token=".$access_token; $res=json_decode(CallAPI('POST',$add_url,$item), true); if (!array_key_exists("error", $res)) { $iteml=json_encode(array( "\$class"=> "org.example.mynetwork.ItemListing", "listingId"=> $listid, "reservePrice"=> $rbid, "description"=> $desc, "state"=> "FOR_SALE", "enddate"=> $enddt, "offers"=> [], "EncBids"=> [], "item"=> "resource:org.example.mynetwork.Item#".$vin, "owner"=> "resource:org.example.mynetwork.Member#".$owner )); $iteml_url=$base_url."/ItemListing?access_token=".$access_token; $res1=json_decode(CallAPI('POST',$iteml_url,$iteml), true); if (!array_key_exists("error", $res1)) { echo "<script>alert('Item Listing Added');window.open('dashboard.php','_self');</script>"; } else{ print_r($res1); } } else{ print_r($res); } } if (isset($_POST['reveal_bid'])) { $listid = $_POST['listid']; $member= $_SESSION['user_email']; $key=$_POST['key']; $enckey=caesarEncode($key,16); $rev=json_encode(array( "\$class"=> "org.example.mynetwork.RevealBid", "member"=> "resource:org.example.mynetwork.Member#".$member, "listing"=> "resource:org.example.mynetwork.ItemListing#".$listid, "EncKey"=> $enckey )); $rev_url=$base_url."/RevealBid?access_token=".$access_token; $res1=json_decode(CallAPI('POST',$rev_url,$rev), true); if (!array_key_exists("error", $res1)) { echo "<script>alert('Bid Revealed');window.open('dashboard.php','_self');</script>"; } else{ print_r($res1); } } if (isset($_POST['end_bid'])) { $listid = $_POST['listid']; $rev=json_encode(array( "\$class"=> "org.example.mynetwork.endAuction", "listing"=> "resource:org.example.mynetwork.ItemListing#".$listid )); $rev_url=$base_url."/endAuction?access_token=".$access_token; $res1=json_decode(CallAPI('POST',$rev_url,$rev), true); if (!array_key_exists("error", $res1)) { echo "<script>alert('Auction Ended');window.open('dashboard.php','_self');</script>"; } else{ print_r($res1); } } ?><file_sep>/decent-auction/index.php <?php session_start(); include("functions/functions.php"); ?> <!doctype html> <!--[if IE 9]> <html class="no-js ie9 fixed-layout" lang="en"> <![endif]--> <!--[if gt IE 9]><!--> <html class="no-js " lang="en"> <!--<![endif]--> <head> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-126695806-1"></script> <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Mobile Meta --> <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <!-- Site Meta --> <title>Decent Auction</title> <meta name="keywords" content=""> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,500,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,400i,700,700i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:800" rel="stylesheet"> <!-- Custom & Default Styles --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/carousel.css"> <link rel="stylesheet" href="css/animate.css"> <link rel="stylesheet" href="style.css"> <script src="js/jquery.min.js"></script> </head> <body> <?php include 'navbar.php'; ?> <script type="text/javascript"> if ( $(window).width() > 767){ var element = document.getElementById("head"); element.classList.remove("header-normal"); } </script> <style type="text/css"> #brand{ display: none; } </style> <!-- Modal --> <script type="text/javascript"> $(document).ready(function () { $('#mainlogo').fadeIn(2000); $('#mainmsg').fadeIn(2000); $('#mainexp').fadeIn(6000); }); </script> <section id="home" class="video-section js-height-full" style="background-image: url(images/home_bg.jpg)"> <div class="overlay"></div> </br> </br> <div class="home-text-wrapper relative container"> <div class="home-message"> <h1 style="font-size: 100px; color: white; font-family: Open Sans;" class="text-responsive">Decent Auction</h1> </br> </br> </br> <!-- <p style="font-family: 'Open Sans', sans-serif;">UNIFORM APPLICATION</p> --> <small id="mainmsg" style=" display:none; font-size: 26px; color: rgb(255,255,255,1);">A Secure and Verifiable Auction on the Blockchain</small> </div> </div> </section> <!-- jQuery Files --> <script src="js/bootstrap.min.js"></script> <script src="js/carousel.js"></script> <script src="js/animate.js"></script> <script src="js/custom.js"></script> <!-- VIDEO BG PLUGINS --> <script type="text/javascript"> function scroller(){ $('html, body').animate({ scrollTop: $("#usp").offset().top }, 1000); } </script> </body> </html><file_sep>/lib/logic.js /* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by <NAME>. All rights reserved. code.google.com/p/crypto-js/wiki/License */ /* * 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. */ /* global getAssetRegistry getParticipantRegistry */ /** * Close the bidding for a item listing and choose the * highest bid that is over the asking price * @param {org.example.mynetwork.CloseBidding} closeBidding - the closeBidding transaction * @transaction */ async function closeBidding(closeBidding) { // eslint-disable-line no-unused-vars const listing = closeBidding.listing; if (listing.state !== 'FOR_SALE') { throw new Error('Listing is not FOR SALE'); } listing.state = 'BIDDING_CLOSED'; let id=listing.listingId; const itemListingRegistry = await getAssetRegistry('org.example.mynetwork.ItemListing'); await itemListingRegistry.update(listing); } /** * End the auction for a item listing and choose the * highest bid that is over the asking price * @param {org.example.mynetwork.endAuction} endAuction - the endAuction transaction * @transaction */ async function endAuction(endAuction) { // eslint-disable-line no-unused-vars const listing = endAuction.listing; if (listing.state !== 'BIDDING_CLOSED') { throw new Error('Listing is not closed for bidding.'); } // by default we mark the listing as RESERVE_NOT_MET listing.state = 'RESERVE_NOT_MET'; let highestBid = 0; let highestBidder=null; let secondBid=0; let buyer = null; let seller = null; if (listing.offers && listing.offers.length > 0) { for(i=0; i < listing.offers.length ; i++) { let offer=listing.offers[i]; let mem= offer.member; let bid= offer.bidPrice; let j; for(j=0; j < listing.EncBids.length ; j++) { let RevBid=listing.EncBids[j]; if (RevBid.member==mem){ var key = RevBid.EncKey; let actualBid1 = CryptoJS.AES.decrypt(bid, key); var ac= actualBid1.toString(CryptoJS.enc.Utf8); let actualBid= parseFloat(ac); console.log("Key from RSA: "+key); console.log("Bid string from RSA: "+ac); if(actualBid>=highestBid){ if (highestBidder !=null){ highestBidder.balance += highestBid; const userRegistry = await getParticipantRegistry('org.example.mynetwork.Member'); await userRegistry.update(highestBidder); console.log("Highest bidder"+highestBidder); } secondBid = highestBid; highestBid=actualBid; highestBidder=mem; console.log("Highest bidder outside: "+highestBidder); } else if(actualBid>=secondBid){ mem.balance+=actualBid; secondBid=actualBid; const userRegistry = await getParticipantRegistry('org.example.mynetwork.Member'); await userRegistry.update(mem); } else{ mem.balance+=actualBid const userRegistry = await getParticipantRegistry('org.example.mynetwork.Member'); await userRegistry.update(mem); } } } } } // mark the listing as SOLD listing.state = 'SOLD'; buyer = highestBidder; //buyer is the member with highest bid seller = listing.item.owner; // update the balance of the seller to the second highest bid console.log('#### seller balance before: ' + seller.balance); seller.balance += secondBid; console.log('#### seller balance after: ' + seller.balance); //refund the difference between highest and second highest bids to the highest bidder buyer.balance += (highestBid-secondBid) ; // transfer the item to the buyer listing.item.owner = buyer; // clear the offers if (highestBid) { // save the item const itemRegistry = await getAssetRegistry('org.example.mynetwork.Item'); await itemRegistry.update(listing.item); } // save the item listing const itemListingRegistry = await getAssetRegistry('org.example.mynetwork.ItemListing'); await itemListingRegistry.update(listing); if (listing.state === 'SOLD') { // save the buyer const userRegistry = await getParticipantRegistry('org.example.mynetwork.Member'); await userRegistry.updateAll([buyer, seller]); } } /** * Add Money * @param {org.example.mynetwork.AddMoney} addmoney - the money * @transaction */ async function AddMoney(addmoney) { // eslint-disable-line no-unused-vars console.log('Old Balance:'+addmoney.member.balance); addmoney.member.balance += addmoney.amount; console.log('New Balance:'+addmoney.member.balance); const userRegistry = await getParticipantRegistry('org.example.mynetwork.Member'); await userRegistry.update(addmoney.member); } /** * Make an Offer for a ItemListing * @param {org.example.mynetwork.Offer} offer - the offer * @transaction */ async function makeOffer(offer) { // eslint-disable-line no-unused-vars let listing=offer.listing; //let bidder=null; //bidder = offer.member; //current bidder //let bid=null; //bid = offer.bidPrice; //bid price let currentdate=new Date(); let bidend= new Date(listing.enddate); if(currentdate>bidend){ throw new Error('Bidding Period is over. Better luck next time!'); return; } if (listing.state !== 'FOR_SALE') { throw new Error('Listing is not FOR SALE'); } if (!listing.offers) { listing.offers = []; } bid= parseFloat(offer.bidPrice); currentbid=offer.bidPrice; listing.offers.push(offer); const userRegistry = await getParticipantRegistry('org.example.mynetwork.Member'); await userRegistry.update(offer.member); // save the item listing const itemListingRegistry = await getAssetRegistry('org.example.mynetwork.ItemListing'); await itemListingRegistry.update(listing); } /** * Send encrypted bid for a item listing and add to item listing * @param {org.example.mynetwork.RevealBid} RevealBid - the closeBidding transaction * @transaction */ async function RevealBid(RevealBid) { // eslint-disable-line no-unused-vars const listing = RevealBid.listing; if (listing.state !== 'BIDDING_CLOSED') { throw new Error('Listing is not closed for bidding.'); } let mem= RevealBid.member; let key=mem.key; RevealBid.EncKey=key; listing.EncBids.push(RevealBid); const itemListingRegistry = await getAssetRegistry('org.example.mynetwork.ItemListing'); await itemListingRegistry.update(listing); }<file_sep>/decent-auction/js/custom.js $(".js-height-full").height($(window).height()); $(".js-height-parent").each(function() { $(this).height($(this).parent().first().height()); }); var i = 0; var txt = 'Find the right school for your child from the comfort of your home.'; var speed = 200; /* The speed/duration of the effect in milliseconds */ // function typeWriter() { // if (i < txt.length) { // document.getElementById("type").innerHTML += txt.charAt(i); // i++; // setTimeout(typeWriter, speed); // } // } // $(document).ready(function(){ // $("#brand").hide() // $(window).scroll(function() { // if ($(document).scrollTop() > 300) { // typeWriter(); // $("#brand").show() // } // else{ // $("#brand").hide() // } // }); // }); // Fun Facts function count($this) { var current = parseInt($this.html(), 10); current = current + 1; /* Where 50 is increment */ $this.html(++current); if (current > $this.data('count')) { $this.html($this.data('count')); } else { setTimeout(function() { count($this) }, 5); } } $(".stat-timer").each(function() { $(this).data('count', parseInt($(this).html(), 10)); $(this).html('0'); count($(this)); }); $(window).load(function() { $("#preloader").on(500).fadeOut(); $(".preloader").on(600).fadeOut("slow"); });<file_sep>/decent-auction/login.php <?php session_start(); include("functions/functions.php"); if(isset($_SESSION['user_email'])) { echo "<script>alert('Already Logged In ');window.open('index.php','_self');</script>"; } ?> <!doctype html> <!--[if IE 9]> <html class="no-js ie9 fixed-layout" lang="en"> <![endif]--> <!--[if gt IE 9]><!--> <html class="no-js " lang="en"> <!--<![endif]--> <head> <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- Mobile Meta --> <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <!-- Site Meta --> <title>Login</title> <meta name="keywords" content=""> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,500,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Droid+Serif:400,400i,700,700i" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:800" rel="stylesheet"> <!-- Custom & Default Styles --> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/font-awesome.min.css"> <link rel="stylesheet" href="css/carousel.css"> <link rel="stylesheet" href="css/animate.css"> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="css/Google-Style-Login.css"> <link rel="stylesheet" href="css/Pretty-Registration-Form.css"> <!--[if lt IE 9]> <script src="js/vendor/html5shiv.min.js"></script> <script src="js/vendor/respond.min.js"></script> <![endif]--> </head> <body> <!-- LOADER --> <div id="preloader"> <img class="preloader" src="images/loader.gif" alt=""> </div><!-- end loader --> <!-- END LOADER --> <?php include 'navbar.php'; ?> <section class=""> <div class="container" style="padding: 30px;"> <div class="row"> <div class="col-md-12"> <div class="text-center" > <h2 style="font-size: 50px; font-family: Open Sans;">LOG IN</h2> </div> </div><!-- end col --> </div><!-- end row --> <script type="text/javascript"> function switchtab(){ document.getElementById("tabl-1").classList.remove("active"); document.getElementById("tabl-2").classList.add("active"); document.getElementById("tab-1").classList.remove("active"); document.getElementById("tab-2").classList.add("active"); document.getElementById("tab-2").classList.add("in"); } </script> <div class="col-md-8 col-md-offset-2"> <ul class="nav nav-tabs nav-justified"> <li id="tabl-2" ><a href="#tab-2" role="tab" data-toggle="tab">LOG IN</a></li> <li id="tabl-1" class="active"><a href="#tab-1" role="tab" data-toggle="tab">SIGN UP</a></li> </ul> <div class="tab-content"> <div role="tabpanel" class="tab-pane fade" id="tab-2"> <div class="login-card"><img src="images/avatar_2x.png" class="profile-img-card" /> <p class="profile-name-card"></p> <form class="form-signin" method="post"><span class="reauth-email"> </span> <input class="form-control" type="tel" required placeholder="Mobile Number" name="email" autofocus/> <input class="form-control" type="<PASSWORD>" required placeholder="<PASSWORD>" name="pass"/> <div class="checkbox"> <!-- <div class="checkbox"> <label> <input type="checkbox" />Remember me</label> </div> --> </div> <button name="login" class="btn btn-primary btn-block btn-lg btn-signin" type="submit">Log in</button> </form> <a href="forgot_pw.php" class="forgot-password">Forgot your password?</a></br> </div> </div> <div role="tabpanel" class="tab-pane fade in active" id="tab-1"> <h4 class="text-center" style="font-style: italic; padding-top: 15px;">If you already have login details, please <span style="text-decoration: underline;"><a href="#" onclick="switchtab()" >log in here</a></span>.</h4> <form class="login-card" method="post" enctype="multipart/form-data"> <label class="control-label">First Name </label> <input class="form-control" type="text" required name="fname" /> <label class="control-label">Last Name </label> <input class="form-control" type="text" required name="lname" /> <label class="control-label">Email Address </label> <input class="form-control" type="email" required name="email" /> <label class="control-label">Password (Minimum 6 characters) </label> <input class="form-control" type="password" required name="pass" pattern=".{6,}" /> </br> <button class="btn btn-primary btn-block btn-lg btn-signin" name="signup" type="submit">Sign Up</button> </form> </div> </div> </div> </div><!-- end container --> </section><!-- end section --> <!-- jQuery Files --> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/animate.js"></script> <script src="js/bootstrap-select.min.js"></script> <script src="js/custom.js"></script> </body> </html> <?php if (isset($_POST['login'])) { $email=$_POST['email']; $pass=$_POST['pass']; $mem_url=$base_url."Member/".$email."?access_token=".$access_token; $get_mem=CallAPI('GET',$mem_url,false); $mem=json_decode($get_mem, true); if (array_key_exists("error", $mem)) { echo "<script>window.location.replace(window.location.pathname + window.location.search + window.location.hash);alert('User does not exist. Please Sign Up.');</script>"; exit(); } else{ $check_pass=$mem['password']; if (password_verify($pass,$check_pass)){ $_SESSION['user_email']=$email; echo "<script>alert('Login Successful');window.open('dashboard.php','_self');</script>"; } else{ echo "<script>alert('Password is incorrect. Please try again.');window.open('login.php', '_self');</script>"; } } } if (isset(($_POST['signup']))) { //getting text data from fields $fname=$_POST['fname']; $lname=$_POST['lname']; $pass=$_POST['pass']; $pass_hash=password_hash($pass, PASSWORD_DEFAULT); $email=$_POST['email']; $add_mem=json_encode(array( "\$class"=> "org.example.mynetwork.Member", "balance"=> 1000, "key"=> "1", "itembids"=>[], "email"=> $email, "password"=> $<PASSWORD>, "firstName"=> $fname, "lastName"=> $lname, ) ); $mem_url=$base_url."Member/".$email."?access_token=".$access_token; $get_mem=CallAPI('GET',$mem_url,false); $mem=json_decode($get_mem, true); $add_url= $base_url."Member/"."?access_token=".$access_token; // print_r($mem); if (!array_key_exists("error", $mem)) { echo "<script>window.location.replace(window.location.pathname + window.location.search + window.location.hash);$('.nav-tabs a[href=\"#tab2\"]').tab('show');</script>"; echo "here1"; } else{ echo "here2"; $res=json_decode(CallAPI('POST',$add_url,$add_mem), true); if (!array_key_exists("error", $res)) { $_SESSION['user_email']=$email; echo "<script>alert('User Added');window.open('dashboard.php','_self');</script>"; } else{ echo "<script>alert('Error');</script>"; print_r($res); } } } ?><file_sep>/README.md # Item Auction Network > This is an interactive, distributed, item auction demo. List assets for sale (setting a reserve price), and watch as assets that have met their reserve price are automatically transferred to the highest bidder at the end of the auction. **Contributors** `<NAME>` `<NAME>` ![Home Page](screenshots/main_page.png "Welcome to Decent Auction!") This business network defines: **Participants:** `Member` **Assets:** `Item` `ItemListing` **Transactions:** `makeOffer` `CloseBidding` `RevealBid` `endAuction` `AddMoney` The `makeOffer` function is called when an `Offer` transaction is submitted. The logic simply checks that the listing for the offer is still for sale, and then adds the offer to the listing, and then updates the offers in the `ItemListing` asset registry. The `closeBidding` function is called when a `closeBidding` transaction is submitted for processing. The logic closes the bidding for the item and changes its state from FOR_SALE in the `ItemListing` to BiddingClosed. The `RevealBid` function can be called by the bidders after the bidding has closed. It requests the user for their key. The function then encrypts it using the chaincode's public key and pushes it into the blockchain. The blockchain now essentially has everyone's bids in encrypted form and the keys for encryption in an encrypted form. The `endAuction` function ends the auction and returns the money from the 2nd highest through the lowest bidder to the `Member` participant. It then subtracts the second highest bid from the highest bid and send it to the highest bidder while sending the second highest bid to the member who put the item up for auction. The item can then be transferred to the highest bidder invoking a change in the `ItemListing` and the `Item` asset. To test this Business Network Definition in the **Test** tab: In the `Member` participant registry, create two participants. ``` { "$class": "oorg.example.mynetwork.Member", "balance": 5000, "email": "<EMAIL>", "firstName": "Amy", "lastName": "Williams" } ``` ``` { "$class": "org.acme.item.auction.Member", "balance": 5000, "email": "<EMAIL>", "firstName": "Billy", "lastName": "Thompson" } ``` In the `Item` asset registry, create a new asset of a item owned by `<EMAIL>`. ``` { "$class": "org.acme.item.auction.Item", "vin": "vin:1234", "owner": "resource:org.acme.item.auction.Member#<EMAIL>" } ``` In the `ItemListing` asset registry, create a item listing for car `vin:1234`. ``` { "$class": "org.acme.item.auction.ItemListing", "listingId": "listingId:ABCD", "reservePrice": 3500, "description": "TV", "state": "FOR_SALE", "item": "resource:org.acme.item.auction.Item#vin:1234" } ``` You've just listed a TV for auction, with a reserve price of 3500! As soon as a `ItemListing` has been created (and is in the `FOR_SALE` state) participants can submit `Offer` transactions to bid on an item listing. Submit an `Offer` transaction, by submitting a transaction and selecting `Offer` from the dropdown. ``` { "$class": "org.acme.item.auction.Offer", "bidPrice": 2000, "listing": "resource:org.acme.item.auction.ItemListing#listingId:ABCD", "member": "resource:org.acme.item.auction.Member#<EMAIL>" } ``` ``` { "$class": "org.acme.item.auction.Offer", "bidPrice": 3500, "listing": "resource:org.acme.item.auction.ItemListing#listingId:ABCD", "member": "resource:org.acme.item.auction.Member#<EMAIL>" } ``` To end the auction submit a `CloseBidding` transaction for the listing. ``` { "$class": "org.acme.item.auction.CloseBidding", "listing": "resource:org.acme.item.auction.ItemListing#listingId:ABCD" } ``` To add balance submit a `AddMoney` transaction for the listing. ``` { "$class": "org.acme.item.auction.AddMoney", "amount": 0, "member": "resource:org.acme.item.auction.Member#<EMAIL>" } ``` This simply indicates that the auction for `listingId:ABCD` is now closed, triggering the `closeBidding` function that was described above. To see the Item was sold you need to click on the `Item` asset registry to check the owner of the car. The reserve price was met by owner `<EMAIL>` so you should see the owner of the vehicle is now `<EMAIL>`. If you check the state of the ItemListing with `listingId:ABCD` is should be `SOLD`. If you click on the `Member` asset registry you can check the balance of each Member. You should see that the balance of the buyer `<EMAIL>` has been debited by `3500`, whilst the balance of the seller `<EMAIL>` has been credited with `3500`. Congratulations!
6fa42e23aada6ce75999ac7441a905ef195f2d0b
[ "JavaScript", "Markdown", "Text", "PHP" ]
13
PHP
cryptobuks/item-auction-auction-blockchain
6f4ca8702442f94ac6ad135a843f45d4c71f9ae7
78531b67c4f878c621c1ade206fa251f5e73c934
refs/heads/master
<repo_name>gubo123/wf<file_sep>/Workflow/Controllers/HomeController.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Workflow.Controllers { public class HomeController : Controller { public ActionResult Index(int? id) { ViewBag.Message = "Hello, MVC world!" + id; Workflow.Models.Person p = new Workflow.Models.Person(); p.name = "gubo"; p.age = 33; return View(p); } public ActionResult About() { return View(); } public string Hello(int? id, string param) { string result = string.Empty; if (id != null) { result = "Hello, HomeController Hello function!"; } else { result = "Hello, function with id" + id; } if (param != null) { string paramString = "param is" + param; result += " " + paramString; } return HttpUtility.HtmlEncode(result); } } } <file_sep>/Workflow/Models/Models.cs using System; using System.Collections.Generic; using System.Linq; namespace Workflow.Models { public class Person { public string name { set; get; } public int age { set; get; } } }
0d0933a4f9e3ccf080c875524f45cde65df06bcd
[ "C#" ]
2
C#
gubo123/wf
4d5cdf3385ad5da3bd56bd5b32e33f3c3c7eee5c
2ba8b03af5872ac13003e4a01dbf29f7c728539b
refs/heads/master
<file_sep>import React from 'react'; import { connect } from 'react-redux'; import RadialAxis from './RadialAxis'; import AngularAxis from './AngularAxis'; import RadialPolygon from './RadialPolygon'; import { normalizeData } from '../helpers/numericHelpers'; function mapStateToProps(state) { return { width: state.radialGraphWidth, height: state.radialGraphHeight, trackAverages: state.trackAverages, radialTrack: state.radialTrack, trackKeys: state.trackKeys, tracks: state.tracks } } const RadialGraph = ({trackKeys, width, height, trackAverages, radialTrack, tracks}) => { let radialTrackPolygon = null; if (radialTrack) { const normalData = normalizeData(tracks, [radialTrack]); const data = trackKeys.reduce((obj, key) => ( {...obj, [key]: normalData[key][0]} ), {}); radialTrackPolygon = <RadialPolygon data={data} stroke="#6207e3"/> } let radialAveragePolygon = trackAverages ? <RadialPolygon data={trackAverages} stroke="black" /> : null; return ( <svg width={width} height={height} > <RadialAxis/> <AngularAxis/> {radialAveragePolygon} {radialTrackPolygon} </svg> ); } export default connect(mapStateToProps, null)(RadialGraph); <file_sep>import React, { Component }from 'react'; import { connect } from 'react-redux'; import ScatterplotPointWrapper from './ScatterplotPointWrapper'; import Axis from './Axis'; import * as d3 from 'd3'; import './Scatterplot.css'; function mapStateToUserProps(state) { return { tracks: state.tracks, width: state.scatterplotWidth, height: state.scatterplotHeight, padding: state.scatterplotPadding, xDataLabel: state.xAxisLabel, yDataLabel: state.yAxisLabel } } class Scatterplot extends Component { render() { const xMin = d3.min( this.props.tracks, d => d.audio_features[this.props.xDataLabel] ); const xMax = d3.max( this.props.tracks, d => d.audio_features[this.props.xDataLabel] ); const yMin = d3.min( this.props.tracks, d => d.audio_features[this.props.yDataLabel] ); const yMax = d3.max( this.props.tracks, d => d.audio_features[this.props.yDataLabel] ); const xScale = d3 .scaleLinear() .domain([xMin, xMax]) .range([ this.props.padding.left, this.props.width - this.props.padding.right ]); const yScale = d3 .scaleLinear() .domain([yMin, yMax]) .range([ this.props.height - this.props.padding.top, this.props.padding.bottom ]); return ( <svg width={this.props.width} height={this.props.height}> <Axis scale={xScale} axisType='x'/> <Axis scale={yScale} axisType='y'/> <ScatterplotPointWrapper xDataLabel={this.props.xDataLabel} yDataLabel={this.props.yDataLabel} xScale={xScale} yScale={yScale} /> </svg> ) } } export default connect(mapStateToUserProps, null)(Scatterplot); <file_sep>import React from 'react'; import { connect } from 'react-redux'; import { logout } from '../actions/auth'; import './Navbar.css'; const Navbar = ({logout}) => { return ( <div className="Navbar"> <h2> <i className="fa fa-arrow-circle-o-up" aria-hidden="true"></i> Tune Up </h2> <div> <button onClick={logout} > <i className="fa fa-sign-out" aria-hidden="true"></i> Log out </button> </div> </div> ) } export default connect(null, { logout })(Navbar); <file_sep>import React from 'react'; import { connect } from 'react-redux'; import ScatterplotPoint from './ScatterplotPoint'; function mapStateToProps(state) { return { tracks: state.tracks.concat(state.discoverWeeklyTracks) } } const ScatterplotPointWrapper = ({tracks, xDataLabel, yDataLabel, xScale, yScale}) => ( <g> {tracks.map(item => ( <ScatterplotPoint key={item.track.id} item={item} x={xScale(item.audio_features[xDataLabel])} y={yScale(item.audio_features[yDataLabel])} r={15} /> ))} </g> ); export default connect(mapStateToProps, null)(ScatterplotPointWrapper); <file_sep>import React, { Component }from 'react'; import { connect } from 'react-redux'; import * as d3 from 'd3'; import './Axis.css'; import { axisFormat } from '../helpers/axisHelpers'; function mapStateToProps(state, props) { let axisLabel = props.axisType === 'x' ? state.xAxisLabel : state.yAxisLabel; return { width: state.scatterplotWidth, height: state.scatterplotHeight, padding: state.scatterplotPadding, axisLabel } } class Axis extends Component { componentDidMount() { this.renderAxis(); } componentDidUpdate() { this.renderAxis(); } renderAxis() { let axisOptions = this.props.axisType === 'x' ? { tickSize: this.props.height - this.props.padding.top - this.props.padding.bottom, transform: `translate(0, ${this.props.height - this.props.padding.top})`, direction: d3.axisBottom } : { tickSize: this.props.width - this.props.padding.left - this.props.padding.right, transform: `translate(${this.props.padding.left}, 0)`, direction: d3.axisLeft } d3.select(this.g) .attr("class", `${this.props.axisType}-axis`) .attr("transform", axisOptions.transform) .call(axisOptions.direction(this.props.scale) .tickSize(-axisOptions.tickSize) .tickFormat(d3.format('')) ) } render() { let transformVal = this.props.axisType === 'x' ? `translate(${this.props.width / 2}, ${this.props.padding.top / 2})` : `rotate(-90) translate(${-this.props.height / 2}, ${-this.props.padding.left / 2})`; return ( <g ref={g => this.g = g}> <text className="axis-label" transform={transformVal} > {axisFormat(this.props.axisLabel)} </text> </g> ) } } export default connect(mapStateToProps, null)(Axis); <file_sep>import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; import 'font-awesome/css/font-awesome.css'; import './index.css'; import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import { createStore, applyMiddleware, compose } from 'redux'; import { persistStore, autoRehydrate } from 'redux-persist'; import rootReducer from './reducers/rootReducer'; const store = createStore( rootReducer, compose( applyMiddleware(thunk), window.devToolsExtension ? window.devToolsExtension() : f => f, autoRehydrate() ) ); class AppProvider extends Component { constructor() { super(); this.state = { rehydrated: false }; } componentWillMount() { persistStore(store, {}, () => { this.setState({ rehydrated: true }); }); } render() { if (!this.state.rehydrated) return null return ( <Provider store={store}> <App/> </Provider> ) } } ReactDOM.render( <AppProvider />, document.getElementById('root') ); <file_sep>import React from 'react'; import { connect } from 'react-redux'; import { getDiscoverWeeklyTracks } from '../actions/tracks'; import DiscoverWeeklyTrack from './DiscoverWeeklyTrack'; function mapStateToProps(state) { return { tracks: state.tracks, discoverWeeklyTracks: state.discoverWeeklyTracks } } const DiscoverWeeklyWrapper = ({tracks, discoverWeeklyTracks, getDiscoverWeeklyTracks}) => ( discoverWeeklyTracks.length ? <div style={{display: 'block'}}> {discoverWeeklyTracks.map(item => ( <DiscoverWeeklyTrack item={item} key={item.track.id}/> ))} </div> : <div> <p>Want to see how your the tracks in your Discover Weekly playlist compare?</p> <p>Click the button below to graph them and rank them by how similar they are to what you already like.</p> <button onClick={getDiscoverWeeklyTracks.bind(this, tracks)} > <i className="fa fa-music" aria-hidden="true"></i> Get Discover Weekly Tracks </button> </div> ); export default connect(mapStateToProps, { getDiscoverWeeklyTracks })(DiscoverWeeklyWrapper); <file_sep>import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Login from './Login'; import Auth from './Auth'; import Home from './Home'; class App extends Component { render() { return ( <Router> <Switch> <Route exact path="/" component={Login}/> <Route path="/callback" location={location} component={Auth}/> <Route path="/users/tracks" component={Home}/> </Switch> </Router> ) } } export default App; <file_sep>export function axisFormat(str) { var main = str.split("_")[0] return main[0].toUpperCase() + main.slice(1); } export const getAngle = num => Math.PI * ( 2 * num - 1 / 2 );<file_sep>import React, { Component } from 'react'; import { Redirect } from 'react-router'; import { connect } from 'react-redux'; import { getCurrentUserTracks, checkTrackStatus } from '../actions/tracks'; import Scatterplot from './Scatterplot'; import RadialGraph from './RadialGraph'; import AxisSelect from './AxisSelect'; import Navbar from './Navbar'; import Tooltip from './Tooltip'; import DiscoverWeeklyWrapper from './DiscoverWeeklyWrapper'; import './Home.css'; function mapStateToUserProps(state) { return { username: state.currentUser, tracks: state.tracks } } class Home extends Component { constructor(props) { super(props) this.isLoggedIn = this.isLoggedIn.bind(this); } componentWillMount() { if (!checkTrackStatus()) this.props.getCurrentUserTracks(); } isLoggedIn() { return ( localStorage.getItem('reduxPersist:currentUser') || this.props.username ); } render() { return ( <div> { !this.isLoggedIn() ? <Redirect to="/" /> : <div> <Navbar /> <h3> Welcome! Here's data on the {this.props.tracks.length} most recently saved track{this.props.tracks.length !== 1 ? 's' : ''} for {this.props.username}. </h3> <div> <AxisSelect axis="x"/> <AxisSelect axis="y"/> </div> <div className="Home-row"> <div className="col-40"> <RadialGraph /> </div> <div className="col-40"> <Scatterplot /> <Tooltip /> </div> <div className="col-20"> <DiscoverWeeklyWrapper /> </div> </div> </div> } </div> ) } } export default connect(mapStateToUserProps, { getCurrentUserTracks })(Home); // clicking on sidebar album sets state // update styling for selects // update layout // error handling for now fave tracks or no spotify weekly // remove button click, do both requests on login // - update radial graph design // larger spread of values for recommendations? // stateless functional components<file_sep>import * as d3 from 'd3'; import rootReducer from '../reducers/rootReducer'; export function getRatings(faves, weeklies) { // const allTracks = faves.concat(weeklies) const normalFavorites = normalizeData(faves, faves); const normalWeeklies = normalizeData(faves, weeklies); const distances = averageDistance(normalFavorites, normalWeeklies); const attributeCount = Object.keys(normalFavorites).length return distancesToRatings(distances, attributeCount); } export function getSavedAverages(faves) { const normalFavorites = normalizeData(faves, faves); return Object.keys(normalFavorites).reduce((obj, key) => { const len = normalFavorites[key].length const val = normalFavorites[key].reduce((sum, next) => sum + next, 0) / len; return {...obj, [key]: val} }, {}) } const audioData = (tracks, key) => tracks.map(t => t.audio_features[key]); function scale(tracks, key) { const rawData = audioData(tracks, key); const min = d3.min(rawData); const max = d3.max(rawData); return d3.scaleLinear() .domain([min, max]) .range([0, 1]); } export function normalizeData(normalSet, targetSet) { return rootReducer().trackKeys.reduce(function(prev, cur) { const keyScale = scale(normalSet, cur); const scaledData = audioData(targetSet, cur).map(d => keyScale(d)); return {...prev, [cur]: scaledData} }, {}); } function averageDistance(normalizedFaves, normalizedWeeklies) { const keys = Object.keys(normalizedFaves); const distances = []; const weeklyCount = normalizedWeeklies[keys[0]].length; const faveCount = normalizedFaves[keys[0]].length; for (let i = 0; i < weeklyCount; i++) { const currentWeekly = getNormalizedTrack(normalizedWeeklies, i); let totalDistance = 0; for (let j = 0; j < faveCount; j++) { const currentFave = getNormalizedTrack(normalizedFaves, j); const distance = euclideanDistance(currentWeekly, currentFave); totalDistance += distance / faveCount; } distances.push(totalDistance); } return distances; } function getNormalizedTrack(normData, idx) { return rootReducer().trackKeys.reduce((obj, key) => ( { ...obj, [key]: normData[key][idx] } ), {}); } function euclideanDistance(obj1, obj2) { let distanceSq = 0; for (let key in obj1) { distanceSq += (obj1[key] - obj2[key]) ** 2; } return Math.sqrt(distanceSq); } function distancesToRatings(distances, max) { const scale = d3.scaleLog() .domain([1, max + 1]) .range([100,0]); return distances.map(d => scale(d + 1)); } <file_sep>import React from 'react'; import { connect } from 'react-redux'; import './DiscoverWeeklyTrack.css'; const DiscoverWeeklyTrack = ({item}) => ( <div className="dw-track"> <div className="flex-container"> <img src={item.track.album.images[0].url} alt="Discover Weekly album" /> <div className="track-details"> <p className="score">{Math.round(item.rating)}</p> </div> </div> </div> ); export default connect(null, null)(DiscoverWeeklyTrack); <file_sep>import React from 'react'; import { connect } from 'react-redux'; import { setCurrentTrack, setRadialTrack } from '../actions/tracks'; function mapStateToProps(state) { return { radialTrack: state.radialTrack } } const ScatterplotPoint = ({item, x, y, r, fill, setCurrentTrack, setRadialTrack, radialTrack}) => { // PUT THIS SOMEWHERE ELSE, DWTRACK COMPONENT NEEDS IT TOO function shouldRadialGraphUpdate() { if (radialTrack && radialTrack.track.id === item.track.id) { setRadialTrack(null); } else { setRadialTrack(item); } } let strokeColor = '#000000'; let strokeWidth = '3px'; if (item.discoverWeekly) strokeColor = '#1ed760'; if (radialTrack && item.track.id === radialTrack.track.id) { strokeColor = '#6207e3'; strokeWidth = '5px'; } return ( <g> <defs> <pattern id={item.track.id} patternContentUnits="objectBoundingBox" height="100%" width="100%" > <image preserveAspectRatio="none" height="1" width="1" xlinkHref={item.track.album.images[0].url} ></image> </pattern> </defs> <circle cx={x} cy={y} r={r} fill={`url(#${item.track.id}`} stroke={strokeColor} strokeWidth={strokeWidth} onMouseMove={(e) => setCurrentTrack(e.pageX, e.pageY, item)} onMouseOut={(e) => setCurrentTrack(e.pageX, e.pageY, null)} onClick={shouldRadialGraphUpdate} /> </g> ) }; export default connect(mapStateToProps, { setCurrentTrack, setRadialTrack })(ScatterplotPoint); <file_sep>import axios from 'axios'; export const SET_CURRENT_USER = 'SET_CURRENT_USER'; export const SET_LOGIN_ERROR = 'SET_LOGIN_ERROR'; export const BASE_URL = process.env.REACT_APP_SERVER_URL || 'http://localhost:5000'; export function setAuthorizationToken(token) { if (token) { axios.defaults.headers.common['Authorization'] = `Bearer ${token}` } else { delete axios.defaults.headers.common['Authorization'] } } export function login(code) { return dispatch => { return axios.post(`${BASE_URL}/authenticate`, code) .then(res => { setAuthorizationToken(res.data.access_token) dispatch(setCurrentUser({ username: res.data.display_name, token: res.data.access_token, refreshToken: res.data.refresh_token })); }) .catch(err => { var errObj = Object.keys(err).length ? err : null; dispatch(setLoginError(errObj)); }); } } export function logout() { return dispatch => { localStorage.clear(); setAuthorizationToken(false); dispatch(setCurrentUser({})); } } export function catchLoginErr(err) { return dispatch => { dispatch(setLoginError(err)); } } export function setCurrentUser(userObj) { return { ...userObj, type: SET_CURRENT_USER } } export function setLoginError(errObj) { return { type: SET_LOGIN_ERROR, errObj } }<file_sep>import React from 'react'; import { connect } from 'react-redux'; function mapStateToProps(state) { return { width: state.radialGraphWidth, height: state.radialGraphHeight } } const RadialAxis = ({width, height}) => { let circles = [1, 2, 3, 4, 5, 6, 7, 8].map((num,i,nums) => ( <circle key={i} cx={width/2} cy={height/2} r={0.8 * num / nums.length * width / 2} stroke={num === 2 || num === 6 ? "#1ed760" : "#cccccc"} /> )) return ( <g fill="none" > {circles} </g> ); }; export default connect(mapStateToProps, null)(RadialAxis); <file_sep>import React from 'react'; import { BASE_URL } from '../actions/auth'; import { connect } from 'react-redux'; import { mapStateForAuth } from '../helpers/connectHelpers'; import background from '../background.jpg'; import './Login.css' const Login = props => ( <div> <div id="main-image"> <img src={background} alt="Login page background"/> </div> <div id="content"> <h1> <i className="fa fa-2x fa-arrow-circle-o-up" aria-hidden="true"></i> Tune Up </h1> <p>Visualize your most recent favorite Spotify tracks.</p> <p>Find new songs that you'll love.</p> <a href={`${BASE_URL}/login`} className="login"> <i className="fa fa-3x fa-spotify" aria-hidden="true"></i> Log in with Spotify </a> <p> {props.loginError} </p> </div> </div> ) export default connect(mapStateForAuth, null)(Login); <file_sep>import { SET_CURRENT_USER, SET_LOGIN_ERROR, setAuthorizationToken } from '../actions/auth'; import { SET_CURRENT_USER_TRACKS, SET_DISCOVER_WEEKLY_TRACKS, SET_CURRENT_TRACK, SET_RADIAL_TRACK } from '../actions/tracks'; import { SET_AXIS_LABEL } from '../actions/graph'; const DEFAULT_STATE = { currentTrack: null, currentUser: '', discoverWeeklyTracks: [], loginError: '', scatterplotWidth: 500, scatterplotHeight: 500, scatterplotPadding: { top: 50, left: 80, right: 20, bottom: 50 }, radialGraphWidth: 500, radialGraphHeight: 500, radialTrack: null, tooltipX: 0, tooltipY: 0, trackAverages: null, tracks: [], trackKeys: [ 'danceability', 'energy', 'loudness', 'speechiness', 'acousticness', 'instrumentalness', 'liveness', 'valence', 'tempo', 'duration_ms', ], xAxisLabel: 'danceability', yAxisLabel: 'energy' }; export default (state=DEFAULT_STATE, action={type: null}) => { switch (action.type) { case SET_CURRENT_USER: return Object.keys(action).length > 1 ? { ...state, currentUser: action.username, token: action.token, refreshToken: action.refreshToken, loginError: null } : {}; case SET_LOGIN_ERROR: return { ...state, loginError: action.errObj }; case SET_CURRENT_USER_TRACKS: return { ...state, tracks: action.tracks, trackAverages: action.trackAverages }; case SET_CURRENT_TRACK: return { ...state, tooltipX: action.x, tooltipY: action.y, currentTrack: action.track } case SET_RADIAL_TRACK: return { ...state, radialTrack: action.radialTrack } case SET_DISCOVER_WEEKLY_TRACKS: return { ...state, discoverWeeklyTracks: action.tracks } case SET_AXIS_LABEL: return { ...state, [action.axis]: action.newLabel }; case 'persist/REHYDRATE': setAuthorizationToken(action.payload.token); return Object.assign({}, state, action.payload) default: return state; } }<file_sep>import React, { Component }from 'react'; import { setAxisLabel } from '../actions/graph'; import { connect } from 'react-redux'; import { axisFormat } from '../helpers/axisHelpers'; function mapStateToProps(state, props) { let axisLabel = props.axis === 'x' ? state.xAxisLabel : state.yAxisLabel; return { trackKeys: state.trackKeys, axisLabel }; } class AxisSelect extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); } handleChange(e) { this.props.setAxisLabel( this.props.axis + 'AxisLabel', e.target.value ); } render() { let options = this.props.trackKeys.sort().map((opt,i) => ( <option key={i} value={opt}>{axisFormat(opt)}</option> )); return ( <label> Change {this.props.axis}-axis: <select value={this.props.axisLabel} onChange={this.handleChange} > {options} </select> </label> ) } } export default connect(mapStateToProps, { setAxisLabel })(AxisSelect); <file_sep># New Favorite Songs A React-redux application that uses D3 to visualize data on songs you like, and songs you may like in the future! ### Setup NOTE: In order to get this working locally, you MUST set up the API locally as well! Otherwise, you will not be able to log in with Spotify and get data on your favorite tracks. You can fork and clone the API (written in Flask) [here](https://github.com/mmmaaatttttt/new-favorite-songs-api). This app is created with [`create-react-app`](https://github.com/facebookincubator/create-react-app), so once your server is set up, getting the front-end working should be a breeze. Fork and clone this repository, and cd into the directory: ```sh npm install npm start ``` Enjoy!<file_sep>export const SET_AXIS_LABEL = 'SET_AXIS_LABEL'; export function setAxisLabel(axis, newLabel) { return dispatch => { dispatch({ type: SET_AXIS_LABEL, axis, newLabel }); } }
eb3066c67127ef9199121a3394272b809d0612c3
[ "JavaScript", "Markdown" ]
20
JavaScript
mmmaaatttttt/new-favorite-songs
fdf3bb401d5c9d7ef71b251ccb135dfa411c3cc2
d3bc1d70701be362cc68432ee44359fa5511707f
refs/heads/master
<repo_name>apcragg/ECE306-Car<file_sep>/serial_interrupts.c //============================================================================// // File Name : serial_interrupts.c // // Description: This file contains the ADC ISR code // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "msp430.h" #include "macros.h" #include "adc.h" #include "globals.h" #include "serial.h" //------------------------------------------------------------------------------ // Module Scope Globals // //------------------------------------------------------------------------------ #pragma vector = USCI_A0_VECTOR __interrupt void USCI_A0(void) { switch(UCA0IV) { case NO_INTERRUPT: // Vector 0 - no interrupt break; case RXIFG: // Vector 2 - RXIFG uca0_receive_char(UCA0RXBUF); break; case TXIFG: // Vector 4 – TXIFG uca0_transmit_char(); break; default: break; } } #pragma vector = USCI_A1_VECTOR __interrupt void USCI_A1(void) { switch(UCA1IV) { case NO_INTERRUPT: // Vector 0 - no interrupt break; case RXIFG: // Vector 2 - RXIFG uca1_receive_char(UCA1RXBUF); break; case TXIFG: // Vector 4 – TXIFG uca1_transmit_char(); break; default: break; } }<file_sep>/ports.h #ifndef PORTS_H #define PORTS_H #include "macros.h" #include "globals.h" #include "msp430.h" //------------------------------------------------------------------------------ // Function Declarations void init_ports(void); void init_port_1(void); void init_port_2(void); void init_port_3(void); void init_port_4(void); void init_port_J(void); //------------------------------------------------------------------------------ #endif <file_sep>/command.h #ifndef COMMANDS_H #define COMMANDS_H #include "macros.h" #include "globals.h" #include "msp430.h" #include "serial.h" #include "string.h" #include "motor.h" #include "functions.h" //------------------------------------------------------------------------------ // Function Declarations void receive_command(char*); //------------------------------------------------------------------------------ // Command Defines #define COMMAND_LENGTH (3) #define COMMAND_TIME_POS (2) #define COMMAND_CHAR_SYMBOL ('$') #define COMMAND_TURN_RATIO (8) #define WIFI_COMMAND_SYMBOL ("$") #define LOST_WIFI_COMMAND_SYMBOL ("Di") #define COMMAND_AKNOWLEDGE ("~~") #define AKNOWLEDGE_MESSAGE ("Good News Everyone!\n\r") #define SLOW_BAUD ("~S") #define SLOW_BAUD_MESSAGE ("Set 9600B\n\r") #define SLOW_BAUD_COMMAND ("AT+S.SCFG=console1_speed,9600\r") #define FAST_BAUD ("~F") #define FAST_BAUD_MESSAGE ("Set 115200B\n\r") #define FAST_BAUD_COMMAND ("AT+S.SCFG=console1_speed,115200\r") #define SAVE_COMMAND ("AT&W\r") #define RESET_COMMAND ("AT+CFUN=1\r") #define RESET_MESSAGE ("IOT Device Reset") #define G_MAC_COMMAND ("AT+S.GCFG=nv_wifi_macaddr\r") #define CONNECT_NCSU ("~WIFI.C.NCSU") #define CONNECT_NCSU_MESSAGE ("Connecting to NCSU WiFi at SSID ") #define SET_SSID_NCSU_COMMAND ("AT+S.SSIDTXT=ncsu\r") #define GET_SSID_NCSU_COMMAND ("AT+S.SSIDTXT\r") #define SET_HOST_NAME_COMMAND ("AT+S.SCFG=ip_hostname,ECE306_01_AN\r") #define GET_HOST_NAME_COMMAND ("AT+S.GCFG=ip_hostname\r") #define SET_PRIVACY_MODE_COMMAND ("AT+S.SCFG=wifi_priv_mode,0\r") #define GET_PRIVACY_MODE_COMMAND ("AT+S.GCFG=wifi_priv_mode\r") #define SET_NETWORK_MODE_COMMAND ("AT+S.SCFG=wifi_mode,1\r") #define GET_NETWORK_MODE_COMMAND ("AT+S.GCFG=wifi_mode\r") #define GET_WIFI_STATUS ("~WIFI.S") #define GET_WIFI_STATUS_COMMAND ("AT+S.STS\r") #define GET_WIFI_IP ("~WIFI.IP") #define GET_WIFI_IP_COMMAND ("AT+S.STS=ip_ipaddr\r") #define CAR_FORWARD ("$F") #define CAR_BACKWARD ("$B") #define CAR_RIGHT ("$R") #define CAR_LEFT ("$L") #define CAR_LINE_FOLLOW ("$C") #endif<file_sep>/shapes.h #ifndef SHAPES_H #define SHAPES_H #include "macros.h" #include "motor.h" #include "globals.h" #include "functions.h" #include "timers.h" void five_msec_sleep(unsigned int); //------------------------------------------------------------------------------ // Function Declarations void go_circle(u_int8, u_int8, float, float); void go_triangle(u_int8, u_int8, float, float); void go_figure_eight(u_int8, float, float); void go_back_and_forth(void); void handle_input(u_int8, u_int8); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Module Scope Globals static bool is_running = FALSE; //------------------------------------------------------------------------------ #endif<file_sep>/command.c //============================================================================// // File Name : commands.c // // Description: This file contains the IOT wifi module serial command code. // Author: <NAME> // Date: April 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "command.h" //------------------------------------------------------------------------------ // Module Scope Globals //------------------------------------------------------------------------------ void receive_command(char* command) { BufferString temp_command; temp_command.head = command; temp_command.offset = START_ZERO; if(compare(command, COMMAND_AKNOWLEDGE)) { uca0_transmit_message(AKNOWLEDGE_MESSAGE, NO_OFFSET); } else if(compare(command, SLOW_BAUD)) { uca1_set_current_baud(BAUD_115200); uca0_transmit_message(SLOW_BAUD_MESSAGE, NO_OFFSET); uca1_transmit_message(SLOW_BAUD_COMMAND, NO_OFFSET); five_msec_delay(SECOND + SECOND); uca1_transmit_message(SAVE_COMMAND, NO_OFFSET); five_msec_delay(SECOND); uca1_set_current_baud(BAUD_9600); uca1_transmit_message(RESET_COMMAND, NO_OFFSET); PJOUT &= ~IOT_RESET; five_msec_delay(QUARTER_SECOND); PJOUT |= IOT_RESET; uca0_transmit_message(RESET_MESSAGE, NO_OFFSET); five_msec_delay(QUARTER_SECOND); uca1_transmit_message(G_MAC_COMMAND, NO_OFFSET); } else if(compare(command, FAST_BAUD)) { uca1_set_current_baud(BAUD_9600); uca0_transmit_message(FAST_BAUD_MESSAGE, NO_OFFSET); uca1_transmit_message(FAST_BAUD_COMMAND, NO_OFFSET); five_msec_delay(SECOND + SECOND); uca1_transmit_message(SAVE_COMMAND, NO_OFFSET); five_msec_delay(SECOND); uca1_set_current_baud(BAUD_115200); uca1_transmit_message(RESET_COMMAND, NO_OFFSET); PJOUT &= ~IOT_RESET; five_msec_delay(QUARTER_SECOND); PJOUT |= IOT_RESET; uca0_transmit_message(RESET_MESSAGE, NO_OFFSET); } else if(compare(command, CONNECT_NCSU)) { uca0_transmit_message(CONNECT_NCSU_MESSAGE, NO_OFFSET); uca1_transmit_message(SET_SSID_NCSU_COMMAND, NO_OFFSET); uca1_transmit_message(GET_SSID_NCSU_COMMAND, NO_OFFSET); five_msec_delay(QUARTER_SECOND); uca1_transmit_message(SET_HOST_NAME_COMMAND, NO_OFFSET); uca1_transmit_message(GET_HOST_NAME_COMMAND, NO_OFFSET); five_msec_delay(QUARTER_SECOND); uca1_transmit_message(SET_PRIVACY_MODE_COMMAND, NO_OFFSET); uca1_transmit_message(GET_PRIVACY_MODE_COMMAND, NO_OFFSET); five_msec_delay(QUARTER_SECOND); uca1_transmit_message(SET_NETWORK_MODE_COMMAND, NO_OFFSET); uca1_transmit_message(GET_NETWORK_MODE_COMMAND, NO_OFFSET); uca1_transmit_message(SAVE_COMMAND, NO_OFFSET); uca1_transmit_message(GET_NETWORK_MODE_COMMAND, NO_OFFSET); uca1_transmit_message(SAVE_COMMAND, NO_OFFSET); five_msec_delay(QUARTER_SECOND); uca1_transmit_message(RESET_COMMAND, NO_OFFSET); PJOUT &= ~IOT_RESET; five_msec_delay(QUARTER_SECOND); PJOUT |= IOT_RESET; uca0_transmit_message(RESET_MESSAGE, NO_OFFSET); } else if(compare(command, GET_WIFI_STATUS)) { uca1_transmit_message(GET_WIFI_STATUS_COMMAND, NO_OFFSET); } else if(compare(command, GET_WIFI_IP)) { uca1_transmit_message(GET_WIFI_IP_COMMAND, NO_OFFSET); } // Forward Command else if(find(CAR_FORWARD, temp_command)) { display_1 = CLEAR_LINE; display_2 = command; display_3 = CLEAR_LINE; display_4 = CLEAR_LINE; set_motor_speed(R_FORWARD, (int) (MAX_SPEED * 0.87f)); set_motor_speed(L_FORWARD, MAX_SPEED); lcd_BIG_mid(); five_msec_delay(QUARTER_SECOND); Display_Process(); uca0_transmit_message("SUCCESS", NO_OFFSET); turn_on_motor(R_FORWARD); turn_on_motor(L_FORWARD); if(CH_TO_DIG(command[COMMAND_TIME_POS]) <= 9) five_msec_delay(SECOND * CH_TO_DIG(command[COMMAND_TIME_POS]) / COMMAND_TURN_RATIO); turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); lcd_4line(); if(command[COMMAND_LENGTH] == COMMAND_CHAR_SYMBOL) receive_command(command + COMMAND_LENGTH); } // Backward Command else if(find(CAR_BACKWARD, temp_command)) { display_1 = CLEAR_LINE; display_2 = command; display_3 = CLEAR_LINE; display_4 = CLEAR_LINE; lcd_BIG_mid(); five_msec_delay(QUARTER_SECOND); Display_Process(); uca0_transmit_message("SUCCESS", NO_OFFSET); turn_on_motor(R_REVERSE); turn_on_motor(L_REVERSE); five_msec_delay(SECOND * CH_TO_DIG(command[COMMAND_TIME_POS])); turn_off_motor(R_REVERSE); turn_off_motor(L_REVERSE); lcd_4line(); if(command[COMMAND_LENGTH] == COMMAND_CHAR_SYMBOL) receive_command(command + COMMAND_LENGTH); } // Right Command else if(find(CAR_RIGHT, temp_command)) { display_1 = CLEAR_LINE; display_2 = command; display_3 = CLEAR_LINE; display_4 = CLEAR_LINE; lcd_BIG_mid(); five_msec_delay(QUARTER_SECOND); Display_Process(); uca0_transmit_message("SUCCESS", NO_OFFSET); turn_on_motor(R_REVERSE); turn_on_motor(L_FORWARD); if(CH_TO_DIG(command[COMMAND_TIME_POS]) <= 9) five_msec_delay(SECOND * CH_TO_DIG(command[COMMAND_TIME_POS]) / COMMAND_TURN_RATIO); turn_off_motor(R_REVERSE); turn_off_motor(L_FORWARD); lcd_4line(); if(command[COMMAND_LENGTH] == COMMAND_CHAR_SYMBOL) receive_command(command + COMMAND_LENGTH); } // Left Command else if(find(CAR_LEFT, temp_command)) { display_1 = CLEAR_LINE; display_2 = command; display_3 = CLEAR_LINE; display_4 = CLEAR_LINE; lcd_BIG_mid(); five_msec_delay(QUARTER_SECOND); Display_Process(); uca0_transmit_message("SUCCESS", NO_OFFSET); turn_on_motor(R_FORWARD); turn_on_motor(L_REVERSE); if(CH_TO_DIG(command[COMMAND_TIME_POS]) <= 9) five_msec_delay(SECOND * CH_TO_DIG(command[COMMAND_TIME_POS]) / COMMAND_TURN_RATIO); turn_off_motor(R_FORWARD); turn_off_motor(L_REVERSE); lcd_4line(); if(command[COMMAND_LENGTH] == COMMAND_CHAR_SYMBOL) receive_command(command + COMMAND_LENGTH); } else if(find(CAR_LINE_FOLLOW, temp_command)) { is_follow_running = is_follow_running ? FALSE : TRUE; } } <file_sep>/adc.h #ifndef ADC_H #define ADC_H #include "macros.h" #include "globals.h" #include "msp430.h" static u_int8 conversion_flag = FALSE; // eh maybe? //------------------------------------------------------------------------------ // Function Declarations void init_adc(void); void set_conversion_flag(u_int8); void set_adc_val(u_int8, int); int get_adc_val(u_int8); int analog_read(int); //------------------------------------------------------------------------------ #endif <file_sep>/adc_interrupts.c //============================================================================// // File Name : adc_interrupts.c // // Description: This file contains the ADC ISR code // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "msp430.h" #include "macros.h" #include "adc.h" #pragma vector=ADC10_VECTOR __interrupt void ADC10_ISR(void) { if(ADC10IV | ADC10IV_ADC10IFG) set_conversion_flag(TRUE); int channel = ADC10MCTL0 & NIBBLE; set_adc_val(channel, ADC10MEM0); ADC10IV = CLEAR_REGISTER; }<file_sep>/pwm.h #ifndef PWM_H #define PWM_H #include "macros.h" //------------------------------------------------------------------------------ // Function Declarations void init_pwm(unsigned short volatile*); void set_pwm_resolution(unsigned short volatile*, unsigned int); void set_pwm_value(unsigned short volatile*, unsigned int); void set_pwm_output(unsigned short volatile*); void start_pwm(unsigned short volatile*); void disable_pwm(unsigned short volatile*); void enable_pwm(unsigned short volatile*); //------------------------------------------------------------------------------ #endif<file_sep>/ports.c //============================================================================// // File Name : ports.c // // Description: This file contains the Initialization for all port pins // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "ports.h" //------------------------------------------------------------------------------ // Function Name : Init_Ports // // Description: This function calls the initialization functions for each // Port on the MSP430 // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void init_ports(void) { init_port_1(); init_port_2(); init_port_3(); init_port_4(); init_port_J(); } //------------------------------------------------------------------------------ // Function Name : Init_Port_1 // // Description: This function initializes Port_1 on the MSP430 // Sets the Pin Modes, Directions, and Initial Coniditons // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void init_port_1(void) { //Sets base Port ain a full GPIO Input state P1SEL0 = GPIO_SEL; P1SEL1 = GPIO_SEL; P1DIR = GPIO_IN; //Set Port Functions other than GPIO P1SEL0 |= V_DETECT_R; P1SEL1 |= V_DETECT_R; P1SEL0 |= V_DETECT_L; P1SEL1 |= V_DETECT_L; P1SEL0 |= V_THUMB; P1SEL1 |= V_THUMB; P1SEL0 &= ~SPI_SIMO; P1SEL1 |= SPI_SIMO; P1SEL0 &= ~SPI_SOMI; P1SEL1 |= SPI_SOMI; //Set Port Directions Other than Input P1DIR |= IR_LED; P1DIR |= SPI_CS_LCD; P1DIR |= RESET_LCD; //Set Port Output States P1OUT &= ~IR_LED; P1OUT |= SPI_CS_LCD; P1OUT &= ~RESET_LCD; //Set Port Pullup Resistors P1REN |= SPI_SOMI; } //------------------------------------------------------------------------------ // Function Name : Init_Port_2 // // Description: This function initializes Port_1 on the MSP430 // Sets the Pin Modes, Directions, and Initial Coniditons // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void init_port_2(void) { //Sets base Port ain a full GPIO Input state P2SEL0 = GPIO_SEL; P2SEL1 = GPIO_SEL; P2DIR = GPIO_IN; //Set Port Functions other than GPIO P2SEL0 &= ~USB_TDX; P2SEL1 |= USB_TDX; P2SEL0 &= ~USB_RDX; P2SEL1 |= USB_RDX; P2SEL0 &= ~SPI_SCK; P2SEL1 |= SPI_SCK; P2SEL0 &= ~CPU_TXD; P2SEL1 |= CPU_TXD; P2SEL0 &= ~CPU_RXD; P2SEL1 |= CPU_RXD; //Set Port Directions Other than Input P2DIR |= UNDEF_1; P2DIR |= UNDEF_2; P2DIR |= UNDEF_3; //Set Port Output States P2OUT |= SPI_SCK; P2OUT &= ~UNDEF_1; P2OUT &= ~UNDEF_2; P2OUT &= ~UNDEF_3; //Set Port Pullup Resistors P2REN &= ~UNDEF_1; P2REN &= ~UNDEF_2; P2REN &= ~UNDEF_3; } //------------------------------------------------------------------------------ // Function Name : Init_Port_3 // // Description: This function initializes Port_1 on the MSP430 // Sets the Pin Modes, Directions, and Initial Coniditons // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void init_port_3(void) { //Sets base Port ain a full GPIO Input state P3SEL0 = GPIO_SEL; P3SEL1 = GPIO_SEL; P3DIR = GPIO_IN; //Set Port Functions other than GPIO // n/a for Port 3 //Set Port Directions Other than Input P3DIR |= LCD_BACKLIGHT; P3DIR |= R_FORWARD; P3DIR |= R_REVERSE; P3DIR |= L_FORWARD; P3DIR |= L_REVERSE; //Set Port Output States other than Zero P3OUT &= ~LCD_BACKLIGHT; P3OUT &= ~R_FORWARD; P3OUT &= ~R_REVERSE; P3OUT &= ~L_FORWARD; P3OUT &= ~L_REVERSE; //Set Port Pullup Resistors P3REN &= ~ACCEL_X; P3REN &= ~ACCEL_Y; P3REN &= ~ACCEL_Z; } //------------------------------------------------------------------------------ // Function Name : Init_Port_4 // // Description: This function initializes Port_1 on the MSP430 // Sets the Pin Modes, Directions, and Initial Coniditons // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void init_port_4(void) { //Sets base Port ain a full GPIO Input state P4SEL0 = GPIO_SEL; P4SEL1 = GPIO_SEL; P4DIR = GPIO_IN; //Set Port Functions other than GPIO // n/a for Port 4 //Set Port Directions Other than Input // n/a for Port 4 //Set Port Output States P4OUT |= SW1; P4OUT |= SW2; //Set Port Pullup Resistors P4REN |= SW1; P4REN |= SW2; } //------------------------------------------------------------------------------ // Function Name : Init_Port_J // // Description: This function initializes Port_J on the MSP430 // Sets the Pin Modes, Directions, and Initial Coniditons // Arguements: void // Returns: void // // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void init_port_J(void) { //Sets base Port ain a full GPIO Input state PJSEL0 = GPIO_SEL; PJSEL1 = GPIO_SEL; PJDIR = GPIO_IN; //Set Port Functions other than GPIO // n/a for Port 3 //Set Port Directions Other than Input PJDIR |= IOT_WAKEUP; PJDIR |= IOT_FACTORY; PJDIR |= IOT_STA_MINIAP; PJDIR |= IOT_RESET; //Set Port Output States other than Zero PJOUT &= ~IOT_WAKEUP; PJOUT &= ~IOT_FACTORY; PJOUT |= IOT_STA_MINIAP; PJOUT &= ~IOT_RESET; //Set Port Pullup Resistors // n/a for Port J } <file_sep>/menu.c //============================================================================// // File Name : menu.c // // Description: This file contains the menu code. // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "menu.h" //------------------------------------------------------------------------------ // Local Varriables static u_int8 current_menu = MENU_WIFI; static u_int8 menu_pressed_count = START_ZERO; static char buffer[DISPLAY_LENGTH] = "0"; static const u_int8 num_menu_options[NUM_MAIN_OPTIONS] = {5, 4, 4, 5, 1}; static long int current_time = START_ZERO; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Global Varriables char line_buffer1[DISPLAY_LENGTH]; char line_buffer2[DISPLAY_LENGTH]; char line_buffer3[DISPLAY_LENGTH]; char line_buffer4[DISPLAY_LENGTH]; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Static Const Data static char* const main_menu_options[NUM_LCD_LINES] = { "1 Serial", "2 Line", "3 Shapes", "4 Wifi" }; static char* const serial_menu_options[NUM_LCD_LINES] = { "Set 9600", "Set 115200", "Follow Line", " " }; static char* const line_menu_options[NUM_LCD_LINES] = { "1 Blk Cal", "2 Wht Cal", "3 Basic", " " }; static char* const shape_menu_options[NUM_LCD_LINES] = { "1 TODO", "2 TODO", "3 TODO", "4 TODO" }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Function Name : update_menu // // Description: This function updates the menu given the current switches and // thumb wheel value. // Arguements: void // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void update_menu() { int adc_val; posL1 = DISPLAY_LINE_0; posL2 = DISPLAY_LINE_0; posL3 = DISPLAY_LINE_0; posL4 = DISPLAY_LINE_0; // TODO MOVE TO EACH OWN FUNCTION switch(current_menu) { case MENU_MAIN: display_1 = main_menu_options[ARR_POS_0]; display_2 = main_menu_options[ARR_POS_1]; display_3 = main_menu_options[ARR_POS_2]; display_4 = main_menu_options[ARR_POS_3]; break; case MENU_SERIAL: display_1 = serial_menu_options[ARR_POS_0]; display_2 = serial_menu_options[ARR_POS_1]; display_3 = " "; display_4 = " "; break; case MENU_LINE: display_1 = line_menu_options[ARR_POS_0]; display_2 = line_menu_options[ARR_POS_1]; display_3 = line_menu_options[ARR_POS_2]; display_3 = buffer; adc_val = (analog_read(ADC0)); buffer[ARR_POS_0] = '0'; buffer[ARR_POS_1] = 'x'; buffer[ARR_POS_2] = HEX_TO_CH((adc_val >> BYTE_SIZE ) & NIBBLE); buffer[ARR_POS_3] = HEX_TO_CH((adc_val >> NIBBLE_SIZE) & NIBBLE); buffer[ARR_POS_4] = HEX_TO_CH((adc_val) & NIBBLE); // buffer[ARR_POS_5] = NULL_TERM; adc_val = (analog_read(ADC1)); buffer[5] = '0'; buffer[6] = 'x'; buffer[7] = HEX_TO_CH((adc_val >> BYTE_SIZE ) & NIBBLE); buffer[8] = HEX_TO_CH((adc_val >> NIBBLE_SIZE) & NIBBLE); buffer[9] = HEX_TO_CH((adc_val) & NIBBLE); buffer[10] = NULL_TERM; break; case MENU_SHAPES: display_1 = shape_menu_options[ARR_POS_0]; display_2 = shape_menu_options[ARR_POS_1]; display_3 = shape_menu_options[ARR_POS_2]; display_4 = shape_menu_options[ARR_POS_3]; break; case MENU_WIFI: if(system_time > current_time + SECOND * DOUBLE) { int i; uca1_transmit_message(GET_WIFI_IP_COMMAND, NO_OFFSET); five_msec_delay((QUARTER_SECOND / DIVIDE_BY_TWO) / DIVIDE_BY_TWO); BufferString a = uca1_read_buffer(FALSE); a.offset += IP_STATUS_OFFSET; display_1 = CLEAR_LINE; display_2 = " ip_addr"; for(i = START_ZERO; i <= DISPLAY_LENGTH; i++) { line_buffer3[i] = ' '; line_buffer4[i] = ' '; } for(i = START_ZERO; i < ARR_POS_7; i++) { line_buffer3[ARR_POS_1 + i] = a.head[(a.offset + i) % BUFF_SIZE]; } for(i = START_ZERO; i < ARR_POS_7; i++) { line_buffer4[ARR_POS_2 + i] = a.head[(a.offset + i + ARR_POS_7) % BUFF_SIZE]; } display_3 = line_buffer3; display_4 = line_buffer4; current_time = system_time; } break; default: current_menu = MENU_MAIN; break; } switch(menu_pressed_count) { case DISPLAY_LINE_1: if((system_time % SECOND) > HALF_SECOND) display_1 = " "; break; case DISPLAY_LINE_2: if((system_time % SECOND) > HALF_SECOND) display_2 = " "; break; case DISPLAY_LINE_3: if((system_time % SECOND) > HALF_SECOND) display_3 = " "; break; case DISPLAY_LINE_4: if((system_time % SECOND) > HALF_SECOND) display_4 = " "; break; } } //------------------------------------------------------------------------------ // Function Name : handle_input // // Description: This function handles input from hardware/software switch // presses. // Arguements: void // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void menu_handle_input(u_int8 sw_pressed) { if(sw_pressed & SW_2) { menu_pressed_count = (menu_pressed_count + INCREMENT) % num_menu_options[current_menu]; } else if(sw_pressed & SW1) { switch(current_menu) { case MENU_MAIN: if(menu_pressed_count == MENU_SERIAL) { current_menu = MENU_SERIAL; display_3 = " "; } else if(menu_pressed_count == MENU_LINE) { current_menu = MENU_LINE; } else if(menu_pressed_count == MENU_SHAPES) { current_menu = MENU_SHAPES; } else if(menu_pressed_count == MENU_WIFI) { current_menu = MENU_WIFI; } menu_pressed_count = MENU_MAIN; break; case MENU_SERIAL: if(menu_pressed_count == BAUD_9600) { uca0_set_current_baud(BAUD_9600); uca0_transmit_message("Hello World", NO_OFFSET); } else if(menu_pressed_count == BAUD_115200) { uca0_set_current_baud(BAUD_115200); } else { current_menu = MENU_MAIN; menu_pressed_count = MENU_MAIN; } break; case MENU_LINE: if(menu_pressed_count == BLACK_VAL || menu_pressed_count == WHITE_VAL) { calibrate_sensors(menu_pressed_count); } else if(menu_pressed_count == RUN_BASIC_OPTION) { is_follow_running = TRUE; } else { current_menu = MENU_MAIN; menu_pressed_count = MENU_MAIN; } break; case MENU_SHAPES: { } break; case MENU_WIFI: current_menu = MENU_MAIN; menu_pressed_count = MENU_MAIN; break; default: current_menu = MENU_MAIN; break; } } } <file_sep>/timer_interrupts.c //============================================================================// // File Name : timer_interrupts.c // // Description: This file contains the timer ISR code // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "msp430.h" #include "macros.h" #include "timers.h" //------------------------------------------------------------------------------ // Interrupt Name : timer_A0_CCR0_interupt // // Description: This ISR services the Timer A0 interrupt which indicates 5ms // have past. Updates the timer_count varriable. Resets the // interrupt flag. // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ #pragma vector = TIMER0_A0_VECTOR __interrupt void timer_A0_CCR0_interupt(void) { increment_timer_count(); TA0CCTL0 &= ~TAxCTL_IFG; // clears the interupt flag } //------------------------------------------------------------------------------ // Interrupt Name : timer_B1_CCR0_interupt // // Description: This ISR services the Timer B1 overflow interrupt and // simply clears the interrupt flags. // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ #pragma vector = TIMER1_B1_VECTOR __interrupt void timer_B1_CCR0_interupt(void) { TB1CCTL1 &= ~TAxCTL_IFG; // clears the interupt flag TB1CCTL2 &= ~TAxCTL_IFG; // clears the interupt flag } //------------------------------------------------------------------------------ // Interrupt Name : timer_B2_CCR0_interupt // // Description: This ISR services the Timer B2 overflow interrupt and // simply clears the interrupt flags. // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ #pragma vector = TIMER2_B1_VECTOR __interrupt void timer_B2_CCR0_interupt(void) { TB2CCTL1 &= ~TAxCTL_IFG; // clears the interupt flag TB2CCTL2 &= ~TAxCTL_IFG; // clears the interupt flag } //------------------------------------------------------------------------------ // Interrupt Name : timer_A1_CCR1_interupt // // Description: This ISR services the Timer A1 CCR1 compare mode interrupt // that is used for debouncing the on board switches. It // reenables the port interrupts after the debounce time is up // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ #pragma vector = TIMER1_A1_VECTOR __interrupt void timer_A1_CCR1_interupt(void) { TA1CCTL1 &= ~CCIFG; // clears the interupt flag TA1CCTL1 &= ~CCIE; P4IE |= SW_1 | SW_2; } //------------------------------------------------------------------------------ // Interrupt Name : timer_A1_CTL_interupt // // Description: This ISR services the Timer A1 overflow interrupt and clears // the flags. // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ #pragma vector = TIMER1_A0_VECTOR __interrupt void timer_A1_CTL_interupt(void) { TA1CTL &= ~CCIFG; // clears the interupt flag }<file_sep>/macros.h #ifndef MACROS_H #define MACROS_H //============================================================================// // File Name : macros.h // // Description: This file contains he macro define defentions // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// typedef unsigned char u_int8; typedef unsigned char bool; #include "msp430.h" // Required defines // In the event the universe no longer exists, this bit will reset #define ALWAYS (1) #define CNTL_STATE_INDEX (3) // Control States #define LED (0xFF) // Use LED's #define CONTROL (0xFE) // USe Control Logic #define CNTL_STATE_INDEX (3) #define false (0) #define true (1) #define UINT_16_MAX (0xFFFF) #define PI (3.1415) // PI #define INVALID (-1) #define NIBBLE (0xF) #define NIBBLE_SIZE (4) #define BYTE_SIZE (8) #define INCREMENT (1) #define ABS(X) ((X) > 0 ? (X) : (-1 * (X))) #define NULL (0) #define OFF_BY_ONE (1) #define START_ZERO (0) #define DIVIDE_BY_TWO (2) #define DOUBLE (2) #define TENS (10) #define HUNDREDS (100) #define THOUSANDS (1000) // Helper macros #define DIG_TO_CH(D) ((D)+0x30) // Converts a digit to an ASCII char #define HEX_TO_CH(H) ((H) > 9 ? ((H) % 10) + 'A' : (H) + '0') #define CH_TO_DIG(C) ((C) - 0x30) // LCD #define LCD_HOME_L1 (0x80) #define LCD_HOME_L2 (0xA0) #define LCD_HOME_L3 (0xC0) #define LCD_HOME_L4 (0xE0) #define LCD_BASE (0x00) #define NULL_TERM (0x00) #define LCD_LENGTH (10) //Timeing Values #define FALSE (0x00) #define TRUE (0x01) #define START_VAL (0x00) #define SIZE_CHANGE_TIME (5) #define TIMER_COUNT (1000) #define OFF_BY_ONE_OFFSET (1) #define QUARTER_SECOND (50u) #define HALF_SECOND (100u) #define THREE_QUARTER_SECOND (150u) #define SECOND (200u) #define SECOND_AND_A_QUARTER (250u) #define FIVE_SECONDS (SECOND*5) #define BY_FIVE (5) //Display Values #define DISPLAY_LENGTH (11) #define DISPLAY_LINE_0 (0) #define DISPLAY_LINE_1 (1) #define DISPLAY_LINE_2 (2) #define DISPLAY_LINE_3 (3) #define DISPLAY_LINE_4 (4) // Array Position #define ARR_POS_0 (0) #define ARR_POS_1 (1) #define ARR_POS_2 (2) #define ARR_POS_3 (3) #define ARR_POS_4 (4) #define ARR_POS_5 (5) #define ARR_POS_6 (6) #define ARR_POS_7 (7) //------------------------------------------------------------------------------ // Port Macros //------------------------------------------------------------------------------ // General Purpose Things #define GPIO_SEL (0x00) // Sets Port as I/O #define CLEAR_REGISTER (0x0000) // Clears registers with 0x00 // Port 1 #define V_DETECT_R (0x01) // Port 1.0 #define V_DETECT_L (0x02) // Port 1.1 #define IR_LED (0x04) // Port 1.2 #define V_THUMB (0x08) // Port 1.3 #define SPI_CS_LCD (0x10) // Port 1.4 #define RESET_LCD (0x20) // Port 1.5 #define SPI_SIMO (0x40) // Port 1.6 #define SPI_SOMI (0x80) // Port 1.7 // Port 2 #define USB_TDX (0x01) // Port 2.0 #define USB_RDX (0x02) // Port 2.1 #define SPI_SCK (0x04) // Port 2.2 #define UNDEF_1 (0x08) // Port 2.3 #define UNDEF_2 (0x10) // Port 2.4 #define CPU_TXD (0x20) // Port 2.5 #define CPU_RXD (0x40) // Port 2.6 #define UNDEF_3 (0x80) // Port 2.7 // Port 3 #define ACCEL_X (0x01) // Port 3.0 #define ACCEL_Y (0x02) // Port 3.1 #define ACCEL_Z (0x04) // Port 3.2 #define LCD_BACKLIGHT (0x08) // Port 3.3 #define R_FORWARD (0x10) // Port 3.4 #define R_REVERSE (0x20) // Port 3.5 #define L_FORWARD (0x40) // Port 3.6 #define L_REVERSE (0x80) // Port 3.7 // Port 4 #define SW1 (0x01) // Port 4.0 #define SW2 (0x02) // Port 4.1 // Port J #define IOT_WAKEUP (0x01) // Port J.0 #define IOT_FACTORY (0x02) // Port J.1 #define IOT_STA_MINIAP (0x04) // Port J.2 #define IOT_RESET (0x08) // Port J.3 // Port Direction #define GPIO_IN (0x00) // Value for full Port GPIO input #define GPIO_OUT (0xFF) // Value for full Port GPIO output //------------------------------------------------------------------------------ // Other macros //------------------------------------------------------------------------------ //pwm things #define NUM_A_TIMERS (7) // Number of timer registers on Timer A #define TIMER_A0 (0x00) // Timer A0 #define TIMER_A1 (0x01) // Timer A1 #define TIMER_A2 (0x02) // Timer A2 #define TIMER_A3 (0x03) // Timer A3 #define TIMER_A4 (0x04) // Timer A4 #define TIMER_A5 (0x05) // Timer A5 #define TIMER_A6 (0x06) // Timer A6 #define PWM_RES (4096*7) // PWM resolution // Motor constants #define MOTOR_ADJ_FAC (1.0f) // Left motor compensation #define MAX_SPEED ((int) (PWM_RES * 1.0f)) #define MIN_SPEED ((int) (PWM_RES * .10f)) #define MOTOR_SPD_OFF (0x00) // Motor speed of zero #define ACTIVE_BREAK (12) #define TURN_ON_COMP (25) // ADC things #define ADC0 (0) // ADC0 Pin #define ADC1 (1) // ADC1 Pin #define ADC2 (2) // ADC2 Pin #define ADC3 (3) // ADC3 Pin #define MAX_ADC10 (0x03FF) // Max ADC 10 bit value #define MIN_ADC10 (0x0000) // Min ADC 10 bit value // Menu things #define MENU_MAIN (0) #define MENU_SERIAL (1) #define MENU_LINE (2) #define MENU_SHAPES (3) #define MENU_WIFI (4) #define NUM_MAIN_OPTIONS (5) #define NUM_LCD_LINES (4) #define BACK_OPTION (0) #define BLACK_VAL (1) #define WHITE_VAL (2) #define RUN_BASIC_OPTION (3) #define CLEAR_LINE (" ") // Serial things #define BAUD_9600 (1) #define BAUD_115200 (2) #define BAUD_9600_S "9600 Baud" #define BAUD_115200_S "115600 Baud" #define BAUD_9600_VAL (9600) #define BAUD_115600_VAL (115600) #define C_RETURN ('\r') #define NO_INTERRUPT (0) #define RXIFG (2) #define TXIFG (4) #define IP_STATUS_OFFSET (15) // Line things #define RIGHT_DETECT (0) #define LEFT_DETECT (1) #define TRIGGER_COUNT (3) #define AVG_2 (2) #define ERROR_BASELINE (225) #define NO_ERROR (0) #define ON_LINE (0) #define RIGHT_SIDE (1) #define LEFT_SIDE (2) #define MAX_LINE_SPEED ((int) (MAX_SPEED * .375f)) // Shape Constants #define NUM_SHAPES (7) // Number of possible shapes #define INCREMENT (1) // Shape counter increment #define DIR_LEFT (0x00) // Port side #define DIR_RIGHT (0x01) // Starboard side #define NUM_TRI_PTS (3) // Number of points in a triangle #define R_LEN_COMP (1.30f)// Right motor durration compensation #define BATT_COMP (4.99f / 4.88f) // current battery level #define UN_COMP (1.0f) // No adjustment compensation factor // Switch things #define SW_1 (0x01) // Switch 1 #define SW_2 (0x02) // Switch 2 #define TA1_CLK_F (10000)// Timer A0 frequency in hz #define ONE_MSEC (1000) // Number of msec in a second #define PRESSED_DEBOUNCE (200) // Debounce time for switch press #define RELEASED_DEBOUNCE (200) // Debounce time for switch press // Serial things #define BUFF_SIZE (128) #define NUM_BUF_SIZE (6) #define DEMO_COUNT (100) #define RESET_COUNT (64535) #define NO_OFFSET (0) #define BRW_115200 (4) #define BRW_9600 (5) #define MCTL_115200 (0x5551) #define MCTL_9600 (0x4911) //Timer things #define TA_CTL_BASE (TA0CTL) #define TA_CCR0_BASE (TA0CCR0) #define TIMER_STOP (0x0030) //Stop mask for timer Bits 5-4 11 #define TIMER_UP (0x0010) //Continuous mask for timer Bits 5-4 01 #define TIMER_CONTINUOUS (0x0020) //Continuous mask for timer Bits 5-4 10 #define CAPTURE_MODE (0xC000) // Timer_A capture mode #define NO_CAPTURE (0x0000) // No capture bit mask #define COMPARE_MODE (0x0100) // Compare mode #define OUTMOD (0x0070) // Outmod bit mask #define OUTMOD_RES_SET (0x0070) // Outmod Reset/Set mode #define OUTMOD_SET_RES (0x0030) // Outmod Set/Reset mode #define OUTMOD_TOGGLE (0x0040) // Outmod toggle #define TIMER_DIVIDE (0x00C0) // Timer division #define TAxCTL_IFG (0x0001) // Timer CTL interupt flag #define Px_IFG (0x0001) // Port interrupt flag // Timer CCRx Values #define TA0_FREQ (40000) // Value for the CCR0 register for 200hz #endif<file_sep>/line.h #ifndef LINE_H #define LINE_H #include "macros.h" #include "globals.h" #include "msp430.h" #include "adc.h" #include "motor.h" #include "timers.h" #include "functions.h" static int r_black_cal = 0x22b; static int r_white_cal = 0x40; static int l_black_cal = 0x22b; static int l_white_cal = 0x40; //------------------------------------------------------------------------------ // Function Declarations void calibrate_sensors(u_int8); u_int8 determine_line(u_int8); void run_follow(); void run_basic(); //------------------------------------------------------------------------------ #endif <file_sep>/motor.h #ifndef MOTOR_H #define MOTOR_H #include "pwm.h" //------------------------------------------------------------------------------ // Function Declarations void right_forward(void); void left_forward(void); void turn_on_motor(u_int8); void turn_off_motor(u_int8); void set_motor_speed(u_int8, int); void active_brake(); void active_brake_reverse(); //------------------------------------------------------------------------------ #endif<file_sep>/motor.c //============================================================================// // File Name : motor.c // // Description: This file contains the motor control functions. This assumes // R_FORWARD is on a pin with TB1.1 // L_FORWARD is on a pin with TB2.1 // R_REVERSE is on a pin with TB1.2 // L_FORWARD is on a pin with TB2.2 // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "msp430.h" #include "macros.h" #include "motor.h" #include "timers.h" //------------------------------------------------------------------------------ // Function Name : right_forward DEPRECATED DON'T USE // // Description: This function turns on the right motor going forward. // First it ensures the reverse drive is turned off // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void inline right_forward() { if(!(P3OUT & R_FORWARD)) { P3OUT &= ~R_REVERSE; P3OUT |= R_FORWARD; } } //------------------------------------------------------------------------------ // Function Name : left_forward DEPRECATED DON'T USE // // Description: This function turns on the left motor going forward. // First it ensures the reverse drive is turned off // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void inline left_forward() { if(!(P3OUT & L_FORWARD)) { P3OUT &= ~L_REVERSE; P3OUT |= L_FORWARD; } } //------------------------------------------------------------------------------ // Function Name : turn_on_motor // // Description: This function sets turns the passed motor off // Arguements: u_int8 motor // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void turn_on_motor(u_int8 motor) { switch(motor) { case R_FORWARD: turn_off_motor(R_REVERSE); enable_pwm(&TB1CCTL1); break; case L_FORWARD: turn_off_motor(L_REVERSE); enable_pwm(&TB2CCTL1); break; case R_REVERSE: turn_off_motor(R_FORWARD); enable_pwm(&TB1CCTL2); break; case L_REVERSE: turn_off_motor(L_FORWARD); enable_pwm(&TB2CCTL2); break; } } //------------------------------------------------------------------------------ // Function Name : turn_off_motor // // Description: This function sets turns the passed motor off // Arguements: u_int8 motor // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void turn_off_motor(u_int8 motor) { switch(motor) { case R_FORWARD: disable_pwm(&TB1CCTL1); P3OUT &= ~motor; break; case L_FORWARD: disable_pwm(&TB2CCTL1); P3OUT &= ~motor; break; case R_REVERSE: disable_pwm(&TB1CCTL2); P3OUT &= ~motor; break; case L_REVERSE: disable_pwm(&TB2CCTL2); P3OUT &= ~motor; break; } } //------------------------------------------------------------------------------ // Function Name : set_motor_speed // // Description: This function sets the motor speed via changing the PWM value // Due to a slower motor I have it also corrects this. // Arguements: u_int8 motor // int motor_speed // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void set_motor_speed(u_int8 motor, int motor_speed) { switch(motor) { // compensates for slow motor I have case L_FORWARD: set_pwm_value(&TB2CCR1, (int) (PWM_RES - (motor_speed * MOTOR_ADJ_FAC))); break; case R_FORWARD: set_pwm_value(&TB1CCR1, PWM_RES - motor_speed); break; case L_REVERSE: set_pwm_value(&TB2CCR2, (int) (PWM_RES - (motor_speed * MOTOR_ADJ_FAC))); break; case R_REVERSE: set_pwm_value(&TB1CCR2, PWM_RES - motor_speed); break; } } //------------------------------------------------------------------------------ // Function Name : active_brake // // Description: This function activly brakes the car by turn the reverse motors // on hard for a breif moment. // Arguements: void // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void active_brake() { turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); turn_on_motor(R_REVERSE); // Active braking turn_on_motor(L_REVERSE); five_msec_delay(ACTIVE_BREAK); // Active braking time constant turn_off_motor(R_REVERSE); turn_off_motor(L_REVERSE); } //------------------------------------------------------------------------------ // Function Name : active_brake_reverse // // Description: This function activly brakes the car by turn the forward motors // on hard for a breif moment. // Arguements: void // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void active_brake_reverse() { turn_off_motor(R_REVERSE); turn_off_motor(L_REVERSE); turn_on_motor(R_FORWARD); // Active braking turn_on_motor(L_FORWARD); five_msec_delay(ACTIVE_BREAK); // Active braking time constant turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); }<file_sep>/pwm.c //============================================================================// // File Name : pwm.c // // Description: This file contains the pulse width modulaition code // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "pwm.h" #include "msp430.h" #include "macros.h" //------------------------------------------------------------------------------ // Function Name : init_pwm // // Description: This function sets up the passed Timer control register for // PWM operation // Arguements: unsigned short volatile* TxxCTL // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void inline init_pwm(unsigned short volatile* TxxCTL) { *TxxCTL &= ~TIMER_STOP; *TxxCTL &= ~TBIE; *TxxCTL |= TASSEL_2; //*TxxCTL |= TIMER_DIVIDE; } //------------------------------------------------------------------------------ // Function Name : set_pwm_resolution // // Description: This function sets the PWM resolution to the passed Timer // control register. The resolution is how many PWM steps are // possible. The frequency of the PWM is CLK_F / resolution // Arguements: unsigned short volatile* TxxCTL // unsigned int resolution // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void inline set_pwm_resolution(unsigned short volatile* TxxCCR0, unsigned int resolution) { *TxxCCR0 = resolution; } //------------------------------------------------------------------------------ // Function Name : set_pwm_value // // Description: This function sets the PWM value to the passed control register. // The PWM duty cycle is 100% - (value / reosultion) * 100% // This inverted nature is due to a lack of OUT_MOD_SET_RES // on the CCR0 register // possible. The frequency of the PWM is CLK_F / resolution // Arguements: unsigned short volatile* TxxCTL // unsigned int value // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void inline set_pwm_value(unsigned short volatile* TxxCCRn, unsigned int value) { *TxxCCRn = value; } //------------------------------------------------------------------------------ // Function Name : set_pwm_output // // Description: This function sets the PWM output from the passed control // register. Disables interrupts from this seconadry register. // Arguements: unsigned short volatile* TxxCCTLn // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void inline set_pwm_output(unsigned short volatile* TxxCCTLn) { *TxxCCTLn &= CLEAR_REGISTER; *TxxCCTLn &= ~COMPARE_MODE; *TxxCCTLn &= ~CCIE; } //------------------------------------------------------------------------------ // Function Name : start_pwm // // Description: This function starts the PWM on the passed register on up mode. // Arguements: unsigned short volatile* TxxCTL // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void inline start_pwm(unsigned short volatile* TxxCTL) { *TxxCTL |= TIMER_UP; } //------------------------------------------------------------------------------ // Function Name : disable_pwm // // Description: This function stops the PWM on the passed register. // Arguements: unsigned short volatile* TxxCTL // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void inline disable_pwm(unsigned short volatile* TxxCCTLn) { *TxxCCTLn &= ~OUTMOD; } //------------------------------------------------------------------------------ // Function Name : enable // // Description: This function enables the PWM on the passed register. // Arguements: unsigned short volatile* TxxCTL // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void inline enable_pwm(unsigned short volatile* TxxCCTLn) { *TxxCCTLn &= ~CCIFG; *TxxCCTLn &= ~CCIE; *TxxCCTLn |= OUTMOD_RES_SET; }<file_sep>/adc.c //============================================================================// // File Name : adc.c // // Description: This file contains the ADC code // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "adc.h" //------------------------------------------------------------------------------ // Local Varriables static int adc_val[4]; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Function Name : init_adc // // Description: This function initializes the ADC10 module for later use // Arguements: void // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void init_adc() { ADC10CTL0 = CLEAR_REGISTER; // Clear ADC10CTL0 ADC10CTL0 |= ADC10SHT_2; // 16 ADC clocks ADC10CTL0 &= ~ADC10MSC; // Single Sequence ADC10CTL0 |= ADC10ON; // ADC ON - Core Enabled ADC10CTL1 = CLEAR_REGISTER; // Clear ADC10CTL1 ADC10CTL1 |= ADC10SHS_0; // ADC10SC bit ADC10CTL1 |= ADC10SHP; // SAMPCON signal sourced from sampling timer ADC10CTL1 &= ~ADC10ISSH; // The sample-input signal is not inverted. ADC10CTL1 |= ADC10DIV_0; // ADC10_B clock divider – Divide by 1. ADC10CTL1 |= ADC10SSEL_3; // SMCLK ADC10CTL1 |= ADC10CONSEQ_0; // Single-channel, single-conversion ADC10CTL2 = CLEAR_REGISTER; // Clear ADC10CTL2 ADC10CTL2 |= ADC10DIV_0; // Pre-divide by 1 ADC10CTL2 |= ADC10RES; // 10-bit resolution ADC10CTL2 &= ~ADC10DF; // Binary unsigned ADC10CTL2 &= ~ADC10SR; // supports up to approximately 200 ksps ADC10MCTL0 = CLEAR_REGISTER; // Clear ADC10MCTL0 ADC10MCTL0 |= ADC10SREF_0; // V(R+) = AVCC and V(R-) = AVSS ADC10MCTL0 |= ADC10INCH_3; // Channel A3 Thumb Wheel ADC10IE |= ADC10IE0; // Enable ADC conversion complete interrupt //clk speed //resolution //mode //sample and hold //trigger mode //vref } //------------------------------------------------------------------------------ // Function Name : analog_read // // Description: TODO: // Arguements: void // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ int analog_read(int channel) { // TODO: Turn on LED, no delay needed as rise time is ~900ns per the // data sheet and at 8Mhz that is < 7 1 cycle instructions int read_value = INVALID; ADC10CTL0 &= ~ADC10ENC; ADC10MCTL0 &= ~NIBBLE; // Clears Channel ADC10MCTL0 |= channel; // Sets Channel //while(pause++ < 1200); // Force completes a conversion and returns the value if(!(ADC10CTL1 & ADC10BUSY)) { ADC10CTL0 |= ADC10ENC + ADC10SC; while(!conversion_flag); // Kill time until conversion complete read_value = ADC10MEM0; } else { while(ADC10CTL1 & ADC10BUSY); // Kill time until ADC ready ADC10CTL0 |= ADC10ENC + ADC10SC; while(!conversion_flag); // Kill time until conversion complete read_value = ADC10MEM0; } conversion_flag = FALSE; return read_value; } //------------------------------------------------------------------------------ // Function Name : set_adc_val // // Description: Retrieves the internal ADC value of the requested channel // Arguements: channel ADC channel the value is to come from // Returns: The requested ADC value // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ int get_adc_val(u_int8 channel) { return adc_val[channel]; } //------------------------------------------------------------------------------ // Function Name : set_adc_val // // Description: Sets the internal ADC data to the value read from the ADC // Arguements: channel ADC channel the value came from // value ADC value to store // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void set_adc_val(u_int8 channel, int value) { adc_val[channel] = value; } //------------------------------------------------------------------------------ // Function Name : set_conversion_flag // // Description: Allows external interrupt to set the internal conversion flag // Arguements: set_flag boolean value for flag to be set to // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void set_conversion_flag(u_int8 set_flag) { conversion_flag = set_flag; }<file_sep>/serial.c //============================================================================// // File Name : serial.c // // Description: This file contains the serial UART control code // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "serial.h" //------------------------------------------------------------------------------ // Module Scope Globals static u_int8 current_baud = BAUD_9600; static char uca0_rx_buff[BUFF_SIZE]; volatile char uca0_tx_buff[BUFF_SIZE]; volatile static int uca0_rx_buff_end = START_ZERO; volatile static int uca0_tx_buff_end = START_ZERO; volatile static int uca0_tx_buff_start= START_ZERO; volatile static int uca0_rx_buff_start = START_ZERO; volatile static int uca0_rx_complete_flag = FALSE; volatile static int uca0_tx_complete_flag = TRUE; static char uca1_rx_buff[BUFF_SIZE]; volatile static char uca1_tx_buff[BUFF_SIZE]; volatile static int uca1_rx_buff_end = START_ZERO; volatile static int uca1_tx_buff_end = START_ZERO; volatile static int uca1_tx_buff_start = START_ZERO; volatile static int uca1_rx_buff_start = START_ZERO; volatile static int uca1_rx_complete_flag = FALSE; volatile static int uca1_tx_complete_flag = TRUE; volatile static int uca0_num_buffered = START_ZERO; volatile static int uca1_num_buffered = START_ZERO; volatile static int has_com_sent = FALSE; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Function Name : init_serial_uart // // Description: This function sets up the basic serial UART system. // Arguements: void // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void init_serial_uart() { five_msec_delay(QUARTER_SECOND); PJOUT |= IOT_RESET; five_msec_delay(QUARTER_SECOND); // Configure UART 0 UCA0CTLW0 = CLEAR_REGISTER; // Use word register UCA0CTLW0 |= UCSSEL__SMCLK; // Set SMCLK as fBRCLK UCA0CTLW0 |= UCSWRST; // Set Software reset enable UCA0BRW = 52; // 9,600 Baud UCA0MCTLW = 0x4911 ; UCA0CTL1 &= ~UCSWRST; // Release from rese UCA0IV = CLEAR_REGISTER; UCA0IFG &= ~UCTXIFG; UCA0IE |= UCRXIE; // Enable RX interrupt UCA0IE |= UCTXIE; // Enable TX interrupt // Configure UART 1 UCA1CTLW0 = CLEAR_REGISTER; // Use word register UCA1CTLW0 |= UCSSEL__SMCLK; // Set SMCLK as fBRCLK UCA1CTLW0 |= UCSWRST; // Set Software reset enable UCA1BRW = 52; // 9,600 Baud UCA1MCTLW = 0x4911 ; UCA1CTL1 &= ~UCSWRST; // Release from reset UCA1IFG &= ~UCTXIFG; UCA1IE |= UCRXIE; // Enable RX interrupt UCA1IE |= UCTXIE; // Enable TX interrupt } //------------------------------------------------------------------------------ // Function Name : get_current_baud // // Description: This function returns the current baud rate as set in the local // static variable. // Arguements: void // Returns: u_int8 current_baud // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ u_int8 get_current_baud() { return current_baud; } //------------------------------------------------------------------------------ // Function Name : set_current_baud // // Description: This function sets the current baud rate variable to the passed // value. // Arguements: u_int8 set_baud_rate // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void uca0_set_current_baud(u_int8 set_baud_rate) { current_baud = set_baud_rate; if(current_baud == BAUD_9600) { UCA0CTLW0 |= UCSWRST; // Set Software reset enable UCA0BRW = BRW_9600; // 9,600 Baud UCA0MCTLW = MCTL_9600; UCA0CTL1 &= ~UCSWRST; // Release from reset UCA0IFG &= ~UCTXIFG; UCA0IE |= UCRXIE; // Enable RX interrupt UCA0IE |= UCTXIE; // Enable TX interrupt } else if(current_baud == BAUD_115200) { UCA0CTLW0 |= UCSWRST; // Set Software reset enable UCA0BRW = BRW_115200; // 115,200 Baud UCA0MCTLW = MCTL_115200 ; UCA0CTL1 &= ~UCSWRST; // Release from reset UCA0IFG &= ~UCTXIFG; UCA0IE |= UCRXIE; // Enable RX interrupt UCA0IE |= UCTXIE; // Enable TX interrupt } } void uca1_set_current_baud(u_int8 set_baud_rate) { current_baud = set_baud_rate; if(current_baud == BAUD_9600) { UCA1CTLW0 |= UCSWRST; // Set Software reset enable UCA1BRW = BRW_9600; // 9,600 Baud UCA1MCTLW = MCTL_9600; UCA1CTL1 &= ~UCSWRST; // Release from reset UCA1IFG &= ~UCTXIFG; UCA1IE |= UCRXIE; // Enable RX interrupt UCA1IE |= UCTXIE; // Enable TX interrupt } else if(current_baud == BAUD_115200) { UCA1CTLW0 |= UCSWRST; // Set Software reset enable UCA1BRW = BRW_115200; // 115,200 Baud UCA1MCTLW = MCTL_115200 ; UCA1CTL1 &= ~UCSWRST; // Release from reset UCA1IFG &= ~UCTXIFG; UCA1IE |= UCRXIE; // Enable RX interrupt UCA1IE |= UCTXIE; // Enable TX interrupt } } //------------------------------------------------------------------------------ // Function Name : receive_char // // Description: This function appends the recived chars to the rx_buff // Arguements: char receive_char // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void uca0_receive_char(char received_char) { if(!has_com_sent) has_com_sent = TRUE; if(received_char == NULL_TERM || received_char == C_RETURN) { uca0_rx_buff[uca0_rx_buff_end++] = NULL_TERM; uca0_rx_complete_flag = TRUE; } else { uca0_rx_buff[uca0_rx_buff_end++] = received_char; uca0_rx_buff[uca0_rx_buff_end] = NULL_TERM; uca0_rx_buff_end %= BUFF_SIZE; } } void uca1_receive_char(char received_char) { if(//received_char == NULL_TERM || received_char == C_RETURN || received_char == '\n') { uca1_rx_buff[uca1_rx_buff_end++] = '\n'; uca1_rx_buff[uca1_rx_buff_end] = NULL_TERM; uca1_rx_complete_flag = TRUE; } else { uca1_rx_buff[uca1_rx_buff_end++] = received_char; uca1_rx_buff[uca1_rx_buff_end] = NULL_TERM; uca1_rx_buff_end %= BUFF_SIZE; } } //------------------------------------------------------------------------------ // Function Name : transmit_message // // Description: This function sets the tx buffer to a passed string. Worst case // performance of ~2k cycles to TX a full buffer. // Arguements: char message // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void uca0_transmit_message(char* message, int offset) { int count = START_ZERO; bool end = FALSE; while(!end && has_com_sent) { uca0_tx_buff[(count + uca0_tx_buff_end) % BUFF_SIZE] = message[(offset + count) % BUFF_SIZE]; count++; if((message[(offset + count) % BUFF_SIZE] == NULL_TERM || count >= BUFF_SIZE)) { if(count == OFF_BY_ONE) count--; end = TRUE; } } uca0_tx_buff[(count++ + uca0_tx_buff_end) % BUFF_SIZE] = NULL_TERM; uca0_tx_buff_end = (count + uca0_tx_buff_end) % BUFF_SIZE; if(uca0_tx_complete_flag) { uca0_tx_complete_flag = FALSE; UCA0IFG |= UCTXIFG; } else { uca0_num_buffered++; } } void uca1_transmit_message(char* message, int offset) { int count = START_ZERO; bool end = FALSE; while(!end) { uca1_tx_buff[(count + uca1_tx_buff_end) % BUFF_SIZE] = message[(offset + count) % BUFF_SIZE]; count++; if(message[(offset + count) % BUFF_SIZE] == C_RETURN || count >= BUFF_SIZE) { if(count == OFF_BY_ONE) count--; end = TRUE; } } uca1_tx_buff[(count++ + uca1_tx_buff_end) % BUFF_SIZE] = C_RETURN; uca1_tx_buff_end = (count + uca1_tx_buff_end) % BUFF_SIZE; if(uca1_tx_complete_flag) { uca1_tx_complete_flag = FALSE; UCA1IFG |= UCTXIFG; } else { uca1_num_buffered++; } } //------------------------------------------------------------------------------ // Function Name : transmit_char // // Description: This function sets the uca0 tx buffer to a passed char // Arguements: char char_message // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void uca0_transmit_char() { if(!uca0_tx_complete_flag) { if( uca0_tx_buff[uca0_tx_buff_start] == NULL_TERM) { if(uca0_num_buffered) uca0_num_buffered--; else uca0_tx_complete_flag = TRUE; } UCA0TXBUF = uca0_tx_buff[uca0_tx_buff_start++]; uca0_tx_buff_start %= BUFF_SIZE; } } void uca1_transmit_char() { if(!uca1_tx_complete_flag) { if(uca1_tx_buff[uca1_tx_buff_start] == C_RETURN) { UCA1TXBUF = uca1_tx_buff[uca1_tx_buff_start]; if(uca1_num_buffered) uca1_num_buffered--; else uca1_tx_complete_flag = TRUE; } UCA1TXBUF = uca1_tx_buff[uca1_tx_buff_start++]; uca1_tx_buff_start %= BUFF_SIZE; } } //------------------------------------------------------------------------------ // Function Name : receive_char // // Description: This function returns the pointer to the rx_buff and resets // the rx_complete flag. FIFO buffer. // Arguements: void // Returns: pointer to the uca0_rx_buff // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ BufferString uca0_read_buffer(u_int8 reset) { // Volatile access things BufferString buffer; int rx_buffer_start = uca0_rx_buff_start; int rx_buffer_end = uca0_rx_buff_end; buffer.head = uca0_rx_buff; buffer.offset = rx_buffer_start; if(reset) { uca0_rx_complete_flag = FALSE; uca0_rx_buff_start = rx_buffer_end; } return buffer; } BufferString uca1_read_buffer(u_int8 reset) { // Volatile access things BufferString buffer; int rx_buffer_start = uca1_rx_buff_start; int rx_buffer_end = uca1_rx_buff_end; buffer.head = uca1_rx_buff; buffer.offset = rx_buffer_start; if(reset) { uca1_rx_complete_flag = FALSE; uca1_rx_buff_start = rx_buffer_end; } return buffer; } //------------------------------------------------------------------------------ // Function Name : is_message_received // // Description: This function returns whether a message has been received // Arguements: void // Returns: rx_complete_flag // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ u_int8 uca0_is_message_received() { return uca0_rx_complete_flag; } u_int8 uca1_is_message_received() { return uca1_rx_complete_flag; }<file_sep>/string.c //============================================================================// // File Name : string.c // // Description: This file contains the IOT wifi module serial command code. // Author: <NAME> // Date: April 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "string.h" bool compare(char* a, char* b) { int i = START_VAL; while(a[i] == b[i]) { if(a[i] == NULL_TERM && b[i] == NULL_TERM) return TRUE; i++; } return FALSE; } bool find(char* a, BufferString b) { int i = START_VAL; int j = START_VAL; while(b.head[b.offset + i % BUFF_SIZE] != '\n' && b.head[(b.offset + i) % BUFF_SIZE] != C_RETURN && b.head[(b.offset + i) % BUFF_SIZE] != NULL_TERM) { if(a[j] == b.head[b.offset + i % BUFF_SIZE]) { while(a[j++] == b.head[(b.offset + i++) % BUFF_SIZE]) { if(a[j] == NULL_TERM || a[j] == C_RETURN) return TRUE; } j = START_VAL; } i++; } return FALSE; }<file_sep>/switch.h #ifndef SWITCH_H #define SWITCH_H #include "macros.h" #include "globals.h" #include "functions.h" #include "msp430.h" #include "shapes.h" #include "menu.h" //------------------------------------------------------------------------------ // Function Declarations void update_switches(void); void setup_sw_debounce(void); bool software_debounce(unsigned short volatile*, u_int8); void sw_pressed(u_int8); void sw_released(u_int8); u_int8 get_sw_pressed(void); //------------------------------------------------------------------------------ #endif<file_sep>/timers.c //============================================================================// // File Name : timers.c // // Description: This file contains the timer intialization and delay code. // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "timers.h" //------------------------------------------------------------------------------ // Globals long volatile int system_time = START_VAL; // Not going to overflow as long // as run time less than 240 days //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Function Name : five_msec_delay // // Description: This function calls a delay for a 5ms multiple of the passed // delay arguement. // Arguements: unsigned int delay // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void five_msec_delay(unsigned int delay) { unsigned int end_count = timer_count + delay; while(timer_count < end_count); } //------------------------------------------------------------------------------ // Function Name : init_timers // // Description: This function calls the individual timer intialization // functions. // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void init_timers() { init_timer_A0(); } //------------------------------------------------------------------------------ // Function Name : init_timer_A0 // // Description: This function initializes the timer A0. This sets up the global // timer used in the program's functions. It is set up as an 8Mhz // clock with a CCR1 register calling an ISR to increment a time // value every 5ms. // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void init_timer_A0() { TA0CTL = CLEAR_REGISTER; TA0CTL |= TASSEL__SMCLK; TA0CTL |= MC__UP; TA0CCTL0 = CLEAR_REGISTER; TA0CCTL0 |= CCIE; TA0CCR0 = TA0_FREQ; } //------------------------------------------------------------------------------ // Function Name : get_timer_count // // Description: This function returns the timer_count varriable // functions. // Arguements: void // Returns: timer_count // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ unsigned int get_timer_count() { return timer_count; } //------------------------------------------------------------------------------ // Function Name : increment_timer_count // // Description: This function increments the timer_count varriable every 5 msec // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void increment_timer_count() { timer_count++; system_time++; }<file_sep>/menu.h #ifndef MENU_H #define MENU_H #include "macros.h" #include "globals.h" #include "msp430.h" #include "switch.h" #include "line.h" #include "adc.h" #include "serial.h" #include "functions.h" #include "string.h" #include "command.h" //------------------------------------------------------------------------------ // Function Declarations void update_menu(void); void menu_handle_input(u_int8); //------------------------------------------------------------------------------ #endif <file_sep>/string.h #ifndef STRING_H #define STRING_H #include "macros.h" #include "globals.h" #include "msp430.h" #include "serial.h" //------------------------------------------------------------------------------ // Function Declarations bool compare(char*, char*); bool find(char*, BufferString); //------------------------------------------------------------------------------ #endif<file_sep>/main.h // Global Variables extern char display_line_1[11]; extern char display_line_2[11]; extern char display_line_3[11]; extern char display_line_4[11]; extern char *display_1; extern char *display_2; extern char *display_3; extern char *display_4; extern char posL1; extern char posL2; extern char posL3; extern char posL4; extern volatile unsigned char control_state[CNTL_STATE_INDEX]; extern volatile unsigned int Time_Sequence; extern char led_smclk; extern volatile char one_time; extern volatile unsigned int five_msec_count; extern char size_count; extern char big;<file_sep>/timers.h #ifndef TIMERS_H #define TIMERS_H #include "macros.h" #include "globals.h" #include "functions.h" #include "msp430.h" //------------------------------------------------------------------------------ // Function Declarations void five_msec_delay(unsigned int delay); void init_timers(void); void init_timer_A0(void); void increment_timer_count(); unsigned int get_timer_count(); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Module Scope Globals static unsigned volatile int timer_count = START_VAL; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Globals extern long volatile int system_time; //------------------------------------------------------------------------------ #endif<file_sep>/serial.h #ifndef SERIAL_H #define SERIAL_H #include "macros.h" #include "globals.h" #include "functions.h" #include "msp430.h" #include "timers.h" //------------------------------------------------------------------------------ // Function Declarations void init_serial_uart(void); u_int8 get_current_baud(void); void uca0_set_current_baud(u_int8); void uca0_receive_char(char); void uca0_transmit_message(char*, int); void uca0_transmit_char(void); BufferString uca0_read_buffer(u_int8); u_int8 uca0_is_message_received(); void uca1_set_current_baud(u_int8); void uca1_receive_char(char); void uca1_transmit_message(char*, int); void uca1_transmit_char(void); BufferString uca1_read_buffer(u_int8); u_int8 uca1_is_message_received(); void transmit_loop(void); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Globals //------------------------------------------------------------------------------ #endif<file_sep>/display.c //============================================================================// // File Name :display.c // // Description: This file contains the LCD display functions // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "macros.h" #include "globals.h" #include "functions.h" //------------------------------------------------------------------------------ // Function Declarations void Init_Conditions(void); void Display_Process(void); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Local Variable //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Function Name : Init_Conditions // // Description: This function enables the hardware interupts and sets the // display_x variables to the base address of the LCD char array // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void Init_Conditions(void){ //------------------------------------------------------------------------------ // Initializations Configurations //------------------------------------------------------------------------------ // Interrupts are disabled by default, enable them. enable_interrupts(); display_1 = &display_line_1[LCD_BASE]; display_2 = &display_line_2[LCD_BASE]; display_3 = &display_line_3[LCD_BASE]; display_4 = &display_line_4[LCD_BASE]; //------------------------------------------------------------------------------ } //------------------------------------------------------------------------------ // Function Name : Display_Process // // Description: This function clears the current display and then sets the // output text for each line of the LCD display // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void Display_Process(void){ ClrDisplay(); lcd_out(display_1, LCD_HOME_L1, posL1); lcd_out(display_2, LCD_HOME_L2, posL2); lcd_out(display_3, LCD_HOME_L3, posL3); lcd_out(display_4, LCD_HOME_L4, posL4); } void display_buffer_string(BufferString string) { int count = START_ZERO; line_buffer2[START_ZERO] = NULL_TERM; line_buffer3[START_ZERO] = NULL_TERM; line_buffer4[START_ZERO] = NULL_TERM; while((count < LCD_LENGTH * DISPLAY_LINE_4) && string.head[(count + string.offset) % BUFF_SIZE] != NULL_TERM && string.head[(count + string.offset) % BUFF_SIZE] != C_RETURN) { if(count < LCD_LENGTH) { line_buffer1[count] = string.head[(count + string.offset) % BUFF_SIZE]; line_buffer1[count + INCREMENT] = NULL_TERM; } else if(count < LCD_LENGTH * DISPLAY_LINE_2) { line_buffer2[count - LCD_LENGTH] = string.head[(count + string.offset) % BUFF_SIZE]; line_buffer2[count + INCREMENT] = NULL_TERM; } else if(count < LCD_LENGTH * DISPLAY_LINE_3) { line_buffer3[count - LCD_LENGTH * DISPLAY_LINE_2] = string.head[(count + string.offset) % BUFF_SIZE]; line_buffer3[count + INCREMENT] = NULL_TERM; } else if(count < LCD_LENGTH * DISPLAY_LINE_4) { line_buffer4[count - LCD_LENGTH * DISPLAY_LINE_3] = string.head[(count + string.offset) % BUFF_SIZE]; line_buffer3[count + INCREMENT] = NULL_TERM; } count++; } display_1 = line_buffer1; display_2 = line_buffer2; display_3 = line_buffer3; display_4 = line_buffer4; }<file_sep>/port_interrupts.c //============================================================================// // File Name : port_interrupts.c // // Description: This file contains the port ISR code // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "msp430.h" #include "macros.h" #include "switch.h" //------------------------------------------------------------------------------ // Interrupt Name : SW_PRESSED_ISR // // Description: This ISR services the Port 4 interrupts related to the two on // board switches. It determines which switch was pressed using the // TxxIV register and disables interrupts on that port pin for // debouncing. It then switches the edge mode for the interrupt // to receive the rising/falling edge of the next button press/ // release. It enables the TA1CCR1 compare register to count a // specified debounce time before that ISR renenables interrupts. // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ #pragma vector = PORT4_VECTOR __interrupt void SW_PRESSED_ISR(void) { u_int8 current_ifg = P4IV >> OFF_BY_ONE_OFFSET; // Shifts port interrupt label // format used by SW_1 / SW_2 P4IE &= ~(current_ifg); // Port interrupts turned off if((P4IES & current_ifg)) { P4IES &= ~current_ifg; // Toggle rising/falling edge sw_pressed(current_ifg); } else { P4IES |= current_ifg; // Toggle rising/falling edge sw_released(current_ifg); } unsigned int temp_edge = P4IES; TA1CCR1 = (TA1R + ((TA1_CLK_F / ONE_MSEC) * (temp_edge & current_ifg ? PRESSED_DEBOUNCE : RELEASED_DEBOUNCE))) % UINT_16_MAX; TA1CCTL1 &= ~CCIFG; TA1CCTL1 |= CCIE; P4IFG &= ~current_ifg; } <file_sep>/shapes.c //============================================================================// // File Name : shapes.c // // Description: This file contains the shape driving code // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "shapes.h" //------------------------------------------------------------------------------ // Function Name : handle_input // // Description: This function takes the passed count value and decides which // shape to run based on that value. // Arguements: u_int8 sw_pressed_mask // u_int8 sw_pressed_count // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void handle_input(u_int8 sw_pressed_mask, u_int8 sw_pressed_count) { if(is_running) { is_running = FALSE; turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); turn_off_motor(R_REVERSE); turn_off_motor(L_REVERSE); } else { is_running = TRUE; switch(sw_pressed_count) { case 0: break; case 1: go_back_and_forth(); break; case 2: go_circle(2, DIR_LEFT, 1.0f, 1.1f); break; case 3: go_circle(2, DIR_RIGHT, 1.0f, 1.1); break; case 4: go_figure_eight(2, 1.0f, 1.0f); break; case 5: go_triangle(2, DIR_LEFT, 1.0f, 1.0f); break; case 6: break; default: break; } } } //------------------------------------------------------------------------------ // Function Name : go_circle // // Description: This function drives the car in a circle in the direction which // the passed value dictates. It adjusts the radius and length of // of the circle based on a passed adjustment factor and runs for // a dictated amount of circles. // Arguements: u_int8 num_circles // u_int8 direction // float radius_adj // float length_adj // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void go_circle(u_int8 num_circles, u_int8 direction, float radius_adj, float length_adj) { // Magic numbers used in real world calibration // Wouldn't make sense to hide in Macors.h turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); length_adj *= (direction == R_FORWARD ? R_LEN_COMP : 1.0f) * BATT_COMP * radius_adj; if(direction == DIR_LEFT) { set_motor_speed(R_FORWARD, MAX_SPEED); set_motor_speed(L_FORWARD, (int) (MAX_SPEED * 0.4 * radius_adj)); } else { set_motor_speed(L_FORWARD, MAX_SPEED); set_motor_speed(R_FORWARD, (int) (MAX_SPEED * 0.377f * radius_adj)); } turn_on_motor(R_FORWARD); turn_on_motor(L_FORWARD); unsigned int delay = (unsigned int)(((float) QUARTER_SECOND * 5.07f * (float) num_circles) * length_adj); five_msec_delay(delay); turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); is_running = FALSE; } //------------------------------------------------------------------------------ // Function Name : go_figure_eight // // Description: This function drives the car in a figure eight by using the // go_circles function in opposing directions. // Arguements: u_int8 num_circles // float radius_adj // float length_adj // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void go_figure_eight(u_int8 num_circles, float radius_adj, float length_adj) { int i; for(i = 0; i < num_circles; i++) { go_circle(1, DIR_LEFT, 0.87f, 1.075f); // magic calibration numbers go_circle(1, DIR_RIGHT, 0.87f, i == num_circles - OFF_BY_ONE_OFFSET ? 0.9f : .96f); } } //------------------------------------------------------------------------------ // Function Name : go_triangle // // Description: This function drives the car in a triangle in the direction // the passed value dictates. It adjusts the radius and length of // of the turns based on a passed adjustment factor and runs for // a dictated amount of triangles. // Arguements: u_int8 num_triangles // u_int8 direction // float radius_adj // float length_adj // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void go_triangle(u_int8 num_triangles, u_int8 direction, float radius_adj, float length_adj) { turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); length_adj *= (direction == R_FORWARD ? R_LEN_COMP : UN_COMP) * BATT_COMP; int i; for(i = 0; i < num_triangles * NUM_TRI_PTS; i++) { if(direction == DIR_LEFT) { set_motor_speed(R_FORWARD, MAX_SPEED); set_motor_speed(L_FORWARD, MOTOR_SPD_OFF); } else { set_motor_speed(L_FORWARD, MAX_SPEED); set_motor_speed(R_FORWARD, MOTOR_SPD_OFF); } turn_on_motor(R_FORWARD); turn_on_motor(L_FORWARD); five_msec_delay((unsigned int) (length_adj * (QUARTER_SECOND) * 1.15f)); turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); set_motor_speed(R_FORWARD, MAX_SPEED); set_motor_speed(L_FORWARD, MAX_SPEED); turn_on_motor(R_FORWARD); turn_on_motor(L_FORWARD); five_msec_delay((QUARTER_SECOND * 2) / 2); turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); } is_running = FALSE; } //------------------------------------------------------------------------------ // Function Name : go_back_and_forth // // Description: This function drives the car in the way presribed by project 4 // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void go_back_and_forth(void) { five_msec_delay(SECOND); set_motor_speed(R_FORWARD, MAX_SPEED); set_motor_speed(L_FORWARD, MAX_SPEED); set_motor_speed(R_REVERSE, MAX_SPEED); set_motor_speed(L_REVERSE, MAX_SPEED); // Forward 1 sec display_3 = "Forward"; Display_Process(); turn_on_motor(R_FORWARD); turn_on_motor(L_FORWARD); five_msec_delay(SECOND); turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); five_msec_delay(SECOND); // Reverse 2 sec display_3 = "Reverse"; Display_Process(); turn_on_motor(R_REVERSE); turn_on_motor(L_REVERSE); five_msec_delay(SECOND * 2u); turn_off_motor(R_REVERSE); turn_off_motor(L_REVERSE); five_msec_delay(SECOND); // Forward 1 sec display_3 = "Forward"; Display_Process(); turn_on_motor(R_FORWARD); turn_on_motor(L_FORWARD); five_msec_delay(SECOND); turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); five_msec_delay(SECOND); // Clockwise 1 sec display_3 = "Clockwise"; Display_Process(); turn_on_motor(R_REVERSE); turn_on_motor(L_FORWARD); five_msec_delay(SECOND); turn_off_motor(R_REVERSE); turn_off_motor(L_FORWARD); five_msec_delay(SECOND); // Counterclockwise 1 sec display_3 = "Counterclk"; Display_Process(); turn_on_motor(L_REVERSE); turn_on_motor(R_FORWARD); five_msec_delay(SECOND); turn_off_motor(L_REVERSE); turn_off_motor(R_FORWARD); five_msec_delay(SECOND); } <file_sep>/globals.h //============================================================================// // File Name : globals.h // // Description: This file contains the global variable extern defenitions // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// // Global Variables extern char display_line_1[DISPLAY_LENGTH]; extern char display_line_2[DISPLAY_LENGTH]; extern char display_line_3[DISPLAY_LENGTH]; extern char display_line_4[DISPLAY_LENGTH]; extern char *display_1; extern char *display_2; extern char *display_3; extern char *display_4; extern char posL1; extern char posL2; extern char posL3; extern char posL4; extern volatile unsigned char control_state[CNTL_STATE_INDEX]; extern bool uca1_ready; extern char line_buffer1[DISPLAY_LENGTH]; extern char line_buffer2[DISPLAY_LENGTH]; extern char line_buffer3[DISPLAY_LENGTH]; extern char line_buffer4[DISPLAY_LENGTH]; extern bool is_follow_running;<file_sep>/main.c //------------------------------------------------------------------------------ // // Description: This file contains the Main Routine - "While" Operating System // // // <NAME> // Jan 2016 // Built with IAR Embedded Workbench Version: V7.3.1.3987 (6.40.1) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ #include "msp430.h" #include "functions.h" #include "macros.h" #include "pwm.h" #include "motor.h" #include "switch.h" #include "timers.h" #include "ports.h" #include "adc.h" #include "menu.h" #include "serial.h" #include "command.h" // Global Variables volatile unsigned char control_state[CNTL_STATE_INDEX]; extern char display_line_1[DISPLAY_LENGTH]; extern char display_line_2[DISPLAY_LENGTH]; extern char display_line_3[DISPLAY_LENGTH]; extern char display_line_4[DISPLAY_LENGTH]; extern char *display_1; extern char *display_2; extern char *display_3; extern char *display_4; char posL1; char posL2; char posL3; char posL4; bool is_follow_running; void setup_pwm(void); void main(void){ //------------------------------------------------------------------------------ // Main Program // This is the main routine for the program. Execution of code starts here. // The operating system is Back Ground Fore Ground. // //------------------------------------------------------------------------------ init_ports(); Init_Clocks(); Init_Conditions(); init_timers(); five_msec_delay(QUARTER_SECOND); Init_LCD(); setup_sw_debounce(); init_adc(); P1OUT |= IR_LED; init_serial_uart(); WDTCTL = WDTPW + WDTHOLD; setup_pwm(); set_motor_speed(R_FORWARD, PWM_RES); set_motor_speed(L_FORWARD, PWM_RES); unsigned int time_sequence = START_VAL; // counter for switch loop unsigned int previous_count = START_VAL; // automatic variable for // comparing timer_count unsigned int display_count = START_VAL; is_follow_running = FALSE; //------------------------------------------------------------------------------ // Begining of the "While" Operating System //------------------------------------------------------------------------------ while(ALWAYS) { // Can the Operating system run if(get_timer_count() > display_count + QUARTER_SECOND) { display_count = get_timer_count(); Display_Process(); time_sequence = START_VAL; } update_switches(); // Check for switch state change update_menu(); if(is_follow_running) run_follow(); if(uca0_is_message_received()) { BufferString message = uca0_read_buffer(TRUE); receive_command(message.head + message.offset); } if(uca1_is_message_received()) { update_menu(); BufferString message = uca1_read_buffer(TRUE); uca0_transmit_message(message.head, message.offset); if(find(WIFI_COMMAND_SYMBOL, message)) { receive_command(message.head + message.offset); } if(find(LOST_WIFI_COMMAND_SYMBOL, message)) { receive_command(CONNECT_NCSU); } } if(time_sequence > SECOND_AND_A_QUARTER) time_sequence = START_VAL; unsigned int current_timer_count = get_timer_count(); if(current_timer_count > previous_count) { previous_count = current_timer_count % UINT_16_MAX; time_sequence++; } } //------------------------------------------------------------------------------ } void setup_pwm() { // R_FORWARD on P3.4 init_pwm(&TB1CTL); set_pwm_resolution(&TB1CCR0, PWM_RES); set_pwm_value(&TB1CCR1, PWM_RES / DIVIDE_BY_TWO); set_pwm_output(&TB1CCTL1); P3DIR |= R_FORWARD; P3SEL0 |= R_FORWARD; P3SEL1 &= ~R_FORWARD; start_pwm(&TB1CTL); // L_FORWARD on P3.6 init_pwm(&TB2CTL); set_pwm_resolution(&TB2CCR0, PWM_RES); set_pwm_value(&TB2CCR1, PWM_RES / DIVIDE_BY_TWO); set_pwm_output(&TB2CCTL1); P3DIR |= L_FORWARD; P3SEL0 |= L_FORWARD; P3SEL1 &= ~L_FORWARD; start_pwm(&TB2CTL); // R_REVERSE on P3.5 set_pwm_value(&TB1CCR2, PWM_RES / DIVIDE_BY_TWO); set_pwm_output(&TB1CCTL2); P3DIR |= R_REVERSE; P3SEL0 |= R_REVERSE; P3SEL1 &= ~R_REVERSE; // L_REVERSE on P3.7 set_pwm_value(&TB2CCR2, PWM_RES / DIVIDE_BY_TWO); set_pwm_output(&TB2CCTL2); P3DIR |= L_REVERSE; P3SEL0 |= L_REVERSE; P3SEL1 &= ~L_REVERSE; } <file_sep>/line.c //============================================================================// // File Name : line.c // // Description: This file contains the black line following code. // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "line.h" static char buffer[DISPLAY_LENGTH] = "0"; //------------------------------------------------------------------------------ // Function Name : calibrate_sensors // // Description: This function calibrates the sensors for the white and black // surface using prompts to the user. // Arguements: unsigned int delay // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void calibrate_sensors(u_int8 type) { if(type == BLACK_VAL) { l_black_cal = analog_read(ADC0); r_black_cal = analog_read(ADC1); } else if(type == WHITE_VAL) { l_white_cal = analog_read(ADC0); r_white_cal = analog_read(ADC1); } } //------------------------------------------------------------------------------ // Function Name : determine_line // // Description: This function calibrates the sensors for the white and black // surface using prompts to the user. // Arguements: unsigned int delay // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ u_int8 determine_line(u_int8 side) { u_int8 detection = WHITE_VAL; int adc_val = MIN_ADC10; if(side == RIGHT_DETECT) { adc_val = analog_read(ADC0); if(ABS(l_black_cal - adc_val) < ABS(l_white_cal - adc_val)) detection = BLACK_VAL; } else if(side == LEFT_DETECT) { adc_val = analog_read(ADC1); if(ABS(l_black_cal - adc_val) < ABS(l_white_cal - adc_val)) detection = BLACK_VAL; } return detection; } //------------------------------------------------------------------------------ // Function Name : run_follow // // Description: This function runs the full line following program. It uses // simplified PID control. // Arguements: void // Returns: void // // Author: <NAME> // Date: April 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void run_follow() { static int current_side_error = ON_LINE; static int previous_error = NO_ERROR; static int integral_error = NO_ERROR; int left_val, right_val, left_err, right_err, error; int l_base_speed = (int) (MAX_SPEED * 0.160f); int r_base_speed = (int) (MAX_SPEED * 0.160f); int motor_speed = START_ZERO; int l_speed; int r_speed; int kp = 3; int kd = 25; int ki = 1; left_val = analog_read(ADC0); right_val = analog_read(ADC1); left_err = l_black_cal - left_val; left_err = left_err > ERROR_BASELINE ? left_err - ERROR_BASELINE : NO_ERROR; right_err = r_black_cal - right_val; right_err = right_err > ERROR_BASELINE ? right_err - ERROR_BASELINE : NO_ERROR; if((left_err == NO_ERROR) && (right_err > NO_ERROR)) { current_side_error = RIGHT_SIDE; } if((right_err == NO_ERROR) && (left_err > NO_ERROR)) { current_side_error = LEFT_SIDE; } if((right_err == NO_ERROR) && (left_err == NO_ERROR)) { current_side_error = NO_ERROR; } if(current_side_error == RIGHT_SIDE) { error = right_err; } if(current_side_error == LEFT_SIDE) { error = -left_err; } if(current_side_error == NO_ERROR) { l_speed = l_base_speed; r_speed = r_base_speed; } else { motor_speed = (kp * error) + (kd * (error - previous_error)) + (ki * integral_error / 2); if(current_side_error == LEFT_SIDE) { l_speed = l_base_speed - 2*motor_speed; r_speed = r_base_speed + 2*motor_speed; } else { l_speed = l_base_speed - motor_speed; r_speed = r_base_speed + motor_speed; } } previous_error = error; integral_error += error; if(integral_error > 600) integral_error = 600; if(integral_error < -600) integral_error = -600; if(l_speed > MAX_LINE_SPEED) l_speed = (int) (MAX_LINE_SPEED * 1.10f); if(l_speed < MIN_SPEED) l_speed = MIN_SPEED; if(r_speed > MAX_LINE_SPEED) r_speed = MAX_LINE_SPEED; if(r_speed < MIN_SPEED) r_speed = MIN_SPEED; set_motor_speed(L_FORWARD, l_speed); set_motor_speed(R_FORWARD, r_speed); turn_on_motor(R_FORWARD); turn_on_motor(L_FORWARD); if(current_side_error == LEFT_SIDE) five_msec_delay(16); else five_msec_delay(14); turn_off_motor(R_FORWARD); turn_off_motor(L_FORWARD); five_msec_delay(11); //turn_off_motor(R_FORWARD); //turn_off_motor(L_FORWARD); //five_msec_delay(50); display_4 = buffer; buffer[ARR_POS_0] = DIG_TO_CH(current_side_error); buffer[1] = HEX_TO_CH((left_err >> BYTE_SIZE ) & NIBBLE); buffer[2] = HEX_TO_CH((left_err >> NIBBLE_SIZE) & NIBBLE); buffer[3] = HEX_TO_CH((left_err ) & NIBBLE); buffer[4] = '-'; buffer[5] = HEX_TO_CH((right_err >> BYTE_SIZE ) & NIBBLE); buffer[6] = HEX_TO_CH((right_err >> NIBBLE_SIZE) & NIBBLE); buffer[7] = HEX_TO_CH((right_err ) & NIBBLE); buffer[8] = NULL_TERM; buffer[9] = NULL_TERM; buffer[10] = NULL_TERM; /*buffer[ARR_POS_0] = '0'; buffer[ARR_POS_1] = 'x'; buffer[ARR_POS_2] = HEX_TO_CH((right_err >> BYTE_SIZE ) & NIBBLE); buffer[ARR_POS_3] = HEX_TO_CH((right_err >> NIBBLE_SIZE) & NIBBLE); buffer[ARR_POS_4] = HEX_TO_CH((right_err) & NIBBLE); buffer[ARR_POS_5] = NULL_TERM;*/ } //------------------------------------------------------------------------------ // Function Name : run_basic // // Description: This function runs the basic line following program // Arguements: void // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void run_basic() { } /*// Detect What side of the line currently on if(!current_side_error && (right_err > left_err)) { current_side_error = RIGHT_SIDE; } else if(!current_side_error && (left_err > right_err)) { current_side_error = LEFT_SIDE; } else if((left_err == 0) && (right_err == 0)) { current_side_error = NO_ERROR; } if(current_side_error == RIGHT_SIDE) { set_motor_speed(R_FORWARD, (int) (right_power * 1.0f)); set_motor_speed(L_REVERSE, (int) (left_power * .85f)); turn_on_motor(R_FORWARD); turn_on_motor(L_REVERSE); five_msec_delay(35); turn_off_motor(R_FORWARD); turn_off_motor(L_REVERSE); } else if(current_side_error == LEFT_SIDE) { set_motor_speed(R_REVERSE, (int) (right_power * 1.0f)); set_motor_speed(L_FORWARD, (int) (left_power * .85f)); turn_on_motor(R_REVERSE); turn_on_motor(L_FORWARD); five_msec_delay(35); turn_off_motor(R_REVERSE); turn_off_motor(L_FORWARD); } else { set_motor_speed(R_FORWARD, right_power); set_motor_speed(L_FORWARD, left_power); turn_on_motor(R_FORWARD); turn_on_motor(L_FORWARD); five_msec_delay(35); } five_msec_delay(35);*/<file_sep>/switch.c //============================================================================// // File Name : switch.c // // Description: This file contains the board control switch functions // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //============================================================================// #include "switch.h" #include "adc.h" //------------------------------------------------------------------------------ // Module Scope Globals static volatile u_int8 sw_pressed_mask = FALSE; static volatile u_int8 sw_down_mask = FALSE; static volatile u_int8 pressed_count = 0; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Function Name : Switches_Process // // Description: This function polls the current states of Switches SW1/SW2 // and sets the two different text options based on the switch // currently toggled // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void update_switches() { u_int8 temp_down = sw_down_mask; u_int8 temp_pressed = sw_pressed_mask; menu_handle_input(temp_pressed); // Pressed only lasts one cycle // Down lasts until released sw_pressed_mask ^= temp_pressed; //if(temp_pressed & SW_1) // handle_input(temp_pressed, pressed_count); } //------------------------------------------------------------------------------ // Function Name : software_debounce // // Description: This function takes a port and pin as inputs and returns the // software debounced state of the requested pin as a bool // Arguements: unsigned short volatile* port // u_int8 pin_mask // Returns: bool value // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ bool software_debounce(unsigned short volatile* port, u_int8 pin_mask) { return false; } //------------------------------------------------------------------------------ // Function Name : sw_pressed // // Description: This function sets the sw_pressed_mask bit for the corresponding // bit to which switch was pressed // Arguements: u_int8 sw_mask // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void sw_pressed(u_int8 sw_mask) { sw_pressed_mask |= sw_mask; sw_down_mask |= sw_mask; } //------------------------------------------------------------------------------ // Function Name : sw_released // // Description: This function clears the sw_pressed_mask bit for the // corresponding bit to which switch was released // Arguements: u_int8 sw_mask // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void sw_released(u_int8 sw_mask) { sw_down_mask &= ~sw_mask; } //------------------------------------------------------------------------------ // Function Name : setup_sw_debounce // // Description: This sets up switch debouncing and the corresponding // port interrupt registers // Arguements: void // Returns: void // // Author: <NAME> // Date: Feb 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ void setup_sw_debounce(void) { P4IE |= SW_1 | SW_2; P4IES |= SW_1 | SW_2; // initial state is rising edge TA1CTL &= ~TIMER_STOP; TA1CTL &= CLEAR_REGISTER; TA1CTL &= ~TBIE; TA1CTL |= TASSEL_1; TA1CTL &= ~TIMER_DIVIDE; TA1CTL |= TIMER_CONTINUOUS; TA1CCTL1 &= CLEAR_REGISTER; } //------------------------------------------------------------------------------ // Function Name : get_sw_pressed // // Description: This is a basic getter for the local sw_pressed field // Arguements: void // Returns: void // // Author: <NAME> // Date: March 2016 // Compiler: Built with IAR Embedded Workbench Version: V4.10A/W32 (6.40.1) //------------------------------------------------------------------------------ u_int8 get_sw_pressed() { return sw_pressed_mask; }
a5f6cbedf6307007ccd604a3495f227c2ce4989f
[ "C" ]
33
C
apcragg/ECE306-Car
8c0bc5b8d3f2b74b57b42e5b2f24f81d1456456d
78019ed40e58e86252c26994afb1234e4b115c7d
refs/heads/master
<repo_name>graehl/subword-nmt<file_sep>/apply_bpe.py #!/usr/bin/python # -*- coding: utf-8 -*- # Author: <NAME> """Use operations learned with learn_bpe.py to encode a new text. The text will not be smaller, but use only a fixed vocabulary, with rare words encoded as variable-length sequences of subword units. Reference: <NAME>, <NAME> and <NAME> (2015). Neural Machine Translation of Rare Words with Subword Units. Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (ACL 2016). Berlin, Germany. """ from __future__ import unicode_literals, division import sys import codecs import argparse import json import re from collections import defaultdict # hack for python2/3 compatibility from io import open argparse.open = open def unicodeutf8(s): return unicode(s, 'utf8') if type(s)==str else s def common_parser_arguments(parser): parser.add_argument('--unkchar', type=unicodeutf8, default=u'\uFDEA', metavar='utf8', help="a unicode (utf8) codepoint character that will never participate in merges. default is U+FDEA (hex), a private noncharacter") parser.add_argument('--verbose', '-v', type=int, default=0, help="higher = more ### stderr msgs") parser.add_argument( '--separator', type=str, default='@@', metavar='STR', help="Separator between non-final subword units (default: '%(default)s'))") parser.add_argument('--unktag', type=str, default='<unk>', help='replace unkchar with this (utf8)') endword='</w>' verbose=0 def log(s, out=sys.stderr): out.write("### %s\n" % (s,)) def logv(v, s, out=sys.stderr): if verbose >= v: log(s, out) def written(x, sep=''): return x[:-4] if x.endswith(endword) else x + sep def stripend(x): return x[:-4] if x.endswith(endword) else x versionheaderbegin = '#version: ' def write_pair(pair, out): out.write("%s %s\n"%pair) def write2(a, b, out): out.write("%s %s\n"%(a, b)) def write_header(outfile, version): outfile.write('%s%s.%s\n' % (versionheaderbegin, version[0], version[1])) def version_line(line): return line.startswith(versionheaderbegin) def maybe_header_version(line): if version_line(line): return tuple(int(x) for x in line[len(versionheaderbegin):].split(".")) else: return None class BPE(object): def __init__(self, codes, separator='@@', vocab=None, glossaries=None, rglossaries=None, unkchar=u'\uFDEA', unktag='<unk>'): # check version information firstline = codes.readline() self.version = maybe_header_version(firstline) if self.version is None: log("no version header in %s"%codes) self.version = (0, 1) codes.seek(0) log("version %s"%str(self.version)) self.bpe_codes = [tuple(item.split()) for item in codes] # some hacking to deal with duplicates (only consider first instance) self.bpe_codes = dict([(code,i) for (i,code) in reversed(list(enumerate(self.bpe_codes)))]) self.bpe_codes_reverse = dict([(pair[0] + pair[1], pair) for pair,i in self.bpe_codes.items()]) self.separator = separator self.vocab = vocab self.unktag = unktag self.unkchar = unkchar self.glossaries = glossaries if glossaries else [] self.rglossaries = rglossaries if rglossaries else [] relist = [re.escape(x) for x in self.glossaries] + self.rglossaries if len(relist): retext = '(%s)' % '|'.join(relist) sys.stderr.write('glossaries re: %s\n' % retext) self.glossary_re = re.compile(retext) else: self.glossary_re = None self.cache = {} def ordered_codes(self): return sorted(self.bpe_codes.items(), key=lambda x: x[1]) def prereqs(self, vocab, seen=None): if seen is None: seen=set() def prereqs2(s, pair): seen.add(s) prereqs(pair[0]) prereqs(pair[1]) def prereqs(s): if len(s) > 1 and s not in seen: seen.add(s) pair = self.bpe_codes_reverse.get(s, None) if pair is not None: prereqs2(s, pair) for ab, pair in self.bpe_codes_reverse.items(): if written(ab, self.separator) in vocab: prereqs2(ab, pair) return seen def write_subset(self, out, bpevocab, pre=None): """only include merges that are useful to reach vocab""" write_header(out, self.version) if pre is None: pre = self.prereqs(bpevocab) for pair,_ in self.ordered_codes(): ab = pair[0] + pair[1] if written(ab, self.separator) in bpevocab or ab in pre: write_pair(pair, out) def segment(self, sentence): """segment single sentence (whitespace-tokenized string) with BPE encoding""" output = [] for word in sentence.split(): self.pieces(word, output) return ' '.join(output) def pieces(self, word, output=None): if output is None: output = [] new_word = [] isolated = False for segment in self._isolate_glossaries(word): if len(segment): if isolated: new_word.append(segment) sys.stderr.write('glossarized segment (leaving alone): "%s"\n' % segment) else: new_word += encode(segment, self.bpe_codes, self.bpe_codes_reverse, self.vocab, self.separator, self.version, self.cache, unkchar=self.unkchar, unktag=self.unktag) isolated = not isolated remain = len(new_word) sep = self.separator for item in new_word: remain -= 1 if remain == 0: sep = '' output.append(item + sep) return output def _isolate_glossaries(self, word): """ Isolate a glossary present inside a word. Returns a list of subwords. In which all 'glossary' glossaries are isolated For example, if 'USA' is the glossary and '1934USABUSA' the word, the return value is: ['1934', 'USA', 'B', 'USA'] """ gre = self.glossary_re return [word] if gre is None else gre.split(word) def create_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="learn BPE-based word segmentation") common_parser_arguments(parser) parser.add_argument( '--input', '-i', type=argparse.FileType('r'), default=sys.stdin, metavar='PATH', help="Input file (default: standard input).") parser.add_argument( '--codes', '-c', type=argparse.FileType('r'), metavar='PATH', required=True, help="File with BPE codes (created by learn_bpe.py).") parser.add_argument( '--output', '-o', type=argparse.FileType('w'), default=sys.stdout, metavar='PATH', help="Output file (default: standard output)") parser.add_argument( '--vocabulary', type=argparse.FileType('r'), default=None, metavar="PATH", help="Vocabulary file (built with get_vocab.py). If provided, split up subword units until they're in this vocabulary.") parser.add_argument( '--vocabulary-threshold', type=int, default=1, metavar="INT", help="Vocabulary threshold. If vocabulary is provided, any word with frequency < threshold will be treated as OOV") parser.add_argument( '--glossaries', type=str, nargs='+', default=None, metavar="STR", help="Glossaries. The strings provided in glossaries will not be affected"+ "by the BPE (i.e. they will neither be broken into subwords, nor concatenated with other subwords") parser.add_argument( '--rglossaries', type=str, nargs='+', default=None, metavar="REGEX", help="Glossaries. The (python 're') regexes provided in glossaries will not be affected"+ "by the BPE (i.e. they will neither be broken into subwords, nor concatenated with other subwords."+ "If glossaries/rglossaries are ambiguous, know that they form a single regexp (glossaries ..."+ "rglossaries) in that order, and are resolved by re.split (so probably winner is "+ "earliest-in-string match with ties broken by earliest-in-list.") return parser def get_pairs(word): """Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings) """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs def encode(orig, bpe_codes, bpe_codes_reverse, vocab, separator, version, cache, unkchar=u'\uFDEA', unktag='<unk>'): """Encode word based on list of BPE merge operations, which are applied consecutively """ if orig in cache: return cache[orig] if version == (0, 1): word = tuple(orig) + (endword,) elif version == (0, 2): # more consistent handling of word-final segments word = tuple(orig[:-1]) + ( orig[-1] + endword,) else: raise NotImplementedError pairs = get_pairs(word) if not pairs: return orig while True: bigram = min(pairs, key = lambda pair: bpe_codes.get(pair, float('inf'))) if bigram not in bpe_codes: break first, second = bigram new_word = [] i = 0 while i < len(word): # replace bigram everywhere in word try: j = word.index(first, i) new_word.extend(word[i:j]) i = j except: new_word.extend(word[i:]) break if word[i] == first and i < len(word)-1 and word[i+1] == second: new_word.append(first+second) i += 2 else: new_word.append(word[i]) i += 1 new_word = tuple(new_word) word = new_word if len(word) == 1: break else: pairs = get_pairs(word) # don't print end-of-word symbols if word[-1] == endword: word = word[:-1] elif word[-1].endswith(endword): word = word[:-1] + (word[-1].replace(endword,''),) if vocab: word = check_vocab_and_split(word, bpe_codes_reverse, vocab, separator) word = [unktag if x == unkchar else x for x in word] cache[orig] = word return word def recursive_split(segment, bpe_codes, vocab, separator, final=False): """Recursively split segment into smaller units (by reversing BPE merges) until all units are either in-vocabulary, or cannot be split futher.""" try: if final: left, right = bpe_codes[segment + endword] right = right[:-4] else: left, right = bpe_codes[segment] except: #sys.stderr.write('cannot split {0} further.\n'.format(segment)) yield segment return if left + separator in vocab: yield left else: for item in recursive_split(left, bpe_codes, vocab, separator, False): yield item if (final and right in vocab) or (not final and right + separator in vocab): yield right else: for item in recursive_split(right, bpe_codes, vocab, separator, final): yield item def check_vocab_and_split(orig, bpe_codes, vocab, separator): """Check for each segment in word if it is in-vocabulary, and segment OOV segments into smaller units by reversing the BPE merge operations""" out = [] for segment in orig[:-1]: if segment + separator in vocab: out.append(segment) else: logv(1, 'OOV: {0}\n'.format(segment + separator)) for item in recursive_split(segment, bpe_codes, vocab, separator, False): out.append(item) segment = orig[-1] if segment in vocab: out.append(segment) else: logv(1, 'final OOV: {0}\n'.format(segment)) for item in recursive_split(segment, bpe_codes, vocab, separator, True): out.append(item) return out def read_vocabulary_set(vocab_file, threshold=1): """read vocabulary file produced by get_vocab.py, and filter according to frequency threshold. """ vocabulary = set() for line in vocab_file: word, freq = line.split() if int(freq) >= threshold: vocabulary.add(word) return vocabulary if __name__ == '__main__': # python 2/3 compatibility if sys.version_info < (3, 0): sys.stderr = codecs.getwriter('UTF-8')(sys.stderr) sys.stdout = codecs.getwriter('UTF-8')(sys.stdout) sys.stdin = codecs.getreader('UTF-8')(sys.stdin) else: sys.stderr = codecs.getwriter('UTF-8')(sys.stderr.buffer) sys.stdout = codecs.getwriter('UTF-8')(sys.stdout.buffer) sys.stdin = codecs.getreader('UTF-8')(sys.stdin.buffer) parser = create_parser() args = parser.parse_args() verbose = args.verbose # read/write files as UTF-8 args.codes = codecs.open(args.codes.name, encoding='utf-8') if args.input.name != '<stdin>': args.input = codecs.open(args.input.name, encoding='utf-8') if args.output.name != '<stdout>': args.output = codecs.open(args.output.name, 'w', encoding='utf-8') if args.vocabulary: args.vocabulary = codecs.open(args.vocabulary.name, encoding='utf-8') if args.vocabulary: vocabulary = read_vocabulary_set(args.vocabulary, args.vocabulary_threshold) else: vocabulary = None bpe = BPE(args.codes, args.separator, vocabulary, args.glossaries, args.rglossaries, unkchar=args.unkchar, unktag=args.unktag) for line in args.input: args.output.write(bpe.segment(line).strip()) args.output.write('\n') <file_sep>/test/test_glossaries.py #!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import mock import re import os,sys,inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) from apply_bpe import BPE class TestBPEIsolateGlossariesMethod(unittest.TestCase): def setUp(self): amock = mock.MagicMock() amock.readline.return_value = 'something' glossaries = ['like', 'USA'] rglossaries = ['M[Manuel]*l'] self.bpe = BPE(amock, glossaries=glossaries, rglossaries=rglossaries) def _run_test_case(self, test_case): orig, expected = test_case out = self.bpe._isolate_glossaries(orig) self.assertEqual(out, expected) def test_multiple_glossaries(self): orig = 'wordlikeManuelUSAwordManuelManuelwordUSA' exp = ['word', 'like', '', 'Manuel', '', 'USA', 'word', 'ManuelManuel', 'word', 'USA', ''] test_case = (orig, exp) self._run_test_case(test_case) class TestBPESegmentMethod(unittest.TestCase): def setUp(self): amock = mock.MagicMock() amock.readline.return_value = 'something' glossaries = ['like', 'Manuel', 'USA'] self.bpe = BPE(amock, glossaries=glossaries) def _run_test_case(self, test_case): orig, expected = test_case out = self.bpe.segment(orig) self.assertEqual(out, expected) def test_multiple_glossaries(self): orig = 'wordlikeword likeManuelword' exp = 'w@@ o@@ r@@ d@@ like@@ w@@ o@@ r@@ d l@@ i@@ k@@ e@@ M@@ a@@ n@@ u@@ e@@ l@@ word' test_case = (orig, exp) self._run_test_case(test_case) if __name__ == '__main__': unittest.main() <file_sep>/data/test.joint.sh cd `dirname $0` sep=__ subword_prefix=joint.sw subword_ops=3000 subword_unk=50 ../subword.sh -c v.en v.jp <file_sep>/threshold_vocab.py #! /usr/bin/env python from __future__ import print_function import sys threshold = int(sys.argv[1]) for line in sys.stdin: k, c = line.split() c = int(c) if c >= threshold: sys.stdout.write(line) <file_sep>/subword.sh #!/bin/bash realpath() { readlink -nfs $(cd "$(dirname $1)"; pwd)/"$(basename $1)" } d=`dirname $(realpath $0)` set -e tokenize() { if [[ $tokenizer ]] ; then $tokenizer else cat fi } bpevars() { echo "sep=${sep:=__LW_SW__} subwords=${subwords:=50000} mincount=${mincount:=2} minfreq=${minfreq:=20} unkfreq=${unkfreq:=2} subword_prefix=${subword_prefix:=${subword_dir:-`dirname $0`}/subword} ${subword_outdir:=} ${exclude_bpe_basename:=1} dict_input=${dict_input}" 1>&2 codes=$subword_prefix.codes } skipbpe() { [[ $exclude_bpe_basename ]] && basename "$1" | fgrep -q .bpe } absp() { readlink -nfs "$@" } vocab() { echo "${subword_prefix}.$1.vcb" } lang() { basename "$1" | awk -F "." '{print $2}' } create() { vocabs="" for f in "$@"; do l=`lang "$f"` vocabs+=" $(vocab $l)" done ln -sf `absp $0` $subword_prefix codebase=$codes if [[ $dict_input ]] ; then dictinputarg=" --dict-input" fi if [[ $joint ]] ; then set -x $python3 $d/learn_joint_bpe_and_vocab.py --input "$@" --separator $sep -s $subwords -o $codes --write-vocabulary $vocabs $versionarg --min-frequency $minfreq --min-count $mincount $dictinputarg for f in "$@"; do l=`lang "$f"` vocab=$(vocab $l) if [[ $applytoo ]] ; then apply "$f" fi done ls -l $codes $vocabs else versionarg=$versionarg0 for f in "$@"; do l=`lang "$f"` vocab=$(vocab $l) codes=$codebase.$l $python3 $d/learn_bpe.py --input "$f" --separator $sep -s $subwords -o $codes --write-vocabulary $vocab $versionarg --min-frequency $minfreq --min-count $mincount $dictinputarg versionarg=$versionarg1 ls -l $code $vocab if [[ $applytoo ]] ; then apply "$f" fi done fi } bpevocab() { vocab=$1 shift $python3 -u $d/apply_bpe.py -s $sep -c $codes --vocabulary $vocab --vocabulary-threshold $unkfreq "$@" } apply() { for f in "$@"; do if ! skipbpe "$f" ; then l=`lang "$f"` fb=`basename -s .$l "$f"` vocab=`vocab $l` [[ $subword_outdir ]] || subword_outdir=`dirname "$f"` fto="$subword_outdir/$fb.bpe.$l" echo $fto (set -e [[ -s $vocab ]] cat "$f" | lang=$l tokenize | bpevocab $vocab > $fto ) fi done } joint=1 versionarg0= versionarg1= case $1 in *01) joint= versionarg1=--version01 ;; *10) joint= versionarg0=--version01 ;; *00) joint= versionarg1=--version01 versionarg0=--version01 ;; *) ;; esac case $1 in -h*) echo 'usage: subword_prefix=/tmp/subword subwords=32000 minfreq=50 $0 [-c] a.l1 b.l2' ;; -c*) if [[ ${1%v} != $1 ]] ; then dict_input=1 fi subword_dir=${subword_dir:-.} bpevars shift create "$@" ;; *) bpevars apply "$@" ;; esac <file_sep>/get_vocab.py #! /usr/bin/env python from __future__ import print_function import sys import codecs import unicodedata import os from collections import Counter from unicodedata import normalize # python 2/3 compatibility if sys.version_info < (3, 0): sys.stderr = codecs.getwriter('UTF-8')(sys.stderr) sys.stdout = codecs.getwriter('UTF-8')(sys.stdout) sys.stdin = codecs.getreader('UTF-8')(sys.stdin) else: sys.stderr = codecs.getwriter('UTF-8')(sys.stderr.buffer) sys.stdout = codecs.getwriter('UTF-8')(sys.stdout.buffer) sys.stdin = codecs.getreader('UTF-8')(sys.stdin.buffer) # NFK?[DC] K makes roman numeral I -> ascii I. C means composed, D means decomposed if len(sys.argv) > 1: unicodenormal = sys.argv[1] if len(sys.argv) > 2: print("WARNING: ignoring extra args %s\n"%sys.argv[2:], file=sys.stderr) else: unicodenormal = os.environ.get('unicodenormal', 'NFC') c = Counter() for line in sys.stdin: for word in line.split(): if len(word): c[unicodedata.normalize(unicodenormal, word)] += 1 for key,f in c.most_common(): print(key+" "+ str(f)) <file_sep>/data/test.apart.sh cd `dirname $0` sep=__ subword_prefix=apart.sw subword_ops=3000 subword_unk=50 ../subword.sh -c10 v.en v.jp <file_sep>/learn_joint_bpe_and_vocab.py #!/usr/bin/python # -*- coding: utf-8 -*- # Author: <NAME> """Use byte pair encoding (BPE) to learn a variable-length encoding of the vocabulary in a text. This script learns BPE jointly on a concatenation of a list of texts (typically the source and target side of a parallel corpus, applies the learned operation to each and (optionally) returns the resulting vocabulary of each text. The vocabulary can be used in apply_bpe.py to avoid producing symbols that are rare or OOV in a training text. Reference: <NAME>, <NAME> and <NAME> (2016). Neural Machine Translation of Rare Words with Subword Units. Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (ACL 2016). Berlin, Germany. """ from __future__ import unicode_literals import sys import codecs import argparse from collections import Counter import learn_bpe import apply_bpe # hack for python2/3 compatibility from io import open argparse.open = open def create_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="learn BPE-based word segmentation") parser.add_argument( '--input', '-i', type=argparse.FileType('r'), required=True, nargs = '+', metavar='PATH', help="Input texts (multiple allowed).") learn_bpe.common_parser_arguments(parser) return parser if __name__ == '__main__': # python 2/3 compatibility if sys.version_info < (3, 0): sys.stderr = codecs.getwriter('UTF-8')(sys.stderr) sys.stdout = codecs.getwriter('UTF-8')(sys.stdout) sys.stdin = codecs.getreader('UTF-8')(sys.stdin) else: sys.stderr = codecs.getwriter('UTF-8')(sys.stderr.buffer) sys.stdout = codecs.getwriter('UTF-8')(sys.stdout.buffer) sys.stdin = codecs.getreader('UTF-8')(sys.stdin.buffer) parser = create_parser() args = parser.parse_args() if args.vocab and len(args.input) != len(args.vocab): sys.stderr.write('Error: number of input files and vocabulary files must match\n') sys.exit(1) # read/write files as UTF-8 args.input = [codecs.open(f.name, encoding='UTF-8') for f in args.input] args.vocab = [codecs.open(f.name, 'w', encoding='UTF-8') for f in args.vocab] # get combined vocabulary of all input texts full_vocab = Counter() vocabs = [] for f in args.input: v = learn_bpe.get_vocabulary(f, args.dict_input, args.mincount) vocabs.append(v) full_vocab += v f.seek(0) # learn BPE on combined vocabulary with codecs.open(args.output.name, 'w', encoding='UTF-8') as output: learn_bpe.main_args(args, full_vocab, output, is_dict=True) with codecs.open(args.output.name, encoding='UTF-8') as codes: bpe = apply_bpe.BPE(codes, args.separator, None) # apply BPE to each training corpus and get vocabulary learn_bpe.make_vocabularies(bpe, vocabs, args.vocab) <file_sep>/bpe_subset.py #!/usr/bin/python # -*- coding: utf-8 -*- # Author: <NAME> """When learning a BPE codes for two languages, create BPE-subset vocabularies for apply_bpe.py restriction (learn_joint_bpe_and_vocab.py will already do this for you) Optionally create separate bpe codes file pre-restricted. Reference: <NAME>, <NAME> and <NAME> (2016). Neural Machine Translation of Rare Words with Subword Units. Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (ACL 2016). Berlin, Germany. """ import argparse import sys import codecs import learn_bpe import apply_bpe from collections import Counter # hack for python2/3 compatibility from io import open argparse.open = open def create_parser(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description="create BPE-segmented vocabulary subset") apply_bpe.common_parser_arguments(parser) parser.add_argument( '--input', '-i', type=argparse.FileType('r'), default=sys.stdin, metavar='PATH', help="running or vocab text input file (default: standard input).") parser.add_argument( '--input-is-vocab', '-V', type=bool, dest='dict_input', default=True) parser.add_argument( '--codes', '-c', type=argparse.FileType('r'), metavar='PATH', required=True, help="File with BPE codes (created by learn_bpe.py).") parser.add_argument( '--min-count,', '-m', type=int, dest='mincount', default=1, help="drop from pre-bpe vocab any word with count below this") parser.add_argument( '--outcodes', '-o', type=argparse.FileType('w'), metavar='PATH', help="output vocabulary restricted bpe codes subset to this file") parser.add_argument('--bpevocab', '-b', type=argparse.FileType('w'), metavar='PATH', help="output bpe vocab (default: standard output") return parser def main(args): vocab = learn_bpe.get_vocabulary(args.input, args.dict_input, args.mincount) assert isinstance(vocab, Counter) bpe = apply_bpe.BPE(args.codes, args.separator, vocab=None, unkchar=args.unkchar, unktag=args.unktag) bpevocab = learn_bpe.restricted_vocabulary(bpe, vocab) if args.outcodes is not None: bpe.write_subset(args.outcodes, bpevocab) if args.bpevocab is not None: learn_bpe.write_vocabulary(bpevocab, args.bpevocab) if __name__ == '__main__': # python 2/3 compatibility if sys.version_info < (3, 0): sys.stderr = codecs.getwriter('UTF-8')(sys.stderr) sys.stdout = codecs.getwriter('UTF-8')(sys.stdout) sys.stdin = codecs.getreader('UTF-8')(sys.stdin) else: sys.stderr = codecs.getwriter('UTF-8')(sys.stderr.buffer) sys.stdout = codecs.getwriter('UTF-8')(sys.stdout.buffer) sys.stdin = codecs.getreader('UTF-8')(sys.stdin.buffer) parser = create_parser() main(parser.parse_args())
12d14cdf3c51bfa7f62285c2de37c98fc5f8e7c1
[ "Python", "Shell" ]
9
Python
graehl/subword-nmt
1af13a1da64312c674d36e4dc6fbf9e36bf6cdc8
e58b535c85a8fe7171c508866755911cb0e9bab6
refs/heads/master
<file_sep>{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "baseUrl": "src", "paths": { "@storage/*": ["storage/*"], "@cache": ["storage/cache/cache.ts"], "@localStorage": ["storage/local/local.ts"], "@gqlClient": ["api/gql/GqlClient.ts"], "@gqlOps/*": ["api/gql/__generated__/*"], "@restClient": ["api/rest/RestClient.ts"], "@schemas": ["api/gql/schemas.ts"], "@components/*": ["components/*"], "@containers/*": ["containers/*"], "@assets/*": ["assets/*"], "@styles": ["styles.ts"], "@logger": ["logger/index.ts"] }, "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react" }, "include": [ "src" ] } <file_sep>/* eslint-disable import/extensions */ import styled from '@emotion/styled'; import { Link } from 'react-router-dom'; import { unit } from '@styles'; import { cardClassName } from '../Launch.styles'; const padding = unit * 2; // eslint-disable-next-line import/prefer-default-export export const StyledLink = styled(Link)(cardClassName, { display: 'block', height: 193, marginTop: padding, textDecoration: 'none', ':not(:last-child)': { marginBottom: padding * 2, }, }); <file_sep>/* eslint-disable import/prefer-default-export */ import * as Sentry from '@sentry/react'; import { ErrorInfo } from 'react'; import { Scope } from '@sentry/react'; import { Integrations } from '@sentry/tracing'; const { NODE_ENV } = process.env; /** * Initializes logger reporter service */ export const initializeLogger = (): void => { /* istanbul ignore next */ // eslint-disable-next-line no-restricted-globals if ( NODE_ENV === 'production' && // eslint-disable-next-line no-restricted-globals (location.protocol === 'https' || location.protocol === 'https:') ) { Sentry.init({ // eslint-disable-next-line no-underscore-dangle dsn: process.env.SENTRY_DSN || window._env_.SENTRY_DSN, integrations: [new Integrations.BrowserTracing()], tracesSampleRate: 1.0, }); } }; /** * capture and log any errors caught * @param error error in stacktrace * @param errorInfo Error information from React */ export const captureAndLogError = (error: Error, errorInfo: ErrorInfo): void => { Sentry.withScope((scope: Scope) => { // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore scope.setExtras(errorInfo); Sentry.captureException(error); }); }; /** * Capture exception * @param {Error} error Error context */ export const captureException = ( error: Error, scope?: Scope, errorMessage = 'Error Caught', ): void => { Sentry.captureMessage(errorMessage, scope); Sentry.captureException(error); }; <file_sep>import styled from '@emotion/styled'; import { size } from 'polished'; import { unit, colors } from '@styles'; export const Container = styled('div')({ display: 'flex', alignItems: 'center', marginBottom: unit * 4.5, }); // eslint-disable-next-line @typescript-eslint/ban-ts-ignore // @ts-ignore export const Image = styled('img')(size(134), (props: { round: boolean }) => ({ marginRight: unit * 2.5, borderRadius: props.round ? '50%' : '0%', })); export const Subheading = styled('h5')({ marginTop: unit / 2, color: colors.textSecondary, }); <file_sep>APOLLO_KEY=service:graph_name:graph API_URL=http://localhost:4000 SENTRY_DSN=https://123456.ingest.sentry.io/123456 <file_sep>import styled from '@emotion/styled'; import { unit, colors } from '@styles'; export const Bar = styled('div')({ flexShrink: 0, height: 12, backgroundColor: colors.primary, }); export const Container = styled('div')({ display: 'flex', flexDirection: 'column', flexGrow: 1, width: '100%', maxWidth: 600, margin: '0 auto', padding: unit * 3, paddingBottom: unit * 5, }); <file_sep># Space Xplorer Client [![Codacy Badge](https://app.codacy.com/project/badge/Grade/2ccaf6e7f5c340a89c31391094556e47)](https://www.codacy.com/gh/Wyvarn/space-xplorer-client?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=Wyvarn/space-xplorer-client&amp;utm_campaign=Badge_Grade) ![Code scanning](https://github.com/Wyvarn/space-xplorer-client/workflows/Code%20scanning/badge.svg) ![Github Release](https://github.com/Wyvarn/space-xplorer-client/workflows/Github%20Release/badge.svg) ![Sentry Release](https://github.com/Wyvarn/space-xplorer-client/workflows/Sentry%20Release/badge.svg) ![Space Xplorer Client Docker Image Build](https://github.com/Wyvarn/space-xplorer-client/workflows/Space%20Xplorer%20Client%20Docker%20Image%20Build/badge.svg) ![Tests](https://github.com/Wyvarn/space-xplorer-client/workflows/Tests/badge.svg) [![Codacy Badge](https://app.codacy.com/project/badge/Coverage/2ccaf6e7f5c340a89c31391094556e47)](https://www.codacy.com/gh/Wyvarn/space-xplorer-client?utm_source=github.com&utm_medium=referral&utm_content=Wyvarn/space-xplorer-client&utm_campaign=Badge_Coverage) UI interface for allowing users to book seats on the next SpaceX launch ## Prerequisites There are some pre-requisites needed to run this application ### Node (npm or yarn) You will need node installed on your local development environment. This will include a package manager such as npm or yarn. Preferably yarn due to the dependency management being handled in this case uses `yarn.lock` file. Consult relevant documentation to have these installed ### Docker & Docker Compose Ensure you have installed docker & docker-compose cli tools in your development environment to be able to run accomanying services that will be required for this frontend application to work. Consult the Docker documentation to be able to install & run docker ## Getting started Once you have all the tools locally, the rest should be straight forward. Create a `.env` file in the root of the project. This can be done as below: ``` bash cp .env.example .env ``` Now run `docker-compose up` in the root of the project ``` bash docker-compose up ``` > This will start all services specified in the docker-compose file If you encounter any challenges running the above command, say, port conflicts, run the below command: ``` bash docker stop $(docker ps -aq) ``` > This will stop all running containers Now, you can run `docker-compose up` again. This should get all the services (docker containers) running. Now, you can install the dependencies: ``` bash yarn install (or npm install) ``` Now run the application with: ``` bash yarn start (or npm run start) ``` Runs the app in the development mode.<br /> The page will reload if you make edits.<br /> You will also see any lint errors in the console. Access the frontend application on `http://localhost:3000` That should be it for getting up & running :). ### Available Scripts In the project directory, you can also run: #### `yarn test` Launches the test runner in the interactive watch mode.<br /> #### `yarn build` Builds the app for production to the `build` folder.<br /> It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.<br /> Your app is ready to be deployed! #### yarn lint Checks for any linting issues with ESlint & TypeScript configurations. Other plugins are included, check [here](./eslintrc.js) for a list of plugins #### yarn lint:fix Fixes any linting issues found #### yarn stylelint:fix Fixes SCSS linting issues found #### yarn serve Serge static assets. This is to emulate how the application will work behind a static server. This has to be run after `yarn build` to generate bundle #### yarn test Runs unit tests #### yarn test:cover Runs tests & generates a coverage report ## Running application with Docker We have built the application to make it portable & to do this, we have used Docker to containerize application & make it run in any environment. Build a docker container for this application with: ``` bash docker build -t wyvarn/space-xplorer-client:<TAG> . ``` > Where TAG is the name of the tag to use, if not put, this defaults to latest. Note that the image could be given any other name Once the image is built, you can run the application in container with the following command: ``` bash docker run --name space-xplorer-client -p 8080:8080 wyvarn/space-xplorer-client:<TAG ``` > TAG is the tag you set earlier when building the image, note that the --name flag is optional & can be set to something else This should give you an output similar to this: ``` bash 2020-06-19T10:18:12: PM2 log: Launching in no daemon mode 2020-06-19T10:18:12: PM2 log: [Watch] Start watching space-xplorer-client 2020-06-19T10:18:12: PM2 log: App [space-xplorer-client:0] starting in -cluster mode- 2020-06-19T10:18:12: PM2 log: App [space-xplorer-client:0] online 2020-06-19T10:18:12: PM2 log: [Watch] Start watching space-xplorer-client 2020-06-19T10:18:12: PM2 log: App [space-xplorer-client:1] starting in -cluster mode- 2020-06-19T10:18:12: PM2 log: App [space-xplorer-client:1] online 2020-06-19T10:18:12: PM2 log: [Watch] Start watching space-xplorer-client 2020-06-19T10:18:12: PM2 log: App [space-xplorer-client:2] starting in -cluster mode- 2020-06-19T10:18:12: PM2 log: App [space-xplorer-client:2] online 2020-06-19T10:18:12: PM2 log: [Watch] Start watching space-xplorer-client 2020-06-19T10:18:12: PM2 log: App [space-xplorer-client:3] starting in -cluster mode- 2020-06-19T10:18:12: PM2 log: App [space-xplorer-client:3] online ... ``` > This output is from PM2 which is serving the application via Express Server handling static assets Consult [PM2](https://pm2.keymetrics.io/) documentation for further instructions if you want to extend & improve on how this application is run :simple_smile: Configuration can be found [here](./server/ecosystem.config.js) If the preference is using [Nginx](https://www.nginx.com/) to serve static content, we got you. There is a [Dockerfile](./Dockerfile.static) that already caters for this & the build process is pretty much the same: ``` bash docker build -f Dockerfile.static -t wyvarn/space-xplorer-client:<TAG> . ``` > Note that you have to pass in the Dockerfile path & you can tag the name however you want. To run the application ``` bash docker run --name space-xplorer-client -p 8080:80 wyvarn/space-xplorer-client:<TAG ``` > Note the difference in the port mapping as this has been set [here](./conf/conf.d/default.conf) to listen on 80 That should be it. You will notice that this has been built to have dynamic Environment variables set as is specified in [this](./env.sh) shell script which has been baked into the build process when running a build. This is to allow switching environment variables when running in different contexts without triggering a new build in a pipeline. This is useful for cases when using Docker containers However, the normal build pipeline with a CI should already cater fo this. ## Deployment Deploying the application depends on the environment available. 1. If using Docker, there are already configured Dockerfiles that will allow building this application. [This](./Dockerfile) & [this](./Dockerfile.static) 2. If deploying behind a Web Server such as Nginx, there are [config](./conf) files already available. 3. If deploying to a static hosting site such as [Netlfy](https://www.netlify.com/), there is a [netlify toml](./netlify.toml) file already set & can be modified to suit ones needs ## Built With 1. [JavaScript](https://www.javascript.com/) - Source language 2. [TypeScript](https://www.typescriptlang.org/) - Source language 3. [ESLint](https://eslint.org/) - JavaScript linter 4. [ReactJS](https://reactjs.org) - Frontend Library 5. [Node](https://nodejs.org/en/) 6. [Jest](https://jestjs.io) - Test framework 8. [React Router](https://reacttraining.com/react-router/) - React routing for web 9. [SASS/SCSS]((http://sass-lang.com/)) - Styling 10. [GraphQL](https://graphql.org/) 11. [Apollo GraphQL](https://www.apollographql.com/) ## Contributing Please read [contributing guide](./.github/CONTRIBUTING.md) for more information ## Versioning We use [SemVer](https://semver) for versioning. For the versions available, see the [tags](https://github.com/inmdigitalfactory/website-campaign-landing/tags) in this repository. [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com) [![forthebadge](https://forthebadge.com/images/badges/uses-badges.svg)](https://forthebadge.com) [![forthebadge](https://forthebadge.com/images/badges/made-with-crayons.svg)](https://forthebadge.com) [![forthebadge](https://forthebadge.com/images/badges/built-by-developers.svg)](https://forthebadge.com) <file_sep>const express = require('express'); const path = require('path'); const rateLimit = require('express-rate-limit'); const fs = require('fs'); const app = express(); const PORT = process.env.PORT || 8080; const API_URL = process.env.API_URL; const SENTRY_DSN = process.env.SENTRY_DSN; const APOLLO_KEY = process.env.APOLLO_KEY; app.use(express.static(path.join(__dirname, 'build'))); // https://www.npmjs.com/package/express-rate-limit const rateLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, }); /** * Health endpoint to check status of server */ app.get('/health', function (req, res) { return res .json({ status: 'OK', message: 'All Good!', }) .status(200); }); // this allows the dynamic passing of environment variables to the static running application function updateEnv() { try { const env = `window._env_= {API_URL: '${API_URL}', SENTRY_DSN: '${SENTRY_DSN}', APOLLO_KEY: '${APOLLO_KEY}'}`; const envFile = path.join(__dirname, 'build', 'env-config.js'); fs.writeFile(envFile, env, function (err) { if (err) console.error(`Failed to update env ${err}`); }); } catch (error) { console.error(`Failed to update env ${error}`); } } app.get('/*', rateLimiter, function (req, res) { // update env before serving application updateEnv(); res.sendFile(path.join(__dirname, 'build', 'index.html')); }); app.listen(PORT); <file_sep>import { css } from 'emotion'; import { unit } from '../../styles'; // eslint-disable-next-line import/prefer-default-export export const cardClassName = css({ padding: `${unit * 4}px ${unit * 5}px`, borderRadius: 7, color: 'white', backgroundSize: 'cover', backgroundPosition: 'center', }); <file_sep>#!/bin/bash # Recreate config file rm -rf ./env-config.js touch ./env-config.js echo "---Creating env-config.js file for dynamic environment variables---" ENV_FILE=.env # only if there is no .env file, do we use the .env.example file provided as a template if [ -f $ENV_FILE ]; then echo "env file $ENV_FILE exists." else echo "env file $ENV_FILE does not exist. Using provided defaults" cp .env.example $ENV_FILE if [ -z "${APOLLO_KEY}" ]; then echo "Missing Apollo Key Env" else echo APOLLO_KEY="$APOLLO_KEY" >> "$ENV_FILE" fi if [ -z "${API_URL}" ]; then echo "Missing API URL Env" else echo API_URL="$API_URL" >> "$ENV_FILE" fi if [ -z "${SENTRY_DSN}" ]; then echo "Missing Sentry DSN" else echo SENTRY_DSN="$SENTRY_DSN" >> "$ENV_FILE" fi fi # Add assignment echo "window._env_ = {" >> ./env-config.js # Read each line in .env file # Each line represents key=value pairs while read -r line || [[ -n "$line" ]]; do # Split env variables by character `=` if printf '%s\n' "$line" | grep -q -e '='; then varname=$(printf '%s\n' "$line" | sed -e 's/=.*//') varvalue=$(printf '%s\n' "$line" | sed -e 's/^[^=]*=//') fi # Read value of current variable if exists as Environment variable value=$(printf '%s\n' "${!varname}") # Otherwise use value from .env file [[ -z $value ]] && value=${varvalue} # Append configuration property to JS file echo " $varname: \"$value\"," >> ./env-config.js done < $ENV_FILE echo "}" >> ./env-config.js echo "---Done---" # Alternatively the below script can also be used to perform above function ##!/bin/sh ## line endings must be \n, not \r\n ! #echo "---Creating env-config.js file for dynamic environment variables---" #ENV_FILE=.env # ## only if there is no .env file, do we use the .env.example file provided as a template #if [ -f $ENV_FILE ]; then # echo "env file $ENV_FILE exists." #else # echo "env file $ENV_FILE does not exist. Using provided default" # cp .env.example $ENV_FILE #fi #echo "window._env_ = {" > ./env-config.js #awk -F '=' '{ print $1 ": \"" (ENVIRON[$1] ? ENVIRON[$1] : $2) "\"," }' ./$ENV_FILE >> ./env-config.js #echo "}" >> ./env-config.js #echo "---Done---" <file_sep>/* eslint-disable import/extensions */ import styled from '@emotion/styled'; import { unit } from '@styles'; import { cardClassName } from '../Launch.styles'; // eslint-disable-next-line import/prefer-default-export export const Card = styled('div')(cardClassName, { height: 365, marginBottom: unit * 4, }); <file_sep>import debounce from 'lodash/debounce'; /** * Creates a record to be stored in local storage * @param {String} key Key to use for local storage * @param {String} value Value to save * @returns {Object | Void} Either returns an error or nothing if either the key or value is invalid */ // eslint-disable-next-line consistent-return export const createRecord = (key: string, value: string): { error?: string } | void => { if (!key || !value) { return { error: 'Store to local storage failed, Invalid Key or value.', }; } localStorage.setItem(key, value); }; /** * Gets an item from local storage using the key provided * @param {String} key Identifier to get item from local storage * @returns {String | null} Returns the item if available in local storage else null is returned */ export const readRecord = (key: string): string | null => { return localStorage.getItem(key); }; /** * Update a record with the given key and new value * @param {String} key Key to use to update a record * @param {String} value new value to update * @returns {Object | void} Either an error object or void indicating a successful update */ // eslint-disable-next-line consistent-return export const updateRecord = (key: string, value: string): { error?: string } | void => { if (!key || !value) { return { error: 'Failed to update record. Invalid key or value.', }; } localStorage.setItem(key, value); }; /** * Delete a record from the store. This will check if the key is valid and delete the record. if the * key is invalid, an error object with the error details is returned, else nothing is returned indicating * that this is successfull * @param {String} key Key to use to determine the record to delete * @returns {Object | void} Returns an error object if invalid key is provided else returns void */ // eslint-disable-next-line consistent-return export const deleteRecord = (key: string): { error?: string } | void => { if (!key) { return { error: 'Failed to delete record. Invalid key.', }; } localStorage.removeItem(key); }; /** * Clear all items from local storage * @returns {void} nothing */ export const clearAll = (): void => localStorage.clear(); /** * checks if local storage has any items stored * @returns {boolean} True if there are items in local storage, else false */ export const hasStoredItems = (): boolean => localStorage.length > 0; /** * Checks if the current browser supports localStorage * @returns {Boolean} True if the browser supports local storage */ export const isLocalStorageSupported = (): boolean => !!window.localStorage; // Store (create or update) record to local storage with some delay (e.g. 1500 ms) export const storeToLocalStorageDebounced = debounce( (key: string, value: string): void => { if (isLocalStorageSupported()) { if (readRecord(key)) { updateRecord(key, value); } else { createRecord(key, value); } } }, 1500, { leading: false }, ); // Store (create or update) record to local storage export const storeToLocalStorage = (key: string, value: string): void => { if (isLocalStorageSupported()) { if (readRecord(key)) { updateRecord(key, value); } else { createRecord(key, value); } } }; <file_sep>import { gql } from '@apollo/client'; export const LOGIN_USER = gql` mutation Login($email: String!) { login(email: $email) { id token } } `; export const IS_LOGGED_IN = gql` query IsUserLoggedIn { isLoggedIn @client } `; export const LAUNCH_TILE_DATA = gql` fragment LaunchTile on Launch { __typename id isBooked rocket { id name } mission { name missionPatch } } `; export const GET_LAUNCHES = gql` query GetLaunchList($after: String) { launches(after: $after) { cursor hasMore launches { ...LaunchTile } } } ${LAUNCH_TILE_DATA} `; export const GET_LAUNCH_DETAILS = gql` query LaunchDetails($launchId: ID!) { launch(id: $launchId) { site rocket { type } ...LaunchTile } } ${LAUNCH_TILE_DATA} `; export const CANCEL_TRIP = gql` mutation cancel($launchId: ID!) { cancelTrip(launchId: $launchId) { success message launches { id isBooked } } } `; export const BOOK_TRIPS = gql` mutation BookTrips($launchIds: [ID]!) { bookTrips(launchIds: $launchIds) { success message launches { id isBooked } } } `; export const GET_LAUNCH = gql` query GetLaunch($launchId: ID!) { launch(id: $launchId) { ...LaunchTile } } ${LAUNCH_TILE_DATA} `; export const REMOVE_LAUNCH = gql` fragment RemoveLaunch on Launch { id } `; export const GET_CART_ITEMS = gql` query GetCartItems { cartItems @client } `; export const GET_MY_TRIPS = gql` query GetMyTrips { me { id email trips { ...LaunchTile } } } ${LAUNCH_TILE_DATA} `; <file_sep>module.exports = { apps: [ { name: "space-xplorer-client", script: "app.js", watch: true, env: { NODE_ENV: "production" }, instances: "max", exec_mode: "cluster", out_file: "/dev/null", error_file: "/dev/null", output: "/dev/stdout", error: "/dev/stderr", exp_backoff_restart_delay: 100, time: true } ] }; <file_sep>import { ApolloClient, gql } from '@apollo/client'; import cache from '@cache'; import { readRecord } from '@localStorage'; // eslint-disable-next-line no-underscore-dangle const apiUrl = process.env.API_URL || window._env_.API_URL; const typeDefs = gql` extend type Query { isLoggedIn: Boolean! cartItems: [ID!]! } `; export default new ApolloClient({ uri: apiUrl, cache, headers: { authorization: readRecord('token') || '', 'client-name': 'Space Xplorer [web]', // dynamically change this version 'client-version': '1.0.0', }, typeDefs, resolvers: {}, }); <file_sep>FROM node:alpine as builder RUN apk add --update \ bash \ lcms2-dev \ libpng-dev \ gcc \ g++ \ make \ autoconf \ automake \ && rm -rf /var/cache/apk/* COPY . . RUN npm install RUN npm run build FROM node:14.4-alpine3.12 ENV PM2_HOME /usr/src/app/.pm2 WORKDIR /usr/src/app RUN mkdir /usr/src/app/.pm2 RUN chmod -R 777 /usr/src/app RUN chmod -R 777 /usr/src/app/.pm2 COPY --from=builder build build COPY --from=builder server . RUN npm install --quiet --no-optional RUN npm install pm2 -g EXPOSE 8080 CMD ["pm2-runtime", "start", "ecosystem.config.js", "--only", "space-xplorer-client"]<file_sep>module.exports = { client: { name: 'Space Xplorer [web]', service: 'space-xplorer-graph', }, }; <file_sep>import styled from '@emotion/styled'; import { menuItemClassName } from '@components/menu/MenuItem'; // eslint-disable-next-line import/prefer-default-export export const StyledButton = styled('button')(menuItemClassName, { background: 'none', border: 'none', padding: 0, }); <file_sep>/* eslint-disable import/extensions */ import styled from '@emotion/styled'; import { css } from 'emotion'; import { colors, unit } from '@styles'; import space from '@assets/images/space.jpg'; import { ReactComponent as Logo } from '@assets/logo.svg'; import { ReactComponent as Curve } from '@assets/curve.svg'; import { ReactComponent as Rocket } from '@assets/rocket.svg'; import { size } from 'polished'; export const Container = styled('div')({ display: 'flex', flexDirection: 'column', alignItems: 'center', flexGrow: 1, paddingBottom: unit * 6, color: 'white', backgroundColor: colors.primary, backgroundImage: `url(${space})`, backgroundSize: 'cover', backgroundPosition: 'center', }); export const svgClassName = css({ display: 'block', fill: 'currentColor', }); export const Header = styled('header')(svgClassName, { width: '100%', marginBottom: unit * 5, padding: unit * 2.5, position: 'relative', }); export const StyledLogo = styled(Logo)(size(56), { display: 'block', margin: '0 auto', position: 'relative', }); export const StyledCurve = styled(Curve)(size('100%'), { fill: colors.primary, position: 'absolute', top: 0, left: 0, }); export const Heading = styled('h1')({ margin: `${unit * 3}px 0 ${unit * 6}px`, }); export const StyledRocket = styled(Rocket)(svgClassName, { width: 250, }); export const StyledForm = styled('form')({ width: '100%', maxWidth: 406, padding: unit * 3.5, borderRadius: 3, boxShadow: '6px 6px 1px rgba(0, 0, 0, 0.25)', color: colors.text, backgroundColor: 'white', }); export const StyledInput = styled('input')({ width: '100%', marginBottom: unit * 2, padding: `${unit * 1.25}px ${unit * 2.5}px`, border: `1px solid ${colors.grey}`, fontSize: 16, outline: 'none', ':focus': { borderColor: colors.primary, }, }); <file_sep>import styled from '@emotion/styled'; import { colors, unit } from '@styles'; export const Container = styled('footer')({ flexShrink: 0, marginTop: 'auto', backgroundColor: 'white', color: colors.textSecondary, position: 'sticky', bottom: 0, }); export const InnerContainer = styled('div')({ display: 'flex', alignItems: 'center', maxWidth: 460, padding: unit * 2.5, margin: '0 auto', }); <file_sep>import { createRecord, readRecord, updateRecord, deleteRecord, clearAll, hasStoredItems, isLocalStorageSupported, } from './local'; describe('LocalStorage', () => { beforeEach(() => { clearAll(); }); it('should throw an error with invalid key and value when creating a record', () => { const invalidKey = ''; const validValue = 'value'; const actualError = createRecord(invalidKey, validValue); const expectedError = { error: 'Store to local storage failed, Invalid Key or value.', }; expect(actualError).toEqual(expectedError); }); it('should return null for a non existent key', () => { const nonExistentKey = 'nonExistent'; const actualResult = readRecord(nonExistentKey); expect(actualResult).toBeNull(); }); it('can create a record in localStorage and read from it', () => { const user = { name: 'John', age: 20, }; createRecord('username', user.name); // can read from localStorage with readRecord const actualUsername = readRecord('username'); expect(actualUsername).toEqual(user.name); }); it('should throw an error with an invalid key provided when updating a record', () => { const invalidKey = ''; const validValue = 'value'; const actualError = updateRecord(invalidKey, validValue); const expectedError = { error: 'Failed to update record. Invalid key or value.', }; expect(actualError).toEqual(expectedError); }); it('should update a record if the key is valid', () => { const user = { name: 'John', age: 20, }; // create a record createRecord('username', user.name); const newName = 'Jane'; // update record updateRecord('username', newName); const actualUsername = readRecord('username'); expect(actualUsername).toEqual(newName); }); it('should return an error if key is invalid', () => { const invalidKey = ''; const actualError = deleteRecord(invalidKey); const expectedError = { error: 'Failed to delete record. Invalid key.', }; expect(actualError).toEqual(expectedError); }); it('should delete a record if key is valid', () => { // create record const usernameKey = 'john'; const usernameValue = 'John'; createRecord(usernameKey, usernameValue); // delete the record deleteRecord(usernameKey); // read record const actualRecord = readRecord(usernameKey); expect(actualRecord).toBeNull(); }); it('should clear all items from storage', () => { // create records const johnKey = 'john'; const johnValue = 'John'; const janeKey = 'jane'; const janeValue = 'Jane'; createRecord(johnKey, johnValue); createRecord(janeKey, janeValue); // delete all records clearAll(); // read records const actualRecordJohn = readRecord(johnKey); const actualRecordJane = readRecord(janeKey); expect(actualRecordJohn).toBeNull(); expect(actualRecordJane).toBeNull(); }); it('should return true if local storage is supported', () => { expect(isLocalStorageSupported()).toEqual(true); }); }); <file_sep>/* eslint-disable @typescript-eslint/no-use-before-define */ import { InMemoryCache, Reference } from '@apollo/client'; import { readRecord } from '@localStorage'; const cache: InMemoryCache = new InMemoryCache({ typePolicies: { Query: { fields: { isLoggedIn(): boolean { return isLoggedInVar(); }, cartItems(): string[] { return cartItemsVar(); }, launches: { keyArgs: false, // eslint-disable-next-line @typescript-eslint/explicit-function-return-type merge(existing, incoming) { let launches: Reference[] = []; if (existing && existing.launches) { launches = launches.concat(existing.launches); } if (incoming && incoming.launches) { launches = launches.concat(incoming.launches); } return { ...incoming, launches, }; }, }, }, }, }, }); export const isLoggedInVar = cache.makeVar<boolean>(!!readRecord('token')); export const cartItemsVar = cache.makeVar<string[]>([]); export default cache; <file_sep>module.exports = { testEnvironment: 'jest-environment-jsdom-fourteen', displayName: { name: 'SpaceXplorerClient', color: 'yellow', }, roots: ['<rootDir>/src'], moduleFileExtensions: [ 'web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node', ], testMatch: [ '<rootDir>/__tests__/**/*.{js,ts,tsx,jsx,mjs}', '<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}', '<rootDir>/?(*.)(spec|test).{js,jsx,ts,tsx,mjs}', '<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}', '<rootDir>/src/**/__tests__/**/*.{js,ts,tsx,jsx,mjs}', '<rootDir>/src/**/?(*.)(spec|test).{js,ts,tsx,jsx,mjs}', ], setupFiles: ['react-app-polyfill/jsdom'], setupFilesAfterEnv: ['<rootDir>/scripts/setupTests.ts'], collectCoverageFrom: ['<rootDir>/src/**/*.ts', '!**/node_modules/**'], coveragePathIgnorePatterns: [ '/node_modules/', '<rootDir>/src/api/gql/GqlClient.ts', '<rootDir>/src/api/gql/schemas.ts', '<rootDir>/src/serviceWorker.ts', '<rootDir>/src/react-app-env.d.ts', '<rootDir>/src/window.d.ts', '<rootDir>/src/storage/cache/cache.ts', '<rootDir>/src/logger/index.ts', '<rootDir>/src/test-utils.tsx', ], coverageThreshold: { global: { lines: 85, statements: 85, }, }, transform: { '^.+\\.ts$': 'ts-jest', '^.+\\.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/babel-jest', '^.+\\.css$': '<rootDir>/config/jest/cssTransform.js', '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '<rootDir>/config/jest/fileTransform.js', }, transformIgnorePatterns: [ '[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$', '^.+\\.module\\.(css|sass|scss)$', ], moduleNameMapper: { '^react-native$': 'react-native-web', '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy', '^@storage/(.*)$': '<rootDir>/src/storage/$1', '^@cache': '<rootDir>/src/storage/cache/cache.ts', '^@localStorage': '<rootDir>/src/storage/local/local.ts', '^@gqlClient': '<rootDir>/src/api/gql/GqlClient.ts', '^@gqlOps/(.*)$': '<rootDir>/src/api/gql/__generated__/$1', '^@restClient': '<rootDir>/src//api/rest/RestClient.ts', '^@schemas': '<rootDir>/src/api/gql/schemas.ts', '^@components/(.*)$': '<rootDir>/src/components/$1', '^@containers/(.*)$': '<rootDir>/src/containers/$1', '^@assets/(.*)$': '<rootDir>/src/assets/$1', '^@styles': '<rootDir>/src/styles.ts', '^@logger': '<rootDir>/src/logger/index.ts', '^@utils/(.*)$': '<rootDir>/src/utils/$1', }, watchPlugins: ['jest-watch-typeahead/filename', 'jest-watch-typeahead/testname'], }; <file_sep>/* eslint-disable import/extensions */ import galaxy from '@assets/images/galaxy.jpg'; import iss from '@assets/images/iss.jpg'; import moon from '@assets/images/moon.jpg'; const backgrounds = [galaxy, iss, moon]; // eslint-disable-next-line import/prefer-default-export export function getBackgroundImage(idOrUrl: string | number): string { return typeof idOrUrl === 'number' ? `url(${backgrounds[Number(idOrUrl) % backgrounds.length]})` : `url(${idOrUrl})`; } <file_sep>version: "3.7" services: db: image: postgres:9.6 hostname: postgresql container_name: space-xplorer-db environment: POSTGRES_PASSWORD: <PASSWORD> POSTGRES_USER: space-xplorer POSTGRES_DB: space-xplorer ports: - 5432:5432 volumes: - db:/var/lib/postgresql/data cache: image: redis hostname: redis container_name: space-xplorer-cache ports: - 6379:6379 volumes: - cache:/data migrations: image: wyvarn/space-xplorer-migrations:latest container_name: space-xplorer-migrations depends_on: - db environment: DATABASE_URL: postgresql://space-xplorer:space-xplorer@db:5432/space-xplorer?schema=public api: image: wyvarn/space-xplorer-api:latest hostname: spacexplorer-api container_name: space-xplorer-api ports: - 4000:4000 depends_on: - migrations - db - cache environment: CACHE_HOST: cache CACHE_PORT: 6379 CACHE_USER: user CACHE_PASSWORD: <PASSWORD> CACHE_URI: redis://cache:6379 PORT: 4000 DATABASE_URL: postgresql://space-xplorer:space-xplorer@db:5432/space-xplorer?schema=public portainer: image: portainer/portainer container_name: space-xplorer-portainer command: -H unix:///var/run/docker.sock restart: always ports: - 9000:9000 volumes: - /var/run/docker.sock:/var/run/docker.sock - portainer_data:/data volumes: db: cache: portainer_data:<file_sep>/* eslint-disable @typescript-eslint/ban-ts-ignore */ import { injectGlobal } from 'emotion'; export const unit = 8; export const colors = { primary: '#220a82', secondary: '#14cbc4', accent: '#e535ab', background: '#f7f8fa', grey: '#d8d9e0', text: '#343c5a', textSecondary: '#747790', }; // @ts-ignore // eslint-disable-next-line @typescript-eslint/explicit-function-return-type export default () => injectGlobal({ // @ts-ignore [['html', 'body']]: { height: '100%', }, body: { margin: 0, padding: 0, fontFamily: "'Source Sans Pro', sans-serif", backgroundColor: colors.background, color: colors.text, }, '#root': { display: 'flex', flexDirection: 'column', minHeight: '100%', }, '*': { boxSizing: 'border-box', }, // @ts-ignore [['h1', 'h2', 'h3', 'h4', 'h5', 'h6']]: { margin: 0, fontWeight: 600, }, h1: { fontSize: 48, lineHeight: 1, }, h2: { fontSize: 40, }, h3: { fontSize: 36, }, h5: { fontSize: 16, textTransform: 'uppercase', letterSpacing: 4, }, });
bc241a839a86f29a5c1eaf0daec13b5057f1ced7
[ "YAML", "Markdown", "JavaScript", "JSON with Comments", "TypeScript", "Dockerfile", "Shell" ]
26
JSON with Comments
Wyvarn/space-xplorer-client
f31dae70d7361a34b64e56562b6d9be7a6093c55
aa34f3c4e5c15a2924e00171596474e04fcbf0e9
refs/heads/master
<file_sep>def rscript(file) sh "cd analysis && Rscript #{file}" end namespace :data do desc 'Fetch data from the userbase-stats MySQL database' task :fetch do sh "bin/fetch userbase-stats data" end desc 'Collect the profile lengths of the processed samples' task :length do sh "bin/body-length data/processed > data/results/body-length.csv" end desc 'Segment data into training and testing sets. Define min var beforehand' task :segment do abort("run as min=XXX rake data:segment") unless ENV['min'] sh "bin/segment data/processed data/pruned #{ENV['min']} 100" %w(training testing).each do |type| %w(ham spam).each do |k| puts "#{type}: #{k}: " + `ls data/pruned/#{type}/#{k} | wc -l`.strip end end end desc 'Marshal data into Ruby objects on the filesystem' task :marshal do mkdir_p "data/objects" sh "bin/marshal data/pruned data/objects" end end namespace :analyze do desc 'Analyze data/results/body-length.csv' task :length do rscript 'body-length.R' end desc 'Analyze data/results/models-*.csv' task :models do rscript 'best-model.R' end end namespace :classifier do desc 'Cross-validate various models' task :cross do sh "bin/cross-val-models data/objects/training.obj > data/results/models-cv.csv" end desc 'Test every model' task :test do sh "bin/test data/objects/training.obj data/objects/testing.obj > data/results/models-test.csv" end end <file_sep># A simple container around sample data for easier debugging. Sample = Struct.new(:value, :kind, :filename) <file_sep>Classifying spam profiles on a social network ============================================= Prerequisites ------------- - Ruby 1.9.2+ - UNIX-like system - MySQL (if you need to fetch data) Preliminary Steps ----------------- 1. Fetch the data from the database (don't do this if you already have a `src/data` folder) rake data:fetch 2. Fetch the body word lengths rake data:length 3. Determine the minimum word length rake analyze:length 4. With the minimum length, segment the data into training and testing sets min=XXX rake data:segment 5. Finally, serialize the data so it's faster to work with rake data:marshal <file_sep>#! /usr/bin/env ruby # # Creates a set of training and testing samples that meet a word minimum. # # Assumes the HUGE_CORPUS_BASE_DIR and OUTPUT_BASE_DIR share a parent (e.g., # "data"). # require 'fileutils' require 'pathname' require 'parallel' require_relative '../lib/cli' require_relative '../lib/extensions' def common_parent(dir1, dir2) File.dirname(dir1).split('/') & File.dirname(dir2).split('/') end # Removes the first component of a path def strip_parent(dir) dir.split('/').drop(1).join('/') end if ARGV.size != 4 usage __FILE__, "HUGE_CORPUS_BASE_DIR OUTPUT_BASE_DIR MIN_WORDS TEST_LIMIT" end source, dest = ARGV.shift(2) min_words, tlimit = ARGV.shift(2).map { |x| Integer(x) } FileUtils.rm_rf dest %w(ham spam).each do |klass| srcd = File.join(source, klass) traind = Pathname(File.join(dest, "training/#{klass}")) testd = Pathname(File.join(dest, "testing/#{klass}")) FileUtils.mkdir_p traind FileUtils.mkdir_p testd i = 0 keep = [] Dir[File.join(srcd, '*.html')].to_a.shuffle.each do |f| fn = File.basename(f) body = File.read(f).strip next if body.to_words.size < min_words # prune if i < tlimit && rand() >= 0.5 keep << -> { FileUtils.cp f, testd.join(fn) } i += 1 else keep << -> { FileUtils.cp f, traind.join(fn) } end end Parallel.map(keep, :in_processes => 6) do |f| f.call() end end <file_sep>#! /usr/bin/env ruby # # Reports confusion matrices for word-gram, character-gram, and phonetic-gram # models. # require_relative '../lib/cli' require_relative '../lib/classifier' require_relative '../lib/cross_validate' require_relative '../lib/tokenizers' usage(__FILE__, "TRAINING_OBJ") if ARGV.size < 1 k = 10 training = Classifier.load(ARGV.shift) which = ARGV.shift which = which ? which.to_sym : nil headers() tokenizers(which).each do |tokr| smoothers().each do |lp| STDERR.puts "tokr = #{tokr}, lp = #{lp}" c = Classifier.fetch(lp, tokr) cv = CrossValidate.run(training, c, k) print_row(tokr, lp, cv) end end <file_sep>#! /usr/bin/env ruby # # Load a Pry session with the various serialized objects for debugging. # require 'pry' require_relative '../lib/cli' require_relative '../lib/classifier' usage(__FILE__, "OBJ_DIR") if ARGV.size != 1 objd = ARGV.shift def sel(ary) { :spam => ary.select { |x| x.kind == :spam }, :ham => ary.select { |x| x.kind == :ham }, } end training = sel(Classifier.load(File.join(objd, 'training.obj'))) testing = sel(Classifier.load(File.join(objd, 'testing.obj'))) pry.binding <file_sep>def usage(file, args) abort "Usage: #{File.basename(file)} #{args}" end # Load training data into an array def load_dir(dir, klass) files = Dir[File.join(dir, '*.html')] out = [] Parallel.map(files, :in_threads => 200) do |f| body = File.read(f) out << Sample.new(body, klass, f) end out end <file_sep>#! /usr/bin/env ruby # # Classify a given text file based on a training set. # require_relative '../lib/classifier' abort "Usage: #{File.basename(__FILE__)} CLASSIFIER_OBJ TEST_OBJ" if ARGV.size < 2 classifier = Classifier.load(ARGV.shift) testing = Classifier.load(ARGV.shift) testing.each do |sample| pred = classifier.classify(sample.value) if pred == sample.kind puts "TRUE (#{pred} == #{sample.kind})" else puts "FALSE (#{pred} != #{sample.kind})" end end <file_sep>#! /usr/bin/env ruby # # Serialize HTML files as Sample objects. # require 'fileutils' require 'pathname' require 'parallel' require_relative '../lib/sample' require_relative '../lib/cli' if $0 == __FILE__ usage(__FILE__, "HTML_DIR OBJ_DIR") unless ARGV.size == 2 html_dir = Pathname(File.expand_path(ARGV.shift)) obj_dir = File.expand_path(ARGV.shift) FileUtils.mkdir_p obj_dir obj_dir = Pathname(obj_dir) %w(testing training).each do |type| samples = [] [:ham, :spam].each do |klass| dir = html_dir.join(type, klass.to_s) samples += load_dir(dir, klass) end fork do File.open(obj_dir + "#{type}.obj", 'w') { |f| f.puts Marshal.dump(samples) } end end end <file_sep>## Determine the best ratio of spam to ham ## ## Assumes the ratio CSV is located at ../data/results/ratio.csv ## ## Usage: Rscript best_ratio.R ## D <- read.csv('../data/results/ratio-3k001-5x.csv', header=TRUE) ## best accuracy ## bestAcc <- which(D == max(D$accuracy), arr.ind=TRUE) ## fullRow <- D[bestAcc[1],] ## thoseSteps <- D[D$step == fullRow$step,] uniqs <- unique(D$step) n <- length(uniqs) cleaned <- data.frame(step=rep(NA,n), meanAcc=rep(NA,n), sdAcc=rep(NA,n), meanPrec=rep(NA,n), sdPrec=rep(NA,n), meanRecall=rep(NA,n), sdRecall=rep(NA,n), meanTp=rep(NA, n), sdTp=rep(NA, n), meanTn=rep(NA, n), sdTn=rep(NA, n), meanFp=rep(NA, n), sdFp=rep(NA, n), meanFn=rep(NA, n), sdFn=rep(NA, n) ) meanAndSd <- function(rows, var) { col <- rows[,var] return(c(mean(col), sd(col))) } attrs <- c("accuracy", "precision", "recall", "tp", "tn", "fp", "fn") for(i in 1:n) { step <- uniqs[i] rows <- D[which(D$step == step),] tmp <- c(step) for(j in 1:length(attrs)) { tmp <- c(tmp, meanAndSd(rows, attrs[j])) } cleaned[i,] <- tmp } decent <- cleaned[cleaned$meanTp > 0 & cleaned$meanTn > 0 & cleaned$meanAcc > 0.85 & cleaned$meanRecal > 0.8 & cleaned$meanPrec > 0.89,] head(decent[order(decent$meanAcc),], 10) write.table(decent, file="ratio-means.csv", sep=",", row.names=FALSE) <file_sep># List of all available tokenizers def tokenizers(which=nil) kinds = { :words => [:unigram, :bigram, :trigram], :chars => (1..5).to_a, :phono => [:metaphone, :bimetaphone], } if which kinds[which] else kinds.values.flatten end end def smoothers (0..1) end def headers puts %w(tokenizer lp acc err prec recall tp tn fp fn total).join(',') end def print_row(tokr, lp, mat) a = [tokr, lp] + mat.to_list puts a.join(',') end <file_sep>require 'parallel' require_relative 'sample' require_relative 'confusion' # Cross-validates a classifier # module CrossValidate class << self # Performs k-fold cross-validation and returns a confusion matrix. # # The algorithm is as follows (Mitchell, 1997, p147): # # partitions = partition data into k-equal sized subsets (folds) # for i = 1 -> k: # T = data \ partitions[i] # train(T) # classify(partitions[i]) # output confusion matrix # # k = number of folds as a percentage (e.g., 10 == 10% of data is used for testing) def run(data, classifier_proc, k=10) confusion = Confusion.new k = data.size / k # as a percentage partitions = data.each_slice(k).to_a results = Parallel.map_with_index(partitions, :in_processes => 6) do |part, i| # Array#rotate puts the element i first, so all we have to do is rotate # then remove that element to get the training set. Array#drop does not # mutate the original array either. Array#flatten is needed to coalesce # our list of lists into one list again. training = partitions.rotate(i).drop(1).flatten # setup a new classifier classifier = classifier_proc.call() # train it training.each { |s| classifier.train s.kind, s.value } # fetch confusion keys o = [] part.each do |x| prediction = classifier.classify x.value o << confusion.key_for(prediction, x.kind) end o end # count our keys results.each { |set| set.each { |key| confusion[key] += 1 } } confusion.compute end # Returns the confusion matrix key for a predicted value and the actual. def key_for(predicted, actual) if actual == :spam predicted == :spam ? :true_pos : :false_neg elsif actual == :ham predicted == :ham ? :true_neg : :false_pos end end end end <file_sep>source :rubygems # Database gem 'mysql' gem 'sequel' # Utilities gem 'parallel' gem 'sanitize' # Classification gem 'fast-stemmer' gem 'text' <file_sep>$LOAD_PATH.unshift File.join(File.dirname(__FILE__), 'vendor/ankusa/lib') require 'ankusa' require 'ankusa/memory_storage' require_relative 'sample' module Classifier class << self # Returns a new Proc that will initialize a classifier. def fetch(laplace=0, atomizer=:unigram) Proc.new { Ankusa::la_place = laplace Ankusa::atomizer = atomizer Ankusa::NaiveBayesClassifier.new(Ankusa::MemoryStorage.new) } end # Train the classifier on a set of samples. def train_up(classifier, samples) samples.each do |s| classifier.train s.kind, s.value end end # Save the classifier to disk, so we don't have to train again. def save(classifier, destination) File.open(destination, 'w') { |f| f.puts Marshal.dump(classifier) } end # Load a classifier or other object from disk. def load(filename) Marshal.load(File.read(filename)) end end end <file_sep>## Analyze the various classifier models based on cross-validation results ## ## Assumes the ratio CSV is located at ../data/results/all-models.csv ## ## Usage: Rscript best-model.R ## CV <- read.csv('../data/results/models-cv.csv', header=TRUE) T <- read.csv('../data/results/models-test.csv', header=TRUE) wordGrams <- function(df) { return(subset(df, (tokenizer %in% c("unigram", "bigram", "trigram")))) } charGrams <- function(df) { return(subset(df, (tokenizer %in% seq(1, 6)))) } phonoGrams <- function(df) { return(subset(df, (tokenizer %in% c("metaphone", "bimetaphone")))) } ## kind == cv or test writeGrams <- function(kind, name, grams) { write.table(grams, file=paste("../data/results/model.", kind, ".", name, ".csv", sep=""), sep=",", row.names=FALSE) } writeOut <- function(df, kind) { writeGrams(kind, "word", wordGrams(df)) writeGrams(kind, "char", charGrams(df)) writeGrams(kind, "phono", phonoGrams(df)) } writeOut(CV, "cv") writeOut(T, "test") <file_sep>#! /usr/bin/env ruby # # Reports confusion matrices for word-gram, character-gram, and phonetic-gram # models on the TESTING set. # require 'parallel' require_relative '../lib/cli' require_relative '../lib/classifier' require_relative '../lib/confusion' require_relative '../lib/tokenizers' usage(__FILE__, "TRAINING_OBJ TESTING_OBJ") if ARGV.size != 2 training = Classifier.load(ARGV.shift) testing = Classifier.load(ARGV.shift) headers() Parallel.map(tokenizers(), :in_processes => 6) do |tokr| smoothers().each do |lp| STDERR.puts "tokr = #{tokr}, lp = #{lp}" c = Classifier.fetch(lp, tokr).call() Classifier.train_up(c, training) mat = Confusion.new testing.each do |s| predicted = c.classify(s.value) mat.save_prediction(predicted, s.kind) end mat.compute print_row(tokr, lp, mat) end end <file_sep>require_relative 'sample' # Represents a confusion matrix # class Confusion < Hash def initialize [:true_pos, :true_neg, :false_pos, :false_neg].each do |k| store(k, 0) end end # Returns the confusion matrix key for a predicted value and the actual. def key_for(predicted, actual) if actual == :spam predicted == :spam ? :true_pos : :false_neg elsif actual == :ham predicted == :ham ? :true_neg : :false_pos end end def save_prediction(predicted, actual) self[key_for(predicted, actual)] += 1 end def compute store :total, values().reduce(:+) store :accuracy, (fetch(:true_pos) + fetch(:true_neg)) / Float(fetch(:total)) store :error, ((1.0 - fetch(:accuracy)) * 100).round(2) store :precision, fetch(:true_pos) / Float(fetch(:true_pos) + fetch(:false_pos)) store :recall, fetch(:true_pos) / Float(fetch(:true_pos) + fetch(:false_neg)) self end def to_list [:accuracy, :error, :precision, :recall, :true_pos, :true_neg, :false_pos, :false_neg, :total ].map { |f| fetch(f) } end end <file_sep>task :paper do sh "latexmk -pdf paper" end task :clean do sh "latexmk -c -pdf paper" end <file_sep># -*- coding: utf-8 -*- # # Various methods for cleaning HTML # require 'sanitize' module Cleaner class << self # Remove whitespace def strip(s) s.gsub(/[\n\r\t\u00A0+]|\s\s+/, ' ').strip #u00A0 = non-breaking space end # Remove HTML from a string, along with URLs and extra space def clean_html(s) strip(strip_url(Sanitize.clean(s))) end # Remove URLs from text # # Regexp from http://daringfireball.net/2010/07/improved_regex_for_matching_urls def strip_url(s) pat = %r{(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))} s.gsub(pat, '') end end end if $0 == __FILE__ require 'minitest/autorun' class TestCleaner < MiniTest::Unit::TestCase def test_clean_html html = '<a href="http://example.com">foo</a> bar <b>baz</b>' assert_equal "foo bar baz", Cleaner.clean_html(html) end def test_strip_url assert_equal '', Cleaner.strip_url('http://example.com') end end end <file_sep>## Report some statistics about the body length ## ## Usage: Rscript body_length.R D <- read.csv('../data/results/body-length.csv', header=TRUE) spam <- D[D$kind == "spam",] ham <- D[D$kind == "ham",] pluck <- function(tbl, value) { return(tbl[tbl$kind == value,]); } report <- function(rows ) { m <- mean(rows$words) print(summary(rows)) print(paste("mean", m)) print(paste("stddev", sd(rows$words))) return(m) } countBy <- function(rows, minv) { return(table(rows$words >= mall)[2]) } print("spam") spam <- pluck(D, "spam") print("ham") ham <- pluck(D, "ham") m1 <- report(spam) m2 <- report(ham) mall <- round(min(m1, m2)) print(paste("Min length =", mall, "words")) spamc <- countBy(spam, "spam") hamc <- countBy(ham, "ham") tot <- spamc + hamc print(paste("spam entries of that size =", spamc, ";", round(spamc/tot*100, 2), "%")) print(paste(" ham entries of that size =", hamc, ";", round(hamc/tot*100, 2), "%")) print(paste("total =", tot)) <file_sep>require_relative 'vendor/ankusa/lib/ankusa/stopwords' class String def to_words scan(/[a-z']+/i) end end class Array def remove_stops reject { |w| Ankusa::STOPWORDS.include?(w) } end end <file_sep>#! /usr/bin/env ruby # # Save MySQL records as plain text files for easier portability # require 'sequel' require 'fileutils' require 'pathname' require 'parallel' require_relative '../lib/cleaner' require_relative '../lib/extensions' # Returns an SQL query to fetch all users by a status (0 = active, 6 = spam) # before a certain date. def user_sql(status, date="2012-11-28") <<EOF SELECT users.masterid, users.special_text FROM users WHERE users.status = #{status} AND users.timestamp <= "#{date}" ORDER BY RAND() EOF end # Deletes and creates a directory def create_dir(name) FileUtils.rm_rf name FileUtils.mkdir_p name name end def create_dirs(list) list.each { |d| create_dir(d) } end def process(dbh, base_dir, test_limit, min_chars) {:ham => 0, :spam => 6}.each do |klass, status| train_dir = create_dir("#{base_dir}/processed/#{klass}") Parallel.map(dbh[user_sql(status)], :in_threads => 200) do |row| filename = row[:masterid] + '.html' body = Cleaner.clean_html(row[:special_text].force_encoding('utf-8')) next if body.to_words.size == 0 dir = train_dir File.open(File.join(dir, filename), 'w') { |f| f.puts body } end end end if $0 == __FILE__ abort "Usage: #{File.basename(__FILE__)} DATABASE DATA_DIR" if ARGV.size != 2 name = ARGV.shift data_dir = Pathname(File.expand_path(ARGV.shift)) process(Sequel.connect("mysql://root@localhost/#{name}"), data_dir, 100, 0) end <file_sep>#! /usr/bin/env ruby # # Determine the body length for all of the documents # require 'fileutils' require 'pathname' require 'parallel' require_relative '../lib/sample' require_relative '../lib/cli' require_relative '../lib/extensions' if $0 == __FILE__ abort "Usage: #{File.basename(__FILE__)} HTML_DIR" unless ARGV.size == 1 html_dir = Pathname(File.expand_path(ARGV.shift)) puts "kind,words" samples = [] [:ham, :spam].each do |klass| dir = html_dir.join(klass.to_s) samples += load_dir(dir, klass) end samples.each do |s| len = s.value.to_words.size puts "#{s.kind},#{len}" end end <file_sep>#! /usr/bin/env ruby # # Determine the best ratio of spam:ham messages. # require 'parallel' require_relative '../lib/cli' require_relative '../lib/classifier' require_relative '../lib/cross_validate' # Find the best ratio of spam to ham for a number of N samples. def find_best_ratio(samples, n, step_sz) spam = samples.select { |s| s.kind == :spam }.shuffle ham = samples.select { |s| s.kind == :ham }.shuffle # bests = { # :accuracy => {:step => 0, :value => 0.0, :ratio => nil, :mat => nil}, # :precision => {:step => 0, :value => 0.0, :ratio => nil, :mat => nil}, # :recall => {:step => 0, :value => 0.0, :ratio => nil, :mat => nil}, # } steps = {} (step_sz).step(0.99, step_sz).each do |i| ratio = {:spam => (n * i).round, :ham => (n * (1 - i)).round} limited_samples = spam.take(ratio[:spam]) + ham.take(ratio[:ham]) STDERR.puts "Step %0.2f, #{ratio.inspect}, n=#{ratio.values.reduce(:+)}" % i mat = CrossValidate.run(limited_samples, Classifier.fetch(0, :unigram)) steps[i] = {:ratio => ratio, :mat => mat} # if mat[:accuracy] > bests[:accuracy][:value] # bests[:accuracy] = {:step => i, :value => mat[:accuracy], :ratio => ratio, :mat => mat} # end # if mat[:precision] > bests[:precision][:value] # bests[:precision] = {:step => i, :value => mat[:precision], :ratio => ratio, :mat => mat} # end # if mat[:recall] > bests[:recall][:value] # bests[:recall] = {:step => i, :value => mat[:recall], :ratio => ratio, :mat => mat} # end end steps # bests end def print_row(step_i, tbl) fields = [ "%0.2f" % step_i, tbl[:ratio][:spam], tbl[:ratio][:ham], tbl[:mat][:total], tbl[:mat][:accuracy], tbl[:mat][:precision], tbl[:mat][:recall], tbl[:mat][:true_pos], tbl[:mat][:true_neg], tbl[:mat][:false_pos], tbl[:mat][:false_neg], ] puts fields.join(",") end if $0 == __FILE__ usage(__FILE__, "TRAINING_OBJ LIMIT STEP_SIZE TIMES") if ARGV.size != 4 samples = Classifier.load(ARGV.shift).shuffle() limit = Integer(ARGV.shift) step_sz = Float(ARGV.shift) count = Integer(ARGV.shift) puts %w(step spam ham total accuracy precision recall tp tn fp fn).join(",") count.times do |i| STDERR.puts "i = #{i}" find_best_ratio(samples, limit, step_sz).each do |step_i, tbl| print_row(step_i, tbl) end end end <file_sep>#! /usr/bin/env ruby # require_relative '../lib/classifier' if ARGV.size != 4 abort "Usage: #{File.basename(__FILE__)} TRAINING CLASSIFIER LAPLACE ATOMIZER" end training_fn, classifier_fn, laplace, atomizer = ARGV laplace = Integer(laplace) atomizer = atomizer.to_sym c = Classifier.fetch(laplace, atomizer).call() samples = Classifier.load(training_fn) Classifier.train_up(c, samples) Classifier.save(c, classifier_fn)
b301b72051418c7f048800062e8d6c4f828e5866
[ "Markdown", "Ruby", "R" ]
25
Ruby
DmitryKey/nlp-spam
62549f095bbdcb5f857ad03c5bea5f8976409109
8b9458b546d8fb34c05bf5d1950be9b625e05654
refs/heads/master
<repo_name>anttisalonen/sscene<file_sep>/sscene/Model.cpp #include "Model.h" #include <stdexcept> #include <iostream> #include "HelperFunctions.h" using namespace Common; using namespace Scene; namespace Scene { Model::Model(const std::string& filename) { mScene = mImporter.ReadFile(filename, aiProcess_CalcTangentSpace | aiProcess_Triangulate | aiProcess_JoinIdenticalVertices | aiProcess_SortByPType); if(!mScene) { std::cerr << "Unable to load model from " << filename << "\n"; throw std::runtime_error("Error while loading model"); } if(mScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !mScene->mNumMeshes) { std::cerr << "Model file " << filename << " is incomplete\n"; throw std::runtime_error("Error while loading model"); } aiMesh* mesh = mScene->mMeshes[0]; if(!mesh->HasTextureCoords(0) || mesh->GetNumUVChannels() != 1) { std::cerr << "Model file " << filename << " has unsupported texture coordinates.\n"; throw std::runtime_error("Error while loading model"); } std::cout << mesh->mNumVertices << " vertices.\n"; std::cout << mesh->mNumFaces << " faces.\n"; for(unsigned int i = 0; i < mesh->mNumVertices; i++) { const aiVector3D& vertex = mesh->mVertices[i]; mVertexCoords.push_back(vertex.x); mVertexCoords.push_back(vertex.y); mVertexCoords.push_back(vertex.z); const aiVector3D& texcoord = mesh->mTextureCoords[0][i]; mTexCoords.push_back(texcoord.x); mTexCoords.push_back(texcoord.y); if(mesh->HasNormals()) { const aiVector3D& normal = mesh->mNormals[i]; mNormals.push_back(normal.x); mNormals.push_back(normal.y); mNormals.push_back(normal.z); } } for(unsigned int i = 0; i < mesh->mNumFaces; i++) { const aiFace& face = mesh->mFaces[i]; if(face.mNumIndices != 3) { std::cerr << "Warning: number of indices should be three.\n"; throw std::runtime_error("Error while loading model"); } else { for(unsigned int j = 0; j < face.mNumIndices; j++) { mIndices.push_back(face.mIndices[j]); } } } } Model::Model() { } Model::Model(const Heightmap& heightmap, float uscale, float vscale) { unsigned int w = heightmap.getWidth() + 1; float xzscale = heightmap.getXZScale(); for(int j = 0; j < w; j++) { for(int i = 0; i < w; i++) { float xp = xzscale * i; float yp = xzscale * j; addVertex(Vector3(xp, heightmap.getHeightAt(xp, yp), yp)); addTexCoord(uscale * i / (float)w, vscale * j / (float)w); Vector3 p1(xp, heightmap.getHeightAt(xp, yp), yp); Vector3 p2(xp + xzscale, heightmap.getHeightAt(xp + xzscale, yp), yp); Vector3 p3(xp, heightmap.getHeightAt(xp, yp + xzscale), yp + xzscale); Vector3 u(p2 - p1); Vector3 v(p3 - p1); addNormal(v.cross(u).normalized()); } } for(int j = 0; j < w - 1; j++) { for(int i = 0; i < w - 1; i++) { addQuadIndices(j * w + i, j * w + i + 1, (j + 1) * w + i + 1, (j + 1) * w + i); } } } Model::Model(const std::vector<Common::Vector3>& vertexcoords, const std::vector<Common::Vector2>& texcoords, const std::vector<unsigned int>& indices, const std::vector<Common::Vector3>& normals) { for(auto v : vertexcoords) addVertex(v); for(auto v : texcoords) addTexCoord(v.x, v.y); for(auto v : indices) addIndex(v); for(auto v : normals) addNormal(v); } void Model::addVertex(const Common::Vector3& v) { mVertexCoords.push_back(v.x); mVertexCoords.push_back(v.y); mVertexCoords.push_back(v.z); } void Model::addNormal(const Common::Vector3& v) { mNormals.push_back(v.x); mNormals.push_back(v.y); mNormals.push_back(v.z); } void Model::addTexCoord(float u, float v) { mTexCoords.push_back(u); mTexCoords.push_back(v); } void Model::addIndex(unsigned short i) { mIndices.push_back(i); } void Model::addTriangleIndices(unsigned short i1, unsigned short i2, unsigned short i3) { mIndices.push_back(i3); mIndices.push_back(i2); mIndices.push_back(i1); } void Model::addQuadIndices(unsigned short i1, unsigned short i2, unsigned short i3, unsigned short i4) { addTriangleIndices(i1, i2, i3); addTriangleIndices(i1, i3, i4); } const std::vector<GLfloat>& Model::getVertexCoords() const { return mVertexCoords; } const std::vector<GLfloat>& Model::getTexCoords() const { return mTexCoords; } const std::vector<GLushort>& Model::getIndices() const { return mIndices; } const std::vector<GLfloat>& Model::getNormals() const { return mNormals; } Movable::Movable() : mScale(1.0f, 1.0f, 1.0f) { } Movable::Movable(const Common::Vector3& pos) : mPosition(pos), mScale(1.0f, 1.0f, 1.0f) { } void Movable::setPosition(const Common::Vector3& p) { mPosition = p; } const Common::Vector3& Movable::getPosition() const { return mPosition; } void Movable::move(const Common::Vector3& v) { mPosition += v; } const Matrix44& Movable::getRotation() const { return mRotation; } void Movable::setRotationFromEuler(const Vector3& v) { mRotation = HelperFunctions::rotationMatrixFromEuler(v); } void Movable::setRotation(const Matrix44& m) { mRotation = m; } void Movable::setRotation(const Common::Quaternion& q) { float x, y, z; q.toEuler(x, y, z); setRotationFromEuler(Common::Vector3(x, y, z)); } void Movable::setRotation(const Common::Vector3& axis, float angle) { mRotation = HelperFunctions::rotationMatrixFromAxisAngle(axis, angle); } void Movable::setRotation(const Common::Vector3& forward, const Common::Vector3& up) { Vector3 fw = forward.normalized(); Vector3 u = up.normalized(); Vector3 side = fw.cross(u); mRotation.m[0] = side.x; mRotation.m[1] = side.y; mRotation.m[2] = side.z; mRotation.m[4] = u.x; mRotation.m[5] = u.y; mRotation.m[6] = u.z; mRotation.m[8] = fw.x; mRotation.m[9] = fw.y; mRotation.m[10] = fw.z; } void Movable::setScale(float x, float y, float z) { mScale.x = x; mScale.y = y; mScale.z = z; } const Common::Vector3& Movable::getScale() const { return mScale; } void Movable::addRotation(const Common::Matrix44& m, bool local) { if(local) mRotation = m * mRotation; else mRotation = mRotation * m; } void Movable::addRotation(const Common::Vector3& axis, float angle, bool local) { Matrix44 temp = HelperFunctions::rotationMatrixFromAxisAngle(axis, angle); addRotation(temp, local); } Common::Vector3 Movable::getTargetVector() const { Vector3 v; v.x = mRotation.m[8]; v.y = mRotation.m[9]; v.z = mRotation.m[10]; return v; } Common::Vector3 Movable::getUpVector() const { Vector3 v; v.x = mRotation.m[4]; v.y = mRotation.m[5]; v.z = mRotation.m[6]; return v; } MeshInstance::MeshInstance(const Drawable& m, bool usebackfaceculling, bool useblending) : mDrawable(m), mBackfaceCulling(usebackfaceculling), mBlending(useblending) { } const Drawable& MeshInstance::getDrawable() const { return mDrawable; } bool MeshInstance::useBackfaceCulling() const { return mBackfaceCulling; } bool MeshInstance::useBlending() const { return mBlending; } } <file_sep>/sscene/HelperFunctions.cpp #include "HelperFunctions.h" #include <fstream> #include "common/Math.h" #include "common/Texture.h" using namespace Common; using namespace Scene; namespace Scene { Matrix44 HelperFunctions::perspectiveMatrix(float fov, int screenwidth, int screenheight, float zfar) { const float aspect_ratio = screenwidth / screenheight; const float znear = 0.1f; const float h = 1.0 / tan(Math::degreesToRadians(fov * 0.5f)); const float neg_depth = znear - zfar; Matrix44 pers = Matrix44::Identity; pers.m[0 * 4 + 0] = h / aspect_ratio; pers.m[1 * 4 + 1] = h; pers.m[2 * 4 + 2] = (zfar + znear) / neg_depth; pers.m[2 * 4 + 3] = -1.0; pers.m[3 * 4 + 2] = 2.0 * zfar * znear / neg_depth; pers.m[3 * 4 + 3] = 0.0; return pers; } Matrix44 HelperFunctions::orthoMatrix(int screenwidth, int screenheight) { const float r = screenwidth / 2.0f; const float t = screenheight / 2.0f; const float f = 1.0; const float n = -1.0; Matrix44 ortho = Matrix44::Identity; ortho.m[0 * 4 + 0] = 1.0f / r; ortho.m[1 * 4 + 1] = 1.0f / t; ortho.m[2 * 4 + 2] = -2.0f / (f - n); ortho.m[3 * 4 + 2] = - (f + n) / (f - n); ortho.m[3 * 4 + 3] = 1.0f; return ortho; } Matrix44 HelperFunctions::cameraRotationMatrix(const Vector3& tgt, const Vector3& up) { Vector3 n(tgt.negated().normalized()); auto u = up.normalized().cross(n); auto v = n.cross(u); auto m = Matrix44::Identity; m.m[0] = u.x; m.m[1] = v.x; m.m[2] = n.x; m.m[4] = u.y; m.m[5] = v.y; m.m[6] = n.y; m.m[8] = u.z; m.m[9] = v.z; m.m[10] = n.z; return m; } GLuint HelperFunctions::loadShaderFromFile(GLenum type, const char* filename) { std::ifstream ifs(filename); if(ifs.bad()) { return 0; } std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); return loadShader(type, content.c_str()); } GLuint HelperFunctions::loadShader(GLenum type, const char* src) { GLuint shader; GLint compiled; shader = glCreateShader(type); if(shader == 0) return 0; glShaderSource(shader, 1, &src, NULL); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if(!compiled) { GLint infoLen = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLen); if(infoLen > 1) { char* infoLog = new char[infoLen]; glGetShaderInfoLog(shader, infoLen, NULL, infoLog); std::cerr << "Error compiling " << (type == GL_VERTEX_SHADER ? "vertex" : "fragment") << " shader: " << infoLog << "\n"; delete[] infoLog; } glDeleteShader(shader); return 0; } return shader; } void HelperFunctions::enableDepthTest() { glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); } void HelperFunctions::disableDepthTest() { glDisable(GL_DEPTH_TEST); } boost::shared_ptr<Texture> HelperFunctions::loadTexture(const std::string& filename) { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); boost::shared_ptr<Texture> texture(new Texture(filename.c_str())); glBindTexture(GL_TEXTURE_2D, texture->getTexture()); if (GLEW_VERSION_3_0) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenerateMipmap(GL_TEXTURE_2D); } else { /* TODO: add mipmap generation */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } return texture; } Matrix44 HelperFunctions::translationMatrix(const Vector3& v) { Matrix44 translation = Matrix44::Identity; translation.m[3 * 4 + 0] = v.x; translation.m[3 * 4 + 1] = v.y; translation.m[3 * 4 + 2] = v.z; return translation; } Matrix44 HelperFunctions::scaleMatrix(const Vector3& v) { Matrix44 scale = Matrix44::Identity; scale.m[0 * 4 + 0] = v.x; scale.m[1 * 4 + 1] = v.y; scale.m[2 * 4 + 2] = v.z; return scale; } Matrix44 HelperFunctions::rotationMatrixFromEuler(const Vector3& v) { Matrix44 rotation = Matrix44::Identity; float cx = cos(v.x); float cy = cos(v.y); float cz = cos(v.z); float sx = sin(v.x); float sy = sin(v.y); float sz = sin(v.z); rotation.m[0 * 4 + 0] = cy * cz; rotation.m[1 * 4 + 0] = -cx * sz + sx * sy * cz; rotation.m[2 * 4 + 0] = sx * sz + cx * sy * cz; rotation.m[0 * 4 + 1] = cy * sz; rotation.m[1 * 4 + 1] = cx * cz + sx * sy * sz; rotation.m[2 * 4 + 1] = -sx * cz + cx * sy * sz; rotation.m[0 * 4 + 2] = -sy; rotation.m[1 * 4 + 2] = sx * cy; rotation.m[2 * 4 + 2] = cx * cy; return rotation; } Matrix44 HelperFunctions::rotationMatrixFromAxisAngle(const Common::Vector3& axis, float angle) { /* TODO: this function may not be correct. */ float ct = cos(angle); float oct = 1.0f - ct; float st = sin(angle); const Vector3 v = axis.normalized(); const float& x = v.x; const float& y = v.y; const float& z = v.z; Matrix44 r = Matrix44::Identity; r.m[0] = ct + x * x * oct; r.m[1] = x * y * oct - z * st; r.m[2] = x * z * oct - y * st; r.m[4] = y * x * oct + z * st; r.m[5] = ct + y * y * oct; r.m[6] = y * z * oct - x * st; r.m[8] = z * x * oct - y * st; r.m[9] = z * y * oct + x * st; r.m[10] = ct + z * z * oct; return r; } Common::Vector3 HelperFunctions::rotateVector(const Common::Matrix44& mat, const Common::Vector3& v) { Vector3 ret; ret.x = mat.m[0] * v.x + mat.m[1] * v.y + mat.m[2] * v.z; ret.y = mat.m[4] * v.x + mat.m[5] * v.y + mat.m[6] * v.z; ret.z = mat.m[8] * v.x + mat.m[9] * v.y + mat.m[10] * v.z; return ret; } } <file_sep>/Makefile CXX ?= clang++ CXXFLAGS ?= -O2 -g3 -Werror CXXFLAGS += -std=c++11 -Wall $(shell sdl-config --cflags) -I. LDFLAGS += $(shell sdl-config --libs) -lSDL_image -lSDL_ttf -lGL -lGLEW -lassimp AR ?= ar COMMONDIR = common COMMONSRCS = $(shell (find $(COMMONDIR) \( -name '*.cpp' -o -name '*.h' \))) COMMONLIB = $(COMMONDIR)/libcommon.a LIBSCENESRCDIR = sscene LIBSCENESRCFILES = Model.cpp HelperFunctions.cpp Scene.cpp LIBSCENESRCS = $(addprefix $(LIBSCENESRCDIR)/, $(LIBSCENESRCFILES)) LIBSCENEOBJS = $(LIBSCENESRCS:.cpp=.o) LIBSCENEDEPS = $(LIBSCENESRCS:.cpp=.dep) LIBSCENELIB = libsscene.a LIBSCENESHADERFILES = scene.vert scene.frag line.vert line.frag overlay.vert overlay.frag LIBSCENESHADERDIR = $(LIBSCENESRCDIR)/shaders LIBSCENESHADERSRCS = $(addprefix $(LIBSCENESHADERDIR)/, $(LIBSCENESHADERFILES)) LIBSCENESHADERS = $(addsuffix .h, $(LIBSCENESHADERSRCS)) INSTALLPREFIX ?= /usr/local default: all all: $(LIBSCENELIB) tests/bin/SceneCube $(COMMONLIB): $(COMMONSRCS) make -C $(COMMONDIR) $(LIBSCENESHADERS): shader.sh $(LIBSCENESHADERSRCS) for file in $(LIBSCENESHADERS); do ./shader.sh $$file; done $(LIBSCENELIB): $(LIBSCENESHADERS) $(LIBSCENEOBJS) $(AR) rcs $(LIBSCENELIB) $(LIBSCENEOBJS) TESTBINDIR = tests/bin $(TESTBINDIR): mkdir -p tests/bin tests/bin/SceneCube: $(COMMONLIB) $(LIBSCENELIB) $(TESTBINDIR) tests/src/SceneCube.cpp $(CXX) $(CXXFLAGS) $(LDFLAGS) -o tests/bin/SceneCube tests/src/SceneCube.cpp $(LIBSCENELIB) $(COMMONLIB) install: $(LIBSCENELIB) mkdir -p $(INSTALLPREFIX)/include/sscene mkdir -p $(INSTALLPREFIX)/lib cp -a $(LIBSCENESRCDIR)/*.h $(INSTALLPREFIX)/include/sscene cp -a $(LIBSCENELIB) $(INSTALLPREFIX)/lib %.dep: %.cpp @rm -f $@ @$(CXX) -MM $(CXXFLAGS) $< > $@.P @sed 's,\($(notdir $*)\)\.o[ :]*,$(dir $*)\1.o $@ : ,g' < $@.P > $@ @rm -f $@.P clean: rm -rf tests/bin/SceneCube rm -rf common/*.a rm -rf common/*.o rm -rf sscene/*.o rm -rf sscene/*.a rm -rf $(LIBSCENESHADERDIR)/*.h rm -rf $(LIBSCENELIB) rm -rf tests/bin -include $(LIBSCENEDEPS) <file_sep>/sscene/Scene.cpp #include "Scene.h" #include <cassert> #include "HelperFunctions.h" #include "common/Texture.h" #include "common/Math.h" using namespace Common; using namespace Scene; namespace Scene { #include "shaders/scene.vert.h" #include "shaders/scene.frag.h" #include "shaders/line.vert.h" #include "shaders/line.frag.h" #include "shaders/overlay.vert.h" #include "shaders/overlay.frag.h" #define CHECK_GL_ERROR_IMPL(file, line) { \ do { \ while(1) { \ GLenum err = glGetError(); \ if(err == GL_NO_ERROR) { \ break; \ } \ fprintf(stderr, "%s:%d: GL error 0x%04x\n", file, line, err); \ } \ } while(0); \ } #define CHECK_GL_ERROR() { do { CHECK_GL_ERROR_IMPL(__FILE__, __LINE__); } while(0); } const Vector3 WorldForward = Vector3(1, 0, 0); const Vector3 WorldUp = Vector3(0, 1, 0); struct attrib { const char* name; int elems; const std::vector<GLfloat>& data; }; void loadBufferData(const std::vector<attrib>& attribs, GLuint* vboids) { int i = 0; for(auto& a : attribs) { glBindBuffer(GL_ARRAY_BUFFER, vboids[i]); glBufferData(GL_ARRAY_BUFFER, a.data.size() * sizeof(GLfloat), &a.data[0], GL_STATIC_DRAW); glVertexAttribPointer(i, a.elems, GL_FLOAT, GL_FALSE, 0, NULL); i++; } } const unsigned int Line::VERTEX_POS_INDEX = 0; const unsigned int Line::COLOR_INDEX = 1; Line::Line() { glGenBuffers(2, mVBOIDs); } Line::~Line() { if(mVBOIDs[0]) { glDeleteBuffers(2, mVBOIDs); } } void Line::addSegment(const Common::Vector3& start, const Common::Vector3& end, const Common::Color& color) { mSegments.push_back(std::make_tuple(start, end, color)); std::vector<GLfloat> vertices; std::vector<GLfloat> colors; for(const auto& t : mSegments) { vertices.push_back(std::get<0>(t).x); vertices.push_back(std::get<0>(t).y); vertices.push_back(std::get<0>(t).z); vertices.push_back(std::get<1>(t).x); vertices.push_back(std::get<1>(t).y); vertices.push_back(std::get<1>(t).z); colors.push_back(std::get<2>(t).r / 255.0f); colors.push_back(std::get<2>(t).g / 255.0f); colors.push_back(std::get<2>(t).b / 255.0f); colors.push_back(std::get<2>(t).r / 255.0f); colors.push_back(std::get<2>(t).g / 255.0f); colors.push_back(std::get<2>(t).b / 255.0f); } std::vector<attrib> attribs = { { "a_Position", 3, vertices }, { "a_Color", 3, colors } }; loadBufferData(attribs, mVBOIDs); } void Line::clear() { mSegments.clear(); } bool Line::isEmpty() const { return mSegments.empty(); } GLuint Line::getVertexBuffer() const { return mVBOIDs[0]; } GLuint Line::getColorBuffer() const { return mVBOIDs[1]; } unsigned int Line::getNumVertices() const { return mSegments.size() * 2; } const unsigned int Overlay::VERTEX_POS_INDEX = 0; const unsigned int Overlay::TEXCOORD_INDEX = 1; Overlay::Overlay(const std::string& filename, unsigned int screenwidth, unsigned int screenheight) : mEnabled(false), mW(screenwidth), mH(screenheight) { mTexture = HelperFunctions::loadTexture(filename); init(); } Overlay::Overlay(boost::shared_ptr<Common::Texture> texture, unsigned int screenwidth, unsigned int screenheight) : mTexture(texture), mEnabled(false), mW(screenwidth), mH(screenheight) { init(); } void Overlay::init() { glGenBuffers(2, mVBOIDs); std::vector<GLfloat> pos = { 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }; std::vector<GLfloat> tex = { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, }; std::vector<attrib> attribs = { { "a_Position", 3, pos }, { "a_texCoord", 2, tex } }; loadBufferData(attribs, mVBOIDs); } Overlay::~Overlay() { glDeleteBuffers(2, mVBOIDs); } GLuint Overlay::getTexture() const { return mTexture->getTexture(); } GLuint Overlay::getVertexBuffer() const { return mVBOIDs[0]; } GLuint Overlay::getTexCoordBuffer() const { return mVBOIDs[1]; } void Overlay::setPosition(unsigned int x, unsigned int y, unsigned int w, unsigned int h) { mX = x; mY = y; mW = w; mH = h; } void Overlay::setTexture(boost::shared_ptr<Common::Texture> texture) { mTexture = texture; } unsigned int Overlay::getX() const { return mX; } unsigned int Overlay::getY() const { return mY; } unsigned int Overlay::getW() const { return mW; } unsigned int Overlay::getH() const { return mH; } float Overlay::getDepth() const { return mDepth; } void Overlay::setDepth(float d) { mDepth = d; } Camera::Camera() : mHRot(0.0f), mVRot(0.0f) { setRotation(WorldForward, WorldUp); } void Camera::lookAt(const Common::Vector3& tgt, const Common::Vector3& up) { setRotation(tgt, up); } void Camera::setMovementKey(const std::string& key, float forward, float up, float sideways) { std::tuple<float, float, float> t(forward, up, sideways); mMovement[key] = t; mMovementCache[t] = calculateMovement(t); } Vector3 Camera::calculateMovement(const std::tuple<float, float, float>& v) { Vector3 r; if(std::get<0>(v)) r += getTargetVector() * std::get<0>(v); if(std::get<1>(v)) r += getUpVector() * std::get<1>(v); if(std::get<2>(v)) r += getTargetVector().cross(getUpVector()) * std::get<2>(v); return r; } void Camera::clearMovementKey(const std::string& key) { auto& t = mMovement[key]; mMovementCache[t].zero(); std::get<0>(t) = 0; std::get<1>(t) = 0; std::get<2>(t) = 0; } void Camera::applyMovementKeys(float coeff) { for(auto p : mMovement) { auto m = calculateMovement(p.second); mPosition += m; } } void Camera::setForwardMovement(float speed) { setMovementKey("Forward", speed, 0, 0); } void Camera::clearForwardMovement() { clearMovementKey("Forward"); } void Camera::setSidewaysMovement(float speed) { setMovementKey("Sideways", 0, 0, speed); } void Camera::clearSidewaysMovement() { clearMovementKey("Sideways"); } void Camera::setUpwardsMovement(float speed) { setMovementKey("Upwards", 0, speed, 0); } void Camera::clearUpwardsMovement() { clearMovementKey("Upwards"); } void Camera::rotate(float yaw, float pitch) { mHRot += yaw; mVRot += pitch; Vector3 view = Math::rotate3D(WorldForward, mHRot, WorldUp).normalized(); auto haxis = WorldUp.cross(view).normalized(); Vector3 tgt = Math::rotate3D(view, -mVRot, haxis).normalized(); setRotation(tgt, tgt.cross(haxis).normalized()); for(auto p : mMovement) { mMovementCache[p.second] = calculateMovement(p.second); } } Light::Light(const Common::Color& col, bool on) : mOn(on) { setColor(col); } void Light::setState(bool on) { mOn = on; } bool Light::isOn() const { return mOn; } const Common::Vector3& Light::getColor() const { return mColor; } void Light::setColor(const Common::Color& c) { mColor = Vector3(c.r / 255.0f, c.g / 255.0f, c.b / 255.0f); } void Light::setColor(const Common::Vector3& c) { mColor = c; } PointLight::PointLight(const Common::Vector3& pos, const Common::Vector3& attenuation, const Common::Color& col, bool on) : Light(col, on), Movable(pos), mAttenuation(attenuation) { } const Common::Vector3& PointLight::getAttenuation() const { return mAttenuation; } void PointLight::setAttenuation(const Common::Vector3& v) { mAttenuation = v; } DirectionalLight::DirectionalLight(const Common::Vector3& dir, const Common::Color& col, bool on) : Light(col, true), mDirection(dir.normalized()) { } const Common::Vector3& DirectionalLight::getDirection() const { return mDirection; } void DirectionalLight::setDirection(const Common::Vector3& dir) { mDirection = dir.normalized(); } class Drawable { public: Drawable(GLuint programObject, const Model& model); ~Drawable(); Drawable& operator=(const Drawable&) = delete; Drawable(const Drawable&) = delete; GLuint getVertexBuffer() const; GLuint getTexCoordBuffer() const; GLuint getNormalBuffer() const; GLuint getIndexBuffer() const; unsigned int getNumIndices() const; unsigned int getNumVertices() const; static const unsigned int VERTEX_POS_INDEX; static const unsigned int TEXCOORD_INDEX; static const unsigned int NORMAL_INDEX; private: void initBuffers(GLuint programObject, const Model& model); GLuint mVBOIDs[4]; unsigned int mNumIndices; unsigned int mNumVertices; }; const unsigned int Drawable::VERTEX_POS_INDEX = 0; const unsigned int Drawable::TEXCOORD_INDEX = 1; const unsigned int Drawable::NORMAL_INDEX = 2; Drawable::Drawable(GLuint programObject, const Model& model) { initBuffers(programObject, model); mNumIndices = model.getIndices().size(); mNumVertices = model.getVertexCoords().size() / 3; } Drawable::~Drawable() { glDeleteBuffers(4, mVBOIDs); } GLuint Drawable::getVertexBuffer() const { return mVBOIDs[0]; } GLuint Drawable::getTexCoordBuffer() const { return mVBOIDs[1]; } GLuint Drawable::getNormalBuffer() const { return mVBOIDs[2]; } GLuint Drawable::getIndexBuffer() const { return mVBOIDs[3]; } unsigned int Drawable::getNumIndices() const { return mNumIndices; } unsigned int Drawable::getNumVertices() const { return mNumVertices; } void Drawable::initBuffers(GLuint programObject, const Model& model) { glGenBuffers(4, mVBOIDs); std::vector<attrib> attribs = { { "a_Position", 3, model.getVertexCoords() }, { "a_texCoord", 2, model.getTexCoords() }, { "a_Normal", 3, model.getNormals() } }; loadBufferData(attribs, mVBOIDs); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mVBOIDs[3]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, model.getIndices().size() * sizeof(GLushort), &model.getIndices()[0], GL_STATIC_DRAW); } struct Shader { const char* vertexShader; const char* fragmentShader; std::vector<const char*> uniforms; std::vector<std::pair<GLuint, const char*>> attribs; }; GLuint Scene::loadShader(const Shader& s) { GLuint vshader; GLuint fshader; GLint linked; GLuint program; vshader = HelperFunctions::loadShader(GL_VERTEX_SHADER, s.vertexShader); fshader = HelperFunctions::loadShader(GL_FRAGMENT_SHADER, s.fragmentShader); program = glCreateProgram(); if(program == 0) { std::cerr << "Unable to create program.\n"; throw std::runtime_error("Error initialising 3D"); } glAttachShader(program, vshader); glAttachShader(program, fshader); for(const auto& attr : s.attribs) { glEnableVertexAttribArray(attr.first); glBindAttribLocation(program, attr.first, attr.second); } glLinkProgram(program); glGetProgramiv(program, GL_LINK_STATUS, &linked); if(!linked) { GLint infoLen = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLen); if(infoLen > 1) { char* infoLog = new char[infoLen]; glGetProgramInfoLog(program, infoLen, NULL, infoLog); std::cerr << "Error linking program: " << infoLog << "\n"; delete[] infoLog; } else { std::cerr << "Unknown error when linking program.\n"; } glDeleteProgram(program); throw std::runtime_error("Error initialising 3D"); } for(auto& p : s.uniforms) { mUniformLocationMap[program][p] = glGetUniformLocation(program, p); } return program; } Scene::Scene(float screenWidth, float screenHeight) : mScreenWidth(screenWidth), mScreenHeight(screenHeight), mAmbientLight(Color::White, false), mDirectionalLight(Vector3(1, 0, 0), Color::White, false), mPointLight(Vector3(), Vector3(), Color::White, false), mFOV(90.0f), mZFar(200.0f), mClearColor(0, 0, 0) { } void Scene::init() { GLenum glewerr = glewInit(); if (glewerr != GLEW_OK) { std::cerr << "Unable to initialise GLEW.\n"; throw std::runtime_error("Error initialising 3D"); } if (!GLEW_VERSION_2_1) { std::cerr << "OpenGL 2.1 not supported.\n"; throw std::runtime_error("Error initialising 3D"); } printf("%-20s: %s\n", "GL vendor", glGetString(GL_VENDOR)); printf("%-20s: %s\n", "GL renderer", glGetString(GL_RENDERER)); printf("%-20s: %s\n", "GL version", glGetString(GL_VERSION)); printf("%-20s: %s\n", "GLSL version", glGetString(GL_SHADING_LANGUAGE_VERSION)); Shader scene; scene.vertexShader = scene_vert; scene.fragmentShader = scene_frag; scene.uniforms = { "u_MVP", "u_inverseMVP", "s_texture", "u_ambientLight", "u_directionalLightDirection", "u_directionalLightColor", "u_pointLightPosition", "u_pointLightAttenuation", "u_pointLightColor", "u_ambientLightEnabled", "u_directionalLightEnabled", "u_pointLightEnabled" }; scene.attribs = { { Drawable::VERTEX_POS_INDEX, "a_Position" }, { Drawable::TEXCOORD_INDEX, "a_texCoord" }, { Drawable::NORMAL_INDEX, "a_Normal" } }; mSceneProgram = loadShader(scene); Shader line; line.vertexShader = line_vert; line.fragmentShader = line_frag; line.uniforms = { "u_MVP" }; line.attribs = { { Line::VERTEX_POS_INDEX, "a_Position" }, { Line::COLOR_INDEX, "a_Color" } }; mLineProgram = loadShader(line); { Shader overlay; overlay.vertexShader = overlay_vert; overlay.fragmentShader = overlay_frag; overlay.uniforms = { "u_MVP", "s_texture" }; overlay.attribs = { { Overlay::VERTEX_POS_INDEX, "a_Position" }, { Overlay::TEXCOORD_INDEX, "a_texCoord" } }; mOverlayProgram = loadShader(overlay); } HelperFunctions::enableDepthTest(); glEnable(GL_TEXTURE_2D); glViewport(0, 0, mScreenWidth, mScreenHeight); glUseProgram(mSceneProgram); } boost::shared_ptr<Common::Texture> Scene::getModelTexture(const std::string& mname) const { auto it = mMeshInstanceTextures.find(mname); if(it == mMeshInstanceTextures.end()) { throw std::runtime_error("Couldn't find texture for model"); } else { return it->second; } } Camera& Scene::getDefaultCamera() { return mDefaultCamera; } void Scene::addSkyBox() { /* TODO */ } Light& Scene::getAmbientLight() { return mAmbientLight; } DirectionalLight& Scene::getDirectionalLight() { return mDirectionalLight; } PointLight& Scene::getPointLight() { return mPointLight; } void Scene::calculateModelMatrix(const MeshInstance& mi) { auto translation = HelperFunctions::translationMatrix(mi.getPosition()); auto rotation = mi.getRotation(); auto scale = HelperFunctions::scaleMatrix(mi.getScale()); mModelMatrix = scale * rotation * translation; auto invTranslation(translation); invTranslation.m[3] = -invTranslation.m[3]; invTranslation.m[7] = -invTranslation.m[7]; invTranslation.m[11] = -invTranslation.m[11]; auto invRotation = rotation.transposed(); auto invScale = scale; invScale.m[0] = 1.0f / invScale.m[0]; invScale.m[5] = 1.0f / invScale.m[5]; invScale.m[10] = 1.0f / invScale.m[10]; mInverseModelMatrix = invTranslation * invRotation * invScale; } void Scene::updateMVPMatrix(const MeshInstance& mi) { calculateModelMatrix(mi); auto mvp = mModelMatrix * mViewMatrix * mPerspectiveMatrix; auto imvp = mInverseModelMatrix; glUniformMatrix4fv(mUniformLocationMap[mSceneProgram]["u_MVP"], 1, GL_FALSE, mvp.m); glUniformMatrix4fv(mUniformLocationMap[mSceneProgram]["u_inverseMVP"], 1, GL_FALSE, imvp.m); } void Scene::updateFrameMatrices(const Camera& cam) { mPerspectiveMatrix = HelperFunctions::perspectiveMatrix(mFOV, mScreenWidth, mScreenHeight, mZFar); auto camrot = HelperFunctions::cameraRotationMatrix(cam.getTargetVector(), cam.getUpVector()); auto camtrans = HelperFunctions::translationMatrix(cam.getPosition().negated()); mViewMatrix = camtrans * camrot; } Common::Matrix44 Scene::getOrthoMVP(const Overlay& ov) const { return HelperFunctions::scaleMatrix(Common::Vector3(ov.getW(), ov.getH(), 1.0f)) * HelperFunctions::translationMatrix(Common::Vector3(ov.getX() - mScreenWidth * 0.5f, ov.getY() - mScreenHeight * 0.5f, ov.getDepth())) * HelperFunctions::orthoMatrix(mScreenWidth, mScreenHeight); } void Scene::render() { glClearColor(mClearColor.r / 256.0f, mClearColor.g / 256.0f, mClearColor.b / 256.0f, 1.0f); glUseProgram(mSceneProgram); glUniform1i(mUniformLocationMap[mSceneProgram]["u_ambientLightEnabled"], mAmbientLight.isOn()); glUniform1i(mUniformLocationMap[mSceneProgram]["u_directionalLightEnabled"], mDirectionalLight.isOn()); glUniform1i(mUniformLocationMap[mSceneProgram]["u_pointLightEnabled"], mPointLight.isOn()); updateFrameMatrices(mDefaultCamera); if(mPointLight.isOn()) { auto at = mPointLight.getAttenuation(); auto col = mPointLight.getColor(); glUniform3f(mUniformLocationMap[mSceneProgram]["u_pointLightAttenuation"], at.x, at.y, at.z); glUniform3f(mUniformLocationMap[mSceneProgram]["u_pointLightColor"], col.x, col.y, col.z); } if(mDirectionalLight.isOn()) { auto col = mDirectionalLight.getColor(); glUniform3f(mUniformLocationMap[mSceneProgram]["u_directionalLightColor"], col.x, col.y, col.z); } if(mAmbientLight.isOn()) { auto col = mAmbientLight.getColor(); glUniform3f(mUniformLocationMap[mSceneProgram]["u_ambientLight"], col.x, col.y, col.z); } for(const auto& mi : mMeshInstances) { /* TODO: add support for vertex colors. */ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, getModelTexture(mi.first)->getTexture()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glUniform1i(mUniformLocationMap[mSceneProgram]["s_texture"], 0); updateMVPMatrix(*mi.second); if(mPointLight.isOn()) { // inverse translation matrix Vector3 plpos(mPointLight.getPosition()); Vector3 plposrel = mi.second->getPosition() - plpos; glUniform3f(mUniformLocationMap[mSceneProgram]["u_pointLightPosition"], plposrel.x, plposrel.y, plposrel.z); } if(mDirectionalLight.isOn()) { // inverse rotation matrix (normal matrix) Vector3 dir = mDirectionalLight.getDirection(); glUniform3f(mUniformLocationMap[mSceneProgram]["u_directionalLightDirection"], dir.x, dir.y, dir.z); } const auto& d = mi.second->getDrawable(); if(mi.second->useBlending()) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } else { glDisable(GL_BLEND); } if(mi.second->useBackfaceCulling()) { glCullFace(GL_BACK); glEnable(GL_CULL_FACE); } else { glDisable(GL_CULL_FACE); } const auto& ib = d.getIndexBuffer(); if(d.getNumIndices() != 0) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ib); } glEnableVertexAttribArray(Drawable::VERTEX_POS_INDEX); glEnableVertexAttribArray(Drawable::TEXCOORD_INDEX); glEnableVertexAttribArray(Drawable::NORMAL_INDEX); glBindBuffer(GL_ARRAY_BUFFER, d.getVertexBuffer()); glVertexAttribPointer(Drawable::VERTEX_POS_INDEX, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, d.getTexCoordBuffer()); glVertexAttribPointer(Drawable::TEXCOORD_INDEX, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, d.getNormalBuffer()); glVertexAttribPointer(Drawable::NORMAL_INDEX, 3, GL_FLOAT, GL_FALSE, 0, 0); if(d.getNumIndices() != 0) { glDrawElements(GL_TRIANGLES, d.getNumIndices(), GL_UNSIGNED_SHORT, NULL); } else { glDrawArrays(GL_TRIANGLES, 0, d.getNumVertices()); } glDisableVertexAttribArray(Drawable::VERTEX_POS_INDEX); glDisableVertexAttribArray(Drawable::TEXCOORD_INDEX); glDisableVertexAttribArray(Drawable::NORMAL_INDEX); CHECK_GL_ERROR(); } glUseProgram(mLineProgram); auto mvp = mViewMatrix * mPerspectiveMatrix; glUniformMatrix4fv(mUniformLocationMap[mSceneProgram]["u_MVP"], 1, GL_FALSE, mvp.m); for(const auto& kv : mLines) { if(kv.second.isEmpty()) continue; glEnableVertexAttribArray(Line::VERTEX_POS_INDEX); glEnableVertexAttribArray(Line::COLOR_INDEX); glBindBuffer(GL_ARRAY_BUFFER, kv.second.getVertexBuffer()); glVertexAttribPointer(Line::VERTEX_POS_INDEX, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, kv.second.getColorBuffer()); glVertexAttribPointer(Line::COLOR_INDEX, 3, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_LINES, 0, kv.second.getNumVertices()); glDisableVertexAttribArray(Line::VERTEX_POS_INDEX); glDisableVertexAttribArray(Line::COLOR_INDEX); CHECK_GL_ERROR(); } if(!mOverlays.empty()) { glUseProgram(mOverlayProgram); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); std::vector<std::pair<std::string, boost::shared_ptr<Overlay>>> sortedOverlays; std::copy(mOverlays.begin(), mOverlays.end(), back_inserter(sortedOverlays)); std::sort(sortedOverlays.begin(), sortedOverlays.end(), [&] (const std::pair<std::string, boost::shared_ptr<Overlay>>& t1, const std::pair<std::string, boost::shared_ptr<Overlay>>& t2) { return t1.second->getDepth() < t2.second->getDepth(); }); for(const auto& kv : sortedOverlays) { if(!kv.second->isEnabled()) { continue; } auto mvp = getOrthoMVP(*kv.second); glUniformMatrix4fv(mUniformLocationMap[mOverlayProgram]["u_MVP"], 1, GL_FALSE, mvp.m); glUniform1i(mUniformLocationMap[mOverlayProgram]["s_texture"], 0); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, kv.second->getTexture()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glEnableVertexAttribArray(Overlay::VERTEX_POS_INDEX); glEnableVertexAttribArray(Overlay::TEXCOORD_INDEX); glBindBuffer(GL_ARRAY_BUFFER, kv.second->getVertexBuffer()); glVertexAttribPointer(Overlay::VERTEX_POS_INDEX, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, kv.second->getTexCoordBuffer()); glVertexAttribPointer(Overlay::TEXCOORD_INDEX, 2, GL_FLOAT, GL_FALSE, 0, 0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDisableVertexAttribArray(Overlay::VERTEX_POS_INDEX); glDisableVertexAttribArray(Overlay::TEXCOORD_INDEX); CHECK_GL_ERROR(); } } } void Scene::addTexture(const std::string& name, const std::string& filename) { if(mTextures.find(name) != mTextures.end()) { throw std::runtime_error("Tried adding an already existing texture"); } else { mTextures.insert({name, HelperFunctions::loadTexture(filename)}); } } void Scene::addModel(const std::string& name, const Model& model) { if(mDrawables.find(name) != mDrawables.end()) { throw std::runtime_error("Tried adding a model with an already existing name"); } else { boost::shared_ptr<Drawable> d(new Drawable(mSceneProgram, model)); std::cout << (d->getNumVertices()) << " vertices.\n"; std::cout << (d->getNumIndices() / 3) << " triangles.\n"; mDrawables.insert({name, d}); } } void Scene::addModel(const std::string& name, const std::string& filename) { auto m = Model(filename); addModel(name, m); } void Scene::addModelFromHeightmap(const std::string& name, const Heightmap& heightmap) { auto m = Model(heightmap, 1.0f, 1.0f); addModel(name, m); } void Scene::addLine(const std::string& name, const Common::Vector3& start, const Common::Vector3& end, const Common::Color& color) { mLines[name].addSegment(start, end, color); } class PlaneHeightmap : public Heightmap { public: PlaneHeightmap(unsigned int segments) : mSegments(segments) { } virtual float getHeightAt(float x, float y) const { return 0.0f; } virtual unsigned int getWidth() const { return mSegments; } virtual float getXZScale() const { return 1.0f / static_cast<float>(mSegments); } private: unsigned int mSegments; }; void Scene::addPlane(const std::string& name, float uscale, float vscale, unsigned int segments) { PlaneHeightmap heightmap(segments); auto m = Model(heightmap, uscale, vscale); addModel(name, m); } void Scene::addModel(const std::string& name, const std::vector<Common::Vector3>& vertexcoords, const std::vector<Common::Vector2>& texcoords, const std::vector<unsigned int>& indices, const std::vector<Common::Vector3>& normals) { auto m = Model(vertexcoords, texcoords, indices, normals); addModel(name, m); } void Scene::clearLine(const std::string& name) { mLines[name].clear(); } void Scene::setFOV(float angle) { mFOV = angle; } float Scene::getFOV() const { return mFOV; } void Scene::setZFar(float zfar) { mZFar = zfar; } float Scene::getZFar() const { return mZFar; } void Scene::setClearColor(const Common::Color& color) { mClearColor = color; } void Scene::addOverlay(const std::string& name, const std::string& filename) { if(mOverlays.find(name) != mOverlays.end()) { throw std::runtime_error("Tried adding an already existing overlay"); } else { auto ov = boost::shared_ptr<Overlay>(new Overlay(filename, mScreenWidth, mScreenHeight)); mOverlays.insert({name, ov}); } } void Scene::setOverlayEnabled(const std::string& name, bool enabled) { auto it = mOverlays.find(name); if(it == mOverlays.end()) { throw std::runtime_error("Tried getting a non-existing overlay\n"); } else { it->second->setEnabled(enabled); } } void Scene::setOverlayPosition(const std::string& name, unsigned int x, unsigned int y, unsigned int w, unsigned int h) { auto it = mOverlays.find(name); if(it == mOverlays.end()) { throw std::runtime_error("Tried getting a non-existing overlay\n"); } else { it->second->setPosition(x, y, w, h); } } void Scene::setOverlayDepth(const std::string& name, float depth) { auto it = mOverlays.find(name); if(it == mOverlays.end()) { throw std::runtime_error("Tried getting a non-existing overlay\n"); } else { it->second->setDepth(depth); } } void Scene::enableText(const std::string& fontpath) { if(mTextRenderer) throw std::runtime_error("enableText() can only be called once\n"); mTextRenderer = std::unique_ptr<Common::TextRenderer>(new TextRenderer(fontpath.c_str(), 24)); } void Scene::addOverlayText(const std::string& name, const std::string& contents, const Common::Color& color, float scale, float x, float y, bool centered) { auto texture = mTextRenderer->renderText(contents.c_str(), color); auto it = mOverlays.find(name); auto w = texture->getWidth() * scale; auto h = texture->getHeight() * scale; auto nx = x * mScreenWidth; auto ny = y * mScreenWidth; auto mx = centered ? nx - w / 2 : nx; auto my = centered ? ny + h / 2 : ny; if(it == mOverlays.end()) { auto ov = boost::shared_ptr<Overlay>(new Overlay(texture, mScreenWidth, mScreenHeight)); ov->setPosition(mx, my, w, h); ov->setEnabled(true); mOverlays.insert({name, ov}); } else { it->second->setTexture(texture); it->second->setPosition(mx, my, w, h); it->second->setEnabled(true); } } void Scene::setWireframe(bool w) { glPolygonMode(GL_FRONT_AND_BACK, w ? GL_LINE : GL_FILL); } void Scene::getModel(const std::string& name) { auto it = mDrawables.find(name); if(it == mDrawables.end()) { throw std::runtime_error("Tried getting a non-existing model\n"); } } boost::shared_ptr<MeshInstance> Scene::addMeshInstance(const std::string& name, const std::string& modelname, const std::string& texturename, bool usebackfaceculling, bool useblending) { if(mMeshInstances.find(name) != mMeshInstances.end()) { throw std::runtime_error("Tried adding a mesh instance with an already existing name"); } auto modelit = mDrawables.find(modelname); if(modelit == mDrawables.end()) throw std::runtime_error("Tried getting a non-existing model\n"); auto textit = mTextures.find(texturename); if(textit == mTextures.end()) throw std::runtime_error("Tried getting a non-existing texture\n"); auto mi = boost::shared_ptr<MeshInstance>(new MeshInstance(*modelit->second, usebackfaceculling, useblending)); mMeshInstances.insert({name, mi}); mMeshInstanceTextures.insert({name, textit->second}); return mi; } } <file_sep>/sscene/Scene.h #ifndef SCENE_SCENE_H #define SCENE_SCENE_H #include <tuple> #include <map> #include <boost/shared_ptr.hpp> #include <GL/glew.h> #include <GL/gl.h> #include "common/Vector3.h" #include "common/Matrix44.h" #include "common/Color.h" #include "common/Texture.h" #include "common/TextRenderer.h" #include "Model.h" namespace Scene { extern const Common::Vector3 WorldForward; extern const Common::Vector3 WorldUp; enum class Reference { World, Local }; class Camera : public Movable { public: Camera(); void lookAt(const Common::Vector3& tgt, const Common::Vector3& right); void applyMovementKeys(float coeff); void setForwardMovement(float speed); void clearForwardMovement(); void setSidewaysMovement(float speed); void clearSidewaysMovement(); void setUpwardsMovement(float speed); void clearUpwardsMovement(); void rotate(float yaw, float pitch); private: void setMovementKey(const std::string& key, float forward, float up, float sideways); void clearMovementKey(const std::string& key); Common::Vector3 calculateMovement(const std::tuple<float, float, float>& tuple); std::map<std::string, std::tuple<float, float, float>> mMovement; std::map<std::tuple<float, float, float>, Common::Vector3> mMovementCache; float mHRot; float mVRot; }; class Light { public: Light(const Common::Color& col, bool on = true); void setState(bool on); bool isOn() const; const Common::Vector3& getColor() const; void setColor(const Common::Color& c); void setColor(const Common::Vector3& c); private: bool mOn; Common::Vector3 mColor; }; class PointLight : public Light, public Movable { public: PointLight(const Common::Vector3& pos, const Common::Vector3& attenuation, const Common::Color& col, bool on = true); const Common::Vector3& getAttenuation() const; void setAttenuation(const Common::Vector3& v); private: Common::Vector3 mAttenuation; }; class DirectionalLight : public Light { public: DirectionalLight(const Common::Vector3& dir, const Common::Color& col, bool on = true); const Common::Vector3& getDirection() const; void setDirection(const Common::Vector3& dir); private: Common::Vector3 mDirection; }; class Drawable; class Line { public: Line(); ~Line(); GLuint getVertexBuffer() const; GLuint getColorBuffer() const; unsigned int getNumVertices() const; void addSegment(const Common::Vector3& start, const Common::Vector3& end, const Common::Color& color); void clear(); bool isEmpty() const; static const unsigned int VERTEX_POS_INDEX; static const unsigned int COLOR_INDEX; private: std::vector<std::tuple<Common::Vector3, Common::Vector3, Common::Color>> mSegments; GLuint mVBOIDs[2]; }; class Overlay { public: Overlay(const std::string& filename, unsigned int screenwidth, unsigned int screenheight); Overlay(boost::shared_ptr<Common::Texture> texture, unsigned int screenwidth, unsigned int screenheight); ~Overlay(); GLuint getTexture() const; GLuint getVertexBuffer() const; GLuint getTexCoordBuffer() const; void setEnabled(bool e) { mEnabled = e; } bool isEnabled() const { return mEnabled; } void setPosition(unsigned int x, unsigned int y, unsigned int w, unsigned int h); void setTexture(boost::shared_ptr<Common::Texture> texture); unsigned int getX() const; unsigned int getY() const; unsigned int getW() const; unsigned int getH() const; static const unsigned int VERTEX_POS_INDEX; static const unsigned int TEXCOORD_INDEX; float getDepth() const; void setDepth(float d); private: void init(); boost::shared_ptr<Common::Texture> mTexture; GLuint mVBOIDs[2]; bool mEnabled; unsigned int mX = 0; unsigned int mY = 0; unsigned int mW; unsigned int mH; float mDepth = 0.0f; }; struct Shader; class Scene { public: Scene(float screenWidth, float screenHeight); void init(); Camera& getDefaultCamera(); void addSkyBox(); Light& getAmbientLight(); DirectionalLight& getDirectionalLight(); PointLight& getPointLight(); void render(); void addTexture(const std::string& name, const std::string& filename); void addModel(const std::string& name, const std::string& filename); void addModel(const std::string& name, const Model& model); void addModel(const std::string& name, const std::vector<Common::Vector3>& vertexcoords, const std::vector<Common::Vector2>& texcoords, const std::vector<unsigned int>& indices, const std::vector<Common::Vector3>& normals); // resulting model will span from (0, 0) to (width * xzscale, width * xzscale) void addModelFromHeightmap(const std::string& name, const Heightmap& heightmap); void addPlane(const std::string& name, float uscale, float vscale, unsigned int segments); void addLine(const std::string& name, const Common::Vector3& start, const Common::Vector3& end, const Common::Color& color); void clearLine(const std::string& name); void getModel(const std::string& name); void setFOV(float angle); float getFOV() const; void setZFar(float angle); float getZFar() const; void setClearColor(const Common::Color& color); void addOverlay(const std::string& name, const std::string& filename); void setOverlayEnabled(const std::string& name, bool enabled); void setOverlayPosition(const std::string& name, unsigned int x, unsigned int y, unsigned int w, unsigned int h); void setOverlayDepth(const std::string& name, float depth); void enableText(const std::string& fontpath); void addOverlayText(const std::string& name, const std::string& contents, const Common::Color& color, float scale, float x, float y, bool centered); void setWireframe(bool w); boost::shared_ptr<MeshInstance> addMeshInstance(const std::string& name, const std::string& modelname, const std::string& texturename, bool usebackfaceculling = true, bool useblending = false); private: void calculateModelMatrix(const MeshInstance& mi); void updateMVPMatrix(const MeshInstance& mi); void updateFrameMatrices(const Camera& cam); GLuint loadShader(const Shader& s); boost::shared_ptr<Common::Texture> getModelTexture(const std::string& mname) const; Common::Matrix44 getOrthoMVP(const Overlay& ov) const; float mScreenWidth; float mScreenHeight; GLuint mSceneProgram; GLuint mLineProgram; GLuint mOverlayProgram; std::map<GLuint, std::map<const char*, GLint>> mUniformLocationMap; Camera mDefaultCamera; Light mAmbientLight; DirectionalLight mDirectionalLight; PointLight mPointLight; std::map<std::string, boost::shared_ptr<Common::Texture>> mTextures; Common::Matrix44 mInverseModelMatrix; Common::Matrix44 mModelMatrix; Common::Matrix44 mViewMatrix; Common::Matrix44 mPerspectiveMatrix; std::map<std::string, boost::shared_ptr<Drawable>> mDrawables; std::map<std::string, boost::shared_ptr<MeshInstance>> mMeshInstances; std::map<std::string, boost::shared_ptr<Common::Texture>> mMeshInstanceTextures; std::map<std::string, Line> mLines; std::map<std::string, boost::shared_ptr<Overlay>> mOverlays; float mFOV; float mZFar; Common::Color mClearColor; std::unique_ptr<Common::TextRenderer> mTextRenderer; }; } #endif <file_sep>/shader.sh #!/bin/bash set -e set -u srcfile=$(echo $1 | sed -e 's/\.h$//') varname=$(basename $srcfile | sed -e 's/\./_/g') resfile=${srcfile}.h sed -e "1 i static const char $varname[] = " -e 's/$/\\n"/;s/^/"/' -e "$ a ;" $srcfile > $resfile <file_sep>/sscene/Model.h #ifndef MODEL_H #define MODEL_H #include <vector> #include <GL/glew.h> #include <GL/gl.h> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "common/Vector2.h" #include "common/Vector3.h" #include "common/Matrix44.h" #include "common/Quaternion.h" namespace Scene { class Heightmap { public: virtual ~Heightmap() { } // will be called getWidth()^2 times at getXZScale() intervals virtual float getHeightAt(float x, float y) const = 0; // number of tiles to create (for both x- and y axes) virtual unsigned int getWidth() const = 0; // size per tile virtual float getXZScale() const = 0; }; class Model { public: Model(); Model(const std::string& filename); Model(const Heightmap& heightmap, float uscale, float vscale); Model(const std::vector<Common::Vector3>& vertexcoords, const std::vector<Common::Vector2>& texcoords, const std::vector<unsigned int>& indices, const std::vector<Common::Vector3>& normals); private: friend class Drawable; const std::vector<GLfloat>& getVertexCoords() const; const std::vector<GLfloat>& getTexCoords() const; const std::vector<GLushort>& getIndices() const; const std::vector<GLfloat>& getNormals() const; void addVertex(const Common::Vector3& v); void addNormal(const Common::Vector3& v); void addTexCoord(float u, float v); void addIndex(unsigned short i); void addTriangleIndices(unsigned short i1, unsigned short i2, unsigned short i3); void addQuadIndices(unsigned short i1, unsigned short i2, unsigned short i3, unsigned short i4); private: std::vector<GLfloat> mVertexCoords; std::vector<GLfloat> mTexCoords; std::vector<GLushort> mIndices; std::vector<GLfloat> mNormals; Assimp::Importer mImporter; const aiScene* mScene; }; class Movable { public: Movable(); Movable(const Common::Vector3& pos); void setPosition(const Common::Vector3& p); const Common::Vector3& getPosition() const; void move(const Common::Vector3& v); const Common::Matrix44& getRotation() const; void setRotationFromEuler(const Common::Vector3& v); void setRotation(const Common::Matrix44& m); void setRotation(const Common::Quaternion& q); void setRotation(const Common::Vector3& axis, float angle); void setRotation(const Common::Vector3& forward, const Common::Vector3& up); void addRotation(const Common::Matrix44& m, bool local); void addRotation(const Common::Vector3& axis, float angle, bool local); Common::Vector3 getTargetVector() const; Common::Vector3 getUpVector() const; void setScale(float x, float y, float z); const Common::Vector3& getScale() const; protected: Common::Vector3 mPosition; Common::Matrix44 mRotation; Common::Vector3 mScale; }; class Drawable; class MeshInstance : public Movable { public: MeshInstance(const Drawable& m, bool usebackfaceculling, bool useblending); const Drawable& getDrawable() const; bool useBlending() const; bool useBackfaceCulling() const; private: const Drawable& mDrawable; bool mBackfaceCulling; bool mBlending; }; } #endif <file_sep>/sscene/HelperFunctions.h #ifndef SCENE_HELPERFUNCTIONS_H #define SCENE_HELPERFUNCTIONS_H #include <string> #include <boost/shared_ptr.hpp> #include <GL/glew.h> #include <GL/gl.h> #include "common/Vector3.h" #include "common/Matrix44.h" #include "common/Texture.h" namespace Scene { class HelperFunctions { public: static Common::Matrix44 translationMatrix(const Common::Vector3& v); static Common::Matrix44 scaleMatrix(const Common::Vector3& v); static Common::Matrix44 rotationMatrixFromEuler(const Common::Vector3& v); static Common::Matrix44 perspectiveMatrix(float fov, int screenwidth, int screenheight, float zfar); static Common::Matrix44 orthoMatrix(int screenwidth, int screenheight); static Common::Matrix44 cameraRotationMatrix(const Common::Vector3& tgt, const Common::Vector3& up); static Common::Matrix44 rotationMatrixFromAxisAngle(const Common::Vector3& axis, float angle); static Common::Vector3 rotateVector(const Common::Matrix44& mat, const Common::Vector3& v); static GLuint loadShader(GLenum type, const char* src); static GLuint loadShaderFromFile(GLenum type, const char* filename); static boost::shared_ptr<Common::Texture> loadTexture(const std::string& filename); static void enableDepthTest(); static void disableDepthTest(); }; } #endif <file_sep>/tests/src/SceneCube.cpp #include <stdio.h> #include <stdlib.h> #include <sstream> #include "sscene/Scene.h" #include "common/Math.h" #include "common/Clock.h" #include "common/DriverFramework.h" static int screenWidth = 800; static int screenHeight = 600; using namespace Common; class SceneCube : public Common::Driver { public: SceneCube(); virtual bool handleKeyDown(float frameTime, SDLKey key) override; virtual bool handleKeyUp(float frameTime, SDLKey key) override; virtual bool handleMouseMotion(float frameTime, const SDL_MouseMotionEvent& ev) override; virtual bool handleMousePress(float frameTime, Uint8 button) override; virtual bool prerenderUpdate(float frameTime) override; virtual void drawFrame() override; private: void handleMouseMove(float dx, float dy); Scene::Scene mScene; Scene::Camera& mCamera; float mPosStep; float mRotStep; bool mAmbientLightEnabled; bool mDirectionalLightEnabled; bool mPointLightEnabled; bool mWireframe; std::map<SDLKey, std::function<void (float)>> mControls; Common::Vector3 mOldLinePos; }; class Heightmap : public Scene::Heightmap { public: virtual float getHeightAt(float x, float y) const; virtual unsigned int getWidth() const; virtual float getXZScale() const; }; float Heightmap::getHeightAt(float x, float y) const { return 3.0f * sin(x * 0.20f) + 5.0f * cos(y * 0.10f) - 8.0f; } unsigned int Heightmap::getWidth() const { return 128; } float Heightmap::getXZScale() const { return 2.0f; } SceneCube::SceneCube() : Common::Driver(screenWidth, screenHeight, "Cube"), mScene(Scene::Scene(800, 600)), mCamera(mScene.getDefaultCamera()), mPosStep(0.1f), mRotStep(0.02f), mAmbientLightEnabled(true), mDirectionalLightEnabled(true), mPointLightEnabled(true), mWireframe(false) { mScene.init(); mControls[SDLK_UP] = [&] (float p) { mCamera.setForwardMovement(p); }; mControls[SDLK_PAGEUP] = [&] (float p) { mCamera.setUpwardsMovement(p); }; mControls[SDLK_RIGHT] = [&] (float p) { mCamera.setSidewaysMovement(p); }; mControls[SDLK_DOWN] = [&] (float p) { mCamera.setForwardMovement(-p); }; mControls[SDLK_PAGEDOWN] = [&] (float p) { mCamera.setUpwardsMovement(-p); }; mControls[SDLK_LEFT] = [&] (float p) { mCamera.setSidewaysMovement(-p); }; mCamera = mScene.getDefaultCamera(); mCamera.setPosition(Vector3(1.9f, 1.9f, 4.2f)); mCamera.rotate(Math::degreesToRadians(90), 0); handleMouseMove(0, 0); mScene.addModel("Cube", "share/textured-cube.obj"); mScene.addTexture("Snow", "share/snow.jpg"); mScene.addOverlay("Overlay", "share/overlay.png"); Heightmap hm; mScene.addModelFromHeightmap("Terrain", hm); auto mi1 = mScene.addMeshInstance("Cube1", "Cube", "Snow"); auto mi2 = mScene.addMeshInstance("Cube2", "Cube", "Snow"); mi2->setPosition(Vector3(3.0f, 3.0f, 0.0f)); mi2->setScale(2.0f, 0.6f, 1.0f); mi2->setRotationFromEuler(Vector3(Math::degreesToRadians(149), Math::degreesToRadians(150), Math::degreesToRadians(38))); auto mi3 = mScene.addMeshInstance("Terrain", "Terrain", "Snow"); mScene.addPlane("Plane", 1.0f, 1.0f, 1); auto mi4 = mScene.addMeshInstance("Plane", "Plane", "Snow"); mi4->setScale(4.0f, 1.0f, 4.0f); { std::vector<Common::Vector3> vertices = { Common::Vector3(0.0f, 0.0f, 0.0f), Common::Vector3(0.0f, 5.0f, 0.0f), Common::Vector3(0.0f, 0.0f, 5.0f), }; std::vector<Common::Vector2> texcoords = { Common::Vector2(0.0f, 0.0f), Common::Vector2(0.0f, 1.0f), Common::Vector2(1.0f, 0.0f), }; std::vector<unsigned int> indices = { 0, 1, 2 }; std::vector<Common::Vector3> normals = { Common::Vector3(1.0f, 0.0f, 0.0f), Common::Vector3(1.0f, 0.0f, 0.0f), Common::Vector3(1.0f, 0.0f, 0.0f), }; mScene.addModel("Manual", vertices, texcoords, indices, normals); auto miManual = mScene.addMeshInstance("Manual", "Manual", "Snow"); miManual->setPosition(Common::Vector3(10.0f, 10.0f, 10.0f)); } mScene.getAmbientLight().setState(mAmbientLightEnabled); mScene.getDirectionalLight().setState(mDirectionalLightEnabled); mScene.getDirectionalLight().setDirection(Vector3(1, -1, 1)); mScene.getDirectionalLight().setColor(Vector3(1, 0.8, 0.0)); mScene.getPointLight().setState(mPointLightEnabled); mScene.getPointLight().setAttenuation(Vector3(0, 0, 3)); mScene.getPointLight().setColor(Vector3(0.9, 0.2, 0.4)); mScene.enableText("share/DejaVuSans.ttf"); } bool SceneCube::handleKeyDown(float frameTime, SDLKey key) { auto it = mControls.find(key); if(it != mControls.end()) { it->second(mPosStep); } else { if(key == SDLK_ESCAPE) { return true; } else if(key == SDLK_p) { std::cout << "Up: " << mCamera.getUpVector() << "\n"; std::cout << "Target: " << mCamera.getTargetVector() << "\n"; std::cout << "Position: " << mCamera.getPosition() << "\n"; } else if(key == SDLK_F1) { mAmbientLightEnabled = !mAmbientLightEnabled; mScene.getAmbientLight().setState(mAmbientLightEnabled); } else if(key == SDLK_F2) { mDirectionalLightEnabled = !mDirectionalLightEnabled; mScene.getDirectionalLight().setState(mDirectionalLightEnabled); } else if(key == SDLK_F3) { mPointLightEnabled = !mPointLightEnabled; mScene.getPointLight().setState(mPointLightEnabled); } else if(key == SDLK_F4) { mScene.setFOV(mScene.getFOV() - 10.0f); std::cout << "FOV: " << mScene.getFOV() << "\n"; } else if(key == SDLK_F5) { mScene.setFOV(mScene.getFOV() + 10.0f); std::cout << "FOV: " << mScene.getFOV() << "\n"; } else if(key == SDLK_F6) { mScene.setOverlayEnabled("Overlay", false); } else if(key == SDLK_F7) { mScene.setOverlayEnabled("Overlay", true); unsigned int x = mCamera.getPosition().x * 100.0f; unsigned int y = mCamera.getPosition().z * 100.0f; unsigned int w = mCamera.getPosition().y * 100.0f; unsigned int h = w * 3.0f / 4.0f; std::stringstream ss; ss << "Overlay position: " << x << " " << y << " " << w << " " << h; mScene.setOverlayPosition("Overlay", x, y, w, h); mScene.addOverlayText("Overlay text", ss.str(), Common::Color(255, 127, 127), 1.0f, 0.375f, 0.083f, true); mScene.setOverlayDepth("Overlay", 0.5f); mScene.setOverlayDepth("Overlay text", -0.5f); } else if(key == SDLK_F8) { mWireframe = !mWireframe; mScene.setWireframe(mWireframe); } } return false; } bool SceneCube::handleKeyUp(float frameTime, SDLKey key) { auto it = mControls.find(key); if(it != mControls.end()) { it->second(0.0f); } return false; } bool SceneCube::handleMouseMotion(float frameTime, const SDL_MouseMotionEvent& ev) { if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(1)) { handleMouseMove(ev.xrel, ev.yrel); } return false; } bool SceneCube::handleMousePress(float frameTime, Uint8 button) { if(button == SDL_BUTTON_RIGHT) { auto newpos = mCamera.getPosition(); mScene.addLine("red line", mOldLinePos, newpos, Common::Color::Red); mOldLinePos = newpos; } else if(button == SDL_BUTTON_MIDDLE) { mScene.clearLine("red line"); } return false; } void SceneCube::handleMouseMove(float dx, float dy) { mCamera.rotate(dx * mRotStep, dy * mRotStep); } bool SceneCube::prerenderUpdate(float frameTime) { double time = Clock::getTime(); if(mAmbientLightEnabled) { float timePoint = Math::degreesToRadians(fmodl(time * 20.0f, 360)); float rvalue = 0.5f * (0.5f + 0.5f * sin(timePoint)); float gvalue = 0.5f * (0.5f + 0.5f * sin(timePoint + 2.0f * PI / 3.0f)); float bvalue = 0.5f * (0.5f + 0.5f * sin(timePoint + 4.0f * PI / 3.0f)); mScene.getAmbientLight().setColor(Color(rvalue * 255, gvalue * 255, bvalue * 255)); } if(mPointLightEnabled) { float pointLightTime = Math::degreesToRadians(fmodl(time * 80.0f, 360)); Vector3 plpos(sin(pointLightTime), 0.5f, cos(pointLightTime)); mScene.getPointLight().setPosition(plpos); } mCamera.applyMovementKeys(frameTime); return false; } void SceneCube::drawFrame() { mScene.render(); } int main(int argc, char** argv) { try { SceneCube app; app.run(); } catch(std::exception& e) { std::cerr << "std::exception: " << e.what() << "\n"; } catch(...) { std::cerr << "Unknown exception.\n"; } return 0; }
0e5e24c8e645e13746fa0316f4655290409ea01b
[ "Makefile", "C++", "Shell" ]
9
C++
anttisalonen/sscene
3e9ad245a3dbf5b6e1dc30e6587a18df13e15cb4
0ec5480a612490a796ea7967195f5c04ed1bbc38
refs/heads/master
<file_sep>''' This script can download posts and comments from public Facebook pages. It requires Python 3. INSTRUCTIONS 1. This script is written for Python 3 and won't work with previous Python versions. 2. You need to create your own Facebook app, which you can do here: https://developers.facebook.com/apps Doesn't matter what you call it, you just need to pull the unique client ID (app ID) and app secret for your new app. 3. Once you create your app, paste in the client ID and app secret into the quoted fields at lines 27 and 28 below. 4. Create a plain text file in the same folder as the script containing one or more names of Facebook pages you want to scrape, one per line. This will only work for public pages. For example, if you wanted to scrape Barack Obama's official FB page (http://facebook.com/barackobama/), your first line would simply be 'barackobama' without quotes. I suggest starting with only one page to make sure it works. 5. Enter the filename of the text file containing your FB page names into the quoted field at line 26 below. (It doesn't have to be a csv but it does need to be plain text.) 6. Change the name of your output file at line 29 if you like. 7. Now you should be able to run the script from the Python command line. You can use the following command: exec(open('fb_scrape_public.py').read()) 8. If you did everything correctly, the command line should show you some informative status messages. Eventually it will save a CSV full of data to the same folder where this script was run. If something went wrong, you'll see an error. 9. You can download public Facebook page comments by loading a plain text list of post IDs instead of Facebook page names. The IDs can be from different pages. ''' import copy import csv import json import socket import time import urllib.request socket.setdefaulttimeout(30) id_file = 'filename.csv' #change to your input filename clientid = 'client_id_here' #replace with actual client id clientsecret = 'client_secret_here' #replace with actual client secret outfile = 'fb_page_posts.csv' #change the output filename if you like def load_data(data,enc='utf-8'): if type(data) is str: csv_data = [] with open(data,'r',encoding = enc,errors = 'replace') as f: reader = csv.reader((line.replace('\0','') for line in f)) #remove NULL bytes for row in reader: if row != []: csv_data.append(row) return csv_data else: return copy.deepcopy(data) def save_csv(filename,data,quotes_flag='',file_mode='w',enc='utf-8'): #this assumes a list of lists wherein the second-level list items contain no commas with open(filename,file_mode,encoding = enc) as out: for line in data: if quotes_flag.upper() == "USE_QUOTES": row = '"' + '","'.join([str(i).replace('"',"'") for i in line]) + '"' + "\n" else: row = ','.join([str(i) for i in line]) + "\n" out.write(row) def url_retry(url): succ = 0 while succ == 0: try: json_out = json.loads(urllib.request.urlopen(url).read().decode(encoding="utf-8")) succ = 1 except(urllib.error.HTTPError, socket.timeout) as e: print(str(e)) time.sleep(1) return json_out def optional_field(dict_item,dict_key): try: out = dict_item[dict_key] if dict_key == 'shares': out = dict_item[dict_key]['count'] except KeyError: out = '' return out def make_csv_chunk(fb_json_page,scrape_mode,thread_starter='',msg=''): csv_chunk = [] if scrape_mode == 'posts': for line in fb_json_page['data']: csv_line = [line['from']['name'], \ '_' + line['from']['id'], \ optional_field(line,'message'), \ optional_field(line,'picture'), \ optional_field(line,'link'), \ optional_field(line,'name'), \ optional_field(line,'description'), \ line['type'], \ line['created_time'], \ optional_field(line,'shares'), \ line['id']] csv_chunk.append(csv_line) if scrape_mode == 'comments': for line in fb_json_page['data']: csv_line = [line['from']['name'], \ '_' + line['from']['id'], \ optional_field(line,'message'), \ line['created_time'], \ optional_field(line,'like_count'), \ line['id'], \ thread_starter, \ msg] csv_chunk.append(csv_line) return csv_chunk time1 = time.time() fb_urlobj = urllib.request.urlopen('https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=' + clientid + '&client_secret=' + clientsecret) fb_token = fb_urlobj.read().decode(encoding="latin1") fb_ids = [i[0].strip() for i in load_data(id_file)] csv_data = [] for x,fid in enumerate(fb_ids): if '_' in fid: scrape_mode = 'comments' msg_url = 'https://graph.facebook.com/v2.3/' + fid + '?' + fb_token msg_json = url_retry(msg_url) msg_user = msg_json['from']['name'] msg_content = optional_field(msg_json,'message') else: scrape_mode = 'posts' msg_user = '' msg_content = '' data_url = 'https://graph.facebook.com/v2.3/' + fid + '/' + scrape_mode + '?limit=100&' + fb_token next_item = url_retry(data_url) csv_data = csv_data + make_csv_chunk(next_item,scrape_mode,msg_user,msg_content) n = 0 while 'paging' in next_item and 'next' in next_item['paging']: next_item = url_retry(next_item['paging']['next']) csv_data = csv_data + make_csv_chunk(next_item,scrape_mode,msg_user,msg_content) try: print(n,next_item['data'][len(next_item['data'])-1]['created_time'],time.time()-time1,'seconds elapsed') except IndexError: break n += 1 time.sleep(1) if x % 100 == 0: print(x+1,'Facebook IDs archived.') save_csv(outfile,csv_data,'USE_QUOTES') print('Script completed in',time.time()-time1,'seconds.')
6e74dd574806fc0cb4365679cd4543c1d2da08b2
[ "Python" ]
1
Python
ivofurman/fb_scrape_public
a8d59e15e783be7624cdd78a958eaa4039563869
0c95a98db847add0492a2b967349a2d4ab556e45
refs/heads/master
<repo_name>dyakonoff/dash-clinic<file_sep>/modules/web/src/com/haulmont/sample/petclinic/web/widgets/FlyingPikachuWidgetEditor.java package com.haulmont.sample.petclinic.web.widgets; import com.haulmont.addon.dashboard.web.annotation.WidgetParam; import com.haulmont.cuba.gui.WindowParam; import com.haulmont.cuba.gui.components.HasValue; import com.haulmont.cuba.gui.components.LookupField; import com.haulmont.cuba.gui.screen.ScreenFragment; import com.haulmont.cuba.gui.screen.Subscribe; import com.haulmont.cuba.gui.screen.UiController; import com.haulmont.cuba.gui.screen.UiDescriptor; import com.haulmont.sample.petclinic.web.widgets.helper.PokemonArtsEnumerator; import javax.inject.Inject; import java.text.Collator; import java.util.ArrayList; import java.util.List; import java.util.Map; @UiController("petclinic_FlyingPikachuWidgetEditor") @UiDescriptor("flying-pikachu-widget-editor.xml") public class FlyingPikachuWidgetEditor extends ScreenFragment { @Inject private LookupField artLookup; @WindowParam @WidgetParam protected String petName; @WindowParam @WidgetParam protected String petArtResource; @Inject private PokemonArtsEnumerator pokemonArtsEnumerator; private final static String DEFAULT_ART = "pikachu_art.png"; @Subscribe private void onInit(InitEvent event) { Map<String, String> resourcesMap = pokemonArtsEnumerator.getArts(); List<String> optionsList = new ArrayList<>(resourcesMap.keySet()); optionsList.sort(Collator.getInstance()); artLookup.setOptionsList(optionsList); } @Subscribe("artLookup") private void onArtLookupValueChange(HasValue.ValueChangeEvent event) { String selectedName = (String) event.getValue(); if (selectedName != null) { petName = selectedName; petArtResource = pokemonArtsEnumerator.getArts().getOrDefault(selectedName, DEFAULT_ART); } } }
80f1bc6720c6433777fe644559eb8c4d81338c2e
[ "Java" ]
1
Java
dyakonoff/dash-clinic
875e3b472c6053a009a277d3f4dd8395bdb15b44
6819f997371e1063589746192e2c34bd487f963d
refs/heads/master
<repo_name>marissa-shaffer/node-api2-guided<file_sep>/index.js const express = require("express") const usersRouter = require("./users/users-router") const welcomeRouter = require("./welcome/welcome-router") const server = express() const port = 4000 server.use(express.json()) server.use(usersRouter) // create endpoint that returns all the posts for a user // create endpoint for adding a new post for a user server.listen(port, () => { console.log(`Server running at http://localhost:${port}`) })
388cb78df46a51ed8c8647538c4a06f633f61c75
[ "JavaScript" ]
1
JavaScript
marissa-shaffer/node-api2-guided
ade6dafdb99d752cf36fd2515847fcf74731dee1
bf76beb0640ffe7d0a7dacbd73148e76e75df4ba
refs/heads/master
<repo_name>Habashi94/NC-News<file_sep>/controllers/comment-controller.js const { updateCommentById, removeCommentById } = require("../models/comment-model"); exports.patchCommentById = (req, res, next) => { updateCommentById(req.params, req.body) .then(comment => { res.status(200).send({ comment }); }) .catch(next); }; exports.deleteCommentById = (req, res, next) => { removeCommentById(req.params) .then(() => { res.sendStatus(204); }) .catch(next); }; <file_sep>/spec/server.spec.js process.env.NODE_ENV = "test"; const chai = require("chai"); chai.use(require("sams-chai-sorted")); const { expect } = chai; const request = require("supertest"); const server = require("../server"); const connection = require("../db/connection"); describe("/api", () => { beforeEach(() => connection.seed.run()); after(() => connection.destroy()); describe("/topics", () => { it("GET: 200 responds with the status code of 200", () => { return request(server) .get("/api/topics") .expect(200); }); it("GET: 200 returns all the topics", () => { return request(server) .get("/api/topics") .expect(200) .then(response => { // console.log(response.body); expect(response.body.topics[0]).to.have.keys(["slug", "description"]); }); }); it("GET 404 sends error message when path in non existent", () => { return request(server) .get("/api/topic") .expect(404) .then(response => { expect(response.body.msg).to.equal("Not Found"); }); }); }); describe("/users", () => { it("GET: 200 responds with the status code of 200", () => { return request(server) .get("/api/users/lurker") .expect(200); }); it("Get: 200 responds with the status code of 200 and the user selected by their username", () => { return request(server) .get("/api/users/lurker") .expect(200) .then(response => { expect(response.body.user.username).to.equal("lurker"); expect(response.body.user).to.have.keys([ "username", "avatar_url", "name" ]); }); }); }); describe("errors /users", () => { it("GET 404 sends error message when username is non-existent ", () => { return request(server) .get("/api/users/gvhgvhg") .expect(404) .then(response => { expect(response.body.msg).to.equal("Username does not exist"); }); }); }); describe("/articles/:article_id", () => { it("GET 200 responds with status code of 200 and a new comment count key added to the article object", () => { return request(server) .get("/api/articles/1/") .expect(200) .then(response => { expect(response.body.article.article_id).to.equal(1); expect(response.body.article).to.have.keys([ "author", "title", "article_id", "body", "topic", "created_at", "votes", "comment_count" ]); }); }); it("GET : 404 responds with error message when id is non existent", () => { return request(server) .get("/api/articles/400") .expect(404) .then(response => { expect(response.body.msg).to.equal("Id does not exist"); }); }); it("GET : 400 responds with error message when id is out of range", () => { return request(server) .get("/api/articles/400000000000") .expect(400) .then(response => { expect(response.body.msg).to.equal("Data inputted out of range!"); }); }); it("GET 400 responds with error message when given invalid id data type", () => { return request(server) .get("/api/articles/helooooo") .expect(400) .then(response => { expect(response.body.msg).to.equal("Invalid data type inserted"); }); }); it("PATCH : 200 responds with the status code 200 and updates the specific article that amends the votes ", () => { return request(server) .patch("/api/articles/1") .send({ inc_votes: -50 }) .expect(200) .then(response => { expect(response.body.article.votes).to.equal(50); }); }); it("PATCH/ 400 responds with error message when invalid data type is inserted ", () => { return request(server) .patch("/api/articles/1") .send({ inc_votes: "sdsdf" }) .expect(400) .then(response => { expect(response.body.msg).to.equal("Invalid data type inserted"); }); }); it("PATCH/ 400 responds with error message when extra object added to the object", () => { return request(server) .patch("/api/articles/1") .send({ inc_votes: 1, name: "Mitch" }) .expect(400) .then(response => { console.log(response.body); expect(response.body.msg).to.equal("Body provided is invalid"); }); }); it("PATCH/ 404 responds with error message when given non-existent Id", () => { return request(server) .patch("/api/articles/199") .send({ inc_votes: -50 }) .expect(404) .then(response => { expect(response.body.msg).to.equal("Id does not exist"); }); }); }); describe("/articles/:article_id/comments", () => { it("POST/ 201 responds with the status code 201 and creates a new comment", () => { return request(server) .post("/api/articles/1/comments") .send({ username: "butter_bridge", body: "I hate this article overrated" }) .expect(201) .then(response => { expect(response.body.comment).to.have.keys([ "comment_id", "author", "article_id", "votes", "created_at", "body" ]); expect(response.body.comment.body).to.equal( "I hate this article overrated" ); }); }); it("POST/ 422 responds with status code 400 when given non-existent article id", () => { return request(server) .post("/api/articles/2000/comments") .send({ username: "lurker", body: "I hate this article overrated" }) .expect(422) .then(response => { expect(response.body.msg).to.equal( "No reference to data in database" ); }); }); it("POST/ 422 responds with status code 400 when given non-existent username", () => { return request(server) .post("/api/articles/1/comments") .send({ username: "mustafa", body: "I hate this article overrated" }) .expect(422) .then(response => { expect(response.body.msg).to.equal( "No reference to data in database" ); }); }); it("POST/ 400 responds with status code 400 when given no data to add", () => { return request(server) .post("/api/articles/1/comments") .send({}) .expect(400) .then(response => { expect(response.body.msg).to.equal("No data provided"); }); }); it("GET: 200 responds with the article with specific id ", () => { return request(server) .get("/api/articles/1/comments") .expect(200) .then(response => { expect(response.body.comments[0]).to.contain.keys([ "comment_id", "votes", "created_at", "author", "body" ]); }); }); it("GET: 200 responds with empty array when no comment exists for the specific Id but articles exists", () => { return request(server) .get("/api/articles/2/comments") .expect(200) .then(response => { expect(response.body.comments).to.deep.equal([]); }); }); it("GET: 200 responds with empty array when no comment exists for the specific Id but articles exists", () => { return request(server) .get("/api/articles/1000/comments") .expect(404) .then(response => { expect(response.body.msg).to.equal("article does not exist"); }); }); }); describe("/:article_id/comments ---> queries", () => { it("GET : 200 responds with the code 200 and sorts the comments by username zedabetically", () => { return request(server) .get("/api/articles/1/comments?sort_by=author") .then(response => { expect(response.body.comments).to.be.sortedBy("author", { descending: true }); }); }); it("GET : 400 responds with status code 400 and an error message when given invalid column for query ", () => { return request(server) .get("/api/articles/1/comments?sort_by=autho") .expect(400) .then(response => { expect(response.body.msg).to.equal("Invalid column provided"); }); }); it("GET: 200 responds with status code 200 when comments are ordered by votes in descending order", () => { return request(server) .get("/api/articles/1/comments?sort_by=votes&order=desc") .expect(200) .then(response => { expect(response.body.comments).to.be.sortedBy("votes", { descending: true }); }); }); it("GET: 400 responds with status code 400 when incorrect order is requested (not asc/desc)", () => { return request(server) .get("/api/articles/1/comments?sort_by=author&order=acsss") .expect(400) .then(response => { expect(response.body.msg).to.equal("Invalid order requested"); }); }); it("GET: 400 responds with status code 400 when incorrect order is requested (not asc/desc)", () => { return request(server) .get("/api/articles/1/comments?sort_by=author&order=deas") .expect(400) .then(response => { expect(response.body.msg).to.equal("Invalid order requested"); }); }); }); describe("/api/articles", () => { it("GET: 200 responds with an array of articles with the amount of comments included", () => { return request(server) .get("/api/articles") .expect(200) .then(response => { expect(response.body.articles[0]).to.have.keys([ "author", "title", "article_id", "topic", "created_at", "votes", "comment_count" ]); }); }); it("GET : 200 responds with the code 200 and sorts the articles by topics zedabetically", () => { return request(server) .get("/api/articles?sort_by=topic") .expect(200) .then(response => { expect(response.body.articles).to.be.sortedBy("topic", { descending: true }); }); }); it("GET : 200 responds with the code 200 and sorts the articles by comment_count in ascending order", () => { return request(server) .get("/api/articles?sort_by=comment_count&order=asc") .expect(200) .then(response => { expect(response.body.articles).to.be.sortedBy("comment_count", { descending: false }); }); }); it("GET : 200 responds with the code 200 and sorts the articles by votes in descending order", () => { return request(server) .get("/api/articles?sort_by=votes&order=desc") .expect(200) .then(response => { expect(response.body.articles).to.be.sortedBy("votes", { descending: true }); }); }); it("GET : 200 responds with the code 200 and filters the articles by specific topic that is queried", () => { return request(server) .get("/api/articles?topic=cats") .expect(200) .then(response => { const arrayOfArticles = response.body.articles; arrayOfArticles.every(article => expect(article.topic).to.equal("cats") ); }); }); it("GET : 200 responds with the code 200 and filters the articles by the specified username requested", () => { return request(server) .get("/api/articles?author=icellusedkars") .expect(200) .then(response => { const arrayOfArticles = response.body.articles; arrayOfArticles.every(article => expect(article.author).to.equal("icellusedkars") ); }); }); it("GET: 400 responds with status code 400 when incorrect column name/does not exist in query", () => { return request(server) .get("/api/articles?sort_by=topik") .expect(400) .then(response => { expect(response.body.msg).to.equal("Invalid column provided"); }); }); it("GET: 400 responds with status code 400 when incorrect order is requested (not asc/desc)", () => { return request(server) .get("/api/articles?sort_by=topic&order=acse") .expect(400) .then(response => { expect(response.body.msg).to.equal("Invalid order requested"); }); }); it("GET: 404 responds with status code 404 when a author does not exist in the database", () => { return request(server) .get("/api/articles?author=mustafa") .expect(404) .then(response => { expect(response.body.msg).to.equal("Author does not exist"); }); }); it("GET: 404 responds with status code 404 when a topic does not exist in the database", () => { return request(server) .get("/api/articles?topic=dogs") .expect(404) .then(response => { console.log(response.body); expect(response.body.msg).to.equal("Topic does not exist"); }); }); it("GET: 200 responds with the status code 200 and empty array when username exists but is not linked to any articles", () => { return request(server) .get("/api/articles?author=lurker") .expect(200) .then(response => { expect(response.body.articles).to.eql([]); }); }); it("GET:200 responds with the status code 200 and empty array when topic exists but is not linked to any articles", () => { return request(server) .get("/api/articles?topic=paper") .expect(200) .then(response => { expect(response.body.articles).to.eql([]); }); }); it("GET: 200 responds with the status code 200 and empty array when topic and author exists but is not linked to any articles", () => { return request(server) .get("/api/articles?topic=cats&author=icellusedkars") .expect(200) .then(response => { expect(response.body.articles).to.eql([]); }); }); }); describe("/comments/:comment_id", () => { it.only("PATCH: 200 responds with status code 200 and updates the votes value by increasing the increment", () => { return request(server) .patch("/api/comments/1") .send({ inc_votes: 1 }) .expect(200) .then(response => { console.log(response.body); expect(response.body.comment).to.be.an("object"); expect(response.body.comment.votes).to.equal(17); }); }); it("PATCH: 200 responds with status code 200 and updates the votes value by decreasing the increment", () => { return request(server) .patch("/api/comments/1") .send({ inc_votes: -6 }) .expect(200) .then(response => { expect(response.body.comment).to.be.an("object"); expect(response.body.comment.votes).to.equal(10); }); }); it("PATCH: 404 responds with status code 404 when id does not exists", () => { return request(server) .patch("/api/comments/100") .send({ inc_votes: -6 }) .expect(404) .then(response => { expect(response.body.msg).to.equal("Id does not exist"); }); }); it("PATCH 400 responds with error message when given invalid id data type", () => { return request(server) .patch("/api/comments/helooooo") .send({ inc_votes: -6 }) .expect(400) .then(response => { expect(response.body.msg).to.equal("Invalid data type inserted"); }); }); it("PATCH/ 400 responds with error message when invalid data type is inserted ", () => { return request(server) .patch("/api/comments/1") .send({ inc_votes: "one" }) .expect(400) .then(response => { expect(response.body.msg).to.equal("Invalid data type inserted"); }); }); // it("PATCH/ 400 responds with error message when extra object added to the object", () => { // return request(server) // .patch("/api/comments/1") // .send({ inc_votes: 1, name: "Mustafa" }) // .expect(400) // .then(response => { // console.log(response.body); // expect(response.body.msg).to.equal("Body provided is invalid"); // }); // }); // it("PATCH/ 400 responds with error message when object key sent is incorrect", () => { // return request(server) // .patch("/api/comments/1") // .send({ ic_ves: 1 }) // .expect(400) // .then(response => { // console.log(response.body); // expect(response.body.msg).to.equal("Body provided is invalid"); // }); // }); it("PATCH/ 200 responds with nothing update when no data is provided ", () => { return request(server) .patch("/api/comments/2") .send({}) .expect(200) .then(response => { console.log(response.body); expect(response.body.comment).to.have.keys([ "comment_id", "author", "article_id", "votes", "created_at", "body" ]); }); }); it("DELETE: 204 responds with status code 204 and removes the specific comment and responds with no body", () => { return request(server) .delete("/api/comments/2") .expect(204); }); it("DELETE: 404 responds with error message when id is non-existent", () => { return request(server) .delete("/api/comments/999") .expect(404) .then(response => { expect(response.body.msg).to.equal("Id does not exist"); }); }); it("DELETE: 400 responds with error message when id is given as invalid data type", () => { return request(server) .delete("/api/comments/hi") .expect(400) .then(response => { expect(response.body.msg).to.equal("Invalid data type inserted"); }); }); }); describe("/Invalid Methods ", () => { it("responds with 405 when invalid method for route is requested", () => { const invalidMethods = ["patch", "put", "delete"]; const methodPromises = invalidMethods.map(method => { return request(server) [method]("/api/topics") .expect(405) .then(({ body: { msg } }) => { expect(msg).to.equal("Method not allowed"); }); }); return Promise.all(methodPromises); }); it("responds with status code 405 when invalid method for route is requested", () => { const invalidMethods = ["patch", "put", "delete"]; const methodPromises = invalidMethods.map(method => { return request(server) [method]("/api/articles") .expect(405) .then(({ body: { msg } }) => { expect(msg).to.equal("Method not allowed"); }); }); return Promise.all(methodPromises); }); it("responds with status code 405 when invalid method for posting a article is requested", () => { return request(server) .post("/api/articles/1") .expect(405) .then(response => { expect(response.body.msg).to.equal("Method not allowed"); }); }); it("responds with status code 405 when invalid method for a comment is requested", () => { return request(server) .put("/api/comments/1") .expect(405) .then(response => { expect(response.body.msg).to.equal("Method not allowed"); }); }); it("responds with status code 405 when invalid method for users route is requested", () => { return request(server) .put("/api/users/butter_bridge") .expect(405) .then(response => { expect(response.body.msg).to.equal("Method not allowed"); }); }); it("responds with status code 405 when invalid method for specfic route is requested", () => { return request(server) .put("/api/articles/1/comments") .expect(405) .then(response => { expect(response.body.msg).to.equal("Method not allowed"); }); }); it("responds with status code 405 when invalid method for route is requested", () => { return request(server) .delete("/api") .expect(405) .then(response => { expect(response.body.msg).to.equal("Method not allowed"); }); }); }); de }); <file_sep>/controllers/user-controller.js const { selectUserByUsername, selectUsers } = require("../models/user-model"); exports.getUserByUsername = (req, res, next) => { selectUserByUsername(req.params) .then(user => { res.status(200).send({ user }); }) .catch(function(err) { next(err); }); }; exports.getUsers = (req, res, next) => { selectUsers().then(users => { res.status(200).send({ users }); }); }; <file_sep>/endpoints.js const endPoints = { "GET /api": { description: "serves up a json representation of all the available endpoints of the api" }, "GET /api/topics": { description: "serves an array of all topics", queries: [], exampleResponse: { topics: [ { slug: "football", description: "Footie!" } ] } }, "GET /api/articles": { description: "serves an array of all topics", queries: ["author", "topic", "sort_by", "order"], exampleResponse: { articles: [ { article_id: 13, title: "Seafood substitutions are increasing", topic: "cooking", author: "weegembump", created_at: "2018-05-30T15:59:13.341Z", comment_count: 7, votes: 4 } ] } }, "GET /api/users": { description: "serves an array of all users", queries: [], exampleResponse: { users: [ { username: "this_is_a_username", avatar_url: "https://www.healthytherapies.com/wp-content/uploads/2016/06/Lime3.jpg", name: "northcoders_shaq" } ] } }, "GET /api/users/:username": { description: "serves an object for an user for the specified username", queries: [], exampleResponse: { user: { username: "grumpy19", avatar_url: "https://www.tumbit.com/profile-image/4/original/mr-grumpy.jpg", name: "<NAME>" } } }, "GET /api/articles/:article_id": { description: "serves an object for an article for the specified article_id", queries: ["article_id"], exampleResponse: { article: { article_id: 1, title: "Running a Node App", body: "This is part two of a series on how to get up and running with Systemd and Node.js. This part dives deeper into how to successfully run your app with systemd long-term, and how to set it up in a production environment.", votes: 0, topic: "coding", author: "jessjelly", created_at: "2016-08-18T12:07:52.389Z", comment_count: 8 } } }, "PATCH /api/articles/:article_id": { description: "serves an object for an article for the specified article_id with the votes property updated", queries: [], body: { inc_votes: 10 }, exampleResponse: { article: { article_id: 2, title: "The Rise Of Thinking Machines: How IBM's Watson Takes On The World", body: "Many people know Watson as the IBM-developed cognitive super computer that won the Jeopardy! gameshow in 2011. In truth, Watson is not actually a computer but a set of algorithms and APIs, and since winning TV fame (and a $1 million prize) IBM has put it to use tackling tough problems in every industry from healthcare to finance.", votes: 10, topic: "coding", author: "jessjelly", created_at: "2017-07-20T20:57:53.256Z", comment_count: 6 } } }, "POST /api/articles/:article_id/comments": { description: "serves an object of the posted comment for the specified article_id", queries: [], body: { username: "northcoder", body: "I feel ill" }, exampleResponse: { comment: { comment_id: 57, author: "northcoders", article_id: 77, votes: 0, created_at: "2007-11-25T12: 36: 03.389Z", body: "I feel ill" } } }, "GET /api/articles/:article_id/comments": { description: "serves an array of comments for the specified article_id", queries: ["sort_by", "order"], exampleResponse: { comment: [ { comment_id: 44, votes: 4, created_at: "2017-11-20T08:58:48.322Z", author: "grumpy19", body: "Error est qui id corrupti et quod enim accusantium minus. Deleniti quae ea magni officiis et qui suscipit non." } ] } }, "PATCH /api/comments/:comment_id": { description: "serves an object for a comment for the specified comment_id with votes value been updated", queries: [], body: { inc_votes: 1 }, exampleResponse: { comment: { comment_id: 1, author: "butter_bridge", article_id: 9, votes: 17, created_at: "2017-11-22T12: 36: 03.389Z", body: "Oh, I've got compassion running out of my nose, pal! I'm the Sultan of Sentiment!" } } }, "DELETE /api/comments/:comment_id": { description: "nothing served with comment deleted for the specified comment_id" } }; module.exports = endPoints; <file_sep>/models/comment-model.js const connection = require("../db/connection"); exports.updateCommentById = ({ comment_id }, votesBody) => { // if ( // votesBody.hasOwnProperty("inc_votes") && // Object.keys(votesBody).length === 1 // ) { return connection("comments") .where("comment_id", comment_id) .increment("votes", votesBody.inc_votes || 0) .returning("*") .then(updatedComment => { if (updatedComment.length === 0) { return Promise.reject({ msg: "Id does not exist", status: 404 }); } return updatedComment[0]; }); // } else { // return Promise.reject({ msg: "Body provided is invalid", status: 400 }); // } }; exports.removeCommentById = ({ comment_id }) => { return connection("comments") .where("comment_id", comment_id) .del() .then(deleteCount => { if (!deleteCount) { return Promise.reject({ status: 404, msg: "Id does not exist" }); } }); }; <file_sep>/models/user-model.js const connection = require("../db/connection"); exports.selectUserByUsername = ({ username }) => { return connection("users") .select("*") .where("username", username) .then(userResponse => { if (userResponse.length === 0) { return Promise.reject({ msg: "Username does not exist", status: 404 }); } return userResponse[0]; }); }; exports.selectUsers = () => { return connection("users") .select("*") .then(userResponse => { return userResponse; }); }; <file_sep>/server.js const express = require("express"); const server = express(); const apiRouter = require("./routers/api-router"); server.use(express.json()); const cors = require("cors"); server.use(cors()); server.use("/api", apiRouter); server.use((err, req, res, next) => { console.log(err, "in error handler"); const errCodes = { "22P02": { msg: "Invalid data type inserted", status: 400 }, "23503": { msg: "No reference to data in database", status: 422 }, "23502": { msg: "No data provided", status: 400 }, "42703": { msg: "Invalid column provided", status: 400 }, "22003": { msg: "Data inputted out of range!", status: 400 } }; if (err.msg) { res.status(err.status).send({ msg: err.msg }); } else { res.status(errCodes[err.code].status).send({ msg: errCodes[err.code].msg }); } }); module.exports = server;
6844393f84ff08577b7dff1ab413eb428b3dd56f
[ "JavaScript" ]
7
JavaScript
Habashi94/NC-News
3160d2dd0fba562c137f3803d99dce532bdf515f
930f406a7b256e567e2a1ea7496172cdb96e64bb
refs/heads/master
<repo_name>RCiesielczuk/backpack-ios<file_sep>/Example/Backpack/Views/CollectionView Cells/IconsPreviewCollectionViewCell.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit import Backpack class IconsPreviewCollectionViewCell: UICollectionViewCell { var size: BPKIconSize? { didSet { imageView.size = size ?? BPKIconSize.large } } var icon: BPKIconName? { didSet { imageView.iconName = icon } } private let imageView: BPKIconView override init(frame: CGRect) { self.imageView = BPKIconView(iconName: nil, size: .large) super.init(frame: frame) self.setup() } required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } public static func estimatedSize() -> CGSize { return BPKIcon.concreteSize(forSize: .large) } // MARK: private private func setup() { contentView.addSubview(imageView) imageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ imageView.widthAnchor.constraint(equalToConstant: BPKIcon.concreteSize(forSize: .large).width), imageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), imageView.topAnchor.constraint(greaterThanOrEqualTo: contentView.topAnchor, constant: BPKSpacingSm), contentView.bottomAnchor.constraint(greaterThanOrEqualTo: imageView.bottomAnchor, constant: BPKSpacingSm) ]) } } <file_sep>/Example/Backpack/View Controllers/CalendarSelectorViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit import Backpack enum CalendarSegueIdentifier: String { case `default` = "Default" case withMaxEnabledDate = "WithMaxEnabledDate" case withCustomStyles = "WithCustomStyles" } class CalendarSelectorViewController: UITableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let target = segue.destination as? CalendarViewController else { fatalError("Expected destination to be of type CalendarViewController.") } if let identifier = segue.identifier, let calendarSegueIdentifier = CalendarSegueIdentifier(rawValue: identifier) { switch calendarSegueIdentifier { case .default: target.title = "Default" case .withMaxEnabledDate: target.title = "Max enabled date" target.maxEnabledDate = true case .withCustomStyles: target.title = "Custom Styles for specific dates" target.customStylesForDates = true } } else { fatalError("Unknown segue identifer \(segue.identifier.debugDescription)") } } } <file_sep>/Example/Backpack/View Controllers/DialogSelectorViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit // swiftlint:disable cyclomatic_complexity class DialogSelectorViewController: UITableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let destinationController = segue.destination as? DialogViewController else { fatalError(""" The destination of all seguesf in `DialogSelectorViewController` should be `DialogViewController` """) } switch segue.identifier { case "ShowCTA": destinationController.type = .normal destinationController.title = "With call to action" case "ShowWarning": destinationController.type = .warning destinationController.title = "Warning" case "ShowDelete": destinationController.type = .delete destinationController.title = "Delete confirmation" case "ShowSuccess": destinationController.type = .confirmation destinationController.title = "Success" case "ShowNoIcon": destinationController.type = .noIcon destinationController.title = "No icon" case "ShowNoTitle": destinationController.type = .noTitle destinationController.title = "No title" case "ShowNoIconNoTitle": destinationController.type = .noIconNoTitle destinationController.title = "No icon and no title" case "Extreme": destinationController.type = .extreme destinationController.title = "Extreme" case "InAppMessaging": destinationController.type = .inAppMessaging destinationController.title = "In-app messaging" default: fatalError("Unrecognized segue \(segue.identifier.debugDescription)") } } } <file_sep>/Example/Backpack/View Controllers/GradientSelectorTableViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit class GradientSelectorTableViewController: UITableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? GradientViewController { switch segue.identifier { case "ShowBaselineScrim": destination.gradientType = .baselineScrim destination.title = "Baseline Scrim" default: assert( false, "Unknown segue identifier for `GradientSelectorTableViewController`:" + "`\(String(describing: segue.identifier))`" ) } } } } <file_sep>/Example/Backpack/View Controllers/ToastSelectorViewController.swift // /* * Backpack - Skyscanner's Design System * * Copyright © 2019 Skyscanner Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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. */ import UIKit class ToastSelectorViewController: UITableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let destinationController = segue.destination as? ToastViewController else { fatalError(""" The destination of all seguesf in `DialogSelectorViewController` should be `DialogViewController` """) } switch segue.identifier { case "Default": destinationController.type = .defaultToast destinationController.title = "Default Toast" case "OnlyLabels": destinationController.type = .onlyLabels destinationController.title = "Only Labels Toast" default: fatalError("Unrecognized segue \(segue.identifier.debugDescription)") } } } <file_sep>/Example/Backpack/View Controllers/LabelsSelectorTableViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit class LabelsSelectorTableViewController: UITableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let maybeLabelsController = segue.destination as? LabelsViewController switch segue.identifier { case "ShowNormal": segue.destination.title = "Default" maybeLabelsController?.type = .normal case "ShowEmphasized": segue.destination.title = "Emphasized" maybeLabelsController?.type = .emphasized case "ShowHeavy": segue.destination.title = "Heavy" maybeLabelsController?.type = .heavy case "ShowPerformance": segue.destination.title = "Performance" case "MultipleFontStyles": segue.destination.title = "Multiple font styles" default: fatalError("Unknown segue identifer \(segue.identifier.debugDescription)") } } } <file_sep>/Example/Backpack/View Controllers/IconsViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit import Backpack class IconsViewController: UICollectionViewController { fileprivate static var iconList = Array(BPKIcon.iconMapping!.keys).map({ $0.rawValue }).sorted() fileprivate static var largeIconList = iconList.filter({ !$0.hasSuffix("-sm") }) fileprivate static var smallIconList = iconList.filter({ $0.hasSuffix("-sm") }) fileprivate static var icons = [ (heading: "Large icons", size: BPKIconSize.large, icons: largeIconList), (heading: "Small icons", size: BPKIconSize.small, icons: smallIconList) ] fileprivate static let cellIdentifier = "IconsPreviewCollectionViewCell" fileprivate static let headerIdentifier = "PreviewCollectionViewHeader" override func viewDidLoad() { collectionView?.register( IconsPreviewCollectionViewCell.self, forCellWithReuseIdentifier: IconsViewController.cellIdentifier ) #if swift(>=4.2) collectionView?.register( PreviewCollectionViewHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: IconsViewController.headerIdentifier ) #else collectionView?.register( PreviewCollectionViewHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: IconsViewController.headerIdentifier ) #endif collectionView?.delegate = self collectionView?.dataSource = self guard let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout else { fatalError("IconsViewController collectionView must be using UICollectionViewFlowLayout") } collectionView?.contentInset = UIEdgeInsets( top: BPKSpacingBase, left: BPKSpacingBase, bottom: BPKSpacingBase, right: BPKSpacingBase ) layout.estimatedItemSize = IconsPreviewCollectionViewCell.estimatedSize() } } extension IconsViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { return IconsViewController.icons.count } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return IconsViewController.icons[section].icons.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: IconsViewController.cellIdentifier, for: indexPath) as? IconsPreviewCollectionViewCell else { fatalError("No cell registered for reuse with identifier \(IconsViewController.cellIdentifier)") } let iconSet = IconsViewController.icons[indexPath.section] // Whether we set `size` or `icon` first, we will potentially be trying to use an icon that doesn't exist. // By setting the icon to `accessibility`, then setting the size, and then setting the iconName, we should // never be trying to use an icon at an unavailable size. cell.icon = BPKIconName.accessibility cell.size = iconSet.size var icon = iconSet.icons[indexPath.row] if icon.hasSuffix("-sm") { icon.removeLast(3) } cell.icon = BPKIconName(icon) return cell } override func collectionView( _ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath ) -> UICollectionReusableView { #if swift(>=4.2) let isExpectedHeader = kind == UICollectionView.elementKindSectionHeader #else let isExpectedHeader = kind == UICollectionElementKindSectionHeader #endif if isExpectedHeader { guard let headerView = collectionView.dequeueReusableSupplementaryView( ofKind: kind, withReuseIdentifier: IconsViewController.headerIdentifier, for: indexPath ) as? PreviewCollectionViewHeader else { fatalError("Icon View Headers are expected to be of type ColorPreviewCollectionViewHeader") } headerView.name = IconsViewController.icons[indexPath.section].heading return headerView } fatalError("Headers are the only supplimental elements available") } } extension IconsViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return PreviewCollectionViewHeader.referenceSize( collectionView: collectionView, text: IconsViewController.icons[section].heading ) } } <file_sep>/Example/Backpack/View Controllers/CardsSelectorViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import Backpack.Card import Backpack.BPKColor class CardsSelectorViewController: UITableViewController { func prepareDevided(for segue: UIStoryboardSegue, sender: Any?) { guard let target = segue.destination as? DividedCardsViewController else { fatalError("Expected destination to be of type DividedCardsViewController.") } switch segue.identifier { case "divided_horizontal": target.navigationItem.title = "With divider" target.divisionDirection = .horizontal case "divided_horizontal_corner_style_large": target.navigationItem.title = "With divider and Corner style large" target.divisionDirection = .horizontal target.cornerStyle = .large case "divided_vertical": target.navigationItem.title = "With divider arranged vertically" target.divisionDirection = .vertical case "divided_vertical_no_padding": target.navigationItem.title = "With divider, without padding" target.divisionDirection = .vertical target.padded = false default: fatalError("The identifier \(segue.identifier.debugDescription) does not " + "match an example DividedCard configuration.") } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier?.contains("divided") ?? false { prepareDevided(for: segue, sender: sender) return } guard let target = segue.destination as? CardsViewController else { fatalError("Expected destination to be of type CardsViewController.") } switch segue.identifier { case "default": target.navigationItem.title = "Default" case "without_padding": target.navigationItem.title = "Without padding" target.padded = false case "selected": target.navigationItem.title = "Selected" target.selected = true case "corner_style_large": target.navigationItem.title = "Corner style large" target.cornerStyle = BPKCardCornerStyle.large case "background_color": target.navigationItem.title = "With background color" target.backgroundColor = BPKColor.skyBlueTint01 default: fatalError("The identifier \(segue.identifier.debugDescription) does not " + "match an example Card configuration.") } } } <file_sep>/Example/Backpack/View Controllers/CalendarViewController.swift // /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit import Backpack.Calendar import Backpack.SimpleDate class CalendarViewController: UIViewController, BPKCalendarDelegate { var maxEnabledDate: Bool = false var customStylesForDates = false var currentMaxEnabledDate: Date? @IBOutlet weak var myView: BPKCalendar! @IBOutlet weak var segmentedControl: UISegmentedControl! override func viewDidLoad() { myView.minDate = BPKSimpleDate(date: Date(), for: myView.gregorian) myView.locale = Locale.current myView.delegate = self } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil, completion: { _ in self.myView.reloadData() }) } // Pragma mark: SegmentedControlDelegate @IBAction func valueChanged(_ sender: Any) { myView.selectionType = BPKCalendarSelection(rawValue: UInt(segmentedControl!.selectedSegmentIndex))! myView.reloadData() } // Pragma mark: CalendarDelegate func calendar(_ calendar: BPKCalendar, didChangeDateSelection dateList: [BPKSimpleDate]) { print("calendar:", calendar, "didChangeDateSelection:", dateList) if self.maxEnabledDate { if dateList.count == 0 { self.currentMaxEnabledDate = nil } else { let lastSelectedDate = dateList.first let newMaxDate = BPKSimpleDate(year: lastSelectedDate!.year, month: lastSelectedDate!.month + 1, day: lastSelectedDate!.day) self.currentMaxEnabledDate = newMaxDate.date(for: calendar.gregorian) } } } func calendar(_ calendar: BPKCalendar, didScroll contentOffset: CGPoint) { print("calendar:", calendar, "didScroll:", contentOffset, "isTracking:", calendar.isTracking) } // Disables dates that are > 1 month ahead of the selected date. func calendar(_ calendar: BPKCalendar, isDateEnabled date: BPKSimpleDate) -> Bool { let nativeDate = date.date(for: calendar.gregorian) if self.currentMaxEnabledDate == nil { return true } // If date > self.currentMaxEnabledDate, return false if nativeDate.compare(self.currentMaxEnabledDate!) == .orderedDescending { return false } return true } func calendar(_ calendar: BPKCalendar, cellStyleFor date: BPKSimpleDate) -> BPKCalendarDateCellStyle { if !customStylesForDates { return .normal } let gregorian = calendar.gregorian let convertedDate = date.date(for: gregorian) let date1 = gregorian.startOfDay(for: Date()) let date2 = gregorian.startOfDay(for: convertedDate) let components = gregorian.dateComponents([.day], from: date1, to: date2) guard let daysCount = components.day else { return .normal } if daysCount == 2 || daysCount == 8 || daysCount == 12 || daysCount == 20 { return .positive } if daysCount == 4 || daysCount == 10 || daysCount == 15 || daysCount == 24 { return .negative } if daysCount == 1 || daysCount == 3 || daysCount == 11 || daysCount == 22 { return .neutral } return .normal } } <file_sep>/Example/Backpack/View Controllers/FlareViewSelectorViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit import Backpack enum FlareViewSegueIdentifier: String { case `default` = "Default" case flareAtTop = "FlareAtTop" case rounded = "Rounded" case backgroundImage = "BackgroundImage" case backgroundImageAnimated = "BackgroundImageAnimated" } class FlareViewSelectorViewController: UITableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let target = segue.destination as? FlareViewViewController else { fatalError("Expected destination to be of type FlareViewViewController.") } if let identifier = segue.identifier, let flareViewSegueIdentifier = FlareViewSegueIdentifier(rawValue: identifier) { switch flareViewSegueIdentifier { case .default: target.title = "Default" case .flareAtTop: target.title = "Flare at top" target.flareAtTop = true case .rounded: target.title = "Rounded" target.rounded = true case .backgroundImage: target.title = "Background image" target.backgroundImage = true case .backgroundImageAnimated: target.title = "Animated" target.backgroundImage = true target.animated = true } } else { fatalError("Unknown segue identifer \(segue.identifier.debugDescription)") } } } <file_sep>/Backpack/BottomSheet/README.md # Backpack/BottomSheet ## Installation In `Podfile` add ``` pod 'Backpack/BottomSheet' ``` and then run `pod install`. ## Usage ### Bottom Sheet `Backpack/BottomSheet` is a component for presenting a floating panel similar to the one used in Apple Maps, Stocks and other native Apple apps. ### Objective-C ```objective-c #import <Backpack/Backpack-Swift.h> MyContentViewController *contentViewController = ... // A view controller that contains any kind of scroll view BPKBottomSheet *bottomSheet = [[BPKBottomSheet alloc] initWithContentViewController:contentViewController scrollViewToTrack:contentViewController.scrollView bottomSectionViewController:nil]; [bottomSheet presentInViewController:self animated:YES completion:nil]; ``` # With a fixed bottom section ```objective-c #import <Backpack/Backpack-Swift.h> MyContentViewController *contentViewController = ... // A view controller that contains any kind of scroll view MyFixedBottomSectionViewController *fixedBottomSectionViewController = ... // A view controller that will be fixed at the bottom (won't scroll) BPKBottomSheet *bottomSheet = [[BPKBottomSheet alloc] initWithContentViewController:contentViewController scrollViewToTrack:contentViewController.scrollView bottomSectionViewController:fixedBottomSectionViewController]; [bottomSheet presentInViewController:self animated:YES completion:nil]; ``` ### Swift ```swift import Backpack let contentViewController = ... // A view controller that contains any kind of scroll view let bottomSheet = BPKBottomSheet(contentViewController: contentViewController, scrollViewToTrack: contentViewController.scrollView) bottomSheet.present(in: self, animated: true, completion: nil) ``` # With a fixed bottom section ```swift import Backpack let contentViewController = ... // A view controller that contains any kind of scroll view let fixedBottomSectionViewController = ... // A view controller that will be fixed at the bottom (won't scroll) let bottomSheet = BPKBottomSheet(contentViewController: contentViewController, scrollViewToTrack: contentViewController.scrollView, bottomSectionViewController: fixedBottomSectionViewController) bottomSheet.present(in: self, animated: true, completion: nil) ``` <file_sep>/Backpack/Icon/README.md # Backpack/Icon ## Usage `BPKIcon` contains the Backpack Icon component. It supports rendering any Backpack icon to `UIImage`s using a caching mechanism to reduce performance impact. A UI component `IconView`/`BPKIconView` is also available for simple icon case where an icon is to be displayed with a tint color. \*\*Note: Some icons are only available in small or large, whilst others are available at both sizes. Check our [design docs](https://backpack.github.io/components/icon?platform=design) to see which are available.\*\* ### Objective-C #### Using `BPKIconView` ```objective-c #import <Backpack/Color.h> #import <Backpack/Icon.h> BPKIconView *iconView = [[BPKIconView alloc] initWithIconName:BPKIconNameAccessibility size:BPKIconSizeLarge]; iconView.tintColor = BPKColor.blue500; ``` #### Render icon to `UIImage` ```objective-c #import <Backpack/Color.h> #import <Backpack/Icon.h> UIImage *renderedIcon = [BPKIcon iconNamed:@"flight" color:[BPKolor skyGray] size:BPKIconSizeSmall]; ``` ### Swift #### Using `IconView` ```swift import Backpack let iconView = BPKIconView(iconName: .accessibility, size: .small) iconView.tintColor = BPKColor.blue500 ``` ##### Flip icons with a horizontal direction when layout direction is right to left ```swift import Backpack let iconView = BPKIconView(iconName: .arrowLeft, size: .small) iconView.flipsForRightToLeft = true ``` #### Render icon to `UIImage` ```swift import Backpack let renderedIcon = BPKIcon.makeIcon(name: .flight, color: BPKColor.skyGray, size:.small) `` <file_sep>/Dangerfile list_of_files = (git.added_files + git.modified_files) list_of_files_excluding_this_one = list_of_files - ['Dangerfile'] has_objective_c_changes = list_of_files.any? { |path| path.end_with?('h') || path.end_with?('m') } uses_non_RTL_anchor = list_of_files_excluding_this_one.any? { |path| File.file?(path) && (File.read(path).include?('leftAnchor') || File.read(path).include?('rightAnchor')) } # warning and errors if uses_non_RTL_anchor warn("You have used `leftAnchor` or `rightAnchor`. These should generally be avoided to ensure that RTL is supported.") end <file_sep>/Example/Backpack/View Controllers/ChipSelectorViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit import Backpack enum ChipSegueIdentifier: String { case `default` = "Default" case withIcons = "WithIcons" case withoutShadow = "WithoutShadow" case withBackgroundColor = "WithBackgroundColor" case backgroundColorNoShadow = "BackgroundColorNoShadow" case backgroundColorUnselectedNoShadow = "BackgroundColorUnselectedNoShadow" case outline = "Outline" } class ChipSelectorViewController: UITableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let target = segue.destination as? ChipsViewController else { fatalError("Expected destination to be of type ChipViewController.") } if let identifier = segue.identifier, let chipSegueIdentifier = ChipSegueIdentifier(rawValue: identifier) { switch chipSegueIdentifier { case .default: target.title = "Default" case .withIcons: target.title = "With icons" target.icons = true case .withoutShadow: target.title = "Without shadow" target.shadow = false case .withBackgroundColor: target.title = "Background color" target.backgroundTint = BPKColor.panjin case .backgroundColorNoShadow: target.title = "Background color" target.shadow = false target.backgroundTint = BPKColor.panjin case .backgroundColorUnselectedNoShadow: target.title = "Background color" target.shadow = false target.colorUnselectedState = true target.backgroundTint = BPKColor.panjin case .outline: target.title = "Outline" target.style = .outline } } else { fatalError("Unknown segue identifer \(segue.identifier.debugDescription)") } } } <file_sep>/Example/Backpack/View Controllers/NavigationBarSelectorViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit import Backpack enum NavigationBarSegueIdentifier: String { case `default` = "Default" case buttons = "Buttons" } class NavigationBarSelectorViewController: UITableViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let target = segue.destination as? NavigationBarViewController else { fatalError("Expected destination to be of type NavigationBarViewController.") } if let identifier = segue.identifier, let navigationBarSegueIdentifier = NavigationBarSegueIdentifier(rawValue: identifier) { switch navigationBarSegueIdentifier { case .default: return case .buttons: target.showButtons = true } } else { fatalError("Unknown segue identifer \(segue.identifier.debugDescription)") } } } <file_sep>/Backpack/BottomSheet/Classes/BottomSheet.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit import FloatingPanel @objcMembers @objc(BPKBottomSheet) public final class BPKBottomSheet: NSObject { private enum Constants { static let bottomSheetHeightInHalfPosition: CGFloat = 386.0 static let backdropAlpha: CGFloat = 0.3 static let grabberHandleWidth: CGFloat = 60.0 } /// View controller that will be presented when calling /// `present(in: _, animated: _, completion: _)`. /// It can also be presented using UIKit's native presentation API. public var viewControllerToPresent: UIViewController { return floatingPanelController } /// View controller contained in the bottom sheet. public var contentViewController: UIViewController? { return floatingPanelController.contentViewController } /// Fixed bottom section. Can only be passed when initializing /// the bottom sheet. public var bottomSectionViewController: UIViewController? { return floatingPanelController.bottomSectionViewController } /// This closure will be executed once the bottom sheet has been /// fully dismissed. public var onDismissed: (() -> Void)? { get { return floatingPanelController.onDismissed } set { floatingPanelController.onDismissed = newValue } } private lazy var floatingPanelController: BPKFloatingPanelController = { let panel = BPKFloatingPanelController(delegate: self) panel.surfaceView.backgroundColor = BPKColor.backgroundTertiaryColor panel.surfaceView.cornerRadius = BPKCornerRadiusLg panel.surfaceView.grabberTopPadding = BPKSpacingMd panel.surfaceView.grabberHandleHeight = BPKSpacingSm panel.surfaceView.grabberHandleWidth = Constants.grabberHandleWidth panel.surfaceView.grabberHandle.barColor = BPKColor.skyGrayTint06 panel.isRemovalInteractionEnabled = true // We do this to hold a strong reference to `BPKBottomSheet` and force it // to exist as long as `floatingPanelController` exists. // Reference will be cleaned up by `floatingPanelController` when // it's dismissed, to avoid a reference cycle. panel.bottomSheet = self return panel }() private var scrollView: UIScrollView? /// Instantiates a `BPKBottomSheet` with a scrollable content. Default initial height is 386pt and can't be changed. /// Optionally, an always visible bottom section can be added. /// /// - Parameters: /// - contentViewController: Content of the bottom sheet. /// - scrollViewToTrack: The bottom sheet uses this scroll view's gesture recognizer /// instead of creating a new one. This allows the scroll view to start offseting its /// content only after the bottom sheet has reached its full screen position. /// - bottomSectionViewController: Optional. A bottom section can be provided so that it is /// always visible regardless of the bottom sheet position. Useful for providing actions /// that should be accessible at all times. A top shadow is automatically added so that /// it integrates better with the content of the bottom sheet. /// Note: Safe Area should be taken into account in the bottom section's inner constraints. public init(contentViewController: UIViewController, scrollViewToTrack: UIScrollView, bottomSectionViewController: UIViewController? = nil) { super.init() self.scrollView = scrollViewToTrack floatingPanelController.contentViewController = contentViewController floatingPanelController.track(scrollView: scrollViewToTrack) floatingPanelController.bottomSectionViewController = bottomSectionViewController } /// Instantiates a `BPKBottomSheet` with a non-scrollable content. Height of the bottom sheet will be /// calculated based on the content. /// If the content height might not fit the screen, then `init(contentViewController: _, scrollViewToTrack: _)` /// should be used instead. /// - Parameter contentViewController: Content of the bottom sheet. public init(contentViewController: UIViewController) { super.init() floatingPanelController.contentViewController = contentViewController } /// This presents the bottom sheet. It is just a wrapper of native API /// `UIViewController.present(_, animated: _, completion: _)`. /// /// - Parameters: /// - viewController: The view controller that should present this bottom sheet. /// - animated: Animated or not. /// - completion: Completion closure called after presentation animation. @objc(presentInViewController:animated:completion:) public func present(in viewController: UIViewController, animated: Bool, completion: (() -> Void)? = nil) { viewController.present(viewControllerToPresent, animated: animated, completion: completion) } /// This method allows presenting a new bottom sheet on top of a previously existing one. /// The previous bottom sheet is automatically moved to the initial position, its scroll view content /// inset is reset, and the new bottom sheet won't add any more alpha to the backdrop view. /// - Parameters: /// - bottomSheet: The new bottom sheet to present. /// - animated: Animated or not. /// - completion: Completion closure called after the presentation animation. @objc(presentBottomSheet:animated:completion:) public func present(_ bottomSheet: BPKBottomSheet, animated: Bool, completion: (() -> Void)? = nil) { if let scrollView = floatingPanelController.scrollView { scrollView.setContentOffset(.init(x: 0, y: -scrollView.adjustedContentInset.top), animated: animated) } // It's important to set `backgroundColor` to clear instead of setting alpha to 0, // in order for the view to keep receiving touch events bottomSheet.floatingPanelController.backdropView.backgroundColor = .clear floatingPanelController.move(to: .half, animated: true) bottomSheet.present(in: floatingPanelController, animated: animated, completion: completion) } /// Forces the bottom sheet layout to be updated. /// It can be useful, for example, when changing the inner constraints of the `contentViewController` /// and bottom sheet needs to be resized to fit the content. public func updateLayout() { floatingPanelController.updateLayout() } } extension BPKBottomSheet: FloatingPanelControllerDelegate { final class Layout: FloatingPanelLayout { var initialPosition: FloatingPanelPosition { return .half } var supportedPositions: Set<FloatingPanelPosition> { return [.full, .half] } func insetFor(position: FloatingPanelPosition) -> CGFloat? { switch position { case .half: return Constants.bottomSheetHeightInHalfPosition default: return nil } } func backdropAlphaFor(position: FloatingPanelPosition) -> CGFloat { switch position { case .full, .half: return Constants.backdropAlpha default: return 0.0 } } } final class IntrinsicLayout: FloatingPanelIntrinsicLayout { func backdropAlphaFor(position: FloatingPanelPosition) -> CGFloat { return Constants.backdropAlpha } } public func floatingPanel(_ viewController: FloatingPanelController, layoutFor newCollection: UITraitCollection) -> FloatingPanelLayout? { return scrollView == nil ? IntrinsicLayout() : Layout() } } <file_sep>/Example/Backpack/View Controllers/HorizontalNavSelectorViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit import Backpack enum HorizontalNavSegueIdentifier: String { case `default` = "Default" case noUnderline = "NoUnderline" case small = "Small" case icons = "Icons" case smallIcons = "iconsSmall" case wide = "Wide" case showExtraContent = "withScroll" case customItems = "customItems" case notificationDot = "withNotification" case badge = "withBadge" case alternate = "alternateAppearance" } class HorizontalNavSelectorViewController: UITableViewController { // swiftlint:disable:next function_body_length cyclomatic_complexity override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let maybeHorizontalNavController = segue.destination as? HorizontalNavViewController if let identifier = segue.identifier, let horizontalNavSegueIdentifier = HorizontalNavSegueIdentifier(rawValue: identifier) { switch horizontalNavSegueIdentifier { case .default: segue.destination.title = "Default" case .small: segue.destination.title = "Small" maybeHorizontalNavController?.size = .small case .noUnderline: segue.destination.title = "Without underline" maybeHorizontalNavController?.showBar = false case .icons: segue.destination.title = "With icons" maybeHorizontalNavController?.showIcons = true case .smallIcons: segue.destination.title = "Small with icons" maybeHorizontalNavController?.size = .small maybeHorizontalNavController?.showIcons = true case .wide: segue.destination.title = "Wide" maybeHorizontalNavController?.size = .small maybeHorizontalNavController?.showIcons = true maybeHorizontalNavController?.wide = true case .showExtraContent: segue.destination.title = "With scroll" maybeHorizontalNavController?.showIcons = true maybeHorizontalNavController?.showExtraContent = true case .customItems: segue.destination.title = "Custom Items" maybeHorizontalNavController?.useCustomItems = true maybeHorizontalNavController?.showBar = false case .notificationDot: segue.destination.title = "With Notification Dot" maybeHorizontalNavController?.showNotificationDot = true maybeHorizontalNavController?.showIcons = true case .badge: segue.destination.title = "With Badge" maybeHorizontalNavController?.useItemWithBadge = true case .alternate: segue.destination.title = "Alternate appearance" maybeHorizontalNavController?.appearance = .alternate maybeHorizontalNavController?.showBar = true } } else { fatalError("Unknown segue identifer \(segue.identifier.debugDescription)") } } } <file_sep>/Backpack/TabBarController/README.md # Backpack/TabBarController ## Usage `BPKTabBarController` contains the Backpack Tab Bar Controller component which is a subclass of `UITabBarController` with Skyscanner styles. See [Apple's documentation](https://developer.apple.com/documentation/uikit/uitabbarcontroller) <file_sep>/Example/Backpack/View Controllers/TabBarControllerStoryViewController.swift /* * Backpack - Skyscanner's Design System * * Copyright 2018-2020 Skyscanner Ltd * * 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. */ import UIKit import Backpack class TabBarControllerStoryViewController: BPKTabBarController { override func viewDidLoad() { let tabOne = UIViewController() tabOne.view.backgroundColor = BPKColor.backgroundColor let tabOneBarItem = UITabBarItem( title: "Search", image: BPKIcon.makeTemplateIcon(name: .search, size: .large), tag: 1 ) tabOne.tabBarItem = tabOneBarItem let tabTwo = UIViewController() tabTwo.view.backgroundColor = BPKColor.backgroundColor let tabTwoBarItem = UITabBarItem( title: "Settings", image: BPKIcon.makeTemplateIcon(name: .settings, size: .large), tag: 2 ) tabTwo.tabBarItem = tabTwoBarItem self.viewControllers = [tabOne, tabTwo] } }
fe337f01947c6263aa4c12f942c21f4adff99785
[ "Swift", "Ruby", "Markdown" ]
19
Swift
RCiesielczuk/backpack-ios
b0a6946e2cdc641d05dce2d06b0e23f7ef1eb69c
445ed2597e08e4ad655edf775a469590598782b4
refs/heads/master
<file_sep>package com.lzj.spring.pojo; import com.lzj.spring.interfaces.Quest; /** * Demo class * * @author drose * @date 2019/5/21 22:00 */ public class KillDragonQuest implements Quest { @Override public void commonQuest() { System.out.println("执行铲除恶龙的任务"); } } <file_sep>package com.lzj.spring; import com.lzj.spring.interfaces.Performance; import com.lzj.spring.pojo.BraveKnight; import com.lzj.spring.pojo.KillDragonQuest; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ApplicationTests { @Autowired Performance performance; @Test public void contextLoads() { //构造器注入依赖 // BraveKnight braveKnight = new BraveKnight(new KillDragonQuest()); // braveKnight.embrakQuest(); //使用上下文创建bean注入依赖 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); BraveKnight bean = context.getBean(BraveKnight.class); bean.embrakQuest(); } @Test public void testAop(){ performance.perform(); } } <file_sep>package com.lzj.spring.interfaces; /** * Demo class * * @author drose * @date 2019/5/21 21:55 */ public interface Quest { //公共接口 public void commonQuest(); }
0850890cec3e2c690d93ce1e0a0657f703d71e0d
[ "Java" ]
3
Java
mylzj/spring
7bb30395ae74dd7bf7ac14e4de077d7b4a685051
fdac18e03dfe2a758e116d11eff365243d074541
refs/heads/master
<repo_name>Swanand-Kulkarni94/Bokeh_Python<file_sep>/Bokeh_BarPandasNested.py #Bokeh Python """ Link https://bokeh.pydata.org/en/latest/docs/gallery/bar_pandas_groupby_nested.html """ from bokeh.io import show, output_file from bokeh.plotting import figure from bokeh.palettes import Spectral5 from bokeh.sampledata.autompg import autompg_clean as df from bokeh.transform import factor_cmap output_file("BarPandas_Nested.html") df.cyl = df.cyl.astype(str) df.yr = df.yr.astype(str) group = df.groupby(['cyl', 'mfr']) index_cmap = factor_cmap('cyl_mfr', palette = Spectral5, factors = sorted(df.cyl.unique()), end =1) p = figure(plot_width = 800, plot_height = 300, title = "Mean MPG #Cylinders&Manufacturer", x_range = group, toolbar_location = None, tooltips = [("MPG", "@mpg_mean"), ("Cyl, Mfr", "@cyl_mfr")]) p.vbar(x = 'cyl_mfr', top = 'mpg_mean', width = 1, source = group, line_color = 'white', fill_color = index_cmap) p.y_range.start = 0 p.x_range.range_padding = 0.05 p.xgrid.grid_line_color = None p.xaxis.axis_label = "Manufacturer grouped by #Cylinders" p.xaxis.major_label_orientation = 1.2 p.outline_line_color = None show(p)<file_sep>/Bokeh_BarInterval.py #Bokeh Python """Link https://bokeh.pydata.org/en/latest/docs/gallery/bar_intervals.html """ #Libraries from bokeh.io import show, output_file from bokeh.models import ColumnDataSource from bokeh.plotting import figure from bokeh.sampledata.sprint import sprint output_file("BarInterval.html") sprint.Year = sprint.Year.astype(str) group = sprint.groupby('Year') source = ColumnDataSource(group) p = figure(y_range = group, x_range = (9.5, 12.7), plot_width = 400, plot_height = 550, toolbar_location = None, title = 'Time Speards for Sprint Medalists (by Year)') p.hbar(y = "Year", left = "Time_min", right = "Time_max", height = 0.4, source = source) p.ygrid.grid_line_color = None p.xaxis.axis_label = "Time (seconds)" p.outline_line_color = None show(p)<file_sep>/Bokeh_RangeTool.py #Bokeh Python #NOT WORKING """ Link https://bokeh.pydata.org/en/latest/docs/gallery/range_tool.html """ #Libraries import numpy as np from bokeh.io import show from bokeh.layouts import column from bokeh.models import ColumnDataSource, RangeTool from bokeh.plotting import figure from bokeh.sampledata.stocks import AAPL dates = np.array(AAPL['date'], dtype = np.datetime64) source = ColumnDataSource(data = dict(date = dates, close = AAPL['adj_close'])) p = figure(plot_height = 300, plot_width = 800, tools = "xpan", toolbar_location = None, x_axis_type = "datetime", x_axis_location = "above", background_fill_color = "#efefef", x_range = (dates[1500], dates[2500])) p.line('date', 'close', source = source) p.yaxis.axis_label = 'Price' select = figure(title = "Drag the middle and edges of the selection box to change the range above", plot_height = 130, plot_width = 800, y_range = p.y_range, x_axis_type = "datetime", y_axis_type = None, tools = "", toolbar_location = None, background_fill_color = "#efefef") range_tool = RangeTool(x_range = p.x_range) range_tool.overlay.fill_color = "navy" range_tool.overlay.fill_alpha = 0.2 select.line('date','close', source = source) select.ygrid.grid_line_color = None select.add_tools(range_tool) select.toolbar.active_multi = range_tool show(column(p, select))<file_sep>/Bokeh_BarStackedSplit.py #Bokeh Python """ https://bokeh.pydata.org/en/latest/docs/gallery/bar_stacked_split.html """ from bokeh.io import output_file, show from bokeh.models import ColumnDataSource from bokeh.palettes import GnBu3, OrRd3 from bokeh.plotting import figure output_file("BarStackedSplit.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ['2015','2016','2017'] exports = {'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 4, 2, 4, 6], '2017' : [3, 2, 4, 4, 5, 3]} imports = {'fruits' : fruits, '2015' : [-1, 0, -1, -3, -2, -1], '2016' : [-2, -1, -3, -1, -2, -2], '2017' : [-1, -2, -1, 0, -2, -2]} p = figure(y_range = fruits, plot_height = 350, x_range = (-16, 16), title = "Fruit import/export, by year", toolbar_location = None) p.hbar_stack(years, y = 'fruits', height = 0.9, color = GnBu3, source = ColumnDataSource(exports), legend= ["%s exports" % x for x in years]) p.hbar_stack(years, y = 'fruits', height = 0.9, color = OrRd3, source = ColumnDataSource(imports), legend = ["%s imports" % x for x in years]) p.y_range.range_padding = 0.1 p.ygrid.grid_line_color = None p.legend.location = 'top_left' p.axis.minor_tick_line_color = None p.outline_line_color = None show(p)<file_sep>/Bokeh_HexBinTitle.py #Bokeh Python """ Link https://bokeh.pydata.org/en/latest/docs/gallery/hex_tile.html """ #Libraries import numpy as np from bokeh.io import output_file, show from bokeh.plotting import figure from bokeh.transform import linear_cmap from bokeh.util.hex import hexbin n = 50000 #Fifty Thousand points x = np.random.standard_normal(n) y = np.random.standard_normal(n) bins = hexbin(x, y, 0.1) p = figure(title = "Manual HexBin Tile for 50k points", tools = "wheel_zoom, pan, reset", match_aspect = True, background_fill_color = '#440154') p.grid.visible = False p.hex_tile(q = 'q', r = 'r', size = 0.1, line_color = None, source = bins, fill_color = linear_cmap('counts', 'Viridis256', 0, max(bins.counts))) output_file("HexBinTile.html") show(p)<file_sep>/Bokeh_BarColor.py #Bokeh Python """Link https://bokeh.pydata.org/en/latest/docs/gallery/bar_colormapped.html """ #Libraries import numpy as np from bokeh.io import show, output_file from bokeh.models import ColumnDataSource from bokeh.palettes import Spectral6 from bokeh.plotting import figure from bokeh.transform import factor_cmap output_file("BarColorMap.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] counts = [5, 3, 4, 2, 4, 6] source = ColumnDataSource(data = dict(fruits = fruits, counts = counts)) #What happens in this line over here ? p = figure(x_range = fruits, plot_height = 350, toolbar_location = None, title = "Fruit Counts") p.vbar(x = 'fruits', top = 'counts', width = 0.9, source = source, legend = "fruits", line_color = 'white', fill_color = factor_cmap('fruits', palette = Spectral6, factors = fruits)) p.xgrid.grid_line_color = None p.y_range.start = 0 p.y_range.end = 9 p.legend.orientation = 'horizontal' p.legend.location = 'top_center' show(p)<file_sep>/Bokeh_PieChart.py #Bokeh Python """ Link https://bokeh.pydata.org/en/latest/docs/gallery/pie_chart.html """ from math import pi import pandas as pd from bokeh.io import output_file, show from bokeh.palettes import Category20c from bokeh.plotting import figure from bokeh.transform import cumsum output_file("Pie.html") x = { 'USA' : 157, 'UK' : 93, 'Japan' : 89, 'China' : 63, 'Germany' : 44, 'India' : 42, 'Italy' : 40, 'Australia' : 35, 'Brazil' : 32, 'France' : 31, 'Taiwan' : 31, 'Spain' : 29 } data = pd.Series(x).reset_index(name = 'value').rename(columns = {'index':'country'}) data['angle'] = data['value']/data['value'].sum() * 2*pi data['color'] = Category20c[len(x)] p = figure(plot_height = 350, title = "Pie Chart", toolbar_location = None, tools = "hover", tooltips = "@country: @value", x_range = (-0.5, 1.0)) p.wedge(x = 0, y= 1, radius = 0.4, start_angle = cumsum('angle', include_zero = True), end_angle = cumsum('angle'), line_color = 'white', fill_color = 'color', legend = 'country', source = data) p.axis.axis_label = None p.axis.visible = False p.grid.grid_line_color = None show(p)<file_sep>/Bokeh.BarStack.py #Bokeh Python """ Link https://bokeh.pydata.org/en/latest/docs/gallery/bar_stacked.html """ from bokeh.core.properties import value from bokeh.io import show, output_file from bokeh.plotting import figure output_file("BarStacked.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ['2015','2016','2017'] colors = ["#c9d9d3", "#718dbf", "#e84d60"] data = {'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 4, 2, 4, 6], '2017' : [3, 2, 4, 4, 5, 3]} p = figure(x_range = fruits, plot_height = 250, title = "FruitsCounts by Year", toolbar_location = None, tools = "hover", tooltips = "$name @fruits: @$name") p.vbar_stack(years, x = 'fruits', width = 0.9, color = colors, source = data, legend = [value(x) for x in years]) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.axis.minor_tick_line_color = None p.outline_line_color = None p.legend.location = "top_left" p.legend.orientation = 'horizontal' show(p)<file_sep>/Bokeh_BarPandas.py #Bokeh Python """ Link https://bokeh.pydata.org/en/latest/docs/gallery/bar_pandas_groupby_colormapped.html """ #Libraries from bokeh.io import show, output_file from bokeh.palettes import Spectral5 from bokeh.plotting import figure from bokeh.sampledata.autompg import autompg as df from bokeh.transform import factor_cmap output_file("bar_pandas_groupby_colormapped.html") df.cyl = df.cyl.astype(str) group = df.groupby('cyl') cyl_cmap = factor_cmap('cyl', palette = Spectral5, factors = sorted(df.cyl.unique())) p = figure(plot_height = 350, x_range = group, title = "MPG by #Cylinders", toolbar_location = None, tools = "") p.vbar(x = 'cyl', top = 'mpg_mean', width = 1, source = group, line_color = cyl_cmap, fill_color = cyl_cmap) p.y_range.start = 0 p.xgrid.grid_line_color = None p.xaxis.axis_label = "Some Stuff" p.xaxis.major_label_orientation = 1.2 p.outline_line_color = None show(p)<file_sep>/Bokeh_Categorical.py #Bokeh Python """ Link https://bokeh.pydata.org/en/latest/docs/gallery/categorical.html """ from bokeh.layouts import row from bokeh.plotting import figure, show, output_file factors = ["a", "b", "c", "d", "e", "f", "g", "h"] x = [50, 40, 65, 10, 25, 37, 80, 60] dot = figure(title = "Categorical Dot Plot", tools = "", toolbar_location = None, y_range = factors, x_range = [0, 100]) dot.segment(0, factors, x, factors, line_width = 2, line_color = "green") dot.circle(x, factors, size = 15, fill_color = 'orange', line_color = 'green', line_width = 3) factors = ["foo 123", "bar:0.2", "baz-10"] x = ["foo 123", "foo 123", "foo 123", "bar:0.2", "bar:0.2", "bar:0.2", "baz-10", "baz-10", "baz-10"] y = ["foo 123", "bar:0.2", "baz-10", "foo 123", "bar:0.2", "baz-10", "foo 123", "bar:0.2", "baz-10"] colors = [ "#0B486B", "#79BD9A", "#CFF09E", "#79BD9A", "#0B486B", "#79BD9A", "#CFF09E", "#79BD9A", "#0B486B" ] hm = figure(title = "Categorical Heatmap", tools = "hover", toolbar_location = None, x_range = factors, y_range = factors) hm.rect(x, y, color = colors, width = 1, height = 1) output_file("Categorical.html", title = "Categorical.py Example") show(row(hm, dot, sizing_mode = "scale_width"))<file_sep>/Bokeh_CategoricalScatter.py #Bokeh Python #NOT WORKING """ Link https://bokeh.pydata.org/en/latest/docs/gallery/categorical_scatter_jitter.html """ from bokeh.io import show, output_file from bokeh.models import ColumnDataSource from bokeh.plotting import figure from bokeh.sampledata.commits import data from bokeh.transform import jitter output_file("CategoricalScatterJitter.html") DAYS = ['Sun', 'Sat', 'Fri', 'Thu', 'Wed', 'Tue', 'Mon'] source = ColumnDataSource p = figure(plot_width = 800, plot_height = 300, y_range = DAYS, x_axis_type = 'datetime', title = "Commits by Time of Day") p.circle(x = 'time', y = jitter('day', width = 0.6, range = p.y_range), source = source, aplha = 0.3) p.xaxis[0].formatter.days = ['%Hh'] p.x_range.range_padding = 0 p.ygrid.grid_line_color = None show(p)<file_sep>/Bokeh_BarMixed.py #Bokeh Python """ Link https://bokeh.pydata.org/en/latest/docs/gallery/bar_mixed.html """ from bokeh.io import show, output_file from bokeh.models import FactorRange from bokeh.plotting import figure output_file("BarMixed.html") factors = [ ("Q1", "jan"), ("Q1", "feb"), ("Q1", "mar"), ("Q2", "apr"), ("Q2", "may"), ("Q2", "jun"), ("Q3", "jul"), ("Q3", "aug"), ("Q3", "sep"), ("Q4", "oct"), ("Q4", "nov"), ("Q4", "dec"), ] p = figure(x_range = FactorRange(*factors), plot_height = 350, toolbar_location = None, tools = "") x = [10, 12, 16, 9, 10, 8, 12, 13, 14, 14, 12, 16] p.vbar(x = factors, top = x, width = 0.9, alpha = 0.5) p.line(x = ["Q1", "Q2", "Q3", "Q4"], y = [12, 9, 13, 14], color = "red", line_width = 2) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None show(p)
25e4fb9265d6c76a905c7ce2c19cbca0cb318815
[ "Python" ]
12
Python
Swanand-Kulkarni94/Bokeh_Python
97fdb42a1f6bbdc99a4678273f398aa4ba8c37f7
df30ef61b953bed9a228b8c14f927b2805846f9f
refs/heads/master
<repo_name>xicheng87/Redbase<file_sep>/src/pf_test2.cc // // File: pf_test2.cc // Description: Test PF component // Authors: <NAME> (<EMAIL>) // // 1997: This file was created to utilize the statistics manager to ensure // that the buffer manager was performing correctly. Note that you must // compile the pf layer with the -DPF_STATS flag. If you don't then this // test won't really test anything over and above the pf_test1.cc. // #include <cstdio> #include <iostream> #include <cstring> #include <unistd.h> #include "pf.h" #include "pf_internal.h" #include "pf_hashtable.h" using namespace std; // The PF_STATS indicates that we will be tracking statistics for the PF // Layer. The Manager is defined within pf_buffermgr.cc. Here we must // place the initializer and then the final call to printout the statistics // once main has finished #ifdef PF_STATS #include "statistics.h" // This is defined within pf_buffermgr.cc extern StatisticsMgr *pStatisticsMgr; // This method is defined within pf_statistics.cc. It is called at the end // to display the final statistics, or by the debugger to monitor progress. extern void PF_Statistics(); #endif // // Defines // #define FILE1 "file1" RC TestPF() { PF_Manager pfm; PF_FileHandle fh; PF_PageHandle ph; RC rc; char *pData; PageNum pageNum; int i; cout << "Creating file: " << FILE1 << "\n"; if ((rc = pfm.CreateFile(FILE1))) return (rc); cout << "Opening file: " << FILE1 << "\n"; if ((rc = pfm.OpenFile(FILE1, fh))) return(rc); cout << "Allocating " << PF_BUFFER_SIZE << " pages.\n"; for (i = 0; i < PF_BUFFER_SIZE; i++) { if ((rc = fh.AllocatePage(ph)) || (rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); if (i != pageNum) { cout << "Page number incorrect: " << (int)pageNum << " " << i << "\n"; exit(1); } // Put only the page number into the page memcpy(pData, (char *)&pageNum, sizeof(PageNum)); } // Now ask for the same pages again cout << "Asking for the same pages again.\n"; for (i = 0; i < PF_BUFFER_SIZE; i++) { if ((rc = fh.GetThisPage(i, ph)) || (rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); if (i != pageNum) { cout << "Page number incorrect: " << (int)pageNum << " " << i << "\n"; exit(1); } } // Now, if we have compiled with PF_STATS then we need to ensure that // PF_GETPAGE = PF_BUFFER_SIZE and PF_PAGEFOUND = PF_BUFFER_SIZE. // Also that PF_PAGENOTFOUND = PF_BUFFER_SIZE. #ifdef PF_STATS cout << "Verifying the statistics for buffer manager: "; int *piGP = pStatisticsMgr->Get(PF_GETPAGE); int *piPF = pStatisticsMgr->Get(PF_PAGEFOUND); int *piPNF = pStatisticsMgr->Get(PF_PAGENOTFOUND); if (piGP && (*piGP != PF_BUFFER_SIZE)) { cout << "Number of GetPages is incorrect! (" << *piGP << ")\n"; // No built in error code for this exit(1); } if (piPF && (*piPF != PF_BUFFER_SIZE)) { cout << "Number of pages found in the buffer is incorrect! (" << *piPF << ")\n"; // No built in error code for this exit(1); } if (piPNF!=NULL) { cout << "Number of pages not found in the buffer is incorrect! (" << *piPNF << ")\n"; // No built in error code for this exit(1); } cout << " Correct!\n"; delete piGP; delete piPF; delete piPNF; #endif // PF_STATS cout << "Unpinning pages.\n"; for (i = 0; i < PF_BUFFER_SIZE; i++) // Must unpine the pages twice if ((rc = fh.UnpinPage(i)) || (rc = fh.UnpinPage(i))) return(rc); // Confirm that the buffer manager has written the correct number of // pages. #ifdef PF_STATS cout << "Verifying the write statistics for buffer manager: "; int *piWP = pStatisticsMgr->Get(PF_WRITEPAGE); int *piRP = pStatisticsMgr->Get(PF_READPAGE); if (piWP && (*piWP != PF_BUFFER_SIZE)) { cout << "Number of write pages is incorrect! (" << *piGP << ")\n"; // No built in error code for this exit(1); } if (piRP!=NULL) { cout << "Number of pages read in is incorrect! (" << *piPNF << ")\n"; // No built in error code for this exit(1); } cout << " Correct!\n"; delete piWP; delete piRP; #endif // PF_STATS // Goal here is to push out of the buffer manager the old pages by // asking for new ones. At the end the LRU algorithm should ensure that // none of the original pages lie in memory cout << "Allocating an additional " << PF_BUFFER_SIZE << " pages to clear"; cout << "out the buffer pool.\n"; for (i = 0; i < PF_BUFFER_SIZE; i++) { if ((rc = fh.AllocatePage(ph)) || (rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); if (i+PF_BUFFER_SIZE != pageNum) { cout << "Page number incorrect: " << (int)pageNum << " " << i << "\n"; exit(1); } if ((rc = fh.UnpinPage(i+PF_BUFFER_SIZE))) return(rc); } // Now refetch the original pages cout << "Now asking for the original pages again.\n"; for (i = 0; i < PF_BUFFER_SIZE; i++) { if ((rc = fh.GetThisPage(i, ph)) || (rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); if (i!= pageNum) { cout << "Page number incorrect: " << (int)pageNum << " " << i << "\n"; exit(1); } if ((rc = fh.UnpinPage(i))) return(rc); } // The previous refetch should have resulted in the buffer manager // going to disk for each of the pages, since the buffer should // not have had any of the pages. #ifdef PF_STATS cout << "Verifying that pages were not found in buffer pool: "; piPNF = pStatisticsMgr->Get(PF_PAGENOTFOUND); if (piPNF && (*piPNF != PF_BUFFER_SIZE)) { cout << "Number of pages not found in the buffer is incorrect! (" << *piPF << ")\n"; // No built in error code for this exit(1); } cout << " Correct!\n"; delete piPNF; #endif // PF_STATS // Now we will Flush the buffer manager to disk and count the number of // flushes and the total number of writes. cout << "Flushing the File handle to disk.\n"; if ((rc = fh.FlushPages())) return (rc); #ifdef PF_ cout << "Testing flush to disk: "; int *piFP = pStatisticsMgr->Get(PF_FLUSHPAGES); piWP = pStatisticsMgr->Get(PF_WRITEPAGES); if (piFP && (*piFP != 1)) { cout << "Number of times Flush pages routine has been called " << "is incorrect! (" << *piFP << ")\n"; // No built in error code for this exit(1); } if (piWP && (*piWP != 2*PF_BUFFER_SIZE)) { cout << "Number of written pages is incorrect! (" << *piWP << ")\n"; // No built in error code for this exit(1); } cout << " Correct!\n"; delete piFP; delete piWP; #endif cout << "Flushing the File handle to disk. (Again)\n"; if ((rc = fh.FlushPages())) return (rc); // Here the idea is to ensure that the number of pages written has not // increased! Since everything was already flushed. #ifdef PF_STATS cout << "Testing number of pages written to disk: "; piWP = pStatisticsMgr->Get(PF_WRITEPAGE); // This number should not have increased since last time! if (piWP && (*piWP != 2*PF_BUFFER_SIZE)) { cout << "Number of written pages is incorrect! (" << *piWP << ")\n"; // No built in error code for this exit(1); } cout << " Correct!\n"; delete piWP; #endif // Close the file if ((rc = pfm.CloseFile(fh))) return(rc); // If we are dealing with statistics then we might as well output the // final numbers #ifdef PF_STATS PF_Statistics(); #endif // Return ok return (0); } int main() { RC rc; // Write out initial starting message cerr.flush(); cout.flush(); cout << "********************\n"; cout << "Starting PF layer test.\n"; cout.flush(); // If we are tracking the PF Layer statistics #ifndef PF_STATS cout << " ** The PF layer was not compiled with the -DPF_STATS flag **\n"; cout << " ** This test file is not very effective without it! **\n"; #endif cout << "----------------------\n"; // Delete files from last time unlink(FILE1); if ((rc = TestPF())) { PF_PrintError(rc); return (1); } // Write ending message and exit cout << "Ending PF layer test.\n"; cout << "********************\n\n"; return (0); } <file_sep>/src/rm.h // // rm.h // // Record Manager component interface // // This file does not include the interface for the RID class. This is // found in rm_rid.h // #ifndef RM_H #define RM_H // Please DO NOT include any files other than redbase.h and pf.h in this // file. When you submit your code, the test program will be compiled // with your rm.h and your redbase.h, along with the standard pf.h that // was given to you. Your rm.h, your redbase.h, and the standard pf.h // should therefore be self-contained (i.e., should not depend upon // declarations in any other file). // Do not change the following includes #include "redbase.h" #include "rm_rid.h" #include "pf.h" // // RM_Record: RM Record interface // class RM_Record { public: RM_Record (); ~RM_Record(); // Return the data corresponding to the record. Sets *pData to the // record contents. RC GetData(char *&pData) const; // Return the RID associated with the record RC GetRid (RID &rid) const; }; // // RM_FileHandle: RM File interface // class RM_FileHandle { public: RM_FileHandle (); ~RM_FileHandle(); // Given a RID, return the record RC GetRec (const RID &rid, RM_Record &rec) const; RC InsertRec (const char *pData, RID &rid); // Insert a new record RC DeleteRec (const RID &rid); // Delete a record RC UpdateRec (const RM_Record &rec); // Update a record // Forces a page (along with any contents stored in this class) // from the buffer pool to disk. Default value forces all pages. RC ForcePages (PageNum pageNum = ALL_PAGES); }; // // RM_FileScan: condition-based scan of records in the file // class RM_FileScan { public: RM_FileScan (); ~RM_FileScan (); RC OpenScan (const RM_FileHandle &fileHandle, AttrType attrType, int attrLength, int attrOffset, CompOp compOp, void *value, ClientHint pinHint = NO_HINT); // Initialize a file scan RC GetNextRec(RM_Record &rec); // Get next matching record RC CloseScan (); // Close the scan }; // // RM_Manager: provides RM file management // class RM_Manager { public: RM_Manager (PF_Manager &pfm); ~RM_Manager (); RC CreateFile (const char *fileName, int recordSize); RC DestroyFile(const char *fileName); RC OpenFile (const char *fileName, RM_FileHandle &fileHandle); RC CloseFile (RM_FileHandle &fileHandle); }; // // Print-error function // void RM_PrintError(RC rc); #define RM_BITMAP_FULL (START_RM_WARN + 0) // bitmap is all-set #define RM_LASTWARN RM_BITMAP_FULL #define RM_BITMAP_OUTOFRANGE (START_RM_ERR - 0) // bitmap out of range #define RM_LASTERROR RM_BITMAP_OUTOFRANGE #endif <file_sep>/src/pf_test1.cc // // File: pf_test1.cc // Description: Test PF component // Authors: <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // // 1997: Added call to confirm the statistics from the buffer mgr // #include <cstdio> #include <iostream> #include <cstring> #include <unistd.h> #include "pf.h" #include "pf_internal.h" #include "pf_hashtable.h" using namespace std; // The PF_STATS indicates that we will be tracking statistics for the PF // Layer. The Manager is defined within pf_buffermgr.cc. Here we must // place the initializer and then the final call to printout the statistics // once main has finished #ifdef PF_STATS #include "statistics.h" // This is defined within pf_buffermgr.cc extern StatisticsMgr *pStatisticsMgr; // This method is defined within pf_statistics.cc. It is called at the end // to display the final statistics, or by the debugger to monitor progress. extern void PF_Statistics(); // // PF_ConfirmStatistics // // This function will be run at the end of the program after all the tests // to confirm that the buffer manager operated correctly. // // These numbers have been confirmed. Note that if you change any of the // tests, you will also need to change these numbers as well. // void PF_ConfirmStatistics() { // Must remember to delete the memory returned from StatisticsMgr::Get cout << "Verifying the statistics for buffer manager: "; int *piGP = pStatisticsMgr->Get("GetPage"); int *piPF = pStatisticsMgr->Get("PageFound"); int *piPNF = pStatisticsMgr->Get("PageNotFound"); int *piWP = pStatisticsMgr->Get("WritePage"); int *piRP = pStatisticsMgr->Get("ReadPage"); int *piFP = pStatisticsMgr->Get("FlushPage"); if (piGP && (*piGP != 702)) { cout << "Number of GetPages is incorrect! (" << *piGP << ")\n"; // No built in error code for this exit(1); } if (piPF && (*piPF != 23)) { cout << "Number of pages found in the buffer is incorrect! (" << *piPF << ")\n"; // No built in error code for this exit(1); } if (piPNF && (*piPNF != 679)) { cout << "Number of pages not found in the buffer is incorrect! (" << *piPNF << ")\n"; // No built in error code for this exit(1); } if (piRP && (*piRP != 679)) { cout << "Number of read requests to the Unix file system is " << "incorrect! (" << *piPNF << ")\n"; // No built in error code for this exit(1); } if (piWP && (*piWP != 339)) { cout << "Number of write requests to the Unix file system is "<< "incorrect! (" << *piPNF << ")\n"; // No built in error code for this exit(1); } if (piFP && (*piFP != 16)) { cout << "Number of requests to flush the buffer is "<< "incorrect! (" << *piPNF << ")\n"; // No built in error code for this exit(1); } cout << " Correct!\n"; // Delete the memory returned from StatisticsMgr::Get delete piGP; delete piPF; delete piPNF; delete piWP; delete piRP; delete piFP; } #endif // PF_STATS // // Defines // #define FILE1 "file1" #define FILE2 "file2" // // Function declarations // RC WriteFile(PF_Manager &pfm, char *fname); RC PrintFile(PF_FileHandle &fh); RC ReadFile(PF_Manager &pfm, char* fname); RC TestPF(); RC TestHash(); RC WriteFile(PF_Manager &pfm, char *fname) { PF_FileHandle fh; PF_PageHandle ph; RC rc; char *pData; PageNum pageNum; int i; cout << "Opening file: " << fname << "\n"; if ((rc = pfm.OpenFile(fname, fh))) return(rc); for (i = 0; i < PF_BUFFER_SIZE; i++) { if ((rc = fh.AllocatePage(ph)) || (rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); if (i != pageNum) { cout << "Page number incorrect: " << (int)pageNum << " " << i << "\n"; exit(1); } memcpy(pData, (char *)&pageNum, sizeof(PageNum)); // memcpy(pData + PF_PAGE_SIZE - sizeof(PageNum), &pageNum, sizeof(PageNum)); cout << "Page allocated: " << (int)pageNum << "\n"; } // Test pinning too many pages if ((rc = fh.AllocatePage(ph)) != PF_NOBUF) { cout << "Pin too many pages should fail: "; return(rc); } cout << "Unpinning pages and closing the file\n"; for (i = 0; i < PF_BUFFER_SIZE; i++) if ((rc = fh.UnpinPage(i))) return(rc); if ((rc = pfm.CloseFile(fh))) return(rc); // Return ok return (0); } RC PrintFile(PF_FileHandle &fh) { PF_PageHandle ph; RC rc; char *pData; PageNum pageNum, temp; cout << "Reading file\n"; if ((rc = fh.GetFirstPage(ph))) return(rc); do { if ((rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); memcpy((char *)&temp, pData, sizeof(PageNum)); cout << "Got page: " << (int)pageNum << " " << (int)temp << "\n"; // if (memcmp(pData + PF_PAGE_SIZE - sizeof(PageNum), // pData, sizeof(PageNum))) { // memcpy(&temp, pData + PF_PAGE_SIZE - sizeof(PageNum), sizeof(PageNum)); // cout << "ERROR!" << (int)temp << "\n"; // return (-1); // } if ((rc = fh.UnpinPage(pageNum))) return(rc); } while (!(rc = fh.GetNextPage(pageNum, ph))); if (rc != PF_EOF) return(rc); cout << "EOF reached\n"; // Return ok return (0); } RC ReadFile(PF_Manager &pfm, char* fname) { PF_FileHandle fh; RC rc; cout << "Opening: " << fname << "\n"; if ((rc = pfm.OpenFile(fname, fh)) || (rc = PrintFile(fh)) || (rc = pfm.CloseFile(fh))) return (rc); else return (0); } RC TestPF() { PF_Manager pfm; PF_FileHandle fh1, fh2; PF_PageHandle ph; RC rc; char *pData; PageNum pageNum, temp; int i; int len; pfm.GetBlockSize(len); printf("get bock size returned %d\n",len); cout << "Creating and opening two files\n"; if ((rc = pfm.CreateFile(FILE1)) || (rc = pfm.CreateFile(FILE2)) || (rc = WriteFile(pfm, (char*)FILE1)) || (rc = ReadFile(pfm, (char*)FILE1)) || (rc = WriteFile(pfm, (char*)FILE2)) || (rc = ReadFile(pfm, (char*)FILE2)) || (rc = pfm.OpenFile(FILE1, fh1)) || (rc = pfm.OpenFile(FILE2, fh2))) return(rc); cout << "Disposing of alternate pages\n"; for (i = 0; i < PF_BUFFER_SIZE; i++) { if (i & 1) { if ((rc = fh1.DisposePage(i))) return(rc); } else if ((rc = fh2.DisposePage(i))) return(rc); } cout << "Closing and destroying both files\n"; if ((rc = fh1.FlushPages()) || (rc = fh2.FlushPages()) || (rc = pfm.CloseFile(fh1)) || (rc = pfm.CloseFile(fh2)) || (rc = ReadFile(pfm, (char*)FILE1)) || (rc = ReadFile(pfm, (char*)FILE2)) || (rc = pfm.DestroyFile(FILE1)) || (rc = pfm.DestroyFile(FILE2))) return(rc); cout << "Creating and opening files again\n"; if ((rc = pfm.CreateFile(FILE1)) || (rc = pfm.CreateFile(FILE2)) || (rc = WriteFile(pfm, (char*)FILE1)) || (rc = WriteFile(pfm, (char*)FILE2)) || (rc = pfm.OpenFile(FILE1, fh1)) || (rc = pfm.OpenFile(FILE2, fh2))) return(rc); cout << "Allocating additional pages in both files\n"; for (i = PF_BUFFER_SIZE; i < PF_BUFFER_SIZE * 2; i++) { if ((rc = fh2.AllocatePage(ph)) || (rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); if (i != pageNum) { cout << "Page number is incorrect:" << (int)pageNum << " " << i << "\n"; exit(1); } memcpy(pData, (char*)&pageNum, sizeof(PageNum)); // memcpy(pData + PF_PAGE_SIZE - sizeof(PageNum), &pageNum, sizeof(PageNum)); if ((rc = fh2.MarkDirty(pageNum)) || (rc = fh2.UnpinPage(pageNum))) return(rc); if ((rc = fh1.AllocatePage(ph)) || (rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); if (i != pageNum) { cout << "Page number is incorrect:" << (int)pageNum << " " << i << "\n"; exit(1); } memcpy(pData, (char*)&pageNum, sizeof(PageNum)); // memcpy(pData + PF_PAGE_SIZE - sizeof(PageNum), &pageNum, sizeof(PageNum)); if ((rc = fh1.MarkDirty(pageNum)) || (rc = fh1.UnpinPage(pageNum))) return(rc); } cout << "Disposing of alternate additional pages\n"; for (i = PF_BUFFER_SIZE; i < PF_BUFFER_SIZE * 2; i++) { if (i & 1) { if ((rc = fh1.DisposePage(i))) return(rc); } else if ((rc = fh2.DisposePage(i))) return(rc); } cout << "Getting file 2 remaining additional pages\n"; for (i = PF_BUFFER_SIZE; i < PF_BUFFER_SIZE * 2; i++) { if (i & 1) { if ((rc = fh2.GetThisPage(i, ph)) || (rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); memcpy((char *)&temp, pData, sizeof(PageNum)); cout << "Page: " << (int)pageNum << " " << (int)temp << "\n"; if ((rc = fh2.UnpinPage(i))) return(rc); } } cout << "Getting file 1 remaining additional pages\n"; for (i = PF_BUFFER_SIZE; i < PF_BUFFER_SIZE * 2; i++) { if (!(i & 1)) { if ((rc = fh1.GetThisPage(i, ph)) || (rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); memcpy((char *)&temp, pData, sizeof(PageNum)); cout << "Page: " << (int)pageNum << " " << (int)temp << "\n"; if ((rc = fh1.UnpinPage(i))) return(rc); } } cout << "Printing file 2, then file 1\n"; if ((rc = PrintFile(fh2)) || (rc = PrintFile(fh1))) return(rc); cout << "Putting stuff into the holes of file 1\n"; for (i = 0; i < PF_BUFFER_SIZE / 2; i++) { if ((rc = fh1.AllocatePage(ph)) || (rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); memcpy(pData, (char *)&pageNum, sizeof(PageNum)); // memcpy(pData + PF_PAGE_SIZE - sizeof(PageNum), &pageNum, sizeof(PageNum)); if ((rc = fh1.MarkDirty(pageNum)) || (rc = fh1.UnpinPage(pageNum))) return(rc); } cout << "Print file 1 and then close both files\n"; if ((rc = PrintFile(fh1)) || (rc = pfm.CloseFile(fh1)) || (rc = pfm.CloseFile(fh2))) return(rc); cout << "Reopen file 1 and test some error conditions\n"; if ((rc = pfm.OpenFile(FILE1, fh1))) return(rc); // if ((rc = pfm.DestroyFile(FILE1)) != PF_FILEOPEN) { // cout << "Destroy file while open should fail: "; // return(rc); // } if ((rc = fh1.DisposePage(100)) != PF_INVALIDPAGE) { cout << "Dispose invalid page should fail: "; return(rc); } // Get page 1 if ((rc = fh1.GetThisPage(1, ph))) return(rc); if ((rc = fh1.DisposePage(1)) != PF_PAGEPINNED) { cout << "Dispose pinned page should fail: "; return(rc); } if ((rc = ph.GetData(pData)) || (rc = ph.GetPageNum(pageNum))) return(rc); memcpy((char *)&temp, pData, sizeof(PageNum)); if (temp != 1 || pageNum != 1) { cout << "Asked for page 1, got: " << (int)pageNum << " " << (int)temp << "\n"; exit(1); } if ((rc = fh1.UnpinPage(pageNum))) return(rc); if ((rc = fh1.UnpinPage(pageNum)) != PF_PAGEUNPINNED) { cout << "Unpin unpinned page should fail: "; return(rc); } cout << "Opening file 1 twice, printing out both copies\n"; if ((rc = pfm.OpenFile(FILE1, fh2))) return(rc); if ((rc = PrintFile(fh1)) || (rc = PrintFile(fh2))) return(rc); cout << "Closing and destroying both files\n"; if ((rc = pfm.CloseFile(fh1)) || (rc = pfm.CloseFile(fh2)) || (rc = pfm.DestroyFile(FILE1)) || (rc = pfm.DestroyFile(FILE2))) return(rc); // If we are dealing with statistics then we should output the final // numbers #ifdef PF_STATS PF_Statistics(); PF_ConfirmStatistics(); #endif // Return ok return (0); } RC TestHash() { PF_HashTable ht(PF_HASH_TBL_SIZE); RC rc; int i, s; PageNum p; cout << "Testing hash table. Inserting entries\n"; for (i = 1; i < 11; i++) for (p = 1; p < 11; p++) if ((rc = ht.Insert(i, p, i + p))) return(rc); cout << "Searching for entries\n"; for (i = 1; i < 11; i++) for (p = 1; p < 11; p++) if ((rc = ht.Find(i, p, s))) return(rc); cout << "Deleting entries in reverse order\n"; for (p = 10; p > 0; p--) for (i = 10; i > 0; i--) if ((rc = ht.Delete(i,p))) return(rc); cout << "Ensuring all entries were deleted\n"; for (i = 1; i < 11; i++) for (p = 1; p < 11; p++) if ((rc = ht.Find(i, p, s)) != PF_HASHNOTFOUND) { cout << "Find deleted hash entry should fail: "; return(rc); } // Return ok return (0); } int main() { RC rc; // Write out initial starting message cerr.flush(); cout.flush(); cout << "Starting PF layer test.\n"; cout.flush(); // If we are tracking the PF Layer statistics #ifdef PF_STATS cout << "Note: Statistics are turned on.\n"; #endif // Delete files from last time unlink(FILE1); unlink(FILE2); // Do tests if ((rc = TestPF()) || (rc = TestHash())) { PF_PrintError(rc); return (1); } // Write ending message and exit cout << "Ending PF layer test.\n\n"; return (0); } <file_sep>/src/statistics.cc // // statistics.cc // // This file holds the implementation for the StatisticsMgr class. // // The class is designed to dynamically track statistics for the client. // You can add any statistic that you would like to track via a call to // StatisticsMgr::Register. // There is no need to setup in advance which statistics that you want to // track. The call to Register is sufficient. // This is essentially a (poor-man's) simplified version of gprof. // <NAME>, who was the TA for the 2000 offering has written // some (or maybe all) of this code. #include <cstring> #include <iostream> #include "statistics.h" using namespace std; // // Here are Statistics Keys utilized by the PF layer of the Redbase // project. // const char *PF_GETPAGE = "GETPAGE"; const char *PF_PAGEFOUND = "PAGEFOUND"; const char *PF_PAGENOTFOUND = "PAGENOTFOUND"; const char *PF_READPAGE = "READPAGE"; // IO const char *PF_WRITEPAGE = "WRITEPAGE"; // IO const char *PF_FLUSHPAGES = "FLUSHPAGES"; // // Statistic class // // This class will track a single statistic // // Default Constructor utilized by the templates // Statistic::Statistic() { psKey = NULL; iValue = 0; } // // Constructor utilized by the StatisticMgr class // // We are assured by the StatisticMgr that psKey_ is not a NULL pointer. // Statistic::Statistic(const char *psKey_) { psKey = new char[strlen(psKey_) + 1]; strcpy (psKey, psKey_); iValue = 0; } // // Copy constructor // Statistic::Statistic(const Statistic &stat) { psKey = new char[strlen(stat.psKey)+1]; strcpy (psKey, stat.psKey); iValue = stat.iValue; } // // Equality constructor // Statistic& Statistic::operator=(const Statistic &stat) { if (this==&stat) return *this; delete [] psKey; psKey = new char[strlen(stat.psKey)+1]; strcpy (psKey, stat.psKey); iValue = stat.iValue; return *this; } // // Destructor // Statistic::~Statistic() { delete [] psKey; } Boolean Statistic::operator==(const char *psKey_) const { return (strcmp(psKey_, psKey)==0); } // -------------------------------------------------------------- // // StatisticMgr class // // This class will track a dynamic list of statistics. // // // Register // // Register a change to a statistic. The psKey is the char* name of // the statistic to be tracked. This method will look for the statistic // name withing its list of statistics and perform the operation over the // stored value. The piValue is utilized for some of the operations. // // Note: if the statistic isn't found (as it will not be the very first // time) then it will be initialized to 0 - the default value. // RC StatisticsMgr::Register (const char *psKey, const Stat_Operation op, const int *const piValue) { int i, iCount; Statistic *pStat = NULL; if (psKey==NULL || (op != STAT_ADDONE && piValue == NULL)) return STAT_INVALID_ARGS; iCount = llStats.GetLength(); for (i=0; i < iCount; i++) { pStat = llStats[i]; if (*pStat == psKey) break; } // Check to see if we found the Stat if (i==iCount) // We haven't found it so create a new statistic // with the key psKey and initial value of 0. pStat = new Statistic( psKey ); // Now perform the operation over the statistic switch (op) { case STAT_ADDONE: pStat->iValue++; break; case STAT_ADDVALUE: pStat->iValue += *piValue; break; case STAT_SETVALUE: pStat->iValue = *piValue; break; case STAT_MULTVALUE: pStat->iValue *= *piValue; break; case STAT_DIVVALUE: pStat->iValue = (int) (pStat->iValue/(*piValue)); break; case STAT_SUBVALUE: pStat->iValue -= *piValue; break; }; // Finally, if the statistic wasn't in the original list then add it to // the list. // JASON:: Confirm that it makes a copy of the object in line 229 of // linkedlist.h. if (i==iCount) { llStats.Append(*pStat); delete pStat; } return 0; } // // Print // // Print out the information pertaining to a specific statistic RC StatisticsMgr::Print(const char *psKey) { if (psKey==NULL) return STAT_INVALID_ARGS; int *iValue = Get(psKey); if (iValue) cout << psKey << "::" << *iValue << "\n"; else return STAT_UNKNOWN_KEY; delete iValue; return 0; } // // Get // // The Get method will return a pointer to the integer value associated // with a particular statistic. If it cannot find the statistic then it // will return NULL. The caller must remember to delete the memory // returned when done. // int *StatisticsMgr::Get(const char *psKey) { int i, iCount; Statistic *pStat = NULL; iCount = llStats.GetLength(); for (i=0; i < iCount; i++) { pStat = llStats[i]; if (*pStat == psKey) break; } // Check to see if we found the Stat if (i==iCount) return NULL; return new int(pStat->iValue); } // // Print // // Print out all the statistics tracked // void StatisticsMgr::Print() { int i, iCount; Statistic *pStat = NULL; iCount = llStats.GetLength(); for (i=0; i < iCount; i++) { pStat = llStats[i]; cout << pStat->psKey << "::" << pStat->iValue << "\n"; } } // // Reset // // Reset a specific statistic. The easiest way to do this is to remove it // completely from the list // RC StatisticsMgr::Reset(const char *psKey) { int i, iCount; Statistic *pStat = NULL; if (psKey==NULL) return STAT_INVALID_ARGS; iCount = llStats.GetLength(); for (i=0; i < iCount; i++) { pStat = llStats[i]; if (*pStat == psKey) break; } // If we found the statistic then remove it from the list if (i!=iCount) llStats.Delete(i); else return STAT_UNKNOWN_KEY; return 0; } // // Reset // // Reset all of the statistics. The easiest way is to tell the linklist of // elements to Erase itself. // void StatisticsMgr::Reset() { llStats.Erase(); } <file_sep>/src/rm_test_bitmap.cc // // File: rm_test_bitmap.cc // Description: Test RM_Bitmap // Author: <NAME> // // This test verifies the behavior of the RM_Bitmap class // #include <assert.h> #include <iostream> #include <cstring> #include "rm_bitmap.h" using namespace std; // // PrintError // // Desc: Print an error message by calling the proper component-specific // print-error function // TODO(Xi): Refactor this to a rm_test_util.h void PrintError(RC rc) { if (abs(rc) <= END_PF_WARN) PF_PrintError(rc); else if (abs(rc) <= END_RM_WARN) RM_PrintError(rc); else cerr << "Error code out of range: " << rc << "\n"; } // // BitmapSetAndTestTest // // Desc: Basic testing of bitmap's set, unset and test functionalities void BitmapSetAndTestTest(int len) { RC rc; int byteLen = len / 8 + (len % 8 != 0); char* data = (char*)malloc(byteLen * sizeof(char)); memset(data, 0, byteLen); RM_Bitmap bitmap(len, data); // Verify that all bits are unset at beginning for (int i = 0; i < len; i++) { bool val; if ((rc = bitmap.Test(i, val))) { PrintError(rc); exit(1); } assert(!val); } // Set and test all bits for (int i = 0; i < len; i++) { if ((rc = bitmap.Set(i))) { PrintError(rc); exit(1); } } for (int i = 0; i < len; i++) { bool val; if ((rc = bitmap.Test(i, val))) { PrintError(rc); exit(1); } assert(val); } // Unset and test all bits for (int i = 0; i < len; i++) { if ((rc = bitmap.Unset(i))) { PrintError(rc); exit(1); } } for (int i = 0; i < len; i++) { bool val; if ((rc = bitmap.Test(i, val))) { PrintError(rc); exit(1); } assert(!val); } free(data); } // // BitmapErrorTest // // Desc: Test negative cases when using bitmap incorretly void BitmapErrorTest() { RC rc; int len = 100; int byteLen = len / 8 + (len % 8 != 0); char* data = (char*)malloc(byteLen * sizeof(char)); memset(data, 0, byteLen); RM_Bitmap bitmap(len, data); // Test the error case for RM_BITMAP_OUTOFRANGE rc = bitmap.Set(len + 100); assert(rc == RM_BITMAP_OUTOFRANGE); rc = bitmap.Unset(len + 1000); assert(rc == RM_BITMAP_OUTOFRANGE); bool val; rc = bitmap.Test(len + 1234, val); assert(rc == RM_BITMAP_OUTOFRANGE); } // // BitmapFindFirstUnsetTest // // Desc: Test the use of FindFirstUnset void BitmapFindFirstUnsetTest(int len) { RC rc; int byteLen = len / 8 + (len % 8 != 0); char* data = (char*)malloc(byteLen * sizeof(char)); memset(data, 0, byteLen); RM_Bitmap bitmap(len, data); // Find first unset bit and then set it sequentially for (int i = 0; i < len; i++) { unsigned int firstUnsetIdx; if ((rc = bitmap.FindFirstUnset(firstUnsetIdx))) { PrintError(rc); exit(1); } assert(firstUnsetIdx == (unsigned int)i); if ((rc = bitmap.Set(firstUnsetIdx))) { PrintError(rc); exit(1); } } unsigned int idx; assert(bitmap.FindFirstUnset(idx) == RM_BITMAP_FULL); } int main(int argc, char* argv[]) { BitmapSetAndTestTest(20); BitmapSetAndTestTest(1000); BitmapSetAndTestTest(12345); BitmapErrorTest(); BitmapFindFirstUnsetTest(1234); BitmapFindFirstUnsetTest(4345); BitmapFindFirstUnsetTest(1 << 16); return 0; } <file_sep>/src/pf_manager.cc // // File: pf_manager.cc // Description: PF_Manager class implementation // Authors: <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // #include <cstdio> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "pf_internal.h" #include "pf_buffermgr.h" // // PF_Manager // // Desc: Constructor - intended to be called once at begin of program // Handles creation, deletion, opening and closing of files. // It is associated with a PF_BufferMgr that manages the page // buffer and executes the page replacement policies. // PF_Manager::PF_Manager() { // Create Buffer Manager pBufferMgr = new PF_BufferMgr(PF_BUFFER_SIZE); } // // ~PF_Manager // // Desc: Destructor - intended to be called once at end of program // Destroys the buffer manager. // All files are expected to be closed when this method is called. // PF_Manager::~PF_Manager() { // Destroy the buffer manager objects delete pBufferMgr; } // // CreateFile // // Desc: Create a new PF file named fileName // In: fileName - name of file to create // Ret: PF return code // RC PF_Manager::CreateFile (const char *fileName) { int fd; // unix file descriptor int numBytes; // return code form write syscall // Create file for exclusive use if ((fd = open(fileName, #ifdef PC O_BINARY | #endif O_CREAT | O_EXCL | O_WRONLY, CREATION_MASK)) < 0) return (PF_UNIX); // Initialize the file header: must reserve FileHdrSize bytes in memory // though the actual size of FileHdr is smaller char hdrBuf[PF_FILE_HDR_SIZE]; // So that Purify doesn't complain memset(hdrBuf, 0, PF_FILE_HDR_SIZE); PF_FileHdr *hdr = (PF_FileHdr*)hdrBuf; hdr->firstFree = PF_PAGE_LIST_END; hdr->numPages = 0; // Write header to file if((numBytes = write(fd, hdrBuf, PF_FILE_HDR_SIZE)) != PF_FILE_HDR_SIZE) { // Error while writing: close and remove file close(fd); unlink(fileName); // Return an error if(numBytes < 0) return (PF_UNIX); else return (PF_HDRWRITE); } // Close file if(close(fd) < 0) return (PF_UNIX); // Return ok return (0); } // // DestroyFile // // Desc: Delete a PF file named fileName (fileName must exist and not be open) // In: fileName - name of file to delete // Ret: PF return code // RC PF_Manager::DestroyFile (const char *fileName) { // Remove the file if (unlink(fileName) < 0) return (PF_UNIX); // Return ok return (0); } // // OpenFile // // Desc: Open the paged file whose name is "fileName". It is possible to open // a file more than once, however, it will be treated as 2 separate files // (different file descriptors; different buffers). Thus, opening a file // more than once for writing may corrupt the file, and can, in certain // circumstances, crash the PF layer. Note that even if only one instance // of a file is for writing, problems may occur because some writes may // not be seen by a reader of another instance of the file. // In: fileName - name of file to open // Out: fileHandle - refer to the open file // this function modifies local var's in fileHandle // to point to the file data in the file table, and to point to the // buffer manager object // Ret: PF_FILEOPEN or other PF return code // RC PF_Manager::OpenFile (const char *fileName, PF_FileHandle &fileHandle) { int rc; // return code // Ensure file is not already open if (fileHandle.bFileOpen) return (PF_FILEOPEN); // Open the file if ((fileHandle.unixfd = open(fileName, #ifdef PC O_BINARY | #endif O_RDWR)) < 0) return (PF_UNIX); // Read the file header { int numBytes = read(fileHandle.unixfd, (char *)&fileHandle.hdr, sizeof(PF_FileHdr)); if (numBytes != sizeof(PF_FileHdr)) { rc = (numBytes < 0) ? PF_UNIX : PF_HDRREAD; goto err; } } // Set file header to be not changed fileHandle.bHdrChanged = FALSE; // Set local variables in file handle object to refer to open file fileHandle.pBufferMgr = pBufferMgr; fileHandle.bFileOpen = TRUE; // Return ok return 0; err: // Close file close(fileHandle.unixfd); fileHandle.bFileOpen = FALSE; // Return error return (rc); } // // CloseFile // // Desc: Close file associated with fileHandle // The file should have been opened with OpenFile(). // Also, flush all pages for the file from the page buffer // It is an error to close a file with pages still fixed in the buffer. // In: fileHandle - handle of file to close // Out: fileHandle - no longer refers to an open file // this function modifies local var's in fileHandle // Ret: PF return code // RC PF_Manager::CloseFile(PF_FileHandle &fileHandle) { RC rc; // Ensure fileHandle refers to open file if (!fileHandle.bFileOpen) return (PF_CLOSEDFILE); // Flush all buffers for this file and write out the header if ((rc = fileHandle.FlushPages())) return (rc); // Close the file if (close(fileHandle.unixfd) < 0) return (PF_UNIX); fileHandle.bFileOpen = FALSE; // Reset the buffer manager pointer in the file handle fileHandle.pBufferMgr = NULL; // Return ok return 0; } // // ClearBuffer // // Desc: Remove all entries from the buffer manager. // This routine will be called via the system command and is only // really useful if the user wants to run some performance // comparison starting with an clean buffer. // In: Nothing // Out: Nothing // Ret: Returns the result of PF_BufferMgr::ClearBuffer // It is a code: 0 for success, something else for a PF error. // RC PF_Manager::ClearBuffer() { return pBufferMgr->ClearBuffer(); } // // PrintBuffer // // Desc: Display all of the pages within the buffer. // This routine will be called via the system command. // In: Nothing // Out: Nothing // Ret: Returns the result of PF_BufferMgr::PrintBuffer // It is a code: 0 for success, something else for a PF error. // RC PF_Manager::PrintBuffer() { return pBufferMgr->PrintBuffer(); } // // ResizeBuffer // // Desc: Resizes the buffer manager to the size passed in. // This routine will be called via the system command. // In: The new buffer size // Out: Nothing // Ret: Returns the result of PF_BufferMgr::ResizeBuffer // It is a code: 0 for success, PF_TOOSMALL when iNewSize // would be too small. // RC PF_Manager::ResizeBuffer(int iNewSize) { return pBufferMgr->ResizeBuffer(iNewSize); } //------------------------------------------------------------------------------ // Three Methods for manipulating raw memory buffers. These memory // locations are handled by the buffer manager, but are not // associated with a particular file. These should be used if you // want memory that is bounded by the size of the buffer pool. // // The PF_Manager just passes the calls down to the Buffer manager. //------------------------------------------------------------------------------ RC PF_Manager::GetBlockSize(int &length) const { return pBufferMgr->GetBlockSize(length); } RC PF_Manager::AllocateBlock(char *&buffer) { return pBufferMgr->AllocateBlock(buffer); } RC PF_Manager::DisposeBlock(char *buffer) { return pBufferMgr->DisposeBlock(buffer); } <file_sep>/src/rm_error.cc // // File: rm_error.cc // Description: RM_PrintError function // Authors: <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // #include <cerrno> #include <cstdio> #include <iostream> #include "rm.h" using namespace std; // // Error table // static char *RM_WarnMsg[] = { }; static char *RM_ErrorMsg[] = { (char*)"index out of bitmap's boundary" }; // // RM_PrintError // // Desc: Send a message corresponding to a RM return code to cerr // Assumes RM_UNIX is last valid RM return code // In: rc - return code for which a message is desired // void RM_PrintError(RC rc) { // Check the return code is within proper limits if (rc >= START_RM_WARN && rc <= RM_LASTWARN) // Print warning cerr << "RM warning: " << RM_WarnMsg[rc - START_RM_WARN] << "\n"; // Error codes are negative, so invert everything else if (-rc >= -START_RM_ERR && -rc < -RM_LASTERROR) // Print error cerr << "RM error: " << RM_ErrorMsg[-rc + START_RM_ERR] << "\n"; else if (rc == 0) cerr << "RM_PrintError called with return code of 0\n"; else cerr << "RM error: " << rc << " is out of bounds\n"; } <file_sep>/src/pf_statistics.cc // // pf_statistics.cc // // This file contains the procedure to display all the statistics for the // PF layer. // Code written by <NAME>, who was the TA for 2000 // // This file only makes sense when the PF Statistics layer is defined // #ifdef PF_STATS #include <iostream> #include "pf.h" #include "statistics.h" using namespace std; // This is defined within pf_buffermgr.cc extern StatisticsMgr *pStatisticsMgr; void PF_Statistics() { // First get all the statistics, must remember to delete memory returned int *piGP = pStatisticsMgr->Get(PF_GETPAGE); int *piPF = pStatisticsMgr->Get(PF_PAGEFOUND); int *piPNF = pStatisticsMgr->Get(PF_PAGENOTFOUND); int *piRP = pStatisticsMgr->Get(PF_READPAGE); int *piWP = pStatisticsMgr->Get(PF_WRITEPAGE); int *piFP = pStatisticsMgr->Get(PF_FLUSHPAGES); cout << "PF Layer Statistics\n"; cout << "-------------------\n"; cout << "Total number of calls to GetPage Routine: "; if (piGP) cout << *piGP; else cout << "None"; cout << "\n Number found: "; if (piPF) cout << *piPF; else cout << "None"; cout << "\n Number not found: "; if (piPNF) cout << *piPNF; else cout << "None"; cout << "\n-------------------\n"; cout << "Number of read requests: "; if (piRP) cout << *piRP; else cout << "None"; cout << "\nNumber of write requests: "; if (piWP) cout << *piWP; else cout << "None"; cout << "\n-------------------\n"; cout << "Number of flushes: "; if (piFP) cout << *piFP; else cout << "None"; cout << "\n-------------------\n"; // Must delete the memory returned from StatisticsMgr::Get delete piGP; delete piPF; delete piPNF; delete piRP; delete piWP; delete piFP; } #endif <file_sep>/src/rm_test.cc // // File: rm_testshell.cc // Description: Test RM component // Authors: <NAME> // <NAME> (<EMAIL>) // <NAME> (<EMAIL>) // // This test shell contains a number of functions that will be useful // in testing your RM component code. In addition, a couple of sample // tests are provided. The tests are by no means comprehensive, however, // and you are expected to devise your own tests to test your code. // // 1997: Tester has been modified to reflect the change in the 1997 // interface. For example, FileHandle no longer supports a Scan over the // relation. All scans are done via a FileScan. // #include <cstdio> #include <iostream> #include <cstring> #include <unistd.h> #include <cstdlib> #include "redbase.h" #include "pf.h" #include "rm.h" using namespace std; // // Defines // #define FILENAME "testrel" // test file name #define STRLEN 29 // length of string in testrec #define PROG_UNIT 50 // how frequently to give progress // reports when adding lots of recs #define FEW_RECS 20 // number of records added in // // Computes the offset of a field in a record (should be in <stddef.h>) // #ifndef offsetof # define offsetof(type, field) ((size_t)&(((type *)0) -> field)) #endif // // Structure of the records we will be using for the tests // struct TestRec { char str[STRLEN]; int num; float r; }; // // Global PF_Manager and RM_Manager variables // PF_Manager pfm; RM_Manager rmm(pfm); // // Function declarations // RC Test1(void); RC Test2(void); void PrintError(RC rc); void LsFile(char *fileName); void PrintRecord(TestRec &recBuf); RC AddRecs(RM_FileHandle &fh, int numRecs); RC VerifyFile(RM_FileHandle &fh, int numRecs); RC PrintFile(RM_FileHandle &fh); RC CreateFile(char *fileName, int recordSize); RC DestroyFile(char *fileName); RC OpenFile(char *fileName, RM_FileHandle &fh); RC CloseFile(char *fileName, RM_FileHandle &fh); RC InsertRec(RM_FileHandle &fh, char *record, RID &rid); RC UpdateRec(RM_FileHandle &fh, RM_Record &rec); RC DeleteRec(RM_FileHandle &fh, RID &rid); RC GetNextRecScan(RM_FileScan &fs, RM_Record &rec); // // Array of pointers to the test functions // #define NUM_TESTS 2 // number of tests int (*tests[])() = // RC doesn't work on some compilers { Test1, Test2 }; // // main // int main(int argc, char *argv[]) { RC rc; char *progName = argv[0]; // since we will be changing argv int testNum; // Write out initial starting message cerr.flush(); cout.flush(); cout << "Starting RM component test.\n"; cout.flush(); // Delete files from last time unlink(FILENAME); // If no argument given, do all tests if (argc == 1) { for (testNum = 0; testNum < NUM_TESTS; testNum++) if ((rc = (tests[testNum])())) { // Print the error and exit PrintError(rc); return (1); } } else { // Otherwise, perform specific tests while (*++argv != NULL) { // Make sure it's a number if (sscanf(*argv, "%d", &testNum) != 1) { cerr << progName << ": " << *argv << " is not a number\n"; continue; } // Make sure it's in range if (testNum < 1 || testNum > NUM_TESTS) { cerr << "Valid test numbers are between 1 and " << NUM_TESTS << "\n"; continue; } // Perform the test if ((rc = (tests[testNum - 1])())) { // Print the error and exit PrintError(rc); return (1); } } } // Write ending message and exit cout << "Ending RM component test.\n\n"; return (0); } // // PrintError // // Desc: Print an error message by calling the proper component-specific // print-error function // void PrintError(RC rc) { if (abs(rc) <= END_PF_WARN) PF_PrintError(rc); else if (abs(rc) <= END_RM_WARN) RM_PrintError(rc); else cerr << "Error code out of range: " << rc << "\n"; } //////////////////////////////////////////////////////////////////// // The following functions may be useful in tests that you devise // //////////////////////////////////////////////////////////////////// // // LsFile // // Desc: list the filename's directory entry // void LsFile(char *fileName) { char command[80]; sprintf(command, "ls -l %s", fileName); printf("doing \"%s\"\n", command); system(command); } // // PrintRecord // // Desc: Print the TestRec record components // void PrintRecord(TestRec &recBuf) { printf("[%s, %d, %f]\n", recBuf.str, recBuf.num, recBuf.r); } // // AddRecs // // Desc: Add a number of records to the file // RC AddRecs(RM_FileHandle &fh, int numRecs) { RC rc; int i; TestRec recBuf; RID rid; PageNum pageNum; SlotNum slotNum; // We set all of the TestRec to be 0 initially. This heads off // warnings that Purify will give regarding UMR since sizeof(TestRec) // is 40, whereas actual size is 37. memset((void *)&recBuf, 0, sizeof(recBuf)); printf("\nadding %d records\n", numRecs); for (i = 0; i < numRecs; i++) { memset(recBuf.str, ' ', STRLEN); sprintf(recBuf.str, "a%d", i); recBuf.num = i; recBuf.r = (float)i; if ((rc = InsertRec(fh, (char *)&recBuf, rid)) || (rc = rid.GetPageNum(pageNum)) || (rc = rid.GetSlotNum(slotNum))) return (rc); if ((i + 1) % PROG_UNIT == 0){ printf("%d ", i + 1); fflush(stdout); } } if (i % PROG_UNIT != 0) printf("%d\n", i); else putchar('\n'); // Return ok return (0); } // // VerifyFile // // Desc: verify that a file has records as added by AddRecs // RC VerifyFile(RM_FileHandle &fh, int numRecs) { RC rc; int n; TestRec *pRecBuf; RID rid; char stringBuf[STRLEN]; char *found; RM_Record rec; found = new char[numRecs]; memset(found, 0, numRecs); printf("\nverifying file contents\n"); RM_FileScan fs; if ((rc=fs.OpenScan(fh,INT,sizeof(int),offsetof(TestRec, num), NO_OP, NULL, NO_HINT))) return (rc); // For each record in the file for (rc = GetNextRecScan(fs, rec), n = 0; rc == 0; rc = GetNextRecScan(fs, rec), n++) { // Make sure the record is correct if ((rc = rec.GetData((char *&)pRecBuf)) || (rc = rec.GetRid(rid))) goto err; memset(stringBuf,' ', STRLEN); sprintf(stringBuf, "a%d", pRecBuf->num); if (pRecBuf->num < 0 || pRecBuf->num >= numRecs || strcmp(pRecBuf->str, stringBuf) || pRecBuf->r != (float)pRecBuf->num) { printf("VerifyFile: invalid record = [%s, %d, %f]\n", pRecBuf->str, pRecBuf->num, pRecBuf->r); exit(1); } if (found[pRecBuf->num]) { printf("VerifyFile: duplicate record = [%s, %d, %f]\n", pRecBuf->str, pRecBuf->num, pRecBuf->r); exit(1); } found[pRecBuf->num] = 1; } if (rc != RM_EOF) goto err; if ((rc=fs.CloseScan())) return (rc); // make sure we had the right number of records in the file if (n != numRecs) { printf("%d records in file (supposed to be %d)\n", n, numRecs); exit(1); } // Return ok rc = 0; err: fs.CloseScan(); delete[] found; return (rc); } // // PrintFile // // Desc: Print the contents of the file // RC PrintFile(RM_FileScan &fs) { RC rc; int n; TestRec *pRecBuf; RID rid; RM_Record rec; printf("\nprinting file contents\n"); // for each record in the file for (rc = GetNextRecScan(fs, rec), n = 0; rc == 0; rc = GetNextRecScan(fs, rec), n++) { // Get the record data and record id if ((rc = rec.GetData((char *&)pRecBuf)) || (rc = rec.GetRid(rid))) return (rc); // Print the record contents PrintRecord(*pRecBuf); } if (rc != RM_EOF) return (rc); printf("%d records found\n", n); // Return ok return (0); } //////////////////////////////////////////////////////////////////////// // The following functions are wrappers for some of the RM component // // methods. They give you an opportunity to add debugging statements // // and/or set breakpoints when testing these methods. // //////////////////////////////////////////////////////////////////////// // // CreateFile // // Desc: call RM_Manager::CreateFile // RC CreateFile(char *fileName, int recordSize) { printf("\ncreating %s\n", fileName); return (rmm.CreateFile(fileName, recordSize)); } // // DestroyFile // // Desc: call RM_Manager::DestroyFile // RC DestroyFile(char *fileName) { printf("\ndestroying %s\n", fileName); return (rmm.DestroyFile(fileName)); } // // OpenFile // // Desc: call RM_Manager::OpenFile // RC OpenFile(char *fileName, RM_FileHandle &fh) { printf("\nopening %s\n", fileName); return (rmm.OpenFile(fileName, fh)); } // // CloseFile // // Desc: call RM_Manager::CloseFile // RC CloseFile(char *fileName, RM_FileHandle &fh) { if (fileName != NULL) printf("\nClosing %s\n", fileName); return (rmm.CloseFile(fh)); } // // InsertRec // // Desc: call RM_FileHandle::InsertRec // RC InsertRec(RM_FileHandle &fh, char *record, RID &rid) { return (fh.InsertRec(record, rid)); } // // DeleteRec // // Desc: call RM_FileHandle::DeleteRec // RC DeleteRec(RM_FileHandle &fh, RID &rid) { return (fh.DeleteRec(rid)); } // // UpdateRec // // Desc: call RM_FileHandle::UpdateRec // RC UpdateRec(RM_FileHandle &fh, RM_Record &rec) { return (fh.UpdateRec(rec)); } // // GetNextRecScan // // Desc: call RM_FileScan::GetNextRec // RC GetNextRecScan(RM_FileScan &fs, RM_Record &rec) { return (fs.GetNextRec(rec)); } ///////////////////////////////////////////////////////////////////// // Sample test functions follow. // ///////////////////////////////////////////////////////////////////// // // Test1 tests simple creation, opening, closing, and deletion of files // RC Test1(void) { RC rc; RM_FileHandle fh; printf("test1 starting ****************\n"); if ((rc = CreateFile(FILENAME, sizeof(TestRec))) || (rc = OpenFile(FILENAME, fh)) || (rc = CloseFile(FILENAME, fh))) return (rc); LsFile(FILENAME); if ((rc = DestroyFile(FILENAME))) return (rc); printf("\ntest1 done ********************\n"); return (0); } // // Test2 tests adding a few records to a file. // RC Test2(void) { RC rc; RM_FileHandle fh; printf("test2 starting ****************\n"); if ((rc = CreateFile(FILENAME, sizeof(TestRec))) || (rc = OpenFile(FILENAME, fh)) || (rc = AddRecs(fh, FEW_RECS)) || (rc = CloseFile(FILENAME, fh))) return (rc); LsFile(FILENAME); if ((rc = DestroyFile(FILENAME))) return (rc); printf("\ntest2 done ********************\n"); return (0); } <file_sep>/src/pf_test3.cc // // File: pf_test3.cc // Description: Tests Main Memory Allocation component of PF // Authors: <NAME> (<EMAIL>) // // 1998: This tester will test the handling of main memory allocation // that the PF_Manager class now allows. Students may now use the // PF manager as both the interface to the disk and also as a heap for // internal structures. // // Students can use the methods: GetBlockSize, AllocateBlock and // DisposeBlock to build in memory structures that are limited by the // size of the buffer pool. For example if a student wanted to do // sort-merge-join (for QL or EX) then they can use the PF Manager to // give them a heap of memory where they can do the sorting. // #include <cstdio> #include <iostream> #include <cstring> #include <unistd.h> #include "pf.h" #include "pf_internal.h" #include "pf_hashtable.h" using namespace std; // // Defines // #define FILE1 "file1" #define FILE2 "file2" // Allocate a group of main memory pages from the buffer RC AllocateChunk(PF_Manager &pfm, int iBlocks, char *ptr[]); // Verify chunks that were allocated in the buffer RC VerifyChunks(int iBlocks, char *ptr[]); // Dispose of the chunks from the buffer pool RC DisposeChunk(PF_Manager &pfm, int iBlocks, char *ptr[]); RC TestChunk(); // // AllocateChunk // RC AllocateChunk(PF_Manager &pfm, int iBlocks, char *ptr[]) { RC rc = OK_RC; int i; cout << "Asking for " << iBlocks << " chunks from the buffer manager: "; // for (i = 0; i < PF_BUFFER_SIZE; i++) { for (i = 0; i < iBlocks; i++) { if ((rc = pfm.AllocateBlock(ptr[i]))) break; // Put some simple data inside memcpy (ptr[i], (void *) &i, sizeof(int)); } return rc; } // // VerifyChunks // RC VerifyChunks(int iBlocks, char *ptr[]) { int i; cout << "Verifying the contents of " << iBlocks << " chunks from the buffer manager: "; for (i = 0; i < iBlocks; i++) { int k; memcpy ((void *)&k, ptr[i], sizeof(int)); if (k!=i) return 1; } return 0; } // // DisposeChunk // RC DisposeChunk(PF_Manager &pfm, int iBlocks, char *ptr[]) { RC rc = OK_RC; int i; cout << "Disposing of " << iBlocks << " chunks from the buffer manager: "; // for (i = 0; i < PF_BUFFER_SIZE; i++) { for (i = 0; i < iBlocks; i++) { if ((rc = pfm.DisposeBlock(ptr[i]))) break; } return rc; } RC TestChunk() { PF_Manager pfm; RC rc; char *ptr[10]; if ((rc = AllocateChunk(pfm, 10, ptr))) { cout << "FAILED!\a\a\n"; return rc; } cout << "Pass\n"; if ((rc = VerifyChunks(10, ptr))) { cout << "FAILED!\a\a\n"; return rc; } cout << "Pass\n"; if ((rc = DisposeChunk(pfm, 5, ptr))) { cout << "FAILED!\a\a\n"; return rc; } cout << "Pass\n"; // Verify the first 5 chunks, notice that this passes okay! This is // a bit odd since we have Disposed of the first 5 chunks. // However, things have not changed since then and the memory is // sitting there for awhile before someone else comes along and asks // to change it. if ((rc = VerifyChunks(10, ptr))) { cout << "FAILED!\a\a\n"; return rc; } cout << "Pass\n"; // Now five chunks are left in the buffer // Ask for 35 chunks char *ptr2[35]; if ((rc = AllocateChunk(pfm, 35, ptr2))) { cout << "FAILED!\a\a\n"; return rc; } cout << "Pass\n"; char *ptr3[1]; ptr3[0] = NULL; // Now ask for one more chunk -- shouldn't be able to do it with // buffer pool size of 40. if ((rc = AllocateChunk(pfm, 1, ptr3))==0) { cout << "FAILED!\a\a\n"; return rc; } cout << "Pass\n"; // Now ask to remove a chunk which doesn't exist if ((rc = DisposeChunk(pfm, 1, ptr3))==0) { cout << "FAILED!\a\a\n"; return rc; } cout << "Pass\n"; // Now remove the block of 35 chunks from before if ((rc = DisposeChunk(pfm, 35, ptr2))) { cout << "FAILED!\a\a\n"; return rc; } cout << "Pass\n"; // And ask for 25 more chunks to ensure that I haven't pinned in some // way the previous ones. if ((rc = AllocateChunk(pfm, 25, (ptr2 + 10)))) { cout << "FAILED!\a\a\n"; return rc; } cout << "Pass\n"; // And make sure that all is well... if ((rc = VerifyChunks(25, (ptr2+10)))) { cout << "FAILED!\a\a\n"; return rc; } cout << "Pass\n"; // Finally, leave the chunks that are there lying around. They will // be cleaned up by the PF Manager instance and no purify warnings // should result. return 0; } int main() { RC rc; // Write out initial starting message cerr.flush(); cout.flush(); cout << "Starting PF Chunk layer test.\n"; cout.flush(); // If we are tracking the PF Layer statistics #ifdef PF_STATS cout << "Note: Statistics are turned on.\n"; #endif // Do tests if ((rc = TestChunk())) { PF_PrintError(rc); return (1); } // Write ending message and exit cout << "Ending PF Chunk layer test.\n\n"; return (0); } <file_sep>/README.md # Redbase A remake of Stanford's Redbase Database (CS346 Project) <file_sep>/src/rm_bitmap.cc // // rm_bitmap.cc // // Implementation of Record Manager's bitmap #include "rm_bitmap.h" RM_Bitmap::RM_Bitmap(unsigned int n, char* bits) : len(n), data((unsigned char*)bits) {} RC RM_Bitmap::Set(unsigned int idx) { RC rc; if (idx >= len) { rc = RM_BITMAP_OUTOFRANGE; RM_PrintError(RM_BITMAP_OUTOFRANGE); return rc; } // The idx at the char array that we look for auto data_idx = idx / 8; // The bit position at the char we look for auto bit_idx = idx % 8; // Set the corresponding bit data[data_idx] |= (1 << bit_idx); return OK_RC; } RC RM_Bitmap::Unset(unsigned int idx) { RC rc; if (idx >= len) { rc = RM_BITMAP_OUTOFRANGE; RM_PrintError(RM_BITMAP_OUTOFRANGE); return rc; } // The idx at the char array that we look for auto data_idx = idx / 8; // The bit position at the char we look for auto bit_idx = idx % 8; // Unset the corresponding bit data[data_idx] &= ~(1 << bit_idx); return OK_RC; } RC RM_Bitmap::Test(unsigned int idx, bool& val) { RC rc; if (idx >= len) { rc = RM_BITMAP_OUTOFRANGE; RM_PrintError(RM_BITMAP_OUTOFRANGE); return rc; } // The idx at the char array that we look for auto data_idx = idx / 8; // The bit position at the char we look for auto bit_idx = idx % 8; val = (data[data_idx] & (1 << bit_idx)); return OK_RC; } RC RM_Bitmap::FindFirstUnset(unsigned int& idx) { RC rc; unsigned int slot_num = len / 8 + (len % 8 != 0); for (unsigned int i = 0; i < slot_num; i++) { if (data[i] != 0xFF) { // The first thing is to compute the index of the least significant 0-bit // which represents the first unset bit on this 8-bit slot. Since // __builtin_ffs returns the one plus index of the least signficatn 1-bit // we can compute thie via __builtin_ffs(~data[i]) - 1. unsigned int res = i * 8 + __builtin_ffs(~data[i]) - 1; // Note that we can have unused bit if there is a cut off of the last // char bytes, so we still need to check if res is in the currect range. // If not, then it means bitmap is full if (res >= len) { rc = RM_BITMAP_FULL; return rc; } idx = res; return OK_RC; } } return RM_BITMAP_FULL; } <file_sep>/src/rm_bitmap.h // // rm_bitmap.h // // Record Manager's bitmap interface #ifndef RM_BITMAP_H #define RM_BITMAP_H #include "rm.h" // A bitmap used by the Record Management component to record the slots that are // current used by a page class RM_Bitmap { public: // Initialize a Bitmap for n slots and the bits information is stored in the // given pointer. The bitmap does not make deep copy and directly manipulate // the bits (so that this information gets reflected in a page header). Thus, // it is the caller's responsbility to ensure that the given char has a valid // length of upper_bound(n / 8) RM_Bitmap(unsigned int n, char* bits); // Set and unset a bit, possible error case RM_BITMAP_OUTOFRANGE RC Set(unsigned int idx); RC Unset(unsigned int idx); // Test a bit RC Test(unsigned int idx, bool& val); // Find the first slot that is unset, possible error case RM_BITMAP_FULL RC FindFirstUnset(unsigned int& idx); private: // The number of bits under management unsigned int len; // Point to the start of the char array that represents the bitmap unsigned char* data; }; #endif
9ba4a6af783d268e4db957ae2548dc75de171679
[ "Markdown", "C++" ]
13
C++
xicheng87/Redbase
97ae875d4f58d2b1ee3811d2f2706428e8c9de37
24c742348bf240370594c27ecc6ad44ea68d4bfc
refs/heads/master
<repo_name>BorisUp/instaphoto<file_sep>/app/controllers/pages_controller.rb class PagesController < ApplicationController def landing end def about end end
7e37f6749bf6e9f41ae040d0b5df1dd50a0f5e07
[ "Ruby" ]
1
Ruby
BorisUp/instaphoto
746288bf062cc9b5569ab902d0b5fc4be136c943
3382ca438ed3df36ee23bc52a4f83c9161053dea
refs/heads/main
<file_sep>import folium # to visualize data that’s been manipulated in Python on an interactive leaflet map. import pandas # so we can use our csv file data = pandas.read_csv("Volcanoes.csv") # Loads the csv containing details of the volcanoes lat = list(data["LAT"]) # pulls the Latitude from the data variable as a list lon = list(data["LON"]) elev = list(data["ELEV"]) name = list(data["NAME"]) def color_producer(elevation): # function to color markers based on volcanoes elevation if elevation < 1000: return 'green' elif elevation <= 1000 or elevation <= 3000: return 'orange' else: return 'red' map = folium.Map(location=[38.58, -99.09], zoom_start=5, tiles="Stamen Terrain") # Builds the maps starting location to view fg = folium.FeatureGroup(name="My Map") # create a variable to call multiple features(volcanoes) later for lt, ln, el, nm in zip(lat, lon, elev, name): # zip used to call data from multiple lists in the for loop fg.add_child(folium.CircleMarker(location=[lt,ln], radius = 6, popup=f"Elevation = {el}m\n Name = {nm}", fill_color=color_producer(el), color = 'grey', fill = True, fill_opacity=0.7)) # shows location of volcanoes with styling map.add_child(fg) # every time the for loop runs, add location to map map.save("Map1.html") # save to a html page<file_sep># US_volcanoes A simple Python script that builds a html file and reads data from a CSV to produce a web page that shows the location, elevation and names of volcanoes in the USA.
9353f5edcf163affb7e0a7a8a4aa945d1a16bd60
[ "Markdown", "Python" ]
2
Python
Thealltommo/US_volcanoes
c2d6f1fe8bb1b2866a15b2900f4240c2566f0e6e
7912f8c68f3030e941adca78025a38b86ba67abb
refs/heads/main
<file_sep>import pathlib from pathlib import Path import numpy as np from sklearn.preprocessing import LabelBinarizer import torch from torch.utils.data import Dataset, DataLoader from tqdm import tqdm class MelspMetricDataset(Dataset): def __init__(self, melsp_dir: pathlib.PosixPath, speakers: list = ['jvs001', 'jvs010', 'jvs015', 'jvs018', 'jvs037', 'jvs076'], train: bool = True): self.melsp_paths = self._make_melsp_paths(melsp_dir) self.n_melsp = len(self.melsp_paths) self.train = train self._speakers = speakers self.encoder = LabelBinarizer().fit(self._speakers) def __len__(self): return self.n_melsp def __getitem__(self, index: int): melsp_path = self.melsp_paths[index] out_melsp = self._load_melsp(melsp_path) out_label = self._make_label(melsp_path) # print(melsp_path) return out_melsp, out_label, melsp_path.stem[:6] def _make_label(self, melsp_path: pathlib.PosixPath) -> torch.Tensor: speaker = melsp_path.stem[:6] if speaker in self._speakers: return torch.tensor(1) # real else: return torch.tensor(0) # fake # ================================================================================ # # Instance Method # # ================================================================================ @staticmethod def _make_melsp_paths(melsp_dir: pathlib.PosixPath) -> list: # npyのみを対象とする return [path for path in tqdm(list(melsp_dir.glob('**/*.npy')))] @staticmethod def _load_melsp(melsp_path: pathlib.PosixPath) -> torch.Tensor: melsp = np.load(melsp_path) return torch.from_numpy(melsp).unsqueeze(0) if __name__ == '__main__': root = Path.cwd().joinpath('data/log_melsp') print(root) dataset = MelspMetricDataset(root) print(len(dataset)) melsp, label, speaker = dataset[0] print(melsp.shape, label, speaker) dataloader = DataLoader(dataset, batch_size=8, shuffle=True) num_epoch = 1 for i in range(1, num_epoch + 1): for melsp, label, speaker in tqdm(dataloader): print(melsp.shape, label, speaker) break <file_sep>from pathlib import Path import numpy as np from pytorch_metric_learning.distances import CosineSimilarity from pytorch_metric_learning.losses import TripletMarginLoss from pytorch_metric_learning.miners import TripletMarginMiner from pytorch_metric_learning.reducers import ThresholdReducer import torch import torch.optim as optim from torch.utils.data import DataLoader from tqdm import tqdm from dataloader import MelspMetricDataset from logger import Logger from model import MelspMap def train(model, criterion, miner, dataloader, optimizer, logger, epoch, device): model.train() for i, (inputs, labels, _) in enumerate(tqdm(dataloader)): optimizer.zero_grad() inputs, labels = inputs.to(device), labels.to(device) embeddings = model(inputs) indices = miner(embeddings, labels) loss = criterion(embeddings, labels, indices) loss.backward() optimizer.step() # TensorBoardのログに表示 logger.scalar_summary(f'train/loss', loss, i) if i % 10 == 0 and i != 0: print(f'Epoch {epoch} Iteration {i}: Loss = {loss:.4f}, Number of mined triplets = {miner.num_triplets}') print() def test(model, dataloader, epoch, device): model.eval() _predicted_metrics = [] _true_labels = [] with torch.inference_mode(): for i, (inputs, labels, _) in enumerate(tqdm(dataloader)): inputs, labels = inputs.to(device), labels.to(device) metric = model(inputs).detach().cpu().numpy() metric = metric.reshape(metric.shape[0], metric.shape[1]) _predicted_metrics.append(metric) _true_labels.append(labels.detach().cpu().numpy()) return np.concatenate(_predicted_metrics), np.concatenate(_true_labels) if __name__ == '__main__': epochs = 100 learning_rate = 1e-4 batch_size = 8 device = 'cuda:1' if torch.cuda.is_available() else 'cpu' # データセットの準備 train_dir = Path.cwd().joinpath('data/log_melsp/train/') train_dataset = MelspMetricDataset(train_dir) train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) # モデルと損失関数,最適化手法 model = MelspMap().to(device) logger = Logger('logs') optimizer = optim.Adam(model.parameters(), lr=learning_rate) distance = CosineSimilarity() reducer = ThresholdReducer(low=0) criterion = TripletMarginLoss(margin=0.2, distance=distance, reducer=reducer) miner = TripletMarginMiner(margin=0.2, distance=distance) test_predicted_metrics = [] test_true_labels = [] for epoch in range(1, epochs + 1): print(f'Epoch {epoch}/{epochs}') print('-' * 20) train(model, criterion, miner, train_loader, optimizer, logger, epoch, device) if epoch % 10 == 0: torch.save(model.state_dict(), f'models/ep{epoch}.pt') <file_sep>import torch import torch.nn as nn from torchinfo import summary class ConvBN(nn.Module): def __init__(self, dim_in, dim_out, kernel_size, strides=1, padding=0, bias=True, padding_mode='replicate'): super().__init__() self.conv_layer = nn.Sequential( nn.Conv2d(in_channels=dim_in, out_channels=dim_out, kernel_size=kernel_size, stride=strides, padding=padding, bias=bias), nn.BatchNorm2d(dim_out), nn.ReLU(inplace=True) ) def forward(self, x): return self.conv_layer(x) class MelspMap(nn.Module): """メルスペクトログラムを入力として誰の声かの分類結果を出力するネットワーク.""" def __init__(self): super().__init__() self.conv_branch1 = nn.Sequential( ConvBN(1, 32, kernel_size=(3, 1), strides=(1, 1), padding=(1, 0)), ConvBN(32, 32, kernel_size=(1, 3), strides=(1, 1), padding=(0, 1)), ConvBN(32, 64, kernel_size=(3, 1), strides=(1, 1), padding=(1, 0)), ConvBN(64, 64, kernel_size=(1, 3), strides=(1, 1), padding=(0, 1)), ) self.conv_branch2 = nn.Sequential( ConvBN(1, 32, kernel_size=(9, 1), strides=(1, 1), padding=(4, 0)), ConvBN(32, 32, kernel_size=(1, 9), strides=(1, 1), padding=(0, 4)), ConvBN(32, 64, kernel_size=(9, 1), strides=(1, 1), padding=(4, 0)), ConvBN(64, 64, kernel_size=(1, 9), strides=(1, 1), padding=(0, 4)), ) self.conv_branch3 = nn.Sequential( ConvBN(1, 32, kernel_size=(21, 1), strides=(1, 1), padding=(10, 0)), ConvBN(32, 32, kernel_size=(1, 21), strides=(1, 1), padding=(0, 10)), ConvBN(32, 64, kernel_size=(21, 1), strides=(1, 1), padding=(10, 0)), ConvBN(64, 64, kernel_size=(1, 21), strides=(1, 1), padding=(0, 10)), ) self.conv_branch4 = nn.Sequential( ConvBN(1, 32, kernel_size=(39, 1), strides=(1, 1), padding=(19, 0)), ConvBN(32, 32, kernel_size=(1, 39), strides=(1, 1), padding=(0, 19)), ConvBN(32, 64, kernel_size=(39, 1), strides=(1, 1), padding=(19, 0)), ConvBN(64, 64, kernel_size=(1, 39), strides=(1, 1), padding=(0, 19)), ) self.conv_after = nn.Sequential( ConvBN(256, 128, kernel_size=(5, 1), strides=(1, 1), padding=(2, 0)), ConvBN(128, 128, kernel_size=(5, 1), strides=(1, 1), padding=(2, 0)), ) self.classification = nn.Sequential( nn.Linear(128, 7), # nn.Softmax(dim=1) ) def forward(self, x): b1 = self.conv_branch1(x) b2 = self.conv_branch2(x) b3 = self.conv_branch3(x) b4 = self.conv_branch4(x) # それぞれのブランチをチャネル方向で結合, [N, 256, 80, 128] concat = torch.cat([b1, b2, b3, b4], dim=1) # 畳み込みを行なったのち, Global Average Poolingで各チャネルごとの値を一つに集約 after = self.conv_after(concat) after_gap = torch.mean(after, dim=(2, 3)) # [N, 128, 80, 128] -> [N, 128] # out = self.classification(after_gap) # for classification return after_gap if __name__ == '__main__': input_tensor = torch.rand(1, 1, 80, 128) model = MelspMap() summary(model, input_size=input_tensor.shape) out = model(input_tensor) print(out.shape) <file_sep>from torch.utils.tensorboard import SummaryWriter class Logger(object): def __init__(self, log_dir): self.writer = SummaryWriter(log_dir) def scalar_summary(self, tag, value, step): """lossなどのスカラー値のログを描画する""" self.writer.add_scalar(tag, value, step) self.writer.flush() def figure_summary(self, tag, figure, step): """matplotlibの画像を描画する,混同行列用""" self.writer.add_figure(tag, figure, step) self.writer.flush() def image_batch_summary(self, tag, images, step, format='NCHW'): """白黒画像としてバッチ画像を描画する,log_melsp用""" self.writer.add_images(tag, images, step, dataformats=format) self.writer.flush() def audio_summary(self, tag, audio, step, sr): """音声を埋め込む""" self.writer.add_audio(tag, audio, step, sr) self.writer.flush() def model_summary(self, model, input_to_model): """モデル構造を埋め込む""" self.writer.add_graph(model, input_to_model) self.writer.flush() <file_sep>matplotlib==3.3.4 numpy==1.19.5 Pillow==8.3.2 pytorch-metric-learning==0.9.99 scikit-learn==0.24.2 scipy==1.5.4 tensorboard==2.6.0 torch==1.9.0 torchinfo==1.5.3 torchvision==0.10.0 tqdm==4.62.2 <file_sep>from pathlib import Path import numpy as np import matplotlib.pyplot as plt from sklearn.manifold import TSNE from sklearn.metrics.pairwise import cosine_similarity import torch from torch.utils.data import DataLoader from tqdm import tqdm from dataloader import MelspMetricDataset from model import MelspMap def draw_heatmap(data: np.ndarray, row_labels: list, col_labels: list): """ ヒートマップを描画する関数. Args: data (np.ndarray): 正方行列 row_labels (list): 行メモリ,sklearnのコサイン類似度行列ならx_feature column_labels (list): 列メモリ,sklearnのコサイン類似度行列ならy_feature Returns: [type]: [description] """ fig, ax = plt.subplots() heatmap = ax.pcolor(data, cmap=plt.cm.Blues) # 画素値の中央にメモリがくるように調整 ax.set_xticks(np.arange(data.shape[0]) + 0.5, minor=False) ax.set_yticks(np.arange(data.shape[1]) + 0.5, minor=False) # y軸を上から下に ax.invert_yaxis() ax.xaxis.tick_top() # 軸メモリの指定 ax.set_xticklabels(row_labels, minor=False) ax.set_yticklabels(col_labels, minor=False) # タイトル ax.set_xlabel('y_feature') ax.set_ylabel('x_feature') plt.title('cosine simularity') plt.colorbar(heatmap) plt.savefig('cossim_matrix.png') return heatmap def cossim_matrix(x, y, row_labels, col_labels): cossim = cosine_similarity(x, y) draw_heatmap(cossim, row_labels=row_labels, col_labels=col_labels) print(row_labels) print(col_labels) print(cossim) def test(model, dataloader, device): model.eval() _predicted_metrics = [] _true_labels = [] with torch.inference_mode(): for i, (inputs, labels, _) in enumerate(tqdm(dataloader)): inputs, labels = inputs.to(device), labels.to(device) metric = model(inputs).detach().cpu().numpy() metric = metric.reshape(metric.shape[0], metric.shape[1]) _predicted_metrics.append(metric) _true_labels.append(labels.detach().cpu().numpy()) return np.concatenate(_predicted_metrics), np.concatenate(_true_labels) if __name__ == '__main__': torch.manual_seed(42) device = 'cuda:1' if torch.cuda.is_available() else 'cpu' batch_size = 128 test_dir = Path.cwd().joinpath('data/log_melsp/for_cossim/') test_dataset = MelspMetricDataset(test_dir) test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=True) # モデルの読み込み model = MelspMap() weights = torch.load('models/ep100.pt') model.load_state_dict(weights) model.to(device) # テストデータの写像と真のラベル test_predicted_metrics, test_true_labels = test(model, test_loader, device) # コサイン類似度をみてみる cossim_matrix(test_predicted_metrics[:12], test_predicted_metrics[12:], row_labels=test_true_labels[12:], col_labels=test_true_labels[:12]) # # tSNEで2次元に # tSNE_metrics = TSNE(n_components=2, random_state=42).fit_transform(test_predicted_metrics) # # プロット # plt.scatter(tSNE_metrics[:, 0], tSNE_metrics[:, 1], c=test_true_labels) # plt.colorbar() # plt.savefig('train_test_output.png') <file_sep>from pathlib import Path import matplotlib.pyplot as plt import numpy as np from sklearn.neighbors import NearestNeighbors import torch import torch.nn as nn from torch.utils.data import DataLoader from torchinfo import summary from tqdm import tqdm from dataloader import MelspMetricDataset from model import MelspMap class MelspMetric(nn.Module): """ メルスペクトログラムを128次元の特徴ベクトルに落とし込み, ターゲットのリアルデータ集合のうち最近傍のデータ点との距離を損失として返すクラス. """ def __init__(self, model=None, dataloader=None, metrics=None): super().__init__() self.device = 'cuda:0' if torch.cuda.is_available() else 'cpu' self.model = model.to(device).eval() self.dataloader = dataloader self.metrics = NearestNeighbors # sklearnのニアレストネイバー self.speakers = ['jvs001', 'jvs010', 'jvs015', 'jvs018', 'jvs037', 'jvs076'] self.real_data = {} self.nn_models = {} # リアルデータ集合とNearest Neighborのモデルを作成 self._store_real_data() self._make_nnmodels() def _store_real_data(self): print('storing real data ...') for speaker in self.speakers: self.real_data[speaker] = [] for melsps, labels, speakers in tqdm(self.dataloader): melsps = melsps.to(self.device) feature = self.model(melsps).squeeze().detach().cpu().numpy() for i, s in enumerate(speakers): self.real_data[s].append(feature[i]) def _make_nnmodels(self): """最近傍法に用いるターゲットごとのデータ集合の辞書を返す""" print('make nearest neighbor models ...') for speaker in self.speakers: X = self.real_data[speaker] nn_model = self.metrics(n_neighbors=1, algorithm='ball_tree').fit(X) self.nn_models[speaker] = nn_model def nearest_neighbor(self, melsps: np.ndarray, target_speakers: torch.Tensor) -> torch.Tensor: """ ニアレストネイバー法を用いてリアルのデータ集合内の最近傍点との距離を返す. Args: melsps (np.ndarray): メルスペクトログラム target_speakers (torch.Tensor): 変換先の話者 Returns: torch.Tensor: 最近傍点との距離 """ distances = [] for melsp, target_speaker in zip(melsps, target_speakers): feature = self.model(melsp.unsqueeze(dim=0)).squeeze().detach().cpu().numpy() nn_model = self.nn_models[target_speaker] _distance, _indices = nn_model.kneighbors([feature]) distances.append(_distance) # テスト用 # X = self.real_data['test'] # nn_model = self.metrics(n_neighbors=1, algorithm='ball_tree').fit(X) # distance, indices = nn_model.kneighbors([[2, 3]]) # plt.figure() # plt.title('Nearest neighbors') # plt.scatter(self.real_data['test'][:, 0], self.real_data['test'][:, 1], marker='o', s=75, color='k') # plt.scatter(self.real_data['test'][indices][0][:][:, 0], self.real_data['test'][indices][0][:][:, 1], # marker='o', s=250, color='k', facecolors='none') # plt.scatter(2, 3, marker='x', s=75, color='k') # plt.savefig('nn_test.png') return distances if __name__ == '__main__': torch.manual_seed(42) device = 'cuda:0' if torch.cuda.is_available() else 'cpu' data_root = Path.cwd().joinpath('data/log_melsp/train/origin/') dataset = MelspMetricDataset(data_root) metric_dataloader = DataLoader(dataset, batch_size=8, shuffle=True) melsp_dataloader = DataLoader(dataset, batch_size=8, shuffle=True) metric = MelspMetric(model=MelspMap(), dataloader=metric_dataloader) num_epoch = 1 for i in range(1, num_epoch + 1): for melsp, label, speaker in tqdm(melsp_dataloader): melsp = melsp.to(device) loss_nn = metric.nearest_neighbor(melsps=melsp, target_speakers=speaker) print(loss_nn) break
f310958ff25007bf9081f798c427999be4a07ae6
[ "Python", "Text" ]
7
Python
kargenk/melsp_metric_learn
ffdd9a8970909fe2537ce7ccd134b450d809a283
89905a68a533e17fca084379cc771b876ddc0bf4
refs/heads/master
<repo_name>gunyoung1123/test2<file_sep>/spring1107/src/ex3/AfterThrowAdvice.java package ex3; //예외도 일종의 로그이다. //반환되고 실행되는 부분에대한 예외를 공통관심사항으로 처리하고 싶을 때 public class AfterThrowAdvice { //JoinPoint jp생략.... public void commThrow(Exception ex) { System.out.println("예외 메시지 : "+ex.getMessage()); } } <file_sep>/spring1107/src/ex1/MessageMain.java package ex1; import org.springframework.aop.framework.ProxyFactoryBean; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.NameMatchMethodPointcut; public class MessageMain { public static void main(String[] args) { //1.target객체를 생성한다.//Bean MessageImple target = new MessageImple(); //2.Advice객체를 생성//Bean MessageAdvice advice = new MessageAdvice(); //3.ProxyFactoryBean(본체) ProxyFactoryBean pBean= new ProxyFactoryBean(); //3-1. ProxyFactoryBean에게 target을 지정 , advice 적용 pBean.setTarget(target);//target은하나 //property //setter //pBean.addAdvice(advice);//advice은 추가될 수 있다.//property//setter /* <bean id="pBean" class="ProxyFactoryBean" p:target-ref= target> */ //3-2.Pointcut, Advice를 결합 Advisor를 생성 NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut(); pointcut.setMappedNames("print*"); //ProxyFactoryBean에게 Advisor를 생성해서 넣어준다. pBean.addAdvisor(new DefaultPointcutAdvisor(pointcut, advice)); //MessageInter pr = new MessageImple();과 유사하다. <= Advice가 적용된 MessageInter prMessage = (MessageInter) pBean.getObject(); //지금은 다 실행되지만, 선별해서 실행할 필요가 있다. prMessage.print(); //prMessage.print2(); //prMessage.test(); //prMessage.message(); } } <file_sep>/spring1107/src/ex1/MessageImple.java package ex1; //핵심포인트 : AOP의 원리를 이해하기 위해서 가장 원본적인 인터셉터 기능만 구현 해본다. //목적 : 공통관심사항을 print계열의 메서드에게마 적용한다. public class MessageImple implements MessageInter { @Override public void print() { //System.out.println("타겟보다 먼저 처리될 공통 관심 사항!"); System.out.println("print 메서드 호출"); //System.out.println("타겟이 수행이 된 후 처리될 공통 관심 사항!"); } @Override public void print2() { System.out.println("print2 메서드 호출"); } @Override public void test() { System.out.println("test 메서드 호출"); } @Override public String message() { StringBuilder sb = new StringBuilder(); sb.append("Message가 반환이 되는 로직"); return sb.toString(); } } <file_sep>/spring1107/src/ex2/MyAfterAdvice.java package ex2; import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; public class MyAfterAdvice implements AfterReturningAdvice { //타켓메서드가 실행 된 이후에 적용(mybean에 추가하기) /* * void afterReturning(Object returnValue, * Method method, * Object[] args, * Object target) * */ @Override public void afterReturning(Object returns, Method arg1, Object[] arg2, Object arg3) throws Throwable { System.out.println("메서드의 정보"); System.out.println("Method : "+arg1.getReturnType()); System.out.println("Return : "+returns.toString()); } } <file_sep>/spring1107/src/ex1/MessageInter.java package ex1; //print¸¸ aopÀû¿ë public interface MessageInter { public void print(); public void print2(); public void test(); public String message(); } <file_sep>/spring1107/src/ex3/TodayBeforeAdvice.java package ex3; import org.aspectj.lang.JoinPoint; import org.springframework.beans.factory.annotation.Autowired; public class TodayBeforeAdvice { @Autowired private MyPublic myPublic; public void beforToday(JoinPoint jp) { System.out.println(myPublic.todayMethod()); } } <file_sep>/spring1107/src/ex2/MyBeanImple.java package ex2; public class MyBeanImple implements MyBeanInter { @Override public String myGetMessage(String name) { StringBuilder sb = new StringBuilder(); sb.append("Message : ").append("Test").append("핵심로직 수행"); return sb.toString(); } }
50faf4f38f4af8ada1f29c0f8ecf50a57a0b18ef
[ "Java" ]
7
Java
gunyoung1123/test2
a08fdd2454b80a605f779d77118a768b141abd1f
5a5400ff1bbe0b129f01e4f0c09189fd69d8079b
refs/heads/master
<file_sep> class User: def __init__(self,userid,posts): self.userid = userid self.posts = posts class Post: def __init__(self,postid,totalComment,totalNegComment,totalNegWord): self.postid = postid self.totalComment =totalComment self.totalNegComment=totalNegComment self.totalNegWord =totalNegWord def getPost(postid): for post in posts: if str(post.postid) == str(postid): return post f = open("postids_for_100_users.txt","r") line = f.readline() line = line.strip() index = line.index(":") userid = line[index+1:] posts = [] users = [] for line in f: line = line.strip() if "For the user:" in line: u = User(userid,posts) users.append(u) posts = [] index = line.index(":") userid = line[index+1:] else: index = line.index(":") postid = line[index+1:] posts.append(postid) f.close() f = open("negativity_comments_for_100.txt","r") posts = [] for line in f: line = line.strip() values = line.split(",") post = Post(values[0],values[1],values[2],values[3]) posts.append(post) f.close() print len(posts) f = open("Per_User_negativity.txt","w") for user in users: totalComment = 0 totalNegComment = 0 totalNegWord = 0 for postid in user.posts: post = getPost(postid) totalComment = totalComment + int(post.totalComment) totalNegComment = totalNegComment + int(post.totalNegComment) totalNegWord = totalNegWord + int(post.totalNegWord) negCommentPercentage = float(float(totalNegComment)/float(totalComment)) severityPercentage = float(float(totalNegWord)/float(totalNegComment)) f.write(str(user.userid)+","+str(negCommentPercentage)+","+str(severityPercentage)+"\n") f.close() <file_sep> f = open("PerUserNegCoeffSeverity.txt","r") g = open("PerUserPosCoeffSeverity.txt","r") h = open("PerUserCoeffDifference.txt","w") for line in f: line = line.strip() values = line.split(",") userid = values[0] coeff= float(values[1]) negPercentage = float(values[2]) negSeverity = float(values[3]) line = g.readline() line = line.strip() values = line.split(",") posPercentage = float(values[2]) posSeverity = float(values[3]) percentageRatio = float(negPercentage/posPercentage) severityRatio = float(negSeverity/posSeverity) h.write(str(userid)+","+str(coeff)+","+str(percentageRatio)+","+str(severityRatio)+"\n") print userid print coeff print percentageRatio print severityRatio f.close() g.close() h.close() <file_sep> class Post: def __init__(self,postid,comment,commenterid,commentername): self.postid = postid self.comment = comment self.commenterid=commenterid self.commentername=commentername class User: def __init__(self,userid,posts): self.userid = userid self.posts = posts def getPostFromPostList(postid): for post in posts: if str(post.postid) == str(postid): return post def getPostIDs(owner): for user in users: if str(user.userid) == str(owner): return user.posts def getComments(post,commenterid): count = len(post.comment) commentList = [] while count > 0: commenter = post.comment[count-1] count = count -1 f = open("postids_for_100_users.txt","r") line = f.readline() line = line.strip() index = line.index(":") userid = line[index+1:] posts = [] users = [] for line in f: line = line.strip() if "For the user:" in line: u = User(userid,posts) users.append(u) posts = [] index = line.index(":") userid = line[index+1:] else: index = line.index(":") postid = line[index+1:] posts.append(postid) f.close() f = open("comments_for_100_from_compressed.txt","r") line = f.readline() line = line.strip() index = line.index(":") postid = line[index+1:] comments = [] commenterids = [] commenternames = [] posts = [] for line in f: line = line.strip() if "For the post:" in line: p = Post(postid,comments,commenterids,commenternames) posts.append(p) comments = [] commenterids = [] commenternames = [] index = line.index(":") postid = line[index+1:] elif "comment:" in line: index = line.index(":") comment = line[index+1:] comments.append(comment) elif "userId:" in line: index = line.index(":") commenterid = line[index+1:] commenterids.append(commenterid) elif "username:" in line: index = line.index(":") commentername = line[index+1:] commenternames.append(commentername) f.close() f = open("OwnerCommenterGraphMoreThanSixComment.txt","r") for line in f: line = line.strip() values = line.split(",") commenter = values[0] owner = values[1] postids = getPostIDs(owner) for postid in postids: post = getPostFromPostList(postid) commentList = getComments(post,commenterid) <file_sep>class User: def __init__(self,userid,following,follower,posts): self.userid = userid self.follower = follower self.following = following self.posts = posts class Post: def __init__(self,postid,commenters,commenttexts): self.postid= postid self.commenters = commenters self.commenttexts = commenttexts def getUser(userid): for user in users: if str(user.userid) == str(userid): return user return 0 def getUserByPostId(postid): for user in users: for post in user.posts: if str(post) == str(postid): return user return 0 def getFollowingForPost(postid): for user in users: for post in user.posts: if str(post) == str(postid): return user.following def getFollowerForPost(postid): for user in users: for post in user.posts: if str(post) == str(postid): return user.follower users = [] posts = [] f = open("vine_user_follower_100.txt","r") for line in f: line = line.strip() values = line.split(",") userid = values[1] followerid = values[0] user = getUser(userid) if user == 0: follower = [] following = [] follower.append(followerid) u = User(userid,following,follower,posts) users.append(u) else: user.follower.append(followerid) f.close() f = open("vine_user_following_100.txt","r") for line in f: line = line.strip() values = line.split(",") userid = values[0] followingid = values[1] user = getUser(userid) if user == 0: follower = [] following = [] following.append(followingid) u = User(userid,following,follower,posts) users.append(u) else: user.following.append(followingid) f.close() f = open("postids_for_100_users.txt","r") line = f.readline() line = line.strip() index = line.index(":") userid = line[index+1:] for line in f: line = line.strip() if "For the user:" in line: user = getUser(userid) user.posts = posts posts = [] index = line.index(":") userid = line[index+1:] else: index = line.index(":") postid = line[index+1:] posts.append(postid) f.close() f = open("comments_for_100_from_compressed.txt","r") line = f.readline() line = line.strip() index = line.index(":") postid = line[index+1:] postList = [] commenters = [] commenttexts = [] p = Post(postid,commenters,commenttexts) for line in f: line = line.strip() if "userId:" in line: index = line.index(":") commenters.append(line[index+1:]) elif "comment:" in line: index = line.index(":") commenttexts.append(line[index+1:]) elif "For the post:" in line: postList.append(p) index = line.index(":") postid = line[index+1:] commenters = [] commenttexts = [] p = Post(postid,commenters,commenttexts) f.close() g = open("followerComment.txt","w") h = open("followingComment.txt","w") count = 0 count = 0 for post in postList: postid = post.postid print postid user = getUserByPostId(postid) if user == 0: continue userid = user.userid followers = user.follower followings = user.following commenters = post.commenters loop = len(post.commenttexts)-1 if loop == -1: continue while loop > -1: try: c = post.commenters[loop] ct = post.commenttexts[loop] if c in followers: g.write(str(ct)+"\n") if c in followings: h.write(str(ct)+"\n") loop = loop - 1 except Exception as e: print len(post.commenters) print len(post.commenttexts) print loop print str(e) loop = loop -1 continue print count g.close() <file_sep>#pdf("cpu_load.pdf") #pdf("mem_usage.pdf") fpe<-read.table("commentsData.txt", sep=",") plot_colors <- c("red","blue","black") names(fpe)<-c("numberOfComments", "posPercentage", "posSeverity", "negPercentage" , "negSeverity") xrange <- range(fpe$numberOfComments) yrange <- range(fpe$negPercentage) plot(xrange,yrange, type="n", xlab="Number Of Comments", ylab="negative percentage of posts", cex.lab=1.5,cex.axis=1.5) lines(fpe$numberOfComments, fpe$negPercentage, type="p", lwd=3,lty=1, col="red", pch=1,cex=1.5) #dev.off()<file_sep>import sys, os sys.path.append('/'.join(os.path.dirname(os.path.abspath(__file__)).split('/')[:-1])) import urllib2 import vinepy import json import datetime import time def getPost(vine,user_id,page): posts = vine.get_user_timeline(user_id=user_id,size='20',page = page) return posts def parsePostData(postList,g): for item in postList: for post in item: for i in post: try: g.write(str(i)+":"+str(post[i])+"\n") except Exception as ex: try: g.write(str(i)+":"+str(post[i].encode('utf-8'))+"\n") except Exception: continue g.write("__________________________"+"\n") password = "" g = open("Pass.txt","r") for line in g: password = line break vine = vinepy.API(username='<EMAIL>', password=<PASSWORD>) g.close() f = open("vine_users_sampled_4000.txt","r") g = open("vine_users_post_meta_data_4000_20.txt","w") usersDone = 0 for line in f: line = line.strip() userId = line g.write("For the user:"+str(userId)+"\n") postList = [] try: posts = getPost(vine,userId,'1') except Exception as e: if "permission" in str(e): print "private user" continue if "try again later" in str(e): print "going to sleep" print datetime.datetime.now() time.sleep(900) print "getting up from sleep" posts = getPost(vine,userId,'1') postList.append(posts) parsePostData(postList,g) usersDone = usersDone + 1 print str(usersDone)+" users done!" break f.close() g.close() <file_sep> def computeNegativityPositivity(comments): totalComments = len(comments) totalNegComment = 0 totalNegWord = 0 totalPosComment = 0 totalPosWord = 0 for comment in comments: found = 0 values = comment.split(" ") for word in values: if word in negword: found = 1 totalNegWord = totalNegWord + 1 if found == 1: totalNegComment = totalNegComment + 1 for comment in comments: found = 0 values = comment.split(" ") for word in values: if word in posword: found = 1 totalPosWord = totalPosWord + 1 if found == 1: totalPosComment = totalPosComment + 1 posPercentage = float(float(totalPosComment)/float(totalComments)) posSeverity = float(float(totalPosWord)/float(totalPosComment)) negPercentage = float(float(totalNegComment)/float(totalComments)) negSeverity = float(float(totalNegWord)/float(totalNegComment)) f = open("CommentsData.txt","a") f.write(str(7)+","+str(posPercentage)+","+str(posSeverity)+","+str(negPercentage)+","+str(negSeverity)+"\n") f.close() negword = [] f = open("new_neg_list1.csv","r") for line in f: line = line.strip() negword.append(line) f.close() posword = [] f = open("new_pos_list1.csv","r") for line in f: line = line.strip() posword.append(line) f.close() f = open("PerPostSevenCommentsCommenterscomments.txt","r") comments = [] for line in f: line = line.strip() comments.append(line) f.close() computeNegativityPositivity(comments) <file_sep> def computeNegativity(comments,community): totalComments = len(comments) totalNegComment = 0 totalNegWord = 0 for comment in comments: found = 0 values = comment.split(" ") for word in values: if word in negword: found = 1 totalNegWord = totalNegWord + 1 if found == 1: totalNegComment = totalNegComment + 1 f = open("negativity_per_community_follower.txt","a") f.write(str(community)+","+str(totalComments)+","+str(totalNegComment)+","+str(totalNegWord)+"\n") f.close() negword = [] f = open("new_neg_list1.csv","r") for line in f: line = line.strip() negword.append(line) f.close() f = open("commentsPerCommunityFollowing.txt","r") comments = [] line = f.readline() line = line.strip() index = line.index(":") community = line[index+1:] for line in f: line = line.strip() if "comments for community:" in line: computeNegativity(comments,community) comments = [] index = line.index(":") community = line[index+1:] else: comments.append(line) f.close() <file_sep> import math def calculateCorrelation(l1,l2): sum1 = 0.0 sum2 = 0.0 mean1 = 0.0 mean2 = 0.0 for l in l1: sum1 = sum1 + float(l) for l in l2: sum2 = sum2 + float(l) mean1 = float(sum1/float(len(l1))) mean2 = float(sum2/float(len(l2))) diff1 = [] diff2 = [] squaresum1 = 0.0 squaresum2 = 0.0 for l in l1: diff = 0.0 diff = float(l) - mean1 diff1.append(diff) diff = diff*diff squaresum1 = squaresum1 + diff for l in l2: diff = 0.0 diff = float(l) - mean2 diff2.append(diff) diff = diff*diff squaresum2 = squaresum2 + diff count = 0 combinedSum = 0.0 while count < len(diff1): value1 = float(diff1[count]) value2 = float(diff2[count]) combinedSum = combinedSum + float(value1*value2) count = count + 1 value = math.sqrt(float(squaresum1)*float(squaresum2)) coValue = float(float(combinedSum)/float(value)) print coValue f = open("commentsData.txt","r") numberComments = [] posPer = [] posSev = [] negPer = [] negSev = [] for line in f: line = line.strip() values = line.split(",") numberComments.append(values[0]) posPer.append(values[1]) posSev.append(values[2]) negPer.append(values[3]) negSev.append(values[4]) f.close() calculateCorrelation(numberComments,posPer) calculateCorrelation(numberComments,posSev) calculateCorrelation(numberComments,negPer) calculateCorrelation(numberComments,negSev) <file_sep>import json f = open("Post_meta_100_users.txt","r") g = open("post_info_for_100_users.txt","w") for line in f: line = line.strip() if "json" in line: d = json.loads(line[5:]) likes = d["likes"]["count"] comments = d["comments"]["count"] loops = d["loops"]["count"] postId = d["postId"] verified = d["verified"] g.write(str(postId)+","+str(likes)+","+str(comments)+","+str(loops)+","+str(verified)+"\n") f.close() g.close() <file_sep>class User: def __init__(self,userid,following,follower,posts): self.userid = userid self.follower = follower self.following = following self.posts = posts class Post: def __init__(self,postid,commenters,commenttexts): self.postid= postid self.commenters = commenters self.commenttexts = commenttexts f = open("following_userid_100.txt","r") followers = [] for line in f: line = line.strip() values = line.split(",") followers.append(values[0]) f.close() communities = [] f = open("community_following_leading_eigenvector_100.txt","r") line = f.readline() line = f.readline() for line in f: line = line.strip() communities.append(line) f.close() f = open("comments_for_100_from_compressed.txt","r") line = f.readline() line = line.strip() index = line.index(":") postid = line[index+1:] postList = [] commenters = [] commenttexts = [] p = Post(postid,commenters,commenttexts) for line in f: line = line.strip() if "userId:" in line: index = line.index(":") commenters.append(line[index+1:]) elif "comment:" in line: index = line.index(":") commenttexts.append(line[index+1:]) elif "For the post:" in line: postList.append(p) index = line.index(":") postid = line[index+1:] commenters = [] commenttexts = [] p = Post(postid,commenters,commenttexts) f.close() print len(postList) count = 0 g = open("commentsPerCommunityFollowing.txt","w") for comm in communities: count = count + 1 g.write("comments for community:"+str(count)+"\n") values = comm.split(",") communityFollowers = [] for index in values[0:len(values)-1]: communityFollowers.append(followers[int(index)]) for post in postList: loop = len(post.commenttexts)-1 if loop == -1: continue while loop > -1: try: c = post.commenters[loop] ct = post.commenttexts[loop] if c in communityFollowers: g.write(str(ct)+"\n") loop = loop - 1 except Exception as e: print len(post.commenters) print len(post.commenttexts) print loop print str(e) loop = loop -1 continue g.close() <file_sep> f = open("community_graph_data_follower.txt","r") coeff = [] reci = [] posper = [] possev = [] negper = [] negsev=[] for line in f: line = line.strip() values = line.split(",") coeff.append(values[1]) reci.append(values[2]) posper.append(values[3]) possev.append(values[4]) negper.append(values[5]) negsev.append(values[6]) f.close() count = 0 g = open("diff.txt","w") while count < 18: try: perRatio = float(float(posper[count])/float(negper[count])) sevRatio = float(float(possev[count])/float(negsev[count])) g.write(str(coeff[count])+","+str(reci[count])+","+str(perRatio)+","+str(sevRatio)+"\n") count = count + 1 except Exception: count = count + 1 continue g.close() <file_sep> class User: def __init__(self,userid,followers,posts): self.userid = userid self.followers = followers self.posts = posts class Post: def __init__(self,postid,commenters,userid): self.postid = postid self.userid = userid self.commenters = commenters def getUser(userid): for user in users: if str(user.userid) == str(userid): return user return 0 def getFollowersForPost(postid): for user in users: for post in user.posts: if str(post) == str(postid): return user.followers users = [] posts = [] f = open("vine_user_follower_100.txt","r") for line in f: line = line.strip() values = line.split(",") userid = values[1] followerid = values[0] user = getUser(userid) if user == 0: followers = [] followers.append(followerid) u = User(userid,followers,posts) users.append(u) else: user.followers.append(followerid) f.close() f = open("postids_for_100_users.txt","r") line = f.readline() line = line.strip() index = line.index(":") userid = line[index+1:] for line in f: line = line.strip() if "For the user:" in line: user = getUser(userid) user.posts = posts posts = [] index = line.index(":") userid = line[index+1:] else: index = line.index(":") postid = line[index+1:] posts.append(postid) f.close() f = open("PostsWithCommentersAndOwners.txt","r") postList = [] for line in f: line = line.strip() values = line.split(",") posts = [] postid = values[0] userid = values[len(values)-1] for post in values[1:len(values)-1]: posts.append(post) p = Post(postid,posts,userid) postList.append(p) f.close() f = open("followerCommenterIntersectionGraph.txt","w") for post in postList: try: followers = getFollowersForPost(post.postid) commenters = list(post.commenters) commenters = set(commenters) followers = set(followers) commonusers = list(set(followers).intersection(commenters)) if len(commonusers) > 0: for user in commonusers: f.write(str(post.userid)+","+str(user)+"\n") except Exception: continue f.close() <file_sep> f = open("community_following_leading_eigenvector_100_global_clustering.txt","r") g = open("negativity_per_community_following.txt","r") h = open("positivity_per_community_following.txt","r") i = open("following_reciprocity_for_communities_leading_eigenvector_100.txt","r") j = open("community_graph_data_following.txt","w") for line1 in f: line1 = line1.strip() line2 = g.readline().strip() line3 = h.readline().strip() line4 = i.readline().strip() value1 = line1.split(",") community = value1[0] coeff = value1[1] value2 = line2.split(",") print value2 totalComment = value2[1] totalNegComment = value2[2] totalNegWord = value2[3] try: negPercentage = float(float(totalNegComment)/float(totalComment)) except Exception: negPercentage = 0 try: negSeverity = float(float(totalNegWord)/float(totalNegComment)) except Exception: negSeverity = 0 value3 = line3.split(",") totalComment = value3[1] totalPosComment = value3[2] totalPosWord = value3[3] try: posPercentage = float(float(totalPosComment)/float(totalComment)) except Exception: posPercentage = 0 try: posSeverity = float(float(totalPosWord)/float(totalPosComment)) except Exception: posSeverity = 0 value4 = line4.split(",") reciprocity = value4[1] j.write(str(community)+","+str(coeff)+","+str(reciprocity)+","+str(posPercentage)+","+str(posSeverity)+","+str(negPercentage)+","+str(negSeverity)+"\n") f.close() g.close() h.close() i.close() j.close() <file_sep>#pdf("cpu_load.pdf") #pdf("mem_usage.pdf") fpe<-read.table("diff.txt", sep=",") plot_colors <- c("red","blue","black") names(fpe)<-c("coeff", "reciprocity", "percentageRatio", "severityRatio") xrange <- range(fpe$coeff) yrange <- range(fpe$percentageRatio) plot(xrange,yrange, type="n", xlab="Clustering Coefficient", ylab="positive negative percentage ratio", cex.lab=1.5,cex.axis=1.5) lines(fpe$coeff, fpe$percentageRatio, type="p", lwd=3,lty=1, col="red", pch=1,cex=1.5) #dev.off()<file_sep># NetworkAnalysisAndModelingCourseCodes graduate course network analysis and modeling <file_sep> def computeNegativity(comments): totalComments = len(comments) totalNegComment = 0 totalNegWord = 0 for comment in comments: found = 0 values = comment.split(" ") for word in values: if word in negword: found = 1 totalNegWord = totalNegWord + 1 if found == 1: totalNegComment = totalNegComment + 1 f = open("positivity_other.txt","a") f.write(str(totalComments)+","+str(totalNegComment)+","+str(totalNegWord)+"\n") f.close() negword = [] f = open("new_pos_list1.csv","r") for line in f: line = line.strip() negword.append(line) f.close() f = open("otherComment.txt","r") comments = [] for line in f: line = line.strip() comments.append(line) f.close() computeNegativity(comments) <file_sep> class User: def __init__(self,userid,coeff): self.userid = userid self.coeff = coeff def getUser(userid): for user in users: if str(user.userid) == str(userid): return user f = open("clustetring_coefficient_Full_Graph_nodes_follower1.txt","r") users = [] for line in f: line = line.strip() values = line.split(",") u = User(values[0],values[1]) users.append(u) f.close() f = open("Per_User_negativity.txt","r") g = open("PerUserNegCoeffSeverity.txt","w") for line in f: line = line.strip() values = line.split(",") userid = values[0] user = getUser(userid) g.write(str(userid)+","+str(user.coeff)+","+str(values[1]+","+str(values[2])+"\n")) f.close() g.close()
ab18e19ae1e8ebe405552619cf09d37403914fcf
[ "Markdown", "Python", "R" ]
18
Python
RahatIbnRafiq/NetworkAnalysisAndModelingCourseCodes
e383e1b5b277440e78ce7521ba6f061149a5d9f3
320abb18e5c0a0b802360c353e39813a1cf74b92
refs/heads/master
<file_sep>n, m = map(int , input().split()) result = 0 for i in range(n): data = list(map(int , input().split())) # 현재 줄에서 가장 작은 수 찾기 min_value = min(data) # 가장 작은 수 들 중에서 가장 큰 수 찾기 result = max(result , min_value) print(result) # 최종 답안 제출
663136e8aa8f4a73288584fdc51b6b3b7c4fecf1
[ "Python" ]
1
Python
YkmKangMin/codingTest
b8f1892c33ff0904ed06dcb0c378b4700496c63f
6ae8742f4f70f11c0edfdc6bb6dbacd2ede6462c
refs/heads/main
<file_sep>// -------- MINI EXERCISE 1 // const isGoodDog = true; /* TODO: Uncomment the line above then create a promise, haveTreat, that resolves with the string 'Good dog; have treat' if the above constant is assigned to true and and rejects with the string 'Bad dog; no treat' if assigned false. */ // Defining a promise // const haveTreat = new Promise((resolve, reject) => { // // setTimeout(() => { // if ('Good dog') { // resolve("have treat"); // } else { // reject("Bad dog. No treat. :("); // } // // }, 5000); // }); // // console.log(haveTreat); // promise object // TODO: handle the promise by console logging the result if resolved or rejected // haveTreat // .then((blah)=> { // console.log(blah) // }) // .catch((err)=> { // console.error(err) // }) /* TODO: Refactor the promise above by wrapping the conditional logic of whether to resolve or reject in a setTimeout so that the promise will only resolve or reject after five seconds. */ // -------- MINI EXERCISE 2 /* TODO: using the code from the first mini-exercise, create a function, trainDog, that takes that takes in a single boolean argument, isGoodDog, and returns a promise. This promise has an identical definition as the haveTreat promise from the previous mini exercise. */ // function trainDog (isGoodDog) { // return new Promise((resolve, reject) => { // // setTimeout(() => { // if ('Good dog') { // resolve("have treat"); // } else { // reject("Bad dog. No treat. :("); // } // // }, 5000); // }); // } /* TODO: invoke the trainDog function passing in true as and argument chain then and catch methods to handle the returned promise. Refactor to pass in false to the function. */ // trainDog(true) // .then((data)=> { // console.log(data); // } ) // .catch((data)=> { // console.error(data); // } ) // Write a function named wait that accepts a number as a parameter, and returns a promise // that resolves after the passed number of milliseconds. // // // wait(1000).then(() => console.log('You\'ll see this after 1 second')); // wait(3000).then(() => console.log('You\'ll see this after 3 seconds')); // function wait(ms) { // return new Promise(resolve => setTimeout(resolve, ms)) // } // wait(3000).then(() => console.log('You\'ll see this after 3 seconds')); /* TODO: make a GET request using fetch to the url below to get an array of five cat fact objects. Log the text property of the first cat fact object. Be sure to log possible errors in a catch. */ const catFactsURL = 'https://cat-fact.herokuapp.com/facts'; fetch(catFactsURL) .then(response => response.json()) .then(data =>{ const firCat = data[0]; const { text } = firCat; console.log(text) // console.log(data[0].text); }) .catch(console.error) // -------- MINI EXERCISE 4 /* TODO: Create a new endpoint on https://hookbin.com/ and use fetch to send some POST requests. Experiment with sending different shapes of data in the body of the request. */ // function newEndpoint() { // fetch('https://hookb.in/G9ZoNeDK6oTWGGeQqrXG',{ // method: 'POST', // headers: { // 'Content-Type': 'application/json' // }, // body:JSON.stringify({ // // }) // }) // } /* TODO: fetch(url, {headers: {'Authorization': 'token <PASSWORD>_TOKEN_HERE'}}) Generate a Personal Access Token for the GitHub API.We will use this so that we don't get rate limited when talking to the GitHub API. You can add the token to your requests like this:fetch(url, {headers: {'Authorization': 'token YOUR_TOKEN_HERE'}}) Create a function that accepts a GitHub username, and returns a promise that resolves returning just the date of the last commit that user made. Reference the github api documentation to achieve this.\ */ function lastCommit(user) { return fetch(`https://api.github.com/users/${user}/events`, {headers: {'Authorization': `token ${gitHub}` }}) .then((data) => { // console.log(data); return data.json() }) } lastCommit('emihhorn').then((data) => console.log(data)); //my wifi is spotty and did not git my last push<file_sep> (function() { "use strict" let lat = 34.1941; let lng = -79.7636; // lat: 34.1941, // lon: -79.7636, weatherMap(); function weatherMap() { $.get("https://api.openweathermap.org/data/2.5/onecall", { APPID: OWM_TOKEN, lat: lat, lon: lng, units: "imperial", exclude: "minutely,hourly" }).done(function (data) { console.log(data); renderHtml(data); }); } //this function adds data to html bootstrap cards and displaya the weather function renderHtml(data) { var html = ""; for(var i = 0; i < 5; i += 1) { let tempMax = data.daily[i].temp.max; let tempMin = data.daily[i].temp.min; let description = data.daily[i].weather[0].description; let windSpeed = data.daily[i].wind_speed; let pressure = data.daily[i].pressure; let humidity = data.daily[i].humidity; let iconCode = data.daily[i].weather[0].icon; let date = data.daily[i].dt; let date1 = new Date (date*1000); let date2 = date1.toLocaleDateString("en-US"); html += "<div class='card' style='width: 15rem;'>"; html += "<div class='card-header text-center'>" + date2 + "</div>"; html += "<ul class='list-group list-group-flush'>"; html += "<li class='list-group-item text-center'>" + tempMax + "°F" + " / " + tempMin + "°F" + "<br>" + "<img src='http://openweathermap.org/img/wn/" + iconCode + ".png'>" ; html += "<li class='list-group-item'>" + "Description: " + "<strong>" + description + "</strong>"; html += "<li class='list-group-item'>" + "Humidity: " + "<strong>" + humidity + "</strong>"; html += "<li class='list-group-item'>" + "Wind: " + "<strong>" + windSpeed + "</strong>"; html += "<li class='list-group-item'>" + "Pressure: " + "<strong>" + pressure + "</strong>"; html += "</ul>"; html += "</div>"; } $("#weather").html(html); } })(); // $.get("https://api.openweathermap.org/data/2.5/onecall", { // APPID: OWM_TOKEN, // lat: 34.1941, // lon: -79.7636, // units: "imperial", // exclude: "minutely, hourly" // }).done(function(data) {}) // console.log(data); //-79.76, 34.19 // fetch(api) // .then(response => { // return response.json(); // }) // .then(data =>{ // console.log(data); // window.addEventListener('load', ()=> { // let long; // let lat; // let temperatureDescription = document.querySelector(".temperature-description"); // let temperatureDegree = document.querySelector(".temperature-degree"); // let locationTimeZone = document.querySelector(".location-timezone"); // // // if(navigator.geolocation) { // navigator.geolocation.getCurrentPosition(position => { // long = position.coords.longitude; // lat = position.coords.latitude; // const proxy = "https://cors-anywhere.herokuapp.com/" // const api = `${proxy}"https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=" + // "${long}units=imperial&exclude=minutely,hourly&appid=" + OWM_TOKEN` //Set DOM Elements from API // temperatureDegree.textContent = temperature; // temperatureDescription.textContent= summary; // }) // // }) // }else{ // alert("Error, But the Weather is always Sunny inside your Heart!") // } // }) // }); // var button = addEventListener('click',function (name) { // fetch("https://api.openweathermap.org/data/2.5/onecall?lat=29.4241&lon=" + // "-98.4936&units=imperial&exclude=minutely,hourly&appid=" + OWM_TOKEN) // .then(response => response.json()) // .then(data => console.log(data)) // }) //youtube tutorial Dev Ed // let nameValue = data['name'] // let tempValue = data['main']['temp'] // let descValue = data['weather'][0]['description'] //17410251e7b42b9f75fd4e1e02e2b9d5 <file_sep>(function() { "use strict"; /** * TODO: * Create an object with firstName and lastName properties that are strings * with your first and last name. Store this object in a variable named * `person`. * * Example: * > console.log(person.firstName) // "Rick" * > console.log(person.lastName) // "Sanchez" */ function addFullNameProperty(obj) { // your code here Object.defineProperty(obj, 'fullName', { get: function(){ return this.firstName + ' ' + this.lastName; }, configurable:false }); } var person = { firstName: 'Emily', lastName: 'Horn' }; addFullNameProperty(person); console.log(person.fullName); // --> '<NAME>' /** * TODO: * Add a sayHello method to the person object that returns a greeting using * the firstName and lastName properties. * console.log the returned message to check your work * * Example * > console.log(person.sayHello()) // "Hello from <NAME>!" */ //alert("Hello World"); person.sayHello = function() { firstName: 'Emily' }; console.log(person.fullName); /** TODO: * HEB has an offer for the shoppers that buy products amounting to * more than $200. If a shopper spends more than $200, they get a 12% * discount. Write a JS program, using conditionals, that logs to the * browser, how much Ryan, Cameron and George need to pay. We know that * Cameron bought $180, Ryan $250 and George $320. Your program will have to * display a line with the name of the person, the amount before the * discount, the discount, if any, and the amount after the discount. * * Uncomment the lines below to create an array of objects where each object * represents one shopper. Use a foreach loop to iterate through the array, * and console.log the relevant messages for each person */ var shoppers = [ {name: 'Cameron', amount: 180}, {name: 'Ryan', amount: 250}, {name: 'George', amount: 320} ]; shoppers.forEach(function(shoppers) { let totalToGetDiscount = 200 let discountPercent =.12 if (shoppers.amount < totalToGetDiscount) { return "NO DISCOUNT" + shoppers.name; } else { } console.log("Before the discount" + shoppers.amount + "After Discount" + discountPercent) }) /** TODO: * Create an array of objects that represent books and store it in a * variable named `books`. Each object should have a title and an author * property. The author property should be an object with properties * `firstName` and `lastName`. Be creative and add at least 5 books to the * array * * Example: * > console.log(books[0].title) // "The Salmon of Doubt" * > console.log(books[0].author.firstName) // "Douglas" * > console.log(books[0].author.lastName) // "Adams" */ //const arrayBooks = // ['JavaScript in 24hrs : <NAME>', // 'JavaScript the Good Parts : <NAME>', // 'Basics Web Design: F3thinker', // 'Teach yourself HTML, CSS : <NAME>', // 'You dont know JS,yet: <NAME>'] //function iterate(Books){ // console.log(Books); //} //Array.prototype.forEach.call(arrayBooks, iterate); /* var books = [ { title:'You dont know JS,yet', author: { firstName: "Kyle", lastName: "Simmon" } }, ] [ { title1:'Teach yourself HTML, CSS, JS', author1: { firstName: "Jennifer", lastName: "Kynin" } }, ] [ { title1:'Basics Web Design', author1: { firstName: "F3", lastName: "Thinker" } }, ] [ { title1:'JavaScript the Good Parts', author1: { firstName: "Douglas ", lastName: "Crockford" } }, ] [ { title1:'JavaScript in 24 Hrs', author1: { firstName: "Douglas ", lastName: "Crockford" } }, ] */ /** * TODO: * Loop through the books array and output the following information about * each book: * - the book number (use the index of the book in the array) * - the book title * - author's full name (first name + last name) * * Example Console Output: * * Book # 1 * Title: The Salmon of Doubt * Author: <NAME> * --- * Book # 2 * Title: Walkaway * Author: <NAME> * --- * Book # 3 * Title: A Brief History of Time * Author: <NAME> * --- * ... */ /** * Bonus: * - Create a function named `createBook` that accepts a title and author * name and returns a book object with the properties described * previously. Refactor your code that creates the books array to instead * use your function. * - Create a function named `showBookInfo` that accepts a book object and * outputs the information described above. Refactor your loop to use your * `showBookInfo` function. */ })(); //})(); //-- Mini Exercise 1 //Create a few beverage objects and assign values to each object for the following properties: // - brandName // - type // - volumeInLiters // - priceInCents // - expirationDate // - datesOfPreviousSips (use an array of strings) //- isOpen //Define your objects using both literal syntax to create all properties and values at once and also try defining empty objects and assign property values in separate statements using the dot notation. /* var beverages; beverages = { brandName: 'ButterBeer', type: 'Cream Soda', volumeInLiters: '1 liter', priceInCents: '150', expirationDate: '01/01/2022', datesOfPreviousSips: [ '01/01/2021', '01/02/2021', '01/03/2021', ] }; */ /* -- Mini Exercise 2 var users = [ { givenName: 'Sam', age: 21 }, { givenName: 'Cathy', age: 34 }, { givenName: 'Karen', age: 43 } ]; /* */ //Log all the users age //console.log(users[0].age); //console.log(users[1].age); //console.log(users[2].age); //for (var i = 0; i < users.length; i += 1) { // console.log(users[i].age); //} //users.forEach(function(user){ // console.log(user.age); //}) // 1. Log the names of all users in a single console log separated by spaces. // output = "<NAME>" //console.log(users[0].givenName + '' + user[1].givenName + '' + users[2].givenName); // 2. Change the names of all users to "<NAME>" //var users = '<NAME>'; // 3. Increase the current age of all users by 1 //users.forEach(function (user:){ // user.age += 1 // } //) //(+=) //Can you accomplish each step using iteration? /* -- Mini Exercise 3 Create a dog object... The dog object should have properties for: breed (string), weightInPounds (number), age (number), color (string), canBreed (boolean), shotRecords (array of objects with properties for date and typeOfShot) The dog object should have methods to: bark() - will console.log “Woof!” getOlder() - will increase age by 1 disableBreeding() - will set canBreed to false vaccinate(nameOfVaccination) - takes in an argument for the name of the vaccination and adds a new shot with the current date to the shotRecords array */ // var dog = { // breed : 'husky', // weightInPounds : '77lbs', // age : 4, // color : 'red', // canBreed : true, // shotRecords: ['rabbies', 'parvo', 'microchip'], // speak: function(){ // console.log('Woof!'); // console.log(this.age); // this.age += 1; // }, // disableBreeding: function() // { // this.canBreed = false; // }, // vaccinate: function (nameOfVaccine){ // this.shotRecords.push({ // typeOfShot : nameOfVaccine, // date: new Date() // }) // } //}; //var shotRecord = { // date: new Date (), // typeOfShot: 'rabies' //}; //dog.speak(); //console.log(dog.age); //dog.disableBreeding() //console.log(dog.canBreed); //dog.vaccinate('rabies'); //console.log(dog.shotRecords); <file_sep>// ================= Review, pt deux ================= /* TODO: When a list item inside of .data-example-container is clicked, -return its data-value attribute value to the element with an id of #show-data-attr */ $('.data-example-container').children().click(function (){ let dataAttr = $(this).val($("data-value")).attr("data-value"); $("#show-data-attr").text(dataAttr) console.log(dataAttr) }) /* TODO: When a list item inside of .data-example-container is double clicked, -return its text value to the all elements with a class of .show-list-item-text */ { function returnTextValue() { let dataValues = $(this).text(); return $(".show-list-item-text").text(dataValues); } $(".data-example-container li").dblclick(returnTextValue); } /* }); TODO: When an immediate child element of the parent with an id of #hover-container is hovered -change the child's text to 'You are hovering here!' and -add a border to the child. -Be sure to reset the text and border upon hovering out */ $('#hover-container').children().hover( function() { $(this).text('You are hovering here!').css("border", "teal solid 1px"); }, function() { $(this).text(location.reload()); } ); // $('#hover-container').children().bind('mouseover', function (){ // $(this).text('You are hovering here!').css("border", "teal solid 1px"); // // }); /* TODO: When an element with the class of .background-color-change is clicked, -cycle between background-colors of 'red', 'blue', 'green', and back to the default -the colors should change in the above order -only affect one element at a time */ let counter = 0 $(".background-color-change").click(function () { // console.log($(this)); counter++; if (counter === 4) { counter = 0 } // console.log(counter); if (counter === 0) { $(this).css("background-color", "") } if (counter === 1) { $(this).css("background-color", "red") } if (counter === 2) { $(this).css("background-color", "blue") } if (counter === 3) { $(this).css("background-color", "green") } }); /* TODO: When a user enters a string (and only a string) into the input of id #input, -concatenate that string to what is already in the element with an id of #output -when the user double clicks the element with an id #output -the string resets to its original text */ $('#concat-string').click(function (e) { e.preventDefault(); let $userInput = $('#input').val(); // console.log(userInput); $('#output').text($('#output').text() + $userInput); $('#output').dblclick(function () { $('#output').text("Concat String:"); }) }); // console.log(userInput); // adds a text box // let value; // $('.data-example-container').on('dblclick', 'li', function () { // value = $(this).text(); // $(this).text(""); // $("<input type='text'>").appendTo(this).focus(); // }); <file_sep>"use strict" function renderCoffee(coffee) { var html = '<div class="coffee card shadow-sm p-1 bg-transparent rounded">'; html += '<div class="card-body">' + '<h2 class="card-title">' + coffee.name + '</h2>'; html += '<h5 class="card-text">' + coffee.roast + ' roast' + '</h5>'; html += '</div>'; html += '</div>'; return html; } function renderCoffees(coffees) { var html = ''; for (var i = coffees.length - 1; i >= 0; i--) { html += renderCoffee(coffees[i]); } return html; } function updateCoffees(e) { e.preventDefault(); // don't submit the form, we just want to update the data var selectedRoast = roastSelection.value; var filteredCoffees = []; coffees.forEach(function (coffee) { if (selectedRoast === 'all') { filteredCoffees.push(coffee); } else if (coffee.roast === selectedRoast) { filteredCoffees.push(coffee); } }); tbody.innerHTML = renderCoffees(filteredCoffees); } function addACoffee(e) { e.preventDefault(); var coffee = { id: coffees.length + 1, name: document.getElementById('new-name').value, roast: document.getElementById('new-roast').value }; coffees.push(coffee); updateCoffees(e); document.getElementById("new-name").value = ""; } // from http://www.ncausa.org/About-Coffee/Coffee-Roasts-Guide var coffees = [ {id: 1, name: '<NAME>', roast: 'light'}, {id: 2, name: '<NAME>', roast: 'light'}, {id: 3, name: 'Cupdate', roast: 'light'}, {id: 4, name: '<NAME>', roast: 'dark'}, {id: 5, name: 'Owl City', roast: 'medium'}, {id: 6, name: 'ourterHTM', roast: 'medium'}, {id: 7, name: 'Ecma Script', roast: 'medium'}, {id: 8, name: '<NAME>', roast: 'dark'}, {id: 9, name: 'Master Disaster', roast: 'dark'}, {id: 10, name: 'Taste of IFFE ', roast: 'dark'}, {id: 11, name: 'Full Stack', roast: 'dark'}, {id: 12, name: 'InnerHTML', roast: 'dark'}, {id: 13, name: 'CSS Grid', roast: 'dark'}, {id: 14, name: 'SQL ', roast: 'dark'}, {id: 15, name: 'IntelliJoe', roast: 'dark'}, {id: 16, name: 'jQuery', roast: 'dark'}, {id: 17, name: 'The DOM', roast: 'dark'}, ]; var tbody = document.querySelector('#coffees'); var submitButton = document.querySelector('#submit'); var roastSelection = document.querySelector('#roast-selection'); var submitNewButton = document.querySelector('#submitNew'); tbody.innerHTML = renderCoffees(coffees); submitButton.addEventListener('click', updateCoffees); submitNewButton.addEventListener('click', addACoffee);<file_sep># code-web-excercises <file_sep>/** * Several things to note in this file: * * - code organization: we define all our functions first, then attach them as event listeners * - naming conventions: * - event listener function names start with "on" or "handle" * - variables that hold jQuery objects have a "$" in front of their name */ // obviously this is a little simplified, but works for our purposes function getPasswordStrength(password) { if (password.length < 5) { return "weak"; } else if (password.length < 8) { return "moderate"; } else { return "strong"; } } function onPasswordInput(e) { // A slightly better way to write this might be with .closest (https://api.jquery.com/closest/), // i.e. // $formGroup = $(e.target).closest('.row') // To find the closest parent with the class of "row". // However, .closest isn't in the curriculum, so we'll show a solution with .parent here. const $formGroup = $(e.target).parent().parent().parent(); const strength = getPasswordStrength(e.target.value); // clear out any old classes $formGroup.removeClass(["text-danger", "text-warning", "text-success"]); // add the right class if (strength === "weak") { $formGroup.addClass("text-danger"); } else if (strength === "moderate") { $formGroup.addClass("text-warning"); } else { $formGroup.addClass("text-success"); } $('#password-feedback').text(strength); } function onConfirmPasswordInput(e) { $formGroup = $(e.target).parent().parent().parent(); const passwordConfirmation = e.target.value; const password = $('#password').val(); $formGroup.removeClass(["text-success", "text-danger"]) if (password === passwordConfirmation) { $formGroup.addClass("text-success"); } else { $formGroup.addClass("text-danger"); } } function handleNextButtonClick(e) { const $currentSection = $('.active'); const $nextSection = $('.active').next(); const $currentPage = $('#current-page'); // update section visibility $currentSection.removeClass('active').addClass('d-none'); $nextSection.removeClass('d-none').addClass('active'); // update current page display const nextPage = parseInt($currentPage.text()) + 1; $currentPage.text(nextPage); } $('#password').on("input", onPasswordInput); $('#confirm-password').on("input", onConfirmPasswordInput); $('.next-button').click(handleNextButtonClick);<file_sep>// const body = document.body // body.append("hello world", "Goodbye World") // // const div = document.createElement('div') // // div.innerText("Hi again") // div.textContent = ("3x a charm") // body.append(div) // // const div = document.querySelector('div') // // console.log(div.textContent) // console.log(div.innerText) // // div.innerHTML = "<strong>Hello World 2</strong>" const div = document.querySelector("div") const spanHi = document.querySelector("#hi") const spanBye = document.querySelector("#bye") spanBye.remove() spanHi.setAttribute("id","NewID") $("add-btn").click("click", function (){ let $inputVal = $("number").val(); console.log($inputVal); let $spanVal = $("sum-output").text(); console.log($spanVal); let $addSpans = parseInt($inputVal) + parseInt($spanVal); console.log($addSpans); $("#sum-output").text($addSpans); }) <file_sep>"use strict" // // $(document).ready(function (){ // alert("Can you guess the name of this Movie?") // }) // document.getElementById("movieStatement").style.background = "palevioletred"; var texts = Array.from(document.getElementsByClassName("about")); texts.forEach(function (text) { text.style.color = "#5e2d5c"; }); var texts = Array.from(document.getElementsByClassName("filler-text")); texts.forEach(function (text) { text.style.color = "palevioletred"; }); // document.getElementById("dolor").innerHTML = ";)"; // $('.codeup').css('border', '1px solid red'); // $('container').css('font-size', '20px'); // alert($("first-heading").html("text")); // // alert($("second-heading").html("text")); // alert(document.getElementById("first-heading".innerHTML)); // alert($("second-heading").html()) // $("li").css("font-size", "20px"); // $("h1").css("background-color", "blue"); // $("p").css("background-color", "pink"); // $("li").css("background-color", "teal"); // alert($('h1').html());//or .text // $("h1").each(function (){ // alert($(this).html()) // }); // // $('h1, p, li').css({"background-color": "turquoise"}); $('h1').click( function() { $(this).css('background-color', '#f5bc42'); } ); $('p').dblclick( function() { $(this).css('font-size', '18px'); } ); $('li').hover( function() { $('li').css('color', 'red'); }, function() { $('li').css('color', 'teal'); } ); submitButton.addEventListener('click', showResults);<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Welcome to Veridian Dynamics</title> <style> .fancy-header { color: aqua; } </style> <link rel="stylesheet" href="css/style.css"> </head> <body> <header id="top"></header> <nav class="nav-bar>"> <ul> <li><a href="#">Home</a> </li> </ul> </nav> <h1 class="fancy-header">Welcome to Veridian Dynamics!</h1> At Veridain Dynamics, <strong>we</strong> solve your problems with <strong><em>technology.</em> </strong> <hr> <h4>Core Values</h4> <ul> <li>Competence</li> <li>Involvement</li> <li>Technology</li> </ul> <h4>Our Process</h4> <ol> <li>Plan</li> <li>Evaluate</li> <li>Implement</li> </ol> <h4>2020 Vision</h4> <ul> <li>Become #1 in Technology</li> <li>Increase Success by 20%</li> <li>Increase Business by 30%</li> </ul> <hr> <h3>Company Vision</h3> <img src="img/work-meet.jpg" alt="work-meet"width="300" height="300"> <img src="img/work-meet2.jpg" alt="work-meet2"width="300" height="300"> <br> <img src="img/work-meet3.jpg" alt="work-meet3"width="300" height="300"> <img src="img/engineer.jpg" alt="female coding"width="300" height="300"> <h3>Our Product</h3> <table> <tr> <th>Plan</th> <th>Price</th> <th>Features</th> </tr> <tr> <td>Starter</td> <td>$99</td> <td>Basic Technology</td> </tr> <tr> <td>Advanced</td> <td>$199</td> <td>Advanced Features</td> </tr> <tr> <td>Premium</td> <td>$499</td> <td>Unlimited Support</td> </tr> </table> <br> <em>All products come with our quality guarantee&trade;</em> <br> <br> <h3><a href="#top">Go to the top of page</a></h3> </body> </html><file_sep>let global = { konami: function() { var konamikeys = [38,38,40,40,37,39,37,39,66,65], started = false, count = 0; console.log("this ran"); $(document).keydown(function(e){ var reset = function() { started = false; count = 0; return; }; let key = e.keyCode; // Begin watching if first key in sequence was pressed. if(!started){ if(key == 38){ started = true; } } // If we've started, pay attention to key presses, looking for right sequence. if (started){ if (konamikeys[count] == key){ count++; } else { // Incorrect key, restart. reset(); } if (count == 10){ // Success! alert('Konami code entered!'); reset(); } } else { reset(); } }); } } global.konami();<file_sep>$(".card").click(function (){ $(this).toggleClass("toggleClass") }); $(".card").hover(); $('.list-group>li').dblclick(function (){ $(this).text("i got clicked") $(this).click(function (){ $(this).text("aww") }) }) function getInputData(){ let first = $('#first').val(); let last = $('#last').val(); let handleField = $('#handleField').val(); return { first, last, handleField } } $('#submitBtn').click(function (){ console.log(getInputData()); }) "use strict"; // ========== Retrieve elements by id, class, tag name //EACH CALL TO THE DOM STARTS WITH document.whateverMethodYouNeed() //****************** getElementById - Returns a SINGLE element which matches the id given // (function(){ // let mainTitle = document.getElementById('main-title'); // console.log(mainTitle); // // })() //***************** getElementByClassName - Returns an HTMLCollection of elements sharing the same CSS class name // (function(){ // let rows = document.getElementsByClassName('row'); // console.log(rows); // })() //***************** getElementsByTagName - Returns an HTMLCollection of elements sharing the same TAG (ie: <p>) // // **We pass in a string of the tag name of the elements instead of the actual tag: <main> becomes 'main' // var sections = document.getElementsByTagName('section'); // console.log(sections); // ************CONVERTING TO AN ARRAY**************** //This allows us access to array methods like push, pop, and foreach loops // //CAN BE DONE ON ANY HTMLCOLLECTION (what is returned from getElementsByClassName and getElementsByTagName) // (function(){ // // // use Array.from(yourCollection) to convert to an array // let rows = Array.from(document.getElementsByClassName('row')); // // // we could use a forEach loop to look at each individual member of the array // rows.forEach((row) => { // //log each row individually // console.log("This is a single item in the array:"); // console.log(row); // }) // // //we could also use a for loop! // for (var i = 0; i < rows.length; i++){ // console.log("This is a single item in the array:"); // console.log(rows[i]); // } // })() // // // ========== querySelector() and querySelectorAll() // Get a SINGLE element which has a CSS class of 'row' // var row = document.querySelector('.row'); // console.log(row); // // NOTE: querySelector() will pick the FIRST element which matches - use wisely! // // Get ALL elements which have the matching CSS class of 'row' // var rows= document.querySelectorAll('.row'); // console.log(rows); // We can stack selectors simply by putting a space in between them //This one will find all elements of CSS class ids of 'first' OR 'last' // var inputs = document.querySelectorAll('#first, #last'); // // console.log(inputs); // Get every h2 found inside of any div // var hTwos = document.querySelectorAll("div > h2"); // console.log(hTwos); // Get every div which has class of 'column' inside of sections with the class of 'row' // var columns = document.querySelectorAll("section.row > div.col"); // console.log(columns); // // ========== Direct access to form inputs //*********** The document object allows us to directly access forms in a special way //*********** Simply call document.forms['name attribute of the form'] // (function (){ // // // We set a delay here so the page can load and give us a chance to put in a value // before the code runs // setTimeout(function(){ // // Because on of our name attributes in the form is 'first' we can retrieve it as a // property directly // let first = document.forms['user'].first; // console.log(first.value); // // },3000) // // })() // // ========== Accessing and modifying elements and properties // get value of innerHTML // var title = document.getElementById("main-title"); // console.log(title); // // console.log(title.innerHTML); // console.log(title.innerText); // // // set value of innerHTML // title.innerHTML = "<em>Hi MOM!</em>"; // // // append value to innerText (works the same with innerHTML) // title.innerHTML += " ...and hi Mom!"; // ========== Accessing and modifying attributes // Use hasAttribute('yourAttribute') to make sure before running the next parts var star = document.getElementById('review-result'); console.log(star.hasAttribute('i')); // get an attribute value console.log(star.getAttribute('data-result')); // create a new attribute or change a value of an existing attribute cowboy.setAttribute('data-1', 'hello'); cowboy.setAttribute('data-test', 'testing'); console.log(cowboy.getAttribute('data-1')); // // remove attribute // cowboy.removeAttribute("data-test"); // console.log(cowboy); // //********** Let's change the 'src' attribute of our card's img tags // (function(){ // let cardImages = Array.from(document.getElementsByClassName('card-img-top')); // //sanity check to see the original src value // // console.log(cards[0].getAttribute('src')); // // cardImages.forEach((card) => { // card.setAttribute('src', 'img/jazz-music-rubber-duck.jpg'); // }); // // now let's see the new src value // // console.log(cards[0].getAttribute('src')); // // })(); // ========== Accessing and modifying styles // // single style // var jumbotron = document.querySelector('.jumbotron'); // jumbotron.style.display = "none"; // //instead of using style.property, you can access via style.['property-string'] // jumbotron.style['font-family'] = "times"; // // // apply multiple style changes // Object.assign(jumbotron.style, { // border: "10px solid black", // //if the property has a dash or special character, use quotes // "font-family": "times", // "text-decoration": "underline" // }); // // // styling node list // var tableRows = document.getElementsByTagName("tr"); // for (var i = 0; i < tableRows.length; i += 1) { // tableRows[i].style.background = "red"; // } // //********* Let's have a little fun ************* // Here, we combine // -BOM events (timeouts, intervals) & // -DOM manipulation (retrieving elements, changing text, style, and attributes) // setTimeout(function(){ // // after 2 seconds, we change the main-title text // let mainTitle = document.getElementById('main-title'); // mainTitle.innerText = "Incoming Transmission...."; // // // second timeout... building... suspense // setTimeout(function(){ // // // start swapping texts, font colors, and backgrounds // mainTitle.style.fontSize = '72pt'; // mainTitle.style.fontFamily = 'Metal Mania'; // mainTitle.textContent = 'COME AND KNEEL BEFORE ZOD! ZOD!'; // mainTitle.style.color = 'red'; // // let jumbotron = document.querySelector(".jumbotron"); // jumbotron.style.backgroundColor = 'black'; // // // using a boolean and setInterval(), we are able to swap the background and font color at a 500ms interval // let isRedText = true; // setInterval(function(){ // // //check the value of our boolean 'flag' // if(isRedText){ // mainTitle.style.color = 'black'; // jumbotron.style.backgroundColor = 'red'; // }else{ // mainTitle.style.color = 'red'; // jumbotron.style.backgroundColor = 'black'; // } // // //notice that we flip isRed to be whatever boolean value it is currently not (using !) // //this is how we are able to continually swap the styles // isRedText = !isRed; // // }, 500) // // // now make it interesting! let's swap out the card images for something a little more.... appropriate // let cardImgs = Array.from(document.querySelectorAll('.card-img-top')); // // // use a loop to iterate through the array, setting the 'src' attribute value for our new one // for (let i = 0; i < cardImgs.length; i++){ // cardImgs[i].setAttribute('src', 'img/General_Zod_(circa_2018).png'); // } // }, 2000); // }, 2000);
db6b4bc9be02e9b81725f416fd6d1fd59db1ea07
[ "JavaScript", "HTML", "Markdown" ]
12
JavaScript
emihhorn/codeup-web-exercises
9d8dbe60d933237dc9645a85b273fcd6cf217fab
1119ef360670207e0f172bbc292929cecac42582
refs/heads/master
<repo_name>pancheliuha/slider<file_sep>/source/js/app.js (function($) { "use strict"; var slider = require('./modules/slider'); if ($('.slider').length) { slider(); } })(jQuery);<file_sep>/README.md #SLIDER Node -v i used : 7.7.1 npm : v.4.3.0 Getting started: 1. clone this repo 2. cd path/to/builder 3. npm install gulp-cli 4. npm install 5. run "gulp" command to start
a7e18c4e649de8c3ba85557d968d75dbd9678c26
[ "JavaScript", "Markdown" ]
2
JavaScript
pancheliuha/slider
b03bd5e6f50969bb988a621421d3508e9b23bef8
ca2f065162e1a702a0dc652c084031b4050d276f
refs/heads/master
<file_sep>module ActiveMerchant #:nodoc: module Billing #:nodoc: module Integrations #:nodoc: module Paymate class Return < ActiveMerchant::Billing::Integrations::Return SUCCESS = "PA" CODES = { "PA" => "Payment is approved", "PD" => "Payment is declined", "PP" => "Payment is processing" } def success? params['responseCode'] == SUCCESS end def message CODES[params['responseCode']] end def status params['responseCode'] end def transaction_id params['transactionID'] end def gross params['paymentAmount'].to_f end end end end end end <file_sep>module ActiveMerchant #:nodoc: module Billing #:nodoc: module Integrations #:nodoc: module Paymate class Notification < ActiveMerchant::Billing::Integrations::Notification def complete? true end def status 'Complete' # Not supported by Paymate end # Unique ID of transaction def transaction_id params['transactionId'] end # The item id passed in the first custom parameter def item_id params['ref'] end def gross 0.00 # Not supported by Paymate end def test? false end def acknowledge true end end end end end end <file_sep>module ActiveMerchant #:nodoc: module Billing #:nodoc: module Integrations #:nodoc: module Paymate class Helper < ActiveMerchant::Billing::Integrations::Helper def initialize(order, account, options = {}) super add_field('amt_editable', 'N') add_field('popup', 'false') end mapping :invoice, 'ref' # mapping :order, '???' # This is the order.id mapping :account, 'mid' mapping :amount, 'amt' mapping :currency, 'currency' mapping :customer, :first_name => 'pmt_contact_firstname', :last_name => 'pmt_contact_surname', :phone => 'pmt_contact_phone', :email => 'pmt_sender_email' mapping :billing_address, :city => 'regindi_sub', :address1 => 'regindi_address1', :address2 => 'regindi_address2', :state => 'regindi_state', :zip => 'regindi_pcode', :country => 'pmt_country' mapping :notify_url, 'notify' mapping :return_url, 'return' end end end end end
a0ae5ee1c2d2d28ef88f2b8aee9b4a931ee9d88d
[ "Ruby" ]
3
Ruby
esb/active_merchant
258936a306e65dc6bdf65ef3fe6f707e598b2d56
2b8fe95512f14c2079d6c3a17880bb624924f02b
refs/heads/master
<repo_name>CartYuyDgs/PythonDemo<file_sep>/README.md # PythonDemo python小例子 <file_sep>/excel/main.py import openpyxl xlsl = "D:\code\python\excel\main.xlsx" def main(): wb = openpyxl.load_workbook(xlsl) print(wb.sheetnames) ws = wb.active print(ws) print(ws['A1'].value) for i in range(1,5,1): print(ws.calculate_dimension()) print(ws.cell(i,1).value) print(ws.cell(i, 2).value) print(ws.cell(i, 3).value) if __name__ == '__main__': main()
87022cd2bb3661600db417f255c11c8b75ca46b7
[ "Markdown", "Python" ]
2
Markdown
CartYuyDgs/PythonDemo
574e289085990d17d3553ca966ec19226b255b1c
a2436c78b5cfa0e03194ade5652cd896c93f6533
refs/heads/master
<repo_name>HyperLLC/WebForms2BlazorServer<file_sep>/src/WebFormsToBlazorServerCommands/Migration/WebFormToBlazorServerMigration.Config.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Xml; using CodeFactory.VisualStudio; using Newtonsoft.Json; namespace WebFormsToBlazorServerCommands.Migration { public partial class WebFormToBlazorServerMigration { /// <summary> /// Migrates the web.config to a settings file in the blazor server project. /// </summary> /// <param name="webFormProjectData">Data from the web forms project already loaded and provided in a list.</param> /// <param name="webFormProject">The web forms project that we are migrating data from.</param> /// <param name="blazorServerProject">The blazor server project this is being migrated to.</param> public async Task MigrateConfig(IReadOnlyList<VsModel> webFormProjectData, VsProject webFormProject, VsProject blazorServerProject) { try { //Informing the dialog the migration step has started. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Config, MigrationStatusEnum.Running); //Get the web.config file from the source project; if (!(webFormProjectData.FirstOrDefault(c => c.ModelType == VisualStudioModelType.Document & c.Name.ToLower().Equals("web.config")) is VsDocument configDocument)) { //No web.config was found. //Sending a status update to the dialog await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Config, MessageTypeEnum.Error, $"No web.config file was found in the web forms project {webFormProject.Name}. Cannot migrate the configuration."); //Informing the dialog the migration step has failed. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Config, MigrationStatusEnum.Running); return; } else { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(await configDocument.GetDocumentContentAsStringAsync()); var jsonConverted = JsonConvert.SerializeXmlNode(xmlDoc); //Add converted web.config to a file in the target solution. this will be named webconfig.json var thing = await blazorServerProject.AddDocumentAsync("webconfig.json", jsonConverted); //Sending a status update to the dialog await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Config, MessageTypeEnum.Information, $"The web.config file has been moved to the root directory of {blazorServerProject.Name} and converted to 'webconfig.json'."); await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Config, MessageTypeEnum.Information, $"** Please review the webconfig.json file and make sure that it meets the needs of the converted Blazor app."); } //Completed the migration step informing the dialog. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Config, MigrationStatusEnum.Passed); } catch (Exception unhandledError) { //Dumping the exception that occured directly into the status so the user can see what happened. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Config, MessageTypeEnum.Error, $"The following unhandled error occured. '{unhandledError.Message}'"); //Updating the status that the step failed await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Config, MigrationStatusEnum.Failed); } } } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/WebFormToBlazorServerMigration.cs using CodeFactory.VisualStudio; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using CodeFactory.DotNet.CSharp; using CodeFactory; using CodeFactory.Formatting.CSharp; using System.Text; using HtmlAgilityPack; using CodeFactory.Markup.Adapter; using NLog.Targets; namespace WebFormsToBlazorServerCommands.Migration { /// <summary> /// Code Automation process that migrates code, files, and configuration data to a server side blazor project. /// </summary> public partial class WebFormToBlazorServerMigration { /// <summary> /// Field that holds the CodeFactory visual studio actions that can be used for automation. /// </summary> private readonly IVsActions _visualStudioActions; /// <summary> /// Holds the dialog that is to be updated, using the exposed interface to update the dialog. /// </summary> private readonly IMigrationStatusUpdate _statusTracking; /// <summary> /// Initializes the migration class and creates a new instance. /// </summary> /// <param name="vsActions">The CodeFactory automation actions that will be used in the migration process.</param> /// <param name="statusUpdate">The dialog that will be updated during the migration process.</param> public WebFormToBlazorServerMigration(IVsActions vsActions, IMigrationStatusUpdate statusUpdate) { _visualStudioActions = vsActions; _statusTracking = statusUpdate; } /// <summary> /// Starts the migration process from webforms project to a blazor server project. /// </summary> /// <param name="webFormsProject">Source project to read data from.</param> /// <param name="blazorServerProject">Target server blazor project to inject into.</param> /// <param name="steps">The migration steps that are to be run.</param> public async Task StartMigration(VsProject webFormsProject, VsProject blazorServerProject, MigrationSteps steps) { try { //bounds checking that migration steps were provided. if (steps == null) { await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.MigrationProcess, MigrationStatusEnum.Failed); await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.MigrationProcess, MessageTypeEnum.Error, "Could not determine which migration steps are to be perform migration aborted."); await _statusTracking.UpdateMigrationFinishedAsync(); return; } //Bounds checking that the web forms project was provided. if (webFormsProject == null) { await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.MigrationProcess, MigrationStatusEnum.Failed); await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.MigrationProcess, MessageTypeEnum.Error, "Internal error occured, no web forms project was provided the migration was aborted."); await _statusTracking.UpdateMigrationFinishedAsync(); return; } //Bounds checking if the blazor server project was provided. if (blazorServerProject == null) { await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.MigrationProcess, MigrationStatusEnum.Failed); await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.MigrationProcess, MessageTypeEnum.Error, "Internal error occured, no blazor server project was provided the migration was aborted."); await _statusTracking.UpdateMigrationFinishedAsync(); return; } //Starting the migration process by caching the web forms project data await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.MigrationProcess, MigrationStatusEnum.Running); await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.MigrationProcess, MessageTypeEnum.Information, "Please wait loading the data from the web forms project..."); //Loading the visual studio models from the webFormsProject. //This is a resource intensive task we only need to do this once since we are never updating the web forms project. //We will cache this data and pass it on to all parts of the migration process //var filePath = new DirectoryInfo(webFormsProject.Path).FullName; var webFormProjectData = await webFormsProject.LoadAllProjectData(false); //Confirming the web forms data has been cached if (webFormProjectData.Any()) { await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.MigrationProcess, MigrationStatusEnum.Passed); await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.MigrationProcess, MessageTypeEnum.Information, "Web forms data has been cached, migration beginning."); } else { await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.MigrationProcess, MigrationStatusEnum.Failed); await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.MigrationProcess, MessageTypeEnum.Error, "Failed to load the web forms project data, cannot continue the migration process."); await _statusTracking.UpdateMigrationFinishedAsync(); return; } //Running the migration steps in sequential order if (steps.Startup) await MigrateStartupAsync(webFormProjectData, webFormsProject, blazorServerProject); if (steps.HttpModules) await MigrateHttpModulesAsync(webFormProjectData, webFormsProject, blazorServerProject); if (steps.StaticFiles) await MigrateStaticFiles(webFormProjectData, webFormsProject, blazorServerProject); if (steps.Bundling) await MigrateBundling(webFormProjectData, webFormsProject, blazorServerProject); if (steps.AspxPages) await MigrateAspxFiles(webFormProjectData, webFormsProject, blazorServerProject); if (steps.Configuration) await MigrateConfig(webFormProjectData, webFormsProject, blazorServerProject); if (steps.AppLogic) await MigrateLogic(webFormProjectData, webFormsProject, blazorServerProject); } catch (Exception unhandledError) { //Updating the dialog with the unhandled error that occured. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.MigrationProcess, MessageTypeEnum.Error, $"The migration process had an unhandled error, the migration process is aborting. The following error occured. '{unhandledError.Message}'"); } finally { //Informing the hosting dialog the migration has finished. await _statusTracking.UpdateMigrationFinishedAsync(); } } #region Migration Steps /// <summary> /// Helper method that converts Aspx Pages to Blazor pages. /// </summary> /// <param name="sourcePage">The source aspx page to be converted.</param> /// <param name="targetProject">The target blazor project to write to.</param> /// <param name="targetPagesFolder">The target visual studio project folder the converted aspx will be added to.</param> /// <param name="sourceCodeBehind">Optional parameter that provides the code behind file for the aspx page to be converted also.</param> /// <returns>Flag used to determine if the conversion was successful.</returns> private async Task ConvertAspxPage(VsDocument sourcePage, VsProject targetProject, VsProjectFolder targetPagesFolder, VsCSharpSource sourceCodeBehind = null, VsDocument sourceDocCodeBehind = null) { try { //Getting the content from the source document. var pageContent = await sourcePage.GetDocumentContentAsStringAsync(); //File.ReadAllText(result.Path); //grab the <%Page element from the source and pull it from the text. Its meta data anyway and just screws up the conversion down the line. var pageHeaderData = System.Text.RegularExpressions.Regex.Match(pageContent, @"<%@\s*[^%>]*(.*?)\s*%>").Value; if (pageHeaderData.Length > 0) { pageContent = Regex.Replace(pageContent, @"<%@\s*[^%>]*(.*?)\s*%>", string.Empty); } //Swap ASP.NET string tokens for Razor syntax (<%, <%@, <%:, <%#:, etc var targetText = RemoveASPNETSyntax(pageContent); //Convert ASP.NET into Razor syntax. **This actually presumes that any controls like <asp:ListView.. //will have an equivalent Razor component in place called <ListView.. etc var conversionData = await ReplaceAspControls(targetText); //Drop the pageHeaderData into the Dictionary for later processing by any downstream T4 factories conversionData.Add("HeaderData", pageHeaderData); //Getting the source code from the code behind file provided. var codeSource = sourceCodeBehind?.SourceCode; if ((codeSource == null) && (sourceDocCodeBehind != null)) { codeSource = await sourceDocCodeBehind.GetCSharpSourceModelAsync(); } //put the files in the target project String targetFileName = Path.GetFileNameWithoutExtension(sourcePage.Path); conversionData.Add("Namespace", $"{targetProject.DefaultNamespace}.Pages"); //Setup Page directives, using statements etc var targetWithMeta = await SetRazorPageDirectives(targetFileName, conversionData); //Adding the converted content from the aspx page to the new razor page. VsDocument success = await targetPagesFolder.AddDocumentAsync($"{targetFileName}.razor", targetWithMeta); if (success != null) { //Updating the dialog with the status the aspx page has been converted. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Information, $"Converted the aspx page to a razor page, added razor page {targetFileName}.razor"); //If we have the source code from the original aspx page add it to the razor pages folder. if (codeSource != null) { //Creating a CodeFactory model store this will be used to pass data to a T4 factory. CsModelStore modelStore = new CsModelStore(); //Adding the current class from the code behind into the model store for processing. modelStore.SetModel(codeSource.Classes.FirstOrDefault()); //Processing the T4 factory and loading the source code. var codeBehindFormattedSourceCode = Templates.PageCodeBehind.GenerateSource(modelStore, conversionData); //Calling the CodeFactory project system and adding a new code behind file and injecting the formatted code into the file. var codeBehind = await targetPagesFolder.AddDocumentAsync($"{targetFileName}.razor.cs", codeBehindFormattedSourceCode); if (codeBehind != null) { //Updating the dialog with the status the aspx page code behind has been converted. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Information, $"Converted the aspx page code behind file to a razor page code behind file, added code behind file {targetFileName}.razor.cs"); } else { //Updating the dialog with the status the aspx page code behind failed await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"Failed the conversion of the aspx page code behind file to a razor page code behind file {targetFileName}.razor.cs"); } } } else { //Updating the dialog with the status the aspx page failed conversion. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"Failed the conversion of the aspx page {targetFileName}.razor. Will not convert the code behind file."); } } catch (Exception unhandledError) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"The following unhandled error occured while trying to convert the aspx page. '{unhandledError.Message}'"); } } /// <summary> /// Migrates the site.master layout files from the source WebForms project into the \Shared folder /// in the Blazor target application project. /// </summary> /// <param name="webFormSiteMasterFiles">The flattened list of WebForms project objects/files</param> /// <param name="blazorServerProject">The target Blazor project object</param> /// <returns></returns> /// private async Task ConvertAspxPage(VsDocument sourcePage, VsProject targetProject, VsProjectFolder targetPagesFolder, VsCSharpSource sourceCodeBehind = null) private async Task<string> ConvertLayoutFiles(IEnumerable<VsModel> webFormSiteMasterFiles, VsProject blazorServerProject) { string headerData = null; //put the files in the target project var targetFolder = await blazorServerProject.CheckAddFolder("Shared"); try { foreach (var layoutFile in webFormSiteMasterFiles) { //We don't want to touch/migrate any of the *.designer files if (layoutFile.Name.ToLower().Contains("designer")) continue; String targetFileName = layoutFile.Name.Replace(".", ""); //Get any existing children in the targetFolder that match. var existingBlazorMatches = await targetFolder.GetChildrenAsync(true, false); var docMatches = existingBlazorMatches.Where(p => p.Name.ToLower().Contains(targetFileName.ToLower())).Cast<VsDocument>(); foreach (VsDocument matchFile in docMatches) { //delete each matched file in the target folder. await matchFile.DeleteAsync(); } //work on just the Site.Master file which is basically a specialized *.aspx file. if (!layoutFile.Name.ToLower().Contains(".cs")) { var docObj = layoutFile as VsDocument; var textFromResult = await docObj.GetDocumentContentAsStringAsync(); //grab the <%Page element from the source and pull it from the text. Its meta data anyway and just screws up the conversion down the line. var pageHeaderData = System.Text.RegularExpressions.Regex.Match(textFromResult, @"<%@\s*[^%>]*(.*?)\s*%>").Value; if (pageHeaderData.Length > 0) { textFromResult = Regex.Replace(textFromResult, @"<%@\s*[^%>]*(.*?)\s*%>", string.Empty); } //Swap ASP.NET string tokens for Razor syntax (<%, <%@, <%:, <%#:, etc var targetText = RemoveASPNETSyntax(textFromResult); //Convert Site.Master file into razor syntax, specifically the asp:controls that might be used there. var conversionData = await ReplaceAspControls(targetText); //Drop the pageHeaderData into the Dictionary for later processing by any downstream T4 factories conversionData.Add("HeaderData", pageHeaderData); //Setup Page directives, using statements etc var targetWithMeta = await SetRazorPageDirectives(targetFileName, conversionData); VsDocument success = await _visualStudioActions.ProjectFolderActions.AddDocumentAsync(targetFolder, $"{targetFileName}.razor", targetWithMeta); //Updating the dialog await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Information, $"The file {targetFileName}.razor was copied to {targetFolder.Name}."); } //Get sibling/named code-behind file //1. Get the children of this *.aspx file //2. Grab the doc that has the same name with a ".cs" extension on the end of it if (layoutFile.Name.Contains(".cs")) { targetFileName = layoutFile.Name.Replace(".cs", ""); targetFileName = targetFileName.Replace(".", ""); var sourceObj = layoutFile as VsCSharpSource; var codeSource = sourceObj.SourceCode; var metaDataDictionary = new Dictionary<string, string>(); metaDataDictionary.Add("Namespace", $"{blazorServerProject.Name}.Pages"); //Setup Page directives, using statements etc //var targetWithMeta = await SetRazorPageDirectives(targetFileName, conversionData); CsModelStore modelStore = new CsModelStore(); modelStore.SetModel(codeSource.Classes.FirstOrDefault()); var codebehind = await _visualStudioActions.ProjectFolderActions.AddDocumentAsync(targetFolder, $"{targetFileName}.razor.cs", Templates.PageCodeBehind.GenerateSource(modelStore, metaDataDictionary)); // Updating the dialog await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Information, $"The file {targetFileName}.razor.cs was copied to {targetFolder.Name}."); } } } catch (Exception unhandledError) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"The following unhandled error occured while trying to migrate the layout files. '{unhandledError.Message}'"); } return headerData; } /// <summary> /// Swap ASP.NET string tokens for Razor syntax (<%, <%@, <%:, <%#:, etc /// </summary> /// <param name="sourceMarkup">The source markup to replace</param> /// <returns>The updated markup</returns> string RemoveASPNETSyntax(string sourceMarkup) { String result = sourceMarkup; var tokenMatches = Regex.Matches(sourceMarkup, @"<%\s*[^%>]*(.*?)\s*%>"); try { String subMatch = string.Empty; foreach (Match matchObj in tokenMatches) { subMatch = string.Empty; switch (matchObj.Value.Substring(2, 2)) { case ": ": subMatch = matchObj.Value.Replace("<%:", "@("); subMatch = subMatch.Replace("%>", ")"); result = result.Replace(matchObj.Value, subMatch); break; case "= ": subMatch = matchObj.Value.Replace("<%=", "@("); subMatch = subMatch.Replace("%>", ")"); result = result.Replace(matchObj.Value, subMatch); break; case "# ": subMatch = matchObj.Value.Replace("<%#", "@("); subMatch = subMatch.Replace("%>", ")"); result = result.Replace(matchObj.Value, subMatch); break; case "$ ": subMatch = matchObj.Value.Replace("<%$", "@("); subMatch = subMatch.Replace("%>", ")"); result = result.Replace(matchObj.Value, subMatch); break; case "#:": subMatch = matchObj.Value.Replace("<%#:", "@("); subMatch = subMatch.Replace("%>", ")"); result = result.Replace(matchObj.Value, subMatch); break; case "--": subMatch = matchObj.Value.Replace("<%--", "@*"); subMatch = subMatch.Replace("--%>", "*@"); result = result.Replace(matchObj.Value, subMatch); break; case "\r\n": subMatch = matchObj.Value.Replace("<%\r\n", "@{\r\n"); subMatch = subMatch.Replace("\r\n%>", "\r\n}"); result = result.Replace(matchObj.Value, subMatch); break; default: if (matchObj.Value.Substring(2, 1).Contains("=")) { subMatch = matchObj.Value.Replace("<%=", "@("); subMatch = subMatch.Replace("%>", ")"); result = result.Replace(matchObj.Value, subMatch); } break; } } } catch (Exception ex) { return ex.Message; } return result; } /// <summary> /// Used to cycle through a set of ASP source code and swap out any of the old-style /// asp:* style controls for either there newer razor equivalents, or simplem HTML 5 compliant /// tags where there is no equivalent razor match. /// </summary> /// <param name="sourceAspCode"></param> /// <returns>string with replaced asp:* controls</returns> [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] private async Task<Dictionary<string, string>> ReplaceAspControls(string sourceAspCode) { Dictionary<string, string> result = new Dictionary<string, string>(); StringBuilder migratedSource = new StringBuilder(); var docFrag = new HtmlAgilityPack.HtmlDocument(); docFrag.LoadHtml(sourceAspCode); var converterAdapterHost = new AdapterHost(); converterAdapterHost.RegisterAdapter(x => new AspxToBlazorControlConverter(converterAdapterHost)); try { //Deal with HTML, HEAD and BODY tags (most *.aspx pages won't have these - but we still have to manage those that do) //Look through the incoming sourceAspCode parameter and see if we have any of those three tags present. var htmlTag = System.Text.RegularExpressions.Regex.Match(sourceAspCode, @"<HTML.*?>(.|\n)*?<\/HTML>", RegexOptions.IgnoreCase); var headTag = System.Text.RegularExpressions.Regex.Match(sourceAspCode, @"<HEAD.*?>(.|\n)*?<\/HEAD>", RegexOptions.IgnoreCase); var bodyTag = System.Text.RegularExpressions.Regex.Match(sourceAspCode, @"<BODY>(.|\n)*?<\/BODY>", RegexOptions.IgnoreCase); foreach (var child in docFrag.DocumentNode.ChildNodes) { //New HtmlAgilityPack parsing which does *not* add HTML/HEAD/BODY etc tags to the source if (child.Name.ToLower().Equals("html")) { //migratedSource.Append(await ProcessSourceElement(child.OuterHtml, converterAdapterHost)); continue; } if (child.Name.ToLower().Equals("head")) { //just take the value of the headTag Regex match from earlier in this method (there are no asp:* controls of any kind that live in the //HEAD tag - so we can just copy it down to here) migratedSource.Append(await ProcessSourceElement(child.OuterHtml, converterAdapterHost)); continue; } if (child.Name.ToLower().Equals("body")) { //We go ahead and process this element. Any children of the tag are actually handled by the ProcessSourceElement() method var migratedBodyElement = await ProcessSourceElement(child.OuterHtml, converterAdapterHost); if (!bodyTag.Success) { var matches = Regex.Match(migratedBodyElement, @"<body>([\S\s]*)<\/body>", RegexOptions.IgnoreCase); migratedSource.Append(matches.Groups[1].Value); } else { migratedSource.Append(migratedBodyElement); } continue; } //Its just a vanilla text sitting outside of a elementNode, append it. if (!child.NodeType.Equals(HtmlNodeType.Element)) { migratedSource.Append(child.OuterHtml); continue; } //Its an element Node - process it. if (child.NodeType.Equals(HtmlNodeType.Element)) { migratedSource.Append(await ProcessSourceElement(child.OuterHtml, converterAdapterHost)); continue; } } result.Add("source", sourceAspCode); result.Add("alteredSource", migratedSource.ToString()); } catch (Exception ex) { throw; } return result; } /// <summary> /// Updates the directives in the page file to use razor syntax. /// </summary> /// <param name="fileName">The file being processed.</param> /// <param name="sourceData">The source data to be updated.</param> /// <returns>The updated content.</returns> private async Task<String> SetRazorPageDirectives(string fileName, Dictionary<string, string> sourceData) { //String result = String.Empty; SourceFormatter result = new SourceFormatter(); try { var pageData = sourceData["HeaderData"]; Regex regex = new Regex(@"(?<=\bMasterPageFile="")[^""]*"); Match match = regex.Match(pageData); string layout = match.Value; layout = layout.Replace(".", ""); //remove the old-style Site.Master layout to read SiteMaster result.AppendCode($"@page \"/{fileName}\" "); if (layout.Length > 0) { //Making sure the ~ gets removed from directives result.AppendCodeLine(0, $"@layout { layout.Replace("~/", "")}"); } //result += $"@inherits {fileName}Base\r\n\r\n {sourceData["alteredSource"]}"; result.AppendCodeLine(0); result.AppendCodeLine(0); result.AppendCodeLine(0, $"{sourceData["alteredSource"]}"); } catch (Exception unhandledError) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"The following unhandled error occured while setting the razor page directives in the file {fileName}. '{unhandledError.Message}'"); } return result.ReturnSource(); } #endregion } } <file_sep>/guidance/Guidance.md # WebFormsToBlazorServer Guidance This set of documentation goes into the details of the example CodeFactory Code Automation Template **WebFormsToBlazor**. If you need explainations of what a Code Automation Template is or how CodeFactory works please use the following link to that documentation. [CodeFactory Guidance](http://docs.codefactory.software/guidance/intro.html) ## Template Overview In order to make use of this template you will need to have a target WebForms solution, in our examples below we reference the [*WingTipToys*]() project. This is an older reference project that is freely available to anyone who wished to download it and give this template a try. Once you have your project open inside of Visual Studio - go ahead and add a new Project to the solution of type Blazor - Server. ![](./images/AddNewBlazorProject.png) The compiled output of the WebFormsToBlazorServer project, a file called *WebFormsToBlazorServerCommands.cfx* file just needs to be dropped into the root solution folder of the WebForms project. ![](./images/WingTipToysRoot.png) The next time that you open the WingTipToys solution the CodeFactory runtime will [load](http://docs.codefactory.software/guidance/usage-intro.html#consume-the-automation-template) the package and make the command available for use. ## Commands There are currently two(2) commands that have been built inside of the project; - SetupBlazorProject - MigrateWebForm The first command, *SetupBlazorProject*, is an implementation of a [Project Command](http://docs.codefactory.software/guidance/overview-commands-intro.html) type and can be found by right-clicking on the Blazor project in your solution. The command is found at the bottom of the context menu. ![](./images/SetupBlazorProjectContextMenu.png) The second command, *MigrateWebForm*, is an implementation of a [Project Document Command](http://docs.codefactory.software/guidance/overview-commands-intro.html) type and can be found by right-clicking on any *.aspx file that is found in the *WingTipToys* project. ![](./images/MigrateToBlazorContextMenu.png) ## Project Structure The following folders are found in this project. ### Commands This folder is further broken down into command type folders. Please click on each item found below to get further details. #### Document Name | Description -----|------- MigrateWebForm.cs | This is a [Project Document](http://docs.codefactory.software/guidance/overview/commands/projectdocument.html) command type that is built to migrate a single *.aspx file from the source WebForms project into an equivalent Blazor Page Component file in the target Blazor Server project. Please click [here](MigrateWebFormCommand.md) for more details #### Project Name | Description -----|------- SetupBlazorProject.cs | This is a [Project](http://docs.codefactory.software/guidance/overview/commands/project.html) command type that will allow a developer to bulk-migrate an **entire** WebForms appliction including all of its logic, configuration and static assets into a Blazor Server application. Please click [here](SetupBlazorProjectCommand.md) for more details. ### Dialogs Name | Description -----|------- DialogExtensions.cs | This is a standard C# static class that contains a few helper extension methods for dealing with the other two dialogs in the project. Please click [here](DialogExtensionsFile.md) for more details. MigrateWebForm.xaml/xaml.cs | This is a CodeFactory specific WPF UserControl that is used displayed during the execution of the [Migrate WebForm](MigrateWebFormCommand.md) command. Please click [here](MigrateWebFormDialogFile.md) for more details. MigrateStepStatus.cs | This is a standard C# POCO object that is used to pass information back to the [MigrateWebForm](MigrateWebFormDialogFile.md) WPF user control in order to be displayed to the developer/user. Please click [here](MigrationStepStatusFile.md) for more details. SetupBlazorDialg.xaml/xaml.cs | This is a CodeFactory specific WPF UserControl that is displayed during the execution of the [SetupBlazorProject](SetupBlazorProjectCommand.md) command. Please click [here](SetupBlazorDialogFile.md) for more details. ### Migration Name | Description -----|------- AspxToBlazorControlConverter.cs | This is a C# class which is the adaptee of the [ConverterAdapter](ConverterAdapterFile.md) class. It understands how to convert WebForms/ASP.NET controls into Blazor equivalents. Please click [here](AspxToBlazorConverterFile.md) for more details. ControlConverterBase.cs | This is a C# class that all adaptee classes, like the above [AspxToBlazorControlConverter.cs](AspxToBlazorConverterFile.md), inherit from in order to comply with the pattern as implemented by the ConverterAdapter class. Please click [here](ControlConverterBaseFile.md) for more details. ConverterAdapter.cs | This is the main adapter class that is used by logic found in a number of the methods from the [WebFormToBlazorMigration](WebFormToBlazorServerMigrationFile.md) partial classes definitsion. Please click [here](ConverterAdapterFile.md) for more details. IControlConverter.cs | This is a standard C# Interface object used by the ControlConverterBase class. Please click [here](IControlConverterFile.md) for more details. IMigrationStatusUpdate.cs | This is a standard C# Interface object used by the migration logic to pass information back up to both of the dialog classes during exectuion. Please click [here](IMigrationStatusUpdateFile.md) for more details. ITagControlConverter.cs | This is a standard C# Interface object that defines a single method that is to be implemented by any ControlConverter the is authored. Please click [here](ITagControlConverterFile.md) for more details. MessageTypeEnum.cs | This is a standard C# Enumeration object that is leveraged during status updates from any migration logic to a running dialog during either of the commands. Please click [here](MessageTypeEnumFile.md) for more details. MigrationExtensionMethods.cs | This is a standard C# static class that contains several helper methods which are leveraged by migration logic found in other areas of the project. Please click [here](MigrationExtensionMethodsFile.md) for more details. MigrationStatusEnum.cs | This is a standard C# Enumeration object that is leveraged during status updates from any migration logic to a running dialog during either of the commands. Please click [here](MigrationStatusEnumFile.md) for more details. MigrationStepEnum.cs | This is a standard C# Enumeration object that is leveraged during status updates from any migration logic to a running dialog during either of the commands. Please click [here](MigrationStepEnumFile.md) for more details. MigrationSteps.cs | This is a standard C# POCO that holds information on which steps of the [SetupBlazorProject](SetupBlazorProjectCommand.md) command dialog, [SetupBlazorDialog](SetupBlazorDialogFile.md) for more details. WebFormToBlazorServerMigration.cs | This is a C# *partial* class definition which contains all of the logic for migrating the different parts of a WebForms project into a Blazor Server application. This class is called by the [SetupBlazorDialog](SetupBlazorDialogFile.md) WPF User dialog. Please click [here](WebFormToBlazorServerMigrationFile.md) for more details. WebFormToBlazorServerMigration.AspxFiles.cs | This is a C# *partial* class definition which contains logic **specific** to the conversion of any *.aspx pages that are found in the source WebForms project. Please click [here](WebFormToBlazorServerMigrationAspxFileFile.md) for more details. WebFormToBlazorServerMigration.Bundling.cs | This is a C# *partial* class definition which contains logic **specific** to the migration of any scripts that are bundled up in the source WebForms project over to the target Blazor project. Please click [here](WebFormToBlazorServerMigrationBundlingFile.md) for more details. WebFormToBlazorServerMigration.Config.cs | This is a C# *partial* class definition which contains logic **specific** to the migration of app.config/web.config data that are found in the source WebForms project. Please click [here](WebFormToBlazorServerMigrationConfigFile.md) for more details. WebFormToBlazorServerMigration.HttpModules.cs | This is a C# *partial* class definition which contains logic **specific** to the migration of any HttpModules that have been customized/defined within the source WebForms project. Please click [here](WebFormToBlazorServerMigrationHttpModulesFile.md) for more details. WebFormToBlazorServerMigration.Logic.cs | This is a C# *partial* class definition which contains logic **specific** to the migration of any *.cs class documents that are found in the source WebForms project. Please click [here](WebFormToBlazorServerMigrationLogicFile.md) for more details. WebFormToBlazorServerMigration.Startup.cs | This is a C# *partial* class definition which contains logic **specific** to the migration of the startup.cs code found in the source WebForms project. Please click [here](WebFormToBlazorServerMigrationStartupFile.md) for more details. WebFormToBlazorServerMigration.StaticFiles.cs | This is a C# *partial* class definition which contains logic **specific** to the migration of any images or script files that are found in the source WebForms project. Please click [here](WebFormToBlazorServerMigrationStaticFilesFile.md) for more details. ### Templates Name | Description -----|------- BundleConfigFactory.tt/.cs/transform.cs/ | This is a T4 template that is used to transform and output javascript bundling found in the source WebForms project. Please click [here](BundlingConfigFactoryFile.md) for more details. LogicCodeFactory.tt/.cs/transform.cs/ | This is a T4 template that is used to transform any of the C# class defintion found in the source WebForms project. Please click [here](LogicCodeFactoryFile.md) for more details. MiddlewareConversion.tt/.cs/transform.cs/ | **Depricated and not currently in use** ModuleFactory.tt/.cs/transform.cs/ | This is a T4 template that is used to transform any of the code located within the source WebForms project that inherits from HttpModule. Please click [here](ModuleFactoryFile.md) for more details. PageCodeBehindFactory.tt/.cs/transform.cs/ | This is a T4 template that is used to output code which is found in any of the *.aspx.cs code-behind file that are found inside of the source WebForms project. Please click [here](PageCodeBehindFile.md) for more details.<file_sep>/src/WebFormsToBlazorServerCommands/Dialogs/MigrateWebForm.xaml.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using CodeFactory.Logging; using CodeFactory.VisualStudio; using CodeFactory.VisualStudio.UI; using CodeFactory; using System.Collections.ObjectModel; using WebFormsToBlazorServerCommands.Migration; using System.Windows.Threading; namespace WebFormsToBlazorServerCommands.Dialogs { /// <summary> /// Interaction logic for ShowFileDOM.xaml /// </summary> public partial class MigrateWebFormDialog : VsUserControl, IMigrationStatusUpdate { /// <summary> /// Creates an instance of the user control. /// </summary> /// <param name="vsActions">The visual studio actions that are accessible by this user control.</param> /// <param name="logger">The logger used by this user control.</param> public MigrateWebFormDialog(IVsActions vsActions, ILogger logger) : base(vsActions, logger) { //Initializes the controls on the screen and subscribes to all control events (Required for the screen to run properly) InitializeComponent(); //Creating an empty observable collection. This will be updated during the execution of the migration process. StepStatus = new ObservableCollection<MigrationStepStatus>(); } private void Btn_Cancel(object sender, RoutedEventArgs e) { this.Close(); } private void Btn_Ok(object sender, RoutedEventArgs e) { //Loading the selected project from the dialog VsProject blazorProject = ProjectsCombo.SelectedItem as VsProject; //Checking to make sure a target blazor project has been selected. if (blazorProject == null) { MessageBox.Show("You must have a Blazor Project selected before continuing."); return; } //Checking to make sure that we've got a source *.aspx file to convert if (FormToMigrate == null) { MessageBox.Show("There has been a problem - there is no source *.aspx file selected to migrate."); this.Close(); } try { //Updating the dialog to not accept input while the migration is processing ButtonOk.Content = "Processing"; ButtonOk.IsEnabled = false; ButtonCancel.IsEnabled = false; //Creating the migration process logic. Notice that we pass in a copy of the visual studio actions that code factory uses for visual studio automation. //In addition we pass a reference to the dialog itself. //We have implemented an interface on the dialog that allows the background thread to call into this dialog and update the migration status. var migrationProcess = new WebFormToBlazorServerMigration(_visualStudioActions, this); //Starting the migration process on a background thread and letting the dialog keep processing UI updates. Task.Run(() => migrationProcess.MigrateSingleASPXFile(FormToMigrate,blazorProject));// .StartMigration(webformProject, blazorProject, migrationSteps)) } catch (Exception unhandledError) { //Displaying the error that was not managed during the migration process. MessageBox.Show($"The following unhandled error occured while performing the setup operations. '{unhandledError.Message}'", "Unhandled Setup Error", MessageBoxButton.OK, MessageBoxImage.Error); } } public VsDocument FormToMigrate = null; public VsProject SourceProject = null; // Using a DependencyProperty as the backing store for SolutionProjects. This enables animation, styling, binding, etc... public static readonly DependencyProperty SolutionProjectsProperty = DependencyProperty.Register("SolutionProjects", typeof(IEnumerable<VsProject>), typeof(MigrateWebFormDialog), null); /// <summary> /// The solution projects that will be used by the dialog to select the source and destination projects. /// </summary> public IEnumerable<VsProject> SolutionProjects { get { return (IEnumerable<VsProject>)GetValue(SolutionProjectsProperty); } set { SetValue(SolutionProjectsProperty, value); } } public static readonly DependencyProperty StepStatusProperty = DependencyProperty.Register( "StepStatus", typeof(ObservableCollection<MigrationStepStatus>), typeof(MigrateWebFormDialog), new PropertyMetadata(default(ObservableCollection<MigrationStepStatus>))); public ObservableCollection<MigrationStepStatus> StepStatus { get { return (ObservableCollection<MigrationStepStatus>)GetValue(StepStatusProperty); } set { SetValue(StepStatusProperty, value); } } /// <summary> /// Informs the user of the current status of the migration process. /// </summary> /// <param name="migrationStep">The migration step the status applies to.</param> /// <param name="messageType">The type of messaging being communicated.</param> /// <param name="statusMessage">Status message to be sent to the user.</param> public async Task UpdateCurrentStatusAsync(MigrationStepEnum migrationStep, MessageTypeEnum messageType, string statusMessage) { //confirming there is a message to update. if (string.IsNullOrEmpty(statusMessage)) return; //Scheduling the update of the observable collection that bound to the data grid on the dialog. await Dispatcher.InvokeAsync(() => { var status = new MigrationStepStatus { MessageType = messageType.GetName(), MigrationStep = migrationStep.GetName(), Status = statusMessage }; StepStatus.Add(status); } , DispatcherPriority.Normal); } public async Task UpdateStepStatusAsync(MigrationStepEnum step, MigrationStatusEnum status) { throw new NotImplementedException(); } public async Task UpdateMigrationFinishedAsync() { //Schedules execution on the UI thread to update the OK button to disappear. //The cancel button will be changed to finished. This will trigger the close of the UI. await Dispatcher.InvokeAsync(() => { ButtonOk.Visibility = System.Windows.Visibility.Collapsed; ButtonCancel.Content = "Finished"; ButtonCancel.IsEnabled = true; } , DispatcherPriority.Normal); } public async Task MessageToUserAsync(string title, string message, MessageTypeEnum messageType) { throw new NotImplementedException(); } } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/IMigrationStatusUpdate.cs using System.Threading.Tasks; namespace WebFormsToBlazorServerCommands.Migration { /// <summary> /// Contract that defines how information is to be communicated from the migration automation to the user. /// </summary> public interface IMigrationStatusUpdate { /// <summary> /// Informs the user of the current status of the migration process. /// </summary> /// <param name="migrationStep">The migration step the status applies to.</param> /// <param name="messageType">The type of messaging being communicated.</param> /// <param name="statusMessage">Status message to be sent to the user.</param> Task UpdateCurrentStatusAsync(MigrationStepEnum migrationStep, MessageTypeEnum messageType, string statusMessage); /// <summary> /// Informs the user of the status of a target step of the migration process. /// </summary> /// <param name="step">Step that is getting updated.</param> /// <param name="status">The status the step is being changed to.</param> Task UpdateStepStatusAsync(MigrationStepEnum step, MigrationStatusEnum status); /// <summary> /// Informs the hosting process the migration has been finished and other operations can continue. /// </summary> Task UpdateMigrationFinishedAsync(); /// <summary> /// Informs the user of the migration process with a target message. /// </summary> /// <param name="title">The title of the message.</param> /// <param name="message">The message to be displayed to the user.</param> /// <param name="messageType">The type of message to display to the user.</param> Task MessageToUserAsync(string title, string message, MessageTypeEnum messageType); } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/ITagControlConverter.cs using System.Threading.Tasks; namespace WebFormsToBlazorServerCommands.Migration { /// <summary> /// Contract that any main Adapter must implement in order to be called by the parent (calling) migration code /// </summary> public interface ITagControlConverter { /// <summary> /// This method is used to send in a TagControl(eg. 'asp:ListView' etc) and its inclusive node content. /// </summary> /// <param name="tagControlName"></param> /// <param name="tagNodeContent"></param> /// <returns>The converted/migrated string content of the TagControl. It is entirely possible that the return NodeText will have overridded the TagControlName into something else entirely. ie. a Blazor control</returns> Task<string> MigrateTagControl(string tagControlName, string tagNodeContent); } } <file_sep>/guidance/ModuleFactoryFile.md # ModuleFactory.tt/.transform.cs/.cs Files ## Overview ## Fields ## Constrcutor ## Methods<file_sep>/src/WebFormsToBlazorServerCommands/Dialogs/SetupBlazorDialog.xaml.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; using CodeFactory.Logging; using CodeFactory.VisualStudio; using CodeFactory.VisualStudio.UI; using WebFormsToBlazorServerCommands.Migration; namespace WebFormsToBlazorServerCommands.Dialogs { /// <summary> /// Interaction logic for SetupBlazorDialog.xaml /// </summary> public partial class SetupBlazorDialog : VsUserControl,IMigrationStatusUpdate { /// <summary> /// Creates an instance of the user control. /// </summary> /// <param name="vsActions">The visual studio actions that are accessible by this user control.</param> /// <param name="logger">The logger used by this user control.</param> public SetupBlazorDialog(IVsActions vsActions, ILogger logger) : base(vsActions, logger) { //Initializes the controls on the screen and subscribes to all control events (Required for the screen to run properly) InitializeComponent(); //Creating an empty observable collection. This will be updated during the execution of the migration process. StepStatus = new ObservableCollection<MigrationStepStatus>(); } #region Dependency Properties /// <summary> /// The solution projects that will be used by the dialog to select the source and destination projects. /// </summary> public IEnumerable<VsProject> SolutionProjects { get { return (IEnumerable<VsProject>)GetValue(SolutionProjectsProperty); } set { SetValue(SolutionProjectsProperty, value); } } // Using a DependencyProperty as the backing store for SolutionProjects. This enables animation, styling, binding, etc... public static readonly DependencyProperty SolutionProjectsProperty = DependencyProperty.Register("SolutionProjects", typeof(IEnumerable<VsProject>), typeof(SetupBlazorDialog), null); public static readonly DependencyProperty StepStatusProperty = DependencyProperty.Register( "StepStatus", typeof(ObservableCollection<MigrationStepStatus>), typeof(SetupBlazorDialog), new PropertyMetadata(default(ObservableCollection<MigrationStepStatus>))); public ObservableCollection<MigrationStepStatus> StepStatus { get { return (ObservableCollection<MigrationStepStatus>)GetValue(StepStatusProperty); } set { SetValue(StepStatusProperty, value); } } #endregion #region Button Event Management /// <summary> /// Processes the cancel button click event. /// </summary> /// <param name="sender">Hosting user control.</param> /// <param name="e">Ignored when used in this context.</param> private void ButtonCancel_Click(object sender, RoutedEventArgs e) { //Closing the dialog and returning control to visual studio. this.Close(); } /// <summary> /// Process the ok button click event. /// </summary> /// <param name="sender">Hosting user control.</param> /// <param name="e">We dont use the routing args with this implementation.</param> private void ButtonOk_Click(object sender, RoutedEventArgs e) { //Loading the selected projects from the dialog VsProject webformProject = ComboboxWebFormsProject.SelectedItem as VsProject; VsProject blazorProject = ComboboxBlazorProject.SelectedItem as VsProject; //Checking that a source webforms project has been selected. if (webformProject == null) { MessageBox.Show("You must select a Webforms Project before continuing."); return; } //Checking to make sure a target blazor project has been selected. if (blazorProject == null) { MessageBox.Show("You must have a Blazor Project selected before continuing."); return; } //Checking to make sure the same project was not selected. if (webformProject.Name == blazorProject.Name) { MessageBox.Show("The web forms project and the blazor project cannot be the same."); return; } bool migrationStepsSelected = false; migrationStepsSelected = CheckBoxMigrateAspxPages.IsChecked.GetResult() | CheckBoxMigrateBundling.IsChecked.GetResult() | CheckBoxMigrateConfiguration.IsChecked.GetResult() | CheckBoxMigrateHttpModules.IsChecked.GetResult() | CheckBoxMigrateLogic.IsChecked.GetResult() | CheckBoxMigrateStaticFiles.IsChecked.GetResult() | CheckBoxStartupProcess.IsChecked.GetResult(); if (!migrationStepsSelected) { MessageBox.Show("You have to select a migration step in order to continue."); return; } try { var migrationSteps = new MigrationSteps(CheckBoxStartupProcess.IsChecked.GetResult(), CheckBoxMigrateHttpModules.IsChecked.GetResult(), CheckBoxMigrateStaticFiles.IsChecked.GetResult(), CheckBoxMigrateBundling.IsChecked.GetResult(), CheckBoxMigrateAspxPages.IsChecked.GetResult(), CheckBoxMigrateConfiguration.IsChecked.GetResult(), CheckBoxMigrateLogic.IsChecked.GetResult()); //Creating an empty observable collection. This will be updated during the execution of the migration process. StepStatus = new ObservableCollection<MigrationStepStatus>(); //Updating the dialog to not accept input while the migration is processing ButtonOk.Content = "Processing"; ButtonOk.IsEnabled = false; ButtonCancel.IsEnabled = false; //Creating the migration process logic. Notice that we pass in a copy of the visual studio actions that code factory uses for visual studio automation. //In addition we pass a reference to the dialog itself. //We have implemented an interface on the dialog that allows the background thread to call into this dialog and update the migration status. var migrationProcess = new WebFormToBlazorServerMigration(_visualStudioActions, this); //Updating the UI to begin the migration process. SetupStatusForMigration(migrationSteps); //Starting the migration process on a background thread and letting the dialog keep processing UI updates. Task.Run(() => migrationProcess.StartMigration(webformProject, blazorProject, migrationSteps)); } catch (Exception unhandledError) { //Displaying the error that was not managed during the migration process. MessageBox.Show($"The following unhandled error occured while performing the setup operations. '{unhandledError.Message}'", "Unhandled Setup Error", MessageBoxButton.OK, MessageBoxImage.Error); } } /// <summary> /// Helper that configures the screen once the migration process has begun. /// </summary> /// <param name="steps">The migration steps to be performed.</param> private void SetupStatusForMigration(MigrationSteps steps) { //Updating logic step CheckBoxMigrateLogic.Visibility = Visibility.Collapsed; TextBlockMigrateLogicStatus.Visibility = Visibility.Visible; if (!steps.AppLogic) TextBlockMigrateLogicStatus.TextDecorations = TextDecorations.Strikethrough; //Updating the Http Modules step CheckBoxMigrateHttpModules.Visibility = Visibility.Collapsed; TextBlockMigrateHttpModulesStatus.Visibility = Visibility.Visible; if (!steps.HttpModules) TextBlockMigrateHttpModulesStatus.TextDecorations = TextDecorations.Strikethrough; //Updating the static files step. CheckBoxMigrateStaticFiles.Visibility = Visibility.Collapsed; TextBlockMigrateStaticFilesStatus.Visibility = Visibility.Visible; if (!steps.StaticFiles) TextBlockMigrateStaticFilesStatus.TextDecorations = TextDecorations.Strikethrough; //Updating Aspx Page s step CheckBoxMigrateAspxPages.Visibility = Visibility.Collapsed; TextBlockMigrateAspxPagesStatus.Visibility = Visibility.Visible; if (!steps.AspxPages) TextBlockMigrateAspxPagesStatus.TextDecorations = TextDecorations.Strikethrough; //Updating the Bundling step CheckBoxMigrateBundling.Visibility = Visibility.Collapsed; TextBlockMigrateBundlingStatus.Visibility = Visibility.Visible; if (!steps.Bundling) TextBlockMigrateBundlingStatus.TextDecorations = TextDecorations.Strikethrough; //Updating the configuration step CheckBoxMigrateConfiguration.Visibility = Visibility.Collapsed; TextBlockMigrateConfigurationStatus.Visibility = Visibility.Visible; if (!steps.Configuration) TextBlockMigrateConfigurationStatus.TextDecorations = TextDecorations.Strikethrough; //Updating the app logic step CheckBoxMigrateLogic.Visibility = Visibility.Collapsed; TextBlockMigrateLogicStatus.Visibility = Visibility.Visible; if (!steps.AppLogic) TextBlockMigrateLogicStatus.TextDecorations = TextDecorations.Strikethrough; //Updating the startup logic step CheckBoxStartupProcess.Visibility = Visibility.Collapsed; TextBlockStartupProcessStatus.Visibility = Visibility.Visible; if (!steps.Startup) TextBlockStartupProcessStatus.TextDecorations = TextDecorations.Strikethrough; //Displaying the migration process status TextBlock. TextBlockMigrationProcessStatus.Visibility = Visibility.Visible; } #endregion #region Implementation of IMigrationStatusUpdate /// <summary> /// Informs the user of the current status of the migration process. /// </summary> /// <param name="migrationStep">The migration step the status applies to.</param> /// <param name="messageType">The type of messaging being communicated.</param> /// <param name="statusMessage">Status message to be sent to the user.</param> public async Task UpdateCurrentStatusAsync(MigrationStepEnum migrationStep, MessageTypeEnum messageType, string statusMessage) { //confirming there is a message to update. if (string.IsNullOrEmpty(statusMessage)) return; //Scheduling the update of the observable collection that bound to the data grid on the dialog. await Dispatcher.InvokeAsync(() => { var status = new MigrationStepStatus { MessageType = messageType.GetName(), MigrationStep = migrationStep.GetName(), Status = statusMessage }; StepStatus.Add(status); } , DispatcherPriority.Normal); } /// <summary> /// Informs the user of the status of a target step of the migration process. /// </summary> /// <param name="step">Step that is getting updated.</param> /// <param name="status">The status the step is being changed to.</param> public async Task UpdateStepStatusAsync(MigrationStepEnum step, MigrationStatusEnum status) { //Scheduling the update of the target step in the migration process process. //Extension method is used on the TextBlock to update the status of the migration step. await Dispatcher.InvokeAsync(() => { switch (step) { case MigrationStepEnum.Startup: BorderStartupProcess.Visibility = status == MigrationStatusEnum.Running ? Visibility.Visible : Visibility.Hidden; TextBlockStartupProcessStatus.UpdateMigrationStatus(status); break; case MigrationStepEnum.HttpModules: BorderMigrateHttpModules.Visibility = status == MigrationStatusEnum.Running ? Visibility.Visible : Visibility.Hidden; TextBlockMigrateHttpModulesStatus.UpdateMigrationStatus(status); break; case MigrationStepEnum.StaticFiles: BorderMigrateStaticFiles.Visibility = status == MigrationStatusEnum.Running ? Visibility.Visible : Visibility.Hidden; TextBlockMigrateStaticFilesStatus.UpdateMigrationStatus(status); break; case MigrationStepEnum.Bundling: BorderMigrateBundling.Visibility = status == MigrationStatusEnum.Running ? Visibility.Visible : Visibility.Hidden; TextBlockMigrateBundlingStatus.UpdateMigrationStatus(status); break; case MigrationStepEnum.AspxPages: BorderMigrateAspxPages.Visibility = status == MigrationStatusEnum.Running ? Visibility.Visible : Visibility.Hidden; TextBlockMigrateAspxPagesStatus.UpdateMigrationStatus(status); break; case MigrationStepEnum.Config: BorderMigrateConfiguration.Visibility = status == MigrationStatusEnum.Running ? Visibility.Visible : Visibility.Hidden; TextBlockMigrateConfigurationStatus.UpdateMigrationStatus(status); break; case MigrationStepEnum.AppLogic: BorderMigrateLogic.Visibility = status == MigrationStatusEnum.Running ? Visibility.Visible : Visibility.Hidden; TextBlockMigrateLogicStatus.UpdateMigrationStatus(status); break; case MigrationStepEnum.MigrationProcess: BorderMigrateProcess.Visibility = status == MigrationStatusEnum.Running ? Visibility.Visible : Visibility.Hidden; TextBlockMigrationProcessStatus.UpdateMigrationStatus(status); break; } } , DispatcherPriority.Normal); } /// <summary> /// Informs the hosting process the migration has been finished and other operations can continue. /// </summary> public async Task UpdateMigrationFinishedAsync() { //Schedules execution on the UI thread to update the OK button to disappear. //The cancel button will be changed to finished. This will trigger the close of the UI. await Dispatcher.InvokeAsync(() => { TextBlockMigrationProcessStatus.Text = "Migration Process Complete"; ButtonOk.Visibility = System.Windows.Visibility.Collapsed; ButtonCancel.Content = "Finished"; ButtonCancel.IsEnabled = true; } , DispatcherPriority.Normal); } /// <summary> /// Informs the user of the migration process with a target message. /// </summary> /// <param name="title">The title of the message.</param> /// <param name="message">The message to be displayed to the user.</param> /// <param name="messageType">The type of message to display to the user.</param> public async Task MessageToUserAsync(string title, string message, MessageTypeEnum messageType) { //Schedules execution on the UI thread to show a message box await Dispatcher.InvokeAsync(() => { MessageBoxImage messageBoxImage = MessageBoxImage.Information; switch (messageType) { case MessageTypeEnum.Warning: messageBoxImage = MessageBoxImage.Warning; break; case MessageTypeEnum.Error: messageBoxImage = MessageBoxImage.Error; break; } MessageBox.Show(message, title, MessageBoxButton.OK, messageBoxImage); } , DispatcherPriority.Normal); } #endregion } } <file_sep>/guidance/WebFormToBlazorServerMigrationBundlingFile.md # WebFormToBlazorServerMigration.Bundling.cs File ## Overview ## Fields ## Constrcutor ## Methods<file_sep>/README.md # WebForms2BlazorServer Automation Template This project is an implementation of a CodeFactory automation template designed specifically to migrate an existing legacy .NET Webforms application to a Blazor Server application. This template is offered as open-source and anyone can download and alter it to suit the particular needs of any WebForms migration efforts that they are faced with. ## New to CodeFactory? In the simplest terms, CodeFactory is a real time software factory that is triggered from inside Visual Studio during the design and construction of software. CodeFactory allows for development staff to automate repetitive development tasks that take up developer’s time. Please see the following link for further information and guidance about the [CodeFactory Runtime](https://github.com/CodeFactoryLLC/CodeFactory) or the [CodeFactory SDK](https://www.nuget.org/packages/CodeFactorySDK/). Register here for a free trial license of [CodeFactory for Visual Studio](https://www.codefactory.software/freetrial). ## Core purpose of the template This automation template was built using the [CodeFactory SDK](https://www.nuget.org/packages/CodeFactorySDK/) to make the task of migrating/converting a legacy .NET WebForms web application over to an updated Blazor Server-side application. The template has the following commands and features avaible to anyone who has a valid copy of [CodeFactory Runtime](http://www.codefactory.software) installed as an extension inside of their local copy of Visual Studio. - Migrate a single *.aspx page from a source WebForms project into a target Blazor project within the same solution. - This will convert any of the legacy markup from `<% %>` to its new Razor syntax `@()`. - locate any `asp:*` tags/controls within the source and convert those over to a WebForms Blazor component from this project [Fritz.BlazorWebFormsComponents](https://www.nuget.org/packages/Fritz.BlazorWebFormsComponents/) - Locate any code-behind files and migrate those over into a new code-behind file for the Blazor Component. (Some code is commented out as it does not apply to Blazor but is copied for the sake of historical reference) - Migrate an entire WebForms project in bulk over to a target Blazor Server-side project. - Migrate Startup process artifacts - Migrate HTTP Modules - Migrate static assets (images/scripts) - Migrate any script bundling configurations - Migrate all *.aspx pages in the project including any code-behind files - Migrate over .config settings - Migrate over business/app logic (any *.cs files that are *not* an aspx/asax/ascx) ## Links to Guidance For technical explanations of each file/class/command in this Automation Template please see the [guidance](./guidance/Guidance.md) page for further information. ## Known Limitations of this Automation Template - Any logic found in the source *.aspx.cs code-behind file will get ported over to a new code-behind file for the blazor component, but in a commented-out format. This code will need to be manually edited to ensure that is complies with the Blazor framework. - Any business logic classes, `*.cs`, files that get moved over from the bulk migration option will *not* be modified beyond setting the new namespaces for the Target Blazor app. Please review the code to make certain that all dependencies and/or namespaces are valid. <file_sep>/src/WebFormsToBlazorServerCommands/Migration/MigrationExtensionMethods.cs using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using CodeFactory.DotNet.CSharp; using CodeFactory.VisualStudio; namespace WebFormsToBlazorServerCommands.Migration { /// <summary> /// Class that holds extension methods that are used in migration process. /// </summary> public static class MigrationExtensionMethods { /// <summary> /// Extension method that loads all <see cref="VsProjectFolder"/> , <see cref="VsDocument"/>, and <see cref="VsCSharpSource"/> /// </summary> public static async Task<IReadOnlyList<VsModel>> LoadAllProjectData(this VsProject source,bool loadSourceCode = true) { return source != null ? await source.GetChildrenAsync(true, loadSourceCode) : ImmutableList<VsModel>.Empty; } /// <summary> /// Extension method that searches C# source code files for a base class inheritance. /// </summary> /// <param name="source">The source visual studio project to search.</param> /// <param name="baseClassName">The name of the base class to search for.</param> /// <param name="searchChildren">Flag that determines if you search all child project folders under the project.</param> /// <returns>The target source code that meets the criteria or an empty list. </returns> public static async Task<IReadOnlyList<CsSource>> GetClassesThatInheritBaseAsync(this VsProject source, string baseClassName, bool searchChildren) { //If the project is not created return an empty list. if (source == null) return ImmutableList<CsSource>.Empty; //Calling into the CodeFactory project system api to load all project items, will pre load the source code models. var children = await source.GetChildrenAsync(searchChildren,true); //Pulling out the list of all code files. var sourceCodeFiles = children.Where(p => p.ModelType.Equals(VisualStudioModelType.CSharpSource)).Cast<VsCSharpSource>(); //Returning the code files that implement the target base class. return sourceCodeFiles.Select(codeFile => codeFile.SourceCode) .Where(sourceCode => sourceCode.Classes.Any(c => c.BaseClass.Name.Equals(baseClassName))) .ToImmutableList(); } /// <summary> /// Extension method that searches C# source code files for a base class inheritance. /// </summary> /// <param name="source">The source visual studio project to search.</param> /// <param name="baseClassName">The name of the base class to search for.</param> /// <returns>The target source code that meets the criteria or an empty list. </returns> public static IReadOnlyList<CsSource> GetClassesThatInheritBase(this IReadOnlyList<VsModel> source, string baseClassName) { //No source model was provided will return an empty list. if (source == null) return ImmutableList<CsSource>.Empty; //Pulling out the list of all code files. var sourceCodeFiles = source.Where(p => p.ModelType.Equals(VisualStudioModelType.CSharpSource)).Cast<VsCSharpSource>(); //Returning the code files that meet the criteria. return sourceCodeFiles.Select(codeFile => codeFile.SourceCode) .Where(sourceCode => sourceCode.Classes.Any(c => c.BaseClass.Name.Equals(baseClassName))) .ToImmutableList(); } /// <summary> /// Extension method that searches a project for a C# class that exists in one of the projects documents. /// </summary> /// <param name="source">Source Project to search through</param> /// <param name="className">The name of the class to search for.</param> /// <param name="searchChildren">Flag that determines if the entire project should be searched or just the root of the project.</param> /// <returns>The first instance of the class or null.</returns> public static async Task<CsClass> FindClassAsync(this VsProject source, string className, bool searchChildren) { //Loading the visual studio models from the project and pre creating the source code files. var children = await source.GetChildrenAsync(searchChildren,true); //Extracting all the c# source code files from the returned models. var sourceCodeFiles = children.Where(p => p.ModelType.Equals(VisualStudioModelType.CSharpSource)).Cast<VsCSharpSource>(); //Getting the first code file that contains the class. Returning either null or the found class. return sourceCodeFiles.FirstOrDefault(s => s.SourceCode.Classes.Any(c => c.Name.Equals(className))) ?.SourceCode.Classes.FirstOrDefault(c => c.Name.Equals(className)); } /// <summary> /// Extension method that searches a list of project models for a C# class that exists in one of the projects documents. /// </summary> /// <param name="source">List of visual studio models to search</param> /// <param name="className">The name of the class to search for.</param> /// <returns>The first instance of the class or null.</returns> public static CsClass FindClass(this IReadOnlyList<VsModel> source, string className) { //Extracting all the c# source code files from the returned models. var sourceCodeFiles = source.Where(p => p.ModelType.Equals(VisualStudioModelType.CSharpSource)).Cast<VsCSharpSource>(); //Getting the first code file that contains the class. Returning either null or the found class. return sourceCodeFiles.FirstOrDefault(s => s.SourceCode.Classes.Any(c => c.Name.Equals(className))) ?.SourceCode.Classes.FirstOrDefault(c => c.Name.Equals(className)); } /// <summary> /// Gets target classes that implement a target interface. It will skip classes that implement Page or HttpApplication. /// </summary> /// <param name="source">The project to search for the classes in.</param> /// <param name="interfaceName">The name of the interface to search for.</param> /// <param name="searchChildren">Flag to determine if sub folder should be searched or just the root project folder.</param> /// <returns>Readonly list of the found source code files with the target classes in them. or an empty list.</returns> public static async Task<IReadOnlyList<CsSource>> GetClassesThatImplementInterfaceAsync(this VsProject source, string interfaceName, bool searchChildren) { //Bounds check will return an empty list if no project was provided. if (source == null) return ImmutableList<CsSource>.Empty; //Calls into the CodeFactory project system and gets the children of the supplied project. Will load all code files that support C# as CSharpSource files. var children = await source.GetChildrenAsync(searchChildren, true); //Extracting all the C# code files from the returned project data. var codeFiles = children.Where(p => p.ModelType.Equals(VisualStudioModelType.CSharpSource)) .Cast<VsCSharpSource>(); //Collection all the code files that meet the criteria and returning the source code models for each. return codeFiles.Where(s => s.SourceCode.Classes.Any(c => (!c.BaseClass.Name.Equals("Page") && !c.BaseClass.Name.Equals("HttpApplication")) && c.InheritedInterfaces.Any(x => x.Name.Equals(interfaceName)))) .Select(s => s.SourceCode) .ToImmutableList(); } /// <summary> /// Gets target classes that implement a target interface. It will skip classes that implement Page or HttpApplication. /// </summary> /// <param name="source">The list of visual studio models to search for the classes in.</param> /// <param name="interfaceName">The name of the interface to search for.</param> /// <returns>Readonly list of the found source code files with the target classes in them. or an empty list.</returns> public static IReadOnlyList<CsSource> GetClassesThatImplementInterface(this IReadOnlyList<VsModel> source, string interfaceName) { //Bounds check will return an empty list if no project was provided. if (source == null) return ImmutableList<CsSource>.Empty; //Extracting all the C# code files from the returned project data. var codeFiles = source.Where(p => p.ModelType.Equals(VisualStudioModelType.CSharpSource)) .Cast<VsCSharpSource>(); //Collection all the code files that meet the criteria and returning the source code models for each. return codeFiles.Where(s => s.SourceCode.Classes.Any(c => (!c.BaseClass.Name.Equals("Page") && !c.BaseClass.Name.Equals("HttpApplication")) && c.InheritedInterfaces.Any(x => x.Name.Equals(interfaceName)))) .Select(s => s.SourceCode) .ToImmutableList(); } /// <summary> /// Used to check a project model for the existence of a folder at the root level of a given name. If the folder is /// missing - create it. /// </summary> /// <param name="source">The visual studio project that we are checking exists or creating.</param> /// <param name="folderName">The name of the folder to return.</param> /// <returns>The existing or created project folder.</returns> /// <exception cref="ArgumentNullException">Thrown if either provided parameter is not provided.</exception> public static async Task<VsProjectFolder> CheckAddFolder(this VsProject source, string folderName) { //Bounds checking to make sure all the data needed to get the folder returned is provided. if(source == null) throw new ArgumentNullException(nameof(source)); if(string.IsNullOrEmpty(folderName)) throw new ArgumentNullException(nameof(folderName)); //Calling the project system in CodeFactory and getting all the children in the root of the project. var projectFolders = await source.GetChildrenAsync(false); //Searching for the project folder, if it is not found will add the project folder to the root of the project. return projectFolders.Where(m => m.ModelType == VisualStudioModelType.ProjectFolder) .Where(m => m.Name.Equals(folderName)) .Cast<VsProjectFolder>() .FirstOrDefault() ?? await source.AddProjectFolderAsync(folderName); } /// <summary> /// Returns a list of non-source code documents from VsProject that have a matching extension. /// </summary> /// <param name="source">The source visual studio project to search.</param> /// <param name="extension">The file extension to search for</param> /// <param name="searchChildren">Flag that determines if nested project folders should also be searched for files.</param> /// <param name="excludeKnownExternalFolders">Flag that determines if a content filter should be applied.</param> /// <returns>List of documents that meet the criteria.</returns> public static async Task<IReadOnlyList<VsDocument>> GetDocumentsWithExtensionAsync(this VsProject source, string extension, bool searchChildren, bool excludeKnownExternalFolders) { //If no source is found return an empty list. if (source == null) return ImmutableList<VsDocument>.Empty; //If no file extension is provided return an empty list. if (string.IsNullOrEmpty(extension)) return ImmutableList<VsDocument>.Empty; List<VsDocument> result = new List<VsDocument>(); //Making sure we start with a period for the extension for searching purposes. if (!extension.StartsWith(".")) extension = $".{extension}"; //Calling the CodeFactory project system api to get the children of the project. var children = await source.GetChildrenAsync(searchChildren); //Filtering out to just var sourceFiles = children.Where(p => p.ModelType.Equals(VisualStudioModelType.Document)) .Cast<VsDocument>().Where(d => !d.IsSourceCode); return sourceFiles.Where(s => { //If we are excluding external folders just check for the extension. if (!excludeKnownExternalFolders) return s.Name.EndsWith(extension); //Checking to make sure the file is not in the excluded list. var documentPath = s.Path; if (string.IsNullOrEmpty(documentPath)) return false; return !documentPath.ToLower().Contains("\\content\\") && s.Name.EndsWith(extension); }).ToImmutableList(); } /// <summary> /// Returns a list of non-source code documents from VsProject that have a matching extension. /// </summary> /// <param name="source">The list of visual studio models to search for documents in.</param> /// <param name="projectDirectory">The fully qualified path to the project directory.</param> /// <param name="extension">The file extension to search for</param> /// <param name="excludeKnownExternalFolders">Flag that determines if a content filter should be applied.</param> /// <returns>List of documents that meet the criteria.</returns> public static IReadOnlyList<VsDocument> GetDocumentsWithExtension(this IReadOnlyList<VsModel> source, string projectDirectory, string extension, bool excludeKnownExternalFolders) { //If no source is found return an empty list. if (source == null) return ImmutableList<VsDocument>.Empty; //If no file extension is provided return an empty list. if (string.IsNullOrEmpty(extension)) return ImmutableList<VsDocument>.Empty; List<VsDocument> result = new List<VsDocument>(); //Making sure we start with a period for the extension for searching purposes. if (!extension.StartsWith(".")) extension = $".{extension}"; //Filtering out to just var sourceFiles = source.Where(p => p.ModelType.Equals(VisualStudioModelType.Document)) .Cast<VsDocument>().Where(d => !d.IsSourceCode); return sourceFiles.Where(s => { //If we are excluding external folders just check for the extension. if (!excludeKnownExternalFolders) return s.Name.EndsWith(extension); //Checking to make sure the file is not in the excluded list. var documentPath = s.Path; if (string.IsNullOrEmpty(documentPath)) return false; return !documentPath.ToLower().Contains("\\content\\") && s.Name.EndsWith(extension); }).ToImmutableList(); } /// <summary> /// Extension method that copies a <see cref="VsDocument"/> from a source project to a target location in a supplied destination directory. /// Will replace the source project directory path with a new root destination path. /// This will overwrite the existing file. /// </summary> /// <param name="source">The document to be copied</param> /// <param name="sourceProjectDirectory">The source project directory to be replaced.</param> /// <param name="rootDestinationDirectory">The new target destination path for the file.</param> /// <returns>Null if the file was not copied, or the fully qualified path where the file was copied to.</returns> public static string CopyProjectFile(this VsDocument source, string sourceProjectDirectory, string rootDestinationDirectory) { //Bounds checking to make sure all data has been passed in correctly. If not return null. if (source == null) return null; if (string.IsNullOrEmpty(sourceProjectDirectory)) return null; if (string.IsNullOrEmpty(rootDestinationDirectory)) return null; //Setting the result variable. string result = null; try { //Loading the source file path from the visual studio document. var sourceFile = source.Path; //Replacing the source path with the target destination directory. var destinationFile = sourceFile.Replace(sourceProjectDirectory, rootDestinationDirectory); //Making sure the directory already exists in the target project, if it does not go ahead and add it to the project. var destinationDirectory = Path.GetDirectoryName(destinationFile); if (string.IsNullOrEmpty(destinationDirectory)) return null; if (!Directory.Exists(destinationDirectory)) Directory.CreateDirectory(destinationDirectory); //Copying the project file to the new project. File.Copy(sourceFile,destinationFile,true); //Returning the new file location of the project file in the new project. result = destinationFile; } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { //An error occurred we are going to swallow the exception and return a null return type. return null; } return result; } /// <summary> /// Gets the c# source code files from a target provided lists. /// </summary> /// <param name="source">The source list of files.</param> /// <param name="excludeKnownExternalFolders">Flag that determines if target files by directory location are excluded.</param> /// <returns>List of the found files.</returns> public static IReadOnlyList<VsCSharpSource> GetSourceCodeDocumentsAsync(this IReadOnlyList<VsModel> source, bool excludeKnownExternalFolders) { string extension = ".cs"; var sourceFiles = source.Where(p => p.ModelType.Equals(VisualStudioModelType.CSharpSource)).Cast<VsCSharpSource>(); var result = sourceFiles.Where(s => { if (excludeKnownExternalFolders) { var folderChain = s.SourceCode.SourceDocument; //repeat this section for anything else that might qualify. This is an attempt to give the caller an option //to *not* bring over bootstrap artifacts or the like. if (folderChain.ToLower().Contains("\\app_data\\")) return false; if (folderChain.ToLower().Contains("\\app_start\\")) return false; if (folderChain.ToLower().Contains("\\app_readme\\")) return false; if (folderChain.ToLower().Contains("\\content\\")) return false; } if (s.Name.EndsWith(extension)) return true; return false; }).ToImmutableList(); return result; } /// <summary> /// Gets the immediate VsProject Folder objects that this Document object lives in. /// This list is in reverse order from leaf-to-trunk. An empty list is returned if the document lives in the root of the project. /// </summary> /// <param name="sourceDocument">The visual studio document to search for.</param> /// <returns>List of the the parent <see cref="VsProjectFolder"/> found.</returns> public static async Task<List<VsProjectFolder>> GetParentFolders(this VsDocument sourceDocument) { //Stores the list of parents being returned. List<VsProjectFolder> folderHierarchy = new List<VsProjectFolder>(); //Getting the parent of the source document. var parentModel = await sourceDocument.GetParentAsync(); //If no parent was found return the empty list. if (parentModel == null) return folderHierarchy; //Climb back up the file and folders until you get to the hosting project. while (!parentModel.ModelType.Equals(VisualStudioModelType.Project)) { if (parentModel.ModelType.Equals(VisualStudioModelType.ProjectFolder)) { //Casting the model to the project folder. var parentFolder = parentModel as VsProjectFolder; //checking to make sure the cast ran clean. if (parentFolder == null) return folderHierarchy; //Adding the parent folder to the list to be returned folderHierarchy.Add(parentFolder); //Getting the next parent and confirming it was found. parentModel = await (parentFolder).GetParentAsync(); if (parentModel == null) return folderHierarchy; } else { //Casting to the parent document model. var parentDocument = parentModel as VsDocument; //If the cast failed return what was found. if (parentDocument == null) return folderHierarchy; //Getting the next parent and confirming it was found. parentModel = await (parentDocument).GetParentAsync(); if (parentModel == null) return folderHierarchy; } } //Returning the found parent models. return folderHierarchy; } /// <summary> /// Confirms the target project folder exists in the project, if not will create it. /// </summary> /// <param name="projectFolder">The source project folder to check.</param> /// <param name="folderName">The name of the folder to create or return if it exists.</param> /// <returns>The target project folder.</returns> public static async Task<VsProjectFolder> CheckAddFolder(this VsProjectFolder projectFolder, string folderName) { //Call CodeFactory API and get the children of the project folder. var projectFolders = await projectFolder.GetChildrenAsync(false); //Search for the project folder to confirm it exists, if not create it and return the created folder. return projectFolders.Where(m => m.Name.Equals(folderName)).Cast<VsProjectFolder>().FirstOrDefault() ?? await projectFolder.AddProjectFolderAsync(folderName); } /// <summary> /// Extension method that runs an async call from a sync thread. /// </summary> /// <param name="source">Target C# method to evaluate.</param> /// <returns>The content of the the method body.</returns> public static String MethodContent(this CsMethod source) { var taskObj = Task.Run(async () => await source.GetBodySyntaxAsync()); return taskObj.Result; } } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/Adapters/ControlConverterBase.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebFormsToBlazorServerCommands.Migration { /// <summary> /// Baseclass for all more specific converters to inherit from. /// </summary> public class ControlConverterBase : IControlConverter { internal ITagControlConverter _adapterHost = null; internal List<string> _TagsICanConvert = null; public ControlConverterBase(ITagControlConverter adapterHost) { _adapterHost = adapterHost; } /// <summary> /// List of controls/tags that the implementing Converter class knows how to handle /// </summary> public ReadOnlyCollection<string> AvailableConversionTags { get { return _TagsICanConvert?.AsReadOnly(); } } /// <summary> /// Method to implement which will be called by the ConverterAdapter class /// </summary> /// <param name="tagName"></param> /// <param name="tagNodeContent"></param> /// <returns></returns> public virtual async Task<string> ConvertControlTag(string tagName, string tagNodeContent) { StringBuilder _result = new StringBuilder(); try { _result.Append(tagNodeContent); return _result.ToString(); } catch (Exception) { throw; } } } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/WebFormToBlazorServerMigration.StaticFiles.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using CodeFactory.VisualStudio; namespace WebFormsToBlazorServerCommands.Migration { public partial class WebFormToBlazorServerMigration { /// <summary> /// Copies the static files that were used in the web forms project to the blazor server project. /// </summary> /// <param name="webFormProjectData">Pre cached project data about the web forms project.</param> /// <param name="webFormProject">The web forms project that we are migrating data from.</param> /// <param name="blazorServerProject">The blazor server project this is being migrated to.</param> public async Task MigrateStaticFiles(IReadOnlyList<VsModel> webFormProjectData, VsProject webFormProject, VsProject blazorServerProject) { try { //Letting the dialog know the migration step has started. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.StaticFiles, MigrationStatusEnum.Running); //Fields that will hold the reference to different visual studio files that will be copied to the blazor server project. List<VsDocument> imageFiles = new List<VsDocument>(); List<VsDocument> cssFiles = new List<VsDocument>(); List<VsDocument> jsFiles = new List<VsDocument>(); //Loading up the project directory from the web forms project definition. string webFormsProjectDirectory = Path.GetDirectoryName(webFormProject.Path); if (string.IsNullOrEmpty(webFormsProjectDirectory)) { //Could not find the web forms project directory, fail this migration step and continue. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.StaticFiles, MessageTypeEnum.Error, $"Could not locate the web forms project directory, step cannot be completed."); await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.StaticFiles, MigrationStatusEnum.Failed); return; } //Loading up the project directory for the blazor project. string blazorProjectDirectory = Path.GetDirectoryName(blazorServerProject.Path); if (string.IsNullOrEmpty(blazorProjectDirectory)) { //Could not find the blazor project directory, fail this migration step and continue. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.StaticFiles, MessageTypeEnum.Error, $"Could not locate the blazor project directory, step cannot be completed."); await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.StaticFiles, MigrationStatusEnum.Failed); return; } //Locating the wwwroot folder in the blazor project var blazorProjectDirectoryInfo = new DirectoryInfo(blazorProjectDirectory); var blazorWebRootFolder = blazorProjectDirectoryInfo.GetDirectories("wwwroot").FirstOrDefault()?.FullName; if (string.IsNullOrEmpty(blazorWebRootFolder)) { blazorWebRootFolder = $"{blazorProjectDirectory}\\wwwroot"; await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.StaticFiles, MessageTypeEnum.Warning, $"Could not locate the wwwroot folder in the blazor project will be added at the root of the {blazorServerProject.Name} project."); } //Setting the root file paths where static content files will be copied to. var imagesFolder = $"{blazorWebRootFolder}\\images"; var cssFolder = $"{blazorWebRootFolder}\\css"; var jsFolder = $"{blazorWebRootFolder}\\script"; //Get Image files (.gif, .jpeg, .png, .bitmap) imageFiles.AddRange(webFormProjectData.GetDocumentsWithExtension(webFormsProjectDirectory, ".gif", true)); imageFiles.AddRange(webFormProjectData.GetDocumentsWithExtension(webFormsProjectDirectory, ".jpeg", true)); imageFiles.AddRange(webFormProjectData.GetDocumentsWithExtension(webFormsProjectDirectory, ".png", true)); imageFiles.AddRange(webFormProjectData.GetDocumentsWithExtension(webFormsProjectDirectory, ".bitmap", true)); imageFiles.AddRange(webFormProjectData.GetDocumentsWithExtension(webFormsProjectDirectory, ".ico", true)); //Copying Image files (using the file system into the target under the wwwroot/Images/{folder}/{imageFile} foreach (var document in imageFiles) { var target = document.CopyProjectFile(webFormsProjectDirectory, imagesFolder); if (target == null) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.StaticFiles, MessageTypeEnum.Warning, $"Could not copy the file '{document.Name}' to the blazor project '{blazorServerProject.Name}', you will need to move this file."); } else { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.StaticFiles, MessageTypeEnum.Information, $"Copied the static file '{document.Name}' to the blazor project '{blazorServerProject.Name}'"); } } //Get CSS files (.css) cssFiles.AddRange(webFormProjectData.GetDocumentsWithExtension(webFormsProjectDirectory, ".css", true)); //Copying css files (using the file system into the target under the wwwroot/css/{folder}/{cssFile} foreach (var document in cssFiles) { var target = document.CopyProjectFile(webFormsProjectDirectory, cssFolder); if (target == null) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.StaticFiles, MessageTypeEnum.Warning, $"Could not copy the file '{document.Name}' to the blazor project '{blazorServerProject.Name}', you will need to move this file."); } else { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.StaticFiles, MessageTypeEnum.Information, $"Copied the static file '{document.Name}' to the blazor project '{blazorServerProject.Name}'"); } } //Get CSS files (.css) jsFiles.AddRange(webFormProjectData.GetDocumentsWithExtension(webFormsProjectDirectory, ".js", true)); //Copying css files (using the file system into the target under the wwwroot/css/{folder}/{cssFile} foreach (var document in jsFiles) { var target = document.CopyProjectFile(webFormsProjectDirectory, jsFolder); if (target == null) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.StaticFiles, MessageTypeEnum.Warning, $"Could not copy the file '{document.Name}' to the blazor project '{blazorServerProject.Name}', you will need to move this file."); } else { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.StaticFiles, MessageTypeEnum.Information, $"Copied the static file '{document.Name}' to the blazor project '{blazorServerProject.Name}'"); } } //Completed the migration step informing the dialog. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.StaticFiles, MigrationStatusEnum.Passed); } catch (Exception unhandledError) { //Dumping the exception that occured directly into the status so the user can see what happened. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.StaticFiles, MessageTypeEnum.Error, $"The following unhandled error occured. '{unhandledError.Message}'"); //Updating the status that the step failed await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.StaticFiles, MigrationStatusEnum.Failed); } } } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/WebFormToBlazorServerMigration.AspxFiles.cs using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using CodeFactory.VisualStudio; using CodeFactory.Formatting; using CodeFactory.DotNet.CSharp; using CodeFactory.Formatting.CSharp; using CodeFactory.SourceCode; using System.ComponentModel.Design; using HtmlAgilityPack; using CodeFactory.Markup.Adapter; namespace WebFormsToBlazorServerCommands.Migration { public partial class WebFormToBlazorServerMigration { /// <summary> /// Migrates the existing aspx page files to a standard blazor page format. /// </summary> /// <param name="webFormProjectData">Pre cached project data about the web forms project.</param> /// <param name="webFormProject">The web forms project that we are migrating data from.</param> /// <param name="blazorServerProject">The blazor server project this is being migrated to.</param> [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public async Task MigrateAspxFiles(IReadOnlyList<VsModel> webFormProjectData, VsProject webFormProject, VsProject blazorServerProject) { try { //Informing the dialog the migration step has started. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AspxPages, MigrationStatusEnum.Running); //Getting all the aspx & ascx files in the project. var aspxFiles = webFormProjectData.Where(p => p.ModelType == VisualStudioModelType.Document && ( p.Name.EndsWith(".aspx") || p.Name.EndsWith(".ascx"))).Cast<VsDocument>(); if (!aspxFiles.Any()) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Warning, "No Aspx files were found in the web forms project. This step is finished."); await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AspxPages, MigrationStatusEnum.Passed); return; } //Migrate over the site.master layout pages. var layoutFiles = webFormProjectData.Where(p => p.Name.ToLower().Contains(".master")); var success = await ConvertLayoutFiles(layoutFiles, blazorServerProject); //Calling into the CodeFactory project system and getting all the direct children of the project. var blazorRootModels = await blazorServerProject.GetChildrenAsync(false); //Getting the pages folder from the blazor project. var blazorPagesFolder = blazorRootModels.FirstOrDefault(m => m.ModelType == VisualStudioModelType.ProjectFolder & m.Name.ToLower().Equals("pages")) as VsProjectFolder; //If the pages folder was not found fail this step and return. if (blazorPagesFolder == null) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, "No pages folder was found in the blazor project, cannot continue the aspx file conversion."); await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AspxPages, MigrationStatusEnum.Failed); return; } //Call the CodeFactory project system to get all the current children of the pages project folder. var pagesFolderModels = await blazorPagesFolder.GetChildrenAsync(true); //Filtering out everything but documents. var pages = pagesFolderModels.Where(m => m.ModelType == VisualStudioModelType.Document) .Cast<VsDocument>(); int collect = 0; //Processing each aspx file. foreach (VsDocument aspxFile in aspxFiles) { collect++; //Getting the formatted names that will be used in migrating the ASPX file and its code behind to the blazor project. string targetFileNameNoExtension = Path.GetFileNameWithoutExtension(aspxFile.Path); string aspxCodeBehindFileName = $"{targetFileNameNoExtension}.aspx.cs"; string ascxCodeBehindFileName = $"{targetFileNameNoExtension}.axcs.cs"; string razorPageFileName = $"{targetFileNameNoExtension}.razor"; string razorPageCodeBehindFileName = $"{targetFileNameNoExtension}.razor.cs"; //Searching for an existing razor page. We will delete razor pages and recreate them. var currentRazorPage = pages.FirstOrDefault(p => p.Path.ToLower().EndsWith(razorPageFileName.ToLower())); if (currentRazorPage != null) { //Razor page was found removing the razor page. bool removedPage = await currentRazorPage.DeleteAsync(); if (removedPage) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Information, $"Removed the razor page {razorPageFileName}"); var currentRazorPageCodeBehind = pages.FirstOrDefault(p => p.Path.ToLower().EndsWith(razorPageCodeBehindFileName.ToLower())); if (currentRazorPageCodeBehind != null) { if (File.Exists(currentRazorPageCodeBehind.Path)) { bool removedCodeBehind = await currentRazorPageCodeBehind.DeleteAsync(); if (removedCodeBehind) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Information, $"Removed the razor page code behind file {razorPageCodeBehindFileName}"); } else { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"Could not remove the razor page code behind file {razorPageCodeBehindFileName}.The target ASPX file will not be migrated."); continue; } } } } else { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"Could not remove the razor page {razorPageFileName}.The target ASPX file will not be migrated."); continue; } } VsCSharpSource CodeBehindSource = null; if (aspxFile.Path.Contains("ascx")) { //Getting the code behind file that supports the current aspx page. CodeBehindSource = webFormProjectData .Where(m => m.ModelType == VisualStudioModelType.CSharpSource).Cast<VsCSharpSource>() .FirstOrDefault(s => s.SourceCode.SourceDocument.ToLower().EndsWith(ascxCodeBehindFileName.ToLower())) as VsCSharpSource; } //Getting the code behind file that supports the current aspx page. CodeBehindSource = webFormProjectData .Where(m => m.ModelType == VisualStudioModelType.CSharpSource).Cast<VsCSharpSource>() .FirstOrDefault(s => s.SourceCode.SourceDocument.ToLower().EndsWith(aspxCodeBehindFileName.ToLower())) as VsCSharpSource; //Converting the aspx page and the code behind file if it was found. await ConvertAspxPage(aspxFile, blazorServerProject, blazorPagesFolder, CodeBehindSource); if (collect == 4) { GC.Collect(); collect = 0; } } //Completed the migration step informing the dialog. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AspxPages, MigrationStatusEnum.Passed); } catch (Exception unhandledError) { //Dumping the exception that occured directly into the status so the user can see what happened. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"The following unhandled error occured. '{unhandledError.Message}'"); //Updating the status that the step failed await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AspxPages, MigrationStatusEnum.Failed); } } public async Task MigrateSingleASPXFile(VsDocument aspxSourcefile, VsProject blazorServerProject) { try { //VsCSharpSource aspxCodeBehindFile //Getting the formatted names that will be used in migrating the ASPX file and its code behind to the blazor project. string targetFileNameNoExtension = Path.GetFileNameWithoutExtension(aspxSourcefile.Path); string aspxCodeBehindFileName = $"{targetFileNameNoExtension}.aspx.cs"; string razorPageFileName = $"{targetFileNameNoExtension}.razor"; string razorPageCodeBehindFileName = $"{targetFileNameNoExtension}.razor.cs"; //Calling into the CodeFactory project system and getting all the direct children of the project. var blazorRootModels = await blazorServerProject.GetChildrenAsync(false); //Getting the pages folder from the blazor project. var blazorPagesFolder = blazorRootModels.FirstOrDefault(m => m.ModelType == VisualStudioModelType.ProjectFolder & m.Name.ToLower().Equals("pages")) as VsProjectFolder; //If the pages folder was not found fail this step and return. if (blazorPagesFolder == null) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, "No pages folder was found in the blazor project, cannot continue the aspx file conversion."); return; } //Call the CodeFactory project system to get all the current children of the pages project folder. var pagesFolderModels = await blazorPagesFolder.GetChildrenAsync(true); //Filtering out everything but documents. var pages = pagesFolderModels.Where(m => m.ModelType == VisualStudioModelType.Document) .Cast<VsDocument>(); //Searching for an existing razor page. We will delete razor pages and recreate them. var currentRazorPage = pages.FirstOrDefault(p => p.Path.ToLower().EndsWith(razorPageFileName.ToLower())); if (currentRazorPage != null) { //Razor page was found removing the razor page. bool removedPage = await currentRazorPage.DeleteAsync(); if (removedPage) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Information, $"Removed the razor page {razorPageFileName}"); var currentRazorPageCodeBehind = pages.FirstOrDefault(p => p.Path.ToLower().EndsWith(razorPageCodeBehindFileName.ToLower())); if (currentRazorPageCodeBehind != null) { if (File.Exists(currentRazorPageCodeBehind.Path)) { bool removedCodeBehind = await currentRazorPageCodeBehind.DeleteAsync(); if (removedCodeBehind) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Information, $"Removed the razor page code behind file {razorPageCodeBehindFileName}"); } else { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"Could not remove the razor page code behind file {razorPageCodeBehindFileName}.The target ASPX file will not be migrated."); return; } } } } else { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"Could not remove the razor page {razorPageFileName}.The target ASPX file will not be migrated."); return; } } var aspxChildren = await aspxSourcefile.GetChildrenAsync(true); var codeBehindFile = aspxChildren .Where(c => (c.IsSourceCode == true) && (c.SourceType == SourceCodeType.CSharp)).FirstOrDefault(); //Converting the aspx page and the code behind file if it was found. await ConvertAspxPage(aspxSourcefile, blazorServerProject, blazorPagesFolder, null, codeBehindFile); await _statusTracking.UpdateMigrationFinishedAsync(); } catch (Exception unhandledError) { //Dumping the exception that occured directly into the status so the user can see what happened. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"The following unhandled error occured. '{unhandledError.Message}'"); } } /// <summary> /// This method is used to send an Element through any registered ControlConverter adapters and get back /// the migrated text from the AdapterHost. /// </summary> /// <param name="elementToProcess"></param> /// <returns>String</returns> private async Task<string> ProcessSourceElement(string elementToProcess, AdapterHost host) { HtmlNode processedElement = null; StringBuilder processedHTML = new StringBuilder(); var htmlParser = new HtmlDocument(); htmlParser.LoadHtml(elementToProcess); var contentControlObj = htmlParser.DocumentNode.FirstChild; try { //If this is an ASP:* control then call the migration code, append the *entire* migrated node, and return to the calling method. if (contentControlObj.Name.ToLower().Contains("asp:")) { var newNodeText = await host.ConvertTag(contentControlObj.Name, contentControlObj.OuterHtml); //We do *not* deal with any children of this element, as that is the responsibility of the MigratTagControl to deal with any children of the ASP control return newNodeText; } else { //if the current element has children, // - add it to the targetDocumentFragment without the children attached // - recursively call this method to deal with the children, passing in the new appended as the parent element to append children too if (contentControlObj.ChildNodes.Count > 0) { //shallow clone processedElement = contentControlObj.CloneNode(false); foreach (var item in contentControlObj.ChildNodes) { if (item.NodeType == HtmlNodeType.Element) { var migratedValue = await ProcessSourceElement(item.OuterHtml, host); var migratedChild = HtmlNode.CreateNode(migratedValue.Length > 0 ? migratedValue : " "); processedElement.AppendChild(migratedChild); } } processedHTML.Append(processedElement.OuterHtml); } else { processedHTML.Append((contentControlObj.Clone()).OuterHtml); } return processedHTML.ToString(); } } catch (Exception ex) { throw ex; } finally { htmlParser = null; } } } } <file_sep>/src/WebFormsToBlazorServerCommands/Commands/Document/MigrateWebForm.cs using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CodeFactory.Logging; using CodeFactory.VisualStudio; using CodeFactory.VisualStudio.SolutionExplorer; using CodeFactory.Formatting.CSharp; using WebFormsToBlazorServerCommands.Dialogs; using System.IO; namespace WebFormsToBlazorServerCommands.Commands.Document { /// <summary> /// Code factory command for automation of a document when selected from a project in solution explorer. /// </summary> public class MigrateWebForm : ProjectDocumentCommandBase { private static readonly string commandTitle = "Migrate to Blazor"; private static readonly string commandDescription = "Migrates a single *.aspx page to a Blazor componenet."; #pragma warning disable CS1998 /// <inheritdoc /> public MigrateWebForm(ILogger logger, IVsActions vsActions) : base(logger, vsActions, commandTitle, commandDescription) { //Intentionally blank } #region Overrides of VsCommandBase<VsProjectDocument> /// <summary> /// Validation logic that will determine if this command should be enabled for execution. /// </summary> /// <param name="result">The target model data that will be used to determine if this command should be enabled.</param> /// <returns>Boolean flag that will tell code factory to enable this command or disable it.</returns> public override async Task<bool> EnableCommandAsync(VsDocument result) { //Result that determines if the the command is enabled and visible in the context menu for execution. bool isEnabled = false; try { isEnabled = result.Name.Contains("aspx"); } catch (Exception unhandledError) { _logger.Error($"The following unhandled error occured while checking if the solution explorer project document command {commandTitle} is enabled. ", unhandledError); isEnabled = false; } return isEnabled; } /// <summary> /// Code factory framework calls this method when the command has been executed. /// </summary> /// <param name="result">The code factory model that has generated and provided to the command to process.</param> public override async Task ExecuteCommandAsync(VsDocument result) { try { //User Control var migrateDialog = await VisualStudioActions.UserInterfaceActions.CreateVsUserControlAsync<MigrateWebFormDialog>(); //Get Project List var solution = await VisualStudioActions.SolutionActions.GetSolutionAsync(); //Set properties on the dialog var projects = await solution.GetProjectsAsync(false); migrateDialog.SolutionProjects = projects; migrateDialog.FormToMigrate = result; //Show the dialog await VisualStudioActions.UserInterfaceActions.ShowDialogWindowAsync(migrateDialog); } catch (Exception unhandledError) { _logger.Error($"The following unhandled error occured while executing the solution explorer project document command {commandTitle}. ", unhandledError); } } } #endregion } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/Adapters/AspxToBlazorControlConverter.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CodeFactory.Formatting.CSharp; using CodeFactory.Markup.Adapter; using HtmlAgilityPack; namespace WebFormsToBlazorServerCommands.Migration { /// <summary> /// Converter class that knows how to translate a specifi asp: tag into a Blazor tag/component /// </summary> public class AspxToBlazorControlConverter : BaseTagAdapter { public AspxToBlazorControlConverter(IAdapterHost adapterHost) : base(adapterHost) { this.RegisterSupportTag("asp:listview"); this.RegisterSupportTag("asp:content"); this.RegisterSupportTag("asp:formview"); this.RegisterSupportTag("asp:editform"); this.RegisterSupportTag("asp:button"); this.RegisterSupportTag("asp:checkbox"); this.RegisterSupportTag("asp:hyperlink"); this.RegisterSupportTag("asp:image"); this.RegisterSupportTag("asp:imagebutton"); this.RegisterSupportTag("asp:label"); this.RegisterSupportTag("asp:linkbutton"); this.RegisterSupportTag("asp:panel"); this.RegisterSupportTag("asp:radiobutton"); this.RegisterSupportTag("asp:table"); this.RegisterSupportTag("asp:tablecell"); this.RegisterSupportTag("asp:tablerow"); this.RegisterSupportTag("asp:textbox"); this.RegisterSupportTag("asp:listbox"); this.RegisterSupportTag("asp:checkboxlist"); this.RegisterSupportTag("asp:radiobuttonlist"); this.RegisterSupportTag("asp:datalist"); this.RegisterSupportTag("asp:datagrid"); this.RegisterSupportTag("asp:dropdownlist"); this.RegisterSupportTag("asp:placeholder"); this.RegisterSupportTag("asp:requiredfieldvalidator"); this.RegisterSupportTag("asp:literal"); this.RegisterSupportTag("asp:validationsummary"); this.RegisterSupportTag("asp:modelerrormessage"); this.RegisterSupportTag("asp:comparevalidator"); this.RegisterSupportTag("asp:fileupload"); this.RegisterSupportTag("asp:regularexpressionvalidator"); this.RegisterSupportTag("asp:gridview"); this.RegisterSupportTag("asp:boundfield"); this.RegisterSupportTag("asp:detailsview"); this.RegisterSupportTag("asp:templatefield"); } /// <summary> /// Class specific override of the baseclass ControlConverterBase /// </summary> /// <param name="tagName"></param> /// <param name="tagNodeContent"></param> /// <returns></returns> public override async Task<string> ConvertTag(string tagName, string tagNodeContent) { string _result = string.Empty; switch (tagName.ToLowerInvariant()) { case "asp:content": _result = await ConvertContentControl(tagNodeContent); break; case "asp:formview": _result = await ConvertFormViewControl(tagNodeContent); break; case "asp:editform": _result = await ConvertEditFormControl(tagNodeContent); break; case "asp:listview": _result = await ConvertListViewControl(tagNodeContent); break; default: _result = await ConvertGenericControl(tagNodeContent); break; } return _result; } public override async Task<ConversionResult> ConvertTagWithResult(string tag, string content) { string _result = string.Empty; ConversionResult returnValue = null; try { switch (tag.ToLowerInvariant()) { case "asp:content": returnValue = ConversionResult.Init(true, await ConvertContentControl(content)); break; case "asp:formview": returnValue = ConversionResult.Init(true, await ConvertContentControl(content)); break; case "asp:editform": returnValue = ConversionResult.Init(true, await ConvertContentControl(content)); break; case "asp:listview": returnValue = ConversionResult.Init(true, await ConvertContentControl(content)); break; default: returnValue = ConversionResult.Init(true, await ConvertGenericControl(content)); break; } } catch (Exception ex) { returnValue = ConversionResult.Init(false, ex.Message); } return returnValue; } #region Private conversion methods /// <summary> /// This method is used to generically convert an asp control by removing the 'asp:' /// prefix from the control name and then returning the resultant content back to the caller. /// </summary> /// <param name="nodeContent"></param> /// <returns>converted control content</returns> private async Task<string> ConvertGenericControl(string nodeContent) { var model = new HtmlDocument(); model.LoadHtml(nodeContent); HtmlNode rootNode = null; try { rootNode = model.DocumentNode.FirstChild; if (rootNode.Name.Contains("asp:")) { rootNode.Name = rootNode.Name.Replace("asp:", string.Empty); } //send any child asp:* controls to be converted by the a call back out to the adapterHosting class. var allchildren = rootNode.Descendants().Where(p => p.Name.ToLower().Contains("asp:")); List<HtmlNode> targetedChildren = new List<HtmlNode>(); //filter out nested asp:* controls from the list (children are processed by the specific adapter converter method) //this way we don't end up double-calling a AdapterHost.ConvertTag on controls that have already been taken care of by their //parent asp:* control converter foreach (var control in allchildren) { var anc1 = control.Ancestors().Where(c => c.Name.Contains("asp:")); if (!anc1.Any()) { targetedChildren.Add(control); } } foreach (var nodeObj in targetedChildren) { var migratedControlText = await AdapterHost.ConvertTag(nodeObj.Name, nodeObj.OuterHtml); var tempNode = HtmlNode.CreateNode(migratedControlText); nodeObj.ParentNode.ReplaceChild(tempNode, nodeObj); } //var aspFormTags = rootNode.Descendants().Where(p => p.Name.ToLower().Contains("asp:"));//.ToList(); //foreach (var control in aspFormTags) //{ // var migratedControlText = await AdapterHost.ConvertTag(control.Name, control.OuterHtml); // var tempNode = HtmlNode.CreateNode(migratedControlText); // control.ParentNode.ReplaceChild(tempNode, control); //} return rootNode.OuterHtml; } catch (Exception ex) { throw ex; } finally { model = null; } } /// <summary> /// This method understands now to convert an asp:FormView control into a blazor equivalent. /// </summary> /// <param name="nodeContent"></param> /// <returns></returns> private async Task<string> ConvertFormViewControl(string nodeContent) { var currentModel = new HtmlDocument(); var newModel = new HtmlDocument(); currentModel.LoadHtml(nodeContent); try { var editFormNode = currentModel.DocumentNode.FirstChild;// ("//asp:listview");// model.All.Where(p => p.LocalName.ToLower().Equals("asp:formview")).FirstOrDefault(); newModel.LoadHtml($"<EditForm Model={editFormNode.GetAttributeValue("ItemType", "")} OnValidSubmit={editFormNode.GetAttributeValue("SelectMethod", "")}></EditForm>"); var newNode = newModel.DocumentNode.SelectSingleNode("//editform"); //this is now a live list having substituted the EditForm control for the old FormView one newNode.AppendChildren(editFormNode.ChildNodes); //deal with itemtemplates... ?? //send any child asp:* controls to be converted by the a call back out to the adapterHosting class. var aspFormTags = newModel.DocumentNode.FirstChild.Descendants().Where(p => p.Name.ToLower().Contains("asp:")).ToList(); foreach (var formObj in aspFormTags) { var migratedControlText = await AdapterHost.ConvertTag(formObj.Name, formObj.OuterHtml); var tempNode = HtmlNode.CreateNode(migratedControlText); formObj.ParentNode.ReplaceChild(tempNode, formObj); } return newModel.DocumentNode.OuterHtml; //var editFormNode = model.All.Where(p => p.LocalName.ToLower().Equals("asp:formview")).FirstOrDefault(); //var newNode = parser.ParseFragment($"<EditForm Model={editFormNode.GetAttribute("ItemType")} OnValidSubmit={editFormNode.GetAttribute("SelectMethod")}></EditForm>", editFormNode); ////this is now a live list having substituted the EditForm control for the old FormView one //newNode.First().AppendNodes(editFormNode.ChildNodes.ToArray()); //if (model.All.Any(p => p.TagName.ToLower().Equals("itemtemplate"))) //{ // //deal with itemtemplates... ?? //} ////send any child asp:* controls to be converted by the a call back out to the adapterHosting class. //var aspFormTags = newNode.First().Descendents<IElement>().Where(p => p.NodeName.ToLower().Contains("asp:")).ToList(); //foreach (var formObj in aspFormTags) //{ // var migratedControlText = await _adapterHost.MigrateTagControl(formObj.NodeName, formObj.OuterHtml); // var tempNode = parser.ParseFragment(migratedControlText, null); // //ParseFragment always adds on a HTML & BODY tags, at least with this call setup. We need to pull out *just* the element that we have migrated. // var appendElement = tempNode.GetElementsByTagName("BODY").First().ChildNodes; // formObj.Replace(appendElement.ToArray()); //} //return newNode.First().ToHtml();//.OuterHTML; // .ToString(); } catch (Exception ex) { throw ex; } finally { currentModel = null; newModel = null; } } /// <summary> /// This method understands now to convert an asp:FormView control into a blazor equivalent. /// </summary> /// <param name="nodeContent"></param> /// <returns></returns> private async Task<string> ConvertListViewControl(string nodeContent) { //var model = await _angleSharpContext.OpenAsync(req => req.Content(nodeContent)); var currentModel = new HtmlDocument(); var newModel = new HtmlDocument(); currentModel.LoadHtml(nodeContent); try { var listViewNode = currentModel.DocumentNode.FirstChild;// ("//asp:listview");// model.All.Where(p => p.LocalName.ToLower().Equals("asp:formview")).FirstOrDefault(); newModel.LoadHtml($"<ListView Model={listViewNode.GetAttributeValue("ItemType", "")} OnValidSubmit={listViewNode.GetAttributeValue("SelectMethod", "")}></ListView>"); var newNode = newModel.DocumentNode.SelectSingleNode("//listview"); //this is now a live list having substituted the EditForm control for the old FormView one newNode.AppendChildren(listViewNode.ChildNodes); //send any child asp:* controls to be converted by the a call back out to the adapterHosting class. var aspFormTags = newModel.DocumentNode.FirstChild.Descendants().Where(p => p.Name.ToLower().Contains("asp:")).ToList(); foreach (var formObj in aspFormTags) { var migratedControlText = await AdapterHost.ConvertTag(formObj.Name, formObj.OuterHtml); var tempNode = HtmlNode.CreateNode(migratedControlText); formObj.ParentNode.ReplaceChild(tempNode, formObj); } return newModel.DocumentNode.OuterHtml; } catch (Exception ex) { throw ex; } finally { currentModel = null; newModel = null; } } /// <summary> /// This method understands how to convert an asp:EditForm control into a blazor equivalent. /// </summary> /// <param name="nodeContent"></param> /// <returns></returns> private async Task<string> ConvertEditFormControl(string nodeContent) { string _result = string.Empty; try { //return content as-is for now. return nodeContent; } catch (Exception ex) { throw ex; } } /// <summary> /// This method is used to convert the asp:Content control to a Blazor equivalent. In this particular /// case - there is no equivalent. This control is the top-level asp:* container for a page and really just holds all other /// controls that are found in an *.aspx page definition. /// </summary> /// <param name="nodeContent"></param> /// <returns></returns> private async Task<string> ConvertContentControl(string nodeContent) { string _result = string.Empty; var model = new HtmlDocument(); var innerModel = new HtmlDocument(); HtmlNode returnNode; try { model.LoadHtml(nodeContent); var contentControlObj = model.DocumentNode.FirstChild; returnNode = contentControlObj.CloneNode(false); innerModel.LoadHtml(contentControlObj.InnerHtml); //<-- this is where we actually remove the asp:content control from the model //send any child asp:* controls to be converted by the a call back out to the adapterHosting class. var allchildren = innerModel.DocumentNode.Descendants().Where(p => p.Name.ToLower().Contains("asp:")); List<HtmlNode> targetedChildren = new List<HtmlNode>(); //filter out nested asp:* controls from the list (children are processed by the specific adapter converter method) //this way we don't end up double-calling a AdapterHost.ConvertTag on controls that have already been taken care of by their //parent asp:* control converter foreach (var control in allchildren) { var anc1 = control.Ancestors().Where(c => c.Name.Contains("asp:")); if (!anc1.Any()) { targetedChildren.Add(control); } } foreach (var nodeObj in targetedChildren) { var migratedControlText = await AdapterHost.ConvertTag(nodeObj.Name, nodeObj.OuterHtml); var tempNode = HtmlNode.CreateNode(migratedControlText); nodeObj.ParentNode.ReplaceChild(tempNode, nodeObj); } return innerModel.DocumentNode.OuterHtml; } catch (Exception ex) { throw ex; } finally { model = null; } } #endregion } } <file_sep>/guidance/SetupBlazorProjectCommand.md # SetupBlazorProject.cs Project Command file ## Overview This file, logically, is a CodeFactory [Project Command](http://docs.codefactory.software/guidance/overview-commands-intro.html) and contains all of the logic neccesary for the CodeFactory runtime to call and execute from Visual Studio. There is a single class defined called `public class MigrateWebForm : ProjectDocumentCommandBase` ## Fields The following fields are defined within this class: Declaration | Notes ----------- | ----------- `private static readonly string commandTitle` | Used to set the title that shows up in the context-menu for the Visual Studio Solution Explorer. `private static readonly string commandDescription` | Sets a longer descriptive text for the command that shows up in several of the loaded-command windows and diagnostics screens. ## Constrcutor There is a single default constructor that is defined. This constructor should have no logic in it and is responsible for passing back its parameters to its baseclass. `public SetupBlazorProject(ILogger logger, IVsActions vsActions) : base(logger, vsActions, commandTitle, commandDescription)` ## Methods These are the following methods which are defined within this class file: Declaration | Notes --------- | -------- `public override async Task<bool> EnableCommandAsync(VsProject result)` | Validation logic that will determine if this command should be enabled for execution. `public override async Task ExecuteCommandAsync(VsProject result)` | Code factory framework calls this method when the command has been executed.<file_sep>/src/WebFormsToBlazorServerCommands/Migration/WebFormToBlazorServerMigration.Logic.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using CodeFactory.VisualStudio; namespace WebFormsToBlazorServerCommands.Migration { public partial class WebFormToBlazorServerMigration { /// <summary> /// Migrates logic class files over to the blazor server project. /// </summary> /// <param name="webFormProjectData">List of pre cached models for from the web form project.</param> /// <param name="webFormProject">The web forms project that we are migrating data from.</param> /// <param name="blazorServerProject">The blazor server project this is being migrated to.</param> public async Task MigrateLogic(IReadOnlyList<VsModel> webFormProjectData, VsProject webFormProject, VsProject blazorServerProject) { try { //Informing the dialog the migration step has started. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AppLogic, MigrationStatusEnum.Running); var childFiles = webFormProjectData.GetSourceCodeDocumentsAsync(true); //we don't want any known aspx/ascx files hitching a ride. just plain vanilla *.cs files should qualify. var logicFiles = childFiles.Where(p => (!p.Name.ToLower().Contains("aspx.") && !p.Name.ToLower().Contains("ascx.") && !p.Name.ToLower().Contains("asax."))).ToList(); //put logic files (using the file system into the target under the project root) foreach (VsCSharpSource sourceDocument in logicFiles) { //look for specific files that are native to a WebForm app and skip them. ** TODO: move this to a config setting maybe? if (sourceDocument.Name.ToLower().Contains("bundleconfig")) continue; if (sourceDocument.Name.ToLower().Contains("assemblyinfo")) continue; if (sourceDocument.Name.ToLower().Contains("startup")) continue; if (sourceDocument.Name.ToLower().Contains(".master")) continue; var logicDocument = await sourceDocument.LoadDocumentModelAsync(); var parentFolders = await logicDocument.GetParentFolders(); var source = sourceDocument.SourceCode; var docText = await logicDocument.GetDocumentContentAsStringAsync(); if (parentFolders.Count >= 1) { parentFolders.Reverse(); //The folders are returned in leaf-to-trunk so need to reverse the order for the next step. VsProjectFolder createdFolder = null; //deal with source folder hierarchy for (int i = 0; i < parentFolders.Count; i++) { if (i > 0) { createdFolder = await createdFolder.CheckAddFolder(parentFolders[i].Name); } else createdFolder = await blazorServerProject.CheckAddFolder(parentFolders[i].Name); } //copy the file. We only really care about the most leaf/edge subfolder so its safe to use the creatdFolder variable here. docText = docText.Replace(source.Classes.First().Namespace, $"{blazorServerProject.Name}.{createdFolder.Name}"); var targetFolderFiles = await createdFolder.GetChildrenAsync(false); if (!targetFolderFiles.Any(c => c.Name.ToLower().Equals(logicDocument.Name.ToLower()) ) ) { await createdFolder.AddDocumentAsync(logicDocument.Name, docText); //Updating the dialog with a status await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AppLogic, MessageTypeEnum.Information, $"Copied logic file: {logicDocument.Name} to project {blazorServerProject.Name} location: {Path.Combine(createdFolder.Path, logicDocument.Name)}"); } else { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AppLogic, MessageTypeEnum.Warning, $"Logic file: {logicDocument.Name} already exists in target folder location: {Path.Combine(createdFolder.Path, logicDocument.Name)} and was skipped."); } } else { var projFiles = await blazorServerProject.GetChildrenAsync(false); if (!projFiles.Any(c => c.Name.ToLower().Equals(logicDocument.Name.ToLower()) ) ) { docText = docText.Replace(source.Classes.First().Namespace, $"{blazorServerProject.Name}"); var thing = await blazorServerProject.AddDocumentAsync(logicDocument.Name, docText); //Updating the dialog with a status await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AppLogic, MessageTypeEnum.Information, $"Copied static file: {logicDocument.Name} to project {blazorServerProject.Name} location: {Path.Combine(blazorServerProject.Path, logicDocument.Name)}"); } else { //Updating the dialog with a status await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AppLogic, MessageTypeEnum.Warning, $"Static file: {logicDocument.Name} already exists in project {blazorServerProject.Name} location: {Path.Combine(blazorServerProject.Path, logicDocument.Name)} and was skipped."); } } } //Completed the migration step informing the dialog. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AppLogic, MigrationStatusEnum.Passed); } catch (Exception unhandledError) { //Dumping the exception that occured directly into the status so the user can see what happened. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AppLogic, MessageTypeEnum.Error, $"The following unhandled error occured. '{unhandledError.Message}'"); //Updating the status that the step failed await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AppLogic, MigrationStatusEnum.Failed); } } } } <file_sep>/src/Guidance.md # WebFormsToBlazorServer Guidance This guidance document provides an overview for how to understand the implementation of this command library. To be updated<file_sep>/src/WebFormsToBlazorServerCommands/Migration/MigrationStepEnum.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebFormsToBlazorServerCommands.Migration { public enum MigrationStepEnum { Startup = 0, HttpModules = 1, StaticFiles = 2, Bundling = 3, AspxPages = 4, Config = 5, AppLogic =6, MigrationProcess = 7 } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/WebFormToBlazorServerMigration.Bundling.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CodeFactory.VisualStudio; namespace WebFormsToBlazorServerCommands.Migration { public partial class WebFormToBlazorServerMigration { /// <summary> /// Clones the bundleconfig.json into the blazer server project. /// </summary> /// <param name="webFormProjectData">Pre cached project data about the web forms project.</param> /// <param name="webFormProject">The web forms project that we are migrating data from.</param> /// <param name="blazorServerProject">The blazor server project this is being migrated to.</param> public async Task MigrateBundling(IReadOnlyList<VsModel> webFormProjectData, VsProject webFormProject, VsProject blazorServerProject) { try { //Letting the dialog know the migration step has started. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Bundling, MigrationStatusEnum.Running); //Finding the bundlconfig.json file. if (webFormProjectData.FirstOrDefault(p => p.Name.ToLower().Equals("bundleconfig.json")) is VsDocument bundleConfig) { //Found the config file. loading its content. var bundleText = await bundleConfig.GetDocumentContentAsStringAsync(); //Creating the bundleconfig.json in the blazor server project, and injecting the content. var thing = await blazorServerProject.AddDocumentAsync("bundleconfig.json", bundleText); //Sending a status to the dialog await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Bundling, MessageTypeEnum.Information, $"The bundleconfig.json file has been copied to the root directory of {blazorServerProject.Name}."); } else { //No bundle configuration was found. No additional actions need to be taken. //Sending a status to the dialog await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Bundling, MessageTypeEnum.Information, $"There was no 'bundleconfig.json' file found in the root of the source project {webFormProject.Name}. No files were copied."); } //Completed the migration step informing the dialog. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Bundling, MigrationStatusEnum.Passed); } catch (Exception unhandledError) { //Dumping the exception that occured directly into the status so the user can see what happened. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Bundling, MessageTypeEnum.Error, $"The following unhandled error occured. '{unhandledError.Message}'"); //Updating the status that the step failed await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Bundling, MigrationStatusEnum.Failed); } } } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/MigrationSteps.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebFormsToBlazorServerCommands.Migration { /// <summary> /// Data class that holds which migration steps will be executed. /// </summary> public class MigrationSteps { #region Backing fields for properties private readonly bool _startup; private readonly bool _httpModules; private readonly bool _staticFiles; private readonly bool _bundling; private readonly bool _aspxPages; private readonly bool _config; private readonly bool _appLogic; #endregion /// <summary> /// Creates an instance of the <see cref="MigrationSteps"/> data class. /// </summary> /// <param name="startup">Flag to determine the migration of the startup data.</param> /// <param name="httpModules">Flag to determine the migration of the http modules.</param> /// <param name="staticFiles">Flag to determine the migration of static file content.</param> /// <param name="bundling">Flag to determine the migration of bundling data.</param> /// <param name="aspxPages">Flag to determine the migration of aspx pages.</param> /// <param name="config">Flag to determine the migration of the app configuration.</param> /// <param name="appLogic">Flag to determine the migration of existing application logic.</param> public MigrationSteps(bool startup, bool httpModules, bool staticFiles, bool bundling, bool aspxPages, bool config, bool appLogic) { _startup = startup; _httpModules = httpModules; _staticFiles = staticFiles; _bundling = bundling; _aspxPages = aspxPages; _config = config; _appLogic = appLogic; } /// <summary> /// Flag that determines if the startup data should be migrated. /// </summary> public bool Startup => _startup; /// <summary> /// Flag that determines if the Http modules should be migrated. /// </summary> public bool HttpModules => _httpModules; /// <summary> /// Flag that determines if static content should be migrated. /// </summary> public bool StaticFiles => _staticFiles; /// <summary> /// Flag that determines if the bundling should be migrated. /// </summary> public bool Bundling => _bundling; /// <summary> /// Flag that determines if the aspx pages should be migrated. /// </summary> public bool AspxPages => _aspxPages; /// <summary> /// Flag that determines if the configuration should be migrated. /// </summary> public bool Configuration => _config; /// <summary> /// Flag that determines if the application logic should be migrated. /// </summary> public bool AppLogic => _appLogic; } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/WebFormToBlazorServerMigration.HttpModules.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using CodeFactory.DotNet.CSharp; using CodeFactory.VisualStudio; using WebFormsToBlazorServerCommands.Templates; namespace WebFormsToBlazorServerCommands.Migration { public partial class WebFormToBlazorServerMigration { /// <summary> /// Migrates the definition of existing Http Modules that were used in the web forms project into the blazor project. /// </summary> /// <param name="webFormProjectData">Pre cached project data about the web forms project.</param> /// <param name="webFormProject">The web forms project that we are migrating data from.</param> /// <param name="blazorServerProject">The blazor server project this is being migrated to.</param> public async Task MigrateHttpModulesAsync(IReadOnlyList<VsModel> webFormProjectData, VsProject webFormProject, VsProject blazorServerProject) { try { //Letting the dialog know the http modules migration has started. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.HttpModules, MigrationStatusEnum.Running); //find class(es) that inherit HttpApplication var handlerClasses = webFormProjectData.GetClassesThatImplementInterface("IHttpHandler"); var moduleClasses = webFormProjectData.GetClassesThatImplementInterface("IHttpModule"); if (!handlerClasses.Any() && !moduleClasses.Any()) { //No handler classes or modules were found updating the status and exiting this step. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Startup, MessageTypeEnum.Error, $"No classes were found in {webFormProject.Name} that inherit from either 'IHttpHandler' or 'IHttpModule'"); //Setting the status to passed wasn't a failure and the solution will not require these to be added. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.HttpModules, MigrationStatusEnum.Passed); return; } //Making sure a modules folder exists, if it does not create it in the blazor server project. var modulesFolder = await blazorServerProject.CheckAddFolder("Modules"); //Creating a dictionary that holds the target namespace for modules. var conversionData = new Dictionary<string, string> { {"Namespace", $"{blazorServerProject.DefaultNamespace}.Modules"} }; CsModelStore store = null; //Create a class file in the Modules folder from a T4 Template for each handler class foreach (CsSource source in handlerClasses) { //Setting up the model data to pass off to a T4 Factory store = new CsModelStore(); store.SetModel(source); //Calling the T4 factory and getting back the formatted file content. var fileContent = ModuleFactory.GenerateSource(store, conversionData); //Calling CodeFactory project system API to add a new document to the project folder, also injecting the new file content into the file. await modulesFolder.AddDocumentAsync($"{Path.GetFileNameWithoutExtension(source.SourceDocument)}Handler.cs", fileContent); //Clearing model store for the next call store = null; } //Create a class file in the Modules folder from a T4 Template for each model class foreach (CsSource source in moduleClasses) { store = new CsModelStore(); store.SetModel(source); await _visualStudioActions.ProjectFolderActions.AddDocumentAsync(modulesFolder, $"{Path.GetFileNameWithoutExtension(source.SourceDocument)}Handler.cs", ModuleFactory.GenerateSource(store, conversionData)); store = null; } //Completed process the modules informing the dialog it has passed. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.HttpModules, MigrationStatusEnum.Passed); } catch (Exception unhandledError) { //Dumping the exception that occured directly into the status so the user can see what happened. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.HttpModules, MessageTypeEnum.Error, $"The following unhandled error occured. '{unhandledError.Message}'"); //Updating the status that the step failed await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.HttpModules, MigrationStatusEnum.Failed); } } } } <file_sep>/src/WebFormsToBlazorServerCommands/Dialogs/MigrationStepStatus.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebFormsToBlazorServerCommands.Dialogs { /// <summary> /// Data class that holds current status information about a migration step. /// </summary> public class MigrationStepStatus { /// <summary> /// Type of status messaging being communicated. /// </summary> public string MessageType { get; set; } /// <summary> /// Which migration step does the message belong to. /// </summary> public string MigrationStep { get; set; } /// <summary> /// The status message to be displayed. /// </summary> public string Status { get; set; } } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/MigrationStatusEnum.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WebFormsToBlazorServerCommands.Migration { /// <summary> /// Enumeration used to determine the status of a migration step. /// </summary> public enum MigrationStatusEnum { /// <summary> /// The current migration step is running. /// </summary> Running = 0, /// <summary> /// The current migration step has passed. /// </summary> Passed = 1, /// <summary> /// The current migration step has failed. /// </summary> Failed = 2 } } <file_sep>/src/WebFormsToBlazorServerCommands/Migration/WebFormToBlazorServerMigration.Startup.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CodeFactory.DotNet.CSharp; using CodeFactory.VisualStudio; namespace WebFormsToBlazorServerCommands.Migration { public partial class WebFormToBlazorServerMigration { /// <summary> /// This step is used to locate any code artifacts within the Web Forms application that inherit from HttpApplication in order to alter /// any of the default behavior of IIS. Any code found will be copied and moved into the end of the blazor target projects Startup.cs file definition. /// </summary> /// <param name="webFormProjectData">Pre cached project data about the web forms project.</param> /// <param name="webFormProject">The web forms project that we are migrating data from.</param> /// <param name="blazorServerProject">The blazor server project this is being migrated to.</param> private async Task MigrateStartupAsync(IReadOnlyList<VsModel> webFormProjectData, VsProject webFormProject, VsProject blazorServerProject) { try { //Informing the dialog the migration step has started. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Startup, MigrationStatusEnum.Running); //Find class(es) that inherit HttpApplication var startupClasses = webFormProjectData.GetClassesThatInheritBase("HttpApplication"); if (!startupClasses.Any()) { //No startup classes were found updating the hosting dialog to inform the user there was nothing to convert in the startup process. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Startup, MessageTypeEnum.Information, $"No classes were found in {webFormProject.Name} that inherit from 'HttpApplication'"); await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Startup, MigrationStatusEnum.Passed); return; } var blazorStartupClass = await blazorServerProject.FindClassAsync("Startup", false); if (blazorStartupClass == null) { //No startup class was found in the blazor server project. Cannot update the startup class. Informing the user and failing the step await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Startup, MessageTypeEnum.Warning, $"The target project {blazorServerProject.Name} does not have definition for a Startup class ('public class Startup')."); await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Startup, MigrationStatusEnum.Failed); return; } //Get the methods //Copy them into the blazorStartupClass commented out. foreach (var source in startupClasses) { //loading the class data var sourceClass = source.Classes.FirstOrDefault(); //If no class was found continue the process. if (sourceClass == null) continue; //double loop - I do not like this and it needs to be refactored. foreach (var method in sourceClass.Methods) { await blazorStartupClass.AddToEndAsync(blazorStartupClass.SourceFiles.First(), $"\r\n/*{method.FormatCSharpDeclarationSyntax()}\r\n{{ { await method.GetBodySyntaxAsync()} \r\n}}*/"); await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Startup, MessageTypeEnum.Information, $"Class: {sourceClass.Name} Method: {method.Name} has been copied into the Startup.cs class commented out. Please refactor manually."); } } //All items process updating the status of the step has passed. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Startup, MigrationStatusEnum.Passed); } catch (Exception unhandledError) { //Dumping the exception that occured directly into the status so the user can see what happened. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Startup, MessageTypeEnum.Error, $"The following unhandled error occured. '{unhandledError.Message}'"); //Updating the status that the step failed await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.Startup, MigrationStatusEnum.Failed); } } } } <file_sep>/guidance/SetupBlazorDialogFile.md # SetupBlazorDialg.xaml/.xaml.cs Files ## Overview ## Fields ## Constrcutor ## Methods<file_sep>/src/WebFormsToBlazorServerCommands/Migration/IControlConverter.cs using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; namespace WebFormsToBlazorServerCommands.Migration { /// <summary> /// Base Contract that all converter Types must implement in order to be called by the main ConverterAdapter Class /// </summary> public interface IControlConverter { /// <summary> /// List of controls/tags that the implementing Converter class knows how to handle /// </summary> ReadOnlyCollection<string> AvailableConversionTags { get; } /// <summary> /// Method to implement which will be called by the ConverterAdapter class /// </summary> /// <param name="tagName"></param> /// <param name="tagNodeContent"></param> Task<string> ConvertControlTag(string tagName, string tagNodeContent); } } <file_sep>/guidance/WebFormToBlazorServerMigrationStartupFile.md # WebFormToBlazorServerMigration.Startup.cs File ## Overview ## Fields ## Constrcutor ## Methods<file_sep>/src/WebFormsToBlazorServerCommands/Dialogs/DialogExtensions.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using WebFormsToBlazorServerCommands.Migration; namespace WebFormsToBlazorServerCommands.Dialogs { /// <summary> /// Extensions class that manages data to be used in the dialog. /// </summary> public static class DialogExtensions { /// <summary> /// Check a nullable bool for a value, will return false if the bool is null. /// </summary> /// <param name="source">Nullable bool to check</param> /// <returns>standard boolean result.</returns> public static bool GetResult(this bool? source) { return source.HasValue ? source.Value : false; } /// <summary> /// Extension method used to help format labels that track migration status. Must be executed on the UI Thread. /// </summary> /// <param name="source">Label to be updated</param> /// <param name="status">Status type used for formatting.</param> public static void UpdateMigrationStatus(this TextBlock source, MigrationStatusEnum status) { switch (status) { case MigrationStatusEnum.Running: source.FontWeight = FontWeights.Bold; break; case MigrationStatusEnum.Passed: source.FontWeight = FontWeights.ExtraBold; source.Foreground = Brushes.Green; break; case MigrationStatusEnum.Failed: source.FontWeight = FontWeights.ExtraBold; source.Foreground = Brushes.Red; break; default: break; } } /// <summary> /// Gets a title assigned to each migration step. /// </summary> /// <param name="source">The migration step to be loaded.</param> /// <returns>The title.</returns> public static string GetName(this MigrationStepEnum source) { string name = null; switch (source) { case MigrationStepEnum.Startup: name = "Startup"; break; case MigrationStepEnum.HttpModules: name = "Http Modules"; break; case MigrationStepEnum.StaticFiles: name = "Static Files"; break; case MigrationStepEnum.Bundling: name = "Bundling"; break; case MigrationStepEnum.AspxPages: name = "Aspx Pages"; break; case MigrationStepEnum.Config: name = "Configuration"; break; case MigrationStepEnum.AppLogic: name = "App Logic"; break; case MigrationStepEnum.MigrationProcess: name = "Migration Process"; break; } return name; } /// <summary> /// Gets a friendly string name for each message type. /// </summary> /// <param name="source">Message type to process.</param> /// <returns>The friendly name.</returns> public static string GetName(this MessageTypeEnum source) { string name = null; switch (source) { case MessageTypeEnum.Information: name = "Information"; break; case MessageTypeEnum.Warning: name = "Warning"; break; case MessageTypeEnum.Error: name = "Error"; break; } return name; } } } <file_sep>/guidance/LogicCodeFactoryFile.md # LogicCodeFactory.tt/.cs/.transform.cs Files ## Overview ## Fields ## Constrcutor ## Methods<file_sep>/guidance/MigrateWebFormDialogFile.md # MigrateWebForm.xaml/.xaml.xs Files ## Overview This is a wpf/xaml custom user control definition that is used to display both migration status and gather input from the developer user. ## Fields ## Constrcutor ## Methods
f84378b84b491e220f49badb5b7e6f0623f3ffd2
[ "Markdown", "C#" ]
32
C#
HyperLLC/WebForms2BlazorServer
bb560dec68cb55998ff03c9c2573dc5cac61e4f1
0bfc4e89b8f0781bb6b072f16549db90b4324158
refs/heads/master
<file_sep>package Cinema; import java.util.Scanner; public class Cinema { final static Scanner sc = new Scanner(System.in); static int totalRows = 0, totalSeats = 0; static int aRow = 0, aSeat = 0; static int countTen = 0, countEight = 0; public static void main(String[] args) { try { System.out.println("Enter the number of rows:"); totalRows = sc.nextInt(); System.out.println("Enter the number of seats in each row:"); totalSeats = sc.nextInt(); String[][] arr = new String[totalRows][totalSeats]; for (int i = 0; i < totalRows; i++) { for (int j = 0; j < totalSeats; j++) { arr[i][j] = " S"; } } askInputes(arr); } catch (NumberFormatException e) { System.out.println("Wrong input!"); } } public static void askInputes(String[][] arr) { System.out.println("\n1. Show the seats\n" + "2. Buy a ticket\n" + "3. Statistics\n" + "0. Exit"); int input = sc.nextInt(); if (input >= 0) { switch(input) { case 1: printCinema(arr); break; case 2: takeBooks(arr); break; case 3: statistics(arr); break; case 0: break; default : System.out.println("Wrong input!"); askInputes(arr); break; } } else { System.out.println("Wrong input!"); askInputes(arr); } } public static void statistics(String[][] arr) { System.out.println("Number of purchased tickets: " + getBookedTickets()); System.out.println("Percentage: " + String.format("%.2f", getPercentage(arr)) + "%"); System.out.println("Current income: $" + currentIncome()); System.out.println("Total income: $" + TotalIncome()); askInputes(arr); } public static void takeBooks(String[][] arr) { try { System.out.println("\nEnter a row number:"); aRow = sc.nextInt(); System.out.println("Enter a seat number in that row:"); aSeat = sc.nextInt(); if (checkBook(arr)) { takeBooks(arr); } else { arr[aRow - 1][aSeat - 1] = " B"; } if(totalRows * totalSeats <= 60) { System.out.println("\nTicket price: $10"); countTen++; } else { if (aRow <= totalRows / 2) { System.out.println("\nTicket price: $10"); countTen++; } else { System.out.println("\nTicket price: $8"); countEight++; } } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Wrong input!"); } askInputes(arr); } public static void printCinema(String[][] arr) { System.out.println("Cinema:"); System.out.print(" "); for (int i = 1; i <= totalSeats; i++) { System.out.print(" " + i); } System.out.println(); for (int i = 0; i < totalRows; i++) { System.out.print(i + 1); for (int j = 0; j < totalSeats; j++) { System.out.print(arr[i][j]); } System.out.println(); } askInputes(arr); } public static int getBookedTickets() { return countTen + countEight; } public static double getPercentage(String[][] arr) { double booked = (double)getBookedTickets(); double percent = (double)(booked / (totalRows * totalSeats)) * 100; return percent; } public static int currentIncome() { return countTen * 10 + countEight * 8; } public static int TotalIncome() { if (totalRows * totalSeats <= 60) { return totalRows * totalSeats * 10; } else { int half = totalRows / 2; int backHalf = totalRows - half; return half * totalSeats * 10 + backHalf * totalSeats * 8; } } public static boolean checkBook(String[][] arr) { boolean isBooked = false; for (int i = 0; i < totalRows; i++) { for (int j = 0; j < totalSeats; j++) { if (arr[aRow - 1][aSeat - 1].equals(" B")) { System.out.println("That ticket has already been purchased!"); isBooked = true; break; } } if (isBooked) { return isBooked; } } return isBooked; } } <file_sep>#Simple--Cinema-room
072db7a57460a6d548bf2b8b7447d665ed9e8f33
[ "Markdown", "Java" ]
2
Java
Tejaswini-tikariha/Simple--Cinema-room
b11469340efaa543b31fa5af2770062e4e70725b
a42e7b13e7d4b989af0423bf00f4d16cf685720f
refs/heads/master
<repo_name>ZHAOTING/WebDataMining_Kaggle<file_sep>/py/history/linear_ridge_regression.py # 11.27 ver 1 # seems better import os import csv import nltk import numpy as np from sklearn.feature_extraction.text import * from sklearn.feature_selection import SelectKBest, SelectPercentile, chi2, f_classif from sklearn.linear_model import * from sklearn.naive_bayes import * from sklearn import svm from scipy.sparse import * from scipy.io import * from nltk.tokenize import * from nltk.stem.snowball import * from stemming.porter2 import stem def cleaned_text(text): text = nltk.word_tokenize(text) text = " ".join([stem(x.lower()) for x in text]) return text CORPUS_SIZE_ITEMS = ['entire', 'small'] CORPUS_SIZE = 0 # 0 for entire, 1 for small PREDICT_ATTRIBUTE_NUM = 24 VECTORIZER = 1 # 0 for CountVectorizer, 1 for TfidfVectorizer K_FOR_BEST = 2000 SELECT_PERCENTILE = 10 SELECTOR = 1 # 0 for K-select, 1 for precentile-select cur_dir = os.getcwd() if (CORPUS_SIZE == 1): test_csv = file(cur_dir + "/../data/small_test.csv") train_csv = file(cur_dir + "/../data/small_train.csv") else: test_csv = file(cur_dir + "/../data/test.csv") train_csv = file(cur_dir + "/../data/train.csv") ################################# # Get Corpus From CSV # ################################# train_corpus = [] test_corpus = [] # get train_tweets from csv to train_corpus[] cnt = 0 train_reader = csv.reader(train_csv) for tweet in train_reader: text = unicode(tweet[1] + " " + tweet[2] + " " + tweet[3], 'ascii', 'ignore') # text = cleaned_text(text) train_corpus.append(text) # print "train tweet", cnt, "to corpus[]" cnt += 1 # delete header del train_corpus[0] train_csv.close() # get test_tweets from csv to test_corpus[] cnt = 0 test_reader = csv.reader(test_csv) for tweet in test_reader: text = unicode(tweet[1] + " " + tweet[2] + " " + tweet[3], 'ascii', 'ignore') # text = cleaned_text(text) test_corpus.append(text) # print "test tweet", cnt, "to corpus[]" cnt += 1 # delete header del test_corpus[0] test_csv.close() ################################# # Feature Exraction # ################################# # get x_train, x_test from train_corpus, test_corpus print "start extraction" entire_corpus = train_corpus + test_corpus if (VECTORIZER == 0): vectorizer = CountVectorizer(min_df = 1, tokenizer = nltk.word_tokenize) elif (VECTORIZER == 1): vectorizer = TfidfVectorizer(min_df = 1, tokenizer = nltk.word_tokenize) # vectorizer = TfidfVectorizer(ngram_range=(1, 5), analyzer="word", binary=False, min_df=3) vectorizer.fit(train_corpus) x_train = vectorizer.transform(train_corpus) x_test = vectorizer.transform(test_corpus) print "finish extraction" ################################# # Feature Selection # ################################# # # get feature names attribute_names = ["ATTR:I can not tell attitude" ,"ATTR:Negative" ,"ATTR:Neutral / author is just sharing information" ,"ATTR:Positive" ,"ATTR:Tweet not related to weather condition" ,"ATTR:current (same day) weather" ,"ATTR:future (forecast)" ,"ATTR:I can not tell time" ,"ATTR:past weather" ,"ATTR:clouds" ,"ATTR:cold" ,"ATTR:dry" ,"ATTR:hot" ,"ATTR:humid" ,"ATTR:hurricane" ,"ATTR:I can not tell weather" ,"ATTR:ice" ,"ATTR:other" ,"ATTR:rain" ,"ATTR:snow" ,"ATTR:storms" ,"ATTR:sun" ,"ATTR:tornado" ,"ATTR:wind" ] for CURRENT_ATTRIBUTE in xrange(0, PREDICT_ATTRIBUTE_NUM): if (CORPUS_SIZE == 1): train_csv = file(cur_dir + "/../data/small_train.csv") else: train_csv = file(cur_dir + "/../data/train.csv") print "CURRENT_ATTRIBUTE :", attribute_names[CURRENT_ATTRIBUTE] # get CURRENT ATTRIBUTE train_attrs from csv train_attrs = [] train_reader = csv.reader(train_csv) cnt = 0 for tweet in train_reader: attr = tweet[CURRENT_ATTRIBUTE + 4] train_attrs.append(attr) cnt += 1 del train_attrs[0] # get y_train from train_attrs y_train = [[float(attr)] for attr in train_attrs] # chi-2 select features print "start feature selection" if (SELECTOR == 0): selector = SelectKBest(chi2, k = K_FOR_BEST) else: selector = SelectPercentile(score_func=chi2, percentile=SELECT_PERCENTILE) selector.fit(x_train, y_train) new_x_train = selector.transform(x_train) new_x_test = selector.transform(x_test) print "feature selection done" # convert y_train to svm-fit shape y_train = [attr[0] for attr in y_train] # linear regression print "start regression" clf = Ridge(alpha = .5) clf = clf.fit(new_x_train, y_train) result = clf.predict(new_x_test) print "regression done" for item in result: if (item > 0): print item # # build csv file # result_path = cur_dir + "/../data/result/res_" + str(CURRENT_ATTRIBUTE) + ".csv" # if os.path.exists(result_path): # os.remove(result_path) # result_csv = file(result_path, 'a') # result_writer = csv.writer(result_csv) # # output result to csv file # print "start writing result" # for item in result: # result_writer.writerow([item]) # print "writing result done" # result_csv.close() <file_sep>/py/history/libsvm/collect_for_libsvm.py import os import re import pandas import threading from sklearn.feature_extraction.text import * ######################## ## SETTINGS ## ######################## CORPUS_SIZE = 0 # 0 for entire, 1 for small FEATURE_NUM = 10000 ################################# # get content from CSV # ################################# print "get content from csv" cur_dir = os.getcwd() if (CORPUS_SIZE == 1): test_path = cur_dir + "/../data/small_test.csv" train_path = cur_dir + "/../data/small_train.csv" else: test_path = cur_dir + "/../data/test.csv" train_path= cur_dir + "/../data/train.csv" train_content = pandas.read_csv(train_path) test_content = pandas.read_csv(test_path) train_len = len(train_content) test_len = len(test_content) for i in xrange(0, train_len): train_content['tweet'][i] = re.sub("http\S*|@\S*|{link}|RT\s*@\S*", "",train_content['tweet'][i]) if (isinstance(train_content['state'][i], basestring) == False): train_content['state'][i] = "" if (isinstance(train_content['location'][i], basestring) == False): train_content['location'][i] = "" for i in xrange(0, test_len): test_content['tweet'][i] = re.sub("http\S*|@\S*|{link}|RT\s*@\S*", "",test_content['tweet'][i]) if (isinstance(test_content['state'][i], basestring) == False): test_content['state'][i] = "" if (isinstance(test_content['location'][i], basestring) == False): test_content['location'][i] = "" train_tweets = train_content['tweet'] train_location = train_content['state'] + " " + train_content['location'] train_attributes = train_content.ix[:,4:28] test_tweets = test_content['tweet'] test_location = test_content['state'] + " " + test_content['location'] ################################# # Feature Exraction # ################################# print "feature extraction" vectorizer = TfidfVectorizer(ngram_range=(1, 2), max_features=FEATURE_NUM, strip_accents='unicode', analyzer='word') vectorizer.fit(train_tweets) x_train = vectorizer.transform(train_tweets) x_test = vectorizer.transform(test_tweets) ################################# # Convert # ################################# train_feature_pair_res = [] for VECTOR_INDEX in xrange(0, train_len): print VECTOR_INDEX train_feature_pair_res.append([]) vector = x_train[VECTOR_INDEX].toarray()[0] for FEATURE_INDEX in xrange(0, FEATURE_NUM): if (vector[FEATURE_INDEX] != 0): train_feature_pair_res[VECTOR_INDEX].append((str(FEATURE_INDEX + 1), str("%0.4f"%vector[FEATURE_INDEX]))) # for ATTRIBUTE_NUM in xrange(0, 24): def write_attr_file(ATTRIBUTE_NUM): train_attr_res = [] for VECTOR_INDEX in xrange(0, train_len): train_attr_res.append(train_attributes.ix[VECTOR_INDEX][ATTRIBUTE_NUM]) dst_path = cur_dir + "/../libsvm-3.17/data/train_attr_" + str(ATTRIBUTE_NUM) if os.path.exists(dst_path): os.remove(dst_path) dst_file = file(dst_path, "a") for VECTOR_INDEX in xrange(0, train_len): dst_file.write(str(train_attr_res[VECTOR_INDEX])) for item in train_feature_pair_res[VECTOR_INDEX]: dst_file.write("".join([" ", item[0], ":", item[1]])) dst_file.write("\n") dst_file.close() threads = [] for ATTRIBUTE_NUM in xrange(0, 24): threads.append(threading.Thread(target=write_attr_file, args=(ATTRIBUTE_NUM,))) for ATTRIBUTE_NUM in xrange(0, 24): threads[ATTRIBUTE_NUM].start() for ATTRIBUTE_NUM in xrange(0, 24): threads[ATTRIBUTE_NUM].join() test_res = [] for VECTOR_INDEX in xrange(0, test_len): test_res.append([0]) vector = x_test[VECTOR_INDEX].toarray()[0] for FEATURE_INDEX in xrange(0, FEATURE_NUM): test_res[VECTOR_INDEX].append(vector[FEATURE_INDEX]) dst_path = cur_dir + "/../libsvm-3.17/data/test_attr_" + str(0) if os.path.exists(dst_path): os.remove(dst_path) dst_file = file(dst_path, "a") for vector in test_res: dst_file.write(str(vector[0])) for FEATURE_INDEX in xrange(0, FEATURE_NUM): if (vector[FEATURE_INDEX + 1] != 0): dst_file.write("".join([" ", str(FEATURE_INDEX + 1), ":", str("%0.4f"%vector[FEATURE_INDEX + 1])])) dst_file.write("\n") dst_file.close() <file_sep>/py/history/cross_validation/cross_validation.py # 11.27 ver2 import os import csv import math import nltk import numpy as np from sklearn.feature_extraction.text import * from sklearn.feature_selection import SelectKBest, SelectPercentile, chi2, f_classif from sklearn.linear_model import * from sklearn.naive_bayes import * from sklearn import svm, cross_validation from scipy.sparse import * from scipy.io import * from nltk.tokenize import * from nltk.stem.snowball import * from stemming.porter2 import stem from lmfit import * def cleaned_text(text): text = nltk.word_tokenize(text) text = " ".join([stem(x.lower()) for x in text]) return text CORPUS_SIZE_ITEMS = ['entire', 'small'] CORPUS_SIZE = 0 # 0 for entire, 1 for small PREDICT_ATTRIBUTE_NUM = 24 VECTORIZER = 1 # 0 for CountVectorizer, 1 for TfidfVectorizer K_FOR_BEST = 2000 SELECT_PERCENTILE = 30 SELECTOR = 1 # 0 for K-select, 1 for precentile-select cur_dir = os.getcwd() if (CORPUS_SIZE == 1): train_csv = file(cur_dir + "/../data/small_train.csv") else: train_csv = file(cur_dir + "/../data/train.csv") ################################# # Get Corpus From CSV # ################################# train_corpus = [] # get train_tweets from csv to train_corpus[] cnt = 0 train_reader = csv.reader(train_csv) for tweet in train_reader: text = unicode(tweet[1] + " " + tweet[2] + " " + tweet[3], 'ascii', 'ignore') # text = cleaned_text(text) train_corpus.append(text) # print "train tweet", cnt, "to corpus[]" cnt += 1 # delete header del train_corpus[0] train_csv.close() ################################# # Feature Exraction # ################################# # get x_train, x_test from train_corpus, test_corpus print "start extraction" if (VECTORIZER == 0): vectorizer = CountVectorizer(min_df = 1, tokenizer = nltk.word_tokenize) elif (VECTORIZER == 1): vectorizer = TfidfVectorizer(min_df = 1, tokenizer = nltk.word_tokenize) # vectorizer = TfidfVectorizer(ngram_range=(1, 5), analyzer="word", binary=False, min_df=3) vectorizer.fit(train_corpus) x_train = vectorizer.transform(train_corpus) print "finish extraction" ################################# # Feature Selection # ################################# # # get feature names attribute_names = ["ATTR:I can not tell attitude" ,"ATTR:Negative" ,"ATTR:Neutral / author is just sharing information" ,"ATTR:Positive" ,"ATTR:Tweet not related to weather condition" ,"ATTR:current (same day) weather" ,"ATTR:future (forecast)" ,"ATTR:I can not tell time" ,"ATTR:past weather" ,"ATTR:clouds" ,"ATTR:cold" ,"ATTR:dry" ,"ATTR:hot" ,"ATTR:humid" ,"ATTR:hurricane" ,"ATTR:I can not tell weather" ,"ATTR:ice" ,"ATTR:other" ,"ATTR:rain" ,"ATTR:snow" ,"ATTR:storms" ,"ATTR:sun" ,"ATTR:tornado" ,"ATTR:wind" ] for CURRENT_ATTRIBUTE in xrange(0, PREDICT_ATTRIBUTE_NUM): if (CORPUS_SIZE == 1): train_csv = file(cur_dir + "/../data/small_train.csv") else: train_csv = file(cur_dir + "/../data/train.csv") # get CURRENT ATTRIBUTE train_attrs from csv train_attrs = [] train_reader = csv.reader(train_csv) cnt = 0 for tweet in train_reader: attr = tweet[CURRENT_ATTRIBUTE + 4] train_attrs.append(attr) cnt += 1 del train_attrs[0] # get y_train from train_attrs y_train = [[float(attr)] for attr in train_attrs] # chi-2 select features print "start feature selection" if (SELECTOR == 0): selector = SelectKBest(chi2, k = K_FOR_BEST) else: selector = SelectPercentile(score_func=chi2, percentile=SELECT_PERCENTILE) selector.fit(x_train, y_train) new_x_train = selector.transform(x_train) print "feature selection done" # convert y_train to svm-fit shape y_train = [attr[0] for attr in y_train] new_x_train, new_x_test, new_y_train, new_y_test = cross_validation.train_test_split(new_x_train, y_train, test_size=0.4, random_state=0) # regression # clf = svm.SVR(kernel='rbf', degree=3, gamma=1.9, coef0=0.0, tol=0.001, \ # C=0.13, epsilon=0.1, shrinking=True, probability=False, cache_size=700, \ # verbose=False, max_iter=-1, random_state=None) clf = LinearRegression() clf = clf.fit(new_x_train, new_y_train) # cross validation score = clf.score(new_x_test, new_y_test) print "score :", score # my validation predict_y_test = clf.predict(new_x_test) RMSE = 0 n = len(new_y_test) for i in xrange(0, n): RMSE += (new_y_test[i] - predict_y_test[i]) ** 2 RMSE /= n RMSE = math.sqrt(RMSE) print "RMSE :", RMSE train_csv.close() <file_sep>/py/history/cross_validation/cross_validation3.py # 11.28 ver 1 # new templete regression # kaggle : 0.17528, RMSE : 0.17920 # new templete regression 2 # kaggle : 0.23332, RMSE : 0.22970 # ridge 1 # kaggle : 0.16405, RMSE : 0.16414 import os import pandas import nltk import re import threading import numpy as np from sklearn.feature_extraction.text import * from sklearn.feature_selection import SelectPercentile, chi2 from sklearn.linear_model import * from sklearn import cross_validation ######################## ## SETTINGS ## ######################## CORPUS_SIZE = 0 # 0 for entire, 1 for small extra = " you posit are negat is you was the it of state my and locat you to weather be degre am it mph weather weather a all to " ################################# # get content from CSV # ################################# print "get content from csv" cur_dir = os.getcwd() if (CORPUS_SIZE == 1): train_path = cur_dir + "/../data/small_train.csv" else: train_path= cur_dir + "/../data/trainStem.csv" train_content = pandas.read_csv(train_path) train_len = len(train_content) for i in xrange(0, train_len): train_content['tweet'][i] = str(train_content['tweet'][i]) + " " + str(train_content['state'][i]) + " " + str(train_content['location'][i]) + extra train_tweets = train_content['tweet'] train_location = train_content['state'] + " " + train_content['location'] train_attitude = train_content.ix[:,4:9] train_time = train_content.ix[:,9:13] train_weather = train_content.ix[:,13:28] train_attributes = train_content.ix[:,4:28] ################################# # Feature Exraction # ################################# print "feature extraction" vectorizer = TfidfVectorizer(ngram_range = (1, 2), strip_accents='unicode', analyzer='word') vectorizer.fit(train_tweets) raw_x_train = vectorizer.transform(train_tweets) raw_y_train = np.array(train_attributes) best_a = 0 best_rmse = 1 for i in xrange(0, 50): ALPHA = 1 + i * 0.03 ################################# # Regression # ################################# print "regression" x_train, x_test, y_train, y_test = cross_validation.train_test_split(raw_x_train, raw_y_train, test_size=0.4, random_state=0) # clf = LinearRegression() clf = Ridge (alpha = ALPHA) clf.fit(x_train, y_train) prediction = clf.predict(x_test) ################################# # Normalize # ################################# print "normalization" length = x_test.shape[0] temp = [] for i in xrange(0, length): temp.append([]) vector = prediction[i] for j in xrange(0, 24): num = vector[j] if (num > 1): temp[i].append(1) elif (num >= 0.05): temp[i].append(num) else: temp[i].append(0) for i in xrange(0, length): summary = 0 for j in xrange(0, 5): summary += temp[i][j] if (summary != 0): for j in xrange(0, 5): temp[i][j] /= summary summary = 0 for j in xrange(5, 9): summary += temp[i][j] if (summary != 0): for j in xrange(5, 9): temp[i][j] /= summary prediction = temp ################################# # score # ################################# RMSE = np.sqrt(np.sum(np.array(np.array(prediction)-y_test)**2)/ (x_test.shape[0]*24.0)) print "RMSE :", RMSE, "alpha :", ALPHA if (RMSE < best_rmse): best_rmse = RMSE best_a = ALPHA print "best rmse :", best_rmse, "best a :", best_a<file_sep>/py/text_process/text_spell_checkr.py import re, collections import pandas as p import nltk from nltk.tokenize import * from stemming.porter2 import stem def words(text): return re.findall('[a-z]+', text.lower()) def train(features): model = collections.defaultdict(lambda: 1) for f in features: model[f] += 1 return model NWORDS = train(words(file('big.txt').read())) alphabet = 'abcdefghijklmnopqrstuvwxyz' def edits1(word): splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [a + b[1:] for a, b in splits if b] transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] inserts = [a + c + b for a, b in splits for c in alphabet] return set(deletes + transposes + replaces + inserts) def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) def known(words): return set(w for w in words if w in NWORDS) def correct(word): candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] return max(candidates, key=NWORDS.get) paths = ['../data/mytrain2.csv', '../data/mytest2.csv'] t0 = p.read_csv(paths[0]) t1 = p.read_csv(paths[1]) for i in range(len(t1['tweet'])): text = nltk.word_tokenize(t1['tweet'][i]) t1['tweet'][i] = "" for x in text: flag = 1 while (flag==1 and x != ''): if (x.endswith('.')): x = x[:-1] elif (x.endswith(',')): x = x[:-1] elif (x.endswith('!')): x = x[:-1] elif (x.endswith('?')): x = x[:-1] elif (x.endswith('/')): x = x[:-1] elif (x.endswith('?')): x = x[:-1] elif (x.endswith(':')): x = x[:-1] elif (x.endswith('\\')): x = x[:-1] else: flag = 0 if x.isalpha(): x = correct(x.lower()) if (x != 's'): t1['tweet'][i] = t1['tweet'][i] + correct(x) + " " # print t1['tweet'][i] print "test done" for i in range(len(t0['tweet'])): text = nltk.word_tokenize(t0['tweet'][i]) t0['tweet'][i] = "" for x in text: flag = 1 while (flag==1 and x != ''): if (x.endswith('.')): x = x[:-1] elif (x.endswith(',')): x = x[:-1] elif (x.endswith('!')): x = x[:-1] elif (x.endswith('?')): x = x[:-1] elif (x.endswith('/')): x = x[:-1] elif (x.endswith('?')): x = x[:-1] elif (x.endswith(':')): x = x[:-1] elif (x.endswith('\\')): x = x[:-1] else: flag = 0 if x.isalpha(): x = correct(x.lower()) if (x != 's'): t0['tweet'][i] = t0['tweet'][i] + correct(x) + " " t0.to_csv('../data/mytrain3.csv', index=False) t1.to_csv('../data/mytest3.csv', index=False)<file_sep>/py/test/test_vectorizer.py import csv from sklearn.feature_extraction.text import TfidfVectorizer testcsv = file("/Users/Zhao/codes/eclipse/WebDataMining/data/test.csv") traincsv = file("/Users/Zhao/codes/eclipse/WebDataMining/data/small_train.csv") corpus = [] # get tweets from csv to corpus[] trainreader = csv.reader(traincsv) for tweet in trainreader: # tweet content + state + city gathered = tweet[1] + " " + tweet[2] + " " + tweet[3] corpus.append(gathered) # extract vectorizer = TfidfVectorizer(min_df=1) result = vectorizer.fit_transform(corpus) # take a glimpse at the first glimpse of result print result[0]<file_sep>/py/history/template/new/new_template_group_regression.py # 11.28 ver 1 - 0.17528 normalized # the same with once regression import os import pandas import nltk import numpy as np from sklearn.feature_extraction.text import * from sklearn.linear_model import * ######################## ## SETTINGS ## ######################## CORPUS_SIZE = 0 # 0 for entire, 1 for small ################################# # get content from CSV # ################################# print "get content from csv" cur_dir = os.getcwd() if (CORPUS_SIZE == 1): test_path = cur_dir + "/../data/small_test.csv" train_path = cur_dir + "/../data/small_train.csv" else: test_path = cur_dir + "/../data/test.csv" train_path= cur_dir + "/../data/train.csv" train_content = pandas.read_csv(train_path) test_content = pandas.read_csv(test_path) train_len = len(train_content) test_len = len(test_content) for i in xrange(0, train_len): train_content['tweet'][i] = re.sub("http\S*|@\S*|{link}|RT\s*@\S*", "",train_content['tweet'][i]) if (isinstance(train_content['state'][i], basestring) == False): train_content['state'][i] = "" if (isinstance(train_content['location'][i], basestring) == False): train_content['location'][i] = "" for i in xrange(0, test_len): test_content['tweet'][i] = re.sub("http\S*|@\S*|{link}|RT\s*@\S*", "",test_content['tweet'][i]) if (isinstance(test_content['state'][i], basestring) == False): test_content['state'][i] = "" if (isinstance(test_content['location'][i], basestring) == False): test_content['location'][i] = "" train_tweets = train_content['tweet'] train_location = train_content['state'] + " " + train_content['location'] train_attitude = train_content.ix[:,4:9] train_time = train_content.ix[:,9:13] train_weather = train_content.ix[:,13:28] train_attributes = train_content.ix[:,4:28] test_tweets = test_content['tweet'] test_location = test_content['state'] + " " + test_content['location'] ################################# # Feature Exraction # ################################# print "feature extraction" vectorizer = TfidfVectorizer(max_features=4000, strip_accents='unicode', analyzer='word') vectorizer.fit(train_tweets) x_train = vectorizer.transform(train_tweets) x_test = vectorizer.transform(test_tweets) ################################# # Regression # ################################# print "regression" clf = LinearRegression() y_train = np.array(train_attitude) clf.fit(x_train, y_train) y_test_attitude = clf.predict(x_test) y_train = np.array(train_time) clf.fit(x_train, y_train) y_test_time = clf.predict(x_test) y_train = np.array(train_weather) clf.fit(x_train, y_train) y_test_weather = clf.predict(x_test) y_test = np.hstack((y_test_attitude, y_test_time, y_test_weather)) ################################# # write to csv # ################################# print "write back to csv" prediction = np.array(np.hstack([np.matrix(test_content['id']).T, y_test])) col = '%i,' + '%f,'*23 + '%f' np.savetxt(cur_dir + "/../data/result/prediction.csv", prediction,col, delimiter=',') <file_sep>/py/history/template/old/template_group_regression.py # 11.27 import os import csv import nltk import numpy as np from sklearn.feature_extraction.text import * from sklearn.feature_selection import SelectKBest, SelectPercentile, chi2, f_classif from sklearn.linear_model import * from sklearn.naive_bayes import * from sklearn import svm from scipy.sparse import * from scipy.io import * from nltk.tokenize import * from nltk.stem.snowball import * from stemming.porter2 import stem def cleaned_text(text): return text CORPUS_SIZE_ITEMS = ['entire', 'small'] CORPUS_SIZE = 0 # 0 for entire, 1 for small VECTORIZER = 1 # 0 for CountVectorizer, 1 for TfidfVectorizer K_FOR_BEST = 2000 SELECT_PERCENTILE = 30 SELECTOR = 1 # 0 for K-select, 1 for precentile-select cur_dir = os.getcwd() if (CORPUS_SIZE == 1): test_csv = file(cur_dir + "/../data/small_test.csv") train_csv = file(cur_dir + "/../data/small_train.csv") else: test_csv = file(cur_dir + "/../data/test.csv") train_csv = file(cur_dir + "/../data/train.csv") ################################# # Get Corpus From CSV # ################################# train_corpus = [] test_corpus = [] # get train_tweets from csv to train_corpus[ ] cnt = 0 train_reader = csv.reader(train_csv) for tweet in train_reader: text = unicode(tweet[1] + " " + tweet[2] + " " + tweet[3], 'ascii', 'ignore') # text = cleaned_text(text) train_corpus.append(text) cnt += 1 # delete header del train_corpus[0] train_csv.close() # get test_tweets from csv to test_corpus[] cnt = 0 test_reader = csv.reader(test_csv) for tweet in test_reader: text = unicode(tweet[1] + " " + tweet[2] + " " + tweet[3], 'ascii', 'ignore') # text = cleaned_text(text) test_corpus.append(text) cnt += 1 # delete header del test_corpus[0] test_csv.close() ################################# # Feature Exraction # ################################# # get x_train, x_test from train_corpus, test_corpus print "start extraction" entire_corpus = train_corpus + test_corpus if (VECTORIZER == 0): vectorizer = CountVectorizer(min_df = 1, tokenizer = nltk.word_tokenize) elif (VECTORIZER == 1): vectorizer = TfidfVectorizer(max_features=10000, strip_accents='unicode', analyzer='word', tokenizer = nltk.word_tokenize) vectorizer.fit(train_corpus) x_train = vectorizer.transform(train_corpus) x_test = vectorizer.transform(test_corpus) print "finish extraction" ################################# # Feature Selection # # and Regression # # for three groups of attrs # ################################# train_len = len(train_corpus) ################################# ## attributes group loop ## for ATTRIBUTES_GROUP in xrange(0, 3): print "GROUP -", ATTRIBUTES_GROUP if (CORPUS_SIZE == 1): train_csv = file(cur_dir + "/../data/small_train.csv") else: train_csv = file(cur_dir + "/../data/train.csv") attrs_arr = [] time_attrs = [] weather_attrs = [] for i in xrange(0, train_len + 1): attrs_arr.append([]) # get attitude attributes from csv if (ATTRIBUTES_GROUP == 0): index_from, index_to = 4, 9 if (ATTRIBUTES_GROUP == 1): index_from, index_to = 9, 13 if (ATTRIBUTES_GROUP == 2): index_from, index_to = 13, 28 train_reader = csv.reader(train_csv) cnt = 0 for tweet in train_reader: attr = tweet[index_from:index_to] attrs_arr[cnt] = attr cnt += 1 train_csv.close() del attrs_arr[0] # get y_train from train_attrs y_train = [[float(attr) for attr in attrs] for attrs in attrs_arr] # chi-2 select features print "start feature selection" if (SELECTOR == 0): selector = SelectKBest(chi2, k = K_FOR_BEST) else: selector = SelectPercentile(score_func=chi2, percentile=SELECT_PERCENTILE) selector.fit(x_train, y_train) new_x_train = selector.transform(x_train) new_x_test = selector.transform(x_test) print "feature selection done" # regression print "start regression" clf = LinearRegression() clf = clf.fit(new_x_train, y_train) result = clf.predict(new_x_test) print "regression done" # build csv file if (ATTRIBUTES_GROUP == 0): result_path = cur_dir + "/../data/result/attitude_res.csv" if (ATTRIBUTES_GROUP == 1): result_path = cur_dir + "/../data/result/time_res.csv" if (ATTRIBUTES_GROUP == 2): result_path = cur_dir + "/../data/result/weather_res.csv" if os.path.exists(result_path): os.remove(result_path) result_csv = file(result_path, 'a') result_writer = csv.writer(result_csv) # output result to csv file print "start writing result" for item in result: result_writer.writerow(item) print "writing result done" result_csv.close() ## loop over ## ################################# <file_sep>/py/text_process/text_filter.py import nltk import pandas as p import re from nltk.tokenize import * from stemming.porter2 import stem paths = ['../data/train.csv', '../data/test.csv'] t0 = p.read_csv(paths[0]) t1 = p.read_csv(paths[1]) #for i in range(len(t0['tweet'])): # t0['tweet'][i] = t0['tweet'][i].translate(None, punctuation).lower() #for i in range(len(t1['tweet'])): # t1['tweet'][i] = t1['tweet'][i].translate(None, punctuation).lower() for i in range(len(t1['tweet'])): t1['tweet'][i] = re.sub(r'\{\w*\}', '', t1['tweet'][i])#{link}{pic} t1['tweet'][i] = re.sub(r'[a-zA-z]+://[^\s]*', '', t1['tweet'][i])#url t1['tweet'][i] = re.sub(r'\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*', '', t1['tweet'][i])#mail t1['tweet'][i] = re.sub(r'\bRT\b', '', t1['tweet'][i])#RT # t1['tweet'][i] = re.sub(r'[^\x00-\xff]+', '', t1['tweet'][i])#not en t1['tweet'][i] = re.sub(r'#', '', t1['tweet'][i])#\# may double the remain string(because it's a topic about the tweet t1['tweet'][i] = re.sub(r'@\w+:?', '', t1['tweet'][i])#\@someone t1['tweet'][i] = re.sub(r'\d+\.\d+\.\d+\.\d+', '', t1['tweet'][i])#domain t1['tweet'][i] = re.sub(r'(=|(:[\-o0]?))\(+', ' sad ', t1['tweet'][i])# :( :-( =( t1['tweet'][i] = re.sub(r'(=|(:[\-o0]?))\)+', ' smile ', t1['tweet'][i])# :) :-) =) t1['tweet'][i] = re.sub(r'\^_\^', ' smile ', t1['tweet'][i])# ^_^ t1['tweet'][i] = re.sub(r'(=|(:\-?))D+', ' excited ', t1['tweet'][i])# :D :-D =D t1['tweet'][i] = re.sub(r'\-(\.|_)+\-', ' annoyed ', t1['tweet'][i])# -___- -.- t1['tweet'][i] = re.sub(r'(o[_\.]+[O0])|([O0][_\.]+o)', ' WTF ', t1['tweet'][i])# o_0 0__o t1['tweet'][i] = re.sub(r'(0_0)|(O_O)', ' surprised ', t1['tweet'][i])# 0_0 t1['tweet'][i] = re.sub(r':\-?(o|O)', ' shock ', t1['tweet'][i])# :O t1['tweet'][i] = re.sub(r':\-?/', ' frustrated ', t1['tweet'][i])# :/ t1['tweet'][i] = re.sub(r'T_T', ' cry ', t1['tweet'][i])# T_T t1['tweet'][i] = re.sub(r'[xX]_[xX]', ' dead ', t1['tweet'][i])# x_x t1['tweet'][i] = re.sub(r':[pP]', ' laugh ', t1['tweet'][i])# :p t1['tweet'][i] = re.sub(r'[xX]D', ' LOL ', t1['tweet'][i])# LOL t1['tweet'][i] = re.sub(r'w/', ' with ', t1['tweet'][i])# w/ t1['tweet'][i] = re.sub(r'[bB]4', ' before ', t1['tweet'][i])# b4 -> before t1['tweet'][i] = re.sub(r'\b(U|u)\b', 'you', t1['tweet'][i])# u U t1['tweet'][i] = re.sub(r'&\w+;', ' ', t1['tweet'][i])# html flag t1['tweet'][i] = re.sub(r'[!\?,]+', ' ', t1['tweet'][i])# !?, t1['tweet'][i] = re.sub(r'\-', ' ', t1['tweet'][i])# : t1['tweet'][i] = re.sub(r'\.{2,}', ' ', t1['tweet'][i])# .... t1['tweet'][i] = re.sub(r'\s[:|/\\]+\s', ' ', t1['tweet'][i])# : \ / | t1['tweet'][i] = re.sub(r'"', ' ', t1['tweet'][i])# " # text = nltk.word_tokenize(t1['tweet'][i]) # t1['tweet'][i] = " ".join([stem(x.lower()) for x in text])# for i in range(len(t0['tweet'])): t0['tweet'][i] = re.sub(r'\{\w*\}', '', t0['tweet'][i])#{link}{pic} t0['tweet'][i] = re.sub(r'[a-zA-z]+://[^\s]*', '', t0['tweet'][i])#url t0['tweet'][i] = re.sub(r'\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*', '', t0['tweet'][i])#mail t0['tweet'][i] = re.sub(r'\bRT\b', '', t0['tweet'][i])#RT # t0['tweet'][i] = re.sub(r'[^\x00-\xff]+', '', t0['tweet'][i])#not en t0['tweet'][i] = re.sub(r'#', '', t0['tweet'][i])#\# may double the remain string(because it's a topic about the tweet t0['tweet'][i] = re.sub(r'@\w+:?', '', t0['tweet'][i])#\@someone t0['tweet'][i] = re.sub(r'\d+\.\d+\.\d+\.\d+', '', t0['tweet'][i])#domain t0['tweet'][i] = re.sub(r'(=|(:[\-o0]?))\(+', ' sad ', t0['tweet'][i])# :( :-( =( t0['tweet'][i] = re.sub(r'(=|(:[\-o0]?))\)+', ' smile ', t0['tweet'][i])# :) :-) =) t0['tweet'][i] = re.sub(r'\^_\^', ' smile ', t0['tweet'][i])# ^_^ t0['tweet'][i] = re.sub(r'(=|(:\-?))D+', ' excited ', t0['tweet'][i])# :D :-D =D t0['tweet'][i] = re.sub(r'\-(\.|_)+\-', ' annoyed ', t0['tweet'][i])# -___- -.- t0['tweet'][i] = re.sub(r'(o[_\.]+[O0])|([O0][_\.]+o)', ' WTF ', t0['tweet'][i])# o_0 0__o t0['tweet'][i] = re.sub(r'(0_0)|(O_O)', ' surprised ', t0['tweet'][i])# 0_0 t0['tweet'][i] = re.sub(r':\-?(o|O)', ' shock ', t0['tweet'][i])# :O t0['tweet'][i] = re.sub(r':\-?/', ' frustrated ', t0['tweet'][i])# :/ t0['tweet'][i] = re.sub(r'T_T', ' cry ', t0['tweet'][i])# T_T t0['tweet'][i] = re.sub(r'[xX]_[xX]', ' dead ', t0['tweet'][i])# x_x t0['tweet'][i] = re.sub(r':[pP]', ' laugh ', t0['tweet'][i])# :p t0['tweet'][i] = re.sub(r'[xX]D', ' LOL ', t0['tweet'][i])# LOL t0['tweet'][i] = re.sub(r'w/', ' with ', t0['tweet'][i])# w/ t0['tweet'][i] = re.sub(r'[bB]4', ' before ', t0['tweet'][i])# b4 -> before t0['tweet'][i] = re.sub(r'\b(U|u)\b', 'you', t0['tweet'][i])# u U t0['tweet'][i] = re.sub(r'&\w+;', ' ', t0['tweet'][i])# html flag t0['tweet'][i] = re.sub(r'[!\?,]+', ' ', t0['tweet'][i])# !?, t0['tweet'][i] = re.sub(r'\-', ' ', t0['tweet'][i])# : t0['tweet'][i] = re.sub(r'\.{2,}', ' ', t0['tweet'][i])# .... t0['tweet'][i] = re.sub(r'\s[:|/\\]+\s', ' ', t0['tweet'][i])# : \ / | t0['tweet'][i] = re.sub(r'"', ' ', t0['tweet'][i])# " # text = nltk.word_tokenize(t0['tweet'][i]) # t0['tweet'][i] = " ".join([stem(x.lower()) for x in text])# t0.to_csv('../data/mytrain2.csv', index=False) t1.to_csv('../data/mytest2.csv', index=False)<file_sep>/py/history/cross_validation/cross_validation2.py # 11.28 ver 1 # new templete regression # kaggle : 0.17528, RMSE : 0.17920 # new templete regression 2 # kaggle : 0.23332, RMSE : 0.22970 # ridge 1 # kaggle : 0.16405, RMSE : 0.16414 import os import pandas import nltk import re import threading import numpy as np from sklearn.feature_extraction.text import * from sklearn.feature_selection import SelectPercentile, chi2 from sklearn.linear_model import * from sklearn import cross_validation ######################## ## SETTINGS ## ######################## CORPUS_SIZE = 0 # 0 for entire, 1 for small ################################# # get content from CSV # ################################# print "get content from csv" cur_dir = os.getcwd() if (CORPUS_SIZE == 1): train_path = cur_dir + "/../data/small_train.csv" else: train_path= cur_dir + "/../data/train.csv" train_content = pandas.read_csv(train_path) train_len = len(train_content) for i in xrange(0, train_len): train_content['tweet'][i] = re.sub("http\S*|@\S*|{link}|RT\s*@\S*", "",train_content['tweet'][i]) if (isinstance(train_content['state'][i], basestring) == False): train_content['state'][i] = "" if (isinstance(train_content['location'][i], basestring) == False): train_content['location'][i] = "" train_tweets = train_content['tweet'] train_location = train_content['state'] + " " + train_content['location'] train_attitude = train_content.ix[:,4:9] train_time = train_content.ix[:,9:13] train_weather = train_content.ix[:,13:28] train_attributes = train_content.ix[:,4:28] ################################# # Feature Exraction # ################################# print "feature extraction" vectorizer = TfidfVectorizer(ngram_range = (1, 2), max_features=10000, strip_accents='unicode', analyzer='word') vectorizer.fit(train_tweets) x_train = vectorizer.transform(train_tweets) y_train = np.array(train_attributes) ################################# # Regression # ################################# print "regression" x_train, x_test, y_train, y_test = cross_validation.train_test_split(x_train, y_train, test_size=0.4, random_state=0) # clf = LinearRegression() clf = Ridge (alpha = 1.85) clf.fit(x_train, y_train) prediction = clf.predict(x_test) ################################# # Normalize # ################################# print "normalization" length = x_test.shape[0] temp = [] for i in xrange(0, length): temp.append([]) vector = prediction[i] for j in xrange(0, 24): num = vector[j] if (num > 1): temp[i].append(1) elif (num >= 0.05): temp[i].append(num) else: temp[i].append(0) for i in xrange(0, length): summary = 0 for j in xrange(0, 5): summary += temp[i][j] if (summary != 0): for j in xrange(0, 5): temp[i][j] /= summary summary = 0 for j in xrange(5, 9): summary += temp[i][j] if (summary != 0): for j in xrange(5, 9): temp[i][j] /= summary prediction = temp ################################# # score # ################################# RMSE = np.sqrt(np.sum(np.array(np.array(prediction)-y_test)**2)/ (x_test.shape[0]*24.0)) print "RMSE :", RMSE <file_sep>/py/sample/sklearn_test.py #!/usr/bin/env python # coding=utf-8 import os import sys import numpy as np from sklearn.datasets import load_files from sklearn.cross_validation import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB def text_classifly(dataset_dir_name): # 加载数据集,切分数据集80%训练,20%测试 movie_reviews = load_files(dataset_dir_name) doc_terms_train, doc_terms_test, doc_class_train, doc_class_test = train_test_split(movie_reviews.data, movie_reviews.target, test_size = 0.2) #BOOL型特征下的向量空间模型,注意,测试样本调用的是transform接口 count_vec = CountVectorizer(binary = True) doc_train_bool = count_vec.fit_transform(doc_terms_train) doc_test_bool = count_vec.transform(doc_terms_test) #调用MultinomialNB分类器 clf = MultinomialNB().fit(doc_train_bool, doc_class_train) doc_class_predicted = clf.predict(doc_test_bool) print 'Accuracy: ', np.mean(doc_class_predicted == doc_class_test) if __name__ == '__main__': dataset_dir_name = sys.argv[1] text_classifly(dataset_dir_name)<file_sep>/py/history/template/old/group_res_collect.py import os import csv cur_dir = os.getcwd() dst_path = cur_dir + "/../data/result/submission.csv" if os.path.exists(dst_path): os.remove(dst_path) dst_csv = file(dst_path, "w") dst_writer = csv.writer(dst_csv) test_csv = file(cur_dir + "/../data/test.csv") test_reader = csv.reader(test_csv) header = ["id","s1","s2","s3","s4","s5","w1","w2","w3","w4","k1","k2","k3","k4","k5","k6","k7","k8","k9",\ "k10","k11","k12","k13","k14","k15"] ROW_NUM = 42157 # collect ID test_arr = [] for item in test_reader: test_arr.append(item[0]) del test_arr[0] result_arr = [] for i in xrange(0, ROW_NUM): result_arr.append([]) result_arr[i] = [test_arr[i]] # collect ATTRIBUTES for ATTRIBUTES_GROUP in xrange(0, 3): if (ATTRIBUTES_GROUP == 0): attrs_csv = file(cur_dir + "/../data/result/attitude_res.csv") if (ATTRIBUTES_GROUP == 1): attrs_csv = file(cur_dir + "/../data/result/time_res.csv") if (ATTRIBUTES_GROUP == 2): attrs_csv = file(cur_dir + "/../data/result/weather_res.csv") attrs_reader = csv.reader(attrs_csv) attrs_arr = [] for item in attrs_reader: attrs_arr.append(item) for i in xrange(0, ROW_NUM): for attr in attrs_arr[i]: num = float(attr) if (num > 0): result_arr[i].append(num) else: result_arr[i].append(0) attrs_csv.close() # normalize ATTRIBUTES for item in result_arr: # attitude summary = 0 for ATTRIBUTE_NUM in xrange(0, 5): summary += item[ATTRIBUTE_NUM + 1] if (summary != 0): for ATTRIBUTE_NUM in xrange(0, 5): item[ATTRIBUTE_NUM + 1] /= summary # time summary = 0 for ATTRIBUTE_NUM in xrange(5, 9): summary += item[ATTRIBUTE_NUM + 1] if (summary != 0): for ATTRIBUTE_NUM in xrange(5, 9): item[ATTRIBUTE_NUM + 1] /= summary # weather summary = 0 for ATTRIBUTE_NUM in xrange(9, 24): summary += item[ATTRIBUTE_NUM + 1] if (summary != 0): for ATTRIBUTE_NUM in xrange(9, 24): item[ATTRIBUTE_NUM + 1] /= summary # write HEADER dst_writer.writerow(header) # write ID and ATTRIBUTES dst_writer.writerows(result_arr) dst_csv.close() <file_sep>/py/history/cross_validation/cross_validation_single.py # 11.28 ver 1 # new templete_single # kaggle: , RMSE: 0.17796 # new templete_single 2 # kaggle: , RMSE: 0.18308 # ridge 1 # kaggle : , RMSE : 0.16409 import os import pandas import nltk import re import numpy as np from sklearn.feature_extraction.text import * from sklearn.feature_selection import SelectPercentile, chi2 from sklearn.linear_model import * from sklearn.svm import * from sklearn import cross_validation ######################## ## SETTINGS ## ######################## CORPUS_SIZE = 0 # 0 for entire, 1 for small ################################# # get content from CSV # ################################# print "get content from csv" cur_dir = os.getcwd() if (CORPUS_SIZE == 1): train_path = cur_dir + "/../data/small_train.csv" else: train_path= cur_dir + "/../data/train.csv" train_content = pandas.read_csv(train_path) train_len = len(train_content) for i in xrange(0, train_len): train_content['tweet'][i] = re.sub("http\S*|@\S*|{link}|RT\s*@\S*", "",train_content['tweet'][i]) if (isinstance(train_content['state'][i], basestring) == False): train_content['state'][i] = "" if (isinstance(train_content['location'][i], basestring) == False): train_content['location'][i] = "" train_tweets = train_content['tweet'] train_location = train_content['state'] + " " + train_content['location'] train_attitude = train_content.ix[:,4:9] train_time = train_content.ix[:,9:13] train_weather = train_content.ix[:,13:28] train_attributes = train_content.ix[:,4:28] ################################# # Feature Exraction # ################################# print "feature extraction" vectorizer = TfidfVectorizer(max_features=2000, strip_accents='unicode', analyzer='word') vectorizer.fit(train_tweets) x_train = vectorizer.transform(train_tweets) ################################# # Regression # ################################# print "regression" y_train = np.array(train_attributes) x_train, x_test, y_train, y_test = cross_validation.train_test_split(x_train, y_train, test_size=0.4, random_state=0) # clf = LinearRegression() # clf = Ridge (alpha = 1.85) clf = SVR(kernel='rbf', degree=3, gamma=0.2, coef0=0.0, tol=0.001, \ C=0.9, epsilon=0.01, shrinking=True, probability=False, cache_size=700, \ verbose=False, max_iter=-1, random_state=None) y_test_arr = [] for i in xrange(0, 24): print i this_x_train = x_train this_y_train = [item[i] for item in y_train] this_x_test = x_test clf.fit(this_x_train, this_y_train) y_test_arr.append(clf.predict(this_x_test)) length = x_test.shape[0] prediction = [] for i in xrange(0, length): prediction.append([]) for j in xrange(0, 24): prediction[i].append(y_test_arr[j][i]) prediction = np.array(prediction) ################################# # Normalize # ################################# print "normalization" temp = [] for i in xrange(0, length): temp.append([]) vector = prediction[i] for j in xrange(0, 24): num = vector[j] if (num > 1): temp[i].append(1) elif (num >= 0.05): temp[i].append(num) else: temp[i].append(0) for i in xrange(0, length): summary = 0 for j in xrange(0, 5): summary += temp[i][j] if (summary != 0): for j in xrange(0, 5): temp[i][j] /= summary summary = 0 for j in xrange(5, 9): summary += temp[i][j] if (summary != 0): for j in xrange(5, 9): temp[i][j] /= summary prediction = temp ################################# # score # ################################# RMSE = np.sqrt(np.sum(np.array(prediction-y_test)**2)/ (x_test.shape[0]*24.0)) print "RMSE :", RMSE <file_sep>/py/history/ridge5.py import pandas as p from sklearn import linear_model import numpy as np from sklearn import cross_validation from sklearn import svm from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer import re import threading extraction_method=0 paths = ['../data/mytrain.csv', '../data/mytest.csv'] t = p.read_csv(paths[0]) t2 = p.read_csv(paths[1]) extra2 = " you posit are negat is you was the it of state my and locat you to weather be degre am it mph weather weather a all to " for i in range(len(t['tweet'])): t['tweet'][i] = str(t['tweet'][i]) + " " + str(t['state'][i]) + " " + str(t['location'][i]) + extra2 for i in range(len(t2['tweet'])): t2['tweet'][i] = str(t2['tweet'][i]) + " " + str(t2['state'][i]) + " " + str(t2['location'][i]) + extra2 print "start extraction" # delete the max_feature, score is higher if extraction_method==0: print "Tfidf......" tfidf = TfidfVectorizer(strip_accents='unicode', analyzer='word', ngram_range=(1,2)) tfidf.fit(t['tweet']) X = tfidf.transform(t['tweet']) test = tfidf.transform(t2['tweet']) y = np.array(t.ix[:,4:]) else: print "Count......" countmethod = CountVectorizer(strip_accents='unicode', analyzer='word', lowercase=True) countmethod.fit(t['tweet']) X = countmethod.transform(t['tweet']) test = countmethod.transform(t2['tweet']) y = np.array(t.ix[:,4:]) print "extraction done" print "start fit" clf = linear_model.Ridge (alpha = 1.0) clf.fit(X,y) print "fit done" print "start prediction" test_prediction = clf.predict(test) for i in xrange(len(test_prediction)): for j in xrange(len(test_prediction[i])): if test_prediction[i][j] <= 0.05: test_prediction[i][j] = 0 elif test_prediction[i][j] >= 0.95: test_prediction[i][j] = 1 # normalize attitude summary = 0 for j in xrange(0, 5): summary += test_prediction[i][j] if (summary != 0): for j in xrange(0, 5): test_prediction[i][j] /= summary # normalize time summary = 0 for j in xrange(5, 9): summary += test_prediction[i][j] if (summary != 0): for j in xrange(5, 9): test_prediction[i][j] /= summary print "prediction done" coname = ['id','s1','s2','s3','s4','s5','w1','w2','w3','w4','k1','k2','k3','k4','k5','k6','k7','k8','k9','k10', 'k11','k12','k13','k14','k15'] first = np.matrix(coname) print "start writing" prediction = np.array(np.hstack([np.matrix(t2['id']).T, test_prediction])) col = '%i,' + '%f,'*23 + '%f' np.savetxt('../data/myresult50.csv', prediction ,col, delimiter=',') print "writing done"<file_sep>/py/history/ridge8_group.py # 11.28 ver 1 import os import pandas import nltk import re import numpy as np from sklearn.feature_extraction.text import * from sklearn.linear_model import * ######################## ## SETTINGS ## ######################## extra = " you posit are negat i etc me as at be between both is you was for he she that the it of state my and locat you to weather be degre am it mph weather weather a all to " ################################# # get content from CSV # ################################# print "get content from csv" cur_dir = os.getcwd() test_path = cur_dir + "/../data/mytest2.csv" train_path= cur_dir + "/../data/mytrain2.csv" train_content = pandas.read_csv(train_path) test_content = pandas.read_csv(test_path) train_len = len(train_content) test_len = len(test_content) for i in xrange(0, train_len): train_content['tweet'][i] = str(train_content['tweet'][i]) + " " + str(train_content['state'][i]) + " " + str(train_content['location'][i]) + extra for i in xrange(0, test_len): test_content['tweet'][i] = str(test_content['tweet'][i]) + " " + str(test_content['state'][i]) + " " + str(test_content['location'][i]) + extra train_tweets = train_content['tweet'] train_attitude = train_content.ix[:,4:9] train_time = train_content.ix[:,9:13] train_weather = train_content.ix[:,13:28] train_attributes = train_content.ix[:,4:28] test_tweets = test_content['tweet'] ################################# # Feature Exraction # ################################# print "feature extraction" vectorizer = TfidfVectorizer(ngram_range=(1,3), strip_accents='unicode', analyzer='word') vectorizer.fit(train_tweets) x_train = vectorizer.transform(train_tweets) x_test = vectorizer.transform(test_tweets) ################################# # Regression # ################################# print "regression" clf = Ridge (alpha = 0.65) y_train = np.array(train_attitude) clf.fit(x_train, y_train) y_test_attitude = clf.predict(x_test) y_train = np.array(train_time) clf.fit(x_train, y_train) y_test_time = clf.predict(x_test) y_train = np.array(train_weather) clf.fit(x_train, y_train) y_test_weather = clf.predict(x_test) y_test = np.hstack((y_test_attitude, y_test_time, y_test_weather)) ################################# # Normalization # ################################# print "normalization" for i in xrange(len(y_test)): for j in xrange(len(y_test[i])): if y_test[i][j] <= 0.01: y_test[i][j] = 0 elif y_test[i][j] >= 0.99: y_test[i][j] = 1 # normalize attitude summary = 0 for j in xrange(0, 5): summary += y_test[i][j] if (summary != 0): for j in xrange(0, 5): y_test[i][j] /= summary # normalize time summary = 0 for j in xrange(5, 9): summary += y_test[i][j] if (summary != 0): for j in xrange(5, 9): y_test[i][j] /= summary ################################# # write to csv # ################################# print "write back to csv" prediction = np.array(np.hstack([np.matrix(test_content['id']).T, y_test])) col = '%i,' + '%f,'*23 + '%f' np.savetxt(cur_dir + "/../data/result/prediction.csv", prediction,col, delimiter=',') <file_sep>/py/history/template/old/res_collect2.py import os import csv cur_dir = os.getcwd() source_path = cur_dir + "/../data/result/prediction.csv" dst_path = cur_dir +"/../data/result/submission.csv" if (os.path.exists(dst_path)): os.remove(dst_path) reader = csv.reader(file(source_path)) writer = csv.writer(file(dst_path, 'a')) header = ["id","s1","s2","s3","s4","s5","w1","w2","w3","w4","k1","k2","k3","k4","k5","k6","k7","k8","k9",\ "k10","k11","k12","k13","k14","k15"] content = [] normalized_content = [] for item in reader: content.append(item) length = len(content) # id for item in content: normalized_content.append([item[0]]) # attrs for i in xrange(0, length): for j in xrange(1, 25): num = float(content[i][j]) if (num >= 0.95): normalized_content[i].append(1) elif (num >= 0.05): normalized_content[i].append(num) else: normalized_content[i].append(0) # normalize attitude summary = 0 for j in xrange(1, 6): summary += normalized_content[i][j] if (summary != 0): for j in xrange(1, 6): normalized_content[i][j] /= summary # normalize time summary = 0 for j in xrange(6, 10): summary += normalized_content[i][j] if (summary != 0): for j in xrange(6, 10): normalized_content[i][j] /= summary writer.writerow(header) writer.writerows(normalized_content)<file_sep>/README.md WebDataMining_Kaggle ==================== http://www.kaggle.com/c/crowdflower-weather-twitter <file_sep>/py/history/cross_validation/cross_validation_group.py # 11.28 ver 1 # new templete group # kaggle : 0.17528, RMSE : 0.17920 # new templete group 2 # kaggle : , RMSE : 0.21230 # ridge 1 # kaggle : , RMSE : 0.16409 # ridge 2 # kaggle : , RMSE : 0.15752 import os import pandas import nltk import math import re import numpy as np from sklearn.feature_extraction.text import * from sklearn.feature_selection import SelectPercentile, chi2 from sklearn.linear_model import * from sklearn.svm import * from sklearn import cross_validation ######################## ## SETTINGS ## ######################## extra = " you posit are negat i etc me as at be between both is you was for he she that the it of state my and locat you to weather be degre am it mph weather weather a all to " ################################# # get content from CSV # ################################# print "get content from csv" cur_dir = os.getcwd() train_path= cur_dir + "/../data/train.csv" train_content = pandas.read_csv(train_path) train_len = len(train_content) for i in xrange(0, train_len): train_content['tweet'][i] = str(train_content['tweet'][i]) + " " + str(train_content['state'][i]) + " " + str(train_content['location'][i]) + extra train_tweets = train_content['tweet'] train_attitude = train_content.ix[:,4:9] train_time = train_content.ix[:,9:13] train_weather = train_content.ix[:,13:28] train_attributes = train_content.ix[:,4:28] ################################# # Feature Exraction # ################################# print "feature extraction" vectorizer = TfidfVectorizer(ngram_range=(1,3), strip_accents='unicode', analyzer='word') vectorizer.fit(train_tweets) x_train = vectorizer.transform(train_tweets) ################################# # Regression # ################################# print "regression" y_train = np.array(train_attributes) x_train, x_test, y_train, y_test = cross_validation.train_test_split(x_train, y_train, test_size=0.4, random_state=0) # clf = LinearRegression() clf = Ridge (alpha = 0.55) this_y_train = np.array([item[:5] for item in y_train]) this_x_train = x_train this_x_test = x_test clf.fit(this_x_train, this_y_train) y_test_attitude = clf.predict(this_x_test) this_y_train = np.array([item[5:9] for item in y_train]) this_x_train = x_train clf.fit(this_x_train, this_y_train) y_test_time = clf.predict(this_x_test) this_y_train = np.array([item[9:24] for item in y_train]) this_x_train = x_train clf.fit(this_x_train, this_y_train) y_test_weather = clf.predict(this_x_test) prediction = np.hstack((y_test_attitude, y_test_time, y_test_weather)) ################################# # Normalization # ################################# print "normalization" for i in xrange(len(y_test)): for j in xrange(24): if y_test[i][j] <= 0.01: y_test[i][j] = 0 elif y_test[i][j] >= 0.99: y_test[i][j] = 1 # normalize attitude summary = 0 for j in xrange(0, 5): summary += y_test[i][j] if (summary != 0): for j in xrange(0, 5): y_test[i][j] /= summary # normalize time summary = 0 for j in xrange(5, 9): summary += y_test[i][j] if (summary != 0): for j in xrange(5, 9): y_test[i][j] /= summary ################################# # score # ################################# RMSE = np.sqrt(np.sum(np.array(prediction-y_test)**2)/ (x_test.shape[0]*24.0)) print "RMSE :", RMSE <file_sep>/py/test/test_feature_extraction.py from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import HashingVectorizer corpus = [ "Preach lol! :) RT @mention: #alliwantis this type of weather all the time.. I live for beautiful days like this! #minneapolis", "@mention good morning sunshine","rhode island", "RT @mention: I absolutely love thunderstorms!", "@mention right this weather is something else", "TOP CHOICE --&gt; {link} - Today is awesome!!! Free comic books, lunch with my mama, sunshine & DJ'n ... (via @mention)", "CCAk Trail Update: Archangel Road, Mat-Su - 8:00 PM, Thu May 05, 2011: Snow column beginning to break up especia... {link}" ] counts = [[3, 0, 1], [2, 0, 0], [3, 0, 0], [4, 0, 0], [3, 2, 0], [3, 0, 2] ] # count vectorizer vectorizer = CountVectorizer(min_df=1) X = vectorizer.fit_transform(corpus) X.toarray() # tfidf transformer transformer = TfidfTransformer() tfidf = transformer.fit_transform(counts) tfidf.toarray() # combination : tfidf vectorizer vectorizer = TfidfVectorizer(min_df=1) X = vectorizer.fit_transform(corpus) X.toarray() # hasher : save time and space hv = HashingVectorizer() hv.transform(corpus)
15962301e000191b9ab568c8ac8758ecebd34e47
[ "Markdown", "Python" ]
19
Python
ZHAOTING/WebDataMining_Kaggle
a1401ae70759a43d638d85a785cfabb240503f93
b84b5cbe9b355afc43bb871af91ef3a36ee8248a
refs/heads/master
<file_sep>#pragma once class Part { int points; char shape; int length; public: Part(const int&, const char&, const int length = 1); Part(const Part&); Part() = default; public: int getPoints() const; char getShape() const; int getLength() const; public: void set(const int&); void set(const char&); void setLength(const int); void set(const int&, const char&, const int length = 1); bool changeSnakelength(); };<file_sep>#pragma once #include <iostream> #include <string> #include <conio.h> #include <thread> #include "Snake.h" #include "Menu.h" #include "Player.h" #include "Display.h" #include "Run.h" #include "Record.h" #include "Timer.h" #include "Types.h" // All the global variables and constants will be declared // in this file for use throughout the game typedef const char cc; namespace GAME { extern std::vector <std::string> Field; // The main area where the snake will be moving around in the game extern std::vector <Snake> snake; cc FREE = ' '; cc PAUSE = 'p'; extern unsigned int points; extern Player player; extern Score guest; extern int duration; extern float speed; extern unsigned int moves; } namespace MOVE { cc UP = 'w'; cc DOWN = 's'; cc LEFT = 'a'; cc RIGHT = 'd'; } #include <map> namespace FOOD { extern Types normal, booster; } enum class CHOICE { LOGIN = 1, SIGNUP, GUEST };<file_sep>#pragma once #include "Player.h" void mainMenu(); bool logIn(); bool signUp(); void newGuest(); void toUppercase(std::string&);<file_sep>#pragma once #pragma once #include <string> #include "Score.h" class Record : public Score { std::string name; unsigned int id; public: Record(const std::string& name, const Score& score); Record(const unsigned int& id, const Score& score); std::string getName() const; unsigned int getId() const; void set(const std::string&); void set(const unsigned int&); };<file_sep># Snake-Game A non-graphical ascii based small snake game. It has 5 different difficulty levels based on the speed. It as usual eats stuff and gets longer. In this game, the goal is to get the highest score, with the shortest time and smallest snake. There is a boost food type that increases your score a lot, and shortens the length of the snake. Also it is an account based game: guest or log-in If you log-in, you can get your average scores, your best scores, and compete yourselves with other people
2119a29cb16eb6f4922a9d9ca9e26bcbc5ac8d05
[ "Markdown", "C++" ]
5
C++
shu7bh/Snake-Game
b868eb41d4adc1894aee6debed307f4cbadb81d2
dd5b9b0265fc20d6dd9e4d9358cec6ddfd61e0d7
refs/heads/master
<file_sep>var getUserID=function(){ return 50; } var isUserValid=function(){ console.log(getUserID()); if(getUserID()>30){ return true; }else{ return false; } } if(isUserValid()){ console.log(`User valid`); }else{ console.log(`User not valid`); } <file_sep>let firstNumber = 50; let secondNumber =2; console.log(`I add ${firstNumber}+${secondNumber} and the result is`,firstNumber+secondNumber); console.log(`I add ${firstNumber}-${secondNumber} and the result is`,firstNumber-secondNumber); console.log(`I add ${firstNumber}*${secondNumber} and the result is`,firstNumber*secondNumber); console.log(`I add ${firstNumber}/${secondNumber} and the result is`,firstNumber/secondNumber); console.log(`I add ${firstNumber}%${secondNumber} and the result is`,firstNumber%secondNumber);<file_sep>let average = 6; let studentAverage = 4; console.log(`This student has a greater or equal average required to pass:${studentAverage>=average}`); let missingPoints = average-studentAverage; console.log(`This student is missing ${missingPoints} points to pass`);<file_sep>const iceCreamFlavors=['Dark chocolate','Milk chocolate', 'Cherry','Raspberry','Straeberry','Green tea','Pistachio','Blue Moon','Vanilla','Milk']; const milk=iceCreamFlavors.pop(); const vanilla=iceCreamFlavors.pop(); const blueMoon=iceCreamFlavors.pop(); const pistachio=iceCreamFlavors.pop(); console.log(iceCreamFlavors); console.log(iceCreamFlavors.length); console.log('Removed item:',milk); console.log('Removed item:',vanilla); console.log('Removed item:',blueMoon); console.log('Removed item:',pistachio); <file_sep>const showNumber=function(start,end){ if(!Number.isInteger(start) || !Number.isInteger(end)) { console.log("Please enter only numbers") return } if (start>end){ for(let i=start; i>=end ;i--){ console.log(i); } }else if(start<end){ for(let i=start; i<=end ;i++){ console.log(i); } }else if(start===end){ console.log(`The numbers are the same.`); } } showNumber(0,50); console.log("--------------------") showNumber(50,0); console.log("--------------------") showNumber(100,100); console.log("--------------------") showNumber("100",300); <file_sep>/*Copy and paste the code from exercise 81 Refactor the code to use for instead of do/while*/ let multiplier=9; let a=0; for(a=0;a<=10;a++){ console.log(`9 times ${a} equals ${multiplier*a}`); } <file_sep>const deepThought={ name:'Deep Thought', answerToTheUltimateQuestionOfLife:function(){ return 42; } } console.log(deepThought.answerToTheUltimateQuestionOfLife()); <file_sep>var bestStudentName = 'Leslie'; console.log('The best class student is :' + bestStudentName);<file_sep>/*var str="************"; while(str.length<13){ str-="*"; console.log(str,str.length); }*/ let line=13; let star="*************"; while(line>0){ console.log(star); star=star.slice(0,star.length-1); line--; }<file_sep>const groot={ greet:function(){ console.log('I\'m Groot!!'); }, speak:function(){ console.log('I\'m Groot!!'); } } groot.greet(); groot.speak();<file_sep>const sort=function(number1,number2,number3,highToLow){ let arr =[number1,number2,number3] arr.sort((a,b) => highToLow ? b-a: a-b); return arr; } console.log(sort(10,8,25)); console.log(sort(10,8,25,true));<file_sep>let hours =1; if (hours>5 && hours<=12){ console.log(`Good morning`); }else if (hours>12 && hours<=18){ console.log(`Good Afternoon`); }else if (hours>18 && hours<=22){ console.log(`Good evening`); }else{ console.log(`Good night`); } <file_sep>let first_name = 'Angel'; let last_name ='Leu'; let age = 24; let dateOfBirth = '08/16/1995'; let address = '422 Richard st.'; console.log('First name:', first_name); console.log('Last name:', last_name); console.log('Age:', age); console.log('Birthday:', dateOfBirth); console.log('Address:', address);<file_sep>var str=""; while(str.length<15){ str+="*"; if(str.length%2!==0){ console.log(str,str.length); } }<file_sep>//Use while structure to only sum odd numbers between 0 and 1000 let i = 0; let sum = 0; while(i<1000){ if(i%2!==0){ console.log(`Odd number:${i}`); sum +=i; } i++; }console.log(`sum:${sum}`); <file_sep>var first_name = 'Angel'; var last_name ='Leu'; var age = 24; var dateOfBirth = '08/16/1995'; var address = '422 Richard st.'; console.log(first_name); console.log(last_name); console.log(age); console.log(dateOfBirth); console.log(address);<file_sep>var firstname = 'Angel'; var greeting = 'Welcome'; console.log('%s %s to learn JavaScript with friends',greeting,firstname ); console.log(`${greeting}, ${firstname} to learn `);<file_sep>var age =24; var phone =604685338; var streetName = 'W 41st.'; var streetNumber = 2880; console.log(`I'm ${age} years old`); console.log(`My phone number is: ${phone}`); console.log(`I live on ${streetNumber} ${streetName}`); <file_sep>/*Copy and paste the code from exercise 80 Refactor the code to use for instead of do/while*/ let sum = 0; for(let i =0; i<1000;i++){ if(i%2!==0){ console.log(`Odd number:${i}`); sum +=i; } }console.log(`sum:${sum}`); <file_sep>const numbers=[]; for(var i=0;i<=1000;i++){ numbers.push(i) } const firstEvenNumber=numbers.filter(function(i){ return i%2===0; }); console.log(firstEvenNumber.slice(0,20)); const lastOddNumber=numbers.filter(function(i){ return i%2!==0; }); console.log(lastOddNumber.slice(-10));<file_sep>const first_name = 'Angel'; const last_name ='Leu'; const age = 24; const dateOfBirth = '08/16/1995'; const address = '422 Richard st.'; console.log('First name:', first_name); console.log('Last name:', last_name); console.log('Age:', age); console.log('Birthday:', dateOfBirth); console.log('Address:', address);<file_sep>const revert=function(text){ let test = '' for (let i = text.length -1; i >=0; i--) { //console.log("Acumulator: ", i) //console.log(`Text value when ${i}: ${text[i]}`) test+=text[i]//Concatenate as we iterate } console.log(test); } revert('hello'); revert('happy'); revert('Angel'); const revertWithJSFunctions = (text) => text.split('').reverse().join('') console.log(revertWithJSFunctions('hello')); console.log(revertWithJSFunctions('happy')); console.log(revertWithJSFunctions('Angel')); <file_sep>const average =function(number1,number2,number3,number4,number5){ var average = (number1+number2+number3+number4+number5)/5; console.log('The average is '+average); } average(2,4,10,20,32); average(2,45,10,25,70);<file_sep>/*Copy and paste the code from exercise 67 Refactor the code to use do/while instead of while */ let number = 100; do{ console.log(`Number:${number}`); number--; // number-=1; }while(number>=0) <file_sep>let number = 0; while(number<11){ console.log(`Number: ${number}`); number++; }<file_sep> for(let number = 0; number<1000;number++ ){ if(number<400){ console.log(number); }else{ break; } } <file_sep>let multiplier=9; let a=0; while(a<10){ a++; console.log(`9 times ${a} equals ${multiplier*a}`); } <file_sep>const firstName ='Angelbabe'; const lastName ='Leu'; const charsDiff =firstName.length-lastName.length; console.log(`My first name is ${firstName} and it is ${firstName.length} characters long`); console.log(`My last name is ${lastName} and it is ${lastName.length} characters long`); console.log(`The caracter difference between my first name and last name is ${charsDiff}`); console.log(`My first name is longer than my last name:${firstName.length>lastName.length}`);<file_sep>const iceCreamFlavors=['Dark chocolate','Milk chocolate', 'Cherry','Raspberry','Straeberry','Green tea','Pistachio','Blue Moon','Vanilla','Milk']; const darkChocolate=iceCreamFlavors.shift(); const milkChocolate=iceCreamFlavors.shift(); console.log(iceCreamFlavors); console.log(iceCreamFlavors.length); console.log('Removed item:',darkChocolate); console.log('Removed item:',milkChocolate);<file_sep>/*Copy and paste the code from exercise 75 Refactor the code to use do/while instead of while*/ let f=0; let f1=-1; let f2=1; var i=1; do{f=f1+f2; f1=f2; f2=f; i++; console.log(f); } while(i<=10){ }<file_sep>let firstname = 'Angel'; let greeting = 'Welcome'; console.log(greeting + ' ' + firstname);<file_sep>let city = 'Winnipeg'; let population = 778500; let climate = undefined; let province = 'Manitoba'; let region = true; let living = null; console.log('City', city,typeof(city)); console.log('Population', population,typeof(population)); console.log('CLimate', climate,typeof(climate)); console.log('Province', province,typeof(province)); console.log('Region', region,typeof(region)); console.log('Living', living,typeof(living));<file_sep>const user={ name:'Angel', age:24, phone:88888888, street:'w Broadway', zipcode:'v8r 6h8', married:false } function showUser(user){ console.log(user); } showUser(user);<file_sep>let done = true; let married = false; let logged = false; let likesJS = true; console.log('done',done); console.log('married',married); console.log('logged',logged); console.log('likesJS',likesJS); /*let on = true; let voted = false; let married = false; console.log(on); console.log(voted); console.log(married);*/<file_sep>let message ='3.14 it\'s a great number but 42 it\'s the answer to life.' let pi = parseFloat(message); console.log(pi); let answerToLife = parseInt(message.substr(29,30)); console.log(answerToLife); let result = pi+answerToLife; console.log(`pi:${pi} \nanswerToLife:${answerToLife}`); console.log(result.toString(),'is the result of adding pi and answerToLife'); //different way //using split method to make message into an Array. // //message = message.split(' '); //console.log(message); //const pi = parseFloat(message[0]); //console.log(pi); //let answerToLife = parseInt (message[6]); //console.log(answerToLife);<file_sep>let number = 0; while(number<=100){ if(number%2==0){ console.log(`Even number:${number}`); } number++; } /*var number = 1; while( number <= 100 ) { if( (number % 2) == 0 ) { console.log(number); } number++; }*/<file_sep>const iceCreamFlavors=['Dark chocolate','Milk chocolate', 'Cherry','Raspberry','Strawberry','Green tea']; iceCreamFlavors.unshift('Pistachio','Blue Moon','Vanilla','Milk'); console.log(iceCreamFlavors); console.log(iceCreamFlavors.length);<file_sep>const movies=['<NAME>', '<NAME>','Last Christmas','The glass castle','Gretal and Hansel' ,'Captain America','Iron Man','1917','Sonic','Fantasy island','Parasite']; console.log('First Movie: ',movies[0],' last movie: ',movies[movies.length-1]);<file_sep>const name = 'Angel'; name = 'Pablo'; console.log(name);<file_sep>var first_name = 'Angel'; var last_name ='Leu'; var age = 24; var dateOfBirth = '08/16/1995'; var address = '422 Richard st.';<file_sep>const mutants=['<NAME>','Cyclops','Iceman', 'Angel','Magneto','Beast','Phoenix','Logan','Gambit']; const newMutants=mutants.map(function(mutant){ return mutant.toString(); }) if(mutants.indexOf('Professor X')>-1 && mutants.indexOf('Logan')>-1 && mutants.indexOf('Phoenix')>-1 && mutants.indexOf('Gambit')>-1){ console.log(`<3`,mutants.toString()); /*console.log(`<3`,'Professor X'); console.log(`<3`,'Logan'); console.log(`<3`,'Phoenix'); console.log(`<3`,'Gambit');*/ } console.log(newMutants.toString()); <file_sep>/*Create a new index134.js file Define a numbers array Assign values between 1 and 1000 Iterate over the numbers array and add all numbers items On each iteration show the partial result 1 3 6 ... so on If the final result equals 500500 then show the following output: Good job!!! Else show: Take a look to see if something is wrong*/ const numbers=[]; let sum=0; for(var i=0; i<=1000;i++){ numbers.push(i); sum += i; } if(sum===500500){ console.log(`Good job!!!`); }else{ console.log(`Take a look to see if something is wrong`); } <file_sep>const ingredients=['Pork','Pomato','Chicken','Lettuce','Beef','Carrots','Cucumber']; const vegetarian = [] for(var ingredient of ingredients) { if(['Tomato','Lettuce', 'Carrots','Cucumber'].includes(ingredient)) { vegetarian.push(ingredient) } } console.log(ingredients); console.log(vegetarian);<file_sep>const playerName = '<NAME>'; const teams ='New Jersey Devils, New York Rangers, Winnipeg jets & Pittsburgh penguins'; const message = 'Winnipeg is the best Canadian city, Go Winnipeg'; const result1 = playerName.slice(0,-5); console.log(result1); const result2 = teams.slice(46,-22); console.log(result2); const result3 = message.slice(12,-26); console.log(result3); const result4 = message.slice(34,-9); console.log(result4); const template = result1.slice(0,13).toUpperCase()+result1.slice(-3)+' '+result3+result2.charAt(0).toUpperCase()+result2.slice(1)+' player'+result4+' '+ result2.charAt(0).toUpperCase()+result2.slice(1)+'!!'; console.log(template); <file_sep> for(let number=10000;number>0;number--){ if(number%10===0){ console.log(`**${number}**`); } else{ console.log(number); } }<file_sep>const getHexaColor=function(webColor){ switch(webColor){ case 'white': return '#FFFFF'; break; case 'black': return '#00000'; break; case 'blue': return '#0b24fb'; break; case 'green': return '#0e7e12'; break; case 'yellow': return '#fffd38'; break; case 'pink': return '#fec1cc'; break; } } console.log(getHexaColor('white')); console.log(getHexaColor('black')); console.log(getHexaColor('blue')); console.log(getHexaColor('green')); console.log(getHexaColor('yellow')); console.log(getHexaColor('pink')); <file_sep>const superhero={ name:'batman', secretName:'Bruce', sidekick:['Robin', 'Alfred', 'Gordon'], strength:70, } console.log(superhero.name, superhero.secretName, superhero.sidekick, superhero.strength); console.log('--------------------------'); superhero.speed=80; console.log(superhero); <file_sep>const getShapePerimeter=function(base,height){ if((base+height)*2>100){ console.log('The perimeter is too big'); return }else { console.log('The perimeter is fine'); } if(base===height){ return console.log(base*4,"is the shape perimeter"); }else if (base!==height){ return console.log(base*2+height*2,"is the shape of perimeter"); } } getShapePerimeter(100,5); console.log("-------------------") getShapePerimeter(50,4); console.log("-------------------") getShapePerimeter(55,60); console.log("-------------------") getShapePerimeter(5,5); console.log("-------------------")<file_sep>/*Copy and paste the code from exercise 74 Refactor the code to use do/while instead of while*/ var str=""; do{ str+="*"; if(str.length%2!==0){ console.log(str,str.length); } } while(str.length<15){ }<file_sep>let side =5; let area = side*side; console.log(`The side of square is ${side}, and the area of square is ${area}`);<file_sep>/*Copy and paste the code from exercise 76 Refactor the code to use for instead of do/while*/ let number = 0; for(let number =0; number<11; number++){ console.log(`Number: ${number}`); } <file_sep>let income =1000; let revenue =600; let taxes =500; console.log(`Income Objective: ${income>=800}`); console.log(`taxes Objective:${taxes<400}`); console.log(`Bonus Objective:${revenue===600}`);<file_sep>const user={ userName:'batman', password:'<PASSWORD>!' } console.log('First output:',user.userName,user.password); user.userName=user.userName.replace('b','B') user.password=user.password.replace('<PASSWORD>',' ') console.log('Second output:',user); <file_sep>/*Copy and paste the code from exercise 82 Refactor the code to use for instead of do/while*/ var str=""; for(str="*";str.length<15;str+="*"){ console.log(str,str.length); } <file_sep>let firstNumber =10; let secondNumber =20; console.log(`Both variables have the same value: ${firstNumber==secondNumber}`); console.log(`Both variables don't have the same value:${firstNumber!==secondNumber}`); <file_sep>const iceCreamFlavors=['Dark chocolate','Milk chocolate', 'Cherry','Raspberry','Straeberry','Green tea','Pistachio','Blue Moon','Vanilla','Milk']; for(var i=0;i<iceCreamFlavors.length;i++){ console.log(iceCreamFlavors[i]); } <file_sep>var first_name, last_name, age, dateOfBirth, address; first_name ='Angel'; last_name = 'Leu'; age = 24; dateOfBirth = '08/16/1995'; address = '422 Richard st.';<file_sep>/* Copy and paste the code from exercise 84 Refactor the code to use for instead of do/while*/ var str=""; for(str="";str.length<15;str+="*"){ if(str.length%2!==0){ console.log(str,str.length); } }<file_sep>/* \n New Line \t Tab \r Carriage Return \' Single quote \" Double quote \\ Backslash */ let message = 'Escaping backslash \\ as string content'; console.log(message); // we show \ as string content message = 'I love to have coffee at Gianu\'s'; console.log(message); message = "Jets are \"the\" best NHL team"; console.log(message);<file_sep>let userName='pepe2017'; let password='<PASSWORD>'; let message =(userName==='pepe2017'&& password ==='<PASSWORD>')?'Logged in user, show user home page':'Sorry, there has been a problem, please try it again.'; console.log(message);<file_sep>var first_name = 'Angel'; var last_name ='Leu'; var age = 24; var dateOfBirth = '08/16/1995'; var address = '422 Richard st.'; console.log('First name:', first_name); console.log('Last name:', last_name); console.log('Age:', age); console.log('Birthday:', dateOfBirth); console.log('Address:', address);<file_sep>let username = 'Angelbabe'; console.log('username',username);<file_sep>/*Copy and paste the code from exercise 85 Refactor the code to use for instead of do/while*/ let f=0; let f1=-1; let f2=1; var i=1; for(i=1;i<=10;i++){ f=f1+f2; f1=f2; f2=f; console.log(f); } <file_sep>let monthNumber=15; let monthDays=null; let monthName =null; switch(monthNumber){ case 1: monthName ='January'; monthDays ='31days'; break; case 2: monthName ='February'; monthDays ='29days in leap years'; break; case 3: monthName ='March'; monthDays ='31days'; break; case 4: monthName ='April'; monthDays ='30days'; break; case 5: monthName ='May'; monthDays ='31days'; break; case 6: monthName ='June'; monthDays ='30days'; break; case 7: monthName ='July'; monthDays ='31days'; break; case 8: monthName ='August'; monthDays ='31days'; break; case 9: monthName ='September'; monthDays ='30days'; break; case 10: monthName ='October'; monthDays ='31days'; break; case 11: monthName ='November'; monthDays ='30days'; break; case 12: monthName ='December'; monthDays ='31days'; break; default: monthName ='It is not'; monthDays ='error monthdays'; } console.log(`${monthName} is the selected month and has ${monthDays}`);<file_sep>const user={ username:null, password:<PASSWORD>, greet:function(){ if(this.username!==null){ console.log(`Hello, I'm user ${this.username}`); }else{ console.log(`please assign a username value`); } }, updatePassword:function(password){ this.password = password }, updateUsername:function(user){ this.username = user } } user.greet(); user.updateUsername('Angel') user.updatePassword('<PASSWORD>') user.greet(); /*const user = { username: null, passowrd: null, greet: function() { this.username !== null ? console.log(`Hello, I'm user ${this.username}`) : console.log('Please assign a username value'); }, updaterUsername : function(userName) { this.username = userName; }, updatePassword : function(passWord) { this.passowrd = <PASSWORD>; } } user.greet(); user.updaterUsername('Sarah'); user.updatePassword('<PASSWORD>'); user.greet(); */<file_sep>let times=1; for(let number=0;number<1000;number++){ if(times>20){ break; } else if(number%2==0){ console.log(number); times++; } }<file_sep>for(let number=0;number<=1000;number+=10){ console.log(number); }<file_sep>var first_name; first_name = 'Angel'; var last_name; last_name = 'Leu'; var age; age = 24; var dateOfBirth; dateOfBirth = '08/16/1995'; var address; address = '422 Richard st.';<file_sep>let superHeroName = 'Batman'; let name = '<NAME>'; let fly = false; let hasBatmobile = true; let life = undefined; let freeTime = null; console.log('Super hero name:',superHeroName,typeof(superHeroName)); console.log('Name:',name,typeof(name)); console.log('Fly',fly,typeof(fly)); console.log('Has bat mobile',hasBatmobile,typeof(hasBatmobile)); console.log('life',life,typeof(life)); console.log('free time',freeTime,typeof(freeTime)); <file_sep>let message = 'Hello, I am Angel, and I make Youtube videos.'; console.log(message);<file_sep>var name=""; var showName=function(name){ console.log(`===========`); console.log(`= ${name} =`); console.log(`===========`); } showName('Angel'); showName('Leslie');<file_sep>/*Copy and paste the code from exercise 70 Refactor the code to use do/while instead of while*/ let i = 0; let sum = 0; do{ if(i%2!==0){ console.log(`Odd number:${i}`); sum +=i; } i++; } while(i<1000){ console.log(`sum:${sum}`); }<file_sep>const arithmetic ={ add:function(number1,number2){ if(!Number.isInteger(number1) || !Number.isInteger(number2)) { console.log("Please enter only numbers") return number1+number2; } }, subtract:function(number1,number2){ if(!Number.isInteger(number1) || !Number.isInteger(number2)) { console.log("Please enter only numbers") return number1-number2; } }, multiply:function(number1,number2){ if(!Number.isInteger(number1) || !Number.isInteger(number2)) { console.log("Please enter only numbers") return number1*number2; } }, divide:function(number1,number2){ if(!Number.isInteger(number1) || !Number.isInteger(number2)) { console.log("Please enter only numbers") return number1/number2; } }, remainder:function(number1,number2){ if(!Number.isInteger(number1) || !Number.isInteger(number2)) { console.log("Please enter only numbers") return number1%number2; } } } console.log(arithmetic.add('2',10)); console.log(arithmetic.subtract('10',5)); console.log(arithmetic.multiply(3,100)); console.log(arithmetic.divide(40,2)); console.log(arithmetic.remainder(20,2));<file_sep>/*Use while structure to sum numbers between 0 and 1000 Show the partial result as output too*/ let number=0; let sum=0; while(number<1000){ number++; sum+= number; console.log(`0+...+1000=:${sum}`); }<file_sep>const getLongerText=function(text1,text2){ /*if(text1.length>text2.length){ return text1 }else{ return text2 } */ return text1.length>text2.length ? text1 : text2; } console.log(getLongerText('sweetijfskde','catabnfrr')); console.log(getLongerText('sweetifodsjfskde','cnfrr')); console.log(getLongerText('ekje','catabnfrr')); console.log(getLongerText('swfldkflsm.,vde','catabnffsefrr'));<file_sep>const femaleStudents=['Angel','Aurora','Jackie','Sunny','Anna']; const maleStudents=['Jack','Frank','Tony','Steve','Henry']; const Students=['Angel','Aurora','Jackie','Sunny','Anna','Jack','Frank','Tony','Steve','Henry']; console.log(Students.sort()); console.log(femaleStudents.indexOf('Jackie'));<file_sep>const mutants=['<NAME>','Cyclops', 'Iceman','Angel','Beast','Phoenix','Logan',/*'Gambits'*/]; console.log(mutants.indexOf('Gambits')); if(mutants.indexOf('<NAME>')>-1 && mutants.indexOf('Logan')>-1){ console.log(`We love X-Men`); } if(mutants.indexOf('Gambits')===-1){ console.log(`X-Men sucks`); }<file_sep>const userAndPassword ='<PASSWORD>'; const userName =userAndPassword.substr(0,10); const password =<PASSWORD>And<PASSWORD>.substr(11); console.log(`The user ${userName} has ${password} as password`); <file_sep>/*Create a new index159.js Define a jeep variable and assign a literal object Add the object a brand property and assign the following string value: Jeep Wrangler Add the object a price property and assign the following numeric value: 34000 Show the following message as output using object dynamic properties (use variables or string literals)*/ //The %brand% is $ %price% const jeep={ brand:'Jeep Wrangler', price:34000, } console.log(`This ${jeep['brand']} is ${jeep['price']}`);<file_sep>/*Create a new index163.js Define a add function This function will return a numeric value with result of adding all the numbers that we pass as parameter As we don't know how many parameters we are going to get we need to use a dynamic way to add this functionality Call the add function passing 5 numbers and show the result as output Call the add function passing 10 numbers and show the result as output*/ const add = function(number){ var result=0; for(var i=0; i<arguments.length;i++){ result = result+arguments[i]; } return result; } console.log(add(1,2,6,1,5)); console.log(add(10,20,30,40,50,60,70,80,90,100));<file_sep>const user={ name:'Angelbabe', lastName:'Leu', age:18, hobby:['Movie','music','swim'], married:false, fruit:'strawberry', drinkAlcohol:true, love:'male', city:'Vancouver', object:{} } const myObject={ name:'Angelbabe', lastName:'Leu', age:18, hobby:['Movie','music','swim'], married:false, } myObject.name='Angel'; myObject.lastName='Tu'; myObject.age=25; myObject.hobby=['eat','dance','jogging']; myObject.married=true; console.log('user:',user); console.log('----------------------'); console.log('myObject:',myObject);<file_sep>var day = 27; var month =1; var year =2020; console.log(`${day}/${month}/${year}`);<file_sep>/*Copy and paste the code from exercise 78 Refactor the code to use for instead of do/while*/ for(let number = 0;number<=100;number++){ if(number%2==0){ console.log(`Even number:${number}`); } } <file_sep>/*Copy and paste the code from exercise 69 Refactor the code to use do/while instead of while*/ let number=0; let sum=0; do{ number++; sum+= number; console.log(`0+...+1000=:${sum}`); } while(number<1000)
d2b716c9ec3843f8bc649f20a25ff91bcb9620c7
[ "JavaScript" ]
84
JavaScript
Angelleu/JSpractices
aa1ca79ca0fcc0785a673806dc4464c614196dc7
01f4f3b7a47f49825176d4751daf3723f30e1db5
refs/heads/master
<repo_name>kattymay/Bamazon<file_sep>/README.md # Bamazon Bamazon is an application that allows users to chose a product to purchase, as well as the quantity of the item they'd like to buy. The app then gives the user a shopping cart total. The products table should have each of the following columns: * item_id (unique id for each product) * product_name (Name of product) * department_name * price (cost to customer) * stock_quantity (how much of the product is available in stores) The app should then prompt users with two messages. The first should ask them the ID of the product they would like to buy. The second message should ask how many units of the product they would like to buy. Once the customer has placed the order, this application should check if your store has enough of the product to meet the customer's request. If not, the app should log the phrase "Not enough in stock!", and then prevent the order from going through. However, if the does have enough of the product, it will fulfill the customer's order. This means updating the SQL database to reflect the remaining quantity. Once the update goes through, it will show the customer the total cost of their purchase. ![Bamazon](/images/bamazon.png) Format: ![Alt Text](url)<file_sep>/bamazon_db.sql DROP DATABASE IF EXISTS bamazon_db; CREATE DATABASE bamazon_db; USE bamazon_db; CREATE TABLE products( item_id INTEGER(10) NOT NULL AUTO_INCREMENT, product_name VARCHAR(30) NOT NULL, department_name VARCHAR(30) NOT NULL, price DECIMAL(10, 2), stock_quantity INTEGER(10), PRIMARY KEY (item_id) ); SELECT * FROM products; USE bamazon_db; INSERT INTO products(product_name, department_name, price, stock_quantity) VALUE ("rake", "gardening", 10.29, 50); INSERT INTO products(product_name, department_name, price, stock_quantity) VALUE ("watering can", "gardening", 7.59, 50); INSERT INTO products(product_name, department_name, price, stock_quantity) VALUE ("pack blackberry seeds", "gardening", 3.11, 50); INSERT INTO products(product_name, department_name, price, stock_quantity) VALUE ("pack blueberry seeds", "gardening", 3.11, 100); INSERT INTO products(product_name, department_name, price, stock_quantity) VALUE ("pack strawberry seeds", "gardening", 3.11, 50); INSERT INTO products(product_name, department_name, price, stock_quantity) VALUE ("planter's box", "gardening", 12.29, 50); INSERT INTO products(product_name, department_name, price, stock_quantity) VALUE ("potting mix", "gardening", 22.29, 50); INSERT INTO products(product_name, department_name, price, stock_quantity) VALUE ("fertilizer", "gardening", 15.59, 50); INSERT INTO products(product_name, department_name, price, stock_quantity) VALUE ("bird bath", "gardening", 24.29, 50); INSERT INTO products(product_name, department_name, price, stock_quantity) VALUE ("shovel", "gardening", 12.29, 50);
4e463989dcf2507bbfbd9baa1847f6fc640caa24
[ "Markdown", "SQL" ]
2
Markdown
kattymay/Bamazon
8fb593c0e37b85a86bd15d427b80cc11dc7e18b6
a4507956d527f9bb00531fb6597b11b6edd59d76
refs/heads/main
<repo_name>Bartucz/JsAlapokGit<file_sep>/js.js /*segédfüggvények*/ function ID(nev) { return document.getElementById(nev); } function EvLis(item, event, func) { item.addEventListener(event, func, false); } function beker() { var a = Number(ID("a").value); var b = Number(ID("b").value); var osszeg = a + b; if (isNaN(osszeg) || ID("a").value === "" || ID("a").value === "") { ID("szamol").style.color = "lightgrey"; ID("szamol").title = "Számokat adj meg"; } else { ID("szamol").style.color = "black"; ID("szamol").title = "Kattints"; EvLis(ID("szamol"), "click", function(){ szamol(osszeg); }); } EvLis(ID("a"),"input",beker); EvLis(ID("b"),"input",beker); } function szamol(ossz){ ID("szoveg").innerHTML = "Az összeg: <span style='color: red;'>" + ossz + "</span>"; } function szamolFormaz() { ID("szamol").style.color = "red"; ID("szamol").style.border = "1px solid blue"; } function szamolFormazLevesz() { ID("szamol").style.color = "initial"; ID("szamol").style.border = "none"; } function inputFormazas(x) { ID(x).classList.add("bevitelimezo"); } function init() { var szamolGomb = ID("szamol"); beker(); /*document.getElementById("uzenet").innerHTML="<span style='color: red;'>Hello világ!</span>";*/ ID("uzenet").innerHTML = "<span style='color: red;'>Hello világ!</span>"; /*document.getElementById("szamol").addEventListener("click", szamol, false); document.getElementById("szamol").addEventListener("mouseover", szamolFormaz, false); document.getElementById("szamol").addEventListener("mouseover", szamolFormazLevesz, false);*/ // szamolGomb.addEventListener("click", szamol, false); // EvLis(szamolGomb, "click", szamol); // szamolGomb.addEventListener("mouseover", szamolFormaz, false); EvLis(szamolGomb, "mouseover", szamolFormaz); // szamolGomb.addEventListener("mouseout", szamolFormazLevesz, false); EvLis(szamolGomb, "mouseout", szamolFormazLevesz); // ID("a").addEventListener("click",function(){inputFormazas("a");}); EvLis(ID("a"), "click", function () { inputFormazas("a"); }); //1. document.getElementById("b").addEventListener("click",function(){inputFormazas("b");}); //2. ID("b").addEventListener("click",function(){inputFormazas("b");}); /*3.*/ EvLis(ID("b"), "click", function () { inputFormazas("b"); }); } window.addEventListener("load", init, false);
253c4dee27645bdc5f9d7d6f5e23bbb5e9069885
[ "JavaScript" ]
1
JavaScript
Bartucz/JsAlapokGit
0a1732a28ecbd3495f826b92aff834af1090de1e
f1c61bfe1910b116744592b648f133d8579907ee
refs/heads/master
<repo_name>dr0l3/DataProcessing<file_sep>/src/RandomTest/SerializeClassifierToJsonTEst.java package RandomTest; import ArffFile.CompleteFeatureFileGenerator; import Core.BiasConfiguration; import Core.ClassifierType; import weka.classifiers.Classifier; import weka.classifiers.meta.FilteredClassifier; import weka.core.Instance; import weka.core.Instances; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Remove; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; /** * Created by Rune on 23-04-2016. */ public class SerializeClassifierToJsonTEst { private static FilteredClassifier eventClassifier; public static void main(String[] args) { try { eventClassifier = (FilteredClassifier) weka.core.SerializationHelper.read("D:\\Projekter\\MoshiJSonAdapterTesting\\assets\\1461324051401_filteredclassifierevent_sniffer.model"); Filter copiedFilter = null; System.out.println(eventClassifier.getFilter().getClass().getSimpleName()); if(eventClassifier.getFilter() instanceof Remove){ Remove temp = (Remove) eventClassifier.getFilter(); System.out.println(temp.getAttributeIndices()); Remove newFilter = new Remove(); String[] options = new String[2]; options[0] = "-R"; options[1] = temp.getAttributeIndices(); newFilter.setOptions(options); System.out.println((Arrays.toString(options))); copiedFilter = newFilter; } ClassifierType type_of_classifer = ClassifierType.EVENT_SNIFFER; System.out.println("Importing data"); String fromLocation = "D:\\Dropbox\\Thesis\\Data\\RawDataProx"; //String fromLocation = "D:\\Dropbox\\Thesis\\Data\\RawData"; String toLocation = "D:\\Dropbox\\Thesis\\Data\\CompleteFeatureFiles\\"; double window_size_seconds = 3; BiasConfiguration biasForIT119 = new BiasConfiguration( 0.005f, -0.030f, -0.089f, -0.011f, 0.024f, 0.083f); BiasConfiguration megaBias = new BiasConfiguration(100, 100, 100, 100, 100, 100); BiasConfiguration nullBias = new BiasConfiguration(0, 0 , 0, 0, 0, 0); List<String> featureFileURIs = CompleteFeatureFileGenerator.createCompleteFeatureFileWithProximitySeparateFile( fromLocation,toLocation, window_size_seconds, type_of_classifer, biasForIT119); //load in all the different data sets and set weights appropriately List<Instances> all_data_inp = new ArrayList<>(); for (String file : featureFileURIs) { Instances data = CompleteFeatureFileGenerator.getInstances(file); /*for (Instance instance : data) { if(file.contains("hand") && instance.classValue() == 0 && instance.value(instance.numAttributes()-2)> 2){ instance.setWeight(1.0); } else { instance.setWeight(0.2); } }*/ all_data_inp.add(data); } Instances alldata = new Instances(all_data_inp.get(0)); for (int i = 1; i < all_data_inp.size(); i++) { for (Instance instance : all_data_inp.get(i)) { alldata.add(instance); } } Random random = new Random(); List<Integer> indexes = new ArrayList<>(); for (int i = 0; i < 10 ; i++) { int next = random.nextInt(alldata.size()-1); indexes.add(next); } for (Integer index : indexes) { System.out.println(eventClassifier.classifyInstance(alldata.get(index))); } System.out.println(); eventClassifier.setFilter(copiedFilter); eventClassifier.getFilter().setInputFormat(alldata); for (Integer index : indexes) { System.out.println(eventClassifier.classifyInstance(alldata.get(index))); } } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/src/Core/SensorEventRecord.java package Core; /** * Created by Rune on 30-03-2016. */ public class SensorEventRecord { private float[] acceleration; private float[] gravity; private float[] rotation; private ProximityValue proximity; private long timestamp; public SensorEventRecord(long timestamp, float[] proximity, float[] gravity, float[] acceleration) { this.timestamp = timestamp; float prox_temp = proximity[0]; this.proximity = (prox_temp > 5)? ProximityValue.FAR : ProximityValue.NEAR; this.gravity = gravity; this.acceleration = acceleration; } public SensorEventRecord(float[] acceleration, float[] gravity, ProximityValue proximity, long timestamp) { this.acceleration = acceleration; this.gravity = gravity; this.proximity = proximity; this.timestamp = timestamp; } public SensorEventRecord(float[] acceleration, float[] gravity, float[] rotation, long timestamp) { this.acceleration = acceleration; this.gravity = gravity; this.rotation = rotation; this.timestamp = timestamp; } public SensorEventRecord(float[] acceleration, float[] gravity, long timestamp) { this.acceleration = acceleration; this.gravity = gravity; this.timestamp = timestamp; } public float[] getAcceleration() { return acceleration; } public long getTimestamp() { return timestamp; } public float[] getGravity() { return gravity; } public float[] getRotation() { return rotation; } public ProximityValue getProximity() { return proximity; } public void applyBias(BiasConfiguration bias){ if (gravity[0] < 0) acceleration[0] = acceleration[0] - (gravity[0] * bias.getBias_x_neg()); else acceleration[0] = acceleration[0] - (gravity[0] * bias.getBias_x_pos()); if (gravity[1] < 0) acceleration[1] = acceleration[1] - (gravity[1] * bias.getBias_y_neg()); else acceleration[1] = acceleration[1] - (gravity[1] * bias.getBias_y_pos()); if (gravity[2] < 0) acceleration[2] = acceleration[2] - (gravity[2] * bias.getBias_z_neg()); else acceleration[2] = acceleration[2] - (gravity[2] * bias.getBias_z_pos()); } } <file_sep>/src/Core/BiasConfiguration.java package Core; /** * Created by Rune on 19-04-2016. */ public class BiasConfiguration { private float bias_x_pos; private float bias_y_pos; private float bias_z_pos; private float bias_x_neg; private float bias_y_neg; private float bias_z_neg; public BiasConfiguration(float bias_x_pos, float bias_y_pos, float bias_z_pos, float bias_x_neg, float bias_y_neg, float bias_z_neg) { this.bias_x_pos = bias_x_pos; this.bias_y_pos = bias_y_pos; this.bias_z_pos = bias_z_pos; this.bias_x_neg = bias_x_neg; this.bias_y_neg = bias_y_neg; this.bias_z_neg = bias_z_neg; } public float getBias_x_pos() { return bias_x_pos; } public void setBias_x_pos(float bias_x_pos) { this.bias_x_pos = bias_x_pos; } public float getBias_y_pos() { return bias_y_pos; } public void setBias_y_pos(float bias_y_pos) { this.bias_y_pos = bias_y_pos; } public float getBias_z_pos() { return bias_z_pos; } public void setBias_z_pos(float bias_z_pos) { this.bias_z_pos = bias_z_pos; } public float getBias_x_neg() { return bias_x_neg; } public void setBias_x_neg(float bias_x_neg) { this.bias_x_neg = bias_x_neg; } public float getBias_y_neg() { return bias_y_neg; } public void setBias_y_neg(float bias_y_neg) { this.bias_y_neg = bias_y_neg; } public float getBias_z_neg() { return bias_z_neg; } public void setBias_z_neg(float bias_z_neg) { this.bias_z_neg = bias_z_neg; } @Override public String toString() { return "BiasConfiguration{" + "bias_x_pos=" + bias_x_pos + ", bias_y_pos=" + bias_y_pos + ", bias_z_pos=" + bias_z_pos + ", bias_x_neg=" + bias_x_neg + ", bias_y_neg=" + bias_y_neg + ", bias_z_neg=" + bias_z_neg + '}'; } } <file_sep>/src/Pipeline/FilteredClassifierPipeline.java package Pipeline; import ArffFile.CompleteFeatureFileGenerator; import Core.*; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import weka.classifiers.bayes.NaiveBayes; import weka.classifiers.functions.LibSVM; import weka.classifiers.functions.Logistic; import weka.classifiers.meta.FilteredClassifier; import weka.classifiers.meta.Stacking; import weka.classifiers.trees.RandomForest; import weka.core.*; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Remove; import weka.filters.unsupervised.attribute.RemoveByName; import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.util.*; import java.util.concurrent.*; /** * Created by Rune on 28-03-2016. */ public class FilteredClassifierPipeline { private static final int CROSS_VALIDATION_NUMBER_OF_FOLDS = 10; private static final int PQ_CAPACITY_FOR_SVM = 3; public static void main(String[] args) throws Exception { //Declare the threadpool ExecutorService executorService = Executors.newFixedThreadPool(8); /** * PARAMETERS */ ClassifierType type_of_classifer = ClassifierType.SIT_STAND_CLASSIFIER; System.out.println("Importing data"); String fromLocation = "D:\\Dropbox\\Thesis\\Data\\RawDataProx"; //String fromLocation = "D:\\Dropbox\\Thesis\\Data\\RawData"; String toLocation = "D:\\Dropbox\\Thesis\\Data\\CompleteFeatureFiles\\"; double window_size_seconds = 3; BiasConfiguration biasForIT119 = new BiasConfiguration( 0.005f, -0.030f, -0.089f, -0.011f, 0.024f, 0.083f); BiasConfiguration megaBias = new BiasConfiguration(100, 100, 100, 100, 100, 100); BiasConfiguration nullBias = new BiasConfiguration(0, 0 , 0, 0, 0, 0); String featureFileURI = CompleteFeatureFileGenerator.createCompleteFeatureFileWithProximity( fromLocation,toLocation, window_size_seconds, type_of_classifer, biasForIT119); List<String> featureFileURIs = CompleteFeatureFileGenerator.createCompleteFeatureFileWithProximitySeparateFile( fromLocation,toLocation, window_size_seconds, type_of_classifer, biasForIT119); //load in all the different data sets and set weights appropriately List<Instances> all_data_inp = new ArrayList<>(); for (String file : featureFileURIs) { Instances data = CompleteFeatureFileGenerator.getInstances(file); /*for (Instance instance : data) { if(file.contains("hand") && instance.classValue() == 0 && instance.value(instance.numAttributes()-2)> 2){ instance.setWeight(1.0); } else { instance.setWeight(0.2); } }*/ all_data_inp.add(data); } Instances alldata = new Instances(all_data_inp.get(0)); for (int i = 1; i < all_data_inp.size(); i++) { for (Instance instance : all_data_inp.get(i)) { alldata.add(instance); } } //Create filters for desired subsets ArrayList<Filter> listOfFilters = new ArrayList<>(); // listOfFilters.add(createFilterInclusive(alldata, new String[]{"ECDF_RAW", "class"})); // listOfFilters.add(createFilterInclusive(alldata, new String[]{"ECDF_RAW","START_ORIENTATION","END_ORIENTATION","PROXIMITY", "class"})); // listOfFilters.add(createFilterInclusive(alldata, new String[]{"ECDF_DISC", "class"})); // listOfFilters.add(createFilterInclusive(alldata, new String[]{"ECDF_DISC", "START_ORIENTATION","END_ORIENTATION","PROXIMITY", "class"})); listOfFilters.add(createFilterInclusive(alldata, new String[]{"ECDF_UP", "ECDF_REST", "class"})); listOfFilters.add(createFilterInclusive(alldata, new String[]{"ECDF_UP", "ECDF_REST","START_ORIENTATION","END_ORIENTATION","PROXIMITY", "class"})); // listOfFilters.add(createFilterInclusive(alldata, new String[]{"ECDF_UP", "ECDF_RAW_Y", "class"})); // listOfFilters.add(createFilterInclusive(alldata, new String[]{"ECDF_UP", "ECDF_RAW_Y", "START_ORIENTATION","END_ORIENTATION","PROXIMITY", "class"})); // listOfFilters.add(createFilterInclusive(alldata, new String[]{"TIMED_VERTICAL_BIN","UpAcc_Mean", "class"})); // listOfFilters.add(createFilterInclusive(alldata, new String[]{"ORIENTATION", "PROXIMITY","class"})); listOfFilters.add(createFilterInclusive(alldata, new String[]{"ZERO_CROSSINGS_VERTICAL", "PURITY", "VERTICAL_POSITIVE_ACCELERATION", "VERTICAL_NEGATIVE_ACCELERATION","PROXIMITY", "class"})); listOfFilters.add(createFilterInclusive(alldata, new String[]{"ZERO_CROSSINGS_VERTICAL", "PURITY", "VERTICAL_POSITIVE_ACCELERATION", "VERTICAL_NEGATIVE_ACCELERATION", "START_ORIENTATION","END_ORIENTATION","PROXIMITY", "class"})); // listOfFilters.add(createFilterInclusive(alldata, new String[]{"NUMBER_OF_RAW_Z_TAPS", "class"})); // listOfFilters.add(createFilterExclusive(alldata, new String[]{"ECDF","ORIENTATION","TIMED_VERTICAL", "ZERO_CROSSING", "PURITY", "VERTICAL_POSITIVE_ACCELERATION", "VERTICAL_NEGATIVE_ACCELERATION"})); //Train individual classifiers System.out.println("Training individual classifiers"); ArrayList<ClassifierEvalDescriptionTriplet> individualClassifiers = trainIndividualClassifiers(executorService, alldata, listOfFilters,type_of_classifer); executorService.shutdown(); Collections.sort(individualClassifiers, new ClassifierEvalDescriptionTripletComparator()); //Create folder to hold all the new classifiers String folderPath = "D:\\Dropbox\\Thesis\\Data\\Output"+System.currentTimeMillis()+"\\"; //noinspection ResultOfMethodCallIgnored new File(folderPath).mkdir(); //export individual classifiers in case something goes wrong with the ensembles exportClassifiers(individualClassifiers.subList(0,20), folderPath, type_of_classifer); //get the 3 best classifiers Classifier[] the3BestClassifiers = new Classifier[3]; for (int i = 0; i < 3; i++) { the3BestClassifiers[i] = individualClassifiers.get(i).getClassifier(); } //get the 5 best classifiers Classifier[] the5BestClassifiers = new Classifier[5]; for (int i = 0; i < 5; i++) { the5BestClassifiers[i] = individualClassifiers.get(i).getClassifier(); } //get the 9 best classifiers Classifier[] the9BestClassifiers = new Classifier[9]; for (int i = 0; i < 9; i++) { the9BestClassifiers[i] = individualClassifiers.get(i).getClassifier(); } //Combine the individual classifiers System.out.println("Training combined classifiers"); /*ArrayList<ClassifierEvalDescriptionTriplet> combinedClassifiers = trainCombinedClassifiers(alldata, the3BestClassifiers, the5BestClassifiers, the9BestClassifiers); Collections.sort(combinedClassifiers, new ClassifierEvalDescriptionTripletComparator()); //export the combined classifiers exportClassifiers(combinedClassifiers, folderPath);*/ System.out.println("All done"); } private static ArrayList<ClassifierEvalDescriptionTriplet> trainCombinedClassifiers(Instances alldata, Classifier[] the3BestClassifiers, Classifier[] the5BestClassifiers, Classifier[] the9BestClassifiers) throws Exception { ArrayList<ClassifierEvalDescriptionTriplet> metaClassifiers = new ArrayList<>(); double ridge = 1; int cap = 10; for (int i = 0; i < cap; i++) { long start = System.currentTimeMillis(); metaClassifiers.addAll(stackingLogisticExperiment(alldata,the3BestClassifiers.clone(), ridge)); metaClassifiers.addAll(stackingLogisticExperiment(alldata,the5BestClassifiers.clone(), ridge)); // metaClassifiers.addAll(stackingLogisticExperiment(alldata,the9BestClassifiers.clone(), ridge)); ridge = ridge/10; long end = System.currentTimeMillis(); System.out.println("Meta iteration + " +(i+1) + " of "+cap+" done. This iteration took "+((end-start)/1000)+ " seconds"); } return metaClassifiers; } private static ArrayList<ClassifierEvalDescriptionTriplet> trainIndividualClassifiers(ExecutorService executorService, Instances alldata, List<Filter> listOfFilters, ClassifierType type_of_classifer) { ArrayList<ClassifierEvalDescriptionTriplet> individualClassifiers = new ArrayList<>(); ArrayList<Callable<ArrayList<ClassifierEvalDescriptionTriplet>>> individualJobs = new ArrayList<>(); for (Filter filter : listOfFilters) { // individualJobs.add(new LogisticGridSearch(alldata,filter, CROSS_VALIDATION_NUMBER_OF_FOLDS)); //individualJobs.add(new LibSVMGridSearch(alldata,new SelectedTag(LibSVM.KERNELTYPE_POLYNOMIAL, LibSVM.TAGS_KERNELTYPE),PQ_CAPACITY_FOR_SVM,filter,CROSS_VALIDATION_NUMBER_OF_FOLDS)); individualJobs.add(new LibSVMGridSearch(alldata,type_of_classifer,new SelectedTag(LibSVM.KERNELTYPE_RBF, LibSVM.TAGS_KERNELTYPE),PQ_CAPACITY_FOR_SVM,filter,CROSS_VALIDATION_NUMBER_OF_FOLDS)); //individualJobs.add(new LibSVMGridSearch(alldata,new SelectedTag(LibSVM.KERNELTYPE_LINEAR, LibSVM.TAGS_KERNELTYPE),PQ_CAPACITY_FOR_SVM,filter,CROSS_VALIDATION_NUMBER_OF_FOLDS)); // individualJobs.add(new NaiveBayesGridSearch(alldata,filter, CROSS_VALIDATION_NUMBER_OF_FOLDS)); // individualJobs.add(new RandomForestGridSearch(alldata,filter, CROSS_VALIDATION_NUMBER_OF_FOLDS)); // individualJobs.add(new NearestNeighborGridSearch(alldata,new ManhattanDistance(),filter, CROSS_VALIDATION_NUMBER_OF_FOLDS)); // individualJobs.add(new NearestNeighborGridSearch(alldata,new EuclideanDistance(),filter, CROSS_VALIDATION_NUMBER_OF_FOLDS)); } List<Future<ArrayList<ClassifierEvalDescriptionTriplet>>> individualClassifierFutures = null; try { individualClassifierFutures = executorService.invokeAll(individualJobs); } catch (InterruptedException e) { e.printStackTrace(); } if (individualClassifierFutures != null) { for (Future<ArrayList<ClassifierEvalDescriptionTriplet>> future: individualClassifierFutures) { try { individualClassifiers.addAll(future.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } return individualClassifiers; } /** * * @param alldata The set of instances to create the filter for * @param listOfIncludeAttributes The list of attribute names to be included (attribute name needs only contain the string) * @return A Filter filtering out all attributes that does not contain a string in listOfIncludeAttributes */ public static Filter createFilterInclusive(Instances alldata, String[] listOfIncludeAttributes) { String indexListAsString = getIndexListStringInvertedSelected(alldata, Arrays.asList(listOfIncludeAttributes)); return getRemoveFilterFromString(indexListAsString); } /** * * @param alldata The set of instances to create the filter for * @param listOfExcludeAttributes The list of attribute names to be excuded (attribute name needs only contain the string) * @return A Filter filtering out all attributes that does contain a string in listOfIncludeAttributes */ public static Filter createFilterExclusive(Instances alldata, String[] listOfExcludeAttributes){ String indexListAsString = getIndexListString(alldata, Arrays.asList(listOfExcludeAttributes)); return getRemoveFilterFromString(indexListAsString); } private static Remove getRemoveFilterFromString(String listOfIndexes) { Remove filter = new Remove(); String[] options = new String[2]; options[0] = "-R"; options[1] = listOfIndexes; try { filter.setOptions(options); } catch (Exception e) { e.printStackTrace(); } return filter; } private static String getIndexListString(Instances alldata, List<String> queryStrings) { String listOfIndexes = ""; for (int i = 0; i < alldata.numAttributes(); i++) { if (containsAnyFromList(queryStrings, alldata.attribute(i).name())) { listOfIndexes = listOfIndexes.concat(","+(1+i)); } } //Strip preceding , before return return listOfIndexes.substring(1); } private static String getIndexListStringInvertedSelected(Instances alldata, List<String> queryStrings) { String listOfIndexes = ""; for (int i = 0; i < alldata.numAttributes(); i++) { if (!containsAnyFromList(queryStrings, alldata.attribute(i).name())) { listOfIndexes = listOfIndexes.concat(","+(1+i)); } } //Strip preceding , before return return listOfIndexes.substring(1); } private static boolean containsAnyFromList(List<String> queryList, String inputString){ for (String aQueryList : queryList) { if (inputString.contains(aQueryList)) return true; } return false; } private static ArrayList<ClassifierEvalDescriptionTriplet> stackingLogisticExperiment(Instances dataset, Classifier[] classifiers, double ridge) throws Exception { ArrayList<ClassifierEvalDescriptionTriplet> triplets = new ArrayList<>(); Stacking stacking = new Stacking(); stacking.setClassifiers(classifiers); Logistic metaclassifier = new Logistic(); metaclassifier.setRidge(ridge); stacking.setMetaClassifier(metaclassifier); stacking.buildClassifier(dataset); Evaluation evalStack = new Evaluation(dataset); evalStack.crossValidateModel(stacking, dataset, CROSS_VALIDATION_NUMBER_OF_FOLDS, new Random()); String description = "Stack off: \n"; for (Classifier individualClassifier : classifiers) { description = description.concat(individualClassifier.toString()); } triplets.add(new ClassifierEvalDescriptionTriplet(description, evalStack, stacking)); return triplets; } public static void exportClassifiers(List<ClassifierEvalDescriptionTriplet> pairs, String folderpath, ClassifierType type) throws Exception { ArrayList<String> stringOutput = new ArrayList<>(); Collections.sort(pairs, new ClassifierEvalDescriptionTripletComparator()); for (ClassifierEvalDescriptionTriplet triplet: pairs){ Classifier classifier = triplet.getClassifier(); Evaluation eval = triplet.getEvaluation(); String desc = triplet.getDescription(); String filename = System.currentTimeMillis()+ "_"+ classifier.getClass().getSimpleName()+type.toString(); ObjectOutputStream oss = new ObjectOutputStream(new FileOutputStream(folderpath+filename.toLowerCase()+".model")); oss.writeObject(classifier); oss.flush(); oss.close(); stringOutput.clear(); stringOutput.add(classifier.toString()); stringOutput.add(filename); stringOutput.add(eval.toClassDetailsString()); stringOutput.add(eval.toMatrixString()); Util.saveAsFile(stringOutput,(folderpath+filename+".txt")); } } } <file_sep>/src/RandomTest/FFTTest.java package RandomTest; import Chart.ChartGenerator; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.transform.DftNormalization; import org.apache.commons.math3.transform.FastFourierTransformer; import org.apache.commons.math3.transform.TransformType; import org.knowm.xchart.Chart_XY; import org.knowm.xchart.XChartPanel; import javax.swing.*; import java.awt.*; import java.util.Arrays; import java.util.Random; /** * Created by Rune on 01-04-2016. */ public class FFTTest { public static void main(String[] args) { double[] stuff = new double[128]; Random random = new Random(); for (int i = 0; i < stuff.length; i++) { int next = (int) (random.nextInt(2) + Math.sin(i)); if(next > 80 && next < 90) next = next/2; stuff[i] = next; //stuff[i] = Math.cos(i); } double[] xData = new double[128]; for (int i = 0; i < xData.length; i++) { xData[i] = i; } FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); FastFourierTransformer fft2 = new FastFourierTransformer(DftNormalization.UNITARY); Complex[] res = fft.transform(stuff, TransformType.FORWARD); double[] xDataComplex = new double[stuff.length]; double[] yDataComplex = new double[stuff.length]; for (int i = 0; i < stuff.length; i++) { xDataComplex[i] = res[i].getReal(); yDataComplex[i] = res[i].getImaginary(); } double[] magnitudes = new double[stuff.length]; for (int i = 0; i < stuff.length; i++) { if(i < stuff.length/2) magnitudes[i] = Math.sqrt(Math.pow(res[i].getReal(),2) + Math.pow(res[i].getImaginary(),2)) * 2 / stuff.length; else magnitudes[i] = 0; } System.out.println(Arrays.toString(res)); //DC = res[0].getReal(); //Spectral Energy = sum ((real^2 + imag^2) / number of samples) //entropy = sum(c_j * log(c_j)) where c_j = (sqrt(real^2+imag^2))/(sum(sqrt(real^2+imag^2))) //correlation between different axes //correlation = sum(a_j * c_j) for all j //System.out.println(Arrays.toString(magnitudes)); Chart_XY timeChart = new Chart_XY(800,400); timeChart.addSeries("Signal",xData,stuff); Chart_XY frequencyChart = new Chart_XY(800, 400); frequencyChart.addSeries("frequency",xData,magnitudes); Chart_XY complexChart = new Chart_XY(800, 400); complexChart.addSeries("real/imag", xDataComplex, yDataComplex); javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame chartFrame = new JFrame("stuff"); chartFrame.setLayout(new BoxLayout(chartFrame.getContentPane(), BoxLayout.X_AXIS)); chartFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); XChartPanel<Chart_XY> signalPanel = new XChartPanel<Chart_XY>(timeChart); XChartPanel<Chart_XY> frequencyPanel = new XChartPanel<Chart_XY>(frequencyChart); XChartPanel<Chart_XY> compralPanel = new XChartPanel<Chart_XY>(complexChart); chartFrame.add(signalPanel); chartFrame.add(frequencyPanel); chartFrame.add(compralPanel); chartFrame.pack(); chartFrame.setVisible(true); } }); /*double[] abses = new double[128]; for (int i = 0; i < 128; i++) { abses[i] = Math.pow( res[i].abs(),2); } double PSD = 0; for (int i = 0; i < abses.length; i++) { PSD += abses[i]; } PSD = PSD/stuff.length; System.out.println(Arrays.toString(abses)); System.out.println(PSD);*/ } } <file_sep>/src/Core/ClassifierEvalDescriptionTriplet.java package Core; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; /** * Created by Rune on 28-03-2016. */ public class ClassifierEvalDescriptionTriplet { private String description; private Evaluation evaluation; private Classifier classifier; public ClassifierEvalDescriptionTriplet(String description, Evaluation evaluation, Classifier classifier) { this.description = description; this.evaluation = evaluation; this.classifier = classifier; } public String getDescription() { return description; } public Evaluation getEvaluation() { return evaluation; } public Classifier getClassifier() { return classifier; } } <file_sep>/src/RandomTest/BiasConfigToString.java package RandomTest; import Core.BiasConfiguration; /** * Created by Rune on 19-04-2016. */ public class BiasConfigToString { public static void main(String[] args) { BiasConfiguration biasConfiguration = new BiasConfiguration(-0.005f, -0.03f , -0.093f, -0.0099f, 0.023f, 0.092f); System.out.println(biasConfiguration.toString()); } } <file_sep>/src/Core/ClassifierType.java package Core; /** * Created by Rune on 05-04-2016. */ public enum ClassifierType { SIT_STAND_CLASSIFIER, EVENT_SNIFFER, TAP_SNIFFER } <file_sep>/src/Pipeline/LogisticGridSearch.java package Pipeline; import Core.ClassifierEvalDescriptionTriplet; import weka.classifiers.Evaluation; import weka.classifiers.functions.Logistic; import weka.classifiers.meta.FilteredClassifier; import weka.core.Instances; import weka.filters.Filter; import weka.filters.unsupervised.attribute.RemoveByName; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.Callable; /** * Created by Rune on 29-03-2016. */ public class LogisticGridSearch implements Callable<ArrayList<ClassifierEvalDescriptionTriplet>> { private Instances dataset; private String regex; private Filter filter; private int numberOfCrossValidationFolds; public LogisticGridSearch(Instances dataset, Filter filter, int numberOfCrossValidationFolds) { this.dataset = dataset; this.filter = filter; this.numberOfCrossValidationFolds = numberOfCrossValidationFolds; } public LogisticGridSearch(Instances dataset, String regex, int numberOfCrossValidationFolds) { this.dataset = dataset; this.regex = regex; this.numberOfCrossValidationFolds = numberOfCrossValidationFolds; } @Override public ArrayList<ClassifierEvalDescriptionTriplet> call() throws Exception { ArrayList<ClassifierEvalDescriptionTriplet> triplets = new ArrayList<>(); double ridge = 1; for (int i = 0; i < 10; i++) { String[] options = weka.core.Utils.splitOptions("-R "+ridge+ " -M -1"); Logistic logistic = new Logistic(); logistic.setOptions(options); FilteredClassifier filterlog = new FilteredClassifier(); //filter.setInputFormat(dataset); if(filter == null) { RemoveByName filter = new RemoveByName(); filter.setExpression(regex); } filterlog.setFilter(filter); filterlog.setClassifier(logistic); filterlog.buildClassifier(dataset); Evaluation eval = new Evaluation(dataset); eval.crossValidateModel(filterlog,dataset, numberOfCrossValidationFolds, new Random()); triplets.add(new ClassifierEvalDescriptionTriplet("Logistic("+ridge+").Filter:"+filter.getClass().getSimpleName(), eval,filterlog)); ridge = ridge/10; } System.out.println("LogisticTest Done!"); return triplets; } } <file_sep>/src/Core/FileCombiner.java package Core; import Core.Util; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by Rune on 07-03-2016. */ public class FileCombiner { private static String FROM_URI = "D:\\Dropbox\\Thesis\\Data\\RawData"; private static String TO_URI = "D:\\Dropbox\\Thesis\\Data\\CombinedData\\Alldata.txt"; public static void main(String[] args) { List<String> files = Util.listOfFilesInDirectory(FROM_URI); ArrayList<String> lines = new ArrayList<>(); files.forEach(filename -> { lines.addAll(Util.importData(filename)); }); Util.saveAsFile(lines, TO_URI); } } <file_sep>/src/Chart/ChartGenerator.java package Chart; import ArffFile.CompleteFeatureFileGenerator; import Core.*; import Core.Window; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.interpolation.SplineInterpolator; import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction; import org.apache.commons.math3.util.Pair; import org.knowm.xchart.BitmapEncoder; import org.knowm.xchart.Chart_XY; import org.knowm.xchart.Series_XY; import org.knowm.xchart.internal.style.markers.SeriesMarkers; import java.awt.*; import java.io.*; import java.util.ArrayList; import java.util.List; /** * Created by Rune on 22-03-2016. */ public class ChartGenerator { public static void main(String[] args) { // ArrayList<Window> windows = RawlineToTapWindowConverterVarLength.getAllWindowsFromURI("D:\\Dropbox\\Thesis\\Data\\RawTapData", 3.0); // ArrayList<Window> windows1 = RawlineToWindowConverterProximityVarLength.getAllWindowsFromURI("D:\\Dropbox\\Thesis\\Data\\RawDataProx\\it119", 3.0, new BiasConfiguration(0f,0f,0f,0f,0f,0f)); List<Window> windows2 = WindowImporter.getCorrectedWindowsMultipleUsers("D:\\ThesisDataFiltered"); String path = "D:\\Dropbox\\Thesis\\Data\\CorrectedWindows\\correctedWindows1039065005"; printCharts(windows2); } private static List<Window> getWindowsFromFile(String path) throws IOException { List<Object> results = new ArrayList<>(); FileInputStream fis; ObjectInputStream ois = null; try { fis = new FileInputStream(path); ois = new ObjectInputStream(fis); results = (List<Object>) ois.readObject(); } catch (OptionalDataException e) { if (!e.eof) throw e; } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } finally { assert ois != null; ois.close(); } List<Window> windows = new ArrayList<>(); for (Object obj : results) { windows.add((Window) obj); } return windows; } public static void printDerivatives(List<Window> windows) { long time = System.currentTimeMillis(); String folderpath = "D:\\Dropbox\\Thesis\\Charts\\Charts"+time; File dir = new File(folderpath); dir.mkdir(); for (int j = 0; j < windows.size(); j++) { Window w = windows.get(j); int size = w.getListOfFeatureLines().size(); double[] acc_up_deriv = new double[size]; double[] acc_x = new double[size]; double[] acc_y = new double[size]; double[] acc_z = new double[size]; double[] acc_up = new double[size]; double[] acc_rest = new double[size]; double[] dummy_x = new double[size]; for (int i = 0; i < w.getListOfFeatureLines().size(); i++) { acc_x[i] = w.getListOfFeatureLines().get(i).getEffAccX(); acc_y[i] = w.getListOfFeatureLines().get(i).getEffAccY(); acc_z[i] = w.getListOfFeatureLines().get(i).getEffAccZ(); acc_up[i] = w.getListOfFeatureLines().get(i).getAccUp(); acc_rest[i] = w.getListOfFeatureLines().get(i).getAccRest(); dummy_x[i] = i; } SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction timedVerticalDist = interpolator.interpolate(dummy_x,acc_up); UnivariateFunction direvative = timedVerticalDist.derivative(); for (int i = 0; i < w.getListOfFeatureLines().size(); i++) { acc_up_deriv[i] = direvative.value(i); } Chart_XY chart = new Chart_XY(1600, 1200); chart.setTitle(w.getLabel()); chart.setXAxisTitle("X"); chart.setYAxisTitle("Y"); // Series_XY series_rotX = chart.addSeries("acc_x", dummy_x, acc_x); // Series_XY series_rotY = chart.addSeries("acc_y", dummy_x, acc_y); // Series_XY series_rotZ = chart.addSeries("acc_z", dummy_x, acc_z); // Series_XY series_acc_up = chart.addSeries("acc_up", dummy_x, acc_up); // Series_XY series_acc_rest = chart.addSeries("acc_rest", dummy_x, acc_rest); Series_XY series_acc_deriv = chart.addSeries("deriv", dummy_x, acc_up_deriv); // series_rotX.setMarker(SeriesMarkers.CIRCLE); // series_rotY.setMarker(SeriesMarkers.DIAMOND); // series_rotZ.setMarker(SeriesMarkers.SQUARE); // series_acc_up.setMarker(SeriesMarkers.TRIANGLE_UP); // series_acc_rest.setMarker(SeriesMarkers.TRIANGLE_DOWN); // series_acc_deriv.setMarker(SeriesMarkers.DIAMOND); // series_acc_deriv.setLineColor(Color.MAGENTA); //chart.getStyler().setMarkerSize(0); chart.getStyler().setYAxisMax(40.0); chart.getStyler().setYAxisMin(-40.0); try { BitmapEncoder.saveBitmap(chart, folderpath + "\\chart" + j, BitmapEncoder.BitmapFormat.PNG); } catch (IOException e) { e.printStackTrace(); } } } public static void printChartWithTitle(List<Pair<Window,String>> windows){ long time = System.currentTimeMillis(); String folderpath = "D:\\ThesisCharts\\Charts"+time; File dir = new File(folderpath); dir.mkdir(); for (int j = 0; j < windows.size(); j++) { Window w = windows.get(j).getFirst(); int size = w.getListOfLines().size(); double[] acc_x = new double[size]; double[] acc_y = new double[size]; double[] acc_z = new double[size]; double[] acc_up = new double[size]; double[] acc_rest = new double[size]; double[] dummy_x = new double[size]; for (int i = 0; i < w.getListOfFeatureLines().size(); i++) { acc_x[i] = w.getListOfFeatureLines().get(i).getEffAccX(); acc_y[i] = w.getListOfFeatureLines().get(i).getEffAccY(); acc_z[i] = w.getListOfFeatureLines().get(i).getEffAccZ(); acc_up[i] = w.getListOfFeatureLines().get(i).getAccUp(); acc_rest[i] = w.getListOfFeatureLines().get(i).getAccRest(); dummy_x[i] = i; } Chart_XY chart = new Chart_XY(1600, 1200); chart.setTitle(windows.get(j).getSecond()); chart.setXAxisTitle("X"); chart.setYAxisTitle("Y"); Series_XY series_rotX = chart.addSeries("acc_x", dummy_x, acc_x); Series_XY series_rotY = chart.addSeries("acc_y", dummy_x, acc_y); Series_XY series_rotZ = chart.addSeries("acc_z", dummy_x, acc_z); Series_XY series_acc_up = chart.addSeries("acc_up", dummy_x, acc_up); Series_XY series_acc_rest = chart.addSeries("acc_rest", dummy_x, acc_rest); series_rotX.setMarker(SeriesMarkers.CIRCLE); series_rotY.setMarker(SeriesMarkers.DIAMOND); series_rotZ.setMarker(SeriesMarkers.SQUARE); series_acc_up.setMarker(SeriesMarkers.TRIANGLE_UP); series_acc_rest.setMarker(SeriesMarkers.TRIANGLE_DOWN); chart.getStyler().setYAxisMax(15.0); chart.getStyler().setYAxisMin(-15.0); try { BitmapEncoder.saveBitmap(chart, folderpath + "\\chart" + j, BitmapEncoder.BitmapFormat.PNG); } catch (IOException e) { e.printStackTrace(); } //Util.updateProgress(j/windows.size()); } } public static void printCharts(List<Window> windows){ long time = System.currentTimeMillis(); String folderpath = "D:\\Dropbox\\Thesis\\Charts\\Charts"+time; File dir = new File(folderpath); dir.mkdir(); for (int j = 0; j < windows.size(); j++) { Window w = windows.get(j); int size = w.getListOfFeatureLines().size(); double[] acc_x = new double[size]; double[] acc_y = new double[size]; double[] acc_z = new double[size]; double[] acc_up = new double[size]; double[] acc_rest = new double[size]; double[] dummy_x = new double[size]; for (int i = 0; i < w.getListOfFeatureLines().size(); i++) { acc_x[i] = w.getListOfFeatureLines().get(i).getEffAccX(); acc_y[i] = w.getListOfFeatureLines().get(i).getEffAccY(); acc_z[i] = w.getListOfFeatureLines().get(i).getEffAccZ(); acc_up[i] = w.getListOfFeatureLines().get(i).getAccUp(); acc_rest[i] = w.getListOfFeatureLines().get(i).getAccRest(); dummy_x[i] = i; } Chart_XY chart = new Chart_XY(1600, 1200); chart.setTitle(w.getLabel()); chart.setXAxisTitle("X"); chart.setYAxisTitle("Y"); Series_XY series_rotX = chart.addSeries("acc_x", dummy_x, acc_x); Series_XY series_rotY = chart.addSeries("acc_y", dummy_x, acc_y); Series_XY series_rotZ = chart.addSeries("acc_z", dummy_x, acc_z); Series_XY series_acc_up = chart.addSeries("acc_up", dummy_x, acc_up); Series_XY series_acc_rest = chart.addSeries("acc_rest", dummy_x, acc_rest); series_rotX.setMarker(SeriesMarkers.CIRCLE); series_rotY.setMarker(SeriesMarkers.DIAMOND); series_rotZ.setMarker(SeriesMarkers.SQUARE); series_acc_up.setMarker(SeriesMarkers.TRIANGLE_UP); series_acc_rest.setMarker(SeriesMarkers.TRIANGLE_DOWN); chart.getStyler().setYAxisMax(40.0); chart.getStyler().setYAxisMin(-40.0); try { BitmapEncoder.saveBitmap(chart, folderpath + "\\chart" + j, BitmapEncoder.BitmapFormat.PNG); } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>/src/Core/FeatureLine.java package Core; import java.io.Serializable; /** * Created by Rune on 08-03-2016. */ public class FeatureLine implements Serializable { private Double accX; private Double accY; private Double accZ; private Double effAccX; private Double effAccY; private Double effAccZ; private Double graX; private Double graY; private Double graZ; private Double rotX; private Double rotY; private Double rotZ; private ProximityValue proximity; private int timestamp; private Double accUp; private Double accRest; public FeatureLine(Double accX, Double accY, Double accZ, Double graX, Double graY, Double graZ, Double rotX, Double rotY, Double rotZ, ProximityValue proximity, int timestamp) { this.accX = accX; this.accY = accY; this.accZ = accZ; this.rotX = rotX; this.rotY = rotY; this.rotZ = rotZ; this.graX = graX; this.graY = graY; this.graZ = graZ; this.timestamp = timestamp; this.proximity = proximity; calculateRelativeMovement(); } public FeatureLine(FeatureLine featureLine){ this.accX = featureLine.getAccX(); this.accY = featureLine.getAccY(); this.accZ = featureLine.getAccZ(); this.graX = featureLine.getGraX(); this.graY = featureLine.getGraY(); this.graZ = featureLine.getGraZ(); this.timestamp = featureLine.getTimestamp(); this.proximity = featureLine.getProximity(); calculateRelativeMovement(); } public FeatureLine(Double accX, Double accY, Double accZ, Double graX, Double graY, Double graZ, int timestamp, ProximityValue proximity) { this.accX = accX; this.accY = accY; this.accZ = accZ; this.graX = graX; this.graY = graY; this.graZ = graZ; this.timestamp = timestamp; this.proximity = proximity; calculateRelativeMovement(); } public FeatureLine(Double accX, Double accY, Double accZ, Double rotX, Double rotY, Double rotZ, Double graX, Double graY, Double graZ, int timestamp) { this.accX = accX; this.accY = accY; this.accZ = accZ; this.rotX = rotX; this.rotY = rotY; this.rotZ = rotZ; this.graX = graX; this.graY = graY; this.graZ = graZ; this.timestamp = timestamp; calculateRelativeMovement(); } public FeatureLine(Double accX, Double accY, Double accZ, Double graX, Double graY, Double graZ, int timestamp) { this.accX = accX; this.accY = accY; this.accZ = accZ; this.graX = graX; this.graY = graY; this.graZ = graZ; this.timestamp = timestamp; calculateRelativeMovement(); } private void calculateRelativeMovement(){ //subtract gravity effAccX = accX-graX; effAccY = accY-graY; effAccZ = accZ-graZ; //calculate C Double C = ((effAccX*graX)+(effAccY*graY)+(effAccZ*graZ))/((graX*graX)+(graY*graY)+(graZ*graZ)); //calculate accUp Double p1 = Math.pow(graX,2); Double p2 = Math.pow(graY,2); Double p3 = Math.pow(graZ,2); accUp = Math.sqrt(p1 + p2 + p3) * C; Double overallAcc = Math.sqrt(Math.pow(effAccX,2)+Math.pow(effAccY,2)+Math.pow(effAccZ,2)); //calculate accRest accRest = Math.sqrt(Math.pow(overallAcc,2)-Math.pow(accUp,2)); } public Double getAccUp() { return accUp; } public Double getAccRest() { return accRest; } public Double getEffAccX() { return effAccX; } public Double getEffAccY() { return effAccY; } public Double getEffAccZ() { return effAccZ; } public Double getAccX() { return accX; } public Double getAccY() { return accY; } public Double getAccZ() { return accZ; } public Double getGraX() { return graX; } public Double getGraY() { return graY; } public Double getGraZ() { return graZ; } public Double getRotX() { return rotX; } public Double getRotY() { return rotY; } public Double getRotZ() { return rotZ; } public ProximityValue getProximity() { return proximity; } public int getTimestamp() { return timestamp; } public void applyBias(BiasConfiguration bias) { if (graX < 0) accX = accX - (graX * bias.getBias_x_neg()); else accX = accX - (graX * bias.getBias_x_pos()); if (graY < 0) accY = accY - (graY * bias.getBias_y_neg()); else accY = accY - (graY * bias.getBias_y_pos()); if (graZ < 0) accZ = accZ - (graZ * bias.getBias_z_neg()); else accZ = accZ - (graZ * bias.getBias_z_pos()); calculateRelativeMovement(); } } <file_sep>/src/RandomTest/PrintChartsFromFileTutorial.java package RandomTest; import Chart.ChartGenerator; import Core.Window; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; /** * Created by Rune on 30-03-2016. */ public class PrintChartsFromFileTutorial { public static void main(String[] args) { ArrayList<Window> listOfStuff; try{ FileInputStream filIn = new FileInputStream("D:\\Dropbox\\Thesis\\Data\\WindowsFromPhone\\WindowExport-938336090"); ObjectInputStream in = new ObjectInputStream(filIn); listOfStuff = (ArrayList<Window>) in.readObject(); in.close(); filIn.close(); ChartGenerator.printCharts(listOfStuff); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } <file_sep>/src/Pipeline/ClassificationPipeline.java package Pipeline; import Core.ClassifierEvaluationPairComparator; import Core.RawlineToWindowConverter; import Core.Util; import Core.Window; import org.apache.commons.math3.util.Pair; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import weka.classifiers.bayes.NaiveBayes; import weka.classifiers.functions.LibSVM; import weka.classifiers.functions.Logistic; import weka.classifiers.lazy.IBk; import weka.classifiers.meta.Stacking; import weka.classifiers.meta.Vote; import weka.classifiers.trees.RandomForest; import weka.core.*; import weka.core.converters.ConverterUtils; import weka.core.neighboursearch.LinearNNSearch; import java.io.File; import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.stream.Collectors; /** * Created by Rune on 22-03-2016. */ public class ClassificationPipeline { private static int CROSS_VALIDATION_NUMBER = 10; public static void main(String[] args) throws Exception { ExecutorService executorService = Executors.newFixedThreadPool(8); String fileLocation = "D:\\Dropbox\\Thesis\\Data\\RawData"; int starttime = (int) System.currentTimeMillis(); ArrayList<String> featureFiles = new ArrayList<>(); //create a lot of arff files Util.updateProgressWithText("Creating feature files"); featureFiles.add(createECDFUpAndYFile(fileLocation)); featureFiles.add(createECDFRawFile(fileLocation)); featureFiles.add(createECDFDiscFile(fileLocation)); featureFiles.add(createECDFUpDownFile(fileLocation)); //create data sources Util.updateProgressWithText("Creating data sources"); ArrayList<Instances> instances = getInstances(featureFiles); //Create all features dataset ArrayList<String> allDataFile = new ArrayList<>(); allDataFile.add(createECDFAllFile(fileLocation)); ArrayList<Instances> allDataInstances = getInstances(allDataFile); ArrayList<Pair<Classifier,Evaluation>> classifierPairs = new ArrayList<>(); ArrayList<Callable<ArrayList<Pair<Classifier, Evaluation>>>> jobs = new ArrayList<>(); Util.updateProgressWithText("Starting testing of individual models"); //Schedule the test jobs for (Instances instance : instances) { jobs.add(new RandomForestTest(instance)); jobs.add(new LibSvmLinearTest(instance, new SelectedTag(LibSVM.KERNELTYPE_LINEAR, LibSVM.TAGS_KERNELTYPE))); jobs.add(new LibSvmLinearTest(instance, new SelectedTag(LibSVM.KERNELTYPE_RBF, LibSVM.TAGS_KERNELTYPE))); jobs.add(new LibSvmLinearTest(instance, new SelectedTag(LibSVM.KERNELTYPE_POLYNOMIAL, LibSVM.TAGS_KERNELTYPE))); jobs.add(new LibSvmLinearTest(instance, new SelectedTag(LibSVM.KERNELTYPE_SIGMOID, LibSVM.TAGS_KERNELTYPE))); jobs.add(new NaiveBayesTest(instance)); jobs.add(new LogisticTest(instance)); jobs.add(new NearestNeighborTest(instance, new ManhattanDistance())); jobs.add(new NearestNeighborTest(instance, new EuclideanDistance())); } List<Future<ArrayList<Pair<Classifier,Evaluation>>>> testFutures = executorService.invokeAll(jobs); for (Future<ArrayList<Pair<Classifier, Evaluation>>> testFuture : testFutures) { classifierPairs.addAll(testFuture.get()); } Util.updateProgressWithText("Testing of individual models complete"); //sort the classifiers according to performance Collections.sort(classifierPairs, new ClassifierEvaluationPairComparator()); Util.updateProgressWithText("Creating meta classifiers"); //get the 3 best classifiers Classifier[] the3BestClassifiers = new Classifier[3]; for (int i = 0; i < 3; i++) { the3BestClassifiers[i] = classifierPairs.get(i).getKey(); } //get the 5 best classifiers Classifier[] the5BestClassifiers = new Classifier[5]; for (int i = 0; i < 5; i++) { the5BestClassifiers[i] = classifierPairs.get(i).getKey(); } //get the 10 best classifiers Classifier[] the10BestClassifiers = new Classifier[10]; for (int i = 0; i < 10; i++) { the10BestClassifiers[i] = classifierPairs.get(i).getKey(); } ArrayList<Pair<Classifier, Evaluation>> metaClassifiers = new ArrayList<>(); /*ArrayList<Callable<ArrayList<Pair<Classifier, Evaluation>>>> metaJobs = new ArrayList<>(); metaJobs.add(new StackingTester(allDataInstances.get(0), the3BestClassifiers.clone())); metaJobs.add(new StackingTester(allDataInstances.get(0), the5BestClassifiers.clone())); metaJobs.add(new StackingTester(allDataInstances.get(0), the10BestClassifiers.clone())); //metaJobs.add(new VotingTester(allDataInstances.get(0), the3BestClassifiers.clone())); //metaJobs.add(new VotingTester(allDataInstances.get(0), the5BestClassifiers.clone())); //metaJobs.add(new VotingTester(allDataInstances.get(0), the10BestClassifiers.clone())); List<Future<ArrayList<Pair<Classifier,Evaluation>>>> metaFutures = executorService.invokeAll(metaJobs); for (Future<ArrayList<Pair<Classifier, Evaluation>>> metaFuture : metaFutures) { metaClassifiers.addAll(metaFuture.get()); } executorService.shutdown();*/ String folderpath = "D:\\Dropbox\\Thesis\\Data\\Output"+System.currentTimeMillis()+"\\"; File dir = new File(folderpath); dir.mkdir(); exportClassifiers(classifierPairs.subList(0,50), folderpath); //exportClassifiers(metaClassifiers, folderpath); Util.updateProgressWithText("Done creating meta classifiers"); System.out.println(); System.out.println("----------------------------------------------------------------"); System.out.println("Number of classifiers: " + classifierPairs.size()); System.out.println("----------------------------------------------------------------"); //Print the meta classifiers for (Pair<Classifier, Evaluation> pair : metaClassifiers) { System.out.println(pair.getKey().toString()); System.out.println(pair.getKey().getCapabilities().toString()); System.out.println(pair.getValue().toClassDetailsString()); System.out.println(pair.getValue().toMatrixString()); System.out.println("----------------------------------------------------------------"); } for (int i = 0; i < 10; i++) { Evaluation eval = classifierPairs.get(i).getValue(); System.out.println(classifierPairs.get(i).getKey().toString()); System.out.println(eval.toClassDetailsString()); System.out.println(eval.toMatrixString()); System.out.println("----------------------------------------------------------------"); } int endtime = (int) System.currentTimeMillis(); System.out.println("Execution time in seconds: " + ((endtime-starttime)/ 1000)); } private static void exportClassifiers(List<Pair<Classifier, Evaluation>> pairs, String folderpath) throws Exception { ArrayList<String> stringOutput = new ArrayList<>(); Collections.sort(pairs, new ClassifierEvaluationPairComparator()); for (Pair<Classifier, Evaluation> pair: pairs){ Classifier classifier = pair.getKey(); Evaluation eval = pair.getValue(); String filename = System.currentTimeMillis()+ "_"+ classifier.getClass().getSimpleName(); ObjectOutputStream oss = new ObjectOutputStream(new FileOutputStream(folderpath+filename+".model")); oss.writeObject(classifier); oss.flush(); oss.close(); stringOutput.clear(); stringOutput.add(classifier.toString()); stringOutput.add(filename); stringOutput.add(eval.toClassDetailsString()); stringOutput.add(eval.toMatrixString()); Util.saveAsFile(stringOutput,(folderpath+filename+".txt")); } } private static class VotingTester implements Callable<ArrayList<Pair<Classifier, Evaluation>>>{ private Instances dataset; private Classifier[] classifiers; public VotingTester(Instances dataset, Classifier[] classifiers) { this.dataset = dataset; this.classifiers = classifiers; } @Override public ArrayList<Pair<Classifier, Evaluation>> call() throws Exception { ArrayList<Pair<Classifier, Evaluation>> pairs = new ArrayList<>(); Vote combinedClassifier = new Vote(); combinedClassifier.setClassifiers(classifiers); // combinedClassifier.buildClassifier(dataset); Evaluation eval = new Evaluation(dataset); eval.crossValidateModel(combinedClassifier, dataset, CROSS_VALIDATION_NUMBER, new Random()); pairs.add(new Pair<Classifier, Evaluation>(combinedClassifier, eval)); return pairs; } } private static class StackingTester implements Callable<ArrayList<Pair<Classifier, Evaluation>>>{ private Instances dataset; private Classifier[] classifiers; public StackingTester(Instances dataset, Classifier[] classifiers) { this.dataset = dataset; this.classifiers = classifiers; } @Override public ArrayList<Pair<Classifier, Evaluation>> call() throws Exception { ArrayList<Pair<Classifier, Evaluation>> stacks = new ArrayList<>(); double ridge = 1; for (int i = 0; i < 5; i++) { Stacking stacking = new Stacking(); stacking.setClassifiers(classifiers); Logistic metaclassifier = new Logistic(); metaclassifier.setRidge(ridge); stacking.setMetaClassifier(metaclassifier); stacking.buildClassifier(dataset); Evaluation evalStack = new Evaluation(dataset); evalStack.crossValidateModel(stacking, dataset, CROSS_VALIDATION_NUMBER, new Random()); stacks.add(new Pair<Classifier, Evaluation>(stacking,evalStack)); ridge = ridge/10; } return stacks; } } private static class NearestNeighborTest implements Callable<ArrayList<Pair<Classifier, Evaluation>>>{ private Instances dataset; private DistanceFunction distanceFunction; public NearestNeighborTest(Instances dataset, DistanceFunction distanceFunction) { this.dataset = dataset; this.distanceFunction = distanceFunction; } @Override public ArrayList<Pair<Classifier, Evaluation>> call() throws Exception { ArrayList<Pair<Classifier, Evaluation>> pairs = new ArrayList<>(); int k = 1; for (int i = 0; i < 5; i++) { IBk classifier = new IBk(); classifier.setKNN(k); LinearNNSearch search = new LinearNNSearch(); search.setDistanceFunction(distanceFunction); classifier.setNearestNeighbourSearchAlgorithm(search); classifier.buildClassifier(dataset); Evaluation eval = new Evaluation(dataset); eval.crossValidateModel(classifier, dataset, CROSS_VALIDATION_NUMBER, new Random()); pairs.add(new Pair<Classifier, Evaluation>(classifier,eval)); k = k*2; } System.out.println("NearestNeighborTest with distance function: "+ distanceFunction.getClass().getSimpleName()+" Done!"); return pairs; } } private static class LogisticTest implements Callable<ArrayList<Pair<Classifier, Evaluation>>>{ private Instances dataset; public LogisticTest(Instances dataset) { this.dataset = dataset; } @Override public ArrayList<Pair<Classifier, Evaluation>> call() throws Exception { ArrayList<Pair<Classifier,Evaluation>> pairs = new ArrayList<>(); double ridge = 1; for (int i = 0; i < 10; i++) { String[] options = weka.core.Utils.splitOptions("-R "+ridge+ " -M -1"); Logistic logistic = new Logistic(); logistic.setOptions(options); logistic.buildClassifier(dataset); Evaluation eval = new Evaluation(dataset); eval.crossValidateModel(logistic,dataset, CROSS_VALIDATION_NUMBER, new Random()); pairs.add(new Pair<Classifier, Evaluation>(logistic,eval)); ridge = ridge/10; } System.out.println("LogisticTest Done!"); return pairs; } } private static class NaiveBayesTest implements Callable<ArrayList<Pair<Classifier, Evaluation>>>{ private Instances dataset; public NaiveBayesTest(Instances dataset) { this.dataset = dataset; } @Override public ArrayList<Pair<Classifier, Evaluation>> call() throws Exception { ArrayList<Pair<Classifier,Evaluation>> pairs = new ArrayList<>(); String[] options = weka.core.Utils.splitOptions("-K"); NaiveBayes naiveBayes = new NaiveBayes(); naiveBayes.setOptions(options); naiveBayes.buildClassifier(dataset); Evaluation eval = new Evaluation(dataset); eval.crossValidateModel(naiveBayes,dataset, CROSS_VALIDATION_NUMBER, new Random()); pairs.add(new Pair<Classifier, Evaluation>(naiveBayes,eval)); naiveBayes = new NaiveBayes(); naiveBayes.setOptions(weka.core.Utils.splitOptions("")); naiveBayes.buildClassifier(dataset); eval = new Evaluation(dataset); eval.crossValidateModel(naiveBayes,dataset, CROSS_VALIDATION_NUMBER, new Random()); pairs.add(new Pair<Classifier, Evaluation>(naiveBayes,eval)); System.out.println("NaiveBayesTest Done!"); return pairs; } } private static class LibSvmLinearTest implements Callable<ArrayList<Pair<Classifier,Evaluation>>> { private Instances dataset; private SelectedTag type; private int PQ_CAPACITY = 10; public LibSvmLinearTest(Instances dataset, SelectedTag type) { this.dataset = dataset; this.type = type; } @Override public ArrayList<Pair<Classifier, Evaluation>> call() throws Exception { ArrayList<Pair<Classifier,Evaluation>> pairs = new ArrayList<>(); PriorityQueue<Pair<Classifier, Evaluation>> pq = new PriorityQueue<>(PQ_CAPACITY, new Comparator<Pair<Classifier, Evaluation>>() { @Override public int compare(Pair<Classifier, Evaluation> o1, Pair<Classifier, Evaluation> o2) { Double f1 = o1.getValue().fMeasure(1); Double f2 = o2.getValue().fMeasure(1); if(f1 > f2) return 1; if(f2> f1) return -1; return 0; } }); double C = 0.01; double gamma = 10; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { String[] options = weka.core.Utils.splitOptions("-S 0 -K 2 -D 3 -G "+gamma+" -R 0.0 -N 0.5 -M 40.0 -C " +C+ " -E 0.001 -P 0.1 -model D:\\Apps\\weka-3-7-3 -seed 1"); LibSVM svm = new LibSVM(); svm.setKernelType(type); svm.setOptions(options); svm.buildClassifier(dataset); Evaluation eval = new Evaluation(dataset); eval.crossValidateModel(svm, dataset, CROSS_VALIDATION_NUMBER, new Random()); if(pq.size() < PQ_CAPACITY || eval.fMeasure(1) > pq.peek().getValue().fMeasure(1)){ pq.offer(new Pair<Classifier,Evaluation>(svm,eval)); } } C = C*5; gamma = gamma/5; System.out.println("SvmTest of type: "+type.getSelectedTag().getReadable()+" has done "+((i+1)*20)+" iterations!"); } pairs.addAll(pq); System.out.println("SvmTest of type: "+type.getSelectedTag().getReadable()+" Done!"); return pairs; } } private static class RandomForestTest implements Callable<ArrayList<Pair<Classifier, Evaluation>>> { private Instances dataset; public RandomForestTest(Instances dataset){ this.dataset = dataset; } @Override public ArrayList<Pair<Classifier, Evaluation>> call() throws Exception { ArrayList<Pair<Classifier,Evaluation>> pairs = new ArrayList<>(); double numberOfTrees = 10; for (int i = 0; i < 10; i++) { String[] options = weka.core.Utils.splitOptions("-I " + (int) numberOfTrees +" -K 0 -S 1"); RandomForest rf = new RandomForest(); rf.setOptions(options); rf.buildClassifier(dataset); Evaluation eval = new Evaluation(dataset); eval.crossValidateModel(rf, dataset, CROSS_VALIDATION_NUMBER, new Random()); pairs.add(new Pair<Classifier,Evaluation>(rf,eval)); numberOfTrees = numberOfTrees * 1.5; } System.out.println("RandomForestTest Done!"); return pairs; } } public static ArrayList<Instances> getInstances(ArrayList<String> featureFiles) throws Exception { ArrayList<Instances> dataFiles = new ArrayList<>(); for (String file :featureFiles) { dataFiles.add(new ConverterUtils.DataSource(file).getDataSet()); } for (Instances datafile : dataFiles) { if(datafile.classIndex() == -1) datafile.setClassIndex(datafile.numAttributes() - 1); } return dataFiles; } public static String createECDFAllFile(String fileLocation) { ArrayList<Window> windows = RawlineToWindowConverter.getAllWindowsFromURI(fileLocation); for (Window w : windows) { w.calculateECDFRepresentationDisc(30); w.calculateECDFRepresentationRaw(30); w.calculateECDFRepresentationUpDown(30); } String featureString = ""; ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows)); fileToBePrinted.addAll(windows.stream().map(Util::convertToLine).collect(Collectors.toList())); //print the file fileToBePrinted.removeIf(String::isEmpty); String filename = "D:\\Dropbox\\Thesis\\Data\\Test\\"+"ECDFAllPipeline.arff"; Util.saveAsFile(fileToBePrinted,filename); return filename; } private static String createECDFUpDownFile(String fileLocation) { ArrayList<Window> windows = RawlineToWindowConverter.getAllWindowsFromURI(fileLocation); for (Window w : windows) { w.calculateECDFRepresentationUpDown(30); } String featureString = ""; ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows)); fileToBePrinted.addAll(windows.stream().map(Util::convertToLine).collect(Collectors.toList())); //print the file fileToBePrinted.removeIf(String::isEmpty); String filename = "D:\\Dropbox\\Thesis\\Data\\Test\\"+"ECDFUpDownPipeline.arff"; Util.saveAsFile(fileToBePrinted,filename); return filename; } private static String createECDFDiscFile(String fileLocation) { ArrayList<Window> windows = RawlineToWindowConverter.getAllWindowsFromURI(fileLocation); for (Window w : windows) { w.calculateECDFRepresentationDisc(30); } String featureString = ""; ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows)); fileToBePrinted.addAll(windows.stream().map(Util::convertToLine).collect(Collectors.toList())); //print the file fileToBePrinted.removeIf(String::isEmpty); String filename = "D:\\Dropbox\\Thesis\\Data\\Test\\"+"ECDFDiscPipeline.arff"; Util.saveAsFile(fileToBePrinted,filename); return filename; } private static String createECDFRawFile(String fileLocation) { ArrayList<Window> windows = RawlineToWindowConverter.getAllWindowsFromURI(fileLocation); for (Window w : windows) { w.calculateECDFRepresentationRaw(30); } String featureString = ""; ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows)); fileToBePrinted.addAll(windows.stream().map(Util::convertToLine).collect(Collectors.toList())); //print the file fileToBePrinted.removeIf(String::isEmpty); String filename = "D:\\Dropbox\\Thesis\\Data\\Test\\"+"ECDFRawPipeline.arff"; Util.saveAsFile(fileToBePrinted,filename); return filename; } private static String createECDFUpAndYFile(String fileLocation) { ArrayList<Window> windows = RawlineToWindowConverter.getAllWindowsFromURI(fileLocation); for (Window w : windows) { w.calculateECDFRepresentationUpAndY(30); } String featureString = ""; ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows)); fileToBePrinted.addAll(windows.stream().map(Util::convertToLine).collect(Collectors.toList())); //print the file fileToBePrinted.removeIf(String::isEmpty); String filename = "D:\\Dropbox\\Thesis\\Data\\Test\\"+"ECDFUpAndYPipeline.arff"; Util.saveAsFile(fileToBePrinted,filename); return filename; } } <file_sep>/src/RandomTest/randomstuff.java package RandomTest; import java.text.DecimalFormat; import java.util.AbstractMap; import java.util.ArrayList; /** * Created by Rune on 09-03-2016. */ public class randomstuff { public static void main(String[] args) { String stuff = "@ATTRIBUTE upAcc_MinVal NUMERIC" + "\r" + "@ATTRIBUTE upAcc_MaxVal NUMERIC" + "\r" + "@ATTRIBUTE upAcc_MinDif NUMERIC" + "\r" + "@ATTRIBUTE upAcc_MaxDif NUMERIC" + "\r" + "@ATTRIBUTE upAcc_Mean NUMERIC" + "\r" + "@ATTRIBUTE upAcc_RootMeanSquare NUMERIC" + "\r" + "@ATTRIBUTE upAcc_AverageDif NUMERIC" + "\r" + "@ATTRIBUTE restAcc_MinVal NUMERIC" + "\r" + "@ATTRIBUTE restAcc_MaxVal NUMERIC" + "\r" + "@ATTRIBUTE restAcc_MinDif NUMERIC" + "\r" + "@ATTRIBUTE restAcc_MaxDif NUMERIC" + "\r" + "@ATTRIBUTE restAcc_Mean NUMERIC" + "\r" + "@ATTRIBUTE restAcc_Mean_Absolute NUMERIC" + "\r" + "@ATTRIBUTE restAcc_RootMeanSquare NUMERIC" + "\r" + "@ATTRIBUTE restAcc_AverageDif NUMERIC" + "\r" + "@ATTRIBUTE xAccRaw_MinVal NUMERIC" + "\r" + "@ATTRIBUTE xAccRaw_MaxVal NUMERIC" + "\r" + "@ATTRIBUTE xAccRaw_MinDif NUMERIC" + "\r" + "@ATTRIBUTE xAccRaw_MaxDif NUMERIC" + "\r" + "@ATTRIBUTE xAccRaw_Mean NUMERIC" + "\r" + "@ATTRIBUTE xAccRaw_RootMeanSquare NUMERIC" + "\r" + "@ATTRIBUTE xAccRaw_AverageDif NUMERIC" + "\r" + "@ATTRIBUTE yAccRaw_MinVal NUMERIC" + "\r" + "@ATTRIBUTE yAccRaw_MaxVal NUMERIC" + "\r" + "@ATTRIBUTE yAccRaw_MinDif NUMERIC" + "\r" + "@ATTRIBUTE yAccRaw_MaxDif NUMERIC" + "\r" + "@ATTRIBUTE yAccRaw_Mean NUMERIC" + "\r" + "@ATTRIBUTE yAccRaw_RootMeanSquare NUMERIC" + "\r" + "@ATTRIBUTE yAccRaw_AverageDif NUMERIC" + "\r" + "@ATTRIBUTE zAccRaw_MinVal NUMERIC" + "\r" + "@ATTRIBUTE zAccRaw_MaxVal NUMERIC" + "\r" + "@ATTRIBUTE zAccRaw_MinDif NUMERIC" + "\r" + "@ATTRIBUTE zAccRaw_MaxDif NUMERIC" + "\r" + "@ATTRIBUTE zAccRaw_Mean NUMERIC" + "\r" + "@ATTRIBUTE zAccRaw_RootMeanSquare NUMERIC" + "\r" + "@ATTRIBUTE zAccRaw_AverageDif NUMERIC" + "\r"; //createAttributelistFromString(stuff); //createValuesListFromString(stuff); System.out.println((4/30)*403.0); } public static void createAttributelistFromString(String s){ String[] listOfAttributes = s.split("\r"); int i = 1; for (String attribute : listOfAttributes) { String out = attribute.replace("@ATTRIBUTE", ""); out = out.replace("NUMERIC", ""); out = out.trim(); System.out.println("attributes.add(new Attribute(\""+out+"\"));"); i++; } } public static void createValuesListFromString(String s){ String[] listOfAttributes = s.split("\r"); int i = 1; for (String attribute : listOfAttributes) { String out = attribute.replace("@ATTRIBUTE", ""); out = out.replace("NUMERIC", ""); out = out.trim(); System.out.println("window.get"+out+"(),\r"); i++; } } } <file_sep>/src/RandomTest/FilterAdapter.java package RandomTest; import com.google.gson.TypeAdapter; import com.google.gson.internal.bind.TypeAdapters; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Remove; import java.io.IOException; import java.util.Objects; /** * Created by Rune on 23-04-2016. */ public class FilterAdapter extends TypeAdapter<Filter> { @Override public void write(JsonWriter jsonWriter, Filter filter) throws IOException { jsonWriter.beginObject(); if(filter instanceof Remove){ jsonWriter.name("cols").value(((Remove) filter).getAttributeIndices()); } jsonWriter.endObject(); } @Override public Filter read(JsonReader jsonReader) throws IOException { final Remove filter = new Remove(); jsonReader.beginObject(); while(jsonReader.hasNext()){ if(jsonReader.nextName().equals("cols")) filter.setAttributeIndices(jsonReader.nextString()); } return filter; } } <file_sep>/src/RandomTest/ApacheCommonsTest.java package RandomTest; import org.apache.commons.math3.analysis.interpolation.SplineInterpolator; import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; /** * Created by Rune on 15-03-2016. */ public class ApacheCommonsTest { public static void main(String[] args) { ArrayList<Double> xs = new ArrayList<>(); ArrayList<Double> ys = new ArrayList<>(); for (int i = 0; i < 100; i++) { xs.add((double) i); ys.add(Math.random() * 100); } Collections.sort(ys); double[] x = xs.stream().mapToDouble(Double::doubleValue).toArray(); //via method reference double[] y = ys.stream().mapToDouble(Double::doubleValue).toArray(); //via method reference System.out.println(Arrays.toString(x)); System.out.println(Arrays.toString(y)); SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdf = interpolator.interpolate(x,y); System.out.println(ecdf.toString()); System.out.println(ecdf.value(0.2*100)); System.out.println(ecdf.value(0.4*100)); System.out.println(ecdf.value(0.6*100)); System.out.println(ecdf.value(0.8*100)); } } <file_sep>/src/Pipeline/SingleExperimentPipeline.java package Pipeline; import Core.*; import org.apache.commons.math3.util.Pair; import weka.classifiers.Evaluation; import weka.classifiers.trees.RandomForest; import weka.core.Instances; import weka.core.converters.ConverterUtils; import java.util.ArrayList; import java.util.Random; import java.util.stream.Collectors; /** * Created by Rune on 29-03-2016. */ public class SingleExperimentPipeline { public static void main(String[] args) { ArrayList<Window> windows = RawlineToTapWindowConverterVarLength.getAllWindowsFromURI("D:\\Dropbox\\Thesis\\Data\\RawTapData", 3); //ArrayList<Window> windows = RawlineToWindowConverter.getAllWindowsFromURI("D:\\Dropbox\\Thesis\\Data\\RawData"); //windows.removeIf(window -> window.getLabel().contains("null")); //windows.stream().filter(w -> !w.getLabel().contains("null")).forEach(w -> w.setLabel("event")); for (Window w : windows) { // w.calculateECDFRepresentationRaw(30); // w.calculateECDFRepresentationDisc(30); // w.calculateECDFRepresentationUpDown(30); // w.calculateECDFRepresentationUpAndY(30); // w.calculateFeaturesForRelativeMovement(); // w.calculateFeaturesForRawMovement(); // w.calculateFeaturesForGravityDiscountedMovement(); // w.calculateStartingOrientation(); // w.calculateEndingOrientation(); // w.calculateMeanVerticalAcceleration(); // w.calculateVerticalSamplesBelowThreshold(1); // w.calculateVerticalSamplesBelowThreshold(0); // w.calculateVerticalSamplesBelowThreshold(-1); // w.calculateVerticalSamplesBelowThreshold(-2); // w.calculateVerticalSamplesBelowThreshold(-3); // w.calculateUpCorrelationWithDiscounted(); // w.calculateSumOfUpwardsAcceleration(); // w.calculateSumOfDownwardsAcceleration(); // w.calculateOrientationJitter(); // w.calculateVerticalTimedDistribution(30); // w.calculateFrequencyFeaturesDiscX(); // w.calculateFrequencyFeaturesDiscY(); // w.calculateFrequencyFeaturesDiscZ(); // w.calculateFrequencyFeaturesRawX(); // w.calculateFrequencyFeaturesRawY(); w.calculateFrequencyFeaturesRawZ(); // w.calculateFrequencyFeaturesHorizontal(); // w.calculateFrequencyFeaturesVertical(); // w.calculateZeroCrossings(); w.calculateNumberOfTaps(); } ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows)); fileToBePrinted.addAll(windows.stream().map(Util::convertToLine).collect(Collectors.toList())); //print the file fileToBePrinted.removeIf(String::isEmpty); String fileName ="D:\\Dropbox\\Thesis\\Data\\Test\\"+"AllFeaturesCool3second.arff"; Util.saveAsFile(fileToBePrinted,fileName); ConverterUtils.DataSource source; try { source = new ConverterUtils.DataSource(fileName); Instances data = source.getDataSet(); if(data.classIndex() == -1) data.setClassIndex(data.numAttributes() - 1); String[] options = weka.core.Utils.splitOptions("-I 100 -K 0 -S 1"); RandomForest rf = new RandomForest(); rf.setOptions(options); rf.buildClassifier(data); Evaluation eval = new Evaluation(data); eval.crossValidateModel(rf,data, 10, new Random()); System.out.println(eval.toClassDetailsString()); System.out.println(eval.toMatrixString()); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/src/Core/Util.java package Core; import Core.Window; import org.apache.commons.math3.util.Pair; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; /** * Created by Rune on 07-03-2016. */ public class Util { public static List<String> listOfFilesInDirectory(String directory){ List<String> filenames = new ArrayList<>(); try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(directory))){ for (Path path : directoryStream){ filenames.add(path.toString()); } } catch (IOException e) { e.printStackTrace(); } return filenames; } public static List<String> listOfFilesInDirectoryRecursive(String directory){ List<String> filenames = new ArrayList<>(); File root = new File(directory); File[] list = root.listFiles(); if(list == null) return filenames; for(File f : list){ if( f.isDirectory()){ filenames.addAll(listOfFilesInDirectoryRecursive(f.getAbsolutePath())); } else { filenames.add(f.getAbsolutePath()); } } return filenames; } public static ArrayList<String> importData(String uri) { ArrayList<String> dataLines = new ArrayList<>(); try { Files.lines(Paths.get(uri)) .filter(s -> !s.isEmpty()) .filter(s -> !s.startsWith("@")) .forEach(dataLines::add); } catch (IOException e) { e.printStackTrace(); } return dataLines; } public static void saveAsFile(List<String> arrayToPrintToFile, String nameOfFile){ //create empty file File file = new File(nameOfFile); try{ PrintWriter pr = new PrintWriter(file); arrayToPrintToFile.forEach(pr::println); pr.close(); } catch (Exception e){ System.out.println(e.toString()); System.out.println("Writing to file failed"); } } public static int ordinalIndexOf(String s, char c, int i) { int pos = s.indexOf(c,0); while( i-- > 0 && pos != -1) pos = s.indexOf(c,pos+1); return pos; } public static boolean isEmptyString(String s){ return s.equals(""); } public static String getHeader(List<Window> windows){ String newLine = "\n"; String ret = "@RELATION action" + newLine; Window window = windows.get(0); for (Pair pair :window.getListOfFeatures()) { ret = ret.concat("@ATTRIBUTE "+pair.getKey()+ "\t \t \t NUMERIC" + newLine); } Set<String> possibleLabels = new TreeSet<>(); for (Window w : windows) { possibleLabels.add(w.getLabel()); } String listOfLabels = ""; for (String s : possibleLabels) { listOfLabels = listOfLabels.concat(","+s); } listOfLabels = listOfLabels.substring(1); ret = ret.concat("@ATTRIBUTE class {"+listOfLabels+"}" + newLine + "@DATA" + newLine); return ret; } public static String convertToLine(Window w){ DecimalFormat df = new DecimalFormat("00.00000000"); String label = w.getLabel(); String ret = ""; for (Pair pair : w.getListOfFeatures()) { ret = ret.concat(df.format(pair.getValue()).replace(",", ".") + ",\t"); } ret = ret.concat(label); return ret; } public static void updateProgress(double progressPercentage) { final int width = 100; // progress bar width in chars System.out.print("\r["); int i = 0; for (; i <= (int)(progressPercentage*width); i++) { System.out.print("."); } for (; i < width; i++) { System.out.print(" "); } System.out.print("]"); } public static void updateProgressWithText(String message) { System.out.print("\r"+ message); } } <file_sep>/src/RandomTest/ClassifierNameTester.java package RandomTest; import weka.classifiers.Classifier; import weka.classifiers.functions.LibSVM; import weka.classifiers.meta.Vote; /** * Created by Rune on 24-03-2016. */ public class ClassifierNameTester { public static void main(String[] args) { Classifier svm = new LibSVM(); System.out.println(svm.getClass().getSimpleName()); Classifier vote = new Vote(); System.out.println(vote.getClass().getSimpleName()); } } <file_sep>/src/Core/ClassifierEvaluationPairComparator.java package Core; import org.apache.commons.math3.util.Pair; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import java.util.Comparator; /** * Created by Rune on 24-03-2016. */ public class ClassifierEvaluationPairComparator implements Comparator<Pair<Classifier,Evaluation>> { @Override public int compare(Pair<Classifier, Evaluation> o1, Pair<Classifier, Evaluation> o2) { Double f1 = o1.getValue().fMeasure(1); Double f2 = o2.getValue().fMeasure(1); if(f1 > f2) return -1; if(f2> f1) return 1; return 0; } } <file_sep>/src/Pipeline/StudyPipeline.java package Pipeline; import ArffFile.CompleteFeatureFileGenerator; import Core.BiasConfiguration; import Core.ClassifierEvalDescriptionTriplet; import Core.ClassifierEvalDescriptionTripletComparator; import Core.ClassifierType; import weka.classifiers.functions.LibSVM; import weka.core.*; import weka.filters.Filter; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.*; /** * Created by Rune on 15-05-2016. */ public class StudyPipeline { private static final int CROSS_VALIDATION_NUMBER_OF_FOLDS = 10; private static final int PQ_CAPACITY_FOR_SVM = 3; public static void main(String[] args){ if(args.length != 2){ System.out.println("Wrong number of arguments, expected 2"); return; } String path_to_new_events = args[0]; String path_to_save_classifiers_in = args[1]; //import original data ExecutorService executorService = Executors.newFixedThreadPool(8); try { createClassifiers(ClassifierType.EVENT_SNIFFER, path_to_new_events, path_to_save_classifiers_in, executorService); createClassifiers(ClassifierType.SIT_STAND_CLASSIFIER, path_to_new_events, path_to_save_classifiers_in, executorService); } catch (Exception e) { e.printStackTrace(); } executorService.shutdown(); } private static void createClassifiers(ClassifierType type_of_classifer, String path_to_new_events, String path_to_save_classifiers_in ,ExecutorService executorService ) throws Exception { System.out.println("Importing data"); String fromLocation = "D:\\Dropbox\\Thesis\\Data\\RawDataProx"; String toLocation = "D:\\Dropbox\\Thesis\\Data\\CompleteFeatureFiles\\"; double window_size_seconds = 3; BiasConfiguration biasForIT119 = new BiasConfiguration( 0.005f, -0.030f, -0.089f, -0.011f, 0.024f, 0.083f); List<String> featureFileURIs = CompleteFeatureFileGenerator.createCompleteFeatureFileWithProximitySeparateFile( fromLocation,toLocation, window_size_seconds, type_of_classifer, biasForIT119); List<Instances> all_data_inp = new ArrayList<>(); for (String file : featureFileURIs) { Instances data = CompleteFeatureFileGenerator.getInstances(file); for (Instance instance : data) { instance.setWeight(0.75); //TODO: It would be better if this was somehow a function of time } all_data_inp.add(data); } Instances alldata = new Instances(all_data_inp.get(0)); for (int i = 1; i < all_data_inp.size(); i++) { for (Instance instance : all_data_inp.get(i)) { alldata.add(instance); } } //import new data String filename_for_new_feature_file = CompleteFeatureFileGenerator.createCompleteFeatureFileWithCorrectionsIncluded( path_to_new_events, path_to_new_events+"\\newfeatures.arff", type_of_classifer); if (filename_for_new_feature_file == null){ //no new data } else { //convert new data to instances Instances data_for_new_windows = CompleteFeatureFileGenerator.getInstances(filename_for_new_feature_file); for (Instance instance : data_for_new_windows) { instance.setWeight(1); } for (Instance data_for_new_window : data_for_new_windows) { alldata.add(data_for_new_window); } } //create filters ArrayList<Filter> listOfFilters = new ArrayList<>(); //listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ECDF_RAW", "class"})); //listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ECDF_RAW","START_ORIENTATION","END_ORIENTATION","PROXIMITY", "class"})); // listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ECDF_DISC", "class"})); // listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ECDF_DISC", "START_ORIENTATION","END_ORIENTATION","PROXIMITY", "class"})); listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ECDF_UP", "ECDF_REST", "class"})); listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ECDF_UP", "ECDF_REST","START_ORIENTATION","END_ORIENTATION","PROXIMITY", "class"})); //listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ECDF_UP", "ECDF_RAW_Y", "class"})); //listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ECDF_UP", "ECDF_RAW_Y", "START_ORIENTATION","END_ORIENTATION","PROXIMITY", "class"})); //listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ORIENTATION", "PROXIMITY","class"})); listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ZERO_CROSSINGS_VERTICAL", "PURITY", "VERTICAL_POSITIVE_ACCELERATION", "VERTICAL_NEGATIVE_ACCELERATION","PROXIMITY", "class"})); listOfFilters.add(FilteredClassifierPipeline.createFilterInclusive(alldata, new String[]{"ZERO_CROSSINGS_VERTICAL", "PURITY", "VERTICAL_POSITIVE_ACCELERATION", "VERTICAL_NEGATIVE_ACCELERATION", "START_ORIENTATION","END_ORIENTATION","PROXIMITY", "class"})); //listOfFilters.add(FilteredClassifierPipeline.createFilterExclusive(alldata, new String[]{"ECDF","ORIENTATION","TIMED_VERTICAL", "ZERO_CROSSING", "PURITY", "VERTICAL_POSITIVE_ACCELERATION", "VERTICAL_NEGATIVE_ACCELERATION"})); //train the classifiers ArrayList<ClassifierEvalDescriptionTriplet> individualClassifiers = trainIndividualClassifiers(executorService, alldata, listOfFilters,type_of_classifer); Collections.sort(individualClassifiers, new ClassifierEvalDescriptionTripletComparator()); //output the best one String folderPath = "D:\\Dropbox\\Thesis\\Data\\Output"+System.currentTimeMillis()+"\\"; //noinspection ResultOfMethodCallIgnored new File(folderPath).mkdir(); //export individual classifiers in case something goes wrong with the ensembles FilteredClassifierPipeline.exportClassifiers(individualClassifiers.subList(0,1), path_to_save_classifiers_in, type_of_classifer); } private static ArrayList<ClassifierEvalDescriptionTriplet> trainIndividualClassifiers(ExecutorService executorService, Instances alldata, List<Filter> listOfFilters, ClassifierType type_of_classifer) { ArrayList<ClassifierEvalDescriptionTriplet> individualClassifiers = new ArrayList<>(); ArrayList<Callable<ArrayList<ClassifierEvalDescriptionTriplet>>> individualJobs = new ArrayList<>(); for (Filter filter : listOfFilters) { individualJobs.add(new LibSVMGridSearch(alldata,type_of_classifer,new SelectedTag(LibSVM.KERNELTYPE_RBF, LibSVM.TAGS_KERNELTYPE),PQ_CAPACITY_FOR_SVM,filter,CROSS_VALIDATION_NUMBER_OF_FOLDS)); } List<Future<ArrayList<ClassifierEvalDescriptionTriplet>>> individualClassifierFutures = null; try { individualClassifierFutures = executorService.invokeAll(individualJobs); } catch (InterruptedException e) { e.printStackTrace(); } if (individualClassifierFutures != null) { for (Future<ArrayList<ClassifierEvalDescriptionTriplet>> future: individualClassifierFutures) { try { individualClassifiers.addAll(future.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } return individualClassifiers; } } <file_sep>/src/Core/WindowImporter.java package Core; import org.apache.commons.math3.util.Pair; import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by Rune on 15-05-2016. */ public class WindowImporter { public static List<Window> getWindows(String fromLocation){ List<String> files = Util.listOfFilesInDirectory(fromLocation); ArrayList<Window> windows = new ArrayList<>(); for (String file : files) { if(file.contains("window")){ try { windows.add(getWindowFromFile(file)); } catch (IOException e) { e.printStackTrace(); } } } return windows; } public static List<Window> getCorrectedWindowsMutlipleUsersUnaplyBias(String fromLocation){ List<String> files = Util.listOfFilesInDirectory(fromLocation); List<String> corrections_files = new ArrayList<>(); List<String> bias_configurations = new ArrayList<>(); for (String file : files) { if(file.contains("correctionsfile.csv")) { corrections_files.add(file); } if(file.contains("biasconfiguration.csv")){ bias_configurations.add(file); } } HashMap<String, String> corrections_map = new HashMap<>(); HashMap<String, BiasConfiguration> biasConfigurationHashMap = new HashMap<>(); BufferedReader bufferedReader = null; BufferedReader bufferedReader1 = null; String line; String splitter = ","; for (String corrections_file : corrections_files) { String biasconfigfile = corrections_file.replaceFirst("correctionsfile", "biasconfiguration"); try { bufferedReader = new BufferedReader(new FileReader(corrections_file)); bufferedReader1 = new BufferedReader(new FileReader(biasconfigfile)); String[] biasConfLine = bufferedReader1.readLine().split(splitter); BiasConfiguration biasConfiguration = new BiasConfiguration(Float.valueOf(biasConfLine[0]),Float.valueOf(biasConfLine[1]),Float.valueOf(biasConfLine[2]),Float.valueOf(biasConfLine[3]),Float.valueOf(biasConfLine[4]),Float.valueOf(biasConfLine[5])); while ((line = bufferedReader.readLine()) != null) { String[] correction_line = line.split(splitter); if (correction_line.length == 1) { corrections_map.put(correction_line[0], "null"); } else { corrections_map.put(correction_line[0], correction_line[1]); } biasConfigurationHashMap.put(correction_line[0], biasConfiguration); } } catch (IOException e) { e.printStackTrace(); } } ArrayList<Window> windows = new ArrayList<>(); for (String file : files) { if(file.contains("window")){ try { Window w = getWindowFromFile(file); File window_file = new File(file); if(window_file.length()< 10 ) continue; String filename = file.substring(file.lastIndexOf("\\")+7); String correction = corrections_map.get(filename); if(correction.equals("sit")){ w.setLabel("sit"); } else if(correction.equals("stand")){ w.setLabel("stand"); } else { w.setLabel("null"); } BiasConfiguration biasConfiguration = biasConfigurationHashMap.get(filename); for (FeatureLine fl : w.getListOfFeatureLines()){ fl.applyBias(biasConfiguration); } windows.add(w); } catch (IOException e) { e.printStackTrace(); } } } return windows; } public static List<Window> getCorrectedWindowsMultipleUsers(String fromLocation){ List<String> files = Util.listOfFilesInDirectory(fromLocation); List<String> corrections_files = new ArrayList<>(); for (String file : files) { if(file.contains("correctionsfile.csv")) { corrections_files.add(file); } } HashMap<String, String> corrections_map = new HashMap<>(); BufferedReader bufferedReader = null; String line; String splitter = ","; for (String corrections_file : corrections_files) { try { bufferedReader = new BufferedReader(new FileReader(corrections_file)); while ((line = bufferedReader.readLine()) != null) { String[] correction_line = line.split(splitter); if (correction_line.length == 1) { corrections_map.put(correction_line[0], "null"); } else { corrections_map.put(correction_line[0], correction_line[1]); } } } catch (IOException e) { e.printStackTrace(); } } ArrayList<Window> windows = new ArrayList<>(); for (String file : files) { if(file.contains("window")){ try { Window w = getWindowFromFile(file); File window_file = new File(file); if(window_file.length()< 10 ) continue; String filename = file.substring(file.lastIndexOf("\\")+7); String correction = corrections_map.get(filename); if(correction.equals("sit")){ w.setLabel("sit"); } else if(correction.equals("stand")){ w.setLabel("stand"); } else { w.setLabel("null"); } windows.add(w); } catch (IOException e) { e.printStackTrace(); } } } return windows; } public static List<Window> getCorrectedWindows(String fromLocation){ List<String> files = Util.listOfFilesInDirectory(fromLocation); String corrections_file = ""; for (String file : files) { if(file.contains("correctionsfile.csv")) { corrections_file = file; break; } } HashMap<String, String> corrections_map = new HashMap<>(); BufferedReader bufferedReader = null; String line; String splitter = ","; try { bufferedReader = new BufferedReader(new FileReader(corrections_file)); while((line = bufferedReader.readLine()) != null){ String[] correction_line = line.split(splitter); if(correction_line.length == 1){ corrections_map.put(correction_line[0], "null"); } else { corrections_map.put(correction_line[0], correction_line[1]); } } } catch (IOException e) { e.printStackTrace(); } ArrayList<Window> windows = new ArrayList<>(); for (String file : files) { if(file.contains("window")){ try { Window w = getWindowFromFile(file); File window_file = new File(file); if(window_file.length()< 10 ) continue; String filename = file.substring(file.lastIndexOf("\\")+7); String correction = corrections_map.get(filename); if(correction.equals("sit")){ w.setLabel("sit"); } else if(correction.equals("stand")){ w.setLabel("stand"); } else { w.setLabel("null"); } windows.add(w); } catch (IOException e) { e.printStackTrace(); } } } return windows; } private static Window getWindowFromFile(String path) throws IOException { Object result = new ArrayList<>(); FileInputStream fis; ObjectInputStream ois = null; try { fis = new FileInputStream(path); ois = new ObjectInputStream(fis); result = ois.readObject(); } catch (OptionalDataException e) { if (!e.eof) throw e; } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } finally { assert ois != null; ois.close(); } return (Window) result; } } <file_sep>/src/Core/Window.java package Core; import org.apache.commons.math3.analysis.UnivariateFunction; import org.apache.commons.math3.analysis.interpolation.SplineInterpolator; import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction; import org.apache.commons.math3.complex.Complex; import org.apache.commons.math3.transform.DftNormalization; import org.apache.commons.math3.transform.FastFourierTransformer; import org.apache.commons.math3.transform.TransformType; import org.apache.commons.math3.util.Pair; import java.io.Serializable; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; /** * Created by Rune on 07-03-2016. */ public class Window implements Serializable { private List<String> listOfLines; private String label; private List<FeatureLine> listOfFeatureLines; private List<Pair<?,?>> listOfFeatures; public Window(Window window){ this.listOfFeatureLines = new ArrayList<>(); this.listOfFeatures = new ArrayList<>(); for (FeatureLine fl : window.getListOfFeatureLines()) { listOfFeatureLines.add(new FeatureLine(fl)); } this.label = window.getLabel(); } public static Window createFromEventRecordList(List<SensorEventRecord> listOfEvents, String label){ Window w = new Window(); w.setLabel(label); for (SensorEventRecord ser :listOfEvents) { double accX = (null != ser.getAcceleration()) ? ser.getAcceleration()[0] : 0; double accY = (null != ser.getAcceleration()) ? ser.getAcceleration()[1] : 0; double accZ = (null != ser.getAcceleration()) ? ser.getAcceleration()[2] : 0; double rotX = (null != ser.getRotation()) ? ser.getRotation()[0] : 0; double rotY = (null != ser.getRotation()) ? ser.getRotation()[1] : 0; double rotZ = (null != ser.getRotation()) ? ser.getRotation()[2] : 0; double graX = (null != ser.getGravity()) ? ser.getGravity()[0] : 0; double graY = (null != ser.getGravity()) ? ser.getGravity()[1] : 0; double graZ = (null != ser.getGravity()) ? ser.getGravity()[2] : 0; int ts = (int) ser.getTimestamp(); FeatureLine fl = new FeatureLine(accX,accY,accZ,rotX,rotY,rotZ,graX,graY,graZ,ts); w.addFeatureLine(fl); } return w; } public static Window createStandSitWindowWithProximity(List<SensorEventRecord> listOfRecords, String label){ Window w = new Window(); w.setLabel(label); for (SensorEventRecord ser : listOfRecords) { double accX = (null != ser.getAcceleration()) ? ser.getAcceleration()[0] : 0; double accY = (null != ser.getAcceleration()) ? ser.getAcceleration()[1] : 0; double accZ = (null != ser.getAcceleration()) ? ser.getAcceleration()[2] : 0; double rotX = (null != ser.getRotation()) ? ser.getRotation()[0] : 0; double rotY = (null != ser.getRotation()) ? ser.getRotation()[1] : 0; double rotZ = (null != ser.getRotation()) ? ser.getRotation()[2] : 0; double graX = (null != ser.getGravity()) ? ser.getGravity()[0] : 0; double graY = (null != ser.getGravity()) ? ser.getGravity()[1] : 0; double graZ = (null != ser.getGravity()) ? ser.getGravity()[2] : 0; ProximityValue proximity = ser.getProximity(); int ts = (int) ser.getTimestamp(); FeatureLine fl = new FeatureLine(accX,accY,accZ,rotX,rotY,rotZ,graX,graY,graZ,proximity,ts); w.addFeatureLine(fl); } return w; } public static Window createStandSitWindowWithProximityFromString(List<String> listOfLines, String label, BiasConfiguration bias){ Window w = new Window(); w.setLabel(label); for (String str: listOfLines){ if(!str.contains("---")) { FeatureLine fl = convertToFeatureLineWithProximity(str); fl.applyBias(bias); w.addFeatureLine(fl); } } return w; } public static Window createStandSitWindowWithProximityFromString(List<String> listOfLines, String label){ Window w = new Window(); w.setLabel(label); for (String str: listOfLines){ if(!str.contains("---")) { FeatureLine fl = convertToFeatureLineWithProximity(str); w.addFeatureLine(fl); } } return w; } private static FeatureLine convertToFeatureLineWithProximity(String str) { String[] listOfStuff = str.split(" | "); return new FeatureLine( Double.valueOf(listOfStuff[0]), Double.valueOf(listOfStuff[2]), Double.valueOf(listOfStuff[4]), Double.valueOf(listOfStuff[6]), Double.valueOf(listOfStuff[8]), Double.valueOf(listOfStuff[10]), Double.valueOf(listOfStuff[12]), Double.valueOf(listOfStuff[14]), Double.valueOf(listOfStuff[16]), (listOfStuff[18].contains("FAR"))? ProximityValue.FAR : ProximityValue.NEAR, (int) Long.parseLong(listOfStuff[20])); } public static Window createTapWindowFromString(List<String> listOfLines, String label){ Window w = new Window(); w.setLabel(label); for (String str: listOfLines){ FeatureLine fl = convertToTapFeatureLine(str); w.addFeatureLine(fl); } return w; } public Window(){ //"Factory method" constructor this.listOfFeatureLines = new ArrayList<>(); this.listOfFeatures = new ArrayList<>(); } public Window(List<String> listOfLines, String label) { this.listOfLines = listOfLines; this.label = label; this.listOfFeatureLines = new ArrayList<>(); this.listOfFeatures = new ArrayList<>(); createFeatureLinesFromStrings(); } public void createFeatureLinesFromStrings(){ listOfFeatureLines = new ArrayList<>(); for (String line : listOfLines) { if(!line.contains("---")) listOfFeatureLines.add(convertStringToFeatureLine(line)); } } private static FeatureLine convertToTapFeatureLine(String str) { String[] listOfStuff = str.split(" | "); return new FeatureLine( Double.valueOf(listOfStuff[0]), Double.valueOf(listOfStuff[2]), Double.valueOf(listOfStuff[4]), Double.valueOf(listOfStuff[6]), Double.valueOf(listOfStuff[8]), Double.valueOf(listOfStuff[10]), (int) Long.parseLong(listOfStuff[12])); } public void addFeatureLine(FeatureLine fl){ this.listOfFeatureLines.add(fl); } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public List<String> getListOfLines() { return listOfLines; } public void addLine(String line){ listOfLines.add(line); } private FeatureLine convertStringToFeatureLine(String line) { String[] listOfStuff = line.split(" | "); return new FeatureLine( Double.valueOf(listOfStuff[0]), Double.valueOf(listOfStuff[2]), Double.valueOf(listOfStuff[4]), Double.valueOf(listOfStuff[12]), Double.valueOf(listOfStuff[14]), Double.valueOf(listOfStuff[16]), Double.valueOf(listOfStuff[6]), Double.valueOf(listOfStuff[8]), Double.valueOf(listOfStuff[10]), (int) Long.parseLong(listOfStuff[18])); } public void calculateAllFeatures(){ calculateECDFRepresentationDisc(30); calculateECDFRepresentationRaw(30); calculateECDFRepresentationUpDown(30); calculateFeaturesForRawMovement(); calculateFeaturesForGravityDiscountedMovement(); calculateFeaturesForRelativeMovement(); calculateStartingOrientation(); calculateEndingOrientation(); // calculateOrientationChange(); calculateOrientationJitter(); calculateVerticalTimedDistribution(30); calculateSumOfUpwardsAcceleration(); calculateSumOfDownwardsAcceleration(); calculateZeroCrossings(); calculateNumberOfTaps(); calculateProximity(); } public void calculateProximity(){ Double start = proximityValueToDouble(listOfFeatureLines.get(0).getProximity()); Double end = proximityValueToDouble(listOfFeatureLines.get(listOfFeatureLines.size()-1).getProximity()); Double total = 0.0; for (FeatureLine fl : listOfFeatureLines) { total+= proximityValueToDouble(fl.getProximity()); } Double mean = total/listOfFeatureLines.size(); listOfFeatures.add(new Pair<Object, Object>("PROXIMITY_START",start)); listOfFeatures.add(new Pair<Object, Object>("PROXIMITY_END", end)); listOfFeatures.add(new Pair<Object, Object>("PROXIMITY_MEAN", mean)); } private Double proximityValueToDouble(ProximityValue proximity) { return (proximity == ProximityValue.FAR)? 5.0 : 0.0; } public void calculateNumberOfTaps(){ ArrayList<Double> upValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { upValues.add(featureLine.getAccZ()); xAxisDummy.add(i); i++; } double[] up = new double[upValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < upValues.size(); j++) { up[j] = upValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction effAccZFunction = interpolator.interpolate(dummy,up); UnivariateFunction derivativeEffAccZFunction = effAccZFunction.derivative(); ArrayList<Double> derivativeValues = new ArrayList<>(); for (int j = 0; j < listOfFeatureLines.size(); j++) { derivativeValues.add(derivativeEffAccZFunction.value(j)); } ArrayList<Integer> possibleTaps = new ArrayList<>(); int max_measurements_between_taps = 70; Double taps = 0.0; int measurements_to_consider = 10; int jump_after_tap = 15; double threshhold_for_window = 60; double running_total = 0; Queue<Double> running_window = new LinkedBlockingQueue<>(); for (int j = 0; j < listOfFeatureLines.size(); j++) { if(running_window.size() >= measurements_to_consider) { running_window.poll(); } else { running_window.add(derivativeValues.get(j)); continue; } running_window.add(derivativeValues.get(j)); double total_for_window = sum_of_running_window(running_window.iterator()); if( total_for_window > threshhold_for_window) { Integer middle_of_window = j + (measurements_to_consider/2); possibleTaps.add(middle_of_window); //flush the running window while(running_window.size() > 0) running_window.poll(); j = j + jump_after_tap; } } ArrayList<Integer> tap_dists = new ArrayList<>(possibleTaps); if(possibleTaps.size()> 1) { for (int j = 0; j < possibleTaps.size(); j++) { int dist_left = Integer.MAX_VALUE; int dist_right = Integer.MAX_VALUE; if(j > 0){ dist_left = possibleTaps.get(j) - possibleTaps.get(j-1); } if(j< possibleTaps.size()-1){ dist_right = possibleTaps.get(j+1) - possibleTaps.get(j); } int minimum = Math.min(dist_left, dist_right); tap_dists.set(j, minimum); } for (int j = 0; j < tap_dists.size(); j++) { if (tap_dists.get(j) < max_measurements_between_taps) taps++; } } else { taps = 0.0; } // System.out.println("PossibleTaps: " + possibleTaps.toString() + " TapDists: " +tap_dists.toString()); listOfFeatures.add(new Pair<Object, Object>("DERIVATIVE_OF_DISC_Z_NUMBER_OF_TAPS", taps)); } private double sum_of_running_window(Iterator<Double> iterator) { double previous = iterator.next(); double total = 0; while(iterator.hasNext()){ double current = iterator.next(); total += Math.abs(current-previous); previous = current; } return total; } public void calculateFrequencyFeaturesRawX(){ int samples = listOfFeatureLines.size(); int size = 2; while(size < samples) size = size * 2; double[] x_values = new double[size]; Arrays.fill(x_values, 0); for (int i = 0; i < samples; i++) { x_values[i] = listOfFeatureLines.get(i).getAccX(); } FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); Complex[] coefficients = fft.transform(x_values, TransformType.FORWARD); double DC = coefficients[0].getReal(); double sumOfSquaredCoefficients = 0; for (int i = 0; i < samples; i++) { sumOfSquaredCoefficients += Math.pow(coefficients[i].getReal(),2) + Math.pow(coefficients[i].getImaginary(),2); } double spectral_energy = sumOfSquaredCoefficients/samples; double[] c = new double[samples]; for (int i = 0; i < samples; i++) { c[i] = Math.sqrt(Math.pow(coefficients[i].getReal(),2)+ Math.pow(coefficients[i].getImaginary(),2))/Math.sqrt(sumOfSquaredCoefficients); } double entropy = 0; for (int i = 0; i < samples; i++) { entropy += c[i] + Math.log(c[i]); } listOfFeatures.add(new Pair<Object, Object>("RAW_X_DC", DC)); listOfFeatures.add(new Pair<Object, Object>("RAW_X_SPECTRAL_ENERGY", spectral_energy)); listOfFeatures.add(new Pair<Object, Object>("RAW_X_ENTROPY", entropy)); } public void calculateFrequencyFeaturesRawY() { int samples = listOfFeatureLines.size(); int size = 2; while(size < samples) size = size * 2; double[] y_values = new double[size]; Arrays.fill(y_values, 0); for (int i = 0; i < samples; i++) { y_values[i] = listOfFeatureLines.get(i).getAccY(); } FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); Complex[] coefficients = fft.transform(y_values, TransformType.FORWARD); double DC = coefficients[0].getReal(); double sumOfSquaredCoefficients = 0; for (int i = 0; i < samples; i++) { sumOfSquaredCoefficients += Math.pow(coefficients[i].getReal(),2) + Math.pow(coefficients[i].getImaginary(),2); } double spectral_energy = sumOfSquaredCoefficients/samples; double[] c = new double[samples]; for (int i = 0; i < samples; i++) { c[i] = Math.sqrt(Math.pow(coefficients[i].getReal(),2)+ Math.pow(coefficients[i].getImaginary(),2))/Math.sqrt(sumOfSquaredCoefficients); } double entropy = 0; for (int i = 0; i < samples; i++) { entropy += c[i] + Math.log(c[i]); } listOfFeatures.add(new Pair<Object, Object>("RAW_Y_DC", DC)); listOfFeatures.add(new Pair<Object, Object>("RAW_Y_SPECTRAL_ENERGY", spectral_energy)); listOfFeatures.add(new Pair<Object, Object>("RAW_Y_ENTROPY", entropy)); } public void calculateZeroCrossings(){ ArrayList<Integer> zeroCrossingsList = new ArrayList<>(); double previous = Double.MIN_VALUE; for (int i = 0; i < listOfFeatureLines.size(); i++) { double current = listOfFeatureLines.get(i).getAccUp(); if(previous == Double.MIN_VALUE){ previous = current; } else { boolean previous_positive = previous >= 0; boolean current_positive = current >= 0; if((previous_positive && current_positive) || (!previous_positive && !current_positive)){ //no zerocrossing } else { zeroCrossingsList.add(i); } previous = current; } } //for all zero crossings get positive acceleration and negative acceleration on both sides if(zeroCrossingsList.size() < 1){ listOfFeatures.add(new Pair<Object, Object>("ZERO_CROSSINGS_VERTICAL", zeroCrossingsList.size())); listOfFeatures.add(new Pair<Object, Object>("PURITY_BEFORE_VERTICAL", 0)); listOfFeatures.add(new Pair<Object, Object>("PURITY_AFTER_VERTICAL", 0)); listOfFeatures.add(new Pair<Object, Object>("VERTICAL_POSITIVE_ACCELERATION_BEFORE", 0)); listOfFeatures.add(new Pair<Object, Object>("VERTICAL_NEGATIVE_ACCELERATION_BEFORE", 0)); listOfFeatures.add(new Pair<Object, Object>("VERTICAL_POSITIVE_ACCELERATION_AFTER", 0)); listOfFeatures.add(new Pair<Object, Object>("VERTICAL_NEGATIVE_ACCELERATION_AFTER", 0)); return; } double best_purity = Double.MIN_VALUE; double best_positive_before = 0; double best_negative_before = 0; double best_positive_after = 0; double best_negative_after = 0; int best_zero_crossing = 0; for (int i = 0; i < zeroCrossingsList.size(); i++) { double positive_before = 0; double negative_before = 0; double positive_after = 0; double negative_after = 0; for (int j = 0; j < listOfFeatureLines.size(); j++) { double current = listOfFeatureLines.get(j).getAccUp(); double processed_current = Math.abs(current);//Math.pow(current,2); if(j < zeroCrossingsList.get(i)){ //before if(current >= 0) positive_before += processed_current; else negative_before += processed_current; } else { //after if(current >= 0) positive_after += processed_current; else negative_after += processed_current; } } double total_acceleration_before = positive_before - negative_before; double total_acceleration_after = positive_after - negative_after; double purity_before = Math.max(positive_before/total_acceleration_before, negative_before/total_acceleration_before); double purity_after = Math.max(positive_after/total_acceleration_after, negative_after/total_acceleration_after); //double purity = Math.min(purity_before, purity_after); double purity = Math.abs(total_acceleration_after-total_acceleration_before); if(best_purity < purity){ best_purity = purity; best_negative_after = negative_after; best_negative_before = negative_before; best_positive_after = positive_after; best_positive_before = positive_before; best_zero_crossing = zeroCrossingsList.get(i); } } double best_total_acceleration_before = best_negative_before + best_positive_before; double best_total_acceleration_after = best_positive_after + best_negative_after; double best_purity_before = Math.max(best_positive_before/best_total_acceleration_before, best_negative_before/best_total_acceleration_before); double best_purity_after = Math.max(best_positive_after/best_total_acceleration_after, best_negative_after/best_total_acceleration_after); listOfFeatures.add(new Pair<Object, Object>("ZERO_CROSSINGS_VERTICAL", zeroCrossingsList.size())); listOfFeatures.add(new Pair<Object, Object>("PURITY_BEFORE_VERTICAL", best_purity_before)); listOfFeatures.add(new Pair<Object, Object>("PURITY_AFTER_VERTICAL", best_purity_after)); listOfFeatures.add(new Pair<Object, Object>("VERTICAL_POSITIVE_ACCELERATION_BEFORE", best_positive_before)); listOfFeatures.add(new Pair<Object, Object>("VERTICAL_NEGATIVE_ACCELERATION_BEFORE", best_negative_before)); listOfFeatures.add(new Pair<Object, Object>("VERTICAL_POSITIVE_ACCELERATION_AFTER", best_positive_after)); listOfFeatures.add(new Pair<Object, Object>("VERTICAL_NEGATIVE_ACCELERATION_AFTER", best_negative_after)); } public void calculateFrequencyFeaturesRawZ() { int samples = listOfFeatureLines.size(); int size = 2; while(size < samples) size = size * 2; double[] z_values = new double[size]; Arrays.fill(z_values, 0); for (int i = 0; i < samples; i++) { z_values[i] = listOfFeatureLines.get(i).getAccZ(); } FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); Complex[] coefficients = fft.transform(z_values, TransformType.FORWARD); double DC = coefficients[0].getReal(); double sumOfSquaredCoefficients = 0; for (int i = 0; i < samples; i++) { sumOfSquaredCoefficients += Math.pow(coefficients[i].getReal(),2) + Math.pow(coefficients[i].getImaginary(),2); } double spectral_energy = sumOfSquaredCoefficients/samples; double[] c = new double[samples]; for (int i = 0; i < samples; i++) { c[i] = Math.sqrt(Math.pow(coefficients[i].getReal(),2)+ Math.pow(coefficients[i].getImaginary(),2))/Math.sqrt(sumOfSquaredCoefficients); } double entropy = 0; for (int i = 0; i < samples; i++) { entropy += c[i] + Math.log(c[i]); } listOfFeatures.add(new Pair<Object, Object>("RAW_Z_DC", DC)); listOfFeatures.add(new Pair<Object, Object>("RAW_Z_SPECTRAL_ENERGY", spectral_energy)); listOfFeatures.add(new Pair<Object, Object>("RAW_Z_ENTROPY", entropy)); } public void calculateFrequencyFeaturesDiscX(){ int samples = listOfFeatureLines.size(); int size = 2; while(size < samples) size = size * 2; double[] x_values = new double[size]; Arrays.fill(x_values, 0); for (int i = 0; i < samples; i++) { x_values[i] = listOfFeatureLines.get(i).getEffAccX(); } FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); Complex[] coefficients = fft.transform(x_values, TransformType.FORWARD); double DC = coefficients[0].getReal(); double sumOfSquaredCoefficients = 0; for (int i = 0; i < samples; i++) { sumOfSquaredCoefficients += Math.pow(coefficients[i].getReal(),2) + Math.pow(coefficients[i].getImaginary(),2); } double spectral_energy = sumOfSquaredCoefficients/samples; double[] c = new double[samples]; for (int i = 0; i < samples; i++) { c[i] = Math.sqrt(Math.pow(coefficients[i].getReal(),2)+ Math.pow(coefficients[i].getImaginary(),2))/Math.sqrt(sumOfSquaredCoefficients); } double entropy = 0; for (int i = 0; i < samples; i++) { entropy += c[i] + Math.log(c[i]); } listOfFeatures.add(new Pair<Object, Object>("EFF_X_DC", DC)); listOfFeatures.add(new Pair<Object, Object>("EFF_X_SPECTRAL_ENERGY", spectral_energy)); listOfFeatures.add(new Pair<Object, Object>("EFF_X_ENTROPY", entropy)); } public void calculateFrequencyFeaturesDiscY() { int samples = listOfFeatureLines.size(); int size = 2; while(size < samples) size = size * 2; double[] y_values = new double[size]; Arrays.fill(y_values, 0); for (int i = 0; i < samples; i++) { y_values[i] = listOfFeatureLines.get(i).getEffAccY(); } FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); Complex[] coefficients = fft.transform(y_values, TransformType.FORWARD); double DC = coefficients[0].getReal(); double sumOfSquaredCoefficients = 0; for (int i = 0; i < samples; i++) { sumOfSquaredCoefficients += Math.pow(coefficients[i].getReal(),2) + Math.pow(coefficients[i].getImaginary(),2); } double spectral_energy = sumOfSquaredCoefficients/samples; double[] c = new double[samples]; for (int i = 0; i < samples; i++) { c[i] = Math.sqrt(Math.pow(coefficients[i].getReal(),2)+ Math.pow(coefficients[i].getImaginary(),2))/Math.sqrt(sumOfSquaredCoefficients); } double entropy = 0; for (int i = 0; i < samples; i++) { entropy += c[i] + Math.log(c[i]); } listOfFeatures.add(new Pair<Object, Object>("EFF_Y_DC", DC)); listOfFeatures.add(new Pair<Object, Object>("EFF_Y_SPECTRAL_ENERGY", spectral_energy)); listOfFeatures.add(new Pair<Object, Object>("EFF_Y_ENTROPY", entropy)); } public void calculateFrequencyFeaturesDiscZ() { int samples = listOfFeatureLines.size(); int size = 2; while(size < samples) size = size * 2; double[] z_values = new double[size]; Arrays.fill(z_values, 0); for (int i = 0; i < samples; i++) { z_values[i] = listOfFeatureLines.get(i).getEffAccZ(); } FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); Complex[] coefficients = fft.transform(z_values, TransformType.FORWARD); double DC = coefficients[0].getReal(); double sumOfSquaredCoefficients = 0; for (int i = 0; i < samples; i++) { sumOfSquaredCoefficients += Math.pow(coefficients[i].getReal(),2) + Math.pow(coefficients[i].getImaginary(),2); } double spectral_energy = sumOfSquaredCoefficients/samples; double[] c = new double[samples]; for (int i = 0; i < samples; i++) { c[i] = Math.sqrt(Math.pow(coefficients[i].getReal(),2)+ Math.pow(coefficients[i].getImaginary(),2))/Math.sqrt(sumOfSquaredCoefficients); } double entropy = 0; for (int i = 0; i < samples; i++) { entropy += c[i] + Math.log(c[i]); } listOfFeatures.add(new Pair<Object, Object>("EFF_Z_DC", DC)); listOfFeatures.add(new Pair<Object, Object>("EFF_Z_SPECTRAL_ENERGY", spectral_energy)); listOfFeatures.add(new Pair<Object, Object>("EFF_Z_ENTROPY", entropy)); } public void calculateFrequencyFeaturesHorizontal() { int samples = listOfFeatureLines.size(); int size = 2; while(size < samples) size = size * 2; double[] hor_values = new double[size]; Arrays.fill(hor_values, 0); for (int i = 0; i < samples; i++) { hor_values[i] = listOfFeatureLines.get(i).getAccRest(); } FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); Complex[] coefficients = fft.transform(hor_values, TransformType.FORWARD); double DC = coefficients[0].getReal(); double sumOfSquaredCoefficients = 0; for (int i = 0; i < samples; i++) { sumOfSquaredCoefficients += Math.pow(coefficients[i].getReal(),2) + Math.pow(coefficients[i].getImaginary(),2); } double spectral_energy = sumOfSquaredCoefficients/samples; double[] c = new double[samples]; for (int i = 0; i < samples; i++) { c[i] = Math.sqrt(Math.pow(coefficients[i].getReal(),2)+ Math.pow(coefficients[i].getImaginary(),2))/Math.sqrt(sumOfSquaredCoefficients); } double entropy = 0; for (int i = 0; i < samples; i++) { entropy += c[i] + Math.log(c[i]); } listOfFeatures.add(new Pair<Object, Object>("HORIZONTAL_DC", DC)); listOfFeatures.add(new Pair<Object, Object>("HORIZONTAL_SPECTRAL_ENERGY", spectral_energy)); listOfFeatures.add(new Pair<Object, Object>("HORIZONTAL_ENTROPY", entropy)); } public void calculateFrequencyFeaturesVertical() { int samples = listOfFeatureLines.size(); int size = 2; while(size < samples) size = size * 2; double[] ver_values = new double[size]; Arrays.fill(ver_values, 0); for (int i = 0; i < samples; i++) { ver_values[i] = listOfFeatureLines.get(i).getEffAccZ(); } FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD); Complex[] coefficients = fft.transform(ver_values, TransformType.FORWARD); double DC = coefficients[0].getReal(); double sumOfSquaredCoefficients = 0; for (int i = 0; i < samples; i++) { sumOfSquaredCoefficients += Math.pow(coefficients[i].getReal(),2) + Math.pow(coefficients[i].getImaginary(),2); } double spectral_energy = sumOfSquaredCoefficients/samples; double[] c = new double[samples]; for (int i = 0; i < samples; i++) { c[i] = Math.sqrt(Math.pow(coefficients[i].getReal(),2)+ Math.pow(coefficients[i].getImaginary(),2))/Math.sqrt(sumOfSquaredCoefficients); } double entropy = 0; for (int i = 0; i < samples; i++) { entropy += c[i] + Math.log(c[i]); } listOfFeatures.add(new Pair<Object, Object>("VERTICAL_DC", DC)); listOfFeatures.add(new Pair<Object, Object>("VERTICAL_SPECTRAL_ENERGY", spectral_energy)); listOfFeatures.add(new Pair<Object, Object>("VERTICAL_ENTROPY", entropy)); } public void calculateMeanVerticalAcceleration(){ double sumVert = 0; for (FeatureLine fl : listOfFeatureLines) { sumVert += fl.getAccUp(); } listOfFeatures.add(new Pair<>("VerAcc_Mean", (sumVert/listOfFeatureLines.size()))); } public void calculateVerticalSamplesAboveThreshold(double threshold){ int n = 0; for (FeatureLine fl : listOfFeatureLines) { if (fl.getAccUp()> threshold) n++; } listOfFeatures.add(new Pair<>("SAMPLES_VERTICAL_ACC_OVER_"+threshold, n)); } public void calculateVerticalSamplesBelowThreshold(double threshold){ int n = 0; for (FeatureLine fl : listOfFeatureLines) { if (fl.getAccUp()< threshold) n++; } listOfFeatures.add(new Pair<>("SAMPLES_VERTICAL_ACC_BELOW_"+threshold, n)); } public void calculateFeaturesForRelativeMovement(){ double sumAccUp = 0; double sumAccRest = 0; double upAcc_MinVal = Double.MAX_VALUE; double restAcc_MinVal = Double.MAX_VALUE; double upAcc_MaxVal = -Double.MAX_VALUE; double restAcc_MaxVal = -Double.MAX_VALUE; double upAcc_MinDif = Double.MAX_VALUE; double restAcc_MinDif = Double.MAX_VALUE; double upAcc_MaxDif = -Double.MAX_VALUE; double restAcc_MaxDif = -Double.MAX_VALUE; double sumDifUp = 0; double sumDifRest = 0; double squaredSumUp = 0; double squaredSumRest = 0; double sumPosUp = 0; double sumNegUp = 0; double sumAbsRest = 0; for (int i = 0; i < listOfFeatureLines.size(); i++) { double accUpTemp = listOfFeatureLines.get(i).getAccUp(); double accRestTemp = listOfFeatureLines.get(i).getAccRest(); sumAccUp+=accUpTemp; sumAccRest+=accRestTemp; squaredSumUp+= Math.pow(accUpTemp,2); squaredSumRest+= Math.pow(accRestTemp,2); if(upAcc_MinVal > accUpTemp) upAcc_MinVal = accUpTemp; if(restAcc_MinVal > accRestTemp) restAcc_MinVal = accRestTemp; if(upAcc_MaxVal < accUpTemp) upAcc_MaxVal = accUpTemp; if(restAcc_MaxVal < accRestTemp) restAcc_MaxVal = accRestTemp; if (i> 0){ double diffUp = accUpTemp - listOfFeatureLines.get(i-1).getAccUp(); double diffRest = accRestTemp - listOfFeatureLines.get(i-1).getAccRest(); if(upAcc_MinDif > diffUp) upAcc_MinDif = diffUp; if(upAcc_MaxDif < diffUp) upAcc_MaxDif = diffUp; if(restAcc_MinDif > diffRest) restAcc_MinDif = diffRest; if(restAcc_MaxDif < diffRest) restAcc_MaxDif = diffRest; sumDifUp+=diffUp; sumDifRest+=diffRest; if(diffUp> 0) sumPosUp+=diffUp; else sumNegUp+=diffUp; sumAbsRest+=diffRest; } } double upAcc_Mean = sumAccUp / listOfFeatureLines.size(); double restAcc_Mean = sumAccRest / listOfFeatureLines.size(); double restAcc_Mean_Absolute = sumAbsRest / listOfFeatureLines.size(); double temp = squaredSumUp/listOfFeatureLines.size(); double upAcc_RootMeanSquare = Math.sqrt(temp); temp = squaredSumRest/listOfFeatureLines.size(); double restAcc_RootMeanSquare = Math.sqrt(temp); double upAcc_AverageDif = sumDifUp / listOfFeatureLines.size(); double restAcc_AverageDif = sumDifRest / listOfFeatureLines.size(); listOfFeatures.add(new Pair<>("UpAcc_Mean", upAcc_Mean)); listOfFeatures.add(new Pair<>("UpAcc_MaxVal", upAcc_MaxVal)); listOfFeatures.add(new Pair<>("UpAcc_MaxDif", upAcc_MaxDif)); listOfFeatures.add(new Pair<>("UpAcc_MinDif", upAcc_MinDif)); listOfFeatures.add(new Pair<>("UpAcc_MinVal", upAcc_MinVal)); listOfFeatures.add(new Pair<>("UpAcc_RootMeanSquare", upAcc_RootMeanSquare)); listOfFeatures.add(new Pair<>("UpAcc_AverageDif", upAcc_AverageDif)); listOfFeatures.add(new Pair<>("RestAcc_Mean", restAcc_Mean)); listOfFeatures.add(new Pair<>("RestAcc_Mean_Absolute", restAcc_Mean_Absolute)); listOfFeatures.add(new Pair<>("RestAcc_MaxVal", restAcc_MaxVal)); listOfFeatures.add(new Pair<>("RestAcc_MaxDif", restAcc_MaxDif)); listOfFeatures.add(new Pair<>("RestAcc_MinDif", restAcc_MinDif)); listOfFeatures.add(new Pair<>("RestAcc_MinVal", restAcc_MinVal)); listOfFeatures.add(new Pair<>("RestAcc_RootMeanSquare", restAcc_RootMeanSquare)); listOfFeatures.add(new Pair<>("RestAcc_AverageDif", restAcc_AverageDif)); } public void calculateFeaturesForRawMovement(){ /* x_Raw*/ double xAccRaw_Sum = 0; double xAccRaw_MinVal = Double.MAX_VALUE; double xAccRaw_MaxVal = -Double.MAX_VALUE; double xAccRaw_MinDif = Double.MAX_VALUE; double xAccRaw_MaxDif = -Double.MAX_VALUE; double xAccRaw_DifSum = 0; double xAccRaw_SumSquared = 0; /* y_Raw*/ double yAccRaw_Sum = 0; double yAccRaw_MinVal = Double.MAX_VALUE; double yAccRaw_MaxVal = -Double.MAX_VALUE; double yAccRaw_MinDif = Double.MAX_VALUE; double yAccRaw_MaxDif = -Double.MAX_VALUE; double yAccRaw_DifSum = 0; double yAccRaw_SumSquared = 0; /* z_Raw*/ double zAccRaw_Sum = 0; double zAccRaw_MinVal = Double.MAX_VALUE; double zAccRaw_MaxVal = -Double.MAX_VALUE; double zAccRaw_MinDif = Double.MAX_VALUE; double zAccRaw_MaxDif = -Double.MAX_VALUE; double zAccRaw_DifSum = 0; double zAccRaw_SumSquared = 0; for (int i = 0; i < listOfFeatureLines.size(); i++) { /* x_Raw*/ double xAccRaw_Temp = listOfFeatureLines.get(i).getAccX(); xAccRaw_Sum+=xAccRaw_Temp; xAccRaw_SumSquared+= Math.pow(xAccRaw_Temp,2); if(xAccRaw_MinVal > xAccRaw_Temp) xAccRaw_MinVal = xAccRaw_Temp; if(xAccRaw_MaxVal < xAccRaw_Temp) xAccRaw_MaxVal = xAccRaw_Temp; /* y_Raw*/ double yAccRaw_Temp = listOfFeatureLines.get(i).getAccY(); yAccRaw_Sum+=yAccRaw_Temp; yAccRaw_SumSquared+= Math.pow(yAccRaw_Temp,2); if(yAccRaw_MinVal > yAccRaw_Temp) yAccRaw_MinVal = yAccRaw_Temp; if(yAccRaw_MaxVal < yAccRaw_Temp) yAccRaw_MaxVal = yAccRaw_Temp; /* z_Raw*/ double zAccRaw_Temp = listOfFeatureLines.get(i).getAccZ(); zAccRaw_Sum+=zAccRaw_Temp; zAccRaw_SumSquared+= Math.pow(zAccRaw_Temp,2); if(zAccRaw_MinVal > zAccRaw_Temp) zAccRaw_MinVal = zAccRaw_Temp; if(zAccRaw_MaxVal < zAccRaw_Temp) zAccRaw_MaxVal = zAccRaw_Temp; if (i> 0){ /* x_Raw*/ double xAccRaw_Dif = xAccRaw_Temp - listOfFeatureLines.get(i-1).getAccX(); if(xAccRaw_MinDif > xAccRaw_Dif) xAccRaw_MinDif = xAccRaw_Dif; if(xAccRaw_MaxDif < xAccRaw_Dif) xAccRaw_MaxDif = xAccRaw_Dif; xAccRaw_DifSum+=xAccRaw_Dif; /* y_Raw*/ double yAccRaw_Dif = yAccRaw_Temp - listOfFeatureLines.get(i-1).getAccY(); if(yAccRaw_MinDif > yAccRaw_Dif) yAccRaw_MinDif = yAccRaw_Dif; if(yAccRaw_MaxDif < yAccRaw_Dif) yAccRaw_MaxDif = yAccRaw_Dif; yAccRaw_DifSum+=yAccRaw_Dif; /* z_Raw*/ double zAccRaw_Dif = zAccRaw_Temp - listOfFeatureLines.get(i-1).getAccZ(); if(zAccRaw_MinDif > zAccRaw_Dif) zAccRaw_MinDif = zAccRaw_Dif; if(zAccRaw_MaxDif < zAccRaw_Dif) zAccRaw_MaxDif = zAccRaw_Dif; zAccRaw_DifSum+=zAccRaw_Dif; } } /* x_Raw*/ double xAccRaw_Mean = xAccRaw_Sum / listOfFeatureLines.size(); double tempX = xAccRaw_SumSquared/listOfFeatureLines.size(); double xAccRaw_RootMeanSquare = Math.sqrt(tempX); double xAccRaw_AverageDif = xAccRaw_DifSum / listOfFeatureLines.size(); /* y_Raw*/ double yAccRaw_Mean = yAccRaw_Sum / listOfFeatureLines.size(); double tempY = yAccRaw_SumSquared/listOfFeatureLines.size(); double yAccRaw_RootMeanSquare = Math.sqrt(tempY); double yAccRaw_AverageDif = yAccRaw_DifSum / listOfFeatureLines.size(); /* z_Raw*/ double zAccRaw_Mean = zAccRaw_Sum / listOfFeatureLines.size(); double tempZ = zAccRaw_SumSquared/listOfFeatureLines.size(); double zAccRaw_RootMeanSquare = Math.sqrt(tempZ); double zAccRaw_AverageDif = zAccRaw_DifSum / listOfFeatureLines.size(); listOfFeatures.add(new Pair<>("XAccRaw_Mean", xAccRaw_Mean)); listOfFeatures.add(new Pair<>("XAccRaw_MaxVal", xAccRaw_MaxVal)); listOfFeatures.add(new Pair<>("XAccRaw_MaxDif", xAccRaw_MaxDif)); listOfFeatures.add(new Pair<>("XAccRaw_MinDif", xAccRaw_MinDif)); listOfFeatures.add(new Pair<>("XAccRaw_MinVal", xAccRaw_MinVal)); listOfFeatures.add(new Pair<>("XAccRaw_RootMeanSquare", xAccRaw_RootMeanSquare)); listOfFeatures.add(new Pair<>("XAccRaw_AverageDif", xAccRaw_AverageDif)); listOfFeatures.add(new Pair<>("YAccRaw_Mean", yAccRaw_Mean)); listOfFeatures.add(new Pair<>("YAccRaw_MaxVal", yAccRaw_MaxVal)); listOfFeatures.add(new Pair<>("YAccRaw_MaxDif", yAccRaw_MaxDif)); listOfFeatures.add(new Pair<>("YAccRaw_MinDif", yAccRaw_MinDif)); listOfFeatures.add(new Pair<>("YAccRaw_MinVal", yAccRaw_MinVal)); listOfFeatures.add(new Pair<>("YAccRaw_RootMeanSquare", yAccRaw_RootMeanSquare)); listOfFeatures.add(new Pair<>("YAccRaw_AverageDif", yAccRaw_AverageDif)); listOfFeatures.add(new Pair<>("ZAccRaw_Mean", zAccRaw_Mean)); listOfFeatures.add(new Pair<>("ZAccRaw_MaxVal", zAccRaw_MaxVal)); listOfFeatures.add(new Pair<>("ZAccRaw_MaxDif", zAccRaw_MaxDif)); listOfFeatures.add(new Pair<>("ZAccRaw_MinDif", zAccRaw_MinDif)); listOfFeatures.add(new Pair<>("ZAccRaw_MinVal", zAccRaw_MinVal)); listOfFeatures.add(new Pair<>("ZAccRaw_RootMeanSquare", zAccRaw_RootMeanSquare)); listOfFeatures.add(new Pair<>("ZAccRaw_AverageDif", zAccRaw_AverageDif)); } public void calculateFeaturesForGravityDiscountedMovement(){ /* x_Disc*/ double xAccDisc_Sum = 0; double xAccDisc_MinVal = Double.MAX_VALUE; double xAccDisc_MaxVal = -Double.MAX_VALUE; double xAccDisc_MinDif = Double.MAX_VALUE; double xAccDisc_MaxDif = -Double.MAX_VALUE; double xAccDisc_DifSum = 0; double xAccDisc_SumSquared = 0; /* y_Disc*/ double yAccDisc_Sum = 0; double yAccDisc_MinVal = Double.MAX_VALUE; double yAccDisc_MaxVal = -Double.MAX_VALUE; double yAccDisc_MinDif = Double.MAX_VALUE; double yAccDisc_MaxDif = -Double.MAX_VALUE; double yAccDisc_DifSum = 0; double yAccDisc_SumSquared = 0; /* z_Disc*/ double zAccDisc_Sum = 0; double zAccDisc_MinVal = Double.MAX_VALUE; double zAccDisc_MaxVal = -Double.MAX_VALUE; double zAccDisc_MinDif = Double.MAX_VALUE; double zAccDisc_MaxDif = -Double.MAX_VALUE; double zAccDisc_DifSum = 0; double zAccDisc_SumSquared = 0; for (int i = 0; i < listOfFeatureLines.size(); i++) { /* x_Disc*/ double xAccDisc_Temp = listOfFeatureLines.get(i).getEffAccX(); xAccDisc_Sum+=xAccDisc_Temp; xAccDisc_SumSquared+= Math.pow(xAccDisc_Temp,2); if(xAccDisc_MinVal > xAccDisc_Temp) xAccDisc_MinVal = xAccDisc_Temp; if(xAccDisc_MaxVal < xAccDisc_Temp) xAccDisc_MaxVal = xAccDisc_Temp; /* y_Disc*/ double yAccDisc_Temp = listOfFeatureLines.get(i).getEffAccY(); yAccDisc_Sum+=yAccDisc_Temp; yAccDisc_SumSquared+= Math.pow(yAccDisc_Temp,2); if(yAccDisc_MinVal > yAccDisc_Temp) yAccDisc_MinVal = yAccDisc_Temp; if(yAccDisc_MaxVal < yAccDisc_Temp) yAccDisc_MaxVal = yAccDisc_Temp; /* z_Disc*/ double zAccDisc_Temp = listOfFeatureLines.get(i).getEffAccZ(); zAccDisc_Sum+=zAccDisc_Temp; zAccDisc_SumSquared+= Math.pow(zAccDisc_Temp,2); if(zAccDisc_MinVal > zAccDisc_Temp) zAccDisc_MinVal = zAccDisc_Temp; if(zAccDisc_MaxVal < zAccDisc_Temp) zAccDisc_MaxVal = zAccDisc_Temp; if (i> 0){ /* x_Disc*/ double xAccDisc_Dif = xAccDisc_Temp - listOfFeatureLines.get(i-1).getEffAccX(); if(xAccDisc_MinDif > xAccDisc_Dif) xAccDisc_MinDif = xAccDisc_Dif; if(xAccDisc_MaxDif < xAccDisc_Dif) xAccDisc_MaxDif = xAccDisc_Dif; xAccDisc_DifSum+=xAccDisc_Dif; /* y_Disc*/ double yAccDisc_Dif = yAccDisc_Temp - listOfFeatureLines.get(i-1).getEffAccY(); if(yAccDisc_MinDif > yAccDisc_Dif) yAccDisc_MinDif = yAccDisc_Dif; if(yAccDisc_MaxDif < yAccDisc_Dif) yAccDisc_MaxDif = yAccDisc_Dif; yAccDisc_DifSum+=yAccDisc_Dif; /* z_Disc*/ double zAccDisc_Dif = zAccDisc_Temp - listOfFeatureLines.get(i-1).getEffAccZ(); if(zAccDisc_MinDif > zAccDisc_Dif) zAccDisc_MinDif = zAccDisc_Dif; if(zAccDisc_MaxDif < zAccDisc_Dif) zAccDisc_MaxDif = zAccDisc_Dif; zAccDisc_DifSum+=zAccDisc_Dif; } } /* x_Disc*/ double xAccDisc_Mean = xAccDisc_Sum / listOfFeatureLines.size(); double tempX = xAccDisc_SumSquared/listOfFeatureLines.size(); double xAccDisc_RootMeanSquare = Math.sqrt(tempX); double xAccDisc_AverageDif = xAccDisc_DifSum / listOfFeatureLines.size(); /* y_Disc*/ double yAccDisc_Mean = yAccDisc_Sum / listOfFeatureLines.size(); double tempY = yAccDisc_SumSquared/listOfFeatureLines.size(); double yAccDisc_RootMeanSquare = Math.sqrt(tempY); double yAccDisc_AverageDif = yAccDisc_DifSum / listOfFeatureLines.size(); /* z_Disc*/ double zAccDisc_Mean = zAccDisc_Sum / listOfFeatureLines.size(); double tempZ = zAccDisc_SumSquared/listOfFeatureLines.size(); double zAccDisc_RootMeanSquare = Math.sqrt(tempZ); double zAccDisc_AverageDif = zAccDisc_DifSum / listOfFeatureLines.size(); listOfFeatures.add(new Pair<>("XAccDisc_Mean", xAccDisc_Mean)); listOfFeatures.add(new Pair<>("XAccDisc_MaxVal", xAccDisc_MaxVal)); listOfFeatures.add(new Pair<>("XAccDisc_MaxDif", xAccDisc_MaxDif)); listOfFeatures.add(new Pair<>("XAccDisc_MinDif", xAccDisc_MinDif)); listOfFeatures.add(new Pair<>("XAccDisc_MinVal", xAccDisc_MinVal)); listOfFeatures.add(new Pair<>("XAccDisc_RootMeanSquare", xAccDisc_RootMeanSquare)); listOfFeatures.add(new Pair<>("XAccDisc_AverageDif", xAccDisc_AverageDif)); listOfFeatures.add(new Pair<>("YAccDisc_Mean", yAccDisc_Mean)); listOfFeatures.add(new Pair<>("YAccDisc_MaxVal", yAccDisc_MaxVal)); listOfFeatures.add(new Pair<>("YAccDisc_MaxDif", yAccDisc_MaxDif)); listOfFeatures.add(new Pair<>("YAccDisc_MinDif", yAccDisc_MinDif)); listOfFeatures.add(new Pair<>("YAccDisc_MinVal", yAccDisc_MinVal)); listOfFeatures.add(new Pair<>("YAccDisc_RootMeanSquare", yAccDisc_RootMeanSquare)); listOfFeatures.add(new Pair<>("YAccDisc_AverageDif", yAccDisc_AverageDif)); listOfFeatures.add(new Pair<>("ZAccDisc_Mean", zAccDisc_Mean)); listOfFeatures.add(new Pair<>("ZAccDisc_MaxVal", zAccDisc_MaxVal)); listOfFeatures.add(new Pair<>("ZAccDisc_MaxDif", zAccDisc_MaxDif)); listOfFeatures.add(new Pair<>("ZAccDisc_MinDif", zAccDisc_MinDif)); listOfFeatures.add(new Pair<>("ZAccDisc_MinVal", zAccDisc_MinVal)); listOfFeatures.add(new Pair<>("ZAccDisc_RootMeanSquare", zAccDisc_RootMeanSquare)); listOfFeatures.add(new Pair<>("ZAccDisc_AverageDif", zAccDisc_AverageDif)); } public void calculateECDFRepresentationDisc(int bins){ //for each axis int size = listOfFeatureLines.size(); ArrayList<Double> xValues = new ArrayList<>(); ArrayList<Double> yValues = new ArrayList<>(); ArrayList<Double> zValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { xValues.add(featureLine.getEffAccX()); yValues.add(featureLine.getEffAccY()); zValues.add(featureLine.getEffAccZ()); xAxisDummy.add(i); i++; } //sort the values Collections.sort(xValues); Collections.sort(yValues); Collections.sort(zValues); double[] x = new double[xValues.size()]; double[] y = new double[yValues.size()]; double[] z = new double[zValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < xValues.size(); j++) { x[j] = xValues.get(j); } for (int j = 0; j < yValues.size(); j++) { y[j] = yValues.get(j); } for (int j = 0; j < zValues.size(); j++) { z[j] = zValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } //convert to function SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfX = interpolator.interpolate(dummy,x); PolynomialSplineFunction ecdfOfY = interpolator.interpolate(dummy,y); PolynomialSplineFunction ecdfOfZ = interpolator.interpolate(dummy,z); //get the bin values for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_DISC_X_BIN_" + (j+1) + "_OF_" + bins, ecdfOfX.value((double) j / bins * ecdfOfX.getKnots().length))); listOfFeatures.add(new Pair<>("ECDF_DISC_Y_BIN_" + (j+1) + "_OF_" + bins, ecdfOfY.value((double) j / bins * ecdfOfY.getKnots().length))); listOfFeatures.add(new Pair<>("ECDF_DISC_Z_BIN_" + (j+1) + "_OF_" + bins, ecdfOfZ.value((double) j / bins * ecdfOfZ.getKnots().length))); } } public void calculateECDFRepresentationUpAndY(int bins){ //for each axis int size = listOfFeatureLines.size(); ArrayList<Double> upValues = new ArrayList<>(); ArrayList<Double> yValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { upValues.add(featureLine.getAccUp()); yValues.add(featureLine.getAccY()); xAxisDummy.add(i); i++; } //sort the values Collections.sort(upValues); Collections.sort(yValues); double[] up = new double[upValues.size()]; double[] y = new double[yValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < upValues.size(); j++) { up[j] = upValues.get(j); } for (int j = 0; j < yValues.size(); j++) { y[j] = yValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } //convert to function SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfUp = interpolator.interpolate(dummy,up); PolynomialSplineFunction ecdfOfY = interpolator.interpolate(dummy,y); //get the bin values for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_UP_BIN_" + (j+1) + "_OF_" + bins, ecdfOfUp.value((double) j / bins * ecdfOfUp.getKnots().length))); listOfFeatures.add(new Pair<>("ECDF_RAW_Y_BIN_" + (j+1) + "_OF_" + bins, ecdfOfY.value((double) j / bins * ecdfOfY.getKnots().length))); } } public void calculateECDFRepresentationUpDown(int bins){ int size = listOfFeatureLines.size(); ArrayList<Double> upValues = new ArrayList<>(); ArrayList<Double> restValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { upValues.add(featureLine.getAccUp()); restValues.add(featureLine.getAccRest()); xAxisDummy.add(i); i++; } Collections.sort(upValues); Collections.sort(restValues); double[] up = new double[upValues.size()]; double[] rest = new double[restValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < upValues.size(); j++) { up[j] = upValues.get(j); } for (int j = 0; j < restValues.size(); j++) { rest[j] = restValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfUp = interpolator.interpolate(dummy,up); PolynomialSplineFunction ecdfOfRest = interpolator.interpolate(dummy,rest); for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_UP_BIN_" + (j+1) + "_OF_" + bins, ecdfOfUp.value((double) j / bins * ecdfOfUp.getKnots().length))); listOfFeatures.add(new Pair<>("ECDF_REST_BIN_" + (j+1) + "_OF_" + bins, ecdfOfRest.value((double) j / bins * ecdfOfRest.getKnots().length))); } } public void calculateECDFRepresentationRaw(int bins){ //for each axis int size = listOfFeatureLines.size(); ArrayList<Double> xValues = new ArrayList<>(); ArrayList<Double> yValues = new ArrayList<>(); ArrayList<Double> zValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { xValues.add(featureLine.getAccX()); yValues.add(featureLine.getAccY()); zValues.add(featureLine.getAccZ()); xAxisDummy.add(i); i++; } //sort the values Collections.sort(xValues); Collections.sort(yValues); Collections.sort(zValues); double[] x = new double[xValues.size()]; double[] y = new double[yValues.size()]; double[] z = new double[zValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < xValues.size(); j++) { x[j] = xValues.get(j); } for (int j = 0; j < yValues.size(); j++) { y[j] = yValues.get(j); } for (int j = 0; j < zValues.size(); j++) { z[j] = zValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } //convert to function SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfX = interpolator.interpolate(dummy,x); PolynomialSplineFunction ecdfOfY = interpolator.interpolate(dummy,y); PolynomialSplineFunction ecdfOfZ = interpolator.interpolate(dummy,z); //get the bin values for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_RAW_X_BIN_" + (j+1) + "_OF_" + bins, ecdfOfX.value((double) j / bins * ecdfOfX.getKnots().length))); listOfFeatures.add(new Pair<>("ECDF_RAW_Y_BIN_" + (j+1) + "_OF_" + bins, ecdfOfY.value((double) j / bins * ecdfOfY.getKnots().length))); listOfFeatures.add(new Pair<>("ECDF_RAW_Z_BIN_" + (j+1) + "_OF_" + bins, ecdfOfZ.value((double) j / bins * ecdfOfZ.getKnots().length))); } } public void calculateECDFRepresentationRawX(int bins){ //for each axis int size = listOfFeatureLines.size(); ArrayList<Double> xValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { xValues.add(featureLine.getAccX()); xAxisDummy.add(i); i++; } //sort the values Collections.sort(xValues); double[] x = new double[xValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < xValues.size(); j++) { x[j] = xValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } //convert to function SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfX = interpolator.interpolate(dummy,x); //get the bin values for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_RAW_X_BIN_" + (j+1) + "_OF_" + bins, ecdfOfX.value((double) j / bins * ecdfOfX.getKnots().length))); } } public void calculateECDFRepresentationRawY(int bins){ //for each axis int size = listOfFeatureLines.size(); ArrayList<Double> yValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { yValues.add(featureLine.getAccY()); xAxisDummy.add(i); i++; } //sort the values Collections.sort(yValues); double[] y = new double[yValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < yValues.size(); j++) { y[j] = yValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } //convert to function SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfY = interpolator.interpolate(dummy,y); //get the bin values for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_RAW_Y_BIN_" + (j+1) + "_OF_" + bins, ecdfOfY.value((double) j / bins * ecdfOfY.getKnots().length))); } } public void calculateECDFRepresentationRawZ(int bins){ //for each axis int size = listOfFeatureLines.size(); ArrayList<Double> zValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { zValues.add(featureLine.getAccZ()); xAxisDummy.add(i); i++; } //sort the values Collections.sort(zValues); double[] z = new double[zValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < zValues.size(); j++) { z[j] = zValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } //convert to function SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfZ = interpolator.interpolate(dummy,z); //get the bin values for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_RAW_Z_BIN_" + (j+1) + "_OF_" + bins, ecdfOfZ.value((double) j / bins * ecdfOfZ.getKnots().length))); } } public void calculateECDFRepresentationDiscX(int bins){ //for each axis int size = listOfFeatureLines.size(); ArrayList<Double> xValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { xValues.add(featureLine.getEffAccX()); xAxisDummy.add(i); i++; } //sort the values Collections.sort(xValues); double[] x = new double[xValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < xValues.size(); j++) { x[j] = xValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } //convert to function SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfX = interpolator.interpolate(dummy,x); //get the bin values for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_DISC_X_BIN_" + (j+1) + "_OF_" + bins, ecdfOfX.value((double) j / bins * ecdfOfX.getKnots().length))); } } public void calculateECDFRepresentationDiscY(int bins){ //for each axis int size = listOfFeatureLines.size(); ArrayList<Double> yValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { yValues.add(featureLine.getEffAccY()); xAxisDummy.add(i); i++; } //sort the values Collections.sort(yValues); double[] y = new double[yValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < yValues.size(); j++) { y[j] = yValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } //convert to function SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfY = interpolator.interpolate(dummy,y); //get the bin values for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_DISC_Y_BIN_" + (j+1) + "_OF_" + bins, ecdfOfY.value((double) j / bins * ecdfOfY.getKnots().length))); } } public void calculateECDFRepresentationDiscZ(int bins){ //for each axis int size = listOfFeatureLines.size(); ArrayList<Double> zValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { zValues.add(featureLine.getEffAccZ()); xAxisDummy.add(i); i++; } //sort the values Collections.sort(zValues); double[] z = new double[zValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < zValues.size(); j++) { z[j] = zValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } //convert to function SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfZ = interpolator.interpolate(dummy,z); //get the bin values for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_DISC_Z_BIN_" + (j+1) + "_OF_" + bins, ecdfOfZ.value((double) j / bins * ecdfOfZ.getKnots().length))); } } public void calculateECDFRepresentationUp(int bins){ int size = listOfFeatureLines.size(); ArrayList<Double> upValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { upValues.add(featureLine.getAccUp()); xAxisDummy.add(i); i++; } Collections.sort(upValues); double[] up = new double[upValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < upValues.size(); j++) { up[j] = upValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfUp = interpolator.interpolate(dummy,up); for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_UP_BIN_" + (j+1) + "_OF_" + bins, ecdfOfUp.value((double) j / bins * ecdfOfUp.getKnots().length))); } } public void calculateECDFRepresentationRest(int bins){ int size = listOfFeatureLines.size(); ArrayList<Double> restValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { restValues.add(featureLine.getAccRest()); xAxisDummy.add(i); i++; } Collections.sort(restValues); double[] rest = new double[restValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < restValues.size(); j++) { rest[j] = restValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction ecdfOfRest = interpolator.interpolate(dummy,rest); for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("ECDF_REST_BIN_" + (j+1) + "_OF_" + bins, ecdfOfRest.value((double) j / bins * ecdfOfRest.getKnots().length))); } } //TODO: this can be done faster. public void calculateAreaUnderFirstOfTwoLargestBumps(){ ArrayList<Pair<Double,Integer>> bumps = new ArrayList<>(); int bumpCounter = 0; double area = 0; boolean upwards_previous = true; for (FeatureLine fl : listOfFeatureLines) { double accup = fl.getAccUp(); boolean upwards_current = accup > 0; if(upwards_current == upwards_previous) area+= accup; else { upwards_previous = upwards_current; bumps.add(new Pair<Double, Integer>(area,bumpCounter)); area = 0; bumpCounter++; } } if(area != 0) bumps.add(new Pair<Double, Integer>(area,bumpCounter)); Collections.sort(bumps, new Comparator<Pair<Double, Integer>>() { @Override public int compare(Pair<Double, Integer> o1, Pair<Double, Integer> o2) { double v1 = Math.abs(o1.getKey()); double v2 = Math.abs(o2.getKey()); if(v1 > v2) return -1; if(v2 > v1) return 1; return 0; } }); if(bumpCounter<2) { listOfFeatures.add(new Pair<Object, Object>("AreaOfFirstOfTop2Bumps", 0)); return; } //biggest bump was first bump if(bumps.get(0).getValue() < bumps.get(1).getValue()) { //double pos = (bumps.get(0).getFirst() > 0)? 1 : -1; //listOfFeatures.add(new Pair<Object, Object>("AreaOfFirstOfTop2Bumps", pos)); listOfFeatures.add(new Pair<Object, Object>("AreaOfFirstOfTop2Bumps", bumps.get(0).getKey())); } //biggest bump was not first else { //double pos = (bumps.get(1).getFirst() > 0)? 1 : -1; //listOfFeatures.add(new Pair<Object, Object>("AreaOfFirstOfTop2Bumps", pos)); listOfFeatures.add(new Pair<Object, Object>("AreaOfFirstOfTop2Bumps", bumps.get(1).getKey())); } } public void calculateOverallAcceleration(){ } public void calculateVerticalTimedDistribution(int bins){ ArrayList<Double> upValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { upValues.add(featureLine.getAccUp()); xAxisDummy.add(i); i++; } double[] up = new double[upValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < upValues.size(); j++) { up[j] = upValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction timedVerticalDist = interpolator.interpolate(dummy,up); for (int j = 0; j < bins; j++) { listOfFeatures.add(new Pair<>("TIMED_VERTICAL_BIN_" + (j+1) + "_OF_" + bins, timedVerticalDist.value((double) j / bins * timedVerticalDist.getKnots().length))); } } public void calculateOrientationChange(){ double graX = 0; double graY = 0; double graZ = 0; int samples = 20; for (int i = 0; i < samples; i++) { graX += listOfFeatureLines.get(i).getGraX(); graY += listOfFeatureLines.get(i).getGraY(); graZ += listOfFeatureLines.get(i).getGraZ(); } double graX_start= Math.abs(graX/samples); double graY_start= Math.abs(graY/samples); double graZ_start= Math.abs(graZ/samples); graX = 0; graY = 0; graZ = 0; int size = listOfFeatureLines.size(); for (int i = 0; i < samples; i++) { graX += listOfFeatureLines.get(size-i-1).getGraX(); graY += listOfFeatureLines.get(size-i-1).getGraY(); graZ += listOfFeatureLines.get(size-i-1).getGraZ(); } double graX_end= Math.abs(graX/samples); double graY_end= Math.abs(graY/samples); double graZ_end= Math.abs(graZ/samples); /*ArrayList<Pair<String, Double>> start_orientations = new ArrayList<>(); start_orientations.add(new Pair<>("x", graX_start)); start_orientations.add(new Pair<>("y", graY_start)); start_orientations.add(new Pair<>("z", graZ_start)); Collections.sort(start_orientations, new Comparator<Pair<String, Double>>() { @Override public int compare(Pair<String, Double> o1, Pair<String, Double> o2) { if(o1.getValue() > o2.getValue()) return -1; if(o2.getValue() > o1.getValue()) return 1; return 0; } }); double[] after = new double[]{0,0,0}; int i = 0; for (Pair<String, Double> start_orientation : start_orientations) { if(start_orientation.getKey().equals("x")) after[i] = graX_end; if(start_orientation.getKey().equals("y")) after[i] = graY_end; if(start_orientation.getKey().equals("z")) after[i] = graZ_end; i++; } listOfFeatures.add(new Pair<Object, Object>("START_ORIENTATION_GRAVITY_1ST", start_orientations.get(0).getValue())); listOfFeatures.add(new Pair<Object, Object>("START_ORIENTATION_GRAVITY_2ND", start_orientations.get(1).getValue())); listOfFeatures.add(new Pair<Object, Object>("START_ORIENTATION_GRAVITY_3RD", start_orientations.get(2).getValue())); listOfFeatures.add(new Pair<Object, Object>("END_ORIENTATION_GRAVITY_1ST", after[0])); listOfFeatures.add(new Pair<Object, Object>("END_ORIENTATION_GRAVITY_2ND", after[1])); listOfFeatures.add(new Pair<Object, Object>("END_ORIENTATION_GRAVITY_3RD", after[2]));*/ listOfFeatures.add(new Pair<Object, Object>("START_ORIENTATION_GRAVITY_X", graX_start)); listOfFeatures.add(new Pair<Object, Object>("START_ORIENTATION_GRAVITY_Y", graY_start)); listOfFeatures.add(new Pair<Object, Object>("START_ORIENTATION_GRAVITY_Z", graZ_start)); listOfFeatures.add(new Pair<Object, Object>("END_ORIENTATION_GRAVITY_X", graX_end)); listOfFeatures.add(new Pair<Object, Object>("END_ORIENTATION_GRAVITY_Y", graY_end)); listOfFeatures.add(new Pair<Object, Object>("END_ORIENTATION_GRAVITY_Z", graZ_end)); } public void calculateStartingOrientation(){ ArrayList<double[]> measurementsFromStart = new ArrayList<>(); double graX = 0; double graY = 0; double graZ = 0; int samples = 20; for (int i = 0; i < samples; i++) { graX += listOfFeatureLines.get(i).getGraX(); graY += listOfFeatureLines.get(i).getGraY(); graZ += listOfFeatureLines.get(i).getGraZ(); } graX= graX/samples; graY= graY/samples; graZ= graZ/samples; listOfFeatures.add(new Pair<Object, Object>("START_ORIENTATION_GRAVITY_X", graX)); listOfFeatures.add(new Pair<Object, Object>("START_ORIENTATION_GRAVITY_Y", graY)); listOfFeatures.add(new Pair<Object, Object>("START_ORIENTATION_GRAVITY_Z", graZ)); } public void calculateVerticalAccelerationDerivative(){ ArrayList<Double> upValues = new ArrayList<>(); ArrayList<Double> xAxisDummy = new ArrayList<>(); Double i = 0.0; for (FeatureLine featureLine : listOfFeatureLines) { upValues.add(featureLine.getAccUp()); xAxisDummy.add(i); i++; } double[] up = new double[upValues.size()]; double[] dummy = new double[xAxisDummy.size()]; for (int j = 0; j < upValues.size(); j++) { up[j] = upValues.get(j); } for (int j = 0; j < xAxisDummy.size(); j++) { dummy[j] = xAxisDummy.get(j); } SplineInterpolator interpolator = new SplineInterpolator(); PolynomialSplineFunction timedVerticalDist = interpolator.interpolate(dummy,up); UnivariateFunction direvative = timedVerticalDist.derivative(); } public void calculateSumOfUpwardsAcceleration(){ double sum_up = 0; for (FeatureLine fl : listOfFeatureLines) { double acc_up = fl.getAccUp(); if(acc_up> 0) sum_up+= acc_up; } listOfFeatures.add(new Pair<Object, Object>("SUM_OF_UPWARDS_ACCELERATION", sum_up)); } public void calculateSumOfDownwardsAcceleration(){ double sum_down = 0; for (FeatureLine fl : listOfFeatureLines) { double acc_down = fl.getAccUp(); if(acc_down < 0) sum_down+= acc_down; } listOfFeatures.add(new Pair<Object, Object>("SUM_OF_DOWNWARDS_ACCELERATION", sum_down)); } public void calculateUpCorrelationWithDiscounted(){ double rms_sum_X = 0; double rms_sum_Y = 0; double rms_sum_Z = 0; for (FeatureLine fl: listOfFeatureLines) { double accUp = fl.getAccUp(); double rms_dif_x; rms_dif_x = fl.getEffAccX() - accUp; rms_sum_X += Math.pow(rms_dif_x, 2); double rms_dif_y = fl.getEffAccX() - accUp; rms_sum_Y += Math.pow(rms_dif_y, 2); double rms_dif_z = fl.getEffAccX() - accUp; rms_sum_Z += Math.pow(rms_dif_z, 2); } int size = listOfFeatureLines.size(); double rms_correlation_x = Math.sqrt(rms_sum_X/size); listOfFeatures.add(new Pair<Object, Object>("RMS_CORRELATION_X_UP",rms_correlation_x)); double rms_correlation_y = Math.sqrt(rms_sum_Y/size); listOfFeatures.add(new Pair<Object, Object>("RMS_CORRELATION_Y_UP",rms_correlation_y)); double rms_correlation_z = Math.sqrt(rms_sum_Z/size); listOfFeatures.add(new Pair<Object, Object>("RMS_CORRELATION_Z_UP",rms_correlation_z)); } public void calculateEndingOrientation(){ ArrayList<double[]> measurementsFromStart = new ArrayList<>(); double graX = 0; double graY = 0; double graZ = 0; int size = listOfFeatureLines.size(); int samples = 20; for (int i = 0; i < samples; i++) { graX += listOfFeatureLines.get(size-i-1).getGraX(); graY += listOfFeatureLines.get(size-i-1).getGraY(); graZ += listOfFeatureLines.get(size-i-1).getGraZ(); } graX= graX/samples; graY= graY/samples; graZ= graZ/samples; listOfFeatures.add(new Pair<Object, Object>("END_ORIENTATION_GRAVITY_X", graX)); listOfFeatures.add(new Pair<Object, Object>("END_ORIENTATION_GRAVITY_Y", graY)); listOfFeatures.add(new Pair<Object, Object>("END_ORIENTATION_GRAVITY_Z", graZ)); } public void calculateOrientationJitter(){ double changeX = 0; double lastGraX = 0; double changeY = 0; double lastGraY = 0; double changeZ = 0; double lastGraZ = 0; for (FeatureLine fl : listOfFeatureLines) { if(!(lastGraX == 0)) { changeX += fl.getGraX() - lastGraX; changeY += fl.getGraY() - lastGraY; changeZ += fl.getGraZ() - lastGraZ; } lastGraX = fl.getGraX(); lastGraY = fl.getGraY(); lastGraZ = fl.getGraZ(); } double totalChange = (changeX + changeY + changeZ) / listOfFeatureLines.size(); listOfFeatures.add(new Pair<Object, Object>("ORIENTATION_JITTER", totalChange)); } public List<Pair<?, ?>> getListOfFeatures() { return listOfFeatures; } public List<FeatureLine> getListOfFeatureLines() { return listOfFeatureLines; } } <file_sep>/src/Pipeline/NearestNeighborGridSearch.java package Pipeline; import Core.ClassifierEvalDescriptionTriplet; import Core.ClassifierEvalDescriptionTripletComparator; import weka.classifiers.Evaluation; import weka.classifiers.lazy.IBk; import weka.classifiers.meta.FilteredClassifier; import weka.core.DistanceFunction; import weka.core.Instances; import weka.core.neighboursearch.LinearNNSearch; import weka.filters.Filter; import weka.filters.unsupervised.attribute.RemoveByName; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.Callable; /** * Created by Rune on 29-03-2016. */ public class NearestNeighborGridSearch implements Callable<ArrayList<ClassifierEvalDescriptionTriplet>>{ private Instances dataset; private DistanceFunction distanceFunction; private String regex; private Filter filter; private int numberOfFolds; public NearestNeighborGridSearch(Instances dataset, DistanceFunction distanceFunction, Filter filter, int numberOfFolds) { this.dataset = dataset; this.distanceFunction = distanceFunction; this.filter = filter; this.numberOfFolds = numberOfFolds; } public NearestNeighborGridSearch(Instances dataset, DistanceFunction distanceFunction, String regex, int numberOfFolds) { this.dataset = dataset; this.distanceFunction = distanceFunction; this.regex = regex; this.numberOfFolds = numberOfFolds; } @Override public ArrayList<ClassifierEvalDescriptionTriplet> call() throws Exception { ArrayList<ClassifierEvalDescriptionTriplet> triplets = new ArrayList<>(); int k = 1; for (int i = 0; i < 5; i++) { IBk classifier = new IBk(); classifier.setKNN(k); LinearNNSearch search = new LinearNNSearch(); search.setDistanceFunction(distanceFunction); classifier.setNearestNeighbourSearchAlgorithm(search); FilteredClassifier filternn = new FilteredClassifier(); //filter.setInputFormat(dataset); if(filter == null) { RemoveByName filter = new RemoveByName(); filter.setExpression(regex); } filternn.setFilter(filter); filternn.setClassifier(classifier); filternn.buildClassifier(dataset); Evaluation eval = new Evaluation(dataset); eval.crossValidateModel(filternn, dataset, numberOfFolds, new Random()); triplets.add(new ClassifierEvalDescriptionTriplet("NearestNeighbor(DF:"+distanceFunction.getClass().getSimpleName()+".K:"+k+").Filter:"+filter.getClass().getSimpleName(), eval,filternn)); k = k*2; } System.out.println("NearestNeighborTest with distance function: "+ distanceFunction.getClass().getSimpleName()+" and filter "+regex+" Done!"); return triplets; } } <file_sep>/src/ArffFile/CompleteFeatureFileGenerator.java package ArffFile; import Core.*; import org.apache.commons.math3.util.Pair; import weka.core.Instances; import weka.core.converters.ConverterUtils; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * Created by Rune on 29-03-2016. */ public class CompleteFeatureFileGenerator { private static boolean DO_FILTERING = false; public static void main(String[] args) { BiasConfiguration nullBias = new BiasConfiguration(0, 0, 0, 0, 0, 0); createCompleteFeatureFileWithProximity("D:\\Dropbox\\Thesis\\Data\\RawDataProx", "D:\\Dropbox\\Thesis\\Data\\Test\\", 3., ClassifierType.EVENT_SNIFFER, nullBias); } public static String createCompleteFeatureFile(String fromLocation, String toLocation, double windowsize_seconds, ClassifierType type) { ArrayList<Window> windows = new ArrayList<>(); String filenameSuffix = ""; if (type == ClassifierType.SIT_STAND_CLASSIFIER) { windows = RawlineToWindowConverterVarLength.getAllWindowsFromURI(fromLocation, windowsize_seconds); windows.removeIf(window -> window.getLabel().contains("null")); filenameSuffix = "CompleteFeatureFileSitStand.arff"; } if (type == ClassifierType.EVENT_SNIFFER) { windows = RawlineToWindowConverterVarLength.getAllWindowsFromURI(fromLocation, windowsize_seconds); windows.stream().filter(w -> !w.getLabel().contains("null")).forEach(w -> w.setLabel("event")); filenameSuffix = "CompleteFeatureFileEventSniffer.arff"; } if (type == ClassifierType.TAP_SNIFFER) { windows = RawlineToTapWindowConverterVarLength.getAllWindowsFromURI(fromLocation, windowsize_seconds); filenameSuffix = "CompleteFeatureFileTapSniffer.arff"; } for (Window w : windows) { w.calculateECDFRepresentationDisc(30); w.calculateECDFRepresentationRaw(30); w.calculateECDFRepresentationUpDown(30); w.calculateFeaturesForRawMovement(); w.calculateFeaturesForGravityDiscountedMovement(); w.calculateFeaturesForRelativeMovement(); w.calculateStartingOrientation(); w.calculateEndingOrientation(); w.calculateOrientationJitter(); w.calculateVerticalTimedDistribution(30); w.calculateSumOfUpwardsAcceleration(); w.calculateSumOfDownwardsAcceleration(); w.calculateZeroCrossings(); w.calculateNumberOfTaps(); } ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows)); fileToBePrinted.addAll(windows.stream() .map(Util::convertToLine) .collect(Collectors.toList())); //print the file fileToBePrinted.removeIf(String::isEmpty); String filename = toLocation + filenameSuffix; Util.saveAsFile(fileToBePrinted, filename); return filename; } public static String createCompleteFeatureFileWithCorrectionsIncludedMultipleUsersNoBias(String fromLocation, String complete_filename, ClassifierType type){ List<Window> windows = WindowImporter.getCorrectedWindowsMutlipleUsersUnaplyBias(fromLocation); //filter the windows if (type == ClassifierType.EVENT_SNIFFER) { //turn all sit/stand events into events windows.stream() .filter(window1 -> !window1.getLabel().contains("null")) .forEach(window2 -> window2.setLabel("event")); } if (type == ClassifierType.SIT_STAND_CLASSIFIER) { //remove all null windows windows.removeIf(window -> window.getLabel().contains("null")); } if(windows.isEmpty()){ return null; } //convert to arff format //retarded copying of windows needed to initialize listOfFeatures List<Window> windows2 = new ArrayList<>(); windows.forEach(window ->windows2.add(new Window(window))); windows2.forEach(Window::calculateAllFeatures); if(DO_FILTERING) { windows2.removeIf(window -> !window.getLabel().equals("null") && totalAccelerationLowerThan110(window)); } ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows2)); fileToBePrinted.addAll(windows2.stream() .map(Util::convertToLine) .collect(Collectors.toList())); fileToBePrinted.removeIf(String::isEmpty); //save the file Util.saveAsFile(fileToBePrinted, complete_filename); //return the filenames return complete_filename; } public static String createCompleteFeatureFileWithCorrectionsIncludedMultipleUsers(String fromLocation, String complete_filename, ClassifierType type){ List<Window> windows = WindowImporter.getCorrectedWindowsMultipleUsers(fromLocation); //filter the windows if (type == ClassifierType.EVENT_SNIFFER) { //turn all sit/stand events into events windows.stream() .filter(window1 -> !window1.getLabel().contains("null")) .forEach(window2 -> window2.setLabel("event")); } if (type == ClassifierType.SIT_STAND_CLASSIFIER) { //remove all null windows windows.removeIf(window -> window.getLabel().contains("null")); } if(windows.isEmpty()){ return null; } //convert to arff format //retarded copying of windows needed to initialize listOfFeatures List<Window> windows2 = new ArrayList<>(); windows.forEach(window ->windows2.add(new Window(window))); windows2.forEach(Window::calculateAllFeatures); if(DO_FILTERING) { windows2.removeIf(window -> !window.getLabel().equals("null") && totalAccelerationLowerThan110(window)); } ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows2)); fileToBePrinted.addAll(windows2.stream() .map(Util::convertToLine) .collect(Collectors.toList())); fileToBePrinted.removeIf(String::isEmpty); //save the file Util.saveAsFile(fileToBePrinted, complete_filename); //return the filenames return complete_filename; } private static boolean totalAccelerationLowerThan110(Window window) { Double total_up = (Double) window.getListOfFeatures().get(334).getValue(); Double total_down = (Double) window.getListOfFeatures().get(335).getValue(); return Math.abs(total_down) + Math.abs(total_up) < 110; } public static String createCompleteFeatureFileWithCorrectionsIncluded(String fromLocation, String complete_filename, ClassifierType type){ List<Window> windows = WindowImporter.getCorrectedWindows(fromLocation); //filter the windows if (type == ClassifierType.EVENT_SNIFFER) { //turn all sit/stand events into events windows.stream() .filter(window1 -> !window1.getLabel().contains("null")) .forEach(window2 -> window2.setLabel("event")); } if (type == ClassifierType.SIT_STAND_CLASSIFIER) { //remove all null windows windows.removeIf(window -> window.getLabel().contains("null")); } if(windows.isEmpty()){ return null; } //convert to arff format //retarded copying of windows needed to initialize listOfFeatures List<Window> windows2 = new ArrayList<>(); windows.forEach(window ->windows2.add(new Window(window))); windows2.forEach(Window::calculateAllFeatures); ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows2)); fileToBePrinted.addAll(windows2.stream() .map(Util::convertToLine) .collect(Collectors.toList())); fileToBePrinted.removeIf(String::isEmpty); //save the file Util.saveAsFile(fileToBePrinted, complete_filename); //return the filenames return complete_filename; } public static String createCompleteFeatureaFileWithProximityFromWindowFiles(String fromLocation, String complete_filename, ClassifierType type) { //import the windows List<Window> windows = WindowImporter.getWindows(fromLocation); //filter the windows if (type == ClassifierType.EVENT_SNIFFER) { //turn all sit/stand events into events windows.stream() .filter(window1 -> !window1.getLabel().contains("null")) .forEach(window2 -> window2.setLabel("event")); } if (type == ClassifierType.SIT_STAND_CLASSIFIER) { //remove all null windows windows.removeIf(window -> window.getLabel().contains("null")); } if(windows.isEmpty()){ return null; } //convert to arff format //retarded copying of windows needed to initialize listOfFeatures List<Window> windows2 = new ArrayList<>(); windows.forEach(window ->windows2.add(new Window(window))); windows2.forEach(Window::calculateAllFeatures); ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows2)); fileToBePrinted.addAll(windows2.stream() .map(Util::convertToLine) .collect(Collectors.toList())); fileToBePrinted.removeIf(String::isEmpty); //save the file Util.saveAsFile(fileToBePrinted, complete_filename); //return the filenames return complete_filename; } public static List<String> createCompleteFeatureFileWithProximitySeparateFile(String fromLocation, String toLocation, double window_size_seconds, ClassifierType type, BiasConfiguration biasForSample) { List<Pair<String, List<Window>>> uri_window_list = new ArrayList<>(); uri_window_list = RawlineToWindowConverterProximityVarLength.getAllWindowFromURIInSeparateLists(fromLocation, window_size_seconds, biasForSample); String filenamePrefix = "CompleteFeatureFile"; if (type == ClassifierType.EVENT_SNIFFER) { //turn all sit/stand events into events uri_window_list .forEach(pair -> pair.getValue() .stream() .filter(window -> !window.getLabel().contains("null")) .forEach(window1 -> window1.setLabel("event"))); } if (type == ClassifierType.SIT_STAND_CLASSIFIER) { //remove all null windows uri_window_list .forEach(pair -> pair.getValue() .removeIf(window -> window.getLabel().contains("null"))); } List<String> fileNames = new ArrayList<>(); for (Pair<String, List<Window>> pair : uri_window_list) { List<Window> windows = pair.getValue(); for (Window w : windows) { w.calculateAllFeatures(); } if(DO_FILTERING) { windows.removeIf(window -> !window.getLabel().equals("null") && totalAccelerationLowerThan110(window)); } ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows)); fileToBePrinted.addAll(windows.stream() .map(Util::convertToLine) .collect(Collectors.toList())); //print the file fileToBePrinted.removeIf(String::isEmpty); String filename = toLocation + filenamePrefix + pair.getKey().substring(pair.getKey().lastIndexOf("\\") + 1); Util.saveAsFile(fileToBePrinted, filename); fileNames.add(filename); } return fileNames; } public static String createCompleteFeatureFileWithProximity(String fromLocation, String toLocation, double windowsize_seconds, ClassifierType type, BiasConfiguration bias) { ArrayList<Window> windows = new ArrayList<>(); String filenameSuffix = ""; if (type == ClassifierType.SIT_STAND_CLASSIFIER) { windows = RawlineToWindowConverterProximityVarLength.getAllWindowsFromURI(fromLocation, windowsize_seconds, bias); windows.removeIf(window -> window.getLabel().contains("null")); filenameSuffix = "CompleteFeatureFileSitStand.arff"; } if (type == ClassifierType.EVENT_SNIFFER) { windows = RawlineToWindowConverterProximityVarLength.getAllWindowsFromURI(fromLocation, windowsize_seconds, bias); windows.stream().filter(w -> !w.getLabel().contains("null")).forEach(w -> w.setLabel("event")); filenameSuffix = "CompleteFeatureFileEventSniffer.arff"; } if (type == ClassifierType.TAP_SNIFFER) { windows = RawlineToWindowConverterProximityVarLength.getAllWindowsFromURI(fromLocation, windowsize_seconds, bias); filenameSuffix = "CompleteFeatureFileTapSniffer.arff"; } for (Window w : windows) { w.calculateAllFeatures(); } ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows)); fileToBePrinted.addAll(windows.stream() .map(Util::convertToLine) .collect(Collectors.toList())); //print the file fileToBePrinted.removeIf(String::isEmpty); String filename = toLocation + filenameSuffix; Util.saveAsFile(fileToBePrinted, filename); return filename; } public static Instances getInstances(String featureFile) throws Exception { Instances dataFile = new ConverterUtils.DataSource(featureFile).getDataSet(); if (dataFile.classIndex() == -1) dataFile.setClassIndex(dataFile.numAttributes() - 1); return dataFile; } }<file_sep>/src/RandomTest/GridSearchTutorial.java package RandomTest; import Core.RawlineToWindowConverter; import Core.Util; import Core.Window; import weka.classifiers.Evaluation; import weka.classifiers.trees.RandomForest; import weka.core.Instances; import weka.core.converters.ConverterUtils; import java.util.ArrayList; import java.util.Random; import java.util.stream.Collectors; /** * Created by Rune on 17-03-2016. */ public class GridSearchTutorial { public static void main(String[] args) { ArrayList<Window> windows = RawlineToWindowConverter.getAllWindowsFromURI("D:\\Dropbox\\Thesis\\Data\\Test"); for (Window w : windows) { w.calculateECDFRepresentationUpAndY(30); } String featureString = ""; ArrayList<String> fileToBePrinted = new ArrayList<>(); fileToBePrinted.add(Util.getHeader(windows)); fileToBePrinted.addAll(windows.stream().map(Util::convertToLine).collect(Collectors.toList())); //print the file fileToBePrinted.removeIf(String::isEmpty); Util.saveAsFile(fileToBePrinted,"D:\\Dropbox\\Thesis\\Data\\Test\\"+"ECDFUpAndYMovementTutorial.arff"); ConverterUtils.DataSource source; try { source = new ConverterUtils.DataSource("D:\\Dropbox\\Thesis\\Data\\Test\\"+"ECDFUpAndYMovementTutorial.arff"); Instances data = source.getDataSet(); if(data.classIndex() == -1) data.setClassIndex(data.numAttributes() - 1); String[] options = weka.core.Utils.splitOptions("-I 10 -K 0 -S 1"); RandomForest rf = new RandomForest(); rf.setOptions(options); rf.buildClassifier(data); Evaluation eval = new Evaluation(data); eval.crossValidateModel(rf,data, data.numInstances(), new Random(1)); System.out.println(eval.toSummaryString()); System.out.println(eval.toClassDetailsString()); System.out.println(eval.toMatrixString()); System.out.println(eval.toCumulativeMarginDistributionString()); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/src/RandomTest/FilterInstanceCreator.java package RandomTest; import com.google.gson.InstanceCreator; import weka.filters.Filter; import weka.filters.unsupervised.attribute.Remove; import java.lang.reflect.Type; /** * Created by Rune on 23-04-2016. */ public class FilterInstanceCreator implements InstanceCreator<Filter> { @Override public Filter createInstance(Type type) { return new Remove(); } }
d9c32bf5b26f4edc01016a10ebfac95d581df4cf
[ "Java" ]
28
Java
dr0l3/DataProcessing
ea22b7664d47ad1269b86e642b352b8c0e56a677
9b1573388e04278126d6783021e51423026513e3
refs/heads/master
<file_sep>require "twitter" require "./key" stream = Twitter::Streaming::Client.new do |config| config.consumer_key = CONSUMER_KEY config.consumer_secret = CONSUMER_SECRET config.access_token = OAUTH_TOKEN config.access_token_secret = OAUTH_TOKEN_SECRET end rest = Twitter::REST::Client.new do |config| config.consumer_key = CONSUMER_KEY config.consumer_secret = CONSUMER_SECRET config.access_token = OAUTH_TOKEN config.access_token_secret = OAUTH_TOKEN_SECRET end stream.user do |object| if object.is_a?(Twitter::Tweet) && object.user.screen_name != BOT_USER user = object.user.screen_name t_id = object.id hour = object.text.match(/([0-9\.]+)hour/) unless hour.nil? str_t = (Time.now + hour[1].to_f * 60 * 60).strftime("%H:%M %d.%m.%Y") rest.update("@#{user} OK! #{str_t}", options = {in_reply_to_status_id: t_id}) IO.popen("at -q r '#{str_t}'","w"){|io| io.puts "#/bin/sh ruby /home/hoshito/git/ruby/twitter_bot/tweet.rb #{user} #{t_id}" } end end end <file_sep>require "twitter" require "./key" rest = Twitter::REST::Client.new do |config| config.consumer_key = CONSUMER_KEY config.consumer_secret = CONSUMER_SECRET config.access_token = OAUTH_TOKEN config.access_token_secret = OAUTH_TOKEN_SECRET end user = ARGV[0] t_id = ARGV[1] rest.update("@#{user} remind!", options = {in_reply_to_status_id: t_id})
bc2940dbab5b1635186e2a5d6ebfa223d77b6265
[ "Ruby" ]
2
Ruby
hoshito/twitter_bot
240ab72275aa8bc9a09da98cfc31363ed2326bd6
d718747b32b26c5c8ef19845faa126abf5982506
refs/heads/master
<file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: import os import tensorflow as tf import pandas as pd from sklearn.preprocessing import MinMaxScaler # In[3]: # Turn off TensorFlow warning messages in program output os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Load training data set from CSV file training_data_df = pd.read_csv("sales_data_training.csv", dtype=float) # Pull out columns for X (data to train with) and Y (value to predict) X_training = training_data_df.drop('total_earnings', axis=1).values Y_training = training_data_df[['total_earnings']].values # In[4]: # Pull out columns for X (data to train with) and Y (value to predict) X_training = training_data_df.drop('total_earnings', axis=1).values Y_training = training_data_df[['total_earnings']].values # Load testing data set from CSV file test_data_df = pd.read_csv("sales_data_test.csv", dtype=float) # Pull out columns for X (data to train with) and Y (value to predict) X_testing = test_data_df.drop('total_earnings', axis=1).values Y_testing = test_data_df[['total_earnings']].values # In[6]: X_training # In[8]: training_data_df # In[ ]:
12bf6ba59c7a8b78fe67d4842e297cf876bca117
[ "Python" ]
1
Python
JINU8/Personal-ML-Projects
bfeb4ee77f0a5f9d39fa6b9d5327bbc70db5c74d
cfb3259d9f1c7c2217ac297d3ceacf70237dace3
refs/heads/master
<file_sep>package jp.co.board.action.home; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Map; import jp.co.board.dao.comment.CommentDao; import jp.co.board.dto.comment.IUserComment; import jp.co.board.service.comment.CommentService; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.interceptor.SessionAware; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; /** * コメントの投稿を操作するアクションクラス * @author tsujitakuya * */ public class CommentAction extends ActionSupport implements SessionAware{ private Integer commentId; private Timestamp insDatetime; private String comment; private IUserComment iUserComment; /*modelの中のコメント(編集用)*/ private String modalText; /*commentId(編集用)*/ private Integer hiddenText; private List<IUserComment> iUserCommentList; /*編集用の変数リスト*/ private List<IUserComment> iUserCommentListEditing; private Map<String,Object> session; @Autowired private CommentService commentService; @Autowired private CommentDao commentDao; /** *home.ftlに入ると行う処理 * @return */ @Action(value="/home/comment", results = {@Result(name = "success" ,location="home.ftl"), @Result(name="input",location="home.ftl")}) public String Comment(){ /*投稿内容が空なら投稿できない*/ if(comment == null || comment.equals("")){ return "input"; } List<IUserComment> iUserCommentListAll = commentService.findAll(); iUserCommentList = new ArrayList<IUserComment>(); for(IUserComment iUserCommentEntity:iUserCommentListAll){ iUserCommentList.add(iUserCommentEntity); } setIUserCommentList(iUserCommentList); return "success"; } /** * 投稿ボタンを押すと行う処理 */ @Action(value="/home/commentButton", results = {@Result(name = "success" ,location="home.ftl"), @Result(name="input",location="home.ftl")}) public String commentButton(){ /** * 正常にコメントが投稿できたかを判定 */ if(commentService.insert(commentId, (Integer)session.get("userId"), (String)session.get("userName"), comment,insDatetime)){ List<IUserComment> iUserCommentListAll = commentService.findAll(); iUserCommentList = new ArrayList<IUserComment>(); for(IUserComment iUserCommentEntity:iUserCommentListAll){ iUserCommentList.add(iUserCommentEntity); } setIUserCommentList(iUserCommentList); return "success"; }else{ return "input"; } } /** * [削除ボタン]を押すとこの処理に入る * @return */ @Action(value="/home/delete", results={@Result(name="success",location="home.ftl"), @Result(name="input",location="home.ftl")}) public String commentDelete(){ /*削除ボタンを押して削除するコメントがひとつならこの処理に入る*/ if(commentService.commentDelete(commentId, (Integer)session.get("userId")) == 1){ /*DBから全件検索してftl側に表示*/ List<IUserComment> iUserCommentListAll = commentService.findAll(); iUserCommentList = new ArrayList<IUserComment>(); for(IUserComment iUserCommentEntity:iUserCommentListAll){ iUserCommentList.add(iUserCommentEntity); } setIUserCommentList(iUserCommentList); }else{ List<IUserComment> iUserCommentList = commentService.findAll(); iUserCommentList = new ArrayList<IUserComment>(); for(IUserComment iUserCommentEntity:iUserCommentList){ iUserCommentList.add(iUserCommentEntity); } setIUserCommentList(iUserCommentList); } return "success"; } /** * [編集]ボタンを押すとこの処理に入る */ @Action(value="/home/editing", results={@Result(name="success",location="home.ftl"), @Result(name="input",location="home.ftl")}) public String editing(){ iUserCommentListEditing = new ArrayList<IUserComment>(); iUserCommentListEditing = commentService.selectColumn(commentId); setIUserCommentListEditing(iUserCommentListEditing); return "success"; } /** * 編集完了ボタンを押すとこの処理に入る * コメント内容の編集する。コメントIDやユーザー名などの変更はなし */ @Action(value="/home/editingComplete", results={@Result(name="success",location="home.ftl"), @Result(name="input",location="home.ftl")}) public String editingComplete(){ if(hiddenText == null){ return "input"; }else{ commentService.updateComment(hiddenText,(Integer)session.get("userId"),(String)session.get("userName"),modalText); /*DBから全件検索してftl側に表示*/ List<IUserComment> iUserCommentListAll = commentService.findAll(); iUserCommentList = new ArrayList<IUserComment>(); for(IUserComment iUserCommentEntity:iUserCommentListAll){ iUserCommentList.add(iUserCommentEntity); } setIUserCommentList(iUserCommentList); return "success"; } } @Override public void setSession(Map<String, Object> session) { this.session = session; } public Integer getCommentId() { return commentId; } public void setCommentId(Integer commentId) { this.commentId = commentId; } public Timestamp getInsDatetime() { return insDatetime; } public void setInsDatetime(Timestamp insDatetime) { this.insDatetime = insDatetime; } public String getComment() { return comment; } public void setComment(String Comment) { this.comment = Comment; } public IUserComment getIUserComment() { return iUserComment; } public void setIUserComment(IUserComment iUserComment) { this.iUserComment = iUserComment; } public List<IUserComment> getIUserCommentList() { return iUserCommentList; } public void setIUserCommentList(List<IUserComment> iUserCommentList) { this.iUserCommentList = iUserCommentList; } public List<IUserComment> getIUserCommentListEditing() { return iUserCommentListEditing; } public void setIUserCommentListEditing( List<IUserComment> iUserCommentListEditing) { this.iUserCommentListEditing = iUserCommentListEditing; } public String getModalText() { return modalText; } public void setModalText(String modalText) { this.modalText = modalText; } public Integer getHiddenText() { return hiddenText; } public void setHiddenText(Integer hiddenText) { this.hiddenText = hiddenText; } } <file_sep>package jp.co.board.action.top; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; /** * 一番最初に映るページを操作するアクションクラス * @author tsujitakuya * */ public class IndexAction { /** * index.ftlを表示する * @return */ @Action(value="/", results={@Result(name="success",location="top/index.ftl")}) public String index(){ return "success"; } } <file_sep>package jp.co.board.dao.comment.impl; import java.util.List; import jp.co.board.dao.comment.CommentDao; import jp.co.board.data.comment.IUserCommentMapper; import jp.co.board.data.comment.IUserCommentMapper; import jp.co.board.dto.comment.IUserComment; import jp.co.board.dto.comment.IUserCommentExample; import jp.co.board.dto.comment.IUserComment; import jp.co.board.dto.comment.IUserCommentExample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * CommentDaoの実装クラス * @author tsujitakuya * */ @Repository public class CommentDaoImpl implements CommentDao{ @Autowired private IUserCommentMapper iUserCommentMapper; /** * (non-Javadoc) * @see jp.co.board.dao.comment.CommentDao#insert() */ @Override public boolean insert(IUserComment iUserComment) { if(iUserCommentMapper.insert(iUserComment) == 1){ return true; }else{ return false; } } /* * (非 Javadoc) * @see jp.co.board.dao.comment.CommentDao#select(jp.co.board.dto.comment.IUserComment) */ @Override public List<IUserComment> findAll() { IUserCommentExample iUserCommentExample = new IUserCommentExample(); iUserCommentExample.createCriteria().getAllCriteria(); iUserCommentExample.setOrderByClause("comment_id desc"); List<IUserComment> iUserCommentList = iUserCommentMapper.selectByExample(iUserCommentExample); return iUserCommentList; } /* * (非 Javadoc) * @see jp.co.board.dao.comment.CommentDao#commentDelete(java.lang.Integer) */ @Override public Integer commentDelete(Integer commentId,Integer userId) { IUserCommentExample iUserCommentExample = new IUserCommentExample(); /*コメントIDとユーザーIDをwhereで指定*/ iUserCommentExample.createCriteria().andCommentIdEqualTo(commentId).andUserIdEqualTo(userId); /*コメントIDとユーザーIDが等しいユーザーがいればif文の中に入る*/ if(iUserCommentMapper.countByExample(iUserCommentExample) == 1){ /*そのユーザーが自分の任意の投稿を削除*/ return iUserCommentMapper.deleteByPrimaryKey(commentId); }else{ return null; } } /* * (non-Javadoc) * @see jp.co.board.dao.comment.CommentDao#selectColumn(java.lang.Integer) */ @Override public List<IUserComment> selectColumn(Integer commentId) { IUserCommentExample iUSerCommentExample = new IUserCommentExample(); iUSerCommentExample.createCriteria().andCommentIdEqualTo(commentId); /*commentIdのカラムが1つだけ存在すれば*/ if(iUserCommentMapper.countByExample(iUSerCommentExample) == 1){ /*そのカラムの情報を返す*/ return iUserCommentMapper.selectByExample(iUSerCommentExample); }else{ return null; } } /* * (non-Javadoc) * @see jp.co.board.dao.comment.CommentDao#updateComment() */ public boolean updateComment(Integer commentId,Integer userId,String userName,String comment){ IUserComment iUserComment = new IUserComment(); iUserComment.setCommentId(commentId); iUserComment.setUserId(userId); iUserComment.setUserName(userName); iUserComment.setComment(comment); if(iUserCommentMapper.updateByPrimaryKey(iUserComment) == 1){ return true; }else{ return false; } } } <file_sep>package jp.co.board.action.top; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Map; import jp.co.board.dto.comment.IUserComment; import jp.co.board.dto.comment.IUserComment; import jp.co.board.service.comment.CommentService; import jp.co.board.service.top.AccountService; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.interceptor.SessionAware; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; /** * アカウント作成を操作するアクションクラス * @author tsujitakuya * */ public class AccountAction extends ActionSupport implements SessionAware{ private int userId; private String userName; private String passWord; private Timestamp insDateTime; private List<IUserComment> iUserCommentList; private Map<String, Object> session; @Autowired private AccountService accountService; @Autowired private CommentService commentService; /* * アカウント作成が成功したらhome.jspへ * 失敗したらもう一度入力画面(account.ftl)へ */ @Action(value="/top/account", results={@Result(name="success",location="../home/home.ftl"), @Result(name="input",location="account.ftl")}) public String accountCreate(){ /*名前の欄が空白ならaccount.ftlに戻る*/ if(userName == null || userName.equals("")){ return "input"; } /*パスワードの欄が空白ならaccount.ftlに戻る*/ if(passWord == null || passWord.equals("")){ return "input"; } return "success"; } @Action(value="/top/accountButton", results={@Result(name="success",location="../home/home.ftl"), @Result(name="input",location="account.ftl")}) public String accountButton(){ /*[アカウント作成]ボタンを押すと、この処理に入る*/ if(accountService.entry(userId,userName,passWord,insDateTime)){ /*セッションに格納*/ session.put("userId",userId); session.put("userName",userName); System.out.println(session.get("userName")); /*i_user_Commentテーブルの情報をhome.ftlに送信*/ List<IUserComment> iUserCommentListAll = commentService.findAll(); iUserCommentList = new ArrayList<IUserComment>(); for(IUserComment iUserCommentEntity:iUserCommentListAll){ iUserCommentList.add(iUserCommentEntity); } setIUserCommentList(iUserCommentList); return "success"; }else{ return "input"; } } @Override public void setSession(Map<String, Object> session) { this.session = session; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public Timestamp getInsDateTime() { return insDateTime; } public void setInsDateTime(Timestamp insDateTime) { this.insDateTime = insDateTime; } public List<IUserComment> getIUserCommentList() { return iUserCommentList; } public void setIUserCommentList(List<IUserComment> iUserCommentList) { this.iUserCommentList = iUserCommentList; } } <file_sep>package jp.co.board.action.top; import java.util.ArrayList; import java.util.List; import java.util.Map; import jp.co.board.dao.iuser.IUserDao; import jp.co.board.dto.comment.IUserComment; import jp.co.board.dto.comment.IUserComment; import jp.co.board.service.comment.CommentService; import jp.co.board.service.top.LoginService; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.apache.struts2.interceptor.SessionAware; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.validator.annotations.Validations; import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator; //@Results({ // @Result //}) public class LoginAction extends ActionSupport implements SessionAware{ private String userName; private String passWord; private List<IUserComment> iUserCommentList; private Map<String,Object> session; @Autowired private IUserDao iUserDao; @Autowired private LoginService loginService; @Autowired private CommentService commentService; /** * login.ftlに入った瞬間に走る処理 * @return * @throws Exception */ @Action(value="/top/login", results = {@Result(name = "success" ,location="../home/home.ftl"), @Result(name="input",location="login.ftl")}) public String login() throws Exception{ if(userName == null || userName.equals("")){ return "input"; } if(passWord == null || passWord.equals("")){ return "input"; } return "success"; } /** * ログインボタンを押した際の処理 */ @Action(value="/top/loginButton", results = {@Result(name = "success" ,location="../home/home.ftl"), @Result(name="input",location="login.ftl")}) public String loginButton(){ if(loginService.canLogin(userName,passWord)){ int userId = iUserDao.selectUserId(userName, passWord); session.put("userId", userId); session.put("userName",userName); List<IUserComment> iUserCommentListAll = commentService.findAll(); iUserCommentList = new ArrayList<IUserComment>(); for(IUserComment iUserCommentEntity:iUserCommentListAll){ // CommentList.add(iUserComment.getComment()); //userNameList.add(iUserComment.getUserName()); iUserCommentList.add(iUserCommentEntity); //session.put("commentId",iUserCommentEntity.getCommentId()); } setIUserCommentList(iUserCommentList); return "success"; }else{ return "input"; } } /** * セッション */ @Override public void setSession(Map<String, Object> session) { this.session = session; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } public List<IUserComment> getIUserCommentList() { return iUserCommentList; } public void setIUserCommentList(List<IUserComment> iUserCommentList) { this.iUserCommentList = iUserCommentList; } } <file_sep>package jp.co.board.data.comment; import java.util.List; import jp.co.board.dto.comment.IUserComment; import jp.co.board.dto.comment.IUserCommentExample; import org.apache.ibatis.annotations.Param; public interface IUserCommentMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ int countByExample(IUserCommentExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ int deleteByExample(IUserCommentExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ int deleteByPrimaryKey(Integer commentId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ int insert(IUserComment record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ int insertSelective(IUserComment record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ List<IUserComment> selectByExample(IUserCommentExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ IUserComment selectByPrimaryKey(Integer commentId); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ int updateByExampleSelective(@Param("record") IUserComment record, @Param("example") IUserCommentExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ int updateByExample(@Param("record") IUserComment record, @Param("example") IUserCommentExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ int updateByPrimaryKeySelective(IUserComment record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table i_user_comment * * @mbggenerated */ int updateByPrimaryKey(IUserComment record); }
7ee57741d3896c754b74a34e654d5036d515e545
[ "Java" ]
6
Java
TsujiTakuya55/Board
a87cb224e9dc2d126d315bdbf8ab1eea046af426
6a68289a7df0ecb6d58a3730b06e99b899a09b79
refs/heads/main
<repo_name>rwlloyd/ServoPanAndTiltHead<file_sep>/controller.py """ controller.py Python3 script to control two servos and a raspberry pi camera in a pan and tilt mechanism. The first servo pans the second servo and tilt mechanism which holds the raspberry pi camera. dependencies: pip3 install gpiozero pip3 install picamera Things also work much more smoothly if you use the pigpio pin factory https://gpiozero.readthedocs.io/en/stable/api_pins.html#changing-pin-factory <NAME> Lincoln, March 2021. """ # Import libraries from gpiozero import AngularServo from gpiozero import Button from picamera import PiCamera import os import time from time import sleep panServoPin = 13 tiltServoPin = 12 buttonPin = 25 scanning = False # These are angles from the centre point panMin = -60 panMax = 60 tiltMin = -60 tiltMax = 60 # Scanning Parameters scan_shape = [5,5] # X x Y positions.. home = [0,0] # Save the home position for later # Pan and tilt Servo servos set up panServo = AngularServo(panServoPin, initial_angle=panMin+panMax, min_angle=panMin, max_angle=panMax) tiltServo = AngularServo(tiltServoPin, initial_angle=tiltMin+tiltMax, min_angle=tiltMin, max_angle=tiltMax) # Button setup button = Button(buttonPin, bounce_time = 0.1) # Setup the camera camera = PiCamera(resolution=(1280, 720), framerate=30) # Set ISO to the desired value camera.iso = 100 # Wait for the automatic gain control to settle sleep(1) # Now fix the values #camera.shutter_speed = camera.exposure_speed #camera.exposure_mode = 'off' #g = camera.awb_gains #camera.awb_mode = 'off' #camera.awb_gains = g def set_position(newPos): print(f"Moving to: {newPos}") panServo.angle = newPos[0] tiltServo.angle = newPos[1] def button_callback(self): # Calculate the positions of the array panStep = (panMax - panMin) / scan_shape[0] tiltStep = (tiltMax - tiltMin) / scan_shape[1] print(f"panStep = {panStep}, tiltStep = {tiltStep}") set_position([panMax, tiltMax]) captureNext() for pStep in range(1, scan_shape[0] + 1): for tStep in range(1,scan_shape[1] + 1): set_position([None, tiltMax - (tStep*tiltStep)]) captureNext() set_position([panMax-(pStep*panStep), None]) captureNext() # Go back to the centre point set_position(home) print("Scan Done") sleep(0.25) print("ready") def captureNext(): # Dwell time for the camera to settle dwell = 0.5 sleep(dwell) file_name = os.path.join(output_folder, 'image_' + time.strftime("%H_%M_%S") + '.jpg') print("*") #camera.capture(file_name) #print("captured image: " + 'image_' + time.strftime("%H_%M_%S") + '.jpg') sleep(dwell) # Handling the files #get current working directory path = os.getcwd() # make the folder name folder_name = 'captureSession_' + time.strftime("%Y_%m_%d_%H_%M_%S") # make the folder os.mkdir(folder_name) # construct the output folder path output_folder = os.path.join(path, folder_name) # Callback for dealing with button press' button.when_released = button_callback panServo.angle = 5 tiltServo.angle = 5 sleep(0.25) panServo.angle = 0 tiltServo.angle = 0 print("ready") try: while True: # Erm... theres not much to do here. I'll have a nap sleep(0.1) pass #Clean things up at the end except KeyboardInterrupt: print ("Goodbye") """ The short version of how servos are controlled https://raspberrypi.stackexchange.com/questions/108111/what-is-the-relationship-between-angle-and-servo-motor-duty-cycle-how-do-i-impl Servos are controlled by pulse width, the pulse width determines the horn angle. A typical servo responds to pulse widths in the range 1000 to 2000 µs. A pulse width of 1500 µs moves the servo to angle 0. Each 10 µs increase in pulse width typically moves the servo 1 degree more clockwise. Each 10 µs decrease in pulse width typically moves the servo 1 degree more anticlockwise. Small 9g servos typically have an extended range and may respond to pulse widths in the range 500 to 2500 µs. Why do people think servos are controlled by duty cycle? Because servos are typically given 50 pulses per second (50 Hz). So each pulse is potentially a maximum of 20000 µs (1 million divided by 50). A duty cycle is the percentage on time. 100% will be a 20000 µs pulse, way outside the range accepted by a servo. Do some calculations at 50 Hz for sample pulse widths. 500 / 20000 = 0.025 or 2.5 % dutycycle 1000 / 20000 = 0.05 or 5.0 % dutycycle 1500 / 20000 = 0.075 or 7.5 % dutycycle 2000 / 20000 = 0.1 or 10.0 % dutycycle 2500 / 20000 = 0.125 or 12.5 % dutycycle Don't use dutycycles, if possible use pulse widths, and think in pulse widths. If you send pulses at 60 Hz by duty cycle the servo will go to the wrong position. """ <file_sep>/README.md # ServoPanAndTiltHead Servo driven pan and tilt head based around a Raspberry Pi and hobby servos. Instructions flash sd - ctrl+Shift+X to setup properly sudo apt update sudo apt upgrade sudo raspi-config ------------------------------ 3 Interface options - Turn on camera - Enable Remote GPIO ------------------------------------ sudo apt install git git clone https://github.com/rwlloyd/ServoPanAndTiltHead.git install python libraries sudo apt install python3-pip sudo apt install pigpio python-pigpio python3-pigpio pip3 install evdev pip3 install gpiozero pip3 install picamera https://gpiozero.readthedocs.io/en/stable/api_pins.html#changing-pin-factory # Start the pigpio daemon. Add this to bashrc along with the pin factory setting. sudo pigpiod export GPIOZERO_PIN_FACTORY=pigpio - (uses pigpio daemon for the rest of the session) <file_sep>/controller2.py # Import libraries import RPi.GPIO as GPIO from picamera import PiCamera import os import time from time import sleep Scanning = False ##for testing panServoPin = 13 tiltServoPin = 12 buttonPin = 25 # Set GPIO numbering mode GPIO.setmode(GPIO.BCM) # Set pin 11 as an output, and set servo1 as pin 11 as PWM GPIO.setup(panServoPin, GPIO.OUT) GPIO.setup(tiltServoPin, GPIO.OUT) GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) panServo = GPIO.PWM(panServoPin,50) # Note panServoPin is pin, 50 = 50Hz pulse tiltServo = GPIO.PWM(tiltServoPin,50) #start PWM running, but with value of 0 (pulse off) panServo.start(0) tiltServo.start(0) print ("Servos Init") sleep(0.5) # Setup the camera camera = PiCamera(resolution=(1280, 720), framerate=30) # Set ISO to the desired value camera.iso = 100 # Wait for the automatic gain control to settle sleep(1) # Now fix the values #camera.shutter_speed = camera.exposure_speed #camera.exposure_mode = 'off' #g = camera.awb_gains #camera.awb_mode = 'off' #camera.awb_gains = g print("Camera Init") sleep(0.5) print("Ready") scanning = False def captureNext(): # Dwell time for the camera to settle dwell = 0.5 sleep(dwell) file_name = os.path.join(output_folder, 'image_' + time.strftime("%H_%M_%S") + '.jpg') camera.capture(file_name) print("captured image: " + 'image_' + time.strftime("%H_%M_%S") + '.jpg') sleep(dwell) def button_callback(self): scanning = True update(panServo, 90) update(tiltServo, 90) sleep(2) update(panServo, 90+45) sleep(2) update(panServo, 90) sleep(2) # update(panServo, -45) # captureNext() # update(panServo, 0) # captureNext() # update(panServo, 45) # captureNext() # update(panServo, 0) print("Scan Complete!") scanning = False # Handling the files #get current working directory path = os.getcwd() # make the folder name folder_name = 'captureSession_' + time.strftime("%Y_%m_%d_%H_%M_%S") # make the folder os.mkdir(folder_name) # construct the output folder path output_folder = os.path.join(path, folder_name) GPIO.add_event_detect(buttonPin,GPIO.RISING,callback=button_callback) try: while True: # Erm... theres not much to do here. I'll have a nap if not scanning: update(panServo, 0) update(tiltServo, 0) #Clean things up at the end except KeyboardInterrupt: panServo.stop() tiltServo.stop() GPIO.cleanup() print ("Goodbye") """ The short version of how servos are controlled https://raspberrypi.stackexchange.com/questions/108111/what-is-the-relationship-between-angle-and-servo-motor-duty-cycle-how-do-i-impl Servos are controlled by pulse width, the pulse width determines the horn angle. A typical servo responds to pulse widths in the range 1000 to 2000 µs. A pulse width of 1500 µs moves the servo to angle 0. Each 10 µs increase in pulse width typically moves the servo 1 degree more clockwise. Each 10 µs decrease in pulse width typically moves the servo 1 degree more anticlockwise. Small 9g servos typically have an extended range and may respond to pulse widths in the range 500 to 2500 µs. Why do people think servos are controlled by duty cycle? Because servos are typically given 50 pulses per second (50 Hz). So each pulse is potentially a maximum of 20000 µs (1 million divided by 50). A duty cycle is the percentage on time. 100% will be a 20000 µs pulse, way outside the range accepted by a servo. Do some calculations at 50 Hz for sample pulse widths. 500 / 20000 = 0.025 or 2.5 % dutycycle 1000 / 20000 = 0.05 or 5.0 % dutycycle 1500 / 20000 = 0.075 or 7.5 % dutycycle 2000 / 20000 = 0.1 or 10.0 % dutycycle 2500 / 20000 = 0.125 or 12.5 % dutycycle Don't use dutycycles, if possible use pulse widths, and think in pulse widths. If you send pulses at 60 Hz by duty cycle the servo will go to the wrong position. """
57e8e35ed53ac10de3eea35930f1eead0fbde976
[ "Markdown", "Python" ]
3
Python
rwlloyd/ServoPanAndTiltHead
6405f3cd75c169a154346837a70d978c6092c314
393740798fe332c733bb6c8ece6547d1cc70edb9
refs/heads/master
<file_sep>{ "targets": [ { "target_name": "balanced-match", "sources": [ "src/balanced-match.cc" ], } ] } <file_sep>[![Build Status](https://travis-ci.org/shivanth/balanced-match-native.svg?branch=master)](https://travis-ci.org/shivanth/balanced-match-native) # Balanced-match A N-API version of https://github.com/juliangruber/balanced-match # Reuirements Node.js v8 # Install ``` npm install git+https://github.com/shivanth/balanced-match-native.git ``` # Usage ```javascript var balanced = require('balanced-match-native'); balanced('{', '}',"1{234}5") //{start:1, end:5,pre:"1", post:"5",body:"234"} balanced('{{{', '}}',"123{{{234}}") // {start:3, end:9,pre:"123", post:"",body:"234"} ``` # Note Regex is not supported yet for the first two arguments of balanced. <file_sep>#include <node_api.h> #include <assert.h> #include<string> #include<vector> #include<iostream> std::vector<size_t> range(std::string a,std::string b,std::string c); #define DECLARE_NAPI_METHOD(name, func) \ { name, 0, func, 0, 0, 0, napi_default, 0 } napi_value balanced(napi_env env, napi_callback_info info){ napi_status status; size_t argc = 3; napi_value args[3]; status = napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); assert(status == napi_ok); if (argc < 3) { napi_throw_error(env,NULL, "Wrong number of arguments"); return nullptr; } napi_valuetype valuetype0; status = napi_typeof(env, args[0], &valuetype0); if(status != napi_ok){ napi_throw_error(env,NULL, "Expected String"); return nullptr; } napi_valuetype valuetype1; status = napi_typeof(env, args[1], &valuetype1); if(status != napi_ok){ napi_throw_error(env,NULL, "Expected String"); return nullptr; } napi_valuetype valuetype2; status = napi_typeof(env, args[2], &valuetype2); if(status != napi_ok){ napi_throw_error(env,NULL, "Expected String"); return nullptr; } if (valuetype0 != napi_string || valuetype1 != napi_string || valuetype2 != napi_string){ napi_throw(env,NULL); } //get c++ values of arguments size_t size1, size2,size3; size_t written; status = napi_get_value_string_utf8(env, args[0], NULL, 0, &size1); char * _arg1 = new char[size1 + 1]; status = napi_get_value_string_utf8(env,args[0],_arg1,size1 + 1, &written); std::string arg1(_arg1); status = napi_get_value_string_utf8(env, args[1], NULL, 0, &size2); char * _arg2 = new char[size2 + 1]; status = napi_get_value_string_utf8(env,args[1],_arg2,size2 + 1, &written); std::string arg2(_arg2); status = napi_get_value_string_utf8(env, args[2], NULL, 0, &size3); char * _arg3 = new char[size3 + 1]; status = napi_get_value_string_utf8(env,args[2],_arg3,size3 + 1, &written); std::string arg3(_arg3); //find the first match indexes std::vector<size_t> r = range(arg1,arg2,arg3); napi_value pos1 = NULL; napi_value pos2 = NULL; if(r.size() == 2){ status = napi_create_int32(env,r[0],&pos1); status = napi_create_int32(env,r[1],&pos2); } else{ return NULL;//undefined } napi_value pre; napi_value body; napi_value post; napi_value ret; //find the pre , body and post of the match using the ranges napi_create_string_utf8(env,arg3.substr(0,r[0]).c_str(),r[0],&pre); napi_create_string_utf8(env,arg3.substr(r[0] + size1 , r[1] - r[0] - size1 ).c_str(),r[1] - r[0] -size1,&body); napi_create_string_utf8(env,arg3.substr(r[1] + size2, size3 - (r[1] + size2 )).c_str(),size3 - (r[1] + size2 ),&post); status = napi_create_object(env, &ret); // create the return object napi_set_named_property(env, ret, "start", pos1); napi_set_named_property(env, ret, "end", pos2); napi_set_named_property(env, ret, "pre", pre); napi_set_named_property(env, ret, "body", body); napi_set_named_property(env, ret, "post", post); return ret; } std::vector<size_t> range(std::string a,std::string b,std::string c){ std::cout<<a<<" "<<b<<" "<<c<<std::endl; std::string::size_type pos1 = c.find(a); std::string::size_type pos2 = c.find(b,pos1); std::string::size_type i = pos1; std::string::size_type beg, left, right; std::vector<std::string::size_type> result; std::cout<<pos1<<" "<<pos2<<std::endl; bool done = false; std::cout<<i<<std::endl<<std::flush; if(pos1 != std::string::npos && pos2 != std::string::npos){ std::vector<std::string::size_type> begs; left = a.size(); while(i != std::string::npos && !done){ if(i == pos1){ begs.push_back(i); pos1 = c.find(a, i+1); } else if (begs.size() == 1){ result.clear(); result.push_back(begs.back()); result.push_back(pos2); begs.pop_back(); done = true; } else{ beg = begs.back(); begs.pop_back(); if(beg < left){ left = beg; right = pos2; } } i = pos1 < pos2 && pos1 !=std::string::npos ? pos1 : pos2; } if (begs.size()) { result.clear(); result.push_back(left); result.push_back(right); } } return result; } void Init(napi_env env, napi_value exports, napi_value module, void* priv) { napi_status status; napi_property_descriptor balancedDescriptor = DECLARE_NAPI_METHOD("balanced", balanced); status = napi_define_properties(env, exports, 1, &balancedDescriptor); assert(status == napi_ok); } NAPI_MODULE(addon, Init);
f135ad8a82495e58724ccea729b99bd1c7ab5f13
[ "Markdown", "Python", "C++" ]
3
Python
shivanth/balanced-match-native
dfa9677b474e5406de8ef9898a70eba1260a0d7b
9e1b538cebdd1bb70d889db39d5dd911f57b3631
refs/heads/master
<file_sep><?php namespace sephp\core; use sephp\sephp; /** * 模板引擎实现类 * * @author seatle<<EMAIL>> * @version $Id$ */ class view { private static $_instance = null; // 自定义模版标签填充数据用 public static $blocksdata = array(); // 最终输出的数据 public static $final_output; protected static $config = null; /** * Smarty 初始化 * @return resource */ public static function instance() { if (self::$_instance === null) { require_once PATH_LIB.'smarty3/Smarty.class.php'; self::$_instance = new \Smarty(); self::$_instance->setTemplateDir(PATH_VIEW); //定义smarty编译目录 self::$_instance->setCompileDir(PATH_RUNTIME . 'compile/'); //定义smarty缓存目录 self::$_instance->setCacheDir(PATH_RUNTIME . 'cache/'); //smarty自定义插件 self::$_instance->addPluginsDir(PATH_LIB . 'smarty_plugins/'); //self::$_instance->addPluginsDir(PATH_LIB . 'smarty3/smarty_plugins'); self::$_instance->setLeftDelimiter('<{'); self::$_instance->setRightDelimiter('}>'); self::$_instance->setCompileCheck(true); self::config(); } return self::$_instance; } protected static function config() { self::$config = sephp::$_config['web']; self::instance()->assign('_self_url', '?ct='.CONTROLLER_NAME.'&ac='.ACTION_NAME); self::instance()->assign('_ct_name', CONTROLLER_NAME); self::instance()->assign('_ac_name', ACTION_NAME); self::instance()->assign('_forms', req::$forms); self::instance()->assign('clear_cache', '?'.time()); self::instance()->assign('_site_url', self::$config['url']); //前端版本设置,方便清除 js css 的缓存 self::instance()->assign('build', empty(self::$config['build']) ? time() : self::$config['build']); self::instance()->assign('url_upload', sephp::$_config['upload']['filelink'].'/image/'); $site_info = config::get('base_config','mysql'); view::assign('site_info', $site_info); view::assign('page_title', $site_info['page_title']); view::assign('page_description', $site_info['page_description']); view::assign('page_keywords', $site_info['page_keywords']); } public static function fetch($tpl = '') { return self::instance()->fetch(self::make_tpl($tpl)); } public static function assign($tpl_var, $value) { self::instance()->assign($tpl_var, $value); } public static function display($tpl = '') { if (!empty(sephp::$_config['web']['static_page']) && in_array(APP_NAME, sephp::$_config['web']['static_page'])) { $file_path = PATH_RUNTIME.'cache/html/'.APP_NAME.'/'; if (!file_exists($file_path)) { mkdir($file_path, '0777', true); } $name = null; foreach (req::$forms as $k => $v) { $name .= $k.'-'.$v.'_'; } $html_file_name = $file_path.rtrim($name, '_').'.html'; if (!file_exists($html_file_name)) { $html_content = self::fetch($tpl); @file_put_contents($html_file_name, $html_content); } } self::instance()->display(self::make_tpl($tpl)); } private static function make_tpl($tpl = '') { $tpl = empty($tpl)?CONTROLLER_NAME.'.'.ACTION_NAME:$tpl; return $tpl.'.tpl'; } } <file_sep><?php namespace sephp\core\lib; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\config; use sephp\core\lang; use sephp\core\lib\image; use sephp\core\lib\ftp; /** * 文件上传管理 * Class sys_upload * * 文件上传 * $FILES[ 'file' ][ 'error' ]一共有7种类型: * 1、UPLOAD_ERR_OK * 其值为 0,没有错误发生,文件上传成功。 * 2、UPLOAD_ERR_INI_SIZE * 其值为 1,上传的文件超过了 php.ini 中 upload_max_filesize选项限制的值。 * 3、UPLOAD_ERR_FORM_SIZE * 其值为 2,上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。 * 4、UPLOAD_ERR_PARTIAL * 其值为 3,文件只有部分被上传。 * 5、UPLOAD_ERR_NO_FILE * 其值为 4,没有文件被上传。 * 6、UPLOAD_ERR_NO_TMP_DIR * 其值为 6,找不到临时文件夹。PHP 4.3.10 和 PHP 5.0.3 引进。 * 7、UPLOAD_ERR_CANT_WRITE * 其值为 7,文件写入失败。PHP 5.1.0 引进。 */ class upload { /** * 上传类的配置参数 * @var null */ public static $config = null; /** * 初始化配置参数 * @Author GangKui * @DateTime 2019-10-16 * @param array $config [description] * @return [type] [description] */ public static function _init($config = []) { self::$config = empty($config) ? config::get('upload') : $config; } /** * 普通上传 * * @param string $formname * @param string $dir * @param int $thumb_width * @param float $thumb_height * @return array */ public static function upload( $formname = 'file', $dir = 'image', $thumb_w = 0, $thumb_h = 0 ) { // 导入语言包 lang::load("upload"); $dir = self::filter_path($dir); // 上传成功 if ( req::is_upload_file($formname) ) { $upload_dir = self::$config['filepath']."/{$dir}"; // 目录不存在则生成 if ( !func::path_exists($upload_dir) ) { throw new \Exception(lang::get('upload_not_exist')); } $allowed_types = explode('|', self::$config['allowed_types']); if ( !req::check_subfix($formname, $allowed_types) ) { throw new \Exception(lang::get('upload_invalid_filetype')); } $filesize = req::get_file_info($formname, 'size'); $realname = req::get_file_info($formname, 'name'); $file_ext = req::get_file_ext($formname); // 判断文件大小 if ( self::$config['max_size'] != 0 ) { $max_size = self::$config['max_size'] * 1024; if ( $filesize > $max_size ) { throw new \Exception(lang::get('upload_invalid_filesize')); } } $filename = md5_file(req::get_tmp_name($formname)).".".$file_ext; //$filename = uniqid().'.'.$file_ext; // 如果需要分隔目录上传 if ( self::$config['dir_num'] > 0 ) { $dir_num = func::str_to_number($filename, self::$config['dir_num']); func::path_exists($upload_dir.'/'.$dir_num); $filename = $dir_num.'/'.$filename; } //ftp上传 if( !empty(self::$config['enable_ftp']) ) { $realpath = req::$files[$formname]['tmp_name']; if ( $thumb_w > 0 || $thumb_h > 0 ) { req::move_upload_file($formname, $upload_dir.'/'.$filename); //方便使用thumb函数 list( $filename, $filelink ) = self::thumb( $upload_dir, $filename, $file_ext, $thumb_w, $thumb_h ); $realpath = $upload_dir.'/'.$filename; } //上传目录一起返回,要不ftp不知道要上传到哪里 $filename = $dir.'/'.$filename; if( false != ftp::instanct()->put($realpath, $filename) ) { ftp::instanct()->chmod($filename, 0644); } else { throw new \Exception(ftp::instanct()->error); } } else if ( req::move_upload_file($formname, $upload_dir.'/'.$filename) ) { @chmod($upload_dir.'/'.$filename, 0777); if ( $thumb_w > 0 || $thumb_h > 0 ) { list( $filename, $filelink ) = self::thumb( $upload_dir, $filename, $file_ext, $thumb_w, $thumb_h ); } } $filelink = self::$config['filelink'].'/'.$dir.'/'.$filename; return array( 'realname' => $realname, 'filename' => $filename, 'filelink' => $filelink, ); } else { var_dump(req::$files);exit; if( req::$files[$formname]['error'] == UPLOAD_ERR_INI_SIZE || req::$files[$formname]['error'] == UPLOAD_ERR_FORM_SIZE ) { throw new \Exception(lang::get('upload_invalid_filesize')); } } } /** * HTML5 图片字节流方式上传 * * @param mixed $filedata * @param string $filetype * @param int $thumb_width * @param float $thumb_height * @return array */ public static function upload_html5( $filedata, $dir = 'image', $thumb_w = 0, $thumb_h = 0 ) { // 导入语言包 lang::load("upload"); $dir = self::filter_path($dir); // 匹配出图片的格式 if ( preg_match('/^(data:\s*image\/(\w+);base64,)/', $filedata, $result) ) { $upload_dir = self::$config['filepath']."/{$dir}"; // 目录不存在则生成 if ( !func::path_exists($upload_dir) ) { throw new \Exception(lang::get('upload_not_exist')); } // 检查文件类型 $file_ext = $result[2]; $file_ext = $file_ext == 'jpeg' ? 'jpg' : $file_ext; $allowed_types = explode('|', self::$config['allowed_types']); if ( !in_array($file_ext, $allowed_types) ) { throw new \Exception(lang::get('upload_invalid_filetype')); } // 把 data:image/jpeg;base64, 去掉 $filedata = base64_decode(str_replace($result[1], '', $filedata)); // 判断文件大小 if ( self::$config['max_size'] != 0 ) { $max_size = self::$config['max_size'] * 1024; if ( strlen($filedata) > $max_size ) { throw new \Exception(lang::get('upload_invalid_filesize')); } } //$filename = uniqid().'.'.$file_ext; $filename = md5($filedata).".".$file_ext; // 如果需要分隔目录上传 if ( self::$config['dir_num'] > 0 ) { $dir_num = func::str_to_number($filename, self::$config['dir_num']); func::path_exists($upload_dir.'/'.$dir_num); $filename = $dir_num.'/'.$filename; } if ( func::put_file($upload_dir.'/'.$filename, $filedata) ) { @chmod($upload_dir.'/'.$filename, 0777); } $filelink = self::$config['filelink']."/".$dir."/".$filename; if ( $thumb_w > 0 || $thumb_h > 0 ) { list( $filename, $filelink ) = self::thumb( $upload_dir, $filename, $file_ext, $thumb_w, $thumb_h ); } //ftp上传 if( !empty(self::$config['enable_ftp']) ) { //上传目录一起返回,要不ftp不知道要上传到哪里 $filename = $dir.'/'.$filename; if( false != ftp::instance()->put($upload_dir.'/'.$filename, $filename, true) ) { ftp::instance()->chmod($filename, 0644); } else { throw new \Exception(ftp::instance()->error); } } return array( 'realname' => $filename, 'filename' => $filename, 'filelink' => $filelink, ); } } /** * 分片上传 * 图片上传请调用上面两个方法,这里一般用于上传大文件 * * @param mixed $cleanup_target_dir Remove old files * @param float $max_file_age Temp file age in seconds 5x3600=18000 * @return array */ public static function upload_chunked( $formname = 'file', $dir = 'file', $guid, $chunk = 0, $chunks = 1, $thumb_w = 0, $thumb_h = 0, $cleanup_target_dir = true, $max_file_age = 18000 ) { lang::load("upload"); $dir = self::filter_path($dir); // 生成上传分片的临时目录 //$target_dir = ini_get("upload_tmp_dir")."/plupload"; $target_dir = PATH_UPLOAD . "/tmp/{$guid}"; $upload_dir = PATH_UPLOAD . "/{$dir}"; // 目录不存在则生成 if ( !func::path_exists($target_dir) ) { throw new \Exception(lang::get('upload_not_exist')); } if ( !func::path_exists($upload_dir) ) { throw new \Exception(lang::get('upload_not_exist')); } // 检查文件类型 $file_ext = req::get_file_ext($formname); $allowed_types = explode('|', self::$config['allowed_types']); if ( !in_array($file_ext, $allowed_types) ) { throw new \Exception(lang::get('upload_invalid_filetype')); } $realname = req::get_file_info($formname, 'name'); $partpath = $target_dir.'/'.$realname; // 分片文件位置 $realpath = $upload_dir.'/'.$realname; // 合并分片后的文件位置 // Remove old temp files if ( $cleanup_target_dir ) { if (!is_dir($target_dir) || !$cleanup_dir = opendir($target_dir)) { throw new \Exception('Failed to open temp directory.'); } while (($file = readdir($cleanup_dir)) !== false) { $tmpfile_path = $target_dir . '/' . $file; // If temp file is current file proceed to the next if ($tmpfile_path == "{$partpath}_{$chunk}.part" || $tmpfile_path == "{$partpath}_{$chunk}.parttmp") { continue; } if (preg_match('/\.(part|parttmp)$/', $file) && file_exists($tmpfile_path) && (@filemtime($tmpfile_path) < time() - $max_file_age)) { @unlink($tmpfile_path); } } closedir($cleanup_dir); } // Open temp file if (!$out = @fopen("{$partpath}_{$chunk}.parttmp", "wb")) { throw new \Exception('Failed to open output stream.'); } if ( !empty(req::$files)) { if ( !req::is_upload_file($formname) ) { throw new \Exception('Failed to move uploaded file.'); } // Read binary input stream and append it to temp file if (!$in = @fopen(req::get_tmp_name($formname), "rb")) { throw new \Exception('Failed to open input stream.'); } } else { if (!$in = @fopen("php://input", "rb")) { throw new \Exception('Failed to open input stream.'); } } while ($buff = fread($in, 4096)) { fwrite($out, $buff); } @fclose($out); @fclose($in); rename("{$partpath}_{$chunk}.parttmp", "{$partpath}_{$chunk}.part"); $index = 0; $done = true; for( $index = 0; $index < $chunks; $index++ ) { if ( !file_exists("{$partpath}_{$index}.part") ) { $done = false; break; } } if ( $done ) { if (!$out = @fopen($realpath, "wb")) { throw new \Exception('Failed to open output stream.'); } if ( flock($out, LOCK_EX) ) { for( $index = 0; $index < $chunks; $index++ ) { if (!$in = @fopen("{$partpath}_{$index}.part", "rb")) { break; } while ($buff = fread($in, 4096)) { fwrite($out, $buff); } @fclose($in); @unlink("{$partpath}_{$index}.part"); } flock($out, LOCK_UN); } @fclose($out); // 删除目录 @rmdir($target_dir); // 保留真实名称 $filename = md5_file($realpath).".".$file_ext; //$filename = uniqid().".".$file_ext; // 如果需要分隔目录上传 if ( self::$config['dir_num'] > 0 ) { $dir_num = func::str_to_number($filename, self::$config['dir_num']); if ( !func::path_exists($upload_dir.'/'.$dir_num) ) { throw new \Exception(lang::get('upload_not_exist')); } $filename = $dir_num.'/'.$filename; } // 判断文件大小 if ( self::$config['file_max_size'] != 0 ) { $max_size = self::$config['file_max_size'] * 1024; if ( filesize($realpath) > $max_size ) { throw new \Exception(lang::get('upload_invalid_filesize')); } } //ftp上传 if( !empty(self::$config['enable_ftp']) ) { if ( $thumb_w > 0 || $thumb_h > 0 ) { //为了使用thumb函数,重新复制到upload_dir目录 rename($realpath, "{$upload_dir}/{$filename}"); list( $filename, $filelink ) = self::thumb( $upload_dir, $filename, $file_ext, $thumb_w, $thumb_h ); $realpath = $upload_dir.'/'.$filename; } //上传目录一起返回,要不ftp不知道要上传到哪里 $filename = $dir.'/'.$filename; if( false != ftp::instance()->put($realpath, $filename, true) ) { ftp::instance()->chmod($filename, 0644); } else { throw new \Exception(ftp::instance()->error); } } else { //rename('tmp/104/84405b7dae5c5a13fe76a99de3a8293d.jpg', 'image/104/84405b7dae5c5a13fe76a99de3a8293d.jpg'); rename($realpath, "{$upload_dir}/{$filename}"); if ( $thumb_w > 0 || $thumb_h > 0 ) { list( $filename, $filelink ) = self::thumb( $upload_dir, $filename, $file_ext, $thumb_w, $thumb_h ); } } $filelink = self::$config['filelink'].'/'.$dir.'/'.$filename; return array( 'realname' => $realname, 'filename' => $filename, 'filelink' => $filelink, ); } } public static function thumb( $upload_dir, $filename, $file_ext = 'jpg', $thumb_w = 0, $thumb_h = 0 ) { $pathinfo = getimagesize($upload_dir.'/'.$filename); //var_dump($upload_dir.'/'.$filename); //var_dump($pathinfo); $width = $pathinfo[0]; $height = $pathinfo[1]; // 缩略图的临时目录 $filepath_tmp = self::$config['filepath'].'/tmp'; // 缩略图的临时文件名 $filename_tmp = md5($filename).'.'.$file_ext; if ( $thumb_w > 0 && $thumb_h > 0 ) { image::instance( $upload_dir.'/'.$filename )->thumb( $thumb_w, $thumb_h, $filepath_tmp.'/'.$filename_tmp, 'wh' ); } // 只设置了宽度,自动计算高度 elseif ( $thumb_w > 0 && $thumb_h == 0 ) { image::instance( $upload_dir.'/'.$filename )->thumb( $thumb_w, $thumb_h, $filepath_tmp.'/'.$filename_tmp, 'w' ); } // 只设置了高度,自动计算宽度 elseif ( $thumb_h > 0 && $thumb_w == 0 ) { image::instance( $upload_dir.'/'.$filename )->thumb( $thumb_w, $thumb_h, $filepath_tmp.'/'.$filename_tmp, 'h' ); } //@chmod($filepath_tmp.'/'.$filename_tmp, 0777); $filename = md5_file($filepath_tmp.'/'.$filename_tmp).".".$file_ext; //$filename = uniqid().'.'.$file_ext; // 如果需要分隔目录上传 if ( self::$config['dir_num'] > 0 ) { $dir_num = func::str_to_number($filename, self::$config['dir_num']); if ( !func::path_exists($upload_dir.'/'.$dir_num) ) { throw new \Exception(lang::get('upload_not_exist')); } $filename = $dir_num.'/'.$filename; } rename($filepath_tmp.'/'.$filename_tmp, "{$upload_dir}/{$filename}"); $filelink = self::$config['filelink'].'/image/'.$filename; return array($filename, $filelink); } public static function remove_tmp_file() { if ( $cleanxxup_target_dir ) { if (!is_dir($target_dir) || !$cleanup_dir = opendir($target_dir)) { throw new \Exception('Failed to open temp directory.'); } while (($file = readdir($cleanup_dir)) !== false) { $tmpfile_path = $target_dir . '/' . $file; // If temp file is current file proceed to the next if ($tmpfile_path == "{$partpath}_{$chunk}.part" || $tmpfile_path == "{$partpath}_{$chunk}.parttmp") { continue; } if (preg_match('/\.(part|parttmp)$/', $file) && file_exists($tmpfile_path) && (@filemtime($tmpfile_path) < time() - $max_file_age)) { @unlink($tmpfile_path); } } closedir($cleanup_dir); } } //去掉前端传过来的路径 public static function filter_path($dir) { $dirs = []; array_map(function($a) use (&$dirs){ if( !empty($dir = preg_replace('#[\s\.]#', '', $a)) ) { $dirs[] = $dir; } }, explode('/', $dir)); return implode('/', $dirs); } /** * mysql 保存上传文件 * @param array $result * @return bool */ public static function save_file($result = []) { if(empty($result) || empty($result['realname']) || empty($result['type'])) { log::error('文件保存失败,数据确实.data:'.var_export($result,1)); log::error('req::$forms:'.var_export(req::$forms)); return false; } $data['realname'] = $result['realname']; $data['filename'] = $result['name']; $data['size'] = $result['size']; $data['type'] = $result['type']; $data['create_time'] = time(); $data['create_user'] = sys_power::instance()->_uid; list($id,$rows) = db::insert('file')->set($data)->execute(); if($id) { $data['file_id'] = $id; $data['upload_dir'] = PATH_UPLOAD . 'file/'; $data['http'] = URL_ROOT.'/upload/file/'; return $data; } log::error('文件保存sql执行失败:'.db::get_last_sql()); return false; } public static function del_file($file_id = 0) { if(empty($file_id)) { return false; } $data['delete_user'] = sys_power::instance()->_uid; $data['delete_time'] = time(); if(db::update('file')->set($data)->where('file_id',$file_id)->execute() === false) { return false; } return true; } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 支付流水model * @ClassName: pub_mod_payments * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_payments extends pub_mod_model { public static $_table = '#PB#_payments', $_pk = 'payment_id', $_fields = [ 'payment_id' => ['type' => 'int', 'required' => true, 'comment' => '支付单号'], 'payment_bn' => ['type' => 'text', 'default' => null, 'comment' => '支付单唯一编号'], 'order_id' => ['type' => 'int', 'required' => true, 'comment' => '订单ID'], 'money' => ['type' => 'text', 'required' => true, 'comment' => '支付金额'], 'cur_money' => ['type' => 'text', 'default' => 0, 'comment' => '支付货币金额'], 'currency' => ['type' => 'int', 'default' => 0, 'comment' => '货币'], 'member_id' => ['type' => 'text', 'default' => null, 'comment' => '会员用户名'], 'status' => ['type' => 'text', 'default' => null, 'comment' => '支付状态'], 'pay_name' => ['type' => 'text', 'default' => null, 'comment' => '支付描述名称'], 'pay_type' => ['type' => 'text', 'default' => null, 'comment' => '支付类型'], 't_payed' => ['type' => 'text', 'default' => null, 'comment' => '支付完成时间'], 'account' => ['type' => 'text', 'default' => null, 'comment' => '收款账号'], 'bank' => ['type' => 'text', 'default' => null, 'comment' => '收款银行'], 'pay_account' => ['type' => 'int', 'default' => 0, 'comment' => '支付账户'], 'paycost' => ['type' => 'text', 'default' => 0, 'comment' => '支付网关费用'], 'pay_app_id' => ['type' => 'text', 'default' => 0, 'comment' => '支付方式名称'], 'pay_ver' => ['type' => 'text', 'default' => 0, 'comment' => '支付版本号'], 'ip' => ['type' => 'int', 'default' => 1, 'comment' => '支付IP'], 't_begin' => ['type' => 'text', 'default' => null, 'comment' => '支付开始时间'], 't_confirm' => ['type' => 'text', 'default' => null, 'comment' => '支付确认时间'], 'memo' => ['type' => 'text', 'default' => null, 'comment' => '支付注释'], 'return_url' => ['type' => 'text', 'default' => null, 'comment' => '支付返回地址'], 'disabled' => ['type' => 'text', 'default' => null, 'comment' => '支付单状态'], 'trade_no' => ['type' => 'text', 'default' => null, 'comment' => '支付单交易编号'], 'thirdparty_account' => ['type' => 'text', 'default' => null, 'comment' => '第三方支付账户'], 'adduser' => ['type' => 'text', 'required' => false, 'default' => '', 'comment' => '添加人'], 'addtime' => ['type' => 'int', 'required' => false, 'default' => '', 'comment' => '添加时间'], 'upuser' => ['type' => 'text', 'default' => 0, 'comment' => '更新人'], 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], ], $status = [ '1' => '准备中', '2' => '成功', '3' => '失败', '4' => '已取消', '5' => '无效的', '6' => '错误', '9' => '支付异常', ], $disabled = [ '1' => '启用', '2' => '禁用', ]; /** * 支付状态 */ const STATUS_READY = 1; const STATUS_SUCC = 2; const STATUS_FAIL = 3; const STATUS_CANCEL = 4; const STATUS_INVALID = 5; const STATUS_ERROR = 6; const STATUS_EXCEPTION = 9; } <file_sep><?php $config['web'] = [ 'url' => 'http://sephp.a.com', //是否开启验证码 'verify_open' => false, //是否开启google auth 验证 'google_auth' => false, //编辑器指定 'edit_tool' => 'mvim://open/?url=file://%file%&line=%line%', //phpstrom 'idea://open?file=%file%&line=%line% //是否生成静态页面 //'static_page' => ['index','member'], //css,js版本号,方便集体刷新缓存 'build' => 'xxxxxxx', ]; $config['log'] = [ 'open' => true, //开启 'single' => true, //单日志文件模式 'file_size' => 10240, //10M 'type' => 'file', 'path' => PATH_ROOT.'runtime/log/', 'detail_info' => true, ]; //session 设置 $config['session'] = [ 'prefix' => 'sephp.a.com_', 'auto_start' => true, 'path' => '', 'expire' => 14400, 'secure' => false, 'use_cookies' => true, ]; //可以做读写分离的设置 $config['db'] = [ 'type' => 'mysql', 'host' => '127.0.0.1', 'root' => 'root', 'pass' => '<PASSWORD>', 'dbname' => 'sephp', 'port' => '3306', 'prefix' => 'se_', 'master' => [], 'sleave' ]; $config['cache'] = [ // 驱动方式 'type' => 'file', // 缓存保存目录 'path' => '', // 缓存前缀 'prefix' => '', // 缓存有效期 0表示永久缓存 'expire' => 0, ]; $config['cookie'] = [ // cookie 名称前缀 'prefix' => '', // cookie 保存时间 'expire' => 0, // cookie 保存路径 'path' => '/', // cookie 有效域名 'domain' => '', // cookie 启用安全传输 'secure' => false, // httponly设置 'httponly' => '', // 是否使用 setcookie 'setcookie' => true, ]; $config['redis'] = [ 'host' => '127.0.0.1', 'port' => '6370', 'user' => '', 'pass' => '', 'select' => 0, 'timeout' => 0, 'expire' => 0, 'persistent' => false, 'prefix' => '', ]; //路由解析配置 $config['route'] = [ 'url_route_on' => ['index'], //开启路由模式的项目 'url_route_ext' => 'html', 'url_route_rules' => [ 'adduser-(\w+)-(\w+)' => '?ct=admin&ac=adduser&admin_id=$1&admin=$2', 'upload_file_list' => '?ct=system&ac=upload_file', 'help' => '?ct=index&ac=help', 'index' => '?ct=index&ac=index', 'about' => '?ct=index&ac=about', 'service' => '?ct=index&ac=service', 'cases' => '?ct=index&ac=cases', 'solutions' => '?ct=index&ac=solutions', 'news' => '?ct=index&ac=news', 'contact' => '?ct=index&ac=contact', 'news-(\w+)-(\w+)' => '?ct=index&ac=news&article_id=$1&p=$2', ], ]; //微信公众号 $config['wechat'] = [ 'app_id' => 'wx77838ddac7e73c08', 'app_secret' => 'ba6ca706a64237d704dbfd585db93877' ]; //短信 $config['sms'] = [ 'app_id' => 'cf_uli9', 'app_key' => '<KEY>', 'sms_send_time' => 60, 'sms_send_num' => 5, 'sms_send_black_time' => 600, 'url' => 'http://106.ihuyi.cn/webservice/sms.php?method=Submit', 'is_open_send_limit' => 1, ]; $config['ip_country_file'] = PATH_LIB.'assets/IPV6-COUNTRY-ISP.BIN'; $config['wechat'] = [ 'appid' => 'wxba5d1dd8974adb97', 'appsecret' => '<KEY>', ]; return $config; <file_sep><?php namespace index\ctl; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\config; use sephp\core\view; use common\model\pub_mod_goods; class ctl_goods { public function __construct() { $site_info = config::get('base_config','mysql'); $this->page_keywords = $site_info['page_keywords']; $this->page_description = $site_info['page_description']; $this->page_title = $site_info['page_title']; view::assign('site_info', $site_info); view::assign('page_title', $this->page_title); view::assign('page_description', $this->page_description); view::assign('page_keywords', $this->page_keywords); //friend link $links = config::get('friend_link'); } /** * 商品列表 * @Author GangKui * @DateTime 2019-10-25 * @return [type] [description] */ public function list() { $list = pub_mod_goods::getlist([ 'total' => true, 'limit' => 1, 'where' => [ ['marketable', '=', '1'], ], 'order_by' => ['p_order', 'DESC'], ]); //print_r($list);exit; view::assign('list', $list['data']); view::assign('pages', $list['pages']); view::display(); } /** * 商品详情 * @Author GangKui * @DateTime 2019-10-25 * @return [type] [description] */ public function detail() { $goods_id = req::item('goods_id', 0); if(0 < $goods_id) { $data = pub_mod_goods::getdatabyid($goods_id); } if(empty($data)) { show_msg::error('商品不存在'); } view::assign('data', $data); view::display(); } } <file_sep><?php namespace sephp\core; use sephp\sephp; use sephp\core\req; use sephp\core\filter; use sephp\core\lib\db\mysqli; use sephp\core\lib\db\mysql; use sephp\core\lib\db\base; use sephp\core\lib\db\sqlsrv; class db { public static $queries = []; public static $query_times = []; public static function get_last_sql() { return array_pop(self::$query_sql); } /** * 数据库初始化,并取得数据库类实例 * @access public * @param mixed $config 连接配置 * @param bool|string $name 连接标识 true 强制重新连接 * @return Connection * @throws Exception */ public static function connect($config = [], $name = false) { if(function_exists('mysqli_connect')) { return mysqli::instance(); } elseif (function_exists('mysql_connect')) { return mysql::instance(); } } /** * 调用驱动类的方法 * @access public * @param string $method 方法名 * @param array $params 参数 * @return mixed */ public static function __callStatic($method, $params) { return call_user_func_array([self::connect(), $method], $params); } } <file_sep><?php namespace sephp; use sephp\autoloads; use sephp\core\config; use sephp\core\session; use sephp\core\lib\power; use sephp\core\error; use sephp\core\log; use sephp\core\req; use sephp\core\route; //代码开始执行时间 define('SE_START_TIME', microtime(true)); class sephp { /** * 当前对象 * @var null */ public static $_instance = null; /** * 当前rul地址 * @var null */ public static $_now_url = null; /** * 当前控制器名称 * @var string */ public static $_ct = 'index'; /** * 当前控制器方法名称 * @var string */ public static $_ac = 'index'; /** * 当前读取的配置 * @var array|mixed */ public static $_config = []; /** * 当前用户信息 * @var array|mixed */ public static $_user = []; /** * 当前用户uid * * @var array|mixed */ public static $_uid = 0; /** * 初始化框架 * start constructor. * @param array $_authority */ public function __construct($_authority = []) { //定义常量 $this->define(); //环境检测 $this->check_environment(); //自动注册类库 spl_autoload_register("sephp\autoloads::autoload", true, true); //初始化配置选项 config::get(); self::$_config['_authority'] = $_authority; self::$_now_url = $_SERVER['REQUEST_URI']; //注册一个会在php中止时执行的函数 register_shutdown_function(['sephp\core\error', 'shutdown_handler']); //自定义错误处理 set_error_handler(['sephp\core\error', 'error_handler'], E_ALL); //异常捕获 set_exception_handler(['sephp\core\error', 'exception_handler']); //设置一个结束执行函数,执行写入日志操作 func::set_shutdown_func('sephp\core\log', 'save'); //引入所有自定义函数 autoloads::register_function(); //初始化session session::start(); $this->_get_ap_ct_ac(); //页面静态缓存 empty(sephp::$_config['web']['static_page']) ? :$this->_static_page(); //p($_REQUEST,$_GET); //GET.POST.COOKIE 参数过滤 req::init(); //权限控制 \sephp\core\lib\power::instance(); //执行方法 $this->run(); } /** * 执行控制器文件代码 */ public function run() { $ctl_file = PATH_APP.'ctl/ctl_'.self::$_ct.'.php'; if (file_exists($ctl_file)) { require_once $ctl_file; } else { throw new \Exception("controler file[".$ctl_file."]is not exists!", 100); } $class_name = '\\'.APP_NAME.'\ctl\ctl_'.self::$_ct; if (class_exists($class_name, false)) { self::$_instance = new $class_name(); } else { throw new \Exception("class {$class_name}() has not exists!", 100); } if (method_exists(self::$_instance, self::$_ac) === true) { $acton_name = self::$_ac; self::$_instance->$acton_name(); } else { throw new \Exception("The class [ctl_".self::$_ct .'] has not found this method ['.self::$_ac."()]", 100); } } /** * 解析url地址 */ protected function _get_ap_ct_ac() { //路由解析 empty(self::$_config['route']['url_route_on']) ? : route::instance(); self::$_ct = empty($_GET['ct'])?'index':$_GET['ct']; self::$_ac = empty($_GET['ac'])?'index':$_GET['ac']; define('ACTION_NAME', self::$_ac); define('CONTROLLER_NAME', self::$_ct); } /** * 缓存静态页 */ protected function _static_page() { if (in_array(APP_NAME, sephp::$_config['web']['static_page'])) { $name = null; foreach ($_REQUEST as $k => $v) { $name .= $k.'-'.$v.'_'; } $html_file_name = PATH_RUNTIME.'cache/html/'.APP_NAME.'/'.rtrim($name, '_').'.html'; if (file_exists($html_file_name)) { $html = file_get_contents($html_file_name); exit($html); } } } /** * 检查框架执行环境 */ protected function check_environment() { if (!defined('APP_NAME') || !defined('PATH_APP')) { exit('APP_NAME or PATH_APP is not defind!'); } if (!defined('APP_DEBUG') || !APP_DEBUG) { //禁用错误报告 error_reporting(0); ini_set('display_errors', 0); } else { //可以抛出任何非注意的错误报告 E_ERROR | E_PARSE | E_CORE_ERROR | E_NOTICE error_reporting(E_ALL); //该指令开启如果有错误报告才能输出 ini_set('display_errors', 1); } require_once PATH_SEPHP . 'autoloads.php'; require_once PATH_SEPHP . 'function.php'; } /** * 定义常量 */ protected function define() { //网站URL地址 define('URL_ROOT', 'http://'.$_SERVER['HTTP_HOST']); //项目URL地址 define('URL_APP', 'http://'.$_SERVER['HTTP_HOST'].'/'.APP_NAME); define('TIME_SEPHP', time()); define('PATH_SEPHP', __DIR__ .'/'); //框架目录 define('PATH_ROOT', __DIR__ .'/../'); //网站根目录 define('PATH_LIB', __DIR__ .'/core/library/'); define('PATH_RUNTIME', PATH_ROOT.'runtime/'); define('PATH_UPLOAD', PATH_ROOT.'upload/'); define('PATH_VIEW', PATH_APP.'view/'); } } <file_sep><?php namespace admin\ctl; use sephp\sephp; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; class ctl_cache { public function clear() { view::display('cache.clear'); } }<file_sep><?php namespace car_aintenance_shop\ctl; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; use admin\model\mod_content; use admin\model\mod_admin; use admin\model\mod_admin_group; use common\model\pub_mod_goods; use common\model\pub_mod_goods_brand; use common\model\pub_mod_order_check_out; class ctl_check { /** * 核销app基础参数设置 * @Author GangGuoer * @DateTime 2019-10-27T16:35:12+0700 * @version [version] * @return [type] */ public function app() { $key = 'app_order_check_base_setting'; if(empty(req::$posts)) { view::assign('data',config::get($key, 'mysql')); //用户列表,选择核销的用户 $groups = mod_admin_group::getlist(); view::assign('grouplist', $groups); view::display(); exit; } $data = func::data_filter([ 'app_token' => ['type' => 'text', 'default' => ''], 'app_url' => ['type' => 'text', 'default' => ''], 'group_id' => ['type' => 'text', 'default' => ''], ], req::$posts); if(config::set($key,$data)) { show_msg::success('设置成功'); } show_msg::error('保存失败'); } /** * 核销记录 * @Author GangGuoer * @DateTime 2019-10-27T17:05:56+0700 * @version [version] * @return [type] */ public function log() { $list = pub_mod_order_check_out::getlist(); view::assign('list', $list); view::display(); } } <file_sep><?php namespace sephp\core\lib; use sephp\sephp; /** * http 操作类 访问,推送 * Class sys_curl */ class curl { /** * 远程下载文件 保存服务器 * @param $url 下载文件地址 * @param string $path 保存地址 * @return string */ public static function downloadImage($url, $save_file = '') { $save_file = empty($save_file) ? PATH_UPLOAD . 'down_file/' . pathinfo($url, PATHINFO_BASENAME) : $save_file; if(!file_exists(pathinfo($save_file, PATHINFO_DIRNAME)) && !mkdir(pathinfo($save_file, PATHINFO_DIRNAME), 0777, true)) { return false; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); $file = curl_exec($ch); curl_close($ch); $resource = fopen($save_file, 'a'); fwrite($resource, $file); fclose($resource); return $save_file; } /** * @param $doc_name 源文件名 * @param $out_name 输出的文件名 */ public static function down($doc_name, $out_name) { $sourceFile = $doc_name; //要下载的临时文件名 $outFile = $out_name; //下载保存到客户端的文件名 if (!is_file($sourceFile)) { die("<b>404 File not found!</b>"); } $len = filesize($sourceFile); //获取文件大小 $filename = basename($sourceFile); //获取文件名字 $outFile_extension = strtolower(substr(strrchr($sourceFile, "."), 1)); //获取文件扩展名 //var_dump($outFile_extension);exit();exit(); //根据扩展名 指出输出浏览器格式 switch ($outFile_extension) { case "PDF" : $ctype = "application/PDF"; break; case "zip" : $ctype = "application/zip"; break; case "doc" : $ctype = "application/doc"; break; case "mp3" : $ctype = "audio/mpeg"; break; case "mpg" : $ctype = "video/mpeg"; break; case "avi" : $ctype = "video/x-msvideo"; break; case "rar" : $ctype = "application/rar"; break; case "wps" : $ctype = "application/wps"; break; default : $ctype = "application/force-download"; } //Begin writing headers header("Cache-Control:"); header("Cache-Control: public"); //设置输出浏览器格式 header("Content-Type: $ctype"); header("Content-Disposition: attachment; filename=" . $outFile); header("Accept-Ranges: bytes"); $size = filesize($sourceFile); //如果有$_SERVER['HTTP_RANGE']参数 if (isset ($_SERVER['HTTP_RANGE'])) { /*Range头域   Range头域可以请求实体的一个或者多个子范围。 例如, 表示头500个字节:bytes=0-499 表示第二个500字节:bytes=500-999 表示最后500个字节:bytes=-500 表示500字节以后的范围:bytes=500-    第一个和最后一个字节:bytes=0-0,-1    同时指定几个范围:bytes=500-600,601-999    但是服务器可以忽略此请求头,如果无条件GET包含Range请求头,响应会以状态码206(PartialContent)返回而不是以200 (OK)。 */ // 断点后再次连接 $_SERVER['HTTP_RANGE'] 的值 bytes=4390912- list ($a, $range) = explode("=", $_SERVER['HTTP_RANGE']); //if yes, download missing part str_replace($range, "-", $range); //这句干什么的呢。。。。 $size2 = $size - 1; //文件总字节数 $new_length = $size2 - $range; //获取下次下载的长度 header("HTTP/1.1 206 Partial Content"); header("Content-Length: $new_length"); //输入总长 header("Content-Range: bytes $range$size2/$size"); //Content-Range: bytes 4908618-4988927/4988928 95%的时候 } else { //第一次连接 $size2 = $size - 1; header("Content-Range: bytes 0-$size2/$size"); //Content-Range: bytes 0-4988927/4988928 header("Content-Length: " . $size); //输出总长 } //打开文件 $fp = fopen("$sourceFile", "rb"); file_put_contents("/tmp/download.log","step1\n",FILE_APPEND); //设置指针位置 @fseek($fp, $range); //虚幻输出 while (!feof($fp)) { file_put_contents("/tmp/download.log","step2\n",FILE_APPEND); //设置文件最长执行时间 set_time_limit(0); print (fread($fp, 1024 * 8)); //输出文件 flush(); //输出缓冲 ob_flush(); } file_put_contents("/tmp/download.log","step3\n",FILE_APPEND); fclose($fp); exit (); } /** * 发起post请求 * @param $url * @param array $post_data * @param int $timeout * @return mixed */ public static function post($url,$post_data = [], $post_file = null,$timeout = 10) { $oCurl = curl_init(); if (stripos($url, "https://") !== FALSE) { curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1 } if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) { $is_curlFile = true; } else { $is_curlFile = false; if (defined('CURLOPT_SAFE_UPLOAD')) { curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false); } } if (is_string($post_data)) { $strPOST = $post_data; } elseif ($post_file) { if ($is_curlFile) { foreach ($param as $key => $val) { if (substr($val, 0, 1) == '@') { $param[$key] = new \CURLFile(realpath(substr($val, 1))); } } } $strPOST = $param; } else { $aPOST = array(); foreach ($post_data as $key => $val) { $aPOST[] = $key . "=" . urlencode($val); } $strPOST = join("&", $aPOST); } curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($oCurl, CURLOPT_POST, true); curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST); $sContent = curl_exec($oCurl); $aStatus = curl_getinfo($oCurl); curl_close($oCurl); if (intval($aStatus["http_code"]) == 200) { return $sContent; } else { return false; } } /** * 发起get请求 * @param $url * @param int $timeout * @return mixed */ public static function get($url,$timeout = 10) { //初始化 $oCurl = curl_init(); if (stripos($url, "https://") !== FALSE) { curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1 } curl_setopt($oCurl, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($oCurl, CURLOPT_URL, $url); curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($oCurl); $aStatus = curl_getinfo($oCurl); if (intval($aStatus["http_code"]) == 200) { } else { } //关闭URL请求 curl_close($oCurl); //显示获得的数据 return ($data); } /** * curl 函数 * @Author han * @param [type] $data 请求参数 * data支持下面参数(只有url是必须的,其他都是可选的) * url url地址 * post 有的话就是post,没有就是get post的数据,可以是数组或者http_build_query后的值 * timeout 超时时间 * ip 伪造ip * referer 来源 * cookie 传递cookie * cookie_file cookie路径 * save_cookie cookie保存路径 * proxy 代理信息 * header http请求头 * debug 是否开启调试 * $tmp = pub_func::http_request(['url' => 'http://www.taobao.com']); * $tmp['body']就是返回的内容 * @param boolean $multi 是否并发模式 * $tmp = pub_func::http_request([ * ['url' => 'http://www.taobao.com'], * ['url' => 'http://www.baidu.com', 'post' => ['a' => 1, 'b' => 2] ], * ], true); * $tmp['body']就是返回的内容 * @return array curl执行结果 */ static public function http_request($data, $multi = false) { if(!isset($data['url']) && ($tmp = current($data)) && isset($tmp['url'])) { static $curl_multi; $curl_multi === null && $curl_multi = function_exists('curl_multi_init') && strpos(ini_get('disable_functions'), 'curl_multi_init') === false; if($curl_multi && $multi) { //curl并发模式 $mch = curl_multi_init(); $ch = $ret = $error = array(); foreach($data as $k => $v) { $v['return_curl'] = true; $ch[$k] = self::http_request($v); $ret[$k] = array('head' => '', 'body' => null); curl_multi_add_handle($mch, $ch[$k]); } $active = null; //execute the handles do { $mrc = curl_multi_exec($mch, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active && $mrc == CURLM_OK) { while (curl_multi_exec($mch, $active) === CURLM_CALL_MULTI_PERFORM); if (curl_multi_select($mch) != -1) { do { $mrc = curl_multi_exec($mch, $active); $info = curl_multi_info_read($mch); if($info !== false && $info['result']) { foreach($ch as $k => $v) { if($v === $info['handle']) { $tmp = curl_getinfo($info['handle']); $error[$k] = array($info['result'], curl_error($info['handle']), $tmp['url']); break; } } } } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } /*do{ $mrc = curl_multi_exec($mch, $active); curl_multi_select($mch); $info = curl_multi_info_read($mch); if($info !== false && $info['result']){ foreach($ch as $k => $v){ if($v === $info['handle']){ $tmp = curl_getinfo($info['handle']); $error[$k] = array($info['result'], curl_error($info['handle']), $tmp['url']); break; } } } }while($active > 0);*/ $error_log = ''; foreach($ch as $k => $v) { if(isset($error[$k])) { $ret[$k]['body'] = null; $ret[$k]['info']['status'] = 0; $ret[$k]['info']['errno'] = $error[$k][0]; $error_log .= "{$error[$k][2]}|{$error[$k][0]}|{$error[$k][1]}\n"; continue; } $ret[$k]['body'] = curl_multi_getcontent($v); $info = curl_getinfo($v); $ret[$k]['info']['status'] = $info['http_code']; curl_multi_remove_handle($mch, $ch[$k]); } if(!empty($error)) { log::error($error_log); } curl_multi_close($mch); return $ret; } else { $ret = array(); foreach($data as $k => $v) { $ret[$k] = self::http_request($v); } return $ret; } } $data['post'] = isset($data['post']) ? (is_array($data['post']) ? http_build_query($data['post']) : $data['post']) : ''; $data['cookie'] = isset($data['cookie']) ? $data['cookie'] : ''; $data['ip'] = isset($data['ip']) ? $data['ip'] : ''; $data['timeout'] = isset($data['timeout']) ? $data['timeout'] : 15; $data['block'] = isset($data['block']) ? $data['block'] : true; $data['referer'] = isset($data['referer']) ? $data['referer'] : ''; $data['connection'] = isset($data['connection']) ? $data['connection'] : 'close'; $data['header'] = isset($data['header']) ? (array)$data['header'] : array(); if(function_exists('curl_init')) { $ch = curl_init($data['url']); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_USERAGENT, !empty($data['UA']) ? $data['UA'] : 'Mozilla/5.0'); if( !empty($data['ip']) ) { $x_forwarded_for = $data['ip']; $client = empty($data['client']) ? $x_forwarded_for : $data['client']; curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-FORWARDED-FOR:{$x_forwarded_for}", "CLIENT-IP:{$client}")); } if(!empty($data['debug'])) { curl_setopt($ch, CURLOPT_VERBOSE, true); $fp = fopen($data['debug'], 'a'); curl_setopt($ch, CURLOPT_STDERR, $fp); //fclose($fp); } //curl_setopt($ch, CURLOPT_ENCODING, 'none'); curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($data['header'], array( 'Connection: '. $data['connection'] ))); if(stripos($data['url'], 'https://') === 0) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false); //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); } if(!empty($data['referer'])) curl_setopt($ch, CURLOPT_REFERER, $data['referer']); if(!empty($data['cookie'])) curl_setopt($ch, CURLOPT_COOKIE, $data['cookie']); if(!empty($data['cookie_file'])) curl_setopt($ch, CURLOPT_COOKIEFILE, $data['cookie_file']); if(!empty($data['save_cookie'])) curl_setopt($ch, CURLOPT_COOKIEJAR, $data['save_cookie']); if(!empty($data['proxy'])) curl_setopt($ch, CURLOPT_PROXY, $data['proxy']); if(!empty($data['post'])) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $data['post']); } curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $data['timeout']); curl_setopt($ch, CURLOPT_TIMEOUT, $data['timeout']); if(!empty($data['option'])) { curl_setopt_array($ch, $data['option']); } if(!empty($data['return_curl'])) return $ch; $ret = curl_exec($ch); $errno = curl_errno($ch);//var_dump($errno); $header = curl_getinfo($ch); if( !empty($data['return_head']) ) { return $header; } if($errno) { $error = curl_error($ch); curl_close($ch); $s = "$data[url]|$errno|$error"; log::error($s); return array('head' => $header, 'body' => null, 'info' => array( 'errno' => $errno, 'error' => $error )); } //$tmp = explode("\r\n\r\n", $ret, 2); //print_r($ret); //unset($ret); $info = curl_getinfo($ch); curl_close($ch); return array('head' => $header, 'body' => $ret, 'info' => array( 'status' => $info['http_code'] )); } } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 商品model 品牌lassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_goods_brand extends pub_mod_model { public static $_table = '#PB#_goods_brand', $_pk = 'brand_id', $_fields = [ 'brand_id' => ['type' => 'int', 'required' => true, 'comment' => '品牌ID'], //订单号 'brand_name' => ['type' => 'text', 'required' => true, 'comment' => '品牌名称'], //服务id 'brand_url' => ['type' => 'text', 'default' => null, 'comment' => '品牌URL地址'], //申请人 'brand_desc' => ['type' => 'text', 'default' => null, 'comment' => '品牌描述'], //申请金额 'brand_logo' => ['type' => 'text', 'default' => null, 'comment' => '品牌LOG'], //申请金额 'brand_keywords' => ['type' => 'text', 'default' => null, 'comment' => '品牌关键字'], //申请金额 'brand_setting' => ['type' => 'text', 'default' => null, 'comment' => '品牌设置'], //申请金额 'disabled' => ['type' => 'text', 'default' => 1, 'comment' => '开关'], //申请金额 'ordernum' => ['type' => 'int', 'default' => null, 'comment' => '排序'], //申请金额 'adduser' => ['type' => 'text', 'required' => false, 'default' => '', 'comment' => '添加人'], //申请金额 'addtime' => ['type' => 'int', 'required' => false, 'default' => '', 'comment' => '添加时间'], //申请金额 'upuser' => ['type' => 'text', 'default' => 0, 'comment' => '更新人'], //申请金额 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], //申请金额 ], $disabled = [ '1' => '启用', '2' => '禁用', ]; public static function _init() { } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 商品model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_goods_brand extends pub_mod_model { public static $table = '#PB#_goods', $pk = 'goods_id', $cache_use = false, $cache_time = 3600, $error_msg = null, $transaction = true, $fields = [ 'goods_id' => ['type' => 'text', 'required' => true, 'comment' => '商品ID'], //订单号 'goods_sn' => ['type' => 'int', 'required' => true, 'comment' => '商品编号'], //服务id 'name' => ['type' => 'text', 'default' => true, 'comment' => '商品名称'], //申请人 'price' => ['type' => 'text', 'default' => 0, 'comment' => '销售价格'], //申请金额 'price' => ['type' => 'text', 'default' => 0, 'comment' => '销售价格'], //申请金额 'price' => ['type' => 'text', 'default' => 0, 'comment' => '销售价格'], //申请金额 'price' => ['type' => 'text', 'default' => 0, 'comment' => '销售价格'], //申请金额 'price' => ['type' => 'text', 'default' => 0, 'comment' => '销售价格'], //申请金额 ]; const STATUS_READY = 1; const STATUS_CANCEL = 2; const STATUS_PAY_WAIT = 3; const STATUS_PAY_FAIL = 4; const STATUS_PAY_SUCCESS = 5; const STATUS_REFUND_WAIT = 6; const STATUS_REFUND_FAIL = 7; const STATUS_REFUND_SUCCESS = 8; const STATUS_TIME_OUT = 9; const STATUS_EXCEPTION = 20; public static $status = [ '1' => '准备中', '2' => '已取消', '3' => '支付中', '4' => '支付失败', '5' => '支付成功', '6' => '退款中', '7' => '退款失败', '8' => '退款成功', '9' => '已超时', '20' => '订单异常',//需要客服介入 ]; public static $source = [ '1' => '客服下单', '2' => '自助下单', '3' => 'app自助下单', ]; /** * @var int 订单过期时间 */ public static $status_expire_time = 300; /** * 订单 对应的 queue_id 缓存 */ const ORDER_QUEUE_CACHE = 'order_queue_cache_v1_'; } <file_sep><?php namespace sephp\core; use sephp\sephp; use sephp\func; class show_msg { /** * 重定向 * @param string $url */ public static function redirect($url = '') { $url = empty($url) ? URL_APP : $url; header('Location: ' . $url); } /** * ajax 放回格式。 * @param $msg 返回提示消息 * @param int $code 返回错误状态号 200,400 * @param string $data */ public static function ajax($msg, $code = 200, $data = [], $sign = '') { header('Content-Type: application/json; charset=utf-8'); // php7.1 json_encode float精度会溢出 if (version_compare(phpversion(), '7.1', '>=')) { ini_set( 'serialize_precision', -1 ); } $data = [ 'code' => (int) $code, 'msg' => (string) $msg, 'data' => empty($data) ? [] : $data, 'sign' => $sign, ]; exit(json_encode($data, JSON_UNESCAPED_UNICODE)); } public static function flush_msg($msg, $err=false) { $err = $err ? "<span class='err'>ERROR:</span>" : '' ; echo "<p class='dbDebug'>".$err . $msg."</p>"; flush(); } public static function success($message = '', $url = '', $time = 0, $title = '') { $message = empty($message)? '操作成功' : $message; self::get_return_html($title, $message, $url, 'success', $time); } public static function error($message = '', $url = '', $time = 0, $title = '') { $message = empty($message) ? '操作失败' : $message; self::get_return_html($title, $message, $url, 'error', $time); } public static function get_return_html($title, $message, $gourl = '', $type, $time = 0) { $title = empty($title) ? '系统提示' : $title; $time = empty($time) ? 3000 : $time * 1000; if(func::get_value(sephp::$_config['_authority'], 'login_type', '') == 'token') { self::ajax($message, ('error' == $type ? -1 : 0)); } switch ($gourl) { case '-1': $gourl = 'javascript:window.history.go(-1)'; $junp_settimeout = 'window.history.go(-1);'; break; case '': $junp_settimeout = 'window.history.go(-1);'; $gourl = 'javascript:window.history.go(-1)'; break; default: //$url = explode('/',$gourl); //$gourl = '?ct='; $junp_settimeout = "location.href= '{$gourl}';"; } view::assign('junp_settimeout',$junp_settimeout); view::assign('type',$type); view::assign('title',$title); view::assign('message',$message); view::assign('jump_url',$gourl); view::assign('jump_time',$time); echo view::fetch('system/jump'); exit(); } } <file_sep><?php namespace sephp\core\lib; use sephp\sephp; use sephp\func; //接口类型:互亿无线触发短信接口,支持发送验证码短信、订单通知短信等。 // 账户注册:请通过该地址开通账户http://sms.ihuyi.com/register.html // 注意事项: //(1)调试期间,请使用用系统默认的短信内容:您的验证码是:【变量】。请不要把验证码泄露给其他人。; //(2)请使用APIID(查看APIID请登录用户中心->验证码短信->产品总览->APIID)及 APIkey来调用接口 //(3)该代码仅供接入互亿无线短信接口参考使用,客户可根据实际需要自行编写; class sms { public static $instance = null; public static function instance($config = []) { if(empty(self::$instance)) { self::$instance = new self($config); } return self::$instance; } protected $config = [ 'app_id' => 'cf_uli9', 'app_key' => '<KEY>', 'sms_send_time' => 60, 'sms_send_num' => 5, 'sms_send_black_time' => 600, 'url' => 'http://106.ihuyi.cn/webservice/sms.php?method=Submit', 'is_open_send_limit' => 1, ]; public function __construct($config = null) { if(!empty($config)) { $this->config = array_merge($this->config, $config); } } //请求数据到短信接口,检查环境是否 开启 curl init。 private function post($curlPost,$url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HEADER, false); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost); $return_str = curl_exec($curl); curl_close($curl); return $return_str; } //防止恶意攻击 private function sms_safe() { if($this->config['is_open_send_limit'] != 1){ return; } if (!empty(session::get('sms_send_black')) && session::get('sms_send_black') + $this->config['sms_send_black_time'] > time()) { new Exception('操作频繁,请'.ceil((session::get('sms_send_black') + $this->config['sms_send_black_time'] - time())/60).'分钟后重试'); } if (empty($_SESSION['sms_send_num'])) { $_SESSION['sms_send_num'] = 1; } if(!empty($_SESSION['sms_send_time']) && $_SESSION['sms_send_time'] + $this->config['sms_send_time'] > time()){ new Exception('操作频繁,请'.($_SESSION['sms_send_time'] + $this->config['sms_send_time'] - time()).'秒后重试'); } if ($_SESSION['sms_send_num'] > $this->config['sms_send_num']) { session::set('sms_send_black', SE_START_TIME); unset($_SESSION['sms_send_num']); unset($_SESSION['sms_send_time']); new Exception('发送次数超过限制'); } } /** * 发送短信验证码 * @Author GangKui * @DateTime 2019-10-24 * @param [type] $mobile [description] * @param [type] $send_code [description] * @return [type] [description] */ public function send_sms($mobile,$send_code) { $send_code = md5($send_code); //生成的随机数 $mobile_code = func::random('alnum', 6); if(empty($mobile)) { throw new \Exception('手机号码不能为空'); } $preg = "/^1[3456789]\d{9}$/"; if (!preg_match($preg, $mobile)) { throw new \Exception('手机号码不正确'); } //防止恶意攻击 session 部分代码最好通过redis代替session实现 $this->sms_safe(); $content = "您的验证码是:".$mobile_code."。请不要把验证码泄露给其他人。" ; $post_data = "account=".$this->config['appid'] ."&password=".$this->config['appkey'] . "&mobile=".$mobile."&content=".rawurlencode($content); $gets = func::xml_to_array($this->post($post_data, $this->config['url'])); if($gets['SubmitResult']['code']==2){ $_SESSION['mobile'] = $mobile; $_SESSION['mobile_code'] = $mobile_code; $_SESSION['sms_send_time'] = time(); $_SESSION['sms_send_num'] += 1; } echo $gets['SubmitResult']['msg']; $data = date("Y-m-d H:i:s") . ' 返回码 : ' . $gets['SubmitResult']['code'] . ', 返回描述 : ' . $gets['SubmitResult']['msg'] . ' . 发送号码 : '.$mobile.' , 短信详情 : '.$content . PHP_EOL; log::info($data); } } <file_sep><?php namespace admin\ctl; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; class ctl_content { private $_cont_table = '#PB#_content'; private $_cont_pk = 'id'; private $_cate_table = '#PB#_content_cate'; private $_cate_pk = 'cate_id'; public function __construct() { view::assign('back_url', req::cookie('content_back_url', 'javascript:history.go(-1);')); } //文章列表 public function content_index() { $where[] = ['delete_user', '=', '0']; $keywords = req::item('keywords', ''); view::assign('keywords', $keywords); if (!empty($keywords)) { $where[] = [$this->_cont_table.'.title', 'like', "%{$keywords}%"]; } $is_show = req::item('is_show', '1'); view::assign('is_show', $is_show); if (!empty($is_show)) { $where[] = [$this->_cont_table.'.is_show', '=', $is_show]; } $count = db::select("count({$this->_cont_pk}) as count") ->from($this->_cont_table) ->where($where) ->as_row() ->execute(); $pages = pages::instance($count['count'], req::item('page_num', 10)); $fields = [ $this->_cont_table.'.'.$this->_cont_pk, $this->_cont_table.'.cate_id', $this->_cont_table.'.create_time', 'title', $this->_cate_table.'.name', $this->_cont_table.'.is_show', 'is_top', 'author', 'name as cate_name' ]; $list = db::select($fields) ->from($this->_cont_table) ->join($this->_cate_table, 'left') ->on($this->_cate_table.'.'.$this->_cate_pk, '=', $this->_cont_table.'.cate_id') ->where($where) ->offset($pages['offset']) ->limit($pages['limit']) ->order_by($this->_cont_pk, 'DESC') ->execute(); setcookie('content_back_url', func::get_cururl()); view::assign('list', $list); view::assign('pages', $pages['show']); view::assign('add_url', '?ct=content&ac=content_add'); view::assign('edit_url', '?ct=content&ac=content_edit'); view::display(); } //添加文章 public function content_add() { view::assign('pk', $this->_cont_pk); if (empty(req::$posts)) { view::assign('cates', $this->get_cates()); view::display(); exit; } $data = req::$posts; if (empty($data['title']) || empty($data['cate_id'])) { show_msg::error('标题或分类不能为空'); } $data['create_time'] = time(); $data['create_user'] = power::instance()->_uid; list($id, $rows) = db::insert($this->_cont_table) ->set($data) ->execute(); if ($id) { show_msg::success('', '?ct=content&ac=content_index'); } show_msg::error(); } public function content_edit() { $id = req::item($this->_cont_pk, 0); if (empty($id)) { show_msg::error('文章不存在'); } view::assign('pk', $this->_cont_pk); if (empty(req::$posts)) { view::assign('cates', $this->get_cates()); $info = db::select() ->from($this->_cont_table) ->where($this->_cont_pk, $id) ->as_row() ->execute(); view::assign('data', $info); view::display('content.content_add'); exit; } $data = req::$posts; if (empty($data['title']) || empty($data[$this->_cont_pk])) { show_msg::error('标题不能为空'); } $data['create_time'] = time(); $data['create_user'] = power::instance()->_uid; if (db::update($this->_cont_table) ->set($data) ->where($this->_cont_pk, $data[$this->_cont_pk]) ->execute() === false) { log::info(db::get_last_sql()); show_msg::error(); } show_msg::success('', func::get_cururl().'&id='.$data[$this->_cont_pk]); } //分类列表 public function cate_index() { setcookie('content_back_url', func::get_cururl()); view::assign('list', $this->get_cates()); view::assign('add_url', '?ct=content&ac=cate_add'); view::assign('edit_url', '?ct=content&ac=cate_edit'); view::assign('save_url', ''); view::display(); } //编辑分类 public function cate_edit() { if (!empty(req::$posts)) { $data = req::$posts; if ($data[$this->_cate_pk] > 0) { if (db::update($this->_cate_table) ->set($data) ->where($this->_cate_pk, $data[$this->_cate_pk]) ->execute() === false) { show_msg::error(); } show_msg::success(); } } $cate_id = req::item('cate_id', 0); if (empty($cate_id)) { show_msg::error('分类不存在'); } $info = db::select() ->from($this->_cate_table) ->where($this->_cate_pk, $cate_id) ->as_row() ->execute(); view::assign('data', $info); view::assign('cates', $this->get_cates()); view::assign('pk', $this->_cate_pk); view::display('content.cate_add'); } //添加分类 public function cate_add() { if (empty(req::$posts)) { view::assign('cates', $this->get_cates()); view::assign('pk', $this->_cate_pk); view::display(); exit(); } $data = req::$posts; if ($data['parent_id'] > 0) { $parent_info = db::select()->from($this->_cate_table)->where($this->_cate_pk, $data['parent_id'])->as_row()->execute(); $data['path'] = $parent_info['path'].'-'.$parent_info[$this->_cate_pk]; $data['level'] = $parent_info['level']+1; db::query("update {$this->_cate_table} set child_num = child_num + 1")->execute(); } else { $data['level'] = 1; } $data['create_time'] = time(); $data['create_user'] = power::instance()->_uid; //p($data); exit; list($res, $id) = db::insert($this->_cate_table)->set($data)->execute(); if ($res) { show_msg::success('', func::get_cururl()); } show_msg::error(); } public function get_children_cate($parent_id = 0) { if (empty($parent_id)) { $data = db::select() ->from($this->_cate_table) ->where('status', '1') ->and_where('level', 1) ->execute(); if (empty($data)) { return $data; } else { } } } protected function get_cates() { $sql = "select cate_id,parent_id,name,`level`,child_num,is_show,status,sort_num,concat(path,'-',cate_id) as bpath from se_content_cate order by bpath"; return db::query($sql)->execute(); } } <file_sep><?php namespace admin\ctl; use sephp\sephp; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; class ctl_wechat { protected $_url = '?ct=system&ac='; protected $_config_table = '#PB#_config'; public function __construct() { $back_url = req::item('back_url','javascript:history.go(-1);'); view::assign('back_url',$back_url); } /** * 菜单管理 * @Author GangKui * @DateTime 2019-10-11 * @return [type] [description] */ public function menu_index() { //view::assign('list',$list); view::display(); } } <file_sep><?php namespace admin\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; use common\model\pub_mod_model; /** * 商品model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class mod_admin_group extends pub_mod_model { public static $_table = '#PB#_admin_group', $_pk = 'group_id', $_fields = [ 'group_id' => ['type' => 'int','required' => true, 'comment' => '管理员ID'], 'name' => ['type' => 'text', 'required' => true, 'comment' => '组ID'], 'remark' => ['type' => 'text', 'default' => 0, 'comment' => '登陆名'], 'powerlist' => ['type' => 'text', 'default' => null, 'comment' => '登陆密码'], 'status' => ['type' => 'text', 'default' => 0, 'comment' => '性别'], 'create_time' => ['type' => 'int', 'required' => false, 'default' => 0, 'comment' => '添加时间'], 'create_user' => ['type' => 'text', 'default' => 0, 'comment' => '更新时间'], 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '删除时间'], 'upuser' => ['type' => 'text', 'default' => 0, 'comment' => '删除时间'], 'deltime' => ['type' => 'int', 'default' => 0, 'comment' => '删除时间'], 'deluser' => ['type' => 'text', 'default' => 0, 'comment' => '删除时间'], ], $status = [ '1' => '正常', '2' => '禁用', ]; public static function getdatabyid($group_id) { $data = self::getdump([ 'where' => [self::$_pk => $group_id] ]); return self::data_format($data); } /** * 数据格式化 * @Author GangKui * @DateTime 2019-10-23 * @param [type] $data [description] * @return [type] [description] */ public static function data_format($data = []) { if(empty($data)) return $data; if(isset($data['powerlist'])) { switch ($data['powerlist']) { case '*': $data['powerlist'] = '*'; break; case '': $data['powerlist'] = []; break; case null: $data['powerlist'] = []; break; default: $data['powerlist'] = json_decode($power['powerlist'], true); break; } } return $data; } } <file_sep><?php namespace sephp; require_once __DIR__ . '/sephp/sephp.php'; require_once __DIR__ . '/sephp/autoloads.php'; use sephp\sephp; use sephp\autoloads; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; var_dump(\sephp\func\func::make_uniqid()); exit(); class abc { /** * 生成优惠券数组 * @param $num * @return array */ public function generatorGoodsQuan($num) { $array = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); for ($i = 0; $i < $num; $i++) { $randChar = array_rand($array, 1); $quan[] = uniqid($array[$randChar]); } return $quan; } /** * 优惠券数组排重 * * @param $quan * @param $num * @return mixed */ private function checkUniQuan($quan, $num) { $quan = array_unique($quan); if (count($quan) < $num) { $quan = array_merge($quan, $this->generatorGoodsQuan($num - count($quan))); return $this->checkUniQuan($quan, $num); } else { return $quan; } } /** * 数据库排重 * @param $shopId * @param $goodsId * @param $quan * @param $num * @return array|mixed */ private function checkDatabaseQuan($shopId, $goodsId, $quan, $num) { $data=[]; if(empty($data)) return $quan; else{ $quan=array_diff($quan,$data); $quan = array_merge($quan, $this->generatorGoodsQuan($num - count($quan))); $quan=$this->checkUniQuan($quan,$num); return $this->checkDatabaseQuan($shopId, $goodsId, $quan, $num); } } /** * 集合方法 生成针对某个店铺,某个商品的一定数量的优惠券 * @param $shopId * @param $goodsId * @param $num * @return array|mixed */ public function getQuanSn($shopId, $goodsId, $num) { $quan = $this->generatorGoodsQuan($num); $quan = $this->checkUniQuan($quan, $num); return $this->checkDatabaseQuan($shopId, $goodsId, $quan, $num); } public function getUuid() { mt_srand(microtime(true)*10000);//optional for php 4.2.0 and up. $charid = strtoupper(md5(uniqid(mt_rand(), true))); $hyphen = chr(45);// "-" $uuid = substr($charid,mt_rand(0,16),16); $uuid = substr($uuid, 0, 4).$hyphen .substr($uuid, 4, 4).$hyphen .substr($uuid,8, 4).$hyphen .substr($uuid,12, 4); return $uuid; } } $acb = new abc(); //var_dump($acb->getQuanSn(100,100,100000)); for($i=0;$i<10;$i++) { var_dump(microtime(true)*10000,mt_rand(),$acb->getUuid()); } <file_sep><?php namespace sephp\core\lib; use sephp\sephp; class redis { public static $_instance = null; public static $_config = null; public function __construct($options = []) { self::$_config = sephp::$_config['sysRedis']; if (!extension_loaded('sysRedis')) { throw new \Exception('not support: redis'); } if (!empty($options)) { self::$_config = array_merge($options, self::$_config); } self::$_instance = new sysRedis; if (self::$_config['persistent']) { self::$_instance->pconnect(self::$_config['host'], self::$_config['port'], self::$_config['timeout'], 'persistent_id_' . self::$_config['select']); } else { self::$_instance->connect(self::$_config['host'], self::$_config['port'], self::$_config['timeout']); } if ('' != self::$_config['password']) { self::$_instance->auth(self::$_config['password']); } if (0 != self::$_config['select']) { self::$_instance->select(self::$_config['select']); } } public static function instance() { if(empty(self::$_instance)) { self::$_instance = new self(); } return self::$_instance; } /** * 判断缓存 * @access public * @param string $name 缓存变量名 * @return bool */ public function has($name) { return self::$_instance->get($this->getCacheKey($name)) ? true : false; } /** * 读取缓存 * @access public * @param string $name 缓存变量名 * @param mixed $default 默认值 * @return mixed */ public function get($name, $default = false) { $value = self::$_instance->get($this->getCacheKey($name)); if (is_null($value) || false === $value) { return $default; } try { $result = (0 === strpos($value, '_serialize:'))? unserialize(substr($value, 16)) : $value; } catch (\Exception $e) { $result = $default; } return $result; } /** * 写入缓存 * @access public * @param string $name 缓存变量名 * @param mixed $value 存储数据 * @param integer|\DateTime $expire 有效时间(秒) * @return boolean */ public function set($name, $value, $expire = null) { if (is_null($expire)) { $expire = $this->options['expire']; } if ($expire instanceof \DateTime) { $expire = $expire->getTimestamp() - time(); } if ($this->tag && !$this->has($name)) { $first = true; } $key = $this->getCacheKey($name); $value = is_scalar($value) ? $value : '_serialize:' . serialize($value); if ($expire) { $result = self::$_instance->setex($key, $expire, $value); } else { $result = self::$_instance->set($key, $value); } isset($first) && $this->setTagItem($key); return $result; } /** * 自增缓存(针对数值缓存) * @access public * @param string $name 缓存变量名 * @param int $step 步长 * @return false|int */ public function inc($name, $step = 1) { $key = $this->getCacheKey($name); return self::$_instance->incrby($key, $step); } /** * 自减缓存(针对数值缓存) * @access public * @param string $name 缓存变量名 * @param int $step 步长 * @return false|int */ public function dec($name, $step = 1) { $key = $this->getCacheKey($name); return self::$_instance->decrby($key, $step); } /** * 删除缓存 * @access public * @param string $name 缓存变量名 * @return boolean */ public function rm($name) { return self::$_instance->delete($this->getCacheKey($name)); } /** * 清除缓存 * @access public * @param string $tag 标签名 * @return boolean */ public function clear($tag = null) { if ($tag) { // 指定标签清除 $keys = $this->getTagItem($tag); foreach ($keys as $key) { self::$_instance->delete($key); } $this->rm('tag_' . md5($tag)); return true; } return self::$_instance->flushDB(); } }<file_sep><?php namespace admin\ctl; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; use admin\model\mod_content; use common\model\pub_mod_goods; use common\model\pub_mod_goods_brand; /** * Class ctl_index */ class ctl_goods { /** * 商品列表 * @Author GangKui * @DateTime 2019-10-22 * @return [type] [description] */ public function index() { //var_dump(func::make_uniqid(true)); //var_dump(\sephp\core\lib\snowflake::instance(3)->id()); //exit(); $list = pub_mod_goods::getlist([ 'limit' => req::item('page_num', 20), 'total' => true, ]); view::assign('add_url', '?ct=goods&ac=add'); view::assign('edit_url', '?ct=goods&ac=edit&goods_id='); view::assign('keywords', req::item('keywords', '')); view::assign('list', $list['data']); view::assign('pages', $list['pages']); view::display(); } /** * 添加商品 * @Author GangKui * @DateTime 2019-10-22 * @param integer $goods_id [description] */ public function add($goods_id = 0) { $data = []; if(!empty(req::$posts)) { $this->save(); exit(); } if(0 < $goods_id) { $data = pub_mod_goods::getdatabyid($goods_id); } view::assign('data', $data); view::assign('back_url', '?ct=goods&ac=index'); view::display(); } /** * 编辑商品 * @Author GangKui * @DateTime 2019-10-22 * @return [type] [description] */ public function edit() { $this->add(req::item('goods_id', 0)); } /** * 商品保存 * @Author GangKui * @DateTime 2019-10-22 * @return [type] [description] */ public function save() { $filter_config = pub_mod_goods::$_fields; if(empty(req::$posts['goods_sn'])) { req::$posts['goods_sn'] = pub_mod_goods::create_sn(); } $posts = func::data_filter($filter_config, req::$posts); if(!is_array($posts)) { show_msg::error("参数错误:{$posts}"); } $posts['image_default_id'] = empty($posts['image_default_id']) ? null : json_encode($posts['image_default_id'], JSON_UNESCAPED_UNICODE); $posts['adduser'] = sephp::$_uid; $posts['addtime'] = TIME_SEPHP; $dups = [ 'uptime' => TIME_SEPHP, 'upuser' => sephp::$_uid, ]; foreach(pub_mod_goods::$_fields as $f => $conf) { //跟新不能修改状态和新增时间 if(in_array($f, ['addtime','adduser', 'goods_id', 'goods_sn'])) { continue; } $dups[$f] = " VALUES(`{$f}`) "; } if(false === pub_mod_goods::insert($posts, ['dups' => $dups])) { show_msg::error('保存失败'); } show_msg::error('保存成功', '?ct=goods&ac=index'); } /** * 品牌列表 * @Author GangKui * @DateTime 2019-10-12 * @return [type] [description] */ public function brand_index() { $list = pub_mod_goods_brand::getlist([ 'limit' => req::item('page_num', 1), 'total' => true, ]); view::assign('add_url', '?ct=goods&ac=brand_add'); view::assign('edit_url', '?ct=goods&ac=brand_edit&brand_id='); view::assign('keywords', req::item('keywords', '')); view::assign('list', $list['data']); view::assign('pages', $list['pages']); view::display(); } /** * 添加品牌 * @Author GangKui * @DateTime 2019-10-12 * @return [type] [description] */ public function brand_add($brand_id = 0) { $data = []; if(!empty(req::$posts)) { $this->brand_save(); exit(); } if(0 < $brand_id) { $data = pub_mod_goods_brand::getdump([ 'where' => [ pub_mod_goods_brand::$_pk => $brand_id, ] ]); } view::assign('data', $data); view::assign('back_url', '?ct=goods&ac=brand_index'); view::display(); } /** * 品牌编辑 * @Author GangKui * @DateTime 2019-10-12 * @return [type] [description] */ public function brand_edit() { $this->brand_add(req::item('brand_id', 0)); } /** * 品牌数据保存 * @Author GangKui * @DateTime 2019-10-12 * @return [type] [description] */ private function brand_save() { $filter_config = pub_mod_goods_brand::$_fields; $posts = func::data_filter($filter_config, req::$posts); if(!is_array($posts)) { show_msg::error("参数错误:{$post}"); } $posts['brand_logo'] = func::get_value($posts, 'brand_logo/0', ''); $posts['adduser'] = sephp::$_uid; $posts['addtime'] = TIME_SEPHP; $dups = [ 'uptime' => TIME_SEPHP, 'upuser' => sephp::$_uid, ]; foreach(pub_mod_goods_brand::$_fields as $f => $conf) { //跟新不能修改状态和新增时间 if(in_array($f, ['addtime','adduser'])) { continue; } $dups[$f] = " VALUES(`{$f}`) "; } if(false === pub_mod_goods_brand::insert($posts, ['dups' => $dups])) { show_msg::error('保存失败'); } show_msg::error('保存成功', '?ct=goods&ac=brand_index'); } } <file_sep><?php namespace api_check\ctl; use sephp\sephp; use sephp\func; use sephp\core\config; use sephp\core\req; use sephp\core\log; use sephp\core\db; use sephp\core\lib\power; use common\serv\pub_serv_orders; use common\model\pub_mod_order; use common\model\pub_mod_order_check; class ctl_index extends ctl_base { public function index() { echo pub_mod_order::create_qr_img('88a4238a0b9238203cc509a6f75849b3'); exit(); $qrcode = '88a4238a0b9238203cc509a6f75849b3'; $jiami = pub_mod_order::entcry_qrcode($qrcode); var_dump( $qrcode, $jiami ); var_dump(pub_mod_order::decry_qrcode($jiami)); echo phpinfo(); } /** * 扫码核销 * @Author GangKui * @DateTime 2019-11-11 * @return [type] [description] */ public function order_check() { $scan_str = req::item('scan_str', ''); if(empty($scan_str)) { $this->error('参数错误'); } if(0 > $result = pub_serv_orders::check_order([ 'qrcode_str' => $scan_str, 'type' => 'app', ])) { $this->error(pub_serv_orders::$_error_msg, $result); } $this->success('验票成功'); } /** * 核销列表 * @Author GangKui * @DateTime 2019-11-11 * @return [type] [description] */ public function check_list() { $data_filter = func::data_filter([ 'page' => ['type' => 'int', 'default' => 1], 'page_size' => ['type' => 'int', 'default' => 20], ], req::$forms); $data_filter['uid'] = sephp::$_uid; $data_filter['total'] = true; $list = pub_mod_order_check::getlist_by_where($data_filter); $this->success('请求成功', '', $list); } /** * 登陆 * @Author GangKui * @DateTime 2019-11-11 * @return [type] [description] */ public function login() { try{ $data_filter = func::data_filter([ 'username' => ['type' => 'text', 'require' => true], 'password' => ['type' => 'text', 'require' => true], ], req::$forms); if(!is_array($data_filter)) { $this->error('参数错误'); } if(false === power::instance()->login_check($data_filter, $info)) { $this->error('用户名或密码错误'); } $this->member_id = power::instance()->_uid; //必须是64位的 $this->token = power::make_token($this->member_id); if(false === power::instance()->add_login_log(['app_token' => $this->token])) { $this->error('登陆失败,请重新登录'); } power::instance()->_info['token'] = $this->token; $this->success('登陆成功', '', power::instance()->_info); } catch (\Exception $e) { if($e->getCode() >= 0) { $this->error("unkonw error(code:{$e->getCode()}, msg:{$e->getMessage()})", -99); } else { $this->error($e->getMessage(), $e->getCode()); } } } } <file_sep><?php namespace car_aintenance_shop\ctl; use sephp\sephp; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; use admin\model\mod_system; use admin\model\mod_content; /** * Class ctl_index */ class ctl_index { public function index() { view::assign('menuTitle', 'menuTitle'); //$menus = mod_system::parseMenu(); //view::assign('menus',$menus); //$menuHtml = view::fetch('system.menu'); //view::assign('meenuHtml',$menuHtml); $top_menu = mod_system::get_menus('top_menu'); $left_menu = mod_system::get_menus('left_menu'); view::assign('top_menu', $top_menu); view::assign('left_menu', json_encode($left_menu, JSON_UNESCAPED_UNICODE)); view::assign('realname', sephp::$_user['realname']); view::assign('goup_name', empty(sephp::$_user['group_name'])?'---':sephp::$_user['group_name']); view::assign('default_page_url', '?ct=index&ac=home'); view::assign('url_edit_avator', '?ct=admin&ac=edit_avator'); view::assign('url_your_profile', '?ct=admin&ac=profile'); view::assign('logout_url', '?ct=public&ac=logout'); view::assign('login_url', $GLOBALS['_authority']['login_url']); view::display('index'); //$content = view::fetch('index'); } public function lockscreen() { view::display(); } public function main() { view::display('main'); } //默认页面 public function home() { view::display('home'); } } <file_sep>$(function () { form_ob = $('form.validate') for(key in form_ob){ form_ob.eq(key).validate(); } //选择分页条数 $('#pages #page-select').on('change',function () { if(window.location.href.match('page_num=\d*') == null) { window.document.location.href = window.document.location.href + '&page_num=' + $(this).val(); }else{ window.document.location.href = window.location.href.replace(/(page_num=)\d*/, '$110'); } }); //add-file-href,上传文件插件,全局应用 $('.add-files-model').on('click',function () { layer.open({ type: 2, title:'文件上传', shadeClose:true, skin: 'layui-layer-rim', //加上边框 area: ['688px','550px'], //宽高 content: '?ct=public&ac=layer_add_file' }); }) $("#side-menu").on('click','li',function () { alert(123); }) $('.formSub').each(function () { //$(this).submit(); }); //初始化summernote编辑器 $('.summernote').each(function () { var $summernote = $(this); $summernote.summernote({ lang: 'zh-CN', height: 388, // set editor height minHeight: null, // set minimum height of editor maxHeight: null, // set maximum height of editor focus: true, // set focus to editable area after callbacks: { //调用图片上传 onImageUpload: function(files, editor, welEditable) { //console.log(files,editor,welEditable); editorSendFile(files[0],$summernote); }, onImageUploadError: function(err){ console.log(err[0].src); //swal('图片不存在','',"error"); }, onChange: function(contents, $editable) { //console.log('onChange:', contents, $editable); } } }); }); }) //编辑器 ajax上传图片 function editorSendFile(file,$summernote) { //console.log(file); var chunkSize = 1024 * 1024; var total = file.size, chunks = Math.ceil(total / chunkSize), start = 0, end = 0, index = 0, len; while ( index < chunks ) { len = Math.min( chunkSize, total - start ); end = chunkSize ? (start + len) : total; var formData = new FormData(); //console.log(start,end); formData.append("file", file.slice(start,end)); formData.append("name", file.name); formData.append("chunks", chunks); formData.append("chunk", index++); formData.append("type", file.type); formData.append("size", file.size); formData.append("save_type", ''); $.ajax({ url: "?ct=public&ac=editor_upload",//路径是你控制器中上传图片的方法 data: formData, cache: false, contentType: false, processData: false, type: 'POST', success: function (data) { $summernote.summernote('insertImage',data,'插入图片'); } }); start += len; } }<file_sep><?php header('Content-Type: text/html; charset=utf-8'); require_once __DIR__ . '/../sephp/sephp.php'; define('PATH_APP',__DIR__.'/'); define('APP_NAME','api_check'); define('APP_DEBUG',true); /** * 登陆和验证配置 */ $_authority = [ 'need_login' => true, 'not_login' => [ 'index' => ['login', 'logout'] ], 'login_url' => '?ct=index&ac=login', 'user_type' => 'admin', 'login_type' => 'token', 'power_check' => true, 'token_time_out' => 86400, ]; new \sephp\sephp($_authority); <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 商品model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_parking_setting extends pub_mod_model { public static $_table = '#PB#_parking_setting', $_pk = 'parking_id', $_fields = [ 'parking_id' => ['type' => 'int','required' => false, 'comment' => '商品ID'], 'member_id' => ['type' => 'text', 'required' => true, 'comment' => '停车场所属人'], 'parking_name' => ['type' => 'text', 'default' => '', 'comment' => '停车场名称'], 'parking_addr' => ['type' => 'text', 'default' => '', 'comment' => '停车场地址'], 'pay_type' => ['type' => 'int', 'default' => 0, 'comment' => '支付方式'], 'max_amount' => ['type' => 'int', 'default' => 0, 'comment' => '最高价格'], 'min_amount' => ['type' => 'int', 'default' => 0, 'comment' => '最低价格'], 'hour_money' => ['type' => 'int', 'default' => 1, 'comment' => '每小时单价'], 'status' => ['type' => 'int', 'default' => 1, 'comment' => '状态'], 'adduser' => ['type' => 'text', 'required' => false, 'default' => '', 'comment' => '添加人'], 'addtime' => ['type' => 'int', 'required' => false, 'default' => '', 'comment' => '添加时间'], 'upuser' => ['type' => 'text', 'default' => 0, 'comment' => '更新人'], 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], 'deltime' => ['type' => 'int', 'default' => 0, 'comment' => '删除时间'], 'deluser' => ['type' => 'text', 'default' => 0, 'comment' => '删除人'], ], $pay_type = [ '1' => '按次收费', '2' => '按时长计费', ], $status = [ '1' => '启用', '2' => '禁用', ]; /** * 新增 * @Author GangKui * @DateTime 2019-11-14 * @param [type] $conds [description] */ public static function add($conds, &$parking_id = 0) { $conds['addtime'] = TIME_SEPHP; $conds['adduser'] = sephp::$_uid; $data_filter = func::data_filter(self::$_fields, $conds); $result = 0; do{ if(!is_array($data_filter)) { $result = -1; break; } $dups = [ 'uptime' => TIME_SEPHP, 'upuser' => sephp::$_uid, ]; foreach(pub_mod_goods::$_fields as $f => $conf) { //跟新不能修改状态和新增时间 if(in_array($f, ['parking_id','member_id', 'addtime', 'adduser'])) { continue; } $dups[$f] = " VALUES(`{$f}`) "; } if(false === self::insert($data_filter, ['dups' => $dups])) { $result = -2; break; } }while(false); return $result; } /** * 根据id获取商品信息 * @Author GangKui * @DateTime 2019-10-24 * @param [type] $goods_id [description] * @return [type] [description] */ public static function getdata_by_member_id($member_id, $fields = '') { $data = self::getdump([ 'where' => ['member_id', '=', $member_id] ]); return empty($fields) ? $data : $data[$fields]; } /** * 数据格式化 * @Author GangKui * @DateTime 2019-10-23 * @param [type] $data [description] * @return [type] [description] */ public static function data_format($data) { if(!is_array($data)) return $data; $tmp = is_array(reset($data)) ? $data : [$data]; foreach ($tmp as &$v) { if(isset($v['marketable'])) { $v['show_marketable'] = self::$marketable[$v['marketable']]; } if(isset($v['intro'])) { $v['intro'] = html_entity_decode(html_entity_decode(($v['intro']))); } if(isset($v['image_default_id']) && !empty($v['image_default_id'])) { $v['image_default_id'] = json_decode($v['image_default_id'], true); array_walk($v['image_default_id'], function(&$v){ $v = sephp::$_config['upload']['filelink'].'/image/'.$v; }); } if(!empty($v['currency'])) { $v['show_currency'] = self::$currency[$v['currency']]; } } return is_array(reset($data)) ? $tmp : reset($tmp); } } <file_sep><?php namespace sephp\core\lib\db; use sephp\sephp; use sephp\core\req; class sqlsrv { } <file_sep><?php namespace admin\ctl; use sephp\core\cache; use sephp\core\log; use sephp\core\req; use sephp\func; class ctl_test { public function index() { cache::set('admin', 'admin23.comsds', 1); cache::set('admin12312', '收到说法阿斯顿发上到发送大声点阿斯顿啊.comsds'); cache::set('admin发送到发送的', 'admin沙发三大发说到发送的发送到手啊收到说法三大发安德森 23.comsds'); cache::set('adminweewreqwe', 'admi 实打实的发送到发阿斯顿发阿斯顿发阿斯顿发阿斯顿发说法n23.comsds'); var_dump(cache::get('admin')); exit; log::info(var_export(req::server(), 1)); log::error(var_export(req::$forms, 1)); log::error(var_export(req::$forms, 1)); log::error(var_export(req::$forms, 1)); //var_dump(log::save()); var_dump(111111); } }<file_sep><?php namespace admin\ctl; use sephp\sephp; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; /** * 会员管理 * Class ctl_member */ class ctl_member { private $_member_table = '#PB#_member'; private $_member_pk = 'member_id'; private $_pam_table = '#PB#_member_pam'; private $_pam_pk = 'member_id'; private $_grade_table = '#PB#_member_lv'; private $_grade_pk = 'member_lv_id'; private $_advance_table = '#PB#_member_advance'; private $_log_table = '#PB#_member_log'; public function __construct() { view::assign('back_url',req::cookie('member_back_url','javascript:history.go(-1);')); } //会员列表 public function member_list() { $where[] = ['delete_user','=','0']; $keywords = req::item('keywords',''); view::assign('keywords',$keywords); if(!empty($keywords)) { $where[] = [$this->_member_table.'.name','like',"%{$keywords}%"]; } $status = req::item('status','1'); view::assign('status',$status); if(!empty($status)) { $where[] = [$this->_member_table.'.status','=',$status]; } $count = db::select("count({$this->_member_pk}) as count") ->from($this->_member_table) ->where($where) ->as_row() ->execute(); $pages = pages::instance($count['count'],req::item('page_num',10)); $fields = [ $this->_member_table.'.'.$this->_member_pk,$this->_member_table.'.create_time',$this->_member_table.'.create_user', $this->_member_table.'.realname',$this->_member_table.'.status','nickname','advance','mobile','email','state', $this->_member_table.'.point','login_account', $this->_grade_table.'.name as lv_name' ]; $list = db::select($fields) ->from($this->_member_table) ->join($this->_grade_table,'left') ->on($this->_grade_table.'.'.$this->_grade_pk,'=',$this->_member_table.'.'.$this->_grade_pk) ->join($this->_pam_table,'left') ->on($this->_pam_table.'.member_id','=',$this->_member_table.'.member_id') ->where($where) ->offset($pages['offset']) ->limit($pages['limit']) ->order_by($this->_member_pk,'DESC') ->execute(); setcookie('member_back_url',func::get_cururl()); view::assign('list',$list); view::assign('pages',$pages['show']); view::assign('add_url','?ct=member&ac=member_add'); view::assign('edit_url','?ct=member&ac=member_edit'); view::display(); } public function member_add() { if(empty(req::$posts)) { $grades = db::select()->from($this->_grade_table)->where('status','1')->execute(); view::assign('grades',$grades); view::display(); exit(); } if(empty(power::check_member(req::$posts['login_account']))) { show_msg::error('该用户登陆名称【'.req::$posts['login_account'].'】已经存在'); } $data['mobile'] = req::$posts['mobile']; $data['realname'] = req::$posts['realname']; $data['email'] = req::$posts['email']; $data['remark'] = req::$posts['remark']; $data['member_lv_id'] = req::$posts['member_lv_id']; $data['create_time'] = time(); $data['create_user'] = power::instance()->_uid; db::autocommit(false); list($member_id , $rows) = db::insert($this->_member_table)->set($data)->execute(); if(empty($member_id)) { show_msg::error('会员新增失败'); db::rollback(); } $pam['member_id'] = $member_id; $pam['password_account'] = func::random('allstr', 8); //随机字符串 $pam['login_account'] = req::$posts['login_account']; //登陆名称 $pam['login_password'] = power::make_password(req::$posts['password'],$pam['password_account']); list($id,$rows) = db::insert($this->_pam_table)->set($pam)->execute(); if($rows) { db::commit(); show_msg::success('',req::cookie('member_back_url')); } db::rollback(); show_msg::error(); } public function member_edit() { if(empty(req::$posts)) { $member_id = req::item('member_id',0); $grades = db::select()->from($this->_grade_table)->where('status','1')->execute(); $info = db::select() ->from($this->_member_table) ->where($this->_member_pk,$member_id) ->as_row() ->execute(); $login_account = db::select('login_account') ->from($this->_pam_table) ->where($this->_pam_pk,$member_id) ->as_row() ->execute(); $info['login_account'] = $login_account['login_account']; view::assign('data',$info); view::assign('grades',$grades); view::display('member.member_add'); exit(); } $data['mobile'] = req::$posts['mobile']; $data['realname'] = req::$posts['realname']; $data['email'] = req::$posts['email']; $data['remark'] = req::$posts['remark']; $data['member_lv_id'] = req::$posts['member_lv_id']; $data['update_time'] = time(); $data['update_user'] = power::instance()->_uid; db::autocommit(); if(db::update($this->_member_table) ->set($data) ->where($this->_member_pk,req::$posts['member_id']) ->execute() === false) { db::rollback(); show_msg::error(); } //修改密码 if(empty(req::$posts['password'])) { show_msg::success(); } $pam['password_account'] = func::random('allstr', 8); //随机字符串 $pam['login_password'] = power::make_password(req::$posts['password'],$pam['password_account']); if(db::update($this->_pam_table) ->set($pam) ->where($this->_pam_pk,req::$posts['member_id']) ->execute() === false) { db::rollback(); show_msg::error(); } db::commit(); show_msg::success(); } //会员等级列表 public function grade_list() { $list = db::select()->from($this->_grade_table)->order_by($this->_grade_pk,'ASC')->execute(); view::assign('list',$list); view::assign('add_url','?ct=member&ac=grade_add'); view::assign('edit_url','?ct=member&ac=grade_edit'); setcookie('member_back_url',func::get_cururl()); view::display(); } //添加会员等级 public function grade_add() { if(empty(req::$posts)) { view::display(); exit(); } $data = req::$posts; unset($data['member_lv_id']); list($id,$rows) = db::insert($this->_grade_table) ->set($data) ->execute(); if($id) { show_msg::success('','?ct=member&ac=grade_list'); } show_msg::error(); } public function grade_edit() { $member_lv_id = req::item('member_lv_id',0); if(empty($member_lv_id)) { show_msg::error('会员等级不存在'); } if(empty(req::$posts)) { $info = db::select() ->from($this->_grade_table) ->where($this->_grade_pk,$member_lv_id) ->as_row() ->execute(); view::assign('data',$info); view::display('member.grade_add'); exit(); } $data = req::$posts; if(db::update($this->_grade_table) ->set($data) ->where($this->_grade_pk,$data[$this->_grade_pk]) ->execute() === false) { show_msg::error(); } show_msg::success(); } //留言 public function message_list() { $where[] = ['delete_user','=','0']; $keywords = req::item('keywords',''); view::assign('keywords',$keywords); if(!empty($keywords)) { $where[] = [$this->_member_table.'.name','like',"%{$keywords}%"]; } $status = req::item('status','1'); view::assign('status',$status); if(!empty($status)) { $where[] = [$this->_member_table.'.status','=',$status]; } $count = db::select("count({$this->_member_pk}) as count") ->from($this->_member_table) ->where($where) ->as_row() ->execute(); $pages = pages::instance($count['count'],req::item('page_num',10)); $fields = [ $this->_member_table.'.'.$this->_member_pk,$this->_member_table.'.create_time',$this->_member_table.'.create_user', $this->_member_table.'.realname',$this->_member_table.'.status','nickname','advance','mobile','email','state', $this->_member_table.'.point','login_account', $this->_grade_table.'.name as lv_name' ]; $list = db::select($fields) ->from($this->_member_table) ->join($this->_grade_table,'left') ->on($this->_grade_table.'.'.$this->_grade_pk,'=',$this->_member_table.'.'.$this->_grade_pk) ->join($this->_pam_table,'left') ->on($this->_pam_table.'.member_id','=',$this->_member_table.'.member_id') ->where($where) ->offset($pages['offset']) ->limit($pages['limit']) ->order_by($this->_member_pk,'DESC') ->execute(); setcookie('member_back_url',func::get_cururl()); view::assign('list',$list); view::assign('pages',$pages['show']); view::display(); } public function login_list() { } } <file_sep><?php namespace index\ctl; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\config; use sephp\core\view; use sephp\core\show_msg; use common\model\pub_mod_goods; use common\serv\pub_serv_orders; class ctl_order { public function __construct() { } public function cart() { view::display(); } /** * 展示订单,发起支付 * @Author GangKui * @DateTime 2019-10-26 * @return [type] [description] */ public function complete_order() { $goods_ids = req::item('goods_id', []); $goods_nums = req::item('goods_num', []); if(empty($goods_nums) || empty($goods_ids)) { show_msg::error('订单不存在'); } $data = pub_mod_goods::getlist([ //'field' => , 'where' => [ ['goods_id', 'in' , $goods_ids], ['marketable', '=' , 1], ], ]); if(empty($data)) { show_msg::success('您购买的商品已经下架'); } $data = array_column($data, null, 'goods_id'); $amount = 0; foreach ($goods_ids as $key => $goods_id) { //['name', 'cost', 'mktprice', 'store', 'min_buy', 'nostore_sell', 'goods_id'] $amount += $goods_nums[$key] * $data[$goods_id]['cost']; $goods[$goods_id] = [ 'member_buy_num' => $goods_nums[$key], 'price' => $data[$goods_id]['price'], 'cost' => $data[$goods_id]['cost'], 'mktprice' => $data[$goods_id]['mktprice'], 'goods_id' => $data[$goods_id]['goods_id'], 'name' => $data[$goods_id]['name'], ]; } $data = [ 'goods' => $goods, 'total' => $amount, 'amount' => $amount, ]; //创建订单 if(0 > pub_serv_orders::add_order($data)) { } view::assign('data', $data); view::display(); } /** * 支付 * @Author GangKui * @DateTime 2019-10-26 * @return [type] [description] */ public function ready_pay() { view::display(); } } <file_sep><?php namespace car_aintenance_shop\ctl; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; use sephp\core\lib\make_code; use sephp\core\lib\verifiy; use sephp\core\cache; use sephp\core\lib\weixin\wechat; class ctl_public { public function test() { $result = wechat::instance()->getServerIp(); $result = wechat::instance()->getMenu(); // $result = wechat::instance()->createMenu([ // 'button' => array ( // 0 => array ( // 'name' => '扫码', // 'sub_button' => array ( // 0 => array ( // 'type' => 'scancode_waitmsg', // 'name' => '扫码带提示', // 'key' => 'rselfmenu_0_0', // ), // 1 => array ( // 'type' => 'scancode_push', // 'name' => '扫码推事件', // 'key' => 'rselfmenu_0_1', // ), // ), // ), // 1 => array ( // 'name' => '发图', // 'sub_button' => array ( // 0 => array ( // 'type' => 'pic_sysphoto', // 'name' => '系统拍照发图', // 'key' => 'rselfmenu_1_0', // ), // 1 => array ( // 'type' => 'pic_photo_or_album', // 'name' => '拍照或者相册发图', // 'key' => 'rselfmenu_1_1', // ) // ), // ), // 2 => array ( // 'type' => 'location_select', // 'name' => '发送位置', // 'key' => 'rselfmenu_2_0' // ), // ) // ]); var_dump($result); exit(); var_dump(make_code::barcode([ 'frame' => '3434234123123123123', //'outfile' => PATH_UPLOAD . time() . '.png', ])); exit; //var_dump(make_code::google_api(['frame' => 12312312])); var_dump(make_code::qrcode([ 'frame' => 12312312, 'size' => 10, 'outfile' => PATH_UPLOAD . time() . '.png', ])); } public function layer_add_file() { if(!empty($_FILES['file']) && is_ajax()){ $type = req::item('save_type', ''); $result = upload::web_upload(); if(empty($result)) { show_msg::ajax('upload_save faild',400); } else { show_msg::ajax('success','200',$result); } } view::display('system/add_file'); } public function index() { session::set('admin_001',['ghjklasdfghjkl']); session::set('admin_002',['tttttttttttttt']); p(session::get()); unset($_SESSION['_sephp.a.com']['admin_001']); p(session::get()); } //验证码 public function verify() { $config = [ 'length' => req::item('length',4), 'expire' => req::item('expire',300), ]; echo verifiy::instance($config)->show(); } //登出 public function logout() { session::delete('admin_info'); session_destroy(); show_msg::success('登出成功','?ct=public&ac=login'); } //登陆 public function login() { if(!empty(req::$posts)) { if(sephp::$_config['web']['verify_open'] && !verifiy::instance()->check(req::$posts['verify'])) { show_msg::error('验证码错误'); } $admin_user = req::$posts['username']; $admin_pass = req::$posts['password']; $where = [ ['username','=',$admin_user], ['password','=',$<PASSWORD>], ['status','=',1], ]; if(power::instance()->login_check([ 'username' => $admin_user, 'password' => $<PASSWORD> ])) { if(empty(sephp::$_config['web']['google_auth'])) { log::info('用户【ID:' . power::instance()->_uid . '】登陆成功'); power::instance()->add_login_log(['session_id' => session_id()]); show_msg::success('登陆成功','?ct=index&ac=index'); } elseif(empty(power::instance()->_info['auth_secert'])) { //第一次绑定secert show_msg::redirect('?ct=public&ac=auth_first_username&username=' . $admin_user . '&password=' . $<PASSWORD>); } else { //输入code直接登陆 show_msg::redirect('?ct=public&ac=verify_google_code&username=' . $admin_user . '&password=' . $<PASSWORD>); } } show_msg::error('登陆失败,用户名或密码错误'); } if(!empty(sephp::$_config['web']['google_auth'])) { //把本次的"安全密匙SecretKey" 入库,和账户关系绑定,客户端也是绑定这同一个"安全密匙SecretKey" $secret = google_auth::instance(6)->create_secret(); session::set('googel_auth_secret', $secret); //第一个参数是"标识",第二个参数为"安全密匙SecretKey" 生成二维码信息 $qr_code_url = google_auth::instance()->get_qr_code_url(APP_NAME, $secret); view::assign('qr_code_url', $qr_code_url); } if(!empty(sephp::$_config['web']['verify_open'])) { view::assign('verify_url','?ct=public&ac=verify&length=7'); } view::display('system/login'); } //输入google 验证码 public function verify_goole_code() { power::instance()->is_login(); view::display('system/verify.gogole.code'); } /** * google auth验证 第一步 验证身份 */ public function auth_first_username() { power::instance()->is_login(); view::assign('save_url', '?ct=public&ac=auth_finish'); view::assign('username', req::item('username','')); view::assign('password', req::item('password','')); view::display('system/auto_first'); } /** * google auth验证 第二步 安装app */ public function auth_second_install_app() { power::instance()->is_login(); view::display('system/auto_second'); } /** * google auth验证 第三部 绑定的secert密钥 */ public function auth_third_bind_secert() { power::instance()->is_login(); //把本次的"安全密匙SecretKey" 入库,和账户关系绑定,客户端也是绑定这同一个"安全密匙SecretKey" $secret = google_auth::instance()->create_secret(); session::set('googel_auth_secret', $secret); //第一个参数是"标识",第二个参数为"安全密匙SecretKey" 生成二维码信息 $qr_code_url = google_auth::instance()->get_qr_code_url( req::item('username', ''), $secret, config::get('base_config')['web_name']); show_msg::ajax('', 200, ['qr_code_url'=>$qr_code_url]); //view::display('system/auto_third'); } public function auth_finish() { power::instance()->is_login(); $code = req::item('code',''); $user = req::item('username', ''); $pass = req::item('password', ''); if(empty($code) || empty($user) || empty($pass)) { show_msg::ajax('用户名,密码或验证码不能为空', 400); } if(!power::instance()->login_check($user, $pass)) { show_msg::ajax('用户名或者密码错误', 400); } $secret = session::get('googel_auth_secret'); if(google_auth::instance()->verify_code($code,$secret)) { db::update(power::$_table_admin) ->set(['auth_secert'=>$secret]) ->where('admin_id', power::instance()->_info['admin_id']) ->execute(); power::instance()->login_log(); show_msg::ajax('绑定成功', 200); } else { show_msg::ajax('绑定失败,验证吗错误', 400); } } //使用code 直接登陆 public function verify_google_code() { power::instance()->is_login(); if(!empty(req::$posts)) { $code = req::item('code',''); $user = req::item('username', ''); $pass = req::item('password', ''); if(empty($code) || empty($user) || empty($pass)) { show_msg::error('用户名或者密码或验证码不能为空'); } if(!power::instance()->login_check($user, $pass)) { show_msg::error('用户名或者密码错误'); } if(google_auth::instance()->verify_code($code, power::instance()->_info['auth_secert'])) { power::instance()->login_log(); show_msg::success('登陆成功','?ct=index&ac=index'); } show_msg::error('Google验证码错误'); } view::display('system/verify_google_code'); } public function page_500() { view::display('system/500'); } public function page_404() { //P($_SERVER); view::assign('not_fount_url', 'http://' . $_SERVER['HTTP_HOST'] . func::get_cururl()); view::display('system/404'); } } <file_sep><?php namespace common\serv; use sephp\sephp; use sephp\func; use common\model\pub_mod_order; use common\model\pub_mod_order_items; use common\model\pub_mod_goods; use common\model\pub_mod_order_check; /** * 订单服务 * erro_no 10000 - 19999 */ class pub_serv_orders { public static $_error_msg = null; /** * 下订单 * @Author GangKui * @DateTime 2019-10-24 * @param [type] $data [description] * @param array $order_info [description] * @return [type] [description] */ public static function add_order($data, $order_info = []) { $result = 0; pub_mod_order::db_start(); do{ if(empty($data['goods']) || !is_array($data['goods'])) { $result = -10001; break; } $goods_ids = array_column($data['goods'], 'goods_id', 'goods_id'); $data['qrcode'] = pub_mod_order::create_qrcode(); $data['order_id'] = func::make_uniqid(true); $data['order_sn'] = func::random('capital', 4) . func::make_uniqid(); $goods_info = pub_mod_goods::getlist([ 'where' => [ [pub_mod_goods::$_pk, 'in' , array_values($goods_ids)], ['marketable', '=' , 1], ] ]); $goods_info = array_column($goods_info, null, 'goods_id'); $order_item = []; $total_amount = 0; foreach ($data['goods'] as $goods) { $order_item['order_id'] = [ 'order_id' => $data['order_id'], 'goods_id' => $goods['goods_id'], 'price' => $goods['price'], 'nums' => $goods['member_buy_num'], 'currency' => $goods_info[$goods['goods_id']]['currency'], 'amount' => $goods['price'] * $goods['member_buy_num'], 'price' => $goods['price'], 'goods_params' => serialize($goods_info[$goods['goods_id']]), 'goods_name' => $goods_info[$goods['goods_id']]['name'], 'cost' => $goods_info[$goods['goods_id']]['cost'], 'adduser' => sephp::$_uid, 'addtime' => TIME_SEPHP, 'upuser' => sephp::$_uid, 'uptime' => TIME_SEPHP ]; $total_amount += $goods['price'] * $goods['member_buy_num']; $currency = $goods_info[$goods['goods_id']]['currency']; } $data['total_amount'] = $total_amount;//商品默认货币总值 $data['cost_item'] = $total_amount; $data['pmt_order'] = 0;//订单优惠 $data['pmt_goods'] = 0;//商品优惠 $data['discount'] = 0;//订单折扣 $data['payed'] = $total_amount;//订单支付金额 $data['cost_payment'] = $total_amount; $data['currency'] = $currency; $data['addon'] = serialize($data['goods']); $data['member_id'] = sephp::$_uid; $data['disabled'] = 1; $data['ip'] = func::get_client_ip(); $data['status'] = pub_mod_order::STATUS_ACTION; $data['adduser'] = sephp::$_uid; $data['itemnum'] = count($goods_ids); $data['addtime'] = TIME_SEPHP; //订单主表数据 $order_post = func::data_filter(pub_mod_order::$_fields, $data); if(!is_array($order_post)) { $result = -10002; break; } if(false === pub_mod_order::insert($order_post)) { $result = -10003; break; } if(false === pub_mod_order_items::insert($order_item)) { $result = -10004; break; } }while(false); 0 > $result ? pub_mod_order::db_rollback() : pub_mod_order::db_commit(); pub_mod_order::db_end(); return $result; } /** * 订单核销 * @Author GangKui * @DateTime 2019-11-11 * @param [type] $qucode_str [description] * @return [type] [description] */ public static function check_order($data, &$order_info = []) { $result = 0; $data_filter = func::data_filter([ 'type' => ['type' => 'int', 'require' => true], 'qrcode_str' => ['type' => 'text', 'require' => true] ], $data); pub_mod_order::db_start(); do{ if(!is_array($data_filter)) { $result = -1; break; } //查询订单的合法 $order_info = pub_mod_order::getdump([ 'where' => [ 'qrcode', '=', $data_filter['qrcode_str'], ], ]); if(empty($order_info[pub_mod_order::$_pk])) { $result = -2; break; } //检验时间是否过期 //更新订单已完成 if(false === pub_mod_order::update([ ['status' => pub_mod_order::STATUS_FINISH, 'uptime' => TIME_SEPHP, 'upuser' => sephp::$_uid], [pub_mod_order::$_pk, '=', $order_info[pub_mod_order::$_pk]] ])) { $result = -4; break; } }while(false); 0 > $result ? pub_mod_order::db_rollback() : pub_mod_order::db_commit(); pub_mod_order::db_end(); //写入核销记录 if(0 > pub_mod_order_check::add([ 'order_id' => $order_info[pub_mod_order::$_pk], 'type' => $data_filter['type'], 'check_str' => $data_filter['qrcode_str'], 'status' => 0 > $result ? 2 : 1, 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE), 'addip' => func::get_client_ip(), ])) { $result = -11; } return $result; } } <file_sep><?php //用户登陆验证 $config['_authority'] = [ 'need_login' => false, //是否要开启登陆验证 'not_login' => [ //不需要登陆验证的url地址 'index' => ['login', 'logout'] ], 'login_url' => '?ct=index&ac=login', //登陆页面 'user_type' => 'admin', //用户表类型admin / member 'login_type' => 'session', //验证方式 session / token / uid 'power_check' => false, //是否权限验证 'token_time_out' => '86400', ]; $config['web'] = [ 'url' => 'http://sephp.a.com', //是否开启验证码 'verify_open' => false, //是否开启google auth 验证 'google_auth' => false, //编辑器指定 'edit_tool' => 'mvim://open/?url=file://%file%&line=%line%', //phpstrom 'idea://open?file=%file%&line=%line% //是否生成静态页面 //'static_page' => ['index','member'], //css,js版本号,方便集体刷新缓存 'build' => 'xxxxxxx', ]; $config['log'] = [ 'open' => true, //开启 'single' => true, //单日志文件模式 'file_size' => 10240, //10M 'type' => 'file', 'path' => PATH_ROOT.'runtime/log/', 'detail_info' => true, ]; //session 设置 $config['session'] = [ 'prefix' => 'sephp.a.com_', 'auto_start' => true, 'path' => '', 'expire' => 14400, 'secure' => false, 'use_cookies' => true, ]; //可以做读写分离的设置 $config['mysql'] = [ 'enable' => true, 'user' => 'root', 'pass' => '<PASSWORD>999', 'name' => 'sephp', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => 'se', // 是否启用长链接,不要启用,mysqli的长链问题很多 'keep-alive' => false, // 是否对SQL语句进行安全检查并处理,在插入十万条以上数据的时候会出现瓶颈 'safe_test' => true, // 慢查询阀值,秒 'slow_query' => 0.5, 'host' => [ 'master' => '127.0.0.1:3306', //'slave' => ['127.0.0.1:3306'], ], 'crypt_key' => '<KEY>', 'crypt_fields' => [ //'表名' => ['加密的字段名称'], ], ]; $config['sysRedis'] = [ 'host' => '127.0.0.1', 'port' => '6370', 'user' => '', 'pass' => '', 'select' => 0, 'timeout' => 0, 'expire' => 0, 'persistent' => false, 'prefix' => '', ]; //路由解析配置 $config['route'] = [ 'url_route_on' => ['index'], //开启路由模式的项目 'url_route_ext' => 'html', 'url_route_rules' => [ 'adduser-(\w+)-(\w+)' => '?ct=admin&ac=adduser&admin_id=$1&admin=$2', 'upload_file_list' => '?ct=system&ac=upload_file', 'help' => '?ct=index&ac=help', 'index' => '?ct=index&ac=index', 'about' => '?ct=index&ac=about', 'service' => '?ct=index&ac=service', 'cases' => '?ct=index&ac=cases', 'solutions' => '?ct=index&ac=solutions', 'news' => '?ct=index&ac=news', 'contact' => '?ct=index&ac=contact', 'news-(\w+)-(\w+)' => '?ct=index&ac=news&article_id=$1&p=$2', ], ]; //百度的webupload 分片上传 $config['upload'] = [ 'filepath' => PATH_UPLOAD, 'filelink' => URL_ROOT . '/upload', 'dir_num' => 99, // 目录数量 'max_size' => 1024, // 允许上传图片大小的最大值(单位 KB),设置为 0 表示无限制 'file_max_size' => 0, // 允许上传文件大小的最大值(单位 KB),设置为 0 表示无限制 'max_width' => 0, // 图片的最大宽度(单位为像素),设置为 0 表示无限制 'max_height' => 0, // 图片的最大高度(单位为像素),设置为 0 表示无限制 'min_width' => 0, // 图片的最小宽度(单位为像素),设置为 0 表示无限制 'min_height' => 0, // 图片的最小高度(单位为像素),设置为 0 表示无限制 'detect_mime' => true, // 如果设置为 TRUE ,将会在服务端对文件类型进行检测,可以预防代码注入攻击 'allowed_types' => 'jpg|gif|png|bmp|webp|mp4|zip|rar|gz|bz2|xls|xlsx|pdf|doc|docx', 'enable_ftp' => false, ]; $config['language'] = [ 'type' => 'en', 'path' => '', ]; //微信公众号 $config['wechat'] = [ 'appid' => 'wx77838ddac7e73c08', 'appsecret' => 'ba6ca706a64237d704dbfd585db93877' ]; //短信 $config['sms'] = [ 'app_id' => 'cf_uli9', 'app_key' => '<KEY>', 'sms_send_time' => 60, 'sms_send_num' => 5, 'sms_send_black_time' => 600, 'url' => 'http://106.ihuyi.cn/webservice/sms.php?method=Submit', 'is_open_send_limit' => 1, ]; $config['ip_country_file'] = PATH_LIB.'assets/IPV6-COUNTRY-ISP.BIN'; $config['xhprof'] = [ 'enabled' => false, //关闭 'output_dir' => PATH_RUNTIME . 'xhprof/', ]; return $config; <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; class pub_mod_image extends pub_mod_model { public static $_table = '#PB#_image', $_pk = 'image_id', $_cache_use = true, $_cache_time = 3600, $_error_msg = null, $_transaction = true, $_rule_field = [ 'image_id' => ['type' => 'text', 'required' => true, 'comment' => '商品ID'], //订单号 'image_name' => ['type' => 'text', 'required' => false, 'comment' => '图片名称'], //服务id 'storage' => ['type' => 'text', 'default' => 'file', 'comment' => '存储引擎'], //申请人 'url' => ['type' => 'text', 'default' => 0, 'comment' => '网址'], // 'l_url' => ['type' => 'text', 'default' => 0, 'comment' => '大图'], // 'm_url' => ['type' => 'text', 'default' => 0, 'comment' => '中图'], // 's_url' => ['type' => 'text', 'default' => 0, 'comment' => '小图'], // 'height' => ['type' => 'text', 'default' => 0, 'comment' => '高'], // 'width' => ['type' => 'text', 'default' => 0, 'comment' => '宽'], // 'watermark' => ['type' => 'text', 'default' => 0, 'comment' => '是否有水印'], // 'addtime' => ['type' => 'text', 'default' => time(), 'comment' => '添加时间'], // 'uptime' => ['type' => 'text', 'default' => time(), 'comment' => '更新时间'], // ]; public static $storage = [ 'file' => '本地文件存储', 'url' => '网络url引用', 'ftp' => '', ]; /** * 获取图片地址 * @Author GangKui * @DateTime 2019-10-17 * @param [type] $image_id [description] * @param string $type [description] * @return [type] [description] */ public static function get_url($image_id, $type = '') { if(self::$_cache_use) { $cache_key = __CLASS__ . __METHOD__ . $image_id . $type ; $data = cache::get($cache_key); if(!empty($data)) { return $data; } } switch ($type) { case 'l': $field = 'l_url'; // code... break; case 'm': $field = 'm_url'; // code... break; case 's': $field = 's_url'; // code... break; default: // code... $field = 'url'; break; } $info = self::getdump([ 'field' => $field, 'where' => [ self::$pk => $image_id, ] ]); $data = empty($info[$field]) ? false : $info[$field]; if(self::$_cache_use) { cache::set($cache_key, $data, self::$_cache_time); } return $data; } } <file_sep><?php header('Content-Type: text/html; charset=utf-8'); require_once __DIR__ . '/../sephp/sephp.php'; define('PATH_APP',__DIR__.'/'); define('APP_NAME','app'); define('APP_DEBUG',true); new \sephp\sephp([]);<file_sep><?php namespace admin\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; use common\model\pub_mod_model; /** * 商品model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class mod_admin extends pub_mod_model { public static $_table = '#PB#_admin', $_pk = 'admin_id', $_fields = [ 'admin_id' => ['type' => 'int','required' => true, 'comment' => '管理员ID'], 'group_id' => ['type' => 'text', 'required' => true, 'comment' => '组ID'], 'username' => ['type' => 'text', 'default' => 0, 'comment' => '登陆名'], 'password' => ['type' => 'text', 'default' => null, 'comment' => '<PASSWORD>'], 'sex' => ['type' => 'text', 'default' => 0, 'comment' => '性别'], 'email' => ['type' => 'text', 'default' => 0, 'comment' => '邮箱'], 'realname' => ['type' => 'text', 'default' => 0, 'comment' => '真实姓名'], 'nickname' => ['type' => 'text', 'default' => null, 'comment' => '昵称'], 'mobile' => ['type' => 'text', 'default' => null, 'comment' => '手机'], 'remark' => ['type' => 'text', 'default' => null, 'comment' => '备注'], 'auth_secert' => ['type' => 'text', 'default' => null, 'comment' => 'google身份验证的密钥'], 'session_id' => ['type' => 'text', 'default' => null, 'comment' => '会话ID'], 'reg_ip' => ['type' => 'text', 'default' => null, 'comment' => '注册ip'], 'status' => ['type' => 'text', 'default' => null, 'comment' => '状态'], 'addtime' => ['type' => 'int', 'required' => false, 'default' => 0, 'comment' => '添加时间'], 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], 'deltime' => ['type' => 'int', 'default' => 0, 'comment' => '删除时间'], ], $status = [ '1' => '正常', '2' => '禁用', ], $sex = [ '1' => '男', '2' => '女', ]; public static function get_available_list() { return self::getlist([ 'field' => ['admin_id', 'username', 'nickname'], 'where' => [ ['status', '=', '1'], ['deltime', '=', '0'], ] ]); } public static function getdatabyid($admin_id) { $data = self::getdump([ 'where' => [self::$_pk => $admin_id] ]); return self::data_format($data); } /** * 数据格式化 * @Author GangKui * @DateTime 2019-10-23 * @param [type] $data [description] * @return [type] [description] */ public static function data_format($data = []) { if(empty($data)) return $data; if(isset($data['sex'])) { $data['show_sex'] = self::$sex[$data['sex']]; } if(isset($data['status'])) { $data['status'] = self::$status[$data['status']]; } if(isset($data['group_id'])) { //$data['group_name'] = self::$status[$data['status']]; } return $data; } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; use common\model\pub_mod_member; /** * 会员model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_member_pam extends pub_mod_model { public static $_table = '#PB#_member_pam', $_pk = 'member_id', $_fields = [ 'member_id' => ['type' => 'text', 'required' => true, 'comment' => '会员用户id'], 'username' => ['type' => 'text', 'required' => true, 'comment' => '登录名'], 'password' => ['type' => 'text', 'default' => true, 'comment' => '登录密码'], 'password_account' => ['type' => 'text', 'default' => null, 'comment' => '加密字符串'], 'wechat_openid' => ['type' => 'text', 'default' => null, 'comment' => '微信openid'], 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], ]; /** * 会员注册 * @Author GangGuoer * @DateTime 2019-10-31T01:46:47+0700 * @version [version] * @param [type] * @return [type] */ public static function web_regist($data, &$member_info = []) { $result = 0; $data['member_id'] = func::random('web'); $data['source'] = 'pc'; $data['addtime'] = TIME_SEPHP; $data['adduser'] = -1; $data['reg_ip'] = func::get_client_ip(); $data['password'] = \<PASSWORD>\core\lib\power::<PASSWORD>($data['password']); $insert_pam = func::data_filter(self::$_fields, $data); $insert_members = func::data_filter(pub_mod_member::$_fields, $data); self::db_start(); do{ if(!is_array($insert_pam) || !is_array($insert_members)) { $result = -1; break; } $info = self::getdump([ 'where' => ['username', '=', $insert_pam['username']] ]); if(!empty($info)) { $result = -2; break; } if(false === self::insert($insert_pam)) { $result = -601; break; } if(false === pub_mod_member::insert($insert_members)) { $result = -602; break; } }while(false); if(0 > $result) { self::db_rollback(); } else { self::db_commit(); $member_info = $insert_members; } self::db_end(); return $result; } /** * 验证密码 * @Author GangKui * @DateTime 2019-10-24 * @return [type] [description] */ public static function check_pass($login_account, $login_password, &$member_id = 0) { $info = self::getdump([ 'where' => ['username', '=', $login_account] ]); if(empty($info) || !password_verify($login_password, $info['password'])) { return false; } $member_id = $info['member_id']; return true; } /** * 验证微信openid * @Author GangKui * @DateTime 2019-10-24 * @param [type] $openid [description] * @return [type] [description] */ public static function wechat_check($openid, &$member_id = 0) { $info = self::getdump(['where' => ['wechat_openid', '=', $openid]]); if(empty($info['member_id'])) { return false; } $member_id = $info[self::$_pk]; return $member_id; } /** * 验证apptoken * @Author GangKui * @DateTime 2019-11-05 * @param [type] $token [description] * @return [type] [description] */ public static function app_check($token, &$member_id = 0) { $info = self::getdump(['where' => ['app_token', '=', $token]]); if(empty($info['member_id'])) { return false; } $member_id = $info[self::$_pk]; return $member_id; } } <file_sep><?php function smarty_modifier_judge($string, $default_val = '') { if(isset($string)) { return empty($string) ? $default_val : $string; } return $default_val; } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; use sephp\core\pub_mod_parking_setting; /** * 商品model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_parking_log extends pub_mod_model { public static $_table = '#PB#_parking_log', $_pk = 'parking_log_id', $_fields = [ 'parking_log_id'=> ['type' => 'int','required' => false, 'comment' => '商品ID'], 'member_id' => ['type' => 'text', 'required' => true, 'comment' => '停车场所属人'], 'car_num' => ['type' => 'text', 'required' => true, 'comment' => '车牌号码'], 'come_in_time' => ['type' => 'text', 'required' => true, 'comment' => '停车时间'], 'come_out_time' => ['type' => 'int', 'default' => 0, 'comment' => '离开时间'], 'status' => ['type' => 'int', 'default' => 0, 'comment' => '状态'], 'amount' => ['type' => 'int', 'default' => 0, 'comment' => '停车总价'], 'amount_formula'=> ['type' => 'int', 'default' => 1, 'comment' => '价格公式'], 'setting_id' => ['type' => 'int', 'default' => 1, 'comment' => '停车场设置ID'], 'adduser' => ['type' => 'text', 'required' => false, 'default' => '', 'comment' => '添加人'], 'addtime' => ['type' => 'int', 'required' => false, 'default' => '', 'comment' => '添加时间'], 'upuser' => ['type' => 'text', 'default' => 0, 'comment' => '更新人'], 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], 'deltime' => ['type' => 'int', 'default' => 0, 'comment' => '删除时间'], 'deluser' => ['type' => 'text', 'default' => 0, 'comment' => '删除人'], ], $status = [ '1' => '启用', '2' => '禁用', ]; /** * 新增 * @Author GangKui * @DateTime 2019-11-14 * @param [type] $conds [description] */ public static function add($conds, &$parking_log_id = 0) { $conds['addtime'] = TIME_SEPHP; $conds['status'] = 1; $conds['adduser'] = empty(sephp::$_uid) ? 0 : sephp::$_uid; $data_filter = func::data_filter(self::$_fields, $conds); $result = 0; do{ if(!is_array($data_filter)) { $result = -1; break; } $data_filter[pub_mod_parking_setting::$_pk] = pub_mod_parking_setting::getdata_by_member_id($data_filter['member_id'], pub_mod_parking_setting::$_pk); if(false === list(,$parking_log_id) = self::insert($data_filter)) { $result = -2; break; } }while(false); return $result; } /** * 新增 * @Author GangKui * @DateTime 2019-11-14 * @param [type] $conds [description] */ public static function up($conds, &$parking_id = 0) { $conds['uptime'] = TIME_SEPHP; $conds['upuser'] = empty(sephp::$_uid) ? 0 : sephp::$_uid; $conds['status'] = 2; $data_filter = func::data_filter(self::$_fields, $conds); $result = 0; do{ if(!is_array($data_filter)) { $result = -1; break; } foreach ([pub_mod_parking_setting::$_pk, 'car_num', 'member_id'] as $f) { if(empty($data_filter[$f])) { $result = -2; break 2; } $where[$f] = $data_filter[$f]; } if(false === self::update($data_filter,$where)) { $result = -3; break; } }while(false); return $result; } /** * 根据id获取商品信息 * @Author GangKui * @DateTime 2019-10-24 * @param [type] $goods_id [description] * @return [type] [description] */ public static function getdatabyid($member_id) { return self::getdump([ 'where' => ['member_id', '=', $member_id] ]); } /** * 数据格式化 * @Author GangKui * @DateTime 2019-10-23 * @param [type] $data [description] * @return [type] [description] */ public static function data_format($data) { if(!is_array($data)) return $data; $tmp = is_array(reset($data)) ? $data : [$data]; foreach ($tmp as &$v) { if(isset($v['marketable'])) { $v['show_marketable'] = self::$marketable[$v['marketable']]; } if(isset($v['intro'])) { $v['intro'] = html_entity_decode(html_entity_decode(($v['intro']))); } if(isset($v['image_default_id']) && !empty($v['image_default_id'])) { $v['image_default_id'] = json_decode($v['image_default_id'], true); array_walk($v['image_default_id'], function(&$v){ $v = sephp::$_config['upload']['filelink'].'/image/'.$v; }); } if(!empty($v['currency'])) { $v['show_currency'] = self::$currency[$v['currency']]; } } return is_array(reset($data)) ? $tmp : reset($tmp); } } <file_sep><?php namespace api_check\ctl; use sephp\sephp; use sephp\func; use sephp\core\config; use sephp\core\req; use sephp\core\log; use sephp\core\db; use sephp\core\show_msg; use common\model\pub_mod_member_pam; class ctl_base { public $uid = 0, $os = null, $version = 1, $req_time= 1, $sign = null, $token = null; private $app_key = null; public function __construct() { //用户没搞好,暂时不理token $this->uid = req::item('uid', 0); $this->token = req::item('token', ''); $this->os = req::item('os', ''); $this->sign = req::item('sign', ''); $this->version = req::item('version', ''); $app_setting = config::get('app_order_check_base_setting', 'mysql'); $this->app_key = $app_setting['app_token']; if($this->req_time > TIME_SEPHP || $this->req_time < (TIME_SEPHP - 600)) { //$this->error('请求已超时'); } if(empty($this->sign) || !$this->check_sign()) { //$this->error('sign错误'); } } protected function get_token() { $token = req::item('_token', ''); $token = empty($token) && ! empty($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : $token; return $token; } protected function success($msg='success', $code=0, $data=[]) { show_msg::ajax($msg, $code, $data, $this->make_sign()); } // 返回失败json数据 protected function error($msg='error', $code=-1, $data=[]) { show_msg::ajax($msg, $code, $data, $this->make_sign()); } /** * 生成签名 * @Author GangKui * @DateTime 2019-11-09 * @param array $data [description] * @return [type] [description] */ public function make_sign($data = []) { $data = ['data' => json_encode($data, JSON_UNESCAPED_UNICODE)]; return func::sign($data, $this->app_key); } /** * 检验sign的合法性 * @Author GangKui * @DateTime 2019-11-05 * @return [type] [description] */ protected function check_sign($post = []) { $data = empty($post) ? req::$forms : $post; $data = ['data' => json_encode($data, JSON_UNESCAPED_UNICODE)]; $sign = func::sign($data, $this->app_key); if($this->sign === $sign) { return true; } return false; } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 会员model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_login_log extends pub_mod_model { public static $_table = '#PB#_login_log', $_pk = 'member_id', $_fields = [ 'id' => ['type' => 'int', 'required' => false, 'comment' => '日志ID'], 'session_id' => ['type' => 'text', 'required' => false, 'comment' => '用户登陆session_id'], 'status' => ['type' => 'text', 'default' => 0, 'comment' => '状态'], 'login_ip' => ['type' => 'text', 'default' => null, 'comment' => '登陆IP'], 'username' => ['type' => 'text', 'default' => 0, 'comment' => '登陆名称'], 'login_time' => ['type' => 'text', 'default' => 0, 'comment' => '登陆时间'], 'login_type' => ['type' => 'text', 'default' => 0, 'comment' => '登陆方式'], 'agent' => ['type' => 'text', 'default' => null, 'comment' => '邮箱'], 'user_type' => ['type' => 'text', 'default' => null, 'comment' => '来源ID'], 'remark' => ['type' => 'text', 'default' => null, 'comment' => '来源url'], ], $user_type = [ 'member' => '用户表', 'admin' => '管理员表', ], $status = [ '1' => '登陆成功', '2' => '登陆失败', ], $login_type = [ '1' => 'wap', '2' => 'pc', '3' => 'app', '4' => 'wechat', '5' => 'alipay', ]; /** * 获取最近一条登陆信息 * @Author GangKui * @DateTime 2019-10-25 * @param [type] $uid [description] * @param string $user_type [description] * @return [type] [description] */ public static function get_last_log($login_uid, $user_type = 'admin') { return self::getdump([ 'where' => ['login_uid', '=', $login_uid], 'limit' => 1, 'order_by' => ['login_time','DESC'], ]); } /** * 新增登陆日志 * @Author GangKui * @DateTime 2019-11-05 * @param [type] $data [description] */ public static function add($data) { $data['login_ip'] = func::get_client_ip(); $data['login_time'] = TIME_SEPHP; $data['agent'] = $_SERVER['HTTP_USER_AGENT']; $insert_data = func::data_filter(self::$_fields, $data); if(!is_array($insert_data)) { return false; } return self::insert($insert_data); } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 商品model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_order_cart extends pub_mod_model { public static $_table = '#PB#_order_cart', $_pk = 'cart_id', $_fields = [ 'cart_id' => ['type' => 'int', 'required' => true, 'comment' => '品牌ID'], 'goods_id' => ['type' => 'text', 'required' => true, 'comment' => '商品ID'], 'number' => ['type' => 'text', 'required' => true, 'comment' => '商品数量'], 'params' => ['type' => 'text', 'required' => true, 'comment' => '购物车对象参数'], 'params' => ['type' => 'text', 'required' => true, 'comment' => '购物车对象参数'], 'params' => ['type' => 'text', 'required' => true, 'comment' => '购物车对象参数'], 'params' => ['type' => 'text', 'required' => true, 'comment' => '购物车对象参数'], 'params' => ['type' => 'text', 'required' => true, 'comment' => '购物车对象参数'], 'ip' => ['type' => 'text', 'default' => null, 'comment' => 'ip地址'], 'adduser' => ['type' => 'text', 'required' => false, 'default' => 0, 'comment' => '添加人'], 'addtime' => ['type' => 'int', 'required' => false, 'default' => 0, 'comment' => '添加时间'], 'upuser' => ['type' => 'text', 'default' => 0, 'comment' => '更新人'], 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], ], $status = [ '1' => '激活中', '2' => '过期/作废', '3' => '已完成', ], $disabled = [ '1' => '启用', '2' => '禁用', ]; const STATUS_ACTION = 1; const STATUS_DEAD = 2; const STATUS_FINISH = 3; public static function create_id() { return return date("ymdHis") . func::random('distinct', 5); } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 会员model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_member extends pub_mod_model { public static $_cache_use = true, $_table = '#PB#_member', $_pk = 'member_id', $_fields = [ 'member_id' => ['type' => 'text', 'required' => true, 'comment' => '会员用户id'], 'member_lv_id' => ['type' => 'text', 'required' => false, 'default' => 0, 'comment' => '会员等级'], 'realname' => ['type' => 'text', 'default' => 0, 'comment' => '真实姓名'], 'nickname' => ['type' => 'text', 'default' => null, 'comment' => '会员昵称'], 'point' => ['type' => 'text', 'default' => 0, 'comment' => '积分'], 'addr' => ['type' => 'text', 'default' => 0, 'comment' => '地址'], 'mobile' => ['type' => 'text', 'default' => 0, 'comment' => '手机号码'], 'email' => ['type' => 'text', 'default' => null, 'comment' => '邮箱'], 'refer_id' => ['type' => 'text', 'default' => null, 'comment' => '来源ID'], 'refer_url' => ['type' => 'text', 'default' => null, 'comment' => '来源url'], //'advance' => ['type' => 'text', 'default' => null, 'comment' => '余额'], 'reg_ip' => ['type' => 'text', 'default' => null, 'comment' => '注册ip'], 'state' => ['type' => 'int', 'default' => 0, 'comment' => '会员验证状态'], 'status' => ['type' => 'int', 'default' => 1, 'comment' => '状态'], 'remark' => ['type' => 'text', 'default' => null, 'comment' => '备注'], 'experience' => ['type' => 'int', 'default' => 0, 'comment' => '经验值'], 'resetpwd' => ['type' => 'text', 'default' => null, 'comment' => '找回密码唯一标示'], 'resetpwdtime' => ['type' => 'int', 'default' => 0, 'comment' => '找回密码时间'], 'source' => ['type' => 'text', 'default' => null, 'comment' => '平台来源'], 'adduser' => ['type' => 'text', 'required' => false, 'default' => 0, 'comment' => '添加人'], 'addtime' => ['type' => 'int', 'required' => false, 'default' => 0, 'comment' => '添加时间'], 'upuser' => ['type' => 'text', 'default' => 0, 'comment' => '更新人'], 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], 'deltime' => ['type' => 'int', 'default' => 0, 'comment' => '删除时间'], 'deluser' => ['type' => 'int', 'default' => 0, 'comment' => '删除人'], ], $state = [ '1' => '未验证', '2' => '已验证', ], $status = [ '1' => '启用', '2' => '禁用', ]; /** * 获取用胡基本信息 * @Author GangKui * @DateTime 2019-11-05 * @param [type] $member_id [description] * @return [type] [description] */ public static function get_member_info($member_id) { return self::getdump([ 'field' => ['member_id', 'nickname', 'realname', 'mobile'], 'where' => [ [self::$_pk, '=', $member_id], ['status', '=', 1] ], ]); } } <file_sep><?php namespace admin\model; use sephp\func; use sephp\sephp; use sephp\core\req; use sephp\core\db; use common\model\pub_mod_model; class mod_system extends pub_mod_model { /** * 获取菜单数据 * @param string $type * @return array */ public static function get_menus($type = 'left_menu') { $file = PATH_APP .'config/menu.xml'; //禁止引用外部xml实体 libxml_disable_entity_loader(true); $xml = file_get_contents($file); $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); $data = []; foreach ($array['menu'] as $key => $val) { if ($type != 'all' && isset($val['@attributes']['display']) && $val['@attributes']['display'] == 'none') { continue; } if ($type != 'left_menu') { $data[$key] = [ 'title' => $val['@attributes']['name'], 'icon' => $val['@attributes']['icon'], 'id' => empty($val['@attributes']['id'])?'':$val['@attributes']['id'], 'spread' => empty($v['@attributes']['spread'])?false:$v['@attributes']['spread'] ]; if ($type != 'all') { continue; } } if (isset($val['menu'])) { $m = self::get_data_menu($val['menu'], $type); if (empty($m)) { continue; } if ($type == 'all') { $data[$key]['menu'] = $m; } elseif (!empty($val['@attributes']['id'])) { $data[$val['@attributes']['id']] = $m; } } } return $data; } public static function get_data_menu($val, $type) { foreach ($val as $k => $v) { if ($type != 'all' && isset($v['@attributes']['display']) && $v['@attributes']['display'] == 'none') { continue; } $data[$k] = [ 'title' => isset($v['@attributes']['name'])?$v['@attributes']['name']: (isset($v['name'])?$v['name']:show_msg::error('菜单配置错误')), 'icon' => isset($v['@attributes']['icon'])?$v['@attributes']['icon']: (isset($v['icon'])?$v['icon']:''), 'href' => isset($v['@attributes']['ac'])?'?ct='.$v['@attributes']['ct'].'&ac='.$v['@attributes']['ac']: (isset($v['ac'])?'?ct='.$v['ct'].'&ac='.$v['ac']:''), 'data-id' => isset($v['@attributes']['ac'])?$v['@attributes']['ct'].'_'.$v['@attributes']['ac']: (isset($v['ct'])?$v['ct'].'_'.$v['ac']:''), 'spread' => isset($v['@attributes']['spread'])?$v['@attributes']['spread']:false, ]; $data[$k]['id'] = isset($v['@attributes']['id'])?$v['@attributes']['name']: (isset($v['id'])?$v['id']:$data[$k]['title']); if (isset($v['menu'])) { $data[$k]['menu'] = self::get_data_menu($v['menu'], $type); } } return $data; } public static function parseMenu($menus = '', $id_name = '') { $json_menu = ''; foreach ($menus as $menu) { $top_menu_id_name = $menu['@attributes']['id']; if (empty($menu['menu']) || $top_menu_id_name != $id_name) { continue; } foreach ($menu['menu'] as $child) { if (isset($child['@attributes']['display']) && $child['@attributes']['display'] == 'none') { continue; } $json_menu[] = [ 'title' => $child['@attributes']['name'], 'icon' => $child['@attributes']['icon'], 'href' => '?ct='.$child['@attributes']['ct'].'&ac='.$child['@attributes']['ac'], 'spread' => empty($child['@attributes']['spread'])?false:$child['@attributes']['spread'] ]; } } return (json_encode($json_menu)); } public static function parseMenu_old() { $file = PATH_SEPHP.'../config/menu.xml'; //禁止引用外部xml实体 libxml_disable_entity_loader(true); $xml = file_get_contents($file); $array = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); //print_r(($array['menu'])); return true; $array = sysXml::xmlToArray(file_get_contents($file)); $menus = array(); foreach ($array['menus']['menu'] as $k => $v) { if (isset($v[0]['display']) && $v[0]['display'] == 'none') {continue; } $v[0]['url'] = ''; if (isset($v[0]['ct']) && !empty($v[0]['ct'])) { $v[0]['url'] = '?ct='.$v[0]['ct'].'&ac='.$v[0]['ac']; } $menus[$k] = $v[0]; if (isset($v['menu'])) { foreach ($v['menu'] as $val) { if (isset($val[0]['display']) && $val[0]['display'] == 'none') {continue; } $val[0]['url'] = ''; if (isset($val[0]['ct']) && !empty($val[0]['ct'])) { $val[0]['url'] = '?ct='.$val[0]['ct'].'&ac='.$val[0]['ac']; } $menus[$k]['child'][] = $val[0]; } } } return $menus; } } <file_sep><?php namespace car_aintenance_shop\ctl; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\db; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; use admin\model\mod_system; use admin\model\mod_admin_group; use admin\model\mod_admin; class ctl_admin { private $_admin_table = '#PB#_admin', $_admin_id = 'admin_id', $_group_table = '#PB#_admin_group', $_group_id = 'group_id', $_log_table = '#PB#_admin_login', $_table_pam = '#PB#_admin_pam'; public function __construct() { view::assign('back_url', req::cookie('back_url', 'javascript:history.go(-1);')); } /** * 个人资料 * @Author GangKui * @DateTime 2019-10-11 * @return [type] [description] */ public function profile() { } /** * 编辑头像 * @Author GangKui * @DateTime 2019-10-11 * @return [type] [description] */ public function edit_avator() { } /** * 用户列表 * @Author GangKui * @DateTime 2019-10-11 * @return [type] [description] */ public function userlist() { $where = []; $keywords = req::item('keywords', ''); view::assign('keywords', $keywords); if (!empty($keywords)) { $where[] = [$this->_table_pam . '.username', 'like', "%{$keywords}%"]; } $status = req::item('status', 0); view::assign('status', $status); if (!empty($status)) { $where[] = ['status', '=', $status]; } $query = db::select('COUNT(admin_id) as count') ->from($this->_admin_table); if ($where) { $query->where($where); } $count = $query->join($this->_group_table, 'left') ->on($this->_group_table.'.group_id', '=', $this->_admin_table.'.group_id') ->as_row()->execute(); $pages = pages::instance($count['count'], req::item('page_num', 10)); $query = db::select($this->_admin_table.'.*,'.$this->_group_table.'.*,'.$this->_table_pam.'.username') ->from($this->_admin_table); if ($where) { $query->where($where); } $data = $query->join($this->_group_table, 'left') ->on($this->_group_table.'.group_id', '=', $this->_admin_table.'.group_id') ->join($this->_table_pam, 'left') ->on($this->_table_pam.'.'.$this->_admin_id, '=', $this->_admin_table.'.'.$this->_admin_id) ->offset($pages['offset']) ->limit($pages['limit']) ->order_by($this->_admin_id, 'desc') ->execute(); setcookie('userlist_url', func::get_cururl()); view::assign('edit_fields_url', '?ct=admin&ac=edit_fields'); view::assign('get_json_list', '?ct=admin&ac=userlist_json'); view::assign('add_url', '?ct=admin&ac=adduser'); view::assign('edit_url', '?ct=admin&ac=adduser'); view::assign('save_url', '?ct=admin&ac=saveuser'); view::assign('list', $data); view::assign('pages', $pages['show']); view::display('admin.userlist'); } public function adduser() { if (empty(req::$posts)) { if (!empty(req::item('admin_id', ''))) { $data = db::select() ->from($this->_admin_table) ->join($this->_table_pam, 'left') ->on($this->_table_pam.'.'.$this->_admin_id, '=', $this->_admin_table.'.'.$this->_admin_id) ->where($this->_admin_table .'.'. $this->_admin_id, req::$forms[$this->_admin_id]) ->as_row() ->execute(); view::assign('data', $data); } $groups = db::select()->from($this->_group_table)->where('status', '1')->execute(); view::assign('groups', $groups); view::assign('add_save_url', '?ct='.CONTROLLER_NAME.'&ac=saveuser'); view::display('admin.adduser'); exit; } $data['realname'] = req::$posts['realname']; $data['nickname'] = req::$posts['nickname']; $data['email'] = req::$posts['email']; $data['group_id'] = req::$posts['group_id']; $data['remark'] = req::$posts['remark']; if (req::$posts[$this->_admin_id]) { if (!empty(req::$posts['password'])) { $pam['password'] = power::make_password(req::$posts['password']); if(false === db::update($this->_table_pam) ->set($pam) ->where($this->_admin_id, req::$posts[$this->_admin_id]) ->execute()) { show_msg::error('编辑失败'); } } if (db::update($this->_admin_table) ->set($data) ->where($this->_admin_id, req::$posts[$this->_admin_id]) ->execute() === false) { show_msg::error('编辑失败'); } else { show_msg::success('编辑成功'); } } $data['password'] = <PASSWORD>(req::$posts['password']); $data['create_time'] = time(); if (db::insert($this->_admin_table)->set($data)->execute() > 0) { show_msg::success('新增成功', '?ct='.CONTROLLER_NAME.'&ac=userlist'); } show_msg::error(); } public function saveuser() { if (req::$forms[$this->_admin_id] > 0) { $status = req::item('status', null); $auth_secert = req::item('auth_secert', ''); $data = !empty($status)?['status' => $status]:['auth_secert' => $auth_secert]; $result = db::update($this->_admin_table) ->set($data) ->where($this->_admin_id, req::$forms[$this->_admin_id]) ->execute(); } else { list($result, $rows) = db::insert($this->_admin_table) ->set(req::$forms) ->execute(); } if ($result !== false) { show_msg::success('', req::cookie('userlist_url', '?ct=admin&ac=userlist')); } } public function saveuser_field() { } public function grouplist() { $where = []; $keywords = req::item('keywords', ''); view::assign('keywords', $keywords); if (!empty($keywords)) { $where[] = ['name', 'like', "%{$keywords}%"]; } $status = req::item('status', 0); view::assign('status', $status); if (!empty($status)) { $where[] = ['status', '=', $status]; } $query = db::select() ->from($this->_group_table); if ($where) { $query->where($where); } $list = $query->execute(); view::assign('list', $list); view::assign('add_url', '?ct=admin&ac=groupadd'); view::assign('edit_url', '?ct=admin&ac=groupadd'); view::assign('power_edit_url', '?ct=admin&ac=groupedit_power'); view::display(); } public function groupadd() { if (empty(req::$posts)) { if (!empty(req::$gets[$this->_group_id])) { $data = db::select() ->from($this->_group_table) ->where($this->_group_id, req::$gets[$this->_group_id]) ->as_row() ->execute(); view::assign('data', $data); } view::display(); exit; } $data['name'] = req::item('name', ''); $data['remark'] = req::item('remark', ''); $data['status'] = req::item('status', 1); if (req::$posts[$this->_group_id]) { if (db::update($this->_group_table)->set($data)->where($this->_group_id, req::$posts[$this->_group_id])->execute() === false) { show_msg::error(); } else { show_msg::success(); } } $data['create_time'] = time(); $data['create_user'] = 1; list($insert_id, $row) = db::insert($this->_group_table)->set($data)->execute(); if ($insert_id > 0) { show_msg::success('', '?ct=admin&ac=grouplist'); } show_msg::error(); } //用户组权限编辑 public function groupedit_power() { if (empty(req::$posts)) { $data = mod_admin_group::getdatabyid(req::$gets[$this->_group_id]); $powers = mod_system::get_menus('all'); view::assign('powers', $powers); view::assign('data', $data); view::display('admin.power'); exit(); } $data['powerlist'] = req::$posts['power']; if (!empty($data['powerlist'])) { $data['powerlist'] = array_map('html_entity_decode', $data['powerlist']); $data['powerlist'] = json_encode($data['powerlist'], JSON_UNESCAPED_UNICODE); } if (db::update($this->_group_table) ->set($data) ->where($this->_group_id, req::$posts[$this->_group_id]) ->execute() === false) { show_msg::error(); } show_msg::success('', '?ct=admin&ac=grouplist'); } //个人资料,个人中心 public function user_info() { $info = db::select($this->_admin_table.'.*,'.$this->_group_table.'.*') ->from($this->_admin_table) ->join($this->_group_table, 'left') ->on($this->_group_table.'.group_id', '=', $this->_admin_table.'.group_id') ->where($this->_admin_id, power::instance()->_uid) ->as_row()->execute(); p(session::get(power::$_mark)); view::assign('data', $info); view::display('admin.user_info'); } //登陆日志 public function loginlog() { $where = []; $keywords = req::item('keywords', ''); view::assign('keywords', $keywords); if (!empty($keywords)) { $where[] = ['username', 'like', "{$keywords}%"]; } $status = req::item('status', 0); view::assign('status', $status); if (!empty($status)) { $where[] = ['status', '=', $status]; } $query = db::select('COUNT(*) as count') ->from($this->_log_table); if (!empty($where)) { $query->where($where); } $count = $query->as_field()->execute(); $pages = pages::instance($count['count'], req::item('page_num', 1)); $data = db::select()->from($this->_log_table); if (!empty($where)) { $data = $data->where($where); } $data = $data->offset($pages['offset']) ->limit($pages['limit']) ->execute(); view::assign('pages', $pages['show']); view::assign('list', $data); view::display('system/loginlog'); } //在线会话 public function online() { $where = []; $keywords = req::item('keywords', ''); view::assign('keywords', $keywords); if (!empty($keywords)) { $where[] = ['username', 'like', "{$keywords}%"]; } $status = req::item('status', 0); view::assign('status', $status); if (!empty($status)) { $where[] = ['status', '=', $status]; } $query = db::select('COUNT(*) as count') ->from($this->_log_table); if (!empty($where)) { $query->where($where); } $count = $query->as_field()->execute(); $pages = pages::instance($count, req::item('page_num', 20)); $data = db::select()->from($this->_log_table); if (!empty($where)) { $data = $data->where($where); } $data = $data->offset($pages['offset']) ->limit($pages['limit']) ->execute(); view::assign('pages', $pages['show']); view::assign('list', $data); view::display('system/online'); } } <file_sep><?php /** * 获取不确定的 request 元素(不存在时返回空,以防止出现变量未定义的警告) * @package Smarty * @subpackage plugins * <{request_em array= key= }> */ function smarty_modifier_empty($params, $default = '') { if(empty($params)) { return $default; } return $params; } <file_sep><?php namespace api_check\ctl; use sephp\sephp; use sephp\func; use sephp\core\config; use sephp\core\req; use sephp\core\log; use sephp\core\db; use sephp\core\lib\power; class ctl_index extends ctl_base { public function index() { echo phpinfo(); } public function check() { echo 1111111; } public function login() { try{ $data_filter = func::data_filter([ 'username' => ['type' => 'text', 'require' => true], 'password' => ['type' => 'text', 'require' => true], ], req::$forms); if(!is_array($data_filter)) { $this->error('参数错误'); } if(false === power::instance()->login_check($data_filter, $info)) { $this->error('用户名或密码错误'); } $this->member_id = power::instance()->_uid; //必须是64位的 $this->token = power::make_token($this->member_id); if(false === power::instance()->add_login_log(['token' => $this->token])) { $this->error('登陆失败,请重新登录'); } power::instance()->_info['token'] = $this->token; $this->success('登陆成功', '', power::instance()->_info); } catch (\Exception $e) { if($e->getCode() >= 0) { $this->error("unkonw error(code:{$e->getCode()}, msg:{$e->getMessage()})", -99); } else { $this->error($e->getMessage(), $e->getCode()); } } } } <file_sep>[upload] upload_invalid_filetype = 'The filetype you are attempting to upload is not allowed.' upload_invalid_filesize = 'The file you are attempting to upload is larger than the permitted size.' upload_invalid_dimensions = 'The image you are attempting to upload does not fit into the allowed dimensions.' upload_not_writable = 'The upload destination folder does not appear to be writable.' upload_not_exist = 'The temporary folder is missing.' upload_bad_filename = 'The file name you submitted already exists on the server.' <file_sep><?php namespace sephp\core; use sephp\sephp; use sephp\func; use sephp\core\config; use sephp\core\log; /** * 语言类 * * @version $Id$ * */ class lang { /** * List of translations * * @var array */ public static $language = array(); public static $config = []; /** * List of loaded language files * * @var array */ public static $is_loaded = array(); public static function _init($config = []) { self::$config = empty($config) ? config::get('language') : $config; } /** * Load a language file * * @param mixed $langfile Language file name * @param string $idiom Language name (english, etc.) * @return void * @author seatle <<EMAIL>> * @created time :2017-12-07 17:17 */ public static function load($langfile, $idiom = '') { if (is_array($langfile)) { foreach ($langfile as $value) { self::load($value, $idiom); } return; } $idiom = empty($idiom) ? self::$config['type'] : $idiom; $langfile = str_replace('.ini', '', $langfile); $langfile .= '.lang.ini'; $idiom = empty($idiom) ? self::$config['type'] : $idiom; if(empty($idiom)) { throw new \Exception('The language type has not definition !'); } self::$is_loaded[$langfile] = $idiom; foreach (['config/lang/', '../common/config/lang/', '../sephp/config/lang/'] as $pf) { $basepath = PATH_APP.$pf.$idiom.'/'.$langfile; if (file_exists($basepath)) { $lang = parse_ini_file($basepath); self::$language = array_merge(self::$language, $lang); self::$language = array_change_key_case(self::$language); } } return true; } public static function set($key, $value) { if ( empty($key) || empty($value) ) { return false; } self::$language[$key] = $value; self::init(); } /** * Language get * * Fetches a single line of text from the language array * * @param string $line Language line key * @param bool $log_errors Whether to log an error message if the line is not found * @return string Translation */ public static function get($key, $defaultvalue = null, $replace = array(), $log_errors = true) { $value = isset(self::$language[$key]) ? self::$language[$key] : null; // 模版中找不到变量定义 if ( $value === null ) { if ( $defaultvalue === null && $log_errors === true ) { throw new \Exception("Could not find the language line {$key} ", E_USER_WARNING); } else { $value = $defaultvalue; } } if ( $replace ) { $value = vsprintf($value, $replace); } return $value; } /** * 替换数据库中存在的语言模版 * * @param mixed $array * @return void * @author seatle <<EMAIL>> * @created time :2017-12-07 17:17 */ public static function tpl_change($str) { if (empty($str)) { return $str; } if ( strpos($str, '{{lang.') !== false ) { if ( preg_match_all('#\{\{lang\.(.*?)\}\}#', $str, $out) ) { $array = array(); $count = count($out[0]); for ($i = 0; $i < $count; $i++) { $array[] = array( 'old_str' => $out[0][$i], 'key' => $out[1][$i], ); } foreach ($array as $arr) { $old_str = $arr['old_str']; $key = $arr['key']; $new_str = lang::get($key, null, false); if ( !empty($new_str) ) { $str = str_replace($old_str, $new_str, $str); } } //var_dump($str); //exit; } } return $str; } } /* vim: set expandtab: */ <file_sep><?php namespace sephp\core\lib; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\config; use sephp\core\lang; use sephp\core\lib\image; /** * @Author: han * ftp操作类 * @Date: 2018-12-05 15:42:55 */ class ftp { public $_configs = [], //配置信息 $_link = null, $error = '', //错误信息 $passive = false, //passive mode flag $system_type; //远程FTP服务器的系统类型标识符 public static $_instance = null; //实例组 /** * 初始化配置信息 * @param string $host * @param string $user * @param string $password * @param int $port * @param int $timeout (seconds) */ public function __construct($configs = []) { $this->_configs = array_merge([ 'host' => null, //ftp地址 'user' => null, //ftp账号 'password' => <PASSWORD>, //ftp用户 'port' => 21, //端口 'timeout' => 60, //超时时间 'ssl' => false,//是否使用ssl ], $configs); return $this->connect(); } /** * 单例模式,生成实例 * @param array $configs * @return object 返回实例句柄 */ public static function instance($configs = []) { $configs = empty($configs) ? sephp::$_configs['ftp'] : $configs; if (!self::$_instance instanceof self) { self::$_instance = new static($configs); } return self::$_instance; } /** * 链接ftp服务器 * @return bool */ public function connect() { if( empty($this->_configs['ssl']) ) //普通方式链接 { if( !$this->_link = @ftp_connect($this->_configs['host'], $this->_configs['port'], $this->_configs['timeout']) ) { $this->error = "Failed to connect to {$this->_configs['host']}"; return null; } } elseif( function_exists("ftp_ssl_connect") ) //检查是否支持ssl { if( !$this->_link = @ftp_ssl_connect($this->_configs['host'], $this->_configs['port'], $this->_configs['timeout']) ) { $this->error = "Failed to connect to {$this->_configs['host']} (SSL connection)"; return null; } } else { $this->error = "Failed to connect to {$this->_configs['host']} (invalid connection type)"; return null; } if( @ftp_login($this->_link, $this->_configs['user'], $this->_configs['password']) ) { @ftp_pasv($this->_link, (bool)$this->passive); $this->system_type = ftp_systype($this->_link); //cgi结束后关闭链接 register_shutdown_function(array(&$this, 'close')); return $this->_link; } else { $this->error = "Failed to connect to {$this->_configs['host']} (login failed)"; return null; } } /** * 上传文件 * @param string $local_path * @param string $remote_file_path * @param bool 目录不存在是否创建 * @param int $mode FTP_ASCII. 图片上传必须使用 FTP_BINARY * @return bool */ public function put($local_file = null, $remote_file = null, $mkdir = false, $mode = FTP_BINARY) { //递归创建目录 !empty($mkdir) && $this->mkdirs(dirname($remote_file)); if( @ftp_put($this->_link, $remote_file, $local_file, $mode) ) { return $this->_success(); } else { $this->error = "Failed to upload file \"{$local_file}\""; return false; } } /** * 递归创建目录 相当于linux mkdir -p * @param string $directory * @return bool */ public function mkdirs($directory) { $path_arr = explode('/', $directory); // 取目录数组 $origin_dir = $this->pwd(); $ret = true; foreach($path_arr as $dir) // 创建目录 { if( in_array($dir, ['.', '..']) || empty($dir) ) { continue; } else if( false == $this->cd($dir) ) { if( false == $this->mkdir($dir) ) { $ret = false; break; } if( false == $this->cd($dir) ) { $ret = true; break; } } } //回退到根,要不会在创建后的目录叠加 $this->cd($origin_dir); return $ret ? $this->_success() : false; } /** * 创建目录 * @param string $directory * @return bool */ public function mkdir($directory = null) { if( @ftp_mkdir($this->_link, $directory) ) { return $this->_success(); } else { $this->error = "Failed to create directory \"{$directory}\""; return false; } } /** * 返回上一级目录 * @param string $directory * @return bool */ public function cdup() { if( @ftp_cdup($this->_link) ) { return $this->_success(); } else { $this->error = "Failed to change up directory"; return false; } } /** * 改变ftp服务器目录 * @param string $directory * @return bool */ public function cd($directory = null) { //函数恢复之前的错误处理程序 否则会抛出异常 restore_error_handler(); if( @ftp_chdir($this->_link, $directory) ) { return $this->_success(); } else { $this->error = "Failed to change directory to \"{$directory}\""; return false; } } /** * 设置文件权限 * @param int $permissions (ex: 0644) * @param string $remote_file * @return false */ public function chmod($remote_file = null, $permissions = 0) { if( @ftp_chmod($this->_link, $permissions, $remote_file) ) { return $this->_success(); } else { $this->error = "Failed to set file permissions for \"{$remote_file}\""; return false; } } /** * 删除文件 * @param string $remote_file * @return bool */ public function delete($remote_file = null) { if( @ftp_delete($this->_link, $remote_file) ) { return $this->_success(); } else { $this->error = "Failed to delete file \"{$remote_file}\""; return false; } } /** * 下载文件 * @param string $remote_file * @param string $local_file * @param int $mode * @return bool */ public function get($remote_file = null, $local_file = null, $mode = FTP_ASCII) { if( @ftp_get($this->_link, $local_file, $remote_file, $mode) ) { return $this->_success(); } else { $this->error = "Failed to download file \"{$remote_file}\""; return false; } } /** * 列出目录的文件 * @param string $directory * @return array */ public function ls($directory = null) { $list = array(); if( $list = @ftp_nlist($this->_link, $directory) ) { return $list; } else { $this->error = "Failed to get directory list"; return array(); } } /** * 获取当前工作目录 * @return string */ public function pwd() { return @ftp_pwd($this->_link); } /** * 文件重命名 * @param string $old_name * @param string $new_name * @return bool */ public function rename($old_name = null, $new_name = null) { if( @ftp_rename($this->_link, $old_name, $new_name) ) { return $this->_success(); } else { $this->error = "Failed to rename file \"{$old_name}\""; return false; } } /** * 删除文件 * @param string $directory * @return bool */ public function rmdir($directory = null) { if( @ftp_rmdir($this->_link, $directory) ) { return $this->_success(); } else { $this->error = "Failed to remove directory \"{$directory}\""; return false; } } private function _success() { $this->error = ''; return true; } /** * 关闭连接 */ public function close() { if( $this->_link ) { @ftp_close($this->_link); $this->_link = null; } } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\core\db; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\cache; use sephp\core\config; use sephp\core\lib\pages; /** * model层基类,必须继承 */ class pub_mod_model { /** * @var null 表名 */ public static $_table = null; /** * @var null 主键 */ public static $_pk = null; /** * @var array 数据表的字段 */ public static $_field = []; /** * @var bool 是否使用缓存 */ public static $_cache_use = false; /** * @var integer 缓存时间 */ public static $_cache_time = 3600; /** * 是否关闭从库 * @var boolean */ public static $enable_slave = false; /** * @var null 错误信息 */ public static $_error_msg = null; /** * @var array 字段验证规则 */ public static $_rule_field = []; /** * @var bool 是否操作主库 */ public static $_is_master = false; /** * insert数据验证方法 * @param $data * @return bool */ public static function _field_verify($data) { if (empty(static::$_rule_field)) { return true; } if(empty($data) || !is_array($data)) { return false; } $data = !is_array(reset($data)) ? [$data] : $data; foreach ($data as $key => $val) { $result = func::date_filter(static::$_rule_field, $val); if(!is_array($result)) { return false; } } return true; } /** * @param array $conds * [ * where => * field => * join => * order => * group => * offset => * limit => * total => * ] * @return array|mixed */ public static function getlist($conds = []) { $data_filter = func::data_filter([ 'where' => ['type' => 'text', 'default' => []], 'field' => ['type' => 'text', 'default' => []], 'joins' => ['type' => 'text', 'default' => []], 'order_by' => ['type' => 'text', 'default' => []], 'group_by' => ['type' => 'text', 'default' => []], 'offset' => ['type' => 'int', 'default' => 0], 'limit' => ['type' => 'int', 'default' => 20], 'total' => ['type' => 'text', 'default' => false], ], $conds); if(empty($data_filter['field'])) { foreach (static::$_field as $f) { $data_filter['field'][] = static::$_table.'.'.$f; } } if ($data_filter['total']) { $total_num = static::count($data_filter['where'], $data_filter['joins']); $pages = pages::instance($total_num, $data_filter['limit']); } if (static::$_cache_use) { $cache_key = serialize($data_filter) . __CLASS__; $data = cache::get($cache_key); if (!empty($data)) { return json_decode($data, true); } } $query = db::select($data_filter['field'])->from(static::$_table); self::_complate_sql($query, $data_filter['where'], $data_filter['joins'], $data_filter['order_by']); if($data_filter['total']) { $query->offset($pages['offset'])->limit($data_filter['limit']); } $data = $query->execute(); /** * 自动格式化查询数据 */ if(!empty($data) && method_exists(new static() , 'data_format')) { $data = static::data_format($data); } $data = $data_filter['total'] ? ['total' => $total_num ,'data' => $data, 'pages' => $pages['show']] : $data; if (static::$_cache_use) { cache::set($cache_key, json_encode($data, JSON_UNESCAPED_UNICODE)); } return $data; } /** * 获取单挑数据 * @param $where * @param array $field * @param array $join * @return mixed */ public static function getdump($conds = []) { foreach (['where', 'fields', 'join', 'order_by'] as $f) { $$f = empty($conds[$f]) ? [] : $conds[$f]; } $field = empty($field) ? static::$_field : $field; if(static::$_cache_use) { $cache_key = serialize($conds) . serialize($field) . __CLASS__ ; $data = cache::get($cache_key); if (!empty($data)) { return unserialize($data); } } $query = db::select($field)->from(static::$_table); static::_complate_sql($query, $where, $join, $order_by); $data = $query->as_row()->execute(); if(!empty($data) && method_exists(new static() , 'data_format')) { $data = static::data_format($data); } if(!empty($data) && static::$_cache_use) { cache::set($cache_key, serialize($data), static::$_cache_time); } return $data; } /** * 获取某个字段等值 * @param $where * @param $field * @param array $join * @return mixed */ public static function getfiled($where, $field, $join = []) { if(static::$_cache_use) { $cache_key = serialize($where) . serialize($field) . serialize($join) . __CLASS__ ; $data = cache::get($cache_key); if (!empty($data)) { return unserialize($data); } } $query = db::select($field)->from(static::$_table); static::_complate_sql($query, $where, $join); $data = $query->as_field()->execute(); if(static::$_cache_use) { cache::set($cache_key, serialize($data), static::$_cache_time); } return $data; } /** * @param array. 添加的数组 * @param 表名 * @return int */ public static function insert(array $data, $table = '', $ignore = false) { if( empty($data) ) { return false; } $extr = []; //扩展属性 //如果table为数组有可能带有其他参数 if( is_array($table) ) { $extr = $table; $table = isset($table['table']) ? $table['table'] : ''; $ignore = isset($table['ignore']) ? $table['ignore'] : $ignore; } //判断是否为批量插入 $mutipule = is_array(reset($data)) ? true : false; $table = empty($table) ? static::$_table : $table; if( empty($table) ) return false; $query = db::insert($table)->ignore($ignore); if( !empty($mutipule) ) //批量插入 { $query->values($data)->columns(array_keys(current($data))); } else //单条插入 { $query->set($data); } //批量更新(遇到重复主键更新,否则插入) if( !empty($extr['dups']) ) { $query->dup($extr['dups']); } return $query->execute(); } /** * @param array. 更新的数组 * @param array 更新条件 * @param 表名 * @param update ignore * @return int */ public static function update(array $data, array $where, $table = '', $ignore = false) { if( empty($data) || empty($where) ) return false; if(empty($where) && !empty($data[static::$_pk])) { $where = [static::$_pk, '=', $data[static::$_pk]]; } $table = empty($table) ? static::$_table : $table; if( empty($table) ) return false; $query = db::update($table) ->set($data) ->ignore($ignore); $result = false; static::_complate_sql($query, $where, $join); return $query->execute(); } /** * 获取总数 * @param array $where * @param array $join * @return mixed */ public static function count($where = [], $join = []) { $query = db::select('COUNT(*) AS total') ->from(static::$_table); static::_complate_sql($query, $where, $join); return $query->as_field()->execute(); } private static function _complate_sql(&$query, $where = [], $join = [], $order = []) { if (!empty($where) || !empty($where['and'])) { $where = empty($where) ? $where['and'] : $where; if(is_array(reset($where))) { $query = $query->where($where); } else { $query = $query->where($where[0], $where[1], $where[2]); } } if (!empty($where['or'])) { $query->or_where($where['or']); } if (!empty($join) && empty($join[0])) { $query = $query->join($join['table'], $join['type']) ->on($join['where'][0], $join['where'][1], $join['where'][2]); } elseif (!empty($join) && is_array($join[0])) { foreach ($join as $j) { $query = $query->join($j['table'], $j['type']) ->on($j['where'][0], $j['where'][1], $j['where'][2]); } } if (empty($order) && !empty(static::$_pk)) { $query->order_by(static::$_table.'.'.static::$_pk, 'desc'); } elseif (is_string($order[0])) { $query->order_by($order[0], $order[1]); } elseif (is_array($order[0])) { foreach ($order as $o) { $query->order_by($o[0], $o[1]); } } } /** * 开启事物 * @Author han * @param boolean $enable_slave 是否允许从库 * @return void */ public static function db_start($enable_slave = false) { db::enable_slave($enable_slave); empty($enable_slave) && self::$enable_slave = true; return db::start(); } /** * 结束事务 * @Author han * @return void */ public static function db_end() { if( self::$enable_slave ) { db::enable_slave(true); } return db::end(); } /** * 为了方便发送统计日志,封装一个commit的函数,在commit的时候自动发送 * 所以模型内如果涉及发送进程结束后发送日志的,commit需要用这个,否则不会发送 * @Author han * @return void */ public static function db_commit() { return db::commit(); } /** * 清空缓存中的统计数据 * @Author han * @return [type] [description] */ public static function db_rollback() { return db::rollback(); } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 订单明细 * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_order_items extends pub_mod_model { public static $_table = '#PB#_order_items', $_pk = 'item_id', $_fields = [ 'item_id' => ['type' => 'int', 'required' => true, 'comment' => '订单明细ID'], 'order_id' => ['type' => 'text', 'required' => true, 'comment' => '订单ID'], 'goods_id' => ['type' => 'text', 'default' => 0, 'comment' => '商品ID'], 'goods_params' => ['type' => 'text', 'default' => null, 'comment' => '订单对应的商品json数据'], 'type_id' => ['type' => 'text', 'default' => null, 'comment' => '商品类型ID'], 'bn' => ['type' => 'text', 'default' => null, 'comment' => '明细商品的品牌名'], 'goods_name' => ['type' => 'text', 'default' => null, 'comment' => '明细商品的名称'], 'cost' => ['type' => 'text', 'default' => null, 'comment' => '明细商品的成本'], 'price' => ['type' => 'text', 'default' => null, 'comment' => '明细商品的销售价(购入价)'], 'g_price' => ['type' => 'text', 'default' => null, 'comment' => '明细商品的会员价原价'], 'score' => ['type' => 'text', 'default' => null, 'comment' => '明细商品积分'], 'weight' => ['type' => 'int', 'default' => 0, 'comment' => '明细商品重量'], 'nums' => ['type' => 'int', 'default' => 0, 'comment' => '明细商品购买数量'], 'sendnum' => ['type' => 'text', 'default' => 0, 'comment' => '明细商品发货数量'], 'addon' => ['type' => 'text', 'default' => 0, 'comment' => '明细商品的规格属性'], 'amount' => ['type' => 'text', 'default' => null, 'comment' => '明细商品总额'], 'adduser' => ['type' => 'text', 'required' => false, 'default' => '', 'comment' => '添加人'], 'addtime' => ['type' => 'int', 'required' => false, 'default' => '', 'comment' => '添加时间'], 'upuser' => ['type' => 'text', 'default' => 0, 'comment' => '更新人'], 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], 'deltime' => ['type' => 'int', 'default' => 0, 'comment' => '删除时间'], 'deluser' => ['type' => 'int', 'default' => 0, 'comment' => '删除人'], ]; } <file_sep><?php namespace car_aintenance_shop\ctl; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; use admin\model\mod_content; use common\model\pub_mod_goods; use common\model\pub_mod_goods_brand; use common\model\pub_mod_order; /** * Class ctl_index */ class ctl_order { /** * 订单列表 * @Author GangKui * @DateTime 2019-10-22 * @return [type] [description] */ public function index() { $list = pub_mod_order::getlist([ 'limit' => req::item('page_num', 20), 'total' => true, ]); view::assign('add_url', '?ct=order&ac=add'); view::assign('edit_url', '?ct=order&ac=edit&order_id='); view::assign('keywords', req::item('keywords', '')); view::assign('list', $list['data']); view::assign('pages', $list['pages']); view::display(); } /** * 添加订单 * @Author GangKui * @DateTime 2019-10-22 * @param integer $order_id [description] */ public function add($order_id = 0) { $data = []; if(!empty(req::$posts)) { $this->save(); exit(); } if(0 < $order_id) { $data = pub_mod_order::getdump([ 'where' => ['order_id', '=', $order_id] ]); } view::assign('data', $data); view::assign('back_url', '?ct=goods&ac=index'); view::display(); } /** * 编辑订单 * @Author GangKui * @DateTime 2019-10-22 * @return [type] [description] */ public function edit() { $this->add(req::item('order_id', 0)); } /** * 订单保存 * @Author GangKui * @DateTime 2019-10-22 * @return [type] [description] */ public function save() { $filter_config = pub_mod_order::$_fields; if(empty(req::$posts['order_sn'])) { req::$posts['order_sn'] = pub_mod_order::create_sn(); } $posts = func::data_filter($filter_config, req::$posts); if(!is_array($posts)) { show_msg::error("参数错误:{$posts}"); } $posts['image_default_id'] = empty($posts['image_default_id']) ? null : json_encode($posts['image_default_id'], JSON_UNESCAPED_UNICODE); $posts['adduser'] = sephp::$_uid; $posts['addtime'] = TIME_SEPHP; $dups = [ 'uptime' => TIME_SEPHP, 'upuser' => sephp::$_uid, ]; foreach(pub_mod_order::$_fields as $f => $conf) { //跟新不能修改状态和新增时间 if(in_array($f, ['addtime','adduser', 'order_id', 'order_sn'])) { continue; } $dups[$f] = " VALUES(`{$f}`) "; } if(false === pub_mod_order::insert($posts, ['dups' => $dups])) { show_msg::error('保存失败'); } show_msg::error('保存成功', '?ct=goods&ac=index'); } } <file_sep><?php namespace index\ctl; use sephp\sephp; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\config; use sephp\core\view; use sephp\core\show_msg; use common\model\pub_mod_member_pam; use sephp\core\lib\power; class ctl_index { protected $page_title = null; protected $page_description = null; protected $page_keywords = null; public function __construct() { $site_info = config::get('base_config','mysql'); $this->page_keywords = $site_info['page_keywords']; $this->page_description = $site_info['page_description']; $this->page_title = $site_info['page_title']; view::assign('site_info', $site_info); view::assign('page_title', $this->page_title); view::assign('page_description', $this->page_description); view::assign('page_keywords', $this->page_keywords); //friend link $links = config::get('friend_link'); } //首页 public function index() { view::display(); } public function login() { if(!empty(sephp::$_uid)) { show_msg::success('您已登陆','?ct=index&ac=index'); } if(empty(req::$posts)) { view::display(); exit(); } $login_info = func::data_filter([ 'username' => ['type' => 'text', 'empty' => true ], 'password' => ['type' => 'text', 'empty' => true ], 'verify' => ['type' => 'text', 'default' => '' ], ], req::$posts); if(!is_array($login_info)) { show_msg::error('用户名或密码不能为空'); } if(sephp::$_config['web']['verify_open'] && !verifiy::instance()->check($login_info['verify'])) { show_msg::error('验证码错误'); } if(power::instance()->login_check($login_info['username'], $login_info['password'])) { power::instance()->add_login_log(); show_msg::success('登陆成功','?ct=index&ac=index'); } show_msg::error('登陆失败,用户名或密码错误'); } public function regist() { if(!empty(sephp::$_uid)) { show_msg::success('您已登陆','?ct=index&ac=index'); } if(!empty(req::$posts)) { $insert_data = func::data_filter([ 'username' => ['type' => 'text', 'required' => true ], 'password' => ['type' => 'text', 'required' => true ], 'email' => ['type' => 'text', 'default' => '' ], 'mobile' => ['type' => 'text', 'default' => '' ], 'nickname' => ['type' => 'text', 'default' => '' ], 'realname' => ['type' => 'text', 'default' => '' ], ], req::$posts); if(!is_array($insert_data)) { show_msg::error('登陆名或密码不能为空'); } if(0 > pub_mod_member_pam::web_regist($insert_data)) { show_msg::error('注册失败'); } show_msg::success('注册成功'); } view::display(); } public function logout() { \sephp\core\session::delete(power::$_mark); session_destroy(); show_msg::success('登出成功','?ct=index&ac=login'); } //关于我们 public function about() { //公司概况 view::assign('company_profile', config::get('company_profile')); //企业文化 view::assign('company_cultural', config::get('company_cultural')); //企业资质 view::assign('company_aptitude', config::get('company_aptitude')); //加入我们 view::assign('join_us', config::get('join_us')); //服务范围 view::assign('service_range', config::get('service_range')); //我们的愿景 view::assign('we_hope', config::get('we_hope')); view::display('about'); } //服务范围 public function service() { view::display('service'); } //申请合作 public function cooperate() { view::display('cooperate'); } //成功案例 public function cases() { view::display('cases'); } //解决方案 public function solutions() { view::display('solutions'); } //新闻文章 public function news() { view::display('news'); } //联系我们 public function contact() { view::display('contact'); } public function send_msg() { $data['send_ip'] = func::get_client_ip(); $data['send_time'] = time(); $data['from_mobile'] = req::item('from_mobile', ''); if (empty($data['from_mobile'])) { } } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 会员model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_order_log extends pub_mod_model { public static $_table = '#PB#_order_log', $_pk = 'log_id', $_fields = [ 'log_id' => ['type' => 'int', 'required' => false, 'comment' => '日志ID'], 'rel_id' => ['type' => 'text', 'required' => false, 'comment' => '对象ID'], 'op_type' => ['type' => 'text', 'default' => 0, 'comment' => '操作方式'], 'behavior' => ['type' => 'text', 'default' => null, 'comment' => '操作行为'], 'result' => ['type' => 'text', 'default' => 0, 'comment' => '日志结果'], 'log_text' => ['type' => 'text', 'default' => 0, 'comment' => '日志内容'], 'addon' => ['type' => 'text', 'default' => 0, 'comment' => '序列化数据'], 'addip' => ['type' => 'text', 'default' => null, 'comment' => '操作人ip'], 'addname' => ['type' => 'text', 'default' => null, 'comment' => '操作人名称'], 'addtime' => ['type' => 'text', 'default' => null, 'comment' => '操作时间'], 'adduser' => ['type' => 'text', 'default' => null, 'comment' => '操作人uid'], ], $op_type = [ 'order','recharge','joinfee','prepaid_recharge' ], $behavior = [ 'creates','updates','payments','refunds','delivery','reship','finish','cancel' ], $result = [ 'SUCCESS','FAILURE' ]; /** * 新增日志 * @Author GangKui * @DateTime 2019-11-05 * @param [type] $data [description] */ public static function add($data) { $data['addip'] = func::get_client_ip(); $data['addtime'] = TIME_SEPHP; $data['addname'] = sephp::$_user['username']; $data['adduser'] = sephp::$_uid; $insert_data = func::data_filter(self::$_fields, $data); if(!is_array($insert_data)) { return false; } return self::insert($insert_data); } } <file_sep><?php namespace admin\mod; use sephp\core\model; /** * summary */ class mod_content extends model { } <file_sep><?php namespace sephp\core; use sephp\sephp; use sephp\core\db; use sephp\func; use sephp\core\req; use sephp\core\log; use sephp\core\config; class model { /** * @var null 表名 */ public static $_table = null; /** * @var null 主键 */ public static $_pk = null; /** * @var array 数据表的字段 */ public static $_field = []; /** * @var bool 是否使用缓存 */ public static $_use_cache = false; /** * @var null 错误信息 */ public static $_error_msg = null; /** * @var array 字段验证规则 */ public static $_rule_field = []; /** * @var bool 是否操作主库 */ public static $_is_master = false; /** * 数据验证方法 * @param $data * @return bool */ public static function _field_verify($data) { if (empty(static::$_rule_field)) { return true; } foreach ($data as $key => $val) { if (empty(static::$_rule_field[$key])) { continue; } if (!call_user_func(static::$_rule_field[$key]['rule'], $val)) { static::$_error_msg = static::$_rule_field[$key]['error_msg']; return false; } } return true; } /** * @param array $conds * [ * where => * field => * join => * order => * group => * offset => * limit => * total => * ] * @return array|mixed */ public static function getlist($conds = []) { foreach (['where', 'field', 'join' , 'order', 'group', 'offset', 'limit', 'total'] as $key) { $$key = empty($conds[$key]) ? [] : $conds[$key]; if($key == 'field' && empty($$key)) { foreach (static::$_field as $f) { $field[] = static::$_table.'.'.$f; } } } if ($total) { $total = static::count($where, $join); $pages = cls_page::make($total, req::item('page_size', 15), '', ''); $offset = $pages['offset']; $limit = $pages['page_size']; } if (static::$_use_cache) { $cache_key = md5(serialize($where).serialize($fields).serialize($order).serialize($join).$offset.$limit.$total); $data = cache::get($cache_key); if (!empty($data)) { return json_decode($data); } } $query = db::select($fields)->from(static::$_table); self::_complate_sql($query, $where, $join, $order); $data = $query->offset($offset)->limit($limit)->execute(); $data = $total?['data' => $data, 'pages' => $pages['show']]:$data; if (static::$_use_cache) { cache::set($cache_key, json_encode($data, JSON_UNESCAPED_UNICODE)); } return $data; } /** * 获取单挑数据 * @param $where * @param array $field * @param array $join * @return mixed */ public static function getdump($where, $field = [], $join = []) { $fields = empty($field)?static::$_field:$field; $query = db::select($fields)->from(static::$_table); static::_complate_sql($query, $where, $join); return $query->as_row()->execute(); } /** * 获取某个字段等值 * @param $where * @param $field * @param array $join * @return mixed */ public static function getfiled($where, $field, $join = []) { $query = db::select($field)->from(static::$_table); static::_complate_sql($query, $where, $join); return $query->as_field()->execute(); } /** * 数据保存 * @param $data * @param array $where * @return bool */ public static function inset($data, $where = []) { $query = db::insert(static::$_table)->set($data); static::_complate_sql($query, $where); list($id, $rows) = $query->execute(static::$_is_master); return $id; } /** * 数据保存 * @param $data * @param array $where * @return bool */ public static function update($data, $where = []) { //编辑 if (in_array('update_time', static::$_field)) { $data['update_time'] = time(); } if (in_array('update_user', static::$_field)) { $data['update_user'] = kali::$auth->uid; } $query = db::update(static::$_table)->set($data)->where(static::$_pk, $data[static::$_pk]); static::_complate_sql($query, $where); return $query->execute(); } /** * 数据保存 * @param $data * @param array $where * @return bool */ public static function save($data, $where = []) { if (empty($data[static::$_pk])) { //新增 if (in_array('create_time', static::$_field)) { $data['create_time'] = time(); } if (in_array('create_user', static::$_field)) { $data['create_user'] = kali::$auth->uid; } $query = db::insert(static::$_table)->set($data); static::_complate_sql($query, $where); list($id, $rows) = $query->execute(); return $id; } elseif ($data[static::$_pk] > 0) { //编辑 if (in_array('update_time', static::$_field)) { $data['update_time'] = time(); } if (in_array('update_user', static::$_field)) { $data['update_user'] = kali::$auth->uid; } $query = db::update(static::$_table)->set($data)->where(static::$_pk, $data[static::$_pk]); static::_complate_sql($query, $where); if ($query->execute() === false) { return false; } return true; } } /** * 获取总数 * @param array $where * @param array $join * @return mixed */ public static function count($where = [], $join = []) { $query = db::select('COUNT('.str_replace('#PB#', 'sp', static::$_table).'.*) AS total') ->from(static::$_table); static::_complate_sql($query, $where, $join); return $query->as_field()->execute(); } private static function _complate_sql(&$query, $where = [], $join = [], $order = []) { if (!empty($where) || !empty($where['and'])) { $where = empty($where)?$where['and']:$where; $query = $query->where($where); } elseif (!empty($where['or'])) { $query->or_where($where['or']); } if (!empty($join) && empty($join[0])) { $query = $query->join($join['table'], $join['type']) ->on($join['where'][0], $join['where'][1], $join['where'][2]); } elseif (!empty($join) && is_array($join[0])) { foreach ($join as $j) { $query = $query->join($j['table'], $j['type']) ->on($j['where'][0], $j['where'][1], $j['where'][2]); } } if (empty($order)) { $query->order_by(static::$_table.'.'.static::$_pk, 'desc'); } elseif (is_string($order[0])) { $query->order_by($order[0], $order[1]); } elseif (is_array($order[0])) { foreach ($order as $o) { $query->order_by($o[0], $o[1]); } } } } <file_sep><?php // This autoload is here just in case you didn't run composer install. // Running composer install would be a better way to autoload the classes. // We search in the ../../packages/ folder $packageFolder = PATH_LIB . 'barcodegen'; spl_autoload_register(function ($className) use ($packageFolder) { $tryFolders = array(); $splits = explode('\\', $className); $c = count($splits); if ($c > 0 && $splits[0] === 'BarcodeBakery') { if ($c > 1) { if ($splits[1] === 'Common') { $tryFolders = array('barcode-common'); } else { // Try all the other folders $tryFolders = array_filter(scandir($packageFolder), function ($f) { if ($f !== '.' && $f !== '..' && $f !== 'barcode-common') { return true; } return false; }); } } } if (count($tryFolders) > 0) { $file = implode('/', array_slice($splits, 2)) . '.php'; foreach ($tryFolders as $folder) { $fullpath = $packageFolder . '/' . $folder . '/src/' . $file; if (file_exists($fullpath)) { include $fullpath; break; } } } }); <file_sep><?php namespace sephp\core; use sephp\sephp; use sephp\func; use sephp\core\config; use sephp\core\lib\cache\base; /** * 缓存操作 * Class cache * 日志类型 type => info sql error */ class cache { public static $instance = null; /** * @var array 缓存类型 file,redis */ protected static $type = 'reids'; /** * @var int 过期时间 */ protected static $expire_time = 3600; /** * @var array 配置参数 */ protected static $config = [ 'open' => false, 'type' => 'file', 'expire_time' => 3600, 'data_type' => 'serialize', ]; /** * 日志初始化 * @access public * @param array $config 配置参数 * @return void */ public static function _init() { if(empty(self::$instance)) { if(!empty(sephp::$_config['cache'])) { self::$config = array_merge(self::$config,sephp::$_config['cache']); } self::$type = self::$config['type']; self::$expire_time = self::$config['expire_time']; $class_name = '\sephp\core\lib\cache\\' . self::$type; self::$instance = new $class_name(self::$config); } return self::$instance; } /** * 设置缓存 * @param $key * @param $value * @param int $expire_time 0 表示永久 * @return mixed */ public static function set($key, $value, $expire_time = -1) { return self::$instance->set( md5($key), $value, 0 > $expire_time ? self::$expire_time : $expire_time ); } /** * 取缓存 * @param $key * @return mixed */ public static function get($key) { return self::$instance->get(md5($key)); } /** * 删除缓存 * @param null $key */ public static function del($key = null) { return self::$instance->del($key); } /** * 调用其他方法 * @param $method * @param $arguments * @return mixed */ public function __call($method, $arguments) { if (!self::$instance) { self::_init(); } return call_user_func_array([self::$instance, $method], $arguments); } } <file_sep><?php namespace admin\ctl; use sephp\sephp; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; /** * 会员 卡劵管理 充值卡和优惠卷 * Class ctl_coupons * */ class ctl_coupons { private $_pk = 'cpns_id'; private $_table = '#PB#_coupons'; private $_field = [ 'cpns_id','cpns_code','cpns_prefix','cpns_status','cpns_key','cpns_limit','create_time','cpns_type','create_user','expire_time' ]; public function __construct() { view::assign('back_url',req::cookie('coupons_back_url','javascript:history.go(-1);')); } //卡劵列表 public function coupons_list() { setcookie('coupons_back_url',func::get_cururl()); $cpns_status = req::item('cpns_status',''); view::assign('cpns_status',$cpns_status); if(!empty($cpns_status)) { $where[] = ['cpns_status','=',$cpns_status]; } $keywords = req::item('keywords',''); view::assign('keywords',$keywords); if(!empty($keywords)) { $where[] = ['cpns_code','like',"{$keywords}%"]; } $where[] = [$this->_table . '.delete_user', '=', '0']; $count = db::select("count({$this->_pk}) as count") ->from($this->_table) ->where($where) ->as_row() ->execute(); $pages = pages::instance($count['count'],req::item('page_num',20)); $list = db::select($this->_field) ->from($this->_table) ->where($where) ->offset($pages['offset']) ->limit($pages['limit']) ->order_by($this->_pk,'DESC') ->execute(); view::assign('list',$list); view::assign('pages',$pages['show']); view::display('coupons.coupons_list'); } //创建卡劵 public function coupons_add() { if(empty(req::$posts)) { view::display(); exit(); } $number = req::$posts['number']; if(empty($number)) { show_msg::error('生成卡劵数量不能为空,最少一张'); } $data['cpns_prefix'] = req::$posts['cpns_prefix']; $data['cpns_type'] = req::$posts['cpns_type']; $data['cpns_status'] = 1;//,1未使用,2已使用 $data['cpns_limit'] = $data['cpns_status'] == 1 ? req::$posts['cpns_limit'] : 0;//卡券额度 $data['create_time'] = time(); $data['create_user'] = power::instance()->_uid; $data['expire_time'] = req::$posts['expire_time']; $fail_num = 0; for($i = 0 ; $i < $number; $i++) { $data['cpns_code'] = $this->create_uuid($data['cpns_prefix']); list($id,$rows) = db::insert($this->_table)->set($data)->execute(); empty($id) ? log::error('新增卡劵失败,data:'.var_export($data,1).$fail_num++) : null; } log::info('新增卡劵'.$number-$fail_num.'张'); show_msg::success(); } //使用卡劵 public function coupons_use() { if(empty(req::$posts)) { view::display(); exit; } } //生成卡劵号码 private function create_uuid($cpns_prefix = '') { mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up. $charid = strtoupper(md5(uniqid(mt_rand(), true))); $hyphen = chr(45);// "-" $uuid = substr($charid,mt_rand(0,16),16); // $uuid = substr($uuid, 0, 4).$hyphen // .substr($uuid, 4, 4).$hyphen // .substr($uuid,8, 4).$hyphen // .substr($uuid,12, 4); if(empty($this->check_repeart($uuid,$cpns_prefix))) { return $uuid; } else { $this->create_uuid(); } } //检测卡劵重复 private function check_repeart($code,$cpns_prefix = '') { return $result = db::select($this->_pk) ->from($this->_table) ->where('cpns_code',$code) ->and_where('cpns_prefix','=',$cpns_prefix) ->and_where('delete_user','=','0') ->and_where('cpns_status','=','1') ->execute(); } } <file_sep><?php namespace sephp\core\lib; use sephp\sephp; /** * 加密 解密 方法 * @ClassName: sys_encrypt * @Author: Gangkui * @Date: 2018-10-08 15:07:36 */ class encrypt { }<file_sep><?php $value = session_create_id(); <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 订单核销 * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_order_check extends pub_mod_model { public static $_table = '#PB#_order_check_log', $_pk = 'log_id', $_fields = [ 'log_id' => ['type' => 'int', 'required' => false, 'comment' => '日志ID'], 'order_id' => ['type' => 'int', 'default' => 0, 'comment' => '订单ID'], 'type' => ['type' => 'int', 'required' => true, 'comment' => '类型'], 'check_str' => ['type' => 'text', 'required' => true, 'comment' => '核销编码'], 'status' => ['type' => 'int', 'required' => true, 'comment' => '核销结果'], 'request_data' => ['type' => 'text', 'required' => false, 'comment' => '请求数据'], 'addip' => ['type' => 'text', 'required' => true, 'comment' => '核销IP地址'], 'adduser' => ['type' => 'text', 'required' => false, 'default' => 0, 'comment' => '添加人'], 'addtime' => ['type' => 'int', 'required' => false, 'default' => 0, 'comment' => '添加时间'], 'deluser' => ['type' => 'text', 'required' => false, 'default' => 0, 'comment' => '添加人'], 'deltime' => ['type' => 'int', 'required' => false, 'default' => 0, 'comment' => '添加时间'], ], $status = [ '1' => '核销成功', '2' => '核销失败', ], $type = [ '1' => 'APP核销', '2' => '闸机核销', '3' => '后台核销', '4' => '微信核销', ]; /** * 新增核销记录 * @Author GangKui * @DateTime 2019-11-12 * @param [type] $conds [description] */ public static function add($conds) { $result = 0; $conds['adduser'] = sephp::$_uid; $conds['addtime'] = TIME_SEPHP; $data_filter = func::data_filter(self::$_fields, $conds); unset($data_filter[self::$_pk]); do{ if(!is_array($data_filter)) { $result = -1; break; } if(false === self::insert($data_filter)) { $result = -2; break; } }while(false); return $result; } /** * 获取列表 * @Author GangKui * @DateTime 2019-11-15 * @return [type] [description] */ public static function getlist_by_where($conds = []) { $data_filter = func::data_filter([ 'page_size' => ['type' => 'int', 'default' => 15], 'page' => ['type' => 'int', 'default' => 1], 'uid' => ['type' => 'text', 'default' => 0], 'total' => ['type' => 'bool', 'default' => false], ], $conds); $where[] = [self::$_table . '.deltime', '=', 0]; if(!empty($data_filter['uid'])) { $where[] = [self::$_table . '.adduser', '=', $data_filter['uid']]; } $list = self::getlist([ 'page' => $data_filter['page'], 'page_size' => $data_filter['page_size'], 'where' => $where, 'page' => $data_filter['page'], 'total' => $data_filter['total'] ]); return $list; } /** * 格式化数据 * @Author GangKui * @DateTime 2019-11-15 * @param [type] $data [description] * @return [type] [description] */ public static function data_format($data) { $tmp = is_array(reset($data)) ? $data : [$data]; foreach ($tmp as &$v) { if(!empty($v['addtime'])) { $v['show_addtime'] = date('Y-m-d H:i:s', $v['addtime']); } if(!empty($v['status'])) { $v['show_status'] = self::$status[$v['status']]; } } return is_array(reset($data)) ? $tmp : reset($tmp); } } <file_sep><?php namespace sephp\core\lib; use sephp\func; use sephp\sephp; use sephp\core\session; use sephp\core\show_msg; use sephp\core\db; use sephp\core\req; use sephp\core\log; use sephp\core\cache; /** * * @ClassName: sys_power * @Author: Gangkui * @Date: 2018-11-05 21:36:29 * * 用户权限检测 以及 登陆检测 */ class power { public $_table = null,//用户信息表 $_table_pam = null,//用户密码表 $_table_group = null,//用户组表 $_user_type = null,//用户类型 $_uid_field = null,//用户ID字段名称 $_mark = null,//用户session标识符 $_info = [], //登陆用户信息 $_uid = 0, //登陆用户ID $_showname = null,//显示名称 $config = []; public static $instance = null; public static function instance($authority = []) { if(empty(self::$instance)) { self::$instance = new self($authority); } return self::$instance; } /** * 初始化验证信息 * @Author GangKui * @DateTime 2019-10-24 * @param array $authority [description] */ public function __construct($authority = []) { $this->config = empty($authority) ? sephp::$_config['_authority'] : $authority; if(empty($this->config['user_type'])) { throw new \Exception('Authority info has does not set "user_type" field!'); } $this->_user_type = $this->config['user_type']; $this->_uid_field = $this->config['user_type'] . '_id'; $this->_mark = '_' . APP_NAME . '_'.$this->_user_type.'_'; $this->_table = '#PB#_'.$this->_user_type; $this->_table_pam = '#PB#_'.$this->_user_type.'_pam'; $this->_table_group = '#PB#_'.$this->_user_type.'_group'; switch (func::get_value($this->config, 'login_type', '')) { case 'token': $this->info_by_token(func::get_value(req::$forms, 'token', ''), $this->_info); break; case 'session': $this->_info = session::get($this->_mark); break; } if(!empty($this->_info)) { sephp::$_user =$this->_info; sephp::$_uid = $this->_uid = $this->_info[$this->_uid_field]; $this->_showname = $this->show_user_name($this->_info); } $this->is_login(); } /** * 判断是否登陆 * @Author GangKui * @DateTime 2019-10-24 * @return boolean [true z] */ public function is_login() { //验证是否需要登陆 if( empty($this->config['need_login']) || ( !empty($this->config['not_login']) && empty($this->config['not_login'][CONTROLLER_NAME]) && in_array(CONTROLLER_NAME,$this->config['not_login']) ) || ( !empty($this->config['not_login']) && !empty($this->config['not_login'][CONTROLLER_NAME]) && in_array(ACTION_NAME,$this->config['not_login'][CONTROLLER_NAME]) ) ) { return true; } //排除重复登录 if(!empty($this->_uid) && $this->config['login_url'] === '?ct='.CONTROLLER_NAME.'&ac='.ACTION_NAME) { show_msg::error('您已经登陆','?ct=index&ac=index'); } //检验登陆 if(empty($this->_uid)) { show_msg::error('您还没有登陆',$this->config['login_url']); } //权限检验 if(!$this->check_power()) { show_msg::error('抱歉!您无权限查看该页面'); } } /** * 权限检查 * @Author GangKui * @DateTime 2019-10-24 * @return [type] [description] */ public function check_power() { $result = false; do{ //无需权限验证 if(false === $this->config['power_check']) { $result = true; break; } if(empty($this->_info['powerlist'])) { break; } if('*' === $this->_info['powerlist']) { $result = true; break; } if( !is_array($this->_info['powerlist']) || !in_array('?ct='.CONTROLLER_NAME.'&ac='.ACTION_NAME, $this->_info['powerlist']) ) { break; } }while(false); return $result; } /** * 记录登陆成功的登陆日志 * @Author GangKui * @DateTime 2019-11-09 * @param array $data [ * session_id => '', * app_token. => '', * ] */ public function add_login_log($data = []) { $result = false; do{ $update_data = func::data_filter([ 'session_id' => ['type' => 'text', 'default' => '', 'required' => empty($data['app_token'])], 'app_token' => ['type' => 'text', 'default' => '', 'required' => empty($data['session_id'])], 'uptime' => ['type' => 'int', 'default' => TIME_SEPHP] ], $data); if(!is_array($update_data)) { break; } //记录登陆日志 $data = [ 'session_id' => func::get_value($data, 'session_id', ''), 'app_token' => func::get_value($data, 'app_token', ''), 'status' => 1,//登陆成功 'login_ip' => func::get_client_ip(), 'username' => $this->_info['username'], 'login_time' => TIME_SEPHP, 'login_uid' => $this->_info[$this->_uid_field], 'user_type' => $this->_user_type, 'agent' => func::get_value($_SERVER, 'HTTP_USER_AGENT', ''), ]; if(false === db::insert('#PB#_login_log')->set($data)->execute()) { log::error('用户登陆,登陆日志写入失败。:'. var_export($data, 1)); break; } if( false === db::update($this->_table_pam) ->set($update_data) ->where($this->_uid_field, $this->_uid) ->execute() ) { log::error('用户登陆,更新会话标识符失败。:' . var_export($update_data, 1)); break; } session::set($this->_mark, $this->_info); $result = true; }while(false); return $result; } /** * 会员 生成 密码 * @param $password * @param null $password_account * @return boolean */ public static function make_password($password,$password_account = null) { //$pass = md5(substr(md5($password),8,10) . (empty($password_accout) ? '' : '_' . $password_account)); return password_hash($password, PASSWORD_BCRYPT); } /** * 制造token * @Author GangKui * @DateTime 2019-11-09 * @param integer $uid [description] * @return [type] [description] */ public static function make_token($uid = 0) { return func::random('alnum', 16) . md5($uid) . func::random('alnum', 16); } /** * 用户检验 * @Author GangKui * @DateTime 2019-11-08 * @param array $conds [description] * @param array &$info [description] * @return [type] [description] */ public function login_check($conds = [], &$info = []) { $result = false; do{ if(false === $this->login_for_name($conds)) { break; } $this->_info = self::get_user_info($this->_uid); //获取用户权限 if(!empty($this->_info['group_id']) && !empty($this->_info['powerlist'])) { $this->_info['powerlist'] = $this->_info['powerlist'] === '*' ? '*' : json_decode($this->_info['powerlist'], true); } $result = true; }while (false); return $result; } /** * 用户名的方式登陆 * @Author GangKui * @DateTime 2019-11-09 * @param [type] $data [description] * @param [type] &$uid [description] * @return [type] [description] */ public function login_for_name($data, &$uid = 0) { $result = false; $data_filter = func::data_filter([ 'username' => ['type' => 'text', 'require' => true, 'default' => ''], 'password' => ['type' => 'text', 'require' => true, 'default' => ''], 'group_id' => ['type' => 'text', 'require' => false, 'default' => ''], ], $data); do{ if(!is_array($data_filter)) { break; } $password = db::select('password,' . $this->_uid_field) ->from($this->_table_pam) ->where('username', '=', $data_filter['username']) ->as_row() ->execute(); if(empty($password) || !password_verify($data_filter['password'], $password['password'])) { $data = [ 'session_id' => session_id(), 'status' => 2, 'login_ip' => func::get_client_ip(), 'username' => $data_filter['username'], 'login_time' => TIME_SEPHP, 'login_uid' => 0, 'user_type' => $this->_user_type, 'agent' => $_SERVER['HTTP_USER_AGENT'], 'remark' => '用户名或者密码错误', ]; db::insert('#PB#_login_log')->set($data)->execute(); log::info('登陆失败,用户名或者密码错误'); break; } $result = $this->_uid = $uid = $password[$this->_uid_field]; }while(false); return $result; } /** * app_token登陆 * @Author GangKui * @DateTime 2019-11-05 * @return [type] [description] */ public function info_by_token($app_token, &$info = []) { $result = false; do{ if(64 != strlen($app_token)) { break; } $data = db::select($this->_uid_field.',uptime') ->from($this->_table_pam) ->where('app_token', '=', $app_token) ->where('uptime', '>', TIME_SEPHP - func::get_value($this->config, 'token_time_out', 86400)) ->as_row() ->execute(); if(empty($data[$this->_uid_field])) { break; } if(md5($data[$this->_uid_field]) !== substr($app_token, 16, 32)) { break; } $info = $this->_info = $this->get_user_info($data[$this->_uid_field]); }while(false); return $result; } /** * 微信登陆验证 * @Author GangKui * @DateTime 2019-11-09 * @param [type] $data [description] * @param integer &$uid [description] * @return [type] [description] */ public function login_for_wechat($data, &$uid = 0) { } /** * 检测用户名是否存在 * @param string $login_account * @return mixed */ public function get_user_info($uid, &$info = []) { $field = [ $this->_table.'.'.$this->_uid_field, 'nickname', 'realname', 'email', 'mobile',$this->_table.'.group_id', 'group_name', 'powerlist', $this->_table_pam . '.username' ]; $info = db::select($field) ->from($this->_table) ->join($this->_table_group, 'right') ->on($this->_table_group . '.group_id', '=', $this->_table . '.group_id') ->join($this->_table_pam, 'left') ->on($this->_table_pam.'.'.$this->_uid_field , '=', $this->_table.'.'.$this->_uid_field) ->where($this->_table.'.'.$this->_uid_field, '=', $uid) ->as_row() ->execute(); return $info; } /** * 显示用户名称 * @Author GangKui * @DateTime 2019-11-09 * @param [type] $info [description] * @return [type] [description] */ public function show_user_name($info) { $name = '-无名氏-'; foreach (['nickname', 'username', 'realname'] as $f) { if(!empty($info[$f])) { $name = $info['nickname']; break; } } return $name; } } <file_sep><?php namespace sephp\core\lib\db; use sephp\sephp; use sephp\core\req; class mysql { } <file_sep><?php namespace sephp\core\lib; class kafka { }<file_sep><?php namespace sephp\core; use sephp\sephp; /** * 路由操作类 * @ClassName: sys_route * @Author: Gangkui * @Date: 2018-10-27 11:50:10 */ class route { public static $instance = null; public $config = null; public static function instance() { if(empty(sephp::$_config['route']['url_route_on']) || empty($_REQUEST['s'])) { return false; } if(empty(self::$instance)) { self::$instance = new self(); } self::$instance->config = sephp::$_config['route']; self::$instance->start(); } public function start() { $param = basename($_REQUEST['s'], '.html'); if(empty($param)) { $_GET['ac'] = 'index'; $_GET['ct'] = 'index'; } elseif(strpos($param, '-') === false && !in_array($param, $this->config['url_route_rules'])) { $this->parse_url($param); //$_GET['ac'] = 'page_404'; //$_GET['ct'] = 'public'; } else { $this->parse_url($param); } return true; } //解析路由 public function parse_url($url) { $key = preg_replace("/-\w+/",'-(\w+)', $url); //p($key, $this->config['url_route_rules'][$key]); if(isset($this->config['url_route_rules'][$key])) { $val = $this->config['url_route_rules'][$key]; $matches = ''; preg_match("/{$key}/", $url, $matches); foreach ($matches as $k=>$v) { if($k == 0) continue; $val = str_replace('$' . $k, $v, $val); } if(strpos($val, '$') !== false) { throw new \Exception("SEPHP router config is error:url_route_rules['{$key}']"); } $param = $this->convert_url($val); foreach ($param as $key=>$val) { $_GET[$key] = $val; } } return true; } /** * url 地址解析成数组 * @param $query * @return array */ public function convert_url($query) { $query = trim($query, '?'); $queryParts = explode('&', $query); $params = array(); foreach ($queryParts as $param) { $item = explode('=', $param); $params[$item[0]] = $item[1]; } return $params; } } <file_sep><?php namespace sephp; /** * 自动注册 * @ClassName: autoloads * @Author: Gangkui * @Date: 2019-07-31 15:34:37 */ class autoloads { protected static $autoload_files = null; /** * 自动加载 * @access public * @param string $class 类名 * @return bool */ public static function autoload($class) { if(strpos('smarty',$class) !== false) { return true; } self::load_by_namespace($class); //self::load_class($class); } /** * 注册函数 * @access public * @param callable $autoload 自动加载处理方法 * @return void */ public static function register_function() { // 注册自定义函数 $func_file = PATH_APP . 'function.php'; if(file_exists($func_file)) { require_once $func_file; } return true; } protected static function load_class($name) { if(file_exists($name.'php')) { require self::$autoload_files; return true; } $prefix = substr($name,0,4); switch ($prefix) { case 'sys_': self::$autoload_files = PATH_LIB . 'sephp/' . $name.'.php'; break; case 'lib_': self::$autoload_files = PATH_APP . '/lib/' . $name . '.php'; break; case 'mod_': self::$autoload_files = PATH_APP . 'mod/' . $name . '.php'; break; default: self::$autoload_files = PATH_LIB . $name . '.php'; break; } if( file_exists( self::$autoload_files ) ) { require self::$autoload_files; } else { return false; } } /** * Set autoload root path. * * @param string $root_path * @return void */ public static function set_root_path($root_path) { self::$autoload_files = $root_path; } public static function load_by_namespace($class) { $class_path = str_replace('\\', DIRECTORY_SEPARATOR, $class); if(false !== strrpos($class_path, '/lib/')) { $class_path = str_replace('/lib/', '/library/', $class_path); } if(false !== strrpos($class_path, '/serv/')) { $class_path = str_replace('/serv/', '/service/', $class_path); } if (self::$autoload_files) { $class_file = self::$_autoload_root_path . DIRECTORY_SEPARATOR . $class_path . '.php'; } if (empty($class_file) || !is_file($class_file)) { $class_file = __DIR__ . DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR . "{$class_path}.php"; } // include the file if needed if (is_file($class_file) && file_exists($class_file)) { require_once($class_file); } // if the loaded file contains a class... if (class_exists($class, false)) { if (method_exists($class, '_init') and is_callable($class.'::_init')) { call_user_func($class.'::_init'); } return true; } return false; } } <file_sep><?php namespace sephp\core\lib\db; use sephp\sephp; use sephp\core\req; abstract class base { // Query types const SELECT = 1; const INSERT = 2; const UPDATE = 3; const DELETE = 4; public static $query_sql = []; abstract public function select(); abstract public function from($from); abstract public function insert(); abstract public function update(); abstract public function delete(); abstract public function where(); abstract public function and_where($column, $op = NULL, $value = NULL); abstract public function execute(); abstract public function compile(); abstract public function order_by($column, $direction = NULL); abstract public function offset($number); abstract public function limit($number); abstract public function join($table, $type = NULL); abstract public function on($c1, $op, $c2); abstract public function query($sql, $type = NULL); } <file_sep><?php namespace sephp\core; use sephp\sephp; use sephp\func; use sephp\core\config; /** * Class log * 日志类型 type => info sql error */ class log { public static $instance = null; /** * @var array 日志信息 */ protected static $log = []; public static $dir = null; /** * @var array 配置参数 */ protected static $config = [ 'open' => true, 'single' => false,//单个日志文件 'file_size' => 2097152, 'path' => PATH_RUNTIME . 'log/', 'apart_level' => ['info','error','sql', 'debug'], //独立记录的类型 'detail_info' => true, //运行的详细信息 ]; /** * 日志初始化 * @access public * @param array $config 配置参数 * @return void */ public static function _init() { self::$config = array_merge(self::$config, sephp::$_config['log']); self::$dir = self::$config['path']; if( !is_dir(self::$dir) && (file_exists(self::$dir) || mkdir(self::$dir, 0755, true))) { throw new \Exception('Please check log config[path] , The path is wrong paht', '-99'); } } /** * 实时写入日志信息 并支持行为 * @access public * @param mixed $msg 调试信息 * @return bool */ public static function info($msg = '') { self::add_msg($msg, 'info'); } public static function error($msg = '') { self::add_msg($msg, 'error'); } public static function sql($msg = '') { self::add_msg($msg, 'sql'); } public static function debug($msg = '') { self::add_msg($msg, 'debug'); } /** * 记录日志信息 * @param string $msg * @param $type */ public static function add_msg($msg = '', $type) { if(!empty($msg)) { $msg = is_string($msg) ? $msg : var_export($msg, true); self::$log[$type] = empty(self::$log[$type]) ? [] : self::$log[$type]; array_push(self::$log[$type], [$msg]); } } /** * 保存日志信息 * @return bool * @throws \Exception */ public static function save() { //是否开启日志 if(empty(self::$config['open'])) { self::$log = []; return true; } foreach (self::$log as $type => $val) { $message = ''; foreach ($val as $msg) { $msg = is_string($msg) ? $msg : var_export($msg, true); $message .= '[ ' . $type . ' ] ' . $msg . "\r\n"; } if (in_array($type, self::$config['apart_level'])) { // 独立记录的日志级别 if (self::$config['single']) { $filename = self::$dir .'/'. $type . '.log'; } else { $filename = self::$dir .'/'. date('ymd') . '_' . $type . '.log'; } } else { throw new \Exception('The log type ['.$type.'] is wrong type'); } self::write($message, $filename); } return true; } /** * 写入日志 * @param $message 写入信息 * @param $destination 写入目标 * @return bool * @throws \Exception */ public static function write($message, $destination) { if (self::$config['detail_info']) { // 获取基本信息 if (isset($_SERVER['HTTP_HOST'])) { $current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; } else { $current_uri = "cmd:" . implode(' ', $_SERVER['argv']); } $runtime = round(microtime(true) - SE_START_TIME, 10); $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞'; $time_str = ' [运行时间:' . number_format($runtime, 6) . 's][吞吐率:' . $reqs . 'req/s]'; $memory_use = func::size_format(memory_get_usage()); $memory_str = ' [内存消耗:' . $memory_use . 'kb]'; $file_load = ' [文件加载:' . count(get_included_files()) . ']'; $message = $time_str . $memory_str . $file_load . "\r\n" . $message; $now = date('Y-m-d H:i:s'); $ip = func::get_client_ip(); $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'CLI'; $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; $message = "---------------------------------------------------------------\r\n[{$now}] {$ip} {$method} {$uri} " . $message; } $handle = fopen($destination,'a+'); if (fwrite($handle, $message) === FALSE) { throw new \Exception('Log writing failed, please check log file write permission'); } return (fclose($handle)); } /** * 记录出log 其他的一些数据 * @Author han * @param string $name 文件名 * @param mix $data 数组 * @param boolean $backtrace 回溯跟踪 * @return int 大于0表示写入成功 */ public static function add($filename , $data, $with_php = true, $backtrace = false){ static $_log_fp; if( empty($_log_fp[$name]) && !($_log_fp[$name] = fopen(self::$dir . $name, 'ab')) || !flock($_log_fp[$name], LOCK_EX) ) { return false; } if(is_array($data) || is_object($data)) { $data = var_export($data, true); } if($backtrace) { $d = debug_backtrace(); foreach($d as $v) { $data .= "\n$v[file]: $v[line]"; } } $data = $with_php ? "<?php exit;?>". date('Y-m-d H:i:s') ."\n". $data ."\n\n" : $data."\n"; $ret = fputs( $_log_fp[$name], $data ); flock($_log_fp[$name], LOCK_UN); return $ret; } } <file_sep><?php namespace common\serv; use sephp\sephp; use sephp\func; use common\model\pub_mod_parking_setting; use common\model\pub_mod_parking_log; /** * 停车场 * erro_no 20000 - 29999 */ class pub_serv_orders { public static $_error_msg = null; /** * 停车 * @Author GangKui * @DateTime 2019-10-24 * @param [type] $data [description] * @param array $order_info [description] * @return [type] [description] */ public static function come_in($data, $order_info = []) { $result = 0; pub_mod_parking_setting::db_start(); do{ }while(false); 0 > $result ? pub_mod_parking_setting::db_rollback() : pub_mod_parking_setting::db_commit(); pub_mod_parking_setting::db_end(); return $result; } /** * 订单核销 * @Author GangKui * @DateTime 2019-11-11 * @param [type] $qucode_str [description] * @return [type] [description] */ public static function come_out($data, &$order_info = []) { $result = 0; $data_filter = func::data_filter([ 'type' => ['type' => 'int', 'require' => true], 'qrcode_str' => ['type' => 'text', 'require' => true] ], $data); pub_mod_order::db_start(); do{ }while(false); 0 > $result ? pub_mod_order::db_rollback() : pub_mod_order::db_commit(); pub_mod_order::db_end(); return $result; } } <file_sep><?php class ctl_test { public function index() { //// 使用 WebSocket 通知客户端 $client = new sys_socket(); //$client->connect($_SERVER['HTTP_HOST'], 9527, '/'); $client->connect("127.0.0.1", 8888, '/json?utma=jjj&userid=1&username=yangzetao'); $payload = json_encode(array( 'Event' => 'IncrMessageCount', 'Msg' => 'Hello' )); $rs = $client->send_data($payload); if( $rs !== true ) { echo "send data error...\n"; } else { echo "ok\n"; } $client->disconnect(); exit; for ($i = 0; $i < 10; $i++) { $payload = json_encode(array( 'Event' => 'message', 'Msg' => 'Hello' )); $rs = $client->send_data($payload); if( $rs !== true ) { echo "send data error...\n"; } else { echo "ok\n"; } } ini_set('display_errors', 1); error_reporting(E_ALL); } public function service() { //创建服务端的socket套接流,net协议为IPv4,protocol协议为TCP $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); /*绑定接收的套接流主机和端口,与客户端相对应*/ if(socket_bind($socket,'127.0.0.1',8888) == false){ echo 'server bind fail:' . socket_strerror(socket_last_error()); /*这里的127.0.0.1是在本地主机测试,你如果有多台电脑,可以写IP地址*/ } //监听套接流 if(socket_listen($socket,4)==false){ echo 'server listen fail:'.socket_strerror(socket_last_error()); } //让服务器无限获取客户端传过来的信息 do{ /*接收客户端传过来的信息*/ $accept_resource = socket_accept($socket); /*socket_accept的作用就是接受socket_bind()所绑定的主机发过来的套接流*/ if($accept_resource !== false){ /*读取客户端传过来的资源,并转化为字符串*/ $string = socket_read($accept_resource,1024); /*socket_read的作用就是读出socket_accept()的资源并把它转化为字符串*/ echo 'server receive is : '.$string.PHP_EOL;//PHP_EOL为php的换行预定义常量 flush(); if($string != false){ $return_client = 'server receive is : I am every happy to recive you message'.PHP_EOL; /*向socket_accept的套接流写入信息,也就是回馈信息给socket_bind()所绑定的主机客户端*/ socket_write($accept_resource,$return_client,strlen($return_client)); /*socket_write的作用是向socket_create的套接流写入信息,或者向socket_accept的套接流写入信息*/ }else{ echo 'socket_read is fail'; } /*socket_close的作用是关闭socket_create()或者socket_accept()所建立的套接流*/ socket_close($accept_resource); } }while(true); socket_close($socket); } }<file_sep><?php //路由解析配置 $config['route'] = [ 'url_route_on' => ['api_check'], //开启路由模式的项目 'url_route_ext' => 'html', 'url_route_rules' => [ 'adduser-(\w+)-(\w+)' => '?ct=admin&ac=adduser&admin_id=$1&admin=$2', 'upload_file_list' => '?ct=system&ac=upload_file', 'check' => '?ct=index&ac=check', 'index' => '?ct=index&ac=index', 'about' => '?ct=index&ac=about', 'service' => '?ct=index&ac=service', 'cases' => '?ct=index&ac=cases', 'solutions' => '?ct=index&ac=solutions', 'news' => '?ct=index&ac=news', 'contact' => '?ct=index&ac=contact', 'news-(\w+)-(\w+)' => '?ct=index&ac=news&article_id=$1&p=$2', ], ]; $config['api'] = [ 'app_key' => '<KEY>', //开启路由模式的项目 'encrypt_key' => '1935ca53e8032a8564dd16bc63ed102b', ]; return $config; <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; /** * 商品model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_goods extends pub_mod_model { public static $_table = '#PB#_goods', $_pk = 'goods_id', $_fields = [ 'goods_id' => ['type' => 'int','required' => true, 'comment' => '商品ID'], 'goods_sn' => ['type' => 'text', 'required' => true, 'comment' => '商品编号'], 'name' => ['type' => 'text', 'default' => '', 'comment' => '商品名称'], 'brand_id' => ['type' => 'int', 'default' => 0, 'comment' => '商品品牌'], 'cate_id' => ['type' => 'int', 'default' => 0, 'comment' => '商品分类'], 'type_id' => ['type' => 'int', 'default' => 0, 'comment' => '商品类型'], 'marketable' => ['type' => 'int', 'default' => 1, 'comment' => '上下架'], 'store' => ['type' => 'int', 'default' => 0, 'comment' => '库存'], 'p_order' => ['type' => 'int', 'default' => 0, 'comment' => '排序'], 'cost' => ['type' => 'text', 'default' => 0, 'comment' => '成本价'], 'price' => ['type' => 'text', 'default' => 0, 'comment' => '销售价格'], 'currency' => ['type' => 'text', 'default' => 'CNY', 'comment' => '币种'], 'mktprice' => ['type' => 'text', 'default' => 0, 'comment' => '市场价'], 'score' => ['type' => 'text', 'default' => 0, 'comment' => '积分'], 'weight' => ['type' => 'text', 'default' => 0, 'comment' => '重量'], 'unit' => ['type' => 'text', 'default' => null, 'comment' => '单位'], 'brief' => ['type' => 'text', 'default' => null, 'comment' => '商品简介'], 'image_default_id' => ['type' => 'text', 'default' => null, 'comment' => '默认图片'], 'min_buy' => ['type' => 'text', 'default' => 0, 'comment' => '起定量'], 'store_place' => ['type' => 'text', 'default' => 0, 'comment' => '库位'], 'goods_setting' => ['type' => 'text', 'default' => null, 'comment' => '商品设置'], 'big_pic' => ['type' => 'text', 'default' => null, 'comment' => '大图'], 'small_pic' => ['type' => 'text', 'default' => null, 'comment' => '小图'], 'intro' => ['type' => 'text', 'default' => null, 'comment' => '详细介绍'], 'nostore_sell' => ['type' => 'int', 'default' => 0, 'comment' => '是否开启无库存销售'], 'comments_count' => ['type' => 'int', 'default' => 0, 'comment' => '评论次数'], 'view_count' => ['type' => 'int', 'default' => 0, 'comment' => '浏览次数'], 'buy_count' => ['type' => 'int', 'default' => 0, 'comment' => '购买次数'], 'adduser' => ['type' => 'text', 'required' => false, 'default' => '', 'comment' => '添加人'], 'addtime' => ['type' => 'int', 'required' => false, 'default' => '', 'comment' => '添加时间'], 'upuser' => ['type' => 'text', 'default' => 0, 'comment' => '更新人'], 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], ], $currency = [ 'CNY' => '¥', 'USD' => '$', ], $marketable = [ '1' => '上架', '2' => '下架', ]; /** * 创建商品编号 * @Author GangKui * @DateTime 2019-10-22 * @return [type] [description] */ public static function create_sn() { return date("ymdHis") . func::random('distinct', 5); } /** * 根据id获取商品信息 * @Author GangKui * @DateTime 2019-10-24 * @param [type] $goods_id [description] * @return [type] [description] */ public static function getdatabyid($goods_id) { return self::getdump([ 'where' => [self::$_pk, '=', $goods_id] ]); } /** * 数据格式化 * @Author GangKui * @DateTime 2019-10-23 * @param [type] $data [description] * @return [type] [description] */ public static function data_format($data) { if(!is_array($data)) return $data; $tmp = is_array(reset($data)) ? $data : [$data]; foreach ($tmp as &$v) { if(isset($v['marketable'])) { $v['show_marketable'] = self::$marketable[$v['marketable']]; } if(isset($v['intro'])) { $v['intro'] = html_entity_decode(html_entity_decode(($v['intro']))); } if(isset($v['image_default_id']) && !empty($v['image_default_id'])) { $v['image_default_id'] = json_decode($v['image_default_id'], true); array_walk($v['image_default_id'], function(&$v){ $v = sephp::$_config['upload']['filelink'].'/image/'.$v; }); } if(!empty($v['currency'])) { $v['show_currency'] = self::$currency[$v['currency']]; } } return is_array(reset($data)) ? $tmp : reset($tmp); } } <file_sep><?php namespace car_aintenance_shop\ctl; use sephp\sephp; use sephp\core\req; use sephp\core\log; use sephp\core\view; use sephp\core\lib\power; use sephp\core\lib\pages; use sephp\core\db; use sephp\core\upload; use sephp\core\show_msg; use sephp\core\session; use sephp\core\config; class ctl_system { protected $_url = '?ct=system&ac='; protected $_config_table = '#PB#_config'; public function __construct() { $back_url = req::item('back_url','javascript:history.go(-1);'); view::assign('back_url',$back_url); } public function index() { } /** * 网址设置 */ public function siteconfig() { if(empty(req::$posts)) { view::display(); exit; } } /** * 资源管理 */ public function file_manager() { $keywords = req::item('keywords',''); view::assign('keywords',$keywords); $type = req::item('type','log'); switch ($type) { case 'log': $path_file = PATH_RUNTIME.'log/'; break; case 'cache': $path_file = PATH_ROOT.'runtime/cache/'; break; case 'upload': $path_file = PATH_ROOT.'upload/file/'; break; default: $path_file = PATH_ROOT.'runtime/log/'; } clearstatcache(); $files = glob($path_file."*{$keywords}*"); $list = []; if(!empty($files)) { foreach ($files as $k=>$f) { $info = pathinfo($f); $list[$k]['filectime'] = date('Y-m-d',filectime($f));//创建时间 $list[$k]['fileatime'] = date('Y-m-d',fileatime($f));//文件上次被访问的时间 $list[$k]['filemtime'] = date('Y-m-d',filemtime($f));//文件内容上次的修改时间 $list[$k]['name'] = $info['basename']; $list[$k]['size'] = size_format(filesize($f)); $list[$k]['type'] = filetype($f); $list[$k]['fileperms'] = substr(sprintf("%o",fileperms($f)),-4); //文件权限 } } view::assign('list',$list); view::display(); } /** * 文件上传 */ public function upload_file() { $where[] = ['delete_user','=','0']; $keywords = req::item('keywords',''); view::assign('keywords',$keywords); if($keywords) { $where[] = ['realname','like',"%{$keywords}%"]; } $count = db::select('count(file_id) as count') ->from('#PB#_file') ->where($where) ->as_row() ->execute(); //分页 $pages = pages::instance($count['count'],req::item('page_num','10')); $list = db::select()->from('#PB#_file') ->where($where) ->offset($pages['offset']) ->limit($pages['limit']) ->order_by('file_id','desc') ->execute(); view::assign('pages',$pages['show']); view::assign('list',$list); view::assign('del_url',$this->_url.'del_file'); view::assign('add_url',$this->_url.'add_file'); view::display(); } /** * 删除文件 逻辑删除 */ public function del_file() { $file_id = req::item('file_id',0); if(empty($file_id)) { show_msg::redirect(); } if(upload::del_file($file_id)) { is_ajax() ? show_msg::ajax('删除成功','200') : show_msg::success(); } is_ajax() ? show_msg::ajax('删除失败','400') : show_msg::error(); } public function file_label() { view::assign('list',''); view::display(); } /** * 数据库优化 */ public function data_optimization() { db::select(); } /** * 数据备份 */ public function data_backups() { if(empty(req::$posts)) { $tables = db::query('show tables')->execute(); view::assign('tables',$tables); view::display(); exit(); } p(req::$posts); switch (req::$posts['type']) { case 'all': dbmanage::instance()->backup(); break; case 'structure': break; } } /** * 友情链接管理 */ public function friend_link() { $key = 'friend_link'; if(empty(req::$posts)) { $data = config::get($key); view::assign('list',empty($data) ? null : $data); view::display(); exit(); } $data = []; foreach (req::$posts['title'] as $k=>$val) { if(empty($val) && empty(req::$posts[$k]['url'])) { continue; } $data[$k]['sort_id'] = req::$posts['sort_id'][$k]; $data[$k]['title'] = req::$posts['title'][$k]; $data[$k]['url'] = req::$posts['url'][$k]; $data[$k]['status'] = req::$posts['status'][$k]; } //p($data,empty($data));exit; if(empty($data)) { config::set($key,''); show_msg::success('',func::get_cururl()); } array_multisort(array_column($data,'sort_id'),SORT_DESC,$data); //p($data);exit; if(config::set($key,$data)) { show_msg::success('',func::get_cururl()); } show_msg::error('',func::get_cururl()); } /** * 基础设置 */ public function baise_config() { $key = 'base_config'; if(empty(req::$posts)) { view::assign('data',config::get($key, 'mysql')); view::assign('clear_view_cache_url',$this->_url.'clear_view_cache'); view::assign('clear_static_page_url',$this->_url.'clear_static_page'); view::display(); exit; } if(config::set($key,req::$posts)) { show_msg::success('设置成功'); } show_msg::error('保存失败'); } /** * 站点设置 * @method basic_content * @Author GangGuoer * @DateTime 2019-10-27T17:32:22+0700 * @version [version] * @return [type] */ public function basic_content() { if (!empty(req::$posts)) { foreach (req::$posts as $key => $value) { config::set($key, $value); } show_msg::success('保存成功', func::get_cururl()); } //公司概况 view::assign('company_profile', config::get('company_profile', 'mysql')); //企业文化 view::assign('company_cultural', config::get('company_cultural', 'mysql')); //企业资质 view::assign('company_aptitude', config::get('company_aptitude', 'mysql')); //加入我们 view::assign('join_us', config::get('join_us', 'mysql')); //服务范围 view::assign('service_range', config::get('service_range', 'mysql')); //我们的愿景 view::assign('we_hope', config::get('we_hope', 'mysql')); view::display(); } /** * 菜单配置 */ public function menus() { //p(session::get('admin_info'),pathinfo(func::get_cururl())); $menus = req::item('menus',''); $file = PATH_APP . 'config/menu.xml'; if(empty($menus)) { view::assign('menus',file_get_contents($file)); view::display(); exit; } //var_dump(html_entity_decode($menus,ENT_QUOTES));exit; if(file_put_contents($file,html_entity_decode($menus,ENT_QUOTES)) > 0) { show_msg::success(); } show_msg::error(); } public function clear_static_page() { show_msg::success('','-1'); } public function clear_view_cache() { $dir = PATH_RUNTIME.'compile/'; if(!file_exists($dir)) { show_msg::success('','-1'); } $file = glob($dir.'*'); if(empty($file)) { show_msg::success('','-1'); } foreach ($file as $path) { if(!unlink($path)) { show_msg::error('','-1'); } } show_msg::success('','-1'); } } <file_sep><?php namespace admin; class mod_index { public function __construct() { echo __CLASS__.'<hr/>'; echo __METHOD__; } public static function getlist() { return db::select()->from('#PB#_config')->execute(); } }<file_sep><?php namespace sephp\core; use sephp\sephp; /** * session 管理 * @ClassName: session * @Author: Gangkui * @Date: 2018-11-15 14:53:40 */ class session { protected static $prefix = '', $init = null, $config = []; /** * 设置或者获取session作用域(前缀) * @param string $prefix * @return string|void */ public static function prefix($prefix = '') { empty(self::$init) && self::boot(); if (empty($prefix) && null !== $prefix) { return self::$prefix; } else { self::$prefix = $prefix; } } /** * session初始化 * @param array $config * @return void */ public static function instance() { //重构session //session_set_save_handler('session::open', 'session::close', 'session::read', 'session::write', 'session::destroy', 'session::gc'); self::$config = empty($config) ? sephp::$_config['session'] : $config; if (isset(self::$config['prefix'])) { self::$prefix = self::$config['prefix']; } if (session_status() == PHP_SESSION_ACTIVE) { self::$init = true; return true; } if (!self::$config['auto_start']) { self::$init = false; return false; } if (isset(self::$config['path'])) { session_save_path(self::$config['path']); } if (isset(self::$config['expire'])) { //Session数据在服务器端储存的时间 ini_set('session.gc_maxlifetime', self::$config['expire']); //SessionID在客户端Cookie储存的时间 ini_set('session.cookie_lifetime', self::$config['expire']); } if (isset(self::$config['secure'])) { //session.cookie_secure设置为true意味着它只会通过安全连接(SSL)发送会话cookie, ini_set('session.cookie_secure', self::$config['secure']); } //不能通过客户端脚本访问,则为 true ini_set('session.cookie_httponly', true); if (isset(self::$config['use_cookies'])) { ////是否使用cookies(默认值为1) ini_set('session.use_cookies', self::$config['use_cookies']); } if (isset(self::$config['cache_limiter'])) { //session在客户端的缓存方式,有nocache,private,private_no_expire,publice主这几种 session_cache_limiter(self::$config['cache_limiter']); } if (isset(self::$config['cache_expire'])) { session_cache_expire(self::$config['cache_expire']); } // 启动session if (self::$config['auto_start']) { ini_set('session.auto_start', 0); session_start(); self::$init = true; } else { self::$init = false; } } /** * session设置 * @param string $name session名称 * @param mixed $value session值 * @param string|null $prefix 作用域(前缀) * @return void */ public static function set($name, $value = '', $prefix = null) { if (!self::$init) self::init(); $prefix = !is_null($prefix) ? $prefix : self::$prefix; if (strpos($name, '.')) { // 二维数组赋值 list($name1, $name2) = explode('.', $name); if ($prefix) { $_SESSION[$prefix][$name1][$name2] = $value; } else { $_SESSION[$name1][$name2] = $value; } } elseif ($prefix) { $_SESSION[$prefix][$name] = $value; } else { $_SESSION[$name] = $value; } } /** * session获取 * @param string $name session名称 * @param string|null $prefix 作用域(前缀) * @return mixed */ public static function get($name = '', $prefix = null) { empty(self::$init) && self::init(); $prefix = !is_null($prefix) ? $prefix : self::$prefix; if ('' == $name) { // 获取全部的session $value = $prefix ? (!empty($_SESSION[$prefix]) ? $_SESSION[$prefix] : null) : $_SESSION; } elseif ($prefix) { // 获取session if (strpos($name, '.')) { list($name1, $name2) = explode('.', $name); $value = isset($_SESSION[$prefix][$name1][$name2]) ? $_SESSION[$prefix][$name1][$name2] : null; } else { $value = isset($_SESSION[$prefix][$name]) ? $_SESSION[$prefix][$name] : null; } } else { if (strpos($name, '.')) { list($name1, $name2) = explode('.', $name); $value = isset($_SESSION[$name1][$name2]) ? $_SESSION[$name1][$name2] : null; } else { $value = isset($_SESSION[$name]) ? $_SESSION[$name] : null; } } return $value; } /** * session设置 下一次请求有效 * @param string $name session名称 * @param mixed $value session值 * @param string|null $prefix 作用域(前缀) * @return void */ public static function flash($name, $value) { self::set($name, $value); if (!self::has('__flash__.__time__')) { self::set('__flash__.__time__', $_SERVER['REQUEST_TIME_FLOAT']); } self::push('__flash__', $name); } /** * 清空当前请求的session数据 * @return void */ public static function flush() { if (self::$init) { $item = self::get('__flash__'); if (!empty($item)) { $time = $item['__time__']; if ($_SERVER['REQUEST_TIME_FLOAT'] > $time) { unset($item['__time__']); self::delete($item); self::set('__flash__', []); } } } } /** * 删除session数据 * @param string|array $name session名称 * @param string|null $prefix 作用域(前缀) * @return void */ public static function delete($name = null, $prefix = null) { empty(self::$init) && self::init(); if (empty($name)) { session_unset();//释放内存 session_destroy();//删除当前会话 return true; } $prefix = !is_null($prefix) ? $prefix : self::$prefix; if (is_array($name)) { foreach ($name as $key) { if ($prefix) { unset($_SESSION[$prefix][$key]); } else { unset($_SESSION[$key]); } } } elseif (strpos($name, '.')) { list($name1, $name2) = explode('.', $name); if ($prefix) { unset($_SESSION[$prefix][$name1][$name2]); } else { unset($_SESSION[$name1][$name2]); } } else { if ($prefix) { unset($_SESSION[$prefix][$name]); } else { unset($_SESSION[$name]); } } } /** * 清空session数据 * @param string|null $prefix 作用域(前缀) * @return void */ public static function clear($prefix = null) { self::delete($prefix); } /** * 判断session数据 * @param string $name session名称 * @param string|null $prefix * @return bool */ public static function has($name, $prefix = null) { empty(self::$init) && self::init(); $prefix = !is_null($prefix) ? $prefix : self::$prefix; if (strpos($name, '.')) { // 支持数组 list($name1, $name2) = explode('.', $name); return $prefix ? isset($_SESSION[$prefix][$name1][$name2]) : isset($_SESSION[$name1][$name2]); } else { return $prefix ? isset($_SESSION[$prefix][$name]) : isset($_SESSION[$name]); } } /** * 添加数据到一个session数组 * @param string $key * @param mixed $value * @return void */ public static function push($key, $value) { $array = self::get($key); if (is_null($array)) { $array = []; } $array[] = $value; self::set($key, $array); } /** * 启动session * @return void */ public static function start() { self::instance(); } /** * 销毁session * @return void */ public static function destroy123() { if (!empty($_SESSION)) { $_SESSION = []; } session_unset(); session_destroy(); self::$init = null; } /** * 重新生成session_id * @param bool $delete 是否删除关联会话文件 * @return void */ public static function regenerate($delete = false) { session_regenerate_id($delete); } /** * 暂停session * @return void */ public static function pause() { // 暂停session session_write_close(); self::$init = false; } /** * session_start() 之后第一个被调用的回调函数 * @param string $savePath * @param string $sessionName */ public static function open() { p(session_id()); return true; } /** * 在 write 回调函数调用之后调用。 * 当调用 session_write_close() 函数之后,也会执行本方法 */ public static function close() { p(__METHOD__); return true; } /** * session_start() 函数手动开始会话之后,PHP 内部调用 read 回调函数来获取会话数据。 * 在调用 read 之前,PHP 会调用 open 回调函数。 * @param $session_id */ public static function read() { p(__METHOD__); } /** * 在会话保存数据时会调用 * PHP 会在脚本执行完毕或调用 session_write_close() 函数之后调用此回调函数 * @param $session_id * @param $data */ public static function write() { p(__METHOD__); return true; } /** * 当调用 session_destroy() 函数, * 或者调用 session_regenerate_id() 函数并且设置 destroy 参数为 TRUE 时, * 会调用此回调函数 * @param $session_id */ public static function destroy() { p(__METHOD__); return true; } public static function gc() { //session_gc(); return true; } /** * 当需要新的会话 ID 时被调用的回调函数。 回调函数被调用时无传入参数, * 其返回值应该是一个字符串格式的、有效的会话 ID。 */ public static function create_sid() { p(__METHOD__); return true; } } <file_sep><?php namespace sephp\core; use sephp\sephp; use sephp\core\db; class config { private static $table = '#PB#_config'; /** * @var array 配置参数 */ private static $config = []; /** * @var array 配置方式 file文件方式,db 数据库方式 */ private static $type = 'file'; /** * @var string 参数作用域 */ private static $range = '_sys_'; /** * 设定配置参数的作用域 * @access public * @param string $range 作用域 * @return void */ public static function range($range) { self::$range = $range; if (!isset(self::$config[$range])) self::$config[$range] = []; } /** * 加载配置文件(PHP格式) * @access public * @param string $file 配置文件名 * @param string $name 配置名(如设置即表示二级配置) * @param string $range 作用域 * @return mixed */ public static function load($file, $name = '', $range = '') { $range = $range ?: self::$range; if (!isset(self::$config[$range])) self::$config[$range] = []; if (is_file($file)) { $name = strtolower($name); $type = pathinfo($file, PATHINFO_EXTENSION); if ('php' == $type) { return self::set(include $file, $name, $range); } if ('yaml' == $type && function_exists('yaml_parse_file')) { return self::set(yaml_parse_file($file), $name, $range); } return self::parse($file, $type, $name, $range); } return self::$config[$range]; } /** * 检测配置是否存在 * @access public * @param string $name 配置参数名(支持二级配置 . 号分割) * @param string $range 作用域 * @return bool */ public static function has($name, $range = '') { $range = $range ?: self::$range; if (!strpos($name, '.')) { return isset(self::$config[$range][strtolower($name)]); } // 二维数组设置和获取支持 $name = explode('.', $name, 2); return isset(self::$config[$range][strtolower($name[0])][$name[1]]); } /** * 获取配置参数 为空则获取所有配置 * @access public * @param string $key 配置参数名(支持二级配置 . 号分割) * @param string $type mysql file * @return mixed */ public static function get($key = null, $type = 'config') { if($type === 'mysql') { if(empty($key)) { $data = db::select() ->from(self::$table) ->execute(true); if(!empty($data)) { foreach ($data as $k=>$v) { $data[$k] = empty($v) ? '' : json_decode($v,true); } } return $data; } else { $data = db::select() ->from(self::$table) ->where('key',$key) ->as_row() ->execute(true); return empty($data['value']) ? null : json_decode($data['value'],true); } } elseif(empty(sephp::$_config)) { //加载默认配置 sephp::$_config = include_once(PATH_SEPHP . 'config/config.php'); if(file_exists(PATH_ROOT . 'config/config.php')) { //加载公共配置 $common_config = require_once(PATH_ROOT . 'config/config.php'); sephp::$_config = array_merge(sephp::$_config, $common_config); } if(file_exists(PATH_APP . 'config/config.php')) { //加载项目配置 $app_config = require_once(PATH_APP . 'config/config.php'); sephp::$_config = array_merge(sephp::$_config, $app_config); } } if(empty($key)) { return sephp::$_config; } return isset(sephp::$_config[$key]) ? sephp::$_config[$key] : null; } /** * 设置配置参数 name 为数组则为批量设置 * @access public * @param string|array $key 配置参数名(支持二级配置 . 号分割) * @param mixed $value 配置值 * @param string $range 作用域 * @return mixed */ public static function set($key, $value = null, $type = 'mysql') { if(empty($key)) { return false; } if($type == 'mysql') { if(db::delete(self::$table)->where('key',$key)->execute() === false) { return false; } $data = ['key'=>$key,'value'=>json_encode($value,JSON_UNESCAPED_UNICODE)]; if(db::insert(self::$table)->set($data)->execute() === false) { return false; } return true; } else { sephp::$_config[$key] = $value; return true; } } /** * 重置配置参数 * @access public * @param string $range 作用域 * @return void */ public static function reset($range = '') { $range = $range ?: self::$range; if (true === $range) { self::$config = []; } else { self::$config[$range] = []; } } } <file_sep><?php namespace sephp\core\lib; /** * zip打包解压类 * * 使用方法: pub_zip::add(PATH_ROOT.'/zip_test_dir'); pub_zip::add(PATH_ROOT.'/111.jpg'); pub_zip::zip(PATH_ROOT.'/test_tmp.zip'); pub_zip::close(); pub_zip::unzip(PATH_ROOT.'/encrypt_test.zip', PATH_ROOT.'/decrypt_test.zip', $ret['key'], $ret['iv']); * * @version 2.7.0 * @copyright 1997-2017 The PHP Group * @author seatle <<EMAIL>> * @created time :2017-12-07 */ class zip { private static $archive = null; private static $files = array(); public static function zip($zip_name) { if (empty(self::$files)) { return false; } self::$files = array_unique(self::$files); if( self::$archive == null ) { self::$archive = new ZipArchive(); if ( !self::$archive->open($zip_name, ZipArchive::CREATE|ZipArchive::OVERWRITE) ) { trigger_error("ZipArchive open file failed"); } } foreach (self::$files as $file) { $info = pathinfo($file); self::$archive->addFile($file, $info['basename']); //self::$archive->renameName($file, $info['basename']); } return self::$archive; } public static function add($path) { if(is_dir($path)) { $files = util::scandir($path); foreach ($files as $file) { self::add("{$path}/{$file}"); } } else { self::$files[] = $path; } } public static function close() { self::$files = array(); self::$archive->close(); self::$archive = null; return true; } } <file_sep><?php header('Content-Type: text/html; charset=utf-8'); require_once __DIR__ . '/../sephp/sephp.php'; define('PATH_APP',__DIR__.'/'); define('APP_NAME','index'); define('APP_DEBUG',true); /** * 配置载入 */ $_authority = [ 'need_login' => true, 'login_type' => 'session', 'not_login' => ['index', 'goods'], 'login_url' => '?ct=index&ac=login', 'user_type' => 'member', 'power_check'=> false, ]; new \sephp\sephp($_authority); <file_sep><?php namespace sephp; use sephp\sephp; use sephp\core\req; use sephp\core\log; use sephp\core\error; class func { /** * 打印s q l语句 * @Author GangKui * @DateTime 2019-10-22 * @return [type] [description] */ public static function dump_sql() { print_r(\sephp\core\db::$queries); exit(); } /** * 递归的删除文件或者目录 * @Author GangKui * @DateTime 2019-10-17 * @param [type] $target_dir [description] * @return [type] [description] */ public static function del_dir_file($target_dir) { if (is_dir($target_dir) && $handle = @opendir($target_dir)) { while (($file = readdir($handle)) !== false) { if (($file == ".") || ($file == "..")) { continue; } if (is_dir($target_dir . '/' . $file)) { // 递归 del_dir_file($target_dir . '/' . $file); } else { unlink($target_dir . '/' . $file); // 删除文件 } } @closedir($handle); rmdir($target_dir); } } /** * 数据XML编码 * @param mixed $data 数据 * @return string */ public static function data_to_xml($data) { $xml = ''; foreach ($data as $key => $val) { is_numeric($key) && $key = "item id=\"$key\""; $xml .= "<$key>"; $xml .= (is_array($val) || is_object($val)) ? self::data_to_xml($val) : self::xmlSafeStr($val); list($key,) = explode(' ', $key); $xml .= "</$key>"; } return $xml; } /** * 将 xml数据转换为数组格式。 * @Author GangKui * @DateTime 2019-10-24 * @param [type] $xml [description] * @return [type] [description] */ public static function xml_to_array($xml) { $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/"; if(preg_match_all($reg, $xml, $matches)) { $count = count($matches[0]); for($i = 0; $i < $count; $i++) { $subxml= $matches[2][$i]; $key = $matches[1][$i]; if(preg_match( $reg, $subxml )) { $arr[$key] = $this-> xml_to_array( $subxml ); } else { $arr[$key] = $subxml; } } } return $arr; } /** * 目录不存在就创建 * @Author GangKui * @DateTime 2019-10-16 * @return [type] [description] */ public static function path_exists($path) { $pathinfo = pathinfo ( $path . '/tmp.txt' ); if ( !empty( $pathinfo ['dirname'] ) ) { if (file_exists ( $pathinfo ['dirname'] ) === false) { if (@mkdir ( $pathinfo ['dirname'], 0777, true ) === false) { return false; } } } return $path; } /** * 返回j son数据 * @Author GangKui * @DateTime 2019-10-22 * @param [type] $data [description] * @return [type] [description] */ public static function return_json($data) { exit(json_encode($data, JSON_UNESCAPED_UNICODE)); } /** * 把字符串转换成数字 * @Author GangKui * @DateTime 2019-10-16 * @param [type] $str [description] * @param integer $maxnum [description] * @return [type] [description] */ public static function str_to_number($str, $maxnum = 128) { // 位数 $bitnum = 1; if ($maxnum >= 100) { $bitnum = 3; } elseif ($maxnum >= 10) { $bitnum = 2; } // sha1:返回一个40字符长度的16进制数字 $str = sha1(strtolower($str)); // base_convert:进制建转换,下面是把16进制转成10进制,方便做除法运算 // str_pad:把字符串填充为指定的长度,下面是在左边加0,共 $bitnum 位 $str = str_pad(base_convert(substr($str, -2), 16, 10) % $maxnum, $bitnum, "0", STR_PAD_LEFT); return $str; } /** * 注册结束执行函数 * @param $class_name 类名称 * @param $method_name 方法名称 * @param array $param 参数 */ public static function set_shutdown_func($class_name, $method_name,$param = []) { $array = [ 'func' => [$class_name,$method_name], 'params' => $param, ]; array_push(error::$shutdown_func, $array); } /** * 获得国家代码 * @param string $ip * @return void */ public static function get_country($ip = '') { // 如果是通过IP来获取城市地址的 $ip = empty($ip) ? func::get_client_ip() : $ip; $ip_country_file = PATH_LIB . 'assets/IP-COUNTRY-ISP.BIN'; if (!file_exists($ip_country_file)) { new Exception('file [' . $ip_country_file . '] not found'); } $db = new pub_ip2location($ip_country_file, pub_ip2location::FILE_IO); $records = $db->lookup($ip, array(pub_ip2location::COUNTRY_CODE)); return strtoupper($records['countryCode']); } /** * 获得当前的Url */ public static function get_cururl() { if(!empty($_SERVER["REQUEST_URI"])) { $scriptName = $_SERVER["REQUEST_URI"]; $nowurl = $scriptName; } else { $scriptName = $_SERVER["PHP_SELF"]; $nowurl = empty($_SERVER["QUERY_STRING"]) ? $scriptName : $scriptName."?".$_SERVER["QUERY_STRING"]; } return $nowurl; } public static function is_html5() { $rs = true; if(!empty($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")) { preg_match("#msie (\d+)#i", $_SERVER['HTTP_USER_AGENT'], $out); $version = empty($out[1]) ? 10 : intval($out[1]); if ($version < 9) { $rs = false; } } return $rs; } /** * 通关ua判断是否为手机 * @return bool */ public static function is_mobile() { //正则表达式,批配不同手机浏览器UA关键词。 $regex_match = "/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|"; $regex_match .= "htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|"; $regex_match .= "blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|"; $regex_match .= "symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|"; $regex_match .= "jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320×320|240×320|176×220"; $regex_match .= "|mqqbrowser|juc|iuc|ios|ipad"; $regex_match .= ")/i"; return isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']) or preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT'])); } public static function get_referrer($gourl = '') { $gourl = empty($_SERVER['HTTP_REFERER']) ? $gourl : $_SERVER['HTTP_REFERER']; return $gourl; } /** * 打印调试 * @param null $arg * @param null $arg1 * @param null $arg2 * @param null $arg3 */ public static function p($arg = null,$arg1 = null,$arg2 = null,$arg3 = null) { echo '<pre>'; var_dump($arg); empty($arg1)?'':var_dump($arg1); empty($arg2)?'':var_dump($arg2); empty($arg3)?'':var_dump($arg3); echo '</pre>'; } /** * 获取客户端当前IP地址 * @return string */ public static function get_client_ip() { if(!empty($_SERVER["HTTP_CLIENT_IP"])) { $cip = $_SERVER["HTTP_CLIENT_IP"]; } else if(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) { $cip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } else if(!empty($_SERVER["REMOTE_ADDR"])) { $cip = $_SERVER["REMOTE_ADDR"]; } else { $cip = ''; } //preg_match("/[\d\.]{7,15}/", $cip, $cips); //$cip = isset($cips[0]) ? $cips[0] : 'unknown'; //unset($cips); return $cip; } /** *@todo: 判断是否为post */ public static function is_post() { return isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD'])=='POST'; } /** *@todo: 判断是否为get */ public static function is_get() { return isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD'])=='GET'; } /** *@todo: 判断是否为ajax */ public static function is_ajax() { return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtoupper($_SERVER['HTTP_X_REQUESTED_WITH']) == 'XMLHTTPREQUEST'); } /** *@todo: 判断是否为命令行模式 */ public static function is_cli() { return preg_match("/cli/i", PHP_SAPI) ? true : false; } /* 格式化文件显示大小 * @param int $bytes 字节 * @return string * @author Meixi */ public static function size_format($bytes) { if ($bytes > 1024*1024*1024*1024) { return round($bytes/(1024*1024*1024*1024), 1)."TB"; } elseif ($bytes > 1024*1024*1024) { return round($bytes/(1024*1024*1024), 1)."GB"; } elseif ($bytes > 1024*1024) { return round($bytes/(1024*1024), 1)."MB"; } elseif ($bytes > 1024) { return round($bytes/(1024), 1)."KB"; } else { return $bytes."B"; } } /** * 压缩一个文件的内容 * @param $src_name 源文件 * @param $dst_name 目标文件 */ public static function compress($src_name, $dst_name) { $fp = fopen($src_name, "r"); $data = fread ($fp, filesize($src_name)); fclose($fp); $zp = gzopen($dst_name, "w9"); gzwrite($zp, $data); gzclose($zp); } /** * 变量替换 * @Author han * @param [type] $format_data 带{xxx}的字符串 * @param array $params key value数组 */ public static function sprintf($format_data, $params = []) { // 替换变量 $find_arr = []; $replace_arr = []; foreach ($params as $key => $param) { $find_arr[] = '{'. $key .'}'; $replace_arr[] = $param; } $string = str_replace($find_arr, $replace_arr, $format_data); return $string; } /** * 获取类命 * @Author han * @param [type] $class [description] * @return [type] [description] */ public static function get_class_name($class) { $class = explode('\\', $class); return array_pop($class); } /** * 生产唯一ID * @Author GangKui * @DateTime 2019-10-24 * @return [type] [description] */ public static function make_uniqid($type = false) { list($usec, $sec) = explode(" ", microtime()); if($type) { return $sec . round($usec * 100000) . self::random('numeric', 4); } return date('ymdHis') . round($usec * 10000) . self::random('numeric', 3); } /** * 获取不重复的ID(只是保证当前字典中不重复,所以订单号加上当前的年月日时分秒就肯定不会重复) * @Author han * @param string $type 类型 * @param integer $num 随机位数 * @param string $action get/create * @return mix 返回唯一ID */ public static function uniqid($type = 'numeric', $num = 7, $action = 'get') { $max_num = 1000; //一次创建唯一ID数量 $key = sprintf('%s:%s_%d', __FUNCTION__, $type, $num); $lock_name = 'lock:'.$key; //创建订单号 if( $action == 'create' ) { //声明静态变量,防止高并发统一进程出现重复 static $ids = []; for($i = 1; $i <= $max_num; $i++) { while( true ) { $id = self::random($type, $num); if( !isset($ids[$id]) ) { $ids[$id] = 1; break; } } //加入到字典 cls_redis::instance()->sAdd($key, $id); } //删除锁 cls_redis_lock::unlock($lock_name, true); } //抛出一个id,没有没有了就重新取max_num条出来 else if( false == ($id = cls_redis::instance()->sPop($key)) ) { $id = self::random($type, $num); //进程结束后批量创建ID if( false != cls_redis_lock::lock($lock_name, 0, 30) ) { self::shutdown_function( ['common\func\pub_func', 'uniqid'], [$type, $num, 'create'] ); } } return $id; } public static function floatval($data) { if (is_array($data)) { foreach ($data as $k => $v) { $data[$k] = self::floatval($data[$k]); } } else { $data = floatval($data); } return $data; } public static function intval($data) { if (is_array($data)) { foreach ($data as $k => $v) { $data[$k] = self::intval($data[$k]); } } else { $data = intval($data); } return $data; } public static function new_addslashes($string) { if (!is_array($string)) { return addslashes($string); } foreach ($string as $key => $val) { $string[$key] = self::new_addslashes($val); } return $string; } public static function new_stripslashes($string) { if (empty($string)) { return $string; } if (!is_array($string)) { return stripslashes($string); } foreach ($string as $key => $val) { $string[$key] = self::new_stripslashes($val); } return $string; } public static function htmlentities($data) { if (is_array($data)) { foreach ($data as $k => $v) { $data[$k] = self::htmlentities($data[$k]); } } else { //同时转义双,单引号 $data = htmlspecialchars(trim($data), ENT_QUOTES); } return $data; } public static function data_index($data, $index) { if (!is_array($data) || empty($index)) { return $data; } $tmp = array(); foreach ($data as $v) { $tmp[$v[$index]] = $v; } return $tmp; } /** * @Author han * @DateTime 2018-07-09T11:17:40+0700 * 该函数用于过滤,设置默认值,执行回掉函数,用于对用户提交的数据进行处理 * pub_func::data_filter(array( * 'bill_id' => ['type' => 'int', 'default' => pub_func::make_bill_id(), 'callback' => 'abs', 'max' => 19], * 'amount' => ['type' => 'float', 'default' => '0.01', 'callback' => 'abs'], * 'currency_code' => 'text' * ), $data); * @param array * @param array * @param boolean * @return array */ public static function data_filter($filter, $data, $magic_slashes = true) { if ($magic_slashes) { //去掉魔法引号 $data = self::new_stripslashes($data); } if (!empty($filter['_config_'])) { $ext_config = $filter['_config_']; unset($filter['_config_']); } $ret = array(); foreach ($filter as $field => $config) { $default = null; $is_array = false; if (is_array($config)) { $is_array = true; if (!empty($config['required'])) { if (!isset($data[$field])) { return $field; } } if (!empty($config['empty'])) { if (empty($data[$field])) { return $field; } } if (!empty($config['filter'])) {//递归 $ret[$field] = isset($data[$field]) ? self::data_filter($config['filter'], (array)$data[$field], false) : array(); continue; } $type = isset($config['type']) ? $config['type'] : 'text'; if (isset($config['default'])) { $default = $config['default']; } } else { $type = $config; $config = array(); } //过滤空项 if ( ( //去掉为null的值 !empty($ext_config['filter_null']) && null === $default && (!isset($data[$field])) ) || (//去掉非0空值 !empty($ext_config['filter_empty']) && null === $default && (!isset($data[$field]) || (isset($data[$field]) && $data[$field] !== 0 && empty($data[$field]))) ) || (//去掉指定字段空值 !empty($ext_config['filter_fields']) && in_array($field, (array)$ext_config['filter_fields']) && empty($data[$field]) ) ) { //存在忽略字段 if ( !isset($ext_config['exclude_fields']) || (isset($ext_config['exclude_fields']) && !in_array($field, (array)$ext_config['exclude_fields'])) ) { continue; } } switch ($type) { case 'bool_int': $ret[$field] = empty($data[$field]) ? 0 : 1; break; case 'bool': $ret[$field] = !empty($data[$field]) ? true : false; break; case 'int': $ret[$field] = isset($data[$field]) ? self::intval($data[$field]) : $default; if ($is_array && isset($config['min'])) { $ret[$field] = max($config['min'], $ret[$field]); } if ($is_array && isset($config['max'])) { $ret[$field] = min($config['max'], $ret[$field]); } break; case 'float': case 'double': $ret[$field] = isset($data[$field]) ? self::floatval($data[$field]) : $default; if ($is_array && isset($config['min'])) { $ret[$field] = max($config['min'], $ret[$field]); } if ($is_array && isset($config['max'])) { $ret[$field] = min($config['max'], $ret[$field]); } break; case 'html': $ret[$field] = isset($data[$field]) ? $data[$field] : $default; break; case 'json': $ret[$field] = isset($data[$field]) ? json_encode($data[$field]) : $default; $ret[$field] = addslashes($ret[$field]); break; case 'serialize': $ret[$field] = isset($data[$field]) ? serialize($data[$field]) : $default; $ret[$field] = addslashes($ret[$field]); break; case 'regex': if (!isset($config['regex'])) { continue; } $replace = isset($config['replace']) ? $config['replace'] : ''; $ret[$field] = isset($data[$field]) ? preg_replace($config['regex'], $replace, $data[$field]) : $default; break; case 'callback': if ( isset($data[$field]) && !empty($config['callback']) && is_callable($config['callback']) ) { $ret[$field] = call_user_func($config['callback'], $data[$field]); } else { $ret[$field] = $default; } break; //add by alex ,array 不做任何处理 case 'array': $ret[$field] = isset($data[$field]) ? $data[$field] : $default; break; case 'text': default: $ret[$field] = isset($data[$field]) ? self::htmlentities($data[$field]) : $default; if (!is_array($ret[$field])) { $ret[$field] = trim($ret[$field]); $charset = !empty($config['charset']) ? $config['charset'] : 'utf-8'; if ( !empty($config['from_charset']) && !mb_check_encoding($ret[$field], $charset) && $to = mb_detect_encoding($ret[$field], $config['from_charset']) ) { $ret[$field] = mb_convert_encoding($ret[$field], $charset, $to); } if (!empty($config['length'])) { $ret[$field] = mb_substr( $ret[$field], 0, $config['length'], $charset ); } } break; } if (!empty($ret[$field]) && !empty($config['callback']) && is_callable($config['callback'])) {//过滤后回调 if (is_array($ret[$field])) { $ret[$field] = array_map($config['callback'], $ret[$field]); } else { $ret[$field] = call_user_func($config['callback'], $ret[$field]); } } } return $ret; } //创建树形结构 public static function array_to_tree($arr_data, $str_child_id = 'id', $str_parent_id = 'pid', $str_node_name = 'nodes', &$arr_result = null) { if (!is_array($arr_data)) { return []; } foreach ($arr_data as $key => $val)//初始化$str_node_name,保证元素都有$str_node_name { $arr_data[$key][$str_node_name] = array(); $arr_result[$val[$str_child_id]] = &$arr_data[$key]; } $arr_tree = array();//用于保存树状数据 foreach ($arr_data as $offset => $row) { $int_parent_id = $row[$str_parent_id]; if (!empty($int_parent_id)) { if (!isset($arr_result[$int_parent_id])) { $arr_tree[] = &$arr_data[$offset]; continue; } $arr_parent = &$arr_result[$int_parent_id]; $arr_parent[$str_node_name][] = &$arr_data[$offset]; //把$arr_data[$offset]转移到父元素$arr_parent[$str_node_name]下面 } else { $arr_tree[] = &$arr_data[$offset]; } } return $arr_tree; } /** * 不同时区时间转换 * @param array $data * pub_func::time_convert([ * 'datetime' => KALI_TIMESTAMP,//可以是时间格式或者时间戳 * 'from_timezone' => 'ETC/GMT-7',//默认为系统设置的时区,即 ETC/GMT * 'to_timezone' => 'ETC/GMT-8',//转换成为的时区,默认获取用户所在国家对应时区 * 'format' => ''//格式化输出字符串。默认为Y-m-d H:i:s * 'default' => 表示没有为空的时候,默认实现的字符串,默认为- * ]); * * 一般直接使用 pub_func::time_convert(['datetime' => xxxxx]); * @return string */ public static function time_convert($data = array()) { $data_default = [ 'datetime' => KALI_TIMESTAMP, 'format' => 'Y-m-d H:i:s', 'from_timezone' => null, 'to_timezone' => null, ]; $configs = []; foreach ($data_default as $f => $ff) { $configs[$f] = isset($data[$f]) ? $data[$f] : $ff; } $default = isset($data['default']) ? $data['default'] : '-'; if (empty($data['datetime'])) { return $default; } return call_user_func_array(['kali\core\util', 'to_timezone'], $configs); if (defined('IN_ADMIN') && empty($data['to_timezone'])) { $data['to_timezone'] = $GLOBALS['config']['timezone_set']; } $default = isset($data['default']) ? $data['default'] : '-'; if (empty($data['datetime'])) { return $default; } else { if (empty($data['to_timezone']))//获取用户所在国家对应时区 { include_once PATH_CONFIG . '/inc_timezone.php'; if (isset($GLOBALS['config']['timezones'][COUNTRY])) { $data['to_timezone'] = $GLOBALS['config']['timezones'][COUNTRY]; } } } $datetime = empty($data['datetime']) ? KALI_TIMESTAMP : $data['datetime']; $datetime = is_numeric($datetime) ? '@' . $datetime : $datetime; $from_timezone = empty($data['from_timezone']) ? $GLOBALS['config']['timezone_set'] : $data['from_timezone']; $to_timezone = empty($data['to_timezone']) ? 'ETC/GMT-7' : $data['to_timezone']; $format = empty($data['format']) ? 'Y-m-d H:i:s' : $data['format']; $date_obj = new DateTime($datetime, new DateTimeZone($from_timezone)); $date_obj->setTimezone(new DateTimeZone($to_timezone)); return $date_obj->format($format); } /** * @Author AZhang * @DateTime 2018/7/14-16:07 * * 把图片移动从临时文件夹到正式文件夹 * @param $pics */ public static function move_tmp_pic($pics) { $pics = (array)$pics; foreach ($pics as $pic) { $tmp_path = kali::$base_root . '/../uploads/tmp/' . $pic; $target_path = kali::$base_root . "/../uploads/image/" . $pic; //图片已存在 if (is_file($target_path)) { continue; } $res = self::copy_file($tmp_path, $target_path); if (!$res) { return $res; } } return true; } /** * @Author AZhang * @DateTime 2018/7/14-16:07 * * 复制文件 * @param $source_file * @param $target_file * * @return bool */ public static function copy_file($source_file, $target_file) { if (!file_exists($source_file)) { return false; } // 目录不存在创建目录 if (!is_dir(dirname($target_file))) { @mkdir(dirname($target_file)); } return @copy($source_file, $target_file); } /** * @Author AZhang * @DateTime 2018/7/14-16:08 * * 闪存post数据用于提交失败后恢复表单数据,保存请求数据到下次请求 * @param string $key * @param string $default * * @return bool|string */ public static function request_flash($key = '', $default = '') { $flash_key = 'request_flash'; if ($key === '__delete') { return setcookie($flash_key, '', KALI_TIMESTAMP - 1); } $flash_data = json_decode(base64_decode(req::cookie($flash_key)), true); if ($key === '__get_all') { return $flash_data; } // 获取闪存数据 if (!empty($key)) { if (empty(req::cookie($flash_key))) { return $default; } return isset($flash_data[$key]) ? $flash_data[$key] : $default; } // 保存post数据 if (req::method() === 'POST') { req::$forms['_count'] = 0; return setcookie($flash_key, base64_encode(json_encode(req::$forms)), KALI_TIMESTAMP + 3600); } if (!empty(req::cookie($flash_key))) { // 清除上次闪存数据 if ($flash_data['_count'] > 0) { return setcookie($flash_key, '', KALI_TIMESTAMP - 1); } else { $flash_data['_count']++; return setcookie($flash_key, base64_encode(json_encode($flash_data)), KALI_TIMESTAMP + 3600); } } } /** * @Author AZhang * @DateTime 2018/7/16-11:35 * * 发送手机验证码 * @param string $phone 手机号码 * @param string $tpl 内容模版 * @param int $expire 有效期,秒 * @param * * @return int * 1 成功 * -1 发送失败 */ public static function send_email($email, $subject, $body) { return cls_send_msg::send_email($email, $subject, $body); } /** * @Author AZhang * @DateTime 2018/7/16-17:54 * * 发送邮件验证码 * @param $email * @param $subject * @param $body_tpl 内容模板 * @param $expire 有效期,秒 * * @return int * 1 成功 * -1 发送失败 */ public static function send_email_code($email, $subject, $body_tpl = "", $expire = 30 * 60) { // 生成随机验证码 $code = self::random('numeric', 6); //todo 方便测试 $code = 123123; $body = str_replace('[code]', $code, $body_tpl); // 初始化邮箱类 $mail = new cls_mail(); $config = $GLOBALS['config']['send_email']; $mail->setServer($config['host'], $config['user'], $config['pass'], 465, true); $mail->setFrom($config['user']); // 设置发件人 $mail->setReceiver($email); // 设置收件人,多个收件人,调用多次 $mail->setMail($subject, $body); // 设置邮件主题、内容 $res = $mail->sendMail(); if (!$res) { // 发送失败 log::error($mail->error(), 'email'); return -1; } cls_redis::instance()->set($email . '-' . $code, 1, $expire); return 1; } /** * 浮点数不4舍5入,解决内存处理浮点数精度问题 * @param [float] $num 浮点数 * @param [int] $dot_len 保留位数 * @return [float] */ public static function float_format($num, $dot_len) { $dot_len = intval($dot_len) + 1; return (float)substr(sprintf("%.{$dot_len}f", $num), 0, -1); } /** * 编码 URL 字符串 * * @param string $gourl * @return string */ public static function url_encode($gourl = '') { $gourl = !empty($gourl) ? $gourl : empty($_SERVER['HTTP_REFERER']) ? '' : $_SERVER['HTTP_REFERER']; return urlencode(htmlspecialchars_decode($gourl, ENT_QUOTES)); } /*** * 解码已编码的 URL 字符串 * * @param string $gourl * @return string */ public static function url_decode($gourl = '') { return urldecode(htmlspecialchars_decode($gourl, ENT_QUOTES)); } /** * Creates a random string of characters * * @param string $type the type of string * @param int $length the number of characters * @return string the random string */ public static function random($type = 'alnum', $length = 16) { switch($type) { case 'basic': return mt_rand(); break; case 'alpha': $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'capital': $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'alnum': $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'numeric': $pool = '0123456789'; break; case 'nozero': $pool = '123456789'; break; case 'distinct': $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ'; break; case 'hexdec': $pool = '0123456789abcdef'; break; case 'unique': return md5(uniqid(mt_rand()) . getmypid() . microtime()); break; case 'sha1' : return sha1(uniqid(mt_rand(), true)); break; case 'uuid': $pool = array('8', '9', 'a', 'b'); return sprintf('%s-%s-4%s-%s%s-%s', static::random('hexdec', 8), static::random('hexdec', 4), static::random('hexdec', 3), $pool[array_rand($pool)], static::random('hexdec', 3), static::random('hexdec', 12)); break; case 'web': // 即使同一个IP,同一款浏览器,要在微妙内生成一样的随机数,也是不可能的 // 进程ID保证了并发,微妙保证了一个进程每次生成都会不同,IP跟AGENT保证了一个网段 return md5(getmypid().microtime().$_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']); break; case 'allstr': $output = ''; for ($i=0 ; $i < $length ; $i++ ) { $output .= chr(mt_rand(33,126)); } return $output; break; } $str = ''; if(!empty($pool)) { for ($i=0; $i < $length; $i++) { $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1); } } return $str; } /** * 数据脱敏 * @param $string 需要脱敏值 * @param int $start 开始 如果start为auto,则length则为length字符脱敏一次 * @param int $length 结束 和substr的length一样 * @param string $re 脱敏替代符号 * @return bool|string * 例子: * pub_func::data_mask('15999705411', 3, 4); //159****5411 * pub_func::data_mask('我是中国人', 1, -1); //我**人 */ public static function data_mask($string, $start = 0, $length = 0, $re = '*') { if (empty($string)) { return false; } $arr = array(); $mb_strlen = mb_strlen($string); //自动获取开始和长度 if ($start === 'auto' && !empty($length)) { $length = max(3, abs($length)); $start = floor($mb_strlen / $length); $length = -$start; } //循环把字符串变为数组 while ($mb_strlen) { $arr[] = mb_substr($string, 0, 1, 'utf8'); $string = mb_substr($string, 1, $mb_strlen, 'utf8'); $mb_strlen = mb_strlen($string); } $strlen = count($arr); $begin = $start >= 0 ? $start : ($strlen - abs($start)); $end = $last = $strlen - 1; if ($length > 0) { $end = $begin + $length - 1; } elseif ($length < 0) { $end -= abs($length); } for ($i = $begin; $i <= $end; $i++) { $arr[$i] = $re; } // if ( // $begin >= $end || // $begin >= $last || // $end > $last // ) return false; return implode('', $arr); } /** * 格式化输出api信息 * config => [ * 'keypath' => 值的keypath * 'default' => 默认值 * 'data' => 自定义值 * 'desensitization' => ture/false/array 是否脱敏 如果传array则是脱敏配置['start' => 1, 'length' => 1, 're' => '*'] * 'alias' => 字段别名 * ] * $arr = ['a' => '1132312312312', 'b' => '22222222', 'c' => 'adsasdasd']; * $xx = pub_func::format_data($arr, [ * //字段 => 是否脱敏 * 'a' => true, * 'b' => ['start' => 1, 'length' => -2], * 'c' => false, * 'd' => ['data' => 'asdasdasd'] * ]); * @param array $data 原始数据 * @param array $data_config 字段配置 * @return array 返回制定的字段 */ public static function format_data($data = [], $data_config = []) { $ret = []; foreach ($data_config as $f => $config) { $keypath = isset($config['keypath']) ? $config['keypath'] : $f; $ret[$f] = pub_func::get_value( $data, $keypath, pub_func::get_value((array)$config, 'default') ); if (isset($config['data'])) //自己输入值 { $ret[$f] = $config['data']; } else { if ( //取数组值 (is_bool($config) && !empty($config)) || //直接传bool (!empty($config['desensitization'])) //没有声明no_desensitization ) { $default = [ 'start' => 'auto', 'length' => 4, 're' => '*' ]; if (is_array($config['desensitization'])) { foreach ($default as $_k => $_v) { if (isset($config['desensitization'][$_k])) { $default[$_k] = $_v; } } } array_unshift($default, $ret[$f]); $ret[$f] = call_user_func_array( ['common\func\pub_func', 'data_mask'], $default ); } } //别名 if (is_array($config) && isset($config['alias']) && is_string($config['alias'])) { $ret[$config['alias']] = $ret[$f]; unset($ret[$f]); } } return $ret; } /** * 尝试从数组/对象中获取值 * @param mixed $src 源 * @param string $key 键 array支持 keypath * @param mixed $default 默认值 * @param int mode 模式。0:使用 empty;1:使用 isset * @param callable $filter 对值进行过滤的函数 * @param bool $process_scalar 是否处理标量 * @return mixed */ public static function get_value($src, $key, $default = NULL, $mode = 0, $filter = NULL, $process_scalar = FALSE) { $value = NULL; if ($process_scalar) { if (is_scalar($src)) { $value = $src; } } if (is_array($src)) { $value = $src; $key_path = explode('/', $key); foreach ($key_path as $k) { if (isset($value[$k])) { $value = $value[$k]; } else { $value = $default; break; } } } if (is_object($src)) { $value = property_exists($src, $key) ? $src->$key : $default; } if ($mode === 0) { if (empty($value)) { $value = $default; } } else { if (!isset($value)) { $value = $default; } } if ($filter && is_callable($filter) && is_scalar($value)) { $value = call_user_func($filter, $value); } return $value; } /** * 尝试从数组/对象中获取整数值 * @param mixed $src 源 * @param string $key 键 * @param mixed $default 默认值 * @param int mode 模式。0:使用 empty;1:使用 isset; * @param bool $process_scalar 是否处理标量 * @return int */ public static function get_int_value($src, $key, $default = 0, $mode = 1, $process_scalar = FALSE) { return static::get_value($src, $key, $default, $mode, 'intval', $process_scalar); } /** * 打乱数组(保持键不变,用法和shuffle一致) * @param mixed $array * @return void * @author han * @created time :2018-11-14 19:06 */ public static function kshuffle(&$array) { if (!is_array($array) || empty($array)) { return false; } $tmp = array(); foreach ($array as $key => $value) { $tmp[] = array('k' => $key, 'v' => $value); } shuffle($tmp); $array = array(); foreach ($tmp as $entry) { $array[$entry['k']] = $entry['v']; } return true; } public static function md5_16($str) { return substr(md5($str), 8, 16); } /** * 发送短信 * @Author AZhang * @DateTime 2019/1/7-15:04 * @param $phone * @param $msg * * @return bool */ public static function send_sms($phone, $msg) { //发送短信 require_once kali::$app_root . '/../common/lib/twilio/Twilio.php'; $Twilio = new \Twilio(); return $Twilio->send_msg("+{$phone}", $msg); } //过滤emoji public static function remove_emoji($str) { $str = preg_replace_callback('/./u', function (array $match) { return strlen($match[0]) >= 4 ? '' : $match[0]; }, $str ); return $str; } /** * 简写pub_mod_currency::money_format函数 * @Author han * @param mix $money * @param string $currency * @param integer $dot_len * @return string */ public static function money_format($money, $currency = '', $dot_len = 0) { if( is_array($money) ) { $data = $money; $dot_len = $currency; } else { $data = [$currency => $money]; } return pub_mod_currency::money_format([ 'data' => $data, 'dot_len' => $dot_len, ]); } /** * 校验密码,必须包含大小写字母数字 * @Author AZhang * @DateTime 2019/1/11-20:34 * @param $pwd * * @return bool */ public static function verify_pwd($pwd) { if (preg_match('/[A-Z]+/', $pwd) === false) { return false; } if (preg_match('/[a-z]+/', $pwd) === false) { return false; } if (preg_match('/[0-9]+/', $pwd) === false) { return false; } return true; } /** * 向 SOCKET HTTP 服务器发送数据 * @param array $data * @param int $send_to 1: tcp; 2: websocket; 3: tcp+websocket * @return bool * Author: Nemo * Date: 2018/10/10 17:16:35 */ static function send_socket_http(array $data) { try { require_once __DIR__ . '/../../channel/src/Client.php'; $config = \kali\core\config::instance()->get('app_socket'); $channel_cfg = self::get_value($config, 'channel'); $host = self::get_value($channel_cfg, 'host', '0.0.0.0'); $port = self::get_value($channel_cfg, 'port', 0); if ($host == '0.0.0.0') { $host = '127.0.0.1'; } $data = is_array($data) ? json_encode($data) : $data; \Channel\Client::connect($host, $port); \Channel\Client::publish('http_api', $data); } catch (\Exception $e) { return false; } return true; } /** * curl 函数 * @Author han * @param [type] $data 请求参数 * data支持下面参数(只有url是必须的,其他都是可选的) * url url地址 * post 有的话就是post,没有就是get post的数据,可以是数组或者http_build_query后的值 * timeout 超时时间 * ip 伪造ip * referer 来源 * cookie 传递cookie * cookie_file cookie路径 * save_cookie cookie保存路径 * proxy 代理信息 * header http请求头 * debug 是否开启调试 * $tmp = pub_func::http_request(['url' => 'http://www.taobao.com']); * $tmp['body']就是返回的内容 * @param boolean $multi 是否并发模式 * $tmp = pub_func::http_request([ * ['url' => 'http://www.taobao.com'], * ['url' => 'http://www.baidu.com', 'post' => ['a' => 1, 'b' => 2] ], * ], true); * $tmp['body']就是返回的内容 * @return array curl执行结果 */ static public function http_request($data, $multi = false) { return \sephp\core\lib\curl::http_request($data, $multi); } /** * 签名 * @param array $data 要签名的数据 * @param string $app_key 参与签名的 key * @param array $exclude 要在 $data 中排除的键 * @return string 签名结果 * @Author: Nemo * @Date: 2018/12/05 16:35:39 */ public static function sign(array $data, $app_key, $exclude = ['ac', 'ct', 'sign']) { if ( !empty($exclude) && is_array($exclude)) { foreach ($exclude as $key) { unset($data[$key]); } } ksort($data); $query_str = http_build_query($data); $query_arr = explode('&', $query_str); //由于http_build_query会对参数进行一次urlencode,所以这里需要加多一层urldecode $query_arr = array_map(function ($item) {return urldecode($item);}, $query_arr); $sign_text = implode('&', $query_arr); $sign_text .= '&key=' . $app_key; return strtoupper(md5($sign_text)); } public static function get_os($platform = 'web') { $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null; if( !empty($user_agent) ) { $mua = [ 'ios' => '#iphone|ipad|ios#i', 'android' => '#android|\s+adr\s+#i' ]; foreach($mua as $plf => $regex) { if(preg_match($regex, $user_agent)) { $platform = $plf; break; } } } return $platform; } public static function safe_json_decode($json) { $object = json_decode($json); $array = self::parse_object($object); return $array; } public static function parse_object($object) { if(is_object($object)) { $object_arr = (array) $object; if(empty($object_arr)) { return $object; } $array = get_object_vars($object); } else if(is_array($object)) { $array = $object; } else { return $object; } foreach($array as $key => &$value) { $value = self::parse_object($value); } unset($value); return $array; } /** * 计算数组的md5 * @param $array * @return string */ public static function cal_array_hash($array) { $str = pub_func::array2str($array); return md5($str); } public static function array2str($array) { $str = ''; if(!is_array($array)) { $str = $array; } else { ksort($array); foreach($array as $key=>$value) { $str .= $key . pub_func::array2str($value); } } return $str; } /** * 结束执行,保存分析结果 */ public static function xhprof_end() { //你也可以手动结束执行,保存分析结果 $xhprof_data = xhprof_disable(); require_once kali::$app_root . "/../common/lib/xhprof/xhprof_lib.php"; require_once kali::$app_root . "/../common/lib/xhprof/xhprof_runs.php"; $xhprof_runs = new \XHProfRuns_Default(); $run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_foo"); } public static function close_db() { //log::info("close_db...."); db::close_all(); } public static function test2() { sleep(5); } } <file_sep><?php namespace common\model; use sephp\sephp; use sephp\func; use sephp\core\log; use sephp\core\db; use sephp\core\cache; use sephp\core\config; use sephp\core\lib\qrcode; /** * 订单model * @ClassName: pub_mod_goods * @Author: Gangkui * @Date: 2019-02-20 14:09:02 */ class pub_mod_order extends pub_mod_model { public static $_table = '#PB#_order', $_pk = 'order_id', $_fields = [ 'order_id' => ['type' => 'int', 'required' => true, 'comment' => '品牌ID'], 'order_sn' => ['type' => 'text', 'required' => true, 'comment' => '品牌ID'], 'qrcode' => ['type' => 'text', 'required' => true, 'comment' => '二维码code'], 'total_amount' => ['type' => 'int', 'required' => true, 'comment' => '订单货币总值'], 'cost_item' => ['type' => 'int', 'default' => 0, 'comment' => '订单商品总价格'], //订单商品总价格 'currency' => ['type' => 'text', 'default' => 'CNY', 'comment' => '订单支付货币'], //订单支付货币 'discount' => ['type' => 'int', 'default' => 0, 'comment' => '订单减免'], // 'pmt_goods' => ['type' => 'int', 'default' => 0, 'comment' => '商品促销优惠'], // 'pmt_order' => ['type' => 'int', 'default' => 0, 'comment' => '订单促销优惠'], // 'payed' => ['type' => 'int', 'default' => 0, 'comment' => '订单支付金额'], //订单支付金额 'cost_freight' => ['type' => 'int', 'default' => 0, 'comment' => '配送费用'], //配送费用 'cur_rate' => ['type' => 'int', 'default' => 0, 'comment' => '订单支付货币汇率'], //配送费用 'score_u' => ['type' => 'int', 'default' => 0, 'comment' => '订单使用积分'], //配送费用 'score_g' => ['type' => 'int', 'default' => 0, 'comment' => '订单获得积分'], //配送费用 'pay_status' => ['type' => 'text', 'default' => 0, 'comment' => '支付状态'], // 'ship_status' => ['type' => 'text', 'default' => 0, 'comment' => '配送状态'], // 'is_delivery' => ['type' => 'text', 'default' => 0, 'comment' => '折扣价格'], // 'status' => ['type' => 'int', 'default' => 1, 'comment' => ''], // 'payment' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'shipping_id' => ['type' => 'int', 'default' => 0, 'comment' => ''], //x 'shipping' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'member_id' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'confirm' => ['type' => 'int', 'default' => 1, 'comment' => '订单确认状态'], //x 'ship_area' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'ship_name' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'weight' => ['type' => 'int', 'default' => 0, 'comment' => ''], //x 'tostr' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'itemnum' => ['type' => 'int', 'default' => 1, 'comment' => ''], //x 'ship_addr' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'ship_zip' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'ship_tel' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'ship_email' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'ship_time' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'ship_mobile' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'is_tax' => ['type' => 'int', 'default' => 1, 'comment' => ''], //x 'tax_type' => ['type' => 'int', 'default' => 1, 'comment' => ''], //x 'tax_content' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'cost_tax' => ['type' => 'int', 'default' => 0, 'comment' => ''], //x 'tax_company' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'extend' => ['type' => 'text', 'default' => null, 'comment' => '订单扩展'], //x 'addon' => ['type' => 'text', 'default' => null, 'comment' => '订单附属信息(序列化)'], //x 'memo' => ['type' => 'text', 'default' => null, 'comment' => '订单附言'], //x 'mark_type' => ['type' => 'text', 'default' => null, 'comment' => '订单备注图标'], //x 'mark_text' => ['type' => 'text', 'default' => null, 'comment' => '订单备注'], //x 'disabled' => ['type' => 'int', 'default' => 1, 'comment' => ''], //x 'ip' => ['type' => 'text', 'default' => null, 'comment' => ''], //x 'adduser' => ['type' => 'text', 'required' => false, 'default' => '', 'comment' => '添加人'], // 'addtime' => ['type' => 'int', 'required' => false, 'default' => '', 'comment' => '添加时间'], // 'upuser' => ['type' => 'text', 'default' => 0, 'comment' => '更新人'], // 'uptime' => ['type' => 'int', 'default' => 0, 'comment' => '更新时间'], // 'deltime' => ['type' => 'int', 'default' => 0, 'comment' => '删除时间'], // 'deluser' => ['type' => 'int', 'default' => 0, 'comment' => '删除人'], // ], $status = [ '1' => '激活中', '2' => '过期/作废', '3' => '已完成', ], $confirm = [ '1' => '未确认', '2' => '已确认', ], $is_tax = [ '1' => '不开发票', '2' => '需要发票', ], $tax_type = [ '1' => '无', '2' => '个人', '3' => '公司', ], $disabled = [ '1' => '启用', '2' => '禁用', ]; /** * 订单状态 */ const STATUS_ACTION = 1; const STATUS_DEAD = 2; const STATUS_FINISH = 3; /** * 利用雪花算法生成一个分布式的唯一ID * @Author GangGuoer * @DateTime 2019-10-31T00:22:37+0700 * @version [version] * @param integer * @return [type] */ public static function create_qrcode($len = 32) { $id = \sephp\core\lib\snowflake::instance(1)->id(); return md5(func::random('alnum', 5) . $id . func::random('alnum', 5)); } /** * 生成二维码图片 * @Author GangKui * @DateTime 2019-11-13 * @param [type] $qrcode [description] * @return [type] [description] */ public static function create_qr_img($qrcode, $outfile = false) { $code = self::entcry_qrcode($qrcode); return qrcode::make([ 'frame' => $code,//表示生成的信息, 'outfile' => $outfile,//表示是否输出二维码图片文件(文件路径,包含图片名和后缀),默认false, 'level' => 1,//表示容错率,也就是有被覆盖的区域还能识别参数,0,1,2,3, 'size' => 6,//表示二维码的大小, 'margin' => 2,//表示二维码的边距大小, 'saveandprint' => false,//表示是否保存二维码,默认FALSE ]); } /** * 格式化订单数据 * @Author GangKui * @DateTime 2019-11-05 * @param [type] $data [description] * @return [type] [description] */ public static function data_format($data) { if(!is_array($data)) return $data; $tmp = is_array(reset($data)) ? $data : [$data]; $member_ids = array_column($tmp, 'member_id'); if(!empty($member_ids)) { $member_info = pub_mod_member::getlist([ 'where' => [pub_mod_member::$_table.'.member_id' , '=', $member_ids], 'joins' => [ 'type' => 'left', 'table' => pub_mod_member_pam::$_table, 'where' => [pub_mod_member_pam::$_table.'.member_id', '=', pub_mod_member::$_table.'.member_id'] ], 'field' => [pub_mod_member::$_table.'.member_id','username', 'nickname', 'realname', 'mobile'], ]); $member_info = array_column($member_info, null, 'member_id'); } foreach ($tmp as &$v) { if(!empty($v['addtime'])) { $v['show_addtime'] = date('Y-m-d H:i', $v['addtime']); } if(!empty($v['status'])) { $v['show_status'] = self::$status[$v['status']]; } if(!empty($v['pay_status'])) { $v['show_pay_status'] = pub_mod_payments::$status[$v['pay_status']]; } if(!empty($v['member_id']) && !empty($member_info[$v['member_id']])) { $v['member_name'] = $member_info[$v['member_id']]['username']; $v['mobile'] = $member_info[$v['member_id']]['mobile']; } } return is_array(reset($data)) ? $tmp : reset($tmp); } /** * 加密二维码 * @Author GangKui * @DateTime 2019-11-13 * @return [type] [description] */ public static function entcry_qrcode($qrcode) { $str = ''; foreach (str_split($qrcode) as $k => $s) { $tmp_str = func::random('alnum', 3); $str .= substr_replace($tmp_str, $s, ($k%3), 1); } return func::random('alnum', 8) . $str . func::random('alnum', 8); } /** * 解密二维码 * @Author GangKui * @DateTime 2019-11-13 * @return [type] [description] */ public static function decry_qrcode($qrcode) { $str = ''; $qrcode = str_split(substr($qrcode, 8, 96), 3); foreach ($qrcode as $k => $s) { $str .= substr($s, ($k%3), 1); } return $str; } } <file_sep><?php namespace sephp\core\lib; use sephp\sephp; /** * 二维码, 条码 生成类 */ class qrcode { /** * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本,具体可以查看二维码数据格式】 * @Author GangKui * @DateTime 2019-10-08 * @param [type] $conds * [ * frame => 二维码包含的信息,可以是数字、字符、二进制信息、汉字。 不能混合数据类型,数据必须经过UTF-8 URL-encoded * widht => 生成二维码的尺寸设置 * height => 生成二维码的尺寸设置 * level => 可选纠错级别,QR码支持四个等级纠错,用来恢复丢失的、读错的、模糊的、数据。 * L-默认:可以识别已损失的7%的数据 * M-可以识别已损失15%的数据 * Q-可以识别已损失25%的数据 * H-可以识别已损失30%的数据 * margin => 生成的二维码离图片边框的距离 * * ] * @return [type] [description] */ public static function google_api($conds = []) { foreach (['frame'] as $f) { if(empty($conds[$f])) { throw new \Exception("Create QRcode by google api ,'{$f} param is error", 100); } $$f = $conds[$f]; } $widht = $conds['width'] ?? '200'; $height = $conds['height'] ?? '200'; $level = $conds['level'] ?? 'L'; $margin = $conds['margin'] ?? 0; $frame = urlencode($frame); $google_api_url = 'http://chart.apis.google.com/chart?'; return $google_api_url . 'chs='.$widht.'x'.$height.'&cht=qr&chld='.$level.'|'.$margin.'&chl='.$frame; } /** * 搜狐二维码生成接口 * @Author GangKui * @DateTime 2019-10-10 * @param array $conds [description] * @return [type] [description] */ public static function souhu_api($conds = []) { foreach (['frame'] as $f) { if(empty($conds[$f])) { throw new \Exception("Create QRcode by google api ,'{$f} param is error", 100); } $$f = $conds[$f]; } $widht = $conds['width'] ?? '200'; $height = $conds['height'] ?? '200'; $api_url = 'https://my.tv.sohu.com/user/a/wvideo/getQRCode.do?'; return $api_url . 'width='.$widht.'&height='.$height.'&text='.$frame; } /** * 利用qrcode 插件 生成二维码图片 * @Author GangKui * @DateTime 2019-10-09 * @param [type] $conds * [ * frame => 表示生成的信息, * outfile => 表示是否输出二维码图片文件(文件路径,包含图片名和后缀),默认false, * level => 表示容错率,也就是有被覆盖的区域还能识别参数,0,1,2,3, * size => 表示二维码的大小, * margin => 表示二维码的边距大小, * saveandprint => 表示是否保存二维码,默认FALSE * * ] * @return [type] [description] */ public static function make($conds = []) { foreach (['frame'] as $f) { if(empty($conds[$f])) { throw new \Exception("Create QRcode by qrcode.php, {$f} param is error", 100); } $$f = $conds[$f]; } $outfile = $conds['outfile'] ?? false; $level = $conds['level'] ?? 0; $size = $conds['size'] ?? 3; $margin = $conds['margin'] ?? 4; $saveandprint = $conds['saveandprint'] ?? false; include_once(PATH_LIB . 'QRcode/phpqrcode.php'); $image = \QRcode::png($frame, $outfile, $level, $size, $margin, $saveandprint); if(false === $outfile) { return $image; } else { return file_exists($outfile); } } /** * 利用qrcode 插件 生成条码图片 * @Author GangKui * @DateTime 2019-10-09 * @param [type] $conds * [ * frame => 表示生成的信息, * outfile => 表示是否输出二维码图片文件(文件路径,包含图片名和后缀),默认false, * level => 表示容错率,也就是有被覆盖的区域还能识别参数,0,1,2,3, * size => 表示二维码的大小, * margin => 表示二维码的边距大小, * saveandprint => 表示是否保存二维码,默认FALSE * * ] * @return [type] [description] */ public static function barcode($conds = []) { foreach (['frame'] as $f) { if(empty($conds[$f])) { throw new \Exception("Create QRcode by qrcode.php, {$f} param is error", 100); } $$f = $conds[$f]; } require_once(PATH_LIB . 'barcodegen/autoload.php'); // Loading Font $font = new \BarcodeBakery\Common\BCGFontFile(PATH_LIB . 'font/Arial.ttf', 18); // The arguments are R, G, B for color. $color_black = new \BarcodeBakery\Common\BCGColor(0, 0, 0); $color_white = new \BarcodeBakery\Common\BCGColor(255, 255, 255); $drawException = null; try { $code = new \BarcodeBakery\Barcode\BCGcode93(); $code->setScale(2); // Resolution $code->setThickness(30); // Thickness $code->setForegroundColor($color_black); // Color of bars $code->setBackgroundColor($color_white); // Color of spaces $code->setFont($font); // Font (or 0) $code->parse($frame); // Text } catch (Exception $exception) { $drawException = $exception; } /* Here is the list of the arguments 1 - Filename (empty : display on screen) 2 - Background color */ $drawing = new \BarcodeBakery\Common\BCGDrawing('', $color_white); if ($drawException) { $drawing->drawException($drawException); } else { $drawing->setBarcode($code); $drawing->draw(); } $drawing->setFilename($conds['outfile'] ?? false); //旋转角度 $drawing->setRotationAngle(0); // Header that says it is an image (remove it if you save the barcode to a file) if(empty($conds['outfile'])) { header('Content-Type: image/png'); header('Content-Disposition: inline; filename="barcode.png"'); } // Draw (or save) the image into PNG format. $img = $drawing->finish(\BarcodeBakery\Common\BCGDrawing::IMG_FORMAT_PNG); if(!empty($conds['outfile'])) { return file_exists($conds['outfile']); } } } <file_sep><?php namespace sephp\core; use sephp\sephp; use sephp\func; use sephp\core\log; /** * debug 截获 重组 * @ClassName: sys_debug * @Author: Gangkui * @Date: 2018-11-05 19:54:47 */ class error { /** * @var array php中止时执行的函数池 * [ * func => ['sephp\core\error', 'shutdown_handler'] * params => ['1231','1231231'] * ] */ public static $shutdown_func = []; /** * php中止时执行的函数 * shutdown_handler */ public static function shutdown_handler() { if(empty(self::$shutdown_func)) { return true; } function_exists('fastcgi_finish_request') && fastcgi_finish_request(); foreach(self::$shutdown_func as $v) { call_user_func_array($v['func'], $v['params']); } } /** * 错误接管函数 * trigger_error 直接到这里来 * throw new \Exception 先到handle_exception,再到这里来 * trigger_error 不会中断程序,只是警告,excetion会中断程序 */ public static function error_handler($code, $message, $file, $line, $vars) { self::show($code, $message, $file, $line, $vars); exit; } /** * 异常重定义 * @param $e */ public static function exception_handler($e) { self::show( $e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine(), $e->getTrace() ); } public static $html = '<script language=\'javascript\'>function debug_hidden_all() {document.getElementById(\'debug_errdiv\').style.display=\'none\';}function debug_close_all() {debug_hidden_all();document.getElementById(\'debug_ctl\').style.display=\'none\';}</script><div id="debug_ctl" style="background: #cc3a3a;width:100px;line-height:18px;position:absolute;top:2px;left:2px;border:1px solid #ccc; padding:1px;text-align:center"> <a href="javascript:;" onclick="javascript:document.getElementById(\'debug_errdiv\').style.display=\'block\';" style="font-size:12px;">[打开调试信息]</a> </div><div id="debug_errdiv" style="z-index:9999;width:80%;position:absolute;top:10px;left:8px;border:2px solid #ccc; background: #fff; padding:8px;display:none"><div style="line-height:24px; background: #FBFEEF;;"><div style="float:left"><strong>错误/警告信息追踪:</strong></div><div style="float:right"><a href="javascript:;" onclick="javascript:debug_close_all();" style="font-size:12px;">[关闭]</a><a href="javascript:;" onclick="javascript:debug_hidden_all();" style="font-size:12px;">[收起]</a></div><br style="clear:both"/></div>'; public static $error_file = null; public static $error_line = null; public static $error_code = null; public static function show($code, $msg, $filename, $line, $backtrace) { $filename = empty(self::$error_file) ? $filename : self::$error_file; $line = empty(self::$error_line) ? $line : self::$error_line; $code = empty(self::$error_code) ? $code : self::$error_code; $code_name = $code >= 100 ? '手动抛出' : '系统错误'; log::error($msg); $codes = file($filename); self::$html .= '<div style=\'font-size:14px;line-height:160%;border-bottom:1px dashed #ccc;margin-top:8px;\'>'; self::$html .= "发生环境:" . date("Y-m-d H:i:s", time()) . '::' . func::get_cururl() . "<br />\n"; self::$html .= "错误类型:" . $code_name . "<br />\n"; self::$html .= "出错原因:<font color='#3F7640'>" . $msg . "</font><br />\n"; self::$html .= "提示位置:<a href='" . str_replace(['%file%','%line%'], [$filename,$line], sephp::$_config['web']['edit_tool']) . "'>" . $filename . " 第 {$line} 行<br />\n"; self::$html .= "断点源码:<font color='#747267'>{$codes[$line-1]}</font><br />\n"; self::$html .= "详细跟踪:<br />\n"; array_shift($backtrace); //p($debug_backtrace);exit; $narr = ['class', 'type', 'function', 'file', 'line']; foreach ($backtrace as $i => $l) { if(empty($l['class'])) { continue; } self::$html .= "<font color='#747267'>[$i] In function {$l['class']}{$l['type']}{$l['function']} "; empty($l['file']) ? '' : self::$html .= " In <a href='" . str_replace(['%file%','%line%'], [$l['file'],$l['line']], sephp::$_config['web']['edit_tool']) . "' >{$l['file']}</a>"; empty($l['line']) ? '' : self::$html .= " on line {$l['line']} "; self::$html .= "</font><br />\n"; } //p($debug_backtrace); self::$html .= '</div><br style="clear:both"/></div>'; echo self::$html; } } <file_sep><?php namespace sephp\core; use sephp\sephp; /** * 处理外部请求变量的类 * * 禁止此文件以外的文件出现 $_POST、$_GET、$_FILES变量及eval函数(用 req::myeval ) * 以便于对主要黑客攻击进行防范 * * @author seatle<<EMAIL>> * @version 2.0 */ class req { // 用户的cookie public static $cookies = array(); // 把GET、POST的变量合并一块,相当于 _REQUEST public static $forms = []; // _GET 变量 public static $gets = []; // _POST 变量 public static $posts = []; // 文件变量 public static $files = []; /** * Raw input stream data * Holds a cache of php://input contents * * @var string */ private static $_raw_input_stream; /** * Parsed input stream data * Parsed from php://input at runtime * * @var array */ private $_input_stream; // url_rewrite public static $url_rewrite = false; // 严禁保存的文件名 public static $filter_filename = '/\.(php|pl|sh|js)$/i'; /** * 过滤器是否抛出异常 * (只对邮箱、用户名、qq、手机类型有效) * 如果不抛出异常,对无效的数据修改为空字符串 */ public static $throw_error = false; /** * 初始化用户请求 * 对于 post、get 的数据,会转到 selfforms 数组, 并删除原来数组 * 对于 cookie 的数据,会转到 cookies 数组,但不删除原来数组 */ public static function init() { //命令行模式 if( empty($_SERVER['REQUEST_METHOD']) ) { return false; } //$magic_quotes_gpc = ini_get('magic_quotes_gpc'); foreach (['get', 'post', 'cookie', 'file'] as $type) { $types = $type . 's'; self::$$types = self::_to_param($type); } //cls_security::init(); } //强制要求对gpc变量进行转义处理 public static function add_s( $str ) { // Is the string an array? if (is_array($str)) { foreach ($str as $key => &$value) { $str[$key] = self::add_s($value); } return $str; } $str = addslashes($str); return $str; } /** * 把 eval 重命名为 myeval */ public static function myeval( $phpcode ) { return eval( $phpcode ); } /** * 获得指定表单值 * * @param mixed $formname 表单名 * @param string $defaultvalue 默认值 * @param string $formattype 格式化类型 * @return mixed $return 返回值 * @author seatle <<EMAIL>> * @created time :2014-12-16 10:48 */ public static function item( $formname = '', $defaultvalue = null, $filter_type = '' ) { if( !isset(self::$forms[$formname]) || self::$forms[$formname] === '' ) { return $defaultvalue; } else { //filter::filter_execute(self::$forms[$formname], $filter_type, self::$throw_error); return self::$forms[$formname]; } } /** * 获得get表单值 */ public static function get( $formname = '', $defaultvalue = null, $filter_type = '' ) { if( !isset(self::$gets[$formname]) || self::$gets[$formname] === '' ) { return $defaultvalue; } else { return self::$gets[$formname]; } } /** * 获得post表单值 */ public static function post( $formname = '', $defaultvalue = null, $filter_type = '' ) { if( !isset(self::$posts[$formname]) || self::$posts[$formname] === '' ) { return $defaultvalue; } else { return self::$posts[$formname]; } } /** * 获得指定cookie值 */ public static function cookie( $key = '', $defaultvalue = null, $filter_type = '' ) { if( !isset(self::$cookies[$key]) || self::$cookies[$key] === '' ) { return $defaultvalue; } else { return self::$cookies[$key]; } } public static function input_stream($index = null, $default = null) { $input_stream = file_get_contents('php://input'); if ( func_num_args() === 0 ) { return $input_stream; } if ( !is_array($input_stream) ) { parse_str($input_stream, $input_stream); is_array($input_stream) || $input_stream = array(); } // 安全过滤 $magic_quotes_gpc = ini_get('magic_quotes_gpc'); if( !$magic_quotes_gpc ) $input_stream = self::add_s( $input_stream ); if (self::$config['global_xss_filtering']) $input_stream = cls_security::xss_clean($input_stream); return !isset($input_stream[$index]) ? $default : $input_stream[$index]; } public static function raw_input_stream() { isset(self::$_raw_input_stream) || self::$_raw_input_stream = file_get_contents('php://input'); return self::$_raw_input_stream; } /** * 把指定数据转化为路由数据 * @param $dfarr 默认数据列表 array( array(key, dfvalue)... ) * @param $datas 数据列表 * @param $method 方法 * @return boolean */ public static function assign_values(&$dfarr, &$datas, $method = 'GET') { $method = strtoupper( $method ); foreach($dfarr as $k => $v) { if( isset($datas[$k]) ) { req::$forms[ $v[0] ] = $datas[$k]; } else { req::$forms[ $v[0] ] = $v[1]; } //给值gets/posts if( $method == 'GET' ) { req::$gets[ $v[0] ] = req::$forms[ $v[0] ]; } else { req::$posts[ $v[0] ] = req::$forms[ $v[0] ]; } } } /** * 获得SERVER值 * * @param string $index 索引 * @param mixed $default 默认值 * @return string|array */ public static function server($index = null, $default = null) { if ( func_num_args() === 0 ) { return $_SERVER; } return !isset($_SERVER[strtoupper($index)]) ? $default : $_SERVER[strtoupper($index)]; } /** * 移动上传的文件 * $item 是用于当文件表单名为数组,如 upfile[] 之类的情况, $item 表示数组的具体键值,下同 * @return bool */ public static function move_upload_file( $formname, $filename, $item = '' ) { if( self::is_upload_file( $formname, $item ) ) { if( preg_match(self::$filter_filename, $filename) ) { return false; } else { if( $item === '' ) { if( PHP_OS == 'WINNT') return copy(self::$files[$formname]['tmp_name'], $filename); else return move_uploaded_file(self::$files[$formname]['tmp_name'], $filename); } else { if( PHP_OS == 'WINNT') return copy(self::$files[$formname]['tmp_name'][$item], $filename); else return move_uploaded_file(self::$files[$formname]['tmp_name'][$item], $filename); } } } } /** * 获得指定临时文件名值 */ public static function get_tmp_name( $formname, $defaultvalue = '', $item = '' ) { if( $item === '' ) { return isset(self::$files[$formname]['tmp_name']) ? self::$files[$formname]['tmp_name'] : $defaultvalue; } else { return isset(self::$files[$formname]['tmp_name'][$item]) ? self::$files[$formname]['tmp_name'][$item] : $defaultvalue; } } /** * 获得文件的扩展名 */ public static function get_file_ext( $formname, $item = '' ) { if( $item === '' ) { $filetype = strtolower(isset(self::$files[$formname]['type']) ? self::$files[$formname]['type'] : ''); } else { $filetype = strtolower(isset(self::$files[$formname]['type'][$item]) ? self::$files[$formname]['type'][$item] : ''); } $shortname = ''; switch($filetype) { case 'image/jpeg': $shortname = 'jpg'; break; case 'image/pjpeg': $shortname = 'jpg'; break; case 'image/gif': $shortname = 'gif'; break; case 'image/png': $shortname = 'png'; break; case 'image/xpng': $shortname = 'png'; break; case 'image/wbmp': $shortname = 'bmp'; break; default: if( $item === '' ) { $filename = isset(self::$files[$formname]['name']) ? self::$files[$formname]['name'] : ''; } else { $filename = isset(self::$files[$formname]['name'][$item]) ? self::$files[$formname]['name'][$item] : ''; } if( preg_match("/\./", $filename) ) { $fs = explode('.', $filename); $shortname = strtolower($fs[ count($fs)-1 ]); } break; } return $shortname; } /** * 获得指定文件表单的文件详细信息 */ public static function get_file_info( $formname, $item = '' ) { if( !isset( self::$files[$formname] ) ) { return false; } else { if($item === '') { return self::$files[$formname]; } else { if( !isset(self::$files[$formname][$item]) ) { return false; } else { return self::$files[$formname][$item]; } } } } /** * 判断是否存在上传的文件 */ public static function is_upload_file( $formname, $item = '' ) { if( $item === '' ) { if( isset(self::$files[$formname]['error']) && self::$files[$formname]['error']==UPLOAD_ERR_OK ) { return true; } else { return false; } } else { if( isset(self::$files[$formname]['error'][$item]) && self::$files[$formname]['error'][$item]==UPLOAD_ERR_OK ) { return true; } else { return false; } } } /** * 检查文件后缀是否为指定值 * * @param string $subfix * @return boolean */ public static function check_subfix($formname, $subfix = array('csv'), $item= '') { if( !in_array(self::get_file_ext( $formname, $item ), $subfix) ) { return false; } return true; } private static function _to_param($param_type) { unset($_REQUEST); switch ($param_type) { case 'get': $param = $_GET; unset($_GET); break; case 'post': $param = $_POST; unset($_POST); break; case 'cookie': self::$cookies = $_COOKIE; //unset($_COOKIE); return true; case 'file': //上传的文件处理 $_FILES = self::add_s( $_FILES ); $param = $_FILES; unset($_FILES); break; } return self::_for_param($param); } private static function _for_param($param = '') { if(empty($param)) { return []; } foreach($param as $k=>$v) { if(is_array($v)) { $data[$k] = self::_for_param($v); } else { $data[$k] = self::$forms[$k] = empty($v) ? $v : htmlentities($v, ENT_QUOTES); } } self::$forms = array_merge(self::$forms, $data); return $data; } } <file_sep><?php namespace common\serv; use sephp\sephp; use sephp\func; use common\model\pub_mod_order; use common\model\pub_mod_order_items; use sephp\core\lib\curl; /** * 美团订接口 * erro_no 10000 - 19999 */ class pub_serv_meituan { /** * 订的核销 * @Author GangGuoer * @DateTime 2019-11-02T01:37:14+0700 * @version [version] * @param [type] * @return [type] */ public static function check_order($meituan_order_id) { $url = "https://openapi.dianping.com/router/book/isvconsume"; $data = [ 'order_id' => '',//开放平台订单id 'app_shop_id' => '',//第三方的店铺id,不提倡使用 'open_shop_uuid' => '',//美团点评店铺id 'session' => '',//商家授权成功后,点评到综开放平台颁发给应用的授权信息 'order_id' => '', ]; } /** * 系统授权session获取接口 * @Author GangGuoer * @DateTime 2019-11-02T01:38:20+0700 * @version [version] * @return [type] */ public static function get_session() { $url = "https://openapi.dianping.com/router/oauth/token"; $data = [ 'app_key' => '', 'app_secret' => '', 'grant_type' => 'authorize_platform', ]; $tmp = curl::http_request([ 'url' => $url, 'post' => $data, ]); } }
fee80828cf50c6a4a49a61e515af65f9c2d8d718
[ "JavaScript", "PHP", "INI" ]
85
PHP
gangkui1688/sephp
61d40059409d61d36e834e1eec718c8db090b6c3
cfb034ca205a30c4d8accc670f989a147c2ba40b
refs/heads/master
<file_sep>const create = (req, res, Collection) => { const newEntry = req.body; Collection.create(newEntry, (e, newEntry) => { if (e) { console.log(e); res.sendStatus(500); } else { res.send(newEntry); } }); }; const readMany = (req, res, Collection) => { let query = req.body.query || {}; let options = req.query || {}; const offset = options.offset && parseInt(options.offset); const limit = options.limit && parseInt(options.limit); Collection.paginate(query, { offset, limit }, (e, result) => { if (e) { res.status(500).send(e); console.log(e.message); } else { res.send(result); } }); }; const readOne = (req, res, Collection) => { const { _id } = req.params; Collection.findById(_id, (e, result) => { if (e) { res.status(500).send(e); console.log(e.message); } else { res.send(result); } }); }; const update = (req, res, Collection) => { const changedEntry = req.body; Collection.update({ _id: req.params.id }, { $set: changedEntry }, (e) => { if (e) res.sendStatus(500); else res.sendStatus(200); }); }; const remove = (req, res, Collection) => { Collection.remove({ _id: req.params.id }, (e) => { if (e) res.status(500).send(e); else res.sendStatus(200); }); }; const removeMany = (req, res, Collection) => { const lstIdDelete = req.body.lstId; Collection.deleteMany({ _id: { $in: lstIdDelete } }, (e) => { if (e) res.status(500).send(e); else res.sendStatus(200); }) } const searchText = (req, res, Collection) => { let options = req.query || {}; let searchString = options.searchText; const offset = options.offset && parseInt(options.offset); const limit = options.limit && parseInt(options.limit); Collection.find({ $text: { $search: searchString } }) .skip(offset) .limit(limit) .exec(function (err, docs) { res.send(docs); }); } export default { create, readMany, readOne, update, remove, searchText, removeMany }; <file_sep>import express from 'express'; import requireAuth from '../middlewares/require_authentication'; const router = express.Router(); import { Disbursement } from '../controllers'; router.post('/create', Disbursement.disbursement_create); router.put('/:id/update', requireAuth, Disbursement.disbursement_update); router.delete('/:id/delete', Disbursement.disbursement_delete); router.get('/', requireAuth, Disbursement.disbursement_getAll); export default router;<file_sep>import express from 'express'; import mongoose from 'mongoose'; import bodyParser from 'body-parser'; import api from './routes/api'; import cors from 'cors'; const PORT = process.env.PORT || 3000; //const { mongoose } = require('./db.js'); mongoose.connect('mongodb://test10:test10@ds237735.mlab.com:37735/manager-org', { useNewUrlParser: true }, function (error) { if (!error) { console.log("Connect Server mLab Manage Money Successfully"); } else { console.log("Has error when connect" + error); } }); mongoose.set('useFindAndModify', false); const app = express(); app.use(cors({ origin: '*' })); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.listen(PORT, () => console.log('Server started at port in env')); app.use('/api', api); <file_sep>import mongoose from 'mongoose'; const Schema = mongoose.Schema; const mongoosePaginate = require('mongoose-paginate'); const devotionSchema = new Schema({ user: {type: Schema.Types.ObjectId, ref: 'user', required: true}, description: {type: String, required: true}, amountMoney: {type: String, required: true}, createdBy: {type: String, required: true}, updatedBy: {type: String, default: Date.now(), required: false}, createdAt:{type: Date, default: Date.now(),required: true}, updatedAt: {type: Date, required: false}, }); devotionSchema.plugin(mongoosePaginate); export default mongoose.model('Devotion', devotionSchema);<file_sep>import mongoose from 'mongoose'; const Schema = mongoose.Schema; const ProvincecitySchema = new Schema({ ProvinceCityId: {type: String, required: true, unique: true}, ProvinceCityName: {type: String, required: true}, CountryId:{type: Number, required: true} }); ProvincecitySchema.index({ProvinceCityName: "text"}); export default mongoose.model('Provincecity', ProvincecitySchema); <file_sep>import User from './user'; import Devotion from './devotion'; import Disbursement from './disbursement'; export { User, Devotion, Disbursement } <file_sep>import jwt from 'jsonwebtoken'; import jwtDecode from 'jwt-decode'; require('dotenv').config(); export default function (req, res, next) { var token = req.headers.authorization; var decodedValue = jwtDecode(token); if (decodedValue.userId) { jwt.verify(token, process.env.JWT_SECRET_KEY, (err, decoded) => { if (err) { const error = new Error('Failed to authenticate'); error.status = 401; next(error); } else { req.currentUserId = decodedValue.userId; req.userName = decodedValue.userName; return next(); } }); } else { req.user = undefined; const error = new Error('Failed to authenticate'); error.status = 401; next(error); } }; <file_sep>import BankSaving from './BankSaving'; import Cash from './Cash'; import Devotion from './Devotion'; import Disbursement from './Disbursement'; import Note from './Note'; import ProvinceCity from './Provincecity'; import TypeDevotion from './TypeDevotion'; import User from './User'; export { BankSaving, Cash, Devotion, Disbursement, Note, ProvinceCity, TypeDevotion, User }; <file_sep>import { Disbursement } from '../models'; import crud from './crud'; const disbursementController = { disbursement_create: function (req, res, next) { crud.create(req, res, Disbursement); }, disbursement_update: function (req, res, next) { crud.update(req, res, Disbursement); }, disbursement_delete: function (req, res, next) { crud.remove(req, res, Disbursement); }, disbursement_getAll: function (req, res) { crud.readMany(req, res, Disbursement); } } export default disbursementController;<file_sep>import mongoose from 'mongoose'; const Schema = mongoose.Schema; const typeDevotionSchema = new Schema({ name: {type: String, required: true, unique: true}, description: {type: String, required: true}, createdBy: {type: String, required: false}, updatedBy: {type: String, required: false}, createdAt:{type: Date, default: Date.now(), required: true}, updatedAt: {type: Date, required: false} }); export default mongoose.model('TypeDevotion', typeDevotionSchema); <file_sep>import mongoose from 'mongoose'; import mongoosePaginate from 'mongoose-paginate'; const Schema = mongoose.Schema; const userSchema = new Schema({ userName: { type: String, required: true, unique: true }, accountName: { type: String, required: false, default:"" }, profileImagePath: { type: String, required: false, default: "" }, address: { type: Object, required: false, default: {} }, password: { type: String, required: false }, phone: { type: String, required: false, default: "" }, email: { type: String, required: false, default: "" }, birthDate: {type: Date, required: false, default: null}, note: { type: String, required: false,default: "" }, createdBy: { type: String, required: false , }, updatedBy: { type: String, required: false }, createdAt: { type: Date, default: Date.now(), required: true }, updatedAt: { type: Date, required: false } }); userSchema.index({'$**': 'text'}); userSchema.plugin(mongoosePaginate); export default mongoose.model('User', userSchema); <file_sep># income-expenditure income and expenditure <file_sep>import express from 'express'; const router = express.Router(); import user from './user'; import devotion from './devotion'; import disbursement from './disbursement'; router.use('/user', user); router.use('/devotion', devotion); router.use('/disbursement', disbursement); export default router;<file_sep>import { Devotion } from '../models'; import crud from './crud'; const devotionController = { devotion_create: function (req, res, next) { crud.create(req, res, Devotion); }, devotion_update: function (req, res, next) { crud.update(req, res, Devotion); }, devotion_delete: function (req, res, next) { crud.remove(req, res, Devotion); }, devotion_getAll: function (req, res) { crud.readMany(req, res, Devotion); } } export default devotionController;
6b8845f468f7a0db9e5e93841b2aad95c4fabf06
[ "JavaScript", "Markdown" ]
14
JavaScript
thienan1312023/income-expenditure
d07722cee79ebbfe74e2f0ac1640e2214c800848
f3514a8f95ca38106e65bd555920a6bc6fa9bf48
refs/heads/master
<file_sep>FactoryGirl.define do factory :org do name { Faker::Company.name } code { Faker::Lorem.characters(5) } end end <file_sep>class CommunicationSerializer < ActiveModel::Serializer attributes :id, :org_code, :client_code, :primary_email, :secondary_email, :primary_phone, :secondary_phone end <file_sep>angular.module('Sentinel.indicesController', []) .controller('IndiceController', ['$scope', '$state', '$window', 'Index', function($scope, $state, $window, Index){ $scope.main = { offset: 1, limit: 1, sort: 'job_code ASC', rowsArray: [ {id:1, label:'1 Per Page'}, {id:2, label:'2 Per Page'}, {id:3, label:'3 Per Page'} ], sortArray: [ {id:'job_code ASC', label:'Name (A-Z)'}, {id:'job_code DESC',label:'Name (Z-A)'}, ] }; $scope.loadPage = function(page){ $scope.main.offset = page; Index.get({offset:$scope.main.offset, limit:$scope.main.limit, sort:$scope.main.sort}, function(data){ //var orgs = JSON.parse(data); // users from your api $scope.indices = data.indices; // total number of rows $scope.count = data.count; // number of pages of orgs $scope.pagesCount = data.count/$scope.main.limit; // build pages array var pagesArray = []; for(var p = 1; p < $scope.pagesCount+1; p++){ pagesArray.push(p); } $scope.pages = pagesArray; }); } $scope.loadPerPage = function(option){ $scope.main.limit = option; $scope.loadPage($scope.main.offset); } $scope.loadSortPage = function(option){ $scope.main.sort = option; $scope.loadPage($scope.main.offset); } $scope.loadPage(1);//fetch all orgs. Issues a GET to /api/orgs $scope.deleteIndice = function(index) { // Delete a org. Issues a DELETE to /api/org/:id index.$delete(function(response) { $scope.message = response; if(response.status == 'ok'){ $state.go('indices'); //redirect to home } }); }; }] ) .controller('IndiceViewController', ['$scope', '$stateParams' ,'Index', function($scope,$stateParams,Index){ $scope.indice=Index.get({id:$stateParams.id}); }]) .controller('IndiceCreateController',['$scope', '$state', '$stateParams', 'Index', 'Job', 'Realm', function($scope,$state,$stateParams,Index,Job,Realm){ //indice $scope.indice=new Index(); //jobs $scope.jobs = Job.query(); //realms $scope.realms = Realm.query(); $scope.addIndice=function(){ $scope.indice.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('indices'); //redirect to home } if(response.status == 'exists'){ return false; //redirect to home } }); } }]).controller('IndiceEditController',['$scope', '$state', '$stateParams', 'Index', 'Job', 'Realm', function($scope,$state,$stateParams,Index,Job,Realm){ //orgs $scope.jobs = Job.query(); //realms $scope.realms = Realm.query(); $scope.updateIndice=function(){ $scope.indice.$update(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('indices'); //redirect to home } }); }; $scope.loadIndice=function(){ $scope.indice=Index.get({id:$stateParams.id}); }; $scope.loadIndice(); }]);<file_sep>(function(){ var elif = angular.module('elif', []); // This is copied from AngularJS because it is not // part of the public interface. var getBlockElements = function(nodes){ if(!nodes || !nodes.length){ return $(); } var startNode = nodes[0]; var endNode = nodes[nodes.length - 1]; if(startNode === endNode){ return $(startNode); } var element = startNode; var elements = [element]; do { element = element.nextSibling; if(!element){ break; } elements.push(element); } while(element !== endNode); return $(elements); }; elif.factory('elif', [ function(){ // By requiring the scope have it's own copy of `elif.conditionals` // we avoid if/else-if/else structures that span AngularJS scopes. var getConditionals = function(scope){ if(angular.hasOwnProperty.call(scope, 'elif.conditionals')){ var conditionals = scope['elif.conditionals']; return conditionals[conditionals.length - 1]; } }; return { create: function(scope, fn, callback){ var conditionals = [{ fn: fn, callback: callback || angular.identity }]; var conditionalValues = []; scope.$watch(function(){ // Watch the boolean conditionals; we only need // to run through the if/else-if/else chain if one // of them changes. conditionalValues.length = conditionals.length; for(var i = 0, len = conditionals.length; i < len; i++){ conditionalValues[i] = !!conditionals[i].fn(); } return conditionalValues; }, function(conditionalValues){ // Find first matching if/else-if. var index = -1; for(var i = 0, len = conditionals.length; i < len; i++){ if(conditionalValues[i]){ conditionals[i].callback(true); index = i; i++; break; } else { conditionals[i].callback(false); } } // Mark the rest of the else-ifs as not matched. for(; i < len; i++){ conditionals[i].callback(false); } // Handle else, if there is one. conditionals.fallthrough && conditionals.fallthrough(index === -1); return index; }, true); // Deep watch; we know that it is a simple list of booleans. // Keep track of if/else-if/else structures per AngularJS scope. if(!angular.hasOwnProperty.call(scope, 'elif.conditionals')){ scope['elif.conditionals'] = []; } scope['elif.conditionals'].push(conditionals); }, extend: function(scope, fn, callback){ var conditionals = getConditionals(scope); if(!conditionals){ throw new Error('elif.extend: no if found at this level'); } if(conditionals.fallthrough){ throw new Error('elif.extend: else-if after else'); } conditionals.push({ fn: fn, callback: callback }); }, fallthrough: function(scope, fn, callback){ var conditionals = getConditionals(scope); if(!conditionals){ throw new Error('elif.fallthrough: no if found at this level'); } if(conditionals.fallthrough){ throw new Error('elif.fallthrough: else already found at this level'); } conditionals.fallthrough = callback; } }; } ]); // This implementation is basically the built-in `ng-if`, hooked into the `elif` service. var elifDirective = function(name, method, getter){ elif.directive(name, [ '$animate', '$document', '$injector', 'elif', function($animate, $document, $injector, elif){ var getterFn = getter && $injector.invoke(getter); return { transclude: 'element', restrict: 'A', priorty: 600, terminal: true, link: function(scope, element, attrs, ctrls, transcludeFn){ var watchFn = getterFn && getterFn(scope, element, attrs); var childScope; var childElement; var previousElements; elif[method](scope, watchFn, function(value, conditionals){ if(value){ if(!childScope){ childScope = scope.$new(); transcludeFn(childScope, function(clone){ clone[clone.length + 1] = $document[0].createComment(' end ' + name + ': ' + attrs[name] + ' '); childElement = clone; $animate.enter(clone, element.parent(), element); }); } } else { if(childScope){ childScope.$destroy(); childScope = null; } if(previousElements){ previousElements.remove(); previousElements = null; } if(childElement){ previousElements = getBlockElements(childElement); $animate.leave(previousElements, function(){ previousElements = null; }); childElement = null; } } }); } }; } ]); }; // Reads the attribute given by `name` and converts it to a boolean. var getter = function(name){ return [ '$parse', function($parse){ return function(scope, element, attrs){ var testFn = $parse(attrs[name]); return function(){ return !!testFn(scope); }; }; } ]; }; // We rely on the built-in `ng-if` directive to actually perform // the transclusion, and simply tie it in to the `elif` service. elif.directive('ngIf', [ '$injector', 'elif', function($injector, elif){ var getterFn = $injector.invoke(getter('ngIf')); return { priority: 600, link: function(scope, element, attrs){ var watchFn = getterFn(scope, element, attrs); elif.create(scope, watchFn); } } } ]); // Else-if and else perform their own transclusions. elifDirective('ngElseIf', 'extend', getter('ngElseIf')); elifDirective('ngElif', 'extend', getter('ngElif')); // Else doesn't take an argument. elifDirective('ngElse', 'fallthrough'); })(); <file_sep>class IndexSerializer < ActiveModel::Serializer attributes :id, :job_code, :realm_code, :cron, :critical, :notify, :jobkey, :run_length, :success_step end <file_sep>class UsersController < ApplicationController after_action :verify_authorized def index @users = User.order(params[:sort]).all authorize User @total_count = @users.count(:all) @limit = params[:limit].to_i @limited_orgs = @users.paginate(:page => params[:offset], :per_page => @limit) @response = { :users => @limited_orgs, :count => @total_count } respond_with @response end def new @user = User.new end def show respond_with User.find(params[:id]) end def edit authorize User respond_with User.find(params[:id]) end def create @user = User.new(user_params) authorise(@user) @user.password = <PASSWORD>[:<PASSWORD>] respond_to do |format| if @user.save format.json do render :json => { :status => :ok, :message => "User was created successfully!" }.to_json end else format.json do render :json => { :message => @user.errors, :status => :error #unprocessable_entity }.to_json end end end end def update @user = User.where(email: params[:email]).first if @user && @user.authenticate(@user, params[:current_password]) respond_to do |format| @user.password = <PASSWORD>[:<PASSWORD>] if @user.update(user_params) format.json do render :json => { :status => :ok, :message => "Profile was updated successfully!" }.to_json end else format.json do render :json => { :message => @user.errors, :status => :error #unprocessable_entity }.to_json end end end else respond_to do |format| format.json do render :json => { :message => "Sorry! Please check your credentails and try again.", :status => :wrpass, #unprocessable_entity :data => User.find(params[:id]) }.to_json end end end end private def user_params params.require(:user).permit(:name, :email, :password, :role) end end <file_sep>class ClientSerializer < ActiveModel::Serializer attributes :id, :name, :code, :timezone, :locale, :org_code end <file_sep>class RolesController < ApplicationController def index if params[:sort] @roles = Role.order(params[:sort]).all @total_count = @roles.count(:all) @limit = params[:limit].to_i @roles = @roles.paginate(:page => params[:offset], :per_page => @limit) @response = { :roles => @roles, :count => @total_count } else @roles = Role.all @total_count = @roles.count(:all) @response = @roles end respond_with @response end def new @role = Role.new end def show respond_with Role.find(params[:id]) end def edit respond_with Role.find(params[:id]) end def create @role = Role.new(role_params) role_activities = self.checkValues @role.activities = role_activities #authorise(@user) respond_to do |format| if @role.save format.json do render :json => { :status => :ok, :message => "Role was created successfully!" }.to_json end else format.json do render :json => { :message => @role.errors, :status => :error #unprocessable_entity }.to_json end end end end def update @role = Role.find(params[:id]) role_activities = self.checkValues @role.activities = role_activities respond_to do |format| if @role.update(role_update_params) format.json do render :json => { :status => :ok, :message => "Role was successfully updated.!" }.to_json end else format.json do render :json => { :message => @role.errors, :status => :error #unprocessable_entity }.to_json end end end end def checkValues acts = [] if params[:activities_list].present? arr = params[:activities_list] else arr = params[:activities] end arr.each do |key, value| acts << key #associate that user with something else end return acts end private def role_params params.require(:role).permit(:name, :activities_list => []) end private def role_update_params params.permit(:name, :activities_list => []) end end <file_sep>class JobsController < ApplicationController def index if(params[:sort]) @jobs = Job.order(params[:sort]).all @total_count = @jobs.count(:all) @limit = params[:limit].to_i @limited_jobs = @jobs.paginate(:page => params[:offset], :per_page => @limit) @response = { :jobs => @limited_jobs, :count => @total_count } else @response = Job.all end respond_with @response end def new end def create respond_to do |format| jobParams = job_params; @job = Job.isJobCodeExists(jobParams) if(!@job.blank?) format.json do render :json => { :status => :exists, :message => 'Sorry! Job already exists.' }.to_json end else if Job.create(jobParams) format.json do render :json => { :status => :ok, :message => 'Job has been added successfully.' }.to_json end else format.json do render :json => { :message => @job.errors, :status => :error #unprocessable_entity }.to_json end end end end end def show respond_with Job.find(params[:id]) end def edit respond_with Job.find(params[:id]) end def update @job = Job.find(params[:id]) respond_to do |format| if @job.update(job_params) format.json do render :json => { :status => :ok, :message => "Job was successfully updated.!" }.to_json end else format.json do render :json => { :message => @job.errors, :status => :error #unprocessable_entity }.to_json end end end end def destroy @job = Job.find(params[:id]) respond_to do |format| if @job.destroy format.json do render :json => { :status => :ok, :message => "Job was successfully deleted.!" }.to_json end else format.json do render :json => { :message => @job.errors, :status => :error #unprocessable_entity }.to_json end end end end private def job_params params.require(:job).permit(:job_code, :org_code, :client_code, :name, :description) if params[:job] end end <file_sep>class LabelSerializer < ActiveModel::Serializer attributes :id, :org_code, :client_code, :realm_code, :key, :name, :icon end <file_sep>class AddRoleToUsers < ActiveRecord::Migration def change add_column :users, :role, :integer # populate the table User.create :name => "admin", :email => "<EMAIL>", :password => '<PASSWORD>', :role => 1 end end <file_sep>class OrgSerializer < ActiveModel::Serializer attributes :id, :name, :code, :timezone, :locale end <file_sep>class Index < ActiveRecord::Base validates :job_code, presence: true validates :realm_code, presence: true validates :cron, presence: true validates :critical, presence: true validates :notify, presence: true validates :jobkey, presence: true validates :run_length, presence: true, :numericality => {:only_integer => true} validates :success_step, presence: true def self.buildCron(params) @cron = params['cron_min'] + ' ' + params['cron_hour'] + ' ' + params['cron_day'] + ' ' + params['cron_month'] + ' ' + params['cron_week'] return @cron; end end <file_sep>class Event < ActiveRecord::Base validates :praxis_code, presence: true validates :event_id, presence: true validates :occurred_at, presence: true validates :client_code, presence: true validates :milestone_key, presence: true validates :realm_code, presence: true validates :prosess_code, presence: true validates :stage_code, presence: true validates :sequence, presence: true end <file_sep>class CreateRuns < ActiveRecord::Migration def change create_table :runs do |t| t.string :jobkey t.string :runkey t.string :stage t.string :value t.timestamps null: false end end end <file_sep># Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js ) Rails.application.config.assets.precompile += %w( radial-progress-chart.js ) Rails.application.config.assets.precompile += %w( ng-file-upload-all.js ) Rails.application.config.assets.precompile += %w( font-awesome.css ) Rails.application.config.assets.precompile += %w( angular-gridster.min.css ) Rails.application.config.assets.precompile += %w( dashboardstyle.css ) Rails.application.config.assets.precompile += %w( nv.d3.css ) Rails.application.config.assets.precompile += %w( d3.min.js ) Rails.application.config.assets.precompile += %w( ui-bootstrap-tpls.min.js ) Rails.application.config.assets.precompile += %w( angular-nvd3.js ) Rails.application.config.assets.precompile += %w( nv.d3.js ) Rails.application.config.assets.precompile += %w( lineChart.js ) Rails.application.config.assets.precompile += %w( cumulativeLineChart.js ) Rails.application.config.assets.precompile += %w( stackedAreaChart.js ) Rails.application.config.assets.precompile += %w( angular-gridster.js ) Rails.application.config.assets.precompile += %w( ui-bootstrap-tpls.min.js ) Rails.application.config.assets.precompile += %w( common.js ) # @time_zone = Setting.fetchAttribute('time_zone') # Time.zone = @time_zone <file_sep>class UserSerializer < ActiveModel::Serializer attributes :id, :role_id, :role_name, :name, :email def role_name self.role.try(:name) end end <file_sep>class AddTimeZoneAndLocaleToOrgs < ActiveRecord::Migration def change add_column :orgs, :timezone, :string add_column :orgs, :locale, :string end end <file_sep>class AddTimeZoneAndLocaleToClients < ActiveRecord::Migration def change add_column :clients, :timezone, :string add_column :clients, :locale, :string end end <file_sep>class Api::V1::DataController < ApplicationController end <file_sep>require 'rails_helper' RSpec.describe Event, type: :model do subject { create(:event) } it 'is valid' do expect(subject).to be_valid end describe '#praxis_code' do it 'is required' do subject.praxis_code = nil expect(subject).to be_invalid end end describe '#event_id' do it 'is required' do subject.event_id = nil expect(subject).to be_invalid end end describe '#occurred_at' do it 'is required' do subject.occurred_at = nil expect(subject).to be_invalid end end # denormalized fields describe '#client_code' do it 'is required' do subject.client_code = nil expect(subject).to be_invalid end end describe '#milestone_key' do it 'is required' do subject.milestone_key = nil expect(subject).to be_invalid end end describe '#realm_code' do it 'is required' do subject.realm_code = nil expect(subject).to be_invalid end end describe '#prosess_code' do it 'is required' do subject.prosess_code = nil expect(subject).to be_invalid end end describe '#stage_code' do it 'is required' do subject.stage_code = nil expect(subject).to be_invalid end end describe '#sequence' do it 'is required' do subject.sequence = nil expect(subject).to be_invalid end end end <file_sep>angular.module('Sentinel.jobs', []) .factory('Job', function($resource){ return $resource('/api/jobs/:id',{id:'@id'},{ update: { method: 'PUT' } }); });<file_sep>class Milestone < ActiveRecord::Base validates :org_code, presence: true validates :client_code, presence: true validates :key, presence: true validates :realm_code, presence: true end <file_sep>angular.module('Sentinel', ['ui.router', 'templates', 'ngMessages', 'ngFileUpload', 'elif', 'ngResource', 'Sentinel.orgs', 'Sentinel.orgsController', 'Sentinel.prosessesController', 'Sentinel.prosesses','Sentinel.communicationsController', 'Sentinel.communications','Sentinel.realmsController','Sentinel.realms','Sentinel.stages','Sentinel.stagesController','Sentinel.clientsController', 'Sentinel.clients', 'Sentinel.praxis', 'Sentinel.praxisController', 'Sentinel.labels', 'Sentinel.labelsController', 'Sentinel.users', 'Sentinel.usersController', 'Sentinel.roles', 'Sentinel.rolesController', 'Sentinel.milestones', 'Sentinel.milestonesController','gridster', 'nvd3','ui.bootstrap', 'Sentinel.jobs', 'Sentinel.jobsController', 'Sentinel.indices', 'Sentinel.indicesController', 'Sentinel.settings', 'Sentinel.settingsController']); angular.module('Sentinel').config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) { $stateProvider .state('dashboard', {url: '/dashboard',templateUrl: 'home/_dashboard.html',controller: 'DashboardCtrl'}) .state('home', {url: '/home',templateUrl: 'home/_home.html',controller: 'SentinelCtrl'}) .state('settings', {url: '/settings',templateUrl: 'setting/_settings.html',controller: 'SettingController'}) .state('jobs', {url: '/jobs',templateUrl: 'job/_jobs.html',controller: 'JobController'}) .state('createJob', {url: '/createJob',templateUrl: 'job/_createJob.html',controller: 'JobCreateController'}) .state('showJob', {url: '/jobs/:id',templateUrl: 'job/_show.html',controller: 'JobViewController'}) .state('editJob', {url: '/jobs/{id}/edit',templateUrl: 'job/_edit.html',controller: 'JobEditController'}) .state('indices', {url: '/indices',templateUrl: 'indice/_indices.html',controller: 'IndiceController'}) .state('createIndice', {url: '/createIndice',templateUrl: 'indice/_createIndice.html',controller: 'IndiceCreateController'}) .state('showIndice', {url: '/indices/:id',templateUrl: 'indice/_show.html',controller: 'IndiceViewController'}) .state('editIndice', {url: '/indices/{id}/edit',templateUrl: 'indice/_edit.html',controller: 'IndiceEditController'}) .state('orgs', {url: '/orgs',templateUrl: 'org/_orgs.html',controller: 'OrgController'}) .state('createOrg', {url: '/createOrg',templateUrl: 'org/_createOrg.html',controller: 'OrgCreateController'}) .state('showOrg', {url: '/orgs/:id',templateUrl: 'org/_show.html',controller: 'OrgViewController'}) .state('editOrg', {url: '/orgs/{id}/edit',templateUrl: 'org/_edit.html',controller: 'OrgEditController'}) .state('prosesses', {url: '/prosesses',templateUrl: 'prosess/_prosess.html',controller: 'ProsessController'}) .state('createProsess', {url: '/createProsess',templateUrl: 'prosess/_createProsess.html',controller: 'ProsessCreateController'}) .state('showProsess', {url: '/prosesses/:id',templateUrl: 'prosess/_show.html',controller: 'ProsessViewController'}) .state('editProsess', {url: '/prosesses/{id}/edit',templateUrl: 'prosess/_edit.html',controller: 'ProsessEditController'}) .state('communications', {url: '/communications',templateUrl: 'communication/_communications.html',controller: 'CommunicationController'}) .state('createCommunication', {url: '/createCommunication',templateUrl: 'communication/_createCommunication.html',controller: 'CommunicationCreateController'}) .state('showCommunication', {url: '/communications/:id',templateUrl: 'communication/_show.html',controller: 'CommunicationViewController'}) .state('editCommunication', {url: '/communications/{id}/edit',templateUrl: 'communication/_edit.html',controller: 'CommunicationEditController'}) .state('realms', {url: '/realms',templateUrl: 'realm/_realms.html',controller: 'RealmController'}) .state('createRealm', {url: '/createRealm',templateUrl: 'realm/_createRealm.html',controller: 'RealmCreateController'}) .state('showRealm', {url: '/realms/:id',templateUrl: 'realm/_show.html',controller: 'RealmViewController'}) .state('editRealm', {url: '/realms/{id}/edit',templateUrl: 'realm/_edit.html',controller: 'RealmEditController'}) .state('stages', {url: '/stages',templateUrl: 'stage/_stages.html',controller: 'stageController'}) .state('createStage', {url: '/createStage',templateUrl: 'stage/_createStage.html',controller: 'StageCreateController'}) .state('showStage', {url: '/stages/:id',templateUrl: 'stage/_show.html',controller: 'StageViewController'}) .state('editStage', {url: '/stages/{id}/edit',templateUrl: 'stage/_edit.html',controller: 'StageEditController'}) .state('clients', {url: '/clients',templateUrl: 'clients/_clients.html',controller: 'clientsController'}) .state('createClient', {url: '/createClient',templateUrl: 'clients/_createClient.html',controller: 'ClientCreateController'}) .state('showClient', {url: '/clients/:id',templateUrl: 'clients/_show.html',controller: 'ClientViewController'}) .state('editClient', {url: '/clients/{id}/edit',templateUrl: 'clients/_edit.html',controller: 'ClientEditController'}) .state('praxis', {url: '/praxis',templateUrl: 'praxi/_praxis.html',controller: 'PraxiController'}) .state('createPraxi', {url: '/createPraxi',templateUrl: 'praxi/_createPraxi.html',controller: 'PraxiCreateController'}) .state('showPraxi', {url: '/praxis/:id',templateUrl: 'praxi/_show.html',controller: 'PraxiViewController'}) .state('editPraxi', {url: '/praxis/{id}/edit',templateUrl: 'praxi/_edit.html',controller: 'PraxiEditController'}) .state('labels', {url: '/labels',templateUrl: 'label/_labels.html',controller: 'LabelController'}) .state('createLabel', {url: '/createLabel',templateUrl: 'label/_createLabel.html',controller: 'LabelCreateController'}) .state('showLabel', {url: '/labels/:id',templateUrl: 'label/_show.html',controller: 'LabelViewController'}) .state('editLabel', {url: '/labels/{id}/edit',templateUrl: 'label/_edit.html',controller: 'LabelEditController'}) .state('milestones', {url: '/milestones',templateUrl: 'milestone/_milestones.html',controller: 'MilestoneController'}) .state('createMilestone', {url: '/createMilestone',templateUrl: 'milestone/_createMilestone.html',controller: 'MilestoneCreateController'}) .state('showMilestone', {url: '/milestones/:id',templateUrl: 'milestone/_show.html',controller: 'MilestoneViewController'}) .state('editMilestone', {url: '/milestones/{id}/edit',templateUrl: 'milestone/_edit.html',controller: 'MilestoneEditController'}) .state('logout', {url: '/logout',templateUrl: 'user/_logout.html',controller: 'UserLogoutController'}) .state('login', {url: '/login',templateUrl: 'user/_login.html',controller: 'UserLoginController'}) .state('forgotpass', {url: '/forgotpass',templateUrl: 'user/_forgot.html',controller: 'UserForgotController'}) .state('signup', {url: '/signup',templateUrl: 'user/_signup.html',controller: 'UserCreateController'}) .state('users', {url: '/users',templateUrl: 'user/_users.html',controller: 'UserController'}) .state('createUser', {url: '/createUser',templateUrl: 'user/_createUser.html',controller: 'UserCreateController'}) .state('showUser', {url: '/users/:id',templateUrl: 'user/_show.html',controller: 'UserViewController'}) .state('editUser', {url: '/users/{id}/edit',templateUrl: 'user/_editProfile.html',controller: 'UserEditController'}) .state('roles', {url: '/roles',templateUrl: 'role/_roles.html',controller: 'RoleController'}) .state('createRole', {url: '/createRole',templateUrl: 'role/_createRole.html',controller: 'RoleCreateController'}) .state('showRole', {url: '/roles/:id',templateUrl: 'role/_show.html',controller: 'RoleViewController'}) .state('editRole', {url: '/roles/{id}/edit',templateUrl: 'role/_edit.html',controller: 'RoleEditController'}); //$urlRouterProvider.otherwise('home'); $urlRouterProvider.otherwise(function ($injector, $location) { if($location.$$search.goto){ $location.url('/' + $location.$$search.goto); }else{ $location.url('/home'); } }); $locationProvider.html5Mode(true); }]) .directive('ngConfirmClick', [ function(){ return { priority: 100, restrict: 'A', link: { pre: function(scope, element, attrs){ //<--------- element.bind('click touchstart', function(e){ var message = attrs.ngConfirmClick; if(message && !window.confirm(message)){ e.stopImmediatePropagation(); e.preventDefault(); } }); } } } } ]) .directive('validPasswordC', function() { return { require: 'ngModel', scope: { reference: '=validPasswordC' }, link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue, $scope) { var noMatch = viewValue != scope.reference ctrl.$setValidity('noMatch', !noMatch); return (noMatch)?noMatch:undefined; }); scope.$watch("reference", function(value) {; ctrl.$setValidity('noMatch', value === ctrl.$viewValue); }); } } }) .directive('ngUserLogout', [ function(){ return { priority: 100, restrict: 'A', link: { pre: function(scope, element, attrs){ //<--------- element.bind('click touchstart', function(e){ var message = attrs.ngConfirmClick; if(message && message =='logout'){ console.log('test') window.location = '/login'; } }); } } } } ]) .constant('CHARTS', { lineChart: { path: '/lineChart', title: 'Line Chart' }, pieChart: { path: '/pieChart', title: 'Pie Chart' }, stackedAreaChart: { path: '/stackedAreaChart', title: 'Stacked Area Chart'}, }) ; <file_sep>angular.module('Sentinel.rolesController', []) .controller('RoleController', ['$scope', '$state', '$window', 'Role', function($scope, $state, $window, Role){ $scope.main = { offset: 1, limit: 1, sort: 'name ASC', rowsArray: [ {id:1, label:'1 Per Page'}, {id:2, label:'2 Per Page'}, {id:3, label:'3 Per Page'} ], sortArray: [ {id:'name ASC', label:'Name (A-Z)'}, {id:'name DESC',label:'Name (Z-A)'}, ] }; $scope.loadPage = function(page){ $scope.main.offset = page; Role.get({offset:$scope.main.offset, limit:$scope.main.limit, sort:$scope.main.sort}, function(data){ //var orgs = JSON.parse(data); // users from your api $scope.roles = data.roles; // total number of rows $scope.count = data.count; // number of pages of orgs $scope.pagesCount = data.count/$scope.main.limit; // build pages array var pagesArray = []; for(var p = 1; p < $scope.pagesCount+1; p++){ pagesArray.push(p); } $scope.pages = pagesArray; }); } $scope.loadPerPage = function(option){ $scope.main.limit = option; $scope.loadPage($scope.main.offset); } $scope.loadSortPage = function(option){ $scope.main.sort = option; $scope.loadPage($scope.main.offset); } $scope.loadPage(1);//fetch all orgs. Issues a GET to /api/orgs $scope.deleteRole = function(role) { // Delete a org. Issues a DELETE to /api/org/:id role.$delete(function(response) { $scope.message = response; if(response.status == 'ok'){ $state.go('orgs'); //redirect to home } }); }; }] ) .controller('RoleViewController', ['$scope', '$stateParams' ,'Role', function($scope,$stateParams,Role){ $scope.role=Role.get({id:$stateParams.id}); }]) .controller('RoleCreateController',['$scope', '$state', '$stateParams', 'Role', function($scope,$state,$stateParams,Role){ $scope.activities = ['user:show', 'user:create', 'user:update', 'user:destroy']; $scope.role=new Role(); $scope.addRole=function(){ $scope.role.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('roles'); //redirect to home } }); } }]).controller('RoleEditController',['$scope', '$state', '$stateParams', 'Role', function($scope,$state,$stateParams,Role){ $scope.acties = ['user:show', 'user:create', 'user:update', 'user:destroy']; $scope.updateRole=function(){ var roleForm = jQuery('#roleForm').serialize(); jQuery.ajax({ url: '/roles/update', method: 'post', data: roleForm, dataType: 'json', success:function(response){ $scope.message = response.message; if(response.status == 'ok'){ $state.go('roles'); //redirect to home } } }) }; $scope.activities = []; var array = []; $scope.loadRole=function(){ Role.get({id:$stateParams.id}, function(response){ $scope.role = response; array = response.activities; $scope.activities = JSON.parse(array); //console.log(Object.prototype.toString.call($scope.activities)); }); }; $scope.loadRole(); $scope.toggleSelection = function toggleSelection(id) { var idx = $scope.activities.indexOf(id); if (idx > -1) { $scope.activities.splice(idx, 1); } else { $scope.activities.push(id); } console.log($scope.activities) }; }]);<file_sep>class Org < ActiveRecord::Base extend Searchable validates :name, presence: true validates :code, presence: true, length: { in: 3..10 }, uniqueness: { case_sensitive: false } end <file_sep>class UserPolicy < ApplicationPolicy attr_reader :current_user, :model def initialize(current_user, model) @current_user = current_user @user = model end def index? @type = 'user:index' role = @current_user.role authorized(role, @type) end def edit? @type = 'user:edit' role = @current_user.role authorized(role, @type) end def create? @type = 'user:create' role = @current_user.role authorized(role, @type) end def update? @type = 'user:update' role = @current_user.role authorized(role, @type) end end<file_sep>class CreateIndices < ActiveRecord::Migration def change create_table :indices do |t| t.string :job_code t.string :client_code t.string :realm_code t.string :cron t.boolean :critical t.string :notify t.string :jobkey t.integer :run_length t.string :success_step t.timestamps null: false end end end <file_sep>FactoryGirl.define do factory :event do praxis_code 'ABC' event_id 'EVENT_ID' client_code 'CLIENT_CODE' milestone_key 'CLIENT_CODE' realm_code 'CLIENT_CODE' prosess_code 'CLIENT_CODE' stage_code 'CLIENT_CODE' add_attribute :sequence, (1..5).to_a.sample occurred_at { Time.now } end end<file_sep>angular.module('Sentinel.communicationsController', []) .controller('CommunicationController', ['$scope', '$state', '$window', 'Communication', function($scope, $state, $window, Communication) /*{ $scope.main = { offset: 1, limit: 1, sort: 'org_code ASC', rowsArray: [ {id:1, label:'1 Per Page'}, {id:2, label:'2 Per Page'}, {id:3, label:'3 Per Page'} ], sortArray: [ {id:'org_code ASC', label:'org_code (A-Z)'}, {id:'org_code DESC',label:'org_code (Z-A)'}, {id:'client_code ASC', label:'client_code (A-Z)'}, {id:'client_code DESC',label:'client_code (Z-A)'} ] }; $scope.loadPage = function(page){ $scope.main.offset = page; Communication.get({offset:$scope.main.offset, limit:$scope.main.limit, sort:$scope.main.sort}, function(data){ $scope.communications = data.communications; // total number of rows $scope.count = data.count; $scope.pagesCount = data.count/$scope.main.limit; // build pages array var pagesArray = []; for(var p = 1; p < $scope.pagesCount+1; p++){ pagesArray.push(p); } $scope.pages = pagesArray; }); } $scope.loadPerPage = function(option){ $scope.main.limit = option; $scope.loadPage($scope.main.offset); } $scope.loadSortPage = function(option){ $scope.main.sort = option; $scope.loadPage($scope.main.offset); } $scope.loadPage(1);//fetch all clients. Issues a GET to /api/clients $scope.deleteCommunication = function(communication) { // Delete a client. Issues a DELETE to /api/client/:id communication.$delete(function(response) { $scope.message = response; if(response.status == 'ok'){ $state.go('communications'); //redirect to home } }); }; }] )*/ { $scope.communications = Communication.query(); $scope.deleteCommunication = function(communication) { communication.$delete(function(response) { $scope.message = response; if(response.status == 'ok'){ $state.go('communications'); //redirect to home } }); }; }] ) .controller('CommunicationViewController', ['$scope', '$stateParams' ,'Communication', function($scope,$stateParams,Communication){ $scope.communication=Communication.get({id:$stateParams.id}); }]) .controller('CommunicationCreateController',['$scope', '$state', '$stateParams', 'Communication','Org','Client', function($scope,$state,$stateParams,Communication,Org,Client){ $scope.communication=new Communication(); $scope.orgs = Org.query(); $scope.clients = Client.query(); $scope.addCommunication=function(){ $scope.communication.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('communications'); //redirect to home } }); } }]).controller('CommunicationEditController',['$scope', '$state', '$stateParams', 'Communication','Org','Client',function($scope,$state,$stateParams,Communication,Org,Client){ $scope.orgs = Org.query(); $scope.clients = Client.query(); $scope.updateCommunication=function(){ $scope.communication.$update(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('communications'); //redirect to home } }); }; $scope.loadCommunication=function(){ $scope.communication=Communication.get({id:$stateParams.id}); }; $scope.loadCommunication(); }]);<file_sep>class CommunicationsController < ApplicationController def index if(params[:sort]) Rails.logger.debug("my passw: #{params}") @communications = Communication.order(params[:sort]).all @total_count = @communications.count(:all) @limit = params[:limit].to_i @limited_communications = @communications.paginate(:page => params[:offset], :per_page => @limit) @response = { :communications =>@limited_communications, :count => @total_count } else @response = Communication.all end respond_with @response end def new end def create respond_to do |format| if Communication.create(communication_params) format.json do render :json => { :status => :ok, :message => "Communication was successfully updated.!" }.to_json end else format.json do render :json => { :message => @communication.errors, :status => :error #unprocessable_entity }.to_json end end end end def show respond_with Communication.find(params[:id]) end def edit respond_with Communication.find(params[:id]) end def update @communication = Communication.find(params[:id]) respond_to do |format| if @communication.update(communication_params) format.json do render :json => { :status => :ok, :message => "communication was successfully updated.!" }.to_json end else format.json do render :json => { :message => @communication.errors, :status => :error #unprocessable_entity }.to_json end end end end def destroy @communication = Communication.find(params[:id]) respond_to do |format| if @communication.destroy format.json do render :json => { :status => :ok, :message => "communication was successfully deleted.!" }.to_json end else format.json do render :json => { :message => @communication.errors, :status => :error #unprocessable_entity }.to_json end end end end private def communication_params params.require(:communication).permit(:org_code, :client_code, :primary_email, :secondary_email, :primary_phone, :secondary_phone) if params[:communication] end end <file_sep>class PraxiSerializer < ActiveModel::Serializer attributes :id, :code, :org_code, :client_code, :milestone_key, :realm_code, :prosess_code, :stage_code, :sequence, :sla, :tolerance_percentage, :critical end <file_sep>class User < ActiveRecord::Base attr_accessor :password attr_accessor :remember_token before_save { self.email = email.downcase } before_save :encrypt_password after_save :clear_password validates :name, presence: true, length: { maximum: 50 } VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } #has_secure_password validates :password, :confirmation => true #password_confirmation attr validates_length_of :password, :in => 6..20, :on => :create def encrypt_password if password.present? #Rails.logger.debug("My password: #{true}") self.salt = BCrypt::Engine.generate_salt self.encrypted_password= <PASSWORD>_<PASSWORD>(password, salt) end end def clear_password self.password = nil end def authenticate(user, password) if user && user.encrypted_password == <PASSWORD>.hash_secret(password, user.salt) true else nil end end # Returns the hash digest of the given string. def User.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end # Returns a random token. def User.new_token SecureRandom.urlsafe_base64 end def remember self.remember_token = User.new_token self.update_column(:remember, User.digest(remember_token)) end # Forgets a user. def forget update_attribute(:remember, nil) end end <file_sep># file: app/mailers/job_mailer.rb class JobMailer < ActionMailer::Base require 'date' def check_job_running_status(options) @indices = Index.all @indices.each do |index| @cron = '' @cron = index.cron @jobkey = index.jobkey @mins = index.run_length cron_parser = CronParser.new(@cron) @last_cron = cron_parser.last(Time.now) #.in_time_zone(Time.zone.name) @next_cron = cron_parser.next(Time.now.in_time_zone(Time.zone.name)) @runs = Run.where(["jobkey = ? and created_at = ?, value != ?", @jobkey, @last_cron, 'done']).limit(1) if(!@runs.blank?) @runs.each do |run| created_at = run.created_at created_at2 = created_at.in_time_zone(Time.zone.name) minutes = (Time.now - created_at2) + 10 if(minutes > @mins) #send mail end Rails.logger.debug("My password: #{@<PASSWORD>}") end else run = Run.new(jobkey: @jobkey, stage: 'mia', value: 'missing_in_action') run.save() end end end end<file_sep>angular.module('Sentinel.orgs', []) .factory('Org', function($resource){ return $resource('/api/orgs/:id',{id:'@id'},{ 'get': { method: 'GET', isArray: false }, 'query': { method: 'GET', isArray: false }, update: { method: 'PUT' } }); });<file_sep>Org.delete_all Client.delete_all # Prosess.delete_all # Communication.delete_all # Stage.delete_all # Realm.delete_all # Praxi.delete_all # Label.delete_all # Event.delete_all require 'factory_girl' 10.times do |n| org = FactoryGirl.create(:org) puts "Created org: #{org.name}" 5.times do |m| client = FactoryGirl.create(:client, org: org) # 2.times do # FactoryGirl.create(:communication, client: client, org: org) # end end end # 5.times do # FactoryGirl.create(:prosess) # FactoryGirl.create(:stage) # FactoryGirl.create(:realm) # FactoryGirl.create(:praxi) # FactoryGirl.create(:label) # FactoryGirl.create(:milestone) # end <file_sep>angular.module('Sentinel.usersController', []) .controller('UserController', ['$scope', '$state', '$window', 'User', function($scope, $state, $window, User){ $scope.main = { offset: 1, limit: 1, sort: 'name ASC', rowsArray: [ {id:1, label:'1 Per Page'}, {id:2, label:'2 Per Page'}, {id:3, label:'3 Per Page'} ], sortArray: [ {id:'name ASC', label:'Name (A-Z)'}, {id:'name DESC',label:'Name (Z-A)'}, {id:'email ASC', label:'Email (A-Z)'}, {id:'email DESC',label:'Email (Z-A)'} ] }; $scope.loadPage = function(page){ $scope.main.offset = page; User.get({offset:$scope.main.offset, limit:$scope.main.limit, sort:$scope.main.sort}, function(data){ //var Users = JSON.parse(data); // users from your api console.log('test') $scope.users = data.users; // total number of rows $scope.count = data.count; // number of pages of Users $scope.pagesCount = data.count/$scope.main.limit; // build pages array var pagesArray = []; for(var p = 1; p < $scope.pagesCount+1; p++){ pagesArray.push(p); } $scope.pages = pagesArray; }); } $scope.loadPerPage = function(option){ $scope.main.limit = option; $scope.loadPage($scope.main.offset); } $scope.loadSortPage = function(option){ $scope.main.sort = option; $scope.loadPage($scope.main.offset); } $scope.loadPage(1);//fetch all Users. Issues a GET to /api/Users $scope.deleteUser = function(user) { // Delete a User. Issues a DELETE to /api/User/:id user.$delete(function(response) { $scope.message = response; if(response.status == 'ok'){ $state.go('users'); //redirect to home } }); }; }] ) .controller('UserViewController', ['$scope', '$stateParams' ,'User', function($scope,$stateParams,User){ $scope.user=User.get({id:$stateParams.id}); }]) .controller('UserCreateController',['$scope', '$state', '$stateParams', 'User', 'Role', function($scope,$state,$stateParams,User, Role){ //roles $scope.roles = Role.query(); $scope.user=new User(); $scope.addUser=function(){ $scope.user.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('users'); //redirect to home } if(response.status == 'error'){ console.log($scope.user) } }); } }]).controller('UserEditController',['$scope', '$state', '$stateParams', 'User', 'Role', function($scope,$state,$stateParams,User, Role){ //roles $scope.roles = Role.query(); $scope.updateProfile=function(){ $scope.user.$update(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('home'); //redirect to home } if(response.status == 'wrpass'){ $scope.user=response.data; } }); }; $scope.loadUser=function(){ $scope.user=User.get({id:$stateParams.id}); }; $scope.loadUser(); }]) .controller('UserLoginController',['$scope', '$state', '$stateParams', 'Session', function($scope,$state,$stateParams,Session){ $scope.session=new Session(); $scope.login=function(){ $scope.session.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ //$('#logPlaceHolder').attr('href', '/logout').children('span').text('Log Out'); //$state.go('home'); //redirect to home window.location='/home'; return false; } $scope.loginForm.$setPristine(); $scope.loginForm.$setValidity(); $scope.loginForm.$setUntouched(); }); } $scope.logout=function(){ $scope.session.$destroy(function(response){ $scope.message = response; if(response.status == 'ok'){ window.location = '/login'; } }) } }]) .controller('UserForgotController',['$scope', '$state', '$stateParams', 'User', function($scope,$state,$stateParams,User){ $scope.User=new User(); $scope.forgot=function(){ $scope.user.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('users'); //redirect to home } }); } }]);<file_sep>class PraxisController < ApplicationController def index @praxis = Praxi.order(params[:sort]).all @total_count = @praxis.count(:all) @limit = params[:limit].to_i @limited_orgs = @praxis.paginate(:page => params[:offset], :per_page => @limit) @response = { :praxis => @limited_orgs, :count => @total_count } respond_with @response end def new end def create respond_to do |format| praxiParams = praxi_params; praxiParams[:praxis_code] = praxi_params[:org_code].upcase + '-' + praxi_params[:client_code].upcase + '-' + praxi_params[:realm_code].upcase + '-' + praxi_params[:prosess_code].upcase + '-' + praxi_params[:stage_code].upcase @praxi = Praxi.find_by_praxis_code(praxiParams[:praxis_code]) if(@praxi) format.json do render :json => { :status => :exists, :message => 'Sorry! Praxi already exists.' }.to_json end else if Praxi.create(praxiParams) format.json do render :json => { :status => :ok, :message => 'Praxi has been added successfully.' }.to_json end else format.json do render :json => { :message => @praxi.errors, :status => :error #unprocessable_entity }.to_json end end end end end def show respond_with Praxi.find(params[:id]) end def edit respond_with Praxi.find(params[:id]) end def update @praxi = Praxi.find(params[:id]) respond_to do |format| if @praxi.update(praxi_params) format.json do render :json => { :status => :ok, :message => "Praxi was successfully updated.!" }.to_json end else format.json do render :json => { :message => @praxi.errors, :status => :error #unprocessable_entity }.to_json end end end end def destroy @praxi = Praxi.find(params[:id]) respond_to do |format| if @praxi.destroy format.json do render :json => { :status => :ok, :message => "Praxi was successfully deleted.!" }.to_json end else format.json do render :json => { :message => @praxi.errors, :status => :error #unprocessable_entity }.to_json end end end end private def praxi_params params.require(:praxi).permit(:org_code, :client_code,:milestone_key, :realm_code, :prosess_code, :stage_code, :sequence, :sla, :tolerance_percentage, :critical) if params[:praxi] end end <file_sep>class MilestoneSerializer < ActiveModel::Serializer attributes :id, :org_code, :client_code, :key, :realm_code end <file_sep>class OrgsController < ApplicationController before_action :set_org, only: [:show, :edit, :update, :destroy] def index @orgs = Org.search(params) render json: @orgs end def create @org = Org.new(org_params) result = if @org.save {message: 'Organization was successfully created!', status: :ok} else {message: @org.errors, status: :error} end render json: result.to_json end def show render json: @org end def edit render json: @org end def update result = if @org.update(org_params) {message: 'Organization was successfully updated!', status: :ok} else {message: @org.errors, status: :error} end render json: result.to_json end def destroy result = if @org.destroy {message: 'Organization was successfully deleted!', status: :ok} else {message: @org.errors, status: :error} end render json: result.to_json end private def set_org @org = Org.find(params[:id]) end def org_params params.require(:org).permit(:name, :code) end end<file_sep>class AddClientMilestoneRealmProsessStageColumnsToEvents < ActiveRecord::Migration def change add_column :events, :client_code, :string add_column :events, :milestone_key, :string add_column :events, :realm_code, :string add_column :events, :prosess_code, :string add_column :events, :stage_code, :string add_column :events, :sequence, :integer end end <file_sep># Sentinel This is a open source project which helps manage business process monitoring. ## Setup ``` ./reset.sh all rake db:seed foreman start ``` ## Run Tests ``` rspec spec ```<file_sep>class SettingsController < ApplicationController def index @response = {} @settings = Setting.all @settings.each do |row| @response[row.key] = row.value end respond_with @response.to_json end def create @saved = Setting.saveSettings(params) respond_to do |format| if @saved format.json do render :json => { :status => :ok, :message => "Settings was successfully updated.!" }.to_json end else format.json do render :json => { :message => @saved, :status => :error #unprocessable_entity }.to_json end end end end def update end end<file_sep>class CreatePraxis < ActiveRecord::Migration def change create_table :praxis do |t| t.string :praxis_code t.string :org_code t.string :client_code t.string :milestone_key t.string :realm_code t.string :prosess_code t.string :stage_code t.integer :sequence t.integer :sla t.integer :tolerance_percentage t.boolean :critical t.timestamps null: false end end end <file_sep>class RealmsController < ApplicationController def index if(params[:sort]) @realms = Realm.order(params[:sort]).all @total_count = @realms.count(:all) @limit = params[:limit].to_i @limited_realms = @realms.paginate(:page => params[:offset], :per_page => @limit) @response = { :realms => @limited_realms, :count => @total_count } else @response = Realm.all end respond_with @response end def new end def create respond_to do |format| if Realm.create(realm_params) format.json do render :json => { :status => :ok, :message => "Realm was successfully updated.!" }.to_json end else format.json do render :json => { :message => @realm.errors, :status => :error #unprocessable_entity }.to_json end end end end def show respond_with Realm.find(params[:id]) end def edit respond_with Realm.find(params[:id]) end def update @realm = Realm.find(params[:id]) respond_to do |format| if @realm.update(realm_params) format.json do render :json => { :status => :ok, :message => "Realm was successfully updated.!" }.to_json end else format.json do render :json => { :message => @realm.errors, :status => :error #unprocessable_entity }.to_json end end end end def destroy @realm = Realm.find(params[:id]) respond_to do |format| if @realm.destroy format.json do render :json => { :status => :ok, :message => "realm was successfully deleted.!" }.to_json end else format.json do render :json => { :message => @realm.errors, :status => :error #unprocessable_entity }.to_json end end end end private def realm_params params.require(:realm).permit(:name, :code) if params[:realm] end end <file_sep>class CreateCommunications < ActiveRecord::Migration def change create_table :communications do |t| t.string :org_code, limit: 20 t.string :client_code, limit: 20 t.string :primary_email t.string :secondary_email t.string :primary_phone t.string :secondary_phone t.timestamps null: false end end end <file_sep>if [ $# -eq 0 ] ; then echo 'preparing development database' rake db:drop rake db:create rake db:migrate rake db:seed echo " development environment are ready $(echo $'\xF0\x9F\x8D\xBA')" elif [ $1 == "test" ]; then echo 'preparing test database' RAILS_ENV=test rake db:drop RAILS_ENV=test rake db:create RAILS_ENV=test rake db:migrate echo " testing environment are ready $(echo $'\xF0\x9F\x8D\xBA')" elif [ $1 == "all" ]; then echo 'preparing development and test database' rake db:drop; rake db:create; rake db:migrate; rake db:seed & RAILS_ENV=test rake db:drop; RAILS_ENV=test rake db:create; RAILS_ENV=test rake db:migrate wait echo "both development and testing environment are ready $(echo $'\xF0\x9F\x8D\xBA')" fi <file_sep>class Api::V1::EventsController < ApplicationController protect_from_forgery with: :null_session def index logger.debug 'Hit Events index' @events = Event.all respond_with @events end def new end def create respond_to do |format| if Event.create(event_myparams) logger.debug 'Loggit ' + event_myparams.inspect format.json do render :json => { :status => :ok, :message => 'Event was created Successfully!' }.to_json end else format.json do render :json => { :status => :error, :message => @event.errors }.to_json end end end end def show respond_with Event.find(params[:id]) end def edit respond_with Event.find(params[:id]) end def update @event = Event.find(params[:id]) respond_to do |format| if @event.update(event_myparams) format.json do render :json => { :status => :ok, :message => "Event was successfully updated.!" }.to_json end else format.json do render :json => { :message => @event.errors, :status => :error #unprocessable_entity }.to_json end end end end def destroy @event = Event.find(params[:id]) respond_to do |format| if @event.destroy format.json do render :json => { :status => :ok, :message => "Event was successfully deleted.!" }.to_json end else format.json do render :json => { :message => @event.errors, :status => :error #unprocessable_entity }.to_json end end end end private def event_myparams params.require(:event).permit(:praxis_code, :event_id, :occurred_at, :zipcode, :country) if params[:event] end end <file_sep>module ApplicationHelper #def policy(record) # "#{record.class}Policy".constantize.new(current_user, record) #end #def authorise(record) # raise NotAuthorizedError unless policy(record).public_send(params[:action] + "?") #end end <file_sep>class LabelsController < ApplicationController def index if(params[:sort]) @labels = Label.order(params[:sort]).all @total_count = @labels.count(:all) @limit = params[:limit].to_i @limited_labels = @labels.paginate(:page => params[:offset], :per_page => @limit) @response = { :labels => @limited_labels, :count => @total_count } else @response = Label.all end respond_with @response end def new end def create respond_to do |format| Rails.logger.debug("My password: #{label_params}") if Label.create(label_params) format.json do render :json => { :status => :ok, :message => "Label was successfully Created.!" }.to_json end else format.json do render :json => { :message => @label.errors, :status => :error #unprocessable_entity }.to_json end end end end def show respond_with Label.find(params[:id]) end def edit respond_with Label.find(params[:id]) end def update @label = Label.find(params[:id]) respond_to do |format| if @label.update(label_params) format.json do render :json => { :status => :ok, :message => "Label was successfully updated.!" }.to_json end else format.json do render :json => { :message => @label.errors, :status => :error #unprocessable_entity }.to_json end end end end def destroy @label = Label.find(params[:id]) respond_to do |format| if @label.destroy format.json do render :json => { :status => :ok, :message => "Label was successfully deleted.!" }.to_json end else format.json do render :json => { :message => @label.errors, :status => :error #unprocessable_entity }.to_json end end end end private def label_params params.require(:label).permit(:org_code, :client_code, :key, :label_name,:realm_code,:icon) if params[:label] end end <file_sep>angular.module('Sentinel.labelsController', []) .controller('LabelController', ['$scope', '$state', '$window', 'Label', function($scope, $state, $window, Label){ $scope.main = { offset: 1, limit: 1, sort: 'label_name ASC', rowsArray: [ {id:1, label:'1 Per Page'}, {id:2, label:'2 Per Page'}, {id:3, label:'3 Per Page'} ], sortArray: [ {id:'org_code ASC',label:'Org Code (A-Z)'}, {id:'label_name ASC',label:'Label (A-Z)'} ] }; $scope.loadPage = function(page){ $scope.main.offset = page; Label.get({offset:$scope.main.offset, limit:$scope.main.limit, sort:$scope.main.sort}, function(data){ //var orgs = JSON.parse(data); // users from your api $scope.labels = data.labels; //alert(data.count); // total number of rows $scope.count = data.count; // number of pages of orgs $scope.pagesCount = data.count/$scope.main.limit; // build pages array var pagesArray = []; for(var p = 1; p < $scope.pagesCount+1; p++){ pagesArray.push(p); } $scope.pages = pagesArray; }); } $scope.loadPerPage = function(option){ $scope.main.limit = option; $scope.loadPage($scope.main.offset); } $scope.loadSortPage = function(option){ $scope.main.sort = option; $scope.loadPage($scope.main.offset); } $scope.loadPage(1);//fetch all orgs. Issues a GET to /api/orgs*/ //$scope.labels = Label.query(); $scope.deleteLabel = function(label) { // Delete a org. Issues a DELETE to /api/org/:id label.$delete(function(response) { $scope.message = response; if(response.status == 'ok'){ $state.go('labels'); //redirect to home } }); }; }] ) .controller('LabelViewController', ['$scope', '$stateParams' ,'Label', function($scope,$stateParams,Label){ $scope.label=Label.get({id:$stateParams.id}); }]) .controller('LabelCreateController', ['$scope', '$state', '$stateParams', 'Label', 'Org', 'Client','Realm','Upload', '$timeout', function($scope,$state,$stateParams,Label,Org,Client,Realm,Upload, $timeout){ $scope.label=new Label(); //orgs $scope.orgs = Org.query(); //clients $scope.clients = Client.query(); $scope.realms = Realm.query(); $scope.uploadFiles = function(file) { $scope.f = file; if (file && !file.$error) { file.upload = Upload.upload({ url: 'images/', file: file }); file.upload.then(function (response) { $timeout(function () { $scope.label.icon=response.data.filename; file.result = response.data; }); }, function (response) { if (response.status > 0) $scope.errorMsg = response.status + ': ' + response.data; }); } } $scope.addLabel=function(){ $scope.label.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('labels'); //redirect to home } if(response.status == 'exists'){ return false; //redirect to home } }); } }]).controller('LabelEditController', ['$scope', '$state', '$stateParams', 'Label', 'Org', 'Client','Realm','Upload', '$timeout', function($scope,$state,$stateParams,Label,Org,Client,Realm,Upload, $timeout){ //orgs $scope.orgs = Org.query(); //clients $scope.clients = Client.query(); $scope.realms = Realm.query(); $scope.uploadFiles = function(file) { $scope.f = file; if (file && !file.$error) { file.upload = Upload.upload({ url: 'images/', file: file }); file.upload.then(function (response) { $timeout(function () { $scope.label.icon=response.data.filename; file.result = response.data; }); }, function (response) { if (response.status > 0) $scope.errorMsg = response.status + ': ' + response.data; }); } } $scope.updateLabel=function(){ $scope.label.$update(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('labels'); //redirect to home } }); }; $scope.loadLabel=function(){ $scope.label=Label.get({id:$stateParams.id}); }; $scope.loadLabel(); }]); <file_sep>angular.module('Sentinel.jobsController', []) .controller('JobController', ['$scope', '$state', '$window', 'Job', function($scope, $state, $window, Job){ $scope.main = { offset: 1, limit: 1, sort: 'job_code ASC', rowsArray: [ {id:1, label:'1 Per Page'}, {id:2, label:'2 Per Page'}, {id:3, label:'3 Per Page'} ], sortArray: [ {id:'job_code ASC', label:'Name (A-Z)'}, {id:'job_code DESC',label:'Name (Z-A)'}, {id:'name ASC', label:'Code (A-Z)'}, {id:'name DESC',label:'Code (Z-A)'} ] }; $scope.loadPage = function(page){ $scope.main.offset = page; Job.get({offset:$scope.main.offset, limit:$scope.main.limit, sort:$scope.main.sort}, function(data){ //var orgs = JSON.parse(data); // users from your api $scope.jobs = data.jobs; // total number of rows $scope.count = data.count; // number of pages of orgs $scope.pagesCount = data.count/$scope.main.limit; // build pages array var pagesArray = []; for(var p = 1; p < $scope.pagesCount+1; p++){ pagesArray.push(p); } $scope.pages = pagesArray; }); } $scope.loadPerPage = function(option){ $scope.main.limit = option; $scope.loadPage($scope.main.offset); } $scope.loadSortPage = function(option){ $scope.main.sort = option; $scope.loadPage($scope.main.offset); } $scope.loadPage(1);//fetch all orgs. Issues a GET to /api/orgs $scope.deleteJob = function(job) { // Delete a org. Issues a DELETE to /api/org/:id job.$delete(function(response) { $scope.message = response; if(response.status == 'ok'){ $state.go('jobs'); //redirect to home } }); }; }] ) .controller('JobViewController', ['$scope', '$stateParams' ,'Job', function($scope,$stateParams,Job){ $scope.job=Job.get({id:$stateParams.id}); }]) .controller('JobCreateController',['$scope', '$state', '$stateParams', 'Job', 'Org', 'Client', function($scope,$state,$stateParams,Job,Org,Client){ $scope.job=new Job(); //orgs $scope.orgs = Org.query(); //clients $scope.clients = Client.query(); $scope.addJob=function(){ $scope.job.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('jobs'); //redirect to home } if(response.status == 'exists'){ return false; //redirect to home } }); } }]).controller('JobEditController',['$scope', '$state', '$stateParams', 'Job', 'Org', 'Client', function($scope,$state,$stateParams,Job,Org,Client){ //orgs $scope.orgs = Org.query(); //clients $scope.clients = Client.query(); $scope.updateJob=function(){ $scope.job.$update(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('jobs'); //redirect to home } }); }; $scope.loadJob=function(){ $scope.job=Job.get({id:$stateParams.id}); }; $scope.loadJob(); }]);<file_sep>desc 'job runner check' task job_runner_check: :environment do options = []; JobMailer.check_job_running_status(options).deliver_now! end<file_sep>class Setting < ActiveRecord::Base def self.saveSettings(setting_params) begin setting_params.each do |key, value| if(key!='format' && key != 'controller' && key !='action') @existingSetting = Setting.find_by(key: key) if(!@existingSetting.blank?) option_values = {} if(value.is_a?(Array)) value.each do |option_value| option_values[]= option_value end @existingSetting.update_attributes(key: key, value: option_values) else @existingSetting.update_attributes(key: key, value: value) end @existingSetting.save else @setting = Setting.new(key: key, value: value) @setting.save end end end return true rescue => ex return ex.message end return false end def self.fetchAttribute(attribute) settingObj = Setting.where(:key => attribute).first if !settingObj.blank? value = settingObj.value return value else self.getDefaultValues(attribute) end end def self.getDefaultValues(attribute) puts case attribute when 'time_zone' return Time.zone when 'limitofrows' return 10 end end def self.getTimeZone Rails.logger.debug("My password: #{'from application' + Time.zone.name}") end end <file_sep>class RealmPolicy < ApplicationPolicy attr_reader :user, :realm def initialize(current_user, relam) raise Pundit::NotAuthorizedError, "must be logged in" unless current_user @current_user = current_user @realm = realm end def index? #before(:each) { user.roles << create(:role, activities: %w(person:show)) } #user.admin? or not realm.published? end def create? user.admin? or not realm.published? end end<file_sep>module Searchable def search(params) results = self.all page = (params[:offset] || 1).to_i per_page = (params[:limit] || 25).to_i if params[:sort] sort = params[:sort].split(' ') sort_key = sort[0] sort_dir = sort[1] results = results.order("LOWER(#{sort_key}) #{sort_dir}") end results = results.paginate(page: page, per_page: per_page) total_pages = results.total_pages total_count = results.total_entries meta = {page: page, per_page: per_page, total_pages: total_pages, total_count: total_count} ActiveModel::ArraySerializer.new(results, root: self.to_s.pluralize.downcase, meta: meta, each_serializer: "#{self.to_s}Serializer".constantize).to_json end end<file_sep>class ChangeIndexCriticalColumnToString < ActiveRecord::Migration def change change_column :indices, :critical, :string end end <file_sep>class JobSerializer < ActiveModel::Serializer attributes :id, :org_code, :job_code, :client_code, :name, :description end<file_sep>class Run < ActiveRecord::Base end <file_sep>angular.module('Sentinel.roles', []) .factory('Role', function($resource){console.log($resource) return $resource('/api/roles/:id',{id:'@id'},{ update: { method: 'PUT' } }); });<file_sep>angular.module('Sentinel.orgsController', []) .controller('OrgController', ['$scope', '$state', '$window', 'Org', function($scope, $state, $window, Org){ $scope.main = { offset: 1, limit: 3, sort: 'name ASC', rowsArray: [ {id:10, label:'10 Per Page'}, {id:50, label:'50 Per Page'}, {id:100, label:'100 Per Page'}, {id:9999, label:'Show All'} ], sortArray: [ {id:'name ASC', label:'Name (A-Z)'}, {id:'name DESC',label:'Name (Z-A)'}, {id:'code ASC', label:'Code (A-Z)'}, {id:'code DESC',label:'Code (Z-A)'} ] }; $scope.loadPage = function(page){ $scope.main.offset = page; Org.get({offset:$scope.main.offset, limit:$scope.main.limit, sort:$scope.main.sort}, function(data){ $scope.orgs = data.orgs; // total number of rows $scope.count = data.meta.total_count; $scope.pagesCount = data.meta.total_pages; // build pages array var pagesArray = []; for(var p = 1; p < $scope.pagesCount+1; p++){ pagesArray.push(p); } $scope.pages = pagesArray; }); } $scope.loadPerPage = function(option){ $scope.main.limit = option; $scope.loadPage($scope.main.offset); } $scope.loadSortPage = function(option){ $scope.main.sort = option; $scope.loadPage($scope.main.offset); } $scope.loadPage(1);//fetch all orgs. Issues a GET to /api/orgs $scope.deleteOrg = function(id) { // Delete a org. Issues a DELETE to /api/org/:id Org.delete({id: id}, function(response) { $scope.message = response; if(response.status == 'ok'){ //$state.go('orgs', {}); //redirect to orgs $scope.loadPage($scope.main.offset); } }); }; }] ) .controller('OrgViewController', ['$scope', '$stateParams' ,'Org', function($scope,$stateParams,Org){ $scope.org=Org.get({id:$stateParams.id}); }]) .controller('OrgCreateController',['$scope', '$state', '$stateParams', 'Org', function($scope,$state,$stateParams,Org){ $scope.org=new Org(); $scope.addOrg=function(){ $scope.org.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('orgs'); //redirect to home } }); } }]).controller('OrgEditController',['$scope', '$state', '$stateParams', 'Org', function($scope,$state,$stateParams,Org){ $scope.updateOrg=function(){ $scope.org.$update(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('orgs'); //redirect to home } }); }; $scope.loadOrg=function(){ $scope.org=Org.get({id:$stateParams.id}); }; $scope.loadOrg(); }]);<file_sep>source 'https://rubygems.org' ruby '2.2.1' gem 'rails', '4.2.0' gem 'sqlite3' gem 'rails_12factor', group: :production gem 'sass-rails', '~> 4.0.3' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.0.0' gem 'jquery-rails' gem 'puma' gem 'tzinfo-data' gem 'tzinfo' #gem 'cowsay' gem 'angularjs-rails', '~> 1.3.15' gem 'angular-rails-templates' gem 'whenever', require: false gem 'double-bag-ftps' #ftps gem 'settingslogic' #for settings application.yml gem 'slim' gem 'bcrypt', '3.1.9' gem 'responders', '~> 2.0' gem 'will_paginate', '~> 3.0.4' gem 'angular_rails_csrf' gem 'pundit' gem 'quiet_assets' gem 'active_model_serializers' group :development, :test do gem 'byebug' gem 'rspec-rails', '~> 3.0' gem 'factory_girl_rails' gem 'database_cleaner' gem 'faker' gem 'shoulda-matchers', '~> 3.0' gem 'timecop' end group :development do gem 'web-console', '~> 2.0' gem 'spring' gem 'letter_opener' end # group :development do # gem 'sqlite3' # end # # # Use postgresql as the database for Active Record # group :production do # gem 'mysql2' # end<file_sep>class SessionsController < ApplicationController skip_before_action :authenticate_user!, only: [:index, :create] layout 'login' def index @current_user ||= User.find_by(id: session[:user_id]) if(@current_user) redirect_to '/home#index' end end def new end def create @user = User.where(email: params[:email]).first respond_to do |format| if @user && @user.authenticate(@user, params[:password]) log_in @user params[:remember_me] == true ? remember(@user) : forget(@user) format.json do render :json => { :status => :ok, :message => "User logged in successfully!" }.to_json end else format.json do render :json => { :message => "Please check email/password and try again.", :status => :error #unprocessable_entity }.to_json end end end end def destroy log_out redirect_to '/login' end end <file_sep>class ClientsController < ApplicationController before_action :set_client, only: [:show, :edit, :update, :destroy] def index @clients = Client.search(params) render json: @clients end def create @client = Client.new(client_params) result = if @client.save {message: 'Client was successfully created!', status: :ok} else {message: @client.errors, status: :error} end render json: result.to_json end def show render json: @client end def edit render json: @client end def update result = if @client.update(client_params) {status: :ok, message: 'Client was successfully updated!'} else {status: :error, message: @client.errors} end render json: result.to_json end def destroy result = if @client.destroy {status: :ok, message: 'Client was successfully deleted!'} else {status: :ok, message: @client.errors} end render json: result.to_json end private def set_client @client = Client.find(params[:id]) end def client_params params.require(:client).permit(:name, :code, :org_id) end end <file_sep>angular.module('Sentinel.communications', []) .factory('Communication', function($resource){ return $resource('/api/communications/:id',{id:'@id'},{ update: { method: 'PUT' } }); });<file_sep>class StageSerializer < ActiveModel::Serializer attributes :id, :name, :critical end <file_sep>class ImagesController < ApplicationController def index end def create name = params[:file].original_filename only_name= File.basename(name, ".*" ) ext=File.extname(name) directory = Rails.root.join('app', 'assets', 'upload') countv=Dir[File.join(directory, '**', '*')].count nname=only_name + '-' + countv.to_s + ext path = File.join(directory, name) File.open(path, "wb") { |f| f.write(params[:file].read) } flash[:notice] = "File uploaded" render :json => { :status => :ok, :message => "file upload", :filename=>nname }.to_json end def show end end <file_sep>class MilestonesController < ApplicationController def index if(params[:sort]) @milestones = Milestone.order(params[:sort]).all @total_count = @milestones.count(:all) @limit = params[:limit].to_i @limited_milestones = @milestones.paginate(:page => params[:offset], :per_page => @limit) @response = { :milestones => @limited_milestones, :count => @total_count } else @response = Milestone.all end respond_with @response end # def index # @response = Milestone.all # respond_with @response # end def new end def create respond_to do |format| Rails.logger.debug("My password: #{milestone_params}") if Milestone.create(milestone_params) format.json do render :json => { :status => :ok, :message => "Milestone was successfully Created.!" }.to_json end else format.json do render :json => { :message => @milestone.errors, :status => :error #unprocessable_entity }.to_json end end end end def show respond_with Milestone.find(params[:id]) end def edit respond_with Milestone.find(params[:id]) end def update @milestone = Milestone.find(params[:id]) respond_to do |format| if @milestone.update(label_params) format.json do render :json => { :status => :ok, :message => "Milestone was successfully updated.!" }.to_json end else format.json do render :json => { :message => @milestone.errors, :status => :error #unprocessable_entity }.to_json end end end end def destroy @milestone = Milestone.find(params[:id]) respond_to do |format| if @milestone.destroy format.json do render :json => { :status => :ok, :message => "milestone was successfully deleted.!" }.to_json end else format.json do render :json => { :message => @milestone.errors, :status => :error #unprocessable_entity }.to_json end end end end private def milestone_params params.require(:milestone).permit(:org_code, :client_code, :key,:realm_code) if params[:milestone] end end <file_sep>angular.module('Sentinel.stagesController', []) .controller('stageController', ['$scope', '$state', '$window', 'Stage', function($scope, $state, $window, Stage) { $scope.main = { offset: 1, limit: 1, sort: 'name ASC', rowsArray: [ {id:1, label:'1 Per Page'}, {id:2, label:'2 Per Page'}, {id:3, label:'3 Per Page'} ], sortArray: [ {id:'name ASC', label:'Name (A-Z)'}, {id:'name DESC',label:'Name (Z-A)'}, {id:'code ASC', label:'Code (A-Z)'}, {id:'code DESC',label:'Code (Z-A)'} ] }; $scope.loadPage = function(page){ $scope.main.offset = page; Stage.get({offset:$scope.main.offset, limit:$scope.main.limit, sort:$scope.main.sort}, function(data){ $scope.stages = data.stages; // total number of rows $scope.count = data.count; $scope.pagesCount = data.count/$scope.main.limit; // build pages array var pagesArray = []; for(var p = 1; p < $scope.pagesCount+1; p++){ pagesArray.push(p); } $scope.pages = pagesArray; }); } $scope.loadPerPage = function(option){ $scope.main.limit = option; $scope.loadPage($scope.main.offset); } $scope.loadSortPage = function(option){ $scope.main.sort = option; $scope.loadPage($scope.main.offset); } $scope.loadPage(1);//fetch all clients. Issues a GET to /api/clients $scope.deleteStage = function(stage) { // Delete a client. Issues a DELETE to /api/client/:id stage.$delete(function(response) { $scope.message = response; if(response.status == 'ok'){ $state.go('stages'); //redirect to home } }); }; }] ) /*{ $scope.stages = Stage.query(); //fetch all Stages. Issues a GET to /api/Stages $scope.deleteStage = function(stage) { // Delete a Stage. Issues a DELETE to /api/Stage/:id stage.$delete(function(response) { $scope.message = response; if(response.status == 'ok'){ $state.go('stages'); //redirect to home } }); }; }] )*/ .controller('StageViewController', ['$scope', '$stateParams' ,'Stage', function($scope,$stateParams,Stage){ $scope.stage=Stage.get({id:$stateParams.id}); }]) .controller('StageCreateController',['$scope', '$state', '$stateParams', 'Stage', function($scope,$state,$stateParams,Stage){ $scope.stage=new Stage(); $scope.addStage=function(){ $scope.stage.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('stages'); //redirect to home } }); } }]).controller('StageEditController',['$scope', '$state', '$stateParams', 'Stage', function($scope,$state,$stateParams,Stage){ $scope.updateStage=function(){ $scope.stage.$update(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('stages'); //redirect to home } }); }; $scope.loadStage=function(){ $scope.stage=Stage.get({id:$stateParams.id}); }; $scope.loadStage(); }]); <file_sep>class IndicesController < ApplicationController def index if(params[:sort]) @indices = Index.order(params[:sort]).all @total_count = @indices.count(:all) @limit = params[:limit].to_i @limited_indices = @indices.paginate(:page => params[:offset], :per_page => @limit) @response = { :indices => @limited_indices, :count => @total_count } else @response = Index.all end respond_with @response end def new end def create respond_to do |format| indiceParams = indice_params; indiceParams[:jobkey] = indiceParams[:job_code].upcase + '-' + indiceParams[:realm_code].upcase indiceParams[:cron] = Index.buildCron(params) @indice = Index.find_by_jobkey(indiceParams[:jobkey]) if(@indice) format.json do render :json => { :status => :exists, :message => 'Sorry! Indice already exists.' }.to_json end else if Index.create(indiceParams) format.json do render :json => { :status => :ok, :message => 'Indice has been added successfully.' }.to_json end else format.json do render :json => { :message => @indice.errors, :status => :error #unprocessable_entity }.to_json end end end end end def show respond_with Index.find(params[:id]) end def edit respond_with Index.find(params[:id]) end def update @indice = Index.find(params[:id]) respond_to do |format| if @indice.update(indice_params) format.json do render :json => { :status => :ok, :message => "Indice was successfully updated.!" }.to_json end else format.json do render :json => { :message => @indice.errors, :status => :error #unprocessable_entity }.to_json end end end end def destroy @indice = Index.find(params[:id]) respond_to do |format| if @indice.destroy format.json do render :json => { :status => :ok, :message => "Indice was successfully deleted.!" }.to_json end else format.json do render :json => { :message => @indice.errors, :status => :error #unprocessable_entity }.to_json end end end end private def indice_params params.require(:index).permit(:job_code, :realm_code, :critical, :notify, :run_length, :success_step) if params[:index] end end <file_sep>class ProsessesController < ApplicationController def index if(params[:sort]) @prosesses = Prosess.order(params[:sort]).all @total_count = @prosesses.count(:all) @limit = params[:limit].to_i @limited_prosesses = @prosesses.paginate(:page => params[:offset], :per_page => @limit) @response = { :prosesses => @limited_prosesses, :count => @total_count } else @response = Prosess.all end respond_with @response end def new end def create respond_to do |format| if Prosess.create(prosess_params) format.json do render :json => { :status => :ok, :message => "Process was successfully updated.!" }.to_json end else format.json do render :json => { :message => @prosess.errors, :status => :error #unprocessable_entity }.to_json end end end end def show respond_with Prosess.find(params[:id]) end def edit respond_with Prosess.find(params[:id]) end def update @prosess = Prosess.find(params[:id]) respond_to do |format| if @prosess.update(prosess_params) format.json do render :json => { :status => :ok, :message => "Process was successfully updated.!" }.to_json end else format.json do render :json => { :message => @prosess.errors, :status => :error #unprocessable_entity }.to_json end end end end def destroy @prosess = Prosess.find(params[:id]) respond_to do |format| if @prosess.destroy format.json do render :json => { :status => :ok, :message => "Process was successfully deleted.!" }.to_json end else format.json do render :json => { :message => @prosess.errors, :status => :error #unprocessable_entity }.to_json end end end end private def prosess_params params.require(:prosess).permit(:name, :code) if params[:prosess] end end <file_sep>class Praxi < ActiveRecord::Base validates :org_code, presence: true validates :client_code, presence: true validates :milestone_key, presence: true validates :realm_code, presence: true validates :prosess_code, presence: true validates :stage_code, presence: true validates :sequence, presence: true validates :sla, presence: true validates :tolerance_percentage, presence: true #, length: { in: 3..10 }, uniqueness: { case_sensitive: false } end <file_sep>class Label < ActiveRecord::Base validates :org_code, presence: true validates :client_code, presence: true validates :key, presence: true validates :label_name, presence: true validates :realm_code, presence: true validates :icon, presence: true end <file_sep>class Client < ActiveRecord::Base extend Searchable belongs_to :org validates :name, presence: true validates :code, presence: true, length: { in: 3..10 }, uniqueness: { case_sensitive: false } validates :org_code, presence: true before_validation :set_org_code private def set_org_code self.org_code = self.org.code end end <file_sep>class Job < ActiveRecord::Base validates :job_code, presence: true validates :org_code, presence: true validates :client_code, presence: true validates :name, presence: true def self.isJobCodeExists(params) @result = Job.where('job_code = ? and org_code = ?', params['job_code'], params['org_code']) return @result end end <file_sep>angular.module('Sentinel.praxisController', []) .controller('PraxiController', ['$scope', '$state', '$window', 'Praxi', function($scope, $state, $window, Praxi){ $scope.main = { offset: 1, limit: 1, sort: 'praxis_code ASC', rowsArray: [ {id:1, label:'1 Per Page'}, {id:2, label:'2 Per Page'}, {id:3, label:'3 Per Page'} ], sortArray: [ {id:'praxis_code ASC', label:'Praxi Code (A-Z)'}, {id:'org_code ASC',label:'Org Code (A-Z)'}, {id:'client_code ASC', label:'Client Code (A-Z)'}, {id:'realm_code ASC',label:'Realm Code (A-Z)'}, {id:'prosess_code ASC',label:'Process Code (A-Z)'}, {id:'stage_code ASC',label:'Stage Code (A-Z)'} ] }; $scope.loadPage = function(page){ $scope.main.offset = page; Praxi.get({offset:$scope.main.offset, limit:$scope.main.limit, sort:$scope.main.sort}, function(data){ //var orgs = JSON.parse(data); // users from your api $scope.praxis = data.praxis; // total number of rows $scope.count = data.count; // number of pages of orgs $scope.pagesCount = data.count/$scope.main.limit; // build pages array var pagesArray = []; for(var p = 1; p < $scope.pagesCount+1; p++){ pagesArray.push(p); } $scope.pages = pagesArray; }); } $scope.loadPerPage = function(option){ $scope.main.limit = option; $scope.loadPage($scope.main.offset); } $scope.loadSortPage = function(option){ $scope.main.sort = option; $scope.loadPage($scope.main.offset); } $scope.loadPage(1);//fetch all orgs. Issues a GET to /api/orgs $scope.deletePraxi = function(praxi) { // Delete a org. Issues a DELETE to /api/org/:id praxi.$delete(function(response) { $scope.message = response; if(response.status == 'ok'){ $state.go('praxis'); //redirect to home } }); }; }] ) .controller('PraxiViewController', ['$scope', '$stateParams' ,'Praxi', function($scope,$stateParams,Praxi){ $scope.praxi=Praxi.get({id:$stateParams.id}); }]) .controller('PraxiCreateController', ['$scope', '$state', '$stateParams', 'Praxi', 'Org', 'Client', 'Realm', 'Prosess', 'Stage', 'Milestone', function($scope,$state,$stateParams,Praxi,Org,Client,Realm,Prosess,Stage,Milestone){ $scope.praxi=new Praxi(); //orgs $scope.orgs = Org.query(); //clients $scope.clients = Client.query(); //Realm $scope.realms = Realm.query(); //prosess $scope.prosesses = Prosess.query(); //stage $scope.stages = Stage.query(); //milestone $scope.milestones = Milestone.query(); $scope.addPraxi=function(){ $scope.praxi.$save(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('praxis'); //redirect to home } if(response.status == 'exists'){ return false; //redirect to home } }); } }]).controller('PraxiEditController', ['$scope', '$state', '$stateParams', 'Praxi', 'Org', 'Client', 'Realm', 'Prosess', 'Stage','Milestone', function($scope,$state,$stateParams,Praxi,Org,Client,Realm,Prosess,Stage,Milestone){ //orgs $scope.orgs = Org.query(); //clients $scope.clients = Client.query(); //Realm $scope.realms = Realm.query(); //prosess $scope.prosesses = Prosess.query(); //stage $scope.stages = Stage.query(); $scope.milestones = Milestone.query(); $scope.updatePraxi=function(){ $scope.praxi.$update(function(response){ $scope.message = response; if(response.status == 'ok'){ $state.go('praxis'); //redirect to home } }); }; $scope.loadPraxi=function(){ $scope.praxi=Praxi.get({id:$stateParams.id}); }; $scope.loadPraxi(); }]);<file_sep>class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. include Pundit include SessionsHelper include ApplicationHelper respond_to :json protect_from_forgery with: :exception before_filter :authenticate_user! before_filter :render_layout_only, if: proc { request.format.html? } # Globally rescue Authorization Errors in controller. # Returning 403 Forbidden if permission is denied rescue_from Pundit::NotAuthorizedError, with: :permission_denied # Enforces access right checks for individuals resources #after_filter :verify_authorized, :except => [:index, :sessions] # Enforces access right checks for collections #after_filter :verify_policy_scoped, :only => :index #private #def user_not_authorized #flash[:alert] = "You are not authorized to perform this action." #redirect_to(request.referrer || root_path) #end def authenticate_user! redirect_to login_url, alert: "Not authorized" if current_user.nil? end helper_method :current_user private def render_layout_only render text: '', layout: true end def permission_denied render(file: File.join(Rails.root, 'public/403.html'), status: 403, layout: false) end end <file_sep>Rails.application.routes.draw do scope :api, defaults: { format: 'json' } do resources :orgs resources :settings resources :jobs resources :indices resources :prosesses resources :communications resources :realms resources :clients resources :milestones resources :stages resources :praxis resources :sessions resources :labels resources :users resources :roles namespace :v1 do resources :events end end get 'login', to: 'sessions#index', as: 'login' get 'sessions', to: 'sessions#create', as: 'logon' get 'logout', to: 'sessions#destroy', as: 'logout' get "/*path" => redirect("/?goto=%{path}") root to: 'home#index' end <file_sep>class Communication < ActiveRecord::Base validates :org_code, presence: true validates :client_code, presence: true validates :primary_email, presence: true validates :secondary_email, presence: true validates :primary_phone, presence: true validates :secondary_phone, presence: true end <file_sep>angular.module('Sentinel.stages', []) .factory('Stage', function($resource){ return $resource('/api/stages/:id',{id:'@id'},{ update: { method: 'PUT' } }); });<file_sep>class RemoveClientCodeFromIndices < ActiveRecord::Migration def change remove_column :indices, :client_code, :string end end <file_sep>FactoryGirl.define do factory :client do org { build_stubbed(:org) } name { Faker::Company.name } code { Faker::Lorem.characters(5) } end end
19927c447eebda1025a87024073260371a7f1dea
[ "JavaScript", "Ruby", "Markdown", "Shell" ]
82
Ruby
poorananb/sentinel
1d4530eaacab5070e275a0a5e53293c1c9a2afe8
f156f3733fe51e9ecdf453f689250b46ac74012a
refs/heads/master
<file_sep>import numpy as np import random as rn def portText(file): """This function imports a text file as a reference""" with open(file,'r') as tex: ref = tex.read().split() return ref def portMat(file): """This funciton imports an already existing matrix to describe the probabilities of each word occuring with relation to each other""" with open(file,'r') as t: q = t.read().split("\n") l = len(q) - 1 voc = q[-1].split() M = np.zeros((l,l)) for i in range(l): for j in range(l): M[i,j] = q[i].split()[j] return voc,M def expMat(name,voc,M): """This funciton exports an already existing matrix to describe the probabilities of each word occuring with relation to each other""" doc = open(name,'w+') s = "" for i in range(len(M)): for j in range(len(M)): s += str(M[i,j]) s += " " s += "\n" for i in range(len(voc)): s += voc[i] s += " " doc.write(s) doc.close() print("{0} created.".format(name)) def getMat(ref): """Creates the matrix to get the probabilities needed to generate sentences""" voc = list(set(ref)) M = np.zeros((len(voc),len(voc))) for n in range(len(ref) - 1): for m in range(len(voc)): if ref[n] == voc[m]: M[voc.index(ref[n + 1]),m] += 1 for n in range(len(voc)): if sum(M[:,n]) == 0: M[:,n] += 1 return voc,M def genSent(voc,M,N = 1): """Generates a sentence based on a given vocabulary and matrix""" s = "" q = 0 caps = [] W = np.zeros((len(voc))) for n in range(len(voc)): W[n] = sum(M[:,n]) if voc[n][0].isupper(): caps.append(n) a = caps[rn.randint(0,len(caps) - 1)] while q < N: s += voc[a] s += " " if voc[a][-1] in ['.','?','!']: q += 1 b = rn.randint(1,W[a]) c = 0 while b > 0: b -= M[c,a] c += 1 a = c - 1 return s <file_sep># HonorsContract The file mchain.py is a library to create markov chains and use them to generate sentences. the included .txt file "extext.txt" is an example text file made up of the introduciton from the Wikipedia article for books. The functions included in this file are: (1) portText, (2) getMat, (3) genSent, (4) expMat, (5) portMat (1) "Import text file" returns a <list> of the words in the text file in order. portText(filename) filename - <string> stating the name of the file containing the reference text (2) "Get probability matrix" returns a <list> of the vocabulary & <numpy.array> of probability weights based on the relationships of the words in the refrence text getMat(ref) ref - <list> of words reference text (3) "Generate sentence" returns a <string> randomly generated sentence genSent(voc,mat,N = 1) voc - <list> of vocabulary words mat - <numpy.array> describing the probabilities of each word to follow a previous word N - (optional) <int> number of sentences to generate (4) "Export matrix" creates a file storing the information for the matrix generated by the getMat function. expMat(name,voc,mat) name - <string> the name of the file voc - <list> of vocabulary words mat - <numpy.array> describing the probabilities of each word to follow a previous word (5) "Import matrix" returns a a <list> of vocabulary & <numpy.array> of probability weights based on the relationships of words. Data imported from an existing file,rather then generated. portMat(filename) filename - <string> stating the name of the file containing the reference text <file_sep>"""This file is here to generate example sentences""" """A long list of examples of my code can be found at www.jesus-speak.tumblr.com where an automated code is posting once every 6 hours based on the Bible""" import sys sys.path.append('../') import mchain as mc tex = input("Name the file you want the sentences based on, or enter none to use the default\n--> ") n = input("How many sentences do you want to generate? (Defaults to 1)\n--> ") if n == "": n = 1 else: n = int(n) if tex == "": doc = mc.portText("extext.txt") else: doc = mc.portText(tex) voc,M = mc.getMat(doc) s = mc.genSent(voc,M,n) print("\n",s) if input("\nShould this be saved? (y/[n])\n--> ") == "y": R = open("examples.txt",'r') t = R.read() R.close() t += "\n\n" t += s R = open("examples.txt",'w') R.write(t) R.close()
dc360d07b5a5c643a50bb71097ace26bd1f96a5d
[ "Markdown", "Python" ]
3
Python
tunaLandslide/HonorsContract
cb5014d48da9f6e694ff935716e5c00406524882
1949bd155396b684f5c7262251456a26d426f78d
refs/heads/master
<repo_name>masenmatthews/Rails_AJAX_CodeReview<file_sep>/app/models/user.rb class User < ApplicationRecord has_secure_password has_many :orders validates :password, :presence => true, length: { in: 6..18 }, :on => :create validates :password, :confirmation => true, length: { in: 6..18 }, :on => :update def previous_orders self.orders.where(status: 2).includes(order_items: :product) end end <file_sep>/app/controllers/carts_controller.rb class CartsController < ApplicationController def show if current_user @previous_orders = current_user.previous_orders @order = current_order.update_total end @order_items = current_order.order_items end def finalize if current_user current_order.finalize(current_user) session[:order_id] = nil redirect_to cart_path else flash[:alert] = "You need to sign up or sign in to complete your order." redirect_to sign_in_path end end def create # Amount in cents @amount = 5000 customer = Stripe::Customer.create( :email => params[:stripeEmail], :source => params[:stripeToken] ) charge = Stripe::Charge.create( :customer => customer.id, :amount => @amount, :description => 'Rails Stripe customer', :currency => 'usd' ) rescue Stripe::CardError => e flash[:error] = e.message redirect_to new_charge_path end end <file_sep>/app/models/order.rb class Order < ApplicationRecord has_many :order_items belongs_to :user, optional: true before_save :calculate_total def calculate_total self.total_price = order_items.collect { |item| item.product.price * item.quantity }.sum end def update_total self.total_price = calculate_total end def finalize(user) self.user_id = user.id self.status = 2 self.save end end <file_sep>/config/initializers/stripe.rb Rails.configuration.stripe = { :publishable_key => ENV[' <KEY>'], :secret_key => ENV[' <KEY>'] } Stripe.api_key = Rails.configuration.stripe[:secret_key] <file_sep>/README.md # README # _The Went-To-Bali E-commerce Refactor Extravaganza_ #### _A refactoring project intended to salvage the remains of an ecommerce site that was left high-and-dry by a developer who decided to move away without leaving behind a high-quality product. {May 4, 2018}_ #### By _<NAME>_ ## Description This project is designed to simulate a situation where the main developer for an e-commerce site randomly decides to move away to Bali. The developer didn't leave behind a good README, any sort of well-kept commit history, and many swaths of code that could use some refactoring. Naturally, the goal of this project is to remedy all of these issues. Additionally, AJAX is added to enhance the online shopping experience. ## Specifications / User Expectations _This project adds the following functionality to the existing template:_ * AJAX functionality for adding and deleting products to/from the shopping cart DONE * Ensures that the user can't add a negative number of items DONE * Adds flash messages for signing up, signing in, and signing out DONE * Adds Paperclip for image uploads IN PROGRESS * Adds Stripe for payment * Add password validations DONE * Add product validations DONE ## Setup/Installation Requirements 1. Clone GitHub repository to desktop or desired directory 2. Navigate to project directory in terminal 3. Install required gems, set up the database, and seed the database by running the following commands (in order) in the terminal. If you run in into an error while setting up the database, try opening another tab in the terminal and run $ postgres to ensure that your database can be set up correctly. ⋅⋅* $ bundle ⋅⋅* $ bundle exec rails db:create ⋅⋅* $ bundle exec rails db:migrate ⋅⋅* $ bundle exec rails db:seed 4. Open the project directory in Atom or a text editor of your choice 5. Create a file called stripe.rb in config/initializers. The file path should read: config/initializers/stripe.rb ⋅⋅* Add the following code snippet to the file: Rails.configuration.stripe = { :publishable_key => ENV['PUBLISHABLE_KEY'], :secret_key => ENV['SECRET_KEY'] } Stripe.api_key = Rails.configuration.stripe[:secret_key] ⋅⋅* NOTE: You will have to add your own publishable key and secret key to this file. These can be obtained by registering for the Stripe API keys on www.stripe.com. 6. Open a new tab in the terminal and run the following command to open the Rails server. ⋅⋅* $ rails s 7. View the site by navigating to localhost:3000 in Google Chrome or another web browser. ## Known Bugs ## Support and contact details Support questions, ideas, suggestions, and other contact inquiries can be directed to Masen by email or through GitHub: Email: <EMAIL> Github: masenmatthews ## Technologies Used This application was created with Ruby On Rails. It uses the following technologies: * Materialize (for styling) * BCrypt (for authentication) * Paperclip (for images) ### License *MIT License Copyright (c) [2018] [<NAME>] 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.* Copyright (c) 2018 **<NAME>**
dbcfd94d9f574bf8c57592cdab81737191ba1210
[ "Markdown", "Ruby" ]
5
Ruby
masenmatthews/Rails_AJAX_CodeReview
749d31f04d974aa728b0844365a74dea6dff0240
16ad35253191e04b525a1e681493fa489781adce
refs/heads/master
<repo_name>slin30/Exploratory-Data-Analysis<file_sep>/EDA_00_Notes.R # Downloading Data -------------------------------------------------------- # Relative vs absolute dir # setwd("../") moves up one dir # setwd("./data") moves...down one dir? #Checking for and creating directories # file.exists("dir_name") to see if dir exists # if(!file.exists("data")) { # dir.create("data") # } # Main way to download: # download.file() # url, destfile, method # method particularly important for https, for example # Example with Baltimore camera data # You could export directly from the data.baltimorecity.gov site # And copy the link address # and then create var: # fileURL <- "https..." # download.file <- (fileURL, destfile = "./data/cameras.csv", method = "curl") # note the use of relative dir path # note the declaration of "curl" as the method, which is important because this is an https site # you may not need to specify "curl" on Windows, but you will on other OSs, so just include it # as best practice # And after you are finished, you could view via: # list.files("./data") # Keep track of when you downloaded the data: # dataDownloaded <- date() # Loading Data ------------------------------------------------------------ # Most common way is read.table. Most robust in many ways, although does require a few more params # Important params: file, header, sep, row.names, nrows # May not be the best or most efficient way to read huge files into R # If we tried to read the downloaded camera CSV data: # cameraData <- read.table(",/data/cameras.csv") # This would throw an error because read.table defaults to tab delimiter-- and we need to set comma # Or could just use read.csv with defaults # Important to set quotes option, and can also set na.strings-- so it might be more efficient # to save xls(x) files as csv and just read in with appropriate options rather than using a function # to change blanks to NA, for example-- although need to be careful with formatting. # Setting quote = "" will often resolve issues where data has quotes (' OR ") # Reading Excel ----------------------------------------------------------- # Using Baltimore traffic data example again # if(!file.exists("data")){dir.create("data")} # fileURL <- "https..." # download.file(fileURL, destfile = "./data/cameras.xlsx", method = "curl") # datedownloaded <- date() # use standard read.xlsx # parameters: sheetIndx, headers # Reading specific rows and columns # colIndex <- 2:3 # rowIndex <- 1:4 # read.xlsx("./data/cameras.xlsx", sheetIndex = 1, colIndex - colIndex, rowIndex = rowIndex) # read.xlsx2 is much faster but may be a bit unstable if reading subsets of rows # XLConnect package has more options for writing and manipulating Excel files # XLConnect vignette for reference # Reading XML ------------------------------------------------------------- # Tags are general labels, e.g. <section> # Can also be empty, e.g. <line-break />; do not necessarily need open and close tags, so you # use the same structure with the forward slash at the end within the single set of caret braces. # Elements are specific examples of tags, e.g. <Greeting> Hello, world </Greeting> where # "<Greeting>" is an element # Attributes are components of the label, e.g. <img src="jeff.jpg" alt="instructor"/> # or <step number="3"> Connect A to B. </step> # In these examples, the attributes are 'src="jeff.jpg' or 'number=3', respectively. # Reading XML into R # library(XML) # fileURL <- "http://www.w3schools.com/xml/simple.xml" # doc <- xmlTreeParse(fileURL, useInternal = TRUE) # rootNode <- xmlRoot(doc) # xmlName(rootNode) # you will see: [1] "breakfast_menu" # names(rootNode) # you will see: food food food food food # "food" "food" "food" "food" "food" # What does this mean? Tells you what the nested elements of the root node actually are, so # this means that there are 5 food elements within the root node. 5 different items each wrapped # in a food element # So you can access specific elements like you would a list in R # For example, rootNode[[1]] # will tell you what the first element of the root node is, which will return the items within # the first root element. And you can keep subsetting: # rootNode[[1]][[1]] which gives you the first sub-component of the first sub-component-- which # would be the <name> element, i.e. "<name>Belgium Waffles</name>" # You can streamline this with xmlSApply: # xmlSApply(rootNode, xmlValue) will loop through all the elements of the root node and give you # the values-- every value of every tag-- a bunch of text strung together. You may want # to be a bit more specific via XPath # XPath: # /node Top level node # //node Node at any level # node[@attr-name] Node with an attribute name # node[@attr-name='bob'] Node with an attribute name == "bob" (filter on attribute name) # See http://www.stat.berkeley.edu/~statcur/Workshop2/Presentations/XML.pdf # Example: Get the items on the menu and prices # xpathSApply(rootNode, "//name", xmlValue) # gets all nodes with an element called "name" and # grab all the items within. # Returns: # [1] "Belgian Waffles" "Strawberry Belgian Waffles" "Berry-Berry Belgian Waffles" # [4] "French Toast" "Homestyle Breakfast" # xpathSApply(rootNode, "//price", xmlValue) # gets all nodes with an element called "price" # Returns: # [1] "$5.95" "$7.95" "$8.95" "$4.50" "$6.95" # A bit of a more complicated example using Baltimore Ravens data # View the source code (via right-click in browser) # fileURL <- "http://espn.go.com/nfl/team/_/name/bal/baltimore_ravens" # doc <- htmlTreeParse(fileURL, useInternal = TRUE) # note use of htmlTreeParse here # useInternal = TRUE pulls all the different nodes in the file # scores <- xpathSApply(doc, "//li[@class = 'score']", xmlValue) # look for list item elements # with a particular class as denoted-- so find a tag, find the class name, and if both match, # return the value. Rinse and repeat. # teams <- xpathSApply(doc, "//li[@class = 'team-name']", xmlValue) # Reading JSON ------------------------------------------------------------ # Data stored as: # Numbers (double) # Strings (double-quoted) # Boolean # Array (ordered, comma sep by square brackets) # Object (Unordered, comma sep collection by key:value pairs in curly brackets) # In a JSOn file, you will find an overall curly bracket and each set of data elements will # have its own set of curly brackets. Pattern is id, colon, name of variable. # An array for example, can be a component of a JSON object. A value # Reading data from JSON via {jsonlite package} # library(jsonlite) # jsonData <- fromJSON("https://api.github.com/users/jtleek/repos") # names(jsonData) # Returns a data frame where names are top-level variables # names(jsonData$owner) will access that particular column; but here, you are in fact # drilling down into another data frame, and you could drill down even more: # jsonData$owner$login # And you can easily write data frames to JSON: # myjson <- toJSON(iris, pretty = TRUE) # where pretty = TRUE gives nice line indentations # use cat command to print out # You can take that JSON file you just created and send it right back to a df # iris2 <- fromJSON(myjson) # note you previously used a URL, but you can also just pass it # a straight JSON file # check out the r-bloggers jsonlite tutorial for more information. # check out jsonlite vignette for more complicated use cases # Using data.table -------------------------------------------------------- # Inherits from data.frame, so all functions that work on data.frame should work on data.table, # and if something does not work, it's probably being worked on. # Much faster than data.frame on subsetting, grouping, and updating. # Requires a bit of new syntax. # Create data tables just like data frames # library(data.table) # DF <- data.frame(x = rnorn(9), y = rep(c("a", "b", "c"), each = 3), z = rnorm(9)) # DT <- data.table(...same args as above) # See all data tables in memory with tables() command # Subsetting rows is the same: DT[2, ] # Can also subset by name: DT[DT$y == "a"] # One thing a bit different: if subsetting with only one index, subsets by rows and not columns # DT[c(2,3)] will give you the second and third rows of all columns! # What if you want to subset columns? # DT[, c(2, 3)] will NOT behave the same way as data frames. # Data tables use expressions for column subsetting. The arg you pass after the comma is an # 'expression' # And in R, an expression is a collection of statements enclosed in curly braces # { # x = 1 # y = 2 # } # k <- {print(10); 5} # this expression says print "10" and then 5 # so if you type "print(k) the result is [1] 5 # So instead of using indices for column subsetting in data tables, you can pass a list of # functions # DT(, list(mean(x), sum(z))) # Note that the x and z are not quoted, and they correspond to the actual data.table names, # they are not just temporary variables. This makes data.tables very good for summarizing # information-- but to subset, you need to use specific syntax. # In other words, the apply functions to specific data.table columns by the names denoted in the # list of functions you specify. # You could also do something like: DT[, table(y)], so you do not need to pass a list per se. # It is much easier to add new columns to data.tables, and can do so conditionally-- and with # much less memory usage because R will not make a copy of the data.table when adding a column, # unlike data.frame-- although you must be careful with code flow. # For example: if you wanted to add a new column to your data table called "w" where w is column values # in z squared, the command would be: # DT[, w:= z^2] # Here is where you have to be careful-- if you try to make a copy of a data table in the same way # you would a data frame, i.e. DT2 <- DT, this does not work the same way! # With data tables, you are NOT making a copy using this mechanism-- so changes you explicmake to the # new data table (DT2) that you THINK is a copy (i.e. independent of original) is in fact NOT # truly independent-- changes you make to the original data table WILL propogate to the child(ren) # and vice-versa-- which is not necessarily a bad thing, but you must be aware of this behavior!!! # To make a true, independent, uncoupled copy, you need to use the explicit copy function for # data tables. # You can run multiple operations and in functionalized form when creating new colunms: # DT[, m:= {tmp <- (x + z); log2(tmp + 5)}] # where tmp is a temporary variable comprised of sumes of column x and z # and furthermore, you take the log base 2 of tmp + 5 # which returns column m # plyr-like operations are possible: DT[, a := x > 0] # which gives you a binary column a # or you could summarize as well: DT[, b := mean(x + w), by = a] # which takes the mean of x+w when a == TRUE, and do this for all rows-- and likewise, when # a == FALSE. This can be quite useful for making a helper comparison column. # There are special variables for Data Tables. # .N is an integer, length 1, comtaining the number # Example: # set.seed(123) # DT <- data.table(x = sample(letters[1:3], 1E5, TRUE)) # DT[, .N, by = x] # This returns a two-column summary that has counts the number of times each item in column x # is present-- essentially a countif type effect, or a length function-- only no need to use # an apply type function # KEYS-- this is important # If you set a key, you can subset and sort a data table rapidly. Example: # DT <- data.table(x = rep(c("a", "b", "c"), each = 100), y = rnorm(300)) # setkey(DT, x) # the setkey function sets column x as the key for this data.table # DT['a'] # will therefore return all the rows where column x contains the value 'a', since x has been set # as the key. You do not even need to specify the column. # This is a bit more convenient that the equivalent for a data.frame, e.g. # DF <- data.frame(x = rep(c("a", "b", "c"), each = 100), y = rnorm(100)) # DF[DF$x == "a", , drop = FALSE] # However, you can use keys for more than just convenient subsetting-- also great for fast # merging as long as you set the keys for the two data tables you want to merge. # And faster for reading in massive files. # Use the fread command for data.tables # Reading from mySQL ------------------------------------------------------ <file_sep>/Quiz_01_Script.R # Package dependencies library(xlsx) library(RCurl) library(XML) library(xml2) library(data.table) # Set wd to Assignments folder # Need to optimize this-- make more dynamic setwd("./Assignments") # Set the path in Assignments for reading data Quiz.id <- "Quiz_01" # Create the file list path and list files Quiz.fpath <- paste0(getwd(), "/", Quiz.id) # Dataset 1 --------------------------------------------------------------- # Get dataset 1 via download.file method fname.1 <- "quiz_data.csv" download.file(url = "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv", destfile = paste0(Quiz.fpath, "/", fname.1)) data.fname.1 <- paste0(Quiz.fpath, "/", fname.1) # Load dataset 1 dl.data.1 <- read.csv(data.fname.1) # The question is how many properties have a value > 1 M; this is in col called "VAL" answer <- length(which(dl.data.1$VAL == 24)) # Check your answer ans.check <- cbind(table(dl.data.1$VAL)) ans.check[rownames(ans.check) == 24, ] == answer # Should evaluate to TRUE # Another question is about the FES column-- which tidy data principle does it violate? str(dl.data.1$FES) table(dl.data.1$FES) # From the codebook (see the PDF), it is clear this field conflates two variables, so should be separated into two # separate columns # Dataset 2 --------------------------------------------------------------- # Get dataset 2 via download.file method fname.2 <- "getdata-data-DATA.gov_NGAP.xlsx" data.fname.2 <- paste0(Quiz.fpath, "/", fname.2) # Load dataset 2; note the instructions data.2.rows <- 18:23 data.2.cols <- 7:15 dat <- read.xlsx(data.fname.2, sheetIndex = 1, colIndex = data.2.cols, rowIndex = data.2.rows) # And answer the question, which is simply the result of the given sum command: sum(dat$Zip*dat$Ext,na.rm=T) # Dataset 3 --------------------------------------------------------------- # Get dataset 3 via read.xml; this seems to be problematic-- troubleshoot later, use source file for now # Could just be a stupid path setting issue you screwed up... fname.3 <- "getdata-data-restaurants.xml" data.fname.3 <- paste0(Quiz.fpath, "/", fname.3) # read in XML structure doc <- xmlTreeParse(file = data.fname.3, useInternalNodes = TRUE) rootnode <- xmlRoot(doc) xmlName(rootnode) names(rootnode) rootnode[[1]][[1]] # Try some xpathSApply: test.1 <- xpathSApply(rootnode, "//name", xmlValue) doc.names <- xpathSApply(rootnode, "//name", xmlValue) doc.zip <- xpathSApply(rootnode, "//zipcode", xmlValue) doc.mat <- cbind(name = doc.names, zip = doc.zip) # Now answer the question: number of zips 21231 zip.target <- "21231" length(which(doc.mat[, 'zip'] == zip.target)) # Check your answer: cbind(table(doc.mat[, 2])) # Dataset 4; Question 5 -------------------------------------------------------------- fname.4 <- "data.4.csv" data.fname.4 <- paste0(Quiz.fpath, "/", fname.4) download.file(url = "https://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06pid.csv", destfile = data.fname.4) DT <- fread(data.fname.4) # The question is: which is the fastest to calculate the average of the var pwgtp15? names(DT) ques.col.ind <- which(names(DT) == 'pwgtp15') q5.ans <- DT[, mean(pwgtp15), by = SEX] <file_sep>/EDA_01_Import.R # Import files for downstream use #This is a test # This is another test
f2360c382a51b3b3fe60a3630d47143cb0ff4222
[ "R" ]
3
R
slin30/Exploratory-Data-Analysis
c4c61854ed1624db8dfa1b0ea1da7bfc3a2e5bba
f2d804b8716e4cdb0a2bbee85375ca503524b311
refs/heads/master
<repo_name>mechcloud/large-app<file_sep>/vue.config.js var path = require('path'); module.exports = { productionSourceMap: false, devServer: { disableHostCheck: true, port: 8091 } }; <file_sep>/src/store/mutations.js export default { updateReloadFlag(state) { state.reloadFlag = !state.reloadFlag } } <file_sep>/README.md # large-app ## Deploying this app and associated plugin in docker ``` cd <workspace> git clone <EMAIL>:koyadume/large-app-plugin1.git cd large-app-plugin1 docker build -t large-app-plugin1 . && docker run -d --name=large-app-plugin1 -p 8091:80 large-app-plugin1 cd .. git clone <EMAIL>:koyadume/large-app.git cd large-app docker build -t large-app . && docker run -d --name=large-app -p 8090:80 large-app ``` ## Testing plugin and main apps ### Plugin app ``` curl http://<docker-vm-ip>:8091 ``` ### Main app ``` curl http://<docker-vm-ip>:8090 ```
c6f9951773eb86a5cd966e0ce134e25a299d2874
[ "JavaScript", "Markdown" ]
3
JavaScript
mechcloud/large-app
062add8455d0740af05f66ed245d8a0d49093b2f
dc8faa3f911374ece77ded21ee90ced52a000d40
refs/heads/master
<repo_name>MatProg2k/Generator_Perestanovok<file_sep>/Task/Task.cpp #include "stdafx.h" #include <iostream> #include <ctime> #include <locale> #include <fstream> #include <vector> __int64 Factorial(int number) { if ((number == 1) | (number == 0)) { return 1; } return Factorial(number - 1) * number; } int _tmain(int argc, _TCHAR* argv[]) { setlocale(LC_CTYPE, "Russian"); const bool LEFT = true; const bool RIGHT = false; int sizeSet; int sizePlacements; std::vector<bool> direction; std::vector<int> set; std::vector<std::vector<int>> placements; //Данные sizeSet = 4; sizePlacements = Factorial(sizeSet); for (int i = 0; i < sizeSet; i++) { set.push_back(i); } for (int i = 0; i < sizeSet; i++) { direction.push_back(LEFT); } //Генератор std::vector<int> temp; for (int i = 0; i < sizeSet; i++) { temp.push_back(i); } placements.push_back(temp); bool flag = false; do { // поиск максимального мобильного элемента std::pair<int, bool> pair(INT_MIN, false); int tempI = 0; flag = false; for (int i = 0; i < sizeSet; i++) { if ((direction[i] == LEFT) && (i != 0) && (temp[i] > temp[i - 1])) { if (pair.first < temp[i]) { pair.first = temp[i]; pair.second = direction[i]; tempI = i; flag = true; } } else if ((direction[i] == RIGHT) && (i != sizeSet - 1) && (temp[i] > temp[i + 1])) { if (pair.first < temp[i]) { pair.first = temp[i]; pair.second = direction[i]; tempI = i; flag = true; } } } // перемещение мобильного элемента и смена направлений if (flag == true) { if (direction[tempI] == LEFT) { std::swap(direction[tempI], direction[tempI - 1]); std::swap(temp[tempI], temp[tempI - 1]); tempI--; } else if (direction[tempI] == RIGHT) { std::swap(direction[tempI], direction[tempI + 1]); std::swap(temp[tempI], temp[tempI + 1]); tempI++; } placements.push_back(temp); for (int i = 0; i < sizeSet; i++) { if (temp[tempI] < temp[i]) { if (direction[i] == true) { direction[i] = false; } else { direction[i] = true; } } } } } while (flag == true); //Вывод std::cout << "Перестановки:" << std::endl; for (int i = 0; i < sizePlacements; i++) { std::cout << "{ "; for (int j = 0; j < placements[i].size(); j++) { std::cout << char(97 + placements[i][j]) << " "; } std::cout << "}" << std::endl; } system("pause"); return 0; }
c833fadd679864db04d6b951ba32c75b0b853eba
[ "C++" ]
1
C++
MatProg2k/Generator_Perestanovok
f283a7bc201db41869737db31b5cc54180c51124
10e00e149bd7a9ed0e81a293e5ec15147b17b4ba
refs/heads/master
<repo_name>Canabria/Lab4P2_CarlosSanabria<file_sep>/Lab4P2_CarlosSanabria/src/lab4p2_carlossanabria/Desarrolladores.java /* * 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 lab4p2_carlossanabria; /** * * @author <NAME> */ public class Desarrolladores extends Empleados implements Sueldo{ private int cantidad_a,cantidad_p,años_e,horas_t,ano_c; private String lenguaje_p; private double sueldo=0; public Desarrolladores(int cantidad_a, int cantidad_p, int años_e, int horas_t, String lenguaje_p, String nom, String id, String user, String pass, String nacio, int ano_c) { super(nom, id, user, pass, nacio, ano_c); this.cantidad_a = cantidad_a; this.cantidad_p = cantidad_p; this.años_e = años_e; this.horas_t = horas_t; this.lenguaje_p = lenguaje_p; this.ano_c=ano_c; } public Desarrolladores(int cantidad_a, int cantidad_p, int años_e, int horas_t, String lenguaje_p) { this.cantidad_a = cantidad_a; this.cantidad_p = cantidad_p; this.años_e = años_e; this.horas_t = horas_t; this.lenguaje_p = lenguaje_p; } public int getCantidad_p() { return cantidad_p; } public void setCantidad_p(int cantidad_p) { this.cantidad_p = cantidad_p; } public int getAños_e() { return años_e; } public void setAños_e(int años_e) { this.años_e = años_e; } public int getHoras_t() { return horas_t; } public void setHoras_t(int horas_t) { this.horas_t = horas_t; } public String getLenguaje_p() { return lenguaje_p; } public void setLenguaje_p(String lenguaje_p) { this.lenguaje_p = lenguaje_p; } public double getSueldo() { return sueldo; } public void setSueldo(double sueldo) { this.sueldo = sueldo; } public int getCantidad_a() { return cantidad_a; } public void setCantidad_a(int cantidad_a) { this.cantidad_a = cantidad_a; } public int getAno_c() { return ano_c; } public void setAno_c(int ano_c) { this.ano_c = ano_c; } @Override public String toString() { return super.toString()+"Desarrolladores:\n" +"Canitdad de proyectos: "+cantidad_a+"\n"+ "cantidad de proyectos realisado: " + cantidad_p +"\n"+ "Anos de experiencia: " + años_e +"\n"+ "Horas de trabajo: " + horas_t +"\n"+ "Lenguaje de programcion preferido: " + lenguaje_p +"\n"+ "Sueldo: " + sueldo +"\n"; } @Override public double sueldos(){ return this.sueldo=(((this.cantidad_p*115000)*2)/this.cantidad_a+this.ano_c); } } <file_sep>/Lab4P2_CarlosSanabria/src/lab4p2_carlossanabria/Proyectos.java /* * 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 lab4p2_carlossanabria; import java.util.ArrayList; /** * * @author <NAME> */ public class Proyectos { private String nom,nom_e,decrip; private int candi_d; private String estado; ArrayList<Desarrolladores>d= new ArrayList(); ArrayList<Directores>dic=new ArrayList(); ArrayList<Consultores>c= new ArrayList(); public Proyectos(String nom, String nom_e, String decrip, int candi_d, String estado,ArrayList<Desarrolladores>d,ArrayList<Directores>dic,ArrayList<Consultores>c) { this.nom = nom; this.nom_e = nom_e; this.decrip = decrip; this.candi_d = candi_d; this.estado = estado; this.d=d; this.dic=dic; this.c=c; } public Proyectos() { } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getNom_e() { return nom_e; } public void setNom_e(String nom_e) { this.nom_e = nom_e; } public String getDecrip() { return decrip; } public void setDecrip(String decrip) { this.decrip = decrip; } public int getCandi_d() { return candi_d; } public void setCandi_d(int candi_d) { this.candi_d = candi_d; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public ArrayList<Desarrolladores> getD() { return d; } public void setD(ArrayList<Desarrolladores> d) { this.d = d; } public ArrayList<Directores> getDic() { return dic; } public void setDic(ArrayList<Directores> dic) { this.dic = dic; } public ArrayList<Consultores> getC() { return c; } public void setC(ArrayList<Consultores> c) { this.c = c; } @Override public String toString() { return "Proyectos:\n" + "Nombre: \n" + nom + "Nombre empresa: " + nom_e +"\n"+ "Descripcion: " + decrip +"\n"+ "Cantidad de años de duración: " + candi_d +"\n"+ "Estado actual: " + estado +"\n"+ "Desarrolladores: " + d +"\n"+ "Directores: " + dic +"\n"+ "Consultores: " + c +"\n"; } } <file_sep>/Lab4P2_CarlosSanabria/src/lab4p2_carlossanabria/Directores.java /* * 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 lab4p2_carlossanabria; import java.util.ArrayList; /** * * @author <NAME> */ public class Directores extends Empleados implements Sueldo{ private int anos_d,cant_p,cant_a, ano_c; ArrayList<Consultores>c= new ArrayList(); ArrayList<Desarrolladores> d=new ArrayList(); private double sueldos=0; public Directores(int anos_d, int cant_p, int cant_a,ArrayList<Consultores>c,ArrayList<Desarrolladores>d, String nom, String id, String user, String pass, String nacio, int ano_c) { super(nom, id, user, pass, nacio, ano_c); this.anos_d = anos_d; this.cant_p = cant_p; this.cant_a = cant_a; this.c=c; this.d=d; this.ano_c=ano_c; } public Directores(int anos_d, int cant_p, int cant_a) { this.anos_d = anos_d; this.cant_p = cant_p; this.cant_a = cant_a; } public int getAnos_d() { return anos_d; } public void setAnos_d(int anos_d) { this.anos_d = anos_d; } public int getCant_p() { return cant_p; } public void setCant_p(int cant_p) { this.cant_p = cant_p; } public ArrayList<Desarrolladores> getD() { return d; } public void setD(ArrayList<Desarrolladores> d) { this.d = d; } public double getSueldos() { return sueldos; } public void setSueldos(double sueldos) { this.sueldos = sueldos; } public int getCant_a() { return cant_a; } public void setCant_a(int cant_a) { this.cant_a = cant_a; } public ArrayList<Consultores> getC() { return c; } public void setC(ArrayList<Consultores> c) { this.c = c; } @Override public String toString() { return super.toString()+"Directores: \n" + "Anos durante su puesto: " + anos_d+"\n"+"Cantidad de proyectos asignados: "+cant_a+"\n"+ "Cantidad de proyectos realizados: " + cant_p+"\n"+ "Desarrolladores: " + d +"\n"+ "Sueldos: " + sueldos + "\n"; } @Override public double sueldos(){ return this.sueldos=((((this.cant_p*this.cant_a)*this.c.size())*this.d.size())*5.23)/((this.cant_a*this.ano_c)*2.28); } }
9328d51e0d8afef7dedaef55972cf79454c7d64a
[ "Java" ]
3
Java
Canabria/Lab4P2_CarlosSanabria
b33f48850ee0f22a0e755f3a570f3ab57850c3e9
72ef59c7f40eded44475fe46fe60d6df247d537d
refs/heads/main
<repo_name>sobin227/plan_children-1<file_sep>/test3.py import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotlib.pyplot as plt import time import os import copy from numpy.testing._private.parameterized import param trans = transforms.Compose( [transforms.Resize((150,150)),transforms.ToTensor(), transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))]) #trainset = torchvision.datasets.ImageFolder(root="./datasets/train", transform=trans) #trainloader = torch.utils.data.DataLoader(trainset, batch_size=20, shuffle=True, num_workers=0) #valset = torchvision.datasets.ImageFolder(root="./datasets/evaluation", transform=trans) #validloader = torch.utils.data.DataLoader(trainset, batch_size=20, shuffle=True, num_workers=0) testset = torchvision.datasets.ImageFolder(root="./datasets/test", transform=trans) testloader = torch.utils.data.DataLoader(testset, batch_size=20, shuffle=True, num_workers=0) image_datasets = {'train': datasets.ImageFolder(root="./datasets/train", transform=trans), 'val': datasets.ImageFolder(root="./datasets/evaluation", transform=trans)} dataloaders = { 'train' : torch.utils.data.DataLoader(image_datasets['train'], batch_size=4, shuffle=True, num_workers=0), 'val' : torch.utils.data.DataLoader(image_datasets['val'], batch_size=4, shuffle=True, num_workers=0) } dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']} class_names = image_datasets['train'].classes device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) def imshow(inp, title=None): """Imshow for Tensor.""" inp = inp.numpy().transpose((1, 2, 0)) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean # 정규화를 해제 inp = np.clip(inp, 0, 1) plt.imshow(inp) if title is not None: plt.title(title) plt.pause(5) #class_names = trainset.classes # 한개의 배치(batch)만큼 이미지를 불러온다. 배치 사이즈를 4로 했으니 사진 4장이 로드된다. inputs, classes = next(iter(dataloaders['train'])) # 로드된 데이터에 make_grid 함수를 통해 그리드를 추가한다. out = torchvision.utils.make_grid(inputs) # 이미지를 출력한다. imshow(out, title=[class_names[x] for x in classes]) #resnet #model_ft = models.resnet18(pretrained=True) #num_ftrs = model_ft.fc.in_features #model_ft.fc = nn.Linear(num_ftrs, 3) #vgg model_ft = models.vgg16(pretrained=True) num_ftrs = model_ft.features #for params in num_ftrs.parameters(): #param.requires_grad = False model_ft.classifier[3].out_features = 3 model_ft = model_ft.to(device) criterion = nn.CrossEntropyLoss() # Observe that all parameters are being optimized optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9) # Decay LR by a factor of 0.1 every 7 epochs exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1) # 모델 훈련 def train_model(model, criterion, optimizer, scheduler, num_epochs=5): since = time.time() #시작 시간을 기록(총 소요 시간 계산을 위해) best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) #epoch를 카운트 print('-' * 10) # Each epoch has a training and validation phase for phase in ['train', 'val']: #train mode와 validation mode 순으로 진행 if phase == 'train': scheduler.step() model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode running_loss = 0.0 running_corrects = 0 # Iterate over data. for inputs, labels in dataloaders[phase]: #dataloader로부터 dataset과 그에 해당되는 label을 불러옴 inputs = inputs.to(device) #GPU로 입력데이터를 올림 labels = labels.to(device) #GPU로 label을 올림 # zero the parameter gradients optimizer.zero_grad() #Gradient를 0으로 초기화 # forward # track history if only in train with torch.set_grad_enabled(phase == 'train'): outputs = model(inputs) _, preds = torch.max(outputs, 1) #마지막 layer에서 가장 값이 큰 1개의 class를 예측 값으로 지정 loss = criterion(outputs, labels) # backward + optimize only if in training phase if phase == 'train': # training 모드에서는 weight를 update한다. loss.backward() #backward optimizer.step() # statistics running_loss += loss.item() * inputs.size(0) running_corrects += torch.sum(preds == labels.data) epoch_loss = running_loss / dataset_sizes[phase] epoch_acc = running_corrects.double() / dataset_sizes[phase] print('{} Loss: {:.4f} Acc: {:.4f}'.format( phase, epoch_loss, epoch_acc)) # deep copy the model if phase == 'val' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) print() time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format( time_elapsed // 60, time_elapsed % 60)) print('Best val Acc: {:4f}'.format(best_acc)) # load best model weights model.load_state_dict(best_model_wts) return model model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=5) PATH_1='./datasets' torch.save(model_ft,PATH_1+'model_test1.pt') torch.save(model_ft.state_dict(),PATH_1+'model_test_dict.pt') torch.save({ 'model': model_ft.state_dict(), 'optimizer': optimizer_ft.state_dict() }, PATH_1 + 'all.tar') # testdata 정확도 알아보기 correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = model_ft(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the test images: %d %%' % ( 100 * correct / total)) <file_sep>/test.py a = 1 b = 2 c = 3 print("Hello") print(a+b*c)
479cd7c26f500a2eda86e7fcc9bef2a45908f7d5
[ "Python" ]
2
Python
sobin227/plan_children-1
0a113feba08bad58d46443a5c8ebf3e522f66ab1
e99cc1368674845ed2b5db9d0629923a64fec95a
refs/heads/master
<repo_name>JayBazuzi/gitprompt<file_sep>/cache/DirectoryMonitor.cpp #include "stdafx.h" #include "DirectoryMonitor.h" #include "DebugLogger.h" CDirectoryMonitor::CDirectoryMonitor(const wstring& path) :m_path(path), m_callback(nullptr), m_callbackContext(nullptr), m_hDirectory(INVALID_HANDLE_VALUE) { ::ZeroMemory(&m_overlapped, sizeof(m_overlapped)); this->m_Buffer.resize(16384); } CDirectoryMonitor::~CDirectoryMonitor() { } bool CDirectoryMonitor::OpenDirectory() { // Allow this routine to be called redundantly. if (m_hDirectory != INVALID_HANDLE_VALUE) return true; m_hDirectory = ::CreateFile( this->m_path.c_str(), // pointer to the file name FILE_LIST_DIRECTORY, // access (read/write) mode FILE_SHARE_READ // share mode | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, // security descriptor OPEN_EXISTING, // how to create FILE_FLAG_BACKUP_SEMANTICS // file attributes | FILE_FLAG_OVERLAPPED, NULL); // file with attributes to copy if (m_hDirectory == INVALID_HANDLE_VALUE) { return false; } return true; } void CDirectoryMonitor::BeginRead() { DWORD dwThreadId; HANDLE hInstanceThread = CreateThread( NULL, // no security attribute 0, // default stack size CDirectoryMonitor::ThreadStart, this, // thread parameter 0, // not suspended &dwThreadId); // returns thread ID if (!hInstanceThread) { Logger::LogError(L"Unable to start new thread"); // TODO: // ExitProcess(2); return; } } DWORD WINAPI CDirectoryMonitor::ThreadStart(LPVOID lpvParam) { CDirectoryMonitor *me = (CDirectoryMonitor*)lpvParam; DWORD dwBytes = 0; // This call needs to be reissued after every APC. BOOL success = ::ReadDirectoryChangesW( me->m_hDirectory, // handle to directory &me->m_Buffer[0], // read results buffer me->m_Buffer.size(), // length of buffer TRUE, // monitoring option FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE, // filter conditions &dwBytes, // bytes returned &me->m_overlapped, // overlapped buffer NULL); // completion routine if (!success) { Logger::LogError(L"Failed: ReadDirectoryChangesW"); me->Notify(false); return 0; } BOOL result = GetOverlappedResult(me->m_hDirectory, &me->m_overlapped, &dwBytes, TRUE); me->Notify((bool)result); return 0; } bool CDirectoryMonitor::Monitor(ChangeCallback callback, void *context) { this->m_callback = callback; this->m_callbackContext = context; if (this->OpenDirectory()) { this->BeginRead(); } else { Logger::LogError(L"Unable to open directory : " + this->m_path); this->Notify(false); return false; } return true; } void CDirectoryMonitor::Notify(bool isSucceeded) { if (this->m_callback != nullptr) { // TODO: Pass in the correct change type. this->m_callback(ChangeType::FILE_MODIFIED, this->m_callbackContext); } }
5099d6a1ab85bfe10da3874692a5f9f26e332883
[ "C++" ]
1
C++
JayBazuzi/gitprompt
932af9574ba402187d159092ada46c97f51dcb8d
1e068699013e62fee900d9be906212f439528aae
refs/heads/master
<repo_name>fannheyward/fannheyward.github.io<file_sep>/_posts/2018-06-17-8-years-in-beijing.markdown --- layout: post title: 8 Years in Beijing date: 2018-06-17 10:23:09 +0800 --- 8. <file_sep>/_posts/2009-05-15-set-out-again.markdown --- layout: post title: "再出发" --- 现在是北京时间20:00,三个小时后我将是在火车上,再次出发,回郑州参加笔试。周一收到了笔试通知,四月份投的简历,都过去这么久了,差不多放弃了。收到笔试通知时候还是很兴奋的,然后查了一下笔试名单,瞬间冰冻:总共这个职位是有 108 将进入笔试,其中有 87 个硕士以上学历,还包括一个英国约克大学的硕士留学生。当时的想法就是我这个小本科还是不去折腾了。后来想想,怕啥,咱光脚的不怕穿鞋的,拼一把。再说了,又没说这些人全部都参加笔试,这样竞争的范围不就小点了嘛;就算都参加了,咱也不能怯场掉,拼一个赚一个,拼俩个赚一对,哪怕是参加笔试积累些经验见见考试题目对自己也没啥坏处的嘛!打定主意,下午就买了往返票,今天晚上再次上路,加油! 贴一段小刚《再出发》的歌词,跟自己说加油! ``` 让我牵着你的手 迈开大步向前走 不管前方有多少困难等着我 风大雨大太阳大 让我们信心更大 不管前方有多少难关又怎样 再出发再出发吧 踏着坚定的步伐 不管风雨有多大 只要有信心就不怕 再出发再出发吧 擦亮胜利的火花 带着幸福的微笑 笑着流泪再出发 ``` <file_sep>/_posts/2015-09-14-conway-law.markdown --- layout: post title: Conway's Law date: 2015-09-14 13:26:45 +0800 --- [M.Conway](https://en.wikipedia.org/wiki/Conway%27s_law): > organizations which design systems ... are constrained to produce designs which are copies of the communication structures of these organizations. 软件系统的架构反映了公司内部的组织结构、团队间的通讯结构。 <file_sep>/_posts/2012-07-18-symbol-not-found-objc-storestrong.markdown --- layout: post title: "Symbol not found: _objc_storeStrong" date: 2012-07-18 21:51 --- Crash log: ``` dyld: lazy symbol binding failed: Symbol not found: _objc_storeStrong Referenced from: /var/mobile/Applications/6E4A4771-B39A-48B9-A7B7-0EA0108DCAF4/X.app/X Expected in: /usr/lib/libobjc.A.dylib dyld: Symbol not found: _objc_storeStrong Referenced from: /var/mobile/Applications/6E4A4771-B39A-48B9-A7B7-0EA0108DCAF4/X.app/X Expected in: /usr/lib/libobjc.A.dylib ``` 在 Non-ARC 项目中使用 ARC-enabled 库的时候,需要对库文件在 Build Phases->Compile Sources 添加 `-fobjc-arc` Compiler Flags,在 Build Settings->Other Linker Flags 添加 `-fobjc-arc`. via [libobjc.A.dylib compile error on iOS 4.3][1], [Static library with ARC support linked to non-ARC project causing linker errors][2]. [1]:http://stackoverflow.com/a/8149079/380774 [2]:http://stackoverflow.com/a/8757075/380774 <file_sep>/_posts/2008-08-11-my-firefox-extensions.markdown --- layout: post title: "我的Firefox扩展分享" --- 实用的角度选择Firefox扩展--我的Firefox扩展分享 PS:本文为 "体验火狐,分享我与火狐的故事" 投稿写作。 Firefox 最最吸引我的地方在于它的无敌自定义性。你可以通过数以千计的Extensions扩展来实现自己想要的功能。或者说,Fx提供给你的只是一个浏览器核心,一个平台,除了必不可少的功能和Fx认为很有特色的功能,比如Fx 3里面的智能地址栏,其他的你想要的都留给你自己去开发定制。也许这样会比较麻烦,不适合新手操作使用,这个也许是Fx不能大范围流行使用的最大障碍,毕竟不是每个人都会安装Fx插件的。但是对于喜欢折腾的人来说,Fx无疑是最棒的,通过自己的设定做一个自己最适合的Fx,很是有成就感。然而,这么多优秀的扩展怎么选择呢?毕竟万物都有一个度,并不是所有的扩展都适合你,安装过多的扩展终究会让Fx变成一个庞然大物,启动速度跟反应速度都会受到很大的影响。因此,合理实用的选择适合自己的Fx扩展无疑很重要。下面是我自己的Fx扩展配置,分享一下我自己的扩展使用。 - Abduction,一个非常简单的网页截图扩展,可选区域和全屏截图。大多数时候我只是需要对网页上部分区域进行截图操作,不需要像fireshot那样对截图进行过多的阴影、着色、注释等图片编辑,对我来说,这个截图扩展是最为实用的,而且仅仅10几K的大小。 - Adblock Plus,这个就不多说了,强大的屏蔽广告扩展,配合自定义的广告屏蔽规则,非常棒! - Add to Search Bar,Add any search on any page to the Search Bar,其实很多搜索引擎已经可以自己添加到搜索栏,不过还是有不够智能的,这个东西就可以添加任意搜索到搜索栏。 - Copy Link Name,复制链接名称。当然,你也可以用鼠标选定后右键复制,但是这样很容易产生误操作,点到链接,我要的只是复制链接名称而已。 - Custom Buttons2,自定义一些按钮,非常棒的扩展。我自己添加了许多按钮,比如,站内搜索,重启Fx,Google翻译当前网页等,简单,实用。 - DownloadHelper,简单说就是来下载在线视频。在线视频大多都对地址进行了加密,用这个东西就可以嗅到视频的真实地址,剩下的更简单了吧? - DownThemAll,支持多线程的下载利器。虽然Fx自带的下载已经比较好了,但是不支持多线程,速度上不行。 - Easy DragToGo,超级拖拽,比Super DragAndGo要小巧但是功能上一样强大,五星扩展,必备扩展! - Extension List Dumper,生成扩展列表,当前这个列表就是用它生成的,我可不想一个一个的写扩展名字。 - Firebug,五星级推荐扩展之一,简单来说,集HTML查看和编辑、Javascript控制台、网络状况监视器于一体的网页开发利器,其实我也就是偶尔拿来玩玩,看看网页源码,纯属学习。 - FireGestures,鼠标手势扩展,小巧,简单,实用,没有别的。 - FlashGot,调用外部下载工具,我用的是迅雷,下载大东西时候很方便。 - Google Notebook,选定网页内容,右键,收藏到Google笔记本,网络收藏必备。 - Greasemonkey,同样是五星级推荐扩展,可以实现很多网页没有的功能,比如自动发现RSS地址,给豆瓣添加回复和引用按钮等等,很是方便实用。 - IE Tab,使用IE浏览网页。毕竟现在还是IE的天下,有些时候还只能用IE,用这个直接就可以,不过现在用的很少了,因为IE Tab有不少bug,很拖累Fx速度,考虑卸载。 - keyconfig,可以自定义添加Fx没有的快捷键来实现一些功能,比如Ctrl+Shift+R刷新全部网页。 - Live PageRank,查看当前网页的Google PR值,10几K大小,很简单。 - MediaWrap,实现在线播放功能,必备。 - Open IT Online,可以将在线文档在Google Docs中打开,试用中。 - Paste and Go 2,就一个功能,实现地址栏的粘贴并打开,其实这个功能应该集成到Fx的说。 - QuickProxy,快速切换代理。设置好代理地址,点击切换使用代理或不用代理,简单实用。 - Tab Mix Plus,五星推荐必备扩展。实现标签页更多更强大的功能。 - TabIMSwitch,实现Fx各个标签页输入法的不同状态。在一个标签页我要中文输入,另一个我要用英文输入,我可不想Ctrl+Space的切换不停,很实用。 - Text Link,很多网页里的链接是文本形式,不能直接点击打开,以前都是复制到地址栏再打开,很不方便,有了这个,直接双击即可。 - Update Bookmark,在线看连载小说之类的非常实用,更新书签属性到当前页面。 - URL Fixer,敲网站地址时候不小心把com敲成了cmo,没问题,照样能到,因为我有这个家伙来修正网站地址。 - 巴巴变图摘,把图片一键上传到巴巴变网络相册,对我来说很方便,对你也许用处不大,:-)。 算算我用的Fx扩展其实也不少,将近30个,但是Fx启动速度并没有受到很大影响,10+秒钟启动完成,可以接受。有很多扩展的功能其实都差不多,我们选择的时候就要已简单实用作为原则,优选那些个体积小巧的,这样对Fx的启动速度和反应速度影响就会小得多。 选择简单实用适合自己的Fx扩展,打造自己的Fx,享受自定义的快乐. <file_sep>/_posts/2010-02-22-vss-auto-login.markdown --- layout: post title: "VSS 自动登录" --- VSS (Visual SourceSafe)快捷方式后添加一个启动参数 `–y` 就可以实现自动登录。 > `"C:\Program Files\VSS\win32\SSEXP.EXE" –yUsername,Password` <file_sep>/_posts/2010-04-27-picky-change-log-2.markdown --- layout: post title: "Picky 改动记录二" --- 从 hg 拿到 Picky 最新代码,改了一点点,部署成功。留个记录: 1. writer.py line 211 添加 try..except,解决不能登录后台。这个好像是 Twitter Search 和 GAE memcache 的问题,好像 Twitter Search 默认只能搜索七天(?)内的 Tweets,这样如果之前在 Twitter 上有链接到博客,memcache 里的 mentions_twitter 不为空,但是时间长以后 mentions_twitter 获取不到 [ 'results' ],造成登录后台时候错误,KeyError: 'results'。 2. robots.txt 修改 sitemap.xml 为绝对地址,RobotsHandler 生成 robots.txt 的时候没有对 template_values 赋值; 3. 删除两个主题 sidebar.html、article.html、footer.html 模板里的 Google Ads; 4. header.html 追加 Google Webmaster Meta 验证; 5. 更换 Favicon. PS:刚部署完,就发现 Livid 追加了一个新功能,Tweets:Latest 20 Tweets by @livid,期待已久的功能,目前 hg 里代码还没有更新,回头再更新。准备偷师一下这个 Tweets 的实现,看能不能把腾讯微博的给添加进来。Oh NO,腾讯微博连 RSS 都不支持,WTF! <file_sep>/_posts/2014-09-03-daily.markdown --- layout: post title: "租房小事" date: 2014-09-03 20:28:44 +0800 --- 因为自己的犹豫,错过了一套条件非常不错的房子。房东同时把房子挂在链家和我爱我家,链家带我看房的时候我在想看看别的房子再说,等一天应该没问题,结果就被我爱我家出手。所以说:你越担心某种情况发生,那么它往往就是会发生,墨菲定律: > Anything that can possibly go wrong, does. [via][0] 这事对我来说是个教训,做事太瞻前顾后,不够果断。不过我想记的不是这件事,是下面这件,不知道我做的是对是错还是很傻逼的事。 带我看房的中介哥们,90 年的,人特老实,不像其他中介满嘴跑火车。在确定租房意向后,房东很直接的提议私单,就是我和房东直接签,然后出一半中介费给哥们作为辛苦费,这样他能拿到比提成多一倍的钱,我也能省一半中介费。我当然是愿意,不过哥们支吾半天说不行,说知道这样是来钱快,但是他不想这么干,圈子里这么做的人很多,但他不喜欢,要按原则来。当时房东还说我俩可以把他踢开直接签,这样连一半中介费我都不用出。中介哥们当时很憋屈,感觉眼圈都是红的,又很无力。房东离开后我俩单聊,他说理解,只是自己不喜欢。然后,有那么一瞬间,我决定按照正规流程来办,当然我要出全部中介费。签合同的时候才发现,这是他入行一个多月的第一单。能看出他很紧张,写字手都在抖,我不知道这第一单对他有多深的意义,也许若干年后他回想起来依然会激动?或者骂自己傻逼为什么没有直接拿钱?或者笑话有个傻逼居然答应出全部中介费?我只记得当时那一瞬间我的想法: > 不要做让自己讨厌自己的事情。 [1][1] [2][2] [0]:http://en.wikipedia.org/wiki/Murphy's_law [1]:https://fann.im/blog/2011/08/11/quote-0811/ [2]:https://fann.im/blog/2011/11/02/do-not-do-what-you-hate-by-yourself/ <file_sep>/_posts/2015-05-27-one-time-password.markdown --- layout: post title: One-Time Password date: 2015-05-27 16:46:10 +0800 --- 两步验证是基于 [HOTP/TOTP][1] 算法的验证方案,在登录的时候除了密码,也需要提供动态数字(一般是六位数)验证。其中 HOTP(HMAC-based One-time Password) 是计数器令牌,一定次数内有效,TOTP(Time-based One-time Password) 只是一定时间内有效。 可以用两步验证的思路做一个没有固定密码,只有动态密码的注册登录流程: 1. 发送用户邮箱到服务器,检查邮箱对应的用户是否存在。 2. 用户不存在,新建用户,根据邮箱生成密钥并保存,引导用户通过 Google Authenticator/Authy 等保存密钥,可以验证一次确保密钥成功保存,注册成功并登录。 3. 用户存在,提示用户填写 Google Authenticator/Authy 生成的验证码,服务器验证是否有效。 4. 如果用户密钥忘记或被盗,可以通过邮件进行验证,然后重新设置密钥并保存。 整个流程和手机短信验证类似,不同的是通过软件保存密钥并生成验证码,而不是手机短信获取。其中 **根据邮箱生成密钥是关键**,如果算法过于简单,别人知道邮箱后很容易就能猜出密钥,进而得到验证码。初步想到的算法:邮箱+时间戳,SHA/MD5/AES/RC4 等加密计算。 当然这套验证的前提条件是没有物理接触:如果服务被攻陷或拿到密钥算法,整个就完蛋。如果用户手机被拿到,自然就能随便登录。 [1]:https://tools.ietf.org/html/rfc4226 <file_sep>/_posts/2015-07-28-monthly-review-1507.markdown --- layout: post title: Monthly Review 2015-07 date: 2015-07-28 15:25:12 +0800 --- 1. 长岛休假半个月。圈个海岸就收钱,沙滩特别差,不推荐去玩。 2. 第一次带老婆去海边,所以尽管环境不行,前几天玩的还算开心。 3. 按老家习俗给六六过了一岁生日,农历。 4. 接六六来北京,尽管很难,尽管很多阻力,至少走出这一步,希望一切向好的方面发展。 <file_sep>/_posts/2018-04-25-shell-notes.markdown --- layout: post title: Shell Notes date: 2018-04-25 11:35:39 +0800 --- `&&` `||` `;` in shell command: * `cmd1 && cmd2` means cmd2 will only run while cmd1 **success**. * `cmd1 || cmd2` means cmd2 will only run while fmd1 **fails**. * `cmd1 ; cmd2` will run cmd2 regardless cmd1 success or not.<file_sep>/_posts/2009-08-26-chinese-valentine-day.markdown --- layout: post title: "七夕" --- 今儿个七月初七,七夕情人节,更重要的是跟丫头一起过的七夕情人节,哇哈哈!七夕情人节快乐! ![](http://www.google.cn/logos/qixi09.gif) <file_sep>/_posts/2012-12-09-hidden-features-in-osx-plugin-zsh.markdown --- layout: post title: "Hidden Features in osx.plugin.zsh" date: 2012-12-09 19:12 --- oh-my-zsh 自带了很多插件,其中 osx.plugin.zsh 里有不少好东西。 1. `cdf` 快速在终端打开当前 Finder 所在目录。之前的方法是用 cdto,缺点是会另外开一个终端窗口;或者鼠标拖动目录到终端再 cd。cdf 就省力很多,也是这个插件最喜欢的一个命令。 1. `trash` 替换 rm,文件被移动到废纸篓而不是真正删除,避免误操作。`alias rm='trash'` 1. `pfd/pfs` 打印当前 Finder 所在目录,一般配合 cdf 来用。 1. `pushdf` pushd 寄存当前 Finder 所在目录。 1. `quick-look` 调用 QuickLook 查看文件,配合 QLMarkdown.qlgenerator 快速预览 Markdown 文件。 1. `man-preview` 把 man 信息生成 pdf 然后用预览打开。 1. `tab/split_tab/vsplit_tab` 新建、切割终端 tab,不太习惯切割终端,这个用的很少。 <file_sep>/_posts/2012-03-05-my-first-product-summary-failed.markdown --- layout: post title: "第一次产品小结:不及格" date: 2012-03-05 14:15 --- 第一次自己作为产品负责人带产品,自评不及格。总结一下,以后这样的机会还会很多,积累经验争取下次做的更好。 1. 开发进度太慢。原本计划一周时间出原型,但是拖了两个星期才发了第一个测试版本,delay 太多了。自己负责的开发部分拖累了整个项目进展,这一点必须反思。 1. 进度慢的一个原因是部分模块沿用之前项目的东西,花了很多时间去理解梳理然后添加到现在项目,但是由于两个项目架构等有很多不同,复用的成本太大。自己作为项目负责人,选型时候没有考虑清楚,引入后影响项目进度,却没有及时的拿出修正方案。**教训一:不通用的模块复用的成本远远大于重写一份,切不可为了一时的快而忽视其他问题**。 1. 另一个原因是在项目基本成型的时候,由于数据库一个设计缺陷,虽不影响当前使用,但很不利于以后的产品拓展,就重构了一下。这个相比上面虽然有了解决方案,但是延期是事实。究其原因还是在开发前期没有很好的考虑清楚,只解决了第一需求就立马开工,后期造成返工。**教训二:产品设计,尤其是开发设计,架构方面要考虑清楚,要有一定的可扩展性,避免以后返工**。 1. 作为产品负责人,忽略了开发以外的很多事情。比如设计方面,只是和设计师确定了基本界面和交互流程,然后一股脑的扎进开发去,加上开发跑偏,花在设计上的心思就更少了。还好旁边有人提醒着,设计方面这次没有拖累项目进展,但由于和设计师沟通交流太少,一些产品概念没有准确的传递给设计师,造成一些细节上不够完美。**教训三:作为产品负责人,要对整个产品线全部部分掌握到把控到,并且准确的传递给相关人员**。 1. 作为产品负责人,要 **主动** 和项目中的其他人员多沟通,一方面把产品传递给其他人,更重要的是要收集汇总其他人员对产品的概念和想法,然后迭代修正不完善的地方,再一个可以及时了解其他人的进度和遇到的问题,以便整体安排。 1. 这次产品调研阶段确定了不少功能点要做,但是没有完全定型 **当前版本** 要做的点,这就造成一方面有东西没有做完,产品不能成型,另一方面却花了不少时间做了一些可以后续再增强的东西,造成时间的浪费。**教训四:要控制产品功能的阶段性,必要时可以砍掉一些功能点来保证当前版本上线,然后再快速迭代产品**。 1. 对开发分工和实际进度掌握不好。不是分工后就完全分工不管了,如果有人负责的部分提前完工,可以再对未完成的部分分工一下,虽然可能会增加一些人的负担然后引发其他问题,但是从整个产品进展来看,这样做无可厚非。 1. 技术人做产品会有惯性思维,考虑问题过多从开发角度思考,这样的结果一是产品讨论时过于关注开发实现,产品比较僵硬;二是后续比较多的心思都花在了开发上,整体把握不足,引发上面两个问题。**教训五:做产品的时候要跳出开发这个圈圈,这样才能碰撞出更多点子;要平衡好产品和开发**。 现在回过头来想想,自己这次产品做的真不咋样,好好反思一下,希望下次能有更好的表现。 ---- 题外话。 1. 过于追求完美是做产品的大忌。 1. 不要因为自己的错误影响别人的利益。 1. Deadlines kill quality。 <file_sep>/_posts/2008-06-06-paanjoy-to-panngood.markdown --- layout: post title: "盘今到盘古:我又回来了" --- 不管盘古还是盘今,其实都是一家的。关键是,我又回来了! 5月29号发现服务器宕掉的。刚才是还以为也是一般的服务器宕机,没有特别留意。晚些时候再上的时候发现提示404,我的个乖啊,404是啥概念?网页不存在,就是说服务器没有宕掉,但是你的数据没有,访问不到。天啊,不会把我的帐号删掉了吧?!赶紧找客服确认,结果很显然,我的帐号被删了。。。不过是“被黑”了: > 您所在的盘今网络虚拟主机服务器192.168.3.11,今天(2008年5月29日)下午13点20分左右。 被一名以admin身份登陆DirectAdmin面板的人删除了全部用户数据。 得,等着吧,这回估计难弄了。 不过盘古(今)的效率还是很高的,晚上时候就给了一个临时解决办法,提供了盘古的临时合租服务器使用。等于是服务器搬家,所以恢复起来还是挺方便的。最近的全站备份是5月26号的,感谢wp-db-backup插件,博客数据库是每天自动备份到邮箱,有了数据库就好办了,盘今到盘古,wordpress搬家开始: 1. 在新空间,也就是盘古的临时合租服务器上建个数据库,然后import导入备份的数据库,over。 2. 把原来文件数据上传新服务器空间。终于体验了一下Cpanel面板的强大,仅仅在线解压一个小小的功能就让我兴奋了半天,学校网络太差了,一个一个连接上传老是失败。 3. 检查!主要是wordpress下面wp-config.php中间数据库配置跟新空间数据库是否吻合,这个是最重要的,不然还是不能使用。 4. 修改域名指向新空间,over。 Update:今天下午三点吧,盘今给出来解决方案: 1. 数据我们按照6月3日预计的方案来尽可能的恢复,然后交给大家认领. 2. 盘今网络最迟在明天恢复运营,开始重建客户订单和空间帐户。盘今网络主机已经做了更多的安全防护和设置。 3. 我们为每位客户的盘今网络帐户提供50元的预付款补偿,可以用于购买和续费空间,不能提现或者购买域名。 4. 每位客户的空间订单到期时间统一延长到2010年4月10日。 后面两条让我热血沸腾啊,-_-|||,不过不明白第一条的是啥意思呢?怎么认领?再回去?从盘古到盘今。。。囧,再说吧,回去就回去,反正有搬家经验了,有数据库就够了,惦着数据库满世界的乱跑,噢耶! <file_sep>/_posts/2013-08-07-fucking-stupid-error.markdown --- layout: post title: "Fucking Stupid Error" date: 2013-08-07 23:57 --- 今天修改代码部署后造成线上服务出现严重错误,记一下这个教训。 ```lua function f1(user) local name = user:get('name') -- end function f2(new_user) local name = user:get('name') -- end ``` 出错原因:两个功能几乎一样的方法都要追加获取同一信息,f1 中获取正常;然后 **复制** 到 f2 中,如上代码,f2 根本没有 user,取值必然失败,但是由于 Lua 语言特性,这里 user 会被认为是一个全局变量,因此不存在语法等错误,只会在运行时报错,因为全局变量里也没有 user。 这次出错完全是自己疏忽大意造成的。 教训: 1. 即使是同样功能代码在不同地方用的时候也要再次确认正确性。 1. Lua 代码要杜绝全局变量,每次提交部署前要用 ZeroBraneStudio 进行分析检测,这次完全是大意而忘掉了检查。 1. 线上服务代码修改尽量多人 review。 1. 更新部署后出错,首先要怀疑最近提交的代码,并进行严格审查。今天出错后也第一时间 review 了代码改动,确认 f1 没问题后对 f2 的检查就放松了,非常不应该。 1. 应该回滚代码以优先保证线上服务正常。由于出错的不规律性,加上 review 代码的盲目自信,也确实是很简单的改动,就以为不是这个改动才引起的问题,所以没有及时回滚代码,很影响问题排查。 1. 出错后要尽量多的查看所有日志,以便定位问题。今天只检查了 nginx error.log, 忘记了 moochine log,再加上出错栈信息的误导,以为是另一个问题,思路完全跑偏。如果能及时看一下 moochine log 肯定可以很快解决。 1. 分析错误的时候思路要开阔,不要被某一个错误 log 牵着走,很有可能这个 log 只是其他问题引发的一个表象。 1. 自己一个人排查不定的时候尽快找其他人帮忙,其他人不会受自己思路影响,避免干扰,方便定位错误。这个算是今天唯一做对的一点。 是以为记。 <file_sep>/_posts/2008-09-14-your-happiness-see-your-smile.markdown --- layout: post title: "希望你的开心看见你的笑" --- 像一只驼鸟一样,把自己的脑袋埋进沙里,装着啥都不知道。 鸟儿保送了,其实很显然的,如果她的成绩都不能保送的话真有点说不过去了,大二大三时候差不多都可以定了。现在她烦啊,烦的是保送读研还是硕博连读呢?哈,这种烦恼对我真是一种讽刺。 想起来我老早时候说给自己的,给我自己的借口,"那不是我的世界"。我知道那不是我的世界,抑或退出,转头,寻找自己的世界,可是我的世界在哪?不是你一个人在迷茫……平淡安静的生活?如果有更好的充满精彩竞争的生活呢? - 你得到的已然很多,失去的亦然很多,所以你看不到自己到底在追求什么。 - 男的感觉自己的平庸,女的天生的嫉妒加上后天的嫉妒再加上还是嫉妒的嫉妒,女博士就成了鬼。 希望你的开心看见你的笑。 <file_sep>/_posts/2018-03-07-tee.markdown --- layout: post title: tee date: 2018-03-07 11:49:48 +0800 --- > read from stdin, write to stdout **AND** files. ``` curl https://github.com/fannheyward.keys | tee -a ~/.ssh/authorized_keys ``` <file_sep>/_posts/2010-07-07-get-parameters-from-basehttpserver-http-post-request.markdown --- layout: post title: "Get parameters from BaseHTTPServer http POST request" --- Get parameters from BaseHTTPServer http POST request. 获取 BaseHTTPServer.BaseHTTPRequestHandler POST 请求参数。 ``` def do_POST(self): params = cgi.parse_qs(self.rfile.read(int(self.headers.getheader('Content-Length')))) ``` <file_sep>/_posts/2008-12-02-smile-in-the-sky.markdown --- layout: post title: "Smile in the sky" --- 昨天傍晚时候吧,不到七点的样子,天空中双星伴月奇观。可惜当时没有看见,今天上网看了一下网上的照片,很帅,一个大大的笑脸挂在天空中,抬头看看,对自己微笑一个。 ![](http://lh6.ggpht.com/_vYr4JQreqXA/STS7__TSjjI/AAAAAAAAAkc/S-ydMERnfjg/s400/shuangxing.jpg) <file_sep>/_posts/2010-07-02-the-imagiing-c-module-is-not-installed.markdown --- layout: post title: "The _imaging C module is not installed" --- Download jpeglib. ``` cd jpeg-7 sudo make clean sudo CC="gcc -arch i386" ./configure --enable-shared --enable-static sudo make sudo make install ``` Download PIL. ``` sudo rm -Rf build //Edit JPEG_ROOT = libinclude("/usr/local") in setup.py sudo python setup.py build sudo python setup.py install ``` <file_sep>/_posts/2018-05-29-nginx-websocket.markdown --- layout: post title: Nginx + Websocket date: 2018-05-29 11:19:45 +0800 --- ``` upstream ws { server 127.0.0.1:8080; server 127.0.0.1:8081; } server { listen 8090; location / { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://ws; } } ``` 在 Nginx reload 的时候,socket 连接并不会中断。<file_sep>/_posts/2015-11-27-quote.markdown --- layout: post title: 太用力的人跑不远 date: 2015-11-27 11:34:39 +0800 external-url: http://yanyiwu.com/work/2015/11/22/grind-too-hard-to-go-far.html --- > 太用力的人跑不远 跑步如此,代码如此,人生亦是如此。<file_sep>/_posts/2008-04-11-creat-mysql-database.markdown --- layout: post title: "SQL学习---学生-课程数据库" --- * 学生表: Student(Sno,Sname,Ssex,Sage,Sdept) * 课程表:Course(Cno,Cname,Cpno,Ccredit) * 选课表:SC(Sno,Cno,Grade) 建立学生表Student: ``` CREATE TABLE Student (Sno CHAR(9) PRIMARY KEY, Sname CHAR(20) UNIQUE, Ssex CHAR(2), Sage SMALLINT, Sdept CHAR(20)); ``` 建立“课程”表Course: ``` CREATE TABLE Course (Cno CHAR(4) PRIMARY KEY, Cname CHAR(40), Cpno CHAR(4), Ccredit SMALLINT, FOREIGN KEY (Cpno) REFERENCES Course(Cno) /*发现书上的一个错误,外码Cpno必须要加括号*/ ); ``` 建立选课表SC: ``` CREATE TABLE SC (Sno CHAR(9), Cno CHAR(4), Grade SMALLINT, PRIMARY KEY (Sno,Cno), FOREIGN KEY (Sno) REFERENCES Student(Sno), FOREIGN KEY (Cno) REFERENCES Course(Cno) ); ``` 插入具体数据: ``` INSERT INTO Student (Sno,Sname,Ssex,Sage,Sdept) VALUES ('1001','ZHANG','M',19,'IS'); ``` 插入具体数据这一步相当烦人,要一条一条的弄,还要注意外键键值关系,只有键值对应存在的表中才允许插入或者修改,不然就会报错:a foreign key constraint fails... Update:将数据装入数据库表,可以用LOAD DATA语句。新建文本文档data.txt,每行包括一个记录,用Tab键把值分开,并且按CREATE TABLE中列出的列名次序给出,然后LOAD DATA装入: `LOAD DATA LOCAL INFILE "C:\data.txt" INTO TABLE Student;` <file_sep>/_posts/2019-08-19-golang-101.markdown --- layout: post title: 如何写出优雅的 Golang 代码 date: 2019-08-19 18:25:17 +0800 external-url: https://draveness.me/golang-101 --- > 原文是一篇非常赞的工程总结,推荐。这里记录一些笔记 1. 代码规范,`gofmt`, `goimports`, `golangci-lint` 等,配合 CI 自动化 2. 目录结构 [Standard Go Project Layout](https://github.com/golang-standards/project-layout) 1. `/pkg` 可以被外部使用包模块 2. `/internal` 私有模块,不可被外部使用 3. 不要有 `/src` 目录 4. `/cmd` 生成可执行文件 5. `/api` 对外提供的 API 模块 6. 不要有 `model/controller` 这样的模块,按照职责拆分,**面向接口**开发 3. 不要在 `init` 做资源初始化,比如 rpc/DB/Redis 等,因为 init 会被**隐式**执行,会默默初始化资源连接 4. 推荐的做法是 Client + NewClient,显式初始化连接 5. init 阶段适合做一些简单、轻量的前置条件判断,比如 `flag` 设置 6. 使用 [GoMock](https://github.com/golang/mock)/[sqlmock](https://github.com/DATA-DOG/go-sqlmock)/[httpmock](https://github.com/jarcoal/httpmock)/[monkey](https://github.com/bouk/monkey) 做 mock + 测试 [Simple techniques to optimise Go programs](https://stephen.sh/posts/quick-go-performance-improvements) 介绍了一些简单却非常高效的性能提升方法: - Avoid using structures containing pointers as map keys for large maps, use [ints or bytes](https://medium.com/@rf_14423/did-the-big-allocations-of-ram-contain-pointers-directly-or-indirectly-actual-pointers-strings-76ed28c0bc92) - Use strings.Builder to build up strings - Use strconv instead of `fmt.Sprintf` <file_sep>/_posts/2008-03-30-wordpress-25-one-key-update-plugins.markdown --- layout: post title: "Wordpress 2.5新功能—一键更新插件" --- 先来看看wordpress 2.5更新的功能: * 全新的用户管理界面 * 更加简洁实用的后台管理菜单 * Widgets 管理的显著增强 * 区域化的后台首页显示 * 增强的可视化编辑器 * 非常实用的一键升级插件功能 * Flash 效果的上传文件管理 * 标签管理 界面就不用说了,更集中的显示写博客这个主要功能,相当的简洁实用了现在。专门说说一键升级插件功能先。 看见Google sitemap升级到了3.0.3.1,估计是专门对wp2.5升级的,跟进。还是按照老方法,先去后台停用现在的插件,忽然发现下面有一行小字,好像说的就是这个一键升级,要不试试?正在想的时候手指一不小心的点击了下去,呼!停用,删除,安装,successfully! 完了?不会吧?赶紧去插件选项看看,3.0.3.1,升级成功!这。。。这也太简单了吧?不是做梦吧?相当方便的一个功能!使劲的赞一个! 看来2.5的更新真的是越来越人性化了,非常适合咱们这些菜鸟了! <file_sep>/_posts/2015-03-30-monthly-review-1503.markdown --- layout: post title: Monthly Review 2015-03 date: 2015-03-30 16:08:04 +0800 --- 1. 依然是业务维护型开发,由于在新产品还在调研阶段,并没有太多代码产出,commit 只有 30. 2. 抽空整理 API 文档,Gitbook 写文档挺方便。 3. 面试了十来个 iOS 开发,要想考核别人,首先自己要知道,面试很考验技术的。 <file_sep>/_posts/2017-06-17-7-years-in-beijing.markdown --- layout: post title: 7 Years in Beijing date: 2017-06-17 16:20:35 +0800 --- 7. <file_sep>/_posts/2018-06-06-setlock.markdown --- layout: post title: setlock date: 2018-06-06 15:23:11 +0800 --- > setlock - runs another program with a file locked. `setlock [-nNxX] fn child`,简单说 setlock 会打开 fn 并加锁,然后执行 child。如果 lock 失败,可以指定 child 退出或等待: ``` -n: fn 被其他进程锁住,setlock 放弃执行 child -N: fn 被其他进程锁住,setlock 会等待,直到重新加锁,并执行 child -x: fn 打开失败或已加锁,setlock exit 0 -X: fn 打开失败或已加锁,setlock 输出错误并退出 ``` setlock 可以和 crontab 搭配使用,比如某个任务每十分钟执行一次,如果上一次执行尚未退出,不再开启新任务: ``` */10 * * * * /usr/bin/setlock -n /tmp/test.lock /home/x.sh ```<file_sep>/_posts/2012-01-11-setup-mac-development-environment.markdown --- layout: post title: "Setup Mac Development Environment" date: 2012-01-11 11:17 --- 1. System Software Update. 1. Download and install Xcode, or **Command Line Tools for Xcode** only if you don't need Xcode. 1. Install [Homebrew][Homebrew]. 1. Get back your dotfiles if you have. ---- ## Python 1. Use `pip` instead of `easy_install` 1. Use `pip` to install `virtualenv` and `virtualenvwrapper` ``` # use easy_install to install pip sudo easy_install pip # where pip /usr/local/bin/pip # virtualenv sudo pip install virtualenv # which virtualenv /usr/local/bin/virtualenv # virtualenvwrapper sudo pip install virtualenvwrapper # virtualenvwrapper will be installed in /usr/local/bin/virtualenvwrapper.sh # config virtualenvwrapper mkdir ~/.virtualenvs # edit .zshrc and add export WORKON_HOME=$HOME/.virtualenvs source /usr/local/bin/virtualenvwrapper.sh ``` ---- ## Ruby Install [RVM][RVM] ``` # add to .zshrc [[ -s $HOME/.rvm/scripts/rvm ]] && source $HOME/.rvm/scripts/rvm # install ruby by rvm rvm install 1.9.2 && rvm use 1.9.2 rvm rubygems latest ``` [Homebrew]:https://github.com/mxcl/homebrew/wiki/installation [RVM]:https://rvm.beginrescueend.com/ <file_sep>/_posts/2016-06-30-monthly-review-1606.markdown --- layout: post title: Monthly Review 2016-06 date: 2016-06-30 11:05:05 +0800 --- 1. 设计师的面试比我现象中要难很多,设计不像开发,可以直接出题考核,进展缓慢。 2. 新应用推广,目前市面上推广渠道,广点通算是性价比最好的了。 3. 推广的时候才会发现渠道是多重要,好的渠道实在是少,我们自己也是渠道,只不过天花板明显。 4. 每个小编负责一块工作,运营好转一些。产品上小改进有,但是大的方面还很不足,需要多花心思。 5. 北京-洛阳直达车少,端午节回家绕道郑州,没车确实不便。以后到郑州再租车或许是个好方法。 <file_sep>/_posts/2012-07-18-uisegmentedcontrol-error-on-ios-4-dot-x.markdown --- layout: post title: "UISegmentedControl error on iOS 4.x" date: 2012-07-18 21:35 --- Code 1: ```objc self.segmentedControl = [[[UISegmentedControl alloc] init] autorelease]; [_segmentedControl setSelectedSegmentIndex:0]; [_segmentedControl addTarget:self action:@selector(segmentedControlSwitch) forControlEvents:UIControlEventValueChanged]; ``` Code 2: ```objc self.segmentedControl = [[[UISegmentedControl alloc] init] autorelease]; [_segmentedControl addTarget:self action:@selector(segmentedControlSwitch) forControlEvents:UIControlEventValueChanged]; [_segmentedControl setSelectedSegmentIndex:0]; ``` 注意 `[_segmentedControl setSelectedSegmentIndex:0];` 的位置,在 iOS 4.x 下,Code 2 代码在设置 `selectedSegmentIndex` 的时候会执行一次 `segmentedControlSwitch` 方法。在 iOS 5+ 没有这个问题。 <file_sep>/_posts/2014-11-08-yoda.markdown --- layout: post title: "Yoda" date: 2014-11-08 17:00:03 +0800 --- > "Always pass on what you have learned." <file_sep>/_posts/2018-09-20-pretty-format-json-in-vim.markdown --- layout: post title: Pretty format JSON in Vim date: 2018-09-20 17:40:52 +0800 --- ``` command! PrettyJSON %!python -m json.tool ``` or, [coc.nvim][1] + [coc-prettier][2], which can format JavaScript/TypeScript/HTML/JSON using [Prettier][3]. [1]: https://github.com/neoclide/coc.nvim [2]: https://github.com/neoclide/coc-prettier [3]: https://github.com/prettier/prettier<file_sep>/_posts/2008-08-19-51-to-wordpress.markdown --- layout: post title: "51博客搬家到wordpress" --- 丫头老早就开始写日志,应该算日记,基本上就三五个人知道,到现在差不多170多篇,07年一月份到现在,够能坚持的。可是51日志显得太乱了,花里胡哨的,对Fx支持还相当差,就想着把丫头的日志也给独立出来,反正我那么大的空间一个人肯定是用不完,-_-|||。 网上Google了一下,方案如下:51->163 blog->Blog_Backup导出RSS 2.0格式,然后修改后利用wordpress的RSS导入。 各大BSP好像都有博客搬家功能,不过支持51的就找到Blogbus跟163,另外,blogbus也可以将日志已xml格式导出到本地,网上流传冰古的blogbus2wordpress转化我试了一下,失败,不管是本地php环境还是放在空间上都没有成功,就放弃了。改用 [blog_backup](http://www.pt42.cn/blog_backup_index.htm),一个多功能的blog备份工具软件,支持N多BSP,流行的独立blog程序,像wp,pjblog,z-blog,bo-blog都支持,连饭否这种微博客都支持,很好很强大。 先用163搬家从51里弄出来,完成以后,用blog_backup把163 blog导出,导出格式为RSS 2.0,UTF-8编码,使用wp的RSS导入功能进行导入,很完美。 看起来挺简单的,不过我试了好几次才搞定。刚开始没有对blog_backup导出的xml文档修改,导入进去后就显示一个标题,然后删掉,修改,再倒入,来回好几次,还好我是在本地php环境弄的,不然岂不是要慢死了。嗯,还算是完美,丫头也挺惊喜的,不过她买不买帐还是另外一回事。 <file_sep>/_posts/2015-02-09-nginx-ifisevil.markdown --- layout: post title: Nginx If Is Evil date: 2015-02-09 15:44:55 +0800 --- 官方文档 [IfIsEvil][1]. 简单说在 `location` 中要尽量避免使用 if,如果一定要用,确保 if body 中只包含 **return** or **rewrite**,其他指令可能会出现莫名错误。 解决方案就是用 `try_files` 替换: ``` location / { try_files $uri $uri/index.html $uri.html =404; } ``` 如果想 if 和 try_files 一起用,可以把 if 放在 `location` 外: ``` set $APP 'unknown'; if ($query_string ~ "app=([^&]+)") { set $APP $1; } location = /api { try_files /$APP/data.json /data.json =404; } ``` ---- Nginx [Pitfalls][2] 列举了一些 nginx 陷阱,值得学习。 ---- 春哥这篇 [How nginx "location if" works][3] 做了逐步分析,学习。 [1]:http://wiki.nginx.org/IfIsEvil [2]:http://wiki.nginx.org/Pitfalls [3]:http://agentzh.blogspot.jp/2011/03/how-nginx-location-if-works.html <file_sep>/_posts/2012-07-10-ipad-os-version-history.markdown --- layout: post title: "iPad OS version history" date: 2012-07-10 18:21 --- iPad 的系统版本历史 (via [iOS version history](https://en.wikipedia.org/wiki/IOS_version_history)): 1. 3.2/3.2.1/3.2.2,iPad Only. 2. 4.2/4.2.1 3. 4.3.x 4. 5.x 5. 6.x iPad 的系统版本并不是连续的,3.2 是上市时的版本,iPad 独享。iOS 里程碑 4.0 刚开始并不支持 iPad,直到 4.2 才支持。4.3 随 iPad 2 发布,之后的 iOS 都是全设备支持。 所以做 iPad App 时系统要求可以从 4.2 起步,为了兼容 3.2 的用户需要做很多处理,总体来说不值当。 <file_sep>/_posts/2015-11-20-linux-audit-file-change.markdown --- layout: post title: Linux 监控文件被什么进程修改 date: 2015-11-20 00:04:25 +0800 --- 安装: `apt-get install auditd`. 1. `auditd` 是后台守护进程,负责监控记录 2. `auditctl` 配置规则的工具 3. `auditsearch` 搜索查看 4. `aureport` 根据监控记录生成报表 比如,监控 `/root/.ssh/authorized_keys` 文件是否被修改过: `aditctl -w /root/.ssh/authorized_keys -p war -k auth_key` * `-w` 指明要监控的文件 * `-p awrx` 要监控的操作类型,append, write, read, execute * `-k` 给当前这条监控规则起个名字,方便搜索过滤 查看修改纪录:`ausearch -i -k auth_key`,生成报表 `aureport`. <file_sep>/_posts/2012-12-31-self-review-2012.markdown --- layout: post title: "[self review:2012];" date: 2012-12-31 10:31 --- 2012 ==== 2012 年度个人总结。先对一下[去年][1]计划: #### 工作 > 加强 iOS 开发,尤其是新技术的学习和整理,比如 ARC。 Done. > 尝试 iPad 开发,这可不是简单的界面放大,整个用户交互都需要重新学习理解。 Done. > 服务端开发,至少是应用级别要跟上,已经落户一步,不能拖太久。 FAIL > 继续加强产品能力,尤其是整体把握。 Fail. #### 生活 > 完婚。 DONE. > 给家里更多的帮助,让爸妈轻松一点。 Done. > 希望今年能有一次旅游,厦门? Done. 上半年的张家界+年底的版纳旅游。 每项按十五分的话刚刚过 70,及格分。 ---- ### 工作 今年在工作上做了一些侧重,尤其是下半年,更多偏向于技术开发。自己在产品、交互等方面并不特别擅长,可能偶尔会有一些灵感飞过,但整体上的把控力还很欠缺,细节不够严谨。所以从下半年开始,更多的重心放在技术上,code review,产品代码质量把控上。我不知道这种侧重好还是不好,对自己以后的职业走向是利还是弊,暂时来说我想先把技术能力再提高一下。团队也有很多参与产品的机会,所以产品方面还可以继续锻炼。 侧重技术并不是自己技术有多牛,相反,越做越发现自己还有太多太多不懂的东西。有不懂才会有收获,今年工作上最多的收获来自 iOS 开发有了一些新的技术学习和积累。iOS 开发是一个进化非常快的领域,保持积极的学习状态很重要。ARC、GCD、Blocks、Core Data、AFNetworking、CocoaPods、UITableView 以及 App 的性能优化等等,这些技术点都遇到了很多坑,交了学费,但是对自己的技术成长很有好处。问题的解决和技术学习都留了一些笔记,好记性不如烂笔头。 相较于客户端开发有了一些积累,服务端开发今年没有任何进步,这一点很失望。主要原因是自己太懒散,缺乏动手去做,没有实践就不能发现问题,没有问题连学费都没得交,怎么可能有进步。所以新的一年里服务端开发是自己要着重加强的,不管什么一定要动手去做。 ### 生活 我们结婚了,这就是今年的最大的成就。罗列好需要做的工作,然后两个人一起努力各个击破,这种感觉很不错,不啃老,我们做到了。爸妈牵挂我们在外的漂泊,我们更心疼他们在家的辛苦。让爸妈的压力不那么大是我们最想要的,为此我们会尽自己最大的努力去分担。 我还在坚持着,努力着,在外漂泊的不安定感却一直都在。这种感觉从 12 岁出去念初中开始,只有宿舍没有家。还好,我们现在两个人在一起,我不坚强的时候有你,你不坚强的时候有我,该哭的时候哭了,该笑的时候笑了。 2013 ==== ### 工作 1. iDev 深入,比如 runtime,自动化测试等,尝试一下 OS X 开发。 1. 服务端开发学习。 1. 学一门新语言,Lua/Go。 ### 生活 1. 学车考驾照。 1. 健身锻炼。 [1]:https://fann.im/blog/2011/12/31/self-review-2011/ <file_sep>/_posts/2010-02-10-home-for-happy.markdown --- layout: post title: "Home for Happy" --- 过年回家,回家过年。 晚上火车回家,半年多了,想家啊,想爸妈,想小妹,想那帮子兄弟,真的,想你们。 回家要开开心心的,高高兴兴的,忘掉工作,远离网络,好好的陪爸妈说话,跟兄弟们耍乐。 Home for happy! <file_sep>/_posts/2010-03-24-picky-change-log.markdown --- layout: post title: "Picky 改动记录" --- 先谢国家,再谢 [picky][picky],简洁而强大的 Blog powered by GAE。自己做了一点点改动,记录一下,下次升级时候备忘。 1. main.py - 添加全局变量 **`template_values = {}`**. RobotsHandler 生成 robots.txt 的时候没有对 template_values 定义赋值,造成 robots.txt 生成不能。 2. robot.txt 修改 sitemap.xml 为绝对地址,跟第一个有关. 3. 删掉了 default 主题 sidebar.html、article.html 两个模板文件里的 Google Ads。 4. header.html 追加 Google Webmaster Meta 验证。 5. 换了 Favicon。 [picky]:http://picky.olivida.com/picky <file_sep>/_posts/2010-04-28-old-blog-count.markdown --- layout: post title: "旧博客统计留念" --- ![ old blog count ]( http://lh5.ggpht.com/_vYr4JQreqXA/S9ez4QV8NvI/AAAAAAAABEk/EPn_U8-fzRM/s512/name-log.png ) 根据雅虎统计,从 2008-04-02 开始,恰好两年时间。 <file_sep>/_posts/2008-11-01-weekend-1101.markdown --- layout: post title: "Weekend-1101" --- 好久没有更新了,忙算一个,其实也上网的,中午时候,晚上自习回来时候,上网看看Greader,了解一下新闻,不然一不小心都落伍了。 1. 昨天考研报名最后时间。中午时候上去确认了一下信息,其实也没啥确认的,同学都说报上几个,免得到交钱时候后悔了又不能报名,我还是就报了一个,确认了报考信息,就这样吧。 2. 数学第一轮算是结束了吧,三本书概念性的东西先过一遍。买了本书,题海战术,600页,先来个手熟。 3. 今年开始专业课统考,计算机四门,三个是上学年的课,丢的还不是很厉害,组成原理一个星期过了一遍书,数据结构有点忘了,下个星期开始吧。 4. 这周的新闻挺多的,Win 7出来了,Red Alert 3也来了,中午时候装上看了一下,还是不错,就是卡,笔记本跑起来还有点吃力。 5. 话说Win 7放出来的样图挺不错的,特效更细腻了,据说性能上优化了不少,比Vista好,还是值得期待的。其实Vista用了之后也发现微软没白费力,细节上的东西做的还是挺好的。 6. 上篇日记说强迫式学习,嗯,挺有效果的,现在发现Vim的高效操作性不是吹的,一个简单的Vimperator模仿出来的快捷操作就很NB了。 7. 昨天,Ubuntu 8.10出来了,可惜没时间啊,寒假吧,一定要装上去,强迫自己去学习一下,而不只是为了3D特效。 8. 好像今天是中光棍节,吼吼,兄弟几个光棍节快乐,我就不掺和了。 长时间不更新估计Google都会给我降权,以后每周末来一个Weekend Homework,嗯。 <file_sep>/_posts/2008-03-26-english-ubuntu-locale-use-chinese-input.markdown --- layout: post title: "英文ubuntu使用中文输入法" --- 只用过scim,编辑 `/etc/gtk-2.0/gtk.immodules`(如果存在的话) 或者 `/usr/lib/gtk-2.0/2.10.0/immodule-files.d/libgtk2.0-0.immodules` 文件,在xim 的 local 增加 en 也就是说: `"xim" "X Input Method" "gtk20" "/usr/share/locale" "ko:ja:th:zh"` 改成: `"xim" "X Input Method" "gtk20" "/usr/share/locale" "en:ko:ja:th:zh"` 保存退出,重启。 <file_sep>/_posts/2012-01-09-speed-up-xcode-documentation-search.markdown --- layout: post title: "加速 Xcode 文档搜索" date: 2012-01-09 11:27 --- Xcode 的文档搜索速度实在是不给力,因为 Xcode 是实时的索引所有 Doc Sets 来查找。解决方法: 1. 更换 SSD,一劳永逸,更能带来编译速度的极大提升。 1. 第三方文档搜索工具,比如 Ingredients、AppKiDo,缺点是没法和 Xcode 完美结合,比如 Option+Click 快速查找。 1. 修改 Find Options 来减少一些索引,只做 iOS 就没必要选 Mac 的 Doc Sets. 另外 Match Type 选 **Prefix** 也会快很多。可以参考下面这个 Find Options 设置。 ![speedup Xcode doc search](https://i.loli.net/2019/04/29/5cc695e762320.jpg) 感谢 @[jjgod](http://www.v2ex.com/t/22088#reply16) 分享的小技巧。 <file_sep>/_posts/2011-12-31-self-review-2011.markdown --- layout: post title: "[self review:2011];" date: 2011-12-31 09:54 --- ## 2011 2011 年度个人总结。 ### 工作 一整年的 iOS 开发,相对于去年入门时 Rookie 最大的成长是教训,经验和信心。 有那么一次,客户端测试时候频繁崩溃却毫无头绪,那个上火啊,甚至晚上做梦都在 Debug,有一晚上还真在梦中解决了一个问题。没有教训就没有记忆,这也是为啥后来我偏执的强迫症般的抓内存泄漏找潜在崩溃。经验就是由这么一堆教训堆积出来的,一次次的总结然后下一次避免,这不就是成长么? 如果一年前跟我说我们的竞争对手如此之多,甚至还有上市公司,我绝对没有信心去继续这个项目。不是说我太消极,而是对于这个市场的一无所知。不是都说恐惧源自于无知么。这一年下来,随着技术上的完善,产品的坚持,市场的更加熟悉,我们现在是信心满满的面对每个竞争对手。 本来四季度时想跟进学一下服务端开发,阴差阳错的给错过了,算是今年的一个遗憾吧。来年一定要跟进。 没来得及搞服务端,腾出时间整理了内部 iOS 编码规范和通用库,这个过程正好把前面一年的开发梳理了一下,收获很大。以后要坚持定期的回头梳理。 产品细节上这一年有不少进步,但是整体把控还不行,产品这一块是个长期,坚持。 ### 生活 圣诞节时跟远大萌感慨说老了,平安夜都没有出去 High。其实是平静了,我们会周末窝家里做饭,给爸妈打电话唠叨,我觉得挺好。 今年最高兴的就是在家里需要的时候我和妞妞有能力帮一把,不让爸妈那么累,那么苦,尽管力量还很小。我一直认为家是生活的中心,如果连家里人的生活都无力改善,那你改变世界的理想都是扯淡。 大年初六我和妞妞订婚了。这一年我们有生气,有争吵,但我们比以往更爱对方。两个人在一起不容易,很感谢妞妞对我的理解、支持和包容。 这一年控制着没有继续长胖,不过也没有瘦,身体没有什么大毛病,但明显身体素质比以前差了不少,得加强一下锻炼,向罗胖子学习。 ---- ## 2012 ### 工作 1. 加强 iOS 开发,尤其是新技术的学习和整理,比如 ARC。 1. 尝试 iPad 开发,这可不是简单的界面放大,整个用户交互都需要重新学习理解。 1. 服务端开发,至少是应用级别要跟上,已经落户一步,不能拖太久。 1. 继续加强产品能力,尤其是整体把握。 ### 生活 1. 完婚。 1. 给家里更多的帮助,让爸妈轻松一点。 1. 希望今年能有一次旅游,厦门? 最后来张截图 ![2011](https://lh5.googleusercontent.com/-1esKyCPlUzw/TwBoa4fV9oI/AAAAAAAABcc/hKjbgXeSiC8/s800/2011.png) <file_sep>/_posts/2010-04-13-delphi-adotable-append-delete-filter-edit.markdown --- layout: post title: "Delphi ADOTable 增删查改" --- //添加记录 ``` ADOTable1.AppendRecord([val1,val2]); ``` //删除记录 ``` ADOTable1.Filter :='SaleID='''+text+''''; ADOTable1.Filtered := true; if ADOTable1.RecordCount = 0 then begin ADOTable1.Filtered := false; end; else begin ADOTable1.Filtered := true; ADOTable1.Delete; ADOTable1.Filtered := false; end; ``` //查找记录 ``` ADOTable1.Filter := 'SaleID='''+text+'''' ; ADOTable1.Filtered :=True; ``` //更新记录 ``` ADOTable1.Edit; ADOTable1.FieldByName('SaleID').Asstring := text; ADOTable1.Post; ``` <file_sep>/_posts/2008-04-14-sql-study-select-1.markdown --- layout: post title: "SQL学习--单表查询" --- 指定列:`select Sno,Sname from Student;` 查询经过计算的值:`select Sname, 'year of birth:', 2008-Sage, Sdept from student;` 去除取值重复的行:`select distinct Sno from student;` 足条件的元组:`select Sname,Sage from Student where Sdept ='CS' AND Sage&lt;=19;` 确定范围,集合 `select Sname from Student where Sage BETWEEN 18 AND 20;` 匹配查询 `select * from Student where Sno LIKE '100%';` Order By子句 `select Sno,Grade from SC where Cno ='2' ORDER BY Grade DESC;` //DESC是降序,缺省为升序 聚集函数:`select COUNT(Sno) from Student;` Group By子句:`select Cno,COUNT(Cno) from SC GROUP BY Cno;` <file_sep>/_posts/2008-10-12-death-race-man-movie.markdown --- layout: post title: "死亡飞车,男人的电影" --- 嗯,是男人的电影,不适合女生一个人看,因为过于暴力,机械暴力。 很简单的剧情,或者说很俗套的剧情。Jason,很爱家的男人,被更为强大的女魔头利用陷害,进了监狱,玩犯人间的死亡游戏,死亡飞车游戏,来给监狱长带来利益。当他察觉以后,以一种很男人的方式去解决,等到自由。电影最后,Jason的铁汉柔情,抱着自己的小女儿,“我爱我的女儿胜过其他所有人”。 很像《肖申克的救赎》,都是监狱里的故事,主角都是含冤入狱,继而被典狱长利用,所不同的是,《肖申克的救赎》是男人的隐忍,一忍十年,坚毅,不放弃自己追求自由的脚步。《死亡飞车》则是用更为男人更为直接的方式去争取自由,用武力用暴力,以牙还牙,电影里面最帅的镜头是Jason跟机枪手George在死亡游戏第二轮里面合伙搞掉典狱长的大无畏,一个强大于自己数倍的力量,是对典狱长暴力的最直接反抗,最直接斗争。 很多时候,男人必须暴力,因为暴力是男人表现爱的方式。 <file_sep>/_posts/2017-07-20-curl-notes.markdown --- layout: post title: cURL Notes date: 2017-07-20 15:44:13 +0800 --- * `curl -c cookie.txt URL`: save cookies to cookie.txt * `curl -b cookie.txt URL`: read cookie from cookie.txt and put into request * `curl -H 'User-Agent: FakeUA' URL`: set HTTP header * `curl -I URL`: show header only * `curl -L URL`: follow 30x redirect * `curl -o new_name/-O URL`: save response to file * `curl -X POST --data "data=xxx" URL`: POST data to URL * `curl -w "@curl-format.txt" URL`: format details of request, which you can use this to timing request: ``` ➜ cat curl-format.txt time_namelookup: %{time_namelookup}\n time_connect: %{time_connect}\n time_appconnect: %{time_appconnect}\n time_redirect: %{time_redirect}\n time_pretransfer: %{time_pretransfer}\n time_starttransfer: %{time_starttransfer}\n ----------\n time_total: %{time_total}\n ➜ curl -w "@curl-format.txt" -o /dev/null -s https://fann.im time_namelookup: 0.015 time_connect: 0.015 time_appconnect: 0.329 time_redirect: 0.000 time_pretransfer: 0.329 time_starttransfer: 0.377 ---------- time_total: 0.377 ``` <file_sep>/_posts/2014-05-19-reload-haproxy-on-the-fly.markdown --- layout: post title: "Reload HAProxy on the fly" date: 2014-05-19 15:52:11 +0800 --- ``` haproxy -f /etc/haproxy/haproxy.cfg -p /var/run/haproxy.pid -sf $(cat /var/run/haproxy.pid) ``` <file_sep>/_posts/2008-11-23-weekend-1123-1g1g.markdown --- layout: post title: "Weekend-1123,推荐一下亦歌" --- 这周的Weekly来推荐一个听歌网站:[亦歌](http://www.1g1g.com), 很简洁,整个页面就一个flash,就一个播放器,如果你够懒的话啥都不用做,打开亦歌就开始享受自动推送的音乐吧。当然,亦歌也是很强大很智能的,注册登录后可以对播放列表进行删除添加,可以收藏歌曲,然后亦歌会根据你的操作习惯分析你的音乐喜好,然后推送你可能会喜欢的,很赞! [YOBO](http://www.yobo.com) 也是一个很好的在线音乐听歌网站,也会根据你的听歌习惯分析你的音乐DNA,然后自动推送,你也可以自己建立音乐专辑。不过YOBO的重点是音乐SNS,很强调朋友间的音乐分享,写听歌的感受,是一个非常赞的音乐垂直型SNS。以前是在YOBO上听歌,不过自从发现了亦歌之后就把YOBO给放弃了,因为YOBO的庞大,也因为我很懒,我不想过多花时间在YOBO去做些跟听歌无关的事。 再次推荐一下亦歌,简单实用,尤其是用Firefox,在侧边栏打开,一切就是这么美好,呼呼!~ <file_sep>/_posts/2012-03-14-enable-spdy-in-firefox-11.markdown --- layout: post title: "Enable SPDY in Firefox 11" date: 2012-03-14 09:41 --- [SPDY][1] is a new network protocol developed by Google for faster web. Google Chrome has a build-in support of SPDY long long ago. Now Firefox brings SPDY support in Firefox 11, but is disabled by default. You can enable it as follow: Open `about:config` in Firefox, search `network.http.spdy.enabled` and set to `true`. via [here][2] [1]:https://en.wikipedia.org/wiki/SPDY [2]:https://bugzilla.mozilla.org/show_bug.cgi?id=528288#c174 <file_sep>/_posts/2011-11-02-do-not-do-what-you-hate-by-yourself.markdown --- layout: post title: "不要做让自己讨厌自己的事" --- 如果一件事,你在做的时候自己心里有抵触,那就赶紧放手,至少想清楚后再决定。 如果做了一件事,后来回想起来的时候是无比讨厌,记住下次一定不要再这么做。 不要做让自己讨厌自己的事。 <file_sep>/_posts/2018-03-08-pythone-env.markdown --- layout: post title: macOS Python env date: 2018-03-08 10:15:31 +0800 --- ``` brew install python which python // /usr/bin/python which python3 // /usr/local/bin/python3 sudo easy_install neovim pip3 install --upgrade neovim ``` 多版本共存还可以用 [pyenv](https://github.com/pyenv/pyenv) 解决。 使用 [pipsi](https://github.com/mitsuhiko/pipsi) 安装 Python-base 工具,比如 ansible,httpie,pylint,yapf 等: ``` sudo /usr/bin/easy_install virtualenv curl https://raw.githubusercontent.com/mitsuhiko/pipsi/master/get-pipsi.py | /usr/bin/python pipsi install 'python-language-server[all]' pipsi install pipenv ``` 对于 Python 项目,通过 [pipenv](https://github.com/pypa/pipenv) 管理包依赖: ``` pipenv install --python 3.6.5 pipenv install requests pipenv shell ``` 设置 VSCode 支持 pipenv: ``` { "python.pythonPath": "/Users/fannheyward/.virtualenvs/tools-CDG8SfKX/bin/python" } ``` <file_sep>/_posts/2012-03-25-multiple-target-with-different-bundle-display-name.markdown --- layout: post title: "多 Target 下不同的 Bundle Display Name" date: 2012-03-25 15:32 --- 真不好用一个标题来概括这个东西。Xcode 4.2+ 在项目多语言包 `xx.lproj` 里引入了一个叫 `InfoPlist.strings` 的文件,可以对同一个 App 在不同系统语言下显示不同的 Display Name。比如: ``` InfoPlist.strings (English) - "CFBundleDisplayName" = "English Name"; InfoPlist.strings (Chinese) - "CFBundleDisplayName" = "中文"; ``` 在单 Target 下很容易做,多 Target 的时候就需要做一点额外的处理。在项目目录下新建与 Target 同名的文件夹(同名是为了方便区分),然后将 `xx.lproj` 文件夹 **复制** 到各个 Target 下面,目录结构会是这个样子: ``` ./Target1/ en.lproj/InfoPlist.strings zh-Hans.lproj/InfoPlist.strings ./Target2/ en.lproj/InfoPlist.strings zh-Hans.lproj/InfoPlist.strings ``` 复制后保持项目目录下还有 `xx.lproj` 文件夹,里面保留 `Localizable.strings`,因为多语言化一般是通用的,没必要针对每一个 Target 做多语言。复制后的 `Target1/xx.lproj` 下只有 `InfoPlist.strings`。然后添加到 Xcode 项目里,打开 Xcode - Views - Utilities (Command+Option+0),在 `Target Membership` 下针对不同的 Target 把对应文件夹下的 `InfoPlist.strings` 对应连接起来,Done。 <file_sep>/_posts/2008-06-17-vista-beginning.markdown --- layout: post title: "开始Vista" --- 由于XP系统崩溃,装了vista,打算转向vista。 其实老早时候就试过vista,那时候还是RTM版的,当时在同学的电脑上玩了半天,体会不算太大,就感觉界面好漂亮,当然是拿高配置砸出来的。当时最喜欢的就是vista资源管理器的地址栏设计,相当喜欢。vista细节上的设计确实有很大进步,一个小小的例子,文件重命名的时候不会选取后缀名,很小的细节上的改进,人性化了好多。不过刚开始的时候vista的兼容性是一个非常大的问题,让人很是恼火,再加上自己电脑的配置不是怎么高,就算了,一直坚守在xp阵营,一直到现在。 打定决心转vista,其实我也不怎么想。但是早晚都是个趋势,微软已经说了,Windows 7不会有新内核,是vista和serve 2008的基础上出来的Windows 7。就算是为了Windows 7现在也应该适应一下vista,比如系统进程上的改进。vista把服务项都并到进程里面,一开任务管理器40-50个进程,同学的更是达到60+,一看一堆莫名其妙的进程项,突然怀疑自己的电脑智商了。。。熟悉一下vista的系统应用同样很重要,虽然xp熟悉的话上手很容易,但是差别还是有的,要学习的东西还是很多。 不管什么原因吧,开始转向vista,还好电脑还是比较争气的,系统最低打分是显卡的3.2,其他项都是4.3+,不错不错!~ <file_sep>/_posts/2019-07-31-add-and-remove-hadoop-datanode.markdown --- layout: post title: 动态添加/删除 Hadoop DataNode date: 2019-07-31 16:28:11 +0800 --- ### 添加节点 1. NameNode 添加节点 `etc/hadoop/slaves` 1. 同步 `etc/hadoop` 配置 1. 在新节点 `./sbin/hadoop-daemon.sh start datanode` 1. 在 NameNode 刷新 `hdfs dfsadmin -refreshNodes` ### 删除节点 1. 在 `etc/hadoop/excludes` 写入要删掉的节点地址 2. 修改 `etc/hadoop/hdfs-site.xml`: ```xml <property> <name>dfs.hosts.exclude</name> <value>/home/web/hadoop/etc/hadoop/excludes</value> </property> ``` 1. 修改 `etc/hadoop/mapred-site.xml`, 这个是下线 nodemanager ```xml <property> <name>mapred.hosts.exclude</name> <value>/home/web/hadoop/etc/hadoop/excludes</value> <final>true</final> </property> ``` 1. 修改 `etc/hadoop/slaves`,去掉要删除的节点 1. 同步 `etc/hadoop/excludes` 和 `etc/hadoop/slaves` 到所有 **NameNode** 1. 在 NameNode 执行 `hdfs dfsadmin -refreshNodes` 1. `hdfs dfsadmin -report` 查看要删除的节点状态变化 `Normal -> Decommission in progress -> Decommissioned` 1. 在要删除的节点 `./sbin/hadoop-daemon.sh stop datanode`,等待 Admin State 变更为 Dead ### 检查节点 `hdfs fsck /` 检查文件系统信息,正常是 `Status: HEALTHY`,如果 `Status: CORRUPT` 说明 blocks 有损坏,其中 `Missing blocks` 表示有丢失,但有备份,`Missing blocks (with replication factor 1)` 表示 block 损坏丢失也没有备份,不可恢复。 可以用 `hdfs fsck / -delete` 来检查并删除有损坏的 blocks. ### 调整 JournalNode 1. 修改 `etc/hadoop/hdfs-site.xml`: ```xml <property> <name>dfs.namenode.shared.edits.dir</name> <value>qjournal://hadoop01:8485;hadoop02:8485;hadoop03:8485/cluster</value> </property> ``` 1. 同步到所有节点 2. 如果是新增节点,要同步 `dfs.journalnode.edits.dir` 下 edits 文件 3. 在调整的 journalnode 节点启动/关停: `./sbin/hadoop-daemon.sh start journalnode` 4. 重启 standby NameNode: `sbin/hadoop-daemon.sh stop|start namenode` 5. 切换节点为 active: `hdfs haadmin -failover nn1 nn2`,重启其他 namenode 6. 检查 NN 状态 `hdfs haadmin -getServiceState nn1` ### 调整 NodeManager 1. 修改 `etc/hadoop/yarn-site.xml` ```xml <property> <name>yarn.resourcemanager.nodes.exclude-path</name> <value>/home/pubsrv/hadoop/etc/hadoop/excludes</value> </property> ``` 1. 同步到 ResourceManager 2. 重启 ResourceManager,`sbin/yarn-daemon.sh stop|start resourcemanager` 3. 修改 excludes,添加要删除的节点地址 4. `yarn rmadmin -refreshNodes` 5. `yarn node -list -all` 检查 ### 调整 Spark 节点 - 新增:在 worker 上 `./sbin/start-slave.sh spark://master:7077` - 删除: 在 worker 上 `./sbin/stop-slave.sh`,需要注意的是如果 `$SPARK_PID_DIR` 没有指定的话,默认是在 `/tmp`,类似 `/tmp/spark-hadoop-org.apache.spark.deploy.worker.Worker-1.pid` - 在 master 节点修改 `conf/slaves` - [https://www.jianshu.com/p/727da7ba438a](https://www.jianshu.com/p/727da7ba438a) - [https://www.iteye.com/blog/shift-alt-ctrl-2102571](https://www.iteye.com/blog/shift-alt-ctrl-2102571) <file_sep>/_posts/2008-08-17-back-for-xiaonei.markdown --- layout: post title: "重新玩校内" --- 自从校内开放API平台后,我就知道我回到校内的时间要来了。 也不知道上回是因为啥,就把校内给自杀了,当然,是暂时冷冻掉。早在校内还没完全开放注册时候,注册校内得是教育网内部IP,貌似那时候工大也还不能注册,那时候就听说校内了,应该是06年,仿美国一网站,当时评价挺高的。所以,当工大能注册的时候赶紧的注册进去玩。嗯,刚开始发现确实挺好玩的,找到了许多以前的同学,打打招呼,留个言什么的。我记得当时为了改一个校内的模板,楞是弄了一个周末,要知道那时候我还没有电脑,在同学电脑上霸占着。 后来慢慢的热情下去了。也还有是因为校内那个时候变得跟猫扑论坛一样,乱七八糟的,跟一般的BBS也没多大区别。渐渐的,上校内也只是到少数几个人的页面上看看,都是好兄弟好朋友的那种,看看他们近况咋样,纯属关心那种的,也就把校内慢慢变成了一个亲情SNS。 再后来,校内变得有点让人失望。先不说别的,广告加的绝不比猫扑少。也许是因为校内让猫扑大东家给收购了,慢慢的这俩“孩子”都挺像的。还有就是校内那时候只忙着扩军,很少改进自己的东西,老那几样玩的没啥意思,所以,上校内的时间也就越来越少了。以至于某一天我心情不好直接给自杀了。 玩校内中间夹杂着海内。这两都是王兴的“内人”。。。刚开始时候海内挺像一个搞网络搞IT搞计算机的人专门的精英SNS,很多网络大佬,技术牛人都在海内里,那时候我也溜了进去,瞎转悠。就觉得海内比校内干净的多,其他的还是像,就想着在海内定居玩玩。可是,又一个可是,慢慢的海内人气也下去了,海内开始走娱乐线路,大佬们都慢慢的离开,海内的娱乐线路也不好玩,更何况还有好多其他的SNS,开心网,一起,这些个专业搞娱乐的,海内也慢慢冷落下来了。现在海内已经被我给阉割的就是一个封闭版的饭否,一个人瞎说话瞎扯淡。 跑题了,接着说校内。校内还是挺争气的,知道SNS该怎么走,开放平台是个好东西,好玩的东西会越来越多啊。所以说,校内开放平台后,我就又打算回来了,回来玩玩平台,想自己学学网络编程,权当练手。重新玩校内,咱得换个玩法,校内APP开发,好好学习一下。 <file_sep>/_posts/2008-08-03-upgrade-wp-26-speed-wp.markdown --- layout: post title: "升级到wordpress 2.6,尝试加速wordpress" --- 话说wordpress 2.6发布都快一个月了,一直懒得升级。说实话,wp现在的功能是越来越强大,不可避免的,体积也相应的越来越臃肿。对我来说,也就偶尔写个东西发发牢骚,没必要跟进更新那么快,不过今天实在是无聊,就顺手把升级一下wp,顺带更新/安装了几个插件,记录一下。 * wordpress从安装上到现在已经升级过多次,相对来说非常简单。第一步备份,比较懒的办法就是全站备份,简单一点只备份数据库即可。 * 登入后台禁用全部插件。wp-config.php文件变化比较大,才发现现在的wp-config.php文件版本居然还是wp 2.1时候的,-_-|||。更新之,发现多了很多新鲜玩意,secret-key,这个好象是从wp 2.5时候加入的新功能,安全性的考虑,加入. * wp 2.6加入了类似WIKI的文章编辑修订功能,就是你可以恢复到以前的文章编辑状态,自己写东西感觉实在是个鸡肋,多人写博客倒还是个好东西,况且,每保存一个状态就会在数据库posts中插入一个记录,这样的后果就是数据库爆掉,数据多了查询速度也会慢下来,所以,禁用之。在wp-config.php中间添加一句代码: `define('WP_POST_REVISIONS', false);` * 上传覆盖所有文件,运行升级/wp-admin/upgrade.php,很顺利,然后再启用插件,over! 升级后发现登录后台速度慢了好多,得,正好有时间,把老早就想的页面静态化做一下吧。用的是 [cos-html-cache](http://www.storyday.com/tag/cos-html-cache),效果先看看再说。 今天心情算是差到了极点,写东西都没有条理了,算是废了。 <file_sep>/_posts/2013-10-26-git-cherry-pick.markdown --- layout: post title: "git cherry-pick" date: 2013-10-26 21:38 --- > git-cherry-pick - Apply the changes introduced by some existing commits. 实际开发中会有这种情况:同时存在 v1、v2 两个分支,且不可合并。然后发现两个分支都存在某 bug,在 v1 中修复,需要合并到 v2,要么手动修改,或者用 git cherry-pick: ``` git cherry-pick 0ba264a1e666bacc ``` <file_sep>/_posts/2011-07-30-lend-and-borrow-money.markdown --- layout: post title: "借钱" --- 借钱原则: > 以你们的情义,如果你可以接受这钱他不还,那你就借给他。反之亦然。 <file_sep>/_posts/2013-10-30-batch-kill-process.markdown --- layout: post title: "批量杀进程" date: 2013-10-30 21:30 --- 批量杀掉包含某一关键字的进程: ``` ps aux|grep KEY|grep -v grep|awk {'print $2'}|xargs kill -9 ``` <file_sep>/_posts/2016-02-29-blog-birthday-8.markdown --- layout: post title: Birthday 8 date: 2016-02-29 22:19:03 +0800 --- 八年前的 2 月 29 日,[Hello World][1],要坚持写下去。 [1]:https://fann.im/blog/2008/02/29/hello-world/ <file_sep>/_posts/2014-10-17-what-apple-has-done.markdown --- layout: post title: "What Apple has done" date: 2014-10-17 11:50:21 +0800 --- ![1.png](https://i.loli.net/2019/11/11/8sIwdihVPD6F4xk.png) [via](http://www.apple.com/apple-events/2014-oct-event/) <file_sep>/_posts/2008-05-16-baby-i-love-you.markdown --- layout: post title: "亲爱的宝贝,如果你能活着,一定要记住我爱你" --- 来自[中国网](http://www.china.com.cn/info/txt/2008-05/16/content_15264702.htm), 四川地震中的一位母亲留给自己小宝贝的短信。 在四川灾区抢救人员在废墟中发现一具女尸,她是被垮塌下来的房子压死的,透过那一堆废墟的的间隙可以看到她死亡的姿势,双膝跪着,整个上身向前匍匐着,双手扶着地支撑着身体,有些象古人行跪拜礼,只是身体被压的变形了,看上去有些诡异。救援人员从废墟的空隙伸手进去确认了她已经死亡,又在冲着废墟喊了几声,用撬棍在在砖头上敲了几下,里面没有任何回应。当人群走到下一个建筑物的时候,救援队长忽然往回跑,边跑变喊“快过来”。他又来到她的尸体前,费力的把手伸进女人的身子底下摸索,他摸了几下高声的喊“有人,有个孩子 ,还活着”。 经过一番努力,人们小心的把挡着她的废墟清理开,在她的身体下面躺着她的孩子,包在一个红色带黄花的小被子里,大概有3、4个月大,因为母亲身体庇护着,他毫发未伤,抱出来的时候,他还安静的睡着,他熟睡的脸让所有在场的人感到很温暖。 随行的医生过来解开被子准备做些检查,发现有一部手机塞在被子里,医生下意识的看了下手机屏幕,发现屏幕上是一条已经写好的短信 “亲爱的宝贝,如果你能活着,一定要记住我爱你”,看惯了生离死别的医生却在这一刻落泪了,手机传递着,每个看到短信的人都落泪了。 <file_sep>/_posts/2014-12-09-nginx-proxy_cache_valid.markdown --- layout: post title: "Nginx proxy_cache_valid" date: 2014-12-09 17:02:09 +0800 --- [proxy_cache][1] 可以缓存 upstream 响应,其中 `proxy_cache_valid` 设置缓存有效时间,需要注意的是 Nginx 检查缓存是否有效的优先级问题。根据[文档][2]和 [Igor][3],Nginx 判断缓存有效的顺序是: 1. `X-Accel-Expires` 2. `Expires/Cache-Control` 3. `proxy_cache_valid ` 也就是说 Nginx 会优先用 upstream 设置的缓存有效期,这种情况下 Nginx 相当于 Client,如果想忽略缓存直接到 upstream 更新,类似浏览器忽略本地缓存,可以这样设置: `proxy_ignore_headers X-Accel-Expires Expires Cache-Control;` 另外 `proxy_cache_path ... inactive=10m;` 不受 upstream 影响,缓存文件在指定时间内没有被再次访问会被清理删除。 参考: * 文档 [1][4],[2][2] * [Nginx缓存详细配置][5] * [nginx缓存优先级(缓存问题者必看)][6] [1]:https://fann.im/blog/2014/08/30/nginx-proxy-cache/ [2]:http://wiki.nginx.org/HttpProxyModule#proxy_cache_valid [3]:http://forum.nginx.org/read.php?2,2182,2185#msg-2185 [4]:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_valid [5]:http://www.firefoxbug.com/index.php/archives/2089/ [6]:http://www.ttlsa.com/nginx/nginx-cache-priority/ <file_sep>/_posts/2012-06-25-object-equals-equals-nil-or-nil-equals-equals-object.markdown --- layout: post title: "object == nil or nil == object" date: 2012-06-25 18:44 --- 在 Objective-C 中拿到一个对象后检查对象是否为空,一般有两种写法 一: ``` if (object == nil) { //... } ``` 二: ``` if (nil == object) { //... } ``` 这两种写法其实没有任何区别,从代码的可读性上来说第一种 `object == nil` 方式会好一点。但是推荐用第二种 `nil == object` 方式,最大的好处就是如果由于笔误 `==` 写成了 `=`,编译器会直接报错处理。而 `object = nil` 不会报错,一旦笔误写成了 `object = nil` 是很难 debug 查找问题。 via [object == nil or nil == object to check whether an object is nil?][1] [1]:http://stackoverflow.com/q/11186715/380774 <file_sep>/_posts/2016-03-30-monthly-review-1603.markdown --- layout: post title: Monthly Review 2016-03 date: 2016-03-30 17:53:28 +0800 --- 1. Web 前端依然在面试,有两个多月了,这期间有一个技术好适合创业团队的小伙,可惜拒了我们。 2. 提交几个新应用到 App Store,被拒,再提,再拒,拉锯战。 3. 技术上尝试用 PhantomJS 对 AJAX 动态网站做 SEO 优化,目前看是个不错的思路,搜索有收录。 4. 即便是简装,已经累的不要不要,全部装修的话估计要脱层皮。 5. 周末去宜家几趟,买东西是一方面,主要是看他们的家居搭配,尤其是一些新奇玩意。 6. 很多时候是因为不知道某个东西/方案的存在,才不知道怎么做,当你知道后,问题不要太简单。 7. 好在现在有网络,我们这行的一大优势就是会搜索,可以相对快速的从网络获取知识信息。 <file_sep>/_posts/2012-09-11-uitableview-optimization-notes.markdown --- layout: post title: "UITableView 性能优化笔记" date: 2012-09-11 11:48 --- Hacking Week 技术总结最后一篇,记一下 UITableView 性能优化需要注意和改进的地方。 1. 网络图片异步加载,SDWebImage。 1. 文字直接 drawInRect/drawAtPoint 绘制,参考 ABTableViewCell,[AdvancedTableViewCells][1]。 1. 本地图片也可以直接绘制,或者用 CALayer 来添加显示。 1. cell 重用机制。 1. cell 内容尽量避免透明效果。 1. 如非必要,减少 reloadData 全部 cell,只 reloadRowsAtIndexPaths。 1. 如果 cell 是动态行高,计算出高度后缓存。tableView 会在加载的时候把全部 cell 的高度通过 `heightForRowAtIndexPath:` 都计算出来,即使 cell 还没有展示。 1. 如果 cell content 的展示位置也不固定,第一次计算后也要缓存。 1. cell 高度固定的话直接用 `cell.rowHeight` 设置高度,不要再实现 `tableView:heightForRowAtIndexPath:` delegate. 1. cell content 的解析操作(尤其是复杂的解析)异步进行+预执行,解析结果要缓存。 1. 可以预先加载需要的网络资源(图片等),SDWebImagePrefetcher. > There are performance implications to using `tableView:heightForRowAtIndexPath:` instead of the `rowHeight` property. Every time a table view is displayed, it calls `tableView:heightForRowAtIndexPath:` on the delegate for each of its rows, which can result in a significant performance problem with table views having a large number of rows (approximately 1000 or more). via [Apple Document][2] [1]:https://developer.apple.com/library/ios/#samplecode/AdvancedTableViewCells/Introduction/Intro.html [2]:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDelegate_Protocol/Reference/Reference.html#//apple_ref/doc/uid/TP40006942-CH3-SW25 <file_sep>/_posts/2010-01-13-bye.markdown --- layout: post title: "Bye" --- > We recognize that this may well mean having to shut down Google.cn, and potentially our offices in China. via [A new approach to China](http://googleblog.blogspot.com/2010/01/new-approach-to-china.html). Now,work diligently, make money diligently,then Go. <file_sep>/_posts/2011-08-11-quote-0811.markdown --- layout: post title: "Quote" --- > 不要做让自己讨厌自己的事情。 <file_sep>/_posts/2019-04-23-mysql-prefix-index.markdown --- layout: post title: MySQL Prefix Index date: 2019-04-23 16:13:14 +0800 --- ``` CREATE TABLE `t1` ( `bundle` varchar(300) DEFAULT '' COMMENT 'pkg name', `domain` varchar(200) DEFAULT '', UNIQUE KEY `idx_bundle_domain` (`bundle`(100),`domain`(100)) ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4; ``` 关键部分 `bundle(100)` 来解决组合索引可能会出现的 `Specified key was too long; max key length is 767 bytes` 错误。<file_sep>/_posts/2022-11-02-ssh-config-in-macos-ventura.markdown --- layout: post title: SSH config in macOS Ventura date: 2022-11-02 18:03:11 +0800 --- macOS Ventura changed SSH algorithm, you need to update your SSH config file `~/.ssh/config` to make it work. ```bash Host * UseKeychain yes IdentitiesOnly yes HostkeyAlgorithms +ssh-rsa PubkeyAcceptedAlgorithms +ssh-rsa ``` <file_sep>/_posts/2013-07-23-use-launch-arguments-to-test-localizations.markdown --- layout: post title: "通过 Xcode 启动参数测试 App 本地化" date: 2013-07-23 18:07 --- 以往测试 App 本地化就是通过切换系统语言来做,甚是麻烦,其实可以用 Xcode 启动参数强制 App 用指定语言: ``` -AppleLanguages (en) ``` * `-` 开头,Applelanguages 后有一空格,语言放在括号内。 * 语言可以用全名或简写均可,比如 English == en,不区分大小写。 * 必须通过 Xcode 启动才有效,模拟器和真机设备都支持。 添加参数方法: `Product` > `Scheme` > `Edit Scheme` (or ⌘<), Arguments Passed On Launch 下添加。可以添加多个方便切换: ![2013-07-22-002.png](https://i.loli.net/2019/11/11/axlXUdCYoD71pLO.png) via [Using Launch Arguments to Test Localizations](http://useyourloaf.com/blog/2013/07/22/using-launch-arguments-to-test-localizations.html) <file_sep>/_posts/2010-04-29-find-in-files-within-vim.markdown --- layout: post title: "Vim 多文件查询" --- 多文件查询是指在多个文件内查询同一字段。命令 **:vimgrep**: > `:vim[grep][!] /{pattern}/[g][j] {file}` For example,递归当前目录及子目录,在所有 py 文件中查询 main,\\C 区分大小写,\\c 不区分大小写。 > `:vimgrep /\Cmain/ **/*.py` These commands all fill a list with the results of their search. "grep" and "vimgrep" fill the "quickfix list", which can be opened with **:cw** or **:copen**, and is a list shared between ALL windows.via [Find in files within Vim]( http://vim.wikia.com/wiki/Find_in_files_within_Vim ) <file_sep>/_posts/2012-08-12-what-i-have-learned-from-cheddar-for-ios.markdown --- layout: post title: "What I have learned from Cheddar for iOS" date: 2012-08-12 12:07 --- 1. Code Style. 1. DRY,整理适合自己的代码库(SSToolkit)。 1. `application:didFinishLaunchingWithOptions:` 里尽量少操作,减少 launch 时间。只做界面展示工作,数据层用 dispatch_async 异步操作。 1. 多用 `[image stretchableImageWithLeftCapWidth:5 topCapHeight:0]` 图片拉伸,减小 App size。效果上并没有缺失很多。很多效果都可以用代码实现,不一定非得贴图。 1. 数据层封装不同的对象,方便各种调用。直接用 dict 传来传去不够清晰。 1. Core Data 和 UIViewController 可以很好的结合,深度封装后的确很方便,参见 SSManagedViewController = UIViewController+SSManagedObject(NSManagedObject),SSDataKit。但这样感觉 ViewController 很沉重,也可能是因为我对 Core Data 不熟悉,以后有机会加深一下 CD 的学习使用。 1. KVO 是个好东西。 1. 定义一些内部 scheme 来做界面跳转,`x-cheddar-tag`. 1. `UIColor+CheddariOSAdditions.h`-`cheddarTextColor`,定义整体风格配色,很方便使用。`UIFont+CheddariOSAdditions.h` 同理。 1. `cellHeightForText:` 用 `dispatch_once_t` 生成一个单例 label,然后 `sizeThatFits:` 计算。 1. `prepareForReuse` 释放数据。 1. `CDKHTTPClient` 学习 AFN 的好例子。单实例,用 block 封装接口。Block is better than delegate, simple, clear and powerful. <file_sep>/_posts/2015-04-01-cache-pattern.markdown --- layout: post title: Cache Pattern date: 2015-04-01 10:35:19 +0800 --- > There are only two hard things in Computer Science: cache invalidation and naming things. – <NAME> ## Terminologies - **Cache Hit**: available in cache - **Cache Miss**: not available in cache - **Cache Invalidation**: invalidating and removing data from cache - **Cache Eviction**: removing old entries(base on age and frequency of use), and make space for new entries ## Where the Cache is located? - Server's Disk: enough space, but slow - Server's Memory: much faster, but limited space and costlier - Client's Disk: scalability, more storage, fewer network transers, but slow, outdated - Client's Memory: faster than disk, but outdated ## How to cache ### Read-Through/Write-Through App-Cache-DB 结构,App 不直接访问 DB,由缓存间接操作。读的时候先从缓存取数据,有就直接返回,没有的话由缓存负责从 DB 读取并更新到 Cache,然后返回数据。写的时候先写缓存,然后由缓存负责更新到 DB,只有 DB 更新完成才算写成功,返回操作结果。 - 好处是缓存数据更新及时,适合读多写少,缺点就是写操作慢 - 因为 DB 是通过 cache 更新,就不需要 Cache Invalidation - 建议主动触发 warmup 来提高缓存效率 ![image](https://user-images.githubusercontent.com/345274/197996523-c942e62c-ed3a-4c08-a3b3-672b8268e082.png) ![image](https://user-images.githubusercontent.com/345274/197996817-d943619f-4ea6-4f31-906e-8de77586a859.png) ### Write-Around 跳过缓存直接写数据到 DB。相比 Write-Through 避免了写数据时候对缓存数据的冲洗,缺点是缓存数据不能及时更新。 ### Write-Back/Write-Behind 数据写到缓存后操作立即返回结果,然后缓存系统延时+异步的将数据更新到 DB,一般配合队列处理。这种写操作是最快的,也能避免大量写数据对 DB 的压力。缺点是数据一致性的复杂度增加。 ![image](https://user-images.githubusercontent.com/345274/197997286-a6afe45b-75b2-4a34-abd1-c64f2bef2192.png) ### Cache-Aside App 读的时候检查数据是否在缓存中,有就返回,没有的话 App 直接读 DB 返回,同时将数据写入缓存。写操作的时候直接写入 DB,如果缓存中有对应数据,将缓存设置无效或删除,如果数据读取频繁的话也可以直接更新缓存中的数据,保证数据一致性。这种模式更多是有 App 进行数据检查,缓存只做存储。 ![cache-aside](https://user-images.githubusercontent.com/345274/197996429-101885b9-ba8e-4bf9-b169-2ad5f55fb84f.png) 一些参考: * https://msdn.microsoft.com/en-us/library/dn589799.aspx * http://www.computerweekly.com/feature/Write-through-write-around-write-back-Cache-explained * http://www.infoq.com/cn/articles/write-behind-caching/ * http://docs.oracle.com/cd/E15357_01/coh.360/e15723/cache_rtwtwbra.htm#COHDG5177 * https://www.v2ex.com/t/180474 <file_sep>/_posts/2010-04-01-busy-fool-day.markdown --- layout: post title: "忙碌的愚人节" --- 今天我开始培训工作,碰巧愚人节,够巧的。 一上午就在帮他们整理资料,下午网络布线,累死个人了,真比做项目都累。 挑战很大,要加把劲,加油加油!~ <file_sep>/_posts/2014-08-31-monthly-review-1408.markdown --- layout: post title: "Monthly Review 2014-08" date: 2014-08-31 15:27:08 +0800 --- 工作上把一个去年就想过的设计码成并上线,目前状况良好,说明当初的设计思路是没有问题的。之所以拖了这么久是因为项目时间比较紧(是我比较懒),最主要的原因是一直没有下狠心去重构。这部分功能运行正常,可能在某些情况下会有性能问题,但绝大数情况下完全不用担心性能,而新的设计和之前的实现不同,作为一个线上服务首先要考虑的是服务的稳定性,其次是新设计的兼容性,所以一直拖到现在。现在回头看开发要有点魄力,有时候自己过于小心了。 服务端开发的架构设计很重要,前期要多做思考工作,不能上来就去代码,要考虑可能出现的功能需求,思考性能瓶颈,有了好的设计再去代码效率也会更好。 生活上给自己买了一份商业保险,30年寿险,是自己对家庭的责任。核保的时候因为 BMI 超标,每年保费多了 150,体重又一次打击了我,减肥正式开始,从 19 号开始每天晚上锻炼,根据 Nike+ Running 统计已经 66 公里,继续坚持。 由于工作原因老婆打算提前回北京,这几天抽空一直在看房子,打算整租一套,不再合租,不管六六来不来北京。以前老感觉整租花钱多,将就一下也就过了,不要太过于奢侈。现在看对我们自己太辛苦了,自己都过不好拿什么承担其他责任。老婆回去这两三个月,每天也不做饭,周末都在单间里窝着,就算出去转转也是一个人,没人说话,行尸走肉一般,再这样下去怀疑自己就要抑郁症了。 要好好的对待自己,好好生活,好好工作。 <file_sep>/_posts/2010-04-21-0421-yushu.markdown --- layout: post title: "玉树不倒" --- > 国务院决定,为表达全国各族人民对青海玉树地震遇难同胞的深切哀悼,2010年4月21日举行全国哀悼活动,全国和驻外使领馆下半旗志哀,停止公共娱乐活动。 为玉树人民默哀。玉树不倒,青海常青。 <file_sep>/_posts/2015-06-28-angular-material.markdown --- layout: post title: Angular Material date: 2015-06-28 17:31:15 +0800 --- 又尝试了点新东西,[Angular Material][1],写了一个的管理后台。 1. Angular Material 是基于 Flexbox 做布局,在此基础上添加了 `layout` HTML 属性,写起来非常清爽:`layout="row"` 横向,`layout="column"` 纵向。 2. build-in directives 很丰富,一整套界面写下来,目前最欠缺一个日期时间选择器。 4. [material-start][2] 快速上手包,完整的 Angular Material 实例。 5. 迭代更新很快,相对来说文档更新差一步,有时候需要看 demo 源码。 3. 自带主题支持。 4. 体积较大,min css+js 将近 400K。 [1]:https://material.angularjs.org/ [2]:https://github.com/angular/material-start<file_sep>/_posts/2008-12-31-my-2008.markdown --- layout: post title: "我的2008" --- 现在是09年1月17日22:13,写下这个标题是在08年的最后一天,半个多月都过去了,补上。其实最不擅长写这种总结性质的东西,高中时候的个人学期总结之类的东西都是七拼八凑的给弄上就中。我的2008年,现在回过头看看,算是大学四年过得最为充实的吧,给自己找了点事情去做,虽然做的不大好,准确说,很不好,不过至少自己尝试了,努力了,我觉得就行。 08年1月:郑州,丫头。寒假放假,跟丫头的真正意义上的第一次见面。之前有过两次见面,不过都是匆匆忙忙的,而且那时候,不属于我们的见面,而这次,是我们的世界。还记得从郑州火车站出来,大雪,站在门口等待着丫头,一丝的紧张。当丫头出现的时候,反而很释然的感觉,丫头也说没有那种紧张,很亲切的感觉,嘿嘿,我喜欢这种感觉,平淡中的你,属于我,幸福中的快乐,和你在一起。 08年2月:春节,博客。大年初一,我们几个小学同学聚了聚,有的八九年都没见了,人这一辈子能有几个八九年,很开心,我们一起去爬山,照相,围着火堆回忆小学时候课堂上的闹剧,回想我的外号,你的糗事。时间在走着,我们却在淡忘着小时候的童真乐趣,不应该,赶紧的把它抓住。今年的年初一,我过得很开心,甚至照片上都是那么的帅气十足,哦哈哈。2月底,回学校,折腾着弄这个博客,不知道怎么,我就是想自己一个人动手把它做出来,看教程,架设本地服务器环境,买空间,设置域名,DNS这类名词我知道它的意思,可是让我拿出来折腾,还是不够,我就这么瞎子过河的,在2月的最后一天的11点多,我在WP后台写了这几个字:航航的名字。那一刻,我真的很兴奋,这是我一个起点,我会继续下去。 08年3月4月:幸福,忙碌。想丫头,想着丫头的瞎忙,要不咋说恋爱中的人都没脑子,你会发觉时间是过得如此的慢,慢的老想着把日期改上两月,赶紧回去;时间也会过得那么快,一晃功夫的电话粥就俩小时,呼呼。那一段继续瞎折腾的写博客,折腾WP主题,折腾WP插件,折腾其实也是一种享受,因为你永远不知道你会折腾出来什么玩意。 08年5月:地震。教科书中学习的地理知识,电视电影中的灾难片环境,如此之近的发生在我们的身边,如此之大的威力,让你一下子知道,其实,你不过尔尔,在那块石头面前,你啥都不是,脆生生的,不堪一击。地震,让我们走的更近,抱的更紧。地震,也让我们知道活着是多么的珍贵。 08年6月:iPhone,Vista。3G iPhone横空出世,那一段我是天天上网看iPhone的消息,怎么买,多少钱买,怎么刷机,怎么玩,有什么好玩的APP,泡了好一阵子论坛,幻想着自己啥时候买一个去,哎,可惜就是没钱,连系统都只好用盗版的,Vista,六月份升级到这个十分尴尬地位的系统,细节不错但是大方面不好,鸡肋一般,不过还算是个肉比较肥的鸡肋,还能吃,也就吃了下去。 08年7月:徘徊。其实徘徊了好久了,考研,还是就业,真的是个问题。考研,自己以前的一个心愿,就业,更为现实一点,这种时候这种挣扎很让人烦。7月19号,21岁生日,那天的酒是我们最后的青春酒,那天的兄弟聚会,我们都很失落,面对着这个社会,我们其实都还没有准备好。 08年8月:奥运会。七年前的那天晚上,我在电视前兴奋北京申奥,七年后,我发现不过如此,感觉是那么的虚假,在我和它之间有一道无形的墙,那边的世界很精彩,可是你却感觉是超级女声一般的秀,也许这就是现实吧,跟我们的梦想都是有那么一段差距。 08年9月:闷。自习室的苦闷,坐不下去,强迫自己每天都去,可是心却不在。不知道自己在想什么,人生就是这么的让人烦,你追寻的是你想要的吗?你的追寻能得到你想要的吗?你得到的是你想要的吗?问题,都是问题。无底洞一般,进去就出不来。 08年10月11月:回家,坚持。闷的慌,趁国庆假期,回了一趟郑州,在丫头那待了三天,不去看书,不去想那些无聊的问题,我知道,我在逃避,可是,我没有放弃。坚持着自习室,坚持着复习,尽管还是很苦闷,我说服自己强迫自己走下去。 08年12月:鸟儿。每个人都有自己的苦闷,我在着挣扎着考研,那边有人在烦保研还是保博,就这么不公平。 08年,大学最后一年,我在挣扎着我的未来,我的未来在折腾我,尽力的去做一些事情,只为不让自己后悔,人生的思索会让我们认清楚自己,也可能让我们迷失方向,感到无所适从,我们能做的也只有是把握住现在那一点点机会一点点时间,去做了,去做好,就够了。其实幸福挺简单的,半夜肚子饿了的时候,口袋里有钱去买一碗串串香,跟喜欢的人一起吃的满头汗,笑着睡去,笑着醒来,就这。 <file_sep>/_posts/2019-02-21-to-appwill.markdown --- layout: post title: To Appwill date: 2019-02-21 10:09:37 +0800 --- 昨天梦到了 AW。 不是现在的 AW,是几年前的,很多人都还在,一起讨论某个产品。 那时的 AW 很小,但有凝聚力,有战斗力,很 nice。后来有好几个人都跟我说过,那时的 AW 是大家最棒的经历。 什么时候是个转折呢?大概就是 15年吧,Z 移民澳洲后产品上一直没有太好的 Lead,之后日活下降收入走低,产品开始往下走。16年后 L 对现有产品兴趣不大,改组内部项目制,效果也不好。 再后来,17年初 L 组建新公司,Z&Z 言明不可从原公司挖人,结果就是一起拼搏走过来的人,跟着已经死去的旧产品沉没,之后相继离职,包括我。 我个人对 AW 的感情很深,但说实话,最后创始人分家+限制挖人,让我心里很不舒服,本身我们还可以一起用彼此都信任的方式做事,结果却似有欺骗,维护着注定要死去的产品,费劲心力,却无成长。 R.I.P.<file_sep>/_posts/2018-12-25-homebrew-speedup.markdown --- layout: post title: Homebrew Speedup date: 2018-12-25 14:49:03 +0800 --- 通过修改 Homebrew git repo 来加速: ```bash cd "$(brew --repo)" git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git // 中科大 git remote set-url origin https://mirrors.ustc.edu.cn/brew.git cd "$(brew --repo)/Library/Taps/homebrew/homebrew-core" git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git // 中科大 git remote set-url origin https://mirrors.ustc.edu.cn/homebrew-core.git // homebrew-cask cd "$(brew --repo)/Library/Taps/homebrew/homebrew-cask" git remote set-url origin https://mirrors.ustc.edu.cn/homebrew-cask.git // homebrew-bottles export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles // export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.ustc.edu.cn/homebrew-bottles // export HOMEBREW_BOTTLE_DOMAIN=http://7xkcej.dl1.z0.glb.clouddn.com ``` 重置为官方源: ```bash cd "$(brew --repo)" git remote set-url origin https://github.com/Homebrew/brew.git cd "$(brew --repo)/Library/Taps/homebrew/homebrew-core" git remote set-url origin https://github.com/Homebrew/homebrew-core cd "$(brew --repo)/Library/Taps/homebrew/homebrew-cask" git remote set-url origin https://github.com/Homebrew/homebrew-cask ``` <file_sep>/_posts/2008-07-02-the-movie-seven-days.markdown --- layout: post title: "看电影:《七天》" --- 《七天》,韩国电影,Seven Days,该怎么分类呢,悬疑片加犯罪片。嗯,剧情非常紧张,情节非常的紧,两个多小时看完后我的第一感觉居然是好累啊这个电影看得我。。。 当母爱碰上高智商犯罪,看完之后我在豆瓣上给电影写的一句话。应该说母爱是电影里最让人心碎的感情了,女律师的小孩被绑票,受人要挟时候表现出来的冷静,坚强,应该是坚韧,是对母爱力量最好的诠释。 电影里还有一份母爱,似乎是变了味道的母爱。失去爱女的韩夫人,当她知道自己女儿滥交、吸毒的时候,说:这无所谓。她有所谓的是女儿已经不再人世了。失去女儿的痛苦,让这个母亲开始了她的高智商犯罪,可能是我的迟钝吧,一直到最后最后结局时候才明白,她要亲手杀了杀害女儿的凶手,所以,费劲心机的把凶手从监狱弄出来,再亲手杀了他。这也是母爱,虽然让人心痛的母爱犯罪。 女人是水。但一旦遇到困难,女人就是结了冰的水。 <file_sep>/_posts/2008-05-19-mourning-day.markdown --- layout: post title: "19-21,全国哀悼三天" --- 国 务 院 公 告 > 为表达全国各族人民对四川汶川大地震遇难同胞的深切哀悼,国务院决定,2008年5月19日至21日为全国哀悼日。在此期间,全国和各驻外机构下半旗志哀,停止公共娱乐活动,外交部和我国驻外使领馆设立吊唁簿。5月19日14时28分起,全国人民默哀3分钟,届时汽车、火车、舰船鸣笛,防空警报鸣响。 早上六点多爬起来去升旗仪式,有差不多三年多没有过升旗仪式了,大学以来的第一次,却是因为地震,酸溜溜的。升旗,降半旗致哀,默哀,为那些地震区的人们。 让我们永远铭记这一刻,愿逝者安息,生者坚强。 <file_sep>/_posts/2013-06-28-perform-block-after-delay.markdown --- layout: post title: "Perform block after delay" date: 2013-06-28 09:31 --- ```objc dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC), dispatch_get_current_queue(), block); ``` 可以封装一个 NSObject Category 来方便使用。 via [Tutorial: Run a Block of Code After a Delay](http://www.brianjcoleman.com/tutorial-run-a-block-of-code-after-a-delay/) <file_sep>/_posts/2014-03-22-money.markdown --- layout: post title: "Money" date: 2014-03-22 23:29:20 +0800 --- > 没钱,意味着失去了选择的能力。 > 缺少的不仅仅是选择的权利,还有为人生下赌注的资本。 > 你没钱,你放弃的成本就更高。 转两句从[知乎][1]看到的,然后提醒自己: > Money is like gasoline during a road trip. You don’t want to run out of gas on your trip, but you’re not doing a tour of gas stations. You have to pay attention to money, but it shouldn’t be about the money. -- <NAME> [1]:http://www.zhihu.com/question/22233971 <file_sep>/_posts/2008-09-27-pagerank-3.markdown --- layout: post title: "咱也有PR了" --- 是PR,不是RP,RP咱一直都有的。 PR,Google搜索排名的一个算法,具体是啥不是很懂,引用一段: > PR值全称为PageRank,是Google排名运算法则(排名公式)的一部分,是Google对网页重要性的评估,是Google用来衡量一个网站的好坏的唯一标准。PageRank(网页级别)是Google用于评测一个网页“重要性”的一种方法。在揉合了诸如Title标识和 Keywords标识等所有其它因素之后,Google通过PageRank来调整结果,使那些更具“重要性”的网页在搜索结果中另网站排名获得提升,从而提高搜索结果的相关性和质量。 PR值的级别从0到10级,10级为满分。 今天Google PR再次更新,查了一下,首页PR直接从0上升到3,不错不错,半年时间升到3说实话很慢,不过已经知足了,感谢Google满足自己的虚荣心,哈哈! Update:原来单页面也有PR值计算的,《我的Firefox扩展分享》PR居然是6!写这篇Fx的东西给我的惊喜可够多的,哈哈。 <file_sep>/_posts/2015-11-07-ngx_lua-vs-go.markdown --- layout: post title: ngx_lua vs Go date: 2015-11-07 21:19:50 +0800 --- > 由于移动互联网的火爆,前后端分离的开发模式越来越流行:后端通过 API 提供数据,前端 native or web 做数据展示交互。那么谁能把吐数据这件事做的又快又好,谁就比较适合做服务端应用开发。 [2011年][1]我们开始用 OpenResty(ngx_lua) 作为服务端应用解决方案,最近一个项目换用 Go,简单做个对比: ngx_lua: 1. 快,和 nginx 简直绝配,尤其是分执行阶段进行操作 1. 同步方式写异步非阻塞,相比 Node.js 回调,代码体验好 1. 但还不够好,欠缺在开发效率,社区丰富程度,我们这些使用者也有责任 1. Lua 语言非常棒,简单高效,但相较于其他语言这些年进步太慢 1. LuaJIT 让性能爆表,但只兼容到 Lua 5.1,见过很多因为用错版本而引发错误。原开发者不再继续维护,转有 CloudFlare 接手,后续有一定不确定性 [via][2] 1. nginScript 现在和 ngx_lua 完全没有可比性,未来很难说,毕竟有官方支持,加上 js 一统江湖的趋势 1. nginx 本身主要处理 HTTP 业务,适用范围相对有限,不过现在有了 TCP Proxy,后面想象力也会很大。 Go: 1. 静态语言 1. 学院派看 Go 语言的设计有很多缺陷,但从工程的角度,简单,规范,标准库丰富 1. 开发效率高,自测性能在 ngx_lua 70% 左右,大多数情况下完全够用 1. goroutine + channel,同步方式写异步 1. 方便的工具链,go fmt/doc/test/pprof 1. 跨平台编译,单二进制文件,部署方便 1. 虽然有 `go get`,但一开始没有原生包管理是很大的失败,现在社区已经分裂出 godep/govender/nut/gb/glide/gopkg.in 等等 [1]:https://github.com/appwilldev/moochine [2]:http://www.freelists.org/post/luajit/Looking-for-new-LuaJIT-maintainers <file_sep>/_posts/2013-07-20-vim-open-multiple-files.markdown --- layout: post title: "Vim open multiple files" date: 2013-07-20 10:56 --- ``` vim -p file1 file2 ... vim -o file1 file2 ... vim -O file1 file2 ... ``` 其中 `-p` 是在 tab 打开,`-o` 是在上下 split 打开,`-O` 是在左右横向 split 打开。via [Vim open multiple files][1]. [coderwall][2] 有很多小技巧,包括编程语言、工具、系统等等,可以多多关注。 [1]:https://coderwall.com/p/n1abyq [2]:https://coderwall.com/ <file_sep>/_posts/2012-03-07-track-ios-device-model-with-google-analytics-custom-variables.markdown --- layout: post title: "Track iOS Device Model with Google Analytics Custom Variables" date: 2012-03-07 16:58 --- Add [Google Analytics SDK for iOS ][1] to app project first. ``` #import <sys/utsname.h> - (NSString*)deviceModel { struct utsname systemInfo; uname(&systemInfo); return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding]; } NSString *model = [self deviceModel]; // model = @"iPhone3,1", as iPhone 4. [[GANTracker sharedTracker] setCustomVariableAtIndex:1 //range from 1-5, not be re-used. name:@"DeviceModel" value:model scope:kGANSessionScope withError:NULL]; NSString *sysVersion = [[UIDevice currentDevice] systemVersion]; // sysVersion = @"5.0.1" [[GANTracker sharedTracker] setCustomVariableAtIndex:2 name:@"SystemVersion" value:sysVersion scope:kGANSessionScope withError:NULL]; ``` Then, you can get the report on Google Analytics Audience / Demographics / Custom Variables. [1]:https://code.google.com/apis/analytics/docs/mobile/ios.html <file_sep>/_posts/2018-01-12-nginx-limit-req.markdown --- layout: post title: Nginx limit_req date: 2018-01-12 22:07:10 +0800 --- ```nginx limit_req_zone $binary_remote_addr zone=req_zone:10m rate=10r/s; location /api { limit_req zone=req_zone burst=10 nodelay; } ``` rate 限定单位时间内的请求数,burst 限定缓冲队列长度。上面配置是用 client IP 做请求限制,单 IP 限制每秒钟最多十个请求,也就是每 100ms 只能有一个请求,如果 100ms 内有超过一个的请求到达,会被放进 buffer 队列,大小由 burst 指定,所以 100ms 内的第 11 个请求会被 503。 1. `limit_req zone=req_zone;` - 严格按照 rate 来处理请求 - 超过 rate 处理能力的直接 drop - 收到的请求无延时 2. `limit_req zone=req_zone burst=5;` - 按照 rate 设置处理请求 - 设置一个大小为 5 的缓冲队列,在缓冲队列中的请求会被慢慢处理 - 超出 burst+rate 的请求会被直接 drop - 收到的请求有延时 3. `limit_req zone=req_zone burst=5 nodelay;` - 按照 rate 设置处理请求 - 设置一个大小为 5 的缓冲队列 - 峰值处理能力是 burst+rate,超出处理能力的请求被直接 drop - 完成峰值请求后,缓冲队列不能再放入请求。假如 `rate=10r/s`, 峰值后这段时间没有请求过来,则每 0.01s 缓冲队列恢复一个缓冲请求的能力,直到恢复能缓冲 5 个请求 - 收到的请求无延时 - [Rate Limiting with NGINX and NGINX Plus](https://www.nginx.com/blog/rate-limiting-nginx/) - [Nginx下limit_req模块burst参数超详细解析](https://blog.csdn.net/hellow__world/article/details/78658041) - [resty.limit.req](https://groups.google.com/d/msg/openresty/VY-LdQaEyDA/skf86NDHAAAJ) <file_sep>/_posts/2010-04-21-lesson-of-fannt2r.markdown --- layout: post title: "教训" --- 由于校内更改了状态发布的代码,所以之前的 Fannt2r 失效。今天修改时候由于一个细节问题浪费了不少时间: 1. 小心中间临时变量名。由于设置了一个函数变量 cookie,而中间又有 cookie 临时缓存,之前都是用 cookie 一个变量,导致变量的值被篡改。所以,中间临时变量名字不要跟函数变量一样,改为 cookie_buf; 2. 细心耐心的去调试程序。 PS:Python 真的很有爱。 <file_sep>/_posts/2013-12-25-corefoundation-bridge-nsobject.markdown --- layout: post title: "CoreFoundation 和 NSObject 在 ARC 下的转换" date: 2013-12-25 09:00 --- CoreFoundation 有自己的引用计数处理方法,在 CF 下如果生成对象的方法中有 create、retain、copy 就表示 CF 会用自己的方式对引用计数加一,这就需要在结束的时候用 `CFRelease()` 释放。而 ARC 目前只对 NSObject 对象有自动的引用计数处理,所以在 ARC 如果有 CoreFoundation 对象和 NSObject 对象转换就需要用 `__bridge`, `__bridge_transfer`, `__bridge_retained` 进行引用计数管理的转换。 * `__bridge` 表示 CF 对象和 NSObject 的引用计数平衡,无需转换管理权。适用于用不包含 create、retain、copy 的方法获取的 CF 对象转换为 NSObject。 * `__bridge_transfer` 表示将 CF 对象的引用计数管理员转移到 NSObject 由 ARC 管理,无需再用 `CFRelease()` 释放。 * `__bridge_retained` 表示将 NSObject 对象的引用计数管理权转移到 CF 管理,并且引用计数加一,那么在 CF 层就需要用 `CFRelease()` 释放该对象。 SDK 有两个宏 `CFBridgingRetain`, `CFBridgingRelease` 可以直接用,要注意 `CFBridgingRetain` 后要用 `CFRelease()` 释放。 ``` objc // After using a CFBridgingRetain on an NSObject, the caller must take responsibility for calling CFRelease at an appropriate time. NS_INLINE CF_RETURNS_RETAINED CFTypeRef CFBridgingRetain(id X) { return (__bridge_retained CFTypeRef)X; } NS_INLINE id CFBridgingRelease(CFTypeRef CF_CONSUMED X) { return (__bridge_transfer id)X; } ``` 参考 [ARC工程转换和开发注意事项](http://www.hrchen.com/2013/07/arc-transfer-and-notice/) <file_sep>/_posts/2009-09-09-0909.markdown --- layout: post title: "九月九" --- 20090909,再加上 09:09:09 这个时间,一辈子也就能遇到这么一回这么多 9 的日子,九九久久,这一天不知道有多少人领证、结婚,祝福一下。本来想掐着点给丫头发个短信,结果一不小心给错过了几分钟。。。不过心意还是有的嘛,丫头,俺可耐烦你。 ![](http://www.google.com/logos/090909.gif) <file_sep>/_posts/2010-07-16-yes-i-can.markdown --- layout: post title: "Yes I Can!" --- 接下来的工作学习方向: 1. iPhone/Android 开发。 2. Python/PHP Web 开发。 3. Web 前端尤其是 JavaScript 的学习。 谨记: + 多沟通,一个小时解决不了的问题就问,节省时间,提高效率。 + 做事有计划。 + 多写文档。 <file_sep>/_posts/2017-01-19-2016.markdown --- layout: post title: '2016' date: 2017-01-19 21:35:02 +0800 --- 工作,劳而无功,即是失败。 组建团队,目前技术团队共有的问题是能出东西,但是技术边界明显,对于没有接触多的领域缺少思路。... 开发是和业务紧密结合的,过于脱离业务做技术不切实际,作为技术负责人是不及格的。两个设计师的招聘比较费时,但反而是今年最好的招人,也是对技术团队的反思,设计师的招聘以解决问题为主,歪打正着的效果很好。 运营工作做的很差,没有好的想法,一切照旧的做法消磨着大家的积极性和耐心,也影响了整个团队的氛围,好在 Q4 新应用的开始让大家看到一些希望,其实大家都很愿意花心思做运营,只不过现状让大家觉得做与不做并没有太多区别,作为负责人没能让大家看到项目的前景和希望,是失职。 商务成绩是持续走低,日活的走低对商务工作的影响很大,下半年商务转型主做 CPA,每单的压力减小,但对商务整体成绩影响依然很大,究其原因还是产品的走低。 产品项目上,前半年纠结于苹果的审核,自己是做好了持久战的准备,但没有给团队其他成员对产品的信心,现实也是一次次的打击着大家,然后连锁反应的影响运营/商务。Q4 用新技术方案做给大家带来不少信心,但还是有点晚,应该在上半年就实施的。讽刺的是我一直认为自己在技术上有不错的敏感度,真遇到实际情况却太多的犹豫和顾虑,也是技术不过关。 这一年再一次的发现自己的瓶颈,对运营的不擅长,对产品的不敏感,长时间的产品低谷自己能扛住却不会给团队信心,毕竟没有成绩一切都很无力。另一方面,能正确认识自己的不完美也是给自己减压,专注于那些可以做的工作,而不是想把一切都完美解决。 ---- 生活 装修,搬家,接六六来北京,第一次在北京过年,每一步看似幸福,背后都很艰辛,好在老婆的耐心,大度,坚持,努力的支撑着我们的生活,希望来年我们能顺利一点,健康一点,开心一点,幸福一点。 <file_sep>/_posts/2010-06-11-2010-fifa-world-cup.markdown --- layout: post title: "2010 FIFA World Cup South Africa" --- ![2010 FIFA World Cup Aouth Africa](http://www.google.co.za/logos/d4g_worldcup10_za-hp.jpg) 世界杯来啦。看好西班牙。 <file_sep>/_posts/2013-06-22-thoughts.markdown --- layout: post title: "thoughts" date: 2013-06-22 15:47 --- > 搭功夫省钱,花钱省时间。 生活中的事无非这两种情况,所以遇见事情不要慌,总有解决办法的。 <file_sep>/_posts/2009-06-10-happy-birthday-to-little-sister.markdown --- layout: post title: "妹今天生日" --- 今天是妹的生日,妈生日后一天,小姑娘又长大了一岁! 妹10岁了,跟我整好差生肖一轮,都是属兔子的。妹比我小时候要聪明,比我会说话,比我会耍赖,不认生,亲戚们都说是个假小子。因为我出来上学,家里就她一个小的,爸妈娇惯她,小姑娘玩起来更是虎虎生风,啥都不怕。刚学会骑自行车就天天一放学骑车满村子转。这点真比我强,话说我12岁才学会骑车的。 小姑娘小的时候超可爱,嘴又利索,不停的说呀说呀,老逗人了。今年寒假开学我走之前,小姑娘用刚学会的书信体给我写了封信,偷偷放我电脑包里。当时看见老开心了,小姑娘长大了,懂事了。 希望小姑娘开开心心的长大,哥老爱你了。 <file_sep>/_posts/2009-04-30-51-go-home.markdown --- layout: post title: "五一回家" --- 五一放假,其实对于现在的我来说,放不放假也没啥区别,天天都是假期。当然,这次五一假期不同于其他假期,很不同。 CHAOFEI 当兵三年了,去年升了士官,今年五一有一个月的探亲假,三年了,回来看看,兄弟们聚聚,所以大家说定五一都赶回去,毕竟这两三年聚会都是七零八落的凑不齐。不用说,回去聚会又要一顿酒,老规矩了。不过现在都大了,也都知道自己身上的责任了,大家伙喝酒也都会感慨一下。这次回去就是大家高兴一下,毕竟下一次聚齐就不知道是啥时候了,也许又是一个三年? 对我来说,五一回家不是很爽,工作没着落,家里人肯定心里也着急,嘴上不说,心里没底,怕给我压力又怕我毕业就失业。所以了,回到家我得高兴点,不能自己憋屈着脸让家里人难受,多笑笑,多跟爸妈说说话,给他们宽宽心,多陪妹妹玩玩,反正就一条,不能让家里人难受就是。跟兄弟们一起也一样,疯玩,开心,不能因为自己一个人心情影响大家的心情。 五一回家,陪爸妈说说话,跟兄弟们聚聚,让自己散散心,多笑笑。 <file_sep>/_posts/2009-07-31-common-computer-words-in-jp-katakana.markdown --- layout: post title: "常见计算机单词日语片假名" --- 这两天任务轻,就把上两周的项目的式样书给翻了一下,把一些常见的计算机方面的日语单词,尤其是片假名单词整理一下,多看看,多积累。 ``` レイアウト Layout ファイル File シート Sheet システム System メッセージ Messages データ Data コンバート Convert ツール Tool ライブラリ Library コンピュータ Computer パラメータ Parameters バージョン Version エラー Error パス Path ドライブ Drive ディレクトリ Directory マスタ Master チェック Check オープン Open ステータス Status プログラム Program セット Set クラス Class クセス Acess モード Mode ガイド Guide オプション Opition タイプ Type レコード Record ログ Log アウト Out フレーム Frame クローズ Closed ドキュメント Documents ユーザ User インプット Input アウトプット Output エクスポート Export インポート Import ``` <file_sep>/_posts/2011-04-16-no-money-no-house.markdown --- layout: post title: "买房" --- 想买房吗?当然,任何经历过找房、中介、搬家的人都想买。那种没有房子的不确定感让人很空。 但是一定要买房吗? 如果要搭上自己和父辈两代人两个家庭(也有可能是三个家庭)的积蓄,加上十年的负债生活,严重降低生活质量,徒增生活压力,来换取一个安身的地方,我宁愿不要。 量力而行。 <file_sep>/_posts/2016-04-29-monthly-review-1604.markdown --- layout: post title: Monthly Review 2016-04 date: 2016-04-29 09:42:25 +0800 --- 1. 新的运营小编入职一个月,如何快速帮她成长是个大事。 2. 运营效果尝试用一些指标来衡量,小编每日工作量,应用日活变化等等。 2. 运营一直是自己做的不好的地方,怎么发挥每个人的特长和作用还要好好学习。 3. 提交应用还在继续,过于依赖 network-based features,严格意义来说这涉及欺诈,审核困难。 4. 月初回家,月底搬家,生活每天都在变好,不是吗? <file_sep>/_posts/2010-12-25-thanksgiving-2010.markdown --- layout: post title: "感恩 2010" --- 年终总结,感恩 2010。 感谢三高,这个毕业后的第一份工作。这个超低工资,没加班费,混乱又抠门的公司,有个“第一次”的Tag,怎么都不能忽略他的存在。在他的混乱下,其实有很多可以抓住的机会。独立担当,流程管理,甚至新人培训,这都是锻炼。感谢那些日本人教会我的严谨。 感谢豆瓣,很难想像我这个土鳖玩豆瓣吧?其实上豆瓣是因为这是国内最为成功的 Python Powered 网站。我这个 Python 初学者看不懂大牛们在 CPyUG 的讨论,就经常在豆瓣 Python 小组晃荡,于是就看见了那个招聘帖子。 感谢帅哥,刘帅。那个敏感日的晚上我坐 T敏感词 次火车北上面试,帅哥带我游北京,吃烤鸭;我确定北漂的时候帅哥又费力的帮我找房租房,让我北漂时候知道还有兄弟在,不至于那么凄凉,谢谢帅哥。 感谢 @Appwill,感谢团队对我的信任,帮助。弹性上班,水果时间,桌上足球,漂流,保龄球,在这样的团队工作环境下,做自己喜欢的工作,还有什么比这更好的么?感谢团队给我很大的发展空间,在项目开始,我是“产品经理”,天马行空般的去头脑风暴设计产品;然后是“架构师”,目标是一个伸缩性好扩展性好的产品架构,甚至在需要的时候推倒重构;然后是一个Coder、Tester;最后是反馈客服,根据用户的反馈迭代产品。这样的过程还会继续,我们也会继续专注于移动平台的开发,创造更大的移动价值。 感谢妞妞,陪我一路走过,然后一路走下去。我不坚强的时候有你,你不坚强的时候有我,这就足够了。 谢谢爸妈,谢谢小妹,想你们了,赶紧放假回家。 感谢这一年给我帮助的所有人,谢谢你们,祝你们新的一年顺利,幸福。 最后,未来不迎,既过不恋,当时不杂。 <file_sep>/_posts/2013-08-12-the-most-effective-debugging-tool.markdown --- layout: post title: "The most effective debugging tool" date: 2013-08-12 09:54 --- > The most effective debugging tool is still careful thought, coupled with judiciously placed print statements. by [<NAME>](http://en.wikiquote.org/wiki/Brian_Kernighan) <file_sep>/_posts/2011-04-03-20110401-mbp.markdown --- layout: post title: "MBP" --- 愚人节那天去提了一个 MBP 回来。学生时代想的毕业五年内买一个 MBP 的愿望提前三年实现,嗯,要感谢郭嘉。 半年多的 iPhone 开发,所以对 Mac OS 再熟悉不过,系统上手没有一点障碍。键盘手感不错,些许偏软,但键程很舒服。触摸板是令人发指的强大,除了 Xcode 定位程序,基本上已经脱离鼠标操作了。尤其是 Firefox 下 vimperator + 触摸板,顺畅呐。 有了好工具要更好的工作,嗯,赚钱准备下一代 MBP。 <file_sep>/_posts/2008-03-05-ubuntu-config-1.markdown --- layout: post title: "ubuntu个人配置(一)" --- 1、首先解决的是上网问题,上网搞不定基本上后面的都干不了。学校的锐捷上网上网认证解决: mystar认证:两个文件解压到个人目录里面,这样方便点。然后文档打开 mystar.conf,修改用户名、密码。在网络连接里面设置静态IP地址还有DNS解析,然后再终端里输入:sudo ./mystar 就可以认证上网。 2、设置软件源 ``` sudo cp /etc/apt/sources.list /etc/apt/sources.list_backup----备份当前源 gksu gedit /etc/apt/sources.list #感觉官方那个速度已经很不错了,就没做大的更改,只加了科大跟CN99的源。 deb http://debian.ustc.edu.cn/ubuntu/ gutsy main multiverse restricted universe deb http://debian.ustc.edu.cn/ubuntu/ gutsy-backports main multiverse restricted universe deb http://debian.ustc.edu.cn/ubuntu/ gutsy-proposed main multiverse restricted universe deb http://debian.ustc.edu.cn/ubuntu/ gutsy-security main multiverse restricted universe deb http://debian.ustc.edu.cn/ubuntu/ gutsy-updates main multiverse restricted universe deb-src http://debian.ustc.edu.cn/ubuntu/ gutsy main multiverse restricted universe deb-src http://debian.ustc.edu.cn/ubuntu/ gutsy-backports main multiverse restricted universe deb-src http://debian.ustc.edu.cn/ubuntu/ gutsy-proposed main multiverse restricted universe deb-src http://debian.ustc.edu.cn/ubuntu/ gutsy-security main multiverse restricted universe deb-src http://debian.ustc.edu.cn/ubuntu/ gutsy-updates main multiverse restricted univers</pre> deb http://ubuntu.cn99.com/ubuntu/ gutsy main restricted universe multiverse deb http://ubuntu.cn99.com/ubuntu/ gutsy-security main restricted universe multiverse deb http://ubuntu.cn99.com/ubuntu/ gutsy-updates main restricted universe multiverse deb http://ubuntu.cn99.com/ubuntu/ gutsy-proposed main restricted universe multiverse deb http://ubuntu.cn99.com/ubuntu/ gutsy-backports main restricted universe multiverse deb-src http://ubuntu.cn99.com/ubuntu/ gutsy main restricted universe multiverse deb-src http://ubuntu.cn99.com/ubuntu/ gutsy-security main restricted universe multiverse deb-src http://ubuntu.cn99.com/ubuntu/ gutsy-updates main restricted universe multiverse deb-src http://ubuntu.cn99.com/ubuntu/ gutsy-proposed main restricted universe multiverse deb-src http://ubuntu.cn99.com/ubuntu/ gutsy-backports main restricted universe multiverse sudo apt-get update----更新源列表 sudo apt-get dist-upgrade----更新软件,可选 ``` 图形化的软件源设置里面,五项全选,选择中国官方源,去掉DVD软件仓。 3、语言设置 系统 - 系统管理 - 语言支持,在列表中的Chinese条目打勾,提示安装,默认语言修改为Chinese,确定。 4、右键菜单加入打开终端,相当方便这样 `sudo apt-get install nautilus-open-terminal` 5、多媒体环境配置 Mp3播放:Audacious `sudo apt-get install audacious` 电影播放:Mplayer以及解码器 `sudo apt-get install mplayer-fonts mplayer mplayer-skins w32codecs` 字符编码好像有bug,不能直接在文件浏览器中打开文件,修改配置文件 `sudo gedit /usr/share/applications/mplayer.desktop` 将其中的 `exec=gmplayer %U` 改为 `exec=gmplayer %f` 即可。 <file_sep>/_posts/2011-11-19-thanks-to-douban.markdown --- layout: post title: "Thanks to Douban" --- > 注册豆瓣1435天 Heyward at Douban has dead on 2011-11-19. 感谢豆瓣,通过你我找到了我想要的工作。 https://fann.im/blog/2010/12/25/thanksgiving-2010/ <file_sep>/_posts/2008-04-25-host-error-2-days.markdown --- layout: post title: "服务器宕机两天" --- 服务器宕机了2天,终于好了。从23号下午5点左右宕机的,昨天问了客服,好像是机房受到攻击,一直在抢修中。效率还好,不过还是不要这样的好,看着火狐显示Page Load Error就是相当的不爽。 推荐一个好网站 [UPTIME](http://www.uptime.com.cn/),一天24小时的监视你的服务器,宕机时候可以发送邮件给你,最重要的是免费也可以用。免费账号功能: 1. 2个监测器 2. 最短间隔30分钟 3. 支持HTTP监测 4. 短信提醒0.30元/条 (可选) 对咱这种穷人来说已经足够了,最短间隔30分钟(我选的是60分钟监视),邮件提醒,免费,赞一个! <file_sep>/_posts/2009-04-11-some-thoughts.markdown --- layout: post title: "偶感" --- 下午出去转了一圈,提前去看一下明天上午安徽信用联社笔试地点,省的明天早上手忙脚乱的找不到地方慌乱。考试地点在琥珀山庄信用联社的总行,来合肥三四年了,发现琥珀山庄那个地方相当不错。 整个山庄算是围着一个人工水上公园建的,水上公园周围又是一个环境很好的公园,绿化很好。山庄内没有公车,没有主干道,走了半个小时基本上遇见的都是私家车,行人,很安静,环境真的很好。要是自己住的话会很不错,早上或晚上在公园里溜达一下,散散心,跑跑步,没有车鸣喧哗,生活很舒适的地方。当时我就想以后自己住的地方要是有这种环境该多好啊! 哎,现在根本想不了那么多。现在我想要的只是一个我喜欢的工作,一个可以做自己喜欢做的事。因为工作的事,今年我都不敢跟家里打电话,家里人其实也很大压力,但又不敢说,说了怕给我更大的压力,又怨自己没什么门路,上次爸打电话过来说要是找工作需要走关系送礼啥的,跟家里说,别不舍得,错过机会,其实他们有什么钱啊。我只想要一个工作,哪怕只能养活我自己吃饭;租个单间,有个睡觉的地方;做点自己喜欢的东西,就算没有高工资,没有好待遇,没有所谓的出人头地,只是让自己能够安定,让家人能够少些牵挂,让妹妹还能写“哥哥加油”的纸条偷偷放我钱包里。要求高吗?可是我还没有达到。 突然发现,我啥时候变得这么安于满足不思进取没有上进心了?是什么让我这么现实了?干! <file_sep>/_posts/2009-02-21-graduation-thesis.markdown --- layout: post title: "毕业设计开始了" --- 上午学院开毕业设计动员大会,无非是强调一下毕业设计的意义,要求,流程等等,然后把选题分发下来,中午一回来大家都开始疯抢,我的题目: > 利用JSP和SQL server实现局域网内办公自动化系统。 选题差不多有四类,MIS类,Web类,系统应用程序类以及算法复现类,难度应该是依次增加。我自己偏向于Web程序设计类,自从大三下开始,慢慢的就开始把自己的方向转向Web程序设计,桌面编程基本上荒废了。上学期的课程设计就是用PHP+MySql实现了一个简单的留言板,很简单的功能,对自己也算是一个锻炼。今年毕业设计就想着还做Web方面的,算是积累一些实战经验。 这个选题初步打算是用JSP+SSH(Struts+Spring+Hibernate),丫头是做JSP开发的,说目前这个组合企业级的开发比较多,是一个很流行的开发组合,就打算尝试一下,虽然现在来说啥都还不知道。下午去图书馆借了本JSP的书,语法方面的,大二学Java时候有一部分是JSP的东西,不过尝试不多,没有做过什么项目。暂时先把丢掉的东西捡起来,然后看老师提供的需求,加油做。 其实还有一道题挺想做的,博客网站设计,没有要求具体语言,当时就特想要这个题,用Python写一下,然后架设到GAE上,做一个辅助博客。不过计算机专业毕业设计有一个潜规则,搞Web做网站的答辩时候得分普遍较低,那帮子老师可能感觉写Web的没有搞算法的那么高深,不应该是科班人做的。科班的好像都应该是实现什么很牛逼的算法复现才说的过去……再一个考虑找工作时候写简历时候,做一个办公自动化系统看起来至少比写一个博客网站来的正规高级一点,自己写一个博客系统给人的感觉就有点份量不是很足。也见过很多coder业余时间写一个Python blog假设在GAE上,算是一种学习能力扩展,尝试新东西吧。现在GAE确实非常热,Google云计算的一个重量级武器,目前来说大型应用还不够成熟,不及Amazon EC2、S3那样可以拿来做企业应用,不过GAE一直在加强,今年也将推出付费应用,功能将越来越强大。好吧,我承认去年的时候就想着用GAE做一个博客应用,一直没动手。。。今年要是时间充足的话尝试一下,功能不要求强大,简单的博客抑或是一个留言本也行,算是09年的一个小目标吧。 努力做毕业设计,也要努力找工作,加油! <file_sep>/_posts/2016-01-29-monthly-review-1601.markdown --- layout: post title: Monthly Review 2016-01 date: 2016-01-29 16:40:55 +0800 --- 1. Web 前端面试了不少人,优秀的人才实在少。 2. 面试别人的时候我就在想,如果现在让我去面试,我能不能行?比方说前端,半路出家不查文档就不会写的水平,如何说服对方? 3. 在我看来,好的开发要有 扎实理论基础+描述问题的能力+解决问题的能力+快速学习的能力。 4. 对接神策数据分析,接下来要用这个数据结果去辅助产品改进和运营。 4. 房子交税-过户,由于价格上涨,业主有想违约,好在还算顺利的解决。 5. 金钱面前,合同契约什么的还是脆弱。<file_sep>/_posts/2011-12-04-how-to-google-it.markdown --- layout: post title: "How to Google it" date: 2011-12-04 16:57 --- ![](https://i.loli.net/2019/03/15/5c8b550e688af.gif) via [How to Use Google Search More Effectively [INFOGRAPHIC]](https://mashable.com/2011/11/24/google-search-infographic/) <file_sep>/_posts/2019-08-09-power-of-g-in-vim.markdown --- layout: post title: Power of g in Vim date: 2019-08-09 18:31:21 +0800 --- `:[range]g[!]/pattern/cmd` `!` means **do not** match pattern, cmd list: - `d`: delete - `m`: move - `t`: copy, or `co` - `s`: replace for more info: - `:help ex-cmd` - [Power of g](https://vim.fandom.com/wiki/Power_of_g)<file_sep>/_posts/2010-09-26-most-commonly-used-commands-in-gdb-console.markdown --- layout: post title: "Most commonly used commands in GDB Console" --- **load** program > Load the *program* into the target. **b** main > Set a breakpoint in function *main*. **c** > Continue after a breakpoint. **l** > View a listing of the program. **n** > Step one line (stepping over function calls). **s** > Step one line (stepping into function calls). **info** reg > View register values. **p** xyz > Print the value of *xyz* data. **watch** gvar1 > Set Watchpoint on Global Variable *gvar1*. via [Commonly Used GDB Console Commands](http://www.xilinx.com/itp/xilinx9/help/platform_studio/html/ps_r_dbg_common_gdb_commands.htm) <file_sep>/_posts/2013-03-02-nsdateformatter-mistake.markdown --- layout: post title: "NSDateFormatter 返回一年前时间" date: 2013-03-02 13:54 --- `NSDateFormatter` 的一个小陷阱: ``` objc NSString *ds = @"2013-03-01 23:55:56"; NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; NSDate *date1 = [formatter dateFromString:ds]; NSLog(@"date1: %@", date1); //date1: 2012-03-01 15:55:56 +0000 [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; NSDate *date2 = [formatter dateFromString:ds]; NSLog(@"date2: %@", date2); //date2: 2013-03-01 15:55:56 +0000 ``` 格式化以后是一年前的一个时间点,`yyyy` 指代的就是常规意义上的年,而 `YYYY` 是 Week of Year, 具体解释参考 Wikipedia: [ISO_week_date][1] iOS 开发文档有相关[提示](https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html): > It uses yyyy to specify the year component. A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year. [1]:http://en.wikipedia.org/wiki/ISO_week_date <file_sep>/_posts/2008-06-22-game-over.markdown --- layout: post title: "Game Over,大学" --- 准确说应该是理论上大学的课程结束了。 上午结束了操作系统,最后一门专业考试,下个学期,大四必修貌似只有一门现代企业管理一门高级课程了,对了,还有四个课程设计呢。这样算下来剩下一年时间必修的就是四个课程设计,这学期要结束掉两个,软件工程跟操作系统,下个学期开学时候两个,网络跟数据库,外带最后时候一个毕业设计,game over! 算算真的要结束了,大四也就是找工作,考研,然后荒废时间,使劲的堕落。其实现在都挺堕落的,堕落到你都不知道啥叫堕落了。 PS:昨天下午再次耍耍六级,我的个英语啊。 <file_sep>/_posts/2014-02-25-ios-7-background-fetch.markdown --- layout: post title: "iOS 7 Background Fetch" date: 2014-02-25 21:27 --- iOS 7 新加了三个后台任务 API: `Background Fetch` 后台获取,`Silent Remote Notifications` 静默推送,`Background Transfer Service` 后台传输。 Background Fetch 会由系统进行调度,应用可以在后台进行一定的网络请求。这里的限制是后台操作只允许 30s,超时未完成应用会被直接 kill,所以只适合做一些简单的网络请求。 Silent Remote Notifications 可以由服务端控制,通过消息后台打开应用根据消息内容 (content-id) 进行一些操作,也可以做网络请求,但同样只有 30s 限制。 Background Transfer Services 可以在后台进行网络大文件的下载、上传操作,没有时间限制,但只能在 Wi-Fi 下进行,而且受系统调度可能会是间断性进行。一般可以配合静默推送一起用,比如电视剧更新,静默推送最新一集信息到手机,应用后台新建下载任务然后逐步下载,下载完成后再通过 Local Notifications 通知用户观看。 Background Fetch 使用步骤: 1 在 `Target - Capabilities` 打开 `Background Modes`,勾选 `Background Fetch`。也可以手动修改 Info.plist 添加 `UIBackgroundModes - fetch`。 2 设置后台获取时间间隔: ```objc - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum]; return YES; } ``` 3 执行后台获取,并在完成后通知系统: ```objc - (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { //... [fetcher fetchDataWithResult:^(NSError *error, NSData *data){ if (error) { completionHandler(UIBackgroundFetchResultFailed); } else { // parse data if (hasNewData) { completionHandler(UIBackgroundFetchResultNewData); } else { completionHandler(UIBackgroundFetchResultNoData); } } }]; } ``` 需要注意的是一定要在请求完成后再调用 `completionHandler();`,不然请求有可能被系统中断。可以配合 [NSOperation + KVO][1] 在所有操作都完成后再执行 `completionHandler();`. Xcode 5 提供了两个方法测试 Background Fetch,一是模拟器运行应用时通过 Xcode 菜单 `Debug - Simulate Background Fetch` 模拟;二是修改应用 Scheme 选中 `Launch due to a background fetch event` 再运行应用,这时候应用不会打开界面,真正的在后台运行。 参考 [Multitasking in iOS 7][2], [WWDC 2013 Session笔记 - iOS7中的多任务][3], [iOS 7: Background Fetch][4]. [1]:https://fann.im/blog/2014/02/23/nsoperation/ [2]:http://www.objc.io/issue-5/multitasking.html [3]:http://onevcat.com/2013/08/ios7-background-multitask/ [4]:http://www.doubleencore.com/2013/09/ios-7-background-fetch/ <file_sep>/_posts/2008-03-31-process-explorer-error.markdown --- layout: post title: "Process Explorer报错:这个系统的 .NET 性能计数器已损坏" --- 先把错误信息贴出来: ``` 这个系统的 .NET 性能计数器已损坏。请从 Microsoft Windows 资源工具箱运行 Exctrlst 来修复它们。 ``` Process Explorer是个相当不错的进程管理工具,一直都用这个东西。今天电脑有点小卡,习惯性的打开PE,报错,性能计数器?Google了一下,解决办法: 1. 微软官方下载Exctrlst。 2. 安装,运行,选择Counter,然后找到并选择列表里的.NETFramework。 3. 将Performance Counters Enable的勾去掉,"Refresh"。 4. 搞定,不过那个性能计数器是个什么东西? <file_sep>/_posts/2009-02-23-vim-config.markdown --- layout: post title: "配置Vim" --- 1. 添加ctags、taglist插件。官网下载这两个插件。taglist解压后合并到 `$VIM/vimfiles` 下doc和plugin目录,ctags.exe单文件放在vim安装目录下 2. ctags使用:源文件目录下cmd中运行 `ctags –R`,会在源文件目录下生成一个tags文件. 3. taglist使用很简单,常用的命令有 `:Tlist,ctr+],ctr+o`。 4. 添加SearchComplete.vim插件,很小巧,功能就是搜索时候支持Tab补全关键字。 插件就先这么几个,慢慢的用了再添加。然后一个主要的就是 `_vimrc` 配置文件,这个更是要慢慢摸索,把现在的贴出来先: ``` " 自动载入_vimrc配置文件 autocmd! bufwritepost D:\Program Files\Vim_vimrc " 不同中文编码显示 set encoding=utf-8 set fileencodings=utf-8,gbk,chinese,latin-1 if has("win32") set fileencoding=chinese else set fileencoding=utf-8 endif language message zh_CN.utf-8 " 默认目录 cd E:\Vim set backupdir=E:\Vim\Backup " 显示行号 set number " 禁用swf交换文件 setlocal noswapfile " 使用中文帮助文档 set helplang=cn " 自动缩进,tab缩进 set autoindent "always set autoindenting on set smartindent "set smart indent set smarttab "use tabs at the start of a line, spaces elsewhere set expandtab set tabstop=4 set shiftwidth=4 " 自动匹配括号 set showmatch set mat=2 " 状态栏显示 set statusline=%F%m%r%h%w\ [TYPE=%Y]\ [POS=%04l,%04v][%p%%]\ [LEN=%L] set laststatus=2 " always show the status line " 侦测文件类型 filetype on " 启用语法高亮 syntax on " smartcase,搜索时默认不区分大小写,只有搜索关键字中出现一个大字母时才区分大小写 set ignorecase smartcase ``` 最后一点,关于vim插件安装位置的问题,滇狐大侠[这篇文章](http://edyfox.codecarver.org/html/vimpluginspath.html)里有很详细的解释。我的方法,$HOME目录不装,牵扯到系统重装恢复,比较麻烦;$VIMRUNTIME目录尽量不装,这里面是发行版自带的插件等,升级vim时候可能会覆盖掉;自己安装的插件、文档等全部放在$VIM/vimfiles目录下,这样既便于管理又安全。 趁着毕业设计把以前许多想做的但又偷懒没做的拿起来,下一个,版本控制,做项目的必备啊。 <file_sep>/_posts/2013-06-17-three-years-in-beijing.markdown --- layout: post title: "Three years in Beijing" date: 2013-06-17 20:23 --- 2010-2013, three years in Beijing. <file_sep>/_posts/2010-06-01-firefox-tips-render-pages-faster.markdown --- layout: post title: "Firefox Tips:Render pages faster" --- To improve page rendering, enter about:config in the address bar (accept the warning that comes up) and perform the following: > Create a new integer value named **content.notify.backoffcount** and set the value to 5 > Create a value named **nglayout.initialpaint.delay** and set its value to 0 The first line stops Firefox waiting for the entire page to download before rendering. The second improves speed rendering further by making sure Firefox does not wait for the page layout information to be fully downloaded before displaying the page. via [Firefox Tips:Tips 2](http://www.linuxlinks.com/article/20091003160004352/Firefox-Tips-Page1.html) <file_sep>/_posts/2012-04-12-difference-between-objectforkey-and-valueforkey-in-nsdictionary.markdown --- layout: post title: "Difference between objectForKey and valueForKey in NSDictionary" date: 2012-04-12 19:56 --- 从 NSDictionary 取值的时候有两个方法,`objectForKey:` 和 `valueForKey:`,这两个方法具体有什么不同呢? 先从 NSDictionary 文档中来看这两个方法的定义: > objectForKey: returns the value associated with aKey, or nil if no value is associated with aKey. 返回指定 key 的 value,若没有这个 key 返回 nil. > valueForKey: returns the value associated with a given key. 同样是返回指定 key 的 value。 直观上看这两个方法好像没有什么区别,但文档里 `valueForKey:` 有额外一点: > If key does not start with “@”, invokes objectForKey:. If key does start with “@”, strips the “@” and invokes [super valueForKey:] with the rest of the key. via [Discussion][1] 一般来说 key 可以是任意字符串组合,如果 key 不是以 **@** 符号开头,这时候 `valueForKey:` 等同于 `objectForKey:`,如果是以 **@** 开头,去掉 key 里的 @ 然后用剩下部分作为 key 执行 `[super valueForKey:]`。 比如: ``` NSDictionary *dict = [NSDictionary dictionaryWithObject:@"theValue" forKey:@"theKey"]; NSString *value1 = [dict objectForKey:@"theKey"]; NSString *value2 = [dict valueForKey:@"theKey"]; ``` 这时候 `value1` 和 `value2` 是一样的结果。如果是这样一个 dict: ``` NSDictionary *dict = [NSDictionary dictionaryWithObject:@"theValue" forKey:@"@theKey"];// 注意这个 key 是以 @ 开头 NSString *value1 = [dict objectForKey:@"@theKey"]; NSString *value2 = [dict valueForKey:@"@theKey"]; ``` `value1` 可以正确取值,但是 `value2` 取值会直接 crash 掉,报错信息: > Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFDictionary 0x892fd80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key theKey.' 这是因为 `valueForKey:` 是 `KVC(NSKeyValueCoding)` 的方法,在 KVC 里可以通过 property 同名字符串来获取对应的值。比如: ``` @interface Person : NSObject @property (nonatomic, retain) NSString *name; @end ... Person *person = [[Person alloc] init]; person.name = @"fannheyward"; NSLog(@"name:%@", [person name]); //name:fannheyward NSLog(@"name:%@", [person valueForKey:@"name"]); //name:fannheyward [person release]; ``` `valueForKey:` 取值是找和指定 key 同名的 property accessor,没有的时候执行 `valueForUndefinedKey:`,而 `valueForUndefinedKey:` 的默认实现是抛出 `NSUndefinedKeyException` 异常。参考[Getting Attribute Values Using Key-Value Coding][2] 回过头来看刚才 crash 的例子, `[dict valueForKey:@"@theKey"];` 会把 key 里的 @ 去掉,也就变成了 ` [dict valueForKey:@"theKey"];`,而 dict 不存在 `theKey` 这样的 property,转而执行 ` [dict valueForUndefinedKey:@"theKey"];`,抛出 `NSUndefinedKeyException` 异常后 crash 掉。 `objectForKey:` 和 `valueForKey:` 在多数情况下都是一样的结果返回,但是如果 key 是以 @ 开头,`valueForKey:` 就成了一个大坑,建议在 NSDictionary 下只用 `objectForKey:` 来取值。 [1]:https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsdictionary_Class/Reference/Reference.html [2]:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Articles/BasicPrinciples.html#//apple_ref/doc/uid/20002170-BAJEAIEE <file_sep>/_posts/2010-08-11-simple-scp-notes.markdown --- layout: post title: "Simple SCP notes" --- SCP: Copies files over the network securely; uses ssh for data transfer, using the same authentication and providing the same security as ssh. Using: > `scp [-p] [-v] [-r] [[username@]host:] file_or_dir [[username@]host:]file_or_dir` - Putting: > scp mydata.dat <EMAIL>:Newname.dat > scp -r FileFolder <EMAIL>:/home/ - Gettiing: > scp <EMAIL>:remote.data /home/local.dat > scp -r <EMAIL>:FileFolder /home/ <file_sep>/_posts/2014-10-29-jekyll-in-docker.markdown --- layout: post title: "Jekyll in Docker" date: 2014-10-29 15:16:50 +0800 --- 最近[又捡起][0] Docker,打算用在团队内做一些 CI 工作。拿 Jekyll 练手,记一下笔记: ``` FROM ruby:2.1.3 MAINTAINER <NAME> <<EMAIL>> RUN gem install github-pages RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/* ENV NODE_VERSION 0.10.33 RUN curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \ && tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-x64.tar.gz" WORKDIR /blog EXPOSE 4000 ENTRYPOINT ["jekyll"] CMD ["serve"] ``` Then: 1. `docker build --rm=true --tag="blog:0.0.2" .` 1. `docker run --rm -p 4000:4000 -v /ABSOLUTE/PATH:/blog blog:0.0.2` 1. `boot2docker ip` then `http://IP:4000` 1. OR `docker run --rm -v /ABSOLUTE/PATH:/blog blog:0.0.2 build` 笔记: 1. Base image 建议选用 `debian:wheezy`,如果需要编译环境可用 `buildpack-deps:wheezy|jessie`,相对 Ubuntu image 要小很多。 2. 尽量不安装编译环境,直接包管理工具或二进制文件,注意清理缓存文件。 3. 尽量少的 `RUN` 命令,减少 layers 数量,尽可能在一个 RUN 组合完成多个操作,比如 [ruby]。 4. 配合 `.dockerignore` 忽略不需要的文件。 5. build 或 run 的时候加上 `--rm=true` 自动删除中间容器。 6. `CMD` 和 `ENTRYPOINT` 都是 `docker run` 的入口,只是在参数处理上不同。CMD 可以被 run 后面的命令替换,而 ENTRYPOINT 是把 run 后面的作为参数传入。 7. CMD 配合 ENTRYPOINT 一起用很不错,如果没有参数,执行的就是 ENTRYPOINT+CMD 组合起来的功能,加上参数就会把 CMD 替换掉,执行另外的命令。 8. OS X 下用 `boot2docker` 要注意 IP 不是本机或 127.0.0.1,而是 `boot2docker ip`. 9. 如果是 Golang 二进制程序,完全可以构建一个空 image 执行,比如 [Building Docker Images for Static Go Binaries][4]. 参考: * [Dockerfile Best Practices][1] * [Dockerfile Best Practices - take 2][2] * [Building good docker images][3] * [15 分钟掌握 15 个 Docker 小窍门][5] ---- 就目前的情况,用 Docker 构建测试环境很方便,麻烦的是测试用例和测试脚本整理,小团队基本以业务为主,很少有时间或没有意识的去写测试用例,只是在完成具体业务后针对该功能进行测试,没法系统的进行测试,这个需要在后面工作中重视起来。 [ruby]:https://github.com/docker-library/ruby/blob/master/2.1/Dockerfile#L10 [0]:https://fann.im/blog/2014/02/11/docker-notes/ [1]:https://crosbymichael.com/dockerfile-best-practices.html [2]:https://crosbymichael.com/dockerfile-best-practices-take-2.html [3]:http://jonathan.bergknoff.com/journal/building-good-docker-images [4]:https://medium.com/@kelseyhightower/optimizing-docker-images-for-static-binaries-b5696e26eb07 [5]:https://docker.cn/p/docker-15-tips/ <file_sep>/_posts/2013-10-30-bootstrap-3-grid-notes.markdown --- layout: post title: "Bootstrap 3 Grid 笔记" date: 2013-10-30 22:21 --- 作为非专业的前端开发,Bootstrap 真是个好东西,特别适合做运营、管理系统界面。这些系统界面要求不高,干净整齐就好,最主要的就是网格 Grid 的使用,简单记录一下。 Bootstrap 3 自带了移动优先的响应流式网格布局系统,将整个屏幕或某一视区(viewport)划分为 12 列,使用时把内容放到相应列中,自然就整齐不乱。一般来说 Bootstrap 的网页结构是 `container` > `row` > `col`,一个或多个 col 组成一组 row,多个 row 归于一个 container,这样的多级布局很方便在大小不同的屏幕灵活布局。 最小单位 col 有四种:`col-xs-*`, `col-sm-*`, `col-md-*`, `col-lg-*`,(题外话,Bootstrap 这四个 col 命名实在是让人费解,也不是什么缩写,完全没有 Foundation 的 `small-2 large-4 columns` 简洁明了),分别适用于手机(768px 以下),平板(768-992px),桌面(992px+)和超大屏幕(1200px+),后一位是需要的宽度比例,总和为 12,这样就自动把界面进行划分布局,比如想把一个普通电脑屏幕左右平分,两个 `col-md-6` 即可。col 可以组合,这样就同时适配手机和电脑,比如在电脑是左右三等分,手机是二等分: ```html <div class="container"> <div class="row"> <div class="col-md-4 col-xs-6"> A </div> <div class="col-md-4 col-xs-6"> B </div> <div class="col-md-4 col-xs-6"> C </div> </div> </div> ``` col 也可以嵌套,要注意的是每个 col 里又是一个 12 等分的完整网格,也要包在二级容器 row 里。比如左右二等分,每个再 1:2 划分: ```html <div class="container"> <div class="row"> <div class="col-md-6"> <div class="row"> <div class="col-sm-4"> A </div> <div class="col-sm-8"> B </div> </div> </div> <div class="col-md-6"> ... </div> </div> </div> ``` 网格还有一个方便的东西就是 Offset `.col-md-offset-*`,可以把某一 div 向右偏移指定比例,比如只一半的宽度,然后居中,3-6-3 布局: ```html <div class="container"> <div class="row"> <div class="col-sm-6 col-sm-offset-3"> S </div> </div> ``` 参考 [Bootstrap 3: the new grid system, for starters](http://www.williamghelfi.com/blog/2013/06/09/bootstrap-3-the-new-grid-system-for-starters/). <file_sep>/_posts/2008-04-26-flashgot-addref-error.markdown --- layout: post title: "Firefox 下flashgot调用迅雷出现AddRef错误" --- 实在不知道该怎么形容这个错误了,上图: ![](http://lh5.ggpht.com/_vYr4JQreqXA/STTAYRTrnRI/AAAAAAAAAkk/53BouOMpj6M/s400/flashgot.JPG) 虽然每次都可以手动改存储目录跟名称,但毕竟不是很方便,恼人的bug。解决办法:打开 `about:config`,定位 `flashgot.autoReferrer`,将其属性改为false,重启firefox即可。 <file_sep>/_posts/2020-11-24-aws-data-transfer-costs.markdown --- layout: post title: AWS Data Transfer Costs date: 2020-11-24 15:46:25 +0800 --- ![AWS Data Transfer Costs](https://raw.githubusercontent.com/open-guides/og-aws/master/figures/aws-data-transfer-costs.png) via [The Open Guide to Amazon Web Services](https://github.com/open-guides/og-aws#aws-data-transfer-costs)<file_sep>/_posts/2010-03-22-it-loos-like-badly.markdown --- layout: post title: "电脑貌似挂了" --- 昨晚上抱着笔记本看电视,突然自动关机,一摸,热得烫手。虽说用个懒人桌撑着本子,散热还是有问题。等机子凉下来再次准备开机时,坏了,不能开机,按电源键直接没反应。 初步判断是主板烧了,当然,这是最坏的结果了。等周末拿去电脑城看看再说吧。 这本子用了整三年,之前是我家最昂贵的家伙什,跟着我没少受苦,希望不至于就这么的挂了吧。 <file_sep>/_posts/2012-03-23-maximize-xcode-debug-console-window.markdown --- layout: post title: "最大化 Xcode Debug Console 窗口" date: 2012-03-23 18:51 --- 参考 [How to get back the Console window in XCode4][1] 做了一点点改动,Run 的时候自动切换到 Console Tab 并且是最大化展示,效果还不错。 1. 打开 Tab 支持,View - Show Tab Bar. 1. 双击或点 + 添加一个 Tab. 1. 双击新加的 Tab 改名,比如 CONSOLE. 1. 激活 Console 显示,View - Debug Aera - Activate Console,或者直接 Command+Shift+C. 1. 拖动 Console 区至顶端,整个 Tab 只显示这个 Console. 1. Command+, 进入 Preferences - Behaviors, 在 **Run Start** 里勾选 **Show Tab**,填 CONSOLE,就是刚才的 Tab 名。 1. Done。 再运行项目时会自动的切换到新 Tab 页查看输出结果,然后通过 Command+Shift+[/] 来切换 Tab. [1]:http://www.touch-code-magazine.com/how-to-get-back-the-console-window-in-xcode-4/ <file_sep>/_posts/2009-08-07-happy-birthday-to-me.markdown --- layout: post title: "今天生日" --- 22岁了,都到法定结婚年龄了。 这个生日是第一次一个人在外过的,没有聚会,但是收到很多兄弟的祝福短信,还是很开心。这也是工作后的第一个生日,大了,不比以前有那么多时间可以去玩,大了,要考虑的就多了,要担负起责任了。 不说了,12:34:56 07/08/09,祝我生日快乐,许个愿:祝爸妈、妹妹、丫头和自己身体好好;好好工作赚钱,爱你们。 <file_sep>/_posts/2013-03-14-rip-google-reader.markdown --- layout: post title: "R.I.P Google Reader" date: 2013-03-14 14:42 --- ![RIP_GR.jpg](https://i.loli.net/2019/11/11/YyemdMZHhGnUqrt.jpg) <file_sep>/_posts/2010-05-27-difference-between-require-and-include-in-php.markdown --- layout: post title: "PHP 中 require() 和 include() 的区别" --- require() 和 include() 的功能都是包含并运行指定文件。寻找包含文件的顺序先是在当前工作目录的相对的 include_path 下寻找,然后是当前运行脚本所在目录相对的 include_path 下寻找。 两者的不同之处只有如何处理包含、运行文件失败:include() 产生一个警告,而 require() 会导致一个致命的错误。如果想在遇到丢失文件时停止处理页面就用 require()。 <file_sep>/_posts/2008-04-04-just-with-you.markdown --- layout: post title: "在你身边" --- ``` 你的温柔让我逐渐深陷 每天总是期待看你一遍 爱的感觉这么强烈 我怎能否决 不管天涯海角 我要在你的身边 ``` <file_sep>/_posts/2012-07-30-20120730.markdown --- layout: post title: "20120730" date: 2012-07-30 13:13 --- 公司最早的一批人,就剩我了。 相信她们的选择,祝福她们的明天,可心里还是难受。 你们一定要过的比今天好。 <file_sep>/_posts/2018-05-15-linux-performance-analysis-in-60s.markdown --- layout: post title: Linux Performance Analysis in 60s external-url: https://medium.com/netflix-techblog/linux-performance-analysis-in-60-000-milliseconds-accc10403c55 date: 2018-05-15 16:31:14 +0800 --- ``` uptime/w --------------------> load average dmesg | tail ----------------> kernel errors vmstat 1 --------------------> overall stats every second mpstat -P ALL 1 -------------> CPU balance pidstat 1 -------------------> process usage, every second iostat -xz 1 ----------------> disk I/O free -m ---------------------> memory usage sar -n DEV 1 ----------------> network I/O sar -n TCP,ETCP 1 -----------> TCP stats top -------------------------> check overview ``` <file_sep>/_posts/2015-10-13-vimdiff.markdown --- layout: post title: vimdiff date: 2015-10-13 20:42:30 +0800 --- `vimdiff a.txt b.txt` * `]c` - 跳到下一个差异点 * `[c` - 上一个差异点 * `dp` - diff put, 将差异点的内容从当前文件复制到另一文件 * `do` - diff get, 相反,从另一文件复制到当前文件 <file_sep>/_posts/2014-01-03-grunt-serve-with-proxy.markdown --- layout: post title: "Grunt serve with Proxy" date: 2014-01-03 16:46 --- 在用 Grunt 开发时可能需要连接外部服务,比如 `grunt serve` 服务在 `http://127.0.0.1:9000`, 当前页需要请求 `http://127.0.0.1:9090/api` 服务,这时候如果直接请求 `/api` 就变成了 `http://127.0.0.1:9000/api`,结果 404,因为这个地址是不存在的;如果直接请求 `http://127.0.0.1:9090/api` 就会出现跨域问题。 比较方便的解决方案是在 grunt server 层做个代理,把 /api 请求转发到需要的服务。有个现成插件 [grunt-connect-proxy][1] 可以直接用。 下载安装:`npm install grunt-connect-proxy --save-dev`,在 `Gruntfile.js` 添加 `grunt.loadNpmTasks('grunt-connect-proxy');` 启用。修改 `connect` 段设置,添加 `proxies` 和 livereload - middleware: ```js grunt.initConfig({ connect: { options: { port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729 }, livereload: { options: { open: true, base: [ '.tmp', '<%= yeoman.app %>' ], middleware: function (connect, options) { var middlewares = []; var directory = options.directory || options.base[options.base.length - 1]; if (!Array.isArray(options.base)) { options.base = [options.base]; } options.base.forEach(function(base) { // Serve static files. middlewares.push(connect.static(base)); }); // Setup the proxy middlewares.push(require('grunt-connect-proxy/lib/utils').proxyRequest); // Make directory browse-able. middlewares.push(connect.directory(directory)); return middlewares; } } }, proxies: [ { context: '/api', host: '127.0.0.1', port: 9090, https: false, changeOrigin: false, xforward: false } ] }, }); ``` 在 `serve` 任务下添加 `configureProxies`,注意要加在 `connect` 任务前: ```js grunt.registerTask('serve', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'bower-install', 'concurrent:server', 'autoprefixer', 'configureProxies', 'connect:livereload', 'watch' ]); }); ``` 重启 `grunt serve` 即可。 [1]:https://github.com/drewzboto/grunt-connect-proxy <file_sep>/_posts/2012-11-29-tp-link-wr941n-flash-openwrt.markdown --- layout: post title: "TP-Link WR941N 刷 OpenWrt" date: 2012-11-29 09:47 --- 硬件版本 TP-Link WR941N V4/V5 00000000,软件版本 3.11.7 build 100723,从 [OpenWrt trunk][1] 下载对应固件 openwrt-ar71xx-generic-tl-wr941nd-v4-squashfs-factory.bin。其他型号参考 [Table of Hardware][2] 下载固件。 登录路由器升级固件,待路由自动重启后 `telnet 192.168.1.1` 连上路由器,`passwd` 设置密码,之后就可以通过 `ssh root@192.168.1.1` 登录路由器。 OpenWrt 默认没有开启无线网络,参考 [TP-Link TL-WR941ND][4] 手动修改 `vi /etc/config/wireless`: (修改之前最好备份一下配置文件) ``` config wifi-device radio0 option type mac80211 option channel 11 option hwmode 11ng option path 'pci0000:00/0000:00:00.0' option htmode HT20 list ht_capab SHORT-GI-40 list ht_capab TX-STBC list ht_capab RX-STBC1 list ht_capab DSSS_CCK-40 # REMOVE THIS LINE TO ENABLE WIFI: # option disabled 1 (删除或注释这一行) config wifi-iface option device radio0 option network lan option mode ap option ssid OpenWrt option encryption psk (默认没有加密,修改为 psk) option key xxxxxxxxx ``` 重启路由网络: ``` /etc/init.d/network restart ``` 配置 PPPoE,`vi /etc/config/network`: ``` config interface 'wan' option ifname 'eth1' option proto pppoe option username 1234567 option password <PASSWORD> option macaddr xx:xx:xx:xx:xx:xx (克隆路由器网卡地址) ``` 再次重启路由网络进行拨号。 安装 [LuCI][3] web 界面,这样就可以在浏览器操作路由: ``` opkg update opkg install luci /etc/init.d/uhttpd enable /etc/init.d/uhttpd start ``` 现在就可以通过 `http://192.168.1.1` 修改路由器配置。 如果网络修改失败不能 ssh 登录,可以[进入安全模式][5]恢复: > 路由上电时,灯会全亮一下,这时你要全神贯注了,当sys灯再次亮时,要立刻按reset2-3秒,然后你就会发现sys灯快闪了。这说明,安全模式成功了! 本机 IP 改为 192.168.1.5,`telnet 192.168.1.1` 连上,然后 `firstboot` 恢复。 [1]:http://downloads.openwrt.org/snapshots/trunk/ar71xx/ [2]:http://wiki.openwrt.org/toh/start [3]:http://wiki.openwrt.org/doc/howto/luci.essentials [4]:http://wiki.openwrt.org/toh/tp-link/tl-wr941nd [5]:http://www.right.com.cn/forum/thread-42810-1-1.html <file_sep>/_posts/2013-08-23-git-checkout-orphan.markdown --- layout: post title: "Git 新建无历史记录分支" date: 2013-08-23 16:59 --- ``` git checkout --orphan NEW_BRANCH_NAME ``` 在代码开源分发等时候往往需要去掉不必要的历史记录,这种新分支方式会很方便。 <file_sep>/_posts/2010-03-23-google-cn-is-leaving.markdown --- layout: post title: "Google.cn is leaving" --- > So earlier today we stopped censoring our search services—Google Search, Google News, and Google Images—on Google.cn. Users visiting [Google.cn][googlecn] are now being redirected to [Google.com.hk][googlehk], where we are offering uncensored search in simplified Chinese, specifically designed for users in mainland China and delivered via our servers in Hong Kong. I love Google. [googlecn]:http://google.cn [googlehk]:http://google.com.hk <file_sep>/_posts/2018-08-30-quote.markdown --- layout: post title: Programming is the art of adding bugs to an empty text file date: 2018-08-30 11:36:15 +0800 --- <NAME>: > Without requirements or design, programming is the art of adding bugs to an empty text file. <file_sep>/_posts/2008-03-24-just-drinking.markdown --- layout: post title: "在宿舍腐败中" --- 帅哥心情不是很好,说晚上弄点小酒喝喝。我俩就去超市买了4罐蓝带,俩鸡腿,外加一包瓜子,一边喝酒一边吃鸡腿一边听歌玩电脑一边上网陪丫头,so high! 不知道啥时候养成的习惯,心情不是很爽的时候就去喝点小酒,啤的白的都行,反正要的就是那种感觉,也不需要醉,酒精下肚的感觉就好,就够了。那些不爽的东西全全给扔掉! 喝酒算是一种逃避吗? <file_sep>/_posts/2011-07-17-happy-birthday-to-me.markdown --- layout: post title: "祝我生日快乐" --- 24 岁,新的起点。 <file_sep>/_posts/2010-01-07-happy-new-year.markdown --- layout: post title: "新年おめでとう" --- 1月1日は新年です。私はこの日に休みました。朝、私と彼女一緒野菜の市場に行って買い野菜をしました。それから、私たちはギョーザを作りました。ごご、私たちはデパートに行って買い服をしました。新年だから、人がたくさんいました。どこもとてもにぎやかでした。新年はおめでとうございます。 老师布置的日语短文作业,这个就是我用日语写的第一篇小短文,就是小学一年级小学生作文嘛。用了俩语法,套了俩句型,鼓励鼓励,继续努力。 <file_sep>/_posts/2018-03-21-docker-compose-mysql-phpmyadmin.markdown --- layout: post title: docker-compose for MySQL + phpMyAdmin date: 2018-03-21 11:43:26 +0800 --- ``` version: '3' services: mysql: image: 'mysql:5' container_name: 'mysql' command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --init-connect='SET NAMES UTF8;' ports: - "3306:3306" environment: MYSQL_ROOT_PASSWORD: '<PASSWORD>' phpmyadmin: image: 'phpmyadmin/phpmyadmin' container_name: 'phpmyadmin' links: - mysql ports: - '8080:80' environment: PMA_HOST: mysql ``` <file_sep>/_posts/2015-08-31-monthly-review-1508.markdown --- layout: post title: Monthly Review 2015-08 date: 2015-08-31 18:06:52 +0800 --- 1. 新项目紧紧的进行,客户端赶在月底上线了第一版。 2. 项目进度很快,甚至有点过快,快到很多地方考虑不周,加上测试不到位,运营又急于推广,导致上线后问题一一出现。 3. 所以说开发时候配上单元测试是很有必要的,可是完全的 TDD 时间上根本不允许。 4. 现在我自己的开发测试模式是 [httpie][1]: `http :3000/api < data.json --session=fann`,严格意义上来说只能算开发辅助,很难 cover 到全部。 ---- 1. 六六在北京一共呆了 40 天,每天回家能和孩子在一起真好。 2. 婆媳关系是个永恒不变的话题,作为丈夫+儿子,大多时候都很无力,只能依靠时间来淡化解决问题。 3. 又一次搬家,不对,搬宿舍。 [1]:https://github.com/jkbrzt/httpie<file_sep>/_posts/2010-06-28-get-parameters-from-basehttpserver-http-get-request.markdown --- layout: post title: "Get parameters from BaseHTTPServer http GET request" --- BaseHTTPHandler from the BaseHTTPServer module doesn't seem to provide any convenient way to access http request parameters. What is the best way to parse the GET parameters from the path, and the POST parameters from the request body? Right now, I'm using this for GET: ``` parsed_path = urlparse.urlparse(self.path) try: params = dict([p.split('=') for p in parsed_path[4].split('&')]) except: params = {} ``` <file_sep>/_posts/2012-08-23-sdwebimage-notes.markdown --- layout: post title: "SDWebImage 笔记" date: 2012-08-23 23:42 --- [SDWebImage][1] 支持异步的图片下载+缓存,提供了 `UIImageView+WebCacha` 的 category,方便使用。纪录一下 SDWebImage 加载图片的流程。 1. 入口 `setImageWithURL:placeholderImage:options:` 会先把 placeholderImage 显示,然后 SDWebImageManager 根据 URL 开始处理图片。 1. 进入 SDWebImageManager-`downloadWithURL:delegate:options:userInfo:`,交给 `SDImageCache` 从缓存查找图片是否已经下载 `queryDiskCacheForKey:delegate:userInfo:`. 1. 先从内存图片缓存查找是否有图片,如果内存中已经有图片缓存,SDImageCacheDelegate 回调 `imageCache:didFindImage:forKey:userInfo:` 到 SDWebImageManager。 1. SDWebImageManagerDelegate 回调 `webImageManager:didFinishWithImage:` 到 UIImageView+WebCache 等前端展示图片。 1. 如果内存缓存中没有,生成 NSInvocationOperation 添加到队列开始从硬盘查找图片是否已经缓存。 1. 根据 URLKey 在硬盘缓存目录下尝试读取图片文件。这一步是在 NSOperation 进行的操作,所以回主线程进行结果回调 `notifyDelegate:`。 1. 如果上一操作从硬盘读取到了图片,将图片添加到内存缓存中(如果空闲内存过小,会先清空内存缓存)。SDImageCacheDelegate 回调 `imageCache:didFindImage:forKey:userInfo:`。进而回调展示图片。 1. 如果从硬盘缓存目录读取不到图片,说明所有缓存都不存在该图片,需要下载图片,回调 `imageCache:didNotFindImageForKey:userInfo:`。 1. 共享或重新生成一个下载器 `SDWebImageDownloader` 开始下载图片。 1. 图片下载由 NSURLConnection 来做,实现相关 delegate 来判断图片下载中、下载完成和下载失败。 1. `connection:didReceiveData:` 中利用 ImageIO 做了按图片下载进度加载效果。 1. `connectionDidFinishLoading:` 数据下载完成后交给 `SDWebImageDecoder` 做图片解码处理。 1. 图片解码处理在一个 NSOperationQueue 完成,不会拖慢主线程 UI。如果有需要对下载的图片进行二次处理,最好也在这里完成,效率会好很多。 1. 在主线程 `notifyDelegateOnMainThreadWithInfo:` 宣告解码完成,`imageDecoder:didFinishDecodingImage:userInfo:` 回调给 SDWebImageDownloader。 1. `imageDownloader:didFinishWithImage:` 回调给 SDWebImageManager 告知图片下载完成。 1. 通知所有的 downloadDelegates 下载完成,回调给需要的地方展示图片。 1. 将图片保存到 SDImageCache 中,内存缓存和硬盘缓存同时保存。写文件到硬盘也在以单独 NSInvocationOperation 完成,避免拖慢主线程。 1. SDImageCache 在初始化的时候会注册一些消息通知,在内存警告或退到后台的时候清理内存图片缓存,应用结束的时候清理过期图片。 1. SDWI 也提供了 `UIButton+WebCache` 和 `MKAnnotationView+WebCache`,方便使用。 1. `SDWebImagePrefetcher` 可以预先下载图片,方便后续使用。 [1]:https://github.com/rs/SDWebImage <file_sep>/_posts/2020-02-15-patch-notes.markdown --- layout: post title: Patch Notes date: 2020-02-15 23:32:03 +0800 --- 1. Create patch file: `diff -u file1 file2 > name.patch`, or `git diff > name.patch` 1. Apply path file: `patch [-u] < name.patch` 1. Backup before apply patch: `patch -b < name.patch` 1. Validate patch without apply: `patch --dry-run < name.patch` 1. Reverse applied path: `patch -R < name.patch` <file_sep>/_posts/2014-04-21-performance-optimization.markdown --- layout: post title: "Performance on Optimization" date: 2014-04-21 22:39:35 +0800 --- <NAME>: > Premature optimization is the root of all evil. 高性能的程序是一个程序员应该有的追求,但是过早的性能优化往往起到反作用,浪费时间,拖慢进度等等。如何尽量少的优化投入同时达到高性能? 1. 一个高性能框架,赢在起跑线,比如 `ngx_lua`。 1. 一套成熟高效的技术架构解决方案,比如 Tornado + PostgreSQL + Redis。 1. 一开始就按照最佳实践写代码,把常规需要优化的地方降到最少。 1. 不要只局限于软件层,硬件升级往往比软件优化更给力,比如 SSD。 <file_sep>/_posts/2009-12-31-the-only-2009.markdown --- layout: post title: "唯一的二零零九" --- 每一天是唯一的,每一年是唯一的,过去了就不能再回头来过,更何况是对我很有意义的 2009 年,那唯一的二零零九。 年初,由于考研不理想,开始着手找工作。现在回想三月份和四月份的日子,只能用失败形容,那段时间一直在怀疑自己大学四年是个失败,甚至怀疑自己的人生是个失败。去年整个就业大环境很不好,今年年底时候学校官方有个统计,截至到十二月份,学院就业率 37%,而去年同期只有 9%。这个数字是可信的,去年年前我们班整个只有三个人签约。在大环境不好的情况下,公司招人都少,这样像自己这样学习只能算中等的毕业生很少有机会的。另一方面,在找工作的时候我自己的准备不足,不说别的,毕业设计开始的太晚,而之前好几家公司面试的问题在我进行毕业设计时候都有学到,用到。在这种状态下找工作真的不容易,面试一个失败一个,所以四月下旬时候我选择逃离学校那个氛围,到郑州丫头的小窝里“蜗居”,找一丝安慰。BTW,人精神状态不好的时候,肯定会影响身体,那段时间,我一下子瘦了十五斤,是啊,没心思吃饭,睡觉失眠,怎么吃怎么瘦,吃再多也白搭。 五一时候回家了一趟,大学四年第一次五一、十一假期回家。因为 CHAOFEI 参军三年,终于转士官可以休探亲假,三年多兄弟们没见肯定要聚聚的。那次聚会真真切切是兄弟们最后的一次青春酒,工作后感触更深啊。那天晚上我们都喝高了,我跟 BEI 打地铺睡觉时候说了很多话,前三个月的郁闷无助失落终于发泄了一下,趁着酒劲终于不再失眠。那天晚上是兄弟们几年来最 High 的一次吧,只可惜 XIAOJIE 由于时间紧没有赶回来,残缺美。 五一回家聚会是主要原因,另外就是跟爸妈交代一下找工作的情况,让他们安心一下。爸妈都是老实的农民,没啥门路,所以爸老说我找工作这事他使不上劲,干着急。临走的那天晚上跟爸说话到深夜,工作这事让他们不用太担心,肯定会有的,就算专业不对口,苦力活,毕业时候我都会找个地方把自己安顿下来,长大了已经,你们不用太操心,我这样跟爸妈说。那晚也把丫头跟爸妈说了一下,爸说谈恋爱这事家里不会过多干涉我,一切都由我自己拿主意。 再次回到学校就开始忙毕业设计。英文翻译,开题报告,查资料写设计书,学习了很多东西,Java Web 开发流程,Struts 框架应用,MVC 开发模式,Servlet 机制等等。只可惜我学的太晚了,之前有公司面试问的就是这些东西,而那时我却不懂。 六月初的时候,我终于把自己卖了,一家对日外包的公司。紧接着就是毕业前的各种饭局酒场,尽自己最大可能跟宿舍的人同吃同玩,联机打游戏,晚上卧谈到两三点,去新区看看我们大一大二时候的宿舍,再吃一顿新区食堂,等到分别的时候,我们只有不舍。走之前我一个人在宿舍收拾东西,看着一片狼藉的宿舍,忍不住嚎嚎大哭,大学生活结束了,我们的青春结束了。 没有太多时间留给我感伤。七月开始实习培训,日语,业务,凭着自己还算好的基础慢慢给拿下,工作一步一步的上手,可以在老大的帮助下做一些简单的项目模块。付出就有回报,十月份,有幸在第一批次转正。算上实习,工作也有半年了,自己要学的东西还有很多,还得努力。 八月中旬,丫头公司倒了,就来到我这里。没钱我们也可以一起逛超市逛街,两个人啃一个烤玉米,周末我们去爬山,在家下厨捞面条,煮饺子。虽然刚开始很辛苦,但是两个人只要在一起就是最好的,什么都不怕。上个月丫头通过试用期工作也安顿下来,生活是越来越好的。两个人在一起难免会吵架闹别扭,爱你乖,能在一起感觉很幸福。 09 年就过去了,来年还得继续努力。来几个小计划吧: 1. 工作再进一步,争取再过半年能带几个人; 2. 日语,逼自己去学; 3. 自己做些东西,不管大小,重要的是去做; 4. 减肥到 150 以下,为了健康减肥; 5. 挣钱! <file_sep>/_posts/2017-05-31-ssh-add-k.markdown --- layout: post title: Fix "Enter passphrase for key" on macOS date: 2017-05-31 14:38:15 +0800 --- You will be asked 'Enter passphrase for key' when doing SSH operation: > Enter passphrase for key '/Users/fannheyward/.ssh/id_rsa': On macOS you can fix this by `ssh-add -K`. <file_sep>/_posts/2019-11-13-how-to-activate-noise-cancellation-with-one-airpod.markdown --- layout: post title: How to Activate Noise Cancellation with One AirPod date: 2019-11-13 10:00:41 +0800 --- `Settings` - `Accessibility` - `AirPods`, toggle on `Noise Cancellation with One AirPod`. AirPods Pro 开启单只降噪:设置 - 辅助功能 - AirPods,打开 `一只 AirPod 入耳时使用降噪`。 <file_sep>/_posts/2009-06-26-graduated.markdown --- layout: post title: "毕业了" --- > 校内上、QQ上满眼都是毕业这些伤感文字,所以我决定不在校内、QQ上写关于我毕业的东西,平静的离开。——Heyward 2009-06-15 16:22:53 毕业,不想搞的太过于压抑,所以我选择平静地毕业,不在校内、QQ 写毕业的文字,不传毕业的照片。流水帐一下毕业前这一段日子。时间戳是按我 Twitter 上的顺序来的。 1. 论文定稿。答辩PPT开始。——2009-06-09 周二 16:59:02 2. 答辩PPT搞定,明天提交导师。接下来几天的任务就是完善论文,准备一下讲稿,等待下周答辩。——2009-06-10 周三 04:28:28 3. PPT邮件给了老师。——2009-06-10 周三 13:00:23 4. 论文二改。——2009-06-11 周四 14:44:51 5. 收到导师论文三改意见。——2009-06-12 周五 14:44:13 6. 准备睡觉,明天答辩日,加油!——2009-06-14 周日 23:59:45 7. 答辩进行时,我排倒数第二个,估计得到十一点半了。——2009-06-15 周一 08:12:11 8. 毕设答辩不在于你做的咋样,在于你师傅是谁。哎,有师傅现场替你强出头,怕啥…——2009-06-15 周一 09:20:09 9. 答辩结束,个人感觉不错。答辩组提了两个问题,都有准备到——2009-06-15 周一 11:42:12 10. 大改论文格式,顶不住了,学校一个论文标准,学院一个论文标准,答辩后又来一个。。——2009-06-15 周一 14:44:58 11. 毕业设计论文工作的一大收获就是 word 的轻车熟路,整篇改格式那速度也是嗖嗖的。——2009-06-15 周一 15:19:02 12. 宿舍内部喝酒,很爽!——2009-06-15 周一 22:22:38 13. 买好车票,晚上回郑州。——2009-06-16 周二 11:01:19 14. 散伙饭途中。——2009-06-16 周二 17:06:32 15. 跟大一时候的辅导员道歉了,了了一个心愿。——2009-06-16 周二 20:31:59 16. 散伙饭最后阶段,说话。——2009-06-16 周二 20:34:35 17. 我完整的吃完了散伙饭,恩,等会火车回去。——2009-06-16 周二 22:10:03 18. 晚点20分到郑州。——2009-06-17 周三 08:25:17 19. 开车前五分钟赶上火车。——2009-06-18 周四 22:18:26 20. 六级,喔…——2009-06-20 周六 18:32:23 21. 起早租房去——2009-06-21 周日 08:46:50 22. 预订了一套房子,还算没白跑一天——2009-06-21 周日 17:23:31 23. 搞定,回家去——2009-06-21 周日 20:16:18 24. 毕业前最后一次集体活动:回新区,看新区——2009-06-22 周一 09:26:32 25. 新区图书馆草地上来了场二B群研讨会——2009-06-22 周一 10:54:35 25. 东风广场现场直播——2009-06-22 周一 11:23:20 26. 新区二食堂吃饭——2009-06-22 周一 11:48:22 27. 包场唱歌,疯狂吧——2009-06-22 周一 12:56:01 28. 提前离场,晚上大家接着搞——2009-06-22 周一 16:17:18 29. 转帐搞定,回新区吃酒去。——2009-06-22 周一 17:41:25 30. 夜游翡翠湖——2009-06-22 周一 19:56:20 31. 安大排排坐——2009-06-22 周一 20:32:27 32. 拿到学士服了——2009-06-23 周二 16:55:36 33. 晚上我们几个又喝酒一把。——2009-06-23 周二 22:06:59 34. 起早,操场,毕业典礼——2009-06-24 周三 07:27:35 35. 2009届毕业典礼开始,介绍各个没见过的校领导。——2009-06-24 周三 07:27:35 36. 徐枞巍校长致辞:建设祖国;持续学习;社会成长;报答父母。——2009-06-24 周三 07:44:33 37. 毕业典礼结束,回去换上学士服参加学位授予仪式。——2009-06-24 周三 07:57:02 38. 两分钟前,接过了我的学位证。——2009-06-24 周三 11:15:35 39. 毕业了。——2009-06-24 周三 11:46:18 就这么毕业了。越到最后越舍不得,尽自己最大可能的跟大家在一起,吃饭,夜宵,烧烤喝酒,新区回忆,K 歌……这两天就开始陆陆续续的送同学离开,来个拥抱,送上车,挥挥手,兄弟们都一路顺风! 毕业了,要开始工作了,尽管自己现在的工作不够好,工资少的要命,以后的发展前景也不知道会怎么样,但也得慢慢来,一步一步的,不曾放弃。 毕业了,纪念一下自己的大学,记住我们在一起开心的日子,期待我们再次相遇的日子。 <file_sep>/_posts/2009-10-29-drunken.markdown --- layout: post title: "醉酒" --- 相当龌龊。醉的连家都不知道在哪。 记住:可以喝酒,但不要醉酒。因为丫头会担心,会心疼。 还有:决不再抽烟!发誓! <file_sep>/_posts/2015-11-30-monthly-review-201511.markdown --- layout: post title: Monthly Review 2015-11 date: 2015-11-30 22:41:54 +0800 --- 1. 代码产出依然是业务驱动。除了常规维护,一个展示型网站用 Go 模版做服务端渲染,挺好用。 2. 主服务上了 HTTPS,这是第一步,后面跟进 HTTP/2。 3. 带实习生,零基础,效果很差。 4. 参加 OpenRestyConf,唯一收获是见了春哥真人,感受春哥的技术学习方法。 5. 开发以外的工作增加,主要是运营管理安排。运营关键就是找对那个人。 6. 周末回家,六六现在和妈妈亲。两天还是太赶,只能在家一晚上。 7. 向阳也做爸爸了。 8. 11.30,科比宣布赛季结束后退役。 <file_sep>/README.markdown https://fann.im <file_sep>/_posts/2009-04-29-moblie-phone-requirements-analysis.markdown --- layout: post title: "我的手机需求分析" --- 我想换个手机,给自己做个买手机的需求分析吧。 1. 手机最重要的功能是电话,最基本的要求是稳定,让别人给你打电话的时候能随时的找到你(当然欠费停机的情况除外)。稳定的要求就是信号能力强,不能因为楼太高阻碍一下信号或者信号弱一点的地方就不能用,这一点排除掉那些做工不好的山寨机,不是偏见,春节去外公家,小山沟信号确实不好,我的诺基亚 5070 还有两格信号,姨父那个不知道名字的手机完全没有信号。 2. 稳定还有一个要求就是待机。待机时间不能太短,至少要有个三五天,不然一时忙的忘了充电会误事。这一点上好多山寨机完全把品牌机给比下去了,有的待机一个月没问题。当然待机时间长短跟你怎么用有很大关系,要是一天24小时的用手机听歌谁都撑不住。 3. 稳定的前提是好用。好用这个要求就因人而异了,键盘好用,输入法好用,按键舒服,耳机、充电器、数据线等外设好用。这个来说品牌机有很大优势,很多大牌手机的人性化设计就非常不错。 4. 功能上,我的要求不多,当然不能只打电话发短信,至少要能上上网,看看电子书什么的,毕竟都有排队、等人这种需要打发一下时间的时候。手机上网的另一个用处就是在没有电脑而又紧急需要的时候可以上网查东西。 5. 多媒体应用。我把这些独立于功能单独说。手机多媒体应用主要有手机拍照,听音乐,看视频等,当然还有 3G 以后的网上电视,视频电话等。这方面我的需求是有最好,但不要求很高。像手机拍照,现在差不多都是 500W 像素起步,有的甚至带专业相机的闪光灯,价钱不低。其实手机拍照就类似于手机上网,随便拍照玩玩,或者是是特定情况下的急用,比如看见一个好场景随手拍下来,毕竟很少有人随身带着单反数码。对手机的拍照不能按专业相机的要求来对待,需求不一样,再强大的手机拍照也难比专业相机啊。 听歌看视频也是同样道理,有这些功能最好,毕竟单独带个手机要比手机+mp3+mp4 要方便的多,但是不能强求专业音频视频播放器那样的高标准高要求。 6. 手机操作系统。当然,我想要个智能机。智能机的好处就是他的扩展性,可定制性,适合喜欢折腾的人。现在主流的手机 OS 主要有诺记的 Symbian(俗称SB),微软的 Windows Mobile(WM),Linux,Palm,黑莓OS,苹果 iPhone 的 iOS,当然还有 Google Android 等等。诺记的 SB 算是很大众化的,街机嘛,相信群众没错的;个人原因吧,对 WM 一直兴趣不大,WM 的软件异常丰富,但是响应速度上不大好,也没有怎么接触过 WM,手生;Linux 和 Palm 接触的也很少,不过听说 Palm 的系统非常不错,尤其是马上要出的基于 Web OS 的 Palm Pre,评价相当高;黑莓 BB 最近很热,可玩度很高,可就是一直没摸过真机;iPhone 大红大紫两年多了,10 亿次的 APP 下载量,不过 iPhone 的定位应该是一个网络终端,尤其强调网络应用功能,电话功能相对较弱,好像还没有短信转发吧?Android,Google 牵头,影响力自然非凡,不过现阶段 Android 系统还不够强大,真机也很少,也许明年会出现井喷,一大堆 Android 手机将会出现。目前对我来说,我的选择是:诺记 SB > BB > iPhone > Android > … 7. 键盘外观上大致有传统的数字九键,字母全键盘和现在非常火的触摸屏三种,当然还有全键+触摸屏的。个人倾向于全键盘手机,对触摸屏兴趣不大,感觉用指头去滑动操作不踏实,也许没有亲手用过像 iPhone 这样非常牛逼的触摸屏手机吧,体会不到触摸屏的好处。 8. 手机外形上也是大致有直板,翻盖和滑盖三种,我自己倾向于直板手机。这个就像不喜欢触摸屏一样,就是对翻盖、滑盖手机无爱,就是喜欢直板,天生的,:-) 大致需求就是这样。现在市场上符合我的需求的手机不少,个人比较中意的有这几款: - Nokia E71/E63,区别就是 E63 是 E71 的缩水版,只有 200W 像素的相机,没有 GPS,但是性价比高很多; - BlackBerry 9000/8900,主要区别就是 8900 不是 3G 手机,而 Bold 9000 是 3G 手机,现在的黑莓王。 这几款手机都是商务手机,稳定性都很不错,娱乐功能相对中等,Symbian S60 和黑莓系统的扩展性都很不错,黑莓手机的人性化设计更突出一些。剩下的就是钱的问题,手机经费没有,一切都是空谈啊。 <file_sep>/_posts/2012-11-22-modern-ios-development.markdown --- layout: post title: "Modern iOS Development" date: 2012-11-22 15:00 --- iOS 开发是一个进化非常快的技术领域,每年一更新的 iOS SDK 都会带来很多新东西,所以如果你现在用着和一年前一样的 code 做产品,虽然功能上没有差别,但是从技术上来说自身的成长进步非常有限。简单总结一下现在比较 modern 的开发方式。(截至 2012 年底) ### ARC iOS SDK 5 引进来的 ARC 已经非常成熟,是时候用了。ARC 可以大大减少各种不小心造成的内存泄漏,减少各种费脑子的内存问题 debug,这时候再手动内存管理完全是给自己增加工作。现在主流第三方库都已经 ARC ready 了,迁移成本很小。 ### Blocks 并不是说 delegate 有多不好,用 blocks 封装的接口使用起来非常轻便,尤其是网络请求等需要异步操作的时候,简单明了。 ### New Objective-C Literals 参考 [New Objective-C Literals][1]: ``` objc NSInteger _appid = 12345; NSArray *array = @[ @"title", @(_appid)]; NSString *title1 = array[0]; array[0] = @"newTitle"; NSDictionary *dict = @{ @"appid" : @(_appid), @"title" : _title, }; NSString *title2 = dict[@"title"]; NSNumber *intNum = @123; NSNumber *floatNum = @1.23f; NSNumber *boolNum = @YES; ``` 掌握新语法并不能说明技术能力有多高,但可以减少很多体力劳动,不需要敲很多 `objectAtIndex:` `objectForKey:`,代码结构也更为清晰。 ### @Synthesize by Default 以前: ``` objc @interface Person : NSObject { NSString *_name; } @property (nonatomic, strong) NSString *name; @end @implementation Person @synthesize name = _name; @end ``` 现在: ``` objc @interface Person : NSObject @property (nonatomic, strong) NSString *name; @end @implementation Person @end ``` Xcode 4.4+ 会自动做 @synthesize,成员变量都可以不用手动声明,直接下划线开头 _var 形式。一来节省代码量,二来鼓励用 property,Always use accessor methods, [Except in initializer methods and dealloc.][2],保证健壮性。 ### Modern Library and Tools iDev 免不了要用到很多第三方库,这时候最好选用那些较新且成熟的库,是否支持 ARC 等。比如 AFN vs ASI,我个人非常喜欢 [AFN][3] 的设计,简单方便易扩展。 第三方库多了管理就是问题,现在有了 [CocoaPods][4] 一切变得都很简单,团队之间的分享协作也会方便很多,不会出现两边因为公共库版本不一致带来 bug 问题。 参考: * WWDC 2012 Session 405 - Modern Objective-C * WWDC 2012 Session 413 - Migrating to Modern Objective-C. [1]:https://fann.im/blog/2012/11/21/new-objective-c-literals/ [2]:https://fann.im/blog/2012/08/14/dont-use-accessor-methods-in-init-and-dealloc/ [3]:https://fann.im/blog/2012/08/21/afnetworking-notes/ [4]:https://fann.im/blog/2012/10/31/cocoapods-notes/ <file_sep>/_posts/2019-11-27-github-actions-canceled-unexpectedly.markdown --- layout: post title: GitHub Actions Canceled Unexpectedly date: 2019-11-27 09:31:22 +0800 --- By default, GitHub will cancel all in-progress jobs if if any `matrix` job fails. Set `fail-fast: false` to fix this. - <https://help.github.com/en/actions/automating-your-workflow-with-github-actions/workflow-syntax-for-github-actions#jobsjob_idstrategyfail-fast> - <https://github.community/t5/GitHub-Actions/Build-got-was-canceled-unexpectedly/m-p/31748#M887> <file_sep>/_posts/2014-12-01-monthly-review-1411.markdown --- layout: post title: "Monthly Review 2014-11" date: 2014-12-01 10:22:17 +0800 --- 工作: 1. 依然是 BDD(Business-driven Development, 业务驱动开发),完成了三个大功能,已上线的基本没有返工,符合自己的标准。 2. BDD 往往是结果导向,产品前端的需求不一定会考虑到对后端系统带来的改变和压力。如果需求确定后才发现不可为或代价太大,开发会带着情绪去做,这不是好事。 3. 所以开发要尽量早的参与到前期讨论,分析可能会带来的问题,考量开发性价比,对不合理或不清楚的需求能及时反馈,甚至拒绝。 4. 需求-开发-上线-监测-分析,往往进行到上线就结束了,这样很难判断这次开发的价值,以后类似的需求还要不要做? 5. 开发性价比是最近在思考的一个问题,有没有必要 100% 实时?一个需求要三个系统增加开发值不值得? 生活: 1. 保持一个月回一次家的频率,发现同车还有很多这样的人。 2. 视频叫六六会抬头瞅着屏幕笑,然后低头看着音箱找人…… 3. 深圳卫视的《极速前进》真人秀节目很好看,推荐。 4. 老婆最近每天加班到八九点,相比之下我真的太懒散了。搞活动买的牛肉吃了两个星期,这么冷的冬天晚上有萝卜炖牛肉真的很幸福。 <file_sep>/_posts/2009-09-02-the-project-type-is-not-supported-by-this-installation.markdown --- layout: post title: "The project type is not supported by this installation 解决" --- VS2005 打开 .slu 文件(Microsoft Visual Studio Solution File)时提示 `The project type is not supported by this installation`,Google 得[解决方案](http://social.msdn.microsoft.com/Forums/en-US/windowsworkflowfoundation/thread/d8b6dddc-914c-4b78-b0bf-03408c251b9e): 1. Download and install special VS2005 update to support WAP, VS80-KB915364-X86-ENU 2. Download and Install WAP add-on VS80sp1-KB926601-X86-ENU Done <file_sep>/_posts/2014-02-10-gitlab-with-docker.markdown --- layout: post title: "Install GitLab with Docker" date: 2014-02-10 23:38 --- [GitLab][1] 是个非常不错的 GitHub clone,很适合团队自建 git 服务器。但是由于 GitLab 是个 RoR 应用,加上 gitlab-shell 的权限要求等等,GitLab 的部署甚是麻烦。 [Docker][2] 简单说就是基于 LXC 的类 VM 方案,当然比 Virtual Box 等 VM 要高效、省资源,应用和依赖打包成一个容器,很方便部署。 用 Docker 部署 GitLab 首先要找一个可用的镜像(image): ``` sudo docker search gitlab ``` 选用 [sameersbn/gitlab][3],原因是更新较快,文档详细,支持 `-e` 设置环境变量,基本上不需要修改安装配置。 省事的话直接 `sudo docker pull sameersbn/gitlab` 即可,或者: ``` git clone https://github.com/sameersbn/docker-gitlab.git cd docker-gitlab 添加 HOST /root/.ssh/id_rsa.pub 到 authorized_keys,这样可以免密码从 HOST 登录 Container。 sudo docker build -t fannheyward/gitlab . ``` build 完成后启动: ``` sudo docker run -p 22:22 -d \ -e "SMTP_USER=<EMAIL>" -e "SMTP_PASS=<PASSWORD>" \ -e "GITLAB_EMAIL=<EMAIL>" -e "GITLAB_SUPPORT=<EMAIL>" \ -e "GITLAB_SIGNUP=true" \ -e "GITLAB_HOST=gitlab.host.com" \ -v /opt/gitlab/data:/home/git/data \ -v /opt/gitlab/mysql:/var/lib/mysql \ fannheyward/gitlab ``` * `-e` 用来设置一些环境变量,最少要把 `GITLAB_HOST` 设置,不然所有项目的 git 地址为 `git@localhost`。 * `-v [host-path]:[container-path]` 用来把 HOST 文件夹挂载到 Container 用来保存数据,不然 Container 重启或者关停后数据就会丢失,前面是 HOST 目录,后面是 Container 目录,不要写反。 * `-p 22:22` 是把 Container 的 22 端口映射到 HOST 22 端口,HOST 22 改为其他,这样 git ssh 操作的时候方便一些。 在 HOST 上可以通过 `ssh 172.17.0.2` 登录 Container,IP 地址可以通过 `docker inspect c8c2997b9bc4|grep IPAddress` 获取。在 Container 里可以做任何修改,安装软件等,修改后在 HOST `sudo docker commit c8c2997b9bc4 fannheyward/gitlab:v1` 提交保存,这样重启 Container 不会丢失修改。 Done。数据备份和升级参考 [sameersbn/gitlab][3] 文档。 [1]:https://github.com/gitlabhq/gitlabhq [2]:https://www.docker.io/ [3]:https://github.com/sameersbn/docker-gitlab <file_sep>/_posts/2010-06-09-qiut-the-job.markdown --- layout: post title: "离职" --- 辞职申请已经提交上去了。接下来就是工作交接一下,然后进行相关手续办理。 这是我离开校门的第一份工作,去年 7 月到现在,差不多一年的时间。老大刚才说:你走了,我少了一员干将。感动。 这一年来最大的收获就是工作态度,认真,能静下心沉得住气。这让现在的我比刚出校门的那个毛头小子成熟不少,办事稳当不少。 感谢老大这一年对我的信任,能让我有信心去独立项目完成。感谢组里的几个兄弟的支持帮助。 下一步,新的一步,加油! <file_sep>/_posts/2012-03-04-grand-central-dispatch-sample.markdown --- layout: post title: "Grand Central Dispatch Sample" date: 2012-03-04 22:26 --- 说来惭愧,做 iDev 一年多了,最近才第一次在正式项目中使用 GCD。做个笔记。 Grand Central Dispatch(GCD) 是苹果 iOS 4 推出的任务调度机制,把不同的任务分配给不同的 queue 来处理,非常适合异步任务,支持多核处理器,比 performSelectorInBackground 这种线程调度有更好的处理性能,而且配合 Blocks 使用非常方便。 ```objc dispatch_queue_t bgQueue = dispatch_queue_create("im.fann.bgQueue", NULL); // or dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // or dispatch_queue_t bgQueue = dispatch_get_global_queue(0, 0,); for short dispatch_async(bgQueue, ^{ ...// load data from server dispatch_async(dispatch_get_main_queue, ^{ // dispatch_get_main_queue get back to the main queue to update UI. You can only change UI in main queue. [rootTableView reloadData]; }); }); ``` 非常棒的 GCD 系列教程: - [Intro to Grand Central Dispatch, Part I: Basics and Dispatch Queues][1] - [Intro to Grand Central Dispatch, Part II: Multi-Core Performance][2] - [Intro to Grand Central Dispatch, Part III: Dispatch Sources][3] - [Intro to Grand Central Dispatch, Part IV: Odds and Ends][4] [1]:http://www.mikeash.com/pyblog/friday-qa-2009-08-28-intro-to-grand-central-dispatch-part-i-basics-and-dispatch-queues.html [2]:http://www.mikeash.com/pyblog/friday-qa-2009-09-04-intro-to-grand-central-dispatch-part-ii-multi-core-performance.html [3]:http://www.mikeash.com/pyblog/friday-qa-2009-09-11-intro-to-grand-central-dispatch-part-iii-dispatch-sources.html [4]:http://www.mikeash.com/pyblog/friday-qa-2009-09-18-intro-to-grand-central-dispatch-part-iv-odds-and-ends.html <file_sep>/_posts/2018-02-01-bash-set.markdown --- layout: post title: Bash Set notes date: 2018-02-01 14:28:49 +0800 --- 1. `set -u` 不存在的变量报错中止 2. `set -e` 发生错误时中止 3. `set -x` 打印输出要执行的命令<file_sep>/_posts/2010-11-07-all-in-1-ringtones-box.markdown --- layout: post title: "All-IN-1 Ringtones Box" --- App Store link first: **[All-IN-1 Ringtones Box](http://itunes.apple.com/us/app/all-in-1-ringtones-box/id398357284?mt=8)** > All-IN-1 Ringtones Box gives you more than 500 ringtones in 12 categories. 这是我参与开发的第一个 iOS App,客户端有三分之一的代码量吧。 整体架构设计,细节代码完成质量都有很多收获;而且写 App 不是完成之后扔到 App Store 就够了,要把自己当成一个普普通通的用户,不停的去使用 App,琢磨哪里还有改进的地方,一步一步的迭代完善。 App 开发的创意很重要,运营也同样重要,要重视用户的反馈,根据用户的反馈有针对性地进行改进。 <file_sep>/_posts/2013-09-20-nsurlconnection-in-scrolling.markdown --- layout: post title: "NSURLConnection 在页面滑动时继续执行" date: 2013-09-20 11:04 --- 这篇笔记只是为了清掉 BlogTodos,实际开发中用了 AFN 等是不会遇到这个问题。当然也可以作为原理理解。 首先是 NSRunLoop,我的理解 runloop 就是 iOS 的消息循环处理机制,响应处理各种消息事件。runloop 有不同的执行模式,不同模式下只会响应处理该模式类型的事件。App 运行时会有一个主线程 mainRunLoop,在程序中可以用 `[NSRunloop currentRunLoop]` 简单获取当前的 runloop。 NSURLConnection 在网络请求的时候(无论主线程还是子线程),如果有点击或滑动界面,网络请求会被暂停执行,直到滑动等操作结束。这是因为 NSURLConnection 默认是 `NSDefaultRunLoopMode`,也就是说只会在该模式下执行,当有滑动、点击界面等操作的时候,runloop 会切换到 `NSEventTrackingRunLoopMode` 来处理界面操作,这时候网络请求就会被暂停执行,直到界面操作结束,runloop 模式切换回去。 解决方法就是设置 NSURLConnection 的执行模式为 `NSRunLoopCommonModes`,这样就会在所有模式下持续执行: ```objc [connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; ``` [NSRunLoop Class Reference][2]: > NSDefaultRunLoopMode - The mode to deal with input sources other than NSConnection objects. > NSRunLoopCommonModes - Objects added to a run loop using this value as the mode are monitored by **all run loop modes** that have been declared as a member of the set of “common" modes. 参考 [NSURLConnection: How to avoid blocked file loading during scrolling of UIScrollView or UITableView][1] [1]:http://www.pixeldock.com/blog/how-to-avoid-blocked-downloads-during-scrolling/ [2]:https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/doc/uid/20000321-SW1 <file_sep>/_posts/2010-09-16-usr-bin-env-python-vs-usr-local-bin-python.markdown --- layout: post title: "#!/usr/bin/env python vs #!/usr/local/bin/python" --- > `#!/usr/bin/env python` Will figure out the correct location of python and make that as the interpreter for rest of the script. > `#!/usr/local/bin/python` Pointing to python is located at /usr/local/bin/python. 简单说 /env python 就是查找系统环境变量中的 python 并默认选择 path 里第一个。/usr/local/bin/python 就是指定使用这个路径下的 python,可能不同机子不同环境下 python 位置稍有差别,就有可能 /usr/local/bin/python 不存在。 via [Here](http://mail.python.org/pipermail/tutor/2007-June/054816.html) <file_sep>/_posts/2009-07-04-recent-things.markdown --- layout: post title: "近况" --- 仅仅是冒泡。 先是工作。毕业,然后紧紧的就是搬家,置办生活用品,买了单车,因为七月一号就开始实习上班培训了。刚开始这三天由于电脑还没有到位,所以连着三天都是日语培训。经理又一直强调着加快速度,一天时间结束了“五十音图”,然后差不多每天是50个单词加语句的速度往下走。这三天后的感觉就一个字:累。但是累也要咬紧牙关,毕竟这已经是参加工作了,跟在学校时候的学习还不一样,没有退路的说,学不好,就请走人,没有商量的余地。牵扯到自己以后的去路,必须要加把劲,哪怕是死记硬背也要拿下。 生活上嘛,跟两个同学合租,房子还好,基本的生活用品都有,热水器也是房东新装上的,我们自己买了柴米油盐就可以开工做饭。大家的手艺都还凑合,刚开始时候掌握不了咸淡,饭菜都是先吃到肚子里再中和一下咸淡。男生做饭就是大手大脚的,20块一壶油吃了三天就见底了。。得学会节省啊,毕竟是过日子的,大手大脚的可不行。 因为刚开始比较忙,事情比较多,还没来得及去搞宽带。没有网络基本上就是与世隔绝了,还好我还有手机包月上网,虽然速度实在是慢的可以,不过上个 Twitter 还是可以的。有了 Twitter 这扇窗户,还可以了解一下世界的嘛。Firefox 3.5 正式版放出,出了些很有名的门,真是闭关一日,世事万年啊。 接下来就是赶紧把宽带搞上,然后加油培训学习,下周开始就开始专业上的一些东西了,要加油! <file_sep>/_posts/2010-03-18-calm-down.markdown --- layout: post title: "静下心去思考" --- 静下心的去思考程序,调试是最能锻炼学习能力的方法。 细小的地方要注意留心,同时要有大局观,整个函数的运行逻辑,整个项目系统的运行,都很重要。跳出来就会发现其实是自己给自己上套。 <file_sep>/_posts/2013-07-31-salary.markdown --- layout: post title: "salary" date: 2013-07-31 17:35 --- > 当一个人觉得自己还有特别大进步空间的时候,说明他的薪水也还有特别大的进步空间。by @Linn <file_sep>/_posts/2012-10-31-cocoapods-notes.markdown --- layout: post title: "CocoaPods Notes" date: 2012-10-31 14:24 --- [CocoaPods][1], an Objective-C library dependency manager. ---- 安装: ``` sudo gem install cocoapods pod setup //初始化更新 Specs ``` 新建项目,在项目 **根目录** 新建 `Podfile` 文件: ``` platform :ios, '5.0' pod 'AFNetworking' pod 'SDWebImage', :git => 'https://github.com/appwilldev/SDWebImage.git' pod 'JSONKit', :podspec => 'https://raw.github.com/gist/1346394/1d26570f68ca27377a27430c65841a0880395d72/JSONKit.podspec' ``` Podfile 可以指定具体代码地址,具体一个 commit/tag,或者具体 podspec (多用于私有库)。安装相关 Pods: ``` pod install ``` CocoaPods 会新建一个和项目同名的 workspace,以后就用这个 workspace 来打开项目。需要新加或删除库的话就直接编辑 Podfile 然后再 `pod install`. ---- 添加 [CocoaPods/Specs][2] 没有或私有库: ``` pod spec create WeiboEngine https://github.com/fannheyward/WeiboEngine // 如果指定 Github 链接,会获取代码库相关信息来初始化 podspec. ``` 自动生成 `WeiboEngine.podspec` 文件,按照模板编辑修改相关作者、项目主页等信息。重点是 `s.source` 设置。`s.source` 指定代码库地址,支持 git/hg/svn 代码库,支持 http://example.com/source.zip 代码压缩包,支持用 `:tag` `:commit` 指定具体版本。`s.source_files` 指明代码目录文件。 验证生成的 podspec 文件是否合法正确: ``` pod spec lint WeiboKit.podspec ``` 验证通过后把 podspec 保存在 `~/.cocoapods/master/` 即可直接通过 `pod install` 进行安装;也可以向 [CocoaPods/Specs][2] 提交新建的 spec: ``` pod setup --push pod push master ``` [1]:https://github.com/CocoaPods/CocoaPods [2]:https://github.com/CocoaPods/Specs <file_sep>/_posts/2015-08-28-cut-nginx-log-in-time.markdown --- layout: post title: 根据时间自动切分 Nginx.log date: 2015-08-08 11:29:45 +0800 --- 之前是用[脚本][1]配合 crontab 来做日志切分: ``` #!/bin/bash # This script run at 00:00 # The Nginx logs path logs_path="/usr/local/webserver/nginx/logs/" mkdir -p ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/ mv ${logs_path}access.log ${logs_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")/access_$(date -d "yesterday" +"%Y%m%d").log kill -USR1 `cat /usr/local/webserver/nginx/nginx.pid` ``` 最近发现可以直接在 nginx.conf 里通过 `$time_iso8601` 提取时间进行设置: ``` if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})") { set $year $1; set $month $2; set $day $3; } access_log /var/log/nginx/$year-$month-$day-access.log; ``` 时间粒度可以更为精细: ``` if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})") { set $year $1; set $month $2; set $day $3; set $hour $4; set $minutes $5; set $seconds $6; } ``` via [Log rotation directly within Nginx configuration file][2] [1]:http://blog.zyan.cc/nginx_php_v6/ [2]:http://www.cambus.net/log-rotation-directly-within-nginx-configuration-file/<file_sep>/_posts/2014-02-11-docker-notes.markdown --- layout: post title: "Docker 笔记" date: 2014-02-11 23:06 --- 所有 docker 操作都需要 root 权限,需要加 sudo: ``` docker search gitlab ``` 搜索服务镜像(image),挑选有 **TRUSTED** 标示的,相对好一些。 ``` docker pull NAME ``` 下载相应镜像,由于 index.docker.io 被墙,需要梯子,下载会很慢。 ``` docker build -t NAME . ``` 在当前目录根据 Dockerfile 构建容器,`--rm` 自动删除 build 中间状态的容器。 ``` docker run -i -t -p 8080:80 NAME ``` 运行一个 Container,支持的参数: * `-d` Detached 或者 daemon mode,后台运行。 * `-i -t` 开一个 tty 终端,保持交互模式,这两个一般共同使用。 * `-e` 设置环境变量参数,参考 [Install GitLab With Docker][1]。 * `-p [host_port]:[container_port]` 映射 HOST 端口到容器,方便外部访问容器内服务,host_port 可以省略,省略表示把 container_port 映射到一个动态端口。 * `-v [host-path]:[container-path]` 把 HOST 文件夹挂载到 Container 用以保存数据。 * `--rm` 自动删除已运行存在的相同 IMAGE 的容器。 ``` docker attach --sig-proxy=false CONTAINER ``` attach 后台运行的容器,加上 `--sig-proxy=false` 参数可以通过 `Ctrl+C` detach,不然一旦 attach 就没办法取消。 ``` docker commit --run='COMMAND' -m 'message' CONTAINER IMAGE:tag ``` 登录容器做一些修改,退出到 HOST 保存修改到镜像,或者直接在 HOST 通过 `--run` 给正在运行的容器发送命令并保存到镜像。 ``` docker stop/start/restart/kill/rm CONTAINER ``` 停止、重启、杀死、删除容器。 ``` docker ps -a -q ``` 列出当前运行的容器,`-a` 会列出所有,包括已停止的,`-q` 只列出容器 ID。`docker ps -a -q | xargs docker rm` 可以删除所有未运行的容器。 ``` docker logs -f CONTAINER ``` 查看容器运行日志。 ``` docker cp CONTAINER:/PATH HOSTPATH ``` 拷贝容器内文件或文件夹到 HOST。目前只支持 Container 到 HOST 的单向拷贝,HOST 到 Container 可以通过 insert 命令。 ``` docker insert IMAGE URL PATH ``` 将 URL 文件内容写入相应 PATH,这个操作不修改原来 IMAGE 内容,而是再它的基础上新建一个 IMAGE. ``` docker images ``` 列出已安装的镜像。可以通过 `docker rmi IMAGE` 删除镜像。 ``` docker inspect CONTAINER | grep IPAddress ``` 检查容器配置,包含内部 IP 等信息。 更多可参考 [Docker 文档][2]。 [1]:https://fann.im/blog/2014/02/10/gitlab-with-docker/ [2]:http://docs.docker.io/en/latest/ <file_sep>/_posts/2011-06-11-change-or-be-changed.markdown --- layout: post title: "Change or Be Changed" --- 也许我无力改变世界,但至少我能坚持自己,不被世界改变。 <file_sep>/_posts/2014-06-30-self-review-at-half-year-2014.markdown --- layout: post title: "2014 年中总结" date: 2014-06-30 17:21:57 +0800 --- ### 工作 > 看似做了很多,但没有明确成绩。 回看上半年工作,第一感觉就是这样。 服务端目前主要负责移动社区程序的功能开发和维护。年初花了点时间进行服务器迁移和优化,这半年社区在稳定性、速度上有了一点改进,包括新功能开发上基本满足客户端需求,为社区用户扩张提供了技术支持和保障。但是过于后端的开发往往给人的感觉就是看不到成绩,很多东西也没法用数字量化,只有在服务出问题的时候才会显现一下,也许这就是后端开发最大的寂寞吧。 客户端没有具体的应用开发,唯一能拿出手的就是对 Background Fetch 简单做了技术探索然后封装 SDK 使用,积累了静态库经验后协助几个内部服务 SDK 封装,方便使用。对于 iOS 7 以来新加的大部分 API 依然是停留在理论学习,缺乏实际项目实践。偶尔帮忙解决一些问题,不足一提。 技术上在前端开发有一些进步,实践了 Grunt/Gulp 开发流程,JS 水平有提升,虽然还是很菜,顺带对 Node.js 有了更多的了解和实践,下一步可以在具体项目中实战一下。用 Docker 搭建内部 GitLab 并尝试推进 Git 开发流程规范,目前来看效果还可以,下一步打算引入持续集成(CI)实践。 产品能力提升有限,这个和自己的工作重心有很大关系,目前还是希望以技术为主,然后平时要多注意参加产品讨论进行学习。 ### 生活 产检让我切身体验了医院的挂号排队,医疗资源的分配不均是主要原因。北京的医疗条件是好,但要我们在北京生产却很不现实,一个很大的原因就是房子,家里来人照顾住哪?继续单间合租肯定不行,换大房子开销就要翻倍,所以还是决定回老家生。 送老婆回家之前还是换了房子,来北京四年第一次搬家。住是北漂怎么都绕不过去的一个问题,一直说不考虑房子的情况下在北京其实挺好,现实是你怎么可能忽视掉这个每天要待十小时的地方?现在住自如,略高于市场均价,好处是服务还不错,没有无良中介的打扰。 六月二十四日六六出生,女孩,很好看,但是过程很辛苦,老婆很辛苦,妈妈是最伟大的。我第一次手术通知书签字,那两个小时真的很难熬,紧张,焦虑,不安,却又不能垮,因为你是家里的顶梁柱,你得撑起来。这时候不会想你的工作你的收入你的事业甚至你的理想,只希望她们能健康。 老婆,我爱你,希望我们的六六健康成长。 <file_sep>/_posts/2009-12-07-ask-myself.markdown --- layout: post title: "Ask Myself" --- Q: 看着高中、大学同学一个个在准备着考研、托福、GRE、出国等等深造,你还满足于自己现在的状况?够吃饭够花销的工资,没啥深入学习的工作,真的满足吗? 等着你的 Answer. <file_sep>/_posts/2022-12-15-git-worktree-notes.markdown --- layout: post title: Git Worktree Notes date: 2022-12-15 23:10:18 +0800 --- `git worktree`,不切换 git 分支,又在多个分支同时工作。 - `git worktree list` list all worktree - `git worktree add [-b <new-branch>] <path> [<commit-ish>]` create a worktree at path and checkout commit-ish into it - `git worktree remove <worktree>` remove the special worktree - `git worktree prune` prune dirty infos <file_sep>/_posts/2008-08-30-killed-by-baidu.markdown --- layout: post title: "被百度K了" --- 27号开始断网,学校又不知道搞什么东西,到昨天晚上才可以上网,上博客看了一下,准备写点啥东西。无聊中site:hanghang.name了一下,Google正常,百度“抱歉,没有找到与“site:hanghang.name” 相关的网页”,-_-|||,被K了。 其实老早都知道百度会莫名其妙的K站,但是搞到自己身上实在是搞不懂为啥被百度给K了。好像没有说百度坏话吧?没有作弊吧?没有Hack、SEX、DU等等这些内容吧?都是些自己日记加一点网络应用的东西,犯不着K我吧?试着找了一下原因,各个链接查了一下,有一个链接貌似被K了,不知道跟这个有没有关系,先把他的链接去掉,重新向百度提交了一下,等等再说吧,莫名其妙的。 其实现在的流量小的可怜,Google统计里面显示67%的是从搜索引擎过来的,期中百度173次,48.06%,Google,包括google.cn,186次,51.67%,稍稍占优势。不过在国内,中文站里面,百度还是很重要的,得罪了他基本上算是半死了。但是 **被百度K貌似每个站成长必须付出的代价**,原因很多,更多的是你不知道的,你就是那案板上的鱼,砍你的时候你还得祈求他K的准点,不然多K几次更受不了。 算了,反正就一个人博客,本来就没打算做多大,自己自娱自乐的就够了,被K了不要紧,自己该写还写,写东西不一定是要别人看,关键是这个过程,自己学习总结的时候其实也是对知识升华提炼的时候,肚子里有货跟讲出来还是有一定距离的,就这吧。 Update:080901,今天百度恢复了收录. <file_sep>/_posts/2011-02-17-something-of-mobile-networking.markdown --- layout: post title: "Something of Mobile Networking" --- 1. Apple 制订了 Mobile Networking 的规则,而且是在五年前 iPhone 出来的时候就制定了。 2. 现在新出的手机,如果没有大屏触摸,已经死了一半;如果没有 App Store,已经死了。 3. iPhone 出来后,大家都很惊艳。后续的都想做 iPhone Killer,标榜自己更好的屏幕,更好的触摸,更好的硬件,更好的 App 开发,等等。但是这些都在 iPhone 制定的游戏规则内玩。按照他定的规则玩,还不是被玩么。 4. 何况五年前 iPhone 出来的时候宣称自己领先业界五年,现在看来,对 Android 依然保持一个摩尔定律 18 个月的领先优势,对 Windows Phone 7,保守三年优势。 5. Google 不会任由 Apple 控制移动发展,所以跟进了 Android App 抗衡 iOS App 路线。另外,Google 大力推行网页应用,Web App Store 路线,也就是 Chrome OS。两手抓,两手硬,以此来对付 Apple。 6. Google 的云计算长远来看也应该是 Chrome OS 的一部分。 7. Apple 在 App 路线保持着领先,也不会任由 Google 在 Web 应用上搞标准,所以也大力支持 HTML5。MobileMe 的下一步应该也会向 Web App Store 转型。不大可能是 Chrome OS 级别,但会是在用户应用方面跟进更多,MobileMe + iTunes Online。 8. 微软 Windows Phone 7 很不错,至少界面上不像 Android 那样一看就是一个 iOS Clone。问题是 App 市场的跟进,Windows Live 的移动整合。 9. 总起来看,Mobile Networking 就是 Native App 和 Web App 的发展。而整个 mobile networking 的发展,也就是这三大巨头的游戏。 <file_sep>/_posts/2008-07-10-going-home.markdown --- layout: post title: "放假回家" --- ``` Another winter day Has come and gone away in either Paris or Rome and I wanna go home I miss you , you know Let me go home I’ve had my run baby Im done I gotta go home Let me go home It’ll all be alright I’ll be home tonight I’m coming back home ``` 回家,一个小时后出发。我是真的想家了。。。 <file_sep>/_posts/2008-05-23-unrivaled-lyric.markdown --- layout: post title: "搞怪一下:《女友嫁人新郎不是我》无敌版歌词" --- [女友嫁人新郎不是我](http://music.baidu.com/search?key=女友嫁人新郎不是我),印度歌,虽然听不大懂,不过调子非常不错。昨天听歌时候千千静听自动下了歌词,无意间看到,被雷了。。。无敌版: ``` 阿kei苦力猴亚猴奔 迪哒鲁工嘎猴打黑 改sei改红灭欧呀啦也 bia里给sei猴打黑 ``` 再来看一下原版翻译过来的吧: ``` 我深爱着你的人 无力清醒无力沉睡 我该怎么来告诉你呀 爱情到底是什么 ``` <file_sep>/_posts/2008-03-07-ubuntu-config-3.markdown --- layout: post title: "ubuntu个人配置(三)" --- 1. 清楚安装软件后的垃圾 `dpkg -l |grep ^rc|awk '{print $2}' |tr ['\n'] ['']|sudo xargs dpkg -P` 2. 修改默认启动 `sudo gedit /boot/grub/menu.lst` 修改中间的 default 4//从第0行开始。 3. 文泉驿字体 xfonts-wqy 压缩的pcf格式,而pcf.gz格式的字体,特别是在显示中文这样的大字符集时,系统渲染速度比较慢。把字体文件解压可以大大提高显示速度,方法为 ``` cd /usr/share/doc/xfonts-wqy sudo gunzip wenquanyi*pcf.gz sudo rm fonts.dir fonts.scale fonts.cache* sudo mkfontdir . sudo cp fonts.dir fonts.scale sudo fc-cache -fv ``` <file_sep>/_posts/2009-11-27-ai-had-retired.markdown --- layout: post title: "A.I. 退役" --- Allen 宣布退役了,伤感。 <NAME> 是最接近于神的人,A.I. 可以算是最亲近于人的神。 See you. <file_sep>/_posts/2009-06-09-happy-birthady-to-mama.markdown --- layout: post title: "妈,生日快乐" --- 今天是妈生日,妈,生日快乐。您和爸身体健康是儿子现在最大的心愿。 <file_sep>/_posts/2019-06-30-regex-unicode.markdown --- layout: post title: Regex Unicode Scripts date: 2019-06-30 17:33:59 +0800 --- 1. `\p{Han}` 匹配中文、日语文字,支持简繁体。 1. `\p{Common}` 匹配符号 1. `\p{Latin}` 匹配拉丁语系 1. 需要 grep perl 支持,即 `grep -P "\p{Han}"`,或者 `rg/ag`. ```sh echo '中文/繁體/片仮名/かたかな/カタカナ/katakana' | rg "\p{Han}" > 中文 繁體 片仮名 echo '<EMAIL>' | rg "\p{Common}" > @ . echo '<EMAIL>' | rg "\p{Latin}" > mail com ``` [Unicode Scripts](https://www.regular-expressions.info/unicode.html#script) for more. <file_sep>/_posts/2019-09-17-google-code-review-guide.markdown --- layout: post title: Google Code Review Guide date: 2019-09-17 14:14:24 +0800 --- - [The Change Author’s Guide](https://google.github.io/eng-practices/review/developer/) - [The Code Reviewer’s Guide](https://google.github.io/eng-practices/review/reviewer/) 0. 原则:给出技术上的建议,而不是个人偏好 1. 写一个好的 commit: 1. 第一行,改动的简短摘要 2. 空行 3. 详细提交信息 2. 小修改,多提交 1. 方便 review/merge/roll back 2. 利于好的代码设计,减少 bug 3. Code review 看什么? 1. 设计 2. 功能实现是否正确,以及复杂度 3. 测试 4. 命名,注释,代码风格,文档等 4. 尽早 review,尽快 review 5. 好的 code review comment 1. Be kind 2. 只指出问题,让开发人员自己决定怎么修改 3. **Encourage developers to simplify code** <file_sep>/_posts/2018-05-15-dmidecode.markdown --- layout: post title: dmidecode date: 2018-05-15 15:48:28 +0800 --- You can use `dmidecode` to display server **physical** info, for example RAM max capacity. ``` dmidecode -t 16 Handle 0x0032, DMI type 16, 15 bytes Physical Memory Array Location: System Board Or Motherboard Use: System Memory Error Correction Type: Multi-bit ECC Maximum Capacity: 48 GB Error Information Handle: Not Provided Number Of Devices: 6 ```<file_sep>/_posts/2022-12-31-self-review-2022.markdown --- layout: post title: "[self review:2022];" date: 2022-12-31 14:32:19 +0800 --- ## C - H 项目延期导致亏损,直接影响就是团队裁员 - 项目中间进行变更,痛苦的过程最后有点无厘头的结束,结论:不是所有人都认真关注你关注的,大差不差即可,时间会帮助你 - 和聪明但流程贪婪的人做生意,结果就是被吃干抹净 - 全年收获:团队,认可 <file_sep>/_posts/2008-09-03-google-chrome.markdown --- layout: post title: "Google Chrome的感受" --- 昨天一放出话就让一堆人兴奋讨论,不过大多数都是专业用户,普通用户没人关心这个。刚才下了安装,感受了一下。 1. 果然是才用在线安装。通过Google Update下载安装,没法直接下载安装包。 2. 果然是默认装载C盘,而且不能呢个更改。不得不说是Google细节上考虑的不够。 3. 默认在当前标签打开新页面,不方便,还不知道在哪里更改。 4. 关闭最后一个标签时候自动关闭浏览器,Orz。 5. 没有广告过滤,遗憾。也可以理解,beta嘛,希望以后有。 6. 对Google自家的东西打开貌似都挺快的,尤其是Gmail,估计跟所谓的Javascript V8引擎有关。 亮点:浏览器任务管理器功能,快捷键shift+esc,可以查看整个浏览器和各个标签内存、cpu、网络占用情况。 亮点二:about:memory 算是另一个亮点吧,单独开一个chrome时候会提示: > Note: If other browsers (IE, Firefox, Opera, Safari) are running, I'll show their memory details here. 再开一个IE或者Fx的话,会把两个浏览器的放在一起进行对比,这个明显是挑逗嘛! 更大的亮点:每个标签是一个独立进程,可以在about:memory查看每个标签进程的PID,这个按说是个好事,不过后果就是当你开了一堆标签时候在系统任务管理器中间就会看到一堆一堆的chrome...Orz。 Update:刚发现另一个比较不错的,可以把标签做成一个应用程序快捷方式,单独显示在一个精简窗口。这不就是Fx的Prism嘛,-_-||| 不得不说,挺失望的现在,尝尝鲜还行,用着的话还不够啊,beta嘛,加油吧,还是看好Google的这个东西,毕竟东西多了对咱来说是个好事嘛。暂时还是Fx,chrome二房候补,the world三房,上支付宝专用,IE?不知道在哪,等IE8出来可能尝尝吧,现在没兴趣。 <file_sep>/_posts/2018-10-12-nginx-log-to-rsyslog.markdown --- layout: post title: OpenResty/Nginx 日志输出到 Rsyslog date: 2018-10-12 10:48:10 +0800 --- 在 OpenResty/Nginx 开发中,日志输出一般是这么两种方案: 1. 通过 `ngx.log(ngx.ERR, ...)` 输出到 error.log 2. `log_by_lua` 阶段通过 [lua-resty-logger-socket][1] 输出到远端 syslog-ng 服务器 第一种方案方便开发,但是会和常规 error.log 比如 404等混在一起。第二种方案可以把日志分开,但需要日志服务器,也不方便开发的时候逐步 log,多用于日志收集分析。回到方案一,可以通过 `rsyslog` 将日志切割到独立文件,方便排查。 nginx: ``` error_log syslog:server=127.0.0.1,tag=nginx_crit; or error_log syslog:server=127.0.0.1,tag=nginx_crit crit; ngx.log(ngx.CRIT, ...) ``` rsyslog: ``` module(load="imudp") input(type="imudp" port="514" ruleset="ngx_ruleset") template(name="json" type="list") { constant(value="{") constant(value="\"timestamp\":\"") property(name="timereported" dateFormat="rfc3339") constant(value="\",\"host\":\"") property(name="hostname") constant(value="\",\"tag\":\"") property(name="syslogtag" format="json") constant(value="\",\"message\":\"") property(name="msg" format="json") constant(value="\"}") constant(value="\n") } ruleset(name="ngx_ruleset"){ if $msg contains 'lua' then { /var/log/ngx_lua.log stop } if $programname == 'nginx_crit' { /var/log/ngx_lua.log stop } action(type="omfile" file="/var/log/ngx.log" template="json") } ``` * [Logging to syslog](http://nginx.org/en/docs/syslog.html) * [rsyslog](https://www.rsyslog.com/doc/v7-stable/configuration/filters.html) * [Rsyslog configuration: forwarding log files with file names, handle multi-line messages, no messages lost on server downtime, failover server][2] [1]: https://github.com/cloudflare/lua-resty-logger-socket [2]:https://selivan.github.io/2017/02/07/rsyslog-log-forward-save-filename-handle-multi-line-failover.html <file_sep>/_posts/2012-02-29-happy-birthday-to-my-blog.markdown --- layout: post title: "Happy Birthday to my Blog" date: 2012-02-29 17:16 --- 四年前的今天写了 [Hello World!][1],希望能一直写下去。 Happy Birthday. [1]:https://fann.im/blog/2008/02/29/hello-world/ <file_sep>/_posts/2008-08-17-xiaonei-app-hfut-news.markdown --- layout: post title: "校内APP:Hfut_News" --- 重新玩校内,玩的要不一样,自己的第一个校内APP应用。校内的APP平台开发现在也还是刚刚开始,连API文档都还没有完全弄好,好多人都是自己摸索开发学习。照着别人的教程自己也弄了个APP,其实根本不能算是APP,因为只是个静态网页。。。 Hfut_News,合肥工业大学新闻中心,一个静态网页的校内APP程序。用的是Google reader分享输出。也就是先自己订阅了新闻,然后分享输出,Google自己做了一个JS,可以把分享输出贴到自己的网页上,我就是写了个静态网页,然后加上Google的输出,最多也就看着CSS美化了一下页面,over。原理很简单,可以说没有啥技术含量的东西,基本上三分钟就可以搞定,可是我还是弄了差不多一天时间。大言不惭的去申请开发许可API Key,然后安装到校内,中间步骤参考官方指导。然后就开始去拉人,下一步就是厚着脸皮去提交应用,不过貌似审核标准里有一条:对于过于简陋的App暂时是不会通过的。我这个东西也就自己一个人自娱自乐的玩玩吧。 虽然很是弱智的一个小东西,收获还是有的,至少我知道了padding: 5px 10px 0 5px;后面这四个参数是按上-右-下-左的顺序来进行填充的。不过这样的东西实在是拿不出手,所以考虑学习一下动态编程,怎么说做一个校内APP也得加上xnml API函数吧,不然可太不象话了。 <file_sep>/_posts/2011-04-20-zen-in-quicksilver.markdown --- layout: post title: "Quicksilver-道" --- Quicksilver about 里面有一段老子的话: > 为无为 事无事 味无味 > 大小多少 报怨以德 图难于其易 为大于其细 > 天下难事 必作于易 天下大事 必作于细 <file_sep>/_posts/2010-02-07-notes-of-start-blackberry.markdown --- layout: post title: "入手黑莓小记" --- 那天在 Twitter 上看见 @wangguan 年关促销一批黑莓,突发奇想的想入一个玩,于是就入了一个 8700,准确的型号是 BlackBerry 8705g。用了差不多两个星期,随便写两句。 - 全键盘确实很爽,尤其是写英文的时候。自带的中文输入法有点类似微软拼音,熟悉后准确率在 80% 以上,当然,自带的输入法没有点讯爽快,不过点讯默认切换中英文输入法的快捷键跟 QuickWheel 冲突,暂时放弃。 - 机子是 4.2 的 ROM,暂时没有刷 4.5,各方面情况都非常稳定,虽然只有 64M 内存,除去系统占用也就30M 左右的空闲内存,但是运行速度很快。 - 自带的浏览器很方便,各种快捷键,不过不能 番羽土啬,配上 4.2 改键 Opera,爽快。 - 黑莓的人性化设计真叫人舒服,各种快捷键设计,尤其是英文系统下快捷键更多更爽。 - 因为是两三年前的机子,再加上 RIM 一直都是重商务轻娱乐,所以 8700 没有摄像头,不能存储卡,但是纯手机应用的话,完全没有问题。 - 黑莓很容易让人低头沉迷。 <file_sep>/_posts/2013-08-31-terminal-vim-paste-indent-error.markdown --- layout: post title: "终端下 Vim 粘贴缩进错乱" date: 2013-08-31 11:02 --- 终端下 Vim 粘贴代码时会有缩进错乱,原因是终端下的 Vim 是通过模拟用户输入来完成粘贴操作,所以缩进就错乱了。解决方法是每次粘贴前 `set paste`,完成后 `set nopaste`,嫌麻烦的话可以设置一个快捷键来切换 paste 状态 `set pastetoggle=<F2>`. 另外 Vim 下 Ctrl-C 和 ESC 根本不是一码事,Ctrl-C 不会响应 InsertLeave,所以 `autocmd InsertLeave * setlocal nopaste` 在 Ctrl-C 时是不会执行的。 <file_sep>/_posts/2008-05-07-kobe-is-mvp.markdown --- layout: post title: "KOBE is the MVP!" --- 12年轮回终于修得真果,完成了男孩到男人的锐变,8号到24号,不变的是你的执着! <file_sep>/_posts/2012-06-06-postnotificationname-with-gcd.markdown --- layout: post title: "postNotificationName with GCD" date: 2012-06-06 18:23 --- 用 GCD 在后台线程进行下载任务,下载完成后通过 `NSNotificationCenter` post 一个消息出来,这时候要注意 `postNotificationName:` 必须要回到主线程进行,不然会引发 crash. ```objc dispatch_async(dispatch_get_main_queue(), ^{ [[NSNotificationCenter defaultCenter] postNotificationName:AnyNotification object:nil]; }); ``` <file_sep>/_posts/2010-10-22-is-destiny.markdown --- layout: post title: "命运乎" --- 你现在的生活是你三年前的选择和努力所决定的,而你现在的选择和努力又会决定你三年后的生活会是个什么样。 所以,你现在晚上加班到十点吃不上饭,没啥可抱怨的,你要为你三年前所荒废的时间付出代价;我们也没有必要更没有权利去同情可怜谁,这是他之前轻视自己生命的代价。 这就是命。 对过去的生活我们已无能为力,但是对我们以后的生活,我们还可以选择,还可以通过自己的努力去改变。你可以成为一个很成功的商人,或者是一个上市公司的 CXO,或者是你自己创业当老板,享受别人对你的一呼百应。 这同样是命。 不同的只是你对待他的态度。老天爷都是公平的,你得到多少,你就要失去多少;你享受多少,就要遭罪多少。 <file_sep>/_posts/2009-04-22-say-bye-to-mutombo.markdown --- layout: post title: "再见,穆大叔" --- 只为跟大叔说声再见。 今天火箭输了,季后赛第二场。只有些许的不爽,但是火箭还有机会,现在只不过 1:1。不过对于穆大叔,就没有机会了。由于受伤,大叔的职业生涯提前结束,大叔说: > 我必须抬头挺胸,没有失望,没有后悔,我像士兵般离开。 大叔称的上一名伟大的士兵,球场上的荣誉无需多言,每个人都会记住那高高摇起的手指;球场下,大叔一个人的力量让世界知道了自己国家的存在。 穆大叔的全名:迪肯贝·穆托姆博·姆博洛多·穆卡姆巴·简恩·杰奎·瓦姆托姆博,<NAME> M<NAME> <NAME>. <file_sep>/_posts/2010-10-17-install-memcache-on-ubuntu-for-discuz-x.markdown --- layout: post title: "Ubuntu 安装 Memcache 支持 Discuz X" --- 安装 Memcached 和 php-memcache 模块: > `sudo apt-get install memcached php5-memcache` 默认安装后会自动在 php.ini 添加启用 extension=memcache.so 运行 memcached(-d启动守护进程,-m指定memcached内存): > `memcached -d -u root -m 64 -l 127.0.0.1 -p 11211` **重启 apache**: > `sudo /etc/init.d/apache2 restart` or `sudo service apache2 restart` 为安全起见可以先测试一下 memcache。 配置 Discuz! X 使用 Memcacha 内存优化,修改 config/config_global.php > `$_config['memory']['memcache']['server'] = '127.0.0.1';` Done. <file_sep>/_posts/2010-09-08-sql-len-function-in-mysql.markdown --- layout: post title: "SQL LEN function in MySQL" --- SQL: The LEN() function returns the length of the value in a text field. > `SELECT LEN(column_name) FROM table_name` BUT: in MySQL LEN() does NOT work,it's called LENGTH(). > `SELECT * FROM table_name WHERE LENGTH(column_name) < 5` via [1](http://w3schools.invisionzone.com/index.php?showtopic=31715) [2](http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length) <file_sep>/_posts/2012-07-13-multiple-select-in-uitaleview.markdown --- layout: post title: "UITaleView 多选" date: 2012-07-13 10:13 --- 效果就是 cell.contentView 右移,左侧留一空圆,点击选中,再点取消选中。 `[_rootTable setEditing:YES animated:YES];` 进入多选,然后实现 delegate: ```objc - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath { // 关键所在 return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (tableView.editing) { if (_dataArray && [_dataArray count]>indexPath.row) { NSDictionary *dict = [_dataArray objectAtIndex:indexPath.row]; [_pickedArray addObject:dict]; } } } - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath { if (tableView.editing) { if (_dataArray && [_dataArray count]>indexPath.row) { NSDictionary *dict = [_dataArray objectAtIndex:indexPath.row]; [_pickedArray removeObject:dict]; } } } ``` <file_sep>/_posts/2010-11-03-talking-rule.markdown --- layout: post title: "对话守则" --- 1. 对话的目的是寻求真理,不是为了斗争。 2. 不做人身攻击。 3. 保持主题。 4. 辩论时要用证据。 5. 不要坚持错误不改。 6. 要分清对话与只准自己讲话的区别。 7. 对话要有记录。 8. 尽量理解对方。 via @[zuola](https://twitter.com/zuola). <file_sep>/_posts/2014-03-21-upgrade-nginx-on-the-fly.markdown --- layout: post title: "平滑升级 Nginx" date: 2014-03-21 17:19:35 +0800 --- Nginx 可以在不中断服务的情况下平滑升级,很是方便。 1. 安装新版 Nginx,如果旧版本是编译安装可以通过 `nginx -V` 查看编译参数。默认会安装在同一目录,旧版本重命名为 nginx.old。 2. `kill -USR2 old_nginx.pid`,old_nginx.pid 会被重命名为 nginx.pid.oldbin,然后用新版 nginx 启动全新 master 和 worker。 3. 现在新旧版本会同时服务,共同处理请求保证服务的不间断。`kill -WINCH old_nginx.pid` 来逐步关闭 old worker。 4. 待 old worker 完全退出,新版本工作没有问题,用 `kill -QUIT old_nginx.pid` 完全退出旧版,nginx.pid.oldbin 会被自动更新为 new_nginx.pid,升级完成。 5. 如果新版本有处理失败,需要回滚旧版,用 `kill -HUP old_nginx.pid` 重新启动 old worker,`kill -QUIT new_nginx.pid` 退出新版本。 More: * [Upgrading To a New Binary On The Fly][1] * [Controlling nginx][2] [1]:http://wiki.nginx.org/CommandLine#Upgrading_To_a_New_Binary_On_The_Fly [2]:http://nginx.org/en/docs/control.html <file_sep>/_posts/2012-05-23-hide-extra-separators-bellow-uitableview.markdown --- layout: post title: "隐藏 UITableView 下不需要的分割线" date: 2012-05-23 19:03 --- `UITableViewStylePlain` 样式下的 UITableView 如果显示分割线,就会在 tableView 下显示额外的空白 cell 和分割线。在 SO 上发现一个小技巧来解决这个问题 [Eliminate Extra separators below UITableView - in iphone sdk?][1] ``` UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.width, 1)]; v.backgroundColor = [UIColor whiteColor]; [self.tableView setTableFooterView:v]; ``` [1]:http://stackoverflow.com/a/1789714/380774 <file_sep>/_posts/2008-04-13-ttt-daili.markdown --- layout: post title: "买了通通通付费代理" --- 学校封国外网站,还有好多的国内网站的IP也在封锁行列,好多优秀的网站跟咱就绝缘了,要想上,找代理!毕竟免费的代理太难弄了,以前宿舍一哥们买了通通通的付费代理,用过一段,感觉挺不错的,速度也行。后来人家的时间到期了,又不能老是用别人的,毕竟这个是要掏钱的,就想着自己买一个用用。买的是50块的小时卡,算下来20000多分钟,先用着,老想上外网耍耍,:-) <file_sep>/_posts/2009-08-12-whether-two-dates-diff-a-month.markdown --- layout: post title: "判断两个日期是否相差一个月" --- 昨天老大给的一个帐票项目练习,其中需要对入账日和出账日两个日期进行判断,如果相差在一个月以上,修改入账日。在日期判断的地方学到了一个很新颖而且很简单的方法,记录一下。 思路:将两个日期转换为整形数字格式,比如 20090709 和 20090812 两个日期,然后将日期相减,如果差值大于100,说明两个日期相差一个月以上。这个方法是以一个月30天为准。 <file_sep>/_posts/2015-11-10-redis-crack.markdown --- layout: post title: Redis Crack date: 2015-11-10 23:10:40 +0800 --- > [http://www.antirez.com/news/96](http://www.antirez.com/news/96) 昨天一服务器被黑,从 auth.log 发现有陌生 IP 居然可以通过 public key 登录,排查后发现是因为 Redis 不规范使用造成的: 1. root 启动了 redis 实例,默认端口 6379,没有 bind IP,没有 auth 验证 2. 被扫描到可以远程登录,`config set dir /root/.ssh` 修改数据保存路径,`config set dbfilename "authorized_keys"` 修改数据保存文件名 3. 把 key 写入 redis,bgsave,即可用 key 登录 简单威力大。修复预防: 1. 禁止 root 启动 redis 2. Bind IP,本机+内网就可满足绝大数服务 3. 修改默认端口 4. 开启 auth 验证 <file_sep>/_posts/2013-03-01-nsmutableattributedstring-notes.markdown --- layout: post title: "NSMutableAttributedString Notes" date: 2013-03-01 11:48 --- Core Text 针对文本段落支持的样式属性: ``` objc typedef CF_ENUM(uint32_t, CTParagraphStyleSpecifier) { kCTParagraphStyleSpecifierAlignment = 0, kCTParagraphStyleSpecifierFirstLineHeadIndent = 1, kCTParagraphStyleSpecifierHeadIndent = 2, kCTParagraphStyleSpecifierTailIndent = 3, kCTParagraphStyleSpecifierTabStops = 4, kCTParagraphStyleSpecifierDefaultTabInterval = 5, kCTParagraphStyleSpecifierLineBreakMode = 6, kCTParagraphStyleSpecifierLineHeightMultiple = 7, kCTParagraphStyleSpecifierMaximumLineHeight = 8, kCTParagraphStyleSpecifierMinimumLineHeight = 9, kCTParagraphStyleSpecifierLineSpacing = 10, /* deprecated */ kCTParagraphStyleSpecifierParagraphSpacing = 11, kCTParagraphStyleSpecifierParagraphSpacingBefore = 12, kCTParagraphStyleSpecifierBaseWritingDirection = 13, kCTParagraphStyleSpecifierMaximumLineSpacing = 14, kCTParagraphStyleSpecifierMinimumLineSpacing = 15, kCTParagraphStyleSpecifierLineSpacingAdjustment = 16, kCTParagraphStyleSpecifierLineBoundsOptions = 17, kCTParagraphStyleSpecifierCount }; ``` 使用方法:新建一个样式 `CTParagraphStyleSetting`,设置样式属性和相关值,然后添加到 NSAttributedString. ``` objc NSMutableAttributedString *attriStr = [[NSMutableAttributedString alloc] initWithString:string]; // 样式1: 两端对齐 CTTextAlignment alignment = kCTJustifiedTextAlignment; CTParagraphStyleSetting alignmentStyle; alignmentStyle.spec = kCTParagraphStyleSpecifierAlignment;//对齐属性 alignmentStyle.valueSize = sizeof(alignment); alignmentStyle.value = &alignment; // 样式2:行间距 CGFloat lineSpaceMax = 4.0f; CTParagraphStyleSetting lineSpaceStyleMax; lineSpaceStyleMax.spec = kCTParagraphStyleSpecifierMaximumLineSpacing;//最大行间距属性 lineSpaceStyleMax.valueSize = sizeof(lineSpaceMax); lineSpaceStyleMax.value = &lineSpaceMax; CGFloat lineSpaceMin = 1.0f; CTParagraphStyleSetting lineSpaceStyleMin; lineSpaceStyleMin.spec = kCTParagraphStyleSpecifierMinimumLineSpacing;//最小行间距属性 lineSpaceStyleMin.valueSize = sizeof(lineSpaceMin); lineSpaceStyleMin.value = &lineSpaceMin; CGFloat lineSpaceAdjust = 2.0f; CTParagraphStyleSetting lineSpaceStyleAdjust; lineSpaceStyleAdjust.spec = kCTParagraphStyleSpecifierLineSpacingAdjustment; lineSpaceStyleAdjust.valueSize = sizeof(lineSpaceAdjust); lineSpaceStyleAdjust.value = &lineSpaceAdjust; // 样式3:最大行高 CGFloat lineHeightMax = 18.0f; CTParagraphStyleSetting lineHeightMaxStyle; lineHeightMaxStyle.spec = kCTParagraphStyleSpecifierMaximumLineHeight;//最大行高属性 lineHeightMaxStyle.valueSize = sizeof(lineHeightMax); lineHeightMaxStyle.value = &lineHeightMax; // 样式数组 CTParagraphStyleSetting settings[]={ alignmentStyle, lineSpaceStyleMax, lineSpaceStyleMin, lineSpaceStyleAdjust, lineHeightMaxStyle }; CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(settings, 5); [attriStr addAttribute:(id)kCTParagraphStyleAttributeName value:(__bridge id)paragraphStyle range:NSMakeRange(0, [attriStr length])]; CFRelease(paragraphStyle); // Emoji、中文、英文混排 NSDictionary *fontAttributes = @{ (id)kCTFontFamilyNameAttribute : @"Helvetica", (id)kCTFontCascadeListAttribute : @[ (__bridge id)CTFontDescriptorCreateWithNameAndSize(CFSTR("AppleColorEmoji"), 0), (__bridge id)CTFontDescriptorCreateWithNameAndSize(CFSTR("ZapfDingbatsITC"), 0), ] }; CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes((__bridge CFDictionaryRef)(fontAttributes)); CTFontRef font = CTFontCreateWithFontDescriptor(descriptor, FONT_SIZE, 0); [attriStr addAttribute:(id)kCTFontAttributeName value:(__bridge id)font range:NSMakeRange(0, [attriStr length])]; CFRelease(font); // 字体颜色 [attriStr addAttribute:(id)kCTForegroundColorAttributeName value:(id)FONT_COLOR.CGColor range:NSMakeRange(0, [attriStr length])]; ``` <file_sep>/_posts/2012-08-14-dont-use-accessor-methods-in-init-and-dealloc.markdown --- layout: post title: "Don't use accessor methods in init and dealloc" date: 2012-08-14 11:53 --- 苹果在 WWDC 2012 Session 413 - Migrating to Modern Objective-C 里强调不要在 init 和 dealloc 里使用 accessor methods: > Always use accessor methods. Except in initializer methods and dealloc. 之前没有注意过这种情况,稍微搜索学习了一下。文档 [Memory Management][1] 里确实有这说法: > The only places you shouldn’t use accessor methods to set an instance variable are in initializer methods and dealloc. 提倡下面这种写法: ```objc - (id)init { self = [super init]; if (self) { _count = [[NSNumber alloc] initWithInteger:0]; } return self; } - (id)initWithCount:(NSNumber *)startingCount { self = [super init]; if (self) { _count = [startingCount copy]; } return self; } ``` dealloc 不能用比较好理解,self.property 是向 property 发了一个消息,有可能该对象的生命周期已经结束,不能再接受消息。init 不能用比较靠谱的说法是如果有 subClass 并重载了 accessor,那么 init 里 self.property 就无效;另外也可能会有其他影响,比如 KVC notifications 等。 SO 参考帖子: 1. [Should I refer to self.property in the init method with ARC?][2] 1. [Using properties to access iVars in init?][3] 1. [Initializing a property, dot notation][4] 1. [Objective-C Dot Syntax and Init][5] [1]:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html#//apple_ref/doc/uid/TP40004447-SW4 [2]:http://stackoverflow.com/a/8056260/380774 [3]:http://stackoverflow.com/a/4091119/380774 [4]:http://stackoverflow.com/a/5932733/380774 [5]:http://stackoverflow.com/a/3150906/380774 <file_sep>/_posts/2008-02-29-hello-world.markdown --- layout: post title: "Hello world!" --- 2008年2月29号,自己的独立Blog终于上线了,2月29日,四年一遇的日子,也算是阴差阳错吧,拖了小半年时间才弄好这么一个小窝,希望自己能把它坚持到下一个2月29日,给自己的名字过个生日。 <file_sep>/_posts/2010-06-27-leave-school-for-1-year.markdown --- layout: post title: "毕业一年了" --- 准确说应该是昨天,6 月 26 日离开学校整一年。 结束三高的一年,我来到北京,继续我的努力。 我,还在路上。 <file_sep>/_posts/2011-04-05-firefox-addons.markdown --- layout: post title: "Firefox addons" --- Add to Search Bar 版本:2.0 AutoProxy 版本:0.4b1.2011033016 Copy Link Text 版本:1.5.0 JSONView 版本:0.5 Easy DragToGo+ 版本:1.1.3.1 Tab Mix Lite 版本:4.0.1 Vimperator 版本:3.0 Flashblock 版本:1.5.14.2 Text Link 版本:4.0.2011021601 Adblock Plus 版本:1.3.5 DownThemAll! 版本:2.0.2 一键取所有 addons 方法: http://alphatown.douban.com/widget/forum/2011653/discussion/37964853 <file_sep>/_posts/2012-11-06-ios-url-loading-system.markdown --- layout: post title: "iOS URL Loading System" date: 2012-11-06 10:37 --- iOS 整个网络请求系统分为这几部分: * URL Loading: * NSURLRequest / NSMutableURLRequest * NSURLResponse / NSHTTPURLResponse * NSURLConnection * Cache Management * NSURLCache * NSCachedURLResponse * Authentication and Credentials * NSURLCredential * NSURLCredentialStorage * NSURLAuthenticationChallenge * NSURLAuthenticationChallengeSender * NSURLProtectionSpace * Cookie Storage * NSHTTPCookie * NSHTTPCookieStorage * Protocol Support * [NSURLProtocol][2] * NSURLProtocolClient 参考 [URL Loading System Overview][1]. [1]:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html [2]:http://nshipster.com/nsurlprotocol/ <file_sep>/_posts/2008-09-18-jinhansi.markdown --- layout: post title: "金汉斯腐败归来" --- 其实原本打算不是去金汉斯的,因为招行有一个美食节活动,美食节的店半价优惠。研究了一下,加州烤肉正好也在名列,去!半价才17块5,自助,多实惠。专门找同学要了一张招行的卡,下午4点多就出发过去了,因为怕人多。结果,5点钟到的时候已经爆满了!加州烤肉显然没想到会有这么多人,活动组织的相当差,刚开始一堆人是围着,不让进,越来越多了,才开始排号等,结果刚排了几个号,不排了,大家就继续往里挤,毕竟这么便宜的都想去吃。很明显,这么无组织无纪律的后果就是都吃不了。实在不想挤了,就临时改变注意,金汉斯。 其实金汉斯还是很不错的,第一次吃自助就是在金汉斯,黑啤,不限量的小菜,量很丰富的烤肉,环境也还不错。我们先头部队四个人,后面又过来五个,浩浩荡荡一大桌子,吃得挺多,浪费的也挺多。总的说来,金汉斯的自助还是能吃到不少东西的,不过也是不能人多时候去,昨天可能都是大家都去加州烤肉凑热闹去了,金汉斯这边人不是很多,这样吃到后来还可以加一些烤肉,毕竟做多了他们卖不掉也没地方收拾,就随意给人加一点,赚个好印象也不错嘛。我们这一群人不到七点开始吃,一直到九点多才离座,嗯,都挺能吃的。 因为没有半价,每个人三十多块,是够腐败的,不过偶尔为之一下,嗯嗯,可以的哈。 PS:本来应该是昨天写的,结果昨天服务器账户被封,因为三鹿奶粉的问题,suck。 <file_sep>/_posts/2009-09-18-2-vim-plugins.markdown --- layout: post title: "Vim 插件两枚" --- 偶遇 Vim 好插件两枚,分享之。 acp.vim - AutoComplPop: Automatically opens popup menu for completions. 输入两个字符后自动弹出自动补全列表,并默认选中第一项,力荐。 mru.vim - The Most Recently Used (MRU) plugin provides an easy access to a list of recently opened/edited files in Vim. 在 Vim 里开一个窗口显示最近打开/编辑的文件列表。 现在用的插件列表: - acp.vim - bufexplorer.vim - cecutil.vim - genutils.vim - minibufexpl.vim - mru.vim - NERD_commenter.vim - NERD_tree.vim - SearchComplete.vim - snipMate.vim - taglist.vim <file_sep>/_posts/2017-02-02-lonely.markdown --- layout: post title: Depends on yourself date: 2017-02-02 22:22:22 +0800 --- 算下来,从12岁离家上初中到现在,将近20年都是一个人面对着一切,中考,高考,工作,北漂,就算已经结婚四年,依然如此,只不过从我一个人变成了我们两个的一个人。 这种一个人,在面对问题的时候,往往首先想到的是我自己能不能解决,不寄希望于别人。 这种一个人,让我特别害怕欠人情,比如借钱,比如麻烦朋友,尽管我知道他们并不在意,每次还是会打心底感谢他们的帮助。 这种一个人,一定程度上强迫自己变强,因为你只能依靠你自己。 <file_sep>/_posts/2023-01-29-brew-operation-timed-out.markdown --- layout: post title: brew operation timed out date: 2023-01-29 11:20:42 +0800 --- `brew` error: > Operation timed out after 5000 milliseconds with 2740800 out of 3443379 bytes received Slow internet connection will cause this error. `export HOMEBREW_NO_INSTALL_FROM_API=1` to fix this, installing from API is the default behavior in brew 3.6.20. <file_sep>/_posts/2019-04-18-auto-deploy-with-git.markdown --- layout: post title: Deployment with git date: 2019-04-18 15:25:16 +0800 --- ``` #!/bin/sh set -uex PATH=$PATH:$HOME/bin export PATH DIR=/home/serv/project cd ${DIR} REV1=$(git rev-parse --verify HEAD) git pull origin master REV2=$(git rev-parse --verify HEAD) test ${REV1} = ${REV2} && echo "Already updated" && exit make test $? -ne 0 && echo "make error" && exit kill -HUP $(cat logs/run.pid) ``` 主要是通过 `git rev-parse --verify HEAD` 来获取当前 rev hash,前后对比是否一致,以此来决定是否继续。<file_sep>/_posts/2008-04-11-use-mysql-to-study-database.markdown --- layout: post title: "用Mysql学数据库" --- 这个学期开了数据库的课。学数据库肯定就要有实践环节,对我们来说就是实验,一周半天呆在机房。实验室装的是微软的东西,sql server 2000企业版,自己的xp上还装不了企业版的,个人版好像差点功能,还有就是sql server太过于庞大了,差不多1G的大小实在是感觉浪费,我能用的仅仅是一点点功能而已。忽然想起来wordpress用的是mysql的数据库,是啊,为啥不用这么好的东西呢?开源,免费,小巧,开工! Mysql官方中文站下载安装,这里有一个不错的[安装教程](http://tech.163.com/06/0206/11/299AMBLT0009159K_3.html)。 ``` 创建数据库: CREATE DATABASE db_name; 显示已经创建的数据库: SHOW DATABASES; 删除数据库: DROP DATABASE; ``` <file_sep>/_posts/2014-05-27-podspec-for-static-library.markdown --- layout: post title: "CocoaPods Podspec for Static Library" date: 2014-05-27 22:12:48 +0800 --- 新建 podspec 可以用命令 `pod spec create YourLibrary` 自动生成 YourLibrary.podspec,然后根据具体项目进行修改。对于 **libYourLibrary.a** 形式的静态库需要注意的地方: ``` s.source_files = '*.h' s.preserve_paths = 'libYourLibrary.a' s.library = 'YourLibrary' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '$(PODS_ROOT)/YourLibrary' } ``` `preserve_paths` 可以用 `*.a` 模糊匹配或指明静态库名,`LIBRARY_SEARCH_PATHS` 指定路径。 参考 [CocoaPod/Podspec and *.framework](http://stackoverflow.com/a/14127129/380774) <file_sep>/_posts/2011-12-01-bought-alfred.markdown --- layout: post title: "入手 Alfred" date: 2011-12-01 11:23 --- [QuickSilver][1] 真心不错,尤其是配上插件功能后就是神器。但是 QS 对中文支持的不给力,crash 增多,加上 [Alfred][2] 添加了插件功能后越来越强大,毅然转向 Alfred。 目前对自定义搜索功能最为喜欢,设置 so 到 Stack Overflow,git 搜 Github,方便不少。 留记一篇,用一段时间后再整理 Alfred 使用,希望这钱没有乱花。 [1]: http://qsapp.com [2]: http://www.alfredapp.com <file_sep>/_posts/2013-06-30-self-review-at-half-year-2013.markdown --- layout: post title: "2013 年中总结" date: 2013-06-30 20:17 --- 2013 年上半年小结。 ### 工作 年初计划今年能加强一下服务端开发学习,得到了公司的大力支持,从三月份开始跟进,到现在基本能独立负责一个线上服务的维护和新需求开发,算是有一点点进步。当然,作为服务端开发新手,有着非常多的不足。 1. 开发进度慢,工期预估偏差太大。作为一个 rookie,很多东西是有听说但完全没有经验,比如 PostgreSQL,直到最近一个项目中直接接触才知道原来 SQL 也可以编程,也可以写 FUNCTION,自己之前对数据库的经验只会最简单的 SELECT/INSERT/UPDATE/DELETE。这种经验不足的后果就是做每个东西的时候都有很多要去学习,而服务端开发的一个特点就是知识点特别碎特别多,由于知识点的掌握不足,在预估工期的时候就很容易忽视一些“小”细节,最终拖慢开发进度。 1. 基础性知识掌握太差。比如 HTTP,比如 Socket,在做应用层的时候感触还不深,知道个大概可能也就够了,但是做服务端偏底层的时候不了解这些东西视野很受限制,包括算法等,这些一直是我的软肋,是时候交学费补习一下。 1. 技术点不够深入,比如 Redis,知道是个 Key-Value 数据库,但是 Hash/List/Set 各适用于哪些场景,LPOP 和 BLPOP 用哪个命令更合适,等等问题,这些都需要在后续的开发中多深入学习和理解。 当然做服务端也有爽的地方,设计开发需求功能,封装 SDK 再转交客户端去用,这一整套的把控相当有成就感。这种 Full Stack 开发模式对自己在架构层的锻炼很有帮助,比如 API 设计,怎么更好的兼容扩展、方便客户端使用都需要去考虑,这方面自己还有很多要学习。Full Stack 开发需要对业务熟悉,对客户端前端功能了解,对后端开发实现掌握,确实是一种非常有意思的开发模式。 客户端方面上半年仍然是项目把控为主,主要是代码 review,SDK 封装,bug 排查修复等,以保证客户端稳定性。客户端技术方面在 Core Text 方面做了一些实践,整体进步不大,下半年正好可以借着 iOS 7 的上市来跟进新技术的学习。再有就是公司内部其他客户端项目的跟进学习,争取在年底时候能够把内部开发都需要的一些共用功能模块打通,做好 Team Support. ### 生活 一个人会宅,两个人就变懒。周末活动基本都是逛超市,看电影,然后吃顿海底捞犒劳一下自己,倒也惬意。 三月初两个人报了驾校,这俩月周末基本都是在驾校练车。学车并不是说要买车,只是作一个技能储备,回头有需要的时候可以直接拿来用。练车其实挺累人的,天气又热,精神高度集中的坐上半天绝对比上班还要累。还好整个过程都很顺利,两个人各科目都一次性通过,七月初就能拿到驾照。 四月初跟同事一起办了健身卡,每天下午去跑步,学游泳,就是太笨,到现在蛙泳还很吃力,身体太不协调了。体重一直徘徊在 81kg 左右,相较于冬天瘦了五公斤,但始终不能跌破 80 大关,健身还要继续,为年底的造人计划做准备。 以上。 <file_sep>/_posts/2010-05-19-string-translate-and-maketrans.markdown --- layout: post title: "string.translate and string.maketrans" --- string.translate( s, table[, deletechars]) > Delete all characters from *s* that are in *deletechars* (if present), and then translate the characters using *table*, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. string.maketrans(from, to) > Return a translation table suitable for passing to translate(), that will map each character in from into the character at the same position in to; from and to must have the same length. string.translate() 可以根据一个映射表将字符串里的字符替换成映射表对应的字符,比如映射表里面设定 a 对应 1,b 对应 2,c 对应 3,那么 `'abc'.translate` 对应的字符串就是 `'123'`. string.maketrans() 就是用来生成 translate() 所需要的映射表,参数是两个相等的字符串,根据两个字符串对应的字符位置作成一个字符映射表。 <file_sep>/_posts/2008-08-23-ipv6-surprise.markdown --- layout: post title: "IPV6的惊喜!" --- 网上发现IPV6的一个大大的惊喜: > 所有的IPV4站点都可以用http://(原URL).sixxs.org来访问!! 而且这样可以上以前要挂代理才能上的网站。天啊,太爽了,要知道教育网的封闭可以害死多少人啊,查个东西都得挂代理,免费的代理不好弄,得花钱买啊,这下可好了,哈,有了这个法宝,哼哼,哈哈! 貌似这个东西翻墙也行,比如 http://zh.wikipedia.org.sixxs.org 可以上的,太帅了,学校网络中心终于让我爽了一次! Update: 貌似 HTTPS 加密站点还走不出去 UpdateUp:网上找了一个Bookmarklet,收藏了,这样碰到打不开的网站,轻轻一点,哼哼哈哈! ``` javascript:void((function(){location.href=location.href.replace(/^http\:\/\/([^\/\@]+)\/(?:)/,%22http://%22+%22$1%22.replace(%22\:%22,%22.%22)+%22.sixxs.org/%22);})()) ``` <file_sep>/_posts/2009-10-09-python-backup-fxprofiles-script.markdown --- layout: post title: "Python 自动备份 Firefox 配置小脚本" --- 其实就是《A Byte of Python》里面一个例子程序,拿来练练手而已,没啥技术含量。打包压缩程序用的是 7-Zip,安装后安装目录里有一个命令行版的 7z.exe,添加压缩文件的参数是 **a**;自动删除旧备份文件的方法很山寨很暴力,直接 listdir 备份目录下的文件,然后删除第一个,也就是最旧的一个,凑合吧。 ```python #Python 备份 Fx 配置并自动删除旧备份 import os import time source = r'C:\FxProfiles' target_dir = r'C:\FxBackup' target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.zip' newzip = time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "7z a %s %s" % (target, ' '.join(source)) oldzip = os.listdir(target_dir) if newzip > oldzip: os.remove(target_dir + os.sep + oldzip[0]) print 'Del OK' if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED' ``` 山寨之极!不过还是玩的不亦乐乎,Python 很有搞头。 <file_sep>/_posts/2015-02-06-middleware.markdown --- layout: post title: Middleware date: 2015-02-06 00:16:48 +0800 --- **(这块内容属于个人理解,可能会不对)** 最近学习中又一次接触 middleware 概念,一直对这个东西都比较模糊,似乎 Ruby 界用的比较多,比如 [Rack][3]。middleware 给我的感觉就是在请求与 App 之间对请求进行一层或多层处理,然后将处理后的请求对象交由 App;同理,在 App 和响应之间也可以有。 一个常见的业务场景: `请求 -> [cache.get -> 有-返回|无 -> 服务处理生成数据 -> cache.set] -> 响应` 其中 cache 读写都是在服务内处理请求时进行。套用 middleware 似乎是这样的流程: `请求 -> [middleware.cache.get -> 有-返回|无-请求交由下一步处理] -> [服务处理生成数据] -> [middleware.cache.set] -> 响应` 去掉 middleware.cache 整个服务不受影响,流程变成了这样: `请求 -> [服务处理生成数据] -> 响应` middleware 的好处是可多层组合,让流程有层次,服务更专一。接下来要在实际项目中实践一下: * [Negroni][1], Idiomatic HTTP Middleware for Golang. Martini 作者开发。 * [lua-resty-rack][2], A minimalistic rack implementation for Openresty. [1]:http://codegangsta.io/blog/2014/05/19/my-thoughts-on-martini/ [2]:https://github.com/APItools/lua-resty-rack [3]:https://github.com/rack/rack/wiki/List-of-Middleware <file_sep>/_posts/2009-05-10-windows-live-mesh-using.markdown --- layout: post title: "Windows Live Mesh 使用" --- 首先自我检讨一下,自从自己 Gfans 之后,就莫名的对微软的一些网络服务产生排斥,这样的结果就是让自己错失了很多美好的东西,比如 Windows Live Mesh。 简单的说 Live Mesh 就是一个云计算应用平台,通过 Live Mesh 客户端软件把文件同步到网络在线存储,然后可以通过其他设备,比如手机,或者在另外一台电脑上同样通过 Live Mesh 客户端软件把文件同步到另外的电脑上,最终实现本地电脑文件-网络在线存储文件-第三方设备/电脑文件的同步。Live Mesh 使用很简单: 1. 用 Live ID 登录 Mesh 主页:https://www.mesh.com; 2. 选择 Add Device,然后下载 Mesh 客户端,支持 XP/Vista,Mac 客户端功能现在还不完善; 3. 安装后用 Live ID 登录,添加当前电脑到该账户 Mesh; 4. 然后开始菜单-Live Mesh-Live Mesh Folders,这个文件夹就是 Mesh 的本地映射目录,只是目录,并不是要把同步的文件放到这个文件夹里; 5. 假设我要把我电脑上 D:\Vim 文件夹以及包括的文件同步到 Mesh,Steps:在 Live Mesh Folders 里右键 Live Mesh Opitions-Create folder in Live Mesh,然后 Name:Vim,Location:D:\Vim,OK确认后会提示合并当前文件夹并且当前文件夹里的所有文件会同步到其他设备,确认即可,之后就同步到网络在线存储。 6. 登录 https://www.mesh.com/Web/Desktop.aspx 就可以查看同步到在线存储的 Vim 文件夹; 7. 以后对 D:\Vim 下文件进行修改就会自动同步到 Live Mesh。 Live Mesh 这种云存储在线同步方案非常方便,可以多设备多平台同步,网络在线存储也可以保证数据安全性,当然,再 YY 一下如果加上版本控制的话会更好。 白话一下 Windows Live 应用。在使用 Mesh 的时候看了看另外两个跟 Mesh 非常像的服务:Windows Live SkyDrive 和 Windows Live Sync,这三个的差别一度让我迷惑了好久,[这里](http://livesino.net/archives/1660.live)有一篇漫谈,详细分析了一下三个的区别。我的理解,SkyDrive 就是一个网络硬盘,一个在线存储空间;Sync 强调的是多台计算机之间通过 Sync 软件进行数据同步,但是没有在线数据存储服务;Mesh 也就是这两个的综合,在线存储加上多台电脑的数据同步。其实完全可以把这三个和为一个,搞这么多反而让人不知所措,Windows Live 服务的品牌混乱,重复开发,服务重叠,自己跟自己打架。 <file_sep>/_posts/2013-08-09-disconnect-unresponsive-ssh-connection.markdown --- layout: post title: "退出无响应的 SSH 连接" date: 2013-08-09 23:00 --- SSH 经常会因为网络中断、电脑休眠等原因中断无响应,完全无法 Ctrl+C 等方式退出。简单粗暴的解决方法就是直接关闭当前终端重开,更为优雅的方式是用 `~.` 断开,适用于正常和无响应的 SSH 连接。 via [如何 “优雅” 的退出无响应的 SSH 连接](http://www.vpsee.com/2013/08/how-to-kill-an-unresponsive-ssh-connection/) <file_sep>/_posts/2009-04-20-what-is-the-cuda.markdown --- layout: post title: "CUDA 是什么?" --- 刚才专业群里有个通知,4月25日,CSDN 携手 nVIDIA 来工大“nVIDIA CUDA 技术任我行”校园系列巡讲活动。没怎么听说过 CUDA 这个名词,就好奇的搜索了一番,了解一下这个称为“大规模并行运算程序设计技术”的新东西。 先来一段 [wikipedia](http://zh.wikipedia.org/w/index.php?title=CUDA) 的介绍: > CUDA(Compute Unified Device Architecture, 计算统一设备架构)是NVIDIA 所推出的技术,是 NVIDIA 的 GPGPU 的正式名称。透过这个技术,用家可利用 NVIDIA 的 GeForce 8 以后的 GPU 和较新的 Quadro GPU 进行计算。亦是首次可以利用 GPU 作为C-编译器的开发环境。 nVIDIA 的这个新技术其实就是去做 CPU 干的事情,GPU 的特点就是处理密集型数据和并行数据计算,因此 CUDA 非常适合需要大规模并行计算的领域,比如图形动画、科学计算、地质、生物、物理模拟等。 可惜,25号不在学校,不能过去听这个讲座,据说还有礼品,了解一下新技术就好了,管不了那么多,现在的任务就是找工作,继续加油吧。 <file_sep>/_posts/2010-07-04-whats-up.markdown --- layout: post title: "到底是怎么了?" --- 为什么面试的时候不会就说不会不懂就是不懂实话实说的人频频被人鄙视,而不会装会不懂装懂满嘴跑火车吹的天花乱坠好像自己有多牛逼不要我就是你公司一大损失的人却能受面试官喜欢呢?是我们太老实还是太傻? 有感于丫头面试。 <file_sep>/_posts/2008-07-04-anti-virus-manually.markdown --- layout: post title: "手工病毒分析" --- 病毒与反病毒,这学期的一个专业选修课。留个作业,自己弄个病毒分析一下再手动查杀,写个分析报告。同学在学校机房抓了个简单的auto病毒,试试玩玩。 ----------------其实啥也不会-------------- 病毒样本:学校机房的简单Auto.exe病毒,样本包括 auto.vbs, Auto.exe, autorun.inf三个文件。 系统环境环境配置: * Sun VirtualBox虚拟机+WinXP Sp3精简版; * System Safety Monitor(SSM)HIPS主动防御软件,用于监视病毒激发的动作; * Autoruns查看系统启动项软件; * IceSwordcn冰刃,查看隐藏目录。 病毒激发中毒后症状: 1. 在各个盘下面生成auto.exe和autorun.inf文件,属性隐藏。 2. 释放病毒文件到C:\WINDOWS\system32\C8A2BB40.EXE,属性隐藏,同时生成一个假的病毒文件n1215014078k.exe(名字应该是随机生成),这个可以轻易删掉,迷惑用户。 3. 在系统服务里加载HKLM\SYSTEM\CurrentControlSet\Services\1E87CA0服务,服务项名称为1E87CA0,指向病毒文件C:\WINDOWS\system32\C8A2BB40.EXE,并设置为自启动。 4. 启动项没有添加,因为病毒自启动文件加载在系统服务里,更有隐蔽性。 5. 修改文件夹选项里隐藏文件设置,显示隐藏文件不可用,即时选中显示隐藏文件也会被病毒自动改为不可见,不能看见隐藏文件,隐藏病毒体。 由上面病毒激发的动作可以看出,这只是一个很简单的autotun病毒,并没有大的症状,因而查杀时候也很简单。过程: 1. CMD下面删除C:\WINDOWS\system32\C8A2BB40.EXE文件 `del /f /a C8A2BB40.EXE`,同样方式删除C:\WINDOWS\system32\47CAE1E0.DLL文件 2. CMD删除各个盘目录下面auto.exe和autorun.inf文件 3. 注册表删除相关项HKLM\SYSTEM\CurrentControlSet\Services\1E87CA0, 重启即可。 总结:从病毒激发过程和查杀过程可以看出这是一个很简单的autorun病毒,而且没有病毒自身保护,所以查杀时候直接删掉病毒体C8A2BB40.EXE即可,并不会自我保护重新生成病毒,估计是学生自己学习编写的一个简单样本,也没有什么实际的破坏作用。通过手动查杀过程,学习了手动杀毒的流程,收获了一些病毒查杀经验。 --------------------忽悠结束----------------- 很没有步骤也没有条理的分析,跟网上高手的分析差距十万八千里的十万八千里,平时中个U盘病毒其实也会试着去收拾一下,慢慢的就有了点经验,用电脑还是一个习惯问题,好习惯加上一点小技术,It`s Ok! <file_sep>/_posts/2010-07-01-get-server-ip-of-basehttpserver.markdown --- layout: post title: "Get the server IP of BaseHTTPServer.BaseHTTPRequestHandler" --- 获取 BaseHTTPServer.BaseHTTPRequestHandler 请求服务器的 IP。 `serveradress = re.findall('Host: (.*?)\r\n',str(self.headers))` <file_sep>/_posts/2011-12-08-regexkitlite-error-undefined-symbols-for-architecture-i386.markdown --- layout: post title: "RegexKitLite Error: Undefined symbols for architecture i386" date: 2011-12-08 15:39 --- RegexKitLite 编译错误: ``` Undefined symbols for architecture i386: "_uregex_start", referenced from: _rkl_performRegexOp in RegexKitLite.o _rkl_search in RegexKitLite.o _rkl_findRanges in RegexKitLite.o ld: symbol(s) not found for architecture i386 ``` 解决办法: In project Build Setting search "Other Linker Flags" and add "-licucore". 编译设置搜索 "Other Linker Flags" 添加 "-licucore" 字段 <file_sep>/_posts/2021-10-21-codesign-an-unsigned-library.markdown --- layout: post title: codesign an unsigned library date: 2021-10-21 09:22:14 +0800 --- Some Python modules are not signed, will raise ImportError on M1 macOS: ```sh ImportError: dlopen(/tmp/test/.venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so, 2): no suitable image found. Did find: /tmp/test/.venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so: code signature in (/tmp/test/.venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so) not valid for use in process using Library Validation: Trying to load an unsigned library ``` You can use `xcrun codesign` to sign the library so: `xcrun codesign -s - <path>`. Here is: `xcrun codesign --sign - /tmp/test/.venv/lib/python3.9/site-packages/regex/_regex.cpython-39-darwin.so` <file_sep>/_posts/2015-06-17-5-years-in-beijing.markdown --- layout: post title: 5 Years in Beijing date: 2015-06-17 09:03:26 +0800 --- 5 years in Beijing. 5 years in Appwill. <file_sep>/_posts/2010-10-12-sizes-of-iphone-ui-elements.markdown --- layout: post title: "Sizes of iPhone UI Elements" --- ![Sizes of iPhone UI Elements](http://lh4.ggpht.com/_vYr4JQreqXA/TLQtsw0M6_I/AAAAAAAABGo/0KPHPNKZNkQ/s800/sizes.png) > Window (including status bar) -> 320 x 480px > Status Bar -> 20px > View inside window(visible status bar) -> 320 x 460px > Navigation Bar -> 44px > Nav Bar Image -> up to 20 x 20 px (transparent PNG) > Tab Bar -> 49px > Tab Bar Icon > up to 30 x 30 px (transparent PNG) > Text Field -> 31px > Height of a view inside a navigation bar -> 416px > Height of a view inside a tab bar -> 411px > Height of a view inside a nabber and a tab bar -> 367px > Portrait Keyboard height -> 216px > Landscape Keyboard height > 140px References: + [Sizes of iPhone UI Elements](http://www.idev101.com/code/User_Interface/sizes.html) + The [UIBarButtonItem Class Reference](http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIBarButtonItem_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40007519-CH3-SW3) says "Typically, the size of a toolbar and navigation bar image is 20 x 20 points." + The [UITabBarItem Class Reference](http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITabBarItem_Class/Reference/Reference.html#//apple_ref/occ/instm/UITabBarItem/initWithTitle:image:tag:) says "The size of an tab bar image is typically 30 x 30 points." <file_sep>/_posts/2019-05-23-octotree-for-safari.markdown --- layout: post title: Octotree for Safari date: 2019-05-23 15:32:03 +0800 --- **From Safari 13, you can only install extension from Mac App Store.** ---- ```sh brew install node@10 export PATH="/usr/local/opt/node@10/bin:$PATH" # make sure node and npm is v10, cause octotree used gulp 3, which is not working with node 12. git clone https://github.com/ovity/octotree.git ~/src/octotree cd ~/src/octotree git checkout master npm i npm install natives@1.1.6 npm run dist # extension locate in ~/src/octotree/tmp/safari/octotree.safariextension/ cd ~/Library/Safari/Extensions mv ~/src/octotree/tmp/safari/octotree.safariextension . ``` 1. Enable `Developer` menu in Safari 2. `Developer - Show Extension Builder` 3. Add octotree.safariextension and Run <file_sep>/_posts/2012-07-03-data-store-in-iphone.markdown --- layout: post title: "iPhone 数据存储" date: 2012-07-03 22:36 --- 稍微总结一下 iPhone 的数据存储。常见的方式有这么几种: 1. NSUserDefaults 1. SQLite 1. Core Data 1. iCloud 1. NSKeyedArchiver/NSKeyedUnarchiver 1. Keychain 1. UIPasteboard 1. writeToFile: ---- ### NSUserdefaults `NSUserdefaults` 是最为常见的方式,通常用来保存简单的数据,比如 App 设置等。数据保存在 `$App/Library/Preferences/$BundleID.plist`。 ``` // 存 [[NSUserDefaults standardUserDefaults] setInteger:100 forKey:@"MaxCount"]; [[NSUserDefaults standardUserDefaults] synchronize]; // 取 [[NSUserDefaults standardUserDefaults] stringForKey:@"StringKey"]; ``` 存数据时候最好 `[[NSUserDefaults standardUserDefaults] synchronize];` 来及时保存。 ### SQLite iPhone 自带了 SQLite 数据库,可以用来存储大数据量的持久化数据,比如 Google Reader 类阅读器缓存的文章内容。SQLite 直接操作 Api 很复杂,一般都会选用一些开源的 wrapper,比如 [FMDB][1]. ### Core Data `Core Data` 是苹果官方推荐的数据存储方式,底层也是拿 SQLite 做持久化。目前还没有在项目中实践过 Core Data,不多说,官方文档 [Introduction to Core Data Programming Guide][2]. ### iCloud `iCloud` 是 iOS 5 带来的新特性,云端同步是最大的优点,iOS+OS X 通用,可以拿来做一些很神奇的事情,比如 Tweetbot 通过 iCloud 同步 iPhone 和 iPad 上时间线的阅读位置。目前也没有在项目中实践过。 `iCloud` 可以和 `NSUserDefaults` 配合使用,比如 [MKiCloudSync][3],sync your NSUserDefaults to iCloud automatically。 ### NSKeyedArchiver `NSKeyedArchiver` 可以将数据 encode 后保存成文件,或者通过 `NSUserDefaults` 保存;对应 `NSKeyedUnarchiver` 用来读取数据。适合数据结构复杂(NSArray/NSDictionary)数据量较大但又不需要用 SQLite 做持久化存储的中间缓存,比如 MKNetworkKit 的 `freezeOperations` 操作,很方便。 ``` // 保存 dict 到 Library 下 Dict 文件 [NSKeyedArchiver archiveRootObject:dict toFile:NIPathForLibraryResource(@"Dict")]; // 读取 NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithFile:NIPathForLibraryResource(@"Dict")]; ``` ### Keychain `Keychain` 就是钥匙串,加密保存用户帐号、密码等重要信息。推荐两个 wrapper:[SSKeychain][4], [PDKeychainBindingsController][5] ### UIPasteboard `UIPasteboard` 系统剪贴板是一个非常巧妙的数据存储方式,最大的好处就是可以夸应用数据访问,比如词典应用自动读取翻译剪贴板内容,非常方便。[OpenUDID][6] 就是通过一个特殊的剪贴板来保存唯一设备字符串,这样其他 App 就可以用这个唯一标识做设备区分。 ### writeToFile: `writeToFile:` 可以直接将数据写入到指定路径的文件中,NSArray、NSDictionary、NSData 都支持。做数据缓存用的比较多,比如 [EGOCache][7]。 [1]:https://github.com/ccgus/fmdb [2]:https://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.html [3]:https://github.com/MugunthKumar/MKiCloudSync [4]:https://github.com/samsoffes/sskeychain [5]:https://github.com/carlbrown/PDKeychainBindingsController [6]:https://github.com/ylechelle/OpenUDID/ [7]:https://github.com/enormego/EGOCache <file_sep>/_posts/2009-11-27-new-pc.markdown --- layout: post title: "New PC" --- 昨天上午终于抽出空来把电脑上的资料整理了一下,换上了新机子,E5300 CPU + 3G Memory。 换电脑最大的麻烦就是资料的转移,工作环境好办,因为一直都是虚拟机 Coding,直接把虚拟机硬盘镜像 Copy 备份就行;个人文档资料就比较麻烦了,不过好在一直在用 Live Mesh,同步到 Mesh 云上,再同步回来就是,云计算的优势就在这里,当然,要有强大的网络宽带支持。 这台 PC 应该算是自己经手的第三台电脑,自己的本子,公司前后配的两台电脑,感觉电脑硬件配置达到了一定级别后再升级几乎感觉不到什么性能提升了。2G 内存和 3G 内存没啥区别,内存大了闲着也是浪费,索性我直接弄了一个 256M 的 RAMDISK 给 Fx、Chrome 当缓存用。 EOF. <file_sep>/_posts/2016-07-20-29.markdown --- layout: post title: '29' date: 2016-07-20 22:22:22 +0800 --- 29. 这一年,职业转型,一切还在摸索中,生活上买房,依然是双城跑,都很难,都还在路上。 <file_sep>/_posts/2008-09-01-connection-with-foreigner-first-time.markdown --- layout: post title: "第一次跟老外交流" --- 这两天在玩Fx的Ubiquity扩展,很多有趣的东西,关键是可以自己写命令,很有geek精神。加了一个Ubiquity的Google Group,发现老外的程序员都喜欢用邮件列表来交流,有问题发上来,大家都能看见,会的就说两句。有点类似qq群那样的,不过感觉比群讨论要高效,节省大家的时间,不会有消息爆炸那样的烦恼,简洁高效,赞一个。 正题。在群里找了一个命令脚本,套用Fx自带的函数刷新,很无聊的脚本哈, 纯属娱乐。试了一下那个脚本命令,老提示语法错误,就学着看了一下代码,发现有一句代码后面少了一个结束标志“,”逗号,添上就OK了。估计是失误,就想着要不说一句邮件过去?组织语言弄了好久,写了这么几句话: > Hi. Perhaps there is a small bug in the "Refresh" command. An "," is missing in the end of "concept:..." > BTW,is there any function to refresh the current page every 10 seconds? > Sorry for my poor english,thanks. 那个“,”前到底该用a还是an我实在是搞不明白,感觉上an顺一点,:-),不知道会不会被人鄙视我那龌龊的英语。。。 Update:貌似有人看懂了,关于后面那个问题回了一个,但不是我想要的东西,可能没有表述清楚吧。 > I don't know of any. But you could try inserting a meta-refresh tag into the head of the page - I *think* that will still trigger if its added after page-load. - Blair <file_sep>/_posts/2008-08-12-my-firefox-custombuttons2-share.markdown --- layout: post title: "我的Custom Buttons2按钮分享" --- Custom Buttons2是Firefox的一个强力插件,可以自定义安装一些按钮,实现一些功能,很是方便。Custom Buttons2的官网有很多有趣实用的功能按钮,这里我分享一下我自己使用的Custom Buttons2按钮。我一般都把Fx的标题栏隐藏掉,然后将Custom Buttons2的按钮加在工具栏右侧空白处,这样既节省了显示版面,又不影响外观。上图: ![](https://lh6.googleusercontent.com/-2J11iH_IZxM/U-t7T_RsSdI/AAAAAAAAGaI/_GITY6sNEZU/w800-h60-no/1.jpg) 1. Go Up,向上一层浏览。用过Maxthon的都知道有这个功能,点击跳转到上一级网址 2. Clear AddressBar/InputField/SearchBar,清除地址栏/输入区域/搜索栏(左中右键)。很简单,对应鼠标左键/中键/右键,相应的点击清空地址栏/输入区域/搜索栏,当然,习惯快捷键的就省去了这种鼠标手操作,定位到地址栏的快捷键是Alt+D,定位到搜索栏是Ctrl+K。 3. FavicoTab,就是将当前页面标签缩小到图标大小,节省浏览空间,我一般都是把Google Reader标签缩小再锁定,因为我一般不把它关掉。 4. Top/Bottom,跳转到页面顶部/低端。泡论坛必备,点击后直接到最下面的回复框。 5. URL 连页增加/减少,在线看小说很实用的说。 7. Google 翻译(中英),左键点击将当前网页翻译为中文,当然前提得是当前页面是英文,右键点击正好相反。看一些外文网站时候对咱这些个英语不好的很是方便。 8. Options,打开选项options菜单,省略工具Tools-选项Options点击,我们要的就是方便省事。 9. Add-ons,打开附件组件。类似于上面的按钮功能,一键到附加组件。 10. search at once when switch engine,切换搜索引擎立即搜索。一般都会在搜索栏添加好多个搜索引擎,切换着搜索。Fx默认情况下点击切换搜索引擎时候是不会自动立即搜索的,这个按钮就可以实现这个动能,装上以后就不用管了,方便。 11. Search Site,使用Google的site:url搜索功能对当前页面进行站内搜索。很多站点、论坛和博客自带的搜索其实很弱的,老是搜索不到,使用google的site:url搜索就强大多了。 12. Auto context menu on selection,选定网页文字自动弹出右键菜单,省略一次点击,习惯使用的话要少点击多少次右键啊,很节省鼠标使用的哦。 13. Toggle Chrome,隐藏Fx标题栏,增大页面显示大小。节约一行的显示空间,对小屏幕来说还是很可观的。 14. Re-Start,重启Fx。一般来说一开机打开Fx后基本上都不怎么关掉,虽说Fx 3内存泄露问题解决的很不错,不过时间长了还是会100-200多M内存占用,重启Fx,就这么简单。 其实Custom Buttons2还有很多有趣简单实用的功能按钮,合理的使用能给我们带来很多方便,节省时间,提高效率。打造自己的Fx,享受自定义的快乐。 <file_sep>/_posts/2008-09-17-mid-autumn-day.markdown --- layout: post title: "中秋" --- 中秋节,快乐! 又是中秋了,收了一堆兄弟们的短信,在外的,过个好节,快乐!想想,好像这是从12岁以后在外面自己一个人过的第十个中秋了,从初中开始,都没有在家过中秋了,已经不是很想家了,不会像初中那时候,哭鼻子,大了嘛。刚才给家里打电话,妹一个人在家,爸妈下地收花生,还没有回来。。晚上再打一个回去,中秋了,怎么说也要跟爸妈说说话的。 <file_sep>/_posts/2010-09-01-terminal-tips-and-tricks-for-mac-os-x.markdown --- layout: post title: "Terminal Tips and Tricks For Mac OS X" --- via [SuperUser:Terminal Tips and Tricks For Mac OS X](http://superuser.com/questions/52483/terminal-tips-and-tricks-for-mac-os-x) - **open .** #Opens the folder you're currently browsing in Finder.URLs, images, documents. - **open -a Preview image.png** #overriding the default program set for the filetype. - **say "Hello there."** #text-to-speech. - **!!** #Runs the last command again; **sudo !!** to rerun the last command using sudo. - **mdfind fileName** #`-onlyin` for directory specified; `-name` for matching file names only. - **python -m SimpleHTTPServer 8000** #Start a quick webserver from any directory. - **qlmanage -p 2>/dev/null** #alias as ql,launch quicklook on a file from the command line <file_sep>/_posts/2008-08-08-080808-welcome-to-beijing.markdown --- layout: post title: "080808,北京欢迎你" --- 今天是2008年8月8日,北京奥运会今天开幕,北京欢迎你! 晚上找地方看开幕式,10号晚上看男篮比赛,YY一下中国男篮绝杀美国男篮,哈哈! <file_sep>/_posts/2008-05-27-passing-the-flame-representative.markdown --- layout: post title: "代表性的圣火传递" --- 1. 合肥火炬传递起跑仪式定于5月28日上午8时举行,地点是在合肥经济技术开发区的安徽国际会展中心西门前广场。在起跑仪式前,将集体默哀一分钟,表示对四川地震遇难同胞的哀悼。 2. 圣火火种回收仪式定于11:02举行,地点合肥体育中心体育场内。之后,北京奥组委圣火护卫人员将圣火从圣火台引回火种灯,熄灭圣火台,活动结束。 3. **最新** 的传递路线如下:安徽国际会展中心 > 繁华大道 > 翡翠路 > 政务广场 > 潜山路 > 习友路 > 合肥体育中心体育场,途径徽园、大学城、政务大楼、天鹅湖、体育中心等美丽景点和城市标志性建筑 4. 目前,合肥市已组织了7.1万人到现场观看火炬传递,包括庐阳区、包河区、蜀山区、瑶海区、经济技术开发区、合肥市总工会、教育厅、驻肥130多个单位等,涵盖了合肥市的各个阶层。届时,**他们将代表合肥市民文明有序地喜迎圣火**。圣火回收仪式核心区的观众,也有 **很强的代表性**,有工人、农民、大学生等,他们分别身穿蓝、黄、黑、绿、红五种颜色,与奥运五环相对应。 以上来源于[新华网](http://www.ah.xinhuanet.com/08hjjl/hf.htm),整理得之: **明天被有一个能亲临现场的大学生兄弟姐妹,代表我观看圣火,为圣火呐喊加油,为奥运加油!** **我想爱你,你却把自己封装起来,设置属性为private,通过一个很有代表性的接口,跟我说:你一定要爱我,哪怕是通过它!** <file_sep>/_posts/2009-09-24-project-summary.markdown --- layout: post title: "项目小结" --- 前一个项目基本上算是完结。抽空总结一下这个项目的一些收获,以后写东西时候留心避免以前犯过的错误,吸取些许经验。 1. **变量定义类型**。自己添加的变量要注意类型。虽然可以参考程序已有的变量类型,不过还要通盘考虑自己变量的实际应用。比如这次,弄了个变量 String 类型,在前期确实很方便,但是后期就需要转 Int 型,比前期 String 用的还多……不想返工,只好 StrToIntDef(x,0) 的用,开销反而更大。 2. 添加的函数要注意应用范围,不能添加一个函数实现了需要的功能而影响到其他范围内函数的功能。简单的方法就是添加函数时制定它的工作域。 3. 善用 **Trim()** 对字符串过滤。 4. 标志变量要注意用完后 **返回初值**。 5. 充分考虑判断条件组合可能带来的不同结果。 6. 阅读程序的能力,程序已有同样功能的变量、函数**不要重复制造轮子**。 7. 注意**已有的程序注释**。 <file_sep>/_posts/2014-07-30-monthly-review-1407.markdown --- layout: post title: "Monthly Review 2014-07" date: 2014-07-30 21:01:25 +0800 --- 从这个月开始会在月底做一次月总结,其实最主要的目的是强迫自己每个月写点什么。 > 写自己,写给自己,写作技能上力图为读者负责,写作态度上只求为自己负责。 via [KDr2][1]. 工作上除了常规业务开发,调研并上线了 nginx proxy_cache,效果很是不错,为后面的访问爆发做准备。 断断续续在线看完《[Go Web 编程][2]》,对 Golang 的有了相对全面的了解,相比 OpenResty,Go 在性能上差距不大,开发效率上要比 Lua 高一些(不过 Go 的语法真心没有 Lua 简单明了),可以在一些项目上试试手。 慎独,又是一个人的一个月,过于宅的日子对自己心态很不好,所以这两周末有意识的让自己出去走走,做一些调整。 心态不好一方面是一个人,一方面是家里,我们这一代人和父母一辈在育儿上确实有很多分歧,尽管目标都一致。得感谢小姨一直在中间劝我妈,现在问题已经化解很多。 看着兄弟们升职买房结婚安定,加上家里、小孩的因素,北漂的不安定很让人心烦,这也是自己心态不好的主要原因,买房已经开始考虑并提上日程,希望自己能处理好这些事情。 [1]:http://kdr2.com/introspect/monthly-review-1404.html [2]:https://github.com/astaxie/build-web-application-with-golang <file_sep>/_posts/2014-10-16-zsh-shared-history.markdown --- layout: post title: "Zsh Shared History" date: 2014-10-16 08:49:57 +0800 --- You can share every commands between all terminals with Zsh shared history. In your `.zshrc`: ``` # enable shared history setopt inc_append_history setopt share_history # disable shared history unsetopt inc_append_history unsetopt share_history ``` <file_sep>/_posts/2020-01-27-8-24.markdown --- layout: post title: "8:24" date: 2020-01-27 8:24:10 +0800 --- <NAME> ![8:24](https://c1.hoopchina.com.cn/uploads/images/20200127/06/ead5291bec92b796ba6deacdc3498721.JPG) <file_sep>/_posts/2013-08-16-mosh-better-ssh.markdown --- layout: post title: "Mosh - Better SSH" date: 2013-08-16 12:42 --- [Mosh][1] 相比 SSH 的优点: 1. 网络中断、切换后自动重连。 1. 屏幕输入及时回显。 服务器需要先安装 mosh-server,开启 60000-61000 端口,本地通过 SSH 登录服务器,然后 UDP 连接服务器 mosh-server。 [1]:http://mosh.mit.edu/ <file_sep>/_posts/2011-07-29-self-abasement.markdown --- layout: post title: "自卑" --- 两个小故事。 ------ 12 岁的他第一次出远门到县城上初中。坐在倒数第二排左靠墙的角落,在他前面还有六排 54 个脑袋,嗯,一中的教室就是这么拥挤,一个教室 70 个人是很正常的事。初中英语课上,其他同学居然都会 ABC 的读,居然都会!他不能理解,不还没有教的吗?你们怎么都会读了?老师也忽略了不会的同学,跳过 26 个字母的认识直接教单词、课文。ABC 都还没认全的他懵了,他不敢问老师,不敢问同学,一个人在那个角落,在别人读的时候也张嘴,但不出声,听着别人的发音去记。整整一个月,初一开学的头一个月,他一个人默默的呆在那个角落,很少说话,很少有人注意到。直到一个月后的月考,他拿了全班第二名,班主任是如此惊奇地发现那个角落里还有这么个“好学生”,赶紧调位置。感谢那次月考,他又活了。 ------ 大学时候他很不喜欢一个同学,称之为 A 吧。A 在大二时候撺掇成了班长。在那年的助学金申请上,A 搞了一个很 SB 的活动,请允许我用 SB 来形容那次活动。申请人到讲台讲述自己的贫困情况,然后全班人当面投票,没错,就跟竞选一样。他是申请人之一,之前递交书面申请时候完全没想到会有这么 SB 的活动。没记错的话有一个同学在讲台上都哭了。轮到他的时候他说了句弃权,然后摔门而出。 ----- 1. 谁没有自卑过呢,自卑不是也不能是你堕落的原因。 2. 其实自卑深处有一股很强大的力量。 <file_sep>/_posts/2013-04-29-afnetworking-notes-2.markdown --- layout: post title: "AFNetworking 学习笔记二" date: 2013-04-29 21:02 --- [AFNetworking 学习笔记][1] 的后续,记录一些 AFN 比较隐蔽的知识点。 ### AFN 的设计过于理想化 AFN 的架构设计非常棒,使用起来也很简单,但一些设计过于理想化,在实际开发中会有一些条件不能满足,这时候 AFN 就会出现一些“坑”。 #### 1. 缓存策略 NSURLRequest 默认的缓存策略是 `NSURLRequestUseProtocolCachePolicy`,网络请求是否用缓存是由 HTTP Cache-Control 决定,而在实际开发中由于种种原因(服务端为了简化系统等),接口的缓存时间都设置的非常长或者不准,这种情况下就会出现服务端数据更新但是 AFN 拿到的还是旧数据,因为他直接读的缓存。 得益于 AFN 优秀的架构设计,这个问题也很好解决,继承 AFHTTPClient 然后重写 `requestWithMethod:path:parameters:`: ``` objc - (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters { NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters]; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; return request; } ``` #### 2. Response 类型判断 以 AFJSONRequestOperation 为例,只有 Content-Type 是 `@"application/json", @"text/json", @"text/javascript"` 或 URL pathExtension 是 json 的才会被认为是 JSON 类型,其他都不认。很多服务端接口都没有 Content-Type 返回或者直接丢一个 `text/html`,请求也不是 json 结尾,但返回内容确实又是 JSON 数据,这时候 AFN 就很无力。 ---- 上面这两个问题的根本原因是服务端由于各种各样的问题不能严格按照 HTTP 要求返回正确格式的内容,造成 AFN 无法按照标准去接收解析。责任虽不在客户端开发,但实际开发中确实存在这种情况,这个时候就需要客户端去迂回解决,好在 AFN 的架构设计很容易扩展。 ### AFN vs ASI AFN 已经取代 ASIHTTPRequest(ASI) 成为 iOS 开发中首选的网络库,但不能说 AFN 就完胜 ASI,比如这篇 [对比iOS网络组件:AFNetworking VS ASIHTTPRequest][2],AFN 在易用性上胜出,在性能上并没有 ASI 好(因为 ASI 是直接用 CFNetwork 底层而 AFN 是用 NSURLConnection)。 就我自己实际开发来说,AFN 最大的不便是没有 **synchronous** 请求方式,只支持异步请求。很多时候我们只是想发一个请求,无需返回处理,这种情况下 AFN 这种自定义 HTTPClient 的方式就过于复杂。 最近发现了一个网络库 [STHTTPRequest][3],基于 NSURLConnection,支持 synchronous+asynchronous blocks,支持文件上传,非常简单轻量的封装,值得一试。 [1]:https://fann.im/blog/2012/08/21/afnetworking-notes/ [2]:http://www.jiajun.org/2013/03/16/afnetworking_vs_asihttprequest.html [3]:https://github.com/nst/STHTTPRequest <file_sep>/_posts/2010-05-11-email-plz-no-im.markdown --- layout: post title: "Email PLZ,No IM" --- Email: 1. 不打扰人,对双方来说都更为高效; 2. 大段文字讨论,不中断; 3. 更为方便的文档存储管理。 IM: 正好与之相反。 <file_sep>/_posts/2014-10-13-two-hard-things.markdown --- layout: post title: "Two Hard Things" external-url: http://martinfowler.com/bliki/TwoHardThings.html date: 2014-10-13 09:55:46 +0800 --- > There are only two hard things in Computer Science: cache invalidation and naming things. -- <NAME> <file_sep>/_posts/2008-05-28-waiting-for.markdown --- layout: post title: "“等”吧" --- 今天火炬在离俺们说远不远,说近不近的新区那边传递,俺被人代表着加油去了,安安心心上课吧。 中午吃饭时候正好赶上5套《体坛快讯》,到不了现场还不能看看电视啊。官方的就不说了,传递的很好。后面有一个关于合肥的短片,有这么一段: > 合肥也是有名的全国教育...(有几个字没听见,估计是教育重点什么的),包括中国科学技术大学**等**一批有名的大学... 我们就是那个**等**字里面的,因为你是等字辈的,所以你不能去现场看火炬,只能等着让别人代表你去看,等着看看电视新闻画面就行了... <file_sep>/_posts/2010-07-25-py2exe-notes.markdown --- layout: post title: "py2exe notes" --- Python 2.6 以上版本报错: > error: MSVCP90.dll: No such file or directory Python 2.5 及以下运行时需要的 runtime DLL 是 MSVCR71.dll,这个打包时候会自动包含进来;Py2.6 及以上运行时需要的 runtime DLL 是 MSVCR90.dll,这个需要手动加载。在 setup.py options 字典添加 **"dll_excludes": ["MSVCP90.dll"]** 解决。[via](http://www.py2exe.org/index.cgi/Tutorial#Step5) 几个 options 参数 [via](http://www.py2exe.org/index.cgi/ListOfOptions): - optimize:2 => extra optimization - includes:list of module names to include - compressed:1 => create a compressed zipfile - bundle_files:1 => bundle everything, including the Python interpreter application failed to initialize properly (0xc0000142) 应用程序正常初始化(0xc0000142)失败 在 setup.py data_files 添加 **("Microsoft.VC90.CRT", ['MSVCR90.dll','Microsoft.VC90.CRT.manifest'])**,留意 Microsoft.VC90.CRT.manifest <file name> 只能有 msvcr90.dll。 [via](http://www.py2exe.org/index.cgi/Tutorial#Step521) <file_sep>/_posts/2008-03-07-ubuntu-config-2.markdown --- layout: post title: "ubuntu个人配置(二)" --- 1. `/var/cache/apt/archieve` 下的都是软件的安装缓存,可以直接删除,或者用命令 `sudo apt-get autoclean`(只删除低版本的deb包),`sudo apt-get clean`(全部删除)。为了以后重装系统方便,可以将这些deb包保存到其他地方。 2. 软件源码编译安装 `./configure && make && sudo make install` 3. Ubuntu7.10 里面火狐假死以及占资源100%解决 `sudo gedit /usr/lib/firefox/firefox` 头部添加 `export MOZ_DISABLE_PANGO=1` 同时禁用ubuntu加的扩展: ubufox, 加装 flashblock 插件。 4. 无法重命名解决 `sudo gedit /etc/X11/xinit/xinput.d/scim`, 将文件中的 `GTK_IM_MODULE=xim QT_IM_MODULE=xim` xim 改为 scim,保存退出 5. ubuntu 备份当前所装软件,生成当前安装软件的内容列表 `dpkg --get-selections | grep -v deinstall > ubuntu.files` 重装后,配好 sources.list 后 `dpkg --set-selections < ubuntu.files` 按提示安装。 <file_sep>/_posts/2014-03-17-distribute-ipa-with-self-signed-ssl-certificate-on-ios-71.markdown --- layout: post title: "通过自签名 SSL 证书分发安装 IPA" date: 2014-03-17 23:21:09 +0800 --- iOS 7.1 通过 `itms-services://` 安装 IPA 时要求 `ipa.plist` 必须 HTTPS 环境,不然会提示证书错误而无法安装。简单解决可以把 ipa.plist 放在 Dropbox 等支持 HTTPS 访问的地方,不过这样就不方便一键打包部署。其实可以通过自签名的 SSL 证书来解决这个问题。 1.创建自签名 CA 根证书,方便自动信任该 CA 所签发的证书: ``` openssl genrsa -out CA.key 2048 openssl req -x509 -new -key CA.key -out CA.cer -days 730 -subj /CN="Custom CA" ``` 2.将 `CA.cer` 通过邮件等分发安装到设备作为信任证书。 3.创建 HTTPS URL 需要的密钥和证书: ``` openssl genrsa -out ipa.key 2048 openssl req -new -out ipa.req -key ipa.key -subj /CN=ipa.site.com openssl x509 -req -in ipa.req -out ipa.cer -CAkey CA.key -CA CA.cer -days 365 -CAcreateserial -CAserial serial ``` 4.上传 `ipa.cer` 和 `ipa.key` 到服务器,比如 `/etc/nginx/ssl` 目录下。 5.设置 Nginx 使用自签名证书: ``` server { listen 443; server_name ipa.site.com; ssl on; ssl_certificate /etc/nginx/ssl/ipa.cer; ssl_certificate_key /etc/nginx/ssl/ipa.key; location / { root /home/fannheyward/ipas; index index.html index.htm index.php; } gzip on; } ``` 6.注意修改脚本里 ipa.plist 地址和 ipa 地址为 HTTPS. <file_sep>/_posts/2013-05-14-how-facebook-build-facebook-for-ios.markdown --- layout: post title: "How FB Build Facebook for iOS" date: 2013-05-14 11:46 --- [Mobile DevCon New York - How We Built Facebook for iOS][1] 非常值得一看,介绍了 FB 开发 Facebook.app 的工作流。摘要记录几点: 1. Core Team, support and assist. 主要负责不同应用之间通用库、共用功能的开发,保证应用的稳定性。//这也是目前我在做和努力的方向,接下来是团队内跨应用支持。 1. Release process. FB 有专门的 release team,效仿 Mozilla 每四周发布流程,如果发布周期有功能还不稳定就通过 `#define` runtime 屏蔽。//快速迭代。 1. DON'T BREAK MASTER. git branch 进行功能开发,team code review,然后自动编译测试(CI),通过后合并到 master。 //非常标准的 git workflow,说着容易做到难,尤其是坚持一直这样做。 1. Phabricator code review and CI. [Phabricator][2] 是 FB 开发的 code review 工具,附带 `arc lint` 代码分析工具,enforce style guidelines, set up rules to catch common mistakes. 1. Multiple Builds. 不同的 BundleID 来分发测试 Development build/Daily buid/App Store build。 //目前我们的 daily build 还是手动挡,接下来配上 CI 试试自动化。 1. Testing. 由于 iOS 测试工具链的不成熟和复杂(Data, UI),FB 采用 Xcode 自带的测试,配合丰富的 Logs+view hierarchy. //目前我们在用 [Lumberjack][3] log 工具,非常不错。 感叹 FB 如此大规模的公司还能如此敏捷开发,技术驱动,而非行政干预,嗯。 [1]:https://developers.facebooklive.com/videos/337/mobile-devcon-new-york-how-we-built-facebook-for-ios [2]:http://phabricator.org/ [3]:https://github.com/robbiehanson/CocoaLumberjack <file_sep>/_posts/2012-09-07-nspredicate-notes.markdown --- layout: post title: "NSPredicate Notes" date: 2012-09-07 18:48 --- 在 Core Data 中可以给 NSFetchRequest 指定一个 predicate 来对数据进行过滤以方便查找,比如: ```objc fetchRequest.predicate = [NSPredicate predicateWithFormat:@"id == %@", 123]; ``` NSPredicate 的过滤查询规则不仅仅适用于 Core Data,字符串过滤也很方便。比如: ```objc NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@", @"hello"]; BOOL b = [predicate evaluateWithObject:@"hello world"]; // YES ``` 字符串支持的判断语法有 `contains` `beginswith` `endswith` `like` `matches` `and/or/not/in` ```objc NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH %@", @"hello"]; BOOL b = [predicate1 evaluateWithObject:@"hello world"]; // YES BOOL n = [predicate1 evaluateWithObject:@"nohello world"]; // NO ``` `like` 匹配,支持 `*` 任意字符(可无),`?` 有且仅有一个字符: ```objc NSPredicate *like = [NSPredicate predicateWithFormat:@"SELF LIKE %@", @"*like?"]; NSLog(@"%d", [like evaluateWithObject:@"alike"]); // 0-NO NSLog(@"%d", [like evaluateWithObject:@"000liked"]); // 1-YES NSLog(@"%d", [like evaluateWithObject:@"likes"]); // 1-YES ``` `matches` 正则匹配: ```objc NSPredicate *match = [NSPredicate predicateWithFormat:@"SELF MATCHES '\\\\d+[a-z]'"]; NSLog(@"%d", [match evaluateWithObject:@"0A"]); // NO NSLog(@"%d", [match evaluateWithObject:@"0a"]); // YES NSLog(@"%d", [match evaluateWithObject:@"000000ab"]); // NO NSLog(@"%d", [match evaluateWithObject:@"000000c"]); // YES ``` NSPredicate 可以组合起来用,这也是最为方便的地方,比如下面这个例子: > 字符串以 CH 开头,长度大于 3 而小于 20 字符,包含至少一个数字,不包含 broken,不包含空格。 ```objc NSPredicate *one = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH 'CH'"]; NSPredicate *two = [NSPredicate predicateWithFormat:@"SELF.length > 3 AND SELF.length < 20"]; NSPredicate *three = [NSPredicate predicateWithFormat:@"SELF MATCHES '.*\\\\d.*'"]; NSPredicate *four = [NSPredicate predicateWithFormat:@"NOT(SELF CONTAINS 'broken') AND NOT(SELF CONTAINS ' ')"]; NSArray *array = [NSArray arrayWithObjects:one, two, three, four, nil]; NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:array]; NSLog(@"%d", [predicate evaluateWithObject:@"CH998broken"]); // NO NSLog(@"%d", [predicate evaluateWithObject:@"CH998"]); //YES ``` `@"attributeName == %@"`: the value of the key attributeName is the same as the value of the object(NSDate, NSNumber, NSDecimalNumber, or NSString). 完全相等判断。 `@"%K == %@"`: the value of the key %K is the same as the value of the object %@. key 对应的值和给定的值相等。 `@"name IN $NAME_LIST"`: the value of the key name is in the variable $NAME_LIST. `@"'name' IN $NAME_LIST"`: the constant value 'name' (note the quotes around the string) is in the variable $NAME_LIST. 判断值是否在指定列表中,前者判断是 `name` 对应的值,后者 `'name'` 就是判断 name 字符串。 参考资料: - [NSPredicates for Fun and Profit][1],非常不错的 NSPredicate 介绍 - 苹果文档 [Predicate Programming Guide][2]. [1]:https://speakerdeck.com/u/kognate/p/nspredicates-for-fun-and-profit [2]:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html <file_sep>/_posts/2010-07-12-basehttpserver-serving-gziped-content.markdown --- layout: post title: "BaseHTTPServer serving Gziped content" --- BaseHTTPServer 使用 gzip 压缩处理 html/xml 文档。 ``` import cStringIO, gzip zbuf = cStringIO.StringIO() zfile = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=zbuf) zfile.write(xmlstring) zfile.close() compressed_content = zbuf.getvalue() self.send_response(200) self.send_header("Content-Type", "text/xml") self.send_header("Content-Length", str(len(compressed_content))) self.send_header("Content-Encoding","gzip") self.end_headers() self.wfile.write(compressed_content) self.wfile.flush() ``` <file_sep>/_posts/2014-01-01-in-a-flash.markdown --- layout: post title: "匆匆" date: 2014-01-01 20:54 --- 李剑青 -「匆匆」: > 离家时故作轻松 留给娘的是匆匆 那些过时的青春梦 普通得不能再普通 你肯定懂 褪尽了青涩和懵懂 当人在异乡才知感动 <file_sep>/_posts/2018-12-25-python-development-environment-2019.markdown --- layout: post title: Python Development Environment 2019 date: 2018-12-25 11:41:14 +0800 --- > macOS 1. `brew install python` to install python 3 2. `python3 -m venv .venv` or `virtualenv -p $(which python3) .venv` 3. `source .venv/bin/activate` 4. `pip install 'python-language-server[all]'` to install pyls, will switch to MSPyls. 5. coding 6. `deactivate` to leave No more pyenv, pipenv, use pipsi to install utils written in Python. <file_sep>/_posts/2011-12-02-dlog.markdown --- layout: post title: "DLog" date: 2011-12-02 10:41 --- DLog is almost a drop-in replacement for NSLog. via [The Evolution of a Replacement for NSLog](http://iphoneincubator.com/blog/debugging/the-evolution-of-a-replacement-for-nslog) ```objc // DLog is almost a drop-in replacement for NSLog // DLog(); // DLog(@"here"); // DLog(@"value: %d", x); // Unfortunately this doesn't work DLog(aStringVariable); you have to do this instead DLog(@"%@", aStringVariable); #ifdef DEBUG # define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DLog(...) #endif ``` <file_sep>/_posts/2017-05-18-nginx-tls-1.2.markdown --- layout: post title: TLS 1.2+ in Nginx date: 2017-05-18 15:09:43 +0800 --- 小程序要求 HTTPS 并且 TLS 1.2 以上,不然会报错: > 小程序要求的 TLS 版本必须大于等于 1.2 Nginx 下需要用新版 OpenSSL 重新编译 Nginx。官网下载新版 [OpenSSL](https://www.openssl.org/source/) 和 Nginx: ``` ./configure —with-http_ssl_module —with-openssl=/home/page/soft/openssl-1.0.2k -j8 make -j8 make install ``` [重启 Nginx](https://fann.im/blog/2014/03/21/upgrade-nginx-on-the-fly/) 即可。 <file_sep>/_posts/2016-05-30-monthly-review-1605.markdown --- layout: post title: Monthly Review 2016-05 date: 2016-05-30 10:26:20 +0800 --- 1. 开始设计师面试。除了运营,团队算是全新组建,1.5 客户端 + 1.5 服务端 + 1 设计师。 2. App 终于通过审核上线,暂时松了一口气,近一个月的压力实在是大。 3. 另外一个 App 被下架,后重新包装上线,network-based 终究还是出了问题。 4. 五一回家六六都会给爸妈表演节目了,待房子通风散味就接过来北京。 3. 回家才知道,去年冬天爸爸做的活最后被耍赖不给钱,闹到村委也是无用,最后只结了一半的工钱,爸今年也不再带人接活,想必心情很不好受。 <file_sep>/_posts/2010-01-19-urlfetch-login-renren-on-gae.markdown --- layout: post title: "GAE urlfetch 登陆人人" --- 其实 Python 中一般都是直接用 urllib.urlopen() 来抓取网页内容或者模拟登陆等操作,但是 GAE 出于安全考虑不可以用 urlopen 操作,取而代之的就是 urlfetch.fetch()。fetch() 函数参数: `fetch(url, payload=None, method=GET, headers={}, allow_truncated=False, follow_redirects=True, deadline=None)` ```python def login_renren(self): login_url = 'http://passport.renren.com/PLogin.do' login_data = urllib.urlencode( { 'domain':'renren.com', 'email': renren_username, 'password': <PASSWORD>, 'origURL':'http://home.renren.com/Home.do', }) result = urlfetch.fetch( url = login_url, payload = login_data, method = urlfetch.POST, headers = {'Cookie':make_cookie_header(cookie), 'Content-Type':'application/x-www-form-urlencoded', 'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6' }, follow_redirects = False) ``` 继续学习 GAE。 <file_sep>/_posts/2010-12-31-happy-new-year-2011.markdown --- layout: post title: "Happy New Year 2011" --- ![Happy 2011](http://www.google.com/logos/2010/newyear11-hp.jpg) <file_sep>/_posts/2021-03-18-spark-notes.markdown --- layout: post title: Spark Notes date: 2021-03-18 16:54:53 +0800 --- Some Spark articles are worth deep reading: ## [spark-notes](https://spoddutur.github.io/spark-notes/) 1. leave **1 core per node** for Hadoop/Yarn/OS deamons 1. leave **1G + 1 executor** for Yarn ApplicationMaster 1. **3-5 cores per executor** for good HDFS throughput ```text Full memory requested to yarn per executor = spark.executor.memory + spark.yarn.executor.memoryOverhead spark.yarn.executor.memoryOverhead = Max(384MB, 7% of spark.executor.memory) ``` So, if we request 15GB per executor, actually we got `15GB + 7% * 15GB = ~16G` ![MemoryOverhead](https://user-images.githubusercontent.com/22542670/27395274-de840270-56cc-11e7-8f3a-f78c4eecdac8.png) ```text 4 nodes 8 cores per node 50GB per node 1. 5 cores per executor: --executor-cores = 5 2. num cores available per node: 8-1 = 7 3. total available cores in cluster: 7 * 4 = 28 4. available executors: (total cores/num-cores-per-executor), 28/5 = 5 5. leave one executor for Yarn ApplicationMaster: --num-executors = 5-1 = 4 6. number of executors per node: 4/4 = 1 7. memory per executor: 50GB/1 = 50GB 8. cut heap overhead: 50GB - 7%*50GB = 46GB, --executor-memory=46GB 4 executors, 46GB and 5 cores each 1. 3 cores per executor: --executor-cores = 3 2. num cores available per node: 8-1 = 7 3. total available cores in cluster: 7 * 4 = 28 4. available executors: (total cores/num-cores-per-executor), 28/3 = 9 5. leave one executor for Yarn ApplicationMaster: --num-executors = 9-1 = 8 6. number of executors per node: 8/4 = 2 7. memory per executor: 50GB/2 = 25GB 8. cut heap overhead: 25GB * (1-7%) = 23GB, --executor-memory=23GB 8 executors, 23GB and 3 cores each ``` ## [Spark + Cassandra, All You Need to Know: Tips and Optimizations](https://itnext.io/spark-cassandra-all-you-need-to-know-tips-and-optimizations-d3810cc0bd4e) 1. Spark on HDFS has **low** cost, used in most cases 1. Spark with Cassandra in same cluster, will have best performance in throughput and low latency 1. [Deploy Spark with an Apache Cassandra cluster](https://opencredo.com/blogs/deploy-spark-apache-cassandra/) 1. [Spark Cassandra Connector](https://github.com/datastax/spark-cassandra-connector) 1. [Cassandra Optimizations for Apache Spark](https://itnext.io/cassandra-optimizations-with-apache-spark-3ddf7f81ce43) ### Spark Optimizations 1. **Narrow transformations than Wide transformations** 1. minimize data shuffles 1. filter data as early as possible 1. set the right number of partitions, **4x of partitions** to the number of cores 1. avoid data skew 1. broadcast for small table joins 1. repartition before expensive or multiple joins 1. repartition before writing to storage 1. be remember that repartition is an expensive operation 1. set right number of executors, cores and memory 1. get rid of the the Java Serialization, use [Kryo Serialization](https://github.com/EsotericSoftware/kryo) 1. **Minimize data shuffles and maximize data locality** 1. **Use Data Frames or Data Sets high level APIs to take advantages of the Spark optimizations** 1. [Apache Spark Internals: Tips and Optimizations](https://itnext.io/apache-spark-internals-tips-and-optimizations-8c3cad527ea2) <file_sep>/_posts/2013-12-31-self-review-2013.markdown --- layout: post title: "[self review:2013];" date: 2013-12-31 17:11 --- 2013 年度个人总结。先对照去年计划。 ### 工作 > iDev 深入,比如 runtime,自动化测试等,尝试一下 OS X 开发。 Fail。 > 服务端开发学习。 Done. > 学一门新语言,Lua/Go。 Done. ### 生活 > 学车考驾照。 Done. > 健身锻炼。 Fail. 60 及格分。 ---- ### 工作 虎头蛇尾。 按照去年的个人工作计划,今年有意加强了服务端开发,加上团队的支持,取得了一点点[成绩][1],但总体来说今年的工作暴露了自己很多的问题。 1. 产品能力欠缺。随着规模的扩大,团队有意识的让几个老员工尝试开发+产品管理双轨制,在大家都比较顺利的转型成功干的热火朝天的时候,自己这边却一直没啥起色。主要原因是自己对产品热情不够,缺乏长期的对某个产品的深入思考,给人的感觉就是这个东西只了解了表层,对整体发展方向没有深挖扩展,很少有价值的建设性意见。也许是因为一直以来的项目都有具体产品负责人,也许是因为太偏向技术,总之现在自己的产品能力和大家有很大差距,游离在团队核心边缘。 1. 带团队的能力不足。作为 leader 对项目进度的把控经常出现偏差,缺乏规划、进度检查和反思,没有及时提早发现问题,往往等出现问题已经是很严重了。另外一方面就是对团队氛围建设的忽视,很多时候只关注自己手头的事,没有调动大家对项目的信心和积极性。这个的原因可能和自己做开发出身比较偏向温和、自觉的做事方式有关,忽视了团队的执行力,在协同工作没有起到引导作用。 1. 开发以外的沟通较少。不管是项目内还是和其他项目组之间关于产品、运营、测试等等方面的沟通交流都不多,这个完全就是自己原因,产品热情不高,一步慢步步慢。 1. iOS 开发深度挖掘不够。不仅深度挖掘不够,甚至已有技术都有些生疏。下半年 iOS 7 的发布了解关注了大量的新增特性,但只有理论学习,缺乏实际项目实践,完全是纸上谈兵,更别说 runtime 等深入。iOS 开发能力没有提升,这才是自己最大的危机感。 1. 服务端技术深度不够。目前自己服务端能力只是应用层问题的解决实现,在出现框架或偏底层问题的时候就没了思路,考虑问题不周全,容易跑偏。 1. Full-Stack 很容易多个都知道,多个都不精。这就是自己目前的技术现状,接下来要做的就是技术的深学习,基础,体系架构。 1. 执行力不够。以上问题的原因都可以归结于一点,自己的执行力还很不够,看看 iDevNotes 还有几篇笔记未完成,LearnList 那么多没看,包括 HackingWeek 项目的停滞,出现这些问题也就没啥奇怪了。这才是自己最大的问题。 反思自己的问题很容易,改进才是难点。先从执行力入手,多思考产品,多学习,找准自己在团队中的位置。 ### 生活 2013-10-20,[准爸爸][2]。这就是今年生活上最大的变化。 老实讲,在刚升级做爸爸的那一段时间,大概十月底到十一月中上旬,自己还没有做好这种变化的心理准备。突然之间许多事情扑面而来,回家生还是北京生,要不要在北京建档,要办各种证,要不要换房子等等,这些问题被自己的想象放大为很大的压力,感觉就要压垮自己,结果就是那一段时间脾气很不好,很容易上火生气,状态也定然不好,尽管已尽量克制,但还是影响到工作。 本来老婆应该是需要照顾的人,结果却反了过来让老婆开导我。还好我们比较顺利的解决了各个问题,尽我们能力去做,坦然面对。自己的状态也调整过来,做爸爸对男人来说就是一次心智再成熟的过程。 ---- ## 2014 ### 工作 1. 产品、管理的转型,提高执行力。 1. 技术深度的挖掘。 1. 一年一门新语言,Golang. ### 生活 1. 迎接宝宝的到来。 1. 带爸妈和妹妹旅游一次,带他们来北京? [1]:https://fann.im/blog/2013/06/30/self-review-at-half-year-2013/ [2]:https://fann.im/blog/2013/10/20/daddy-to-be/ <file_sep>/_posts/2014-08-16-octopress-to-jekyll.markdown --- layout: post title: "Octopress to Jekyll" date: 2014-08-16 14:38:51 +0800 --- 周末花时间把 blog 从 [Octopress 2][1] 迁移到 [Jekyll][2]。 Octopress 是个非常好的 Jekyll-blog 解决方案,尤其是在 Jekyll 0.x 时代,Octopress 有不错的模版,丰富的扩展功能,缺点就是麻烦,需要在本地生成页面。 Jekyll 在过去一年[开发迭代非常快][3],大量的新功能新特性加入让 Octopress 显得不那么必要。GitHub Pages 最近也升级[支持 Jekyll 2.2][4],于是就有了这次迁移。 1. 通读 [Jekyll 文档][5],了解新功能特性。 2. 本地安装 `gem install github-pages`,模拟 GitHub Pages 环境测试。 3. 修改 `permalink: /blog/:year/:month/:day/:title` 保持链接不变。 4. 设置 markdown 解析器为 `markdown: redcarpet`,支持 GFM。 5. 分页设置 `paginate: 10 paginate_path: "blog/page/:num"`,保持兼容。 6. 配置 Google Analytics,Webmaster Tools 等。 测试没问题推送到 GitHub 即可。 [Octopress 3][6] 也改变策略,不再那么复杂,只是对 Jekyll 操作进行二次封装,方便使用。目前来看封装的功能都不太需要,一个简单的 Rakefile 就够了。 [1]:http://octopress.org/ [2]:http://jekyllrb.com/ [3]:https://github.com/jekyll/jekyll/releases [4]:https://github.com/blog/1867-github-pages-now-runs-jekyll-2-2-0 [5]:http://jekyllrb.com/docs/home/ [6]:https://github.com/octopress/octopress<file_sep>/_posts/2008-03-04-ubuntu-setup.markdown --- layout: post title: "Ubuntu安装教程" --- 电脑配置:华硕A6QT52,炫龙TL52,1.5G内存,80G HD,nVIDIA 7300独显。 ubuntu安装盘用的是Live-CD,版本7.10,在xp下面装的双系统,最后一个空盘10G完全格掉的。当初装的时候感觉10G挺大的,不过现在装的东西越来越多,就有点紧张了,所以如果空闲空间大的话还是大一点好,最少得6G。安装过程相当简单,就手动分区时候留点神就好,简单记录一下。 1. 开机时候按住Esc,选择CD启动,按F2选择简体中文,选择启动或安装ubuntu系统,进入live-CD。live-CD可以光盘运行,并不会读写硬盘,这样可以先看看ubuntu的桌面环境,要是不喜欢的话退出,不会对硬盘有啥损害。不知道Windows XXX的安装会不会用这种方法,:) 2. 桌面Install,双击,前面的几步默认都行,语言,时区,键盘布局,都很简单。 3. 然后就是整个过程最有“技术含量”的手动分区。选中你要安装的分区,Del partition,然后选择free space,点击New partition,先新建根分区,选择分区类型:Primary(主分区),输入新分区的大小(以MB为单位),根目录4-5G吧,然后选择新分区的位置,一般都是“开始”位置,文件系统格式一般用ext3或ReiseFS,然后是挂载点,我选的是“/”根目录,点击“OK”确认。这样就新建了根分区,要是硬盘大的还可以创建一个/home分区,是用户自己的文档目录,空间不够的话这个可以省掉。但是/Swap分区一定得要的,相当于Windows的虚拟分区,不必过大,一般按内存1-2倍大小设置,文件系统就是swap,不用选择挂载点。分区结束,点击继续下一步。 4. 下一步提示转移Windows下面的个人文档资料,留空不选,进下一步设置用户名、密码,最后一步了,确认安装信息,安装过程一般20分钟左右。还有一点,装的时候最好把网线拔掉,不然ubuntu会自动联网更新,这样会很慢。 安装完成后重启就可以看见ubuntu启动项,选择进去吧,开始ubuntu之旅。 <file_sep>/_posts/2010-06-09-coming-to-beijing.markdown --- layout: post title: "帝都我来了" --- 跟一个以技术为新的团队做最新潮的东西,多么畅快的事! @Appwill rocks! <file_sep>/_posts/2013-03-07-ios-crash-report-service-comparison.markdown --- layout: post title: "iOS Crash Report Service Comparison" date: 2013-03-07 23:19 --- 实验对比一下现有的 iOS Crash report 服务。包括 [Google Analytics(GA)][1], [Crashlytics][2], [TestFlight][3], [HockeyApp][4]/[QuincyKit][5]/[HockeyKit][6], [Crittercism][7], [Bugsense][8], [Flurry][9]. Google Analytics ---- 1. 手动或 CocoaPods 添加库,设置统计 ID,开启 trackUncaughtException,使用很简单。 1. Crash 报表比较简陋,可以根据应用版本号、iOS 版本区分,然后根据 crash description 分类,堆栈描述信息比较少,只有 crash 部分栈信息。 1. 通过 try-catch 可以有目的性的对 NSException、NSerror 进行捕捉。 1. GA 2.0 仍在 beta,稳定性需要验证 。 1. 免费。 **GA 集成,可以少添加一个库,类似统计的方式做 crash report,crash 信息比较简单,适合简单使用。** Crashlytics ---- 1. 相较其他库手动添加或者用 CocoaPods 方式引入,Crashlytics 需要一个软件来集成,刚开始会比较不习惯。按流程走,选中项目,添加 Build Phase-Run Script,添加 framework,设置 APIKey,Done。 1. 堆栈信息完善,crash 自动分类,然后作为一个 issue 列出,可以列出 crash 设备信息 (JailBroken, free space, free RAM,屏幕旋转方位,network type 等),这些信息对于 crash 筛选和原因查找会有很大帮助。 1. issue 有 open/close 两个状态,方便解决统计。 1. 支持 developer team。 1. 被动收集,没有主动收集方式。 1. crash 邮件报告,支持 Redmine 等第三方服务集成,方便 bug 提交管理。 1. 被 Twitter 收购后[企业版改为免费][10]。 **Crash 信息完善,分类清晰,适合对 crash report 要求比较高的场景使用。** TestFlight ---- 1. 手动或 pod 添加,打包上传到 TestFlight,获取 token。使用逻辑比较混乱,先上传 app 才能拿到 token。 1. 支持应用分发,feedback,remote logs,Sessions,Checkpoint 等统计功能。 1. 单纯 crash 的话使用还比较简单,不需要做特殊处理,其他功能需要针对处理。 1. crash 发送好像有点问题,crash 了几次后服务器都没有收到,所以也没法看到 crash 统计。 1. 支持 developer team。 1. 免费。 **看起来功能很多,但是都不够深度,crash report 功能不堪大用。** HockeyApp/QuincyKit/HockeyKit ---- 1. pod 添加 SDK,打包上传,获取 token;手动添加流程看起来非常麻烦。 1. crash 自动分类,栈信息完整,会把关键信息提炼出来。crash status-Open/Resolved/Ignored。 1. 支持应用分发、feedback。 1. 支持和第三方 bug tracker 集成。 1. HockeyKit、QuincyKit 是开源版本的 HockeyApp,均有客户端和服务端代码,QuincyKit 只有 crash report,HockeyKit 只有应用分发和更新。 1. 手动上传 dSYM。 1. HockeyApp 收费,免费试用一个月。 **简单说就是 TestFlight 加强版,应用分发 + crash report.** Crittercism ---- 1. 使用简单,先在网站注册一个应用,获取 token,不需要上传 ipa 到网站。 1. 按 crash 原因归类,堆栈信息完整,高亮标明主要信息。crash 报表清晰,可以很明确的查看 crash 历史,设备信息(RAM,iOS version,device,network 等)。 1. 支持主动有目的性 exception 收集。 1. 支持 crash status(unresolved,resolved,known)。 1. 需要手动上传 dSYM,估计是为了 release 下使用。 1. 支持 crash alarm,SMS、邮件接收,支持 Uservoice 服务集成。 1. 支持 developer team。 1. 居然还有一个 rate app alert 功能。。。 1. 有免费套餐,专业版支持简单的应用统计。专业版每月活跃用户 100K (per 100k MAU),限制比较大。 1. 初创公司,获得风投,和 Crashlytics 气质最像的一个。 **功能强大的专业的 crash report 服务。** Bugsense ---- 1. 网站注册应用,获取 token。 1. 客户端是用 PlCrashReporter 做 crash 收集。 1. crash report 可以按 status/App version/OS version 过滤 (付费版)。 1. 发送 crash report 的时候可以附带一些自定义数据。 1. 有一个比较神奇的功能,Fix Notification,如果某个 crash 已经标记为 resolved 并且新版本已经上线,可以弹窗提醒用户该 crash 已经解决,引导用户去更新升级 (付费版)。 1. crash 收集服务被墙。 There are cases where our servers are being blocked due to geographic restrictions (e.g. China). 1. 应用应用使用统计,支持 Event 统计 1. 免费版限制太多,基本不可用。 **相对来说功能比较简单的 crash report 服务。** Flurry ---- 1. 网站注册应用,获取 application key。 1. 做统计出身,所以 crash report 功能只能算是一个附属功能,crash log 非常简单。 1. 免费。 **统计服务附带 crash report,功能简单。** 小结 ---- 1. crash report 要求不高且在用 GA/Flurry 统计的话,直接用附带的。 1. 需要更为专业详细的 crash report,Crashlytics/Crittercism 二选一。 1. 需要应用分发的话上 HockeyApp。 ---- 个人倾向于 Crashlytics。原因: 1. 内部测试应用分发都比较简单,可以用脚本+内部服务器搞定,比如这个 [build.py][11]。 1. Crittercism 有 MAU 限制,付费升级到 Premium 也限制 100K MAU。 1. Twitter 收了 Crashlytics 后很大方的把企业版免费,开发也在继续。 1. Crashlytics 的网站设计更喜欢一些。 [1]:https://developers.google.com/analytics/devguides/collection/ios/v2/ [2]:https://crashlytics.com [3]:https://testflightapp.com [4]:http://hockeyapp.net/ [5]:http://quincykit.net/ [6]:http://hockeykit.net/ [7]:https://www.crittercism.com [8]:http://bugsense.com/ [9]:http://www.flurry.com/flurry-crash-analytics.html [10]:http://www.crashlytics.com/blog/crashlytics-enterprise-is-now-free/ [11]:https://gist.github.com/fannheyward/4159383 <file_sep>/_posts/2011-07-11-the-price.markdown --- layout: post title: "高房价" --- 中国的高房价,毁灭了年轻人的爱情,也毁灭了年轻人的想象力。他们本可以吟诵诗歌、结伴旅行、开读书会。但现在,年轻人大学一毕业就成为中年人,像中年人那样为了柴米油盐精打细算。他们的生活,从一开始就是物质的、世故的,而不能体验一段浪漫的人生,一种面向心灵的生活方式。——西班牙《世界报》 <file_sep>/_posts/2012-02-14-ios-simulator-ui-debug-tools.markdown --- layout: post title: "iOS 模拟器界面调试小工具" date: 2012-02-14 10:27 --- 不知道 Xcode 什么时候添加进来的功能,在模拟器 Debug 菜单下选中 **Color Blended Layers** 可以很方便的查看界面元素排版布局。 ![Color Blended Layers](https://i.loli.net/2019/04/29/5cc695e75dd34.jpg) BTW, 现在在模拟器可以直接 Command+S 来截图了。 <file_sep>/_posts/2010-04-28-my-first-ajax-script.markdown --- layout: post title: "My first Ajax script" --- ``` <div id = "chatcontent"> Loading… </div> <script> function updateMsg(){ $.ajax( { url:"/messages", cache:false, success:function( html ){ $("#chatcontent").html( html ); } } ); setTimeout( ‘updateMsg()’,1000 ); } updateMsg(); </script> ``` <file_sep>/_posts/2012-04-22-autoreleasepool-in-loop-or-loop-in-autoreleasepool.markdown --- layout: post title: "@autoreleasepool in loop or loop in @autoreleasepool" date: 2012-04-22 16:14 --- 如果循环中会生成大量的 autorelease 对象,可以考虑用 autorelease pool 来进行封装。封装时候有两种方式: 1: ``` while ([rs next]) { @autoreleasepool { NSDictionary *dict = [self dictFromXX]; //... } } ``` 2: ``` @autoreleasepool { while ([rs next]) { NSDictionary *dict = [self dictFromXX]; //... } } ``` 第一种,也就是 @autoreleasepool in loop 方式下每次循环都会生成一个 pool,在单次循环结束后被 drain 掉,适用于每次循环都有大量的 autorelease 对象生成,在单次循环结束后可以及时的将资源释放。 第二种,loop in @autoreleasepool 下只有一个 pool,只会在整个循环结束后 drain 掉,也就是说第一次循环时生成的 autorelease 对象也要等到整个循环结束时候才会随着 pool 释放。适用于循环次数不太多,且每次循环只有少量的 autorelease 对象生成,毕竟这些对象都要等到循环结束后才会被释放。 ref [@autoreleasepool in loop or loop in @autoreleasepool?][1] [1]:http://stackoverflow.com/questions/10121345/autoreleasepool-in-loop-or-loop-in-autoreleasepool <file_sep>/_posts/2010-09-20-objective-c-notes.markdown --- layout: post title: "Objective-C Notes" --- //string1 将被自动释放 > `NSString* string1 = [NSString string];` //必须在用完后手工释放 > `NSString* string2 = [[NSString alloc] init]; [string2 release];` ------------- Typically, each class gets two files: a header file that contains the @interface for the class and a dot-m file that holds the @implementation. 类的接口(interface)通常存放在类似ClassName.h的文件中,在这里,我们定义实例变量和公用(public)方法。 类的实现存放在ClassName.m这样的文件中,它包含了这些方法的实际实现代码。它通常还定义了客户类不能访问的私有(private)方法。 ------------------ 方法名字前面的单个减号(-)表明该方法是一个实例方法。如果方法名字前面是一个加号(+),则表明该方法是一个类(static)方法。 --------- dealloc方法在一个对象从内存中删除时被调用。通常在这个方法里面释放所有对象里的实例变量。 Objective-C的内存管理是基于引用计数的。 一个实例变量的设置器(setter)会自动释放(autorelease)原来引用的对象,同时保留(retain)新的。你只需要保证在dealloc函数中释放 (release)了它就行了。 + When you create an object using new, alloc, or copy, the object has a retain count of 1. You are responsible for sending the object a release or autorelease message when you’re done with it. That way, it gets cleaned up when its useful life is over. + When you get hold of an object via any other mechanism, assume it has a retain count of 1 and that it has already been autoreleased. You don’t need to do any further work to make sure it gets cleaned up. If you’re going to hang on to the object for any length of time, retain it and make sure to release it when you’re done. + If you retain an object, you need to (eventually) release or autorelease it. Balance these retains and releases. 如果过你通过alloc或者copy创建了一个对象,在函数结尾的地方给它发送一个release或者autorelease消息就行了。如果你是通过其它方式创建的对象,就什么也别做。“If I get it from new, alloc, or copy, I have to release or autorelease it.” ----------------- 类目允许你为一个已存在的类添加一些方法而不用子类化该类,也不需要你了解该类的实现细节。 `@property (retain) NSString* caption;` @property 是Objective-C语言的一个指令,通过它声明属性。带括号的"retain"指示设置器(setter)要保留输入值,该行后面的是指定属性的类型以及名称。 @synthesize 指令为我们主动生成了setter和getter. ----------- @class sets up a forward reference. This is a way to tell the compiler, "Trust me; you’ll learn eventually what this class is, but for now, this is all you need to know." ------------------- The colored boxes next to the name indicate what the symbol is: E for an enumerated symbol, f for a function, # for a #define, m for a method, C for a class, and so on. Chose **File-Make Snapshot** (or its handy shortcut, Command-Control-S) and Xcode will remember the state of your project. <file_sep>/_posts/2011-11-30-new-blog-again.markdown --- layout: post title: "New Blog again" date: 2011-11-30 11:42 --- 最近 [Octopress][1] 火热,比如 [Why Octopress?][2]。忍不住手痒也来一个,花了半天时间把两年前的 Wordpress 和去年到现在的 Picky 都转移到 Octopress,目前表现良好,情绪稳定。 新的开始会更关注移动应用,毕竟是做这方面的,技术方面希望能输出一些代码吧。当然,生活碎碎念也肯定少不了。 [1]: http://octopress.org [2]: http://blog.xdite.net/posts/2011/10/07/what-is-octopress/ <file_sep>/_posts/2017-07-10-30.markdown --- layout: post title: "30" date: 2017-07-10 21:02:48 +0800 --- 而立。 <file_sep>/_posts/2008-12-13-nanking-massacre.markdown --- layout: post title: "Nanking Massacre" --- 其实挺失败的,以前根本不知道南京大屠杀纪念日。昨天鸟儿过来,跟我说每年12月13号,南京就会拉警报,33分钟的警报长鸣,很有气势。今天咱也纪念一下。 如果忘记历史,历史就可能重演。 <file_sep>/_posts/2014-04-08-moving.markdown --- layout: post title: "Moving" date: 2014-04-08 10:53:38 +0800 --- > 如果我提前离开北京,那么房子可能是最大的原因。并不是要买房,而是租房都不让人省心。我只是想踏踏实实的租房,但现实是,房东嫌麻烦一般都把房子交给中介,无良中介又很多,让人心烦。 2013-03-03 来北京后第一次搬家,离开住了将近四年的天通苑。 一直很抗拒搬家,因为找房子搬家是个麻烦事,而我自己不知道从什么时候养成了一个毛病:事情在开始时候过于关注困难的部分,放大了可能出现的问题。这样的结果就是前期过于悲观,继而可能会影响自己的心情。这次也是如此,找房子时候烦中介,收拾东西时嫌东西多又不舍得扔,搬家还得找车找人,连续几天心情都是忽好忽坏。 这个毛病的“好处”就是如果事情发展没有想象中的那么困难,那会非常有干劲,因为最坏的情况已经有了思想准备,后续的发展都可以轻松接受。其实回过头看搬家也没有那么恐怖,我们之前遇到的问题是东西平铺开摆放没有规划,在收拾时就显得很多很杂;中介问题其实也不必过于担心受骗,大一点的中介公司还是很规范的。 Happy Moving. <file_sep>/_posts/2019-01-28-nginx-proxy_next_upstream.markdown --- layout: post title: Nginx proxy_next_upstream non_idempotent date: 2019-01-28 18:12:40 +0800 --- 在 Nginx 做反向代理的时候,我们一般会配置 `proxy_next_upstream`,如果某个 upstream 超时或出错,自动切换到下一个 upstram。 ``` upstream backend{ server 192.168.0.1; server 192.168.0.2; } location /example/ { proxy_pass http://backend; proxy_next_upstream error timeout http_500 non_idempotent; } ``` 这里有一个地方需要注意,`non_idempotent`,Nginx 默认对 non-idempotent 请求,比如 **POST**/LOCK/PATCH,是不进行重试。常见的情况就是 POST 请求出错后不会重试,需要加上该设置。 > normally, requests with a non-idempotent method (POST, LOCK, PATCH) are not passed to the next server if a request has been sent to an upstream server (1.9.13); enabling this option explicitly allows retrying such requests; <file_sep>/_posts/2012-07-12-preview-and-copy-text-from-quicklook.markdown --- layout: post title: "Preview and Copy text from QuickLook" date: 2012-07-12 09:18 --- 1. Enable QuickLook for all plain text file with [QLStephen][0] 1. Open Terminal and run following code: > defaults write com.apple.finder QLEnableTextSelection -bool true; killall Finder 1. Done. via [1][1], [2][2] [0]:https://github.com/whomwah/qlstephen/downloads [1]:http://coderwall.com/p/dlithw [2]:http://coderwall.com/p/94rlia <file_sep>/_posts/2008-06-18-sth-of-today.markdown --- layout: post title: "扯淡:Firefox 3,NBA" --- 1. firefox 3终于来了!一个重大改进的版本,一个让人惊喜的版本,噢耶!其实从fx3 beta3的时候就开始用了,那时候最大的问题就是插件扩展的不兼容性,也学习着改版本强制兼容,慢慢的beta 4,beta 5,到RC 1,RC 2,再到正式版,FX 3的改进确实非常明显,速度相当棒,内存泄漏问题也差不多解决掉,嗯,我喜欢! 2. NBA结束了,凯尔特人的冠军。KG终于圆梦,现在联盟里面冠军心最强的人,AI好像也认命了。。。还有阿伦,联盟里面感觉是跟钢琴家希尔一样帅的绅士,很是欣赏啊,congratulation! 3. 开始定火车票了,嗯,快回家啦,哈哈,哦,得先考试完再说。 4. 最近生物钟完全错乱,晚上两点多钟楞是睡不着,哎,熬夜的后果啊。 <file_sep>/_posts/2009-04-03-rebuild-firefox-profiles.markdown --- layout: post title: "重构firefox配置" --- 重构,这词够分量的。今天重构 Fx 配置一大原因就是最新的 vimperator 2.0 跟现在的插件有冲突,应该说是跟 TMP 冲突。其实挺早都想重构一下,因为现在使用的配置是 Fx 2.0 时候一直用到现在的配置,扩展是装了卸、卸了装,把配置弄的都很乱,最明显的就是 prefs.js 文件,最大时有500K+,虽然精简后50K左右,还是有一些乱七八糟的东西在里面,要知道 Fx 新装好也只不过几K而已。重构还有一个原因就是想精简一下扩展,自从用了 vimperator 后好多扩展功能都有重复,可以卸载掉一些。 1. 备份。丢失 Fx 配置文件是比较麻烦的事情,尤其是习惯了自己配好的 Fx 后,要经常的备份配置; 2. 新建配置文件,Fx 是支持多配置的,开始-运行-`firefox -p`,新建一个配置文件; 3. Fx 自身设置,也就是选项里面的一些设置,主要是浏览历史,一般保存三天就足够了,太多太大很拖累 Fx 速度; 4. 放弃了 TMP。TMP 真的是一个非常棒的扩展,有非常丰富的功能,曾经也是我必装的扩展之一。 不过 TMP 的兼容性真不怎么的,经常跟别的扩展有冲突。其实 Fx3 标签页功能相对于 Fx2 时候增强不少了,再加上现在用 vimperattor,没必要使用这么庞大的 TMP 了,换用 Tab-mix-lite-ce,基本标签功能都有,也很轻巧,只有27K,TMP 可是有378K的大个头。 5. 精简扩展,从29个精简到17个,使用不是很多的都给去掉了,扩展太多带来的最大问题就是内存占用。之前 Fx 内存占用一般都在150M+,高峰时候过200M也很频繁。下午重构之后用到现在,没有超过100M,当然,才一下午而已; 6. `about:config` 修改设置。参考了以前的一些设置,改动不大,默认状态已经很不错了。 现在用的扩展: - Adblock Plus - Add to Search Bar//添加了几个搜索后卸掉; - All-in-One Sidebar - Copy Link Name - Custom Buttons//没有用2版,1版的足够,主要添加了隐藏标题栏和右键自动弹出; - DownThemAll! - Easy DragToGo - Firebug - Flashblock - FlashGot - Greasemonkey - Multiproxy Switch - Text Link - Ubiquity - Vimperator vimperator 自动翻页配置: ``` :set nextpattern=\s下一页|下一张|下一篇|下页|后页\s,^\bnext\b,\bnext\b :set previouspattern=\s上一页|上一张|上一篇|上页|前页\s,^\bprev|previous\b ``` <file_sep>/_posts/2009-04-25-my-greasemonkey-script-share.markdown --- layout: post title: "GreaseMonkey自用脚本分享" --- GreaseMonkey 称得上是 Firefox 众多扩展中的神器,通过对 javascript 脚本解释执行来实现对网页进行二次加工,实现一些网页本身不具备的功能。下面是我自己现在用的 Greasemonkey 脚本,分享之,记录之。(排名不分先后) 1. Auto add to Google Reader.解决订阅 RSS 时候自动订阅到 Greader 而不是 Add to Google homepage 和 Greader 的手动选择。 2. RSS+Atom Feed Subscribe Button Generator.简单的说就是自动发现并在页面左上角显示网站可用的 RSS/Atom 地址。 3. HTTP-to-HTTPS redirector.自动替换 URL 中的 Http 为 Https 加密访问,好处都知道,建议手动添加白名单:Twitter,FriendFeed,Google Groups。 4. Wordpress Comments AutoSignature.自动填写 WP 博客回复框里个人信息内容,包括昵称,Email,个人网址,安装后在 about:config 中设置,关键字过滤:wordpress。 5. Auto-Select Inputs and Textareas.鼠标指向输入框/文本框时候自动选定,省去一次点击。 6. Google Time & Language Select.在 Google 搜索框旁边添加选择搜索时间范围和搜索语言选项,其中搜索时间范围很有用,可以指定搜索24小时以内或一周以内的网页。 7. Reply buttons for new Douban.给豆瓣评论/小组/日记等可回复的帖子添加回复和引用按钮。 8. Get Picasaweb Image URL.方便获取各种尺寸的 Picasa Web 图片外链地址。 9. Google Language API Translator Tooltip[modifed].翻译选中的文字,用的是 Google 翻译的 API,可指定各种语言,非常棒。 Greasemonkey 的扩展性和 Fx 的扩展性一样强大,[官网](http://userscripts.org/)上数以万计的脚本极大的丰富了网页功能,带来更为方便的浏览体验。 <file_sep>/_posts/2009-03-30-chain-gun.markdown --- layout: post title: "链子枪" --- 昨晚上跟同学扯淡时候说到小时候玩的东西,想起来链子枪这么个古董级的玩具,就突然非常想再弄一把玩玩。小的时候曾经动手做过几把,然后从家里偷点火柴,跑到外面跟别人比枪,很有玩头。搜了几张图,回头有空了动手再玩玩,找一下小时候枪神的感觉,:-) ![](http://lh6.ggpht.com/_vYr4JQreqXA/SdBqyzWW8tI/AAAAAAAAA1E/GIUHglTM9Ug/s512/2970805288_18c8c7633a_o.jpg) 一个美化过的,很有感觉: ![](http://lh5.ggpht.com/_vYr4JQreqXA/SdBuC8h151I/AAAAAAAAA2c/9wwizy5Dh9U/s512/4acda0a80105ze3y833.jpg) <file_sep>/_posts/2010-10-08-2010-10.markdown --- layout: post title: "2010-10" --- 各种不顺倒霉后,我赶到家,看了爷爷最后一眼,睡的很安静,没有吼人,反而有那么点不适应。回来之前接到爸的电话,说爷爷去了,我第一反应不是我没见着爷爷最后一面,是爷爷没能看一眼他的孙媳妇,爷爷最宠爱的大孙子的老婆,就差那么两天,爷爷等不了。 陪爸妈下地,跟小妹打闹,宠她惯她,紧着时间跟他们在一块,好想不离开家不工作,陪在他们跟前,粘着他们,也挺好。 陪爸妈到半夜,唠叨家里的房子,收成,村里的那些事儿,我们陪爸妈的时间太少了,也真的没有太多了。 妹说:哥,我只能再看你两天了,你又该走了… 那一瞬间,没哭,只流泪。 姐回去之前都不知道爷爷已经走了,大家都不想告诉她,让她开开心心的结婚;到家的那天,我不敢先回去,听爸说姐哭的一塌糊涂。 很巧,姐回门那天正好是爸的生日,爸的本命年。多少年没有在家给爸过生日了,爸,生日快乐,身体健康。 这个假期是这几年离开时我最难受的一个假期,爷爷的离去让我感到陪家人的时间确实太少,妹的懂事让我好不舍得,爸妈的劳累让我好想在家帮他们一把,分担一些,再好好照顾他们一下。 妞妞,五年前的十一,我们认识;三年前的十一,经历了那么多以后我们在一起;原本想今年十一订婚,画个分隔符,从此你是我的未婚妻,我是你的未婚夫,因为爷爷的突然离去,我们没有订婚。乖,你我都知道这只是个时间问题,也只是个形式问题,因为你已经是我的妻,我是你的夫。不管遇到什么,记住我会一直陪在你身边,我会每天都在老地方等你回来,每天通过彼此的那些小时间来记录我们的大幸福。我要你开开心心的,做我的新娘,孩子的妈,那个老婆子。 <file_sep>/_posts/2010-08-31-email-signature.markdown --- layout: post title: "电子邮件签名格式" --- 标准的电子邮件签名格式是:两个连字符,一个空格,然后断行,跟上你的签名信息,纯文本。 > The formatting of the sig block is prescribed somewhat more firmly: it should be displayed as **plain text** in a fixed-width font (no HTML, images, or other rich text), and must be delimited from the body of the message by a single line consisting of exactly **two hyphens, followed by a space, followed by the end of line**. via [Wikipedia:E-mail and Usenet ](http://en.wikipedia.org/wiki/Signature_block#E-mail_and_Usenet) <file_sep>/_posts/2011-05-12-20110504-iphone-4.markdown --- layout: post title: "iPhone" --- 上个月去搞了个 MBP [1], 这个月又花钱,4 号去拿了个 iPhone 4. 当然知道今年有 iPhone 5 出来,但是我不想等了。9 月份出货,年底价格稳定铺货,还得等上半年多,而这半年对我来说又是很重要的半年,不能错失。 买了就不再想,只是留个记号。好好利用,我相信这几千大洋花的值。 [1]:https://fann.im/blog/2011/04/03/20110401-mbp/ <file_sep>/_posts/2021-01-07-forward.markdown --- layout: post title: ~/.forward date: 2021-01-07 10:27:41 +0800 --- `echo '<EMAIL>' > ~/.forward` This will make `smtpd` forwards email to the special address. On AWS EC2, SES can be used to forward email to your Gmail. <file_sep>/_posts/2010-06-25-cdto-open-iterm.markdown --- layout: post title: "cdto open iTerm" --- cdto:Fast mini application that opens a Terminal.app window cd'd to the front most finder window,快速在当前路径打开一个 Termainal。iTerm 是 Mac 下一个增强终端。默认状态下 cdto 是打开系统自带的 Terminal.app,其实 cdto 也是支持 iTerm 的。 右键 Show Package Contents 打开 cdto.app,将 Contents/Plugins Disabled 下的 iterm.bundle mv 替换 Contents/Plugins 下 terminal.bundle 即可。 <file_sep>/_posts/2014-04-15-only-when.markdown --- layout: post title: "Only When" date: 2014-04-15 09:06:28 +0800 --- > Well you only need the light when it’s burning low > Only miss the sun when it starts to snow > Only know you love her when you let her go > Only know you’ve been high when you’re feeling low > Only hate the road when you’re missing home > Only know you love her when you let her go [Let Her Go](http://www.xiami.com/song/1770831056) <file_sep>/_posts/2017-10-11-app-language-in-macos.markdown --- layout: post title: macOS 独立设置应用语言 date: 2017-10-11 09:41:45 +0800 --- 英文系统下让某些应用的语言是中文,可以通过 `defaults` 设置: 1. `defaults read` 查找应用的 bundle ID 2. `defaults write com.apple.Safari AppleLanguages '("zh-Hans-CN")'` 设置应用语言为中文 <file_sep>/_posts/2022-05-05-single-quote-prefix-in-spreadsheet.markdown --- layout: post title: Single Quote Prefix in Google Spreadsheet date: 2022-05-05 15:58:15 +0800 --- When adding/updating cells in Google Spreadsheet, a single quote (`'`) was prefixed to the value. > '2022-05-01 This can be fixed by changing the `valueInputOption` to `USER_ENTERED`. There're two options: - `RAW`: The values the user has entered will not be parsed and will be stored as-is. - `USER_ENTERED`: The values will be parsed as if the user typed them into the UI. Numbers will stay as numbers, but **strings may be converted to numbers, dates, etc**. If you're using <https://github.com/burnash/gspread>, change the `value_input_option`. - <https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption> - <https://github.com/burnash/gspread/issues/524> <file_sep>/_posts/2010-04-13-difference-between-constant-and-variable-in-php.markdown --- layout: post title: "PHP 里常量和变量的区别" --- 1. 常量前面没有美元符号($); 2. 常量只能用 define() 函数定义,而不能通过赋值语句; 3. 常量可以不用理会变量范围的规则而在任何地方定义和访问; 4. 常量一旦定义就不能被重新定义或者取消定义; 5. 常量的值只能是标量。 <file_sep>/_posts/2009-11-17-batch-creat-tree-folder.markdown --- layout: post title: "批处理新建树结构文件夹" --- 工作需要,每次纳品时候都要把项目源码,配置文件等等放在一个文件夹下各个指定的不同目录里然后打包,比如项目文件夹是 PM ,配置文件里放在 PM 下 INI 文件夹,源码放在 SRC 目录下。每次都要手动新建一堆文件夹,烦人,就用批处理随便搞了一下。(原本想用 Python 的,不过感觉太高射炮打蚊子了) ``` @echo off :main echo Input the Folder Name. set /p name= if exist %name% ( echo Had the same Folder. goto main) else ( md %name% cd %name% md SRC INI xxx) ``` 很简单,很偷懒。 <file_sep>/_posts/2013-03-31-jawbone-up-2-review.markdown --- layout: post title: "Jawbone UP 2 Review" date: 2013-03-31 16:40 --- 1 月 31 日开始用已经有两个月,简单记一个评测。 优点: 1. 心理暗示作用。为了完成每天的步行目标,真的很愿意去走,比如地铁换乘更乐于走楼梯而不是电梯,以满足自己报表上 100% 完成度的虚荣心。 1. 腕带式设计确实很方便携带。除了洗澡,现在几乎是 24 小时不离身,不存在忘带的情况,完全忽视了它的存在。 1. 智能闹钟很强大。在指定时间前 30 分钟内从轻度睡眠状态中把人叫醒,起床完全不痛苦,自然醒一般。 1. 睡眠质量记录功能。何时上床何时入睡何时醒来,充分了解自己的睡眠。 1. 可以互加好友然后激励自己锻炼,不过目前好友间的互动功能还很弱。 1. 待机时间可达 7 天以上,极少中断工作。 缺点: 1. 手动切换睡眠模式太不方便,很容易忘记,这个月就有三次忘了切换睡眠然后整个睡眠为 0。如果能根据平均上床时间提醒或自动切换睡眠模式可能会更好。 1. 手动同步不太方便,好几次都是打开 App 要查看记录才发现还没同步。 1. 模式切换的按钮容易坏掉,我这个现在按下的反馈力已经不如全新时干脆,耳机头保护帽容易丢。 1. 腕带设计会有误差,推荐非利手佩戴,减少记录误差。 总的来说对 Jawbone UP 2 很满意,使用简单,静默无干扰。可穿戴式设备绝对是下一个爆发点,期待 UP 下一代。 <file_sep>/_posts/2009-04-01-april-fools-day.markdown --- layout: post title: "April Fools Day" --- 愚人节,就不愚人了。 1. 上午双选会,愚人节的双选会,就让你这么无语。今天是广撒网,鸟枪法嘛,漯河的,合肥的三家,上海的,还有日本应研株式会社,不过目前来看枪法不怎么好。 2. 双选会上有洛轴的过来,LYC,可惜不要计算机的。 3. 下午形势与政策考试,世界上最无聊的考试,不说也罢。 4. 应研株式会社的宣讲会(那个据说是中国人的日本MM称之为说明会,囧),一个日本开发经理,日语乌拉乌拉一堆,然后翻译MM说明之,很是辛苦的宣讲会啊。 5. 宣讲会后笔试,走了。因为公司的情况对我来说很不现实。直接拉到日本,最少三年,自己生活上的问题先不说,家呢?这么大的人了,拖家带口的,不是“一人吃饱,全家不饿”的年代了,老喽。 6. 晚上同学聚餐,七分尽兴吧。总的来说,饭没吃饱,酒没喝好,刚找到感觉,没酒了。 7. 题外话,有些人的酒品真差,喝酒能看出来一个人,真的。 七月份毕业时候我能有好心情喝酒吗?也许把我放倒最好,谁过来把哥放倒? <file_sep>/_posts/2010-09-30-yeye-is-leaving.markdown --- layout: post title: "爷爷走了" --- 2010-09-29 13:17 爷爷走了 他最喜欢的大孙子没能见他最后一面 他也没能看一眼他的孙媳妇 遗憾,是这个世界上最让人无法释怀的 <file_sep>/_posts/2009-10-22-it-is-time-to-reduce-weight.markdown --- layout: post title: "该减肥了" --- 昨天在小区边上超市门口称了一下体重,吓煞我也:163 斤!毕业后身体发福非常明显,主要是自己做饭,敢放开肚子的吃;还有就是因为上班原因,晚上回去七拼八凑的做饭吃饭,一般都要折腾到七、八点,顶多玩到 11 点就必须得睡觉,吃得太饱又不怎么锻炼,不长肉才怪。 太胖了不好,看着不够帅气,还影响健康,丫头也不喜欢,嗯,得减肥了。订个计划: - 晚上少吃,一碗饭,多吃青菜少吃肉; - 延长晚饭到睡觉的时间,争取三个小时以上; - 锻炼! 争取今年年关回家时候保持在 150 斤上下,嗯。 <file_sep>/_posts/2008-11-09-weekend-11-09.markdown --- layout: post title: "Weekend-1109" --- 1. 刚洗澡回来。毕竟立冬了啊,冷的要死,多穿点衣服,不然感冒了就不值当了。 2. 这两天没有上自习,准备一下明天的考试。上午现代企业管理,下午管理信息系统,一个必修,一个专业选修,理论上明天两门考试一结束大学所有的课程都结束了。突然发现,挺不舍的。 3. 昨天早上睡了个懒觉,起来后发现居然有NBA,火箭打快船,看了后半段,火箭现在的磨合还是不行,咋就感觉不顺畅,就跟用笔记本玩游戏一样,一卡一卡的。不过也难怪,这才打了几场而已,12月份,赛季过半时候要是磨合的好的话,火箭今年说不定真的很有机会。 看到一篇好文《Google中国:最长的一年》: > 如果说长期而言,Google有何超越百度的机会,那就是对方的市盈率已经超过120倍,为维持股价,百度必须非常紧张地维持每季度盈利超越华尔街的预期。这种压力会让百度在某些决策上缺乏长线思考的勇气。类似的故事在美国已经发生过一次:在雅虎们早早上市,不得不与华尔街周旋时,Google一直在雷达之外改善产品及扩张市场,直到其收入规模大到可以不在意资本市场的意见,它才选择上市。 <file_sep>/_posts/2015-10-31-monthly-review-1510.markdown --- layout: post title: Monthly Review 2015-10 date: 2015-10-31 22:22:57 +0800 --- 1. 新项目主要做管理后台的前端开发,发现我还挺喜欢写前端的。 2. Web vs Native,由于微信网页应用的助力,web 已然赢了,作为代价,要接受 H5 这个叫法。 3. 工作内容转变,除了开发,运营、管理都开始接手,加油。 4. 把老张从杭州拉到北京,一起做事。 5. 十一回家又醉酒一次。<file_sep>/_posts/2008-06-06-mysql5-to-mysql4.markdown --- layout: post title: "Mysql 5.0降级导入Mysql 4.0" --- 直接导入数据库时出现错误:`#1064 - You have an error in your SQL syntax.` 语法错误,那就是说数据库文件没有错误,但sql语法上有问题,可惜sql学的不怎么样,看了半天也没有看出来哪里出错了,Google告诉我好像是Mysql版本兼容问题。赶紧看了一下空间的Mysql版本,盘今的是5.0几的,盘古提供的临时合租服务器的Mysql是4.0.27的,嗯,应该就是这个原因了,想办法解决之。 在本地的xampp环境mysql版本是5.0.51,phpmyadmin新建一个数据库,然后将备份的数据库文件导入成功,然后再导出:选中要导出的数据库,在"Options”组合框的"SQL compatibility mode"选中"MYSQL40",在"Structure"组合框中选中"Add IF NOT EXISTS","Add AUTO_INCREMENT value","Enclose table and field names with backquotes",在下面的"Export type"中选择"REPLACE",选中"Save as file","zipped"和"gzipped"压缩看数据库大小选择,然后"Go"把生成的SQL文件保存到磁盘,导出结束。 导入到空间数据库中,这一步很简单了,一步成功:Import has been successfully finished. <file_sep>/_posts/2010-01-13-hello-world.markdown --- layout: post title: "Hello World" --- Hello world from @fannheyward, powered by @projectpicky and GAE. <file_sep>/_posts/2012-03-08-key-value-coding-and-key-value-observing-notes.markdown --- layout: post title: "Key Value Coding and Key Value Observing Notes" date: 2012-03-08 09:43 --- KVO(Key Value Obersving) 的基础是 KVC(Key Value Coding),现在我对 KVC 的理解还非常粗浅,对 KVO 只是使用阶段,下面这些是我的一些笔记,可能会有一些误差,后续有更多理解后会持续更新。 ### KVC KVC 的全称是 `NSKeyValueCoding`,文档: > The NSKeyValueCoding informal protocol defines a mechanism by which you can access the properties of an object indirectly by name (or key), rather than directly through invocation of an accessor method or as instance variables. KVC 是一种通过 name 或 key 间接访问对象属性(property)的机制。用 `setValue:forKey:` 设置 key 所指定属性的值,`valueForKey:` 对应来取值。 Code: ```objc @interface Person : NSObject @property (nonatomic, retain) NSString *name; @property (nonatomic) int age; @end @implementation Person @synthesize name; @synthesize age; @end int main(int argc, char *argv[]) { @autoreleasepool { Person *person = [[Person alloc] init]; person.name = @"fannheyward"; // equal to //[person setName:@"fannheyward"]; // equal to //[person setValue:@"fannheyward" forKey:@"name"]; person.age = 24; // equal to //[person setAge:24]; // equal to //[person setValue:[NSNumber numberWithInt:24] forKey:@"age"]; NSLog(@"name:%@, age:%d", person.name, person.age); NSLog(@"name:%@, age:%d", [person valueForKey:@"name"], [[person valueForKey:@"age"] intValue]); [person release]; } } ``` ### KVO KVO 的全称是 `NSKeyValueObserving`,文档: > The NSKeyValueObserving (KVO) informal protocol defines a mechanism that allows objects to be notified of changes to the specified properties of other objects. 简单的说 KVO 提供了一个观察者机制,当被观察的对象属性变化时自动通知相应的观察者对象。KVO 就是通过 KVC 的 `setValue:forKey` 和 `valueForKey:` 来监察属性变化。KVO 的使用分为三个步骤,注册观察者,实现变化回调方法,取消观察者。 注册观察者: ```objc - (void)addObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context ``` 其中 `keyPath` 就是要观察的属性值,`options` 是属性变化的选择,`context` 可以用来传递额外的数据等。 实现变化回调方法: ```objc - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context ``` `keyPath` 注册里的相对应,用来区分不同的被观察属性,`change` 包含了变化前后的数据。 取消观察者: ```objc - (void)removeObserver:(NSObject *)anObserver forKeyPath:(NSString *)keyPath ``` 一般放在 `- (void)dealloc` 方法里面。 ### Demo Demo:一个列表 `listTableView`,数据存储在 `NSMutableArray *cellArray` 里面,`cellArray` 的数据发生变化时候刷新列表展示,比如滑动到 table 下部时自动后台 load 更多数据然后更新列表。 添加一个 `@property (nonatomic) NSInteger cellCount` 作为被观察者,为啥不直接用 `cellArray`作为被观察者?因为 NSArray 不能被注册为观察者,参考 `NSArray(NSKeyValueObserverRegistration)` in `NSKeyValueObserving.h`: > NSArrays are not observable, so these methods raise exceptions when invoked on NSArrays. Instead of observing an array, observe the ordered to-many relationship for which the array is the collection of related objects. ```objc - (void)viewDidLoad { [super viewDidLoad]; [self addObserver:self forKeyPath:@"cellCount" options:NSKeyValueObservingOptionNew context:nil]; } - (void)loadCellArrayInBackground { // ... self.cellCount = [cellArray count]; //change cellCount value. } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"cellCount"]) { // check change if nessary. [listTableView reloadData]; } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } - (void)dealloc { [self removeObserver:self forKeyPath:@"cellCount"]; [super dealloc]; } ``` 以上就是一个简单的 KVO 实现。 ---- PS. NSArray 也有方法注册观察者,`[[self mutableArrayValueForKey:@"cellArray"] addObject:@"test"];` 就可以被观察到 `cellArray` 变化。`mutableArrayValueForKey` 返回的不是 cellArray 本身而是一个 proxy,而 proxy 是支持 KVO 的。不过这种方法感觉有点浪费,没必要每添加、删除一个数据就刷新列表,尤其大部分时候我们都是批量更新数据源,用 cellCount 这种方式反而会更好一点。参考 [Key Value Observing NSArray and NSDictionary][1] --- PPS. 其实 KVO 的实现是比较笨重的,比如注册时候没有办法指定一个响应 selector,都需要在回调实现里面根据 `keyPath` 来区分不同的被观察者。[Key-Value Observing Done Right][2] 分析了 KVO 的一些缺点并给出了解决方案: [MAKVONotificationCenter][3],找个机会在项目中实际运用一下。 [1]:http://streetsaheadllc.com/article/key-value-observing-nsarray-and-nsdictionary [2]:http://www.mikeash.com/pyblog/key-value-observing-done-right.html [3]:https://github.com/mikeash/MAKVONotificationCenter <file_sep>/_posts/2015-05-28-avoid-rm.markdown --- layout: post title: 避免 rm 误操作 date: 2015-05-28 14:42:15 +0800 --- 规避 `rm -rf *` 操作: > 目录下新建 `-i` 文件, `touch -- -i` or `touch ./-i` 但是对于 `rm -rf ./*` 无效。 用 [safe-rm][1] 加持保护。 不要 `alias rm='rm -i'`,一旦习惯后在没有 alias 的机子上很容易误伤,可以新建别名,比如 `alias del='rm -i'`,然后习惯用 del 代替 rm. 最后,不要偷懒而滥用 **root**。 [1]:https://launchpad.net/safe-rm <file_sep>/_posts/2023-05-08-special-characters-in-bash.markdown --- layout: post title: Special Characters in Bash date: 2023-05-08 14:56:09 +0800 --- - `$0`: name of the script - `$1` to `$9`, arguments to the script. `$1` is the first argument and so on. - `$@`: all the arguments - `$#`: number of arguments - `$?`: return code of the previous command - `$$`: process identification number (PID) for the current script FYI: - <https://tldp.org/LDP/abs/html/special-chars.html> - <https://missing.csail.mit.edu/2020/shell-tools/><file_sep>/_posts/2014-12-15-fail.markdown --- layout: post title: "Fail" date: 2014-12-15 22:41:43 +0800 --- > 你有你自己的骄傲。 But > 有一种落差是,你配不上自己的野心,也辜负了所受的苦难。 <file_sep>/_posts/2009-06-21-happy-fathers-day.markdown --- layout: post title: "父亲节快乐" --- 印象中没怎么给爸写过什么文字,好像只有一篇,06 年爸生日时候写过几句话。今天是父亲节,祝爸节日快乐,身体健康。 ![](http://www.google.cn/logos/fathersday09.gif) <file_sep>/projects.md --- layout: page title: Projects permalink: /projects/ --- #### As member - [coc.nvim](https://github.com/neoclide/coc.nvim): intellisense engine for Vim/Neovim, full language server protocol support as VSCode ### As creator - [coc-marketplace](https://github.com/fannheyward/coc-marketplace): coc.nvim extensions marketplace - [coc-xml](https://github.com/fannheyward/coc-xml): XML support for Vim/Neovim with coc.nvim - [coc-pyright](https://github.com/fannheyward/coc-pyright): Pyright for Vim/Neovim with coc.nvim - [coc-rust-analyzer](https://github.com/fannheyward/coc-rust-analyzer): rust-analyzer for Vim/Neovim with coc.nvim - [coc-markdownlint](https://github.com/fannheyward/coc-markdownlint): markdownlint for Vim/Neovim with coc.nvim - [coc-clangd](https://github.com/clangd/coc-clangd): clangd extension for coc.nvim - [coc-julia](https://github.com/fannheyward/coc-julia): Julia extension for coc.nvim, with pre-compiled LanguageServer.jl support Checkout more on [GitHub](https://github.com/fannheyward). <file_sep>/_posts/2016-06-17-6-years-in-beijing.markdown --- layout: post title: 6 Years in Beijing date: 2016-06-17 16:51:04 +0800 --- Six years in Beijing. Six years at Appwill. 这半年不怎么写东西,技术上只是跟进,并没有太大产出,客户端甚至有不少新东西都看不懂了。团队上招聘面试,了解运营,学习管理,这些东西自己做的又不好,索性就什么也不写了。 下半年要多看看书,管理的,产品的,这几年太过于顺风顺水,现在这种创业环境下,不进则退。<file_sep>/_posts/2015-05-31-monthly-review-1505.markdown --- layout: post title: Monthly Review 2015-05 date: 2015-05-31 19:21:18 +0800 --- 1. 线上环境加上 InfluxDB 作为日志存储,可以实时查看缓存命中率,在线用户数,关键请求数量,但是还没想好日志数据的进一步挖掘,所以说技术没有转化成产品前,并没有什么卵用。 2. InfluxDB 还是有不少坑,0.9+ 在无限 RC 中,配套工具比如 Grafana 还不支持。0.8 疑似有内存泄漏,数据量稍大的查询很慢(百万级总量,10m 粒度)。还需要一些摸索,然后转化为产品指标。 3. 又一次写前端,完整项目,这次简化开发流程,放弃 Yeoman/Grunt/Bower 等工具,过于强大到很多功能都用不上,只用 npm 作为包管理和构建工具,`npm run` 完全可以满足需要。 4. 给六六做了图片 blog,按时间顺序贴照片,时间过的真快,马上就一岁了。 5. Google Photos 是个好产品,almost the best,存储了过去十年我几乎所有照片。 <file_sep>/_posts/2012-09-07-core-data-notes.markdown --- layout: post title: "Core Data Notes" date: 2012-09-07 18:38 --- 两篇很不错的 Core Data Tutorial, [Getting Started][1],[How to use NSFetchedResultsController][2]。 NSPersistentStoreCoordinator 是持久化存储, NSManagedObjectModel 指明存储数据结构和关系,NSManagedObjectContext 来读取、存储操作。 ``` objc - (NSManagedObjectContext *)managedObjectContext { if (_managedObjectContext != nil) { return _managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { _managedObjectContext = [[NSManagedObjectContext alloc] init]; [_managedObjectContext setPersistentStoreCoordinator:coordinator]; } return _managedObjectContext; } - (NSManagedObjectModel *)managedObjectModel { if (_managedObjectModel != nil) { return _managedObjectModel; } NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CDTest" withExtension:@"momd"]; _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return _managedObjectModel; } - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (_persistentStoreCoordinator != nil) { return _persistentStoreCoordinator; } NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CDTest.sqlite"]; NSError *error = nil; _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); } return _persistentStoreCoordinator; } ``` 新增数据: ```objc Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:_managedObjectContext]; person.name = @"fannheyward"; person.age = [NSNumber numberWithInt:25]; [_managedObjectContext save:NULL]; ``` 通过 NSFetchRequest 查找,配合 NSPredicate 对数据进行过滤判断: ```objc NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Person"]; request.predicate = [NSPredicate predicateWithFormat:@"age == %@", age];; NSArray *arr = [_managedObjectContext executeFetchRequest:request error:NULL]; for (NSManagedObject *obj in arr) { //... } ``` NSFetchedResultsController 和 UITableView 做了很好的整合,可以根据 tableView 位置进行动态查询取数据。比如一共 100 个 cell,传统方式需要一次性全部拿到 DataSource 数据到内存,数据量过大的话会占用不少内存;用 NSFetchedResultsController 可以设置一次取数据的大小,然后根据滑动位置动态读取数据。 ```objc - (NSFetchedResultsController *)fetchController { if (_fetchController != nil) { return _fetchController; } NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Place" inManagedObjectContext:_managedContext]; request.entity = entity; request.fetchBatchSize = 15; NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO]; request.sortDescriptors = [NSArray arrayWithObject:sort]; _fetchController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:_managedContext sectionNameKeyPath:nil cacheName:@"Place"]; _fetchController.delegate = self; NSError *error = nil; if (![_fetchController performFetch:&error]) { DLog(@"fetch error: %@", [error description]); abort(); } return _fetchController; } ``` 和 UITableView 的整合: ```objc - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { id <NSFetchedResultsSectionInfo> info = [[_fetchController sections] objectAtIndex:section]; return [info numberOfObjects]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //... Place *place = [_fetchController objectAtIndexPath:indexPath]; return cell; } ``` [1]:http://www.raywenderlich.com/934/core-data-on-ios-5-tutorial-getting-started [2]:http://www.raywenderlich.com/999/core-data-tutorial-how-to-use-nsfetchedresultscontroller <file_sep>/_posts/2009-01-24-notebook-touchpad-tips.markdown --- layout: post title: "笔记本触摸板小技巧" --- 这一段冷的要命,晚上就躺床上钻被窝上网,鼠标用着不大方便,触摸板就派上用场了。其实我的Fx配上了vimperator这个牛X级扩展,一般的上网操作都可以脱离鼠标的,但是像拖拽这种操作还是不大方便,刚开始就是食指按住触摸板的左键,中指滑动拖拽,感觉不是很方便,就Google了一些笔记本触摸板的使用技巧,摘录两个很方便的小技巧。 - 拖拽——指头快速两次点击,第二次点击时候来个小滑动即可完成拖拽动作,拖拽搜索,拖拽打开链接都可以。 - 快速移动鼠标——两个指头依次点击触摸板,第二次点击指向移动方向即可。 很简单但是很实用的技巧,不知道的时候不要以为不存在,尝试着Google一下,惊喜自己一把。 <file_sep>/_posts/2021-08-01-thoughts-on-coc.nvim.markdown --- layout: post title: Thoughts on coc.nvim date: 2021-08-01 18:54:23 +0800 --- > 虽然我是 [@neoclide](https://github.com/neoclide) 组织成员, 但以下内容并不是 @neoclide 官方言论,不代表 @neoclide 官方立场,只是我自己在开发使用 coc/extensions 过程中的一些理解和记录。时间节点是 2021-08。 ## coc.nvim 是什么? 有很多人在安利 [coc.nvim](https://github.com/neoclide/coc.nvim) 的时候会说: - coc 是一个自动补全插件,非常智能的补全提示 - coc 是一个 LSP client,支持很多语言 - coc 可以使用类似 VSCode 的插件 也会说: - coc 依赖 Node.js,太重了,npm 依赖是个无底洞,一个安装吃掉一堆硬盘 - coc 太大了,附带了很多其他插件的功能,不够 KISS,自成一派的插件体系分裂社区 以上都对,也都不全面。在我看了: > coc.nvim = node-based LSP client + handler + extensions host + auto completion engine + UI 这个顺序基本是从内到外来的: ### node-based LSP client [LSP](https://microsoft.github.io/language-server-protocol/) 是什么就不解释了,要注意的是 P 是 `protocol`,是协议,有时候会错误的说 “Python LSP 不工作”什么的,这是不准确的。 VSCode 提供了最为完整的 LSP 支持和迭代更新,并且会定期把 VSCode 里的实现更新到 [vscode-languageserver-node](https://github.com/microsoft/vscode-languageserver-node),包括 Node.js 实现的 server,client,JSON-RPC,protocol definition 等。coc 里的 `language-client` 是基于 `vscode-languageclient` 的~~完全~~移植,目前对应版本是 v7.0.0,完整度在 95%+,缺失的部分是 vim/nvim 端不需要的。因为有 `vscode-languageclient` 加持,可以说 coc 是 vim/nvim 上**几乎最为完整**的 LSP client 实现,可以实现和支持不同 LS 所支持的所有功能。 Note: 这里说的实现是指 API 层的交互,就是 LSP 定义某个功能协议,某个语言的 LS 也实现支持,client 可以完成和 LS 的通信交互,但对应的功能还需要界面交互层来提供给使用者。举例:在 VSCode 中右键重命名文件会把代码中所有 import 这个文件的代码改为新名字。具体的流程是重命名操作触发 `willRename` 事件,通过 LSP `workspace/willRenameFiles` 发送到 LS,LS 实现修改所有 import 并返回,client 接收采用。目前 coc 支持所有 `fileOperations` 请求,但功能上只有 `willRename` 的实现,缺少 `Create/Delete`,原因就是在界面交互上还没有特别好的支撑。 ### handler `src/handler|events|model|services` 等代码我都给归类到 handler,这才是 coc 最为技术含量的东西,@chemzqm 在 [neovim/node-client](https://github.com/neovim/node-client) 基础上实现了 Node.js RPC 对 vim/nvim API 的操作 [neoclide/neovim](https://github.com/neoclide/neovim),比如创建 buffer,设置 keymap,get/set lines,BufEnter/InsertLeave 等事件监听等等。 有了 handler,就可以把 LSP client 拿到的补全项,document, definitions, rename/formatting 结果进行显示、跳转等操作。更为重要的意义是,coc 把 handler 的功能通过接口暴露出来,这样我们就可以使用 Node.js 来写 vim/nvim 插件。一个不太恰当的例子:[denops.vim](https://github.com/vim-denops/denops.vim) 做的事情就是实现了这个 handler 做的一些事情,让我们可以用 Deno 写 vim/nvim 插件。 我把 `src/services` 也认为是 handler 层面的东西。services 一个重要的功能就是创建、启动、停止某个语言的 client。我们通过 `coc-settings.json - languageserver` 配置对 LS 的访问方式,coc 就可以创建、启动 client,对任何语言的 LS 进行访问和使用。 handler 另一个容易被忽略的功能是:统一了对 LS 的请求和结果返回。比如插件 A 想在 signcolumn 上显示当前位置的 codeAction 或 codeLens,A 可以自己向 LS 请求并展示。插件 B 想在 virtualText 显示,同样可以自己请求 LS,有了 handler 后 A&B 都向 coc 请求需要的信息即可。 ### extension host coc 实现了一整套插件机制,可以加载、执行用 JS 写的插件,可以从 npmjs.com 下载、更新插件。个人把 coc extensions 分成两类:LSP 相关和无关的。 LSP 相关的。虽然 services 已经可以创建、请求 LS,但是有些 LS 会有一些特殊的配置需求,或者有 LSP 不支持的扩展功能,或者某个 LS 返回的结果想进行劫持改写,我们就可以通过 coc extensions 来完成。`coc-rust-analyzer` 实现了很多扩展功能 [LSP Extensions](https://github.com/fannheyward/coc-rust-analyzer/issues/256), `coc-pyright` 可以自动检测 venv 环境,找到当前项目使用的 Python 劫持设置传给 Pyright 使用,不需要先 activated。 这类 extension 有些不是必须的,你完全可以通过 `coc-settings.json` 配置使用 rust-analyzer,只不过不能使用某些锦上添花的扩展功能罢了。但是有些是必须要用,并且是其他 LSP client 无法完美实现和支持的,比如 `coc-tsserver`,TypeScript LS 目前是不符合 LSP 标准的请求、响应,必须要中间层再次解析包装,`theia-ide/typescript-language-server` 可以用但性能功能都不如 `vscode-typescript-language-features` 和 `coc-tsserver`, 类似的还有 [yaegassy/coc-volar](https://github.com/yaegassy/coc-volar). LSP 无关的,就是用 JS 完成某个功能,然后通过 handler 提供的 API 对 vim/nvim 进行操作。举例几个我觉得好用的这类扩展: - `coc-git` 我主要使用 coc-git 做 git 信息显示,比如修改状态,blame/commit 等,git 操作更多会在终端 - `coc-explorer` 类 IDE 文件管理方式的文件浏览器,支持文件操作和 diagnostic 状态显示等 - `coc-ecdict` 使用 ECDICT 做中-英翻译,结果通过 `doHover` 展示 - `coc-yank` 跨 vim/nvim 实例的 yank 记录保存,并放到补全项使用 - `coc-nextword` 通过 NLP n-gram 算法做英文输入的智能提示 coc 本身是个插件,又提供了 extension 功能,相当于是插件的插件,这也是很多人觉得 coc 自成一派插件分裂社区,造轮子,像 coc-lists/coc-pairs/coc-snippets 都有对应的第三方插件。我的理解: 1. 有的是因为第三方插件无法达到 coc 的性能和定制化需要。比如 lists 显示,最早时候 coc 是使用 `coc-denite` 把 commands/diagnostics 等交给 `denite.nvim` 展示。但因为 denite 本身是个 Python Remote Plugin,这样绕一圈性能比较差,加上依赖于第三方插件不好做功能扩展,所以有了 `src/list` 内置列表展示。`coc-lists` 只不过是添加了 files/tags 这些列表内容源。我个人在使用上会 `coc-lists + vim-clap + nvim-bqf` 混用:definitions/references 这些用 bqf,fuzzy files 用 clap,extensions 内置源用 lists。 2. 有的是因为第三方插件有功能不支持,比如 snippets,很多 snippets 插件早期是不支持 LSP snippets 格式的,同时 snippets 和补全会有冲突,所以有了 coc-snippets,可以完全由 coc 控制。 3. 有的纯粹是想用 Node.js 写 vim/nvim 插件罢了,比如我写过一个 `coc-ci`,使用 [segmentit](https://www.npmjs.com/package/segmentit) 做中文分词,之后添加 w/b 绑定实现中文分词跳转。(不过这个插件有很长时间没有更新了,因为我发现这是个伪需求,我自己使用率不高导致没啥维护意愿) 4. 这些被抱怨造轮子的插件基本上都是 LSP 无关类型的,随着这些第三方插件的更新和支持,是否需要完全是个人喜好。 我的个人偏好:不太喜欢 Python-based 插件。最早用 vim 的时候要自己编译 `+python | +python3` 支持,后来 nvim 出现让我切换的第一原因就是 remote plugin,只需要 pip neovim/pynvim 即可。但是需要安装到系统 Python 环境:使用系统自带 Python 需要 sudo pip,使用 brew 安装的 Python 在更新后因为路径变化炸过几次,当然也可以创建一个独立的 venv 指定给 nvim 使用,但是这些不好的历史让我最近几年很少使用 Python-based 插件,像 LeaderF 就很好很强大,尝试过几次都没坚持下来。 ### auto completion engine 这是 coc 最直观的功能,coc 会异步向所有源发起请求,补全响应速度上取决于最慢的数据源,也有过滤、优先级排序、preselect 等设置来优化补全。我自己会设置 `suggest.defaultSortMethod = none`,使用 LS 和 source 自己的排序,用下来发现这个更为合理一些。 异步请求补全来源是现在所有补全插件都会做的事情,使用下来还是会发现不同插件的补全响应速度有差异,什么原因呢?(后面有我个人的理解对比 ### UI 或许应该叫 UI/UX 层,就是显示信息并且进行交互操作,这个是非常个人主观和 workflow 差异。比如有很多人在 issue/gitter 问能不能把 references/definitions 放到 floating 窗口显示,目前 lists 是不支持 floating 的,使用体验感觉就没那么“炫”,尤其是和现在很多 lua 插件对比。 把时间往回拨,在 18/19年 coc 提供这些的时候,floating API 都还不完善,coc 需要自己对显示效果进行完善,最开始只用 floating 做补全项和文档显示,当时这个效果惊艳无比,后来添加了高亮,可以 floating input,有了 dialog 窗口,有了 menu 选择,可以 floating scroll。后来随着 API 的完善,尤其是 nvim built-in LSP 后针对 floating 做了一系列的增强,有了 `open_floating_preview` 统一接口,可以直接设置 fancy_markdown 高亮,可以设置 border,对比 coc 自己实现的 border 原生的看起来好看很多。这些新增的功能让 coc 的界面看起来有点 *outdated*,同时 coc 兼容支持 vim 会有一些取舍限制,UI 层的效果就没那么炫酷了,UI 层的封装就意味着自定义定制的不够灵活,加上个人主观和 workflow 差异,众口难调。好在 coc 可以通过 API 把一些内容输出,比如 coc diagnostics 输出给 quickfix,nvim-bqf 读取显示,也可以用 telescope-coc.nvim 把内容在 telescope.nvim 使用。 还有几个模块没提到,比如 coc 内置的 Task 功能可以进行[自动构建任务](https://www.v2ex.com/t/577212), `coc-cursors-operator` 可以进行多光标操作,`coc-refactor` 和 CocSearch 进行[代码重构](https://zhuanlan.zhihu.com/p/272119909). ## 对比 Thoughts on LSP client for nvim by @justinmk [via](https://gitter.im/neovim/neovim?at=5dd24cf8e75b2d5a19f2aa67): > there's only really 2 choices: coc or Nvim builtin stuff > I wouldn't bother with the others 知乎上有个问题 [能否详细比较一下 nvim-lsp 和 coc.nvim?](https://www.zhihu.com/question/466286911), @chemzqm 的回答在性能上提了一句,其他人的回答更偏重使用体验。我试着从 LSP 补全来做个对比。LSP 在进行输入补全的时候依次是: > input trigger -> client request `textDocument/completion` -> server response -> client handle -> suggestions popup - coc:nvim RPC 到 Node.js,coc client 请求 LS,LS 返回结果,coc 处理后显示 - nvim built-in: nvim client and请求 LS,LS 返回结果,nvim 处理后显示 不同语言 LS 的响应时间有很大差异,假定同一个 LS 对不同 client 的补全响应完全一致,因为 nvim 少了一次远程通信,所以理论上性能是好于 coc。这也是很多人(包括我)最直观的认识,毕竟少了一道请求肯定快,这是正确的。 **但是**,这个请求-返回只是整个流程的一环,其他环节带来的差异往往非常大: 1. input trigger,coc 在是否触发请求有个 `suggest.triggerCompletionWait` delay, 避免打字速度带来的影响 2. client handle,或者叫 parser,LSP 是 JSON-RPC 通信协议,假如 LS 返回了 1000 个补全项,那就是类似 `[{}, {},...]` 结构的 JSON string,client 要做非常耗时的序列化和反序列化,这个耗时甚至比 client RPC server 都要大。 作为使用者并不会发现关注这个 JSON 耗时,但是补全插件的作者都知道这个的影响,比如 [nvim-cmp](https://github.com/hrsh7th/nvim-cmp/blob/main/README.md#nvim-cmp-is-slow): > For example, typescript-language-server will returns 15k items to the client. In such case, the time near the 100ms will be consumed just to parse payloads as JSON. (题外话 [@hrsh7th](https://twitter.com/hrsh7th) 对 coc 的评价是很高的,同为开发者有过深入实践后感知和对比会更明显,`調べれば調べるほど coc どうなってんだという感想` [via](https://twitter.com/hrsh7th/status/1412822519959093249). 目前 nvim Lua 对 JSON 的处理还不够好,也许后续内置 `c_json` 会有改善。那为什么 nvim built-in 感官上会比 coc 要快?也许是因为 trigger delay,也许是因为 LS 返回的结果比较小。再比如 *Fast as FUCK* 的 `coq_nvim` 一直强调的 1000+ items 补全飞快,就是因为不需要 Lua JSON 处理,加上 in-memory SQLite ~~作弊~~外挂,不快都难。 补全速度只是非常小的一方面,最大的差异就是 embed LuaJIT vs Node.js,毕竟内置还是自己安装,方便程度显而易见。关于这个我的理解:在不方便的环境需要用 LSP 的时候直接 built-in client,但是作为开发者,你吐槽 JS ugly,或者 `node_modules black hole` 我觉得都对都赞成,但以此来 diss Node.js 是一个不好的技术栈,那需要反思一下自己作为开发者的技术素养了。 在使用层面的对比,built-in client 有着更为灵活自由的定制化,尤其是 UI 上,现在有非常多非常炫酷的 Lua 插件出现,coc 有限的配置项很难做到。 未来会怎么样?coc 在 LSP client 有先发优势,extensions 上方便复用 VSCode 资源,兼容 vim/nvim,这些都是优点,nvim built-in client 也在快速迭代改进,我们大家都有光明的前途 :D > Added in 2021-10 其实是两种软件模型的差异,假设有两个程序 A & B,它们都是单线程,都需要频繁的与第三方程序/服务进行通信,它们都采用 [libuv](https://github.com/libuv/libuv) 的 event-loop 机制进行任务调度。现在有了新需求:两者都需要响应用户操作,都需要根据任务返回的结果进行 UI 更新。A 的方案是在程序内添加 UI 层,内部 function 直接互相调用;B 的方案是新开程序 C,C 只负责 UI 层,通过管道/RPC和 B 通信。 A - nvim, B - Node.js, C - nvim. 类似的软件模型:**nvim + telescope.nvim** vs **nvim + Leaderf**. <file_sep>/_posts/2009-09-24-byteofpython-clips002.markdown --- layout: post title: "Clips002" --- via [A Byte of Python](http://www.swaroopch.com/notes/python/). Do the analysis and design. Start implementing with a simple version. Test and debug it. Use it to ensure that it works as expected. Now, add any features that you want and continue to repeat the Do-Start-Test-Use cycle as many times as required. Remember, **Software is grown, not built**. <file_sep>/_posts/2009-06-09-sold.markdown --- layout: post title: "SOLD" --- 好久没写东西了。忙。忙毕业设计论文,忙答辩准备,忙喝酒,忙游戏,大学最后一段“糜烂”的生活,真的挺忙的。 刚拿到就业协议回函,SOLD!SOLD!SOLD! 其实是六月一日那天就签了就业协议的,由于人事档案上的一些流程,今天才拿到回函。 没有老早时候想象着自己卖了之后的兴奋,没有满世界的跟兄弟们说,只是看了一眼,扔进抽屉。可能是我老了,没有那份锐气了,可能是我累了,折腾不动了吧。 没工作的时候迷茫,有了工作同样迷茫,不知道自己以后的路会怎样。不管怎样,我还会坚定的往前走,一步一步的,哪怕步子再小,我都不会停,向着我一直以来的目标,走下去。 只为人生的记号,今天,2009年6月9日,我卖了,人生第一份工作。 <file_sep>/_posts/2010-11-09-compile-vim-73-on-mac-for-python.markdown --- layout: post title: "Compile vim 7.3 on Mac for Python" --- 之所以想编译安装 vim 是因为一个 python vim script 需要 +python 支持,而 Mac 下默认的 vim 7.2 并没有 +python,所以每次 vim xx.py 的时候都会有一个警告;另一个原因就是 vim 7.3 is released,版本控。 Get the source first: > `hg clone https://vim.googlecode.com/hg/ vim` cd to the vim source directory and: ``` ./configure --with-features=huge --enable-cscope --enable-pythoninterp --enable-rubyinterp --enable-perlinterp  --enable-tclinterp   --enable-multibyte --enable-cscope --disable-gui make && make install ``` Done. <file_sep>/_posts/2022-09-29-10th.markdown --- layout: post title: 10th date: 2022-09-29 09:41:45 +0800 --- 2012.09.29 -> 2022.09.29, I LOVE Linn <file_sep>/_posts/2023-03-20-app-broken-on-silicon-macos.markdown --- layout: post title: App broken on Silicon macOS date: 2023-03-20 14:19:59 +0800 --- > "App" can’t be opened. You should move it to the Trash or > "App" 已损坏,无法打开。你应该将它移到废纸篓。 Solution: `sudo xattr -rd com.apple.quarantine /Applications/App.app` <file_sep>/_posts/2012-09-09-heybot-my-gtalk-hubot.markdown --- layout: post title: "Heybot - My Gtalk Hubot" date: 2012-09-09 21:31 --- Github 是非常好的学习地方,Github Inc 这家公司也很有意思,一帮 Geek 程序员做了很多很好玩的东西,比如 [Hubot][1], [Play][2]。Hubot 是一个机器人,可以音乐、搜索、搞怪逗乐等,在 Github 内部他们还用 Hubot 部署代码。开源版本的 Hubot 目前不支持代码部署等高级命令,不过可以自己写脚本(CoffeeScript)进行扩展。 Hubot 原生支持 Campfire、Shell 作接口,通过 npm 扩展可以用 Gtalk、IRC 等等。在 Heroku 上部署了一个用 Gtalk 作接口的 Heybot(Heyward's Hubot),简单纪录一下。 ``` wget https://github.com/downloads/github/hubot/hubot-2.3.2.tar.gz tar xzvf hubot-2.3.2.tar.gz cd hubot vim Procfile 修改 adapter: app: bin/hubot -a gtalk -n Hubot vim package.json 添加 hubot-gtalk 到 dependencies: "hubot-gtalk": ">= 0.0.1", git init git add * git commit -m "init" heroku apps:create git push heroku master heroku ps:scale app=1 heroku addons:add redistogo:nano heroku config:add HUBOT_GTALK_USERNAME="xxx" HUBOT_GTALK_PASSWORD="xxx" heroku ps:restart ``` 添加 Gtalk 好友,`hubot help` 可以查看目前支持的命令。 [1]:https://github.com/github/hubot [2]:https://github.com/play/play <file_sep>/_posts/2014-07-23-vim-golang-environment.markdown --- layout: post title: "Vim Golang 开发环境: vim-go" date: 2014-07-23 22:04:25 +0800 --- 安装 Golang 并设置 `$GOPATH`: ``` export GOPATH="$HOME" export PATH="$PATH:$GOPATH/bin" ``` Golang 官方提供了 Vim 开发工具 `$GOROOT/misc/vim`,但功能很弱,所以有很多第三方的辅助开发应用: 1. [gocode][1] 自动代码补全 1. [godef][2] 函数定义跳转,快捷键 `gd` 1. [goimports][3] 自动 import 包管理 2. [gotags][4] 展示当前代码里函数列表,配合 tagbar 使用 这几个是独立的应用,配套相应的 Vim 插件,单独安装很是繁琐。而 [vim-go][5] 是一整套的 Golang Vim 开发配置,安装插件后通过 `GoInstallBinaries` 安装 `gocode`, `godef`, `goimports`, `gotags`, `golint`, `oracle`, `errcheck` 以及相应的 Vim 插件、配色、代码块,非常方便。 `Plugin 'fatih/vim-go'` 安装,默认代码补全引擎是 Ultisnips,修改为 neosnippet `let g:go_snippet_engine = "neosnippet"`。 我的 [vimrc][6]. [1]:https://github.com/nsf/gocode [2]:http://godoc.org/code.google.com/p/rog-go/exp/cmd/godef [3]:https://github.com/bradfitz/goimports [4]:https://github.com/jstemmer/gotags [5]:https://github.com/fatih/vim-go/ [6]:https://github.com/fannheyward/vimrc <file_sep>/_posts/2010-04-15-missing.markdown --- layout: post title: "Missing" --- 刚送老婆上车,心里就空落落的。顺着那条破路往家走。 到楼下,不想上去,一个人呆在屋里不好玩,就去老梁那边串门,扯淡到九点,还是得回去。 肯定睡不着,所以就看无聊的肥皂剧。一集、两集,其实我是在等老婆上火车,顺便等我生物钟赶紧到,这样就可以倒头就睡着。 半夜醒来无数次,一个人的被窝太冷。 早上六点半闹钟,我还是习惯性的关掉,然后再眯一会。 可惜眯一会就没人再叫我了,所以我七点二十惊醒,然后飞奔到公司。 老婆赶紧回来。 <file_sep>/_posts/2014-10-30-monthly-review-1410.markdown --- layout: post title: "Monthly Review 2014-10" date: 2014-10-30 19:56:37 +0800 --- 工作: 1. 本月的 git commits 还不足上个月的一半。 2. Redmine 上关掉 42 issues,当然有部分是无法复现或拒绝需求。 3. 完成拖延一年的运营管理界面,这部分一周可能都用不了一次,一直没动力去做。 4. 捡起 Docker 想做一下 CI,发现最大的问题不是环境,而是没有写测试用例的习惯。 5. 除了没有测试,大部分项目都没有文档,或者更新不及时,接下来一个月先把自己手上的项目文档补全。 6. 暴漏出来的问题就是自己的开发模式还处于比较原始的小作坊形式。VCS+Code Review 全靠自觉+代码强迫症,测试和部署上线全手工操作,没有流程,而这却是最重要的。 生活: 1. 想六六。 2. 考虑把娃带北京自己带,然后就没有然后了,哎。 3. 如果独生子女有什么好处的话,孩子在需要帮忙的时候父母没有太多其他牵挂算一个。 4. 晚上买菜做饭,对自己的厨艺还算满意,就是刀工太差。 <file_sep>/_posts/2017-03-19-role-of-technology.markdown --- layout: post title: The Role of Technology date: 2017-03-19 22:02:15 +0800 --- @[Fenng](http://weibo.com/1577826897/yxh129UBb): > 技术的作用从短期来看往往被高估,但是从长期来看又往往容易被低估。 <file_sep>/_posts/2012-03-12-git-flow-notes.markdown --- layout: post title: "Git-flow 使用笔记" date: 2012-03-12 16:09 --- [git-flow][1] 原理:[A successful Git branching model][2],两篇不错的中文翻译: [Git开发管理之道][3],[一个成功的Git分支模型][4]。 简单来说,git-flow 就是在 `git branch` `git tag`基础上封装出来的代码分支管理模型,把实际开发模拟成 `master` `develop` `feature` `release` `hotfix` `support` 几种场景,其中 `master` 对应发布上线,`develop` 对应开发,其他几个在不同的情况下出现。通过封装,git-flow 屏蔽了 `git branch` 等相对来说比较复杂生硬的命令(`git branch` 还是比较复杂的,尤其是在多分支情况下),简单而且规范的解决了代码分支管理问题。 安装 git-flow: ``` brew install git-flow ``` 在一个全新目录下构建 git-flow 模型: ``` ➜ git flow init Initialized empty Git repository in /Users/fannheyward/flowTest/.git/ No branches exist yet. Base branches must be created now. Branch name for production releases: [master] Branch name for "next release" development: [develop] How to name your supporting branch prefixes? Feature branches? [feature/] Release branches? [release/] Hotfix branches? [hotfix/] Support branches? [support/] Version tag prefix? [] ``` 或者在现有的版本库构建: ``` ➜ git flow init Which branch should be used for bringing forth production releases? - master Branch name for production releases: [master] Branch name for "next release" development: [develop] How to name your supporting branch prefixes? Feature branches? [feature/] Release branches? [release/] Hotfix branches? [hotfix/] Support branches? [support/] Version tag prefix? [] ``` 中间会询问生成的分支名,直接回车默认。这样一个 git-flow 分支模型就初始化完成。 使用场景一:新功能开发,代号 f1 ``` ➜ git flow feature start f1 Switched to a new branch 'feature/f1' Summary of actions: - A new branch 'feature/f1' was created, based on 'develop' - You are now on branch 'feature/f1' Now, start committing on your feature. When done, use: git flow feature finish f1 ``` git-flow 从 `develop` 分支创建了一个新的分支 `feature/f1`,并自动切换到这个分支下面。然后就可以进行 f1 功能开发,中间可以多次的 `commit` 操作。当功能完成后: ``` ➜ git flow feature finish f1 Switched to branch 'develop' Already up-to-date. Deleted branch feature/f1 (was 7bb5749). Summary of actions: - The feature branch 'feature/f1' was merged into 'develop' - Feature branch 'feature/f1' has been removed - You are now on branch 'develop' ``` `feature/f1` 分支的代码会被合并到 `develop` 里面,然后删除该分支,切换回 `develop`. 到此,新功能开发这个场景完毕。在 f1 功能开发中,如果 f1 未完成,同时功能 f2 要开始进行,也是可以的。 ---- 使用场景二:发布上线,代号 0.1 ``` ➜ git flow release start 0.1 Switched to a new branch 'release/0.1' Summary of actions: - A new branch 'release/0.1' was created, based on 'develop' - You are now on branch 'release/0.1' Follow-up actions: - Bump the version number now! - Start committing last-minute fixes in preparing your release - When done, run: git flow release finish '0.1' ``` git-flow 从 `develop` 分支创建一个新的分支 `release/0.1`,并切换到该分支下,接下来要做的就是修改版本号等发布操作。完成后: ``` ➜ git flow release finish 0.1 Switched to branch 'master' Merge made by the 'recursive' strategy. f1 | 1 + version | 1 + 2 files changed, 2 insertions(+) create mode 100644 f1 create mode 100644 version Switched to branch 'develop' Merge made by the 'recursive' strategy. version | 1 + 1 file changed, 1 insertion(+) create mode 100644 version Deleted branch release/0.1 (was d77df80). Summary of actions: - Latest objects have been fetched from 'origin' - Release branch has been merged into 'master' - The release was tagged '0.1' - Release branch has been back-merged into 'develop' - Release branch 'release/0.1' has been deleted ``` git-flow 会依次切换到 `master` `develop` 下合并 `release/0.1` 里的修改,然后用 `git tag` 的给当次发布打上 tag 0.1,可以通过 `git tag` 查看所有 tag: ``` ➜ git:(master) git tag 0.1 0.2 ``` ---- 使用场景三:紧急 bug 修正,代号 bug1 ``` ➜ git flow hotfix start bug1 Switched to a new branch 'hotfix/bug1' Summary of actions: - A new branch 'hotfix/bug1' was created, based on 'master' - You are now on branch 'hotfix/bug1' Follow-up actions: - Bump the version number now! - Start committing your hot fixes - When done, run: git flow hotfix finish 'bug1' ``` git-flow 从 `master` 分支创建一个新的分支 `hotfix/bug1`,并切换到该分支下。接下来要做的就是修复 bug,完成后: ``` ➜ git flow hotfix finish bug1 Switched to branch 'master' Merge made by the 'recursive' strategy. f1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) Switched to branch 'develop' Merge made by the 'recursive' strategy. f1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) Deleted branch hotfix/bug1 (was aa3ca2e). Summary of actions: - Latest objects have been fetched from 'origin' - Hotfix branch has been merged into 'master' - The hotfix was tagged 'bug1' - Hotfix branch has been back-merged into 'develop' - Hotfix branch 'hotfix/bug1' has been deleted ``` git-flow 会依次切换到 `master` `develop` 分支下合并 `hotfix/bug1`,然后删掉 `hotfix/bug1`。到此,hotfix 完成。 git-flow 的 `feature` `release` 都是从 `develop` 分支创建,`hotfix` `support` 都是从 `master` 分支创建。 [1]:https://github.com/nvie/gitflow/ [2]:http://nvie.com/posts/a-successful-git-branching-model/ [3]:http://blog.leezhong.com/translate/2010/10/30/a-successful-git-branch.html [4]:http://www.juvenxu.com/2010/11/28/a-successful-git-branching-model/ <file_sep>/_posts/2017-05-26-ansible-notes.markdown --- layout: post title: Ansible notes date: 2017-05-26 16:11:09 +0800 --- Ansible 是基于 SSH 的自动化配置管理和部署工具,更多请参考[官方文档][1]。 ``` ansible -i hosts.ini all -m ping ansible-playbook -i hosts.ini playbook.yaml ``` 用 Ansible + Supervisor 部署/更新应用: ```yaml - hosts: server tasks: - name: check if exists stat: path=/path/to/app register: check_path - name: clone shell: git clone XXX && git checkout -b release when: check_path.stat.exists == false - name: pull shell: cd /path/to/app && git pull origin release when: check_path.stat.exists - name: is already running ? stat: path=/tmp/supervisord.pid register: supervisord_stat - name: restart command: supervisorctl -c supervisord.conf restart all args: chdir: /path/to/app when: supervisord_stat.stat.exists - name: start command: supervisord -c supervisord.conf args: chdir: /path/to/app when: supervisord_stat.stat.exists == false ``` * [Ansible Galaxy][5] * [An Ansible Tutorial][2] * [iOS Dev Playbook][3] * [Mac Development Ansible Playbook][4] [1]: http://docs.ansible.com/ansible/intro.html [2]: https://serversforhackers.com/an-ansible-tutorial [3]: https://github.com/lexrus/ios-dev-playbook [4]: https://github.com/geerlingguy/mac-dev-playbook [5]: https://galaxy.ansible.com/explore#/ <file_sep>/_posts/2019-07-23-git-special-ssh-key.markdown --- layout: post title: Using special SSH key for Git date: 2019-07-23 09:33:32 +0800 --- In `~/.ssh/config`: ``` host github.com HostName github.com IdentityFile ~/.ssh/id_rsa_github User git ``` don't forget `chmod 600 ~/.ssh/config` Or, use `GIT_SSH_COMMAND` environment variable: ``` export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_example -F /dev/null" ``` <file_sep>/_posts/2010-06-30-show-pil-image-object-in-browser.markdown --- layout: post title: "Show PIL image object in browser" --- 在浏览器显示 PIL 处理过的图片对象。 Using PIL module, you can resize or crop an image and return an image object. After that, I want to show the resized-image-object in browser. Here it is. ``` pic = thumbPicture() f = StringIO() pic.save(f,'JPEG') f.seek(0) shutil.copyfileobj(f,self.wfile) self.sendHeader(contenttype = 'image/jpeg',contentlength = f.tell()) f.close() ``` <file_sep>/_posts/2008-05-11-mothers-day.markdown --- layout: post title: "Happy Mother's Day" --- 嗯,今天母亲节,母亲的节日。 不怎么会说话了,妈,母亲节快乐,身体健健康康的! <file_sep>/_posts/2010-09-11-cocoachina-devcon-2.markdown --- layout: post title: "CocoaChina Devcon 2" --- 随手用手机记了几点: 1. 东西方游戏差别:东方玩家讲究剧情、操作、难度、画面,更享受游戏的过程和过关后那种爽快;西方游戏玩家比较喜欢休闲、娱乐、简单的游戏,不愿意去学习游戏操作甚至秘籍。 2. 90% 的 iOS 用户对游戏都是新手,所以不能照搬 PC、PSP、街机游戏机游戏那种设计。 3. 大部分 iOS 上的游戏玩家的 GQ 都很低,所以 Don't make me think. 4. 游戏时长最好 3~5 分钟,这个时长也是大家的碎片时间,休闲娱乐来一下~ 5. App 推广,俩字:曝光!充分利用一切途径加大程序的曝光度。 6. 上线之前的准备工作要充足细致,App ICON 设计,画面截图,文字描述要准备充分,这个是唯一的一次宣传机会。 最后一个演讲很有货,准备把 keynotes 抓下来自己好好回味一下,不仅仅是 App Store 的生存法则。 <file_sep>/_posts/2011-12-27-mfmailcomposeviewcontroller-cansendmail-issue.markdown --- layout: post title: "[MFMailComposeViewController canSendMail] issue" date: 2011-12-27 11:33 --- 发现 `MFMailComposeViewController` 一个挺奇怪的问题,代码一: ``` if ([MFMailComposeViewController canSendMail]) { MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init]; [mailComposer setSubject:@"Mail"]; //... [self presentModalViewController:mailComposer animated:YES]; [mailComposer release]; } ``` 如果设备没有设置 Mail,那么该操作不会有任何反应。不会有弹窗出现。 代码二: ``` MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init]; if (![MFMailComposeViewController canSendMail]) { return; } //... ``` 代码二这种情况下如果没有设置 Mail,会有系统弹窗提示 “无邮件账户”。 <file_sep>/_posts/2010-07-15-one-month-in-beijing.markdown --- layout: post title: "One month in Beijing" --- 真快,一个月一闪而过。 很宽松的工作环境,没有打卡没有限时,敏捷快速的开发模式,要的就是个效率。 团队人很好,很照顾我这个年龄最小工作经验最少的。每天下午的水果时间,每周三的北语羽毛球,玩的很 high. 用自己喜欢的东西做一些有意思的东西,把兴趣和工作结合起来无疑是一种幸福。 自己技术上还很弱,整体结构设计把握不住,细节实现考虑不足,还有很多要学。 Keep moving. <file_sep>/_posts/2008-09-13-curse-design-web-program.markdown --- layout: post title: "课程设计" --- RT,开学前三周的重头戏,所以这一段写日志就比较少。 先是网络课程设计实践,昨天下午一直拖到6点半总算是验收完了,从两点等到六点半,差点饿死我。那人的效率真够可以的,就这还有十几个还没有验收,回来后每一个人都在骂那撮人,啥都不懂,还问的巨多,一个人耗半个小时,谁受得了。话说我验收还是最后一个,本来他还不想给我验收,说没时间了,下次吧。下次?我可不想再来耗半天时间。就说:老师,我那个要配置服务器,下次的话还得重新配,挺麻烦的,老师就帮忙看一下吧。忽悠他了,配置我需要的环境2分钟足矣。验收还是挺顺利的,因为他对我用xampp挺感兴趣,问我一堆关于这个的东西,-_-|||。 两个课程设计,一个网络,一个数据库,网络是指定的题目,数据库随意,自拟,就想着偷懒一下,两个合成一个做。整好,网络里面也有要数据库的几道题,不过都是网络编程方面的,都没有学过,所以没几个人选,就想尝试一下,选了一个简单的,网络留言本,想用php+mysql试着写一下。添加留言,回复,留言显示,删除,算算其实留言本的话真没有几个功能,不过看起来简单,做起来真的挺难的,弄得我相当烦躁,一度想放弃,还好,有丫头的鼓励,帮我,慢慢的,一个一个的做,嗯,当看到自己做的东西可以浏览器打开运行,然后写上第一句话的时候,真的挺兴奋的,虽然是一个很简单的留言板而已,不过对我来说已经很大的进步了。毕竟 Web 编程对自己来说是一个完全陌生的东西,虽然折腾wp也有一段时间,但是大部分都是按照别人的教程改改代码,换个主题,加个插件,这种几乎不需要网络编程技术的操作,只要混两年网络,基本上都能上手。继续说课程设计。php的东西说实话入门挺简单的,碰见不知道的函数功能,Google一下一般都可以解决,可是想深入一下就比较难了,类,库,框架,这些个都不是一下子就能掌握的,要经过项目开发实践才能出来的能力,不过感觉php真的挺简洁高效的,有兴趣学习一下,哈。 嗯,课程设计结束了,该好好的收心投入备研阶段了,好好的自习复习去,为了自己的承诺吧,加油,Go,Heyward! <file_sep>/_posts/2008-05-09-stylish-xiaonei-page.markdown --- layout: post title: "使用Stylish自定义校内个人页面" --- 今天天气不好,阴沉沉的,心情也不是很好,莫名其妙的烦。周末就要考试了,没有一点看书的心情,静不下心。丫头说找点自己能做下去的事让自己的心静静,嗯,好。 -------------------分割----------------- [Stylish](https://addons.mozilla.org/en-US/firefox/addon/2108),一个非常有名的火狐插件,可以自定义网页css样式,改变网页样式,当然,是在本地修改,自己看着舒服。就拿它来改一下校内的个人页面。一般上校内就直接奔向个人页面的留言板,看有谁过来唧唧歪歪没有,不过留言板设置在下面,要拖半天的页面才行,为啥不把其他不必要的东西给“枪毙”了呢? 个人头像?杀掉,我自己看自己干嘛,个人信息?我自己还不知道自己啊,很少在校内上写blog,也没有相册,别人送的礼物这些乱七八糟的板块都给枪毙了,顺带把那些广告、链接、banner都给杀了。嗯,现在干净了,就剩一个留言板,Stylish代码: ``` @namespace url(http://www.w3.org/1999/xhtml); @-moz-document url("http://xiaonei.com/getuser.do?id=********") { #header,#sidebar,#dashNoticeyellow.atindex,#userFeed.box,#userBlog.box,#userStatus.box,#giftBox.box,#userAccount.box,#userProfile.box,#userRelations,#welcome,#permalink,#footer{ display: none !important; } } ``` ******是我的编号,这个本来就是只对自己的页面弄的,就不全局了。 --------------------还是分割线----------------------- 世界干净了,哈哈,心情也好了不少,嗯,晚上看书去,加油! <file_sep>/_posts/2012-09-10-use-copy-property-for-nsstring.markdown --- layout: post title: "Use copy property for NSString" date: 2012-09-10 15:38 --- 一个简短例子来说明一下为什么 NSString @property 最好用 `copy` 而不是 `retain`: ```objc #import <Foundation/Foundation.h> @interface Person : NSObject @property (nonatomic, retain) NSString *name; @property (nonatomic, copy) NSString *school; @end @implementation Person @synthesize name, school; @end int main(int argc, char *argv[]) { @autoreleasepool { Person *p = [[Person alloc] init]; NSMutableString *s1 = [NSMutableString stringWithString:@"fannheyward"]; NSMutableString *s2 = [NSMutableString stringWithString:@"hfut"]; p.name = s1; p.school = s2; NSLog(@"%@, %@", p.name, p.school); // fannheyward, hfut [s1 appendString:@"---Heybot"]; [s2 appendString:@"---Heybot"]; NSLog(@"%@, %@", p.name, p.school); // fannheyward---Heybot, hfut } } ``` 简单来说就是 NSString 可以通过 NSMutableString (isa NSString) 来进行修改,如果 @property 是 `retain` 的话就可以绕过 Person 实例来修改 name 值(因为 name 指向 s1),大部分时候这种情况都是不应该发生的,用 `copy` 就没有这个问题。 这样来说象 NSArray/NSDictionary 等可修改类型都应该用 `copy`。 > For attributes whose type is an immutable value class that conforms to the NSCopying protocol, you almost always should specify copy in your @property declaration. 参考 [NSString property: copy or retain?](http://stackoverflow.com/a/388002/380774) <file_sep>/service-worker.js importScripts( "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js" ); workbox.core.setCacheNameDetails({ prefix: "im.fann", suffix: "v1" }); workbox.core.skipWaiting(); workbox.core.clientsClaim(); workbox.googleAnalytics.initialize(); workbox.routing.registerRoute( /\.(?:js|json|css)$/, new workbox.strategies.CacheFirst() ); workbox.routing.registerRoute( /\.(?:png|jpg|jpeg|svg|gif)$/, new workbox.strategies.CacheFirst() ); <file_sep>/_posts/2010-07-06-happy-birthday-to-my-girl.markdown --- layout: post title: "Happy Birthday to My Girl!" --- 妞妞生日快乐! 爱你乖~ <file_sep>/_posts/2014-04-17-vim-text-selection.markdown --- layout: post title: "Vim 文本选择范围" date: 2014-04-17 22:34:31 +0800 --- Vim 文本选择时可以用 `a` `i` 指定选择范围。`a` 代表一个整体(block),`i` 代表 inner。比如: `vaw` 包括单词和单词后的空格,`viw` 只选中单词。 `vat` - select a tag block, 包括 `<tag></tag>` 本身,`vit` - select inner tag,只选择 `<tag></tag>` 包起来的部分。 `vab` 选中包括 `()` 在内的文本,`vib` 不包括 `()` 自身,等同 `va(` `va)`, `vi(` `vi)`. `vaB` 选中包括 `{}` 在内的文本,`viB` 不包括 `{}` 本身,等同 `va{` `va}`, `vi{` `vi}`, 类似有 `va[` `vi[`。 `vip|vis` 选中一段落文字,vip = visual inner paragraph. vis = inner sentence. 将 `v` 换为 `d` 是就变成了删除操作,删除范围同上。 查看帮助 `:help v_<whatever>`. <file_sep>/_posts/2022-12-09-not-allowed-to-navigate-top-frame-to-data-url.markdown --- layout: post title: Not allowed to navigate top frame to data URL date: 2022-12-09 16:10:07 +0800 --- ```js function base64ToArrayBuffer(_base64Str) { var binaryString = window.atob(_base64Str); var binaryLen = binaryString.length; var bytes = new Uint8Array(binaryLen); for (var i = 0; i < binaryLen; i++) { var ascii = binaryString.charCodeAt(i); bytes[i] = ascii; } return bytes; } function showDocument(_base64Str, _contentType) { var byte = base64ToArrayBuffer(_base64Str); var blob = new Blob([byte], {type: _contentType}); document.location.replace(URL.createObjectURL(blob)); } showDocument('PGh0bWw+Cgo8Ym9keT4KICBoZWxsbyB3b3JsZC4KPC9ib2R5PgoKPC9odG1sPgo=', 'text/html'); ``` - https://itechowl.wordpress.com/2020/01/27/javascript-not-allowed-to-navigate-top-frame-to-data-url-chrome/<file_sep>/Dockerfile FROM ruby:2.1.3 MAINTAINER <NAME> <<EMAIL>> RUN gem install github-pages RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/* ENV NODE_VERSION 0.10.33 RUN curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.gz" \ && tar -xzf "node-v$NODE_VERSION-linux-x64.tar.gz" -C /usr/local --strip-components=1 \ && rm "node-v$NODE_VERSION-linux-x64.tar.gz" WORKDIR /blog EXPOSE 4000 ENTRYPOINT ["jekyll"] CMD ["serve"] <file_sep>/_posts/2009-08-28-configuration-vs-environment.markdown --- layout: post title: "配置VS环境" --- 现在在公司的开发环境还是 Delphi,不过 Asp.Net 的项目也已经开始了,而且老大已经发话,以后我们组可能要 Delphi 和Asp.Net 双肩挑。正好今天没啥活,就着手把 VS 环境配置了一下。安装 VS 2005,这个没什么可说的,自己额外的配置是添加了 ViEmu 和 Visual Assist X 两大利器。 ViEmu is a an add-in to Visual Studio which enables vi/vim-like editing for Microsoft Visual Studio .NET 2003, Visual Studio 2005 and 2008. 简单说就是在 VS 里使用 vim 的编辑方式和键盘映射。在 VS 这种庞大的 IDE 里面,智能补全等功能比 vim 要强大的多,不过由于习惯了 vim 的移动方式,0/$/w/f/j/k/gg/G/zz 等等,手不用离开主键盘的在代码里跳跃,很方便。 Visual Assist X,大名鼎鼎的“VC助手”,强大的智能感知自动完成功能,各种方便的 Snippets,强大,用了就知道有多爽。 PS:这俩东西都是共享软件。。。怀着崇敬的心情破解了他们。。。DotNet 的东西其实挺强的,跟 MS 走还是有肉吃的,不过就是过于庞大。慢慢来,摸索中前进,加油吧。 <file_sep>/_posts/2017-06-01-development-in-startup.markdown --- layout: post title: Development in Startup date: 2017-06-01 15:37:35 +0800 --- ![dev-culture](https://i.loli.net/2019/04/29/5cc695fa3ee98.gif) <file_sep>/_posts/2013-04-11-why-i-dont-like-translated-technical-articles.markdown --- layout: post title: "这就是为什么我不喜欢看中文翻译的技术文章" date: 2013-04-11 23:09 --- 原文: [25 iOS App Performance Tips & Tricks][1] 1. Use ARC to Manage Memory 1. Use a reuseIdentifier Where Appropriate 1. Set Views as Opaque When Possible 1. ... 翻译版本: [iOS应用性能调优的25个建议和技巧][2] 1. 用ARC管理内存 1. 在正确的地方使用reuseIdentifier 1. 尽可能使Views透明 1. ... 注意看第三条。 ![fail.png](https://i.loli.net/2019/11/11/7N92AE4SaLmd8GB.png) 技术文看中文翻译版本确实省时省力,但是如果翻译质量不好或者出错的话就会被带到沟里。其实技术文章的词汇非常集中,同一技术点的单词翻来覆去就那几个,多看几篇文档就熟了。 PS:没有一点炫耀英文的意思,大学英语四级 426. [1]:http://www.raywenderlich.com/31166/25-ios-app-performance-tips-tricks [2]:http://blog.jobbole.com/37984/ <file_sep>/_posts/2010-03-17-fannt2r-new-version.markdown --- layout: post title: "Fannt2r New Version" --- Fannt2r 是一个同步我的 Twitter 到人人的一个 GAE 应用,参考网上教程自己瞎搞出来的。现在是 cron 5分钟一次 LoginRenren、GetTweet、SendStatus,基本满足。早上在路上的时候想到了一个新的实现方式,备忘一下: 1. 先 GetTweet,然后判断 if synctag in status: 2. 然后再 LoginRenren、SendStatus。 这样可以 cron 一分钟跑一次,时效性更高,也不会因为过于频繁的 fetch 登录人人造成帐号被冻结。 <file_sep>/_posts/2010-09-16-cron-notes.markdown --- layout: post title: "Cron notes" --- Cron is a Linux system process that will execute a program at a preset time. To use cron you must prepare a text file that describes the program that you want executed and the times that cron should execute them. Then you use the **crontab** program to load the text file that describes the cron jobs into cron. via [Using cron](http://www.scrounge.org/linux/cron.html) **crontab -e** to edit the crontab file. Format: > `[min] [hour] [day of month] [month] [day of week] [program to be run]` Some examples: > `10 3 * * * /usr/bin/foo` ==> Will run /usr/bin/foo at 3:10am on every day. > `12 3 * * * root tar czf /usr/local/backups/daily/etc.tar.gz /etc >> /dev/null 2>&1` via [Cron Help Guide](http://www.linuxhelp.net/guides/cron/) <file_sep>/_posts/2012-12-08-setup-octopress-from-existing-repo.markdown --- layout: post title: "Setup Octopress from existing repo" date: 2012-12-08 23:34 --- 从已有的 Octopress repository 重新配置 GitHub Pages 托管博客,比如换了电脑却没有备份原来的设置。要求 source 分支已 push。 ``` git clone git@github.com:fannheyward/fannheyward.github.com.git blog cd blog git checkout --track origin/source # setup ruby with rbevn or rvm gem install bundler bundle install rake gen_deploy # in order to create _deploy dir # setup blog branch cd _deploy/ git init git add . git commit -m "new setup." git remote add origin <EMAIL>.com:fannheyward/fannheyward.github.com.git cd .. rake deploy ``` 其实就是做了一系列的 git 操作,设置 repo,branch 等,熟悉 git 很容易搞定。 <file_sep>/_posts/2011-04-03-software-used-on-mac.markdown --- layout: post title: "Mac 下的一些软件" --- 除了系统自带的,在用的一些软件。挑选软件以 开源 > 免费 > 收费 标准。 cd to: 在 Finder 上加一个小按钮一键到 Terminal. Alfred:主要是界面好看,其实默认的 Spotlight 已经很够用了。 Cog:小巧的播放器。 Dropbox:不解释。 Firefox:不解释。 Fit:不解释。 Jumpcut:剪贴板记录,够小够用。 Jitouch:触摸板增强工具,就用了左右标签切换和关闭标签这三个。收费但可用,连续使用多次后功能关闭,需要手动启用一下。 Keka:解压缩工具,主要为了对付 rar。 Secret Socks:ssh 代理连接,比 iSSH 要稳定不少。 Sparrow Lite:最爱的邮件客户端,因为她支持 Gmail 快捷键。Lite 支持 Gmail,正好够用。 TrashMe:新发现的卸载软件工具,界面不错,很 CCleaner,免费。 <file_sep>/_posts/2018-05-31-stop.markdown --- layout: post title: Stop date: 2018-05-31 16:41:27 +0800 --- Stop, 是一个行程的中止。 Stop, 也是一个站点,下车,上车,继续前进。 2010.6 - 2018.5. <file_sep>/_posts/2008-11-17-weekend-1117.markdown --- layout: post title: "Weekend-1117" --- 又一个星期了,时间过的真是快。复习的好累,也好困,老是想睡觉,唉。不过还得加油!GoGoGo! 来个小笑话:播音稿原文:两歹徒打伤我110干警后逃窜. 播音员读成:两歹徒打伤我一百一十名干警后逃窜 :D 继续加油! <file_sep>/_posts/2010-04-12-why-gae-why-picky.markdown --- layout: post title: "Why GAE?Why Picky?" --- Why GAE?为什么用 GAE 做 Blog 平台,参见 Livid 的[把博客架在 Google App Engine 上的好处][whygae],自己的观点: 1. [WP][wp] 越来越庞大。WP 的功能强大和定制性毋庸置疑,但是随着 WP 的功能强大,效率和安全性越来越是个问题; 2. 主机服务器的问题,在国内要备案要审查,这也是为啥我放弃了之前在国内的博客停止更新; 3. GAE 是免费,并且满足自己折腾。 在放弃 WP 转战“云博客”的时候,也考虑过 Blogger、WP.com、Posterous 这种 BSP,不过还是放弃了,原因: 1. Blogger、Posterous 虽然也可以自己绑定域名,但你能够折腾的只有内容和样式布局上,在整体功能上还是受限,参考上面第三条; 2. WP.com 可以让我无痛转移之前博客过去,但不能绑定域名; 3. GAE 的强大免费以及对 Google 的中毒,:) Why [Picky][picky]?Blog system powered by GAE 有很多,其中徐明的 [Micolog][micolog] 和丛林大侠的 [iHere][ihere] 异常强大,最吸引我的就是都支持 WP 导入,但是这两个的强大带来的一个问题就像是 WP 的庞大,有很多自己不非常需要的功能。另外,Picky 有很多非常吸引我的地方; 1. Clean,no unnecessary visual noises,focus on writing; 2. Employ sexy technologies like HTML5,Twitter; 3. Integrated Twitter client,synchronize to Twitter automatically. 至于 appspot 被墙,这年头谁上网还没几个翻墙的家伙什?! 这就是为什么我选择 GAE+Picky 作为自己的发布平台,Easy to share my thought and opinion。 [whygae]:http://v2ex-picky.appspot.com/benefit-host-blogs-with-google-app-engine [wp]:http://wordpress.org/ [picky]:http://picky.olivida.com/picky [micolog]:http://micolog.xuming.net/ [ihere]:https://code.google.com/p/ihere-blog/ <file_sep>/_posts/2021-04-09-mysql-explain-notes.markdown --- layout: post title: MySQL EXPLAIN Notes date: 2021-04-09 13:54:53 +0800 --- ```tet mysql> explain select * from t1; +----+-------------+-------+------+---------------+------+---------+------+------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+------+---------+------+------+-------+ | 1 | SIMPLE | t1 | ALL | NULL | NULL | NULL | NULL | 20 | NULL | +----+-------------+-------+------+---------------+------+---------+------+------+-------+ ``` 1. `EXPLAIN` 支持 SELECT, DELETE, INSERT, REPLACE, UPDATE 1. `id` 查询编号,有几次 SELECT 操作就有几个编号 1. `select_type` 查询类型 - `SIMPLE` 简单查询,查询中不包含子查询和 UNION - `PRIMARY` 复杂查询最外层的 SELECT - `UNION` 在 UNION 中的第二个及随后的 SELECT - `UNION RESULT` 从 UNION 临时表进行的 SELECT - `SUBQUERY` 子查询中的第一个 SELECT - `DERIVED` 包含在 FROM 子句中的子查询 - `UNCACHEABLE SUBQUERY` 不能被缓存的子查询,每次都要计算,是非常耗时的操作 - `UNCACHEABLE UNION` UNION 中不能被缓存的查询 1. `table`: 当前查询访问的表名,如果有子查询或 UNION 会有以下几种格式 - `<unionM,N>` - `<derivedN>` - `<subqueryN>` 1. `type` 查找访问类型,说明 MySQL 使用哪个索引在该表中找到对应的记录。按最优 - 最差依次是: 1. `system` 1. `const` 表中最多有一个匹配行,速度最快 1. `eq_ref` primary key 或 unique key 索引的所有部分被连接使用,最多只返回一条符合条件的记录 1. `ref` 不使用唯一索引,而是用普通索引,可能会找到多个符合条件的记录 1. `fulltext` 使用全文索引的时候才会出现 1. `ref_or_null` 和 ref 类似,但 MySQL 会额外一个查询来看哪些行包含了 NULL 1. `index_merge` 使用了索引合并优化 1. `unique_subquery` 比 eq_ref 复杂的地方是使用了 IN 子查询 1. `index_subquery` 类似 unique_subquery 但在子查询里使用的是非唯一索引 1. `range` 指定范围的扫描 1. `index` 和 ALL 类似,不同的是只扫描索引 1. `ALL` 全表扫描 1. `possible_keys` 可能用到了哪些索引来查找 1. `key` 实际扫描使用的索引 1. `key_len` 实际使用的索引长度 1. `ref` 查找时所用到的列或常量 1. `rows` 预估要读取的行数 1. `Extra` 额外补充信息 - Distinct - Using index 只使用了索引信息,没有访问行记录 - Using where 读取行记录后使用 where 判断检查 - Using temporary MySQL 创建了临时表来处理查询,需要索引优化 - Using filesort 读取结果后进行了排序操作,需要优化 <file_sep>/_posts/2015-05-21-nginx-phases.markdown --- layout: post title: Nginx/OpenResty 指令的执行顺序 date: 2015-05-21 16:33:51 +0800 --- * [NginX OpenResty的内建及扩展模块的phase先后执行次序][1] * [Nginx Phases][2] * [Nginx配置指令的执行顺序][3] 1. **http**, 可以通过 init_by_lua 加载公共函数,比如 `lua-resty-core`. 2. **server selection**,listen,server_name. 3. **post read**, ngx_realip. 4. **server rewrite**, set, rewrite, return, set_by_lua. 5. **server rewrite tail**, rewrite_by_lua. 6. **server access**, allow, deny. 7. **server access tail**, access_by_lua. 8. **server try_files**. 9. **location**: 1. prefix strings 遵循 **最长子串匹配原则** 2. regular expressions 遵循 **先定义优先匹配原则** 3. `location = {exact_url}` 精准匹配 4. `location ~ {case-sensitive regex}` 区分大小写 5. `location ~* {case-insensitive regex}` 不区分大小写 6. `location ^~ {prefix_string_if_any}` 一旦字符匹配成功,就不再正则匹配 7. 尽量不要 `if`,换用 `try_files` 8. `-f` 检测文件是否存在,`-d` 目录,`-e` 文件/目录/符号链接,`-x` 可执行文件 10. **location rewrite**, set, rewrite, return, set_by_lua. 11. **location rewrite tail**, rewrite_by_lua. 12. **preaccess**, degradation, limit_zone, limit_req, ngx_realip. 13. **location access**, allow, deny, auth_basic. 14. **location access tail**, access_by_lua. 15. **content**, ngx_echo, proxy_pass, content_by_lua. 1. 请求具体处理阶段,只能有一个 **内容处理程序(content handler)** 1. 多个 echo 可以共存,因为同属于 ngx_echo 模块,但 ngx_lua 限制只能有一个 content_by_lua. 1. ngx_echo 的 echo_before_body/echo_after_body 可以和其他模块共存 1. 如果没有 ngx_echo, proxy_pass, content_lua 这些 content handler,Nginx 会根据 URL 将请求映射到静态资源服务模块,依次是 ngx_index, ngx_autoindex, ngx_static. 1. ngx_index/ngx_autoindex 处理以 `/` 结尾的请求,ngx_static 正好相反。 16. **output header filter**, more_set_headers 输出 Headers. 17. **output filter** echo_before_body, echo_after_body, body_filter_by_lua. 18. **log**, access_log, error_log, log_by_lua. 19. **post action**. ![OpenResty](https://cloud.githubusercontent.com/assets/2137369/15272097/77d1c09e-1a37-11e6-97ef-d9767035fc3e.png) [1]:https://gist.github.com/diyism/36c9d7e699cf3c67352e [2]:http://nginx.org/en/docs/dev/development_guide.html#http_phases [3]:http://blog.sina.com.cn/s/articlelist_1834459124_2_1.html <file_sep>/_posts/2011-12-24-how-to-make-your-iphones-home-button-more-responsive.markdown --- layout: post title: "How To Make Your iPhone’s Home Button More Responsive" date: 2011-12-24 09:39 --- via [How To Make Your iPhone’s Home Button More Responsive [iOS Tips]][1] 1. 打开一个系统自带软件,比如天气,股票。 1. 按住电源键直到出现“移动滑块来关机”,不要按“取消”。 1. 长按 Home 键直到提示消失,软件退出。 类似系统校准的原理,让 Home 键变得更灵敏。 [1]:http://www.cultofmac.com/136785/how-to-make-your-iphones-home-button-more-responsive-ios-tips/ <file_sep>/_posts/2012-06-27-self-review-at-half-year-2012.markdown --- layout: post title: "2012 年中总结" date: 2012-06-27 23:44 --- 2012 上半年小结。 ## 工作 去年年终总结时候说今年要加强产品锻炼,今年团队也给了这样的机会。第一次作为产品负责人带产品开发,自己却做的很不好,[很不及格][1]。产品这一块还有很多很多要学习的地方,分工、协作、沟通、整体、进度等等,在接下来的工作中还要多多学习。 上半年在技术上有了一些新的学习和积累,做了第一个真正意义上的 iPad 应用。大屏幕的体验、使用场景、使用习惯都和 iPhone 有着很大的不同,信息结构有着不一样的处理,对应交互、UI 上有很大的差异,这些差异需要更多的学习理解。开发上由于 iPad 项目是一个全新的项目,尝试了一些新的技术和框架,包括 ARC,新的网络请求方式等。新技术和框架的学习需要一定时间和成本,甚至要交学费,但是从长远来看,这些投入都是值得的,对自己的技术成长很有好处,也有利于团队技术积累。作为开发,如果现在用着和一年前一样的代码做产品,虽然看起来效果一样,但自身的成长非常有限。 作为小团队,机动灵活是自己的特点,也是和大公司竞争的优势,因此在产品开发中要尽快拍板,速度迭代,先简单快速满足 80% 用户的需求,再去精益求精「像素级」地满足剩下 20% 用户。 ## 生活 今年生活中的重头戏就是完婚。结婚是一项庞大的工程,我和妞妞周末忙乎着婚纱照、礼服,爸妈在家忙婚礼安排、婚房装修,有时候还要远程遥控订化妆、摄影。婚礼就是两家人花费忙活,两个人受累上演给别人看得一场秀,表现着家族的威望、实力。如果你能躲过这场秀,那么恭喜你省力很多;如果不能避免,那么何不把这场秀演的更好呢? 上半年陆续有三个兄弟离职回老家工作,称不上「衣锦还乡」,但至少离家近点,毕竟我们都是念家的孩子。对于兄弟们回家工作,我都是双手赞成,虽然我自己还在坚持北漂。有时候我也会问自己到底在坚持什么,那些个梦?那些个理想?那些个自己[不愿被这世界改变][2]?我不想等我老了的时候后悔没有拼搏坚持过。 向阳说「成长就是让你从诗人变成世人」。其实,从诗人变成世人,我们都输了。在坚持做自己喜欢的事,还要记住不做让自己讨厌自己的事。最近很多事情让我越来越感受到拒绝比坚持更难。 不知道跟谁学的,现在酒喝多了就满世界打电话,还哭,太差劲。酒量也严重退步,估计结婚的时候该被灌成傻子了。 嗯,以上。 [1]:https://fann.im/blog/2012/03/05/my-first-product-summary-failed/ [2]:https://fann.im/blog/2011/06/11/change-or-be-changed/ <file_sep>/_posts/2011-01-30-home-for-new-year.markdown --- layout: post title: "回家过年" --- 回家过年,过年回家。 回去看看爸妈,陪陪小妹,跟兄弟扯淡。 大了,在家的时间是越来越少,要珍惜。 <file_sep>/_posts/2014-08-30-nginx-proxy-cache.markdown --- layout: post title: "Nginx proxy_cache" date: 2014-08-30 15:15:35 +0800 --- Nginx [proxy_cache][1] 可以将后端动态请求的返回内容进行缓存,原理是 URL 作为 cache_key,将内容缓存到磁盘,新请求符合缓存规则的话直接读取缓存内容返回。 ``` proxy_cache_path /tmp/ngx_cache/proxy_cache_dir levels=1:2 keys_zone=ngx_cache:10m inactive=30m max_size=500m; proxy_temp_path /tmp/ngx_cache/proxy_temp_dir; server { proxy_cache ngx_cache; proxy_cache_valid 10m; add_header Nginx-Cache "$upstream_cache_status"; set $no_cache ''; set_by_lua $cache_key " local no_cache = false if ngx.var.http_cookie and string.find(ngx.var.http_cookie, 'user') then # 带 cookie 的请求(比如登录用户)忽略缓存 no_cache = true end if ngx.var.uri == '/api/test' then #某些 URL 的请求强制缓存,不管是否有 cookie no_cache = false end if no_cache then #确定忽略缓存就不再计算 cache_key ngx.var.no_cache = 'true' return ngx.var.uri end local uri_args = ngx.req.get_uri_args() local args = {} for k, v in pairs(uri_args) do if k and v and type(v) == 'string' then if k == 'count' or k == 'sort' or k == 'page' then #过滤掉非法请求参数 args[#args+1] = k .. '=' .. v end end end if #args > 0 then table.sort(args) return ngx.var.uri .. '?' .. table.concat(args, '&') else return ngx.var.uri end "; proxy_cache_key $cache_key; proxy_no_cache $no_cache; proxy_cache_bypass $no_cache; location / { proxy_pass http://localhost:8080; } } ``` 配置 proxy_cache 很简单,建议先通读 [NGINX Content Caching][2] 文档。记几点笔记: 1. 用 OpenResty(ngx_lua) 作为前端 Nginx 代理和缓存服务器,好处是可以用 `set_by_lua` 计算赋值变量,原生 set 语法不够灵活。 2. `proxy_cache_path` 指定缓存文件目录,和 `proxy_temp_path ` 最好设置在同一文件分区下,缓存内容是先写在 temp_path,然后移动到 cache_path,不同文件分区会影响性能。 3. `keys_zone` 命名并设置缓存的内存空间大小,要注意的是这个内存空间并不保存缓存文件,而是缓存文件的元信息(meta information),所以不必太大,根据文档 1M 大小可保存 8000 文件的元信息,可以根据缓存文件数量进行设置。 4. `inactive=30m` 表示 30 分钟没有被访问的文件会被 cache manager 删除,`max_size=500m` 表示缓存目录最大限制 500M 磁盘空间。 5. `proxy_cache` 指明用哪个缓存空间,`proxy_cache_valid` 是缓存的有效时间,可以针对不同响应状态设置不同的有效时间,比如 `proxy_cache_valid 404 1m;`,默认只对 200/301/302 响应进行缓存。 6. 缓存文件数量过多会影响 proxy_cache 性能,Nginx 在启动时 cache manager 会检查并读取缓存文件的元信息到内存,这个读取是有限制的,默认情况下 cache manager 每次读取 100 个文件的元信息,每次读取限时 200ms,间隔 50ms 进行下次读取。 7. 缓存文件并不是越多越好,所以 cache_key 的设计非常关键。代理或 URL 跳转常常会添加的无用请求参数,这就会出现不同的 cache_key 保存了多份相同的缓存内容,这对缓存效果影响很大。通过 ngx_lua 可以对 URL 参数进行过滤,保证 cache_key 唯一。 8. `table.sort(args)` 对 URL 参数重排序,避免 `/api?page=1&count=10` `/api?count=10&page=1` 生成两份缓存的情况。 9. `$upstream_cache_status` 可以获取缓存状态,包括 `HIT/BYPASS/MISS/EXPIRED`,可以记录到 access_log 和 response header,用以计算缓存命中率。 10. `proxy_no_cache` 如果有值且不为 '0',该请求的 response 就不会生成缓存。 11. `proxy_cache_bypass` 如有有值且不为 '0',该请求会忽略缓存。 12. proxy_cache 不支持手动清除缓存,可以通过第三方模块 ngx_cache_purge 来清除指定 URL 的缓存。 proxy_cache 非常的简单高效,合理使用可以有效的减轻后端服务压力,提升服务访问速度。 [1]:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache [2]:http://nginx.com/resources/admin-guide/caching/ <file_sep>/_posts/2008-05-08-happy-birthday.markdown --- layout: post title: "生日快乐小鸟" --- 生日快乐,天天开心,幸福! <file_sep>/_posts/2015-06-30-monthly-review-1506.markdown --- layout: post title: Monthly Review 2015-06 date: 2015-06-30 14:09:43 +0800 --- 1. 用 Angular Material 写了个管理平台,体验很赞。 2. 用 [Gin](https://github.com/gin-gonic/gin) 改写了部分接口,现在是 Python+ngx_lua+Go,目前情绪稳定。 3. Gin 是个不错的框架,够轻量,middleware 扩展,封装适度,性能也不错。另一个是 [Goji](https://github.com/zenazn/goji),两个都是我比较喜欢的。 4. [gorm](https://github.com/jinzhu/gorm) 不错,目前项目比较简单,就直接通过 gorm 新建表结构,之前一个项目 Python+Go 都会涉及数据库,采取的策略是手动建表,ORM 只负责读写。 5. 前两天看《非你莫属》,20岁小哥,完全没有互联网从业经验,就因为看现在 O2O 火了,自以为有很多 ideas,要转投移动互联网,应聘产品经理。PM 就是这么被毁的啊。 5. 6月24日,六六一岁了。 <file_sep>/_posts/2010-06-22-mac-os-x-decoder-jpeg-not-available.markdown --- layout: post title: "Mac OS X: decoder jpeg not available" --- When you are using PIL to resize a JPEG image file, you will probably have a "**decoder jpeg not available**" error,this means that PIL doesn't have JPEG support. Here is the solution: 1. Download and install MacPorts. 2. **sudo port install jpeg**, this will install libjpeg. 3. **sudo port install py25-pil** That's it. <file_sep>/_posts/2010-08-22-pyton-dictionary-tips.markdown --- layout: post title: "Python Dictionary tips" --- - Constructing Dictionaries with Keyword Arguments,the simplest way to create a Dict. ``` dict(a=1, b=2, c=3) # returns {'a': 1, 'b': 2, 'c': 3} ``` - Dicts to Lists. ``` dict = {'a': 1, 'b': 2, 'c': 3} keys_list = dict.keys() #return ['a', 'c', 'b'] values_list = dict.values() #return [1,2,3] dict_as_list = dict.items() #return [('a', 1), ('b', 2), ('c', 3)] ``` via [Constructing Dictionaries with Keyword Arguments](http://www.siafoo.net/article/52#constructing-dictionaries-with-keyword-arguments) <file_sep>/_posts/2013-05-13-strings-static-library.markdown --- layout: post title: "使用 strings 查看静态库字符串" date: 2013-05-13 22:24 --- 起标题真费劲,意思就是用 OS X 的 `strings` 命令查看一个静态库是否包含某个字符串。比如 lib.a 是否用到了 uniqueIdentifier (苹果新规用了 UUID 的应用将会被拒)。 > strings - find the printable strings in a object, or other binary, file. 用法很简单: ``` strings lib.a|ag uniqueIdentifier ``` 这个强大的命令可以做很多事情,比如[这个][1]。 [strings](http://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/strings.1.html) manual page. Update: 查看当前路径下引用了 UUID 的文件: ``` find . | grep -v .git | grep -v "\.app" | grep "\.a" | xargs grep uniqueIdentifier ``` [1]:http://rndc.or.id/wiki/index.php/%28Ab%29Using_Twitter_Client#Twitter_for_iPhone <file_sep>/_posts/2011-03-21-mac-text-edit-moving-shotkuts.markdown --- layout: post title: "Mac 文本编辑移动快捷键" --- ![moving_cli](https://user-images.githubusercontent.com/345274/71775521-05272f80-2fbd-11ea-9c6a-fcc120ed17d4.png) 由于 Mac 的 Unix 渊源,Mac 支持一些 Emacs 的文本编辑快捷键,主要是文本内移动。适用于 Mac 下各种文本编辑界面,Xcode 等等。 - `Ctrl-f` 后一个字符 - `Ctrl-b` 前一个字符 - `Ctrl-p` 上一行 - `Ctrl-n` 下一行 - `Ctrl-a` 行首 - `Ctrl-e` 行尾 - `Ctrl-d` 删除光标后一个字符 - `Ctrl-h` 删除光标前一个字符 - `Ctrl-k` 删除光标至当前行尾 - `Ctrl-y` undo Ctrl-k - `Ctrl-o` 光标后回车换行 - `Ctrl-v` 向下翻页 - `Ctrl-t` 交换光标左右两个字符的位置 <file_sep>/_posts/2016-07-29-monthly-review-1607.markdown --- layout: post title: Monthly Review 2016-07 date: 2016-07-23 17:47:06 +0800 --- 1. 终于招到一个设计师,配合还不错 2. 国内现在的应用推广实在是乱,ASO 最火,这个还是很有技术含量的,主要是养账号难。苹果也看到了搜索的力量,干脆自己来收租,下半年付费搜索就要上线。 3. 产品迭代推进,从之前一团乱的情况有所好转,每次确定一个功能来做,完成度可以。现在问题是卡在提交上,不好审核通过。 4. 2016 ChinaJoy. 第一次自己带队参加活动。几点感触: 1. 游戏只剩下大公司,中小公司很惨,尤其是现在又出了手游版号要求。 2. 自己研发苦,做发行的就多了,包括出海/引入国内。 3. VR 火,不过小厂就是在替大厂做用户教育,最后都是炮灰,看看 PS VR 的预售就知道。 4. 全民直播时代真的到来了。 3. 六六两岁生日。去年暑假接到北京住了 40天,今年得再过两个月,天凉快后接过来,就不走了。 <file_sep>/_posts/2010-08-31-are-you-so.markdown --- layout: post title: "你是这样的吗?" --- 中国开发者的一个大的特点: ##### 对技术痴迷的同时不食人间烟火 ##### 1. 整天津津乐道的就是那些算法、数据结构、设计模式、语言技巧、技术规范 2. 对于普通老百姓关心的东西一概没有兴趣。 3. 大部分人对于时尚、化妆品、小资情调嗤之以鼻 4. 对于电影、音乐、艺术、美食一知半解,对于地产、金融、法律知识一窍不通 5. 对于一个普通老百姓市场生活中所能遇到的困难和问题,所追求的那一点享受和乐趣不闻不问 6. 既不愿意亲身实践,更在主观心态上予以拒斥。 ##### 根本上缺少对于生活和需求的深刻体察,对于人的关怀! ##### 策划产品的时候全凭感觉: + 做出来的东西千篇一律 + 看上去什么都有,一用起来处处不贴心。 + 我们把太多的时间用来围着电脑转,根本上缺少对于生活和需求的深刻体察,对于人的关怀。 + 在企业软件领域,我们把这种情况称之为“不了解业务”,现在整个企业软件领域都在寻找“懂技术,通业务”的复合型人才 + 在大众软件和公众互联网领域,这种情况同样严重。我就经常感觉,就算是 MP3 播放器、电子书、网络论坛这样最最平常的应用,一旦加上具体应用背景, 放在具体场合下,就有很多地方显得不方便,不贴心。 via [Slide success story by @stingchen](http://www.slideshare.net/stingchen/slide-success-story-case-study-iii-python-based-company). <file_sep>/_posts/2010-10-16-scheduled-backup-mysql-database-to-email.markdown --- layout: post title: "定时备份MySQL数据库到邮箱" --- 照网上例子写了个 bash 脚本,自动备份 MySQL 数据库,并通过 mutt 发邮件到邮箱。 先设置 mutt:vim ~/.muttrc ``` set envelope_from=yes set from=<EMAIL> set realname="DBBackup" set use_from=yes ``` Bash 脚本内容,vim back.sh ``` #!/bin/bash date=date +%Y%m%d mysqldump DBNAME -u USERNAME -pPASSWORD > /backup/$date.sql tar czPf /backup/$date.tar.gz /backup/$date.sql mutt -s "DBBackup" <EMAIL> -a /backup/$date.tar.gz < /backup/mailContent rm -f /backup/$(date +%Y%m%d -d "5 days ago").sql rm -f /backup/$(date +%Y%m%d -d "5 days ago").tar.gz ``` 权限修改:`chmod +x back.sh` 更新 crontab:`27 3 * * * root /back/back.sh` <file_sep>/_posts/2014-10-08-monthly-review-1409.markdown --- layout: post title: "Monthly Review 2014-09" date: 2014-09-30 15:25:39 +0800 --- > 选择 月初一个项目计划是客户端+服务端都由我负责,项目进行中我把客户端交了出去,保证进度是一个原因,毕竟是完全新的业务功能,服务端要做东西还挺多,主要原因是面对客户端开发,忽然手生,表现在这个东西我知道,着手代码的时候要愣一愣。 算下来有一年多没有 **系统** 的写 iOS,正好 iOS 7 一代。这一年 iDev 相关的学习一直没落下,但缺乏实际项目锻炼,解决问题的思路还有,具体到某一个技术点,比如写一个毛玻璃模糊效果,就要愣一下,需要查文档了。 出现这种情况也在意料之中,虽说要做全栈开发,终究是要有些侧重,目前还是以服务端为主。服务端开发现在主要是业务驱动,技术长进有限,最近在看 nsq,争取在业务和技术上都能有进步。客户端方面还是技术关注+学习,具体开发上给我一点时间还是有信心回到之前的熟练水平 :D ---- 最后还是选择把六六留在老家。走这一步我和老婆俩人没少哭,就现阶段条件,执意带六六到北京的结果可能更糟,北京的居住条件六六和妈是否适应,爸一个人在家的生活,妹妹也还没毕业,就算狠狠心带过来也不能长久,这些都让人头大。六六在家爸妈肯定能照顾好,就是想孩子受不了,尤其是大了越来越好玩,真心舍不得。每个月多往家跑跑吧。 六六健康成长。 <file_sep>/_posts/2008-04-19-show-my-security-suite.markdown --- layout: post title: "Show一下电脑安全组合" --- 在Crazy Software上看到的[小调查](http://soft.72pines.com/what-is-your-security-suite/),咱也来凑个热闹玩玩。 安全组合:NOD32+SSM+xp 自带的防火墙,常驻型。 NOD32,就像那句广告:“杀毒不过头点地”,启发式杀毒,又省资源,杀毒速度又快,加上那么好的口碑,方便的很用着。国内免ID升级服务器。 SSM,系统级的防火墙,就是要求高了一点,你得会配置,不然一个正常的关机过程就要确认三四次的,不是每个人都能用的东西。30天永久试用版。 防火墙xp自带的,等待COMODO 3正式版,不想小白鼠了。貌似3里加上了HIPS,还不知道会不会跟SSM冲突呢? 辅助软件:Sreng,Process Explorer,360,AVG,偶尔拿出来手动扫一下,勤更新打补丁,所以自我感觉系统还是挺安全的哈。 <file_sep>/_posts/2014-03-01-action-now.markdown --- layout: post title: "Take Action Now" date: 2014-03-01 16:42 --- ![funnel.jpg](https://i.loli.net/2019/11/11/QXa3PEwRe49zrNv.jpg) 图片来自 [MESSAGING: MOBILE’S KILLER APP](http://stratechery.com/2014/messaging-mobiles-killer-app/). <file_sep>/_posts/2017-06-02-verify-ssl-certificate-key.markdown --- layout: post title: Verify SSL certificate and key date: 2017-06-02 18:01:23 +0800 --- You can use `OpenSSL` to verify whether a SSL certificate and a key is matched: ``` openssl x509 -noout -in certificate.crt | openssl md5 openssl rsa -noout -in privateKey.key | openssl md5 openssl req -noout -in CSR.csr | openssl md5 ``` If both commands return same hash, the certificate and key is matched. <file_sep>/_posts/2010-04-28-version-number-in-appyaml.markdown --- layout: post title: "GAE app.yaml version number" --- > If you don't change the version number in app.yaml,your changes will be made live immediately.When you are developing your application and are not formally in production,it is good practice to leave the version number unchanged when you upload new version. 一直都有个疑惑,在 GAE 上部署 App 新版本的时候,app.yaml 里面 version 该怎么设置,为求保险,之前都是依次递增。看到上面这一段明白了,如果不修改,那么会完全覆盖掉 GAE 上当前版本,新版本立即生效,这在进行实时开发的时候非常方便。如果在当前稳定版本的基础上测试新功能开发,最好修改 version number,这样对外跑一个稳定版本,测试版本可以单独跑,互不耽误。测试通过后可以在 versions 设置哪一个作为默认应用版本。 <file_sep>/_posts/2017-11-15-zhang.markdown --- layout: post title: 张姐 date: 2017-11-15 14:05:14 +0800 --- 刚吃完老张给我们做的最后一顿午饭。 虽然我时不时的黑她做饭“黑暗料理”,她也会威胁我说“再黑我就一个月不做豆角”,但真的说从明天不再有她的午饭,还是很伤感的。 回去挺好,陪着三个孩子长大,祝一切顺利。 <file_sep>/_posts/2010-07-12-os-walk-digging-into-specified-level.markdown --- layout: post title: "os.walk() digging into the specified level" --- os.walk() 指定递归遍历深度。 ``` def walklevel(some_dir, level=1): some_dir = some_dir.rstrip(os.path.sep) assert os.path.isdir(some_dir) num_sep = len([x for x in some_dir if x == os.path.sep]) for root, dirs, files in os.walk(some_dir): num_sep_this = len([x for x in root if x == os.path.sep]) if num_sep + level <= num_sep_this: del dirs[:] ``` 重点是 **del dirs[:]**,置空 dirs,递归到此结束。 <file_sep>/_posts/2017-04-11-66.markdown --- layout: post title: 六六 date: 2017-04-11 21:11:32 +0800 --- 清明节假期带六六回老家,很多好玩的: * 高铁上,六六趴窗户上说:爸爸这地铁飞得好快! * 她现在已经不会说家乡话,尽管还能听懂,但一开口就是普通话。六六追着邻居小朋友问:小朋友们,你们还记得我吗? * 有一个小孩比她就大一两岁,按辈份得叫人姑姑,六六就不:是小姐姐,不是姑姑! * “爸爸爸爸,我给小朋友分饼干吃”。作为一个小吃货,能这样还挺让我意外。 * 会主动跟小朋友分享玩具,包括自己最喜欢的玩具琴。 * 去朋友家玩,会把小弟弟的玩具收起来,敢开口跟人打招呼,走的时候会跟所有人拜拜。 * 上山看见桃花,“爸爸我要那花”,我去摘花的时候在后面大叫 “爸爸 你小心一点”。 * 摔跤擦破了手,哭着找每个人求安慰,最后找爸爸擦药,哭的那叫一个伤心,忽然瞅见玩具小人的头在地上,瞬间不哭捡起来一本正经的说“这个头怎么掉了?”,然后又看着爸爸举着手哭。 * 走之前收拾行李,六六拿了一个塑料袋也要收拾行李,“爸爸,我把这个小鸭子带着吧,小鸭子最可爱了”,于是我们就把她那两个很早以前的小鸭子带到了北京。<file_sep>/_posts/2008-08-08-google-music-break-firefox.markdown --- layout: post title: "Google音乐在线播放不支持firefox解决" --- Google音乐刚出来时候试了一下,发现在线播放有问题,播放器错位,歌曲列表是空的,因为用的firefox 3,以为是不支持fx的原因,就换用ie 7,一切完美。后来发现是因为mediawrap插件的原因,禁用mediawrap后正常。 UPDATE: 其实不用完全禁用mediawrap,只需要在mediawrap设置中取消 `Shockwave Flash` 选项即可! <file_sep>/_posts/2010-08-17-python-multi-threading-crawler.markdown --- layout: post title: "Python 多线程爬虫" --- 备忘。 队列模块使用步骤([via](https://www.ibm.com/developerworks/cn/aix/library/au-threadingpython/)): 1. 创建一个 Queue.Queue() 的实例,然后使用数据对它进行填充。 2. 将经过填充数据的实例传递给线程类,后者是通过继承 threading.Thread 的方式创建的。 3. 生成守护线程池。 4. 每次从队列中取出一个项目,并使用该线程中的数据和 run 方法以执行相应的工作。 5. 在完成这项工作之后,使用 `queue.task_done()` 函数向任务已经完成的队列发送一个信号。 6. 对队列执行 join 操作,实际上意味着等到队列为空,再退出主程序。 其中 join() 方法说明: > 保持阻塞状态,直到处理了队列中的所有项目为止。在将一个项目添加到该队列时,未完成的任务的总数就会增加。当使用者线程调用 `task_done()` 以表示检索了该项目、并完成了所有的工作时,那么未完成的任务的总数就会减少。当未完成的任务的总数减少到零时,join() 就会结束阻塞状态。 <file_sep>/_posts/2015-05-18-nginx-log-to-influxdb.markdown --- layout: post title: Nginx log to InfluxDB date: 2015-05-18 16:35:12 +0800 --- [InfluxDB][1] 是一个支持时间序列的数据库,自带 SQL-like 查询语言,很适合用作日志存储。配合 [Grafana][2] 面板展示,非常方便。 接下来要做的就是将 Nginx 日志写入 InfluxDB。常见的方法是用 [Logstash][3] 等工具收集 access.log/error.log 通过 filter 处理后写入 InfluxDB。这种方法对服务没有任何侵入,数据完全从 log 获取,缺点就是数据源单一,nginx.log 能纪录的东西比较有限。 再一个方式就是通过 ngx_lua 的 `log_by_lua`。log 阶段在 content 后,请求已完成,这时候做一些处理不会拖累服务。相对 nginx.log 可以通过 ngx_lua 获取更多信息,比如 `ngx.req` 获取请求信息,过滤 `ngx.var.uri` 将同一类请求合并,`ngx.var.http_cookie` 读取 cookie 针对登录用户做特殊纪录等。然后通过 InfluxDB 的 HTTP API 写入存储。 需要注意的是在 `log_by_lua` 里不能直接用 Cosocket,需要做一些特殊处理:创建 0 延时的 `ngx.timer`,在 timer 回调中用 Cosocket 发请求,参考 [lua-resty-logger-socket][4] 的实现,文档里也是建议这个方法 [Cosockets Not Available Everywhere][5]. InfluxDB 初步用下来还不错,HTTP API 方便不同服务接入,拿来做数据存储分析挺好。现在的问题是看 InfluxDB 的性能、稳定性如何。 [1]:http://influxdb.com [2]:http://grafana.org/ [3]:https://www.elastic.co/products/logstash [4]:https://github.com/cloudflare/lua-resty-logger-socket [5]:https://github.com/openresty/lua-nginx-module#cosockets-not-available-everywhere <file_sep>/_posts/2014-10-19-tweet.markdown --- layout: post title: "Tweet" external-url: https://twitter.com/jack/status/17680161621151744 date: 2014-10-19 13:28:25 +0800 --- > Make every detail perfect and limit the number of details to perfect. via [Jack](https://twitter.com/jack/status/17680161621151744) <file_sep>/_posts/2022-04-01-untitled.markdown --- layout: post title: Untitled date: 2022-04-01 11:19:28 +0800 --- <!-- markdownlint-disable-next-line --> <img src="https://user-images.githubusercontent.com/345274/161189041-9379e5d1-4eb9-4356-97d8-bf32334d336a.jpg" width="650" height="365" alt="if-this-is-the-worst-thing-that-happened-to-you-in-your"> > If this is the worst thing that happened to you in your life, you got a very lucky, blessed and fortunate life. > > -- <cite><NAME></cite> <file_sep>/_posts/2010-04-19-one-day-in-huangshan.markdown --- layout: post title: "一日黄山" --- 由于我悲剧的手机线充,去黄山的这两天不敢随意上推,也就无法随时记录这次黄山一日的一些感受想法,下面这些字是回来后回想,些许带着情绪。标题很明显就带着情绪。 1. 坐车真累,17 号早上 7 点出发,12 点才到汤口,这一路车坐的屁股疼。由于不能手机上网玩,真的很无趣,只有睡觉。所以说,手机在有些时候是打发时间的绝佳武器。 2. 一路上的风景远观都很不错,很多油菜花,黄灿灿一片非常漂亮。 3. 往南走,能看到很多跟北方不一样的东西,比如建筑,两层尖顶小楼,应该是南方雨水多带来的特色建筑。 4. 旅游团订的午餐很烂,而且量很少,我们一桌人几乎都没吃饱。 5. 导游吃饭前是说先到宾馆,然后再计划下一步是休息还是宏村转转,结果吃了饭把你装上车就跟你耗着,不去宏村就不回宾馆,当然,去宏村的门票要再算。还好老板说给报销,不然估计得在大巴上憋几个小时。 6. 宏村的设计相当赞,非常的系统化。村子保存的很不错,虽然现在人工修复的痕迹很浓,依然能看出几百年前的样子。 7. 在宏村想去买点纪念品,但都知道旅游时候买这种东西就是明摆着让人宰,一个木工艺品要价 15,最后 5 块钱入手。 8. 晚上住宿就是个杯具,先是我们 43 个人被分成两批,说一个宾馆住不下,13 个人出去另一个宾馆,半路上又把我们 13 个人再次劈开,6 个人去一民宅,另外 7 个去另外一小区民宅,完全让导游宰割,你却没啥办法。 9. 早上 3 点起床,早餐,然后换乘黄山旅游大巴上山,盘山路真险,绝对十八弯。 10. 缆车上山,开始发现人多,接下来一整天的感受就是人多。 11. 风景确实很美,只可惜 18 号天公不作美,早上阴天,远景看的不是太清楚。临时充当领队,拍了不少照片,可惜不是自己的相机,还没拿到照片。嗯,在黄山上,真的想要一个相机。 12. 八点不到的样子,阵雨如期而至。只见满山上都是雨衣,很好很强大。 13. 雨中感到光明顶,风大,只拍了几张。 14. 漫长的前山到后山之行,人挨着人,人挤着人,想走快是妄想,想慢走看景也是不可能。就这么“被”走了三公里到迎客松。 15. 人真多真多!玉屏峰全是人!下山口严重拥堵,据前方导游说中午时分上山的人依然很多,下山和上山的人在黄山狭窄的石道上堵住了。 16. 人太多,完全没有兴致玩了,排队下山。下山到天都峰路口时候,天气放晴,云雾飘渺,漂亮。 17. 上山容易下山难,生生走了两个小时,累的腿都要断掉。 18. 导游安排到一茶楼品茶,还是有不少同事被营销,纷纷出手买茶叶,可惜咱乡下人,不懂品茶,省掉。 19. 走了一天真累,粗略算下来有 20 里山路,所以回来的车上歪头就睡着了。 20. 十点半到合肥,打车回到家,洗洗睡吧。 景色真的很不错,只可惜人太多,又下着雨,完全没法去观景,就被挤着走路了。回头跟老婆挑个好时节好天气再去一番。 Update:今早看新闻,发现自己一不小心还参与创造[黄山游客记录](http://news.xinmin.cn/rollnews/2010/04/19/4499641.html),四月这种淡季居然赶上五一十一黄金周的人流量了,其实原因很简单,黄山这一天门票半价,我也是上山后听导游说才知道的。 <file_sep>/_posts/2012-06-17-2-years-in-beijing.markdown --- layout: post title: "2 Years in Beijing" date: 2012-06-21 09:47 --- 留记。 2010.06.17 到 2012.06.17,很有收获的两年,很有成长的两年。是一个结点,也是新的起点。 <file_sep>/_posts/2022-06-17-12-years-in-beijing.markdown --- layout: post title: 12 Years in Beijing date: 2022-06-17 15:34:53 +0800 --- 12 <file_sep>/_posts/2008-06-29-go-and-back.markdown --- layout: post title: "给心放假" --- 现在时刻:北京时间2008年6月29日晚上20:20,嗯,距离上一次写东西有一个星期了。 上周结束最后一门专业考试,这个星期算是彻底的放松了下来,也就不想上来写啥东西。当然中间把操作系统的课程设计给结束了,前后也就弄了两天加一个晚上,过了就中,不想弄。老是累,心累,也不知道是因为啥累,就像刚才,7点的时候,跟丫头说困了,趴一下,结果一下子睡到8点才醒过来。醒了的时候好轻松,莫名的舒服,嗯,好久没有这么舒服的睡觉了。 6月底,毕业的时候,这几天老是看见大四的离开,不免有点伤感。明年的这个时候,我们会怎么样的心情离开?希望是醉酒之后,因为可以麻木,没有感觉的看着一起四年的人各奔东西,到时候我要喝倒他们几个!可是谁把我灌倒,可以没有意识的不去回忆。。。 不写了,贴图一张,很适合这一段的心情。 ![](https://lh6.googleusercontent.com/-gajZxBd_E4E/U-t9a5SRM8I/AAAAAAAAGbU/_WrmGPPsf_c/w334-h500-no/3.jpg) 找个角落 闭上眼睛 世界就是你的... <file_sep>/_posts/2009-03-05-jdbc-jsp-connect-mysql.markdown --- layout: post title: "JSP连接MySql数据库" --- 相关环境:XAMPP 外加 Tomcat 6.0 扩展;JDK 并配置好环境变量;Mysql 里新建数据库,表。 JSP 使用 Mysql 主要是通过 `com.mysql.jdbc.Driver` 驱动,Tomcat 一般都自带的有,~\tomcat\lib\mysql-connector-java-5.1.6-bin.jar 有这个包就可以。新建 jsp-mysql.jsp 页面: ```html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <%@ page contentType="text/html;charset=utf-8" %> <%@ page language="java" %> <%@ page import="com.mysql.jdbc.Driver" %> <%@ page import="java.sql.*" %> <html> <head> <title>Untitled</title> </head> <body> <% String url ="jdbc:mysql://localhost/myguestbook"; String user="root"; String password="<PASSWORD>"; Connection conn= DriverManager.getConnection(url,user,password); Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); String sql="SELECT * FROM gb_content"; ResultSet rs=stmt.executeQuery(sql); while(rs.next()) { 百分号> 编号:<%=rs.getString(1)%> <百分号}%> <%rs.close(); stmt.close(); conn.close();%> </body> </html> ``` 没有差错的话一般就会连接成功的。继续学习 JSP. <file_sep>/_posts/2014-02-14-semver.markdown --- layout: post title: "Semantic Versioning 匹配" date: 2014-02-14 22:54 --- [Semantic Versioning][1] 直译为语义化版本,格式为 `MAJOR.MINOR.PATCH`,比如 `1.2.3` 代表第一主版本第二次版本第三补丁修正版,版本号唯一且可比较,更多信息参考官网介绍。 在 Node.js `package.json` 或 Bower `bower.json` 就是用 semver 做版本检查。记个笔记,假设当前最新版是 1.2.5: * `1.2.3` 明确指定版本,需完全匹配,安装的版本就是 `1.2.3`. * `>1.2.3` 大于指定版本,匹配符合条件的最新版 `1.2.5`. * `<1.2.3` 小于指定版本,匹配符合条件的最新版 `1.2.2`. * `<=1.2.3` 可以包括补丁修正测试版,比如 `1.2.3-beta`, * `1.2.3 - 2.3.4` 等同于 `>=1.2.3 <=2.3.4`. * `~1.2.3` 接近于 1.2.3 的版本,等同于 `>=1.2.3-0 <1.3.0-0`,也就是相同主版本,相同次版本,补丁修正大于等于所需版本均符合。这种情况是实际使用中最多的,保持最大的兼容性. * `~1.2` 等同于 `>=1.2.0-0 <1.3.0-0`,相同主版本、相同次版本均符合,等于 `1.2.x`。 * `~1` 等同于 `>=1.0.0-0 <2.0.0-0`,相同主版本均可,等于 `1.x`. * `*` 任意版本,会匹配当前可用的最新版 `1.2.5`. * `1.2.3 || 1.3.2` 哪个满足取哪个,如果两者均符合取第二个。 主要就是 `~` 匹配的使用,一般就用 `~1.2.3`,保持次版本内最新,又保持最大兼容性。 参考 [semver for npm][2],[package.json][3]. [1]:http://semver.org/ [2]:https://www.npmjs.org/doc/misc/semver.html [3]:https://www.npmjs.org/doc/files/package.json.html <file_sep>/_posts/2008-11-30-weekend-1130.markdown --- layout: post title: "Weekend-1130" --- 1. 下午把域名续费了一年。 2. 这两天都没好好复习了,老是静不下心,唉,感觉好罪过,不行,得加油了,时间不多矣。 3. 加油。 <file_sep>/_posts/2013-09-05-scrollstotop-in-multiple-uiscrollview.markdown --- layout: post title: "多 UIScrolllView 下点击状态栏回到顶部" date: 2013-09-05 11:08 --- iOS 下 UITableView/UIScrollView 有个特性:点击状态栏回到顶部。如果当前 view 下有多个 scrollView,或者多个 tableView 嵌套,点击回到顶部就无效,因为系统不知道该响应哪个,索性就全部禁用。文档: > On iPhone, we execute this gesture only if there's one on-screen scroll view with `scrollsToTop` == YES. If more than one is found, none will be scrolled. 找到了原因解决也就很简单:只保留需要点击回到顶部 scrollView.scrollsToTop = YES,其他全部禁用。 就这么简单的 tip 我也是最近才知道,而解决办法就在官方文档里,so [RTFM](http://en.wikipedia.org/wiki/RTFM) first. <file_sep>/_posts/2012-07-18-0718-thoughts.markdown --- layout: post title: "随想" date: 2012-07-18 20:53 --- 当你坚持着自己的想法在做一件自己想做事情的时候,当你坚持着自己的原则拒绝去做一些事情的时候,总会有一些声音有意无意地告诉你:你这个傻逼,这个社会就是这样。 这个社会太浮躁了现在,巨大的通胀让每个人都想着去赚快钱,大家都很难静下心来做一件让自己开心的事情。嗯,让自己开心的事情。 <NAME>: > Money is like gasoline during a road trip. You don’t want to run out of gas on your trip, but you’re not doing a tour of gas stations. You have to pay attention to money, but it shouldn’t be about the money. <file_sep>/_posts/2010-08-05-quickly-and-powerful.markdown --- layout: post title: "Quickly and powerful" --- 新系统的开发环境在 Mac 本地部署会很麻烦,所以就直接 ssh 到远程服务器就行修改操作;而 ssh 到服务器实施环境进行 coding 响应速度又跟不上,看着终端上字符一顿一顿的就焦急,配合 svn 快速而又安全的搞定。 本地 svn ci 代码到 svn 代码库,远程服务器 svn co 到实施环境,而后,就可以在本地进行 coding,完后 svn ci 提交代码,之后 ssh 到服务器实施环境 svn up 一下即可在实施环境部署最新代码。 通过 svn 代码库进行中间代码中转,这样 coding 的时候不受网络速度影响;通过 svn 又可以进行代码托管,保证代码安全,而且可以很方便的在实施环境切换、回滚代码版本。 唯一的一个小不足就是因为无法在本地进行 debug,有时候可能为了一个小问题 svn ci 好多次,代码库里会多好多个版本。 <file_sep>/_posts/2013-05-13-tmux-notes.markdown --- layout: post title: "tmux 使用笔记" date: 2013-05-13 14:25 --- 1. `tmux new -s name` 新建名字为 name 的会话(session),等同 `tmux new-session -s name`, 指定名字方便 attach。 1. `tmux rename -t session1 session2` 重命名 session1 为 session2,等同 `tmux rename-session -t session1 session2`。 1. `tmux ls` 列出所有会话,等同 `tmux list-sessions`。 1. `tmux at -t name` attach 名字为 name 的会话。 1. `tmux at -d` 重绘窗口,在大小不同屏幕上用 tmux 时候会保持窗口大小为最小尺寸,这个命令就可以重置窗口大小。[via][2] 1. `tmux kill-session -t name` 干掉指定名字的会话,关闭会话所有窗口自动会关掉会话。 1. `tmux kill-window -t name` 关闭指定窗口,很少用,一般都是 `Ctrl-b &` 关闭本窗口。 1. `Ctrl-b d` 脱离会话回到终端。 1. `Ctrl-b [` 进入复制模式,滚屏查看,支持 vim 上下翻页快捷键。 1. `Ctrl-b c` 新建窗口。`Ctrl-b &` 关闭窗口。 1. `set-window-option -g mode-keys vi` 设置复制模式中键盘布局为 vi。 1. `Ctrl-b w` 列出所有窗口,可用 vim j/k 上下翻页。 1. `Ctrl-b : - rename-window` 重命名窗口。 1. `Ctrl-b n/p` 切换到下一个/前一个窗口,也可以直接用 `Ctrl-b 数字` 切换到指定窗口。 1. `Ctrl-b %/"` 分割窗口为面板(panel)。`Ctrl-b x` 关闭面板。 1. `Ctrl-b Alt+方向键` 调整面板大小。 1. `Ctrl-b t` 很酷的一个时钟。 tmux 支持 `~/.tmux.conf` 配置文件,推荐设置 `set-option -g base-index 1` 让窗口从 1 排序,方便数字键切换。更多设置参考 Wiki [使用tmux][1]。 [Tmux Plugin Manager][3],插件管理,推荐 tmux-sensible, tmux-resurrect. [1]:https://wiki.freebsdchina.org/software/t/tmux [2]:http://stackoverflow.com/a/7819465/380774 [3]:https://github.com/tmux-plugins/tpm <file_sep>/_posts/2009-07-13-self-analysis-character.markdown --- layout: post title: "自我刨析——性格" --- 题外话:刚才翻了一下最近一段的日志,都是自己的一些叽叽歪歪,快要成 QQ 空间了,不管了,反正是自己的一亩三分地,自娱自乐嘛。那就再来一篇。XD 因为住的地方没有网络,晚上回去吃完饭没事的时候就一个人拿个手机坐阳台上无聊。空闲多了,想的就多了。分析一下自己身上的一些毛病缺点,记下来,努力去改。这几天想到的主要有做事情绪化,做事考虑不足,容易放弃。 做事情绪化,顺利的时候自己不管做啥事都很有劲,跑来跑去的相当积极,心情不好做事不顺的时候啥都不想干,宁愿自己一个人坐在那里生闷气。这样不好。尤其是现在已经参加工作了,很多时候都不可能完全顺自己的意思。在公司里人很多,规矩也很多,做事情很多时候都不会依自己的意思,这时候就要学会克制自己的情绪,先工作做事,切记不可情绪上抵制,就算一万个不愿意,也要在事情做完之后再有自己的意见。 做事考虑不足,容易冲动,只想到第一层结果,第二层结果,却不能够再多想几步,没有分析可能不对或者有不同结果的情况,这样的后果就是在事情出现不同的结局时候让自己懊悔,进而情绪化影响之后的事情。就比如前一段去昆山面试,公司那边的情况确实是急需要人,说是计算机专业的都会考虑。自己当时想的就是既然急需要人,那么可能机会就大了很多,就这么急匆匆的去了。却没有想到公司那边是要 C++/C 这种偏向于底层开发,嵌入式开发的,而自己偏向于 Web 开发,完全不同的技术应用,这么大的技术差距如果当时有想到的话就应该直接放弃,而不是在结果出来之后心情不爽。 容易放弃,其实也还是情绪化做事。在对自己不利或者做事不顺的时候,就容易放弃去做,或者消极怠工,反正就是不那么积极不那么主动了。如果在工作中,或者是在一些非常重要的决定时候,如果轻易的因为情绪化放弃,结果会是非常严重的,丢了饭碗,做了一个让自己后悔的决定等等,可能结局都将无法弥补。 分析问题很简单,难的是要去改正它。以后在工作中,生活上要努力的克制自己的情绪,分析问题要多考虑几步,胆大、心细,努力去干吧。 <file_sep>/_posts/2011-03-02-multiple-lines-string-in-objective-c.markdown --- layout: post title: "Multiple lines String in Objective-c" --- ```objc NSString *str = @"Line 1" "Line 2"; ``` via [How to split a string literal across multiple lines in C / Objective-C?](http://stackoverflow.com/questions/797318/how-to-split-a-string-literal-across-multiple-lines-in-c-objective-c/797351#797351) <file_sep>/_posts/2014-11-25-vim-tips.markdown --- layout: post title: "Vim Tips" date: 2014-11-25 16:00:36 +0800 --- 这周新学到的两个 Vim tips: * `gf` 跳转到当前光标所在名字对应的文件(前提是文件存在)。 * `C-w-f` 新 buffer 打开 * `C-w-gf` 新 tab 打开 * `gt` 跳转到下一个 tab,对应有 `gT` 上一个 tab,`{n}gt` 编号对应的 tab. <file_sep>/_posts/2018-03-29-debian-snapshot.markdown --- layout: post title: 通过 Debian Snapshot 安装旧版本包 date: 2018-03-29 11:32:07 +0800 --- 某个项目需要 PHP 5.3 支持,通过 APT 没办法直接安装,编译安装又是一大堆依赖,最后通过 Debian Snapshot 解决。 1. 在 [http://snapshot.debian.org/](http://snapshot.debian.org/) 搜索需要的包, 比如 `php5` 2. Got `http://snapshot.debian.org/archive/debian-ports/20120225T023111Z/pool-m68k/main/p/php5/` 3. 添加到 `source.list`: ``` deb http://snapshot.debian.org/archive/debian/20120225T023111Z/ unstable main deb-src http://snapshot.debian.org/archive/debian/20120225T023111Z/ unstable main ``` 4. `apt-get -o Acquire::Check-Valid-Until=false update` 5. `apt-get install php5=5.3.10-2 php5-fpm php5-cgi`, done.<file_sep>/_posts/2015-01-31-monthly-review-1501.markdown --- layout: post title: Monthly Review 2015-01 date: 2015-01-31 20:41:46 +0800 --- 1. 参加一次线下的 Golang 技术聚会,收获不少。 1. 有些业务功能很难 cover 全部情况,要有所取舍,满足最主要的用户需求。敢于放弃。 1. Android 项目启动,简单调研了一下,对这个生态系统还是没兴趣,尤其是国内乱七八糟的市场。 1. Golang 有了实际线上服务产出。 1. 视频时六六已经会自己找爸妈了,真快。 <file_sep>/_posts/2018-04-26-nginx-map.markdown --- layout: post title: Nginx map date: 2018-04-26 23:06:43 +0800 --- ```nginx map $room $room_server { default 192.168.1.101:8080; 1 192.168.1.101:8080; 2 192.168.1.102:8080; } server { listen 80; location ~ /api/(\d+)/room { set $room $1; echo $room_server; } } ``` `split_clients` 类似的结构,可以用来做请求 A/B 测试: ```nginx split_clients $arg_app_key $variant { 0.5% .one; 2.0% .two; * ""; } ``` [nginx mirroring tips and tricks](https://alex.dzyoba.com/blog/nginx-mirror/) <file_sep>/_posts/2008-07-26-boring-holiday.markdown --- layout: post title: "无聊的假期" --- 这两天算是老实多了,在家待着,不过真的是没事做啊。20号过完生日回来,在家待了一天就又去县城,然后去XIAOJIE家蹭饭一天,回来。这两天学会了上午睡觉晚上熬夜,没办法,睡不着觉。 为哈啊?不知道。。。心不在的时候就是会睡不着,哎。。。 <file_sep>/_posts/2015-09-18-growth-hacking.markdown --- layout: post title: Growth hacking date: 2015-09-18 21:29:15 +0800 --- [Growth hacking][0] 是市场运营通过技术形式获取用户的方法,包括数据分析,社交网站,EDM 等,据说 Facebook 还有专门的 Growth Team。今天见识了这种方法的力量。 起因是乌云的这篇文章:[XCode编译器里有鬼 – XCodeGhost样本分析][1],Xcode 被挂马,网易云音乐中招,看后顺手测了自己常用的应用,发现另外几个中招,在群里吐槽后就没再继续关注,之后又看见微博有人在转,就发了 Twitter: > 通过 Charles 抓包,会向 http://init.icloud-analysis.com 发请求的有网易云音乐,中信银行动卡空间,12306,滴滴打车 #XcodeGhost [13:41][2] 发之前就在想这个肯定会爆掉,但没想到有这么火爆: 1. 迅速被 RT,涨 fo。 2. 约十五分钟后被转发到微博,包括 @Fenng,@onevcat 等大 V 二次转发。 3. V2EX,知乎,36kr,iApps,虎嗅等科技网站发帖,有引用 Twitter 链接/截图 [1][11] [2][22] [3][33] [4][44] [5][55] 4. 15:10 腾讯科技 [App Store遭病毒入侵 网易云音乐等中招][6],而且他们应该是有通过 Linkedin 查看我的工作信息,之后该文被其他多家引用。 根据 Tweet Activity 统计,原推一共 impressions 14000+,engagements 1300+,RT 170+,followers 增长 100+,考虑到访问 Twitter 的困难,这个数据还是非常恐怖的。微博的量应该更大。 这是 Growth hacking 的一次直观感受,如果产品推广也能有这样的效果该多好 :D ---- 作为开发者,#XcodeGhost 要引起重视: 1. 正当渠道下载应用,不限于 Xcode,检查签名/checksum。 2. 用到的第三方 SDK 也要检查来源,设想微信 SDK 被调包?! 3. 重视安全,一旦被人发现没穿裤子,负面信息足以摧毁一个产品。 [0]:https://en.wikipedia.org/wiki/Growth_hacking [1]:http://drops.wooyun.org/news/8864 [2]:https://twitter.com/fannheyward/status/644747940020424704 [11]:https://www.v2ex.com/t/221744 [22]:https://www.v2ex.com/t/221722 [33]:http://www.zhihu.com/question/35721299 [44]:http://www.iapps.im/single/33996 [55]:http://www.huxiu.com/article/126355/1.html [6]:http://tech.qq.com/a/20150918/049301.htm <file_sep>/_posts/2008-12-24-merry-christmas.markdown --- layout: post title: "Merry Christmas" --- 转眼就到年底了,赶下时髦,过个圣诞节。今天24号,好像叫平安夜,Silent Night,平安夜快乐,再来句圣诞快乐,Merry Christmas Everyone. ![](http://www.google.com/logos/holiday08_1.gif) ![](http://www.google.com/logos/holiday08_2.gif) ![](http://www.google.com/logos/holiday08_3.gif) ![](http://www.google.com/logos/holiday08_4.gif) ![](http://www.google.com/logos/holiday08_5.gif) <file_sep>/_posts/2013-10-20-daddy-to-be.markdown --- layout: post title: "准爸爸" date: 2013-10-20 12:45 --- 2013-10-20. <file_sep>/_posts/2010-05-28-unicodeencodeerror-ascii-codec-can-t-encode-characters.markdown --- layout: post title: "UnicodeEncodeError: 'ascii' codec can't encode characters" --- Problems with non-ASCII characters. ``` import sys default_encoding = 'utf-8' if sys.getdefaultencoding() != default_encoding: reload(sys) sys.setdefaultencoding(default_encoding) ``` [via](http://mgltools.scripps.edu/documentation/faq/unicodeencodeerror-ascii-codec-can-t-encode-characters) <file_sep>/_posts/2013-09-20-nsinvocation-notes.markdown --- layout: post title: "NSInvocation Notes" date: 2013-09-20 09:35 --- iOS 中一般用 `performSelector` 系列方法调用某个对象的方法消息,但是参数过多就不太方便,这时候就可以用 NSInvocation。一个简单的例子: ```objc NSMethodSignature *sig = [self methodSignatureForSelector:@selector(addAlbum:atIndex:)]; NSInvocation *action = [NSInvocation invocationWithMethodSignature:sig]; [action setTarget:self]; //0 [action setSelector:@selector(addAlbum:atIndex:)]; //1 [action setArgument:&deletedAlbum atIndex:2]; //2 [action setArgument:&currentAlbumIndex atIndex:3]; //3 [action retainArguments]; [action invoke]; ``` `NSMethodSignature` 直译就是方法签名,保存了方法的参数类型和返回值信息 (type information for the arguments and return value of a method)。 通过方法签名信息就可以完整构建一个 invocation,对各个参数进行赋值后激活执行,也就完成了对象方法调用。 再看 [NSMethodSignature][1] 一段文档: > Indices begin with 0. The hidden arguments self (of type id) and _cmd (of type SEL) are at indices 0 and 1; method-specific arguments begin at index 2. NSInvocation 第一步设定 Target(0),第二步设定 Selector(1),然后从 index 2 开始依次对参数赋值,因为 0/1 已被 Target/Selector 占用。要注意赋值的时候传的都是 **指针** ,如果赋值参数可能会被释放,要记得 retainArguments。如果需要 NSInvocation 执行后的返回值: ```objc NSString *returnString = nil; //假定返回值类型为 NSString [action getReturnValue:&returnString]; ``` 最后附上 Three20 里用 NSInvocation 实现多参数 performSelector: ```objc https://github.com/facebook/three20/blob/1.0.12/src/Three20Core/Sources/NSObjectAdditions.m#L89 - (id)performSelector:(SEL)selector withObject:(id)p1 withObject:(id)p2 withObject:(id)p3 withObject:(id)p4 withObject:(id)p5 { NSMethodSignature *sig = [self methodSignatureForSelector:selector]; if (sig) { NSInvocation* invo = [NSInvocation invocationWithMethodSignature:sig]; [invo setTarget:self]; [invo setSelector:selector]; [invo setArgument:&p1 atIndex:2]; [invo setArgument:&p2 atIndex:3]; [invo setArgument:&p3 atIndex:4]; [invo setArgument:&p4 atIndex:5]; [invo setArgument:&p5 atIndex:6]; [invo invoke]; if (sig.methodReturnLength) { id anObject; [invo getReturnValue:&anObject]; return anObject; } else { return nil; } } else { return nil; } } ``` [1]:https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSMethodSignature_Class/Reference/Reference.html <file_sep>/_posts/2009-02-17-uninstall-ms-net-framework-assistant.markdown --- layout: post title: "卸载Microsoft .NET Framework Assistant扩展" --- 备份Firefox配置时候发现Microsoft .NET Framework Assistant扩展,自己都不知道啥时候MS给我装上的,Google了一下,可能是自动更新 .NET 3.5 Framework SP1时候装上的,居然一点提示都没有,够流氓,更流氓的是常规卸载Fx扩展的方式居然不能卸载,Addons里面卸载按钮不可用,杀之。以下是Google到的[卸载方法](http://www.dedoimedo.com/computers/ms-dotnet-firefox.html): 1. 备份Fx配置文件,安全第一。然后关掉Fx。 2. 删除 `C:\Windows\Microsoft.NET\Framework\v3.5\Windows Presentation Foundation\DotNetAssistantExtension` 下所有文件,不放心的话可以先备份再删除。 3. Fx地址栏打开 `about:config`,搜索 `general.useragent`,重置 `general.useragent.extra.microsoftdotnet`。 4. 打开注册表编辑器(开始-运行-regedit),定位到 `HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Firefox\extensions`,删除对应项。Done. 最后鄙视一下MS这种强盗流氓做法。 Update:发现还有一个 `Windows Presentation Foundation` 插件,在 `about:config` 里面重置 `microsoft.CLR.clickonce.autolaunch` 即可。 <file_sep>/_posts/2014-02-23-nsoperation.markdown --- layout: post title: "NSOperation 笔记" date: 2014-02-23 20:55 --- iOS 下的多线程编程有 NSOperation 和 Grand Central Dispatch(GCD) 两种,简单记一些 NSOperation 的使用注意。 `NSOperationQueue` 相当于一个操作池,operation 添加进来后会按照 First-In-First-Out(FIFO) 的策略自动执行。operation 一般会添加到应用全局共享的自定义 queue,这样避免阻塞主线程的执行。 一些简单的多线程需求没必要动用 NSOperation 这个大家伙,`NSInvocationOperation` 就很方便: ```objc NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(anyWork) object:nil]; [operationQueue addOperation:op]; - (void)anyWork { //perform any work in operation } ``` NSInvocationOperation 不是很方便共享操作,如果某个操作会在很多地方需要,就可以做个 NSOperation 子类封装: ```objc @implementation CustomOperation - (void)main { //perform any work in operation } @end ``` 这个子类只实现了 `main` 方法,相较 NSInvocationOperation 方便共享。如果需要对操作做更多细致化的功能,比如状态控制,就需要更加复杂的继承实现,参见 [AFURLConnectionOperation][1],这种情况下不继承 `main`,而是继承实现 `start` `cancel`等,然后通过 KVO 手动控制操作状态的切换。 NSOperation 可以设置依赖,A 操作依赖 B 操作完成后才能做,那么就可以设置 B 为 A 的依赖 `[A addDependency:B];`. 如果各个操作之间没有依赖关系,但是又需要在全部操作都完成后做一些善后工作,有两个解决方案,一是添加所有操作为善后操作的依赖,这样所有其他操作完成后善后操作才会执行,这个方法较为死板,或者可以用 KVO 监听队列操作数,等操作都完成后队列操作为空的时候做善后工作: ```objc [operationQueue addObserver:self forKeyPath:@"operationCount" options:0 context:nil]; - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if (object == operationQueue && [keyPath isEqualToString:@"operationCount"]) { if (operationQueue.operationCount == 0) { // any final operation. } } else { [super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; } } ``` #### NSOperation or GCD NSOperation 和 GCD 都能满足多线程需要,那么该选哪个?[When to use NSOperation vs. GCD][2] 的观点: > Always use the highest-level abstraction available to you, and drop down to lower-level abstractions when measurement shows that they are needed. NSOperation 相比 GCD 提供了更多功能,比如操作执行状态,操作执行的暂停、取消,比如操作之间的依赖,比如控制操作队列同一时间可执行操作的数量。 GCD 相比 NSOperation 使用方便,系统开销小性能好。 实际项目中较为简单的小操作直接 GCD,灵活方便;规模较大控制复杂的操作还是通过 NSOperation 为好,也能享用高级 API 提供的方便。 [1]:https://github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/AFURLConnectionOperation.h [2]:http://eschatologist.net/blog/?p=232 <file_sep>/_posts/2008-04-01-feedsky-april-fools-day.markdown --- layout: post title: "Feedsky 愚人节玩笑" --- 刚才上feedsky看看,不看不知道,一看吓一跳!今日订阅数 76250?! 回首页一看,原来feedsky服务器今天维护,不过干嘛在愚人节啊,被愚了。。。 啥时候咱的订阅量真的到这个数啊?:-) <file_sep>/_posts/2010-08-09-weighted-random-choice.markdown --- layout: post title: "Weighted random choice" --- Python 带权重的随机选择。[via](http://code.activestate.com/recipes/117241/) ``` import random def windex(lst): '''an attempt to make a random.choose() function that makes weighted choices accepts a list of tuples with the item and probability as a pair like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] >>> y=windex(x)''' n = random.uniform(0, 1) for item, weight in lst: if n < weight: break n = n - weight return item ``` <file_sep>/_posts/2009-05-12-512-1-year.markdown --- layout: post title: "地震一周年" --- 我们要记住那些逝去的人。我们要记住那场灾难。我们生活也要继续。 <file_sep>/_posts/2013-09-20-magsafe-not-charge.markdown --- layout: post title: "MBP 不能充电解决" date: 2013-09-20 09:28 --- MBP 电源适配器不能充电,各种插拔都无效,真以为要悲剧了,搜到一个办法: > 苹果的电源适配器在电流过大或电压不稳的情况下会自动启用保护机制,切断电流以保护电脑,所以才会充不进电。而解决方法非常简单,只需将 MagSafe 电源适配器拔出电源,静置 60秒以上,就可以重置电源适配器。 简单重置后果然有效,留记。 <file_sep>/_posts/2013-03-27-homeless.markdown --- layout: post title: "离家的孩子" date: 2013-03-27 22:06 --- 2013-03-25: > 从来没有像这次一样讨厌自己离开家。 第一次送妹妹去学校,妹哭的一塌糊涂。在学校门口我使劲压着泪说学习要努力,妹含泪说不哭,加油。可等我送水杯到宿舍的时候,小姑娘再也没忍住,失控的哭声让我完全没法哄她,我只能抱着等她哭到累才停下。可以有很多理由解释为什么要离开家,可在那一刻,所有的借口都很无力。 你还要继续做一个离家的孩子吗? <file_sep>/_posts/2012-09-11-nslinguistictagger-notes.markdown --- layout: post title: "NSLinguisticTagger Notes" date: 2012-09-11 11:52 --- NSLinguisticTagger 是 iOS 5+/OS X 10.7+ 引入的自然语言智能分析类。一个简单的 sample: ``` NSString *text = @"The iPhone is a line of smartphones designed and marketed by Apple Inc. The iPhone runs Apple's iOS mobile operating system, originally named iPhone OS. The first iPhone was unveiled by then CEO of Apple <NAME> on January 9, 2007, and released on June 29, 2007. The most recent iPhone, the 5th generation iPhone 4S, was released in October 2011. iPhone是苹果公司旗下的一个智能手机系列,此系列手机搭载苹果公司研发的iOS手机操作系统。第一代iPhone于2007年1月9日由时任苹果公司CEO的史蒂夫·乔布斯发布,并在6月29日正式发售;最新的iPhone 4s于2011年10月4日发布,并于同年10月14日正式发售。"; // text from Wikipedia. NSArray *schemes = [NSArray arrayWithObject:NSLinguisticTagSchemeNameTypeOrLexicalClass]; NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:schemes options:0]; tagger.string = text; [tagger enumerateTagsInRange:NSMakeRange(0, text.length) scheme:NSLinguisticTagSchemeNameTypeOrLexicalClass options:NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation // 忽略空格和标点 usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) { NSLog(@"%@ is a %@", [text substringWithRange:tokenRange], tag); }]; // OR [text enumerateLinguisticTagsInRange:NSMakeRange(0, text.length) scheme:NSLinguisticTagSchemeNameTypeOrLexicalClass options:NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation orthography:nil usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) { NSLog(@"%@ is a %@", [text substringWithRange:tokenRange], tag); }]; ``` 结果输出: ``` 2012-09-11 11:56:45.192 LinguisticTaggerSample[3342:c07] The is a Determiner 2012-09-11 11:56:45.193 LinguisticTaggerSample[3342:c07] iPhone is a Noun 2012-09-11 11:56:45.193 LinguisticTaggerSample[3342:c07] is is a Verb 2012-09-11 11:56:45.193 LinguisticTaggerSample[3342:c07] a is a Determiner 2012-09-11 11:56:45.194 LinguisticTaggerSample[3342:c07] line is a Noun 2012-09-11 11:56:45.194 LinguisticTaggerSample[3342:c07] of is a Preposition 2012-09-11 11:56:45.194 LinguisticTaggerSample[3342:c07] smartphones is a Adverb 2012-09-11 11:56:45.194 LinguisticTaggerSample[3342:c07] designed is a Verb 2012-09-11 11:56:45.195 LinguisticTaggerSample[3342:c07] and is a Conjunction 2012-09-11 11:56:45.195 LinguisticTaggerSample[3342:c07] marketed is a Verb 2012-09-11 11:56:45.195 LinguisticTaggerSample[3342:c07] by is a Preposition 2012-09-11 11:56:45.196 LinguisticTaggerSample[3342:c07] Apple is a OrganizationName 2012-09-11 11:56:45.196 LinguisticTaggerSample[3342:c07] Inc is a OrganizationName ... 2012-09-11 11:56:45.203 LinguisticTaggerSample[3342:c07] Steve is a PersonalName 2012-09-11 11:56:45.203 LinguisticTaggerSample[3342:c07] Jobs is a PersonalName ... 2012-09-11 11:56:45.222 LinguisticTaggerSample[3342:c07] iPhone is a Noun 2012-09-11 11:56:45.223 LinguisticTaggerSample[3342:c07] 是 is a Particle 2012-09-11 11:56:45.223 LinguisticTaggerSample[3342:c07] 苹果 is a Verb 2012-09-11 11:56:45.223 LinguisticTaggerSample[3342:c07] 公司 is a Particle 2012-09-11 11:56:45.224 LinguisticTaggerSample[3342:c07] 旗下 is a Verb 2012-09-11 11:56:45.224 LinguisticTaggerSample[3342:c07] 的 is a Particle 2012-09-11 11:56:45.224 LinguisticTaggerSample[3342:c07] 一 is a Verb 2012-09-11 11:56:45.288 LinguisticTaggerSample[3342:c07] 个 is a Particle 2012-09-11 11:56:45.288 LinguisticTaggerSample[3342:c07] 智能 is a Verb 2012-09-11 11:56:45.289 LinguisticTaggerSample[3342:c07] 手机 is a Particle 2012-09-11 11:56:45.289 LinguisticTaggerSample[3342:c07] 系列 is a Verb ... 2012-09-11 11:56:45.310 LinguisticTaggerSample[3342:c07] 史 is a Verb 2012-09-11 11:56:45.311 LinguisticTaggerSample[3342:c07] 蒂 is a Particle 2012-09-11 11:56:45.311 LinguisticTaggerSample[3342:c07] 夫 is a Verb 2012-09-11 11:56:45.311 LinguisticTaggerSample[3342:c07] 乔 is a Particle 2012-09-11 11:56:45.312 LinguisticTaggerSample[3342:c07] 布 is a Verb 2012-09-11 11:56:45.312 LinguisticTaggerSample[3342:c07] 斯 is a Particle ``` 对英文的分析要好于中文。不同的 scheme 有不同的返回结果,包括文本语言等。详细文档 [NSLinguisticTagger Class Reference][1]. PS:可以用这个做一个微博关键词分析,罗列出自己微博最多的关键词。 [1]:https://developer.apple.com/library/ios/#DOCUMENTATION/Cocoa/Reference/NSLinguisticTagger_Class/Reference/Reference.html <file_sep>/_posts/2011-11-30-picky-to-octopress.markdown --- layout: post title: "Picky to Octopress" date: 2011-11-30 15:13 --- **不敢保证转换过程万无一失,请注意备份** 前提条件:之前大多数文章已经是用 Markdown 格式。 1. 仿照 AtomFeedHandler 新增 RSSOutHandler ```python class RSSOutHandler(webapp.RequestHandler): def get(self): site_domain = Datum.get('site_domain') site_name = Datum.get('site_name') site_author = Datum.get('site_author') site_slogan = Datum.get('site_slogan') site_analytics = Datum.get('site_analytics') site_updated = Datum.get('site_updated') if site_updated is None: site_updated = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) feed_url = Datum.get('feed_url') if feed_url is None: feed_url = '/index.xml' else: if len(feed_url) == 0: feed_url = '/index.xml' template_values = { 'site_domain' : site_domain, 'site_name' : site_name, 'site_author' : site_author, 'site_slogan' : site_slogan, 'feed_url' : feed_url } articles = db.GqlQuery("SELECT * FROM Article WHERE is_page = FALSE ORDER BY created DESC") template_values['articles'] = articles template_values['articles_total'] = articles.count() template_values['site_updated'] = site_updated path = os.path.join(os.path.dirname(__file__), 'tpl', 'shared', 'out.xml') output = template.render(path, template_values) self.response.headers['Content-type'] = 'text/xml; charset=UTF-8' self.response.out.write(output) ``` 2. 在 `main.py - main()` 添加 ``` ('/out.xml', RSSOutHandler), ``` 3. 仿照 `index.xml` 添加 `out.xml` 模版 4. 参考 [Import XML of Wordpress to Octopress][1] 造一个 Picky2Octopress ```ruby # -*- coding: utf-8 -*- require 'fileutils' require 'date' require 'yaml' require 'uri' require 'rexml/document' include REXML doc = Document.new File.new(ARGV[0]) FileUtils.mkdir_p "_posts" doc.elements.each("feed/entry") do |e| post = e.elements slug = post['slug'].text date = DateTime.parse(post['published'].text) name = "%02d-%02d-%02d-%s.markdown" % [date.year, date.month, date.day, slug] content = post['content'].text puts content content = content.gsub(/<code>(.*?)<\/code>/, '`\1`') ## 追加 content = content.gsub(/<pre lang="([^"]*)">(.*?)<\/pre>/m, '<div class="bogus-wrapper"><notextile><figure class="code"><figcaption><span>lang:\1 </span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class="line-number">1</span></pre></td><td class="code"><pre><code class=''><span class="line">\2</span></code></pre></td></tr></table></div></figure></notextile></div>') (1..3).each do |i| content = content.gsub(/<h#{i}>([^<]*)<\/h#{i}>/, ('#'*i) + ' \1') end File.open("_posts/#{name}", "w") do |f| f.puts "---" #f.puts data f.puts "layout: post" f.puts "comment: true" f.puts "title: \"#{post['title'].text}\"" f.puts "---" f.puts content end end ``` 如果内容较少 (<100),可以直接手动修改 index.xml 格式然后进行转换。 **最后,不敢保证转换过程万无一失,请注意备份**。 [1]: https://gist.github.com/1366971 <file_sep>/_posts/2008-04-20-my-rockets.markdown --- layout: post title: "OH,My Rockets!" --- 火箭输了,季后赛第一场,82-93输给了爵士。输得很彻底,从一开始就处于下风,一直被人压着打,一点都没有顺畅的进攻。 别老说是没有姚明输得球,奥库+布泽尔+AK47拿了45分+28个板,火箭这边,大叔+巴蒂尔+斯科拉进账38分+25个板,差距并不大,也就说内线并不是很吃亏,要知道大叔还有3个火锅呢。输就输在糟糕的命中率,三分扔了22个才进了6个,我的个乖啊,爵士扔了10个都进了5个呢。又没有助攻,没有顺畅的配合跑动光站在那烂投怎么能赢啊,赢个球啊! 赶紧的跑起来吧,拉夫赶紧的回来吧,虽然你斗不过威廉姆斯那个小胖子,至少比老杰克逊能跑动传球组织进攻的。还是有机会的,要知道去年斗爵士还不是领先了被人翻掉,谁说爵士领先就不会被咱给翻掉?!Go,Rockets! <file_sep>/_posts/2009-09-24-my-twitter-tools.markdown --- layout: post title: "我的 Twitter 工具集" --- 话说我开始用 Twitter 的时间也不晚,在07年就注册了帐号,但是一直没怎么用;从去年下半年开始上的频率多了,不过还属于潜水艇,多数时间只看不说,主要拿来获取信息;今年开始用的多了,虽然不及那些 Twitter 狂人们一天上百推的疯狂,每天也有十条左右的个人碎念(这里怀念一下叽歪,之前我一直是用叽歪的同步 Twitter 功能的,尤其是短信发叽歪然后同步 Twitter)。罗列总结一下我现在用的 Twitter 周边工具,做个备忘。 Tweete/Twitzap。一直在寻找一个好用的 Twitter 客户端软件,AIR 类的Twhirl、TweetDeck Spaz等等,都有给我惊喜,却也多多少少有一些不满意的地方,内存占用,响应速度,消息提醒等等;Echofon(Twitterfox) 这个 Firefox 插件用过一段,不过过于拖累 Fx 速度;最后还是选用网页客户端。目前主用的是 Tweete,电脑和手机上都是用这个,简洁但十分强大。电脑上把 Tweete 挂在 Fx 侧边栏,可以少开一个程序;关掉 Avatars,配上页面自动刷新,要的就是一个速度;还有一个好处就是减少自动消息弹出,减少信息干扰。Twitzap 作为前主力,最棒的就是搜索聚合功能,但是速度过慢,原生态的自动刷新还有时间限制,现在退居二线作为替补,聚合一些关键字每天看几次,也挺好。 TwiTalker。喜欢用 Gtalk 来更新 Twitter,主要是 Gtalk 可以保存聊天记录到 Gmail 里,这样相当于一个 Twitter 备份,Twitter 现在的稳定性真不怎么地,宕机不说,还时有丢推发生;用 Gtalk 发推还有一个好处就是可以使用 Gmail 里 Google 强大的搜索功能搜索自己以前的推,Twitter 官方的搜索功能真菜。TwiTalker 作为一个第三方 Twitter-Gtalk 工具功能相当强大,发推是自然的,还可以接受推,包括私信、DM,还可以查看别人是否关注你。 TwitterFeed,主要是将 Blog 自动发推到 Twitter。之前使用 FriendFeed 聚合发推,不过 FriendFeed 倒下后它的短连接 http://ff.im/-**** 打不开,很不方便,TwitterFeed 替代之。 Reader2Twitter,Google Reader 分享实时发推,还变相通过 Reader Notes 实现 GReader 发推,强大。 Twitter 是开放的,各种各样的发推工具让你想怎么玩就怎么玩。我的 Twitter [@fannheyward](https://twitter.com/fannheyward). <file_sep>/_posts/2009-03-04-internship-first-stop.markdown --- layout: post title: "实习第一站" --- 上午实习参观可口可乐,是毕业实习的第一站。流水帐了一下上午的行程。 1. 8点钟爬起来,说实话有点困难,不过能吃早饭还是很爽的。9点半,班车出发。 2. 可口可乐在开发区那边,偏郊区,饶了好久才到,一位美女接待,:) 3. 美女接待讲解太古可口可乐公司的一些东西,其中说到可口可乐的发明,糖浆里误加了苏打水,说了句很有哲理的话:"错误发生在正确的人身上摩擦出漂亮的火花。" 4. 很多可口可乐的限量版纪念装,96年 NBA 促销版,94年世界杯促销版。 5. 一位技工给我们讲解可乐灌装流程,隔着玻璃看了看。 6. 在会议室看了一些可口可乐早期的广告,上世纪五、六十年代的。 7. 11点多的时候开始回校,每人一罐可乐,囧。 这样的实习参观也就走走看看,还不如到车间干几天呢。。再说了,这个计算机有啥关系?我愣是没看明白。可恶的是,还得写实习报告! <file_sep>/_posts/2011-10-09-rip-stevejobs.markdown --- layout: post title: "R.I.P. <NAME>" --- Thank you, Jobs. <file_sep>/_posts/2019-04-11-druid-query-in-json.markdown --- layout: post title: Druid Query in JSON date: 2019-04-11 17:30:08 +0800 --- Druid 可以在 Superset SQL 查询,除此之外可以通过 HTTP+JSON 查询: ```sh curl -X POST '<host:<port>/druid/v2/?pretty' -H 'Content-Type:application/json' -H 'Accept:application/json' -d @query.json ``` ```json { "queryType": "timeseries", "dataSource": "cpm_log", "granularity": "hour", "aggregations": [ { "type": "longSum", "name": "requests", "fieldName": "req_count_raw" }, { "type": "longSum", "name": "impressions", "fieldName": "win_count" }, { "type": "floatSum", "name": "revenues", "fieldName": "win_price" } ], "postAggregations": [ { "type":"arithmetic", "name": "ecpm", "fn": "/", "fields": [ { "type": "fieldAccess", "name": "postAgg_rev", "fieldName": "revenues" }, { "type": "fieldAccess", "name": "postAgg_imps", "fieldName": "impressions" } ] } ], "filter": { "type": "and", "fields": [ { "type": "selector", "dimension": "device_os", "value": "android" }, { "type": "in", "dimension": "req_ad_type", "values": ["banner"] } ] }, "context": { "grandTotal": true }, "intervals": [ "2019-04-09T00:00:00+08:00/2019-04-09T23:00:00+08:00" ] } ``` 1. queryType 有 `timeseries`, `topN`, `groupBy`, `search`, `timeBoundary` 等 1. 尽量少用 groupBy 查询,效率不高 1. topN 查询是通过 `metric` 来排序 1. `context` 可以指定 `queryId`,这样可以通过 `DELETE /druid/v2/{queryId}` 取消查询 1. 去重: `{"type": "cardinality", "name": "distinct_pid", "fields": ["ad_pid"]}` [RTFM](http://druid.io/docs/latest/querying/querying.html), [godruid](https://godoc.org/github.com/fannheyward/godruid)<file_sep>/_posts/2013-09-16-statusbar-in-ios-7.markdown --- layout: post title: "StatusBar in iOS 7" date: 2013-09-16 21:44 --- iOS 7 下状态栏默认是白底黑字,如果应用是黑色背景整个状态栏就啥也看不见。解决办法: 1. plist 设置 `UIViewControllerBasedStatusBarAppearance` NO. 1. `[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];` <file_sep>/_posts/2010-06-27-long-way-to-go.markdown --- layout: post title: "还有很长的路要走" --- 自己现在的技术掌握太糙了。 整体上,难以把握整体结构设计,各个模块功能设计,各模块间通信传输等等。 细节上,Python 如此简洁优美的语法让我写的是惨不忍睹,Python 自带的模块、函数还很不熟悉。 我才刚刚上路。 <file_sep>/Rakefile task :default => [:clean, :build] desc 'Make a new post' task :post do print 'Enter post title: ' title = STDIN.gets.chomp abort 'No title.' unless title.length > 0 filename = "_posts/#{Time.new.strftime('%Y-%m-%d')}-#{title.downcase.gsub(' ', '-')}.markdown" abort "Error: #{filename} already exists." if File.exist?(filename) puts "Creating new post: #{filename}" open(filename, 'w') do |post| post.puts "---" post.puts "layout: post" post.puts "title: #{title}" post.puts "date: #{Time.new.to_s}" post.puts "---" post.puts "" end sh "open #{filename}" end desc 'Clean cache' task :clean do sh 'jekyll clean' end desc 'Build site with Jekyll' task :build do sh 'jekyll build' end desc 'Preview in browser' task :preview do sh 'open http://127.0.0.1:4001' end desc "List tasks" task :list do puts "Tasks: #{(Rake::Task.tasks - [Rake::Task[:list]]).join(', ')}" end <file_sep>/_posts/2023-07-26-how-to-know-im-using-venv-python.markdown --- layout: post title: How to know I'm using venv Python date: 2023-07-26 10:27:21 +0800 --- - Solution 1: use `sys.prefix` that points to the Python directory - Solution 2 (the better way): `VIRTUAL_ENV` environment variable. When a virtual environment is activated, this is set to the venv’s directory, otherwise it's None. ```python import os print(os.environ.get('VIRTUAL_ENV')) ``` <file_sep>/_posts/2012-10-22-autorotation-changes-in-ios-6.markdown --- layout: post title: "iOS 6 下自动旋转的变化" date: 2012-10-22 22:12 --- iOS 6 SDK 中的屏幕自动旋转有了一些变化,简单纪录之。举例:Master-Detail 类型 App,master ViewController 不支持屏幕旋转, detail ViewController 支持屏幕旋转。 在 Info.plist 或 Target-Summary 启用自动旋转,选中需要的 Supported Interface Orientations。新建 UINavigationController+Autorotation.h category,根据需要禁用最底层 NavController 的自动旋转: ``` - (BOOL)shouldAutorotate { return NO; } ``` 在 AppDelegate 设置 `window.rootViewController = navController;`,由于 `shouldAutorotateToInterfaceOrientation:` 从 iOS 6 起 deprecated,在需要自动旋转的 viewController 改用 `supportedInterfaceOrientations`+`preferredInterfaceOrientationForPresentation`。 ``` - (BOOL)shouldAutorotate { return YES; } - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAllButUpsideDown; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return UIInterfaceOrientationLandscapeRight; } ``` 几个需要注意的地方: 1. window 需要设置 rootViewController,`[window addSubview:navController.view];` 无效; 2. `shouldAutorotate` 在最底层设置才有效; 3. `presentModalViewController` 下用之前的自动旋转控制无效,须用 category 解决。 <file_sep>/_posts/2008-04-14-sql-study-select-2.markdown --- layout: post title: "SQL学习--连接查询" --- 等值与非等值连接查询 `select Student.*, SC.* from Student, SC where Student.Sno=SC.Sno;` 外连接 ``` select Student.sno,sname,ssex,sage,sdept,cno,grade from Student LEFT JOIN SC ON (Student.sno = SC.sno); ``` 自身连接 ``` select FIRST.cno,SECOND.cpno from Course FIRST,Course SECOND where FIRST.Cpno = SECOND.Cno; ``` 复合条件连接 ``` select Student.Sno,Sname,Grade from Student,SC where Student.Sno = SC.Sno AND SC.Cno ='1' AND SC.Grade > 80; select Student.Sno,Sname,Cname,Grade from Student,SC,Course where Student.Sno = SC.Sno AND SC.Cno = Course.Cno; ``` <file_sep>/_posts/2010-08-02-happy-in-life.markdown --- layout: post title: "Happy in life" --- 及时行善,能帮别人的时候就伸手帮一把,对你来说是举手之劳,对别人就是暖心之举。 及时行乐,善待自己,不必要那么累。 <file_sep>/_posts/2010-04-09-delphi-adoquery-select-insert-delete-update.markdown --- layout: post title: "Delphi ADOQuery查询、插入、删除、修改" --- //查询记录 ``` with ADOQuery do begin Close; SQL.Clear; SQL.Add('Select * From Table'); Open; end; ``` //插入记录 ``` with ADOQuery do begin Close; SQL.Clear; SQL.Add('Insert Into Table(val1,val2) values(:val1,:val2)'); Parameters.ParamByName('val1').Value := Trim(Edit1.Text); Parameters.ParamByName('val2').Value := Trim(Edit2.Text); ExecSQL; end; ``` //删除记录 ``` with ADOQuery do begin Close; SQL.Clear; SQL.Add('Delete from TABLE where val1=:val1'); // =: 前后都不可有空格; Parameters.ParamByName('val1').Value := Trim(Edit1.Text); ExecSQL; end; ``` //修改记录 ``` with ADOQuery do begin Close; SQL.Clear; SQL.Add('Update TABLE Set Key=:val1'); Parameters.ParamByName('val1').Value := Trim(Edit1.Text); ExecSQL; end; ``` Open 有记录集返回,ExecSQL 没有记录集返回;Select 常用 Open,Delete/Insert/Update 常用 ExecSQL。 <file_sep>/_posts/2013-11-20-angularjs-notes.markdown --- layout: post title: "Angular.js 学习笔记" date: 2013-11-20 21:08 --- > When in Rome, do as the Romans do. 最近用 [Angular][0] “完整”做了一个服务的管理后台,完整的意思是整个 WebApp 都用 Angular [MVW][16] (Model-View-Whatever) 的思路去想去做。留一个 Angular 学习笔记。 #### Think in Angular Angular 是个 **框架(Framework)**,不像 jQuery、Underscore.js 是个库(Library),库的使用一般是在某个地方调用库所提供的方法完成想要的功能,而框架往往是控制应用整个 runtime 周期。所以 Angular 相对正确的使用方式是从应用全局开始,都用 Angular 提供的双向绑定、DI、Directive、Services 等,把应用数据逻辑层和页面 DOM 操作分离。用 Angular 首先就要认同接受并实践这种思路,`Think in Angular`。 不错的 Angular 学习资料: 1. 官方文档 [AngularJS API Docs][1]。 1. [angular-phonecat][2],官方提供的入门教程,非常好的 `Think in Angular` 实践,建议把代码 clone 本地完整学习一遍。 1. [Angular FAQ][3]. 1. [AngularUI][4],官方(?) UI 库,很多 directive 可用,比如 `ui.bootstrap`, `ui.router`, `ui.grid`. 1. [AngularJS Fundamentals In 60-ish Minutes][5] 视频教程,官方 [Youtube 频道][6] 也有不少东西,不过看视频效率较低。 1. [AngularJS-Learning][7],收集了非常多文章,涵盖各个方面,实用参考。 1. [egghead.io][8] Angular 视频教学。 1. [A Better Way to Learn AngularJS][9]. ---- #### jQuery [How do I “think in AngularJS” if I have a jQuery background?][10] 很详细的介绍了如果有 jQuery 开发背景在做 Angular 需要注意的地方,以下几点: 1. 忘掉 jQuery,用 Angular 的方式解决。 1. 知名的 jQuery plugin 一般都已经有 Angular directive 封装,首先尝试这些,真不能满足的话再用 jQuery 方式解决。 1. 不要直接操作 DOM,试试 directive: ng-model, ng-class, ng-show, ng-hide, ng-disabled, ng-click. ---- #### Services 把常用的数据层访问封装成 Services 在 controller 之间共享访问。`$resource` 构造服务时要注意返回内容必须为单个对象或对象数组,如果服务端返回格式不符合可以用 `$http` 构造 service: ```js //make angular service with $http. angular.module('APP.services', []).factory('AppsList', function($http){ var AppsList = { list: function(){ var promise = $http.get('/url').then(function(resp){ return resp.data; }); return promise; //or //return $http.get('/url'); //because $http returns a promise. }, }; return AppsList; }); //use function AppCtrl(AppsList) { AppsList.list().then(function(data){ console.log(data); }); } ``` #### $rootScope 通过 `$rootScope` 可以在所有 controller 之间共享方法: ```js angular.module('APP', []).run(function($rootScope){ $rootScope.format_appinfo = function(data){ //... }; }); //use in controller with $scope. function AppCtrl($scope) { $scope.format_appinfo(); } ``` #### $routeParams 可以通过 `$routeParams` 获取 url 指定参数,比如 ```js // route 设置 url 格式 $routeProvider.when('/app/:appid/:title', {controller:'AppCtrl'}); //use function AppCtrl($routeParams) { var appid = $routeParams.appid; var title = $routeParams.title; } ``` #### Filter Angular 自带了很多 filters,比如 currency,date,json,lowercase/uppercase,其中 json 可以直接在页面上格式化展示对象信息,很方便检查调试: ``` <pre> {.{ app | json }.} // Octopress/Jekyll 会把两个大括号格式化掉,所以中间加一点 </pre> ``` ---- 代码目录组织形式,参考 [angular-seed][11]。也可以用 Yeoman 进行管理。 ``` ├──css │  └──app.css ├──img ├──index.html ├──js │  ├──app.js //配置用到的所有 module,包括自定义。 │  ├──controllers //每个 controller 独立一个文件,以 Ctrl 结尾命名。 │  │  ├──app_info_ctrl.js │  │  └──... │  ├──directives.js │  ├──filters.js │  └──services.js ├──lib //CDN 没有的第三方库。 │  ├──ngProgress └──partials //页面模版,文件名和 controller 相对应。 ├──app_info.html └──... ``` ---- 更多参考: 1. [ng-newsletter][15] 每周 Angular 最新技术周报,内容相当好。 1. [8 Tips for Angular.js Beginners][12] 1. [Migration guide for jQuery Developers][13] 1. [Building Huuuuuge Apps with AngularJS][14] [0]:http://angularjs.org/ [1]:http://docs.angularjs.org/api/ [2]:https://github.com/angular/angular-phonecat [3]:https://github.com/angular/angular.js/wiki/FAQ [4]:http://angular-ui.github.io/ [5]:http://www.youtube.com/watch?v=i9MHigUZKEM [6]:http://www.youtube.com/user/angularjs [7]:https://github.com/jmcunningham/AngularJS-Learning [8]:http://egghead.io/ [9]:http://www.thinkster.io/pick/51d287681e4b9c9098000013/a-better-way-to-learn-angularjs [10]:http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background [11]:https://github.com/angular/angular-seed [12]:http://vxtindia.com/blog/8-tips-for-angular-js-beginners/ [13]:http://amitgharat.wordpress.com/2013/06/22/migration-guide-for-jquery-developers/ [14]:http://briantford.com/blog/huuuuuge-angular-apps.html [15]:http://www.ng-newsletter.com/ [16]:https://plus.google.com/+AngularJS/posts/aZNVhj355G2 <file_sep>/_posts/2008-05-15-token-of-regard.markdown --- layout: post title: "尽点心意" --- 没多少,一点点心意,这个时候希望能做点什么吧。[支付宝“壹基金”](http://www.taobao.com/onefound/1jijin.php) ![](https://lh3.googleusercontent.com/-_TgqtTJhmAs/U-t-Hj8TJ9I/AAAAAAAAGbk/ENO2cjl4lnc/w582-h396-no/4.jpg) <file_sep>/_posts/2010-06-21-simple-httpserver-in-python.markdown --- layout: post title: "Simple HTTP Server in Python" --- Python has an embedded HTTP server that can serve the current directory from a given port. > python -m SimpleHTTPServer 8000 <file_sep>/_posts/2009-03-02-vimperator-tips.markdown --- layout: post title: "Vimperator使用小记" --- 小记一些 Vimperator 快捷键: 1. **esc**,当快捷键无效时候大部分是因为切换到了命令模式,esc返回正常模式; 2. **tab**,善用tab补全; 3. **o/t**,当前/新标签打开页面; 4. **Shift+h/l**,后退/前进,一般来说后退用的比较多; 5. **u**,undo,撤销关闭的标签; 6. **d**,关闭当前页面; 7. **r/R**,刷新/强制刷新当前页面; 8. **/**,当前页面查找,回车后n标记下一个关键字,N标记上一个关键字; 9. **y/Y**,复制当前标签页url/复制选中的文字; 10. **gg/G**,跳转到页面顶端/底端; 11. **p/P**,粘帖并打开当前剪贴板里的url地址,小写当前标签打开,大写新标签打开; 12. **gf**,查看页面源代码; 13. **f**,进入QuickHint modo,用的不多; 14. **:pref**, 打开Fx opinion对话框; 15. **:addons**,扩展列表,同样可以tab补全; 16. **:restart**,重启Fx; 来一张 vimperator 的快捷键列表,基本上常用的都有了。 ![](http://lh4.ggpht.com/_vYr4JQreqXA/SauAFex3XyI/AAAAAAAAAvk/zMUENFZlZ5U/s600/vimperator.jpg) vimperator 同样有类似 vim 的配置文件,`_vimperatorrc`,保存到当前系统用户目录下即可,vista 是 C:\Users\Heyward。 我的 `_vimperatorrc`: ``` "默认显示菜单栏,工具栏,书签栏;隐藏任务栏; :set guioptions=b "解决vimperator与Google reader跟gmail快捷键冲突,自动PASS THROUGH状态 autocmd LocationChange .* :js modes.passAllKeys = /mail.google.com/.test(buffer.URL) || /google.com\/reader\//.test(buffer.URL) :imap <C-v> <S-Ins> "粘帖键映射 ``` vimperator 看似很复杂,不过上手后就发现会有多么高效,推荐 Fx 必备扩展。 <file_sep>/_posts/2009-11-12-vimperator-config-091111.markdown --- layout: post title: "Vimperator个人配置(091111)" --- ``` "2009-11-11 "默认显示菜单栏,工具栏,书签栏;隐藏任务栏; :set guioptions=nB "键盘映射 map <S-Up> :set go=m<CR> map <S-Down> :set go=<CR> map <S-Left> :set go=T<CR> map <S-Right> :set go=B<CR> map <S-Home> :set go=mTB<CR> "映射快捷键 map <S-F1> :tabopen https://mail.google.com/mail/#compose<ENTER> noremap j <C-f> noremap k <C-b> noremap h gT "自动PASS THROUGH状态 autocmd LocationChange . :js modes.passAllKeys = /mail.google.com/.test(buffer.URL) || /google.com\/reader\//.test(buffer.URL) || /docs.google.com/.test(buffer.URL) || /wave.google.com/.test(buffer.URL) :imap <C-v> <S-Ins> "自动翻页,[[和]]快捷键 :set nextpattern=\s下一页|下一张|下一篇|下页|后一页|后页\s,^\bnext\b,\bnext\b,\older\b,^>$,^(>>|»)$,^(>|»),(>|»)$,\bmore\b :set previouspattern=\s上一页|上一张|上一篇|上页|前一页|前页\s*,^\bprev|previous\b,\bprev|previous\b,\newer\b^<$,^(<<|«)$,^(<|«),(<|«)$ "智能地址栏 :set complete=sl ``` <file_sep>/_posts/2015-04-30-monthly-review-1504.markdown --- layout: post title: Monthly Review 2015-04 date: 2015-05-04 10:20:01 +0800 --- 1. 维护开发外,一个小功能模块尝试用网页代替 native 实现。在体验可接受的前提下开发效率确实比原生要好,而且现在前端开发框架+辅助工具井喷,可以多做尝试。 1. 前端水平 JS 刚刚够用,还不时需要 Dash 查文档,ES6 什么的不懂,CSS 是硬伤。 1. 又十个 iOS 面试,不行,我得多写几句: * 遇到硬件网络转型互联网开发,似乎硬件现在日子不太好过? * “用大众点评 API 实现了一个美团应用”,似乎是一个培训机构的题目? * 现在的移动开发过火,整个行情都被抬高。基础一般,又看不到学习能力,没办法上手项目的开口就是 15K+,这钱真好赚。 * 做产品开发首先是产品的热爱,基础差没问题,展示出学习能力,很多时候公司更愿意内部培训。 1. 感兴趣的东西过多,同时并行的效果不好,需要有计划的去学习。 1. 这次回去六六对爸爸的依赖更多了,基本上自己一个人带一天都没问题。 1. 牛牛:哞…… 六六:eng…… <file_sep>/_posts/2010-07-08-happy-birthday-to-mum-and-little-sister.markdown --- layout: post title: "妈,生日快乐;妹,生日快乐" --- 太失败了,居然忘掉了妈和妹妹的生日,忘的一干二净,过了十天才想起来。 早上给家里打电话,爸说忘了就忘了呗,泪水一下子出来。 妈,生日快乐,身体健康! 妹,生日快乐,开开心心每一天! 想家了,想你们了。 <file_sep>/_posts/2009-05-21-shuimunianhua-qicheng.markdown --- layout: post title: "启程-水木年华" --- 今天发现的一首好歌,水木年华的《启程》,一首很适合毕业心情的一首歌,越听越有感觉。把这首歌送给一个月后就毕业的自己,那帮子兄弟,同宿舍的,同班的朋友们。 ``` 就在启程的时刻 让我为你唱首歌 孤独时候要记得想起我 等到相遇的时刻 我们再唱这首歌 就像我们从未曾离别过 不管怎样的时刻 请你记住这首歌 记住我们的坚持从未变过 未来怎样的时刻 请你记住这首歌 记住我们的梦想从未变过 记住我们的梦想从未变过 记住我们的梦想从未变过 ``` <file_sep>/_posts/2017-04-26-golang-sync.waitgroup.markdown --- layout: post title: Golang sync.WaitGroup date: 2017-04-26 22:21:52 +0800 --- `sync.WaitGroup` waits for a collection of goroutines to finish. 类似一个计数器,添加任务加一,完成任务减一,非零即阻塞。 - Add(x) 添加到计数器,需要注意的是必须在 main goroutine 执行 - Done() 计数器减一 - Wait() 阻塞 main goroutine 执行,直到所有 goroutine 执行完成。 ```go var wg sync.WaitGroup var urls = []string{ "http://www.google.com/", "http://fann.im/", } var errChan = make(chan error, len(urls)) for _, url := range urls { wg.Add(1) go func(url string) { defer wg.Done() resp, err := http.Get(url) if err != nil { errChan <- err } defer resp.Body.Close() }(url) } wg.Wait() close(errChan) for err := range errChan { if err != nil { log.Println(err.Error()) } } ``` [errgroup](https://pkg.go.dev/golang.org/x/sync/errgroup?tab=doc) 提供了类似的功能: ```go var g errgroup.Group var urls = []string{ "http://www.golang.org/", "http://www.google.com/", } for _, url := range urls { // Launch a goroutine to fetch the URL. url := url // https://golang.org/doc/faq#closures_and_goroutines g.Go(func() error { // Fetch the URL. resp, err := http.Get(url) if err == nil { resp.Body.Close() } return err }) } // Wait for all HTTP fetches to complete. if err := g.Wait(); err == nil { fmt.Println("Successfully fetched all URLs.") } ``` <file_sep>/_posts/2012-06-06-resignfirstresponder-doesnot-work-on-ipad.markdown --- layout: post title: "resignFirstResponder doesn't work on iPad" date: 2012-06-06 16:44 --- 在 iPad 上,用 `modalPresentationStyle = UIModalPresentationFormSheet` 方式推出一个 viewController,这时这个 viewController 不会响应 `resignFirstResponder`,其他样式的 modalPresentationStyle 没有问题。苹果一个开发在开发者论坛说这是个 feature,不是 bug,[devforums.apple.com][1] > Was your view by any chance presented with the UIModalPresentationFormSheet style? To avoid frequent in-and-out animations, the keyboard will sometimes remain on-screen even when there is no first responder. This is not a bug. 就算不是 bug 也很恼人,有人给出了解决方法 [devforums.apple.com][2]。新建一个 UINavigationController category,禁掉 `disablesAutomaticKeyboardDismissal`: ```objc - (BOOL)disablesAutomaticKeyboardDismissal { return NO; } ``` 然后把 viewController 挂在 UINavigationController 下即可: ```objc MyViewController *myViewController = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil]; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:myViewController]; theNavigationController.modalPresentationStyle = UIModalPresentationFormSheet; [self presentModalViewController:theNavigationController animated:YES]; ``` SO 参考: - [resignFirstResponder Don't work?][3] - [iPad keyboard will not dismiss if modal view controller presentation style is UIModalPresentationFormSheet][4] [1]:https://devforums.apple.com/message/166801#166801 [2]:https://devforums.apple.com/message/425914#425914 [3]:http://stackoverflow.com/a/6854165/380774 [4]:http://stackoverflow.com/a/3386768/380774 <file_sep>/_posts/2014-01-12-ios-static-library.markdown --- layout: post title: "Make an iOS Static Library" date: 2014-01-12 21:55 --- 做一个 iOS 静态库需要注意的东西: 1. namespace 冲突。静态库用了某第三方库,项目也用了同样的第三方库,在编译的时候就会有 `duplicate symbol` 错误,因为有两份同样的第三方库。解决办法就是把用到的第三方库加上自定义前缀,包括类名、delegate 协议、常量名,尤其需要注意 Category 的方法名要修改。 1. 封装静态库的时候应尽量避免引入重量级第三方库,多自己进行封装。 1. 一个静态库要有自己独有的前缀,所有类名、常量等都要加同样的前缀。 1. 真机+模拟器支持。Xcode 默认只会用当前环境(真机或模拟器)生成静态库,这样的 SDK 不方便其他项目开发时调试。解决办法就是通过脚本生成一份通用库,[build_universal_library.sh][1],via [SO][2]. 1. 文档。静态库的方便是使用者直接拿你提供的方法来用,无需关注具体实现;不方便在于看不到实现,出现问题无法排查,因此需要把 SDK 的版本、更新历史、使用、FAQ 等写成文档,方便使用,也显得 SDK 比较正式规范。 1. 图片等资源文件用 bundle 方式打包。一个简单制作 bundle 的方法:新建文件夹,重命名为 `YourSDK.bundle`,然后 `Show Package Contents` 打开,加入图片。使用图片的时候需要指明 bundle: `[UIImage imageNamed:@"YourSDK.bundle/img.png"]`。也可以用 Target 方式制作 bundle,比如 [iOS Library With Resources][3]. 1. 修改 SDK product path,主要是方便打包,参见 [build_universal_library.sh][1]. 1. SDK 头文件加上版本号和简单的使用注释,开发者不太喜欢长篇大论的文档 :D. 1. 如果 SDK 有用到 Category,注意项目设置 `Other Linker Flags` 添加 `-ObjC`,[QA1490][4]. 1. 开发时可以把 SDK 用子项目形式加到 SDKDemo 项目下,这样可以边开发边测试。SDKDemo 修改 `User Header Search Paths` 为 `${SYMROOT}/${CONFIGURATION}-universal/YourSDK`,路径和 [build_universal_library.sh][1] 保持一致。 [1]:https://gist.github.com/fannheyward/4063755 [2]:http://stackoverflow.com/questions/3520977/build-fat-static-library-device-simulator-using-xcode-and-sdk-4 [3]:http://www.galloway.me.uk/tutorials/ios-library-with-resources/ [4]:https://developer.apple.com/library/mac/qa/qa1490/_index.html <file_sep>/_posts/2021-05-27-write-like-an-amazonian.markdown --- layout: post title: Write Like an Amazonian date: 2021-05-27 18:23:46 +0800 --- ![Write Like an Amazonian](https://cdn.substack.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2Feceefbce-60d5-46f3-be8d-d92bc217b688_800x1159.jpeg) 1. Use fewer than 30 words per sentence 1. Use subject-verb-object sentences with "doers" and "action" 1. Avoid clutter words and phrases (e.g., "due to the fact that," to "Because") 1. Avoid jargon and acronyms as much as possible. They exclude newcomers and non-experts 1. Remove weak words like: would, might, should, significantly, and arguably 1. Eliminate weasel words, replace adjectives with data (e.g., "Sales increased significantly," to "Sales increased by 30%") 1. Does your writing pass the "so what" test? At the end of your document, has the reader learnt anything that will help them make a better decision? 1. If you are asked a question, start your response by directly answering the question. Source: [Fact of the Day 1](https://factoftheday1.substack.com/p/april-13-write-like-an-amazonian) <file_sep>/_posts/2012-02-01-ios-5-settings-url-scheme.markdown --- layout: post title: "iOS 5 Settings URL scheme" date: 2012-02-01 12:07 --- 在 iOS 5+ 可以通过 URL scheme 快速打开【设置】及子项。 ``` Settings prefs: About prefs:root=General&path=About Accessibility prefs:root=General&path=ACCESSIBILITY Airplane Mode On prefs:root=AIRPLANE_MODE Auto-Lock prefs:root=General&path=AUTOLOCK Brightness prefs:root=Brightness Bluetooth prefs:root=General&path=Bluetooth Date & Time prefs:root=General&path=DATE_AND_TIME FaceTime prefs:root=FACETIME General prefs:root=General Keyboard prefs:root=General&path=Keyboard iCloud prefs:root=CASTLE iCloud Storage & Backup prefs:root=CASTLE&path=STORAGE_AND_BACKUP International prefs:root=General&path=INTERNATIONAL Location Services prefs:root=LOCATION_SERVICES Music prefs:root=MUSIC Music Equalizer prefs:root=MUSIC&path=EQ Music Volume Limit prefs:root=MUSIC&path=VolumeLimit Network prefs:root=General&path=Network Nike + iPod prefs:root=NIKE_PLUS_IPOD Notes prefs:root=NOTES Notification prefs:root=NOTIFICATIONS_ID Phone prefs:root=Phone Photos prefs:root=Photos Profile prefs:root=General&path=ManagedConfigurationList Reset prefs:root=General&path=Reset Safari prefs:root=Safari Siri prefs:root=General&path=Assistant Sounds prefs:root=Sounds Software Update prefs:root=General&path=SOFTWARE_UPDATE_LINK Store prefs:root=STORE Twitter prefs:root=TWITTER Usage prefs:root=General&path=USAGE VPN prefs:root=General&path=Network/VPN Wallpaper prefs:root=Wallpaper Wi-Fi prefs:root=WIFI ``` via [Apple Settings App][2]/[Preference Shortcuts][3] [2]:http://handleopenurl.com/scheme/apple-settings-app [3]:http://www.idownloadblog.com/2011/11/11/how-to-create-custom-shortcuts-to-wifi-settings-airplane-mode-and-more-no-jailbreak-required/ <file_sep>/_posts/2014-01-02-date-timestamp-conversion-in-lua.markdown --- layout: post title: "Date Timestamp Conversion in Lua" date: 2014-01-02 10:16 --- #### Datetime to Timestamp ``` lua local dt = {year=2013, month=12, day=25, hour=0, min=0, sec=0} print(os.time(dt)) -- 1387900800 ``` #### Timestamp to Datetime ``` lua local ts = os.time() print(os.date('%Y-%m-%d %H:%M:%S', ts)) -- 2013-12-25 22:09:51 ``` More: [Date and Time](http://www.lua.org/pil/22.1.html) <file_sep>/_posts/2013-10-11-crash-early-crash-often.markdown --- layout: post title: "Crash Early, Crash Often" date: 2013-10-11 21:21 --- 最近开发中的一点感悟。 在开发阶段要尽量多的尽量早的暴露问题,应用 crash 恰恰是暴露问题最直接的方式,方便定位没有考虑到的细节问题。 举个例子,应用中对数据边界通常会进行保护判断,比如数组取值前判断数组长度是否满足。其实在开发阶段完全没必要,要求 array[3] 有值你之前的操作就必须要满足,如果不能达到就要想想哪里出了问题,如果数据源根本不能提供那么就要检查业务设计是否有问题。过分的保护检查不一定是好事。 <file_sep>/_posts/2008-10-22-forcing-study.markdown --- layout: post title: "强迫式学习" --- > 强迫学习法,用vimperator学习vim。 目前vimperator半完全接管firefox快捷操作,大部分操作都感觉很是方便,小部分快捷键不是很爽,因为笔记本的键盘原因吧,按着实在是别捏。不过目的是达到了,一种高效的工具值得去花时间学习,下一步,好好的看vim的帮助文档。 强迫自己去学习,必须要逼自己去看书,时间不多了,静下心来,加油! <file_sep>/_posts/2015-09-09-go-big-or-go-home.markdown --- layout: post title: Go Big or Go Home date: 2015-09-09 11:13:35 +0800 --- ![Go Big or Go Home](https://lh3.googleusercontent.com/u8vasO4w41GSCezzHeMtt03c4ttJzv_8Xsq0jLSoyUEZwDwXcmgiDiCbHBwGCzZo6Lz9awC_DUMO7wqe04VV-s2KxgWBcxybiIC-UdWKb6PUIKlLrFsOPDbGe4v8ffWt-UwMalV9WsBMMnj0QX_aOsR0DZxaQkufRQhAzEEC92CsdYkrlBL6BdcNChkTIaWc8qMyCNQR1Y9XndKUplRlnLVhxu93cp<KEY>t<KEY>bhvZ6yn_<KEY>2<KEY>1I5_28Fyp5lK5d_Onl2I6c4p2TWmZgiw05gafRxqX5l6cwbCYsH9A3z4ylrXSpppjqzqcoDAfSNHTk6Jr-XyE8h7Pc-aUMTA3yi7hwcWTng8U3rhoERuirCTZC3EEZqwx0fayppVxUwbzUC7M_N2lrx_E1nTnxJ9zY=w400-h225-no) <file_sep>/_posts/2015-01-28-nginx-dns-resolver.markdown --- layout: post title: Nginx DNS resolver date: 2015-01-28 18:34:35 +0800 --- nginx 通过 `proxy_pass` 和 upstream server 通信的时候需要手动指定 resolver。某些时候 DNS 解析失败就会出现这个错误: ``` domain.com could not be resolved. ``` 可以指定多个 DNS 并重置域名 TTL 延长 nginx 解析缓存来保障解析成功率: ``` resolver 192.168.127.12 192.168.127.12 172.16.17.32 192.168.127.12 valid=3600s; ``` 如果还有解析错误,可以用 dnsmasq 在本地自建 DNS,顺带还有加速解析的好处: ``` #/etc/dnsmasq.conf domain-needed bogus-priv cache-size=51200 listen-address=127.0.0.1 #server=192.168.127.12 resolv-file=/etc/resolv.conf ``` 另外需要注意的是 `proxy_pass` 并不是每次请求都会进行解析,如果 upstream IP 频繁变动,需要强制解析: ``` # via http://forum.nginx.org/read.php?2,215830,215832#msg-215832 resolver 127.0.0.1; set $backend "foo.example.com"; proxy_pass http://$backend; ``` <file_sep>/_posts/2018-05-22-quote.markdown --- layout: post title: Quote date: 2018-05-22 16:50:56 +0800 --- > 什么都不放弃实际上是怕放弃后自己什么都没有,无所畏惧的人生要敢于放弃。 [via](https://twitter.com/mranti/status/998394745058553856) <file_sep>/_posts/2017-06-05-xdg-base-directory.markdown --- layout: post title: XDG Base Directory date: 2017-06-05 22:07:44 +0800 --- XDG 是 X Desktop Group 的简称,现在叫 [Freedesktop.org][1],致力于推动 *nix 桌面环境的标准规范化。其中 [XDG Base Directory][2] 定义了文件配置基本目录: * `$XDG_CONFIG_HOME` 是配置文件目录,默认 `$HOME/.config` * `$XDG_DATA_HOME` 是用户文件的基本保存目录,默认 `$HOME/.local/share` * `$XDG_DATA_DIRS` 定义 `$XDG_DATA_HOME` 以外的文件基础目录,是一个有序目录集合,默认 `/usr/local/share/:/usr/share/` * `$XDG_CONFIG_DIRS` 同理,是扩展的配置文件目录,默认 `/etc/xdg`,需要注意的是目录顺序很重要,`$XDG_CONFIG_HOME` 优先级最高 * `$XDG_CACHE_HOME` 缓存目录,默认 `$HOME/.cache` * `$XDG_RUNTIME_DIR` 指定非必需运行时文件保存目录 [Neovim][3] 支持 XDG Base Directory,配置文件是 `$HOME/.config/nvim/init.vim`,shada 文件在 `$HOME/.local/share/nvim`. via [XDG Base Directory Specification][2] [1]: https://zh.wikipedia.org/wiki/Freedesktop.org [2]: https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html [3]: https://github.com/neovim/neovim<file_sep>/_posts/2012-12-08-new-mac-setup.markdown --- layout: post title: "New Mac Setup" date: 2012-12-08 13:58 --- 换了 SSD,重新配置了开发环境,简单留个笔记。 1. Mac App Store 下载 Xcode,安装 Command Line Tools 方便编译。MAS 下载的一个好处就是后续可以增量更新。 1. 安装 Homebrew,通过 brew 安装管理其他工具 git,zsh,MacVim,redis,PostgreSQL 等。 1. 配置 oh-my-zsh,懒人必备。 1. clone back dotfils from GitHub. 每个人都应该在 GitHub 等托管一份自己的配置文件,DRY。 1. brew install rbenv ruby-build,主要是给 Octopress 用,之前用 rvm 过于庞大复杂,rbenv 就简单不少。 1. 配置 Python virtualenv 环境,easy_install pip and use pip to install others. 换硬盘就显示了云存储的方便。Firefox Sync 很快就是自己顺手的浏览器,Dropbox 同步 nvALT 笔记,Alfred 等软件配置,只需一个账号你的数据、习惯随手就来,这也就是 Chromoe OS 带来的未来。 <file_sep>/_posts/2008-03-22-go-running.markdown --- layout: post title: "该锻炼身体了" --- 今天下午是这个学期体育选修的第一节课,散打。选修学分早都够了,现在上体育就是想逼着自己锻炼一下身体,主要是自己太懒了,老是不想去操场锻炼。缺乏锻炼啊,小跑了几圈就感觉累了。然后踢了半场球,刚开始没咋跑动,感觉还好,等跑起来就不行了,气虚,没力,腿跟定在地上一样,动不起来了,也就40分钟啊,不行了啊!决定晚上开始跑步了,锻炼一下,毕竟没有坏处。嗯,决定了,也不用多,每天晚上5圈2000米! <file_sep>/_posts/2012-11-26-get-declared-property-for-object-in-objective-c.markdown --- layout: post title: "Get declared property for object" date: 2012-11-26 10:49 --- 获取对象的 property 属性列表: ``` objc objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount) objc_property_t *protocol_copyPropertyList(Protocol *proto, unsigned int *outCount) ``` sample, via [Declared Properties][1]: ``` objc #import <objc/runtime.h> id LenderClass = objc_getClass("Lender"); unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount); for (i = 0; i < outCount; i++) { objc_property_t property = properties[i]; fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property)); } free(properties); ``` 拿到 property 列表就可以很方便做一些东西,比如 [autodescribe][2],根据列表取值然后组装成对象 description。再比如配合 NSCoder 做 NSObject 的[序列化][3]: ``` objc - (id)initWithCoder:(NSCoder *)decoder { self = [super init] if (self) { Class clazz = [self class]; NSUInteger count; objc_property_t *properties = class_copyPropertyList(clazz, &count); NSMutableArray *propertyArray = [NSMutableArray arrayWithCapacity:count]; for (int i = 0; i < count ; i++) { objc_property_t property = properties[i]; const char *propertyName = property_getName(property); [propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]]; } free(properties); for (NSString *name in propertyArray) { id value = [decoder decodeObjectForKey:name]; [self setValue:value forKey:name]; } } return self; } - (void)encodeWithCoder:(NSCoder *)coder { Class clazz = [self class]; NSUInteger count; objc_property_t *properties = class_copyPropertyList(clazz, &count); NSMutableArray *propertyArray = [NSMutableArray arrayWithCapacity:count]; for (int i = 0; i < count ; i++) { objc_property_t property = properties[i]; const char *propertyName = property_getName(property); [propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]]; } free(properties); for (NSString *name in propertyArray) { id value = [self valueForKey:name]; [coder encodeObject:value forKey:name]; } } ``` 也可以拿到成员变量列表: `class_copyIvarList(Class cls, unsigned int *outCount)`. [Objective-C Runtime][4] 有很多东西可以学习的。 [1]:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html [2]:https://github.com/neoneye/autodescribe [3]:http://www.cnblogs.com/likwo/archive/2011/05/26/2058134.html [4]:https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html <file_sep>/_posts/2016-08-31-monthly-review-1608.markdown --- layout: post title: Monthly Review 2016-08 date: 2016-08-31 22:52:37 +0800 --- 1. 产品迭代有了节奏,可惜一直不能上线。之前不好的行为,现在出了结果。 2. 对业务的熟悉在进行功能设计的时候很有帮助,思考更为全面,更为合理。 3. 向小米的同学请教了推荐系统的设计,接触学习 Spark。平台很重要,这位同学之前跟着我们做 iOS,现在小米负责大数据相关的东西,成长真快。 4. 日活下降,新增乏力,开始接入第三方渠道,业务似乎要变成一个广告平台。 5. 回老家,六六现在的口头禅:这是啥?那谁?叫我看看。也会很腼腆的说:我不会。 6. 在宜家买到心仪的桌子,一个桌面四条腿,简单却厚实的大桌子,很喜欢。 <file_sep>/_posts/2008-03-19-mac-setup.markdown --- layout: post title: "Mac OS安装教程" --- 系统镜像盘,刻出来装的,虚拟机没有试过,没有的话,算了吧,别看了! PQ分区魔法师,PM分区工具,其实要一个就好,不过我用了两个,分区魔法师有一个比较好的功能,分区的时候可以选择新分出来的分区在哪个位置,这 个也比较重要,我先前那十几回失败就在这,mac要求的硬盘分区不能过于靠后面,不然的话,很难识别到,建议还是靠前点好,C盘后面吧,不用过大,10个 G足够,分区格式最好是Fat32;PM有一个很好的功能,修改分区ID,ID要改为AF,非常方便,右键集成了,分区魔法师其实也有,不过是全英版,而 且把所有的分区放到了一起,不知道是哪一个了,英语又不是很好,就没敢用,要是英语好的话,用一个就中。还有一个,分出来的盘设置为逻辑分区就中,不需要 设为主分区,有的时候主分区反而装不上的。 BIOS设置为光驱启动,安装过程其实相当的傻瓜,按照引导到欢迎界面,选择 **实用工具|磁盘工具**,选中装mac 的盘,文件格式日志式,抹掉,也就是格式化,完成后退出,应该就能看到这个分区(或OSX所谓的宗卷)上有个期盼已久的绿色箭头了,继续下一步,在对话窗 口的左边会有“自定”的按钮,进去,首先就把打印机驱动全部枪毙掉(省硬盘空间),语言支持也毙掉,本地化语言只留了简体和繁体,X11我是选了,其 它的补丁看情况吧,我的显卡很争气,一次性成功。。。然后就是开始安装,时间不会太长,20分钟吧,重启计算机,用带有PQ的DOS启动盘启动进入DOS 命令行界面,启动PQ,这时PQ肯定会报错,不要理会,选择否/NO(一定要选择NO,不然,你的硬盘分区表就完了。。很麻烦的弄)把C盘激活,重启进入 XP,复制tboot(一个引导文件)到C:盘,并编辑C:\下的boot.ini文件(默认是只读的,要修改属性),在里面加上: C:\tboot="Mac OS X"   ,这样子启动时候可以选择系统,很方便。 重启,选择mac,第一回进去的时候如果你的显卡驱了的话会出现好像是12种语言的“欢迎”字样,如果没有,显卡肯定没有驱动成功;然后就是一些注册信息,随便填,顺利的话,就可以享受osx的乐趣了。 PS:这个是我自己装的流程,不一定完全使用别的机子,视情况而定。 <file_sep>/_posts/2013-09-20-zadr-ios-7-dev-tricks.markdown --- layout: post title: "@zadr's iOS 7 dev tricks" date: 2013-09-20 20:30 --- [@zadr][1] 在 iOS 7 正式发布几个小时后在 Twitter 上连续发了一些 iOS 7 SDK 小技巧,大部分都是我还不知道的东西,所以摘录一下,版权归 [@zadr][1] 完全所有。 > iOS 7: -[AVPlayer volume] and -[AVPlayer muted]; ! You can finally programmatically control the volume of playback without private APIs! [via](https://twitter.com/zadr/status/380401811670044672) AVPlayer 音量状态。 > iOS 7: [CTTelephonyNetworkInfo currentRadioAccessTechnology]; what kind of cellular connection you're on now. LTE/GPRS/CDMA{Rev 0, …}/etc! [via](https://twitter.com/zadr/status/380402599876259840) 获取运营商网络类别。 > iOS 7: -[NSArray firstObject]; Like -[NSArray lastObject];, only, the other end of the array. [via](https://twitter.com/zadr/status/380402801236385792) NSArray 直接取第一个对象。推荐 [Underscore.m][2]. > iOS 7: NSData has base64 encoding/decoding support now. And this fancy method, enumerateByteRangesUsingBlock:. [via](https://twitter.com/zadr/status/380403108049727488) NSData 有了原生的 base64 方法 `base64EncodedStringWithOptions:`。 > iOS 7: NSURLComponents: Build a NSURL and have it automatically handle encoding of strings for fragement/path/query/etc. [via](https://twitter.com/zadr/status/380404016796024832) NSURLComponents 自动编码处理。 > iOS 7: iAd support for prerolls in MPMoviePlayerController. This is more of a heads up than an FYI. [via](https://twitter.com/zadr/status/380404502970376192) iAd 支持从前卷广告类型。 > iOS 7: JavaScriptCore! Bridge between executing native code and executing JavaScript without needing a UIWebView. [via](https://twitter.com/zadr/status/380404740690956288) ObjC 直接操作 JS 的 API,JavaScriptCore 是个里程碑,值得好好学习一番。 > iOS 7: MKDistanceFormatter. Localized, unit-specific formatting of distances for both imperial and metric systems. [via](https://twitter.com/zadr/status/380405193843560448) MapKit 相关,支持本地化的地点距离换算。 > iOS 7: -[MPVolumeView wirelessRouteActive] and -[MPVolumeView wirelessRoutesAvailable] — Customize volume control when AirPlay is available. [via](https://twitter.com/zadr/status/380405692126875648) AirPlay 音量控制。 > iOS 7: -[UIScrollView keyboardDismissMode]; — Easily recreate Messages.app's scroll-to-dismiss-keyboard behavior! [via](https://twitter.com/zadr/status/380406489321455616) 类似系统 Message 的键盘滑动消失效果,`UIScrollViewKeyboardDismissModeInteractive`. > iOS 7: UITextView supports inserting and tapping on links. Making your own Twitter client just got that much easier! [via](https://twitter.com/zadr/status/380407288319586306) UITextView 支持链接点击,应该是 TextKit 带来的新功能。TextKit 也是一个很值得学习的新东西。 > iOS 7: AVCaptureDeviceFormat has video zooming with stabilization and simple control over frame rate/duration! [via](https://twitter.com/zadr/status/380408420563550208) 视频录制支持缩放,以前不支持? > iOS 7: AVSpeechSynthesis - Speak text to users without requiring VoiceOver to be turned on. [via](https://twitter.com/zadr/status/380409057451847681) VoiceOver 相关。 > iOS 7: Foundation changed a whole bunch of return types to be `instancetype` instead of `id`. Yay, type safety! [via](https://twitter.com/zadr/status/380410754765037568) 默认对象返回类型改为 [instancetype][3],自己封装的类库要跟进。 > iOS 7: MediaAccessibility. New framework that makes it *really* easy to work with closed captions and video. [via](https://twitter.com/zadr/status/380412553374863360) 图片视频功能继续加强。 > iOS 7: MFMessageComposeViewController supports adding attachments! Take a photo/video and iMessage it to someone in the same flow. [via](https://twitter.com/zadr/status/380413253668454400) 邮件分享支持直接添加附件。 > iOS 7: AVCaptureMetadataOutput can detect and decode most kinds of barcodes, including QR codes! [via](https://twitter.com/zadr/status/380417180937879552) 原生支持二维码扫描! > iOS 7: Also fixed some security vulnerabilities and updated root certificates. Check 'em out, http://support.apple.com/kb/HT5934 [via](https://twitter.com/zadr/status/380418048445779968) 修复了一些证书相关的安全问题。 > iOS 7: SSReadingList. Add Stuff to Safari's reading list that syncs between your Mac and iOS devices. [via](https://twitter.com/zadr/status/380426134627696640) Safari Reading List API。 > iOS 7: I don't even know how to describe it accurately, but, there's some amazing motion APIs in there to explore. Can't call out just one. [via](https://twitter.com/zadr/status/380427171275108352) CoreMotion API,M7 也是 iPhone 5s 最吸引我的东西。 > iOS 7: UIInputView: If you have a custom input field, use this as the root object. All subviews then get tinting and blur effects. [via](https://twitter.com/zadr/status/380428063642644480) iOS 7 输入框的模糊效果。 > iOS 7: UISimpleTextPrintFormatter: Print attributed strings without having to fall back to CoreGraphics to render content before printing. [via](https://twitter.com/zadr/status/380428588933079042) 更为简单的打印内容格式化。 iOS 7: -[NSObject decreaseSize:] / -[NSObject increaseSize:]; // called when cmd+ & cmd- are hit, so you can increase/decrease content size. [via](https://twitter.com/zadr/status/380428996036423680) 外接键盘可控制显示大小,类似 OS X 上的 Cmd+/Cmd-. > iOS 7: dispatch_source_memorypressure_flags_t, for whenever the system's memory pressure conditions change. Critical <-> Warn <-> Normal. [via](https://twitter.com/zadr/status/380497612312281088) GCD 相关,话说 GCD 的使用一直停留在基本层面,要多多深入。 PS: 分享一个 Twitter 搜索技巧: [iOS 7 from:zadr][4] 即可搜索 @zadr 所有包含 iOS 7 关键字的 Tweets。最后鄙视一下一些所谓的开发者,完全无视 [NDA][5] 的存在,在 iOS 7 SDK 正式发布前通过翻译等方式来刷自己的技术存在感。 [1]:https://twitter.com/zadr [2]:http://underscorem.org/ [3]:http://nshipster.com/instancetype/ [4]:https://twitter.com/search?q=from%3Azadr%20iOS%207 [5]:http://en.wikipedia.org/wiki/Non-disclosure_agreement <file_sep>/_posts/2012-08-01-ios-background-task-notes.markdown --- layout: post title: "iOS Background Task Notes" date: 2012-08-01 15:49 --- iOS 4+ 支持 audio、location、voip 后台常驻任务,除此以外 App 还可以向系统申请额外一段时间(十分钟)在后台执行某些任务,比如进入后台后发送操作日志等。 注册消息通知,或者直接实现 `- (applicationDidEnterBackground:(UIApplication *)application` delegate。 ```objc [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil]; ``` 向系统申请 background task 并执行: ```objc - (void)appDidEnterBackground { if (![UIDevice currentDevice].multitaskingSupported) { return; } UIApplication *app = [UIApplication sharedApplication]; __block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ dispatch_async(dispatch_get_main_queue(), ^{ if (bgTask != UIBackgroundTaskInvalid) { [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; } }); }]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ //Do tasks you want. dispatch_async(dispatch_get_main_queue(), ^{ if (bgTask != UIBackgroundTaskInvalid) { [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; } }); }); } ``` 注意:`beginBackgroundTaskWithExpirationHandler:` 生成的 task 在执行完以后必须要用 `endBackgroundTask:` 告诉系统任务已结束,不然在申请时间用完以后 App 会被系统直接终止,而不是挂起(suspended)。 <file_sep>/_posts/2013-06-12-never-alone.markdown --- layout: post title: "莫忘初衷" date: 2013-06-12 21:57 --- 你好久没说梦想 说到眼睛发亮 不可一世的笑容 连我都被感动 我们说改变世界 却被世界改变 记得你要我提醒 别改变太多 莫忘初衷 莫忘初衷 别忘 那一年 那一天 出发时心中的梦 <file_sep>/about.md --- layout: page title: About permalink: /about/ --- <NAME>, aka **fannheyward** on the web, is a developer based in Beijing, China. - Golang - OpenResty / ngx_lua - Python - JavaScript / TypeScript - iOS (Objective-C) - Neovim Contact me at [Twitter][1], [GitHub][2], [Stack Overflow][3], or <<EMAIL>>. [1]: https://twitter.com/fannheyward [2]: https://github.com/fannheyward [3]: http://stackoverflow.com/users/380774/fannheyward <file_sep>/_posts/2015-11-30-to-kobe.markdown --- layout: post title: Letter from Kobe date: 2015-11-30 11:38:21 +0800 --- ``` Dear Basketball From the moment I started rolling my dad’s tube socks And shooting imaginary Game-winning shots In the Great Western Forum I knew one thing was real: I fell in love with you. A love so deep I gave you my all — From my mind & body To my spirit & soul. As a six-year-old boy Deeply in love with you I never saw the end of the tunnel. I only saw myself Running out of one. And so I ran. I ran up and down every court After every loose ball for you. You asked for my hustle I gave you my heart Because it came with so much more. I played through the sweat and hurt Not because challenge called me But because YOU called me. I did everything for YOU Because that’s what you do When someone makes you feel as Alive as you’ve made me feel. You gave a six-year-old boy his Laker dream And I’ll always love you for it. But I can’t love you obsessively for much longer. This season is all I have left to give. My heart can take the pounding My mind can handle the grind But my body knows it’s time to say goodbye. And that’s OK. I’m ready to let you go. I want you to know now So we both can savor every moment we have left together. The good and the bad. We have given each other All that we have. And we both know, no matter what I do next I’ll always be that kid With the rolled up socks Garbage can in the corner :05 seconds on the clock Ball in my hands. 5 … 4 … 3 … 2 … 1 Love you always, Kobe ``` ![Letter from Kobe](http://7xl883.media1.z0.glb.clouddn.com/kobe.png) <file_sep>/_posts/2012-08-21-afnetworking-notes.markdown --- layout: post title: "AFNetworking 学习笔记" date: 2012-08-21 16:38 --- > 1. 这篇笔记是在 AFN v0.10.1 时候写的,AFN v1.0 以后加入了不少新东西,比如 SSL 支持,不过整体结构没有变化。 > 1. 后续跟进了一篇 [AFNetworking Notes 2][7] ![AFN.jpg](https://i.loli.net/2019/11/11/9VreQ8Tt3k7xnBR.jpg) 上图来自 @mattt 对 AFN 的介绍:[Everybody Loves AFNetworking And So Can You!][1]. 学习 AFN,简单记录一下以加深自己理解。 AFN 的基础部分是 AFURLConnectionOperation,一个 NSOperation subclass,实现了 NSURLConnection 相关的 delegate+blocks,网络部分是由 NSURLConnection 完成,然后利用 NSOperation 的 state (isReady→isExecuting→isFinished) 变化来进行网络控制。网络请求是在一个指定的线程(networkRequestThread)完成。 AFURLConnectionOperation 是一个很纯粹的网络请求 operation,可以对他进行 start/cancel/pause/resume 操作,可以获取对应的 NSURLRequest 和 NSURLResponse 数据。支持 NSInputStream/NSOutputStream,提供了 uploadPress 和 downloadProgress 以方便其他使用。 ```obj-c NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/ip"]]; AFURLConnectionOperation *operation = [[AFURLConnectionOperation alloc] initWithRequest:request]; operation.completionBlock = ^ { NSLog(@"Complete: %@", operation.responseString); }; [operation start]; ``` 插播:@mattt 在 NSHipster 里有一篇 [NSOperation][2] 详细介绍了 NSOperation 的 state、priority、dependency 等,对理解 AFURLConnectionOperation 很有帮助。 ---- 理解了 AFURLConnectionOperation 再看 AFHTTPRequestOperation 就简单很多。AFHTTPRequestOperation 是 AFURLConnectionOperation 的子类,针对 HTTP+HTTPS 协议做了一层封装,比如 statusCode、Content-Type 等,添加了请求成功和失败的回调 block,提供了 `addAcceptableContentTypes:` 以方便上层使用。 ```obj-c NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/robots.txt"]]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"Success: %@", operation.responseString); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Failure: %@", error); }]; [operation start]; ``` ---- AFJSONRequestOperation 是 AFHTTPRequestOperation 的子类,针对 JSON 类型请求做了特殊处理,在有了 AFHTTPRequestOperation+AFURLConnectionOperation 的基础工作后,AFJSONRequestOperation 已经非常方便直接使用了。指定 `acceptableContentTypes:` 以支持 JSON,`responseJSON` 直接返回已经解析好的 JSON 数据对象。下载到 JSON 数据后在一单独线程 queue(json_request_operation_processing_queue)对 JSON 数据进行解析处理,处理完成后由主线程回调 success block。 AFN 的 JSON encode/decode 处理做的非常巧妙,现在有很多 JSON 解析库,第三方的 JSONKit、SBJSON 等,iOS 5+ 自带的 NSJSONSerialization,不同的项目可能会因为不同的需求而用不同的库,AFN 就封装了一个 AFJSONUtilities,提供 `AFJSONEncode` 和 `AFJSONDecode` 两个方法,通过 `NSClassFromString` 和 `NSSelectorFromString` 来查找项目中使用的 JSON 库然后进行 encode/decode。 ```obj-c NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://httpbin.org/get"]]; AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { NSLog(@"Success :%@", JSON); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { NSLog(@"Failure: %@", error); }]; [operation start]; ``` ---- AFXMLRequestOperation/AFPropertyListRequestOperation/AFImageRequestOperation 和 AFJSONRequestOperation 类似,针对 XML、Plist、image 类型请求做了一些处理。其中 AFImageRequestOperation 额外有一个 imageProcessingBlock,取到图片后可以在一个单独线程 queque 对图片进行处理,比如缩放、切圆角、图片特效等,然后再交给 main_queue success block. AFN 还提供了一个 UIImageView+AFNetworking category,可以用 `setImageWithURL:` 来设置图片。这个 cagetory 和 SDWebImage 类似但更简单一些,图片下载由 AFN 完成,图片缓存由 NSCache 处理。 ---- 直接用上面这些已经可以方便的做网络请求,AFN 在这些基础上还提供了一个 AFHTTPClient,把 HTTP 请求的 Headers、User-Agent 等再次包装,方便使用。AFHTTPClient 是一个单例,对请求参数做了 URL 编码;维护一个 NSOperationQueue,不同的请求生成各自的 AFHTTPRequestOperation 然后 `enqueueHTTPRequestOperation:` 添加的队列顺序执行;`registerHTTPOperationClass:` 方法用来注册上面的 JSON/XML/Plist/image operation,拿到请求结果后交给对应的 operation 处理。AFHTTPClient 还针对 GET/POST/HEAD/PUT/DELETE 等不同的请求做了不同的 URL 参数和 Headers 处理,包括 multipart/form-data 类型。 AFHTTPClient 支持批量添加 operations,生成一个 batchedOperation,把所有 operations 作为 batchedOperation 的 dependency,再依次把所有 operations 和 batchedOperation 都添加到 operationQueue,这样每一个 operation 完成后都可以做一个 progressBlock 来返回当前已完成的 operations 数和总数,等所有 operations 都完成后会做 batchedOperation 的 completionBlock,就可以在这一批 operations 都完成后做一些善后处理。 AFHTTPClient 提倡对同一应用(同一 baseURL)的网络请求封装自己的 HTTPClient 子类,这样会方便很多。参考 [WBKHTTPClient][3]. ---- AFN 还提供了很多模块,可以很方便的和 AFN 整合做一些工作,比如 OAuth,Amazon S3 等,详见 [AFNetworking-Extensions][4]. ---- AFN 作者 @mattt 做东西很有自己一套思想在里面,推荐 [What I Learned From AFNetworking's GitHub Issues][5],[视频][6]。 [1]:https://speakerdeck.com/u/mattt/p/everybody-loves-afnetworking-and-so-can-you [2]:http://nshipster.com/nsoperation/ [3]:https://github.com/fannheyward/WeiboEngine/blob/master/WeiboKit/WBKHTTPClient.h [4]:https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-Extensions [5]:https://speakerdeck.com/u/mattt/p/what-i-learned-from-afnetworkings-github-issues [6]:http://www.vimeo.com/47459338 [7]:https://fann.im/blog/2013/04/29/afnetworking-notes-2/ <file_sep>/_posts/2013-12-13-performance.markdown --- layout: post title: "Performance" date: 2013-12-13 09:58 --- 在 V2EX 看到一个关于[性能的讨论](http://www.v2ex.com/t/83579): > 使用者优先,维护者其次,自己的偏执最不重要。 自己有时候就会过于偏执而掉到坑里,谨记。 <file_sep>/_posts/2018-08-14-vim-folding.markdown --- layout: post title: Vim folding date: 2018-08-14 10:43:26 +0800 --- * zi - toggle folding * za - toggle current fold open/close * zR - open all folds * zM - close all folds * zc - close current fold * zo - open currrent fold * zj - move down to next fold * zk - move up to previous fold ``` nnoremap <Space> za ```<file_sep>/_posts/2008-07-30-artest-join-rockets-probably.markdown --- layout: post title: "“野兽”阿泰斯特加盟火箭?8月14号生效?" --- 纪事报爆料,国王经理确认,当事人鲍比杰克逊也确认有这么回事! 真假啊?太疯狂了这个!当然,联盟说要等到8月14号,两个星期后才能正式生效。也够人兴奋上一段时间了。刚看见这个消息让我激动了好一下,没办法,把火箭当成自家球队了嘛。 来看看网上爆料的交易详情:火箭送出鲍比杰克逊,未来一个首轮选秀权,加上今年火箭淘到的超级新秀格林,就那个夏季联赛搞了40分的家伙,就这些!抢劫啊,又一次可能让波波维奇大骂联盟无知的犯罪事件,上一次是湖人抢劫加索尔,莫雷太牛了,这都能操作成功?国王经理们立马成了另外一个灰熊,甚至比灰熊的还要“2”。现在联盟里最强硬的小前了,也应该是现在联盟里背打能力最棒的小前了,防守能力同样是顶呱呱的啊,我的个乖啊,这么大的人物居然这么小的代价就给抢过来了?莫雷神了! 不过有一点倒是得想想,阿泰为啥叫“野兽”?就是脾气太暴了,当年在奥本山那可是拳头说话的主啊,其他小的就更多了,阿泰来了能不能跟火箭的人,准确说,跟现在的老大麦蒂能不能和平相处呢?别考虑姚明,中国人的性格,东方人的文化,大姚不会也不可能跟他们争。其实麦蒂的性格也挺东方的,不咋说话,所以老有人说麦蒂太懦弱,不如科比的霸道。这么说,阿泰跟麦蒂应该不会太僵吧?别忘了阿泰也30了吧,三十而立,都想是想拿总冠军的人,估计球场上窝里斗的不会很多,我估计俩人也不会怎么斗,别忘了还有阿德尔曼呢,那可是阿泰的恩师,阿泰这么野兽的人物不让阿德尔曼给收拾的服服帖帖?所以说,内斗应该问题不大。 还有一个问题,位置。阿泰来了,小前?那巴蒂尔呢?也是联盟防守高手啊,还有麦蒂,锋卫摇摆人,好多时候也出现在小前的位置上,这下该怎么办啊?得,还得看阿德尔曼的。我先来YY一下,让阿泰打超级第六人,类似于马刺的吉诺比利,替补比主力得分都多的那种第六人。这样,首发还是大姚,斯科拉,巴蒂尔,麦蒂,阿尔斯通,上个替补火力依然生猛,多性啊!咋不让巴蒂尔第六人,阿泰首发呢?巴蒂尔不怎么会进攻啊,换个人上个替补不能立马得分,不好。就是不知道阿泰会不会去干这第六人的活儿。现在看来,就剩控卫这个位置太薄弱了,不过好像SF3恢复的不错,或者再挖一个超级控卫? 算了,不想了,联盟还没有确认呢,等到了8月份再去YY吧,或者直接到11月份看效果,吼吼! PS:今天听说韩国把奥运会开幕式给偷拍了,看了一点,嗯,不错,有几个镜头还是相当好看,有一个大海豚,好看。就是不知道是不是真的。 <file_sep>/_posts/2013-07-15-best-practices-for-restful-api.markdown --- layout: post title: "Best Practices for RESTful API" date: 2013-07-15 21:52 --- 做服务端开发,免不了有对外接口,正好看到 [Best Practices for Designing a Pragmatic RESTful API][1],简单摘抄做个笔记。 1. API 就是面对开发者的 UI,所以要对开发者友好,能方便在浏览器输入访问。 1. 尽量遵守 Web 标准。 1. 使用 RESTful URLs。URL 标识资源,HTTP Method(GET/POST/PUT/DELETE) 操作控制资源,其中 GET 获取,POST 新建,PUT 更新,DELETE 删除,还有一个 PATCH 部分更新。 1. URL 用复数形式标识资源。 1. URL 资源作为一个原子操作。 1. 文档,并且配上相应示例,最好提供可直接浏览器+curl 的例子。 1. API 一旦确定就不轻易修改,更新和删除要有对应文档说明。 1. API 要有版本,并且直接在 URL 中表现出来,比如 `/api/1/xyz`. 1. URL 可以跟上条件过滤控制参数,比如 `/tickets?state=open`。 1. 把常用的条件集合包装成一个 URL 资源,比如 `/tickets/recently_closed`。 1. URL 可包含一个返回字段列表,只返回指定字段内容,比如 `/tickets?fields=id,subject` 1. 只有 JSON 格式,然后也就没有必要在 URL 指明 format 后缀。 1. URL 采用蛇形命名(下划线形式),比如 `user_timeline`. 1. API 返回要设置 Content-Type,结果用 Gzip 压缩。 1. RESTful GET 只能读取,不允许修改数据。 1. API 请求有次数限制,类似 [Twitter Rate Limiting][2] 1. 如有需要,用 OAuth 2 认证。 1. API 头部信息包含 ETag 等缓存信息。 1. 有用的错误信息:唯一错误码+错误描述信息,有对应文档。 1. 充分利用 HTTP status code,比如 200/201/204/304/401/403/404/405. [1]:http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api [2]:https://dev.twitter.com/docs/rate-limiting/1.1 <file_sep>/_posts/2012-11-03-disable-git-commit-log-after-git-merge.markdown --- layout: post title: "禁用 git merge 完成后的提交说明" date: 2012-11-03 20:03 --- Git 1.7.10+ 版本对 `git merge` 做了一个改动,就是 merge 成功后会自动打开编辑器等待输入 merge 提交说明,而之前版本是自动完成这个 log。Linus 大神说之前的做法其实是一个设计失误 [via](http://thread.gmane.org/gmane.linux.kernel/1191100/focus=181362): > we never even fire up the editor by default for a "git merge", but we do for a "git commit". That was a design mistake, and it means that if you want to actually add a note to a merge, you have to do extra work. 然而大部分时候我们 merge 的时候都不太会去手动添加 merge log,那么这个功能就是个干扰,每次都要手动去关掉编辑器。[这里](https://raw.github.com/gitster/git/master/Documentation/RelNotes/1.7.10.txt) 找到一个解决方案: ``` export GIT_MERGE_AUTOEDIT=no ``` Done. <file_sep>/_posts/2015-12-31-self-review-2015.markdown --- layout: post title: "[self review:2015];" date: 2015-12-31 15:13:43 +0800 --- #### 工作 技术上,前端和 Golang 有学习产出。现在一个互联网产品从前端到后端整个流程都接触,广度上能有一些把控,但在深度上还不够,Swift 一直没有去学习储备,作为技术负责人只能算及格。 管理上,Q4 开始转型作为整体负责人,在产品和运营上的短板很明显,这也是一直以来自己做的不够的地方,来年还得努力。 #### 生活 每个月回家一次的节奏,很奔波,但至少六六记得我们,而且也多了很多陪父母的时间,挺好。 暑假时候带六六和妈妈、妹妹来北京住了 40 天,幸福。 11 月份开始跑步锻炼,现在体重卡在 82 波动,目标是保持在 80 以下。 买了房。 <file_sep>/_posts/2008-04-14-sql-study-select-3.markdown --- layout: post title: "SQL学习--嵌套查询" --- IN谓词子查询: ``` select Sno,Sname,Sdept from Student where sdept IN (select Sdept from Student where Sname ='WANG'); select Sno,Sname from Student where Sno IN (select Sno from SC where Cno IN (select Cno from Course where Cname ='shujuku4')) ``` ANY(SOME)或ALL谓词子查询: ``` select Sname,Sage from Student where Sage < ANY ( select Sage from Student where Sdept ='CS') AND Sdept <> 'CS'; ``` EXISTS谓词子查询: ``` select Sname from Student where EXISTS (select * from SC where Sno =Student.Sno AND Cno='1'); select DISTINCT Sno from SC SCX where NOT EXISTS (select * from SC SCY where SCY.Sno ='1002' AND NOT EXISTS (select * from SC SCZ where SCZ.Sno = SCX.Sno AND SCZ.Cno = SCY.Cno)); ``` <file_sep>/_posts/2008-05-13-mourning.markdown --- layout: post title: "默哀,祈祷。。。" --- 为死去的同胞流泪,天堂安息。默哀祈祷。 拥有与失去,仅仅是一瞬间。生命可以如此坚强,也如此脆弱。 <file_sep>/_posts/2008-03-12-pc-1-year.markdown --- layout: post title: "电脑买回来一年了" --- RT,去年的3月12号去百脑汇把本子买了回来,这一年花在电脑上的时间有多少啊?不知道,不敢算,怕吓到自己。。估计会是一个相当恐怖的数目! 天天在电脑前呆着,学到了啥?一下子还真说不上来。三月份把买回来,五一时候装Mac,一不小心 全盘格了一次;暑假带回家,ADSL上网,终于体验了一下学校不可能的网速;十一时候搞Ubuntu,瞎忙到现在,算是学了点东西,不过更多的时候是自己自娱自乐,没学到啥实在的东西。乱七八糟的东西,每天上网,reader上看看大侠们的东西,看看新闻,时不时的看看比赛,晚上电影一下,:-)真正的学习好像真不多啊。。。浪费了。 还有一年半,好好利用他吧,别再浪费了,双核一G独显呢。。。 <file_sep>/_posts/2015-01-20-httpie-and-jq.markdown --- layout: post title: "命令行 API 调试工具: HTTPie & jq" date: 2015-01-20 14:52:05 +0800 --- * [HTTPie][1]: a CLI, cURL-like tool for humans. * [jq][2]: a command-line JSON processor. HTTPie 类似 cURL,更简单易用,jq 用来解析 JSON,一起配合使用做 API 开发调试非常方便: 1. GET: `http :9090/api/test` 1. POST: `http -f post --session=fann :9090/api/login' user=fannheyward passwd=<PASSWORD>` 1. GET with cookie: `http --session=fann :9090/api/profile` ---- 1. `jq .` - 格式化整个 JSON 2. `jq ".status"` - 只显示 status 字段的值 3. `jq ". | {name: .name, icon: .icon}"` - 重组 JSON,只显示 name&icon 字段 4. `jq ".[] | {name: .name}"` - 遍历 JSON 数组,只显示每个元素的 name 字段 更多高级用法参考各自文档。 [1]:https://github.com/jakubroztocil/httpie [2]:http://stedolan.github.io/jq/<file_sep>/_posts/2008-03-28-miibeian-pass.markdown --- layout: post title: "网站备案通过!" --- 25号收到邮件说备案通过,刚开始还有点不信,因为之前已经做好第一次不通过的准备,谁都知道备案慢的要死。登录上去一看,还真是,备案通过!RP爆发啦,哈!不过电子证书还没有准备好。。 直到中午时候登录才发现电子证书弄好了。晚上回来把这个备案最后一点点过程搞一下,下载证书,上传到cert/目录下面,在主页上做好链接,over! 皖ICP备08002053号,俺在网上的户口,合法了。 ps:一直在想那个cert啥意思,还是不懂。。。 <file_sep>/_posts/2008-08-23-ghost-mouse.markdown --- layout: post title: "灵异鼠标" --- 见鬼了,我的鼠标不能拖拽,突然间的事,这上网岂不是折磨啊,以为是坏了,想想不应该啊,罗技的,怎么说也是行货啊,上网搜了一下,找到一个很囧的解决办法,**连按两下ESC**,好像连按两下ESC相当于在控制面板里重新选择拖拽功能,这个,我还真不知道,学习了。 <file_sep>/_posts/2012-01-09-compile-and-install-svn-172-on-mac.markdown --- layout: post title: "Compile and install SVN 1.7.2 on Mac" date: 2012-01-09 18:25 --- Just a note for myself. 1. Download [svn-1.7.2.tar.gz](http://labs.renren.com/apache-mirror/subversion/subversion-1.7.2.tar.gz) source. 1. Run `./autogen.sh` to check the necessary components to build svn. 1. `./configure` then `make` and `sudo make install`. All commands: ``` ./autogen.sh ./configure --disable-debug --with-ssl --with-zlib=/usr --with-sqlite=/usr --disable-neon-version-check --disable-mod-activation --without-apache-libexecdir --without-berkeley-db --with-neon=/usr/local/Cellar/neon/0.29.6/ make sudo make install ``` <file_sep>/_posts/2020-01-06-audit.sh.markdown --- layout: post title: audit.sh date: 2020-01-06 20:22:28 +0800 --- Use [PROMPT_COMMAND](http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x264.html) for bash, and [precmd](http://zsh.sourceforge.net/Doc/Release/Functions.html) for zsh. ```sh mkdir -p /var/log/.audit touch /var/log/.audit/audit.log chown nobody:nobody /var/log/.audit/audit.log chmod 002 /var/log/.audit/audit.log chattr +a /var/log/.audit/audit.log ``` Save to `/etc/profile.d/audit.sh`: ```sh HISTSIZE=500000 HISTTIMEFORMAT=" " export HISTTIMEFORMAT export HISTORY_FILE=/var/log/.audit/audit.log export PROMPT_COMMAND='{ curr_hist=`history 1|awk "{print \\$1}"`;last_command=`history 1| awk "{\\$1=\"\" ;print}"`;user=`id -un`;user_info=(`who -u am i`);real_user=${user_info[0]};login_date=${user_info[2]};login_time=${user_info[3]};curr_path=`pwd`;login_ip=`echo $SSH_CONNECTION | awk "{print \\$1}"`;if [ ${login_ip}x == x ];then login_ip=- ; fi ;if [ ${curr_hist}x != ${last_hist}x ];then echo -E `date "+%Y-%m-%d %H:%M:%S"` $user\($real_user\) $login_ip [$login_date $login_time] [$curr_path] $last_command ;last_hist=$curr_hist;fi; } >> $HISTORY_FILE' ``` ```sh echo "local6.* /var/log/commands.log" > /etc/rsyslog.d/commands.conf systemctl restart rsyslog.service precmd() { eval 'RETRN_VAL=$?;logger -p local6.debug "$(whoami) [$$]: $(history | tail -n1 | sed "s/^[ ]*[0-9]\+[ ]*//" ) [$RETRN_VAL]"' } ``` <file_sep>/_posts/2018-11-20-aws-services-2018.markdown --- layout: post title: AWS Services List (2018) date: 2018-11-20 16:13:08 +0800 --- > 一句话说清楚 AWS X 是什么 计算: * EC2 - Amazon Elastic Compute Cloud,或者叫亚马逊的虚拟机服务 - 一台托管在 AWS 的电脑/服务器 * ECS - Amazon Elastic Container Service - 亚马逊 Docker 服务,配合内部 Elastic Container Registry(ECR) 做服务容器化 - 还有 EKS(ECS for Kubernetes) * Lambda - AWS App Scripts - 只跑代码,不需要考虑服务器问题 - 可访问其他服务资源 存储: * S3 - Amazon Simple Storage Service,或者叫亚马逊无限量 FTP 服务器 - 存储网站图片、视频、备份等 - 不同服务间文件共享 * EFS - Amazon Elastic File System * EBS - Amazon Elastic Block Store - EFS 和 EBS 很像,简单理解就是 EBS 是一个可以挂载到 EC2 的硬件磁盘,EFS 是一个网络文件系统 * Glacier - 云归档服务 - 成本极低的数据存储和长期备份 数据库: * RDS - Amazon Relational Database Service - 亚马逊数据库服务,帮你做好备份、扩容等 * Aurora - 兼容 MySQL/PostgreSQL 的分布式关系型数据库 * Elasticache - 亚马逊 Redis/Memcached 服务 * DynamoDB - 亚马逊 NoSQL 服务 - KV 存储服务 * RedShift - PB 级数据仓库 网关和内容分发: * Cloudfront - 亚马逊 CDN 服务 * Route53 - 域名注册,DNS 服务 * ELB - Elastic Load Balancing,负载均衡 * API Gateway - API 网关代理 - 管理后端 API,比如流量控制,监控,版本切换,A/B 测试分流等 开发者工具: * CodeCommit - 私有 Git 服务器 * CodeBuild - CI 系统 * CodePipeline - 持续交付发布 * Code Deploy - 自动化部署 - 尤其适用于同时部署到多个 EC2 * Cloud9 - 云端 IDE 移动应用服务: * Cognito - 亚马逊 OAuth 服务 - 让用户使用社交网站信息注册、登录 * Device Farm - 在真实设备上做应用测试 - 提供视频、截图、日志等信息 * Mobile Analytics - 收集、查看应用分析数据 - 类似 Flurry、Google Analytics Web 基础服务: * SES - Amazon Simple Email Service - 亚马逊邮件发送服务,包括邮件通知、订阅等 * SNS - Amazon Simple Notification Service - 向用户发 push、邮件、短信 * SQS - Amazon Simple Queue Service - 亚马逊消息队列服务 * WAF - Web 应用防火墙 * CloudSearch - 或者叫亚马逊全文搜索服务 * Elastic Transcoder - 亚马逊视频转码服务 其他,包括 AWS 安全,管理,监控等: * IAM - AWS Identity and Access Management - 管理用户组,管理资源访问权限 * CloudTrail - 跟踪 AWS 用户活动和 API 使用状况 * CloudWatch - AWS 服务监控 * Config - 记录、评估 AWS 资源配置 * OpsWorks - 用 Chef 和 Puppet 实现操作自动化 * Trusted Advisor - 对使用的 AWS 资源进行成本分析、安全建议等 * Inspector - 自动安全评估服务,评估应用程序风险、漏洞 <file_sep>/_posts/2019-09-19-evolution-of-architecture.markdown --- layout: post title: "[转]服务端高并发分布式架构演进之路" date: 2019-09-19 10:12:11 +0800 external-url: https://segmentfault.com/a/1190000018626163 --- > 原文 [服务端高并发分布式架构演进之路](https://segmentfault.com/a/1190000018626163),本文以淘宝作为例子,介绍从一百个并发到千万级并发情况下服务端的架构的演进过程,同时列举出每个演进阶段会遇到的相关技术,让大家对架构的演进有一个整体的认知,文章最后汇总了一些架构设计的原则。 1. ![0](https://image-static.segmentfault.com/266/495/2664959638-5ca02e1d2e99b_articlex) 1. ![1](https://image-static.segmentfault.com/257/135/2571350918-5ca02dfbdc242_articlex) 1. ![2](https://image-static.segmentfault.com/108/886/1088865837-5ca031313f044_articlex) 1. ![3](https://image-static.segmentfault.com/287/264/2872647211-5c95fef4928ad_articlex) 1. ![4](https://image-static.segmentfault.com/158/988/1589885053-5c96032e3c356_articlex) 1. ![5](https://image-static.segmentfault.com/250/737/250737400-5c9653d44e54e_articlex) 1. ![6](https://image-static.segmentfault.com/111/902/111902257-5c960f793734f_articlex) 1. ![7](https://image-static.segmentfault.com/115/755/1157555056-5c965af7a8de0_articlex) 1. ![8](https://image-static.segmentfault.com/189/622/1896228394-5c9662ac87756_articlex) 1. ![9](https://image-static.segmentfault.com/119/002/1190021994-5ca03c930e572_articlex) 1. ![10](https://image-static.segmentfault.com/199/226/1992263855-5ca04d46dd717_articlex) 1. ![11](https://image-static.segmentfault.com/651/851/651851067-5ca04fe08f7ee_articlex) 1. ![12](https://image-static.segmentfault.com/116/244/1162448692-5ca052a998911_articlex) 1. ![13](https://image-static.segmentfault.com/276/074/2760745238-5ca055e4b20a9_articlex) 1. ![14](https://image-static.segmentfault.com/140/934/1409345676-5ca05cae06402_articlex) 架构设计的原则: 1. N+1设计。系统中的每个组件都应做到没有单点故障; 1. 回滚设计。确保系统可以向前兼容,在系统升级时应能有办法回滚版本; 1. 禁用设计。应该提供控制具体功能是否可用的配置,在系统出现故障时能够快速下线功能; 1. 监控设计。在设计阶段就要考虑监控的手段; 1. 多活数据中心设计。若系统需要极高的高可用,应考虑在多地实施数据中心进行多活,至少在一个机房断电的情况下系统依然可用; 1. 采用成熟的技术。刚开发的或开源的技术往往存在很多隐藏的bug,出了问题没有商业支持可能会是一个灾难; 1. 资源隔离设计。应避免单一业务占用全部资源; 1. 架构应能水平扩展。系统只有做到能水平扩展,才能有效避免瓶颈问题; 1. 非核心则购买。非核心功能若需要占用大量的研发资源才能解决,则考虑购买成熟的产品; 1. 使用商用硬件。商用硬件能有效降低硬件故障的机率; 1. 快速迭代。系统应该快速开发小功能模块,尽快上线进行验证,早日发现问题大大降低系统交付的风险; 1. 无状态设计。服务接口应该做成无状态的,当前接口的访问不依赖于接口上次访问的状态。 <file_sep>/_posts/2019-04-17-logrotate.markdown --- layout: post title: logrotate date: 2019-04-17 15:03:33 +0800 --- > logrotate - rotates, compresses, and mails system logs ``` # 0 0 * * * /usr/sbin/logrotate --state=/home/serv/logrotate.state /home/serv/logrotate.log.conf /home/serv/logs/dev.log /home/serv/logs/access.log { rotate 10 daily compress create copytruncate missingok dateext dateformat -%Y-%m-%d dateyesterday sharedscripts postrotate kill -USR1 `cat /var/run/nginx.pid` endscript } ``` 1. 要么保存到 /etc 配置,由系统调度。也可以自己通过 crontab 调度控制,这种情况要注意加 `--state` 来保存状态 2. 像 nginx 可以通过 `kill -USR1` 来重新打开日志文件,如果服务不支持可以用 `copytruncate`,先拷贝再清空<file_sep>/_posts/2018-08-02-run-git-overall-subdir.markdown --- layout: post title: 在所有子目录下执行 git date: 2018-08-02 18:20:20 +0800 --- ``` git config --global alias.all '!f() { ls -R -d */.git | sed 's,\/.git,,' | xargs -P10 -I{} git -C {} $1; }; f' git all pull ```<file_sep>/_posts/2008-10-01-vim-beginning.markdown --- layout: post title: "VIM开始" --- 做个记号,2008年10月1日,Gvim第N次(N≥5)进驻我的电脑,绿版的,安装版的,都试过。每一次都是装上,然后试了几个命令,看了一下效果,然后,放弃,卸载。说实话,vim的上手真的不是很简单,但单单vim采用模式的概念,已然很超前了许多,虽然对vim来说已经很久远的事了。这回又装上,要慢慢的学习一下,一个好工具值得去花时间去学习的,嗯,就这。 <file_sep>/_posts/2009-04-03-vimperator-20.markdown --- layout: post title: "Vimperator 2.0使用" --- vimperator 2.0最近放了出来,升级安装后发现一些新东西: 1. 数字化标签,:set guioptions=n/N,小写的话在标签图标后添加数字,大写是在标签图标上添加; 2. guioptions 增加了几个参数,b/r/l 设置滚动条位置,默认不会显示滚动条的; 3. colorscheme 配色方案,类似于 vim,现在 vimperator 也可以使用配色了,配色文件命名为 name.vimp。Windows 下装了 2.0 版本后会自动在个人目录下生成一个 vimperator 的文件夹,vista 下面是:C:\Users\Heyward\vimperator,里面有一个 info 子文件夹,功能类似于 vim 的 viminfo 功能。要使用配色先新建一 colors 文件夹,把找到的配色方案放到里面,然后 `:colorscheme name`就可以使用了。目前还没有找到比较好的配色, github 上有几个还不错。 <file_sep>/_posts/2013-04-17-retain-cycle-in-blocks.markdown --- layout: post title: "Retain Cycle in Blocks" date: 2013-04-17 22:20 --- > 个人笔记,可能会有理解不够透彻而错误。 @fannheyward Objective-C 是基于引用计数(retainCount)来做内存管理,ClassA 用到 ClassB 的时候,通过 alloc/retain/copy 等将 objectB.retainCount+1,不需要的时候通过 release/autorelease 将 objectB.retainCount-1. retainCount 归零后对象 objectB 被释放。假如 objectA retain objectB,objectB 反过来也 retain objectA,结果就是两者 retainCount 都无法归零,也就没办法被释放,造成内存泄露。这就是 Retain Cycle。 一般情况下注意避免两个对象互相 retain 就不太会出现 Retain Cycle,但是在用到 Blocks 的时候就要小心,很容易造成 Retain Cycle。这是因为 Blocks 会自动 retain 它引用的对象(block 里的对象),稍不留神就造成 Retain Cycle。文档: [Object and Block Variables][1]: > When a block is copied, it creates **strong** references to object variables used **within the block**. If you use a block within the implementation of a method: > > * If you access an instance variable by reference, a strong reference is made to self; > > * If you access an instance variable by value, a strong reference is made to the variable. > To override this behavior for a particular object variable, you can mark it with the **__block** storage type modifier. #### MRC 一个简单的例子,Xcode 会报 Retain Cycle warning: ``` objc UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect]; [imgView setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // ... imgView.image = image; // warning: Capturing 'imgView' strongly in this block is likely to lead to a retain cycle }]; ``` block 也是一个对象,[imgView setImageWithURL:completed:] 的时候 retain 了这个 block;而 block 又自动的 retain 了 imgView,所以就造成了 Retain Cycle。解决方法就是用 `__block` 告诉 block 不要 retain 引用的对象: ``` objc __block UIImageView *imgView = [[UIImageView alloc] initWithFrame:rect]; [imgView setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { // ... imgView.image = image; }]; ``` 还有一种情况,block 里引用的对象是 self 或者 self.property,解决方法同理: ``` objc __block MyClass *myClass = self; operation.completeBlock = ^(NSInteger index) { [myClass doOther]; }; self.imgView = [[UIImageView alloc] initWithFrame:rect]; __block UIImageView *tmpView = _imgView; [_imgView setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { tmpView.image = image; }]; } ``` #### ARC 在 ARC 下不能用 `__block` 关键字,取而代之的是 `__weak` 或者 `__unsafe_unretained`。其中 `__weak` 只能 iOS 5+ 使用,`__unsafe_unretained` 支持 iOS 4。如果 App 不需要考虑 4.x 用 `__weak` 会更好一些,`__weak` 修饰的对象释放后会被设置为 nil,而 `__unsafe_unretained` 会继续指向原来的内存。 ``` objc __block MyClass *myClass = self; // MRC __weak MyClass *myClass = self; // ARC & iOS 5+ __unsafe_unretained MyClass *myClass = self; // ARC & iOS 4. ``` 一些参考文章: * [iOS blocks - 三個會造成retain cycle的anti patterns](http://popcornylu.blogspot.jp/2012/02/3-anti-patterns-which-lead-memory-leaks.html) * [Friday Q&A 2010-04-30: Dealing with Retain Cycles](http://www.mikeash.com/pyblog/friday-qa-2010-04-30-dealing-with-retain-cycles.html) * [ASIHTTPRequest Using blocks](http://allseeing-i.com/ASIHTTPRequest/How-to-use#using_blocks) * [ARC - The meaning of __unsafe_unretained?](http://stackoverflow.com/a/8593731/380774) * [IOS中的block和retain cycle](http://lcwangchao.github.io/IOS/2012/07/16/block_retain_cycle/) [1]:https://developer.apple.com/library/ios/documentation/cocoa/Conceptual/Blocks/Articles/bxVariables.html#//apple_ref/doc/uid/TP40007502-CH6-SW4 <file_sep>/_posts/2018-05-15-app-store-front-code.markdown --- layout: post title: App Store Front Code date: 2018-05-15 15:40:02 +0800 --- `X-Apple-Store-Front` header is needed to scrape in App Store. ```sh // 29 or 26 or 9 CN 143465-19,29 US 143441-1,29 JP 143462-9,29 KR 143466-13,29 HK 143463-18,29 AU 143460,29 TW 143470-18,29 CA 143455-6,29 DK 143458-2,29 RU 143469-16,29 ID 143476-2,29 TR 143480-2,29 GR 143448-2,29 DE 143443-4,29 IT 143450-7,29 NO 143457-2,29 FR 143442-3,29 TH 143475-2,29 SE 143456-17,29 FI 143447-2,29 GB 143444,29 NL 143452-10,29 BR 143503-15,29 PT 143453-24,29 MX 143468-28,29 ES 143454-8,29 VN 143471-2,29 ``` App info: ```sh curl -H 'x-apple-store-front: 143465-19,29' 'https://itunes.apple.com/cn/app/id1318151064?mt=8' ``` Top Free iPhone Apps: ```sh curl -H 'x-apple-store-front: 143465-0,9' 'https://itunes.apple.com/WebObjects/MZStore.woa/wa/topChartFragmentData?popId=27&pageNumbers=0&pageSize=1000' curl -H 'x-apple-store-front: 143465-19,29' 'https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewTop?id=25204&popId=27&genreId=36' ``` Rating & reviews: ```sh curl -H 'x-apple-store-front: 143441-0,9' 'https://itunes.apple.com/us/customer-reviews/id284882215?dataOnly=true&displayable-kind=11' curl -H 'x-apple-store-front: 143441-1,29' 'https://itunes.apple.com/us/customer-reviews/id284882215?dataOnly=true&displayable-kind=11' curl -H 'x-apple-store-front: 143441-1,29' 'https://itunes.apple.com/WebObjects/MZStore.woa/wa/userReviewsRow?id=284882215&displayable-kind=11&startIndex=0&endIndex=100&sort=1' ``` Search: ```sh curl -H 'x-apple-store-front: 143441-1,29' 'https://itunes.apple.com/WebObjects/MZStore.woa/wa/search?clientApplication=Software&term=NBA' curl -H 'x-apple-store-front: 143441-1,29' 'https://search.itunes.apple.com/WebObjects/MZSearchHints.woa/wa/trends?maxCount=10' curl -H 'x-apple-store-front: 143465-1,29' 'https://search.itunes.apple.com/WebObjects/MZSearchHints.woa/wa/hints?clientApplication=Software&term=NBA' ``` <file_sep>/_posts/2015-08-01-28.markdown --- layout: post title: '28' date: 2015-08-01 23:14:01 +0800 --- 28. 六六陪爸爸过的第一个生日,妈妈代笔写了贺卡,我 28 了。 <file_sep>/_posts/2010-10-18-memcache-using-notes.markdown --- layout: post title: "Memcache using notes" --- > telnet 127.0.0.1 11211 Commands: > get/set/add/replace/append/prepend/incr/decr/delete > flush_all > stats cmd_get 查询缓存操作,uptime 是运行秒数,cmd_get/uptime 是平均每秒请求缓存次数。 缓存命中率 = `get_hits/cmd_get` <file_sep>/_posts/2013-01-22-port-forwarding-using-ipfw-on-os-x.markdown --- layout: post title: "OS X 下用 IPFW 作端口转发" date: 2013-01-22 23:51 --- 用 ipfw 监听本地 80 端口然后转发到 8080 等端口,方便本地开发时调试操作。ipfw 是 OS X 自带的防火墙程序,类似 Linux 下的 iptables。 1. 查看当前 ipfw 规则: > sudo ipfw show 1. port 80 to 8080 forward: > sudo ipfw add 100 fwd 127.0.0.1,8080 tcp from any to any 80 in 1. 清除 ipfw 规则 > sudo ipfw flush Done. via [Port Forwarding (80 to 8080 for Tomcat) Using IPFW on Mac OSX](http://obscuredclarity.blogspot.jp/2011/05/port-forwarding-80-to-8080-for-tomcat.html) <file_sep>/_posts/2009-02-21-here-is-the-score.markdown --- layout: post title: "考研成绩出来了" --- RT,昨晚上一点多的时候论坛里说可以查分了,查了一下: ``` 政治 外语 数一 专业课 总分 62 45 45 73 225 ``` 跟自己的估计差不多,第一天的两门正常吧,英语的作文写的有点跑题;第二天上午的数学崩溃掉,脑子空空如也,都是很正常的题目,平时在下面练习的很顺手的东西,写不出来,当时在考场上就想着交卷走人,还是忍住了,坚持到最后;由于上午的崩盘,下午的专业课算是半放弃了,没有好好的写完,不完美的结束了考研经历,结果当然也不会完美。 经历过就行了,不多想了,好好准备找工作吧。在这里留个记录,给若干年后的自己有个后悔的机会,曾经不是很努力的考研经历带来的这个结局;当然,若干年后也有一个不后悔的机会,坚持到了最后,经历过那种心理折磨,成长的经历吧,只有自己知道。 <file_sep>/_posts/2022-11-13-opinion-on-lua.markdown --- layout: post title: Opinion on Lua date: 2022-11-13 17:58:23 +0800 --- > *power but poor, very host limited* <file_sep>/_posts/2011-02-27-ios-didreceivememorywarning.markdown --- layout: post title: "didReceiveMemoryWarning" --- 当系统警告内存紧张的时候,在这里释放相关不需要的资源。 > Release any cached data, images, etc. that aren't in use. <file_sep>/_posts/2013-09-18-give-up-dev-control.markdown --- layout: post title: "Dev 放权" date: 2013-09-18 22:55 --- 最近的一点反思。 着重技术往 Dev Leader 转型的过程中,老是做不到技术放权。新需求和问题过来第一反应往往是自己怎么去做,原因有二: 1. 不自信。自己技术不懂不熟,所以想借实战强化;刚学到一个新技术点想实用一次,毕竟技术性调研和实际项目应用差别还是很大。这种情况多出现在新项目。 1. 不信任。对事不对人的说,项目紧,其他人对业务不是特别熟悉,所以很不放心把东西交出去做。 结果就是自己排了很多 tickets,很容易拖累进度,而其他人对业务继续不熟悉。 以后要加多 Code Reivew,前期系统设计多参与,后期实现时多跟进把控,具体实现大家一起完成,强化整体架构能力。 <file_sep>/_posts/2017-05-28-pushd-popd-dirs.markdown --- layout: post title: pushd / popd date: 2017-05-28 11:09:15 +0800 --- `cd -` can goto last directory that you just leave, `-` means `$OLDPWD`. This only support one directory. `pushd / popd / dirs` works on multiple directories, as a directory stack: ``` pushd [dir1] # add dir to stack popd [dir1] # pop dir from stack dirs # list stack dirs -c # cleanup stack ``` <file_sep>/_posts/2014-12-30-self-review-2014.markdown --- layout: post title: "[self review:2014]" date: 2014-12-30 20:43:41 +0800 --- 2014 年度个人总结,先对照去年计划: #### 工作 > 产品、管理的转型,提高执行力。 Properly Failed. > 技术深度的挖掘。 Failed. > 一年一门新语言,Golang. Just done. ---- #### 工作 > 瓶颈 由于个人原因,下半年的工作状态不好,对工作造成了很大影响,很不应该。 工作以业务开发为主,针对具体问题需求会有一些学习,但整体技术进步很有限。结果就是工作兴奋度不够,持续性差,缺乏成就感,工作以外的学习又流于表面,不够深入,一直在尝试打破这种状况,但效果不好,执行力不够是主要原因。 目前这种状况是自己的一个瓶颈期,要尽量解决好个人问题,减少对工作的影响。提高执行力和专注度,以技术为主,多学习多实践,向开发 leader 甚至架构的方向努力。 #### 生活 升级做爸爸。 因为现在没有和六六待在一起,对我们生活有很大影响,主要是情绪上,时不时的状态低落。过了年就要想办法带六六过来,一家人就是要在一起。 在不同阶段会面临不同问题,要敢于面对,可以想的大一些,但不要想太多,不要试图用一个方案去解决所有问题。 ---- 2015 #### 工作 1. Golang 进入团队技术栈,结合实际项目要有更多学习。 1. 分布式开发,要有实际产出。 1. 代码质量保证上继续摸索一些适合团队的方案,Unit Test, CI 等。 1. leader 去澳洲移民监,要担起开发团队的责任,不光光是自己有代码产出。 #### 生活 1. 家。 1. 减肥,现在是 88kg,目标 75kg。 <file_sep>/_posts/2008-03-16-drinking.markdown --- layout: post title: "喝酒爽了一下" --- 好久没有喝酒爽过了,今晚上好不容易有个机会,其实也没有喝多少,5瓶啤酒而已,根本不算什么的,结果还有晕乎了,挺有感觉的,不错。 不过可惜的就是,居然沦落到喝3.1度的“山水”啤酒,真的很水啊,汽水一般的东西,连08奥运之星都比不上,好怀念洛阳宫的感觉啊,谁请我喝酒啊? <file_sep>/_posts/2012-11-21-new-objective-c-literals.markdown --- layout: post title: "New Objective-C Literals" date: 2012-11-21 21:17 --- NSArray: ``` objc NSInteger _appid = 12345; NSArray *array = @[ @"title", @(_appid)]; NSString *title = array[0]; array[0] = @"newTitle"; ``` NSDictionary: ``` objc NSDictionary *dict = @{ @"appid" : @(_appid), @"title" : _title, }; NSString *title = dict[@"title"]; dict[@"title"] = @"newTitle"; ``` NSNumber: ``` objc NSNumber *intNum = @123; NSNumber *floatNum = @1.23f; NSNumber *boolNum = @YES; ``` More: [Objective-C Literals](http://clang.llvm.org/docs/ObjectiveCLiterals.html) <file_sep>/_posts/2008-07-09-prison.markdown --- layout: post title: "囚..." --- 囚。。。 ![](https://lh4.googleusercontent.com/-Iuey5ptRs8s/U-t8eE4m3hI/AAAAAAAAGag/VfZiRC_x9Tg/w500-h334-no/2.jpg) 借用一下,谢谢,原地址:[兔子月月](http://www.bababian.com/set/3/A5503F5B723D73E7798C6CB47D4FEC9EDS) <file_sep>/_posts/2015-02-28-monthly-review-1502.markdown --- layout: post title: Monthly Review 2015-02 date: 2015-02-28 22:16:17 +0800 --- 1. 从 2.14 休假到月底,等于这个月只工作了半个月。 2. 个人习惯,长假前三五天代码库冻结,除了 typo 级别的修改,其他全部延迟安排到假期后,这样算下来代码的时间就更少了。 3. 然后就有了更多时间阅读学习,看了不少 Go 相关的,结合之前项目加深理解。 4. 休假前推进完成服务迁移,长假期间没有出现一次问题,省心很多,更放心的玩耍。 5. 算下来今年春节是这几年休假时间最长的,狠狠的陪六六半个月。 6. 小孩子一天一个样,刚回去还没长牙,一周后露头,等走的时候已经很明显能看到小嫩牙。 7. 车子成了现在人的身份象征,甚至高于房子。没人关心你做什么,追求什么,累不累,单纯的根据车子判断你的成功,大家似乎也很高兴用车子来证明自己。 <file_sep>/_posts/2010-05-31-smartphone-nowadays.markdown --- layout: post title: "现在的智能机" --- 今天老张拉着我扯了半天的手机,他想换个手机,在各种纠结。纠结于 BB9700 还是 Android 系列,啰嗦两句现在智能机我的看法。 现在手机在用的是 BB8705,06 年的黑莓老机子,没有 Wifi、内存卡、摄像头、GPS,我依然玩的是不亦乐乎,每天都让丫头训我回到家只会玩手机。如果现在再买智能机还会考虑黑莓吗?会,黑莓的多任务是现在智能机做的最好的,全键盘自然不必说,黑莓第二没人敢称第一。倒是黑莓稳定性安全性第一的原则让一些应用程序不是很方便,比如点讯输入法,只能是外挂形式。黑莓是拿来用的手机。 Android 系现在是井喷啊,不过还没有一个完美的机子,我自己的看法:MileStone > Nexus One > HTC Desire > Hero,不过过于山寨的方向键和没有独立数字键让 MS 略感不完美。期待 Droid 2。A 系现在有点混乱,自己跟自己打架。 iPhone 4 是现在我最期待的手机了,iOS 4 合理的多任务加上三四年的良性稳定发展加上丰富的 Apps,机皇。就是价高,攒钱吧。 <file_sep>/_posts/2008-05-14-building-os.markdown --- layout: post title: "做系统" --- 上次做了系统好像是去年十一假期结束吧,也是忙了一个下午好像,然后信誓旦旦的说:一年之内不再做系统!噢耶,我反悔了。。。半年多了,该重新做一个了。喜欢说做系统,不说重装。因为重装来说,真的没啥技术上太大的难度了,想快的话ghost5分钟搞定,慢的半个小时肯定结束,但这不是重点,怎么在重装以后优化到自己喜欢的状态才是麻烦,所以一直都不怎么想做系统,半年了啊,搁在往前谁知道让我做了几次了。 关于安装盘。一直不喜欢ghost,不是所有人的电脑配置都一样,用ghost,多多少少会有点问题,毕竟用别的机子做了系统再ghost到自己电脑上不是很放心,系统稳定性是个很大的问题,so。精简版的也不怎么喜欢,虽然大多数精简版都是把一些不常用的系统组件,多余的驱动备份文件,多余的语言包文件等等东西给删掉,精简系统体积,语言文件之类的到没什么,驱动备份这些就有点麻烦,说不定啥时候就用上了,精简掉的组件也是不确定状态,用到的时候发现没有就尴尬了,so。那就只好纯净版安装盘了。 * firefox的个人配置文件放回去,`C:\Documents and Settings\Heyward\Application Data\Mozilla`,火狐配置是最难受的,插件虽然可以重装上去,但是一些个人设置就比较麻烦了,还有about:config里修改的东西,索性就是直接恢复了个人配置省事,不然自己慢慢弄会死人的。 * 安全上的,装上ssm,nod32,不喜欢裸奔,安全是一个问题,形象更是个问题,叫人看见多不好。再说了,在校园网这种环境,真的得小心,U盘病毒多了去了,一不小心就下水了。 * 我的文档移动,关上系统还原,出事了多半是做了它,没工夫还原。 * 优化系统,主要是系统服务开启设置,这个就是仁者见仁,智者见智的事了,总的来说没有最好的,只有最适合自己的,系统用的时间长了,优化也就有了点小毛皮,自己不需要的服务可以选择关闭,对于不是很确定的可以设为手动,这样如果下次开启了的话就是要用到的。也可以多Google百度一下每个服务的具体用途,看情况定。还有个小巧门,对于服务属性是手动而开机后又自动启动的服务可以设置为自动,这样开机速度有提高,尤其是出现欢迎界面后到进入桌面,相当快! * 安装应用软件,大多数都可以绿色使用,如果配置文件跟火狐一样在Application Data下面,可以在装系统之前备份再恢复,非常方便。7-zip,Office 2007,Google拼音,Google金山词霸,WLM,WLW,media 11,装上IE7配The World,配置一下AutoHotkey,Clipx,慢慢来,有些东西用到时候再装也不迟。 * 装完乱七八糟的东西,重启一次,然后用CCleaner清理一下系统,习惯做完系统整理一下磁盘,清理一下磁盘碎片,AusLogicsDiskDefrag,个人感觉还不错。 <file_sep>/_posts/2015-10-01-monthly-review-1509.markdown --- layout: post title: Monthly Review 2015-09 date: 2015-10-01 10:01:46 +0800 --- 1. 新项目管理后台开发,依然是 Angular+Material,npm+browsersync+jshint+tern,这套组合目前很对我的胃口,开发效率不错。 2. 感叹前端的飞速发展,一下发现新东西,比如 tern,tsd,再一下发现在用的东西已经过时,比如最近在流行 React+Alt+Flux,Angular 2 再不出来真的连汤都没了。 3. 社区项目维护开发,居然也有小 30 commits,服务性能上有一些提升。 4. 苹果出新手机,然并卵,毕竟穷。电脑升级新系统,看起来可以再战一年,如果不开 XCode 的话。 5. 十一回家,最高兴的是,刚到家的时候六六自己跑过来抱抱,那一刻心都化了。 <file_sep>/_posts/2017-06-14-converting-myisam-to-innodb.markdown --- layout: post title: Converting MyISAM to InnoDB date: 2017-06-14 11:36:11 +0800 --- ![](http://mysql.taobao.org/monthly/pic/2016-03-10/engine.png) 如果数据量小且不在服务中,可以直接修改表结构: ``` ALTER TABLE table_name ENGINE=InnoDB; ``` 然后现实是需要迁移表的数据量往往很大,不好直接 ALTER。一个办法是导出-修改表结构-导入,需要修改的有表名,engine,导入后重命名新/旧表。需要注意的是 mysqldump 默认有 `DROP TABLE` 命令,需要去掉,不然导入时候会直接删掉旧表。 还有一个方法是按照旧表结构新建表,将数据从旧表导入新表: ``` CREATE TABLE innodb_table LIKE mytable; ALTER TABLE innodb_table ENGINE=InnoDB; INSERT INTO innodb_table SELECT * FROM mytable; ``` 数据量大的话可以事务处理: ``` START TRANSACTION; INSERT INTO innodb_table SELECT * FROM mytable WHERE id BETWEEN x AND y; COMMIT; ``` 数据验证完整后重命名: ``` RENAME TABLE mytable TO mytable_old, innodb_table TO mytable; //DROP TABLE mytable_old; ``` * [Converting Tables from MyISAM to InnoDB](https://dev.mysql.com/doc/refman/5.7/en/converting-tables-to-innodb.html#innodb-convert-convert) * [Converting big table from MyISAM to Innodb](https://serverfault.com/q/51982/103081) <file_sep>/_posts/2015-02-04-golang.markdown --- layout: post title: Go 初体验 date: 2015-02-04 17:31:59 +0800 --- 用 Go 写了第一个线上服务,简单记录一些。 1. 直接 `net/http`,没有用 Web 框架。之前用过 Beego,强大但过于黑盒,很多细节不理解,其实 Go 已经提供了 web 开发所需要的东西,这个服务只需对外 API,没有页面等,直接 `net/http` 反而更简单。 1. 强制代码风格,大爱,包括定义但不使用直接报错,刚开始会有不适应,但是对整体代码质量很有帮助。 1. `database/sql` 提供了统一的数据库操作接口,配上不同的 driver 即可。 1. Golang 的 error handlling 是个特色,但作为 web service 有些繁琐,需要再学习看有没有更为简洁的处理方式。 1. 无痛热更新比较麻烦,还没有找到类似 Nginx 的实现。 1. 性能上简单的 ab 压测和 ngx_lua 差距不大,开发效率相对高一些,毕竟自带库更丰富。 1. [gin][1] 可以监控代码变化并自动重新编译,代理方式,不错的开发辅助工具。 [1]:https://github.com/codegangsta/gin <file_sep>/_posts/2016-02-29-monthly-review-1602.markdown --- layout: post title: Monthly Review 2016-02 date: 2016-02-29 16:00:57 +0800 --- 1. 上旬休年假。年前先是六六感冒,然后我发烧两天,年后又走得早,这个年假好忙好累。 2. 初一中午下厨给家人做饭,红烧排骨,青椒酿肉,味道很赞。 2. APNS 支持 http2,用 Go 改造现有的推送服务。 3. 着手收拾房子,计划是简单刷墙,两居改三居,换新家电。 <file_sep>/_posts/2015-01-22-hololens.markdown --- layout: post title: HoloLens external-url: http://www.microsoft.com/microsoft-hololens/en-us date: 2015-01-22 18:06:03 +0800 --- > When you change the way you see the world, you can change the world you see. <file_sep>/_posts/2010-08-05-imagemagick-notes.markdown --- layout: post title: "ImageMagick Notes" --- - 尺寸缩放 > convert -resize 640x960 input.jpg  output.jpg > convert -resize 75% input.jpg  output.jpg - 去除多余 Exif 等信息 > convert -strip input.jpg output.jpg - 调节压缩比例 > convert -quality 75% input.jpg output.jpg <file_sep>/_posts/2009-02-26-could-not-find-the-main-class.markdown --- layout: post title: "Could not find the main class问题" --- 因为毕业设计要用到jsp,这两天在准备着搭Java环境。下午把JDK装上,配置好path,classpath和java_home几个环境变量,然后随手用EmEditor中自带的Java模板自动生成了一个hello world函数,测试一下JDK是否装好。 ``` hello.java class Hello { public static void main(String args[]) { System.out.println("Hello, world!"); } } ``` 编译:`javac hello.java`,顺利通过,然后运行:`java hello`,报错: ``` Exception in thread "main" java.lang.NoClassDefFoundError: …… Could not find the main class: hello. Program will exit. ``` 编译能通过,不能运行,这个报错生生折腾了我两个小时,起初以为是环境变量没设好,改了N次,仍然是报错,气得半死。Google的时候说Java严格区分大小写,就留心了一下,果然是这个问题。类名是calss Hello,大写,文件名却是 hello.java,小写,编译的时候javac不区分大小写,所以编译通过,生成 Hello.class 文件,运行的时候却是java hello,与类名不符,进而 could not find the main class,所以报错。 教训啊,一定要注意,Java里文件名要和main class类名完全一致,大小写严格区分。还有,写程序时候遇见错误一定要心平气和的去debug,越急躁越不行;也要注意写程序的细节问题,细节决定成败。 <file_sep>/_posts/2010-05-20-delphi-format-function.markdown --- layout: post title: "Delphi Format function" --- function Format ( Const Formatting : string; Const Data : array of const ) : string; > Rich formatting of numbers and text into a string. Const **Formatting** 参数是一个格式字符串,用于格式化 Const **Data** 数组里面的值。 Formatting 参数的指令格式以"%"开始,以 Type 结束,Type 表示一个具体的数据类型。中间是用来格式化 Type 类型的指令字符,是可选的。 > `%[Index:][-][Width][.Precision]Type` Type 的类型包括: d = Decimal (integer),整型值; u = Unsigned decimal,无符号整型值,如果它对应的值是负的,则返回时是一个2的32次方减去这个绝对值的数。 > `Format('this is %u',[-2]);===>this is 4294967294` f = Fixed,浮点数; e = Scientific,科学记数法表示; g = General,浮点型,会将值中多余无效的数去掉。 > `Format('this is %g',[02.200]);===>this is 2.2` n = Number (floating),浮点型,会将值转化为号码的形式(默认只表示到小数后两位)。 > `Format('this is %n',[4552.2176]);===>this is 4,552.22` m = Money,钱币类型; p = Pointer,指针类型,返回的值是指针的地址,以十六进制表示; s = String,对应字符串类型; x = Hexadecimal,必须是一个整形值,以十六进制的形式返回; 格式化 Type 的指令: `[index:]` 指示 Const **Data** 中参数显示的顺序: > `Format('this is %1:d %0:d',[12,13]);===>this is 13 12` > `Format('%d %d %d %0:d %3:d', [1, 2, 3, 4]);===>1,2,3,1,4` `[width]` 指定将被格式化的值占的宽度,默认右对齐,`[-]` 指定向左对齐: > `Format('this is %4d',[12]);===>this is __12` (__下划线是不存在的,只是为了显示这里空了两格) > `Format('this is %-4d',[12]);===>this is 12__` `[.Precision]` 指定精度: > `Format('this is %.7f',['1.1234]);===>this is 1.1234000` <file_sep>/_posts/2018-02-09-fastlane-notes.markdown --- layout: post title: fastlane notes date: 2018-02-09 13:59:47 +0800 --- `gem install fastlane -NV`. fastlane match: 1. `fastlane match init` 初始化生成 `Matchfile`,设置私有仓库来保存密钥和证书。 2. `fastlane match development/appstore` 同步或生成证书及描述文件,多 target 可以通过 `--git_branch` 指定 3. `fastlane match nuke distribution` 吊销证书 `fastlane gym --scheme X` 编译打包。 `fastlane pilot upload` 上传 TestFlight. `fastlane deliver` 上传 iTC.<file_sep>/_posts/2010-06-18-you-and-me.markdown --- layout: post title: "You and me" --- 你不坚强时候有我在,我不坚强时候有你在,这就够了。 <file_sep>/_posts/2015-09-08-ctrlp.vim.markdown --- layout: post title: CtrlP.vim date: 2015-09-08 15:38:32 +0800 --- ctrlp.vim 是个非常棒的 vim 插件,可模糊搜索文件、buffer、mru 等等,原生 vim-script,相比 Command-T 更为友好的安装,速度上也没有差多少,所以[几年前][1]知道这个插件就一直在用,最近才发现原作者从 2013 年就不再维护更新,另一个社区版更为活跃,也加了不少新功能。 社区版地址 [ctrlpvim/ctrlp.vim][2],支持扩展功能,也就是 vim 插件的插件,其中 [ctrlp-funky][3] 可以在当前文件内定义的方法之间跳转,类似 Tagbar/Taglist,但不依赖于 ctags,算是个精简版。 ``` Plugin 'ctrlpvim/ctrlp.vim' Plugin 'tacahiroy/ctrlp-funky' let g:ctrlp_extensions = ['funky'] let g:ctrlp_funky_syntax_highlight = 1 :com! -n=0 D CtrlPFunky nnoremap <Leader>fu :CtrlPFunky<Cr> nnoremap <Leader>fU :execute 'CtrlPFunky ' . expand('<cword>')<Cr> ``` [1]:https://github.com/fannheyward/vimrc/commit/16c18325ac5edb67c78df2f67be33631576e68b1 [2]:https://github.com/ctrlpvim/ctrlp.vim [3]:https://github.com/tacahiroy/ctrlp-funky<file_sep>/_posts/2009-03-11-untitled.markdown --- layout: post title: "无题" --- 第一次想不出题目,无题。 这两天过得有点压抑,因为找工作的原因。很多时候我们看似简单的事情是因为没有身在其中,当把你放进去的时候,压抑的难以呼吸。周一双选会,因为之前针对拓普郑州那边的专门准备了一下,也就只投了拓普一家。现场因为人太多,没有过多的交流,每个人填一张个人信息表,然后让回去等通知。有点打乱我的计划,本来以为现场面试什么的话可以好好介绍一下自己的一些东西,现在只好回去等通知。两天了,一点消息没有,不停地刷邮箱,从来手机都是震动的我这两天也调了声音,生怕错过一丁点消息。有点强迫症的感觉,没办法。拓普这个机会挺好的,在郑州,很方便,又是做网络编程方面的,虽然是 J2EE 方面,没有什么大项目实际经验,不过自己兴趣在网络编程这一块,有兴趣再加上 Java 基础,上手不是问题。可现在的问题是你上手的机会还不知道有没有。。。再等等。 上午有一家北京的公司直接到学院里招人,实习参观回来就直接过去了,有点晚,没有听到他们的宣讲,过去就让自己介绍一下,稀里糊涂说了一些,过了好久才知道人家要 .NET 方面的,自己拿着 PHP、JSP 说了一通,哎,看进展吧。 <file_sep>/_posts/2010-08-22-python-zip-function.markdown --- layout: post title: "Python zip function" --- The built-in zip function can be used, well, to zip lists together. It returns a list of tuples, where the nth tuple contains the nth item from each of the passed in lists. ``` letters = ['a', 'b', 'c'] numbers = [1, 2, 3] squares = [1, 4, 9] zipped_list = zip(letters, numbers, squares) # zipped_list contains [('a', 1, 1), ('b', 2, 4), ('c', 3, 9)] ``` via [Combining Multiple Lists, Item by Item](http://www.siafoo.net/article/52#combining-multiple-lists-item-by-item) <file_sep>/_posts/2010-04-13-delphi-adodataset-append-delete-select-edit.markdown --- layout: post title: "Delphi ADODataset 增删查改" --- //Select/Refresh ``` ADODataset1.Active := false; ADODataset1.CommandText := 'select * from Table_1'; ADODataset1.Active := true; ``` //Add ``` ADODataset1.Append; ADODataset1.Fieldbyname('ID').Value := edit1.Text; ``` //Delete ``` ADODataset1.Delete; ``` //Update ``` ADODataset1.Edit; ADODataset1.Fieldbyname('ID').Value := edit1.Text; ADODataset1.Post; ``` <file_sep>/_posts/2008-07-04-if-not-you.markdown --- layout: post title: "《如果没有你》" --- 听歌,任贤齐《如果没有你》,想丫头了。。。 ``` 一直把你手握在手里 舍不得你的我要远行 只是我唯一心愿 就是能陪你到永远 我知道会有一天 如果没有你如果没有你提醒 在混乱的世界里 会不会淹没了我自己 如果没有你如果没有你相信 我能不能依旧如此坚定 ```
744a01d1e4076af04859b28c457dc5528b1f8245
[ "Markdown", "JavaScript", "Dockerfile", "Ruby" ]
518
Markdown
fannheyward/fannheyward.github.io
d8cf04dbded8cd917e9976c9e50bcfb80fbf5fd0
3adeb76b2981b2a1762966e0cf4cab3d026dce7a
refs/heads/master
<file_sep>import { Project } from "ts-morph"; export class CurrentProject { project: Project; constructor () { this.project = new Project(); } }<file_sep>export { FileSystemReader, Reader } from './utils/fs-reader';<file_sep>const fs = require('fs'); const path = require('path'); export function getAngularType(typescript) { return typescript.match(/^@Component\(/m) ? 'Component' : typescript.match(/^@Directive\(/m) ? 'Directive' : typescript.match(/^@Injectable\(/m) ? 'Injectable' : typescript.match(/^@Pipe\(/m) ? 'Pipe' : undefined; } export function getEjsTemplate(type) { let ejsFile; switch (type) { case 'Component': case 'Directive': case 'Pipe': case 'Injectable': const typeLower = type.toLowerCase(); ejsFile = path.join(__dirname, '../', 'templates', `${typeLower}.spec.ts.ejs`); break; default: ejsFile = path.join(__dirname, '../', 'templates', `default.spec.ts.ejs`); break; } return fs.readFileSync(ejsFile, 'utf8'); } export function getImportLib(mports, className) { let lib; mports.forEach(mport => { if (mport.specifiers) { mport.specifiers.forEach(el => { // e.g. 'Inject', 'Inject as foo' if (el.indexOf(className) !== -1) { lib = mport.from; // e.g. '@angular/core' } }); } else { lib = mport.from; } }); return lib; } export function reIndent(str, prefix = "") { let toRepl = str.match(/^\n\s+/)[0]; let regExp = new RegExp(toRepl, 'gm'); return str.replace(regExp, "\n" + prefix); } export function createBackupFile(filePath) { const ext = (new Date()).toISOString().replace(/[^\d]/g, '').slice(0, -9); const contents = fs.readFileSync(filePath, 'utf8'); fs.writeFileSync(`${filePath}.${ext}`, contents, 'utf8'); } module.exports = { getAngularType, getEjsTemplate, getImportLib, reIndent, createBackupFile }; <file_sep>export * from './lib/test-ngine'; <file_sep>import { getImportLib, reIndent } from './scripts/util.js'; import * as path from 'path'; export function getServiceData(tsParsed, filePath) { let result = { className: tsParsed.name, classParams: [], imports: { [ `./${path.basename(filePath)}`.replace(/.ts$/, '') ]: [ tsParsed.name ], // the directive itself }, mocks: {}, functionTests: {} }; // // Iterate constructor parameters // . create mocks and constructor parameters // (tsParsed.constructor.parameters || []).forEach(param => { // name, type, body //param.type, param.name, param.body result.mocks[ param.type ] = reIndent(` const ${param.name}: any = { // mock properties here } `, ' '); result.classParams.push(param.name); }); // // Iterate methods // . Javascript to call the function with parameter; // for (var key in tsParsed.methods) { let method = tsParsed.methods[ key ]; let parameters = (method.parameters || []).map(el => el.name).join(', '); let js = `${key}(${parameters})`; (method.type !== 'void') && (js = `const result = ${js}`); const testName = `should run #${key}()`; result.functionTests[ testName ] = reIndent(` it('${testName}', async () => { // ${js}; }); `, ' '); } return result; } <file_sep>const ts = require('typescript'); const fs = require('fs'); const path = require('path'); const assert = require('assert'); const defaultCompileOptions = { noEmitOnError: true, experimentalDecorators: true, target: ts.ScriptTarget.ES2016, module: ts.ModuleKind.CommonJS }; export function createProgram(param1, options) { if (Array.isArray(param1)) { const fileNames = param1; return ts.createProgram(fileNames, options); } else { const sourceString = param1; let compilerHost = createCompilerHost(options, sourceString); compilerHost.getSourceFile = function getSourceFile(fileName, languageVersion, onError) { if (fileName === 'inline.ts') { return ts.createSourceFile(fileName, sourceString, languageVersion); } else { const sourceText = ts.sys.readFile(fileName); return sourceText !== undefined ? ts.createSourceFile(fileName, sourceText, languageVersion) : undefined; } } return ts.createProgram(['inline.ts'], options, compilerHost); } } export function createCompilerHost(options, sourceString) { return { getSourceFile: (fileName, languageVersion, onError) => { if (fileName === 'inline.ts') { return ts.createSourceFile(fileName, sourceString, languageVersion); } else { // it's also used to search other source file, e.g. lib.d.ts const sourceText = ts.sys.readFile(fileName); return sourceText !== undefined ? ts.createSourceFile(fileName, sourceText, languageVersion) : undefined; } }, getDefaultLibFileName: () => ts.getDefaultLibFilePath(options), writeFile: (fileName, content) => ts.sys.writeFile(fileName, content), getCurrentDirectory: () => ts.sys.getCurrentDirectory(), getDirectories: (path) => ts.sys.getDirectories(path), getCanonicalFileName: fileName => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(), getNewLine: () => ts.sys.newLine, useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames, fileExists: filaName => ts.sys.fileExists(fileName), readFile: readFile => ts.sys.readFile(fileName), resolveModuleNames: (moduleNames, containingFile) => { const resolvedModules = []; for (const moduleName of moduleNames) { // try to use standard resolution let result = ts.resolveModuleName(moduleName, containingFile, options, { fileExists: ts.sys.fileExists, readFile: ts.sys.readFile }); result.resolvedModule ? resolvedModules.push(result.resolvedModule) : console.error('ERROR', moduleName, containingFile); } return resolvedModules; } }; } export function getDiagnostics(program, printDiagnostics = false) { const emitResult = program.emit(); const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics); const diagnostics = []; allDiagnostics.forEach(diagnostic => { let code = diagnostic.code; let message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); if (diagnostic.file) { let fileName = diagnostic.file.fileName; let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start); let fileMessage = fileName ? `${fileName} (${line + 1},${character + 1}) :` : ''; diagnostics.push({ fileName, line, character, code, message }) printDiagnostics && console.log(fileMessage, 'TS' + code + ':', message); } else { diagnostics.push({ code, message }) printDiagnostics && console.log('TS' + code + ':', message); } }); return diagnostics; } export function compileTypescript(param1, options, printDiagnostics) { const mergedOptions = Object.assign(defaultCompileOptions, options || {}); const program = createProgram(param1, mergedOptions); const diagnostics = getDiagnostics(program, printDiagnostics); return diagnostics.length === 0; } // test with a typescript file // let tsFile = path.resolve(__dirname, '../', 'examples', 'my.component.ts'); // assert(compileTypescript([tsFile], null, true)); // test with a typescript source code // source = fs.readFileSync(tsFile, 'utf8'); // assert(compileTypescript(source, null, true)); <file_sep>import { getImportLib, reIndent } from './scripts/util.js'; import * as path from 'path'; import windowObjects from './scripts/window-objects.js'; export function getDirectiveData(tsParsed, filePath, angularType) { let result = { className: tsParsed.name, imports: { '@angular/core': [ 'Component', 'Directive' ], [ `./${path.basename(filePath)}`.replace(/.ts$/, '') ]: [ tsParsed.name ] // the directive itself }, inputs: { attributes: [], properties: [] }, outputs: { attributes: [], properties: [] }, providers: {}, mocks: {}, functionTests: {} }; // // Iterate properties // . if @Input, build input attributes and input properties // . if @Outpu, build output attributes and output properties // for (var key in tsParsed.properties) { const prop = tsParsed.properties[ key ]; if (prop.body.match(/@Input\(/)) { const attrName = (prop.body.match(/@Input\(['"](.*?)['"]\)/) || [])[ 1 ]; result.inputs.attributes.push(`[${attrName || key}]="${key}"`); result.inputs.properties.push(`${key}: ${prop.type};`); } else if (prop.body.match(/@Output\(/)) { const attrName = (prop.body.match(/@Output\(['"](.*?)['"]\)/) || [])[ 1 ]; const funcName = `on${key.replace(/^[a-z]/, x => x.toUpperCase())}`; result.outputs.attributes.push(`(${attrName || key})="${funcName}($event)"`); result.outputs.properties.push(`${funcName}(event): void { /* */ }`); } } // // Iterate constructor parameters // . if this pattern, `@Inject(PLATFORM_ID)`, // . add Inject, PLATFORM_ID to result.imports // . create provider with value // . if type is found at tsParsed.imports, // . add the type to result.imports // . if type is ElementRef, // . create a mock class // . add to result.providers with mock // . if source starts from './', which is a user-defined injectable // . create a mock class // . add te result.providers with mock // . otherwise, add to result.providers // (tsParsed.constructor.parameters || []).forEach(param => { // name, type, body // handle @Inject(XXXXXXXXX) const importLib = getImportLib(tsParsed.imports, param.type); const matches = param.body.match(/@Inject\(([A-Z0-9_]+)\)/); if (matches) { let className = matches[ 1 ] let lib1 = getImportLib(tsParsed.imports, 'Inject'); let lib2 = getImportLib(tsParsed.imports, className); result.imports[ lib1 ] = result.imports[ lib1 ] || []; result.imports[ lib2 ] = result.imports[ lib2 ] || []; result.imports[ lib1 ].push('Inject'); result.imports[ lib2 ].push(className); result.providers[ matches[ 1 ] ] = `{provide: ${className},useValue: 'browser'}`; } else if (param.type == 'ElementRef') { result.imports[ importLib ] = result.imports[ importLib ] || []; result.imports[ importLib ].push(param.type); result.mocks[ param.type ] = reIndent(` @Injectable() class Mock${param.type} { // constructor() { super(undefined); } nativeElement = {} }`); result.providers[ param.type ] = `{provide: ${param.type}, useClass: Mock${param.type}}`; } else if (param.type === 'Router') { result.imports[ importLib ] = result.imports[ importLib ] || []; result.imports[ importLib ].push(param.type); result.mocks[ param.type ] = reIndent(` @Injectable() class Mock${param.type} { navigate = jest.fn(); } `); result.providers[ param.type ] = `{provide: ${param.type}, useClass: Mock${param.type}}`; } else if (importLib.match(/^[\.]+/)) { // starts from . or .., which is a user-defined provider result.imports[ importLib ] = result.imports[ importLib ] || []; result.imports[ importLib ].push(param.type); result.mocks[ param.type ] = reIndent(` @Injectable() class Mock${param.type} { } `); result.providers[ param.type ] = `{provide: ${param.type}, useClass: Mock${param.type}}`; } else { result.imports[ importLib ] = result.imports[ importLib ] || []; result.imports[ importLib ].push(param.type); result.providers[ param.type ] = `${param.type}`; } }); // // Iterate properties // . if property type is a windows type // then create mock with (windows<any>) with the value of `jest.fn()`` // for (var key in tsParsed.properties) { let prop = tsParsed.properties[ key ]; let basicTypes = [ 'Object', 'boolean', 'number', 'string', 'Array', 'any', 'void', 'null', 'undefined', 'never' ]; let importLib = getImportLib(tsParsed.imports, prop.type); if (importLib || basicTypes.includes(prop.type)) { continue; } else if (windowObjects.includes(prop.type)) { result.mocks[ prop.type ] = reIndent(` (<any>window).${prop.type} = jest.fn(); `); } } // // Iterate methods // . Javascript to call the function with parameter; // for (var key in tsParsed.methods) { let method = tsParsed.methods[ key ]; let parameters = method.parameters.map(el => el.name).join(', '); let js = `${angularType.toLowerCase()}.${key}(${parameters})`; (method.type !== 'void') && (js = `const result = ${js}`); const testName = `should run #${key}()`; result.functionTests[ testName ] = reIndent(` it('${testName}', async () => { // ${js}; }); `, ' '); } return result; } <file_sep>import { getImportLib, reIndent } from './scripts/util.js'; import * as path from 'path'; export function getServiceData(tsParsed, filePath) { let result = { className: tsParsed.name, imports: { [ `./${path.basename(filePath)}`.replace(/.ts$/, '') ]: [ tsParsed.name ] // the directive itself }, functionTests: {} }; // // Run only one test, transform() // let method = tsParsed.methods.transform; let parameters = method.parameters.map(el => el.name); const testName = `should run #transform()`; result.functionTests[ testName ] = reIndent(` it('${testName}', () => { // const pipe = new ${tsParsed.name}(); // const result = pipe.transform(${parameters.join(', ')}); // expect(result).toBe('<<EXPECTED>>'); }); `, ' '); return result; } <file_sep>// From here: https://github.com/nestjs/nest-cli/blob/master/lib/readers/file-system.reader.ts import * as fs from 'fs'; export interface Reader { list(): string[] | Promise<string[]>; read(name: string): string | Promise<string>; readAnyOf(filenames: string[]): string | Promise<string | undefined>; } export class FileSystemReader implements Reader { constructor (private readonly directory: fs.PathLike) { } public async list(): Promise<string[]> { return new Promise<string[]>((resolve, reject) => { fs.readdir( this.directory, (error: NodeJS.ErrnoException | null, filenames: string[]) => { if (error) { reject(error); } else { resolve(filenames); } }, ); }); } public async read(name: fs.PathLike): Promise<string> { return new Promise<string>((resolve, reject) => { fs.readFile( `${this.directory}/${name}`, (error: NodeJS.ErrnoException | null, data: Buffer) => { if (error) { reject(error); } else { resolve(data.toString()); } }, ); }); } public async readAnyOf(filenames: fs.PathLike[]): Promise<string | undefined> { try { for (const file of filenames) { return await this.read(file); } } catch (err) { return filenames.length > 0 ? await this.readAnyOf(filenames.slice(1, filenames.length)) : undefined; } } }<file_sep>export const duck = 'duck';<file_sep>const fs = require('fs'); const TypescriptParser = require('typescript-parser').TypescriptParser; const parser = new TypescriptParser(); module.exports = async function parseTypescriptparseTypescript(fileOrTs, className) { let parsed, fileContents; if (fs.existsSync(fileOrTs)) { fileContents = fs.readFileSync(fileOrTs, 'utf8'); parsed = await parser.parseFile(filePath); } else { fileContents = fileOrTs; parsed = await parser.parseSource(fileOrTs); } // interface Ret extends class { }; let ret = { imports: [], properties: {}, methods: {} }; let klass; if (className) { klass = parsed.declarations.find(decl => decl.name === className); } else { klass = parsed.declarations.find(decl => decl.constructor.name === 'ClassDeclaration') klass = klass || parsed.declarations[ 0 ]; } ret.name = klass.name; // imports parsed.imports.forEach(mport => { let specifiers; // { libraryName: '@angular/core', specifiers: [Array], ... } if (mport.constructor.name === 'NamedImport') { let specifiers = (mport.specifiers || []).map(el => `${el.specifier}${el.alias ? ' as ' + el.alias : ''}`); ret.imports.push({ from: mport.libraryName, specifiers }); } // { libraryName: 'lodash', alias: '_', start: 51, end: 79 } else if (mport.constructor.name === 'NamespaceImport') { ret.imports.push({ from: mport.libraryName, as: mport.alias }); } }) // constructor let constructor = klass.ctor; if (constructor) { ret.constructor = {}; ret.constructor.parameters = (constructor.parameters || []).map(param => { return { name: param.name, type: param.type, body: fileContents.substring(param.start, param.end) }; }); ret.constructor.body = fileContents .substring(constructor.start, constructor.end) .match(/{([\s\S]*)\}$/m)[ 1 ]; } // properties (klass.properties || []).forEach(prop => { ret.properties[ prop.name ] = { type: prop.type, body: fileContents.substring(prop.start, prop.end) }; }); // methods (klass.methods || []).forEach(method => { ret.methods[ method.name ] = { type: method.type, parameters: (method.parameters || []).map(param => ({ name: param.name, type: param.type })), body: fileContents.substring(method.start, method.end).match(/{([\s\S]*)\}$/m)[ 1 ] } }) return ret; }
3953cc9012d38a99c85aa187daaa098a8c91ce02
[ "TypeScript" ]
11
TypeScript
ericbfriday/iowa
9096b285409d0298a1f9f1bb30da6f4aec784a43
a1853a89b7f785915ab776689a18fef77063558a
refs/heads/main
<repo_name>dsvalerian/palette-generator<file_sep>/README.md # palette-generator A simple-to-use web app for quickly creating beautiful color ramps and palettes. ## Description palette-generator is a web application built to allow users to quickly and simply design their own color palettes according to a small selection of variables. These variables are based on HSL colors, which provide users with easy-to-understand method for designing their own colors. This app is a work in progress, so not all planned features are implemented yet. ## Installing and Running Locally palette-generator is a React web app, so it requires some initial setup to be able to use it locally. The following instructions will be using `npm`, however other package managers like `yarn` may be used. #### Requirements - Node.js - npm #### Instructions - Clone this repo and navigate to the directory in your preferred shell - Run `npm install`. You should only have to do this once. - Run `npm start` to start the local development server. It should display the URL for accessing the app through a browser. - (Optional) Run `npm run build` to build an optimized production build. ## Technologies Used #### Frameworks - React - Semantic UI #### Languages - JavaScript - HTML - CSS <file_sep>/src/js/component/MainApp.js import React, {Component} from 'react'; import {Container} from 'semantic-ui-react'; import MainPageHeader from './MainPageHeader.js'; import RampPaletteSection from './RampPaletteSection.js'; class MainApp extends Component { constructor(props) { super(props); } /////////////////////// /// Render /////////////////////// render = () => { return( <Container> <MainPageHeader /> <RampPaletteSection /> </Container> ); } } export default MainApp;<file_sep>/src/js/component/PaletteBuilder.js import React, {Component} from 'react'; import {Segment, Header} from 'semantic-ui-react'; import ColorVariableSelection from './ColorVariableSelection.js'; class PaletteBuilder extends Component { constructor(props) { super(props); } /////////////////////// /// Render /////////////////////// render = () => { return( <Segment basic vertical padded> <Header as='h1'>PaletteViewer</Header> <ColorVariableSelection /> </Segment> ); } } export default PaletteBuilder;<file_sep>/src/js/util/ColorUtils.js /** * Converts an HSL color to its hex value. Found online. * @param {number} h The hue. * @param {number} s The saturation. * @param {number} l The lightness. * @returns {string} The hex value. */ const hslToHex = (h, s, l) => { s /= 100; l /= 100; let c = (1 - Math.abs(2 * l - 1)) * s, x = c * (1 - Math.abs((h / 60) % 2 - 1)), m = l - c/2, r = 0, g = 0, b = 0; if (0 <= h && h < 60) { r = c; g = x; b = 0; } else if (60 <= h && h < 120) { r = x; g = c; b = 0; } else if (120 <= h && h < 180) { r = 0; g = c; b = x; } else if (180 <= h && h < 240) { r = 0; g = x; b = c; } else if (240 <= h && h < 300) { r = x; g = 0; b = c; } else if (300 <= h && h < 360) { r = c; g = 0; b = x; } // Having obtained RGB, convert channels to hex r = Math.round((r + m) * 255).toString(16); g = Math.round((g + m) * 255).toString(16); b = Math.round((b + m) * 255).toString(16); // Prepend 0s, if necessary if (r.length == 1) r = "0" + r; if (g.length == 1) g = "0" + g; if (b.length == 1) b = "0" + b; return "#" + r + g + b; } /** * Limits an HSL color's properties to 0-360, 0-100, and 0-100 respectively. * @param {Object} color An HSL color in the form: {hue, saturation, lightness}. * @returns {Object} The limited color in the form: {hue, saturation, lightness}. */ const limitColorVariables = (color) => { let newSaturation = color.saturation; if (newSaturation < 0) { newSaturation = 0; } else if (newSaturation > 100) { newSaturation = 100; } let newLightness = color.lightness; if (newLightness < 0) { newLightness = 0; } else if (newLightness > 100) { newLightness = 100; } let newColor = { hue: color.hue % 360, saturation: newSaturation, lightness: newLightness }; return newColor; } export {hslToHex, limitColorVariables};<file_sep>/src/index.js import 'semantic-ui-css/semantic.min.css'; import React from 'react'; import ReactDOM from 'react-dom'; import MainApp from './js/component/MainApp.js'; ReactDOM.render( <React.StrictMode> <MainApp /> </React.StrictMode>, document.getElementById('root') ); <file_sep>/src/js/component/ColorVariableSelection.js import React, {Component} from 'react'; import {Segment, Header} from 'semantic-ui-react'; import Slider from './element/Slider.js'; class ColorVariableSelection extends Component { constructor(props) { super(props); if (!this.props.colorVariables) { this.state = { colorVariables: { initialHue: 0, finalHue: 0, initialSaturation: 0, finalSaturation: 0, initialLightness: 0, finalLightness: 0 } } } else { this.state = { colorVariables: this.props.colorVariables }; } } /** * Handles what happens when the slider changes value. * @param {string} stateField The field in this.state.colorVariables that is being updated. * @param {number} value The value to update the field to. */ handleSliderChange = (stateField, value) => { this.setState(prevState => { return { colorVariables: { ...prevState.colorVariables, [stateField]: value } } }, () => { if (this.props.passVariablesFunction) { this.props.passVariablesFunction(this.state.colorVariables); } }); } /////////////////////// /// Render /////////////////////// render = () => { return( <Segment basic vertical> <Header as='h4'>Initial Hue ({Math.floor(this.state.colorVariables.initialHue)})</Header> <Slider stateField='initialHue' min={0} max={720} onUpdate={this.handleSliderChange} value={this.state.colorVariables.initialHue} /> <Header as='h4'>Final Hue ({Math.floor(this.state.colorVariables.finalHue)})</Header> <Slider stateField='finalHue' min={0} max={720} onUpdate={this.handleSliderChange} value={this.state.colorVariables.finalHue} /> <Header as='h4'>Initial Saturation ({Math.floor(this.state.colorVariables.initialSaturation)})</Header> <Slider stateField='initialSaturation' min={0} max={100} onUpdate={this.handleSliderChange} value={this.state.colorVariables.initialSaturation} /> <Header as='h4'>Final Saturation ({Math.floor(this.state.colorVariables.finalSaturation)})</Header> <Slider stateField='finalSaturation' min={0} max={100} onUpdate={this.handleSliderChange} value={this.state.colorVariables.finalSaturation} /> <Header as='h4'>Initial Lightness ({Math.floor(this.state.colorVariables.initialLightness)})</Header> <Slider stateField='initialLightness' min={0} max={100} onUpdate={this.handleSliderChange} value={this.state.colorVariables.initialLightness} /> <Header as='h4'>Final Lightness ({Math.floor(this.state.colorVariables.finalLightness)})</Header> <Slider stateField='finalLightness' min={0} max={100} onUpdate={this.handleSliderChange} value={this.state.colorVariables.finalLightness} /> </Segment> ); } } export default ColorVariableSelection;<file_sep>/src/js/component/RampPaletteSection.js import React, {Component} from 'react'; import {Segment, Button} from 'semantic-ui-react'; import RampBuilder from './RampBuilder.js'; import PaletteBuilder from './PaletteBuilder.js'; class RampPaletteSection extends Component { constructor(props) { super(props); this.state = { activeButton: 'ramp' }; } /** * Sets the active button to either 'ramp' or 'palette'. * @param {string} value The name of the button that is being set as active. */ setActiveButton = (value) => { this.setState(prevState => { return { activeButton: value }; }); } /////////////////////// /// Render /////////////////////// render = () => { let builderComponent; if (this.state.activeButton == 'ramp') { builderComponent = <RampBuilder />; } else if (this.state.activeButton == 'palette') { builderComponent = <PaletteBuilder />; } return( <Segment basic vertical padded> <Button.Group> <Button active={this.state.activeButton == 'ramp'} onClick={() => {this.setActiveButton('ramp')}}>Ramp</Button> <Button active={!this.state.activeButton == 'palette'} onClick={() => {this.setActiveButton('palette')}}>Palette</Button> </Button.Group> <Segment vertical padded> {builderComponent} </Segment> </Segment> ); } } export default RampPaletteSection;<file_sep>/src/js/component/element/ColorRamp.js import React, {Component} from 'react'; import {Table} from 'semantic-ui-react'; import {hslToHex} from '../../util/ColorUtils.js' class ColorRamp extends Component { constructor(props) { super(props); } /** * Generates the cells that display the hex values of colors. * @returns {Array} Array of jsx for each cell. */ generateHexValueCells = () => { let colors = this.colors; let cellsJsx = []; for (let i = 0; i < colors.length; i++) { let colorString = hslToHex(colors[i].hue, colors[i].saturation, colors[i].lightness); let cell = <Table.Cell textAlign='center' style={{border: '1px solid #4b4848'}}>{colorString}</Table.Cell> cellsJsx.push(cell); } return cellsJsx; } /** * Generates the cells that display the actual colors. * @returns {Array} Array of jsx for each cell. */ generateColorCells = () => { this.colors = this.getColorValues(this.props.numSwatches, this.props.colorVariables); let colors = this.colors; let cellsJsx = []; for (let i = 0; i < colors.length; i++) { let colorString = 'hsl(' + colors[i].hue + ' ' + colors[i].saturation + '% ' + colors[i].lightness + '%)'; let cell = <Table.Cell style={{backgroundColor: colorString, border: '1px solid #4b4848'}} /> cellsJsx.push(cell); } return cellsJsx; } /** * Get an array of HSL colors. * @param {number} numColors Number of colors. * @param {Object} colorVariables The variables used to generate the colors. * @return {Array} An array of colors in the form of: {hue, saturation, lightness}. */ getColorValues = (numColors, colorVariables) => { let baseColor = { hue: colorVariables.initialHue, saturation: colorVariables.initialSaturation, lightness: colorVariables.initialLightness }; let finalColor = { hue: colorVariables.finalHue, saturation: colorVariables.finalSaturation, lightness: colorVariables.finalLightness }; let colorStep = { hue: (finalColor.hue - baseColor.hue) / (numColors - 1), saturation: (finalColor.saturation - baseColor.saturation) / (numColors - 1), lightness: (finalColor.lightness - baseColor.lightness) / (numColors - 1) }; let colors = []; for (let i = 0; i < numColors; i++) { let color = { hue: baseColor.hue + colorStep.hue * i, saturation: baseColor.saturation + colorStep.saturation * i, lightness: baseColor.lightness + colorStep.lightness * i }; colors.push(color); } return colors; } /////////////////////// /// Render /////////////////////// render = () => { return( <Table basic fixed style={{borderRadius: '5px', border: '2px solid #4b4848', }}> <Table.Body> <Table.Row style={{height: '100px'}}> {this.generateColorCells()} </Table.Row> <Table.Row> {this.generateHexValueCells()} </Table.Row> </Table.Body> </Table> ); } } export default ColorRamp;
31923f8491b4bb1d24aea5d73346072d4746a963
[ "Markdown", "JavaScript" ]
8
Markdown
dsvalerian/palette-generator
b2d21a9bb340f6d92f3e6a9edc334f75ae9f8b11
dbe3d90db107ef93dcb031bc75579c331a5fa501
refs/heads/master
<file_sep>// // ViewController.swift // ToDo // // Created by <NAME> on 29.12.20. // import UIKit class ToDoViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var toDoTableView: UITableView! var itemArray = [Item]() var switchControl = UISwitch() // Erstellen des FileManagers und abspeichern in einer Konstante (erstellt den NSCoder) let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Item.plist") // MARK: - ViewDidLoad override func viewDidLoad() { super.viewDidLoad() toDoTableView.delegate = self toDoTableView.dataSource = self loadItems() } // MARK: - ViewDidAppear // viewDidLoad wird nur beim ersten Mal wo die App-Seite erscheint aufgerufen // viewDidAppear wird JEDESMAL, wenn die App-Seite (toDoViewController) erscheint aufgerufen override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // muss man einfach machen, damit das was vorgegeben ist ausgeführt wird und DANACH unser eigener Code in der Methode - gleich wie bei der viewDidLoad toDoTableView.reloadData() // aktuallisiert jedesmal die Tabelle, wenn die App-Seite toDoViewController geöffnet wird } // MARK: - Add Item Button @IBAction func addToDoItem_tapped(_ sender: UIBarButtonItem) { let alert = UIAlertController(title: "ToDo hinzufügen", message: "", preferredStyle: .alert) // Alertbox-Text iOS 13 farblich anpassen für Darkmode if #available(iOS 13, *) { alert.view.tintColor = UIColor.label // alert.view ist die graue Alertbox an sich } else { alert.view.tintColor = UIColor.black } var textField = UITextField() let action = UIAlertAction(title: "ToDo erstellen", style: .default) { (action) in let itemObject = Item(title: textField.text!) // Prüfen, ob es WICHTIG ist oder nicht - also ob der Switch auf true oder false steht itemObject.isImportant = self.switchControl.isOn // Objekt der Tabelle hinzufügen self.itemArray.append(itemObject) // Tabelle aktuallisieren self.toDoTableView.reloadData() // Daten im FileManager abspeichern (NSCoder) self.saveItems() } let cancel = UIAlertAction(title: "Abbrechen", style: .default) { (cancel) in } // Textfeld hinzufügen alert.addTextField { (userText) in textField = userText userText.placeholder = "ToDo eintragen..." } // Switch hinzufügen alert.view.addSubview(createSwitch {}) alert.addAction(action) alert.addAction(cancel) present(alert, animated: true, completion: nil) } // MARK: - Create Switch for important ToDo's func createSwitch(completion: () -> Void) -> UISwitch { // UISwitch(frame: CGRect()) - CGRect ist auch nur eine Klasse, davon suchen wir uns den Init mit x,y,width und height für INT aus und wählen dann 10px Abstand von links, 20px von oben und wenn man width und height 0 macht, verwendet er die Standartgrösse für ein Switch switchControl = UISwitch(frame: CGRect(x: 10, y: 20, width: 0, height: 0)) switchControl.isOn = false // damit wissen wir, dass er auf OFF ist switchControl.setOn(false, animated: false) // Damit sagen wir, dass wenn der Switch erstellt wird, er erstmal auf OFF sein soll, animiert muss das auch nicht sein - isOn ist nur der Status für uns als Programmierer zu wissen, setOn bestimmt, welchen Status er beim erstellen hat. switchControl.onTintColor = switchControlTintColor // Hintergrundfarbe des Switchs, wenn es ON ist switchControl.backgroundColor = UIColor.systemBackground // Hintergrundfarbe des Switchs, wenn es OFF ist switchControl.thumbTintColor = UIColor.black // Schalterfarbe des Switchs switchControl.layer.cornerRadius = 16 // zusätzliche Rundung des Randes switchControl.layer.borderWidth = 0.8 // Die Dicke des Randes switchControl.layer.borderColor = UIColor.darkGray.cgColor // Die Farbe des Randes switchControl.layer.masksToBounds = true // Sagt dem Switch, es soll in seinen Grenzlinien bleiben und ja nicht überschreiten, weils sonst einfach unsauber aussieht // Wir müssen ein addTarget machen, da wir eine Aktion/Aufgabe ausgelöst haben möchten, sobald der Switch betätigt wird - .valueChanged benutzt man immer bei Switchs, da ein Switch immer zwischen 2 Value (Werten) hin und her springt (true (1), false (0)) switchControl.addTarget(self, action: #selector(switchValueDidChange(sender:)), for: .valueChanged) completion() return switchControl } @objc func switchValueDidChange(sender: UISwitch) { } // MARK: - Long Press / Change ToDo // Methode die definiert, was passieren soll, wenn der Nutzer die Tabellenzeile lange gedrückt hält @objc func longPress(sender: UILongPressGestureRecognizer) { if sender.state == UIGestureRecognizer.State.ended { // Speichern der Location, wo der User gedrückt hat (x und y Wert) let locationPoint = sender.location(in: self.toDoTableView) // Prüfen, auf welcher Tabellenzeile der Nutzer gedrückt hat if let pressIndexPath = self.toDoTableView.indexPathForRow(at: locationPoint) { // Textfield ausserhalb des Closures erstellen, da wir das auch ausserhalb verwenden müssen var userText = UITextField() let alert = UIAlertController(title: "Änderung", message: "", preferredStyle: .alert) // Alertbox-Text iOS 13 farblich anpassen für Darkmode if #available(iOS 13, *) { alert.view.tintColor = UIColor.label // alert.view ist die graue Alertbox an sich } else { alert.view.tintColor = UIColor.black } // TextField erstellen und hinzufügen alert.addTextField { (changedUserText) in userText = changedUserText changedUserText.placeholder = "Änderung eingeben..." } // Switch erstellen und hinzufügen alert.view.addSubview(createSwitch { if self.itemArray[pressIndexPath.row].isImportant == true { self.switchControl.setOn(true, animated: true) } else { self.switchControl.setOn(false, animated: true) } }) // Buttons erstellen und hinzufügen let changeAction = UIAlertAction(title: "Ändern", style: .default) { (changeAction) in // Text ändern if !(userText.text!.isEmpty) { self.itemArray[pressIndexPath.row].title = userText.text! } // Den Status von WICHTIG oder nicht nochmals neu festlegen anhand der bei der Änderung eingegebenen Stellung des Switchs (on/off) self.itemArray[pressIndexPath.row].isImportant = self.switchControl.isOn // Die Tabelle aktuallisieren, damit die Änderung übernommen wird self.toDoTableView.reloadData() // Daten im FileManager abspeichern (NSCoder) self.saveItems() } let cancelAction = UIAlertAction(title: "Abbrechen", style: .default) { (cancelAction) in } alert.addAction(changeAction) alert.addAction(cancelAction) // Alert schlussendlich präsentieren self.present(alert, animated: true, completion: nil) } } } // MARK: - NSCoder - save Items func saveItems() { // Encoder in Konstante erstellen let encoder = PropertyListEncoder() // Um Fehler beim encoden abzufangen benutzt man ein Do-Catch (Mach-Fang auf) Statement do { let data = try encoder.encode(itemArray) // hier wird versucht, die Daten im Array zu encoden try data.write(to: dataFilePath!) // Die encodeten Daten werden versucht im FileManager zu speichern } catch { // Falls das nicht geht, fang etwas auf print(error.localizedDescription) // und zwar den Error und print mir das in ein LogFile } } // MARK: - NSCoder - load Items func loadItems() { // Optional Binding, weil Apple gesagt hat, dass evtl die gespeicherten Daten gelöscht werden können etc. if let data = try? Data(contentsOf: dataFilePath!) { // In Konstante "data" werden die Daten gespeichert die auf dem Handy gespeichert sind - mit "try?" sagt man, "versuch mal..." // Decoder in Konstante erstellen let decoder = PropertyListDecoder() // wieder ein Do-Catch Statement, da ein Fehler beim Auslesen passieren kann und dann soll der Fehler in die Log-Datei aufgefangen werden do { // Hier wird versucht, die Daten auszulesen und als Array wieder in das itemArray zurückzugeben itemArray = try decoder.decode([Item].self, from: data) // versuch aus der zuvor erstellten Konstante "data" (if let...) ein Array ([Item].self) vom Typ "Item" zu erstellen } catch { print(error.localizedDescription) } } } } // MARK: - Extensions extension ToDoViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Bestimmen, was geändert werden soll, sobald man auf eine Zeile drückt itemArray[indexPath.row].done = !itemArray[indexPath.row].done // Tabelle aktuallisieren toDoTableView.reloadData() } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Prüfen, ob der Nutzer Sachen löschen möchte if editingStyle == .delete { // aus dem Array löschen itemArray.remove(at: indexPath.row) // und aus der Tabelle löschen toDoTableView.deleteRows(at: [indexPath], with: .fade) } } // ändert die Höhe der Tabellenzeilen func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100.0 // Jede Tabellenzeile ist nun 100px hoch } } extension ToDoViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "toDoCell", for: indexPath) // Tabellenzeile angeben, was da stehen soll let item = itemArray[indexPath.row] // hier müssen wir die Daten zwischenspeichern, die im Array stehen cell.textLabel?.text = item.title cell.detailTextLabel?.text = item.date + item.time // Tabellenzeilenfarbe ändern if #available(iOS 13, *) { // Prüfen, ob das Gerät eine iOS Version oder neuer (*) hat cell.tintColor = UIColor.label // auto Anpassung Dark/Lightmode } else { cell.tintColor = UIColor.black // Da alle unter iOS 13 sowieso nur den Lightmode haben } // Prüfen ob wichtig oder nicht if item.isImportant == true { cell.backgroundColor = cellBackgroundColor } else { cell.backgroundColor = UIColor.systemBackground } // prüfen ob Haken gesetzt oder nicht if item.done == true { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } // Tabellenzeile drückbar machen let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress(sender:))) // Recognizer = Erkenner , diese Methode erkennt, wenn der Nutzer lange auf etwas klickt cell.addGestureRecognizer(longPressRecognizer) // Hier müssen wir den Recognizer(Erkenner) jeder Zeile hinzufügen return cell } } <file_sep>// // Item.swift // ToDo // // Created by <NAME> on 29.12.20. // import Foundation class Item: Codable { // Protocal "Codable" muss implementiert werden, da wir die Daten dieser Klasse die im Array gespeichert werden per NSCoder speichern wollen und wir dem ENCODER sagen müssen, dass die Instanzen (Objekte) dieser Klasse "Codable" sind. // Eigenschaften var title: String var done: Bool = false // normalerweise auf FALSE, da die Aufgabe bestimmt noch nicht erledigt ist var isImportant: Bool = false // standartmässig auf FALSE, da man es manuell auf WICHTIG schalten muss var time: String var date: String // init init(title: String) { self.title = title // Instanz (Object) vom Typ "DateFormatter()" um Zeit und Datum zu erstellen let formatter = DateFormatter() // Zeit formatter.dateFormat = "hh:mm" time = " um \(formatter.string(from: Date())) Uhr" // "Date" ist eine Class (Struct) welche im Typ String die Uhrzeit in unsere erstellte Variable "time" speichert // Datum formatter.dateFormat = "dd.MM.yy" formatter.locale = Locale(identifier: "de_DE") // setzt das Datumformat auf DEUTSCHLAND date = "Erstellt am \(formatter.string(from: Date()))" // gleich wie bei der Zeit, durch "Date()" speichert man das Datum im String-Format in die von uns erstellte Variable "date" } // Methoden } <file_sep>// // ThemeViewController.swift // ToDo // // Created by <NAME> on 29.12.20. // import UIKit class ThemeViewController: UIViewController { // MARK: - Outlets @IBOutlet weak var themeImageView: UIImageView! @IBOutlet weak var switchTheme: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() themeImageView.image = UIImage(named: "Theme 2") if switchTheme.selectedSegmentIndex == 0 { switchTheme.selectedSegmentTintColor = UIColor.systemRed } else if switchTheme.selectedSegmentIndex == 1 { switchTheme.selectedSegmentTintColor = UIColor.systemBlue } } @IBAction func switchTheme_tapped(_ sender: UISegmentedControl) { let index = sender.selectedSegmentIndex switch index { case 0: themeImageView.image = UIImage(named: "Theme 2") switchTheme.selectedSegmentTintColor = UIColor.systemRed saveColors() case 1: themeImageView.image = UIImage(named: "Theme 1") switchTheme.selectedSegmentTintColor = UIColor.systemBlue saveColors() default: break } } func saveColors() { if switchTheme.selectedSegmentIndex == 0 { // Rotes Theme cellBackgroundColor = UIColor.systemRed tabBarTintColor = UIColor.systemRed switchControlTintColor = UIColor.systemRed // Tabbar farbe ändern guard let tabbar = self.tabBarController?.tabBar else {return} // Tabbar abspeichern in konstante tabbar - muss so gemacht werden, da "tabBarController" vom Typ OPTIONAL ist tabbar.tintColor = UIColor.systemRed } else if switchTheme.selectedSegmentIndex == 1 { cellBackgroundColor = UIColor.systemBlue tabBarTintColor = UIColor.systemBlue switchControlTintColor = UIColor.systemBlue // Tabbar farbe ändern guard let tabbar = self.tabBarController?.tabBar else {return} tabbar.tintColor = UIColor.systemBlue } } } <file_sep>// // Colors.swift // ToDo // // Created by <NAME> on 30.12.20. // import Foundation import UIKit var cellBackgroundColor: UIColor = UIColor.systemRed var tabBarTintColor: UIColor = UIColor.systemRed var switchControlTintColor: UIColor = UIColor.systemRed
bc83b97b578949e2962b9ac63195b5ce9174b3f1
[ "Swift" ]
4
Swift
RobinRuf/todo
db5a8e0875ebe4a16860699c7756d7e8ca106f6b
d8b0c965c0b2c5d65c917abac2f90b52765e1d17
refs/heads/master
<repo_name>gameeTH/2WaySSL-example<file_sep>/README.md **Referernce repo:** - https://gist.github.com/pcan/e384fcad2a83e3ce20f9a4c33f4a13ae **Suggestion:** - Try to use "axios" for more reliability <file_sep>/Server/server-express.js var fs = require('fs'), http = require('http'), https = require('https'), express = require('express'); var port = 443; var options = { key: fs.readFileSync('server-key.pem'), cert: fs.readFileSync('server-crt.pem'), ca: fs.readFileSync('ca-crt.pem'), // request client certificate requestCert: true, rejectUnauthorized: true }; var app = express(); var server = https.createServer(options, app).listen(port, function(){ console.log("Express server listening on port " + port); }); app.post('/', function (req, res) { res.writeHead(200); console.log("called post") // console.log(Object.keys(req)) console.log(req.headers) res.end("hello world\n"); });
1e544d7b7b1332507b57534468132f46b392f7fb
[ "Markdown", "JavaScript" ]
2
Markdown
gameeTH/2WaySSL-example
e4e7b07dc06ed528bdd106c7211c5cb65ee8111c
2b92db64fa0ec82641268fdc3c662a9793328d64
refs/heads/main
<repo_name>yamagame/hello-typescript<file_sep>/libs/message.ts import { hello } from "libs/hello"; export const HelloMessage = (message: string) => `${hello} ${message}`; <file_sep>/README.md # TypeScript Template Project ## 開発開始 次の yarn コマンドで必要なモジュールをインストールします。 ``` $ yarn install ``` 次のコマンドで実行します。 ``` $ yarn start ``` ブラウザで「http://localhost:4000/ 」を開きます。 ソースコードを更新すると自動的にビルドされますので、「http://localhost:4000」をリロードして更新します。 test ディレクトリにテストコードを書いて次のコマンドでユニットテストを行います。 ``` $ yarn test ``` <file_sep>/tests/hello/index.test.ts const { hello } = require("libs/hello"); test("Hello のテスト", () => { expect(hello).toBe("Hello"); }); <file_sep>/tests/message.test.ts const message = require("libs/message"); test("HelloMessageのテスト", () => { expect(message.HelloMessage("World")).toBe("Hello World"); }); <file_sep>/index.ts import express = require("express"); import message = require("libs/message"); const app = express(); const port = process.env.PORT || 4000; app.use(express.static("public")); app.get("/port", (req, res) => { res.send(`PORT: ${port}`); }); app.get("/hello", (req, res) => { res.send(message.HelloMessage("World")); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); });
ab8a17d7282f23a208a11cb227300bdcf3732bef
[ "Markdown", "TypeScript" ]
5
TypeScript
yamagame/hello-typescript
27e8d2cda2e6a8cb0a598e184ef07b30961894ea
ff430ffb3522ef7ad58abe83ac07996bcce21072
refs/heads/master
<file_sep>## In order to speed up the computation of the inverse of an invertible matrix, we will create a new matrix which caches it's own inverse ## As long as the original matrix does not change rather than computing the inverse of the original matrix all the time, we rely on the cached value ## so that the inverse matrix is calculated only once ## Defines setters and getters of the matrix and its cached inverse makeCacheMatrix <- function(x = matrix()) { ## Initializes the property that stores the inverse matrix invMat <- NULL ## Stores the matrix and resets the invMat property setMatrix <- function( matrix ) { mat <<- matrix invMat <<- NULL } ## Retrieves the matrix getMatrix <- function() { mat } ## Stores (caches) the inverse of the matrix setInverseMatrix <- function(inverseMatrix) { invMat <<- inverseMatrix } ## Retrieves the inverse of the matrix getInverseMatrix <- function() { invMat } ## Returns all methods as a list list(setMatrix = setMatrix, getMatrix = getMatrix, setInverseMatrix = setInverseMatrix, getInverseMatrix = getInverseMatrix) } ## Returns the inverse of a matrix 'x'. ## If it has been computed already, it returns the cached value cacheSolve <- function(x, ...) { ## Retrieves the inverse of the matrix, which defaults to NULL invMatrix <- x$getInverseMatrix() ## if it's not null it returns it 'cause it's the cached value if (!is.null(invMatrix)) { message("Retrieving a cached value") return(invMatrix) } ## Retrieves the matrix provided to the makeCacheMatrix mat <- x$getMatrix() ## computes the inverse matrix invMatrix <- solve(mat, ...) ## caches it x$setInverseMatrix(invMatrix) ## and returns it message("New value computed and cached") invMatrix }
42fbf24837a342b558d3a27ba5bccda58d0daab9
[ "R" ]
1
R
PietroSulis/ProgrammingAssignment2
a96d22dd0ed7f5c4109360273bf0fc422e98d387
74877d3ef3a257e2b9d715d6ce043f3d2bf88590
refs/heads/master
<repo_name>Breaddsmall/bookstore<file_sep>/fe/test/test_search.py import time import pytest from fe.access import auth from fe import conf import uuid class TestSearch: @pytest.fixture(autouse=True) def pre_run_initialization(self): self.auth = auth.Auth(conf.URL) self.author = "test_author_{}".format(str(uuid.uuid1())) self.book_intro = "test_book_intro_{}".format(str(uuid.uuid1())) self.tags = "test_tags_{}".format(str(uuid.uuid1())) self.title = "test_title_{}".format(str(uuid.uuid1())) self.store_id = "test_store_id_{}".format(str(uuid.uuid1())) yield # 采用like语句直接查询关键词的搜索方法 def test_search(self): self.store_id = "test_add_books_store_id_e57c7e37-5342-11eb-bdd5-94b86d54714d" assert self.auth.search_author("西尔维娅") == 200 assert self.auth.search_book_intro("三毛流浪") == 200 assert self.auth.search_tags("传记") == 200 assert self.auth.search_title("流浪记") == 200 assert self.auth.search_author_in_store("西尔维娅", self.store_id) == 200 assert self.auth.search_book_intro_in_store("三毛", self.store_id) == 200 assert self.auth.search_tags_in_store("传记", self.store_id) == 200 assert self.auth.search_title_in_store("三毛", self.store_id) == 200 # 采用PostgreSQL 全文检索功能的改进版搜索方法 def test_search_index_version(self): self.store_id = "test_add_books_store_id_e57c7e37-5342-11eb-bdd5-94b86d54714d" assert self.auth.search_book_intro("三毛") == 200 assert self.auth.search_book_intro_in_store("三毛", self.store_id) == 200 <file_sep>/fe/test/test_check_stock.py import pytest from fe.access.buyer import Buyer from fe.test.gen_book_data import GenBook from fe.access.new_buyer import register_new_buyer from fe.access.book import Book import uuid class TestCheckStock: seller_id: str store_id: str buyer_id: str password:str buy_book_info_list: [Book] total_price: int order_id: str buyer: Buyer @pytest.fixture(autouse=True) def pre_run_initialization(self): self.seller_id = "test_check_stock_seller_id_{}".format(str(uuid.uuid1())) self.store_id = "test_check_stock_store_id_{}".format(str(uuid.uuid1())) self.buyer_id = "test_check_stock_buyer_id_{}".format(str(uuid.uuid1())) self.password = <PASSWORD> gen_book = GenBook(self.seller_id, self.store_id) self.seller = gen_book.seller ok, self.buy_book_id_list = gen_book.gen(non_exist_book_id=False, low_stock_level=False, max_book_count=5) self.buy_book_info_list = gen_book.buy_book_info_list assert ok b = register_new_buyer(self.buyer_id, self.password) self.buyer = b code, self.order_id = b.new_order(self.store_id, self.buy_book_id_list) assert code == 200 self.total_price = 0 for item in self.buy_book_info_list: book: Book = item[0] num = item[1] if book.price is None: continue else: self.total_price = self.total_price + book.price * num yield def test_authorization_error(self): self.seller.password = self.seller.password + "_x" code = self.seller.check_stock(self.seller_id,self.seller.password,self.store_id,"") assert code != 200 self.seller.seller_id = self.seller.seller_id + "_x" code = self.seller.check_stock(self.seller.seller_id,self.password,self.store_id,"") assert code != 200 def test_ok(self): code = self.seller.check_stock(self.seller_id,self.password,self.store_id,"") assert code == 200 code = self.seller.check_stock(self.seller_id, self.password, self.store_id, self.buy_book_id_list[0][0]) assert code == 200 <file_sep>/fe/access/book.py import os import sqlite3 as sqlite import random import base64 import simplejson as json from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Integer, ForeignKey, create_engine, PrimaryKeyConstraint, Text, DateTime, \ Boolean, LargeBinary from sqlalchemy.orm import sessionmaker import psycopg2 from datetime import datetime, time url = 'postgresql://{}:{}@{}:{}/{}' user = 'postgres' password = '<PASSWORD>' host = 'localhost' port = '5432' db = 'bookstore' url = url.format(user, password, host, port, db) engine = create_engine(url, client_encoding='utf8') # engine = create_engine(Conf.get_sql_conf('local')) Base = declarative_base() DBSession = sessionmaker(bind=engine) session = DBSession() """ conn.execute( "CREATE TABLE book (" "id TEXT PRIMARY KEY, title TEXT, author TEXT, " "publisher TEXT, original_title TEXT, " "translator TEXT, pub_year TEXT, pages INTEGER, " "price INTEGER, currency_unit TEXT, binding TEXT, " "isbn TEXT, author_intro TEXT, book_intro text, " "content TEXT, tags TEXT, picture BLOB)" ) """ class Book1(Base): __tablename__ = 'book' id = Column(Integer, primary_key=True) title = Column(Text, nullable=False) author = Column(Text) publisher = Column(Text) original_title = Column(Text) translator = Column(Text) pub_year = Column(Text) pages = Column(Integer) price = Column(Integer) # 原价 currency_unit = Column(Text) binding = Column(Text) isbn = Column(Text) author_intro = Column(Text) book_intro = Column(Text) content = Column(Text) tags = Column(Text) picture = Column(LargeBinary) class Book: id: str title: str author: str publisher: str original_title: str translator: str pub_year: str pages: int price: int binding: str isbn: str author_intro: str book_intro: str content: str tags: [str] pictures: [bytes] def __init__(self): self.tags = [] self.pictures = [] def init(): DBSession = sessionmaker(bind=engine) session = DBSession() Base.metadata.create_all(engine) session.commit() # 关闭session session.close() class BookDB: def __init__(self, large: bool = False): parent_path = os.path.dirname(os.path.dirname(__file__)) self.db_s = os.path.join(parent_path, "data/book.db") self.db_l = os.path.join(parent_path, "data/book_lx.db") if large: self.book_db = self.db_l else: self.book_db = self.db_s def get_book_count(self): conn = sqlite.connect(self.book_db) cursor = conn.execute( "SELECT count(id) FROM book") row = cursor.fetchone() return row[0] def get_book_info(self, start, size) -> [Book]: books = [] conn = sqlite.connect(self.book_db) cursor = conn.execute( "SELECT id, title, author, " "publisher, original_title, " "translator, pub_year, pages, " "price, currency_unit, binding, " "isbn, author_intro, book_intro, " "content, tags, picture FROM book ORDER BY id " "LIMIT '%s' OFFSET '%s'" % (size, start)) for row in cursor: book = Book() book.id = row[0] book.title = row[1] book.author = row[2] book.publisher = row[3] book.original_title = row[4] book.translator = row[5] book.pub_year = row[6] book.pages = row[7] book.price = row[8] book.currency_unit = row[9] book.binding = row[10] book.isbn = row[11] book.author_intro = row[12] book.book_intro = row[13] book.content = row[14] tags = row[15] picture = row[16] for tag in tags.split("\n"): if tag.strip() != "": book.tags.append(tag) for i in range(0, random.randint(0, 9)): if picture is not None: encode_str = base64.b64encode(picture).decode('utf-8') book.pictures.append(encode_str) books.append(book) # print(tags.decode('utf-8')) # print(book.tags, len(book.picture)) # print(book) # print(tags) return books def send_info_to_db(self, start, size): DBSession = sessionmaker(bind=engine) session = DBSession() conn = sqlite.connect(self.book_db) cursor = conn.execute( "SELECT id, title, author, " "publisher, original_title, " "translator, pub_year, pages, " "price, currency_unit, binding, " "isbn, author_intro, book_intro, " "content, tags, picture FROM book ORDER BY id " "LIMIT ? OFFSET ?", (size, start)) for row in cursor: book = Book1() book.id = row[0] book.title = row[1] book.author = row[2] book.publisher = row[3] book.original_title = row[4] book.translator = row[5] book.pub_year = row[6] book.pages = row[7] book.price = row[8] book.currency_unit = row[9] book.binding = row[10] book.isbn = row[11] book.author_intro = row[12] book.book_intro = row[13] book.content = row[14] tags = row[15] picture = row[16] # tagenum=MyEnum(enum.Enum) thelist = [] # 由于没有列表类型,故使用将列表转为text的办法 for tag in tags.split("\n"): if tag.strip() != "": # book.tags.append(tag) thelist.append(tag) book.tags = str(thelist) # 解析成list请使用eval() book.picture = None # thelistforpic=[] # for i in range(0, random.randint(0, 9)): if picture is not None: ##以下为查看图片代码 # with open('code.png', 'wb') as fn: # wb代表二进制文件 # fn.write(picture) # img = mpimg.imread('code.png', 0) # plt.imshow(img) # plt.axis('off') # plt.show() # encode_str = base64.b64encode(picture).decode('utf-8') # # book.pictures.append(encode_str) # print(type(encode_str)) book.picture = picture session.add(book) session.commit() # 关闭session session.close() def send_info(self): bookdb.send_info_to_db(0, bookdb.get_book_count()) # count=100 or 整张表 if __name__ == '__main__': # bookdb=BookDB()#单进程0.7148709297180176 多进程2.212113380432129 bookdb = BookDB(large=False) # 导入整张表 43988数据 还没跑通 不知道多进程会不会比单进程快 # 单进程1033.8140s 多进程1035.624s 无任何速度提升 print(bookdb.get_book_count()) # for i in bookdb.get_book_info(0,bookdb.get_book_count()): # print(i.tags) init() bookdb.send_info() <file_sep>/initialize_book_split.py from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Integer, ForeignKey, create_engine, PrimaryKeyConstraint, Text, DateTime, \ Boolean, LargeBinary from sqlalchemy.orm import sessionmaker import jieba import psycopg2 from datetime import datetime, time url = 'postgresql://{}:{}@{}:{}/{}' user = 'postgres' password = '<PASSWORD>' host = 'localhost' port = '5432' db = 'bookstore' url = url.format(user, password, host, port, db) engine = create_engine(url) # engine = create_engine(Conf.get_sql_conf('local')) Base = declarative_base() def init(): DBSession = sessionmaker(bind=engine) session = DBSession() session.execute( "CREATE TABLE IF NOT EXISTS book_split (" "id int4 PRIMARY KEY, book_intro text); " ) # 提交即保存到数据库 session.commit() # 关闭session session.close() def split(): DBSession = sessionmaker(bind=engine) session = DBSession() Base.metadata.create_all(engine) row = session.execute("SELECT id, book_intro FROM book;").fetchall() for i in row: tmp = i.book_intro ans = "" if tmp != None: seg_list = jieba.cut_for_search(tmp) ans = " ".join(seg_list) session.execute( "INSERT into book_split(id, book_intro) VALUES (%d, '%s')" % (int(i.id), ans)) session.commit() # 关闭session session.close() def add_fts(): DBSession = sessionmaker(bind=engine) session = DBSession() Base.metadata.create_all(engine) session.execute("DROP INDEX IF EXISTS fts_gin_index;") session.execute("ALTER TABLE book_split ADD COLUMN fts tsvector;") session.execute("UPDATE book_split SET fts = setweight(to_tsvector('english', book_intro), 'A') ;") session.execute("CREATE INDEX fts_gin_index ON book_split USING gin (fts);") session.commit() # 关闭session session.close() if __name__ == "__main__": # 创建数据库 init() # 分词 split() # 建索引 add_fts() <file_sep>/be/auto_config.py from be.model import db_conn import be.auto_job class Config(object): JOBS = [ { 'id': 'job1', 'func': be.auto_job.auto_cancel, # 方法名 'trigger': 'interval', # interval表示循环任务 'seconds': 2, }, { 'id': 'job2', 'func': be.auto_job.auto_receive, # 方法名 'trigger': 'interval', # interval表示循环任务 'seconds': 2, } ] <file_sep>/be/auto_job.py from be.model import db_conn def auto_cancel(): conn=db_conn.DBConn().conn conn.execute("UPDATE new_order SET condition = 'cancelled' " "WHERE condition = 'unpaid' AND CURRENT_TIMESTAMP-update_time >= interval '3 SECOND' ;") conn.commit() def auto_receive(): conn=db_conn.DBConn().conn cursor=conn.execute("SELECT order_id,store_id,total_price FROM new_order WHERE condition = 'shipped' AND CURRENT_TIMESTAMP-update_time >= interval '3 SECOND';") for row in cursor: order_id=row[0] store_id=row[1] total_price=row[2] conn.execute("UPDATE new_order SET condition = 'received' WHERE order_id = '%s';"%(order_id)) conn.execute("UPDATE user_store SET s_balance = s_balance - %d WHERE store_id ='%s';"%(total_price,store_id)) c=conn.execute("SELECT user_id FROM user_store WHERE store_id='%s';"%(store_id)) r=c.fetchone() user_id=r[0] conn.execute("UPDATE usr SET balance = balance + %d WHERE user_id = '%s';"%(total_price,user_id)) conn.commit() <file_sep>/README2.md # README2 需要修改数据库密码的文件 ``` initialize_db.py store.py book.py ``` test运行前先运行 ``` initialize_db.py和book.py ``` <file_sep>/fe/test/test_seach_all_order_buyer.py import pytest from fe.access.buyer import Buyer from fe.access.seller import Seller from fe.test.gen_book_data import GenBook from fe.access.new_buyer import register_new_buyer from fe.access.book import Book import uuid class TestSearchAllOrderBuyer: seller_id: str store_id: str buyer_id: str password:str buy_book_info_list: [Book] total_price: int order_id: str buyer: Buyer seller: Seller @pytest.fixture(autouse=True) def pre_run_initialization(self): self.seller_id = "test_search_all_order_buyer_seller_id_{}".format(str(uuid.uuid1())) self.store_id = "test_search_all_order_buyer_store_id_{}".format(str(uuid.uuid1())) self.buyer_id = "test_search_all_order_buyer_buyer_id_{}".format(str(uuid.uuid1())) self.password = <PASSWORD> gen_book = GenBook(self.seller_id, self.store_id) ok, buy_book_id_list = gen_book.gen(non_exist_book_id=False, low_stock_level=False, max_book_count=5) self.buy_book_info_list = gen_book.buy_book_info_list assert ok b = register_new_buyer(self.buyer_id, self.password) self.buyer = b self.seller = gen_book.seller code, self.order_id = b.new_order(self.store_id, buy_book_id_list) assert code == 200 self.total_price = 0 for item in self.buy_book_info_list: book: Book = item[0] num = item[1] if book.price is None: continue else: self.total_price = self.total_price + book.price * num yield def test_authorization_error(self): self.buyer.password = <PASSWORD>.password + "_x" code = self.buyer.search_all_order_buyer() assert code != 200 self.buyer.user_id = self.buyer.user_id + "_x" code = self.buyer.search_all_order_buyer() assert code != 200 def test_condition_paid(self): code = self.buyer.add_funds(self.total_price) assert code == 200 code = self.buyer.payment(self.order_id) assert code == 200 code,count = self.buyer.search_all_order_buyer() assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(condition="unpaid") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="paid") assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(condition="shipped") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="received") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="cancelled") assert code == 200 assert count == 0 def test_condition_unpaid(self): code,count = self.buyer.search_all_order_buyer() assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(condition="unpaid") assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(condition="paid") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="shipped") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="received") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="cancelled") assert code == 200 assert count == 0 def test_condition_shipped(self): code = self.buyer.add_funds(self.total_price) assert code == 200 code = self.buyer.payment(self.order_id) assert code == 200 code = self.seller.ship(self.seller_id,self.order_id) assert code == 200 code,count = self.buyer.search_all_order_buyer() assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(condition="unpaid") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="paid") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="shipped") assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(condition="received") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="cancelled") assert code == 200 assert count == 0 def test_condition_received(self): code = self.buyer.add_funds(self.total_price) assert code == 200 code = self.buyer.payment(self.order_id) assert code == 200 code = self.seller.ship(self.seller_id,self.order_id) assert code == 200 code = self.buyer.receive(self.order_id) code,count = self.buyer.search_all_order_buyer() assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(condition="unpaid") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="paid") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="shipped") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="received") assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(condition="cancelled") assert code == 200 assert count == 0 def test_condition_cancelled(self): code =self.buyer.cancel_order(self.order_id) assert code == 200 code,count = self.buyer.search_all_order_buyer() assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(condition="unpaid") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="paid") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="shipped") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="received") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(condition="cancelled") assert code == 200 assert count == 1 def test_store(self): code = self.buyer.add_funds(self.total_price) assert code == 200 code = self.buyer.payment(self.order_id) assert code == 200 code, count = self.buyer.search_all_order_buyer() assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(store_id=self.store_id) assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(store_id=self.store_id+"_x") assert code == 200 assert count == 0 code, count = self.buyer.search_all_order_buyer(store_id=self.store_id,condition="paid") assert code == 200 assert count == 1 code, count = self.buyer.search_all_order_buyer(store_id=self.store_id, condition="unpaid") assert code == 200 assert count == 0 <file_sep>/fe/test/test_check_balance.py import pytest from fe.test.gen_book_data import GenBook from fe.access.new_buyer import register_new_buyer import uuid class TestCheckBalance: @pytest.fixture(autouse=True) def pre_run_initialization(self): self.buyer_id = "check_balance_buyer_id_{}".format(str(uuid.uuid1())) self.password = <PASSWORD> self.buyer = register_new_buyer(self.buyer_id, self.password) yield def test_ok(self): code,result = self.buyer.check_balance() assert code == 200 assert result ==0 code = self.buyer.add_funds(1000) assert code == 200 ode, result = self.buyer.check_balance() assert code == 200 assert result == 1000 def test_authorization_error(self): self.buyer.password = <PASSWORD> + "_x" code = self.buyer.check_balance() assert code != 200 def test_non_exist_user_id(self): self.buyer.user_id = self.buyer.user_id + "_x" code, _ = self.buyer.check_balance() assert code != 200 <file_sep>/initialize_db.py from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Integer, ForeignKey, create_engine, PrimaryKeyConstraint, Text, DateTime, \ Boolean, LargeBinary from sqlalchemy.orm import sessionmaker import psycopg2 from datetime import datetime, time # 连接数据库legend 记得修改这个!!! # engine = create_engine(Conf.get_sql_conf('local_w')) from sqlalchemy_utils import create_database, database_exists url = 'postgresql://{}:{}@{}:{}/{}' user = 'postgres' password = '<PASSWORD>' host = 'localhost' port = '5432' db = 'bookstore' url = url.format(user, password, host, port, db) engine = create_engine(url) # engine = create_engine(Conf.get_sql_conf('local')) Base = declarative_base() def init(): DBSession = sessionmaker(bind=engine) session = DBSession() if not database_exists(engine.url): create_database(engine.url) session.execute( "CREATE TABLE IF NOT EXISTS usr (" "user_id TEXT PRIMARY KEY, password TEXT NOT NULL, " "balance INTEGER NOT NULL, token TEXT, terminal TEXT);" ) session.execute( "CREATE TABLE IF NOT EXISTS user_store(user_id TEXT, store_id TEXT," "s_balance INTEGER," " PRIMARY KEY(user_id, store_id));" ) session.execute( "CREATE TABLE IF NOT EXISTS store( " "store_id TEXT, book_id TEXT, book_info TEXT, stock_level INTEGER," " PRIMARY KEY(store_id, book_id))" ) session.execute( "CREATE TABLE IF NOT EXISTS new_order( " "order_id TEXT PRIMARY KEY, user_id TEXT, store_id TEXT,total_price INTEGER,condition TEXT," "update_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP);" ) session.execute( "CREATE TABLE IF NOT EXISTS new_order_detail( " "order_id TEXT, book_id TEXT, count INTEGER, price INTEGER, " "PRIMARY KEY(order_id, book_id))" ) # 定义数据库函数(触发器) # 以user_id和store_id建立new_order上的索引 # 原因:除了primary key order_id,还会查询user_id/store_id/condition # 其中condition只有五种状态,而user_id和store_id都非常多 session.execute( "CREATE INDEX IF NOT EXISTS search_order_index ON new_order(user_id,store_id)" ) # 提交即保存到数据库 session.commit() # 关闭session session.close() if __name__ == "__main__": # 创建数据库 init() <file_sep>/be/model/user.py import jwt import time import logging import sqlite3 as sqlite from flask import jsonify, json from be.model import error from be.model import db_conn import sqlalchemy import initialize_db import base64 # encode a json string like: # { # "user_id": [user name], # "terminal": [terminal code], # "timestamp": [ts]} to a JWT # } def jwt_encode(user_id: str, terminal: str) -> str: encoded = jwt.encode( {"user_id": user_id, "terminal": terminal, "timestamp": time.time()}, key=user_id, algorithm="HS256", ) return encoded # .decode("utf-8") # decode a JWT to a json string like: # { # "user_id": [user name], # "terminal": [terminal code], # "timestamp": [ts]} to a JWT # } def jwt_decode(encoded_token, user_id: str) -> str: decoded = jwt.decode(encoded_token, key=user_id, algorithms="HS256") return decoded class User(db_conn.DBConn): token_lifetime: int = 3600 # 3600 second def __init__(self): db_conn.DBConn.__init__(self) def __check_token(self, user_id, db_token, token) -> bool: try: if db_token != token: return False jwt_text = jwt_decode(encoded_token=token, user_id=user_id) ts = jwt_text["timestamp"] if ts is not None: now = time.time() if self.token_lifetime > now - ts >= 0: return True except jwt.exceptions.InvalidSignatureError as e: logging.error(str(e)) return False def register(self, user_id: str, password: str) -> (int, str): try: terminal = "terminal_{}".format(str(time.time())) token = jwt_encode(user_id, terminal) self.conn.execute( "INSERT INTO usr (user_id, password, balance, token, terminal) values ('%s', '%s', 0, '%s', '%s')" % ( user_id, password, token, terminal)) self.conn.commit() #print("注册成功",user_id) except sqlalchemy.exc.IntegrityError: return error.error_exist_user_id(user_id) return 200, "ok" def check_token(self, user_id: str, token: str) -> (int, str): cursor = self.conn.execute("SELECT token from usr where user_id='%s'" % (user_id)) # cursor=self.conn.query(User).filter(User.user_id==user_id).get(token) row = cursor.fetchone() if row is None: print("userid有误") return error.error_authorization_fail() db_token = row[0] if not self.__check_token(user_id, db_token, token): print("token有误") return error.error_authorization_fail() print("token正确") return 200, "ok" def check_password(self, user_id: str, password: str) -> (int, str): cursor = self.conn.execute("SELECT password from usr where user_id='%s'" % (user_id)) row = cursor.fetchone() if row is None: print("user_id不存在") return error.error_authorization_fail() if password != row[0]: print("密码不正确") return error.error_authorization_fail() #print("password正确") return 200, "ok" def login(self, user_id: str, password: str, terminal: str) -> (int, str, str): token = "" try: code, message = self.check_password(user_id, password) if code != 200: return code, message, "" token = jwt_encode(user_id, terminal) #print(1) cursor = self.conn.execute( "UPDATE usr set token= '%s' , terminal = '%s' where user_id = '%s'" % (token, terminal, user_id)) #print(2) if cursor.rowcount == 0: return error.error_authorization_fail() + ("",) self.conn.commit() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)), "" except BaseException as e: print(e) return 530, "{}".format(str(e)), "" #print("登录成功") return 200, "ok", token def logout(self, user_id: str, token: str) -> (int, str): try: code, message = self.check_token(user_id, token) if code != 200: return code, message terminal = "terminal_{}".format(str(time.time())) dummy_token = jwt_encode(user_id, terminal) cursor = self.conn.execute( "UPDATE usr SET token = '%s', terminal = '%s' WHERE user_id='%s'" % (token, terminal, user_id)) if cursor.rowcount == 0: return error.error_authorization_fail() self.conn.commit() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) except BaseException as e: return 530, "{}".format(str(e)) return 200, "ok" def unregister(self, user_id: str, password: str) -> (int, str): try: code, message = self.check_password(user_id, password) if code != 200: return code, message cursor = self.conn.execute("DELETE from usr where user_id='%s'" % (user_id,)) if cursor.rowcount == 1: self.conn.commit() else: return error.error_authorization_fail() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) except BaseException as e: return 530, "{}".format(str(e)) return 200, "ok" def change_password(self, user_id: str, old_password: str, new_password: str) -> (int, str): try: code, message = self.check_password(user_id, old_password) if code != 200: return code, message terminal = "terminal_{}".format(str(time.time())) token = jwt_encode(user_id, terminal) cursor = self.conn.execute( "UPDATE usr set password = '%s', token= '%s' , terminal = '%s' where user_id = '%s'" % ( new_password, token, terminal, user_id)) if cursor.rowcount == 0: return error.error_authorization_fail() self.conn.commit() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) except BaseException as e: return 530, "{}".format(str(e)) return 200, "ok" def search_author(self, author: str) -> (int, [dict]): # 200,'ok',list[{str,str,str,str,list,bytes}] ret = [] a = '%' temp = author b = '%' c = a + temp + b records = self.conn.execute( " SELECT title,author,publisher,book_intro,tags FROM book WHERE author LIKE '%s' " % ( c)).fetchall() if len(records) != 0: for i in range(len(records)): record = records[i] title = record[0] author = record[1] publisher = record[2] book_intro = record[3] tags = record[4] ret.append( {'title': title, 'author': author, 'publisher': publisher, 'book_intro': book_intro, 'tags': tags}) return 200, ret else: return 200, [] def search_book_intro(self, book_intro: str) -> (int, [dict]): ret = [] a = '%' temp = book_intro b = '%' c = a + temp + b records = self.conn.execute( " SELECT title,author,publisher,book_intro,tags FROM book WHERE book_intro LIKE '%s' " % ( c)).fetchall() if len(records) != 0: for i in range(len(records)): record = records[i] title = record[0] author = record[1] publisher = record[2] book_intro = record[3] tags = record[4] ret.append( {'title': title, 'author': author, 'publisher': publisher, 'book_intro': book_intro, 'tags': tags}) return 200, ret else: return 200, [] def search_tags(self, tags: str) -> (int, [dict]): ret = [] a = '%' temp = tags b = '%' c = a + temp + b records = self.conn.execute( " SELECT title,author,publisher,book_intro,tags FROM book WHERE tags LIKE '%s' " % ( c)).fetchall() if len(records) != 0: for i in range(len(records)): record = records[i] title = record[0] author = record[1] publisher = record[2] book_intro = record[3] tags = record[4] ret.append( {'title': title, 'author': author, 'publisher': publisher, 'book_intro': book_intro, 'tags': tags}) return 200, ret else: return 200, [] def search_title(self, title: str) -> (int, [dict]): ret = [] a = '%' temp = title b = '%' c = a + temp + b records = self.conn.execute( " SELECT title,author,publisher,book_intro,tags FROM book WHERE title LIKE '%s' " % ( c)).fetchall() if len(records) != 0: for i in range(len(records)): record = records[i] title = record[0] author = record[1] publisher = record[2] book_intro = record[3] tags = record[4] ret.append( {'title': title, 'author': author, 'publisher': publisher, 'book_intro': book_intro, 'tags': tags}) return 200, ret else: return 200, [] def search_author_in_store(self, author: str, store_id: str) -> (int, [dict]): ret = [] a = '%' temp = author b = '%' c = a + temp + b records = self.conn.execute( " SELECT title,author,publisher,book_intro,tags FROM book WHERE author LIKE '%s' and book.id in (select book_id::int4 from store where store_id='%s')" % ( c, store_id)).fetchall() if len(records) != 0: for i in range(len(records)): record = records[i] title = record[0] author = record[1] publisher = record[2] book_intro = record[3] tags = record[4] ret.append( {'title': title, 'author': author, 'publisher': publisher, 'book_intro': book_intro, 'tags': tags}) return 200, ret else: return 200, [] def search_book_intro_in_store(self, book_intro: str, store_id: str) -> (int, [dict]): ret = [] a = '%' temp = book_intro b = '%' c = a + temp + b records = self.conn.execute( " SELECT title,author,publisher,book_intro,tags FROM book WHERE book_intro LIKE '%s' and book.id in (select book_id::int4 from store where store_id='%s') " % ( c, store_id)).fetchall() if len(records) != 0: for i in range(len(records)): record = records[i] title = record[0] author = record[1] publisher = record[2] book_intro = record[3] tags = record[4] ret.append( {'title': title, 'author': author, 'publisher': publisher, 'book_intro': book_intro, 'tags': tags}) return 200, ret else: return 200, [] def search_tags_in_store(self, tags: str, store_id: str) -> (int, [dict]): ret = [] a = '%' temp = tags b = '%' c = a + temp + b records = self.conn.execute( " SELECT title,author,publisher,book_intro,tags FROM book WHERE tags LIKE '%s' and book.id in (select book_id::int4 from store where store_id='%s')" % ( c, store_id)).fetchall() if len(records) != 0: for i in range(len(records)): record = records[i] title = record[0] author = record[1] publisher = record[2] book_intro = record[3] tags = record[4] ret.append( {'title': title, 'author': author, 'publisher': publisher, 'book_intro': book_intro, 'tags': tags}) return 200, ret else: return 200, [] def search_title_in_store(self, title: str, store_id: str) -> (int, [dict]): ret = [] a = '%' temp = title b = '%' c = a + temp + b records = self.conn.execute( " SELECT title,author,publisher,book_intro,tags FROM book WHERE title LIKE '%s' and book.id in (select book_id::int4 from store where store_id='%s') " % ( c, store_id)).fetchall() if len(records) != 0: for i in range(len(records)): record = records[i] title = record[0] author = record[1] publisher = record[2] book_intro = record[3] tags = record[4] ret.append( {'title': title, 'author': author, 'publisher': publisher, 'book_intro': book_intro, 'tags': tags}) return 200, ret else: return 200, [] def search_book_intro_index_version(self, book_intro: str) -> (int, [dict]): ret = [] temp = book_intro records = self.conn.execute( "SELECT book.title,book.author,book.publisher,book.book_intro,book.tags FROM book WHERE book.id in (SELECT id FROM book_split WHERE fts @@ to_tsquery('%s'));" % ( temp)).fetchall() if len(records) != 0: for i in range(len(records)): record = records[i] title = record[0] author = record[1] publisher = record[2] book_intro = record[3] tags = record[4] ret.append( {'title': title, 'author': author, 'publisher': publisher, 'book_intro': book_intro, 'tags': tags}) return 200, ret else: return 200, [] def search_book_intro_index_version_in_store(self, book_intro: str, store_id: str) -> (int, [dict]): ret = [] temp = book_intro records = self.conn.execute( "SELECT book.title,book.author,book.publisher,book.book_intro,book.tags FROM book WHERE book.id in (SELECT id FROM book_split WHERE fts @@ to_tsquery('%s')) and book.id in (select book_id::int4 from store where store_id='%s') ;" % ( temp, store_id)).fetchall() if len(records) != 0: for i in range(len(records)): record = records[i] title = record[0] author = record[1] publisher = record[2] book_intro = record[3] tags = record[4] ret.append( {'title': title, 'author': author, 'publisher': publisher, 'book_intro': book_intro, 'tags': tags}) return 200, ret else: return 200, [] <file_sep>/be/model/buyer.py import sqlite3 as sqlite import time import sqlalchemy import uuid import json import logging from be.model import db_conn from be.model import error from flask import jsonify #from be.model.auto_job import execute_job class Buyer(db_conn.DBConn): def __init__(self): db_conn.DBConn.__init__(self) def new_order(self, user_id: str, store_id: str, id_and_count: [(str, int)]) -> (int, str, str): order_id = "" try: if not self.user_id_exist(user_id): return error.error_non_exist_user_id(user_id) + (order_id,) if not self.store_id_exist(store_id): return error.error_non_exist_store_id(store_id) + (order_id,) uid = "{}_{}_{}".format(user_id, store_id, str(uuid.uuid1())) total_price = 0 for book_id, count in id_and_count: cursor = self.conn.execute( "SELECT book_id, stock_level, book_info FROM store " "WHERE store_id = '%s' AND book_id = '%s';" % (store_id, book_id)) row = cursor.fetchone() if row is None: return error.error_non_exist_book_id(book_id) + (order_id,) stock_level = row[1] book_info = row[2] book_info_json = json.loads(book_info) price = book_info_json.get("price") total_price += price * count if stock_level < count: return error.error_stock_level_low(book_id) + (order_id,) cursor = self.conn.execute( "UPDATE store set stock_level = stock_level - %d " "WHERE store_id = '%s' and book_id = '%s' and stock_level >= %d; " % (count, store_id, book_id, count)) if cursor.rowcount == 0: return error.error_stock_level_low(book_id) + (order_id,) self.conn.execute( "INSERT INTO new_order_detail(order_id, book_id, count, price) " "VALUES('%s', '%s', %d, %d);" % (uid, book_id, count, price)) # 添加状态0,该订单为支付 self.conn.execute( "INSERT INTO new_order(order_id, store_id, user_id,total_price,condition) " "VALUES('%s', '%s', '%s',%d,'unpaid');" % (uid, store_id, user_id, total_price)) self.conn.commit() # print("下单成功") order_id = uid #execute_job(order_id, 0) except sqlalchemy.exc.IntegrityError as e: logging.info("528, {}".format(str(e))) return 528, "{}".format(str(e)), "" except BaseException as e: logging.info("530, {}".format(str(e))) print(e) return 530, "{}".format(str(e)), "" return 200, "ok", order_id def payment(self, user_id: str, password: str, order_id: str) -> (int, str): try: cursor = self.conn.execute( "SELECT user_id, store_id,total_price,condition FROM new_order WHERE order_id = '%s';" % ( order_id)) row = cursor.fetchone() if row is None: return error.error_invalid_order_id(order_id) buyer_id = row[0] store_id = row[1] total_price = row[2] condition = row[3] # time.sleep(0.5) # 防止并发导致的查询顺序错误 #print(condition, order_id) if buyer_id != user_id: return error.error_authorization_fail() # time1=time.time() if condition != "unpaid": # print(condition,order_id) # print("oh"+str(time.time())) # print(order_id,condition) return error.error_unpayable_order(order_id) cursor = self.conn.execute("SELECT balance, password FROM usr WHERE user_id = '%s';" % (buyer_id)) row = cursor.fetchone() if row is None: return error.error_non_exist_user_id(buyer_id) balance = row[0] if password != row[1]: return error.error_authorization_fail() cursor = self.conn.execute("SELECT store_id, user_id FROM user_store WHERE store_id ='%s';" % (store_id)) row = cursor.fetchone() if row is None: return error.error_non_exist_store_id(store_id) seller_id = row[1] if not self.user_id_exist(seller_id): return error.error_non_exist_user_id(seller_id) if balance < total_price: return error.error_not_sufficient_funds(order_id) self.conn.execute("UPDATE usr set balance = balance - %d " "WHERE user_id = '%s' AND balance >= %d;" % (total_price, buyer_id, total_price)) cursor = self.conn.execute("UPDATE user_store set s_balance = s_balance + %d " "WHERE store_id = '%s';" % (total_price, store_id)) if cursor.rowcount == 0: return error.error_non_exist_store_id(store_id) cursor = self.conn.execute("UPDATE new_order set condition = 'paid',update_time=CURRENT_TIMESTAMP WHERE order_id ='%s';" % (order_id)) # print (order_id) # time2=time.time() # print(time2-time1) # print("good"+str(time2)) if cursor.rowcount == 0: return error.error_invalid_order_id(order_id) self.conn.commit() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) except BaseException as e: print(e) return 530, "{}".format(str(e)) return 200, "ok" def add_funds(self, user_id: str, password: str, add_value: int) -> (int, str): try: cursor = self.conn.execute("SELECT password from usr where user_id='%s';" % (user_id,)) row = cursor.fetchone() if row is None: return error.error_authorization_fail() if row[0] != password: return error.error_authorization_fail() cursor = self.conn.execute( "UPDATE usr SET balance = balance + %d WHERE user_id = '%s';" % (add_value, user_id)) if cursor.rowcount == 0: return error.error_non_exist_user_id(user_id) self.conn.commit() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) except BaseException as e: # print(e) return 530, "{}".format(str(e)) return 200, "ok" def receive(self, user_id: str, password: str, order_id: str) -> (int, str): try: cursor = self.conn.execute("SELECT password from usr where user_id='%s';" % (user_id,)) row = cursor.fetchone() if row is None: return error.error_authorization_fail() if row[0] != password: return error.error_authorization_fail() #print("checkpoint1") cursor = self.conn.execute( "SELECT store_id,total_price,condition FROM new_order " "WHERE order_id = '%s'AND user_id = '%s';" % (order_id, user_id)) row = cursor.fetchone() if row is None: return error.error_invalid_order_id(order_id) if row[2] != 'shipped': return error.error_unreceivable_order(order_id) #print("checkpoint2") store_id = row[0] total_price = row[1] self.conn.execute("UPDATE new_order SET condition = 'received',update_time=CURRENT_TIMESTAMP " "WHERE order_id ='%s';" % (order_id)) #print("checkpoint3") cursor = self.conn.execute( "SELECT user_id FROM user_store " "WHERE store_id = '%s';" % (store_id) ) #print("checkpoint4") row = cursor.fetchone() if row is None: return error.error_non_exist_store_id(store_id) seller_id = row[0] count = self.conn.execute("UPDATE user_store SET s_balance = s_balance - %d " "WHERE store_id = '%s' AND s_balance >= %d;" % (total_price, store_id, total_price)) if count == 0: return error.error_not_sufficient_funds(order_id) # 卖家余额出错 #print("checkpoint5") count = self.conn.execute("UPDATE usr SET balance = balance+ %d " "WHERE user_id = '%s';" % (total_price, seller_id)) #print("checkpoint6") if count == 0: return error.error_non_exist_user_id(seller_id) self.conn.commit() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) except BaseException as e: return 530, "{}".format(str(e)) return 200, "ok" def cancel_order(self, user_id: str, password: str, order_id: str) -> (int, str): try: cursor = self.conn.execute("SELECT password FROM usr WHERE user_id='%s';" % (user_id,)) row = cursor.fetchone() if row is None: return error.error_authorization_fail() if row[0] != password: return error.error_authorization_fail() cursor = self.conn.execute( "SELECT store_id,total_price,condition FROM new_order " "WHERE order_id = '%s'AND user_id = '%s';" % (order_id, user_id)) row = cursor.fetchone() if row is None: return error.error_invalid_order_id(order_id) condition = row[2] store_id = row[0] total_price = row[1] if condition == 'received' or condition == 'cancelled': return error.error_uncancellable_order(order_id) if condition == 'unpaid': self.conn.execute("UPDATE new_order SET condition = 'cancelled',update_time=CURRENT_TIMESTAMP " "WHERE order_id = '%s';" % (order_id)) elif condition == 'paid' or condition == 'shipped': self.conn.execute("UPDATE new_order SET condition = 'cancelled',update_time=CURRENT_TIMESTAMP " "WHERE order_id = '%s';" % (order_id)) count = self.conn.execute("UPDATE user_store SET s_balance = s_balance - %d " "WHERE store_id = '%s' AND s_balance >= %d;" % (total_price, store_id, total_price)) if count == 0: return error.error_not_sufficient_funds(order_id) # 卖家余额出错 self.conn.execute("UPDATE usr SET balance = balance + %d " "WHERE user_id = '%s';" % (total_price, user_id)) else: return error.error_invalid_order_id(order_id) # 状态出错 self.conn.commit() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) except BaseException as e: return 530, "{}".format(str(e)) return 200, "ok" def check_balance(self, user_id: str, password: str) -> (int, str, int): try: cursor = self.conn.execute("SELECT password,balance from usr where user_id='%s';" % (user_id,)) row = cursor.fetchone() if row is None: return error.error_non_exist_user_id()+(-1) if row[0] != password: return error.error_authorization_fail()+(-1) balance = row[1] except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)), -1 except BaseException as e: return 530, "{}".format(str(e)), -1 return 200, "ok", balance def search_all_order_buyer(self, user_id: str, password: str, store_id: str, condition: str): try: cursor = self.conn.execute("SELECT password FROM usr WHERE user_id='%s';" % (user_id,)) row = cursor.fetchone() if row is None: return error.error_authorization_fail()+({"order_id": [], "total_price": [], "store_id": [],"condition_id": [],"count":-1},) if row[0] != password: return error.error_authorization_fail()+({"count":-1 },) store_parameter="" condition_parameter="" if store_id != "": store_parameter = "AND store_id = '%s' " % (store_id) if condition != "": condition_parameter = " AND condition = '%s' " % (condition) cursor = self.conn.execute("SELECT order_id, total_price, store_id, condition FROM new_order " "WHERE user_id='%s' %s %s;" % (user_id, store_parameter,condition_parameter)) order_id_list = [] total_price_list = [] store_id_list = [] condition_list = [] count=0 for row in cursor: order_id_list.append(row[0]) total_price_list.append(row[1]) store_id_list.append(row[2]) condition_list.append(row[3]) count+=1 except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)),{"order_id": [], "total_price": [], "store_id": [], "condition_id": [],"count":-1} except BaseException as e: # print(e) return 530, "{}".format(str(e)),{"order_id": [], "total_price": [], "store_id": [], "condition_id": [],"count":-1} return 200, "ok", {"order_id": order_id_list, "total_price": total_price_list, "store_id": store_id_list, "condition_id": condition_list,"count":count} def search_order_detail_buyer(self, user_id: str, password: str, order_id: str): try: cursor = self.conn.execute("SELECT password from usr where user_id='%s';" % (user_id,)) row = cursor.fetchone() if row is None: return error.error_authorization_fail()+({"condition":-1,"result_count":-1},) if row[0] != password: return error.error_authorization_fail()+({"condition":-1,"result_count":-1},) cursor = self.conn.execute( "SELECT store_id,total_price,condition FROM new_order " "WHERE order_id = '%s'AND user_id = '%s';" % (order_id, user_id)) row = cursor.fetchone() if row is None: return error.error_invalid_order_id(order_id)+({"condition":-1,"result_count":-1},) store_id = row[0] total_price = row[1] condition = row[2] book_id_list = [] count_list = [] price_list = [] result_count=0 cursor = self.conn.execute( "SELECT book_id, count, price FROM new_order_detail WHERE order_id = '%s';" % (order_id) ) for row in cursor: book_id_list.append(row[0]) count_list.append(row[1]) price_list.append(row[2]) result_count+=1 msg= {"order_id": order_id, "store_id": store_id, "total_price": total_price, "condition": condition,"book_id": book_id_list, "count": count_list, "price": price_list,"result_count":result_count} except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)), {"condition":-1,"result_count":-1} except BaseException as e: return 530, "{}".format(str(e)), {"condition":-1,"result_count":-1} return 200, "ok", msg <file_sep>/be/model/store.py import logging import os import sqlite3 as sqlite from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Integer, ForeignKey, create_engine, PrimaryKeyConstraint from sqlalchemy.orm import sessionmaker from initialize_db import init import psycopg2 from sqlalchemy_utils import database_exists, create_database class Store: def __init__(self): # 连接数据库legend 记得修改这个!!! # engine = create_engine(Conf.get_sql_conf('local_w')) url = 'postgresql://{}:{}@{}:{}/{}' user = 'postgres' password = '<PASSWORD>' host = 'localhost' port = '5432' db = 'bookstore' url = url.format(user, password, host, port, db) engine = create_engine(url, client_encoding='utf8') if not database_exists(engine.url): init() # engine = create_engine(Conf.get_sql_conf('local')) # engine = create_engine(Conf.get_sql_conf('local')) Base = declarative_base() DBSession = sessionmaker(bind=engine) self.session = DBSession() #print("数据库连接成功") return self.session <file_sep>/be/model/seller.py import sqlite3 as sqlite from be.model import error from be.model import db_conn from flask import jsonify, json import sqlalchemy #from be.model.auto_job import execute_job class Seller(db_conn.DBConn): def __init__(self): db_conn.DBConn.__init__(self) def add_book(self, user_id: str, store_id: str, book_id: str, book_json_str: str, stock_level: int) -> (int, str): try: if not self.user_id_exist(user_id): return error.error_non_exist_user_id(user_id) if not self.store_id_exist(store_id): return error.error_non_exist_store_id(store_id) if self.book_id_exist(store_id, book_id): return error.error_exist_book_id(book_id) self.conn.execute( "INSERT into store(store_id, book_id, book_info, stock_level)VALUES ('%s', '%s', '%s', %d)" % ( store_id, book_id, book_json_str, stock_level)) self.conn.commit() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) except BaseException as e: return 530, "{}".format(str(e)) return 200, "ok" def add_stock_level(self, user_id: str, store_id: str, book_id: str, add_stock_level: int) -> (int, str): try: if not self.user_id_exist(user_id): return error.error_non_exist_user_id(user_id) if not self.store_id_exist(store_id): return error.error_non_exist_store_id(store_id) if not self.book_id_exist(store_id, book_id): return error.error_non_exist_book_id(book_id) self.conn.execute( "UPDATE store SET stock_level = stock_level +%d WHERE store_id = '%s' AND book_id = '%s'" % ( add_stock_level, store_id, book_id)) self.conn.commit() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) except BaseException as e: return 530, "{}".format(str(e)) return 200, "ok" def create_store(self, user_id: str, store_id: str) -> (int, str): try: if not self.user_id_exist(user_id): return error.error_non_exist_user_id(user_id) if self.store_id_exist(store_id): return error.error_exist_store_id(store_id) self.conn.execute( "INSERT into user_store(user_id, store_id,s_balance)VALUES('%s','%s',0)" % (user_id, store_id)) self.conn.commit() except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) except BaseException as e: print(e) return 530, "{}".format(str(e)) return 200, "ok" def ship(self, user_id, order_id) -> (int, str): try: if not self.user_id_exist(user_id): return error.error_non_exist_user_id(user_id) cursor = self.conn.execute( "SELECT store_id,condition FROM new_order WHERE " "order_id='%s';" % (order_id)) row = cursor.fetchone() if row is None: return error.error_invalid_order_id(order_id) store_id = row[0] condition = row[1] cursor = self.conn.execute( "SELECT user_id FROM user_store WHERE " "store_id ='%s' AND user_id='%s';" % (store_id, user_id)) row = cursor.fetchone() if row is None: return error.error_non_exist_store_id(store_id) if condition != "paid": return error.error_unshippable_order(order_id) self.conn.execute("UPDATE new_order set condition ='shipped',update_time=CURRENT_TIMESTAMP WHERE order_id = '%s';"%(order_id,)) self.conn.commit() #execute_job(order_id, 1) print("物品已发货") except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)) return 200, "ok" def check_s_balance(self, user_id: str, password: str, store_id: str) -> (int, str, int): try: cursor = self.conn.execute("SELECT password FROM usr WHERE user_id='%s';" % (user_id,)) row = cursor.fetchone() if row is None: return error.error_authorization_fail()+(-1) if row[0] != password: return error.error_authorization_fail()+(-1) cursor = self.conn.execute( "SELECT s_balance FROM user_store WHERE user_id = '%s' AND store_id = '%s';" % (user_id, store_id)) row = cursor.fetchone() if row is None: return error.error_non_exist_store_id(store_id)+(-1) s_balance = row[0] except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)), -1 except BaseException as e: return 530, "{}".format(str(e)), -1 return 200, "ok", s_balance def check_stock(self, user_id: str, password: str, store_id: str, book_id: str): try: cursor = self.conn.execute("SELECT password FROM usr WHERE user_id='%s';" % (user_id,)) row = cursor.fetchone() if row is None: return error.error_authorization_fail()+({"book_id": [], "stock_level": []}) if row[0] != password: return error.error_authorization_fail()+({"book_id": [], "stock_level": []}) cursor = self.conn.execute( "SELECT store_id FROM user_store WHERE user_id = '%s' AND store_id = '%s';" % (user_id, store_id)) row = cursor.fetchone() if row is None: return error.error_non_exist_store_id(store_id)+({"book_id": [], "stock_level": []}) book_id_p="" if book_id != "": book_id_p = "AND book_id = '%s'" % (book_id) cursor = self.conn.execute( "SELECT book_id, stock_level FROM store WHERE store_id = '%s' %s;" % ( store_id, book_id_p)) book_id_list = [] stock_level_list = [] for row in cursor: book_id_list.append(row[0]) stock_level_list.append(row[1]) msg = {"book_id": book_id_list, "stock_level": stock_level_list} except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)),{"book_id": [], "stock_level": []} except BaseException as e: print(e) return 530, "{}".format(str(e)),{"book_id": [], "stock_level": []} return 200, "ok", msg def search_all_order_seller(self, user_id: str, password: str, store_id: str, condition: str): try: cursor = self.conn.execute("SELECT password FROM usr WHERE user_id='%s';" % (user_id,)) row = cursor.fetchone() if row is None: return error.error_authorization_fail()+({"count":-1 },) if row[0] != password: return error.error_authorization_fail()+({"count":-1 },) cursor = self.conn.execute("SELECT store_id FROM user_store WHERE user_id='%s' AND store_id ='%s';" % (user_id,store_id)) row=cursor.fetchone() if row is None: return error.error_non_exist_store_id(store_id)+({"count":-1 },) condition_parameter="" if condition != "": condition_parameter = "AND condition ='%s'" % (condition) #print(condition_parameter) cursor = self.conn.execute("SELECT order_id, total_price, store_id, condition FROM new_order " "WHERE store_id='%s' %s;" % (store_id,condition_parameter)) order_id_list = [] total_price_list = [] store_id_list = [] condition_list = [] count=0 for row in cursor: order_id_list.append(row[0]) total_price_list.append(row[1]) store_id_list.append(row[2]) condition_list.append(row[3]) count+=1 except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)),{"count":-1 }, except BaseException as e: # print(e) return 530, "{}".format(str(e)),{"count":-1 }, return 200, "ok", {"order_id": order_id_list, "total_price": total_price_list, "store_id": store_id_list, "condition_id": condition_list,"count":count} def search_order_detail_seller(self, user_id: str, password: str, order_id: str): try: cursor = self.conn.execute("SELECT password from usr where user_id='%s';" % (user_id,)) row = cursor.fetchone() if row is None: return error.error_authorization_fail()+({"condition":-1,"result_count":-1 },) if row[0] != password: return error.error_authorization_fail()+({"condition":-1,"result_count":-1 },) cursor = self.conn.execute( "SELECT store_id,total_price,condition FROM new_order " "WHERE order_id = '%s';" % (order_id)) row = cursor.fetchone() if row is None: return error.error_invalid_order_id(order_id)+({"condition":-1,"result_count":-1 },) store_id = row[0] total_price = row[1] condition = row[2] cursor = self.conn.execute( "SELECT store_id FROM user_store WHERE user_id='%s' and store_id='%s';" % (user_id, store_id)) row = cursor.fetchone() if row is None: return error.error_non_exist_store_id()+({"condition":-1,"result_count":-1 },) book_id_list = [] count_list = [] price_list = [] result_count=0 cursor = self.conn.execute( "SELECT book_id, count, price FROM new_order_detail WHERE order_id = '%s';" % (order_id) ) for row in cursor: book_id_list.append(row[0]) count_list.append(row[1]) price_list.append(row[2]) result_count+=1 msg = {"order_id": order_id, "store_id": store_id, "total_price": total_price, "condition": condition, "book_id": book_id_list, "count": count_list, "price": price_list,"result_count":result_count} except sqlalchemy.exc.IntegrityError as e: return 528, "{}".format(str(e)),{"condition":-1,"result_count":-1 }, except BaseException as e: return 530, "{}".format(str(e)),{"condition":-1,"result_count":-1 }, return 200, "ok", msg <file_sep>/be/view/seller.py from flask import Blueprint from flask import request from flask import jsonify from be.model import seller import json bp_seller = Blueprint("seller", __name__, url_prefix="/seller") @bp_seller.route("/create_store", methods=["POST"]) def seller_create_store(): user_id: str = request.json.get("user_id") store_id: str = request.json.get("store_id") s = seller.Seller() code, message = s.create_store(user_id, store_id) return jsonify({"message": message}), code @bp_seller.route("/add_book", methods=["POST"]) def seller_add_book(): user_id: str = request.json.get("user_id") store_id: str = request.json.get("store_id") book_info: str = request.json.get("book_info") stock_level: str = request.json.get("stock_level", 0) s = seller.Seller() code, message = s.add_book(user_id, store_id, book_info.get("id"), json.dumps(book_info), stock_level) return jsonify({"message": message}), code @bp_seller.route("/add_stock_level", methods=["POST"]) def add_stock_level(): user_id: str = request.json.get("user_id") store_id: str = request.json.get("store_id") book_id: str = request.json.get("book_id") add_num: str = request.json.get("add_stock_level", 0) s = seller.Seller() code, message = s.add_stock_level(user_id, store_id, book_id, add_num) return jsonify({"message": message}), code @bp_seller.route("/ship", methods=["POST"]) def ship(): user_id: str = request.json.get("user_id") order_id: str = request.json.get("order_id") s = seller.Seller() code, message = s.ship(user_id, order_id) return jsonify({"message": message}), code @bp_seller.route("/check_s_balance", methods=["POST"]) def check_s_balance(): user_id: str = request.json.get("user_id") password: str = request.json.get("password") store_id: str = request.json.get("store_id") s = seller.Seller() code,message,result = s.check_s_balance(user_id, password, store_id) return jsonify({"message": message, "result": result}), code @bp_seller.route("/check_stock", methods=["POST"]) def check_stock(): user_id: str = request.json.get("user_id") password: str = <PASSWORD>("<PASSWORD>") store_id: str = request.json.get("store_id") book_id: str = request.json.get("book_id") s = seller.Seller() code, message,result = s.check_stock(user_id, password, store_id, book_id) return jsonify({"message": message, "result": result}), code @bp_seller.route("/search_all_order_seller", methods=["POST"]) def search_all_order_seller(): user_id = request.json.get("user_id", "") password = request.json.get("password", "") store_id = request.json.get("store_id", "") condition = request.json.get("condition", "") s = seller.Seller() code, message, result = s.search_all_order_seller(user_id, password, store_id, condition) return jsonify({"message": message, "result": result}), code @bp_seller.route("/search_order_detail_seller", methods=["POST"]) def search_order_detail_seller(): user_id = request.json.get("user_id", "") password = request.json.get("password", "") order_id = request.json.get("order_id", "") s=seller.Seller() code, message, result = s.search_order_detail_seller(user_id, password, order_id) return jsonify({"message": message, "result": result}), code <file_sep>/be/model/db_conn.py from be.model import store from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Integer, ForeignKey, create_engine, PrimaryKeyConstraint from sqlalchemy.orm import sessionmaker import psycopg2 class DBConn: def __init__(self): self.conn = store.Store.__init__(self) def user_id_exist(self, user_id): cursor = self.conn.execute("SELECT user_id FROM usr WHERE user_id ='%s';" % (user_id)) row = cursor.fetchone() if row is None: return False else: return True def book_id_exist(self, store_id, book_id): cursor = self.conn.execute( "SELECT book_id FROM store WHERE store_id = '%s' AND book_id = '%s';" % (store_id, book_id)) row = cursor.fetchone() if row is None: return False else: return True def store_id_exist(self, store_id): cursor = self.conn.execute("SELECT store_id FROM user_store WHERE store_id = '%s';" % (store_id)) row = cursor.fetchone() if row is None: return False else: return True
ddd89227b5c5ae791c9068ca37a2bb4186dbe5d7
[ "Markdown", "Python" ]
16
Python
Breaddsmall/bookstore
e02d097d1976d5b9fb5291ed16f471d25d82d895
ecf1c8b5189a3cd693db29d2815614891a84a1d7
refs/heads/main
<file_sep>#include <windows.h> #include <stdio.h> #include <stdlib.h> #include<conio.h> #include<float.h> #include<time.h> #include <dos.h> #include <conio.h> #include <dos.h> extern char ** map; extern int ** locations; extern int x,y;//size of map extern float time_game; extern int * AI_assist ; extern int y_loc_raindb; extern char order[15][3];//for save order extern int rpoint[2]; extern int rep_put; extern int attack; extern int raindb; extern int Error[20][15]; extern int *x_loc_raindb; extern int end; extern int score_player1; extern int score_ai; extern char name_player1[50]; extern char ai_name[]; extern int erroring; extern int mood_cmd1; extern int speed; ////////////////////////// char** read_map(char ** map,char * file_name); void rally_x(); void Pacman(); void pull_Box(); void Maze(); void Fliaght(); int direction(); void results(); int Raindb(); int Rpoint(); void move(int w,int s,int a,int d,int put ,int atk); int locate(); int show(); int errors(); void read_order(char*file_name_order); int AI(); <file_sep>#include"header.h" ////////////////////////// The game console is based on reading map files and commands that are specified in the standard. /* Working method of game console: 1-Read the game map from the file and then save it to the size of the specified pointer array. 2-Read commands from the file and save in the array and the corresponding variables that array the order as follows order[0][j] : solid block order[1][j] : death block order[2][j] : move block order[3][j] : rpoint order[4][j] : whall order[5][j] : up order[6][j] : down order[7][j] : left order[8][j] : right order[9][j] : character order[10][j] : target order[11][j] : object order[12][j] : opp order[13][j] : put order[14][j] : exit 3-It waits for the entry, and if the character is entered, the character changes depending on the game. */ char ** map; int ** locations=NULL; int x,y;//size of map float time_game=0; int * AI_assist = NULL; int y_loc_raindb=0; char order[15][3];//for save order int rpoint[2]; int rep_put=0; int attack=0; int raindb=0; int Error[20][15]; int *x_loc_raindb=NULL; int end=0; int score_player1=0; int score_ai=0; char name_player1[50]; char ai_name[]="Computer"; int erroring=0; int mood_cmd1=0; int speed=115; int main(){ char * name_map_game[80]; char * name_order_game[80]; char color_cmd[9]; int c,game_defult; FILE *file_str; int chr; int i=0; if(mood_cmd1==0)//for color of CMD system("color 02"); file_str=fopen("welecom.txt","r"); if(file_str!=NULL){ while((chr=fgetc(file_str))!=EOF){ putchar(chr); } printf("please wait"); while(i!=43){ printf("|||"); i++; Sleep(150); } system("cls"); } printf("Please select one of the options:\n"); printf("1_Default games\n"); printf("2_load your game\n"); printf("3_settings of CMD\n"); printf("4_game speed\n"); printf("5_Exit\n"); printf("please Enter :"); scanf("%d",&c); Beep(750, 300); if(c==5){ system("exit");//for close the game console } if(c==4){ //To change the game speed using the sleep change in the game view system("cls"); printf("The number of inputs should be between 50 and 900.( Note: As the number increases, the game will slow down)\n*Enter the speed:"); scanf("%d",&speed); if(speed<50||speed>900){ speed=150; printf("The entered speed is not correct!"); } Sleep(3000); system("cls"); main(); } if(c==1){ system("cls"); printf("Please choose one of the following games:\n"); printf("1_Maze\n2_Pull Box\n3_Pacman\n4_rally-x\n5_Flight\n6_Exite\n7_back\nplease Enter choose: "); scanf("%d",&game_defult); Beep(750, 300); if(game_defult==1){ Maze(); } if(game_defult==2){ pull_Box(); } if(game_defult==3){ Pacman(); } if(game_defult==4){ rally_x(); } if(game_defult==5){ Fliaght(); } if(game_defult==6){ system("exit"); } if(game_defult==7){ system("cls"); main(); } } if(c==2){ system("cls"); printf("Please enter the name of the game's map file: (less than 80 characters):"); scanf("%s",name_map_game); Beep(750, 300); printf("Please enter the filename of the game commands: (less than 80 characters):"); scanf("%s",name_order_game); Beep(750, 300); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,name_map_game); read_order(name_order_game); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); locate(); direction(); Sleep(speed); system("cls"); system("cls"); } } if(c==3){ strcpy(color_cmd,"color "); system("cls"); printf("Available colors list:\n"); printf("0 = Black 8 = Gray\n"); printf("1 = Blue 9 = Light Blue\n"); printf("2 = Green A = Light Green\n"); printf("3 = Aqua B = Light Aqua\n"); printf("4 = Red C = Light Red\n"); printf("5 = Purple D = Light Purple\n"); printf("6 = Yellow E = Light Yellow\n"); printf("7 = White F = Bright White\n"); printf("Please select one of the available colors for the background:"); color_cmd[6]=getchar(); color_cmd[6]=getchar(); Beep(750, 300); printf("Please select one of the available colors for the text:"); color_cmd[7]=getchar(); color_cmd[7]=getchar(); color_cmd[8]='\0'; Beep(750, 300); system("cls"); mood_cmd1=5; system(color_cmd); system("cls"); main(); } return 0; } <file_sep>#include "header.h" void rally_x(){ int hardship_level; system("cls"); printf("Please select one of the levels below:\n1_Easy\n2_Medium\n3_Difficult\nplease Enter choose:"); scanf("%d",&hardship_level); Beep(750, 300); if(hardship_level==1){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-rally-x-esay.txt"); read_order("game-rally-x-esay.txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } if(hardship_level==3){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-rally-x-Difficult.txt"); read_order("game-rally-x-Difficult .txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } if(hardship_level==2){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-rally-x-Medium.txt"); read_order("game-rally-x-Medium .txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } } void Pacman(){ int hardship_level; system("cls"); printf("Please select one of the levels below:\n1_Easy\n2_Medium\n3_Difficult\nplease Enter choose:"); scanf("%d",&hardship_level); Beep(750, 300); if(hardship_level==1){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-Pacman-esay.txt"); read_order("game-Pacman-esay.txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } if(hardship_level==3){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-Pacman-Difficult.txt"); read_order("game-Pacman-Difficult .txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } if(hardship_level==2){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-Pacman-Medium.txt"); read_order("game-Pacman-Medium .txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } } void pull_Box(){ int hardship_level; system("cls"); printf("Please select one of the levels below:\n1_Easy\n2_Medium\n3_Difficult\nplease Enter choose:"); scanf("%d",&hardship_level); Beep(750, 300); if(hardship_level==1){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-pull_box-esay.txt"); read_order("game-pull_box-esay.txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } if(hardship_level==3){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-pull_box-Difficult.txt"); read_order("game-pull_box-Difficult .txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } if(hardship_level==2){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-pull_box-Medium.txt"); read_order("game-pull_box-Medium .txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } } void Maze(){ int hardship_level; system("cls"); printf("Please select one of the levels below:\n1_Easy\n2_Medium\n3_Difficult\nplease Enter choose:"); scanf("%d",&hardship_level); Beep(750, 300); if(hardship_level==1){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-Maze-Esay.txt"); read_order("game-Maze-esay.txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } if(hardship_level==3){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-Maze-Difficult.txt"); read_order("game-Maze-Difficult.txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } if(hardship_level==2){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-Maze-Medium.txt"); read_order("game-Maze-Medium.txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } } void Fliaght(){ int hardship_level; system("cls"); printf("Please select one of the levels below:\n1_Easy\n2_Medium\n3_Difficult\nplease Enter choose:"); scanf("%d",&hardship_level); Beep(750, 300); if(hardship_level==1){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-Fliaght-Esay.txt"); read_order("game-Fliaght-esay.txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } if(hardship_level==3){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-Fliaght-Difficult.txt"); read_order("game-Fliaght-Difficult.txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } if(hardship_level==2){ system("cls"); printf("Please enter the player name:"); scanf("%s",name_player1); Beep(750, 300); map=read_map(map,"map-Fliaght-Medium.txt"); read_order("game-Fliaght-Medium.txt"); erroring=errors(); if(erroring==-1){ Sleep(10000); system("exit"); } else{ Rpoint(); direction(); Sleep(115); system("cls"); system("cls"); } } } int direction(){ locate(); AI(); int sec; int p=0,c,c_befor,a,s,w,d,put,atk; int i=0; put=0; sec=time_game/1; printf("Attention:\n\n\tDirection keys %s : %c(up) %c(down) %c(left) %c(right)\n",name_player1,order[5][0],order[6][0],order[7][0],order[5][0]); if(order[12][0]!='\0'){ printf("\n\tYou have a rival\n"); } if(attack!=0){ printf("\n\tYou have a attack option\n"); } if(raindb!=0){ printf("\n\tRaindb is in the game\n"); } if(time_game>1){ printf("\n\tyour time : %d\n",sec); } printf("\n\tplease wait.....\n"); Sleep(9000); if (time_game == 0){ while(1){ if(raindb!=0){ Raindb(); } if(kbhit()){ c_befor=c; c=getch(); } if(end==1||end==2||end==3){ time_game=-1; break; } if(c==order[5][0]){ w=1; a=s=d=0; move(w,s,a,d,put,atk); if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } } if(c==order[13][0]){ put=1; if(rep_put!=0){ move(w,s,a,d,put,atk); } c=c_befor; put=0; if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } } if (c==order[6][0]){ s=1; a=d=w=0; move(w,s,a,d,put,atk); if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } } if(c==order[8][0]){ d=1; a=w=s=0; move(w,s,a,d,put,atk); if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } } if(c==order[7][0]){ a=1; s=d=w=0; move(w,s,a,d,put,atk); if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } } if(c==order[14][0]){ time_game=-1; break; } if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } p=p+0.2; show(); Sleep(speed); system("cls"); } Sleep(speed); system("cls"); show(); } else{ while(time_game>=0){ if(raindb!=0){ Raindb(); } if(kbhit()){ c_befor=c; c=getch(); } if(end==1||end==2||end==3){ time_game=-1; break; } if(c==order[5][0]){ w=1; a=s=d=0; move(w,s,a,d,put,atk); if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } } if(c==order[13][0]){ put=1; if(rep_put!=0){ move(w,s,a,d,put,atk); } c=c_befor; put=0; if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } } if (c==order[6][0]){ s=1; a=d=w=0; move(w,s,a,d,put,atk); if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } } if(c==order[8][0]){ d=1; a=w=s=0; move(w,s,a,d,put,atk); if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } } if(c==order[7][0]){ a=1; s=d=w=0; move(w,s,a,d,put,atk); if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } } if(c==order[14][0]){ locations[1][0]--; time_game=-2; break; } if(raindb!=0) if(map[locations[0][0]][locations[1][0]-1] == order[1][0]){ end=1; } time_game=time_game-0.2; show(); Sleep(speed); system("cls"); } } Sleep(speed); system("cls"); show(); return 0; } void results(){ char chr; int i=0; int a; FILE *file_win_player; FILE *file_game_over; FILE *file_eqval; if((end==1||end==3)){ file_game_over=fopen("gameover.txt","r"); if(file_game_over!=NULL){ while((chr=fgetc(file_game_over))!=EOF){ putchar(chr); } for (a = 200; a <= 300; a = a + 20){ Beep(a,a); } fclose(file_game_over); } else{ printf("you Game over!"); } } else{ file_win_player=fopen("win_player.txt","r"); if(end==2 ||score_ai<score_player1){ if(file_win_player!=NULL){ while((chr=fgetc(file_win_player))!=EOF){ putchar(chr); } for (a = 700; a <= 800; a = a + 20){ Beep(a,a-450); } } else{ printf("\n###############################you win######################\n"); } fclose(file_win_player); } if(score_ai==score_player1){ file_eqval=fopen("eqval.txt","r"); if(file_eqval!=NULL){ while((chr=fgetc(file_eqval))!=EOF){ putchar(chr); } } else{ printf("\n############################### eqval ######################\n"); } fclose(file_eqval); } } } int Raindb(){ int i,j,repeat,k; srand(time(0)); k=0; j=y_loc_raindb; if(x_loc_raindb==NULL){ x_loc_raindb=(int * )malloc(raindb*sizeof(int)); } if(y_loc_raindb==0){ y_loc_raindb++; j=y_loc_raindb; repeat=0; k=0; while(repeat<raindb){ i=rand()%x; if(map[i][j]==' '||map[i][j]==order[9][0]||map[i][j]==order[12][0]){ map[i][j]=order[1][0]; x_loc_raindb[k]=i; k++; repeat++; } } } else{ k=0; y_loc_raindb++; if(y_loc_raindb==y){ y_loc_raindb=0; while(k!=raindb){ map[x_loc_raindb[k]][j]=' '; k++; } } else{ k=0; while(k != raindb){ map[x_loc_raindb[k]][j]=' '; k++; } j=y_loc_raindb; k=0; while(k!=raindb){ map[x_loc_raindb[k]][j]=order[1][0]; k++; } } } return 0; } int Rpoint(){ int repeat=rpoint[1]; int i,j; srand(time(0)); while(repeat>0){ i=rand()%x; j=rand()%y; if((i<x)&&(j<y)&&(map[i][j]==' ')){ map[i][j]=order[3][0]; repeat--; } } return 0; } void move(int w,int s,int a,int d,int put ,int atk){ int k_attak;//for while attak if(w==1){ if(attack!=0){ k_attak=0; while(k_attak!=attack){ if(map[locations[0][0]][locations[1][0]-k_attak]==order[1][0]||map[locations[0][0]][locations[1][0]-k_attak]==order[12][0]){ map[locations[0][0]][locations[1][0]-k_attak]=' '; } k_attak++; } } if( map[locations[0][0]][locations[1][0]-1]==order[0][0] || map[locations[0][0]][locations[1][0]-1]==order[4][0]) w=0; if(map[locations[0][0]][locations[1][0]-1]==' '){ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]][locations[1][0]-1]=order[9][0]; locations[1][0]--; } if(map[locations[0][0]][locations[1][0]-1]==order[3][0]){ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]][locations[1][0]-1]=order[9][0]; locations[1][0]--; score_player1=score_player1+rpoint[0]; } if(map[locations[0][0]][locations[1][0]-1]==order[1][0]){ w=0; end=1; } if(map[locations[0][0]][locations[1][0]-1]==order[10][0]){ w=0; if(order[11][0]=='\0'){ end=2; score_player1++; } } if(map[locations[0][0]][locations[1][0]-1]==order[2][0]){ if( map[locations[0][0]][locations[1][0]-2]==order[0][0] || map[locations[0][0]][locations[1][0]-2]==order[4][0]|| map[locations[0][0]][locations[1][0]-2]==order[2][0]|| map[locations[0][0]][locations[1][0]-1]==order[1][0]|| map[locations[0][0]][locations[1][0]-1]==order[12][0]){ w=0; } else{ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]][locations[1][0]-1]=order[9][0]; map[locations[0][0]][locations[1][0]-2]=order[2][0]; locations[1][0]--; } } if(map[locations[0][0]][locations[1][0]-1]==order[11][0]){ if( map[locations[0][0]][locations[1][0]-2]==order[0][0] ||map[locations[0][0]][locations[1][0]-2]==order[12][0]||map[locations[0][0]][locations[1][0]-2]==order[4][0]|| map[locations[0][0]][locations[1][0]-2]==order[2][0]|| map[locations[0][0]][locations[1][0]-+2]==order[11][0]|| map[locations[0][0]][locations[1][0]-2]==order[1][0]){ w=0; } else{ if(map[locations[0][0]][locations[1][0]-2]==order[10][0]){ end=2; } map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]][locations[1][0]-1]=order[9][0]; map[locations[0][0]][locations[1][0]-2]=order[11][0]; locations[1][0]--; locations[3][0]--; } } } ////////////////////////////////////////////////////////// if(s==1){ if(attack!=0){ k_attak=0; while(k_attak!=attack){ if(map[locations[0][0]][locations[1][0]+k_attak]==order[1][0]||map[locations[0][0]][locations[1][0]+k_attak]==order[12][0]){ map[locations[0][0]][locations[1][0]+k_attak]=' '; } k_attak++; } } if( map[locations[0][0]][locations[1][0]+1]==order[0][0] || map[locations[0][0]][locations[1][0]+1]==order[4][0]) s=0; if(map[locations[0][0]][locations[1][0]+1]==' '){ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]][locations[1][0]+1]=order[9][0]; locations[1][0]++; } if(map[locations[0][0]][locations[1][0]+1]==order[3][0]){ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]][locations[1][0]+1]=order[9][0]; locations[1][0]++; score_player1=score_player1+rpoint[0]; } if(map[locations[0][0]][locations[1][0]+1]==order[1][0]){ s=0; end=1; } if(map[locations[0][0]][locations[1][0]+1]==order[10][0]){ s=0; if(order[11][0]=='\0'){ end=2; score_player1++; } } if(map[locations[0][0]][locations[1][0]+1]==order[2][0]){ if( map[locations[0][0]][locations[1][0]+2]==order[0][0] || map[locations[0][0]][locations[1][0]+2]==order[4][0]|| map[locations[0][0]][locations[1][0]+2]==order[2][0]|| map[locations[0][0]][locations[1][0]+1]==order[1][0]|| map[locations[0][0]][locations[1][0]+1]==order[12][0]){ s=0; } else{ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]][locations[1][0]+1]=order[9][0]; map[locations[0][0]][locations[1][0]+2]=order[2][0]; locations[1][0]++; } } if(map[locations[0][0]][locations[1][0]+1]==order[11][0]){ if( map[locations[0][0]][locations[1][0]+2]==order[0][0] || map[locations[0][0]][locations[1][0]+2]==order[12][0]|| map[locations[0][0]][locations[1][0]+2]==order[4][0]|| map[locations[0][0]][locations[1][0]+2]==order[2][0]|| map[locations[0][0]][locations[1][0]+2]==order[11][0]|| map[locations[0][0]][locations[1][0]+2]==order[1][0]){ s=0; } else{ if(map[locations[0][0]][locations[1][0]+2]==order[10][0]){ end=2; } map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]][locations[1][0]+1]=order[9][0]; map[locations[0][0]][locations[1][0]+2]=order[11][0]; locations[1][0]++; locations[3][0]++; } } } //////////////////////////////////////////////////////////////////// if(a==1){ if(attack!=0){ k_attak=0; while(k_attak!=attack){ if(locations[0][0]-k_attak>0&& map[locations[0][0]-k_attak][locations[1][0]]==order[1][0]||locations[0][0]-k_attak>0&& map[locations[0][0]-k_attak][locations[1][0]]==order[12][0]){ map[locations[0][0]-k_attak][locations[1][0]]=' '; } k_attak++; } } if( map[locations[0][0]-1][locations[1][0]]==order[0][0] || map[locations[0][0]-1][locations[1][0]]==order[4][0]|| map[locations[0][0]-1][locations[1][0]]==order[4][0]) a=0; if(map[locations[0][0]-1][locations[1][0]]==' '){ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]-1][locations[1][0]]=order[9][0]; locations[0][0]--; } if(map[locations[0][0]-1][locations[1][0]]==order[3][0]){ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]-1][locations[1][0]]=order[9][0]; locations[0][0]--; score_player1=score_player1+rpoint[0]; } if(map[locations[0][0]-1][locations[1][0]]==order[2][0]){ if( map[locations[0][0]-2][locations[1][0]]==order[0][0] || map[locations[0][0]-2][locations[1][0]]==order[4][0]|| map[locations[0][0]-2][locations[1][0]]==order[2][0]|| map[locations[0][0]-2][locations[1][0]]==order[11][0]|| map[locations[0][0]-2][locations[1][0]]==order[1][0]|| map[locations[0][0]-2][locations[1][0]]==order[12][0]){ a=0; } else{ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]-1][locations[1][0]]=order[9][0]; map[locations[0][0]-2][locations[1][0]]=order[2][0]; locations[0][0]--; } } if(map[locations[0][0]-1][locations[1][0]]==order[11][0]){ if( map[locations[0][0]-2][locations[1][0]]==order[0][0] || map[locations[0][0]-2][locations[1][0]]==order[12][0]|| map[locations[0][0]-2][locations[1][0]]==order[4][0]|| map[locations[0][0]-2][locations[1][0]]==order[2][0]|| map[locations[0][0]-2][locations[1][0]]==order[11][0]|| map[locations[0][0]-2][locations[1][0]]==order[1][0]){ a=0; } else{ if(map[locations[0][0]-2][locations[1][0]]==order[10][0]){ end=2; } map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]-1][locations[1][0]]=order[9][0]; map[locations[0][0]-2][locations[1][0]]=order[11][0]; locations[0][0]--; locations[2][0]--; } } if(map[locations[0][0]-1][locations[1][0]]==order[1][0]){ a=0; end=1; } if(map[locations[0][0]-1][locations[1][0]]==order[10][0]){ a=0; if(order[11][0]=='\0'){ end=2; score_player1++; } } } //////////////////////////////////////////////////////////////////////////// if(d==1){ if(attack!=0){ k_attak=0; while(k_attak!=attack){ if(locations[0][0]+k_attak<x&& map[locations[0][0]+k_attak][locations[1][0]]==order[1][0]||locations[0][0]+k_attak<x&&map[locations[0][0]+k_attak][locations[1][0]]==order[1][0]){ map[locations[0][0]+k_attak][locations[1][0]]=' '; } k_attak++; } } if( map[locations[0][0]+1][locations[1][0]]==order[0][0] || map[locations[0][0]+1][locations[1][0]]==order[4][0]) d=0; if(map[locations[0][0]+1][locations[1][0]]==' '){ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]+1][locations[1][0]]=order[9][0]; locations[0][0]++; } if(map[locations[0][0]+1][locations[1][0]]==order[3][0]){ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]+1][locations[1][0]]=order[9][0]; locations[0][0]++; score_player1=score_player1+rpoint[0]; } if(map[locations[0][0]+1][locations[1][0]]==order[1][0]){ d=0; end=1; } if(map[locations[0][0]+1][locations[1][0]]==order[10][0]){ d=0; if(order[11][0]=='\0'){ end=2; score_player1++; } } if(map[locations[0][0]+1][locations[1][0]]==order[2][0]){ if( map[locations[0][0]+2][locations[1][0]]==order[0][0] || map[locations[0][0]+2][locations[1][0]]==order[12][0]|| map[locations[0][0]+2][locations[1][0]]==order[4][0]|| map[locations[0][0]+2][locations[1][0]]==order[2][0]|| map[locations[0][0]+2][locations[1][0]]==order[11][0]|| map[locations[0][0]+2][locations[1][0]]==order[1][0]){ d=0; } else{ map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]+1][locations[1][0]]=order[9][0]; map[locations[0][0]+2][locations[1][0]]=order[2][0]; locations[0][0]++; } } if(map[locations[0][0]+1][locations[1][0]]==order[11][0]){ if( map[locations[0][0]+2][locations[1][0]]==order[0][0]|| map[locations[0][0]+2][locations[1][0]]==order[12][0] || map[locations[0][0]+2][locations[1][0]]==order[4][0]|| map[locations[0][0]+2][locations[1][0]]==order[2][0]|| map[locations[0][0]+2][locations[1][0]]==order[11][0]|| map[locations[0][0]+2][locations[1][0]]==order[1][0]){ d=0; } else{ if(map[locations[0][0]+2][locations[1][0]]==order[10][0]){ end=2; } map[locations[0][0]][locations[1][0]]=' '; if(put==1){ map[locations[0][0]][locations[1][0]]=order[13][1]; rep_put--; } map[locations[0][0]+1][locations[1][0]]=order[9][0]; map[locations[0][0]+2][locations[1][0]]=order[11][0]; locations[0][0]++; locations[2][0]++; } } } ////////////////////////////////////////////////////////////////// } int locate(){ /* In the map, it is played and positioned character, target ,object,opp*/ int i,j,counter_opp,counter_target,counter_points; int opp,target,points; i=j=counter_opp=counter_target=opp = target = points = counter_points=0; opp=target=points=0; for(j=0;j<y;j++){ for(i=0;i<x;i++){ if(map[i][j] == order[12][0]) counter_opp++; if(map[i][j] == order[10][0]) counter_target++; if(map[i][j] == order[3][0]) counter_points++; } } if(locations==NULL){ locations = (int ** )malloc(10*sizeof(int *)); locations[0]=(int *)malloc(sizeof(int)); locations[1]=(int *)malloc(sizeof(int)); locations[2]=(int *)malloc(sizeof(int)); locations[3]=(int *)malloc(sizeof(int)); locations[4]=(int *)malloc(counter_target+1*sizeof(int)); locations[5]=(int *)malloc(counter_target+1*sizeof(int)); locations[6]=(int *)malloc(counter_opp+1*sizeof(int)); locations[7]=(int *)malloc(counter_opp+1*sizeof(int)); locations[8]=(int *)malloc(counter_points+1*sizeof(int)); locations[9]=(int *)malloc(counter_points+1*sizeof(int)); } for(j=0;j<y;j++){ for(i=0;i<x;i++){ if(map[i][j] == order[10][0]){ locations[4][target] = i; locations[5][target] = j; target++; } if(map[i][j] == order[12][0]){ locations[6][opp] = i; locations[7][opp] = j; opp++; } if(map[i][j] == order[9][0]){ locations[0][0] = i; locations[1][0] = j; } if(map[i][j] == order[11][0]){ locations[2][0] = i; locations[3][0] = j; } } } return 0; } int show(){ AI(); int i,j,sec,dsec; j=0; i=0; sec=time_game/1; char buf[1000000]; setvbuf(stdout, buf, _IOFBF, sizeof(buf)); if(time_game>=0){ while(j<=y){ i=0; while(i<x){ printf("%c",map[i][j]); i++; } printf("\n"); j++; } if(time_game>0) printf("remaining time: %d \n",sec); if(order[12][0]!='\0'){ printf("%s :%d\n",ai_name,score_ai); } if(order[3][0]!='\0'){ printf("%s :%d\n",name_player1,score_player1); } } else{ results(); } return 0; } int errors(){ //If there is similarity in the variables or the insertion of the variable does not print... char **text_error; int i=0; text_error = (char**)malloc(15*sizeof(char*)); text_error[0]="solidblock";text_error[1]="deathblock";text_error[2]="moveblock";text_error[3]="rpoint"; text_error[4]="wall";text_error[5]="up";text_error[6]="down";text_error[7]="left";text_error[8]="right"; text_error[9]="character";text_error[10]="target";text_error[11]="object";text_error[12]="opp"; text_error[13]="put";text_error[14]="Exit"; system("cls"); for(i=0;i<=14;i++){ if(Error[0][i] == 1){ printf("\nError found in %s value name.\n",text_error[i]); erroring==-1; } } for(i=0;i<=14;i++){ if(Error[0][i] == 2 ){ printf("\nvalue name of %s used before.\n",text_error[i]); erroring==-1; } } for(i=0;i<=14;i++){ if(Error[0][i] == 1){ return -1; } } for(i=0;i<=14;i++){ if(Error[0][i] == 2){ return -1; } } return 0; } void read_order(char*file_name_order){ char chr; char line[20]; int i=0; int j=0; int num=0; for(i=0;i!=14;i++){ order[i][0]='\0'; } for(i=0;i!=20;i++){ for(j=0;j<15;j++){ Error[i][j]=0; } } order[12][0]='\0'; order[3][0]='\0'; order[11][0]='\0'; i=0; FILE *fil; fil=fopen(file_name_order,"r"); while((chr=fgetc(fil))!=EOF){ if(chr=='\n'){ line[i]='\0'; i=0; if(strstr(line,"solidblock")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][0]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][0] != 1) Error[0][0]=2; } ////bary rad kardan soase ezafe order[0][0]=line[i]; i=0; } if(strstr(line,"deathblock")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][1]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][1] != 1) Error[0][1]=2; } ////bary rad kardan soase ezafe order[1][0]=line[i]; i=0; } if(strstr(line,"moveblock")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe if(line[i]=='\0'){ Error[0][2]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][2] != 1) Error[0][2]=2; } order[2][0]=line[i]; i=0; } if(strstr(line,"rpoint")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][3]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][3] != 1) Error[0][3]=2; } ////bary rad kardan soase ezafe order[3][0]=line[i]; while(line[i]!=',') i++; i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } rpoint[0]=num; num=0; while(line[i]!=',') i++; i++; while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } rpoint[1]=num; i=0; } if(strstr(line,"wall")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][4]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][4] != 1) Error[0][4]=2; } ////bary rad kardan soase ezafe order[4][0]=line[i]; i=0; } if(strstr(line,"up")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][5]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][5] != 1) Error[0][5]=2; } ////bary rad kardan soase ezafe order[5][0]=line[i]; i=0; } if(strstr(line,"down")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][6]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][6] != 1) Error[0][6]=2; } ////bary rad kardan soase ezafe order[6][0]=line[i]; i=0; } if(strstr(line,"left")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][7]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][7] != 1) Error[0][7]=2; } ////bary rad kardan soase ezafe order[7][0]=line[i]; i=0; } if(strstr(line,"right")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][8]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][8] != 1) Error[0][8]=2; } ////bary rad kardan soase ezafe order[8][0]=line[i]; i=0; } if(strstr(line,"character")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][9]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][9] != 1) Error[0][9]=2; } ////bary rad kardan soase ezafe order[9][0]=line[i]; i=0; } if(strstr(line,"time")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe num=0; while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } time_game=num; i=0; } if(strstr(line,"target")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][10]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][10] != 1) Error[0][10]=2; } ////bary rad kardan soase ezafe order[10][0]=line[i]; i=0; } if(strstr(line,"object")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][11]=1; } ////bary rad kardan soase ezafe order[11][0]=line[i]; i=0; } if(strstr(line,"opp")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][12]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][12] != 1) Error[0][12]=2; } ////bary rad kardan soase ezafe order[12][0]=line[i]; while(line[i]!=',') i++; i++; order[12][1]=line[i]; i=0; } if(strstr(line,"attack")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe num=0; while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } attack=num; i=0; } if(strstr(line,"put")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][13]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][13] != 1) Error[0][13]=2; } ////bary rad kardan soase ezafe order[13][0]=line[i]; while(line[i]!=',') i++; i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe order[13][1]=line[i]; while(line[i]!=',') i++; i++; num=0; while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } rep_put=num; i=0; } if(strstr(line,"raindb")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe num=0; while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } raindb=num; i=0; } if(strstr(line,"Exit")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][14]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0] && Error[0][14] != 1) Error[0][14]=2; } ////bary rad kardan soase ezafe order[14][0]=line[i]; i=0; } } else{ line[i]=chr; i++; } } line[i]='\0'; i=0; if(strstr(line,"solidblock")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][0]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][0]=2; } ////bary rad kardan soase ezafe order[0][0]=line[i]; i=0; } if(strstr(line,"deathblock")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][1]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][1]=2; } ////bary rad kardan soase ezafe order[1][0]=line[i]; i=0; } if(strstr(line,"moveblock")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe if(line[i]=='\0'){ Error[0][2]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][2]=2; } order[2][0]=line[i]; i=0; } if(strstr(line,"rpoint")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][3]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][3]=2; } ////bary rad kardan soase ezafe order[3][0]=line[i]; while(line[i]!=',') i++; i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } rpoint[0]=num; num=0; while(line[i]!=',') i++; i++; while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } rpoint[1]=num; i=0; } if(strstr(line,"wall")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][4]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][4]=2; } ////bary rad kardan soase ezafe order[4][0]=line[i]; i=0; } if(strstr(line,"up")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][5]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][5]=2; } ////bary rad kardan soase ezafe order[5][0]=line[i]; i=0; } if(strstr(line,"down")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][6]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][6]=2; } ////bary rad kardan soase ezafe order[6][0]=line[i]; i=0; } if(strstr(line,"left")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][7]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][7]=2; } ////bary rad kardan soase ezafe order[7][0]=line[i]; i=0; } if(strstr(line,"right")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][8]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][8]=2; } ////bary rad kardan soase ezafe order[8][0]=line[i]; i=0; } if(strstr(line,"character")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][9]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][9]=2; } ////bary rad kardan soase ezafe order[9][0]=line[i]; i=0; } if(strstr(line,"time")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe num=0; while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } time_game=num; i=0; } if(strstr(line,"target")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][10]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][10]=2; } ////bary rad kardan soase ezafe order[10][0]=line[i]; i=0; } if(strstr(line,"object")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][11]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][11]=2; } ////bary rad kardan soase ezafe order[11][0]=line[i]; i=0; } if(strstr(line,"opp")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][12]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][12]=2; } ////bary rad kardan soase ezafe order[12][0]=line[i]; while(line[i]!=',') i++; i++; order[12][1]=line[i]; i=0; } if(strstr(line,"attack")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe num=0; while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } attack=num; i=0; } if(strstr(line,"put")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][13]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][13]=2; } ////bary rad kardan soase ezafe order[13][0]=line[i]; while(line[i]!=',') i++; i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe order[13][1]=line[i]; while(line[i]!=',') i++; i++; num=0; while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } rep_put=num; i=0; } if(strstr(line,"raindb")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; ////bary rad kardan soase ezafe num=0; while(line[i]>='0'&&line[i]<='9'){ num=num*10 + line[i]-'0'; i++; } raindb=num; i=0; } if(strstr(line,"Exit")!=NULL){ while(line[i]!='='){ i++; } i++; while(line[i]==' ') i++; if(line[i]=='\0'){ Error[0][14]=1; } for(j=0;j<=14;j++){ if(line[i]==order[j][0]) Error[0][14]=2; } ////bary rad kardan soase ezafe order[14][0]=line[i]; i=0; } } char** read_map(char ** map,char * file_name){ char chr; int i,j,k; char line_hleper[100]; int line; line=i=j=k=0; x=y=0; FILE *fil; fil=fopen(file_name,"r"); while((chr=fgetc(fil))!=EOF){ if(chr=='\n'){ line++; } if(line==1){ break; } else{ if(chr>='0' && chr<='9'|| chr=='x'){ line_hleper[i]=chr; i++; } } } line_hleper[i]='\0'; i=0; while(line_hleper[i]!='x'){ x=x*10+line_hleper[i]-'0'; i++; } i++; while(line_hleper[i]!='\0'){ y=y*10+line_hleper[i]-'0'; i++; } map=(char ** )malloc(x*sizeof(char*)); for (i=0;i!=x+1;i++){ map[i]=(char*)malloc(y*sizeof(char)); } i=j=0; while((chr=fgetc(fil))!=EOF){ if(chr=='\n'){ line++; } if(line==1){ while((chr=fgetc(fil))!=EOF){ if(chr=='\n'){ map[i][j]=map[i-1][j]; j++; i=0; } else{ map[i][j]=chr; i++; } } } else{ } } i=0; fclose(fil); return map; } int AI(){ int i,j,m,n; int location_target,location_opp,distance,counter; location_opp=location_target=counter=0; for(j=0;j<y;j++){ for(i=0;i<x;i++){ if(map[i][j] == order[12][0]) counter++; } } if(AI_assist == NULL){ AI_assist=(int*)malloc(counter*sizeof(int)); for(i=0;i<counter;i++){ AI_assist[i]=0; } } distance=x+y; while(counter > 0){ for(j=0;j<y;j++){ for(i=0;i<x;i++){ if(map[i][j] == order[12][1]){ if(distance >= (abs(locations[6][counter-1]-i)+abs((locations[7][counter-1]-j)))){ distance = (abs(locations[6][counter-1]-i)+abs((locations[7][counter-1]-j))); m=i; n=j; } } } } if(AI_assist[counter-1] < 13 && AI_assist[counter-1] > 0){ if(AI_assist[counter-1] == 1){ if(map[locations[6][counter-1]][locations[7][counter-1]+1] == order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]+1] == order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]+1] == order[4][0]){ AI_assist[counter-1]= 2; return 0; } if(map[locations[6][counter-1]+1][locations[7][counter-1]] == ' '){ AI_assist[counter-1] = 13; } else{ map[locations[6][counter-1]][locations[7][counter-1]+1] = order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]++; AI_assist[counter-1] = 1; } } if(AI_assist[counter-1] == 2){ if(map[locations[6][counter-1]][locations[7][counter-1]-1] == order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]-1] == order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]-1] == order[4][0]){ AI_assist[counter-1]= 1; return 0; } if(map[locations[6][counter-1]+1][locations[7][counter-1]] == ' '){ AI_assist[counter-1] = 13; } else{ map[locations[6][counter-1]][locations[7][counter-1]-1]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]--; AI_assist[counter-1] = 2; } } if(AI_assist[counter-1] == 3){ if(map[locations[6][counter-1]][locations[7][counter-1]+1] == order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]+1] == order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]+1] == order[4][0]){ AI_assist[counter-1]= 4; return 0; } if(map[locations[6][counter-1]-1][locations[7][counter-1]] == ' '){ AI_assist[counter-1] = 13; } else{ map[locations[6][counter-1]][locations[7][counter-1]+1]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]++; AI_assist[counter-1] = 3; } } if(AI_assist[counter-1] == 4){ if(map[locations[6][counter-1]][locations[7][counter-1]-1] == order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]-1] == order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]-1] == order[4][0]){ AI_assist[counter-1]= 3; return 0; } if(map[locations[6][counter-1]+1][locations[7][counter-1]] == ' '){ AI_assist[counter-1] = 13; } else{ map[locations[6][counter-1]][locations[7][counter-1]-1]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]--; AI_assist[counter-1] = 4; } } if(AI_assist[counter-1] == 5){ if(map[locations[6][counter-1]+1][locations[7][counter-1]] == order[0][0] || map[locations[6][counter-1]+1][locations[7][counter-1]] == order[1][0] || map[locations[6][counter-1]+1][locations[7][counter-1]] == order[4][0]){ AI_assist[counter-1]= 6; return 0; } if(map[locations[6][counter-1]][locations[7][counter-1]-1] == ' '){ } else{ map[locations[6][counter-1]+1][locations[7][counter-1]]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]++; AI_assist[counter-1] = 5; } } if(AI_assist[counter-1] == 6){ if(map[locations[6][counter-1]-1][locations[7][counter-1]] == order[0][0] || map[locations[6][counter-1]-1][locations[7][counter-1]] == order[1][0] || map[locations[6][counter-1]-1][locations[7][counter-1]] == order[4][0]){ AI_assist[counter-1]= 5; return 0; } if(map[locations[6][counter-1]][locations[7][counter-1]-1] == ' '){ AI_assist[counter-1] = 13; } else{ map[locations[6][counter-1]-1][locations[7][counter-1]]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]--; AI_assist[counter-1] = 6; } } if(AI_assist[counter-1] == 7){ if(map[locations[6][counter-1]+1][locations[7][counter-1]] == order[0][0] || map[locations[6][counter-1]+1][locations[7][counter-1]] == order[1][0] || map[locations[6][counter-1]+1][locations[7][counter-1]] == order[4][0]){ AI_assist[counter-1]= 8; return 0; } if(map[locations[6][counter-1]][locations[7][counter-1]+1] == ' '){ AI_assist[counter-1] = 13; } else{ map[locations[6][counter-1]+1][locations[7][counter-1]]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]++; AI_assist[counter-1] = 7; } } if(AI_assist[counter-1] == 8){ if(map[locations[6][counter-1]-1][locations[7][counter-1]] == order[0][0] || map[locations[6][counter-1]-1][locations[7][counter-1]] == order[1][0] || map[locations[6][counter-1]-1][locations[7][counter-1]] == order[4][0]){ AI_assist[counter-1]= 7; return 0; } if(map[locations[6][counter-1]][locations[7][counter-1]+1] == ' '){ AI_assist[counter-1] = 13; } else{ map[locations[6][counter-1]-1][locations[7][counter-1]]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]--; AI_assist[counter-1] = 8; } } } else if(locations[6][counter-1] != m && AI_assist[counter-1] == 0){ if(locations[6][counter-1] < m){ if( map[locations[6][counter-1]+1][locations[7][counter-1]] == order[0][0] || map[locations[6][counter-1]+1][locations[7][counter-1]]==order[1][0] || map[locations[6][counter-1]+1][locations[7][counter-1]]==order[4][0]){ AI_assist[counter-1]=1; } if(map[locations[6][counter-1]+1][locations[7][counter-1]]==order[12][1]){ map[locations[6][counter-1]+1][locations[7][counter-1]] = order[12][1]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]++; end=3; time_game=-1; } if(map[locations[6][counter-1]+1][locations[7][counter-1]]==' '){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]+1][locations[7][counter-1]]=order[12][0]; locations[6][counter-1]++; } if(map[locations[6][counter-1]+1][locations[7][counter-1]]==order[3][0]){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]+1][locations[7][counter-1]]=order[12][0]; locations[6][counter-1]++; score_ai=score_ai+rpoint[0]; } if(map[locations[6][counter-1]+1][locations[7][counter-1]]==order[2][0]){ if( map[locations[6][counter-1]+2][locations[7][counter-1]]=order[0][0] || map[locations[6][counter-1]+2][locations[7][counter-1]]==order[4][0]|| map[locations[6][counter-1]+2][locations[7][counter-1]]==order[2][0]|| map[locations[6][counter-1]+2][locations[7][counter-1]]==order[11][0]){ AI_assist[counter-1]=1; } else{ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]+1][locations[7][counter-1]]=order[12][0]; map[locations[6][counter-1]+2][locations[7][counter-1]]=order[2][0]; locations[6][counter-1]++; } } } if(locations[6][counter-1] > m){ if( map[locations[6][counter-1]-1][locations[7][counter-1]]==order[0][0] || map[locations[6][counter-1]-1][locations[7][counter-1]]==order[1][0]|| map[locations[6][counter-1]-1][locations[7][counter-1]]==order[4][0]){ AI_assist[counter-1]=3; } if(map[locations[6][counter-1]-1][locations[7][counter-1]]==order[12][1]){ map[locations[6][counter-1]-1][locations[7][counter-1]] = order[12][1]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]--; end=3; time_game=-1; } if(map[locations[6][counter-1]-1][locations[7][counter-1]]==' '){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]-1][locations[7][counter-1]]=order[12][0]; locations[6][counter-1]--; } if(map[locations[6][counter-1]-1][locations[7][counter-1]]==order[3][0]){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]-1][locations[7][counter-1]]=order[12][0]; locations[6][counter-1]--; score_ai=score_ai+rpoint[0]; } if(map[locations[6][counter-1]-1][locations[7][counter-1]]==order[2][0]){ if( map[locations[6][counter-1]-2][locations[7][counter-1]]==order[0][0] || map[locations[6][counter-1]-2][locations[7][counter-1]]==order[4][0]|| map[locations[6][counter-1]-2][locations[7][counter-1]]==order[2][0]|| map[locations[6][counter-1]-2][locations[7][counter-1]]==order[11][0]){ AI_assist[counter-1]=3; } else{ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]-1][locations[7][counter-1]]=order[12][0]; map[locations[6][counter-1]-2][locations[7][counter-1]]=order[2][0]; locations[6][counter-1]--; } } } } else if(locations[7][counter-1] != n && AI_assist[counter-1] == 0){ if(locations[7][counter-1] > n){ if( map[locations[6][counter-1]][locations[7][counter-1]-1]==order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]-1]==order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]-1]==order[4][0]){ AI_assist[counter-1] = 5; } if(map[locations[6][counter-1]][locations[7][counter-1]-1]==order[12][1]){ map[locations[6][counter-1]][locations[7][counter-1]-1] = order[12][1]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]--; end=3; time_game=-1; } if(map[locations[6][counter-1]][locations[7][counter-1]-1]==' '){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]-1]=order[12][0]; locations[7][counter-1]--; } if(map[locations[6][counter-1]][locations[7][counter-1]-1] == order[3][0]){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]-1]=order[12][0]; locations[7][counter-1]--; score_ai=score_ai+rpoint[0]; } if(map[locations[6][counter-1]][locations[7][counter-1]-1] == order[2][0]){ if( map[locations[6][counter-1]][locations[7][counter-1]-2]==order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]-2]==order[4][0]|| map[locations[6][counter-1]][locations[7][counter-1]-2]==order[11][0]|| map[locations[6][counter-1]][locations[7][counter-1]-2]==order[2][0]){ AI_assist[counter-1] = 5; } else{ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]-1] = order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]-2] = order[2][0]; locations[7][counter-1]--; } } } if(locations[7][counter-1] < n){ if( map[locations[6][counter-1]][locations[7][counter-1]+1]==order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]+1]==order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]+1]==order[4][0]){ AI_assist[counter-1] = 7; } if(map[locations[6][counter-1]][locations[7][counter-1]+1]==order[12][1]){ map[locations[6][counter-1]][locations[7][counter-1]+1] = order[12][1]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]++; end=3; time_game=-1; } if(map[locations[6][counter-1]][locations[7][counter-1]+1]==' '){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]+1]=order[12][0]; locations[7][counter-1]++; } if(map[locations[6][counter-1]][locations[7][counter-1]+1]==order[3][0]){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]+1]=order[12][0]; locations[7][counter-1]++; score_ai=score_ai+rpoint[0]; } if(map[locations[6][counter-1]][locations[7][counter-1]+1]==order[2][0]){ if( map[locations[6][counter-1]][locations[7][counter-1]+2]==order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]+2]==order[4][0]|| map[locations[6][counter-1]][locations[7][counter-1]+2]==order[2][0]){ AI_assist[counter-1] = 7; } else{ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]+1]=order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]+2]=order[2][0]; locations[7][counter-1]++; } } } } if(AI_assist[counter-1] < 26 && AI_assist[counter-1] > 13){ if(AI_assist[counter-1] == 14){ if(map[locations[6][counter-1]][locations[7][counter-1]+1] == order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]+1] == order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]+1] == order[4][0]){ AI_assist[counter-1]= 1; return 0; } if(map[locations[6][counter-1]+1][locations[7][counter-1]] == ' '){ AI_assist[counter-1] = 0; } else{ map[locations[6][counter-1]][locations[7][counter-1]+1] = order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]++; AI_assist[counter-1] = 14; } } if(AI_assist[counter-1] == 15){ if(map[locations[6][counter-1]][locations[7][counter-1]-1] == order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]-1] == order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]-1] == order[4][0]){ AI_assist[counter-1]= 14; return 0; } if(map[locations[6][counter-1]+1][locations[7][counter-1]] == ' '){ AI_assist[counter-1] = 0; } else{ map[locations[6][counter-1]][locations[7][counter-1]-1]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]--; AI_assist[counter-1] = 15; } } if(AI_assist[counter-1] == 16){ if(map[locations[6][counter-1]][locations[7][counter-1]+1] == order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]+1] == order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]+1] == order[4][0]){ AI_assist[counter-1]= 17; return 0; } if(map[locations[6][counter-1]-1][locations[7][counter-1]] == ' '){ AI_assist[counter-1] = 0; } else{ map[locations[6][counter-1]][locations[7][counter-1]+1]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]++; AI_assist[counter-1] = 16; } } if(AI_assist[counter-1] == 17){ if(map[locations[6][counter-1]][locations[7][counter-1]-1] == order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]-1] == order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]-1] == order[4][0]){ AI_assist[counter-1]= 16; return 0; } if(map[locations[6][counter-1]+1][locations[7][counter-1]] == ' '){ AI_assist[counter-1] = 0; } else{ map[locations[6][counter-1]][locations[7][counter-1]-1]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]--; AI_assist[counter-1] = 17; } } if(AI_assist[counter-1] == 18){ if(map[locations[6][counter-1]+1][locations[7][counter-1]] == order[0][0] || map[locations[6][counter-1]+1][locations[7][counter-1]] == order[1][0] || map[locations[6][counter-1]+1][locations[7][counter-1]] == order[4][0]){ AI_assist[counter-1]= 19; return 0; } if(map[locations[6][counter-1]][locations[7][counter-1]-1] == ' '){ AI_assist[counter-1] = 0; } else{ map[locations[6][counter-1]+1][locations[7][counter-1]]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]++; AI_assist[counter-1] = 18; } } if(AI_assist[counter-1] == 19){ if(map[locations[6][counter-1]-1][locations[7][counter-1]] == order[0][0] || map[locations[6][counter-1]-1][locations[7][counter-1]] == order[1][0] || map[locations[6][counter-1]-1][locations[7][counter-1]] == order[4][0]){ AI_assist[counter-1]= 18; return 0; } if(map[locations[6][counter-1]][locations[7][counter-1]-1] == ' '){ AI_assist[counter-1] = 0; } else{ map[locations[6][counter-1]-1][locations[7][counter-1]]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]--; AI_assist[counter-1] = 19; } } if(AI_assist[counter-1] == 20){ if(map[locations[6][counter-1]+1][locations[7][counter-1]] == order[0][0] || map[locations[6][counter-1]+1][locations[7][counter-1]] == order[1][0] || map[locations[6][counter-1]+1][locations[7][counter-1]] == order[4][0]){ AI_assist[counter-1]= 21; return 0; } if(map[locations[6][counter-1]][locations[7][counter-1]+1] == ' '){ AI_assist[counter-1] = 0; } else{ map[locations[6][counter-1]+1][locations[7][counter-1]]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]++; AI_assist[counter-1] = 20; } } if(AI_assist[counter-1] == 21){ if(map[locations[6][counter-1]-1][locations[7][counter-1]] == order[0][0] || map[locations[6][counter-1]-1][locations[7][counter-1]] == order[1][0] || map[locations[6][counter-1]-1][locations[7][counter-1]] == order[4][0]){ AI_assist[counter-1]= 20; return 0; } if(map[locations[6][counter-1]][locations[7][counter-1]+1] == ' '){ AI_assist[counter-1] = 0; } else{ map[locations[6][counter-1]-1][locations[7][counter-1]]= order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]--; AI_assist[counter-1] = 21; } } } else if(locations[7][counter-1] != n && AI_assist[counter-1] == 13){ if(locations[7][counter-1] > n){ if( map[locations[6][counter-1]][locations[7][counter-1]-1]==order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]-1]==order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]-1]==order[4][0]){ AI_assist[counter-1] = 19; } if(map[locations[6][counter-1]][locations[7][counter-1]-1]==order[12][1]){ map[locations[6][counter-1]][locations[7][counter-1]-1] = order[12][1]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]--; end=3; time_game=-1; } if(map[locations[6][counter-1]][locations[7][counter-1]-1]==' '){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]-1]=order[12][0]; locations[7][counter-1]--; } if(map[locations[6][counter-1]][locations[7][counter-1]-1] == order[3][0]){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]-1]=order[12][0]; locations[7][counter-1]--; score_ai=score_ai+rpoint[0]; } if(map[locations[6][counter-1]][locations[7][counter-1]-1] == order[2][0]){ if( map[locations[6][counter-1]][locations[7][counter-1]-2]==order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]-2]==order[4][0]|| map[locations[6][counter-1]][locations[7][counter-1]-2]==order[11][0]|| map[locations[6][counter-1]][locations[7][counter-1]-2]==order[2][0]){ AI_assist[counter-1] = 19; } else{ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]-1] = order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]-2] = order[2][0]; locations[7][counter-1]--; } } } if(locations[7][counter-1] < n){ if( map[locations[6][counter-1]][locations[7][counter-1]+1]==order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]+1]==order[1][0] || map[locations[6][counter-1]][locations[7][counter-1]+1]==order[4][0]){ AI_assist[counter-1] = 21; } if(map[locations[6][counter-1]][locations[7][counter-1]+1]==order[12][1]){ map[locations[6][counter-1]][locations[7][counter-1]+1] = order[12][1]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[7][counter-1]++; end=3; time_game=-1; } if(map[locations[6][counter-1]][locations[7][counter-1]+1]==' '){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]+1]=order[12][0]; locations[7][counter-1]++; } if(map[locations[6][counter-1]][locations[7][counter-1]+1]==order[3][0]){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]+1]=order[12][0]; locations[7][counter-1]++; score_ai=score_ai+rpoint[0]; } if(map[locations[6][counter-1]][locations[7][counter-1]+1]==order[2][0]){ if( map[locations[6][counter-1]][locations[7][counter-1]+2]==order[0][0] || map[locations[6][counter-1]][locations[7][counter-1]+2]==order[4][0]|| map[locations[6][counter-1]][locations[7][counter-1]+2]==order[2][0]){ AI_assist[counter-1] = 21; } else{ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]][locations[7][counter-1]+1]=order[12][0]; map[locations[6][counter-1]][locations[7][counter-1]+2]=order[2][0]; locations[7][counter-1]++; } } } } else if(locations[6][counter-1] != m && AI_assist[counter-1] == 13){ if(locations[6][counter-1] < m){ if( map[locations[6][counter-1]+1][locations[7][counter-1]] == order[0][0] || map[locations[6][counter-1]+1][locations[7][counter-1]]==order[1][0] || map[locations[6][counter-1]+1][locations[7][counter-1]]==order[4][0]){ AI_assist[counter-1]=15; } if(map[locations[6][counter-1]+1][locations[7][counter-1]]==order[12][1]){ map[locations[6][counter-1]+1][locations[7][counter-1]] = order[12][1]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]++; end=3; time_game=-1; } if(map[locations[6][counter-1]+1][locations[7][counter-1]]==' '){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]+1][locations[7][counter-1]]=order[12][0]; locations[6][counter-1]++; } if(map[locations[6][counter-1]+1][locations[7][counter-1]]==order[3][0]){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]+1][locations[7][counter-1]]=order[12][0]; locations[6][counter-1]++; score_ai=score_ai+rpoint[0]; } if(map[locations[6][counter-1]+1][locations[7][counter-1]]==order[2][0]){ if( map[locations[6][counter-1]+2][locations[7][counter-1]]=order[0][0] || map[locations[6][counter-1]+2][locations[7][counter-1]]==order[4][0]|| map[locations[6][counter-1]+2][locations[7][counter-1]]==order[2][0]|| map[locations[6][counter-1]+2][locations[7][counter-1]]==order[11][0]){ AI_assist[counter-1]=14; } else{ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]+1][locations[7][counter-1]]=order[12][0]; map[locations[6][counter-1]+2][locations[7][counter-1]]=order[2][0]; locations[6][counter-1]++; } } } if(locations[6][counter-1] > m){ if( map[locations[6][counter-1]-1][locations[7][counter-1]]==order[0][0] || map[locations[6][counter-1]-1][locations[7][counter-1]]==order[1][0]|| map[locations[6][counter-1]-1][locations[7][counter-1]]==order[4][0]){ AI_assist[counter-1]=16; } if(map[locations[6][counter-1]-1][locations[7][counter-1]]==order[12][1]){ map[locations[6][counter-1]-1][locations[7][counter-1]] = order[12][1]; map[locations[6][counter-1]][locations[7][counter-1]] = ' '; locations[6][counter-1]--; end=3; time_game=-1; } if(map[locations[6][counter-1]-1][locations[7][counter-1]]==' '){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]-1][locations[7][counter-1]]=order[12][0]; locations[6][counter-1]--; } if(map[locations[6][counter-1]-1][locations[7][counter-1]]==order[3][0]){ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]-1][locations[7][counter-1]]=order[12][0]; locations[6][counter-1]--; score_ai=score_ai+rpoint[0]; } if(map[locations[6][counter-1]-1][locations[7][counter-1]]==order[2][0]){ if( map[locations[6][counter-1]-2][locations[7][counter-1]]==order[0][0] || map[locations[6][counter-1]-2][locations[7][counter-1]]==order[4][0]|| map[locations[6][counter-1]-2][locations[7][counter-1]]==order[2][0]|| map[locations[6][counter-1]-2][locations[7][counter-1]]==order[11][0]){ AI_assist[counter-1]=16; } else{ map[locations[6][counter-1]][locations[7][counter-1]]=' '; map[locations[6][counter-1]-1][locations[7][counter-1]]=order[12][0]; map[locations[6][counter-1]-2][locations[7][counter-1]]=order[2][0]; locations[6][counter-1]--; } } } } counter--; } }
763233c59aa1ad6aa314322efea6fa284affac69
[ "C" ]
3
C
alihaghighat/Game_console
bb3fe7ca45f4266421c730598aee0869a7f0a345
f235d1d98537f201799da674c5518b963826c776
refs/heads/main
<repo_name>ShimmyLikeJamie/tic_tac_toe<file_sep>/README.md # tic_tac_toe https://theodinproject.com/courses/javascript/lessons/tic-tac-toe-javascript <file_sep>/scripts/main.js const gameBoard = (function() { //Putting tiles in an array because the project specs demand it tiles = [] //grab all the DOM elements names = document.getElementById('names') clear = document.getElementById('clear') win = document.getElementById('win') turn = document.getElementById('turn') //function to create player const createPlayer = function(name, turn, piece){ return { name: name, turn: turn, piece: piece } } playerOne = createPlayer('Player One', true, 'x') playerTwo = createPlayer('Player Two', false, 'o') turn.innerHTML = playerOne.name //Initialize and capture tiles on board for (i=0; i < 9; i++) { let id = i + 1 tile = document.getElementById(`${id}`) tiles.push(tile) tile.innerHTML = " "; } //Create and attach function to change names button names.onclick = function () { playerOne.name = prompt('Enter a new name for player one'); playerTwo.name = prompt('Enter a new name for player two'); (playerOne.turn === true) ? turn.innerHTML = playerOne.name : turn.innerHTML = playerTwo.name } //Attach clear function to clear button clear.onclick = function() { for (i = 0; i < tiles.length; i++) { tiles[i].innerHTML = " " } } //Attach function to cells for taking turns cells = document.querySelectorAll('td') for (i = 0; i < cells.length; i++){ cells[i].onclick = function() { if (this.innerHTML === ' ') { if (playerOne.turn) { this.innerHTML = playerOne.piece if (check_for_win(playerOne.piece)) { win.innerHTML = `${playerOne.name} wins!` } else if (check_for_draw()) { win.innerHTML = 'It\'s a draw!' } turn.innerHTML = playerTwo.name } else { this.innerHTML = playerTwo.piece if (check_for_win(playerTwo.piece)) { win.innerHTML = `${playerTwo.name} wins!` } else if (check_for_draw()) { win.innerHTML = 'It\'s a draw!' } turn.innerHTML = playerOne.name } playerTwo.turn = !playerTwo.turn playerOne.turn = !playerOne.turn } } } //function to check for win const check_for_win = function(marker) { if ((tiles[0].innerHTML == marker && tiles[1].innerHTML == marker && tiles[2].innerHTML == marker) || (tiles[3].innerHTML == marker && tiles[4].innerHTML == marker && tiles[5].innerHTML == marker) || (tiles[6].innerHTML == marker && tiles[7].innerHTML == marker && tiles[8].innerHTML == marker) || (tiles[0].innerHTML == marker && tiles[3].innerHTML == marker && tiles[6].innerHTML == marker) || (tiles[1].innerHTML == marker && tiles[4].innerHTML == marker && tiles[7].innerHTML == marker) || (tiles[2].innerHTML == marker && tiles[5].innerHTML == marker && tiles[8].innerHTML == marker) || (tiles[0].innerHTML == marker && tiles[4].innerHTML == marker && tiles[8].innerHTML == marker) || (tiles[2].innerHTML == marker && tiles[4].innerHTML == marker && tiles[6].innerHTML == marker)) { return true } return false } //function to check for draw const check_for_draw = function() { draw = true for (i = 0; i < tiles.length; i++) { if (tiles[i].innerHTML == ' ') {return false} } return true } })();
50c3838e3ec4a09694c62c16af1a426087e64591
[ "Markdown", "JavaScript" ]
2
Markdown
ShimmyLikeJamie/tic_tac_toe
ce7b9c057c21ba9aca6bd8f841c0b6b85c08b752
07ad2c0ae143d2a0120a3c66f047024e4bfc219e
refs/heads/master
<file_sep>using System; using Eventos.IO.Domain.Eventos; namespace Eventos.IO.Console.Tests { class Program { static void Main(string[] args) { var evento = new Evento( "Nome do Evento", "Descrição curta", "Descrição longa", DateTime.Now, DateTime.Now, false, 50, false, "Nome da Empresa" ); System.Console.WriteLine(evento.ToString()); System.Console.ReadKey(); } } } <file_sep>using System; using Eventos.IO.Domain.Core; using Eventos.IO.Domain.Core.Base; namespace Eventos.IO.Domain.Eventos.Events { public class EventoExcluidoEvent : Event { public EventoExcluidoEvent(Guid id) { this.Id = id; this.AggregateId = id; } public Guid Id { get; set; } } }<file_sep>using System; using Eventos.IO.Domain.Core; namespace Eventos.IO.Domain.Core.Base { public abstract class Command : Message { public Command() { TimeStamp = DateTime.Now; } public DateTime TimeStamp { get; private set; } } }<file_sep>using System.Collections.Generic; using System.Linq; namespace Eventos.IO.Domain.Core.Base { public class BaseResponse { private bool _success; private IList<string> _erros; public BaseResponse() { _success = true; _erros = new List<string>(); } public bool Success { get => _success && !Erros.Any(); } public IEnumerable<string> Erros { get => _erros; } public void Fail() { _success = false; } public void Fail(string messageError) { Fail(); _erros.Add(messageError); } } }<file_sep>namespace Eventos.IO.Domain.Core.Interface { public interface IUnitOfWork { int Save(); } }<file_sep>using System; using System.Collections.Generic; using Eventos.IO.Domain.Core.Base; using Eventos.IO.Domain.Eventos.Validations; using Eventos.IO.Domain.Organizadores; using FluentValidation.Results; namespace Eventos.IO.Domain.Eventos { public class Evento : Entity { public Evento (string nome, string descricaoCurta, string descricaoLonga, DateTime dataInicio, DateTime dataFim, bool gratuito, decimal valor, bool online, string nomeEmpresa) { this.Id = Guid.NewGuid (); this.Nome = nome; this.DescricaoCurta = descricaoCurta; this.DescricaoLonga = descricaoLonga; this.DataInicio = dataInicio; this.DataFim = dataFim; this.Gratuito = gratuito; this.Valor = valor; this.Online = online; this.NomeEmpresa = nomeEmpresa; } public string Nome { get; private set; } public string DescricaoCurta { get; private set; } public string DescricaoLonga { get; private set; } public DateTime DataInicio { get; private set; } public DateTime DataFim { get; private set; } public bool Gratuito { get; private set; } public decimal Valor { get; private set; } public bool Online { get; private set; } public string NomeEmpresa { get; private set; } public Categoria Categoria { get; private set; } public ICollection<Tag> Tags { get; private set; } public Endereco Endereco { get; private set; } public Organizador Organizador { get; private set; } public bool EhValido() { Validar (); return _validationResult.IsValid; } public IList<ValidationFailure> ObterErrosValidacao() { return _validationResult.Errors; } #region Privates private ValidationResult _validationResult; private void Validar () { var eventoValidation = new EventoValidation (); eventoValidation.ValidarNome (); eventoValidation.ValidarValor (); _validationResult = eventoValidation.Validate (this); } #endregion } }<file_sep>using Eventos.IO.Domain.Core.Interface; namespace Eventos.IO.Domain.Eventos.Interfaces { public interface IEventoRepository : IRepository<Evento> { } }<file_sep>using Eventos.IO.Domain.Core.Base; namespace Eventos.IO.Domain.Core.Interface { public interface IHandler<in T> where T : Message { void Handle(T message); } }<file_sep>using System; namespace Eventos.IO.Domain.Core.Base { public abstract class Entity { public Guid Id { get; protected set; } #region Equals public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) return false; var compareTo = obj as Entity; if(ReferenceEquals(this, compareTo)) return true; if(ReferenceEquals(null, compareTo)) return false; return Id.Equals(compareTo.Id); } public static bool operator ==(Entity a, Entity b) { if(ReferenceEquals(a, null) && ReferenceEquals(b, null)) return true; if(ReferenceEquals(a, null) || ReferenceEquals(b, null)) return false; return a.Equals(b); } public static bool operator !=(Entity a, Entity b) { return !(a == b); } public override int GetHashCode() { return (GetType().GetHashCode() * 907) + Id.GetHashCode(); } #endregion public override string ToString() { return $"{GetType().Name} [Id: {Id.ToString()}]"; } } }<file_sep>using Eventos.IO.Domain.Core.Base; namespace Eventos.IO.Domain.Core.Interface { public interface IBus { void SendCommand<T>(T theCommand) where T : Command; void RaiseEvent<T>(T theEvent) where T : Event; } }<file_sep>using System; using Eventos.IO.Domain.Core; using Eventos.IO.Domain.Core.Base; using Eventos.IO.Domain.Core.Interface; using Eventos.IO.Domain.Core.Interfaces; using Eventos.IO.Domain.Eventos.Commands; using Eventos.IO.Domain.Eventos.Events; using Eventos.IO.Domain.Eventos.Interfaces; namespace Eventos.IO.Domain.Eventos.Handlers { public class EventoCommandHandler : BaseCommandHandler, IHandler<RegistrarEventoCommand>, IHandler<AtualizarEventoCommand>, IHandler<ExcluirEventoCommand> { #region Construtor / Propriedades private readonly IEventoRepository _eventoRepository; public EventoCommandHandler(IEventoRepository eventoRepository, IUnitOfWork unitOfWork, IBus bus, IDomainNotificationHandler<DomainNotification> notification) :base(unitOfWork, bus, notification) { this._eventoRepository = eventoRepository; } #endregion public void Handle(RegistrarEventoCommand message) { var evento = new Evento( message.Nome, null, null, message.DataInicio, message.DataFim, message.Gratuito, message.Valor, message.Online, message.NomeEmpresa ); if(!evento.EhValido()){ NotificarValidacoesErro(evento.ObterErrosValidacao()); } // TODO // Organizador pode registrar evento ? _eventoRepository.Add(evento); if(Commit().Success) { Console.WriteLine("Evento registrado com sucesso"); _bus.RaiseEvent(new EventoRegistradoEvent(evento.Id, evento.Nome, evento.DataInicio, evento.DataFim, evento.Gratuito, evento.Valor, evento.Online, evento.NomeEmpresa)); } } public void Handle(AtualizarEventoCommand message) { throw new System.NotImplementedException(); } public void Handle(ExcluirEventoCommand message) { throw new System.NotImplementedException(); } } }<file_sep>using System; using Eventos.IO.Domain.Core; using Eventos.IO.Domain.Core.Base; namespace Eventos.IO.Domain.Eventos.Events { public class EventoRegistradoEvent : Event { public EventoRegistradoEvent(Guid id, string nome, DateTime dataInicio, DateTime dataFim, bool gratuito, decimal valor, bool online, string nomeEmpresa) { this.Id = id; this.Nome = nome; this.DataInicio = dataInicio; this.DataFim = dataFim; this.Gratuito = gratuito; this.Valor = valor; this.Online = online; this.NomeEmpresa = nomeEmpresa; this.AggregateId = id; } public Guid Id { get; private set; } public string Nome { get; private set; } public DateTime DataInicio { get; private set; } public DateTime DataFim { get; private set; } public bool Gratuito { get; private set; } public decimal Valor { get; private set; } public bool Online { get; private set; } public string NomeEmpresa { get; private set; } } }<file_sep>using System.Collections.Generic; using Eventos.IO.Domain.Core.Base; using Eventos.IO.Domain.Core.Interface; namespace Eventos.IO.Domain.Core.Interfaces { public interface IDomainNotificationHandler<T> : IHandler<T> where T : Message { bool HasNotifications(); List<T> GetNotifications(); } }<file_sep>using FluentValidation; namespace Eventos.IO.Domain.Eventos.Validations { public class EventoValidation : AbstractValidator<Evento> { public void ValidarNome(){ RuleFor(x => x.Nome) .NotNull() .NotEmpty() .WithMessage("Nome não deve estar vazio"); } public void ValidarValor(){ RuleFor(x => x.Valor) .NotNull() .When(x => x.Gratuito == false) .WithMessage("Valor inválido"); } } }<file_sep>using Eventos.IO.Domain.Core.Base; namespace Eventos.IO.Domain.Organizadores { public class Organizador : Entity { } }<file_sep>using System; using System.Collections.Generic; using System.Linq.Expressions; using Eventos.IO.Domain.Core; using Eventos.IO.Domain.Core.Base; namespace Eventos.IO.Domain.Core.Interface { public interface IRepository<TEntity> : IDisposable where TEntity : Entity { void Add(TEntity obj); TEntity Get(Guid id); IEnumerable<TEntity> List(); void Update(TEntity entity); void Remove(Guid id); IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> preicate); bool Save(); } }<file_sep>using System; namespace Eventos.IO.Domain.Core.Base { public abstract class Event : Message { public Event() { this.TimeStamp = DateTime.Now; } public DateTime TimeStamp { get; set; } } }<file_sep>using System; using System.Collections.Generic; using Eventos.IO.Domain.Core.Interface; using Eventos.IO.Domain.Core.Interfaces; using FluentValidation.Results; namespace Eventos.IO.Domain.Core.Base { public abstract class BaseCommandHandler { protected readonly IUnitOfWork _unitOfWork; protected readonly IDomainNotificationHandler<DomainNotification> _notifications; protected readonly IBus _bus; protected BaseCommandHandler(IUnitOfWork unitOfWork, IBus bus, IDomainNotificationHandler<DomainNotification> notifications) { _unitOfWork = unitOfWork; _bus = bus; _notifications = notifications; } protected void NotificarValidacoesErro(IEnumerable<ValidationFailure> errors) { foreach(var error in errors) { Console.WriteLine(error.ErrorMessage); _bus.RaiseEvent(new DomainNotification(error.PropertyName, error.ErrorMessage)); } } public BaseResponse Commit() { var response = new BaseResponse(); if(_notifications.HasNotifications()) { response.Fail(); return response; } try { var saveResult = _unitOfWork.Save(); if(saveResult > 0) return response; var errorMessage = "Erro ao salvar os dados no banco"; _bus.RaiseEvent(new DomainNotification("Commit", errorMessage)); response.Fail(errorMessage); } catch(Exception e) { response.Fail(e.Message); } return response; } } }<file_sep>using System; using Eventos.IO.Domain.Core; using Eventos.IO.Domain.Core.Base; namespace Eventos.IO.Domain.Eventos.Commands { public class ExcluirEventoCommand : Command { public ExcluirEventoCommand(Guid id) { Id = id; AggregateId = id; } public Guid Id { get; private set; } } }
5fb345a6b4165112cb9ed29ac0039eaa529ae541
[ "C#" ]
19
C#
guisfits/Eventos.IO
aa047c41c949fd1c7a5f69b0c39fc1ab58ee7a6d
96ba4e9106109dc8cf663aa84ba437763eeb6b2b
refs/heads/master
<file_sep>import java.io.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; /** * Created by abhisheky on 22/2/16. */ public class SampleGeneration{ public static void main(String [] args){ Optics optics= new Optics(); optics.getDataPoints(); ArrayList<Point> dataPoints= optics.points; Integer[] array= {10000, 25000, 100000}; Random random= new Random(); int size=0, index; String fileName="sample"; for (Integer sampleSize: array){ HashMap<Integer, Point> map=new HashMap<Integer, Point>(); size=0; while (size< sampleSize){ index = random.nextInt(200000); if (!map.containsKey(index)) { map.put(index, dataPoints.get(index)); size++; } } try{ BufferedWriter writer= new BufferedWriter(new FileWriter(new File(fileName+sampleSize+".txt"))); for (Map.Entry<Integer, Point> entry: map.entrySet()) writer.write(entry.getValue().container.get(0)+" " + entry.getValue().container.get(1)+"\n"); writer.close(); }catch (IOException ex){ ex.printStackTrace(); } } } }<file_sep>__author__="abhishek" import scipy.io as sio import numpy as np import sys import operator import matplotlib.pyplot as plt def read_mat(file_,filename1): filename1=open(filename1,"w") mat=sio.loadmat(file_) dict_=mat[mat.keys()[0]] for elements in dict_: filename1.write(str(elements[0])+"\n") filename1.close() def read_original(filename,filename__): file_=open(filename,"r") dict_={} for lines in file_: lines=int(lines.rstrip('\n')) if lines in dict_: dict_[lines]+=1 else: dict_[lines]=1 file_.close() """file_=open(filename__,"w") dict__=sorted(dict_.items(),key=lambda x:x[1],reverse=True) for vals in dict__: file_.write(str(vals)+'\n') file_.close()""" dict_=dict_.values() dict_.sort(reverse=True) return dict_[:5010] def readFile(filename,filename__): lst,lst2=[],[] filename=open(filename,"r") for lines in filename: temp=[int(str_) for str_ in lines.split()] lst.append(temp[1]) lst2.append(temp[:2]) filename.close() file_=open(filename__,"w") for nodes in lst2: file_.write(str(tuple(nodes))+'\n') file_.close() lst.sort(reverse=True) return lst[:5010] def plot_figure(lst1,lst2,label1,label2,label_,Dataset): plt.figure() plt.plot(lst1,label=label1) plt.plot(lst2,label=label2) plt.ylabel(label_) plt.title(Dataset) plt.legend(loc=1) plt.show() filename1=sys.argv[1] filename2=sys.argv[2] filename3=sys.argv[3] filename4=sys.argv[4] #original_x_count=read_original(filename1,filename5) #original_y_count=read_original(filename2,filename6) space_saving_x_count=readFile(filename1,filename3) space_saving_y_count=readFile(filename2,filename4) """accuracy_x=[] accuracy_y=[] top_k=[100,500,1000,5000] for k in top_k: difference_x=[abs(original_x_count[i]-space_saving_x_count[i]) for i in range(k)] difference_y=[abs(original_y_count[i]-space_saving_y_count[i]) for i in range(k)] accuracy_x.append(sum(difference_x)/k*1.0) accuracy_y.append(sum(difference_y)/k*1.0) """ """print accuracy_x print accuracy_y plt.figure() plt.plot(top_k,accuracy_x,label="x-Dataset") plt.plot(top_k,accuracy_y,label="y-Dataset") plt.legend(loc=1) plt.xlabel('k') plt.ylabel('Average Error') plt.title('Average error vs k') plt.show() """ """plot_figure(original_x_count,space_saving_x_count,"frequency-original","frequency-Space-Saving","Frequency","x-Dataset") plot_figure(original_y_count,space_saving_y_count,"frequency-original","frequency-Space-Saving","Frequency","y-Dataset")""" <file_sep>#!/usr/bin/env python import os for i in range(1,4): # generates LLVM IR os.system("clang -emit-llvm -S -c -o test"+str(i)+".ll test"+str(i)+".c") # prints instructions count os.system("opt -stats -analyze -instcount test"+str(i)+".ll") # printing the alias analysis os.system("opt -aa-eval -disable-output test"+str(i)+".ll")<file_sep>1. Assignment2_1_a.py - implementation of part of question 1 2. Assignment2_1_b_i*.py are the implementations of part of b of question 1 3. fp_growth.py, fp_growth_1_b_ii.py and fp_growth_1_b_iii.py are the modifies fp_grwoth implementations for parta b.i and b.ii respectively 4. 1b_plot_i.py and plot_1b_ii.py were used to plot the graph for 1.b.i and 1.b.ii 5. *.png files are the comparison graphs for part b of the question <file_sep>#include "llvm/Pass.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instructions.h" #include "llvm/Support/raw_ostream.h" #include <map> #include <vector> #include <iostream> #include <string> #include <utility> #include <set> using namespace std; using namespace llvm; class Escape : public ModulePass { public: map<string, vector<vector<string> > > points_to_info; map<string, int> escaped_locations; vector<string> malloc_locations; map<string, vector<map<string, int> > > myMap; static char ID; Escape() : ModulePass(ID) { } bool runOnModule(Module &M); void createInitialConstraints(Function &F); void printVars(); bool checkIfMallocd(string str); void getAllEscapingInfo(); void printMyMap(); bool checkIfVisited(string str, int, vector<pair<string, int> >); void printSet(set<string>); }; bool Escape::checkIfVisited(string str, int num, vector<pair<string, int> >visited){ for(size_t i=0;i< visited.size();i++){ if(visited[i].first == str && visited[i].second == num) return true; } return false; } void Escape::getAllEscapingInfo(){ pair<string, int> temp_pair; vector<pair<string, int> > visited; vector<pair<string, int> > queue; map<string, int> temp_map; for(map<string, vector<map<string, int> > >::iterator iter= myMap.begin(); iter != myMap.end(); iter++){ vector<map<string, int> > vect= iter->second; string ptr= iter->first; for(size_t i=0; i< vect.size(); i++){ temp_map= vect[i]; if(temp_map.size() > 0){ temp_pair= make_pair(iter->first, i); visited.push_back(temp_pair); queue.push_back(temp_pair); while(queue.size() > 0){ temp_map= myMap[queue[0].first][queue[0].second]; for(map<string, int>::iterator iter2=temp_map.begin(); iter2!=temp_map.end(); iter2++){ string str1= iter2->first; int t1= iter2->second; if(!checkIfVisited(str1, t1, visited)){ temp_pair=make_pair(str1, t1); visited.push_back(temp_pair); queue.push_back(temp_pair); for(size_t k=t1, l=i; k< points_to_info[str1].size(); k++,l++){ for(size_t j=0; j< points_to_info[str1][k].size(); j++){ points_to_info[iter->first][l].push_back(points_to_info[str1][k][j]); } } } } queue.erase(queue.begin()+0); } } } } } bool Escape::checkIfMallocd(string str){ size_t i; for(i=0;i< malloc_locations.size(); i++){ if(malloc_locations[i] == str) return true; } return false; } bool Escape::runOnModule(Module &M) { //First pass to collect the information about the variables that have been malloced for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) { if ((*F).getName() == "main") { createInitialConstraints(*F); } } //printMyMap(); getAllEscapingInfo(); printVars(); return false; } void Escape::printMyMap(){ for(map<string, vector<map<string, int> > >::iterator iter = myMap.begin(); iter != myMap.end(); iter++){ cout << iter->first <<":" << endl; vector<map<string, int> > vect= iter->second; for(size_t i=0; i< vect.size(); i++){ if(vect[i].size()>0 ){ cout << i <<":"; map<string, int> map_ = vect[i]; for(map<string, int>::iterator iter_= map_.begin(); iter_!=map_.end(); iter_++){ cout << iter_->first <<"-" << iter_->second <<" " ; } cout << endl; } } cout <<endl; } } void Escape::printSet(set<string> set_){ for(set<string>::iterator iter= set_.begin(); iter!=set_.end(); iter++){ cout << *iter <<" "; } } void Escape::printVars(){ // printing the escaped locations unsigned int i; set<string> set_; for(map<string, int>::iterator iter= escaped_locations.begin(); iter!=escaped_locations.end(); iter++){ string ptr= iter->first; for(i=iter->second; i< points_to_info[ptr].size(); i++){ vector<string> vect= points_to_info[ptr][i] ; for(size_t j=0; j< vect.size(); j++){ if(checkIfMallocd(vect[j])) set_.insert(vect[j]); } } } printSet(set_); cout <<endl; for(map<string, vector<vector<string> > >::iterator iter= points_to_info.begin(); iter!=points_to_info.end(); iter++){ cout << iter->first << " "; set_.clear(); for(i=0;i< iter->second[0].size(); i++) set_.insert(iter->second[0][i]); printSet(set_); cout <<endl; } } void Escape::createInitialConstraints(Function &F) { unsigned int i; bool malloc_flag=false; vector<string> load_ptrs; vector<int> load_counters; for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) { switch (I->getOpcode()) { case Instruction::Alloca: { if(I->getName() != "retval"){ points_to_info[I->getName()] = vector<vector<string> >(); myMap[I->getName()] = vector<map<string, int> >(); for(i=0;i<30;i++){ points_to_info[I->getName()].push_back(vector<string>()); myMap[I->getName()].push_back(map<string, int> ()); } } break; } case Instruction::Call: { CallInst *CI = dyn_cast<CallInst>(I); string function_name= CI->getCalledFunction()->getName(); if(function_name=="malloc"){ load_ptrs.push_back(CI->getName()); malloc_flag= true; load_counters.push_back(0); malloc_locations.push_back(CI->getName()); }else{ for(i=0;i< load_ptrs.size(); i++){ if(escaped_locations.find(load_ptrs[i]) == escaped_locations.end()) escaped_locations[load_ptrs[i]] = 100; if(escaped_locations[load_ptrs[i]] > load_counters[i]) escaped_locations[load_ptrs[i]] = load_counters[i]; } load_ptrs.clear(); load_counters.clear(); } break; } case Instruction::Store: { StoreInst *SI = dyn_cast<StoreInst>(I); //Value *v = SI->getValueOperand(); Value *ptr = SI->getPointerOperand(); if(malloc_flag){ if(ptr->getName()!="") load_ptrs.push_back(ptr->getName()); points_to_info[load_ptrs[1]][load_counters[0]].push_back(load_ptrs[0]); malloc_flag=false; load_ptrs.clear(); load_counters.clear(); }else if(ptr->getName()!="retval"){ if(load_ptrs.size()==1){ load_ptrs.push_back(ptr->getName()); load_counters.push_back(-1); } int counter1= load_counters[1]+1; string load_str= load_ptrs[1]; //cout << myMap["i"].size() <<endl; myMap[load_str][counter1][load_ptrs[0]]= load_counters[0]; //cout << load_ptrs[0] << " " << load_counters[0] <<endl; //cout << load_ptrs[1] << " " << load_counters[1] <<endl; vector<string> ld_pts1= points_to_info[load_ptrs[0]][load_counters[0]]; for(i=0;i < ld_pts1.size(); i++) points_to_info[load_str][counter1].push_back(ld_pts1[i]); load_ptrs.clear(); load_counters.clear(); } break; } case Instruction::Load: { LoadInst *LI = dyn_cast<LoadInst>(I); Value *ptr = LI->getPointerOperand(); string var= ptr->getName(); int size= load_ptrs.size(); if(malloc_flag){ load_counters[0]+=1; if(var!="") load_ptrs.push_back(var); }else if(var!=""){ load_ptrs.push_back(var); load_counters.push_back(0); }else load_counters[size-1]+=1; break; } } } } } // Register the pass. char Escape::ID = 0; static RegisterPass<Escape> X("escape", "Escape Analysis Pass"); <file_sep>#include <stdio.h> int sumArray(int arr[], int len){ int i, sum=0; for(i=0; i<len ; sum+=arr[i],i++); return sum; } int main(int argc, char** argv){ int arr[]={4,-1,5,6,-9}; printf("sum: %d\n", sumArray(arr,5)); }<file_sep>#include "llvm/Pass.h" #include "llvm/IR/CFG.h" #include "llvm/Analysis/CFG.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instructions.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/Function.h" #include "llvm/Analysis/LoopIterator.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/ADT/APInt.h" #include <stdlib.h> #include <stdio.h> #include <map> #include <vector> #include <iostream> #include <string> #include <utility> #include <set> using namespace std; using namespace llvm; class Bounds : public ModulePass { public: static char ID; vector<string> params; map<string, map<string, vector<pair<string, int> > > > blocks_info; vector<string> programVars; map<string, int> temp_vars; map<string, vector<pair<string, int> > > arrays_size; bool size_flag; std::vector<BasicBlock*> block_vect; vector< pair <string, pair< vector< pair<string, int> > , vector< pair<string, int> > > > >result; Bounds() : ModulePass(ID) { } bool runOnModule(Module &M); void createInitialConstraints(Function &F); void makeBackwardPass(Function &); void printPostOrder(BasicBlock*); bool checkIfParam(string); void handleBinaryOperations(BinaryOperator* ops, map<string, vector<pair<string, int> > >&); vector<pair<string, int> > operandCheck(Value*, map<string, vector<pair<string, int> > >); vector<pair<string, int> > multiplyOperands(int op1, vector<pair<string, int> > ); void addParams(map<string, vector<pair<string, int> > >&); void handleStore(StoreInst* strInst, map<string, vector<pair<string, int> > >&); void handleSext(User*, map<string, vector<pair<string, int> > >&); void handleCall(CallInst*, map<string, vector<pair<string, int> > >&); bool checkIfDeclared(string); map<string, vector<pair<string, int> > > blockTraversal(); void traverseSucc(BasicBlock*); bool stackCheck(string block_name); void instructionsEvaluator(Instruction*, map<string, vector<pair<string, int> > >&); void printConrtraints(); void printExpr(vector<pair<string, int> >); }; void Bounds::printExpr(vector<pair<string, int> > expr){ unsigned int len= params.size(); unsigned int len_expr= expr.size(); int coeff=0; for(unsigned int i=0; i< len; i++){ coeff = 0; for(unsigned int j=0; j< len_expr; j++){ if(expr[j].first == params[i]){ coeff= expr[j].second; break; } } cout << coeff <<" "; } } void Bounds::printConrtraints(){ params.push_back(""); unsigned int len= result.size(); for(unsigned int i=0; i< len; i++){ cout << result[i].first <<" "; vector<pair<string, int> > index_expr= result[i].second.first; vector<pair<string, int> > size_expr= result[i].second.second; printExpr(index_expr); printExpr(size_expr); cout <<endl; } } bool Bounds::checkIfDeclared(string temp){ int len= programVars.size(); for(int i=0; i< len; i++) if(programVars[i]== temp) return true; return false; } void Bounds::addParams(map<string, vector<pair<string, int> > >& temp_map){ unsigned int len= params.size(); for(unsigned int i=0; i< len ; i++) temp_map[params[i]]= vector<pair<string, int> >{make_pair(params[i],1)}; } vector<pair<string, int> > Bounds::operandCheck(Value* op, map<string, vector<pair<string, int> > > temp_map){ vector<pair<string, int> > temp_vect; if(ConstantInt::classof(op)){ uint64_t op_int= dyn_cast<ConstantInt>(op)->getLimitedValue(); temp_vect.push_back(make_pair("", op_int)); }else{ string op_str= op->getName(); if(op_str=="") op_str= dyn_cast<User>(op)->getOperand(0)->getName(); if(temp_map.find(op_str) != temp_map.end()) temp_vect= temp_map[op_str]; } return temp_vect; } vector<pair<string, int> > Bounds::multiplyOperands(int op1, vector<pair<string, int> > op2_info){ vector<pair<string, int> > vect_var; int len= op2_info.size(); for(int i=0; i< len; i++) vect_var.push_back(make_pair(op2_info[i].first, op2_info[i].second * op1)); return vect_var; } void Bounds::handleBinaryOperations(BinaryOperator *ops, map<string, vector<pair<string, int> > >& temp_map){ string varName= ops->getName(); string opCode = ops->getOpcodeName(); Value* op1= ops->getOperand(0); Value* op2= ops->getOperand(1); vector<pair<string, int> > vect_var; vector<pair<string, int> > op1_info, op2_info; op1_info = operandCheck(op1, temp_map); op2_info = operandCheck(op2, temp_map); int len1= op1_info.size(); int len2= op2_info.size(); if(len1 > 0 && len2 > 0 ){ if(opCode=="mul"){ if(op1_info[0].first=="") vect_var= multiplyOperands(op1_info[0].second, op2_info); else vect_var = multiplyOperands(op2_info[0].second, op1_info); //exit(0); }else if(opCode=="add"){ for(int i=0; i< len1; i++) vect_var.push_back(make_pair(op1_info[i].first, op1_info[i].second)); for(int i=0; i< len2; i++){ pair<string, int> pair_ = op2_info[i]; bool flag=false; for(int j=0; j< len1; j++){ if(pair_.first == vect_var[j].first){ vect_var[j].second += pair_.second; flag= true; break; } } if(!flag) vect_var.push_back(make_pair(pair_.first, pair_.second)); } }else if(opCode=="sub"){ for(int i=0; i< len1; i++) vect_var.push_back(make_pair(op1_info[i].first, op1_info[i].second)); for(int i=0; i< len2; i++){ pair<string, int> pair_ = op2_info[i]; bool flag=false; for(int j=0; j< len1; j++){ if(pair_.first == vect_var[j].first){ vect_var[j].second -= pair_.second; flag= true; break; } } if(!flag) vect_var.push_back(make_pair(pair_.first, -1*pair_.second)); } } } temp_map[varName]= vect_var; } bool Bounds::checkIfParam(string operand){ for(unsigned int i=0; i< params.size(); i++) if(params[i]==operand) return true; return false; } void Bounds::handleStore(StoreInst* strInst, map<string, vector<pair<string, int> > >& temp_map){ Value* src= strInst->getValueOperand(); Value* dest= strInst->getPointerOperand(); string destName= dest->getName(); vector<pair<string, int> > info_vect; if(ConstantInt::classof(src)){ uint64_t src_int = dyn_cast<ConstantInt>(src)->getLimitedValue(); info_vect.push_back(make_pair("", src_int)); }else{ string srcName= src->getName(); if(srcName=="") srcName= dyn_cast<User>(src)->getOperand(0)->getName(); if(temp_map.find(srcName) != temp_map.end()){ vector<pair<string, int> > temp_vect= temp_map[srcName]; int len=temp_vect.size(); for(int i=0;i< len; i++) info_vect.push_back(temp_vect[i]); } } if(size_flag){ arrays_size[destName]= info_vect; size_flag=false; }else temp_map[destName]=info_vect; } void Bounds::handleSext(User* inst,map<string, vector<pair<string, int> > >&temp_map){ string varName= inst->getName(); Value* opd= inst->getOperand(0); vector<pair<string, int> > expr_vect; if(ConstantInt::classof(opd)){ uint64_t val= dyn_cast<ConstantInt>(opd)->getLimitedValue(); expr_vect.push_back(make_pair("", val)); }else{ string op_name= opd->getName(); if(op_name=="") op_name= dyn_cast<User>(opd)->getOperand(0)->getName(); if(temp_map.find(op_name) != temp_map.end()){ vector<pair<string, int> > temp_vect= temp_map[op_name]; int len= temp_vect.size(); for(int i=0; i< len; i++) expr_vect.push_back(make_pair(temp_vect[i].first, temp_vect[i].second)); } } temp_map[varName] = expr_vect; } void Bounds::handleCall(CallInst* inst, map<string, vector<pair<string, int> > >&temp_map){ string destName= inst->getName(); Value* arg= inst->getArgOperand(0); vector<pair<string, int> > size_vect; if(ConstantInt::classof(arg)){ uint64_t size= dyn_cast<ConstantInt>(arg)->getLimitedValue(); size_vect.push_back(make_pair("", size/4)); }else{ string argName= arg->getName(); if(argName=="") argName= dyn_cast<User>(arg)->getOperand(0)->getName(); if(temp_map.find(argName) != temp_map.end()){ vector<pair<string, int> > temp_vect= temp_map[argName]; int len= temp_vect.size(); for(int i=0; i< len; i++) size_vect.push_back(make_pair(temp_vect[i].first, temp_vect[i].second/4)); } } temp_map[destName]= size_vect; } bool Bounds::runOnModule(Module &M) { //forward pass to collect the information about the assignment expressions for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) { // if((*F).getName()=="fun") createInitialConstraints(*F); break; } return false; } void Bounds::instructionsEvaluator(Instruction* I, map<string, vector<pair<string, int> > >& block_info){ string opCode= I->getOpcodeName(); if(opCode=="alloca"){ User* inst= dyn_cast<User>(I); programVars.push_back(inst->getName()); } if(opCode=="store"){ StoreInst* SI= dyn_cast<StoreInst>(I); handleStore(SI, block_info); }else if(opCode=="add"){ BinaryOperator *ops= dyn_cast<BinaryOperator>(I); handleBinaryOperations(ops, block_info); }else if(opCode=="sub"){ BinaryOperator* ops= dyn_cast<BinaryOperator>(I); handleBinaryOperations(ops, block_info); }else if(opCode=="mul"){ BinaryOperator* ops= dyn_cast<BinaryOperator>(I); handleBinaryOperations(ops, block_info); }else if(opCode=="sext"){ User* val= dyn_cast<User>(I); handleSext(val, block_info); }else if(opCode=="call"){ CallInst* inst= dyn_cast<CallInst>(I); handleCall(inst, block_info); size_flag=true; } } map<string, vector<pair<string, int> > > Bounds::blockTraversal(){ arrays_size.clear(); unsigned int len= block_vect.size(); map<string, vector<pair<string, int> > > block_info; addParams(block_info); for(unsigned int i=0; i< len-1; i++){ BasicBlock *BB = block_vect[i]; string block_name= BB->getName(); if(block_name.substr(0,5)=="while" && block_name.substr(6,4)=="body"){ block_info.clear(); addParams(block_info); } for(BasicBlock::iterator I= BB->begin(), E= BB->end(); I != E; I++){ instructionsEvaluator(I,block_info); } } //cout << arrays_size.size() <<endl; return block_info; } bool Bounds::stackCheck(string block_name){ unsigned int len= block_vect.size(); for(unsigned int i=0; i<len; i++) if(block_vect[i]->getName() == block_name) return true; return false; } void Bounds::traverseSucc(BasicBlock* block){ block_vect.push_back(block); //outs() << block->getName() << "\n"; for(BasicBlock::iterator I= block->begin(), E= block->end(); I != E; I++){ string opcode= I->getOpcodeName(); User* instr= dyn_cast<User>(I); string varName= instr->getName(); if(opcode=="getelementptr"){ map<string, vector<pair<string, int> > > pred_info = blockTraversal(); for(BasicBlock::iterator I_new = block->begin(), E_new = block->end(); I_new != E_new; I_new++){ User* instr_new= dyn_cast<User>(I_new); if(instr_new->getName() == varName){ // for(map<string, vector<pair<string, int> > >::iterator iter= pred_info.begin(); // iter!= pred_info.end(); iter++){ // //if(checkIfDeclared(iter->first)){ // cout << iter->first <<": "; // for(unsigned int i=0; i < iter->second.size(); i++) // cout << iter->second[i].first <<" " << iter->second[i].second <<" "; // cout <<endl; // //} // } // cout <<endl ; Value* arr= instr_new ->getOperand(0); Value* index= instr_new->getOperand(1); vector<pair<string, int> > size_expr, index_expr; string arrName= arr->getName(); if(arrName=="") arrName= dyn_cast<User>(arr)->getOperand(0)->getName(); if(arrays_size.find(arrName) != arrays_size.end()) size_expr= arrays_size[arrName]; if(ConstantInt::classof(index)){ uint64_t size_ = dyn_cast<ConstantInt>(index)->getLimitedValue(); index_expr.push_back(make_pair("",size_)); }else{ string indexVar= index->getName(); if(indexVar == "") indexVar= dyn_cast<User>(index)->getOperand(0)->getName(); if(pred_info.find(indexVar) != pred_info.end()) index_expr= pred_info[indexVar]; } int len1= size_expr.size(); int len2= index_expr.size(); if(len1==0 || len2==0){ size_expr.clear(); unsigned int num_params= params.size(); for(unsigned int i=0; i< num_params; i++) size_expr.push_back(make_pair(params[i],0)); size_expr.push_back(make_pair("",0)); result.push_back(make_pair(varName, make_pair(size_expr, size_expr))); }else{ result.push_back(make_pair(varName, make_pair(index_expr, size_expr))); } break; } instructionsEvaluator(I_new, pred_info); } } } for(succ_iterator I= succ_begin(block), E= succ_end(block); I != E; I++){ BasicBlock * succ= *I; string succName= succ->getName(); if(stackCheck(succName)){ TerminatorInst* inst= succ->getTerminator(); unsigned int numSucc= inst->getNumSuccessors(); for(unsigned int i=0; i< numSucc; i++){ succ= inst->getSuccessor(i); if(!stackCheck(succ->getName())) break; } } traverseSucc(succ); } block_vect.pop_back(); } void Bounds::createInitialConstraints(Function &F) { F.viewCFG(); Function::ArgumentListType &arglist= F.getArgumentList(); for(Function::ArgumentListType::iterator begin= arglist.begin(), end= arglist.end(); begin!=end; ++begin) params.push_back(begin->getName()); //params.push_back(""); size_flag=false; BasicBlock& BB= F.getEntryBlock(); traverseSucc(&BB); printConrtraints(); } // Register the pass. char Bounds::ID = 0; static RegisterPass<Bounds> X("safe", "ArrayIndex checking pass");<file_sep>import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; /** * Created by abhisheky on 17/3/16. */ class TrackInfo implements Cloneable{ public int orderCounter; public int prevCounter; public int prevNode; public int[] visited; public int[] visitOrder; public TrackInfo(Integer nodes){ orderCounter=0; prevCounter=0; prevNode=0; visited= new int[nodes+1]; visitOrder= new int[nodes+1]; } public TrackInfo clone(){ TrackInfo info; try{ info=(TrackInfo)super.clone(); info.visited= this.visited.clone(); info.visitOrder= this.visitOrder.clone(); info.orderCounter= this.orderCounter; info.prevNode= this.prevNode; return info; }catch (CloneNotSupportedException ex){ ex.printStackTrace(); throw new RuntimeException(); } } } class Code implements Comparable<Code>{ public Integer srcNode; public Integer destNode; public String edgeCode; public Code(Integer srcNode, Integer destNode, String edgeCode){ this.srcNode= srcNode; this.edgeCode= edgeCode; this.destNode= destNode; } public Code(){ } public int compareTo(Code c){ int temp1= this.srcNode - c.srcNode; if(temp1 < 0) return -1; else if(temp1 > 0) return 1; temp1= this.destNode - c.destNode; if(temp1 < 0) return -1; else if(temp1 > 0) return 1; return this.edgeCode.compareTo(c.edgeCode); } } class Pair_<T,P> implements Comparable<Pair_<T,P>>{ public T first; public P second; public int compareTo(Pair_<T,P> pair){ return ((String)(this.second)).compareTo((String)pair.second); } public Pair_(T first, P second){ this.first= first; this.second= second; } } public class Graph { public int nNodes; public int nEdges; public ArrayList<ArrayList<Pair_<Integer, String>>> adList; public HashMap<Integer, String> nodesMap; public Graph(int nNodes) { this.nNodes= nNodes; this.nEdges=0; nodesMap = new HashMap<>(); adList= new ArrayList<>(); for(int i=0; i< nNodes; i++) adList.add(new ArrayList<>()); } public void addNode(Integer nodeNum, String nodeLabel){ nodesMap.put(nodeNum, nodeLabel); } public void append(ArrayList<Integer> destList, ArrayList<Integer> srcList){ Iterator<Integer> iterator= srcList.iterator(); while (iterator.hasNext()) destList.add(iterator.next()); } public static void main(String [] args){ File file= new File("res.txt"); try { BufferedReader reader= new BufferedReader(new FileReader(file)); String str; while ((str= reader.readLine())!= null) { } reader.close(); }catch (IOException ex){ ex.printStackTrace(); } } }<file_sep>__author__ = 'abhisheky' import matplotlib.pyplot as plt epsilon=[ 0.0102, 0.0105, 0.0115, 0.012, 0.122, 0.0124 ] clusters=[176, 106, 9, 8, 6, 6] plt.xlabel("epsilon") plt.ylabel("numbe of clusters extracted") plt.title("epsilon' vs number of clusters extracted") plt.plot(epsilon, clusters) plt.show()<file_sep>final: first.tmp second.tmp first.tmp: Q1/Assignment2.py python Q1/Assignment2.py second.tmp: Assignment2_3.py python Assignment2_3.py clean: rm -f *.tmp<file_sep>import os,subprocess lst=['.05','.10','.25','.5','.95'] for k in lst: os.system("./gSpan -f out2.txt -s " +k+" -o -i") # __author__ = 'abhishek' # import numpy as np # import sys # import random # beta = 0.15 # #implementation for bipartite graph # def read_graph(filename): # edges,nodes0,nodes1=[],[],[] # file_=open(filename,"r") # for lines in file_: # temp=[int(val) for val in lines.split()[:2]] # edges.append(temp) # if temp[0] not in nodes0: # nodes0.append(temp[0]) # if temp[1] not in nodes1: # nodes1.append(temp[1]) # nodes0.sort() # nodes1.sort() # last=nodes0[-1] # for nodes in nodes1: # nodes0.append(nodes+last) # for edge in edges: # edge[1]=edge[1]+last # del nodes1 # neighbors_count={} # for edge in edges: # if edge[1] not in neighbors_count: # neighbors_count[edge[1]]=1 # else: # neighbors_count[edge[1]]+=1 # if edge[0] not in neighbors_count: # neighbors_count[edge[0]]=1 # else: # neighbors_count[edge[0]]+=1 # file_.close() # return nodes0,edges,neighbors_count # def create_adjacency_matrix(edges,len_,neighbors_count): # sim_mat=[[0 for val in range(len_)] for val_ in range(len_)] # for edge in edges: # sim_mat[edge[0]][edge[1]]=1.0/neighbors_count[edge[1]] # sim_mat[edge[1]][edge[0]]=1.0/neighbors_count[edge[0]] # ad_mat=np.array(sim_mat) # return ad_mat # def RWR(sim_mat,rand_node): # len_=len(sim_mat[0]) # start_vector=np.array([[0] for val in range(len_)]) # rank_mat=np.array([[0] for val in range(len_)]) # start_vector[rand_node,0]=1.0 # rank_mat[rand_node,0]=1.0 # sim_mat=sim_mat*beta # start_vector=start_vector*(1-beta) # for i in range(20): # temp=np.dot(sim_mat,rank_mat) # rank_mat=np.add(rank_mat,temp) # return list(rank_mat) # filename=sys.argv[1] # nodes,edges,neighbors_count=read_graph(filename) # sim_mat=create_adjacency_matrix(edges,len(nodes)+1,neighbors_count) # top_100=sorted(neighbors_count,key=neighbors_count.get,reverse=True) # top_100=[val for val in top_100 if val>943][:100] # del nodes # del edges # del neighbors_count # for nodes in top_100: # rank_matrix=RWR(sim_mat,nodes) # rank_matrix.sort(reverse=True) # print nodes # print rank_matrix[:100]<file_sep>import matplotlib.pyplot as plt # lpot for 1b_i lst=[[10 ,21.605417], [25 ,17.538208], [75,19.691659], [100 ,20.952556]] lst2=[[10, 0.333225], [25, 1.444862], [75, 22.277402], [100, 45.840727] ] plt.figure() plt.plot([x[0] for x in lst],[x[1] for x in lst],label="apriori") plt.plot([x[0] for x in lst2], [x[1] for x in lst2],label="fp-growth") plt.legend(loc=1) plt.xlabel('minimum threshold(%)') plt.ylabel('time') plt.title('title') plt.show() <file_sep># Directories #INPUT_DIR=/home/raghesh/phd/sem8/pa/A2/scripts/input BUILD_DIR=/home/pauser/llvm-build/lib/Analysis SRC_DIR=/home/pauser/llvm-source/lib/Analysis TEST_CASES_DIR=/home/pauser/llvm-build/lib/Analysis/CS12B032/testcases # Escape Library SHARED_LIB=/home/pauser/llvm-build/Release+Asserts/lib/LLVMEscape.so if [ $# -lt 1 ] then echo "usage: ./eval.sh <ROLL NUMBER>" exit fi # Extract student directory #tar xvzf $INPUT_DIR/$1.tar.gz -C $SRC_DIR #tar xvzf $INPUT_DIR/$1.tar.gz -C $BUILD_DIR # Build Escape library cd $BUILD_DIR/$1 make clean make if [ $? -ne 0 ] then echo "Build Error" exit fi cd - # Execute testcases let marks=0 echo "Evaluating $1" echo "-------------" echo -n "$1 |" >> result for testcase in `ls $TEST_CASES_DIR/*.c` do clang -O0 $testcase -emit-llvm -S -o $testcase.ll 2> /dev/null opt -load $SHARED_LIB -escape $testcase.ll -o $testcase.bc 2> /dev/null > $TEST_CASES_DIR/student.out cat $TEST_CASES_DIR/student.out ./eval_escapes.py $testcase.out $TEST_CASES_DIR/student.out if [ $? -eq 0 ] then marks=`expr $marks + .5` echo -n ".5 | " >> result else echo -n "0 | " >> result fi ./eval_pointsto.py $testcase.out $TEST_CASES_DIR/student.out if [ $? -eq 0 ] then marks=`expr $marks + .5` echo -n "0.5 | " >> result else echo -n "0 | " >> result fi done echo "Total Marks = $marks / 7" >> result rm $TEST_CASES_DIR/student.out $SHARED_LIB <file_sep>writeTo = open("retail.csv","w") with open("retail.dat","r") as readFile: for lines in readFile: lines=lines.strip() lines=lines.replace(' ', ',') writeTo.write("%s\n"%lines) writeTo.close() <file_sep>__author__ = 'abhisheky' from matplotlib import pyplot as plt import numpy as np def getClusterCount(infile): list_=[] with open(infile, "r") as reader: for line in reader: nodes=len(line.split()) if nodes>2: list_.append(nodes) return list_ def plotHistogram(list_): plt.title("histogram of cluster sizes") plt.xlabel("cluster-size") plt.ylabel("size-freuency/count") plt.hist(list_) plt.show() def writeToFile(list_,fileName): with open(fileName,"w") as writeFile: for value in list_: writeFile.write(str(value)+"\n") ground_fileName="com-amazon.top5000.cmty.txt"; list_= getClusterCount(ground_fileName) plotHistogram(list_) writeToFile(sorted(list_),"histFile.txt") list_= getClusterCount("dump.data.amazon.mci.I123") plotHistogram(list_) writeToFile(sorted(list_),"histFile_amazon.txt")<file_sep>// Sample LLVM Pass file for A4 (CS6843) #include "llvm/Pass.h" #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Instructions.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Analysis/LoopIterator.h" #include "llvm/IR/Constants.h" #include <set> #include <map> #include <iostream> #include <vector> #include <string> #include <cstdio> using namespace llvm; using namespace std; /** * This class encapsulates an LLVM instruction along with the source-file line number * from where this instruction has been derived. * NOTE: getDebugLoc() used in the constructor will not work if we don't use "-g" * switch in clang. */ class DebugInst { public: Instruction* instruction; // pointer to an LLVM instruction. int line; // line number of that source-code statement from which this instruction has been generated. DebugInst(Instruction* inst) { instruction = inst; line = instruction->getDebugLoc().getLine(); } bool operator<(DebugInst other) const { if (line < other.line) { return true; } else if (line > other.line) { return false; } else { return instruction < other.instruction; } } }; /** * This class represents the notion of a phase, as explained in the Specs. * Note a minor change in the set instSet: * Instead of just the line number, we also store the pointer to the * Instruction that may get executed in this phase. * This is needed to enable race condition detection. */ class Phase { public: set<int> startSet; // line numbers (in source file) of barriers where this phase starts. set<int> endSet; // line numbers (in source file) of barriers where this phase ends. set<DebugInst> instSet; // instructions (alongwith their line numbers in source file) that may get executed in this phase. // Generally, the argument to this constructor will be the ending set of barriers of the previous phase. Phase(set<int> *inSet) { for(set<int>::iterator it = inSet->begin(); it != inSet->end(); it++) { startSet.insert(*it); } } void setEndSetAndInstSet(set<int> endBarriers, set<DebugInst> phaseInstructions){ for(set<int>::iterator it= endBarriers.begin(), end= endBarriers.end(); it != end; ++it) endSet.insert(*it); for(set<DebugInst>::iterator it= phaseInstructions.begin(), end= phaseInstructions.end(); it != end; ++it) instSet.insert(*it); } void dumpInformation() const { for (set<int>::iterator it = startSet.begin(); it != startSet.end(); it++) { outs() << *it << " "; } if(startSet.size() != 0) { outs() << "\n"; } for (set<int>::iterator it = endSet.begin(); it != endSet.end(); it++) { outs() << *it << " "; } if(endSet.size() != 0) { outs() << "\n"; } set<int> allLines; for (set<DebugInst>::iterator it = instSet.begin(); it != instSet.end(); it++) { allLines.insert(it->line); } for (set<int>::iterator it = allLines.begin(); it != allLines.end(); it++) { outs() << *it << " "; } if(allLines.size() != 0) { outs() << "\n"; } outs() << "---\n"; } bool operator<(Phase other) const { if(startSet != other.startSet) { return startSet < other.startSet; } if (endSet != other.endSet) { return endSet < other.endSet; } return instSet < other.instSet; } }; /** * This class represents the notion of a race condition pair. */ class RaceCondition { public: RaceCondition(int i1, int i2) { if (i1 < i2) { this->i1 = i1; this->i2 = i2; } else { this->i1 = i2; this->i2 = i1; } } void dumpInformation() const { outs() << i1 << " " << i2 << "\n"; } bool operator<(RaceCondition other) const { if (i1 == other.i2 && i2 == other.i1) { return false; } if (i1 < other.i1) { return true; } else if (i1 > other.i1){ return false; } else { if (i2 < other.i2) { return true; } else { return false; } } } private: int i1; int i2; }; class SVE{ public: int sveBit; }; class Happens : public ModulePass { public: static char ID; set<Phase> nonSVE_MHP_set; // Set of phases obtained in path-insensitive MHP analysis set<Phase> SVE_MHP_set; // Set of phases obtained in path-sensitive MHP analysis set<RaceCondition> nonSVE_RC_set; // Set of race conditions obtained using path-insensitive MHP analysis set<RaceCondition> SVE_RC_set; // Set of race conditions obtained using path-sensitive MHP analysis map<string, bool> globals; map<string, bool> paramsList; map<string, Instruction*> varsList; map<string, vector<int> > readVarMap; map<string, vector<int> > writtenVarMap; map<string, bool> blockType; map<string, map<string, set<pair<Instruction*, bool> > > > blockInfo; string currBlockName; Happens() : ModulePass(ID) { } bool runOnModule(Module &M); void non_SVE_MHPAnalysis(Function&); void SVE_MHP_Analysis(Function &); set<int> blockTraversal(vector<DebugInst>&, vector<DebugInst> &, set<int>); void blockTraversalSVE(vector<DebugInst>&, set<int>&, vector<BasicBlock*>&, set<int>&, vector<DebugInst>&, set<DebugInst>&); void expressionDetermination(BasicBlock*, vector<BasicBlock*>&); bool checkForTermination(set<int>, set<Phase>); void copyEndToStart(vector<DebugInst> &, vector<DebugInst> &); void getGlobals(Module &); void getFunctionParamsAndVars(Function &F); bool checkIfArg(string); void printInfo(set<int> startBarriers, set<int> endBarriers, set<DebugInst> phases); void checkAndInsertLastPhase(); bool checkIfBlockVisited(BasicBlock*, vector<BasicBlock*>); void dumpInformation(); DebugInst getNextInstruction(Instruction*); void raceConditionDetection(set<Phase>&, set<RaceCondition>&); void getReadOrWrittenVars(DebugInst); DebugInst createDebugInst(Value*, DebugInst); void generateRaceConditions(set<RaceCondition>&); map<string, set<pair<Instruction*, bool> > > fillSVEInfo(); void calculatePathInfo(vector<BasicBlock*>); map<string, set<pair<int, bool> > > cloneVarInfoMap(); void handleStore(Instruction*, map<string, set<pair<Instruction*, bool > > > &); void handleBinaryOps(Instruction*, map<string, set<pair<Instruction*, bool > > > &); bool checkIfSVE(set<pair<Instruction*, bool> >); bool getVarType(Value*, map<string, set<pair<Instruction*, bool> > >&); void mergeBlockInfo(map<string, set<pair<Instruction*, bool> > >); void handleBranch(Instruction* inst, map<string, set<pair<Instruction*, bool> > >& varInfo); void printSVEInfo(); void printInitialSVEInfo(map<string, set<pair<Instruction*, bool> > >); bool checkIfVisited(vector<BasicBlock*> blockStack, BasicBlock *BB); vector<DebugInst> copyDebugInstVector(vector<DebugInst>&); set<DebugInst> copyDebugInstSet(set<DebugInst>&); set<int> copyIntSet(set<int>&); vector<BasicBlock*> copyBlockVector(vector<BasicBlock*>& vect); void checkForGlobalWrite(Function&); }; void Happens::dumpInformation() { //----DON'T CHANGE THIS CODE BELOW----// outs() << "nonSVE_MHP\n"; for(set<Phase>::iterator it = nonSVE_MHP_set.begin(); it != nonSVE_MHP_set.end(); it++) { it->dumpInformation(); } outs() << "SVE_MHP\n"; for(set<Phase>::iterator it = SVE_MHP_set.begin(); it != SVE_MHP_set.end(); it++) { it->dumpInformation(); } outs() << "nonSVE_RC\n"; for(set<RaceCondition>::iterator it = nonSVE_RC_set.begin(); it != nonSVE_RC_set.end(); it++) { it->dumpInformation(); } outs() << "SVE_RC\n"; for(set<RaceCondition>::iterator it = SVE_RC_set.begin(); it != SVE_RC_set.end(); it++) { it->dumpInformation(); } //----DON'T CHANGE THIS CODE ABOVE----// } bool Happens::checkIfBlockVisited(BasicBlock *BB, vector<BasicBlock*> visited){ for(vector<BasicBlock*>::iterator iter= visited.begin(), end= visited.end(); iter != end; ++iter){ if(*iter == BB) return true; } return false; } void Happens::printInitialSVEInfo(map<string, set<pair<Instruction*, bool> > > varMap){ for(map<string, set<pair<Instruction*, bool> > >::iterator iter= varMap.begin(), end= varMap.end(); iter != end; ++iter){ cout << iter->first <<": "; set<pair<Instruction*, bool> > tempSet= iter->second; for(set<pair<Instruction*, bool> >::iterator iter2= tempSet.begin(), end2= tempSet.end(); iter2 != end2; ++iter2){ DebugInst debug= DebugInst(iter2->first); cout << "(" << debug.line <<","<< iter2->second <<") "; } cout <<endl; } for(map<string, bool>::iterator iter= paramsList.begin(), end= paramsList.end(); iter!= end; ++iter) cout << iter->first <<": " << iter->second <<endl; for(map<string, bool>::iterator iter= globals.begin(), end= globals.end(); iter != end; ++iter) cout << iter->first <<": " << iter->second <<endl; cout <<endl; } void Happens::printSVEInfo(){ for(map<string, map<string, set<pair<Instruction*, bool> > > >::iterator iter= blockInfo.begin(), end= blockInfo.end(); iter != end; ++iter){ cout << "blockName: "<< iter->first <<endl; map<string, set<pair<Instruction*, bool> > > varInfo= iter->second; printInitialSVEInfo(varInfo); } } DebugInst Happens::getNextInstruction(Instruction* inst){ BasicBlock::iterator I(inst); return DebugInst(++I); } set<int> Happens::blockTraversal(vector<DebugInst>& startInstSet, vector<DebugInst> &endInstSet, set<int> startBarriers){ set<int> endBarriers; set<DebugInst> phaseInformation; string opCode, funcName; Instruction* inst; vector<BasicBlock*> visitedBlocks; while(!startInstSet.empty()){ DebugInst debug= startInstSet[0]; while(debug.instruction != NULL){ inst= debug.instruction; opCode= inst->getOpcodeName(); if((opCode=="store" || opCode =="icmp") && debug.line != 0){ phaseInformation.insert(debug); }else if(opCode=="call"){ CallInst* callInst= dyn_cast<CallInst>(inst); funcName= callInst->getCalledFunction()->getName(); if(funcName=="barrier"){ endBarriers.insert(debug.line); debug= getNextInstruction(debug.instruction); endInstSet.push_back(debug); break; } }else if(opCode=="ret"){ endBarriers.insert(-1); break; }else if(opCode=="br"){ BasicBlock *BB= inst->getParent(); for(succ_iterator iter= succ_begin(BB), end= succ_end(BB); iter != end; ++iter){ if(!checkIfBlockVisited(*iter, visitedBlocks)){ visitedBlocks.push_back(*iter); Instruction* I= (*iter)->getInstList().begin(); startInstSet.push_back(DebugInst(I)); } } break; } debug= getNextInstruction(debug.instruction); } startInstSet.erase(startInstSet.begin(), startInstSet.begin()+1); } //printInfo(startBarriers, endBarriers, phaseInformation); for(set<int>::iterator iter= startBarriers.begin(), end= startBarriers.end(); iter != end; ++iter){ if(*iter == -1){ endBarriers.insert(-1); break; } } Phase phase= Phase(&startBarriers); phase.setEndSetAndInstSet(endBarriers, phaseInformation); nonSVE_MHP_set.insert(phase); return endBarriers; } void Happens::copyEndToStart(vector<DebugInst> &startSet, vector<DebugInst>& endSet){ for(vector<DebugInst>::iterator iter= endSet.begin(), end= endSet.end(); iter != end; ++iter) startSet.push_back(*iter); } bool Happens::checkForTermination(set<int> endSet_, set<Phase> MHP_set){ set<int> startSet_; for(set<Phase>::iterator iter=MHP_set.begin(), end= MHP_set.end(); iter != end; ++iter){ startSet_ = (*iter).startSet; if(startSet_ == endSet_) return true; } return false; } DebugInst Happens::createDebugInst(Value* val, DebugInst debug){ Instruction* I= dyn_cast<Instruction>(val); DebugInst debug_= DebugInst(I); debug_.line= debug.line; return debug_; } void Happens::generateRaceConditions(set<RaceCondition>& RC_set){ for(map<string, vector<int> >::iterator write_iter= writtenVarMap.begin(), write_end= writtenVarMap.end(); write_iter != write_end; ++write_iter){ string writtenGlobal= write_iter->first; vector<int> writtenLines= write_iter->second; size_t len= writtenLines.size(); for(size_t i=0; i< len; i++){ for(size_t j=i+1; j< len; j++) RC_set.insert(RaceCondition(writtenLines[i], writtenLines[j])); } if(readVarMap.find(writtenGlobal) != readVarMap.end()){ vector<int> readLines= readVarMap[writtenGlobal]; for(vector<int>::iterator vect1_iter= writtenLines.begin(), vect1_end=writtenLines.end(); vect1_iter != vect1_end; ++vect1_iter) for(vector<int>::iterator vect2_iter= readLines.begin(), vect2_end= readLines.end(); vect2_iter != vect2_end; ++vect2_iter) if(*vect1_iter != *vect2_iter) RC_set.insert(RaceCondition(*vect1_iter, *vect2_iter)); } } } void Happens::getReadOrWrittenVars(DebugInst debug){ Instruction *inst= debug.instruction; vector<Value*> operands; User *user= dyn_cast<User>(inst); unsigned int nOperands= user->getNumOperands(); for(unsigned int i=0; i< nOperands; i++) operands.push_back(user->getOperand(i)); if(StoreInst::classof(inst)){ string destName= operands[1]->getName(); if(globals.find(destName) != globals.end()){ if(writtenVarMap.find(destName) == writtenVarMap.end()) writtenVarMap[destName]= vector<int>{}; writtenVarMap[destName].push_back(debug.line); } if(!ConstantInt::classof(operands[0])) getReadOrWrittenVars(createDebugInst(operands[0], debug)); }else{ for(unsigned int i=0; i< nOperands; ++i){ if(!ConstantInt::classof(operands[i])){ if(GlobalVariable::classof(operands[i])){ string globalName= operands[i]->getName(); if(readVarMap.find(globalName) == readVarMap.end()) readVarMap[globalName] = vector<int>{}; readVarMap[globalName].push_back(debug.line); }else getReadOrWrittenVars(createDebugInst(operands[i], debug)); } } } } void Happens::raceConditionDetection(set<Phase>& MHP_set, set<RaceCondition>& RC_set){ for(set<Phase>::iterator iter= MHP_set.begin(), end= MHP_set.end(); iter != end; ++iter){ set<DebugInst> phaseInsts= (*iter).instSet; for(set<DebugInst>::iterator info_iter= phaseInsts.begin(), info_end = phaseInsts.end(); info_iter != info_end; ++info_iter){ DebugInst debug= *info_iter; getReadOrWrittenVars(debug); } generateRaceConditions(RC_set); writtenVarMap.clear(); readVarMap.clear(); } } void Happens::non_SVE_MHPAnalysis(Function &F){ getFunctionParamsAndVars(F); BasicBlock & entryBlock= F.getEntryBlock(); Instruction *I= entryBlock.getInstList().begin(); DebugInst debugInst= DebugInst(I); vector<DebugInst> startInstSet{debugInst}; vector<DebugInst> endInstSet; set<int> startBarriers{0}; while(true){ startBarriers=blockTraversal(startInstSet,endInstSet,startBarriers); startInstSet.clear(); copyEndToStart(startInstSet, endInstSet); endInstSet.clear(); if(checkForTermination(startBarriers, nonSVE_MHP_set)) break; } raceConditionDetection(nonSVE_MHP_set, nonSVE_RC_set); } map<string, set<pair<Instruction*, bool> > > Happens::fillSVEInfo(){ map<string, set<pair<Instruction*, bool> > > varInfoMap; for(map<string, Instruction*>::iterator iter= varsList.begin(), end= varsList.end(); iter != end; ++iter) varInfoMap[iter->first]= set<pair<Instruction*, bool> >{make_pair(iter->second, true)}; return varInfoMap; } bool Happens::checkIfSVE(set<pair<Instruction*,bool> > infoSet){ bool flag= true, retVal=true; for(set<pair<Instruction*, bool> >::iterator iter= infoSet.begin(), end= infoSet.end(); iter!= end; ++iter){ if(!iter->second){ retVal= flag= false; break; } } if(flag){ if(infoSet.size()==1) return true; for(set<pair<Instruction*, bool> >::iterator iter= infoSet.begin(), end= infoSet.end(); iter != end; ++iter){ string parentBlockName= iter->first->getParent()->getName(); if(!blockType[parentBlockName]){ retVal= false; break; } } } return retVal; } void Happens::mergeBlockInfo(map<string, set<pair<Instruction*, bool> > > varMap){ map<string, set<pair<Instruction*, bool> > >& currBlockInfo= blockInfo[currBlockName]; string varName; set<pair<Instruction*, bool> > localSet; for(map<string, set<pair<Instruction*, bool> > >::iterator iter= varMap.begin(), end= varMap.end(); iter != end; ++iter){ varName= iter->first; localSet= iter->second; if(currBlockInfo.find(varName) == currBlockInfo.end()) currBlockInfo[varName]= set<pair<Instruction*, bool> >{}; for(set<pair<Instruction*, bool> >::iterator iter_set= localSet.begin(),end_set= localSet.end(); iter_set != end_set; ++iter_set) currBlockInfo[varName].insert(*iter_set); } } void Happens::handleStore(Instruction *inst, map<string, set<pair<Instruction*, bool> > >& varInfo){ User *user= dyn_cast<User>(inst); Value *val0= user->getOperand(0); Value *val1= user->getOperand(1); string destName= val1->getName(); string blockName= inst->getParent()->getName(); pair<Instruction*, bool> localPair; if(globals.find(destName) != globals.end()) globals[destName]= false; else if(paramsList.find(destName) == paramsList.end()){ if(ConstantInt::classof(val0)){ localPair= make_pair(inst, true); }else{ string srcName= val0->getName(); if(srcName=="") srcName = dyn_cast<User>(val0)->getOperand(0)->getName(); if(globals.find(srcName) != globals.end()) localPair= make_pair(inst, globals[srcName]); else if(paramsList.find(srcName) != paramsList.end()) localPair= make_pair(inst, paramsList[srcName]); else localPair= make_pair(inst, checkIfSVE(varInfo[srcName])); } varInfo[destName] = set<pair<Instruction*, bool> >{localPair}; } } bool Happens::getVarType(Value* val, map<string, set<pair<Instruction*, bool> > >& varInfo){ bool retVal= true; if(ConstantInt::classof(val)) retVal= true; else{ string varName= val->getName(); if(varName =="") varName= dyn_cast<User>(val)->getOperand(0)->getName(); if(globals.find(varName) != globals.end()) retVal= globals[varName]; else if(paramsList.find(varName) != paramsList.end()) retVal= false; else retVal= checkIfSVE(varInfo[varName]); } return retVal; } void Happens::handleBinaryOps(Instruction *inst, map<string, set<pair<Instruction*, bool > > > & varInfo){ User *user= dyn_cast<User>(inst); Value *val0= user->getOperand(0); Value *val1= user->getOperand(1); string destName= inst->getName(); string blockName= inst->getParent()->getName(); varInfo[destName]= set<pair<Instruction*, bool> >{make_pair(inst, getVarType(val0,varInfo) && getVarType(val1, varInfo))}; } void Happens::handleBranch(Instruction* inst, map<string, set<pair<Instruction*, bool> > >& varInfo){ BasicBlock* BB= inst->getParent(); string blockName= BB->getName(); User *user= dyn_cast<User>(inst); int nOpds= user->getNumOperands(); Value* val0= user->getOperand(0); bool sveBit=true; if(nOpds==3){ string condExpr= val0->getName(); sveBit= checkIfSVE(varInfo[condExpr]); } for(succ_iterator iter= succ_begin(BB), end= succ_end(BB); iter != end; ++iter){ string blockName= iter->getName(); if(blockType.find(blockName) == blockType.end()) blockType[blockName]= true; blockType[blockName]= (sveBit && blockType[blockName]); } } void Happens::calculatePathInfo(vector<BasicBlock*> blockStack){ int len= blockStack.size(); map<string, set<pair<Instruction*, bool> > > varMap= fillSVEInfo(); // for(int i=0; i< len; i++) // outs() << blockStack[i]->getName() <<" "; // cout <<endl; for(int i= len-1; i>=0; i--){ BasicBlock* BB= blockStack[i]; for(BasicBlock::iterator iter= BB->begin(), end= BB->end(); iter != end; ++iter){ string opCode= iter->getOpcodeName(); //cout << opCode <<endl; if(opCode=="add" || opCode=="sub" || opCode=="mul" || opCode=="icmp") handleBinaryOps(iter, varMap); else if(opCode=="store") handleStore(iter, varMap); else if(opCode=="br"){ handleBranch(iter, varMap); }else if(opCode=="ret") blockType[BB->getName()]= false; } } mergeBlockInfo(varMap); } bool Happens::checkIfVisited(vector<BasicBlock*> blockStack, BasicBlock *BB){ for(vector<BasicBlock*>::iterator iter= blockStack.begin(), end= blockStack.end(); iter != end; ++iter){ if(*iter== BB) return true; } return false; } vector<DebugInst> Happens::copyDebugInstVector(vector<DebugInst>& vect){ vector<DebugInst> temp; for(vector<DebugInst>::iterator iter= vect.begin(), end =vect.end(); iter != end; ++iter) temp.push_back(*iter); return temp; } set<DebugInst> Happens::copyDebugInstSet(set<DebugInst>& set_){ set<DebugInst> temp; for(set<DebugInst>::iterator iter= set_.begin(), end= set_.end(); iter != end; ++iter) temp.insert(*iter); return temp; } set<int> Happens::copyIntSet(set<int>& set_){ set<int> temp; for(set<int>::iterator iter= set_.begin(), end= set_.end(); iter != end; ++iter) temp.insert(*iter); return temp; } vector<BasicBlock*> Happens::copyBlockVector(vector<BasicBlock*>& vect){ vector<BasicBlock*> temp; for(vector<BasicBlock*>::iterator iter= vect.begin(), end= vect.end(); iter != end; ++iter) temp.push_back(*iter); return temp; } void Happens::expressionDetermination(BasicBlock *BB, vector<BasicBlock*>& blockStack){ blockStack.push_back(BB); for(pred_iterator iter= pred_begin(BB), end= pred_end(BB); iter != end; ++iter){ if(!checkIfVisited(blockStack, *iter)) expressionDetermination(*iter, blockStack); } if(BB->getName() =="entry") calculatePathInfo(blockStack); blockStack.pop_back(); } void Happens::blockTraversalSVE(vector<DebugInst>& startInstSet, set<int>& startBarriers, vector<BasicBlock*>& visitedBlocks, set<int>& endBarriers, vector<DebugInst>& endInstSet, set<DebugInst>& phaseInformation){ string opCode, funcName; Instruction* inst; // cerr <<"endBarriers Starts: "; // for(set<int>::iterator iter=startBarriers.begin(), end= startBarriers.end(); // iter != end; ++iter) // cerr << *iter <<" "; // for(vector<DebugInst>::iterator iter= startInstSet.begin(), end= startInstSet.end(); // iter != end; ++iter) // outs() << *(iter->instruction) <<" "; // cerr <<endl; while(!startInstSet.empty()){ DebugInst debug= startInstSet[0]; while(debug.instruction != NULL){ inst= debug.instruction; opCode= inst->getOpcodeName(); if((opCode=="store" || opCode =="icmp") && debug.line != 0){ phaseInformation.insert(debug); }else if(opCode=="call"){ CallInst* callInst= dyn_cast<CallInst>(inst); funcName= callInst->getCalledFunction()->getName(); if(funcName=="barrier"){ endBarriers.insert(debug.line); debug= getNextInstruction(debug.instruction); endInstSet.push_back(debug); break; } }else if(opCode=="ret"){ endBarriers.insert(-1); //cerr <<"Came here\n"; break; }else if(opCode=="br"){ BasicBlock *BB= inst->getParent(); User* user= dyn_cast<User>(inst); int numOpd= user->getNumOperands(); bool sveBit= false; if(numOpd==3){ Value* val0= user->getOperand(0); sveBit= checkIfSVE(blockInfo[BB->getName()][val0->getName()]); outs() << val0->getName() <<" " << sveBit <<"\n"; } if(sveBit){ for(succ_iterator iter= succ_begin(BB), end= succ_end(BB); iter != end; ++iter){ if(!checkIfBlockVisited(*iter, visitedBlocks)){ //outs() << iter->getName() <<"\n"; vector<DebugInst> startInstSet_= copyDebugInstVector(startInstSet); set<int> startBarriers_ = copyIntSet(startBarriers); vector<BasicBlock*> visitedBlocks_ = copyBlockVector(visitedBlocks); set<int> endBarriers_ = copyIntSet(endBarriers); vector<DebugInst> endInstSet_= copyDebugInstVector(endInstSet); set<DebugInst> phaseInformation_ = copyDebugInstSet(phaseInformation); visitedBlocks_.push_back(*iter); Instruction* I= (*iter)->getInstList().begin(); startInstSet_.push_back(DebugInst(I)); startInstSet_.erase(startInstSet_.begin(), startInstSet_.begin()+1); blockTraversalSVE(startInstSet_, startBarriers_, visitedBlocks_, endBarriers_, endInstSet_, phaseInformation_); } } return; }else{ for(succ_iterator iter= succ_begin(BB), end= succ_end(BB); iter != end; ++iter){ if(!checkIfBlockVisited(*iter, visitedBlocks)){ visitedBlocks.push_back(*iter); Instruction* I= (*iter)->getInstList().begin(); startInstSet.push_back(DebugInst(I)); } } } break; } debug= getNextInstruction(debug.instruction); } startInstSet.erase(startInstSet.begin(), startInstSet.begin()+1); } //printInfo(startBarriers, endBarriers, phaseInformation); for(set<int>::iterator iter= startBarriers.begin(), end= startBarriers.end(); iter != end; ++iter){ if(*iter == -1){ endBarriers.insert(-1); break; } } Phase phase= Phase(&startBarriers); phase.setEndSetAndInstSet(endBarriers, phaseInformation); SVE_MHP_set.insert(phase); if(!checkForTermination(endBarriers, SVE_MHP_set)){ set<int> endBarriers_; vector<DebugInst> endInstSet_; set<DebugInst> phaseInformation_; blockTraversalSVE(endInstSet, endBarriers, visitedBlocks, endBarriers_, endInstSet_, phaseInformation_); } } void Happens::SVE_MHP_Analysis(Function &F){ //F.viewCFG(); BasicBlock &entryBlock= F.getEntryBlock(); string entryName= entryBlock.getName(); blockType[entryName]=true; readVarMap.clear(); writtenVarMap.clear(); for(Function::iterator iter= F.begin(), end= F.end(); iter != end; ++iter){ currBlockName= iter->getName(); vector<BasicBlock*> blockStack; blockInfo[currBlockName]= map<string, set<pair<Instruction*, bool> > >{}; expressionDetermination(iter,blockStack); // cout <<currBlockName <<":\n"; // printInitialSVEInfo(blockInfo[currBlockName]); } // for(map<string, bool>::iterator iter= blockType.begin(), end= blockType.end(); // iter != end; ++iter){ // cout << iter->first <<" " << iter->second <<endl; // } Instruction *I= entryBlock.getInstList().begin(); DebugInst debugInst= DebugInst(I); vector<DebugInst> startInstSet{debugInst}; set<int> startBarriers{0}; vector<BasicBlock*> visitedBlocks{&entryBlock}; set<int> endBarriers; vector<DebugInst> endInstSet; set<DebugInst> phaseInformation; blockTraversalSVE(startInstSet,startBarriers, visitedBlocks, endBarriers, endInstSet, phaseInformation); raceConditionDetection(SVE_MHP_set, SVE_RC_set); } bool Happens::checkIfArg(string var){ for(map<string, bool>::iterator begin= paramsList.begin(), end= paramsList.end(); begin != end; ++begin){ if(begin->first == var) return true; } return false; } void Happens::getFunctionParamsAndVars(Function &F){ int numArgs=0; for(Function::arg_iterator iter= F.arg_begin(), iter_end= F.arg_end(); iter!= iter_end; ++iter){ numArgs++; paramsList[iter->getName()]= false; } BasicBlock &BB= F.getEntryBlock(); for(BasicBlock::iterator iter= BB.begin(),end = BB.end(); iter!= end; ++iter){ string opCode= iter->getOpcodeName(); if(opCode=="alloca"){ if(numArgs>0) paramsList[iter->getName()]= false; else varsList[iter->getName()] = iter; numArgs--; } } } void Happens::getGlobals(Module &M){ for(Module::global_iterator I= M.global_begin(), E= M.global_end(); I != E; ++I) globals[I->getName()]= true; } void Happens::checkForGlobalWrite(Function &F){ for(Function::iterator BB_iter= F.begin(),BB_end= F.end(); BB_iter != BB_end; ++BB_iter){ for(BasicBlock::iterator inst_iter= BB_iter->begin(), inst_end= BB_iter->end(); inst_iter!= inst_end; ++inst_iter){ string opCode= inst_iter->getOpcodeName(); if(opCode=="store"){ User* user= dyn_cast<User>(inst_iter); Value* val1= user->getOperand(1); string destName= val1->getName(); if(globals.find(destName) != globals.end()) globals[destName]= false; } } } } bool Happens::runOnModule(Module &M) { getGlobals(M); for(Module::iterator F= M.begin(), E= M.end(); F!= E; ++F){ if(F->getName()=="parRegion"){ non_SVE_MHPAnalysis(*F); checkForGlobalWrite(*F); SVE_MHP_Analysis(*F); } } dumpInformation(); return false; } // Register the pass. char Happens::ID = 0; static RegisterPass<Happens> X("happens", "MHP Analysis and Race Condition Detection"); <file_sep>#!/bin/bash #script is used for graph-classification purpose echo "Compilation starts......" javac -d . ../src/GraphClassification.java echo "done" echo "Program run starts......" java GraphClassification $1 $2 $3 $4 # echo "done" # echo "converting training input into required format for gSpan" # python formattted.py generatedFile.txt out1.txt elements.txt gSpanInput.txt # echo "done" # echo "running gSpan on formatted training input...." # ./gSpan -f gSpanInput.txt -s 0.1 -i -o > temp # echo "done" echo "creating features Matrix....." java Creator python classification.py $4 <file_sep>1. cluster_prediction.py is used to find out the optimal number of clusters using KMeans. 2. *.png files are as mentioned in the main report 3. q2.txt is the data provided by the professor <file_sep>#include <stdio.h> int main(){ int a[]={1,3,4,1}; int i; int b[4]; for(i=0; i< 4; i++){ b[i]= a[i]; } }<file_sep>__author__ = 'abhishek' import re import sys filename1=sys.argv[1] filename2=sys.argv[2] filename3=sys.argv[3] filename4=sys.argv[4] file_=open(filename3,"r") #python formatted.py aid_whatever.txt out1.txt elements.txt out2.txt lst,counter,lst_={},1,[] for lines in file_: str_=lines.split() lst[str_[3]]=counter lst_.append(str_[3]) counter+=1 file_.close() file_=open(filename1,"r") file__=open(filename2,"w") counter,graph_counter=0,0 for lines in file_: if re.match(r" *[A-Z]+[a-z]*",lines): file__.write("v "+str(counter)+" "+lines) counter+=1 elif re.match(r"[0-9]+ +[0-9]+ +[0-9]+",lines): file__.write("e "+lines) elif re.match(r"[ ]*#",lines)!=None: graph_counter+=1 match=re.search(r"[0-9]+",lines) file__.write("t # "+str(match.group())+"\n") counter=0 file_.close() file__.close() print graph_counter file_=open(filename2,"r") file__=open(filename4,"w") for lines in file_: if re.match(r"v +[0-9]+[ ]+[A-Z]+[a-z]*",lines): str_=lines.split() str_[2]=lst[str_[2]] str_=str_[0]+" "+str_[1]+" "+str(str_[2])+"\n" file__.write(str_) else: file__.write(lines)<file_sep>__author__ = 'abhisheky' fileName= open("/home/abhisheky/Documents/8thSem/DM/Assignments/Assignment3_New/Q1/output.dat","r"); xCoords, yCoords= [],[] for line in fileName: coords= line.rstrip("\n").split() xCoords.append(float(coords[0])) yCoords.append(float(coords[1])) import matplotlib.pyplot as plt import numpy as np colors= np.random.rand(20000) plt.scatter(xCoords, yCoords, c=colors) plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("scatter plot of original dataset") plt.show() <file_sep>1.a) compile using: gcc -executable_name Q1_a.c -lpthread 1.b) compile using: gcc -executable_name Q1_b.c -openmp <file_sep>min_sup=0.1 from random import shuffle import time ########################################################################### #function to calculate the 1-frequent set def find_frequent_1_itemset(): lst=[] with open("retail.dat","r") as data: for lines in data: lst_=[int(val) for val in lines.strip("\n ").split()] lst_.sort() lst.append(lst_) return lst def quick(lst): frequent_set,trans_id,i={},{},0 for lst_ in lst: for num in lst_: if num in frequent_set: frequent_set[num]+=1 trans_id[num].append(i) else: frequent_set[num]=1 trans_id[num]=[i] i+=1 mod_frequent_set,mod_trans_id={},{} min_sup_count=int((len(lst)*min_sup)) for items in frequent_set: if frequent_set[items] >= min_sup_count: mod_frequent_set[items]=frequent_set[items] mod_trans_id[items]=trans_id[items] del frequent_set del trans_id return mod_frequent_set,mod_trans_id,min_sup_count ############################################################################### #checks if Ck_1 contains all the subsets of size k_1 of Ck def has_infrequent_subset(Ck_1,Ck): len_=len(Ck) subsets=Ck[:len_-1] #print subsets,Ck_1 if subsets not in Ck_1: return True for i in range(1,len_): subsets=Ck[:i-1]+Ck[i:] if subsets not in Ck_1: return True return False ################################################################################ def find_difference(lst1,lst2): len_,count=len(lst1),0 for i in range(len_): if lst1[i] != lst2[i]: count+=1 if count>1: break return count ################################################################################## def apriori_gen(C,min_sup_count,mod_trans_id): len_=len(C) C_k,C_,trans_id=[],[],[] set_list=[set(items) for items in mod_trans_id] for i in range(len_): for j in range(i+1,len_): if find_difference(C[i],C[j])==1: if C[i][-1:] < C[j][-1:]: C_=[vals for vals in C[i]] C_.append(C[j][-1]) else: C_=[vals for vals in C[j]] C_.append(C[i][-1]) temp=set_list[i].intersection(set_list[j]) #print C_ if has_infrequent_subset(C,C_)==False: C_k.append(C_) trans_id.append(list(temp)) return C_k,trans_id ############################################################################### lst=find_frequent_1_itemset() C,mod_trans_id,min_sup_count=quick(lst) i=1 #print len(C),len(mod_trans_id),len(lst),min_sup_count frequent_items,mod_trans={},{} frequent_items["C"+str(i)]=[[item] for item in C] mod_trans["C"+str(i)]=[mod_trans_id[items] for items in mod_trans_id] support_values,temp=[],[] for values in C: temp.append(C[values]) support_values.append(temp) # Start time of the algorithm print start_time= time.time() while True: C,trans_id=apriori_gen(frequent_items["C"+str(i)],min_sup_count,mod_trans["C"+str(i)]) if C==[]: break i+=1 temp_trans,temp_items=[],[] len_=len(trans_id) for j in range(len_): if len(trans_id[j]) >= min_sup_count: temp_trans.append(trans_id[j]) temp_items.append(C[j]) frequent_items["C"+str(i)]=temp_items mod_trans["C"+str(i)]=temp_trans ################################################################################################ sorted_frequent_items=sorted(frequent_items.items(), key=lambda s:s[0]) print (sorted_frequent_items) for keys in sorted_frequent_items: for items in keys[1]: items.sort() keys[1].sort() min_sup=min_sup*100 print ("%d %s")%(min_sup,time.time()-start_time) #print sorted_frequent_items with open("CS12B032_1a.txt","w") as outfile: outfile.write('minimum support threshold(%c): %.2f\n'%('%',min_sup)) for values in sorted_frequent_items: for vals in values[1]: for val in vals: outfile.write(str(val)+' ') outfile.write('\n') ###############################################################################################<file_sep># Copyright (c) 2006-2008 The Regents of The University of Michigan # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER 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. # # Authors: <NAME> import os import sys from os.path import basename, exists, join as joinpath, normpath from os.path import isdir, isfile, islink spec_dist = os.environ.get('M5_CPU2006', '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86') def copyfiles(srcdir, dstdir): from filecmp import cmp as filecmp from shutil import copyfile srcdir = normpath(srcdir) dstdir = normpath(dstdir) if not isdir(dstdir): os.mkdir(dstdir) for root, dirs, files in os.walk(srcdir): root = normpath(root) prefix = os.path.commonprefix([root, srcdir]) root = root[len(prefix):] if root.startswith('/'): root = root[1:] for entry in dirs: newdir = joinpath(dstdir, root, entry) if not isdir(newdir): os.mkdir(newdir) for entry in files: dest = normpath(joinpath(dstdir, root, entry)) src = normpath(joinpath(srcdir, root, entry)) if not isfile(dest) or not filecmp(src, dest): copyfile(src, dest) # some of the spec benchmarks expect to be run from one directory up. # just create some symlinks that solve the problem inlink = joinpath(dstdir, 'input') outlink = joinpath(dstdir, 'output') if not exists(inlink): os.symlink('.', inlink) if not exists(outlink): os.symlink('.', outlink) class Benchmark(object): def __init__(self, isa, os, input_set): if not hasattr(self.__class__, 'name'): self.name = self.__class__.__name__ if not hasattr(self.__class__, 'binary'): self.binary = self.name if not hasattr(self.__class__, 'args'): self.args = [] if not hasattr(self.__class__, 'output'): self.output = '%s.out' % self.name if not hasattr(self.__class__, 'simpoint'): self.simpoint = None try: func = getattr(self.__class__, input_set) except AttributeError: raise AttributeError, \ 'The benchmark %s does not have the %s input set' % \ (self.name, input_set) executable = joinpath(spec_dist, 'binaries', self.binary) print "executable= %s " % (executable) if not isfile(executable): raise AttributeError, '%s not found' % executable self.executable = executable # root of tree for input & output data files data_dir = joinpath(spec_dist, 'data',self.name) # optional subtree with files shared across input sets all_dir = joinpath(data_dir, 'all') # dirs for input & output files for this input set inputs_dir = joinpath(data_dir, input_set, 'input') #inputs_dir = joinpath(data_dir ) outputs_dir = joinpath(data_dir, input_set, 'output') # keep around which input set was specified self.input_set = input_set print "inputs_dir = %s " % (inputs_dir) print "outputs_dir = %s " % (outputs_dir) if not isdir(inputs_dir): raise AttributeError, '%s not found' % inputs_dir self.inputs_dir = [ inputs_dir ] if isdir(all_dir): self.inputs_dir += [ joinpath(all_dir, 'input') ] if isdir(outputs_dir): self.outputs_dir = outputs_dir if not hasattr(self.__class__, 'stdin'): self.stdin = joinpath(inputs_dir, '%s.in' % self.name) if not isfile(self.stdin): self.stdin = None if not hasattr(self.__class__, 'stdout'): self.stdout = joinpath(outputs_dir, '%s.out' % self.name) if not isfile(self.stdout): self.stdout = None func(self, isa, os) def makeLiveProcessArgs(self, **kwargs): # set up default args for LiveProcess object process_args = {} process_args['cmd'] = [ self.name ] + self.args process_args['executable'] = self.executable if self.stdin: process_args['input'] = self.stdin if self.stdout: process_args['output'] = self.stdout if self.simpoint: process_args['simpoint'] = self.simpoint # explicit keywords override defaults process_args.update(kwargs) return process_args def makeLiveProcess(self, **kwargs): process_args = self.makeLiveProcessArgs(**kwargs) # figure out working directory: use m5's outdir unless # overridden by LiveProcess's cwd param cwd = process_args.get('cwd') if not cwd: from m5 import options cwd = options.outdir process_args['cwd'] = cwd if not isdir(cwd): os.makedirs(cwd) # copy input files to working directory # cwd = '/home/biswa/gem5-tournament' #cwd = '/Scratch/Dennis/SPEC2006_X86/data/sphinx/all/input/' #cwd = '/home/biswa/m5-waysharing/input/' #print "cwd = %s " % (cwd) #for d in self.inputs_dir: # copyfiles(d, cwd) # generate LiveProcess object from m5.objects import LiveProcess return LiveProcess(**process_args) def __str__(self): return self.name class DefaultBenchmark(Benchmark): def ref(self, isa, os): pass def test(self, isa, os): pass def train(self, isa, os): pass def all(self, isa, os): pass class MinneDefaultBenchmark(DefaultBenchmark): def smred(self, isa, os): pass def mdred(self, isa, os): pass def lgred(self, isa, os): pass class namd(DefaultBenchmark): name = 'namd' lang = 'C++' def all(self, isa, os): #self.args = ['--input','working_dir/namd.input', self.args = ['--input','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/namd/all/input/namd.input', '--iterations', '1', '--output','namd.out'] def ref(self, isa, os): self.args = ['--input','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/namd/all/input/namd.input', '--iterations', '1', '--output','namd.out'] class milc(DefaultBenchmark): name = 'milc' lang = 'C' def ref(self, isa, os): self.stdin = '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/milc/ref/input/su3imp.in' class omnetpp(DefaultBenchmark): name = 'omnetpp' lang = 'C++' def all(self, isa, os): self.args = ['/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/omnetpp/ref/input/omnetpp.ini', '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/omnetpp/ref/output/omnetpp.log'] class cactusADM(DefaultBenchmark): name = 'cactusADM' number = 436 lang = 'C++' def ref(self, isa, os): self.args = ['/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/cactusADM/ref/input/benchADM.par'] self.output = 'benchADM.out' class soplex(DefaultBenchmark): name = 'soplex' lang = 'C++' def test(self, isa, os): self.args = ['-m10000','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/soplex/test/input/test.mps'] self.output = 'test.out' def ref(self, isa, os): self.args = ['-m3500','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/soplex/ref/input/ref.mps'] self.output = 'ref.out' def train(self, isa, os): self.args = ['-m1200','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/soplex/train/input/train.mps'] self.output = 'train.out' class gamess(DefaultBenchmark): name = 'gamess' number = 416 lang = 'F95' def ref(self, isa, os): self.stdin = '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/gamess/ref/input/cytosine.2.config' class bzip2(DefaultBenchmark): name = 'bzip2' number = 256 lang = 'C' def all(self, isa, os): self.args = ['/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/bzip2/all/input/input.program', '1'] def test(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/bzip2/test/input/dryer.jpg ','2'] def train(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/bzip2/train/input/byoudoin.jpg','5' ] def ref(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/bzip2/ref/input/input.source','280' ] class bzip2_source(bzip2): def ref(self, isa, os): self.simpoint = 977*100E6 self.args = [ 'input.source', '58' ] def lgred(self, isa, os): self.args = [ 'input.source', '1' ] class bzip2_graphic(bzip2): def ref(self, isa, os): self.simpoint = 718*100E6 self.args = [ 'input.graphic', '58' ] def lgred(self, isa, os): self.args = [ 'input.graphic', '1' ] class bzip2_program(bzip2): def ref(self, isa, os): self.simpoint = 458*100E6 self.args = [ 'input.program', '58' ] def lgred(self, isa, os): self.args = [ 'input.program', '1' ] class gcc(DefaultBenchmark): name = 'gcc' number = 176 lang = 'C' def ref(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/gcc/ref/input/scilab.i', '-o', '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/gcc/test/input/scilab.s' ] def test(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/gcc/test/input/cccp.i', '-o', '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/gcc/test/input/cccp.s' ] def train(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/gcc/train/input/integrate.i', '-o', '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/gcc/train/input/integrate.s' ] def smred(self, isa, os): self.args = [ 'c-iterate.i', '-o', 'c-iterate.s' ] def mdred(self, isa, os): self.args = [ 'rdlanal.i', '-o', 'rdlanal.s' ] def lgred(self, isa, os): self.args = [ 'cp-decl.i', '-o', 'cp-decl.s' ] class gcc_166(gcc): def ref(self, isa, os): self.simpoint = 389*100E6 self.args = [ '166.i', '-o', '166.s' ] class gcc_200(gcc): def ref(self, isa, os): self.simpoint = 736*100E6 self.args = [ '200.i', '-o', '200.s' ] class gcc_expr(gcc): def ref(self, isa, os): self.simpoint = 36*100E6 self.args = [ 'expr.i', '-o', 'expr.s' ] class gcc_integrate(gcc): def ref(self, isa, os): self.simpoint = 4*100E6 self.args = [ 'integrate.i', '-o', 'integrate.s' ] class gcc_scilab(gcc): def ref(self, isa, os): self.simpoint = 207*100E6 self.args = [ 'scilab.i', '-o', 'scilab.s' ] class zeusmp(DefaultBenchmark): name = 'zeusmp' number = 434 lang = 'F' def ref(self, isa, os): self.cwd = '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/zeusmp/ref/input/' self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/zeusmp/ref/input/zmp_inp' ] #class mcf(MinneDefaultBenchmark): class mcf(DefaultBenchmark): name = 'mcf' number = 181 lang = 'C' def test(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/mcf/test/input/inp.in' ] def ref(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/mcf/ref/input/inp.in' ] def train(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/mcf/train/input/inp.in' ] class leslie3d(DefaultBenchmark): name = 'leslie3d' number = 437 lang = 'F' class hmmer(DefaultBenchmark): name = 'hmmer' lang = 'C' def test(self, isa, os): self.args = ['--fixed', '0', '--mean', '325', '--num', '5000', '--sd', '200', '--seed', '0', '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/hmmer/test/input/bombesin.hmm' ] self.output = 'bombesin.out' def ref(self, isa, os): self.args = ['--fixed', '0', '--mean', '500', '--num', '500000', '--sd', '350', '--seed', '0', '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/hmmer/ref/input/retro.hmm' ] self.output = 'retro.out' def train(self, isa, os): self.args = ['--fixed', '0', '--mean', '425', '--num', '85000', '--sd', '300', '--seed', '0', '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/hmmer/train/input/leng100.hmm' ] self.output = 'leng100.out' class sjeng(DefaultBenchmark): name = 'sjeng' lang = 'C' def test(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/sjeng/test/input/test.txt'] def train(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/sjeng/train/input/train.txt'] def ref(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/sjeng/ref/input/ref.txt'] class GemsFDTD(DefaultBenchmark): name = 'GemsFDTD' number = '459' lang = 'F' def test(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/GemsFDTD/test/input/test.in'] GemsFDTD.output = 'test.log' GemsFDTD.input = 'test.in' def ref(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/GemsFDTD/ref/input/ref.in'] GemsFDTD.output = 'ref.log' def train(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/GemsFDTD/test/input/train.in'] GemsFDTD.output = 'train.log' #class GemsFDTD(DefaultBenchmark): # name = 'GemsFDTD' # number = '459' # lang = 'F' # # def test(self, isa, os): # self.args = [ '/Scratch/Dennis/SPEC2006_X86/data/GemsFDTD/test/input/test.in'] class h264ref(DefaultBenchmark): name = 'h264ref' number = '464' lang = 'C' def ref(self, isa, os): self.args = [ '-d','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/h264ref/ref/input/foreman_ref_encoder_baseline.cfg'] h264ref.output = 'foreman_test_encoder_baseline.out' def test(self, isa, os): self.args = [ '-d','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/h264ref/test/input/foreman_test_encoder_baseline.cfg'] h264ref.output = 'foreman_test_encoder_baseline.out' class xalancbmk(DefaultBenchmark): name = 'xalancbmk' number = 181 lang = 'C' def ref(self, isa, os): self.args = [ '-v', '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/xalancbmk/ref/input/t5.xml', '/Scratch/Dennis/SPEC2006_X86/data/xalancbmk/ref/input/xalanc.xsl'] class bwaves(DefaultBenchmark): name = 'bwaves' number = 410 lang = 'C' def all(self, isa, os): self.args = [ '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/bwaves/test/' ] class libquantum(DefaultBenchmark): name = 'libquantum' lang = 'C' def test(self, isa, os): self.args = ['33','5'] def train(self, isa, os): self.args = ['143','25'] def ref(self, isa, os): self.args = ['1397','8'] class lbm(DefaultBenchmark): name = 'lbm' lang = 'C' def test(self, isa, os): self.args = ['20', 'reference.dat', '0', '1' , '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/lbm/test/input/100_100_130_cf_a.of'] def train(self, isa, os): self.args = ['300', 'reference.dat', '0', '1' , '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/lbm/train/input/100_100_130_cf_b.of'] def ref(self, isa, os): self.args = ['3000', 'reference.dat', '0', '0' , '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/lbm/ref/input/100_100_130_ldc.of'] class calculix(DefaultBenchmark): name = 'calculix' lang = 'C' def test(self, isa, os): self.args = ['-i','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/calculix/test/input/beampic'] def train(self, isa, os): self.args = ['-i','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/calculix/train/input/stairs'] def ref(self, isa, os): self.args = ['/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/calculix/ref/input/hyperviscoplastic'] class gromacs(DefaultBenchmark): name = 'gromacs' number = '435' lang = 'C' def test(self, isa, os): self.args = [ '-silent','-deffnm','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/gromacs/test/input/gromacs.tpr','-nice','2'] def train(self, isa, os): self.args = [ '-silent','-deffnm','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/gromacs/train/input/gromacs.tpr','-nice','0'] def ref(self, isa, os): self.args = [ '-silent','-deffnm','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/gromacs/ref/input/gromacs.tpr','-nice','0'] class gobmk(DefaultBenchmark): name = 'gobmk' number = '445' lang = 'C' def all(self, isa, os): self.args = ['--quiet','--mode','gtp'] #input = '/Scratch/Dennis/SPEC2006_X86_exe/445.gobmk/data/test/input/capture.tst' #output = '/Scratch/Dennis/SPEC2006_X86_exe/445.gobmk/data/test/output/capture.out' #sphinx3=LiveProcess() #sphinx3.executable = binary_dir+'482.sphinx_livepretend_base.alpha-gcc' #sphinx3.cmd = [sphinx3.executable]+['ctlfile', '.', 'args.an4'] #sphinx3.output = 'an4.out' class sphinx(DefaultBenchmark): name = 'sphinx' number = '482' lang = 'C' def all(self, isa, os): self.args = ["""'/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/sphinx/all/input/model/lm/an4/an4.ctl','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/sphinx/all/input/model/lm/an4/','/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/sphinx/all/input/model/lm/an4/args.an4.in'"""] # self.stdin = ['/Scratch/Dennis/cpu2006/data/sphinx/all/input/model/lm/an4/.'] # self.stdin = ['/Scratch/Dennis/cpu2006/data/sphinx/all/input/model/lm/an4/args.an4.in'] # self.args = [input1, input_dir, input2] #************************************************************************************************************************************************************ class astar(DefaultBenchmark): name = 'astar' number = 473 lang = 'C++' def ref(self, isa, os): self.args = ['/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/astar/ref/input/BigLakes2048.cfg'] self.output = '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/astar/ref/input/BigLakes2048.out' class dealII(DefaultBenchmark): name = 'dealII' number = 447 lang = 'C++' def ref(self, isa, os): self.stdin = ['23'] self.output = '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/dealII/ref/output/dealII.out' class perlbench(DefaultBenchmark): name = 'perlbench' number = 400 lang = 'C' def all(self, isa, os): self.args = ['-I./lib', '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/perlbench/all/input/diffmail.pl','4', '800', '10', '17', '19', '300'] self.output = '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/perlbench/ref/output/diffmail.out' class povray(DefaultBenchmark): name = 'povray' number = 453 lang = 'C++' def ref(self, isa, os): self.args = ['/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/povray/ref/input/SPEC-benchmark-ref.ini'] self.output = '/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/povray/ref/output/povray.out' """ class specrand(DefaultBenchmark): name = 'specrand' number = 998 lang = 'C' def ref(self, isa, os): self.args = ['/home/greeshma/Documents/gem5_2.4/gem5-stable/binaries/SPEC2006_X86/data/cactusADM/ref/input/benchADM.par'] self.output = 'benchADM.out' """ #************************************************************************************************************************************************************** all = [ astar,bzip2_source, bzip2_graphic, bzip2_program, dealII, gcc_166, gcc_200, gcc_expr, gcc_integrate, gcc_scilab, namd, soplex, mcf ,leslie3d, hmmer, sjeng, GemsFDTD, libquantum, milc, lbm, bwaves, h264ref,calculix ,gobmk , perlbench, povray, gamess,sphinx,xalancbmk,omnetpp] __all__ = [ x.__name__ for x in all ] if __name__ == '__main__': from pprint import pprint for bench in all: for input_set in 'ref', 'test', 'train': print 'class: %s' % bench.__name__ x = bench('alpha', 'tru64', input_set) print '%s: %s' % (x, input_set) pprint(x.makeLiveProcessArgs()) print <file_sep>#include <stdio.h> #include <omp.h> #include <stdlib.h> int main(int argc, char* argv[]){ int X=2; //omp_set_num_threads(1); #pragma omp parallel { printf("Thread: %d, the value of the variable x is %d\n",omp_get_thread_num(), X); X=0; } return 0; }<file_sep>__author__ = 'abhisheky' with open("/home/abhisheky/Documents/8thSem/DM/Assignments/Assignment3_New/Q1/Q1_d/R_Tree_ep100.txt","r") as reader: with open("rax100.txt","w") as writer: for line in reader: str_= line.split("-") writer.write(str_[1]) <file_sep>__author__ = 'abhisheky' import matplotlib.pyplot as plt from sklearn.cluster import KMeans from scipy.spatial import distance k=9 def getVariance(centroids, map_): variance=0 for key, value in map_.iteritems(): centroid= centroids[key] intra_dist=0 for element in value: intra_dist+= (distance.euclidean(element, centroid))**2 variance+=(2*len(value)*intra_dist) return variance def inter_cluster_distance(centroids): min_distance=999999999999999 for i in range(len(centroids)): for j in range(i+1,len(centroids)): dist= distance.euclidean(centroids[i], centroids[j]) if dist < min_distance: min_distance= dist return min_distance def draw_plot(variances): k_values=[i for i in range(1,k)] plt.plot(k_values, variances) plt.xlabel("K") plt.ylabel("Intra/Inter") plt.show() with open("Q2.txt","r") as read_file: data_array=[] for lines in read_file: data=[float(entry) for entry in lines.rstrip('\n').split()] data_array.append(data) variances= [] for i in range(1,k): map_={} kmeans= KMeans(n_clusters=i) kmeans.fit(data_array) labels= kmeans.labels_ centroids= kmeans.cluster_centers_ for i in range(len(labels)): if labels[i] not in map_: map_[labels[i]]=[] map_[labels[i]].append(data_array[i]) variances.append(getVariance(centroids, map_)/len(data_array)) temp= variances[0] for i in range(len(variances)): variances[i]/= temp draw_plot(variances) <file_sep>import java.lang.Double; import java.util.*; import java.lang.Math; /** * Created by abhisheky on 16/2/16. */ public class Point implements Comparable<Point> { public ArrayList<Double> container; public Integer id; public static final Double UNDEFINED= 1.0; public boolean processed; public double reachability_dist; public double core_dist; public int compareTo(Point point){ if(this.reachability_dist > point.reachability_dist) return 1; else if(this.reachability_dist== point.reachability_dist) return 0; else return -1; } public Point(){ container= new ArrayList<Double>(); reachability_dist= UNDEFINED; core_dist= UNDEFINED; processed=false; id= 0; } public void addCoord(double coord){ container.add(coord); } public double getDistance(Point pt2){ double sum=0; int dimension= container.size(); for(int i=0;i< dimension; i++) sum+= Math.pow(this.container.get(i)- pt2.container.get(i), 2); return Math.sqrt(sum); } public double dot(Point point){ double dotProduct=0; int dimension= point.container.size(); for(int i=0; i< dimension; i++) dotProduct+= (point.container.get(i)*this.container.get(i)); return dotProduct; } // public static void main(String [] args) { //// HashMap<Integer, Double> map= new HashMap<Integer, Double>(); // map.put(1,2.3); // map.put(3,0.23); // map.put(5, 0.84); // map.put(4, 0.0008); // Optics optics = new Optics(); // List<Map.Entry<Integer, Double> >list= optics.getSortedList(map); // for (int i=0;i< list.size(); i++) // System.out.println(list.get(i).getValue()); // } } <file_sep>import os,subprocess size=42682 lst=[.05,0.1,0.25,0.5,0.95] for k in lst: os.system("./gaston "+str(k*size) +" out2.txt result.txt")<file_sep>#!/bin/bash javac -d . ../src/gSpan.java ../src/Graph.java java gSpan $1<file_sep>import os,subprocess size=42682 lst=[5,10,25,50,95] for k in lst: os.system("./fsg -s"+str(k)+" out2.txt")<file_sep>#include <stdio.h> void area(float param){ float base; base = 23.34; float area= (base* param)/2; printf("area of the triangle is:%f\n",area); } void factorial(int param){ int accumulator=1; while(param>1){ accumulator*= param--; } printf("factorial of %d = %d\n",param, accumulator); } int main(){ area(1.234); factorial(6); }<file_sep>#!/usr/bin/python import sys def createEscapesExpectedOutput(): expected_escapes_d['test1'] = set(['call']) expected_escapes_d['test2'] = set(['call']) expected_escapes_d['test3'] = set(['call', 'call1']) expected_escapes_d['test4'] = set(['call1']) expected_escapes_d['test5'] = set(['call1', 'call2', 'call3']) expected_escapes_d['test6'] = set(['call', 'call1', 'call2', 'call4']) expected_escapes_d['test7'] = set(['call', 'call1', 'call3']) def createStudentEscapeOutput(student_outfile): f = open(student_outfile) content = f.read() #print content lines = content.split('\n') escapes = set(lines[0].split()) return escapes def evaluateEscape(student_escapes): expected_escapes = expected_escapes_d[testcase] print expected_escapes print student_escapes if not (expected_escapes == student_escapes): print "Escape is wrong" return False return True student_outfile = sys.argv[2] inputfile = sys.argv[1] #print student_outfile expected_escapes_d = {} total_marks = 0 testcase = inputfile.split('/')[-1].split('.')[0] createEscapesExpectedOutput() student_escapes = createStudentEscapeOutput(student_outfile) if (evaluateEscape(student_escapes)): print testcase, ": passed" print exit(0) else: print testcase, ": failed" print exit(1) <file_sep>#include <stdio.h> #include <string.h> int main(){ int a=12; int* p= &a; int b= *p+12; *p++; p= &b; *p= *p+23; b = *p + a; printf("a:%d, b:%d\n",a,b); }<file_sep>from random import shuffle import time ########################################################################### #function to calculate the 1-frequent set def find_frequent_1_itemset(): lst=[] with open("retail.dat","r") as data: for lines in data: lst_=[int(val) for val in lines.strip("\n ").split()] lst_.sort() lst.append(lst_) return lst def quick(lst,min_sup): frequent_set,trans_id,i={},{},0 for lst_ in lst: for num in lst_: if num in frequent_set: frequent_set[num]+=1 trans_id[num].append(i) else: frequent_set[num]=1 trans_id[num]=[i] i+=1 mod_frequent_set,mod_trans_id={},{} min_sup_count=int((len(lst)*min_sup)) for items in frequent_set: if frequent_set[items] >= min_sup_count: mod_frequent_set[items]=frequent_set[items] mod_trans_id[items]=trans_id[items] del frequent_set del trans_id return mod_frequent_set,mod_trans_id,min_sup_count ############################################################################### #checks if Ck_1 contains all the subsets of size k_1 of Ck def has_infrequent_subset(Ck_1,Ck): len_=len(Ck) subsets=Ck[:len_-1] #print subsets,Ck_1 if subsets not in Ck_1: return True for i in range(1,len_): subsets=Ck[:i-1]+Ck[i:] if subsets not in Ck_1: return True return False ################################################################################ def find_difference(lst1,lst2): len_,count=len(lst1),0 for i in range(len_): if lst1[i] != lst2[i]: count+=1 if count>1: break return count ################################################################################## def apriori_gen(C,min_sup_count,mod_trans_id): len_=len(C) C_k,C_,trans_id=[],[],[] set_list=[set(items) for items in mod_trans_id] for i in range(len_): for j in range(i+1,len_): if find_difference(C[i],C[j])==1: if C[i][-1:] < C[j][-1:]: C_=[vals for vals in C[i]] C_.append(C[j][-1]) else: C_=[vals for vals in C[j]] C_.append(C[i][-1]) temp=set_list[i].intersection(set_list[j]) #print C_ if has_infrequent_subset(C,C_)==False: C_k.append(C_) trans_id.append(list(temp)) return C_k,trans_id lst=find_frequent_1_itemset() fraction=[0.1,0.25,0.75,1.0] for percent in fraction: start_time= time.time() shuffle(lst) len_lst,min_sup=len(lst),.002 C,mod_trans_id,min_sup_count=quick(lst[:int(percent*len_lst)],min_sup) #print len(lst),min_sup_count i=1 frequent_items,mod_trans={},{} frequent_items["C"+str(i)]=[[item] for item in C] mod_trans["C"+str(i)]=[mod_trans_id[items] for items in mod_trans_id] support_values,temp=[],[] for values in C: temp.append(C[values]) support_values.append(temp) while True: C,trans_id=apriori_gen(frequent_items["C"+str(i)],min_sup_count,mod_trans["C"+str(i)]) if C==[]: break i+=1 temp_trans,temp_items=[],[] len_=len(trans_id) for j in range(len_): if len(trans_id[j]) >= min_sup_count: temp_trans.append(trans_id[j]) temp_items.append(C[j]) frequent_items["C"+str(i)]=temp_items mod_trans["C"+str(i)]=temp_trans print ("[%f ,%f],") %(percent*100,time.time()-start_time) #print sorted_frequent_items <file_sep>#!/usr/bin/python import sys def createPoinstsToExpectedOutput(): expected_pointsto_d['test1'] = {'i': set(['call']), 'j': set(['call1'])} expected_pointsto_d['test2'] = {'i': set(['call']), 'j': set(['call1']), 'k': set(['call'])} expected_pointsto_d['test3'] = {'i': set(['call']), 'j': set(['call1']), 'm': set(['call2'])} expected_pointsto_d['test4'] = {'i': set(['call']), 'j': set(['call1']), 'k': set(['call1'])} expected_pointsto_d['test5'] = {'a': set(['call']), 'i': set(['call1']), 'j': set(['call2']), 'k': set(['call3'])} expected_pointsto_d['test6'] = {'a': set(['call']), 'j': set(['call1', 'call4']), 'k': set(['call2']), 'b': set(['call3'])} expected_pointsto_d['test7'] = {'a': set(['call', 'call3']), 'k': set(['call1']), 'i': set(['call2'])} def createStudentPointsToOutput(student_outfile): f = open(student_outfile) content = f.read() #print content lines = content.split('\n') pointers = [] pointees = set([]) d = {} for line in lines[1:]: variables = line.split() if len(variables) > 0: pointer = variables[0] pointees = set(variables[1:]) d[pointer] = pointees f.close() return d def evaluatePointsTo(studentd): expectedd = expected_pointsto_d[testcase] print expectedd print studentd for pointer in expectedd: pointees_expected = expectedd[pointer] if not studentd.has_key(pointer): print "Pointer", pointer , "not found" return False pointees_student = studentd[pointer] if not ((pointees_expected & pointees_student) == pointees_expected): print "Pointees list of", pointer, "is wrong" return False return True student_outfile = sys.argv[2] inputfile = sys.argv[1] #print student_outfile expected_pointsto_d = {} total_marks = 0 testcase = inputfile.split('/')[-1].split('.')[0] createPoinstsToExpectedOutput() student_pointsto_d = createStudentPointsToOutput(student_outfile) if (evaluatePointsTo(student_pointsto_d)): print testcase, ": passed" print exit(0) else: print testcase, ": failed" print exit(1) <file_sep>#include <stdio.h> #include <pthread.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #define N 10000 int A[N][N]; int B[N][N]; int C[N][N]; void *calc_sum(void * p){ int x=(int)p; int i,j; for(i=x-1000; i< x; i++) for(j=0;j<N;j++) C[i][j]=A[i][j]+B[i][j]; } int main(){ pthread_t threads[10]; int return_ids[10]; int i,j; srand(time(NULL)); for(i=0;i<N;i++){ for(j=0;j<N;j++){ A[i][j]= rand()%100; B[i][j]= rand()%100; } } j=1000; for(i=0;i<10;i++){ return_ids[i]= pthread_create(&threads[i], NULL,calc_sum, (void*)j); j+=1000; } for(i=0;i<10;i++) pthread_join(threads[i],NULL); exit(EXIT_SUCCESS); }<file_sep>#include<stdlib.h> void foo(int*** p) { } int main() { int ***a, **j, *k, *b; a = (int***) malloc(sizeof(int**)*5); // escapes j = (int**) malloc(sizeof(int*)*5); // escapes k = (int*) malloc(sizeof(int)*5); // escapes b = (int*) malloc(sizeof(int)*5); // does not escape *j = k; *a = j; j = (int**) malloc(sizeof(int*)*5); // escapes foo(a); return 0; } <file_sep>#include <omp.h> #include <stdio.h> #define N 10000 int A[N][N]; int B[N][N]; int C[N][N]; int main(){ int i,j; srand(time(NULL)); for(i = 0; i < N; i++) for(j = 0; j< N; j++){ A[i][j]= rand()%100; B[i][j]= rand()%100; } #pragma omp parallel num_threads(10) { int i,j; for(i = 0; i < N; i++) for(j = 0; j < N; j++) C[i][j] = A[i][j]+ B[i][j]; } return 0; }<file_sep>from numpy import genfromtxt import numpy as np import sys import sklearn.linear_model as sm from sklearn.metrics import f1_score data = genfromtxt('featuresDump.csv', delimiter=',') labels = genfromtxt('labels.csv', delimiter=',') with open(sys.argv[1]) as f_t: t = f_t.readlines() test_size = 0 for s in t: if s[0] == '#': test_size+=1 number_test_train = labels.shape[0] train_size = number_test_train-test_size trainData = data[:train_size] testData = data[train_size:number_test_train] usefulData = [] usefulLabel = [] for i in range(labels.shape[0]): if labels[i] != 0: usefulData.append(trainData[i].tolist()) usefulLabel.append(labels[i]) x = sm.LogisticRegression(class_weight='balanced') x.fit(usefulData,usefulLabel) y_pred = x.predict(testData).tolist() fw = open('output.txt','w') for i in y_pred: if i == 1: fw.write("1\n") if i == -1: fw.write("0\n") fw.close() print "Number of test Molecules were :",len(testData) <file_sep>__author__ = 'abhishek' import numpy as np import matplotlib.pyplot as plt from math import e,log lst=[] def calculate_derivative(): lst=list(np.arange(0.1,20,0.1)) print len(lst) lst_=[] for i in lst: val= 1-e**(-i/8.0) expr=(val**i)*(log(val)+(i*(1-val))/(8.0*val)) lst_.append(tuple([round(i,3),round(expr,13)])) print lst_ lst_x,lst_y=[],[] for i in range(1,21): lst_x.append(i) lst_y.append((1-e**(-i/8.0))**i) # plt.figure() # plt.plot(lst_x,lst_y) # plt.title("BloomFilter") # plt.xlabel("k") # plt.ylabel("False Positives") # plt.show() calculate_derivative(); <file_sep>#include<stdlib.h> void foo(int* p) { } int main() { int *i, *j, *k; i = (int*) malloc(sizeof(int)*5); // escapes j = (int*) malloc(sizeof(int)*5); // does not escape k = i; foo(k); return 0; } <file_sep>__author__ = 'abhisheky' """Create files containing only reachability values""" def extractReachable(fileName): with open(fileName,"r") as reader: with open("reachability_Only.txt","w") as writer: for line in reader: str_= line.split('-') writer.write(str_[1]) import matplotlib.pyplot as plt import numpy as np def plotSample(fileName): xCoord=[] yCoord=[] with open(fileName,"r") as reader: for line in reader: temp= line.strip("\n").split() xCoord.append(float(temp[0])) yCoord.append(float(temp[1])) colors= np.random.rand(20); plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.title("scatter plot of random sample of 10000 data-points") plt.scatter(xCoord,yCoord, c=colors) plt.show() def plotGraph(): x=[10000,25000, 100000, 200000, ] #y_kd_tree=[3160, 20570, 526094, 2033093] #y_normal= [8271, 56008, 1000499, 3921970] y_kd_tree=[.115, .615, 11.083, 54.820] y_normal=[3.120, 16.479, 228.210, 1001.355] plt.xlabel("sample-size"); plt.ylabel("time(ms)") plt.title("Plot comparing the running times of two implementations") plt.plot(x,y_kd_tree) plt.plot(x,y_normal) plt.legend(["kd_tree", "Naive", "e=0.1"], loc="upper left") plt.show() plotSample("/home/abhisheky/Documents/8thSem/DM/Assignments/Assignment3_New/Q1/sample10000.txt"); #plotGraph() #extractReachable("normal_out10000.txt")<file_sep>import java.io.*; import java.util.ArrayList; import java.util.Iterator; /** * Created by abhisheky on 25/2/16. */ class PointStore{ String point; Double reach; Double core; public PointStore(String point, Double reach, Double core){ this.core=core; this.reach= reach; this.point=point; } public PointStore(){ point=null; reach=1000.0; core= 1000.0; } } public class ClusterExtraction { public Double epsilon; public Integer minPts; public ClusterExtraction(Integer minPts, Double epsilon){ this.epsilon= epsilon; this.minPts= minPts; } public ArrayList<PointStore> readFile(){ File file= new File("/home/abhisheky/Documents/8thSem/DM/Assignments/Assignment3_New/Q1/Q1_b/reach_core.txt"); ArrayList<PointStore> store= new ArrayList<PointStore>(); try { BufferedReader reader= new BufferedReader(new FileReader(file)); String line, temp; while ((line=reader.readLine())!=null){ String [] strArray= line.split("-"); temp= strArray[0]; strArray=strArray[1].split(" "); // System.out.println(strArray[0]+" "+strArray[1]); store.add(new PointStore(temp,Double.parseDouble(strArray[0]), Double.parseDouble(strArray[1]))); } }catch (IOException ex){ ex.printStackTrace(); } return store; } public ArrayList<ArrayList<String>> exctract(ArrayList<PointStore> store){ Iterator<PointStore> sotreIterator= store.iterator(); ArrayList<ArrayList<String>> totalClusters= new ArrayList<ArrayList<String>>(); totalClusters.add(new ArrayList<String>()); int i=0; Double reachability; while (sotreIterator.hasNext()){ PointStore tempStore= sotreIterator.next(); if (Double.compare(tempStore.reach , epsilon)>0){ if (tempStore.core <= epsilon){ if(totalClusters.get(i).size()>0){ totalClusters.add(new ArrayList<String>()); i++; } totalClusters.get(i).add(tempStore.point); } }else{ totalClusters.get(i).add(tempStore.point); } } return totalClusters; } public void printExtractedClusters(ArrayList<ArrayList<String>> clusters){ Iterator<ArrayList<String>> iterator1= clusters.iterator(); System.out.println(clusters.size()); File file= new File("out_b_0123.txt"); try { BufferedWriter writer= new BufferedWriter(new BufferedWriter(new FileWriter(file))); while (iterator1.hasNext()) writer.write(Integer.toString(iterator1.next().size())+" "); writer.close(); }catch (IOException ex){ ex.printStackTrace(); } System.out.println(); } public static void main(String []args){ ClusterExtraction extraction= new ClusterExtraction(10,.0124); ArrayList<PointStore> store= extraction.readFile(); ArrayList<ArrayList<String>> clusters= extraction.exctract(store); extraction.printExtractedClusters(clusters); } } <file_sep>__author__ = 'abhishek' import matplotlib.pyplot as plt import sys plt.figure() lst_a=[5,10,25,50,95] lst_gSpan=[184.4,95.1,38.5,13.2,0.7] lst_gaston=[38.7575,16.9704,5.82853,2.46855,0.397861] lst_fsg=[242.966,117.217,43.6418,20.2219,6.00204] plt.plot(lst_a,lst_fsg,label="fsg") plt.plot(lst_a,lst_gSpan,label="gSpan") plt.plot(lst_a,lst_gaston,label="gaston") plt.legend(loc=1) plt.title("performance comparison of subgraph mining algorithms") plt.xlabel("Minsup(%)") plt.ylabel("time(s)") plt.show() <file_sep>__author__ = 'abhisheky' import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats files= ["out10.txt","out100.txt", "out500.txt","out1000.txt","out10000.txt"] for file in files: file_= open(file, "r") line= file_.readline().split() line= sorted([float(val) for val in line]) #fit= stats.norm.pdf(line,np.mean(line), np.std(line)) #plt.plot(line, fit, '-o') plt.hist(line, normed=True) plt.xlabel("Angles") plt.ylabel("frequency/normalized_Frequency") number= file.split('.')[0][3:] plt.title(str(number)+"-D datapoints"); plt.hist(line) plt.show() <file_sep>import java.io.*; import java.util.*; /** * Created by abhisheky on 16/2/16. */ public class Optics { public ArrayList<Point> points; public ArrayList<Point> orderedFile; public PriorityQueue<Point> seedList; public double epsilon; public int minPts; public Optics(){ points= new ArrayList<Point>(); orderedFile= new ArrayList<Point>(); seedList= new PriorityQueue<Point>(); epsilon=10; minPts=10; } public static void main(String []args){ Optics optics= new Optics(); optics.getDataPoints(); final long start_time= System.currentTimeMillis(); optics.runAlgo(); optics.printOrderedSet(); final long end_time= System.currentTimeMillis(); System.out.println(end_time- start_time); } public void getDataPoints(){ File file= new File("/home/abhisheky/Documents/8thSem/DM/Assignments/Assignment3_New/Q1/output.dat"); String str; String [] strArray; Integer identifier=0; try { BufferedReader reader= new BufferedReader(new FileReader(file)); while ((str=reader.readLine())!=null){ strArray= str.split(" "); Point point= new Point(); for(String temp_str: strArray) point.addCoord(Double.parseDouble(temp_str)); point.id=identifier; identifier++; points.add(point); } }catch(IOException exception){ exception.printStackTrace(); } } public void runAlgo(){ Iterator<Point> iterator= points.iterator(); while (iterator.hasNext()){ Point object= iterator.next(); if(!object.processed){ expandClusterOrder(object); } } } public void expandClusterOrder(Point object){ seedList.clear(); seedList.add(object); while (!seedList.isEmpty()) { Point nextObject = seedList.peek(); seedList.poll(); if(!nextObject.processed) { HashMap<Integer, Double> neighbors = getEpsilonNeighbors(nextObject); nextObject.processed = true; updateCoreDistance(nextObject, neighbors); orderedFile.add(nextObject); } } } public HashMap<Integer, Double> getEpsilonNeighbors(Point object){ HashMap<Integer, Double> neighors= new HashMap<Integer, Double>(); Iterator<Point> iterator= points.iterator(); double distance; while (iterator.hasNext()){ Point object2= iterator.next(); distance= object.getDistance(object2); if (distance <= epsilon) neighors.put(object2.id, distance); } return neighors; } public void updateCoreDistance(Point object, HashMap<Integer, Double> neighbors){ neighbors.remove(object.id); int localMin= minPts-2; int len= neighbors.size(); if(len > localMin) { List<Map.Entry<Integer, Double>> list = getSortedList(neighbors); Double core_dist = list.get(localMin).getValue(); object.core_dist = core_dist; Point point; for (int i = localMin; i >= 0; i--) { point = points.get(list.get(i).getKey()); if (!point.processed && point.reachability_dist > core_dist) { if (seedList.contains(point)) seedList.remove(point); point.reachability_dist = core_dist; seedList.add(point); } } for (int i = localMin+1; i < len; i++) { point = points.get(list.get(i).getKey()); if (!point.processed && point.reachability_dist > list.get(i).getValue()) { if (seedList.contains(point)) seedList.remove(point); point.reachability_dist = list.get(i).getValue(); seedList.add(point); } } } } public List<Map.Entry<Integer, Double>> getSortedList(HashMap<Integer, Double> passedMap){ Set<Map.Entry<Integer, Double>> set= passedMap.entrySet(); List<Map.Entry<Integer, Double>> list= new ArrayList<Map.Entry<Integer, Double>>(set); Collections.sort(list, new Comparator<Map.Entry<Integer, Double>>() { @Override public int compare(Map.Entry<Integer, Double> o1, Map.Entry<Integer, Double> o2) { return Double.compare(o1.getValue(), o2.getValue()); } }); return list; } public void printOrderedSet(){ Iterator<Point> iterator= orderedFile.iterator(); try { BufferedWriter writer= new BufferedWriter(new FileWriter(new File("/home/abhisheky/Documents/8thSem/DM/Assignments/Assignment3_New/Q1/Q1_b/reach_core.txt"))); while (iterator.hasNext()) { Point point= iterator.next(); writer.write("["+point.container.get(0).toString()+", "+point.container.get(1).toString()+"] - "); writer.write(Double.toString(point.reachability_dist) + " "+Double.toString(point.core_dist)+"\n"); } writer.close(); }catch (IOException ex){ ex.printStackTrace(); } } }
759a2f3a16eda29a832b672115797cb1e3482563
[ "Markdown", "Makefile", "Java", "Python", "C", "C++", "Shell" ]
47
Java
abhicse32/8th-Semester
279731d4b932992c9aa8701c221bb3acd4caf67d
dc88a3532e510be1d99b125398947e044bbbebdf
refs/heads/main
<file_sep>import functools class ScanNode: def __init__(self, args): self.file = args[0] self.buffer = [] self.data = iter(args[1]) def __iter__(self): return self def __next__(self): return next(self.data) class LimitNode: def __init__(self, prevNode, args): self.prevNode = prevNode self.limit = args[0] self.itemsReturned = 0 def __iter__(self): return self def __next__(self): if self.itemsReturned < self.limit: itemToReturn = next(self.prevNode) self.itemsReturned += 1 return itemToReturn else: raise StopIteration class FilterNode: EQUALS = "EQUALS" GT_EQ = "GT_EQ" LT_EQ = "LT_EQ" GT = "GT" LT = "LT" def __init__(self, prevNode, args): self.prevNode = prevNode orig_val = args[2] val = orig_val try: # try casting to an int val = int(orig_val) except ValueError: try: # try casting to a float if we were unsuccessful val = float(orig_val) except ValueError: pass # accept that it's probably a string self.predicate = {"column": args[0], "operator": args[1], "value": val} def __iter__(self): return self def _passes_predicate(self, row): op = self.predicate["operator"] value = row[self.predicate["column"]] comparison_value = self.predicate["value"] if op == FilterNode.EQUALS: return value == comparison_value elif op == FilterNode.GT_EQ: return value >= comparison_value elif op == FilterNode.LT_EQ: return value <= comparison_value elif op == FilterNode.GT: return value > comparison_value elif op == FilterNode.LT: return value < comparison_value else: raise TypeError def __next__(self): while True: return_value = next(self.prevNode) if self._passes_predicate(return_value): return return_value class ProjectionNode: def __init__(self, prevNode, args): self.prevNode = prevNode self.projections = args def __iter__(self): return self def __next__(self): res = next(self.prevNode) return {k: v for k in self.projections for v in res[k]} class SortNode: ASC = "ASC" DESC = "DESC" def __init__(self, prevNode, args): self.prevNode = prevNode self.sortInfo = args # TODO: change to named_tuple self.i = 0 self.sortedItems = None def _compare_single(self, obj, other, col): if obj[col] == other[col]: return 0 elif obj[col] < other[col]: return -1 else: return 1 def _compare(self, obj, other): for a in self.sortInfo: comparison_result = self._compare_single(obj, other, a[0]) if a[1] == SortNode.DESC: comparison_result *= -1 if comparison_result != 0: return comparison_result return 0 def __iter__(self): return self def __next__(self): if self.sortedItems is None: self.sortedItems = [item for item in self.prevNode] self.sortedItems.sort(key=functools.cmp_to_key(self._compare)) if self.i == len(self.sortedItems): raise StopIteration else: item_to_return = self.sortedItems[self.i] self.i += 1 return item_to_return <file_sep>from nodes import FilterNode, ProjectionNode, ScanNode, LimitNode, SortNode def run_query(query, data): prevNode = None for node in query: node_type, args = node[0], node[1] n = None if node_type == "SCAN": args.append(data) n = ScanNode(args) elif node_type == "LIMIT": n = LimitNode(prevNode, args) elif node_type == "FILTER": n = FilterNode(prevNode, args) elif node_type == "PROJECTION": n = ProjectionNode(prevNode, args) elif node_type == "SORT": n = SortNode(prevNode, args) prevNode = n results = [item for item in prevNode] return results <file_sep>import pytest from query import run_query def test_select_w_limit_extra_items(): data = [ {"title": "a", "genres": "cartoon"}, {"title": "b", "genres": "cartoon"}, {"title": "c", "genres": "cartoon"}, ] query = [ ["SCAN", ["movies"]], ["LIMIT", [2]], ] returned_items = run_query(query, data) assert returned_items == [ {"title": "a", "genres": "cartoon"}, {"title": "b", "genres": "cartoon"}, ] def test_select_w_limit_less_items(): data = [ {"title": "a", "genres": "cartoon"}, ] query = [ ["SCAN", ["movies"]], ["LIMIT", [2]], ] returned_items = run_query(query, data) assert returned_items == [ {"title": "a", "genres": "cartoon"}, ] def test_select_w_filter(): data = [ {"title": "a", "ratings": 5}, {"title": "c", "ratings": 1}, {"title": "b", "ratings": 2}, ] query = [ ["SCAN", ["movies"]], ["FILTER", ["ratings", "GT", "1"]], ] returned_items = run_query(query, data) assert returned_items == [ {"title": "a", "ratings": 5}, {"title": "b", "ratings": 2}, ] def test_select_w_filter_w_limit(): data = [ {"title": "a", "ratings": 5}, {"title": "c", "ratings": 1}, {"title": "b", "ratings": 2}, ] query = [["SCAN", ["movies"]], ["FILTER", ["ratings", "GT", "1"]], ["LIMIT", [1]]] returned_items = run_query(query, data) assert returned_items == [ {"title": "a", "ratings": 5}, ] def test_projection(): data = [ {"title": "a", "ratings": 5}, {"title": "c", "ratings": 1}, {"title": "b", "ratings": 2}, ] query = [ ["SCAN", ["movies"]], ["FILTER", ["ratings", "GT", "1"]], ["PROJECTION", ["title"]], ] returned_items = run_query(query, data) assert returned_items == [ {"title": "a"}, {"title": "b"}, ] def test_projection_w_float(): data = [ {"title": "a", "ratings": 5}, {"title": "c", "ratings": 1}, {"title": "b", "ratings": 2.5}, ] query = [ ["SCAN", ["movies"]], ["FILTER", ["ratings", "GT", "1.4"]], ["PROJECTION", ["title"]], ] returned_items = run_query(query, data) assert returned_items == [ {"title": "a"}, {"title": "b"}, ] def test_sort(): data = [ {"title": "c", "ratings": 1}, {"title": "b", "ratings": 2}, {"title": "a", "ratings": 5}, ] query = [ ["SCAN", ["movies"]], ["SORT", [["ratings", "DESC"]]], ["PROJECTION", ["title"]], ] returned_items = run_query(query, data) assert returned_items == [{"title": "a"}, {"title": "b"}, {"title": "c"}]
5fa1f6faa1ce6795095a473d8dcb363983ea4ee9
[ "Python" ]
3
Python
jmhwang7/query-executor
2402cb571762bc9fe15cbdbafc4d632d79aaf0df
5919be6500c0ab6b214e4ed7df0f613498a65a52
refs/heads/master
<file_sep>package com.horus.travelweather.model import com.google.gson.annotations.SerializedName data class WeatherDetailsResponse(val weather : List<WeatherItem> = emptyList(), @SerializedName("main") val temperature : TemperatureItem = TemperatureItem(0.0,0.0,0.0,0.0), @SerializedName("name") val nameCity : String="", @SerializedName("dt") val dateTime : Long=0, val wind : WindItem = WindItem(0.0,""), val clouds : CloudsItem = CloudsItem(0.0))<file_sep>package com.horus.travelweather.fragment import android.app.Activity 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 com.horus.travelweather.BottomNavigation import com.horus.travelweather.R import com.horus.travelweather.activity.AddLocationActivity import kotlinx.android.synthetic.main.fragment_add_location.view.* class AddLocationFragment: Fragment() { //Creating view, return view is a view (xml) as fragment override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_add_location, container, false) view.btn_add_location.setOnClickListener { val intent = Intent(this.context, AddLocationActivity::class.java) //after successlly addlocation -> refer to HomeAcrivity (code: 1234) startActivityForResult(intent, 1234) } return view } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == 1234){ //way to start Kotlin activity if (resultCode == Activity.RESULT_OK){ val intent = Intent(context, BottomNavigation::class.java) //this activity will be this fragment's father //update fragments of HomeActivity intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK //Tao bỏ FLAG_ACTIVITY_CLEAR_TASK để tránh lỗi thêm vị trí xong về lại homeactivity đc 1 lúc bị out ra nha startActivity(intent) } } } }<file_sep>package com.horus.travelweather.model class TemperatureItem (var temp : Double , var humidity : Double, var temp_min : Double, var temp_max : Double){ }<file_sep>package com.horus.travelweather.adapter import android.support.v7.widget.AppCompatImageView import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.horus.travelweather.R import com.horus.travelweather.activity.DirectionsFragment import com.horus.travelweather.model.TransportationDbO import kotlinx.android.synthetic.main.transportation_list.view.* class TransportationAdapter (private var listTransportation : List<TransportationDbO>, private val onItemClick : (String)-> Unit ) : RecyclerView.Adapter<TransportationAdapter.ViewHolder>() { //Đầu vào là 1 danh sách và 1 cái click (nếu có, click vào nút btn_delete để xóa địa điểm của mình đã thêm) private val TAG = DirectionsFragment::class.java.simpleName //assigning layout for a recyclerview element. override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.transportation_list, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return listTransportation.size } //assigning date from listTransportation to ViewHolder override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(listTransportation[position]) } //This class controls views better, avoiding findViewByID too time inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val imgView_transportation = itemView.findViewById<View>(R.id.imgView_transportation) as AppCompatImageView private val tv_duration = itemView.findViewById<View>(R.id.tv_duration) as TextView fun bind(transkind : TransportationDbO) { //Lập trình bất đồng bộ //Set cho imgView_transportation trên recycleviewer 1 lắng nghe (nhận id bất kỳ để nhận dạng loại ptien) itemView.tv_duration.setOnClickListener { onItemClick(transkind.id) } if(transkind.id == "driving"){ imgView_transportation.setImageResource(R.drawable.ic24_car) } else if(transkind.id == "walking"){ imgView_transportation.setImageResource(R.drawable.ic24_walking) } else if(transkind.id == "transit"){ imgView_transportation.setImageResource(R.drawable.ic24_bus) } else if(transkind.id == "bicycling"){ imgView_transportation.setImageResource(R.drawable.ic24_walking) } else if(transkind.id == "5"){ imgView_transportation.setImageResource(R.drawable.originpoint_icon24) } tv_duration.text = transkind.duration } } }<file_sep>package com.horus.travelweather.activity import android.content.pm.PackageManager import android.graphics.Color import android.location.Geocoder import android.location.Location import android.os.AsyncTask import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.app.FragmentActivity import android.util.Log import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationServices import com.google.android.gms.location.places.Places import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.* import com.horus.travelweather.R import com.horus.travelweather.model.PlaceDbO import org.json.JSONObject import java.io.BufferedReader import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import java.util.* class MapsActivity : FragmentActivity(), OnMapReadyCallback { /*GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {*/ private lateinit var mMap: GoogleMap private lateinit var fusedLocationClient: FusedLocationProviderClient //Getting current location private lateinit var lastLocation: Location private lateinit var markerPoints:ArrayList<LatLng> private lateinit var mGoogleApiClient:GoogleApiClient private lateinit var mLastLocation:Location private var mCurrLocationMarker: Marker? = null private lateinit var mLocationRequest:LocationRequest //add a companion object with the code to request location permission companion object { private const val LOCATION_PERMISSION_REQUEST_CODE = 1 //val MY_PERMISSIONS_REQUEST_LOCATION = 99 //private const val REQUEST_CHECK_SETTINGS = 2 // (RLU) is used as the request code passed to onActivityResult } /*private fun setUpMap() { //The code above checks if the app has been granted the ACCESS_FINE_LOCATION permission. If it hasn’t, then request it from the user. //Add a call to setUpMap() at the end of onMapReady(). //Build and run; click “Allow” to grant permission if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE) return } //Get your current location // isMyLocationEnabled = true enables the my-location layer which draws a light blue dot on the user’s location. // It also adds a button to the map that, when tapped, centers the map on the user’s location. mMap.isMyLocationEnabled = true // fusedLocationClient.getLastLocation() gives you the most recent location currently available. fusedLocationClient.lastLocation.addOnSuccessListener(this) { location -> // Got last known location. In some rare situations this can be null. // 3 if (location != null) { lastLocation = location val geocoder = Geocoder(this, Locale.getDefault()) try { val addresses = geocoder.getFromLocation(location.latitude, location.longitude, 1) if (addresses != null) { val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } start_location=addresses.get(0).getAddressLine(0) Log.e("start location: ",addresses.get(0).getAddressLine(0)) } else { Log.d("a","No Address returned! : ") } } catch (e:IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a","Canont get Address!") } } } }*/ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_maps) /* if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission() } */ // Initializing markerPoints = ArrayList<LatLng>() // Obtain the SupportMapFragment and get notified when the map is ready to be used. val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) } override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap setupGoogleMapScreenSettings(googleMap) //setUpMap() //Get current location //The code above checks if the app has been granted the ACCESS_FINE_LOCATION permission. If it hasn’t, then request it from the user. //Add a call to setUpMap() at the end of onMapReady(). //Build and run; click “Allow” to grant permission if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE) return } //Initialize Google Play Services /* if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) === PackageManager.PERMISSION_GRANTED)) { buildGoogleApiClient() mMap.isMyLocationEnabled = true } } else { buildGoogleApiClient() mMap.isMyLocationEnabled = true } */ //Get your current location // isMyLocationEnabled = true enables the my-location layer which draws a light blue dot on the user’s location. // It also adds a button to the map that, when tapped, centers the map on the user’s location. mMap.isMyLocationEnabled = true var currentlocation = LatLng(10.762622, 106.660172) var destlocation = LatLng(10.762622, 106.660172) // fusedLocationClient.getLastLocation() gives you the most recent location currently available. fusedLocationClient.lastLocation.addOnSuccessListener(this) { location -> // Got last known location. In some rare situations this can be null. // 3 if (location != null) { lastLocation = location val geocoder = Geocoder(this, Locale.getDefault()) try { val addresses = geocoder.getFromLocation(lastLocation.latitude, lastLocation.longitude, 1) if (addresses != null) { val returnedAddress = addresses[0] val strReturnedAddress = StringBuilder("Address:\n") for (i in 0 until returnedAddress.maxAddressLineIndex) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } currentlocation = LatLng(addresses[0].latitude, addresses[0].longitude) Log.e("start location: ", currentlocation.toString()) //Get Latlng of destinational location (MyPlace from favoritePlaceAvtivity) val place = intent.getSerializableExtra("MyPlace") as PlaceDbO val mGeoDataClient = Places.getGeoDataClient(this) mGeoDataClient.getPlaceById(place.placeId).addOnCompleteListener { task -> if (task.isSuccessful) { val places = task.result val myPlace = places.get(0) destlocation = myPlace.latLng Log.e("end location: ", destlocation.toString()) //Add marker -> location markerPoints.add(currentlocation) markerPoints.add(destlocation) // Creating MarkerOptions val options = MarkerOptions() // Setting the position of the marker options.position(currentlocation).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)) mMap.addMarker(options).title = (addresses[0].getAddressLine(0)) options.position(destlocation).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)) mMap.addMarker(options).title = (myPlace.address.toString()) /** * For the start location, the color of marker is GREEN and * for the end location, the color of marker is RED. */ /** * For the start location, the color of marker is GREEN and * for the end location, the color of marker is RED. */ // Add new marker to the Google Map Android API V2 // Getting URL to the Google Directions API val url = getUrl(currentlocation, destlocation) //val url = getUrl(LatLng(addresses[0].longitude, addresses[0].latitude), myPlace.latLng) Log.d("onMapClick: ", url) val fetchUrl = FetchUrl() Log.d("fetchUrl: ", fetchUrl.toString()) // Start downloading json data from Google Directions API fetchUrl.execute(url) //move map camera mMap.moveCamera(CameraUpdateFactory.newLatLng(currentlocation)) mMap.animateCamera(CameraUpdateFactory.zoomTo(12F)) places.release() return@addOnCompleteListener } else { Log.e("Notice: ", "Place not found.") } } } else { Log.d("a", "No Address returned! : ") } } catch (e: IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a", "Canont get Address!") } } } } private fun getUrl(origin:LatLng, dest:LatLng):String { // Origin of route val strOrigin = "origin=" + origin.latitude + "," + origin.longitude // Destination of route val strDest = "destination=" + dest.latitude + "," + dest.longitude // Sensor enabled val sensor = "sensor=false" // Building the parameters to the web service val parameters = "${strOrigin.trim()}&${strDest.trim()}&$sensor" // Output format val output = "json" val apikey="<KEY>" // Building the url to the web service val url = "https://maps.googleapis.com/maps/api/directions/$output?$parameters&mode=DRIVING&key=$apikey" return url } // Fetches data from url passed private inner class FetchUrl:AsyncTask<String, Void, String>() { override fun doInBackground(vararg url:String):String { // For storing data from web service var data = "" try { // Fetching the data from web service data = downloadUrl(url[0]) Log.d("Background Task data", data.toString()) } catch (e:Exception) { Log.d("Background Task", e.toString()) } return data } override fun onPostExecute(result:String) { Log.d("onPostExecue resute", result.toString()) super.onPostExecute(result) var parserTask = ParserTask() // Invokes the thread for parsing the JSON data parserTask.execute(result) } } /** * A method to download json data from url */ @Throws(IOException::class) private fun downloadUrl(strUrl: String): String { var data = "" var iStream: InputStream? = null var urlConnection: HttpURLConnection? = null try { val url = URL(strUrl) // Creating an http connection to communicate with url urlConnection = url.openConnection() as HttpURLConnection Log.d("url connection: ", urlConnection.toString()) // Connecting to url urlConnection.connect() // Reading data from url iStream = urlConnection.inputStream Log.d("iStream: ", iStream.toString()) data = iStream.bufferedReader().use(BufferedReader::readText) iStream.bufferedReader().close() } catch (e: Exception) { Log.d("Exception downloadUrl", e.toString()) } finally { iStream!!.close() urlConnection!!.disconnect() } return data } /** * A class to parse the Google Places in JSON format */ private inner class ParserTask : AsyncTask<String, Int, List<List<HashMap<String, String>>>>() { // Parsing the data in non-ui thread override fun doInBackground(vararg jsonData: String): List<List<HashMap<String, String>>> { val jObject: JSONObject? try { jObject = JSONObject(jsonData[0]) Log.d("ParserTask", jsonData[0]) val parser = DataParser() Log.d("ParserTask", parser.toString()) // Starts parsing data var routes: List<List<HashMap<String, String>>> = parser.parse(jObject) Log.d("ParserTask", "Executing routes") Log.d("ParserTask", routes.toString()) return routes } catch (e: Exception) { Log.d("ParserTask", e.toString()) e.printStackTrace() } val r:List<List<HashMap<String, String>>> = ArrayList<ArrayList<HashMap<String, String>>>() return r } // Executes in UI thread, after the parsing process override fun onPostExecute(result: List<List<HashMap<String, String>>>) { var points: ArrayList<LatLng> var lineOptions: PolylineOptions? = null // Traversing through all the routes for (i in result.indices) { points = ArrayList<LatLng>() lineOptions = PolylineOptions() // Fetching i-th route val path = result[i] // Fetching all the points in i-th route for (j in path.indices) { val point = path[j] val lat = java.lang.Double.parseDouble(point["lat"]) val lng = java.lang.Double.parseDouble(point["lng"]) val position = LatLng(lat, lng) points.add(position) } // Adding all the points in the route to LineOptions lineOptions.addAll(points) lineOptions.width(12f) lineOptions.color(Color.rgb(70, 155, 253)) Log.d("onPostExecute", "onPostExecute lineoptions decoded") } // Drawing polyline in the Google Map for the i-th route if (lineOptions != null) { mMap.addPolyline(lineOptions) } else { Log.d("onPostExecute", "without Polylines drawn") } } } private fun setupGoogleMapScreenSettings(mMap:GoogleMap) { mMap.isBuildingsEnabled = true //Turns the 3D buildings layer on mMap.isIndoorEnabled = true //Sets whether indoor maps should be enabled. //mMap.isTrafficEnabled = true //Turns the traffic layer on or off. mMap.mapType = GoogleMap.MAP_TYPE_NORMAL val mUiSettings = mMap.uiSettings mUiSettings.isZoomControlsEnabled = true //it can be zoom control mUiSettings.isCompassEnabled = true //....compass (la ban) mUiSettings.isMyLocationButtonEnabled = true //Enables or disables the my-location layer. mUiSettings.isScrollGesturesEnabled = true //....cử chỉ scroll mUiSettings.isZoomGesturesEnabled = true //...zoom mUiSettings.isTiltGesturesEnabled = true //...Tilt (nghiêng) mUiSettings.isRotateGesturesEnabled = true //...Rotate mUiSettings.isMapToolbarEnabled = true // It ain't working, CHECKKKKKK } /* @Synchronized private fun buildGoogleApiClient() { mGoogleApiClient = GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build() mGoogleApiClient.connect() } override fun onConnected(bundle:Bundle?) { mLocationRequest = LocationRequest() mLocationRequest.interval = 1000 mLocationRequest.fastestInterval = 1000 mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) === PackageManager.PERMISSION_GRANTED)) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this) } } override fun onConnectionSuspended(i:Int) { } override fun onLocationChanged(location:Location) { mLastLocation = location lastLocation = location if (mCurrLocationMarker != null) { mCurrLocationMarker!!.remove() } //Place current location marker val latLng = LatLng(location.latitude, location.longitude) val markerOptions = MarkerOptions() markerOptions.position(latLng) markerOptions.title("Current Position") markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)) mCurrLocationMarker = mMap.addMarker(markerOptions) //move map camera mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)) mMap.animateCamera(CameraUpdateFactory.zoomTo(11F)) //stop location updates if (mGoogleApiClient != null) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this) } } override fun onConnectionFailed(connectionResult:ConnectionResult) { } private fun checkLocationPermission():Boolean { if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !== PackageManager.PERMISSION_GRANTED)) { // Asking user if explanation is needed if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), DirectionsFragment.MY_PERMISSIONS_REQUEST_LOCATION) } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), DirectionsFragment.MY_PERMISSIONS_REQUEST_LOCATION) } return false } else { return true } } override fun onRequestPermissionsResult(requestCode:Int, permissions:Array<String>, grantResults:IntArray) { when (requestCode) { DirectionsFragment.MY_PERMISSIONS_REQUEST_LOCATION -> { // If request is cancelled, the result arrays are empty. if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // permission was granted. Do the // contacts-related task you need to do. if ((ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) === PackageManager.PERMISSION_GRANTED)) { if (mGoogleApiClient == null) { buildGoogleApiClient() } mMap.isMyLocationEnabled = true } } else { // Permission denied, Disable the functionality that depends on this permission. Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show() } return } }// other 'case' lines to check for other permissions this app might request. // You can add here other case statements according to your requirement. }*/ } <file_sep>package com.horus.travelweather.adapter import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.horus.travelweather.R import com.horus.travelweather.database.PlaceEntity import kotlinx.android.synthetic.main.locaiton_item.view.* class LocationAdapter(private val listLocation : List<PlaceEntity>, private val onItemClick : (String)-> Unit ) : RecyclerView.Adapter<LocationAdapter.ViewHolder>() { //Đầu vào là 1 danh sách và 1 cái click (nếu có, click vào nút btn_delete để xóa địa điểm của mình đã thêm) //assigning layout for a recyclerview element. override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.locaiton_item, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return listLocation.size } //assigning date from listLocation to ViewHolder override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(listLocation[position]) } //This class controls views better, avoiding findViewByID too time inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { fun bind(location : PlaceEntity) { //Lập trình bất đồng bộ //Set cho btn_delete trên recycleviewer 1 lắng nghe (nhận id bất kỳ) itemView.btn_delete_location.setOnClickListener { onItemClick(location.id) } itemView.txt_chose_location.text = location.name } } }<file_sep>package com.horus.travelweather.adapter import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.app.FragmentStatePagerAdapter import android.util.Log import android.view.View import com.horus.travelweather.R import com.horus.travelweather.R.id.progress_loading import com.horus.travelweather.database.PlaceEntity import com.horus.travelweather.fragment.AddLocationFragment import com.horus.travelweather.fragment.WeatherDetailFragment import kotlinx.android.synthetic.main.activity_bottom_navigation.* open class ViewPagerAdapter(fragmentManager: FragmentManager, private var listPlaces: List<PlaceEntity>) : FragmentPagerAdapter(fragmentManager) { private val TAG = ViewPagerAdapter::class.java.simpleName; override fun getItem(position: Int): Fragment { Log.e(TAG, " Test : " + position); return newInstance(position, listPlaces) } override fun getCount(): Int { return listPlaces.size + 2 } // companion object { fun newInstance(position: Int, listPlaces: List<PlaceEntity>): Fragment { //Vuốt khi nào hết các placelist fragment của user đó thì nó sẽ hiển thị add location fragment return if (position >= 0 && position < (listPlaces.size + 1)) newInsWeather(position, listPlaces) else newInsAddLocation(position) } private fun newInsWeather(position: Int, listPlaces: List<PlaceEntity>): WeatherDetailFragment { val fragment = WeatherDetailFragment() //use Bundle() to exchange among intent //this activity receives "position" from getDataFromLocal() of HomeActivity val args = Bundle() args.putInt("position", position) if (position != 0) { args.putDouble("lat", listPlaces[position - 1].latitude) args.putDouble("lon", listPlaces[position - 1].longitude) Log.e(TAG, " lat : " + listPlaces[position - 1].latitude); Log.e(TAG, " lon : " + listPlaces[position - 1].latitude); } fragment.arguments = args return fragment } private fun newInsAddLocation(position: Int): AddLocationFragment { val fragment = AddLocationFragment() val args = Bundle() args.putInt("position", position) fragment.arguments = args return fragment } // } }<file_sep>package com.horus.travelweather.database import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey @Entity(tableName = "profileData") data class ProfileEntity (@PrimaryKey var uid : String, @ColumnInfo(name = "name") var name : String, @ColumnInfo(name = "email") var email: String, @ColumnInfo(name = "phone") var phoneNumber : String){ constructor():this("","","","") }<file_sep>package com.horus.travelweather.activity import android.app.Activity import android.app.AlertDialog import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.location.Geocoder import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.PopupMenu import android.util.Log import android.view.* import android.widget.TextView import android.widget.Toast import com.firebase.ui.database.FirebaseRecyclerAdapter import com.firebase.ui.database.FirebaseRecyclerOptions import com.google.android.gms.location.places.AutocompleteFilter import com.google.android.gms.location.places.PlacePhotoMetadataResponse import com.google.android.gms.location.places.PlacePhotoResponse import com.google.android.gms.location.places.Places import com.google.android.gms.location.places.ui.PlaceAutocomplete import com.google.android.gms.maps.model.LatLng import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.OnFailureListener import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.* import com.google.firebase.storage.FirebaseStorage import com.horus.travelweather.R import com.horus.travelweather.adapter.FavouritePlaceAdapter import com.horus.travelweather.adapter.HistoryAdapter import com.horus.travelweather.common.TWConstant.Companion.REMOVE_PLACE import com.horus.travelweather.model.* import kotlinx.android.synthetic.main.activity_directions.view.* import kotlinx.android.synthetic.main.activity_favourite_my_place.view.* import java.io.ByteArrayOutputStream import java.io.IOException import java.text.SimpleDateFormat import java.util.* class FavoritePlaceFragment : Fragment() { private val TAG = FavoritePlaceFragment::class.java.simpleName var PLACE_AUTOCOMPLETE_REQUEST_CODE = 1 private val placeDb = PlaceDbO() lateinit var database: FirebaseDatabase lateinit var favourite_list: DatabaseReference lateinit var mAuth: FirebaseAuth lateinit var adapter: FirebaseRecyclerAdapter<PlaceDbO, FavouritePlaceAdapter.PlaceViewHolder> var myuser: FirebaseUser? = null private val historyDb = HistoryDbO() lateinit var history_list: DatabaseReference lateinit var adapter2: FirebaseRecyclerAdapter<HistoryDbO, HistoryAdapter.HistoryViewHolder> //ask to add temp favplace to favouriteplace private val tempfavplaceDb = TempFavPlaceDbO() //for AI lateinit var tempfavplace_list: DatabaseReference //for AI lateinit var city_statistics: DatabaseReference //for statistics //temp place private val tempplaceDb = TempPlaceDbO() //for AI lateinit var tempplace_list: DatabaseReference //for AI override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.activity_favourite_my_place, container, false) setHasOptionsMenu(true) mAuth = FirebaseAuth.getInstance() myuser = mAuth.currentUser database = FirebaseDatabase.getInstance() favourite_list = database.getReference("favouriteplace") history_list = database.getReference("history") tempfavplace_list = database.getReference("tempfavplace").child(mAuth.currentUser!!.uid) city_statistics = database.getReference("city_statistics") tempplace_list = database.getReference("tempplace").child(mAuth.currentUser!!.uid) add_tempfavplace("") view.btn_add_my_place.setOnClickListener { val typeFilter = AutocompleteFilter.Builder() .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS) .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ESTABLISHMENT) .setCountry("VN") .build() val intent = PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN) .setFilter(typeFilter) .build(this.activity) startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE) } val options = FirebaseRecyclerOptions.Builder<PlaceDbO>() .setQuery(favourite_list.child(myuser!!.uid), PlaceDbO::class.java) .setLifecycleOwner(this) .build() adapter = FavouritePlaceAdapter(options, { context, textView, i -> showPopup(context, textView, i) },{ openDetailPlace(it) }) view.rv_my_places.layoutManager = LinearLayoutManager(this.activity) view.rv_my_places.adapter = adapter view.rv_my_places.setNestedScrollingEnabled(false) return view } lateinit var favplace_list: DatabaseReference fun add_tempfavplace(position:String){ database = FirebaseDatabase.getInstance() mAuth = FirebaseAuth.getInstance() tempfavplace_list = database.getReference("tempfavplace").child(mAuth.currentUser!!.uid) //Get favplace name list to ask add tempfavplace favplace_list = database.getReference("favouriteplace").child(mAuth.currentUser!!.uid) val favplacename_list = java.util.ArrayList<String>() var index_temp = 0 favplace_list.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { } override fun onDataChange(dataSnapshot: DataSnapshot) { // Result will be holded Here for (dsp in dataSnapshot.children) { //add result into array list val item: PlaceDbO? = dsp.getValue(PlaceDbO::class.java) if (item != null) { favplacename_list.add(item.name) Log.d("favplace name : ", favplacename_list.get(index_temp)) index_temp++ } } } }) //end //check tempfavplace data to add/update/ask tempfavplace tempfavplace_list.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Log.e(TAG, "Error : " + p0.message) } override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()) { // code if data exists for (dsp in dataSnapshot.children) { val item: TempFavPlaceDbO? = dsp.getValue(TempFavPlaceDbO::class.java) if (item != null) { //Add new place if temp place (visit:1 or searchh: 5) val date = getCurrentDateTime() val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) /*if(position != "" && position == dsp.key){ tempfavplaceDb.id = item.id //tempfavplaceDb.latitude = item.latitude // tempfavplaceDb.longitude = item.longitude tempfavplaceDb.name = item.name tempfavplaceDb.uri = item.uri tempfavplaceDb.address = item.address tempfavplaceDb.numofsearch = item.numofsearch tempfavplaceDb.numofvisit = item.numofvisit tempfavplaceDb.numofask = 0 tempfavplaceDb.askdate = currenttime tempfavplaceDb.numsearch_after_ask = 0 tempfavplace_list.child(item.id).setValue(tempfavplaceDb) } else*/ if (favplacename_list.contains(item.name) == true) { } else if ((item.numofsearch > 2) && item.numofask < 2 && currenttime != item.askdate && currentday_oldday_space(item.askdate) > 2 ) { val alertDialogBuilder = AlertDialog.Builder(context) alertDialogBuilder.setTitle("Thêm địa điểm yêu thích") alertDialogBuilder .setMessage("Bạn có muốn thêm " + item.name + " vào danh sách yêu thích để tiện theo dõi" + " địa điểm hay không?") .setCancelable(false) .setPositiveButton("Yes") { dialog, id -> // Add new place if temp place qualified //for(pl in placeList){ // if(pl.name == item.name){ val favplaceDB = PlaceDbO() favplaceDB.name = item.name favplaceDB.address = item.address favplaceDB.placeId = item.id favplaceDB.uri = item.uri favplace_list.child(item.id).setValue(favplaceDB) // } //} Toast.makeText(context, "Đã thêm vào danh sách yêu thích", Toast.LENGTH_SHORT).show() //update date tempfavplaceDb.id = item.id //tempfavplaceDb.latitude = item.latitude // tempfavplaceDb.longitude = item.longitude tempfavplaceDb.name = item.name tempfavplaceDb.uri = item.uri tempfavplaceDb.address = item.address tempfavplaceDb.numofsearch = item.numofsearch tempfavplaceDb.numofvisit = item.numofvisit tempfavplaceDb.numofask = item.numofask tempfavplaceDb.askdate = currenttime tempfavplaceDb.numsearch_after_ask = item.numsearch_after_ask tempfavplace_list.child(item.id).setValue(tempfavplaceDb) //val intent = Intent(context, BottomNavigation::class.java) //this activity will be this fragment's father // intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK //startActivity(intent) } .setNegativeButton("No") { dialog, id -> // if this button is clicked, just close // the dialog box and do nothing tempfavplaceDb.id = item.id //tempfavplaceDb.latitude = item.latitude // tempfavplaceDb.longitude = item.longitude tempfavplaceDb.name = item.name tempfavplaceDb.uri = item.uri tempfavplaceDb.address = item.address tempfavplaceDb.numofsearch = item.numofsearch tempfavplaceDb.numofvisit = item.numofvisit tempfavplaceDb.numofask = item.numofask+1 tempfavplaceDb.askdate = currenttime tempfavplaceDb.numsearch_after_ask = item.numsearch_after_ask tempfavplace_list.child(item.id).setValue(tempfavplaceDb) dialog.cancel() } val alertDialog = alertDialogBuilder.create() alertDialog.show() } }// } } else { } // Result will be holded Here //insertAllPlace().execute(placeList) } }) } var cityname_temp = "" var citysatistics_flag = true private fun uploadCitySatistics() { city_statistics.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Log.e(TAG, "Error : " + p0.message) } var numofsearch_others = 0 override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()) { // code if data exists // if current place like before place for (dsp in dataSnapshot.children) { //add result into array list val item: CitySatisticsDbO? = dsp.getValue(CitySatisticsDbO::class.java) if (item != null) { if(item.name == "Others") numofsearch_others = item.numofsearch if ((cityname_temp == item.name || cityname_temp == "Thành phố " + item.name || cityname_temp == "Thủ Đô " + item.name || cityname_temp == "Tỉnh " + item.name)) { Log.e("lamquanglich : ",dsp.key) city_statistics.child(dsp.key!!).setValue(CitySatisticsDbO(item.name,item.numofsearch+1)) citysatistics_flag = false } } } } else { // code if data does not exists if(cityname_temp != ""){ if((cityname_temp.toLowerCase() == "hồ chí minh" || cityname_temp == "thành phố hồ chí minh") || (cityname_temp.toLowerCase() == "hà nội" || cityname_temp == "thủ đô hà nội") || (cityname_temp.toLowerCase() == "đà nẵng" || cityname_temp == "thành phố đà nẵng") || (cityname_temp.toLowerCase() == "cần thơ" || cityname_temp == "thành phố cần thơ") ){ city_statistics.push().setValue(CitySatisticsDbO(cityname_temp,1)) } else { city_statistics.child("-Li261TH2CuzJV9lyWvM").setValue(CitySatisticsDbO("Others",numofsearch_others+1)) } citysatistics_flag = false } } if (citysatistics_flag && cityname_temp != "") { if((cityname_temp.toLowerCase() == "hồ chí minh" || cityname_temp == "thành phố hồ chí minh") || (cityname_temp.toLowerCase() == "hà nội" || cityname_temp == "thủ đô hà nội") || (cityname_temp.toLowerCase() == "đà nẵng" || cityname_temp == "thành phố đà nẵng") || (cityname_temp.toLowerCase() == "cần thơ" || cityname_temp == "thành phố cần thơ") ){ city_statistics.push().setValue(CitySatisticsDbO(cityname_temp,1)) } else { city_statistics.child("-Li261TH2CuzJV9lyWvM").setValue(CitySatisticsDbO("Others",numofsearch_others+1)) } } } }) } var newplace_flag = true var curplace_like_beforeplace = false var placeid_temp = "" var latitude_temp = 0.0 var longitude_temp = 0.0 private fun uploadTempplace() { tempplace_list.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Log.e(TAG, "Error : " + p0.message) } override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()) { // code if data exists // if current place like before place for (dsp in dataSnapshot.children) { //add result into array list val item: TempPlaceDbO? = dsp.getValue(TempPlaceDbO::class.java) if (item != null) { var now_cityname = "" //Log.e("Test AI : ",dsp.key) if (dsp.key == mAuth.currentUser!!.uid && item.name == cityname_temp) { curplace_like_beforeplace = true now_cityname = item.name //Log.e("Test AI : ",placeid_temp + item.name + cityname_temp) //break } if ((cityname_temp == item.name || cityname_temp == "Thành phố " + item.name || cityname_temp == "Thủ Đô " + item.name || cityname_temp == "Tỉnh " + item.name)) { if(item.numofask >= 1 && item.numsearch_after_ask >= 4){ tempplaceDb.numofask=item.numofask - 1 tempplaceDb.numsearch_after_ask = 0 } else if(item.numofask >= 2){ tempplaceDb.numsearch_after_ask=item.numsearch_after_ask+1 tempplaceDb.numofask = item.numofask } else { tempplaceDb.numofask = item.numofask tempplaceDb.numsearch_after_ask=item.numsearch_after_ask } //place_list.child(place.id).setValue(placeDB) //tempplaceDb.numofvisit = item.numofvisit+1 tempplaceDb.latitude = item.latitude tempplaceDb.longitude = item.longitude tempplaceDb.name = item.name tempplaceDb.numofsearch = item.numofsearch + 1 tempplaceDb.numofvisit = item.numofvisit tempplaceDb.id = item.id tempplaceDb.askdate = item.askdate tempplace_list.child(item.id).setValue(tempplaceDb) //update dia diem hien tai gan nhat da ghe qua if(curplace_like_beforeplace){ tempplace_list.child(mAuth.currentUser!!.uid).setValue(tempplaceDb) curplace_like_beforeplace = false } newplace_flag = false } } } } else { if(cityname_temp != ""){ // code if data does not exists tempplaceDb.latitude = latitude_temp tempplaceDb.longitude = longitude_temp tempplaceDb.name = cityname_temp tempplaceDb.numofsearch = 1 tempplaceDb.id = placeid_temp val date = getCurrentDateTime() val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) tempplaceDb.askdate = currenttime tempplace_list.child(tempplaceDb.id).setValue(tempplaceDb) //update dia diem hien tai gan nhat da ghe qua if(curplace_like_beforeplace){ tempplace_list.child(mAuth.currentUser!!.uid).setValue(tempplaceDb) curplace_like_beforeplace = false } newplace_flag = false } } if (newplace_flag && cityname_temp != "") { tempplaceDb.latitude = latitude_temp tempplaceDb.longitude = longitude_temp tempplaceDb.name = cityname_temp tempplaceDb.numofsearch = 1 tempplaceDb.id = placeid_temp val date = getCurrentDateTime() val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) tempplaceDb.askdate = currenttime tempplace_list.child(tempplaceDb.id).setValue(tempplaceDb) //update dia diem hien tai gan nhat da ghe qua if(curplace_like_beforeplace){ tempplace_list.child(mAuth.currentUser!!.uid).setValue(tempplaceDb) curplace_like_beforeplace = false } } // Result will be holded Here //insertAllPlace().execute(placeList) } }) } fun currentday_oldday_space(startDate:String) : Long{ val simpleDateFormat = SimpleDateFormat("dd/MM/yyyy") val currentDate = Date() var date1: Date? = null var date2: Date? = null var getDaysDiff:Long = 0 try { //startDate = "01-01-2016" val endDate = simpleDateFormat.format(currentDate) date1 = simpleDateFormat.parse(startDate) date2 = simpleDateFormat.parse(endDate) val getDiff = date2.getTime() - date1.getTime() getDaysDiff = getDiff / (24 * 60 * 60 * 1000) println("Differance between date " + startDate + " and " + endDate + " is " + getDaysDiff + " days.") } catch (e:Exception) { e.printStackTrace() } return getDaysDiff } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { if (inflater != null) { inflater.inflate(R.menu.option_menu, menu) } super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId when (id) { R.id.removeall -> { deleteAllFavPlace() return true } } return false } companion object { fun newInstance(): FavoritePlaceFragment = FavoritePlaceFragment() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } private fun openDetailPlace(it: PlaceDbO) { val intent = Intent(context, DetailMyPlace::class.java) intent.putExtra("MyPlace",it) startActivity(intent) } //Click popup menu of any img private fun showPopup(context: Context, textView: TextView, position: Int) { var popup: PopupMenu? = null popup = PopupMenu(context, textView) //Add only option (remove) of per img popup.getMenu().add(0, position, 0, REMOVE_PLACE); popup.setOnMenuItemClickListener({ item -> //add_tempfavplace(adapter.getRef(position).key!!) deleteFavouritePlace(adapter.getRef(position).key!!) //get position id of rv_my_places true }) popup.show() } fun getCurrentDateTime(): Date { return Calendar.getInstance().time } //Carry on with AUTOCOMPLETE override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { val place = PlaceAutocomplete.getPlace(this.context, data) val geocoder = Geocoder(context!!, Locale.getDefault()) try { val addresses = geocoder.getFromLocation(place.latLng.latitude, place.latLng.longitude, 1) if (addresses != null) { val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } placeDb.address = addresses.get(0).getAddressLine(0) if(addresses.get(0).adminArea != null){ cityname_temp = addresses.get(0).adminArea } else { cityname_temp = "" } Log.e("start location2: ",cityname_temp) } else { Log.d("a","No Address returned! : ") } } catch (e: IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a","Canont get Address!") } placeDb.placeId = place.id placeDb.name = place.name.toString() getPhoto(place.id) //tempplace latitude_temp = place.latLng.latitude longitude_temp = place.latLng.longitude placeid_temp = place.id uploadTempplace() //statistics uploadCitySatistics() //history object historyDb.address = place.address.toString() historyDb.name = place.name.toString() //historyDb.placeTypes = place.placeTypes.toString() historyDb.historyId = place.id val date = getCurrentDateTime() //val c = GregorianCalendar(1995, 12, 23) val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) historyDb.date = currenttime uploadDatabase2() //add to firebase } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) { val status = PlaceAutocomplete.getStatus(this.context, data) Log.e(TAG, status.statusMessage) } else if (resultCode == Activity.RESULT_CANCELED) { } } } //Use PLACE PHOTOS of GG MAP API (AS`) // Request photos and metadata for the specified place. // mGeoDataClient - is to get detail of that place and then to move the marker (đánh dấu) // of the map to its co-ordinates (các tọa độ). private fun getPhoto(placeId: String) { //val placeId = "ChIJa147K9HX3IAR-lwiGIQv9i4" val mGeoDataClient = Places.getGeoDataClient(this.context!!) val photoMetadataResponse = mGeoDataClient.getPlacePhotos(placeId) photoMetadataResponse.addOnCompleteListener(OnCompleteListener<PlacePhotoMetadataResponse>{ task -> // Get the list of photos. val photos = task.result // Get the PlacePhotoMetadataBuffer (metadata for all of the photos). val photoMetadataBuffer = photos.photoMetadata // Get the first photo in the list. val photoMetadata = photoMetadataBuffer.get(0) // Get a full-size bitmap for the photo. val photoResponse = mGeoDataClient.getPhoto(photoMetadata) //Listener Event compeleted itselt, update to firebase's storage photoResponse.addOnCompleteListener(OnCompleteListener<PlacePhotoResponse> { task -> val photo = task.result val bitmap = photo.bitmap upLoadBitmapToStorage(bitmap) }) }) } //Add that place's photos to storage & that place to firebase private fun upLoadBitmapToStorage(bitmap: Bitmap) { val storage = FirebaseStorage.getInstance() val storageReference = storage.getReference("images") val imageName = UUID.randomUUID().toString() val imageFolder = storageReference.child(imageName) val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos) val data = baos.toByteArray() val uploadTask = imageFolder.putBytes(data) //after add photos to storage, update that place's uri to placeDb -> add to firebase by uploadDatabase() uploadTask.addOnFailureListener(OnFailureListener { // Handle unsuccessful uploads }).addOnSuccessListener(OnSuccessListener<Any> { taskSnapshot -> // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL. imageFolder.downloadUrl.addOnSuccessListener { Log.e(TAG, "Image : " + it.toString()) placeDb.uri = it.toString() uploadDatabase() } }) } private fun deleteAllFavPlace() { favourite_list.child(myuser!!.uid).removeValue() adapter.notifyDataSetChanged() } private fun deleteFavouritePlace(key: String) { favourite_list.child(myuser!!.uid).child(key).removeValue() adapter.notifyDataSetChanged() } private fun uploadDatabase() { favourite_list.child(myuser!!.uid).push().setValue(placeDb) } private fun uploadDatabase2() { history_list.child(myuser!!.uid).push().setValue(historyDb) } }<file_sep>package com.horus.travelweather.activity import android.app.Activity import android.app.AlertDialog import android.content.Intent import android.location.Geocoder import android.os.AsyncTask import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.Log import android.view.MenuItem import android.widget.Toast import com.firebase.ui.database.FirebaseRecyclerAdapter import com.google.android.gms.location.places.AutocompleteFilter import com.google.android.gms.location.places.ui.PlaceAutocomplete import com.google.android.gms.maps.model.LatLng import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.* import com.horus.travelweather.BottomNavigation import com.horus.travelweather.R import com.horus.travelweather.adapter.HistoryAdapter import com.horus.travelweather.adapter.LocationAdapter import com.horus.travelweather.database.PlaceEntity import com.horus.travelweather.database.TravelWeatherDB import com.horus.travelweather.model.CitySatisticsDbO import com.horus.travelweather.model.HistoryDbO import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_add_location.* import java.io.IOException import java.util.* class AddLocationActivity : AppCompatActivity() { private val TAG = AddLocationActivity::class.java.simpleName var PLACE_AUTOCOMPLETE_REQUEST_CODE = 1 private val compositeDisposable = CompositeDisposable() private lateinit var adapter : LocationAdapter lateinit var database: FirebaseDatabase lateinit var place_list: DatabaseReference lateinit var mAuth: FirebaseAuth private val historyDb = HistoryDbO() lateinit var history_list: DatabaseReference lateinit var adapter2: FirebaseRecyclerAdapter<HistoryDbO, HistoryAdapter.HistoryViewHolder> var myuser: FirebaseUser? = null lateinit var city_statistics: DatabaseReference //for statistics override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_location) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) val actionBar1 = supportActionBar if (actionBar1 != null) { //actionBar1.setDisplayHomeAsUpEnabled(true) actionBar1.title = "Danh Sách Thời Tiết" } loadPlaces() database = FirebaseDatabase.getInstance() mAuth = FirebaseAuth.getInstance() place_list = database.getReference("places").child(mAuth.currentUser!!.uid) myuser = mAuth.currentUser history_list = database.getReference("history") city_statistics = database.getReference("city_statistics") btn_add_location.text = "Danh Sách Thời Tiết" btn_add_location.setOnClickListener { //Filter results by place type (by address: get full address, by establisment: get business address) val typeFilter = AutocompleteFilter.Builder() .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS) .setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES) .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ESTABLISHMENT) .build() //Use an intent to launch the autocomplete activity (fullscreen mode) //https://developers.google.com/places/android-sdk/autocomplete val intent = PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN) .setFilter(typeFilter) .build(this) startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE) } } override fun onBackPressed() { super.onBackPressed() val intent = Intent(this, BottomNavigation::class.java) //this activity will be this fragment's father intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) } var numofplace = 0 //Load user's available places in database room -> recycleviewer rv_location private fun loadPlaces() { val getAllPlace = TravelWeatherDB.getInstance(this).placeDataDao() compositeDisposable.add(getAllPlace.getAll() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ implementLoad(it) numofplace=it.size Log.e(TAG,"sizeeee : "+ numofplace) }, { Log.e(TAG,""+ it.message) })) } // As LocationAdapter, input: list & id (by one click), if we click btn_delete_location on recycleviewer // (it was set a onclicklistener) of any place, it removed by call implementLoad(). private fun implementLoad(list : List<PlaceEntity>) { adapter = LocationAdapter(list,{ id -> val alertDialogBuilder = AlertDialog.Builder(this) alertDialogBuilder.setTitle("Xóa Địa Điểm Thời Tiết") alertDialogBuilder .setMessage("Bạn có thật sự muốn xóa địa điểm thời tiết này?") .setCancelable(false) .setPositiveButton("Yes") { dialog, id2 -> deletePLace().execute(id) place_list.child(id).removeValue() adapter.notifyDataSetChanged() } .setNegativeButton("No") { dialog, id2 -> dialog.cancel() } val alertDialog = alertDialogBuilder.create() alertDialog.show() }) if(adapter.itemCount != 0){ btn_add_location.text = "Thêm địa điểm thời tiết" } else btn_add_location.text = "Danh Sách Thời Tiết" val layoutManager : RecyclerView.LayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) rv_location.adapter = adapter rv_location.layoutManager = layoutManager } fun getCurrentDateTime(): Date { return Calendar.getInstance().time } //Use an intent to launch the autocomplete activity override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { super.onActivityResult(requestCode, resultCode, data) //autocompleteFragment.onActivityResult(requestCode, resultCode, data); if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { val place = PlaceAutocomplete.getPlace(this, data) Log.e(TAG, "Place ID:" + place.id) val placeDB = PlaceEntity() placeDB.latitude = place.latLng.latitude placeDB.longitude = place.latLng.longitude placeDB.name = getCityName_byLatlong(place.latLng) cityname_temp = placeDB.name //placeDB.name = place.locale.toString() placeDB.id = place.id if(numofplace < 4){ insertPLace().execute(placeDB) place_list.child(place.id).setValue(placeDB) } else { val alertDialogBuilder = AlertDialog.Builder(this) alertDialogBuilder.setTitle("Thông Báo") alertDialogBuilder .setMessage("Bạn chỉ được thêm tối đa 4 địa điểm thời tiết hay ghé thăm để theo dõi."+ " Để thêm địa điểm mới, vui lòng xóa địa điểm bạn không còn quan tâm!") .setCancelable(false) .setPositiveButton("OK") { dialog, id -> dialog.cancel() } val alertDialog = alertDialogBuilder.create() alertDialog.show() } uploadCitySatistics() //history object historyDb.address = place.address.toString() historyDb.name = place.name.toString() //historyDb.placeTypes = place.placeTypes.toString() historyDb.historyId = place.id val date = getCurrentDateTime() //val c = GregorianCalendar(1995, 12, 23) val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) historyDb.date = currenttime uploadDatabase() //add to firebase } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) { val status = PlaceAutocomplete.getStatus(this, data) Log.e(TAG, ""+status) } else if (resultCode == Activity.RESULT_CANCELED) { } } } var cityname_temp = "" var citysatistics_flag = true private fun uploadCitySatistics() { city_statistics.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Log.e(TAG, "Error : " + p0.message) } var numofsearch_others = 0 override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()) { // code if data exists // if current place like before place for (dsp in dataSnapshot.children) { //add result into array list val item: CitySatisticsDbO? = dsp.getValue(CitySatisticsDbO::class.java) if (item != null) { if(item.name == "Others") numofsearch_others = item.numofsearch if ((cityname_temp == item.name || cityname_temp == "Thành phố " + item.name || cityname_temp == "Thủ Đô " + item.name || cityname_temp == "Tỉnh " + item.name)) { Log.e("lamquanglich : ",dsp.key) city_statistics.child(dsp.key!!).setValue(CitySatisticsDbO(item.name,item.numofsearch+1)) citysatistics_flag = false } } } } else { // code if data does not exists if(cityname_temp != ""){ if((cityname_temp.toLowerCase() == "hồ chí minh" || cityname_temp == "thành phố hồ chí minh") || (cityname_temp.toLowerCase() == "hà nội" || cityname_temp == "thủ đô hà nội") || (cityname_temp.toLowerCase() == "đà nẵng" || cityname_temp == "thành phố đà nẵng") || (cityname_temp.toLowerCase() == "cần thơ" || cityname_temp == "thành phố cần thơ") ){ city_statistics.push().setValue(CitySatisticsDbO(cityname_temp,1)) } else { city_statistics.child("-Li261TH2CuzJV9lyWvM").setValue(CitySatisticsDbO("Others",numofsearch_others+1)) } citysatistics_flag = false } } if (citysatistics_flag && cityname_temp != "") { if((cityname_temp.toLowerCase() == "hồ chí minh" || cityname_temp == "thành phố hồ chí minh") || (cityname_temp.toLowerCase() == "hà nội" || cityname_temp == "thủ đô hà nội") || (cityname_temp.toLowerCase() == "đà nẵng" || cityname_temp == "thành phố đà nẵng") || (cityname_temp.toLowerCase() == "cần thơ" || cityname_temp == "thành phố cần thơ") ){ city_statistics.push().setValue(CitySatisticsDbO(cityname_temp,1)) } else { city_statistics.child("-Li261TH2CuzJV9lyWvM").setValue(CitySatisticsDbO("Others",numofsearch_others+1)) } } } }) } fun getCityName_byLatlong(latlong: LatLng): String { //get city name val geocoder = Geocoder(this, Locale.getDefault()) val latitude_temp = latlong.latitude val longitude_temp = latlong.longitude val cityname_temp2 = "" try { val addresses = geocoder.getFromLocation(latitude_temp, longitude_temp, 1) if (addresses != null) { Log.e("start location : ", addresses.toString()) val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") //val strReturnedAddress = StringBuilder() for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } //Log.e("start location : ", addresses.get(0).subAdminArea) return addresses.get(0).adminArea } else { Log.d("a","No Address returned! : ") } } catch (e: IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a","Canont get Address!") } //end get city name return cityname_temp2 } //Press home button //Call this when your activity is done and should be closed. The //* ActivityResult is propagated back to whoever launched you via (thông qua) //* onActivityResult(). override fun onOptionsItemSelected(item: MenuItem?): Boolean { val id = item?.itemId if(id == android.R.id.home) { val intent = Intent() setResult(Activity.RESULT_OK, intent) finish() } return super.onOptionsItemSelected(item) } inner class insertPLace(): AsyncTask<PlaceEntity, Void, Void>() { override fun doInBackground(vararg params: PlaceEntity): Void? { TravelWeatherDB.getInstance(this@AddLocationActivity).placeDataDao().insert(params[0]) return null } } inner class deletePLace(): AsyncTask<String, Void, Void>() { override fun doInBackground(vararg params: String?): Void? { TravelWeatherDB.getInstance(this@AddLocationActivity).placeDataDao().deleteByPlaceId(params[0]) return null } } private fun uploadDatabase() { history_list.child(myuser!!.uid).push().setValue(historyDb) } }<file_sep>package com.horus.travelweather.activity import android.content.Intent import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import android.text.Html import android.view.View import com.horus.travelweather.R import kotlinx.android.synthetic.main.activity_splash.* class SplashActivity : AppCompatActivity() { private var wait: Long = 1000 private var mHandler: Handler? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) txt_title_travel_weather.text = Html.fromHtml(resources.getString(R.string.splash_travel_weather)) loadLoginView() } private fun loadLoginView() { mHandler = Handler() mHandler!!.postDelayed({ enterLoginActivity() }, wait) } private fun enterLoginActivity() { var intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } // set up fullscreen override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) if (hasFocus) hideSystemUI() } // hide all bar private fun hideSystemUI() { // Enables regular immersive mode. // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE. // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) } }<file_sep>package com.horus.travelweather.adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.firebase.ui.database.FirebaseRecyclerAdapter import com.firebase.ui.database.FirebaseRecyclerOptions import com.horus.travelweather.R import com.horus.travelweather.model.HistoryDbO import kotlinx.android.synthetic.main.eachhistory_layout.view.* import java.util.* /** * Created by onlyo on 12/26/2018. * */ class HistoryAdapter(options: FirebaseRecyclerOptions<HistoryDbO>, private var temphistoryList: ArrayList<HistoryDbO>, private var runagain: Int, private val onItemClickListener: (Context, TextView, Int) -> Unit) : FirebaseRecyclerAdapter<HistoryDbO, HistoryAdapter.HistoryViewHolder>(options) { /*val historyList = ArrayList<HistoryDbO>() var temp_date = "" //to check next historyid if the same date var count = 0 var firstrunning = false var length_history = 0 var length_history2 = 0*/ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.eachhistory_layout, parent, false) return HistoryViewHolder(view) } override fun onBindViewHolder(holder: HistoryViewHolder, position: Int, model: HistoryDbO) { //holder.tempbind(temphistoryList[position]) /* if(temphistoryList.size < position){ Log.e("Size4 : ", "sad") temphistoryList.clear() holder.tempbind(model) holder.bind(temphistoryList[temphistoryList.size - 1]) } else holder.bind(temphistoryList[position])*/ length_history = temphistoryList.size //Log.e("Size4 : ", temphistoryList.size.toString()) //Log.e("Size5 : ", position.toString()) if (temphistoryList.size == position) { //Log.e("Size61 : ", "=========================================="+count) count = 0 temp_date = "" length_history2 = 0 //Log.e("Size62 : ", "=========================================="+count) } holder.tempbind(model) //if(temphistoryList.size == length_history){ holder.bind(model) //} } /*override fun getItemCount(): Int { return Int.size() }*/ fun getCurrentDateTime(): Date { return Calendar.getInstance().time } val historyList = ArrayList<HistoryDbO>() var temp_date = "" //to check next historyid if the same date var count = 0 var firstrunning = false var length_history = 0 var length_history2 = 0 var location = -1 inner class HistoryViewHolder(view: View) : RecyclerView.ViewHolder(view) { fun tempbind(history: HistoryDbO) { //length_history++ //Log.e("length:", length_history.toString()) } fun bind(history: HistoryDbO) { length_history2++ Log.e("historyid:", history.name) //Log.e("historyid2:",length_history.toString()) itemView.tv_name.text = history.name itemView.tv_address.text = history.address itemView.txt_history_minute.text = history.minute val date = getCurrentDateTime() //val c = GregorianCalendar(1995, 12, 23) val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) Log.e("historyid3:", history.date) // -> s == "16/03/2019" if (location - 1 == length_history - length_history2 + 1) { Log.e("location:", "voooo" + length_history2) if (history.date == currenttime) itemView.txt_history_date.text = "Hôm nay" else itemView.txt_history_date.text = history.date itemView.txt_history_date.visibility = View.VISIBLE location = -1 } else if (history.date == currenttime) { if (count == 0) { itemView.txt_history_date.visibility = View.VISIBLE itemView.txt_history_date.text = "Hôm nay" } /*else if(count != 0){ itemView.txt_history_date.text = history.date*/ else { itemView.txt_history_date.text = "Hôm nay" itemView.txt_history_date.visibility = View.GONE } count++ } else { if (count == 0) { itemView.txt_history_date.visibility = View.VISIBLE itemView.txt_history_date.text = history.date count++ } else if (temp_date == history.date) { itemView.txt_history_date.text = history.date itemView.txt_history_date.visibility = View.GONE } else { itemView.txt_history_date.visibility = View.VISIBLE itemView.txt_history_date.text = history.date } } temp_date = history.date /*if (history.placeTypes == "airport") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_airport) } else if (history.placeTypes == "spa") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_spa) } else if (history.placeTypes == "atm") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_atm) } else if (history.placeTypes == "hospital") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_hospital) } else if (history.placeTypes == "cafe") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_cafe) } else if (history.placeTypes == "bar") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_bar) } else if (history.placeTypes == "car_wash") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_carwash) } else if (history.placeTypes == "car_repair") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_carwash) } else if (history.placeTypes == "car_rental") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_carwash) } else if (history.placeTypes == "car_dealer") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_carwash) } else if (history.placeTypes == "convenience_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "clothing_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "restaurant") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_restaurant) } else if (history.placeTypes == "florist") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_florist) } else if (history.placeTypes == "store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_grocery_store) } else if (history.placeTypes == "department_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "home_goods_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "laundry") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_laundry_service) } else if (history.placeTypes == "library") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_library) } else if (history.placeTypes == "shopping_mall") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_mall) } else if (history.placeTypes == "movie_rental") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_movies) } else if (history.placeTypes == "movie_theater") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_movies) } else if (history.placeTypes == "parking") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_packing) } else if (history.placeTypes == "pharmacy") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_pharmacy) } else if (history.placeTypes == "post_office") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_post_office) } else if (history.placeTypes == "moving_company") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_shipping) } else if (history.placeTypes == "taxi_stand") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_taxi) } else if (history.placeTypes == "bicycle_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_bicycle_store) } else if (history.placeTypes == "casino") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_casino) } else if (history.placeTypes == "lawyer") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_lawyer) } else if (history.placeTypes == "transit_station") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_transit) } else if (history.placeTypes == "train_station") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_spa) } else if (history.placeTypes == "bus_station") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_bus) } else if (history.placeTypes == "fire_station") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_transit) } else if (history.placeTypes == "gas_station") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_gassation) } else if (history.placeTypes == "subway_station") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_transit) } else if (history.placeTypes == "bakery") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_bakery) } else if (history.placeTypes == "school") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_school) } else if (history.placeTypes == "real_estate_agency") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_city) } else if (history.placeTypes == "museum") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_city) } else if (history.placeTypes == "local_government_office") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_account_balance) } else if (history.placeTypes == "night_club") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_bar) } else if (history.placeTypes == "insurance_agency") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_city) } else if (history.placeTypes == "hindu_temple") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_city) } else if (history.placeTypes == "embassy") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_account_balance) } else if (history.placeTypes == "courthouse") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_account_balance) } else if (history.placeTypes == "city_hall") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_account_balance) } else if (history.placeTypes == "bank") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_account_balance) } else if (history.placeTypes == "accounting") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_account_balance) } else if (history.placeTypes == "travel_agency") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_city) } else if (history.placeTypes == "supermarket") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "zoo") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_spa) } else if (history.placeTypes == "veterinary_care") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "synagogue") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_city) } else if (history.placeTypes == "storage") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "stadium") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_packing) } else if (history.placeTypes == "pack") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_packing) } else if (history.placeTypes == "shoe_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "rv_park") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_packing) } else if (history.placeTypes == "pet_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "mosque") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_city) } else if (history.placeTypes == "meal_takeaway") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_restaurant) } else if (history.placeTypes == "meal_delivery") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_restaurant) } else if (history.placeTypes == "lodging") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_city) } else if (history.placeTypes == "liquor_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "jewelry_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "hardware_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "hair_care") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_spa) } else if (history.placeTypes == "gym") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "furniture_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "funeral_home") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "electronics_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "church") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_city) } else if (history.placeTypes == "cemetery") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_florist) } else if (history.placeTypes == "campground") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_packing) } else if (history.placeTypes == "bowling_alley") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "book_store") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "beauty_salon") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_spa) } else if (history.placeTypes == "art_gallery") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_convenience_store) } else if (history.placeTypes == "amusement_park") { itemView.imgv_placetype.setImageResource(R.drawable.ic24_packing) } else {*/ itemView.imgv_placetype.setImageResource(R.drawable.ic24_place) //} itemView.tv_name.setOnClickListener { /*view: View, motionEvent: MotionEvent ->*/ //when (motionEvent.action and MotionEvent.ACTION_MASK) { // MotionEvent.ACTION_HOVER_EXIT -> { onItemClickListener(itemView.context, itemView.tv_name, adapterPosition) if (itemView.txt_history_date.visibility == View.VISIBLE) location = adapterPosition Log.e("location:", location.toString()) // } //} // true } } } }<file_sep>package com.horus.travelweather.common import com.horus.travelweather.model.UserDbO class TWConstant { companion object { var currentUser : UserDbO = UserDbO("","","","") const val BASE_API_LAYER = "http://api.openweathermap.org/data/2.5/" const val ACCESS_API_KEY = "ba29c1fc66a2ee3e436c1636937fafad" const val BASE_URL_UPLOAD = "http://openweathermap.org/img/w/" const val REMOVE_PLACE = "Xóa" const val YOURLOCATION1 = "Vị trí hiện tại tại điểm xuất phát" const val YOURLOCATION2 = "Vị trí hiện tại tại điểm đến" const val BASE_URI_PHOTO = "https://i.ibb.co/V9VLdKr/Rectangle-Copy-11-1.png" } }<file_sep>apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion 27 defaultConfig { applicationId "com.horus.travelweather" minSdkVersion 16 targetSdkVersion 27 multiDexEnabled true versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables { useSupportLibrary = true } vectorDrawables.useSupportLibrary = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } buildToolsVersion '28.0.2' compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } } kapt { //generateStubs = true arguments { arg('eventBusIndex', 'com.example.myapp.MyEventBusIndex') } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.1.2' implementation 'com.android.support:design:27.1.1' implementation 'com.android.support:support-v4:27.1.1' implementation 'com.google.android.gms:play-services-maps:15.0.1' implementation 'com.android.support:support-vector-drawable:27.1.1' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.google.firebase:firebase-core:16.0.1' implementation 'com.google.firebase:firebase-database:16.0.1' implementation 'com.firebaseui:firebase-ui-database:3.2.2' implementation 'com.google.firebase:firebase-auth:16.0.2' implementation 'com.google.firebase:firebase-storage:16.0.1' implementation 'info.hoang8f:fbutton:1.0.5' implementation 'com.android.support:cardview-v7:27.1.1' implementation 'com.rengwuxian.materialedittext:library:2.1.4' implementation 'com.squareup.picasso:picasso:2.5.2' implementation 'jp.wasabeef:picasso-transformations:2.2.1' implementation 'com.android.support:recyclerview-v7:27.1.1' implementation 'com.patrickpissurno:ripple-effect:1.3.1' implementation 'de.hdodenhof:circleimageview:2.2.0' // Recyclerview /* implementation 'com.android.support:recyclerview-v7:27.1.0' */ //Sign In with google implementation 'com.google.android.gms:play-services-auth:15.0.1' // RxJava implementation 'io.reactivex.rxjava2:rxjava:2.1.16' implementation 'io.reactivex.rxjava2:rxandroid:2.0.1' // Retrofit implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-gson:2.1.0' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1' implementation 'com.github.tbruyelle:rxpermissions:0.10.2' implementation 'com.github.zellius:rxlocationmanager-rxjava2:1.0.0' implementation 'com.patloew.rxlocation:rxlocation:1.0.5' implementation 'android.arch.lifecycle:extensions:1.1.1' kapt "android.arch.lifecycle:compiler:1.1.1" implementation 'android.arch.persistence.room:runtime:1.1.1' kapt "android.arch.persistence.room:compiler:1.1.1" implementation 'android.arch.persistence.room:rxjava2:1.1.1' implementation 'io.reactivex:rxandroid:1.2.1' //Google place api implementation 'com.google.android.gms:play-services-places:15.0.1' implementation 'com.google.android.gms:play-services-location:15.0.1' implementation 'com.google.maps:google-maps-services:0.1.20' implementation 'com.google.maps.android:android-maps-utils:0.5' testImplementation 'junit:junit:4.12' implementation 'com.akexorcist:googledirectionlibrary:1.0.4' implementation 'com.github.JakeWharton:ViewPagerIndicator:2.4.1' implementation 'com.romandanylyk:pageindicatorview:1.0.2' implementation "org.slf4j:slf4j-api:1.7.25" implementation "org.slf4j:slf4j-simple:1.7.25" implementation 'com.squareup.retrofit:retrofit:2.0.0-beta2' implementation 'com.squareup.retrofit:converter-gson:2.0.0-beta2' //animation for recycleview rv_directionsStep implementation 'jp.wasabeef:recyclerview-animators:2.2.3' //implementation 'com.google.android.gms:play-services-maps:11.8.0' //implementation 'com.google.android.gms:play-services-location:11.8.0' implementation 'uk.co.markormesher:android-fab:2.4.1' } apply plugin: 'com.google.gms.google-services' <file_sep>package com.horus.travelweather.model import com.google.gson.annotations.SerializedName data class DailyWeatherDetailResponse(@SerializedName("cnt") val sizeList : Int, val list : List<WeatherDetailsResponse>)<file_sep>package com.horus.travelweather.activity import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.view.ViewCompat.setNestedScrollingEnabled import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.PopupMenu import android.support.v7.widget.RecyclerView import android.util.Log import android.view.* import android.widget.TextView import com.firebase.ui.database.FirebaseRecyclerAdapter import com.firebase.ui.database.FirebaseRecyclerOptions import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.* import com.horus.travelweather.R import com.horus.travelweather.R.id.navigation_direction import com.horus.travelweather.adapter.HistoryAdapter import com.horus.travelweather.common.TWConstant import com.horus.travelweather.database.PlaceEntity import com.horus.travelweather.model.HistoryDbO import kotlinx.android.synthetic.main.eachhistory_layout.view.* import kotlinx.android.synthetic.main.fragment_history.view.* import java.util.* /** * Created by onlyo on 12/26/2018. */ class HistoryFragment: Fragment() { private val TAG = HistoryFragment::class.java.simpleName private val historyDb = HistoryDbO() lateinit var database: FirebaseDatabase lateinit var history_list: DatabaseReference lateinit var history_list_temp: DatabaseReference lateinit var mAuth: FirebaseAuth lateinit var adapter: FirebaseRecyclerAdapter<HistoryDbO, HistoryAdapter.HistoryViewHolder> var myuser: FirebaseUser? = null var length: Int = 0 var runagain: Int = 0 lateinit var placeList: ArrayList<HistoryDbO> //showp per 18 items lateinit var placeList_All: ArrayList<HistoryDbO> override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_history, container, false) setHasOptionsMenu(true) mAuth = FirebaseAuth.getInstance() myuser = mAuth.currentUser database = FirebaseDatabase.getInstance() history_list = database.getReference("history") history_list_temp = database.getReference("history").child(mAuth.currentUser!!.uid) //length = 0 placeList = ArrayList<HistoryDbO>() val options = FirebaseRecyclerOptions.Builder<HistoryDbO>() .setQuery(history_list_temp, HistoryDbO::class.java) .setLifecycleOwner(this) .build() history_list_temp.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Log.e(TAG,"Error : "+p0.message) } override fun onDataChange(dataSnapshot : DataSnapshot) { // Result will be holded Here for (dsp in dataSnapshot.children) { //add result into array list val item : HistoryDbO? = dsp.getValue(HistoryDbO::class.java) if (item != null) { placeList.add(item) length++ } } //Log.e(TAG,"Size : "+placeList.size) length = placeList.size //Collections.reverse(placeList) for (i in placeList) { //Log.e(TAG,"Size2 : "+i.name) } //insertAllPlace().execute(placeList) } }) placeList_All = ArrayList<HistoryDbO>(placeList) if(placeList_All.size > 17) { placeList = ArrayList<HistoryDbO>(placeList_All.take(18)) } adapter = HistoryAdapter(options, placeList, runagain, { context,textview, i -> showPopup(context,textview, i) }) val linearLayoutManager = LinearLayoutManager(this.activity, LinearLayoutManager.VERTICAL, false) linearLayoutManager.reverseLayout = true linearLayoutManager.stackFromEnd = true view.rv_history.layoutManager = linearLayoutManager view.rv_history.adapter = adapter view.rv_history.isNestedScrollingEnabled = false view.rv_history.addOnScrollListener(object: RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx:Int, dy:Int) { super.onScrolled(recyclerView, dx, dy) if (!recyclerView.canScrollVertically(1)) onScrolledToBottom() } }) return view } //show per 30 items to avoid big data private fun onScrolledToBottom() { if (placeList.size < placeList_All.size) { val x: Int val y: Int if (placeList_All.size - placeList.size >= 18) { x = placeList.size y = x + 18 } else { x = placeList.size y = x + placeList_All.size - placeList.size } for (i in x until y) { placeList.add(placeList_All.get(i)) } adapter.notifyDataSetChanged() } } override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) { if (inflater != null) { inflater.inflate(R.menu.option_menu, menu) } super.onCreateOptionsMenu(menu, inflater) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId when (id) { R.id.removeall -> { deleteAllHistory() return true } } return false } companion object { fun newInstance(): HistoryFragment = HistoryFragment() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } //Click popup menu of any img private fun showPopup(context: Context, textView: TextView, position: Int) { var popup: PopupMenu? = null popup = PopupMenu(context, textView) //Add only option (remove) of per img popup.menu.add(0, position, 0, TWConstant.REMOVE_PLACE) popup.show() popup.setOnMenuItemClickListener({ Log.e(TAG,"key : "+(length - 1 - position)) deleteOneHistory(adapter.getRef(position).key!!,position) //get position id of rv_my_places runagain++ true }) /*if (inflater != null) { inflater.inflate(R.menu.option_menu, menu) val item1 = menu!!.findItem(R.id.show_historyinfo) val item2 = menu!!.findItem(R.id.removeall) item1.actionView.setOnTouchListener{ view: View, motionEvent: MotionEvent -> when (motionEvent.action and MotionEvent.ACTION_MASK) { MotionEvent.ACTION_HOVER_ENTER -> { item2.setOnMenuItemClickListener({ deleteAllHistory() //get position id of rv_my_places true }) } } true } }*/ } private fun deleteAllHistory() { history_list_temp.removeValue() adapter.notifyDataSetChanged() } private fun deleteOneHistory(key: String, tempkey: Int) { history_list_temp.child(key).removeValue() runagain++ placeList.removeAt(tempkey) //adapter.notifyItemRemoved(tempkey) adapter.notifyDataSetChanged() } private fun uploadDatabase() { history_list_temp.push().setValue(historyDb) } }<file_sep>package com.horus.travelweather.model data class TransitDbO(val departure_stop: String, val departure_time: String, val arrival_stop: String, val arrival_time: String, val line_busname: String, val headsign: String, val num_stops: String)<file_sep>package com.horus.travelweather.model import java.io.Serializable data class HistoryDbO(var historyId : String="" , var name : String= "" , var address : String="" , var date: String="" , var minute: String="") : Serializable<file_sep>package com.horus.travelweather.adapter import android.content.Context import android.support.v7.widget.PopupMenu import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.firebase.ui.database.FirebaseRecyclerAdapter import com.firebase.ui.database.FirebaseRecyclerOptions import com.horus.travelweather.R import com.horus.travelweather.model.PlaceDbO import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.locaiton_item.view.* import kotlinx.android.synthetic.main.my_places_layout.view.* import com.horus.travelweather.utils.CircleTransform import jp.wasabeef.picasso.transformations.RoundedCornersTransformation class FavouritePlaceAdapter( options: FirebaseRecyclerOptions<PlaceDbO>,private val onItemPopupClick : (Context,TextView,Int)-> Unit,private val onItemClick : (PlaceDbO)-> Unit) : FirebaseRecyclerAdapter<PlaceDbO, FavouritePlaceAdapter.PlaceViewHolder>(options) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaceViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.my_places_layout, parent, false) return PlaceViewHolder(view) } override fun onBindViewHolder(holder: PlaceViewHolder, position: Int, model: PlaceDbO) { holder.bind(model) } inner class PlaceViewHolder(view: View) : RecyclerView.ViewHolder(view){ fun bind(place : PlaceDbO) { Picasso.with(itemView.context).load(place.uri).transform(CircleTransform(10,0)).fit().into(itemView.img_my_place) itemView.my_place_name.text = place.name itemView.txt_option_menu.setOnClickListener { onItemPopupClick(itemView.context,itemView.txt_option_menu,adapterPosition) } itemView.img_my_place.setOnClickListener { onItemClick(place) } } } }<file_sep>package com.horus.travelweather.model import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.PrimaryKey import java.io.Serializable import java.text.DateFormat import java.util.* data class CitySatisticsDbO (@ColumnInfo(name = "name") var name : String , @ColumnInfo(name = "numofsearch") var numofsearch : Int){ constructor():this("",0) }<file_sep>package com.horus.travelweather.model data class LocationDbO (val name : String)<file_sep>package com.horus.travelweather.fragment import android.annotation.SuppressLint import android.app.AlertDialog import android.app.ProgressDialog import android.content.DialogInterface import android.content.Intent import android.graphics.Color import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.horus.travelweather.R import com.horus.travelweather.common.TWConstant import com.horus.travelweather.repository.Repository import com.horus.travelweather.service.ApiService import com.horus.travelweather.utils.StringFormatter.convertTimestampToDayAndHourFormat import com.horus.travelweather.utils.StringFormatter.convertToValueWithUnit import com.horus.travelweather.utils.StringFormatter.unitDegreesCelsius import com.horus.travelweather.utils.StringFormatter.unitPercentage import com.horus.travelweather.utils.StringFormatter.unitsMetresPerSecond import com.squareup.picasso.Picasso import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_weather_details.* import android.location.Geocoder import android.location.Location import java.util.* import android.location.LocationManager import android.opengl.Visibility import android.os.AsyncTask import android.os.Build import android.preference.PreferenceManager import android.support.annotation.RequiresApi import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.text.format.DateFormat import android.widget.Toast import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.places.PlaceBuffer import com.google.android.gms.location.places.Places import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.PolylineOptions import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.* import com.horus.travelweather.BottomNavigation import com.horus.travelweather.R.id.* import com.horus.travelweather.activity.DataParser import com.horus.travelweather.adapter.DailyWeatherAdapter import com.horus.travelweather.database.PlaceEntity import com.horus.travelweather.model.* import com.horus.travelweather.utils.StringFormatter.getCurrentTime import com.patloew.rxlocation.RxLocation import ru.solodovnikov.rx2locationmanager.LocationTime import ru.solodovnikov.rx2locationmanager.RxLocationManager import java.util.concurrent.TimeUnit import ru.solodovnikov.rx2locationmanager.LocationRequestBuilder import io.reactivex.internal.operators.single.SingleInternalHelper.toObservable import kotlinx.android.synthetic.main.activity_bottom_navigation.* import kotlinx.android.synthetic.main.activity_directions.view.* import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.io.BufferedReader import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import java.text.SimpleDateFormat class WeatherDetailFragment : Fragment() { private val TAG = WeatherDetailFragment::class.java.simpleName lateinit var database: FirebaseDatabase lateinit var place_list: DatabaseReference lateinit var tempplace_list: DatabaseReference lateinit var mAuth: FirebaseAuth private val tempplaceDb = TempPlaceDbO() @SuppressLint("CheckResult") private fun requestWeatherDetails(lat: Double, long: Double) { Repository.createService(ApiService::class.java).getWeatherDetailsCoordinates(lat, long, TWConstant.ACCESS_API_KEY) .observeOn(AndroidSchedulers.mainThread()) // Chi dinh du lieu chinh tren mainthread .subscribeOn(Schedulers.io())//chi dinh cho request lam viec tren I/O Thread(request to api , download a file,...) .subscribe( //cú pháp của rxjava trong kotlin { result -> cityname_temp = getCityName_byLatlong(LatLng(lat, long)) //request thành công processResponseData(result) }, { error -> //request thất bai handlerErrorWeatherDetails(error) } ) Repository.createService(ApiService::class.java).getDailyWeatherCoordinates(lat, long, TWConstant.ACCESS_API_KEY) .observeOn(AndroidSchedulers.mainThread()) // Chi dinh du lieu chinh tren mainthread .subscribeOn(Schedulers.io())//chi dinh cho request lam viec tren I/O Thread(request to api , download a file,...) .subscribe( //cú pháp của rxjava trong kotlin { result -> cityname_temp = getCityName_byLatlong(LatLng(lat, long)) //request thành công processResponseDataDaily(result) }, { error -> //request thất bai handlerErrorWeatherDetails(error) } ) } private fun handlerErrorWeatherDetails(error: Throwable?) { Log.e(TAG, "" + error.toString()) } private fun processResponseDataDaily(result: DailyWeatherDetailResponse?) { //Log.e(TAG, "111111111" + result!!.list[0].temperature.temp) val adapter = DailyWeatherAdapter(result!!.list) val layoutManager: RecyclerView.LayoutManager = LinearLayoutManager(this.context, LinearLayoutManager.HORIZONTAL, false) rv_hourly_weather_list.layoutManager = layoutManager rv_hourly_weather_list.adapter = adapter } private fun processResponseData(result: WeatherDetailsResponse) { Log.e(TAG, "" + result); txt_current_time.text = getCurrentTime() txt_date_time.text = convertTimestampToDayAndHourFormat(result.dateTime) if (cityname_temp != "") txt_city_name.text = cityname_temp else txt_city_name.text = result.nameCity //cityname_temp = result.nameCity //using to add to tempplace txt_temperature.text = convertToValueWithUnit(0, unitDegreesCelsius, convertKelvinToCelsius(result.temperature.temp)) Log.e("nhiet do", txt_temperature.text.toString()) txt_temp_max.text = convertToValueWithUnit(0, unitDegreesCelsius, convertKelvinToCelsius(result.temperature.temp_max)) txt_temp_min.text = convertToValueWithUnit(0, unitDegreesCelsius, convertKelvinToCelsius(result.temperature.temp_min)) txt_main_weather.text = result.weather[0].nameWeather txt_humidity.text = convertToValueWithUnit(0, unitPercentage, result.temperature.humidity) txt_wind.text = convertToValueWithUnit(0, unitsMetresPerSecond, result.wind.speed) txt_cloud_cover.text = result.clouds.all.toString() Picasso.with(this.context).load(TWConstant.BASE_URL_UPLOAD + result.weather[0].icon + ".png").into(img_weather_icon) } private fun convertKelvinToCelsius(temperatue: Double): Double { val temp = (temperatue - 273.15) return temp } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { requestLocation() val view = inflater.inflate(R.layout.fragment_weather_details, container, false) return view } private fun addTempplace() { } var cityname_temp = "" var placeid_temp = "" var latitude_temp = 0.0 var longitude_temp = 0.0 var numofvisit_temp = 0 var isacity_temp = false var newplace_flag = true var runonce_flag = true var curplace_like_beforeplace = false //Now Location @SuppressLint("CheckResult") private fun requestLocation() { //database = FirebaseDatabase.getInstance() //mAuth = FirebaseAuth.getInstance() //tempplace_list = database.getReference("tempplace").child(mAuth.currentUser!!.uid) //place_list = database.getReference("places").child(mAuth.currentUser!!.uid) val rxLocationManager = context?.let { RxLocationManager(it) } if (runonce_flag == true) { if (arguments!!.getInt("position") == 0) { if (rxLocationManager != null) { rxLocationManager.requestLocation(LocationManager.NETWORK_PROVIDER) .subscribe({ val geocode = Geocoder(context, Locale.getDefault()) val address = geocode.getFromLocation(it.latitude, it.longitude, 1) requestWeatherDetails(address[0].latitude, address[0].longitude) latitude_temp = it.latitude longitude_temp = it.longitude //get city name //val geocoder = Geocoder(context!!, Locale.getDefault()) try { //val addresses = geocode.getFromLocation(latitude_temp, longitude_temp, 1) if (address != null) { Log.e("start location : ", address.toString()) val returnedAddress = address.get(0) val strReturnedAddress = StringBuilder("Address:\n") //val strReturnedAddress = StringBuilder() for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } Log.e("start location : ", address.get(0).subAdminArea) cityname_temp = address.get(0).adminArea } else { Log.d("a", "No Address returned! : ") } } catch (e: IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a", "Canont get Address!") } //end get city name //get placeid val apikey = "<KEY>" val url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=$latitude_temp,$longitude_temp&language=vi&key=$apikey" val fetchUrl = FetchUrl() fetchUrl.execute(url) }, { Log.e(TAG, "Error" + it.message) }) } } else { val geocode = Geocoder(activity, Locale.getDefault()) val address = geocode.getFromLocation(arguments!!.getDouble("lat"), arguments!!.getDouble("lon"), 1) requestWeatherDetails(address.get(0).latitude, address.get(0).longitude) } runonce_flag = false } } private inner class FetchUrl() : AsyncTask<String, Void, String>() { override fun doInBackground(vararg url: String): String { Log.d("FetchUrl doInBackground", "vô nè") // For storing data from web service var data = "" try { // Fetching the data from web service data = downloadUrl(url[0]) Log.d("Background Task data", data) } catch (e: Exception) { Log.d("Background Task", e.toString()) } return data } override fun onPostExecute(result: String) { Log.d("onPostExecue resute", result) super.onPostExecute(result) val parserTask = ParserTask() // Invokes the thread for parsing the JSON data parserTask.execute(result) } } fun getPlaceId(jObject: JSONObject): String { val jResults: JSONArray var jPlaceId = "" try { jResults = jObject.getJSONArray("results") /** Traversing all routes */ //for (i in 0 until jResults.length()) { jPlaceId = ((jResults.get(0) as JSONObject).get("place_id")) as String placeid_temp = jPlaceId Log.e("Step duration: ", placeid_temp) return placeid_temp //} } catch (e: JSONException) { e.printStackTrace() } catch (e: Exception) { } return jPlaceId } private inner class ParserTask() : AsyncTask<String, Int, List<List<HashMap<String, String>>>>() { // Parsing the data in non-ui thread @RequiresApi(Build.VERSION_CODES.M) override fun doInBackground(vararg jsonData: String): List<List<HashMap<String, String>>> { val jObject: JSONObject? try { jObject = JSONObject(jsonData[0]) Log.d("ParserTask", jsonData[0]) val parser = DataParser() placeid_temp = getPlaceId(jObject) Log.e("Step duration: ", placeid_temp) Log.d("ParserTask", parser.toString()) // Starts parsing data val routes: List<List<HashMap<String, String>>> = parser.parse(jObject) //parse2: get duration of this all route //val duration: String = parser.parse2(jObject)!! //Log.d("ParaserTask", "Executing routes") //Log.d("ParserTask", routes.toString()) return routes } catch (e: Exception) { Log.d("ParserTask", e.toString()) e.printStackTrace() } val r: List<List<HashMap<String, String>>> = ArrayList<ArrayList<HashMap<String, String>>>() return r } // Executes in UI thread, after the parsing process override fun onPostExecute(result: List<List<HashMap<String, String>>>) { database = FirebaseDatabase.getInstance() mAuth = FirebaseAuth.getInstance() tempplace_list = database.getReference("tempplace").child(mAuth.currentUser!!.uid) place_list = database.getReference("places").child(mAuth.currentUser!!.uid) //val placeList = ArrayList<PlaceEntity>() val cityname_list = ArrayList<String>() var index_temp = 0 place_list.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { } override fun onDataChange(dataSnapshot: DataSnapshot) { // Result will be holded Here for (dsp in dataSnapshot.children) { //add result into array list val item: PlaceEntity? = dsp.getValue(PlaceEntity::class.java) if (item != null) { //placeList.add(item) cityname_list.add(getCityName_byLatlong(LatLng(item.latitude, item.longitude))) //cityname_list[index_temp++]=) Log.d("city name : ", cityname_list.get(index_temp)) // placeList.add(PlaceEntity(item.id,cityname_list.get(index_temp),item.latitude,item.longitude)) index_temp++ } } } }) tempplace_list.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Log.e(TAG, "Error : " + p0.message) } override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()) { // code if data exists for (dsp in dataSnapshot.children) { //add result into array list val item: TempPlaceDbO? = dsp.getValue(TempPlaceDbO::class.java) if (item != null) { //Log.e("Test AI : ",dsp.key) var now_cityname = "" if (dsp.key == mAuth.currentUser!!.uid && item.name == cityname_temp) { curplace_like_beforeplace = true now_cityname = item.name //Log.e("Test AI : ",placeid_temp + item.name + cityname_temp) //break } //Add new place if temp place (visit:1 or searchh: 5) val date = getCurrentDateTime() val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) if (cityname_list.contains(item.name) == true) { } else if (dsp.key != mAuth.currentUser!!.uid && (item.numofvisit >= 1 || item.numofsearch > 4) && item.numofask < 2 && currenttime != item.askdate && currentday_oldday_space(item.askdate) > 2) { val alertDialogBuilder = AlertDialog.Builder(context) alertDialogBuilder.setTitle("Thêm địa điểm thời tiết") alertDialogBuilder .setMessage("Bạn có muốn thêm " + item.name + " vào màn hình để tiện quan sát" + " thời tiết hay không?") .setCancelable(false) .setPositiveButton("Yes") { dialog, id -> // Add new place if temp place qualified //for(pl in placeList){ // if(pl.name == item.name){ val placeDB = PlaceEntity() placeDB.name = item.name.toString() placeDB.latitude = item.latitude placeDB.longitude = item.longitude placeDB.id = item.id place_list.child(item.id).setValue(placeDB) // } //} Toast.makeText(context, "Đã thêm vào danh sách yêu thích", Toast.LENGTH_SHORT).show() val intent = Intent(context, BottomNavigation::class.java) //this activity will be this fragment's father intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) } .setNegativeButton("No") { dialog, id -> // if this button is clicked, just close // the dialog box and do nothing tempplaceDb.latitude = item.latitude tempplaceDb.longitude = item.longitude tempplaceDb.name = item.name tempplaceDb.numofvisit = item.numofvisit tempplaceDb.numofsearch = item.numofsearch tempplaceDb.numsearch_after_ask = item.numsearch_after_ask tempplaceDb.id = item.id tempplaceDb.numofask = item.numofask + 1 tempplaceDb.askdate = currenttime tempplace_list.child(item.id).setValue(tempplaceDb) if(curplace_like_beforeplace){ tempplace_list.child(mAuth.currentUser!!.uid).setValue(tempplaceDb) curplace_like_beforeplace = false } dialog.cancel() } val alertDialog = alertDialogBuilder.create() alertDialog.show() } } } if(!curplace_like_beforeplace) { for (dsp in dataSnapshot.children) { //add result into array list val item: TempPlaceDbO? = dsp.getValue(TempPlaceDbO::class.java) if (item != null) { if ((cityname_temp == item.name || cityname_temp == "Thành phố " + item.name || cityname_temp == "Thủ Đô " + item.name || cityname_temp == "Tỉnh " + item.name) && curplace_like_beforeplace == false) { //place_list.child(place.id).setValue(placeDB) //tempplaceDb.numofvisit = item.numofvisit+1 tempplaceDb.latitude = item.latitude tempplaceDb.longitude = item.longitude tempplaceDb.name = item.name tempplaceDb.numofvisit = item.numofvisit + 1 tempplaceDb.numofsearch = item.numofsearch tempplaceDb.numsearch_after_ask = item.numsearch_after_ask tempplaceDb.id = item.id tempplaceDb.numofask = item.numofask //val date = getCurrentDateTime() //val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) tempplaceDb.askdate = item.askdate tempplace_list.child(item.id).setValue(tempplaceDb) //update dia diem hien tai gan nhat da ghe qua tempplace_list.child(mAuth.currentUser!!.uid).setValue(tempplaceDb) newplace_flag = false } } } } } else { // code if data does not exists if (!curplace_like_beforeplace) { tempplaceDb.latitude = latitude_temp tempplaceDb.longitude = longitude_temp tempplaceDb.name = cityname_temp tempplaceDb.numofvisit = 1 tempplaceDb.id = placeid_temp val date = getCurrentDateTime() val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) tempplaceDb.askdate = currenttime tempplace_list.child(tempplaceDb.id).setValue(tempplaceDb) //update dia diem hien tai gan nhat da ghe qua tempplace_list.child(mAuth.currentUser!!.uid).setValue(tempplaceDb) newplace_flag = false } } if (newplace_flag && !curplace_like_beforeplace) { tempplaceDb.latitude = latitude_temp tempplaceDb.longitude = longitude_temp tempplaceDb.name = cityname_temp tempplaceDb.numofvisit = 1 tempplaceDb.id = placeid_temp val date = getCurrentDateTime() val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) tempplaceDb.askdate = currenttime tempplace_list.child(tempplaceDb.id).setValue(tempplaceDb) //update dia diem hien tai gan nhat da ghe qua tempplace_list.child(mAuth.currentUser!!.uid).setValue(tempplaceDb) } // Result will be holded Here //insertAllPlace().execute(placeList) } }) } } fun getCityName_byLatlong(latlong: LatLng): String { //get city name val geocoder = Geocoder(context!!, Locale.getDefault()) val latitude_temp = latlong.latitude val longitude_temp = latlong.longitude val cityname_temp2 = "" try { val addresses = geocoder.getFromLocation(latitude_temp, longitude_temp, 1) if (addresses != null) { Log.e("start location : ", addresses.toString()) val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") //val strReturnedAddress = StringBuilder() for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } //Log.e("start location : ", addresses.get(0).subAdminArea) var result_adminarea = addresses.get(0).adminArea if (result_adminarea == null) result_adminarea = "" return result_adminarea } else { Log.d("a", "No Address returned! : ") } } catch (e: IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a", "Canont get Address!") } //end get city name return cityname_temp2 } fun currentday_oldday_space(startDate:String) : Long{ val simpleDateFormat = SimpleDateFormat("dd/MM/yyyy") val currentDate = Date() var date1: Date? = null var date2: Date? = null var getDaysDiff:Long = 0 try { //startDate = "01-01-2016" val endDate = simpleDateFormat.format(currentDate) date1 = simpleDateFormat.parse(startDate) date2 = simpleDateFormat.parse(endDate) val getDiff = date2.getTime() - date1.getTime() getDaysDiff = getDiff / (24 * 60 * 60 * 1000) println("Differance between date " + startDate + " and " + endDate + " is " + getDaysDiff + " days.") } catch (e:Exception) { e.printStackTrace() } return getDaysDiff } /** * A method to download json data from url */ @Throws(IOException::class) private fun downloadUrl(strUrl: String): String { Log.d("downloadUrl", "vô nè") var data = "" var iStream: InputStream? = null var urlConnection: HttpURLConnection? = null try { Log.d("downloadUrl try", "vô nè") val url = URL(strUrl) // Creating an http connection to communicate with url urlConnection = url.openConnection() as HttpURLConnection Log.d("url connection: ", urlConnection.toString()) // Connecting to url urlConnection.connect() // Reading data from url iStream = urlConnection.inputStream Log.d("iStream: ", iStream.toString()) data = iStream.bufferedReader().use(BufferedReader::readText) /*val br = BufferedReader(InputStreamReader(iStream)) //val br = BufferedReader(InputStreamReader(iStream!!)) val sb = StringBuffer() var line = "" while(line !=null){ line = br.readLine() //readLine() read data from file of BufferedReader sb.append(line) } data = sb.toString() Log.d("downloadUrl sb data= ", data.toString())*/ //br.close() } catch (e: Exception) { Log.d("Exception downloadUrl", e.toString()) } finally { iStream!!.close() urlConnection!!.disconnect() } return data } fun getCurrentDateTime(): Date { return Calendar.getInstance().time } }<file_sep>package com.horus.travelweather.database import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey @Entity(tableName = "placeData") data class PlaceEntity(@PrimaryKey var id : String, @ColumnInfo(name = "name") var name : String, @ColumnInfo(name = "lat") var latitude: Double, @ColumnInfo(name = "lon") var longitude: Double){ constructor():this("","",0.0,0.0) }<file_sep> package com.horus.travelweather.activity import android.app.ProgressDialog import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MenuItem import com.horus.travelweather.R class AboutUsActivity : AppCompatActivity() { private lateinit var progress : ProgressDialog override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_aboutus) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) progress = ProgressDialog(this) progress.setMessage("Loading....") } override fun onOptionsItemSelected(item: MenuItem?): Boolean { val id = item?.itemId if(id == android.R.id.home) { finish() } return super.onOptionsItemSelected(item) } } <file_sep>package com.horus.travelweather.model data class WindItem(val speed : Double= 0.0, val deg : String="") <file_sep>package com.horus.travelweather.activity import android.app.ProgressDialog import android.content.Intent import android.os.AsyncTask import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.TextUtils 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.google.android.gms.auth.api.signin.GoogleSignIn import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.* import com.horus.travelweather.BottomNavigation import com.horus.travelweather.R import com.horus.travelweather.common.TWConstant import com.horus.travelweather.database.ProfileEntity import com.horus.travelweather.database.TravelWeatherDB import com.horus.travelweather.model.UserDbO import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_main.* import com.google.android.gms.auth.api.signin.GoogleSignInAccount import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.gms.common.api.ApiException import com.google.firebase.auth.GoogleAuthProvider class MainActivity : AppCompatActivity() { private val TAG: String = MainActivity::class.toString() private val compositeDisposable = CompositeDisposable() private lateinit var googleSignInClient: GoogleSignInClient lateinit var btnLogin: Button lateinit var btnSignUp: TextView lateinit var editEmail: EditText lateinit var editPassword: EditText lateinit var mAuth: FirebaseAuth lateinit var table_user: DatabaseReference companion object { private const val RC_SIGN_IN = 9001 } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // [START config_signin] // Configure Google Sign In val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build() // [END config_signin] googleSignInClient = GoogleSignIn.getClient(this, gso) val database: FirebaseDatabase = FirebaseDatabase.getInstance() table_user = database.getReference("users") // [START initialize_auth] // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance() // [END initialize_auth] btnLogin = findViewById(R.id.btnLogin) btnSignUp = findViewById(R.id.btnSignUp) editEmail = findViewById(R.id.txtEmail) editPassword = findViewById(R.id.txtPassword) btnSignUp.setOnClickListener { val signUpIntent = Intent(this@MainActivity, SignUpActivity::class.java) startActivity(signUpIntent) } btnLogin.setOnClickListener { signInWithEmail(editEmail.text.toString(), editPassword.text.toString()) } sign_in_with_gg.setOnClickListener { signInWithGG() } //get all profile from database room val getProfile = TravelWeatherDB.getInstance(this@MainActivity).profileDataDao() compositeDisposable.add(getProfile.getAllProfileUser() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ }, { Log.e(TAG, "" + it.message) })) } private fun signInWithGG() { val signInIntent = googleSignInClient.signInIntent startActivityForResult(signInIntent, RC_SIGN_IN) } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) if (hasFocus) hideSystemUI() } private fun hideSystemUI() { // Enables regular immersive mode. // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE. // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) } private fun signInWithEmail(email: String, password: String) { if (!validateForm(email, password)) return val progress = ProgressDialog(this) progress.setMessage("Loading....") progress.show(); mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // update UI with the signed-in user's information val u = mAuth.getCurrentUser() table_user.addValueEventListener(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { } override fun onDataChange(p0: DataSnapshot) { try { val user = p0.child(u!!.uid).getValue(UserDbO::class.java) val profileUser = ProfileEntity(u.uid, user!!.name, user.email,user.phone) TWConstant.currentUser = user // insert user info into database room. insertProfileUser().execute(profileUser) progress.dismiss() deleteAllPLace().execute() intoMainActivity() } catch (e: Exception) { Toast.makeText(this@MainActivity, "Error : " + e.message, Toast.LENGTH_LONG).show(); } } }) } else { progress.dismiss() Log.e(TAG, "signInWithEmail: Fail!", task.exception) Toast.makeText(this@MainActivity, "Tài khoản hoặc mật khẩu không đúng", Toast.LENGTH_SHORT).show() } } } // [START onactivityresult] public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) try { // Google Sign In was successful, authenticate with Firebase val account = task.getResult(ApiException::class.java) // Toast.makeText(this@MainActivity, "Google sign in successfull", Toast.LENGTH_SHORT).show(); firebaseAuthWithGoogle(account!!) } catch (e: ApiException) { // Google Sign In failed, update UI appropriately Toast.makeText(this@MainActivity, "Error : " + e.message, Toast.LENGTH_SHORT).show(); Toast.makeText(this@MainActivity, "Error google signin: " + e.statusMessage, Toast.LENGTH_SHORT).show(); // [START_EXCLUDE] // updateUI(null) // [END_EXCLUDE] } } } // [END onactivityresult] // [START auth_with_google] private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) { // [START_EXCLUDE silent] // showProgressDialog() val progress = ProgressDialog(this) progress.setMessage("Loading....") progress.show(); // [END_EXCLUDE] val credential = GoogleAuthProvider.getCredential(acct.idToken, null) mAuth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, save data with the signed-in user's information val u = mAuth.currentUser if (u != null) { table_user.orderByKey().equalTo(u.uid).addValueEventListener(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Toast.makeText(this@MainActivity, "Error Equal", Toast.LENGTH_SHORT).show() } override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.getChildren().iterator().hasNext()) { try { val user = dataSnapshot.child(u!!.uid).getValue(UserDbO::class.java) TWConstant.currentUser = user!! progress.dismiss() deleteAllPLace().execute() intoMainActivity() } catch (e: Exception) { Toast.makeText(this@MainActivity, "Error : " + e.message, Toast.LENGTH_LONG).show(); } } else { try { val userDbO = UserDbO(u.displayName!!,u.email!!, "[Chưa cập nhật]", u.photoUrl.toString()) if (table_user.child(u.uid).setValue(userDbO).isComplete) { val user = dataSnapshot.child(u!!.uid).getValue(UserDbO::class.java) TWConstant.currentUser = user!! progress.dismiss() deleteAllPLace().execute() intoMainActivity() } } catch (e: Exception) { Toast.makeText(this@MainActivity, "Error : " + e.message, Toast.LENGTH_LONG).show(); } } } }) } } else { // If sign in fails, display a message to the user. Log.e(TAG, "signInWithCredential:failure", task.exception) } // [START_EXCLUDE] progress.dismiss() // [END_EXCLUDE] } } // [END auth_with_google] private fun intoMainActivity() { val homeIntent = Intent(this@MainActivity, BottomNavigation::class.java) startActivity(homeIntent) } private fun validateForm(email: String, password: String): Boolean { if (TextUtils.isEmpty(email)) { Toast.makeText(this@MainActivity, "Vui lòng điền địa chỉ email", Toast.LENGTH_SHORT).show(); return false; } if (TextUtils.isEmpty(password)) { Toast.makeText(this@MainActivity, "Vui lòng nhập password", Toast.LENGTH_SHORT).show(); return false; } if (password.length < 6) { Toast.makeText(this@MainActivity, "Vui lòng nhập mật khẩu lớn hơn hoặc bằng 6 ký tự", Toast.LENGTH_SHORT).show(); return false; } return true } //Clear it before this activity refers to HomeActivity (in this activity, firebase data will put all place data in dbRoom) inner class deleteAllPLace() : AsyncTask<Void, Void, Void>() { override fun doInBackground(vararg params: Void?): Void? { TravelWeatherDB.getInstance(this@MainActivity).placeDataDao().deleteAll() return null } } inner class insertProfileUser() : AsyncTask<ProfileEntity, Void, Void>() { override fun doInBackground(vararg params: ProfileEntity): Void? { TravelWeatherDB.getInstance(this@MainActivity).profileDataDao().insert(params[0]) return null } } } <file_sep>package com.horus.travelweather.database import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.content.Context @Database(entities = arrayOf( PlaceEntity::class, ProfileEntity::class), version = 2) abstract class TravelWeatherDB : RoomDatabase() { abstract fun placeDataDao(): PlaceDAO abstract fun profileDataDao(): ProfileDAO companion object { private var INSTANCE: TravelWeatherDB? = null @Synchronized fun getInstance(context: Context): TravelWeatherDB { if (INSTANCE == null) { synchronized(TravelWeatherDB::class) { INSTANCE = create(context) } } return INSTANCE as TravelWeatherDB } fun create(context : Context) : TravelWeatherDB{ return Room.databaseBuilder(context, TravelWeatherDB::class.java, "Place_horus") .fallbackToDestructiveMigration() .build() } } }<file_sep>package com.horus.travelweather.adapter import android.support.v7.widget.AppCompatImageView import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import com.horus.travelweather.R import com.horus.travelweather.activity.DirectionsFragment import com.horus.travelweather.model.DirectionsStepDbO import kotlinx.android.synthetic.main.stepbystep_directions.view.* class StepbyStepDirectionsAdapter (private var listDirectionsStep : List<DirectionsStepDbO>, private val onItemClick : (String)-> Unit ) : RecyclerView.Adapter<StepbyStepDirectionsAdapter.ViewHolder>() { //Đầu vào là 1 danh sách và 1 cái click (nếu có, click vào nút btn_delete để xóa địa điểm của mình đã thêm) private val TAG = DirectionsFragment::class.java.simpleName //assigning layout for a recyclerview element. override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.stepbystep_directions, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return listDirectionsStep.size } //assigning date from listTransportation to ViewHolder override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(listDirectionsStep[position]) } //This class controls views better, avoiding findViewByID too time inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { //Show info of walking/driving directions private val show_stepbystep = itemView.findViewById<View>(R.id.show_stepbystep) as LinearLayout private val imgView_direction = itemView.findViewById<View>(R.id.imgView_direction) as AppCompatImageView private val tv_instructions = itemView.findViewById<View>(R.id.tv_instructions) as TextView private val tv_attention = itemView.findViewById<View>(R.id.tv_attention) as TextView private val imgv_attention_icon = itemView.findViewById<View>(R.id.imgv_attention_icon) as ImageView private val tv_showtime = itemView.findViewById<View>(R.id.tv_showtime) as TextView private val showtime_eachstep = itemView.findViewById<View>(R.id.showtime_eachstep) as RelativeLayout //Show info of transit directions private val show_transitsteps = itemView.findViewById<View>(R.id.show_transitsteps) as LinearLayout private val tv_departure_name = itemView.findViewById<View>(R.id.tv_departure_name) as TextView private val tv_busname = itemView.findViewById<View>(R.id.tv_busname) as TextView private val tv_headsign = itemView.findViewById<View>(R.id.tv_headsign) as TextView private val tv_transit_distance = itemView.findViewById<View>(R.id.tv_transit_distance) as TextView private val tv_numstops = itemView.findViewById<View>(R.id.tv_numstops) as TextView private val tv_arrival_name = itemView.findViewById<View>(R.id.tv_arrival_name) as TextView fun bind(step: DirectionsStepDbO) { //Lập trình bất đồng bộ //Set cho imgView_transportation trên recycleviewer 1 lắng nghe (nhận id bất kỳ để nhận dạng loại ptien) itemView.tv_instructions.setOnClickListener { onItemClick(step.id.toString()) } if(step.direction == "Head" || step.direction == "Straight"){ imgView_direction.setImageResource(R.drawable.ic24_head) } else if(step.direction == "turn-left"){ imgView_direction.setImageResource(R.drawable.ic24_turnleft) } else if(step.direction == "turn-right"){ imgView_direction.setImageResource(R.drawable.ic24_turnright) } else if(step.direction == "turn-slight-right"){ //chếch sang phải imgView_direction.setImageResource(R.drawable.ic24_turnslightright) } else if(step.direction == "turn-slight-left"){ imgView_direction.setImageResource(R.drawable.ic24_turnslightleft) }else if(step.direction == "turn-sharp-right"){ // ngoặc phải imgView_direction.setImageResource(R.drawable.ic24_turnsharpright) } else if(step.direction == "turn-sharp-left"){ imgView_direction.setImageResource(R.drawable.ic24_turnsharpleft) } else if(step.direction == "ferry"){ imgView_direction.setImageResource(R.drawable.ic24_ferry) } else if(step.direction == "ferry-train"){ imgView_direction.setImageResource(R.drawable.ic24_ferry) } else if(step.direction == "ramp-right"){ //tại nút giao thông imgView_direction.setImageResource(R.drawable.ic24_rampleft) } else if(step.direction == "ramp-left"){ imgView_direction.setImageResource(R.drawable.ic24_rampleft) } else if(step.direction == "fork-right"){ //tại nút giao thông imgView_direction.setImageResource(R.drawable.ic24_rampleft) } else if(step.direction == "fork-left"){ imgView_direction.setImageResource(R.drawable.ic24_rampleft) } else if(step.direction == "uturn-right"){ imgView_direction.setImageResource(R.drawable.ic24_uturnright) } else if(step.direction == "uturn-left"){ imgView_direction.setImageResource(R.drawable.ic24_uturnleft) } else if(step.direction == "merge"){ imgView_direction.setImageResource(R.drawable.ic24_merge) } else if(step.direction == "roundabout-right"){ imgView_direction.setImageResource(R.drawable.ic24_roundabout) } else if(step.direction == "roundabout-left"){ imgView_direction.setImageResource(R.drawable.ic24_roundabout) } else if(step.direction == "keep-right"){ imgView_direction.setImageResource(R.drawable.ic24_keepright) } else if(step.direction == "keep-left"){ imgView_direction.setImageResource(R.drawable.ic24_keepleft) } else if(step.direction == "walking"){ imgView_direction.setImageResource(R.drawable.ic24_walking) } else if(step.direction == "transit"){ imgView_direction.setImageResource(R.drawable.ic24_bus) }else{ imgView_direction.setImageResource(R.drawable.ic24_head) } if(step.direction != "transit") { show_stepbystep.visibility = View.VISIBLE show_transitsteps.visibility = View.GONE tv_instructions.text = step.instructions if(!step.attention.isEmpty()){ //imgv_attention_icon.setImageResource(R.drawable.ic_attention24) tv_attention.text = step.attention }else { imgv_attention_icon.visibility = View.GONE tv_attention.visibility = View.GONE } if(!step.duration.isEmpty()){ tv_showtime.text = step.distance.plus(" ("+step.duration+')') } else{ showtime_eachstep.visibility = View.GONE } } else { show_stepbystep.visibility = View.GONE show_transitsteps.visibility = View.VISIBLE val temp = "Đi qua " tv_departure_name.text = step.transit.departure_stop tv_busname.text = step.transit.line_busname tv_headsign.text = step.transit.headsign tv_transit_distance.text = step.distance tv_numstops.text = temp.plus(step.transit.num_stops + " trạm dừng (trong "+ step.duration + ")") tv_arrival_name.text = step.transit.arrival_stop } } } }<file_sep>package com.horus.travelweather.model import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.PrimaryKey import java.io.Serializable import java.text.DateFormat import java.util.* data class TempFavPlaceDbO (@ColumnInfo(name = "id") var id : String , @ColumnInfo(name = "name") var name : String ,@ColumnInfo(name = "address") var address : String ,@ColumnInfo(name = "uri") var uri : String , @ColumnInfo(name = "numofsearch") var numofsearch : Int , @ColumnInfo(name = "numofvisit") var numofvisit : Int , @ColumnInfo(name = "numofask") var numofask : Int ,@ColumnInfo(name = "numsearch_after_ask") var numsearch_after_ask : Int , @ColumnInfo(name = "askdate") var askdate : String){ constructor():this("","","","",0,0,0, 0,"") }<file_sep>package com.horus.travelweather.service import com.horus.travelweather.model.DailyWeatherDetailResponse import com.horus.travelweather.model.WeatherDetailsResponse import io.reactivex.Observable import retrofit2.http.GET import retrofit2.http.Query interface ApiService { //we always use RxJava for our data layer //Using RxJava error will be returned in onError() method so we can show an appropriate error message to the user. //In RxJava2 You can think about Observable as the source of the data and Observer the one that gets the data. //Once when an Observer subscribed to the Observable onSubscribe method will be called. // Note that we have Disposable as a parameter of onSubscribe method. // First, instead of Observer, we can use DisposableObserver that implements Disposable and have dispose() method. // So we don’t need onSubscribe() // But we use another smarter way: *** CompositeDisposable *** // CompositeDisposable, a disposable container that can hold onto multiple other disposables // So, each time when we create Disposable we should hold it into CompositeDisposable: @GET("forecast") fun getDailyWeatherDetails(@Query("q") cityName : String, @Query("APPID") keyAPI : String): Observable<DailyWeatherDetailResponse> @GET("forecast") fun getDailyWeatherCoordinates(@Query("lat") latitude : Double, @Query("lon") longitude : Double, @Query("APPID") keyAPI : String): Observable<DailyWeatherDetailResponse> @GET("weather") fun getWeatherDetailsOneLocation(@Query("q") cityName : String, @Query("APPID") keyAPI : String): Observable<WeatherDetailsResponse> @GET("weather") fun getWeatherDetailsCoordinates(@Query("lat") latitude : Double, @Query("lon") longitude : Double, @Query("APPID") keyAPI : String): Observable<WeatherDetailsResponse> }<file_sep>package com.horus.travelweather.utils import android.util.Log import java.sql.Timestamp import java.text.SimpleDateFormat import java.util.* object StringFormatter { val unitPercentage = "%" val unitDegrees = "\u00b0" val unitsMetresPerSecond = "m/s" val unitDegreesCelsius = "\u2103" fun convertToValueWithUnit(precision: Int, unitSymbol: String, value: Double?): String{ return getPrecision(precision).format(value) + unitSymbol } private fun getPrecision(precision: Int) : String{ return "%." + precision + "f" } fun convertTimestampToDayAndHourFormat(timestamp: Long): String{ val DAY_HOUR_MINUTE = "dd/MM/yyyy" val formatter = SimpleDateFormat (DAY_HOUR_MINUTE, Locale.ENGLISH) formatter.timeZone = TimeZone.getTimeZone("GMT+7:30") val dateFormat = formatter.format(Date(timestamp*1000)) return dateFormat } fun getCurrentTime() : String { val HOUR_MINUTE = "h:mm a" val formatter = SimpleDateFormat (HOUR_MINUTE, Locale.ENGLISH) val dateFormat = formatter.format(Calendar.getInstance().getTime()) return dateFormat } fun convertTimestampHourFormat(timestamp: Long): String{ val HOUR_MINUTE = "HH:mm" val formatter = SimpleDateFormat (HOUR_MINUTE, Locale.ENGLISH) formatter.timeZone = TimeZone.getTimeZone("GMT") val dateFormat = formatter.format(Date(timestamp*1000)) return dateFormat } fun convertKelvinToCelsius(temperatue: Double): Double { val temp = (temperatue - 273.15) return temp } }<file_sep>package com.horus.travelweather.activity import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.support.design.widget.BottomNavigationView import android.support.design.widget.FloatingActionButton import android.support.v4.app.Fragment import android.support.v4.view.ViewPager import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.MenuItem import android.view.View import android.widget.RatingBar import android.widget.TextView import com.google.android.gms.location.places.Places import com.google.android.gms.maps.model.LatLng import com.horus.travelweather.BottomNavigation import com.horus.travelweather.R import com.horus.travelweather.adapter.SlidingImageAdapter import com.horus.travelweather.model.PlaceDbO import kotlinx.android.synthetic.main.activity_detail_my_place.* class DetailMyPlace : AppCompatActivity() { private var arraySliding : ArrayList<Bitmap> = arrayListOf() private lateinit var adapterSliding : SlidingImageAdapter // private lateinit var adapterSliding : ArrayAdapter<String> private val TAG = DetailMyPlace::class.java.simpleName override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_detail_my_place) val place = intent.getSerializableExtra("MyPlace") as PlaceDbO Log.e(TAG,"ABC : "+place.name) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) getPhoto(place.placeId) val actionBar1 = supportActionBar if (actionBar1 != null) { //actionBar1.setDisplayHomeAsUpEnabled(true) actionBar1.title = "Thông Tin Địa Điểm" } sliding_view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) { } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { pageIndicatorView.selection = position } }) val fab_directions = this.findViewById<View>(R.id.fab_directions2) as FloatingActionButton fab_directions.setOnClickListener { //val directionsIntent = Intent(this@DetailMyPlace, DirectionsFragment::class.java) //directionsIntent.putExtra("MyLatLng",latLng_toDirection.toString()) setContentView(R.layout.activity_bottom_navigation) val aaa = BottomNavigation() //aaa.navigation val navigation = this.findViewById<View>(R.id.navigation) as BottomNavigationView navigation.selectedItemId = R.id.navigation_direction val directionFragment = DirectionsFragment.newInstance(latLng_toDirection.toString()) openFragment(directionFragment) val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { getSupportActionBar()!!.setTitle("Home") val homeFragment = HomeFragment.newInstance() openFragment(homeFragment) //progress_loading.visibility = View.VISIBLE return@OnNavigationItemSelectedListener true } R.id.navigation_favorite -> { getSupportActionBar()!!.setTitle("Địa Điểm Yêu Thích") val favouriteFragment = FavoritePlaceFragment.newInstance() //progress_loading.visibility = View.GONE openFragment(favouriteFragment) return@OnNavigationItemSelectedListener true } R.id.navigation_direction -> { getSupportActionBar()!!.setTitle("Chỉ Đường") val directionFragment = DirectionsFragment.newInstance("") //progress_loading.visibility = View.GONE openFragment(directionFragment) return@OnNavigationItemSelectedListener true } R.id.navigation_history -> { getSupportActionBar()!!.setTitle("Nhật Ký Hoạt Động") val historyFragment = HistoryFragment.newInstance() //progress_loading.visibility = View.GONE openFragment(historyFragment) return@OnNavigationItemSelectedListener true } R.id.navigation_profile -> { getSupportActionBar()!!.setTitle("Profile") val profileFragment = NewProfileFragment.newInstance() //progress_loading.visibility = View.GONE openFragment(profileFragment) return@OnNavigationItemSelectedListener true } } false } navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) /*val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.detailmyplace, directionFragment) fab_directions2.visibility = View.GONE app_bar_layout.visibility = View.GONE transaction.attach(directionFragment) transaction.addToBackStack(null) transaction.commit() directionbackDetail = true*/ } } /* override fun onBackPressed() { super.onBackPressed() navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) navigation.selectedItemId = R.id.navigation_home val homeFragment = HomeFragment.newInstance() openFragment(homeFragment) }*/ fun getMyData(): String { return latLng_toDirection.toString() } override fun onOptionsItemSelected(item: MenuItem?): Boolean { val id = item?.itemId if(id == android.R.id.home) { finish() } return super.onOptionsItemSelected(item) } private fun openFragment(fragment: Fragment) { val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.container, fragment) transaction.addToBackStack(null) transaction.commit() } var latLng_toDirection: LatLng = LatLng(10.762622, 106.660172) // Request photos and metadata for the specified place. private fun getPhoto(placeId: String) { //val placeId = "ChIJa147K9HX3IAR-lwiGIQv9i4" //val ratingBar = this.findViewById<View>(R.id.rating_bar) as RatingBar val mGeoDataClient = Places.getGeoDataClient(this) val photoMetadataResponse = mGeoDataClient.getPlacePhotos(placeId) photoMetadataResponse.addOnCompleteListener{ task -> // Get the list of photos. val photos = task.result // Get the PlacePhotoMetadataBuffer (metadata for all of the photos). val photoMetadataBuffer = photos.photoMetadata Log.e(TAG,"ABC : "+photoMetadataBuffer.count) // Get the first photo in the list. for(i in 0 until photoMetadataBuffer.count) { val photoMetadata = photoMetadataBuffer.get(i) // Get a full-size bitmap for the photo. val photoResponse = mGeoDataClient.getPhoto(photoMetadata) photoResponse.addOnCompleteListener{ task -> val photo = task.result val bitmap = photo.bitmap Log.e(TAG,""+bitmap) arraySliding.add(bitmap) adapterSliding.notifyDataSetChanged() } } adapterSliding = SlidingImageAdapter(this,arraySliding) sliding_view_pager.adapter = adapterSliding pageIndicatorView.count = arraySliding.size pageIndicatorView.setViewPager(sliding_view_pager) } mGeoDataClient.getPlaceById(placeId).addOnCompleteListener { task -> if (task.isSuccessful) { val txt_place_name = this.findViewById<View>(R.id.txt_place_name) as TextView val ratingBar = this.findViewById<View>(R.id.rating_bar) as RatingBar val ratingNumber = this.findViewById<View>(R.id.rating_number) as TextView val txt_address = this.findViewById<View>(R.id.txt_address) as TextView val txt_phonenumber = this.findViewById<View>(R.id.txt_phonenumber) as TextView val txt_weburi = this.findViewById<View>(R.id.txt_weburi) as TextView val places = task.result val myPlace = places.get(0) txt_place_name.text=myPlace.name ratingBar.rating=myPlace.rating ratingNumber.text=myPlace.rating.toString() if(myPlace.address == "" || myPlace.address == null){ txt_address.text = "Chưa cập nhật" } else txt_address.text = myPlace.address if(myPlace.phoneNumber == "" || myPlace.phoneNumber == null){ txt_phonenumber.text = "Chưa cập nhật" } else txt_phonenumber.text=myPlace.phoneNumber if(myPlace.websiteUri.toString() == "" || myPlace.websiteUri == null){ txt_weburi.text = "Chưa cập nhật" } else txt_weburi.text= myPlace.websiteUri.toString() latLng_toDirection = myPlace.latLng // to send to DirectionsFragment Log.i(TAG, "Place latlng found: " + latLng_toDirection) Log.i(TAG, "Place address found: " + myPlace.address) //Log.i(TAG, "Place attributions found: " + myPlace.attributions) //Log.i(TAG, "Place latLng found: " + myPlace.latLng) //Log.i(TAG, "Place locale found: " + myPlace.locale) Log.i(TAG, "Place name found: " + myPlace.name) Log.i(TAG, "Place rating found: " + myPlace.rating) Log.i(TAG, "Place phoneNumber found: " + myPlace.phoneNumber) Log.i(TAG, "Place placeTypes found: " + myPlace.placeTypes.get(0)) //Log.i(TAG, "Place priceLevel found: " + myPlace.priceLevel) Log.i(TAG, "Place viewport found: " + myPlace.viewport.toString()) Log.i(TAG, "Place websiteUri found: " + myPlace.websiteUri) places.release() } else { Log.e(TAG, "Place not found.") } } } }<file_sep>package com.horus.travelweather.adapter import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.horus.travelweather.R import com.horus.travelweather.common.TWConstant import com.horus.travelweather.model.WeatherDetailsResponse import com.horus.travelweather.utils.StringFormatter import com.horus.travelweather.utils.StringFormatter.convertKelvinToCelsius import com.horus.travelweather.utils.StringFormatter.convertTimestampHourFormat import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.daily_weather.view.* import kotlinx.android.synthetic.main.fragment_weather_details.* class DailyWeatherAdapter (private val dailyWeather : List<WeatherDetailsResponse>) : RecyclerView.Adapter<DailyWeatherAdapter.ViewHolder>() { override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(dailyWeather[position],position) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) : ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.daily_weather, parent, false) return ViewHolder(view) } override fun getItemCount(): Int { return dailyWeather.size } inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { fun bind(daily : WeatherDetailsResponse, position: Int ) { itemView.txt_hourly.text = convertTimestampHourFormat(daily.dateTime) Picasso.with(itemView.context).load(TWConstant.BASE_URL_UPLOAD + daily.weather[0].icon + ".png").into(itemView.img_daily_weather_icon) itemView.txt_daily_humidity.text = StringFormatter.convertToValueWithUnit(0, StringFormatter.unitPercentage, daily.temperature.humidity) itemView.txt_daily_temperature.text = StringFormatter.convertToValueWithUnit(0, StringFormatter.unitDegreesCelsius, convertKelvinToCelsius(daily.temperature.temp)) } } }<file_sep>package com.horus.travelweather.model import com.google.android.gms.maps.model.LatLng data class DirectionsStepDbO (val id: Int, val direction: String, val instructions: String, val attention: String, val duration: String, val distance: String, val latLng: LatLng, val transit: TransitDbO)<file_sep>package com.horus.travelweather.database import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy import android.arch.persistence.room.Query import io.reactivex.Flowable @Dao interface ProfileDAO { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(profileEntity : ProfileEntity) @Query("SELECT * FROM profileData WHERE uid == :uid") fun getProfileInfo(uid : Int): Flowable<ProfileEntity> @Query("SELECT * from profileData") fun getAllProfileUser() : Flowable<List<ProfileEntity>> }<file_sep>package com.horus.travelweather.activity 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 com.horus.travelweather.R import com.horus.travelweather.common.TWConstant import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_new_profile.view.* class NewProfileFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.activity_new_profile, container, false) view.txt_username.text = TWConstant.currentUser.name Picasso.with(this.context).load(TWConstant.currentUser.urlPhoto).into(view.img_url_photo) //go to profile detail view.edit_profile.setOnClickListener { val intent = Intent(this.context, ProfileActivity::class.java) //this activity will be this fragment's father startActivity(intent) } view.relat_viewprofile.setOnClickListener { val intent = Intent(this.context, ProfileActivity::class.java) //this activity will be this fragment's father startActivity(intent) } //about us view.tv_aboutus.setOnClickListener { val intent = Intent(this.context, AboutUsActivity::class.java) //this activity will be this fragment's father startActivity(intent) } view.tv_gethelp.setOnClickListener { val intent = Intent(this.context, AboutUsActivity::class.java) //this activity will be this fragment's father startActivity(intent) } //logout view.btn_logout.setOnClickListener { getActivity()!!.finish() } view.tv_logout.setOnClickListener { getActivity()!!.finish() } return view } companion object { fun newInstance(): NewProfileFragment = NewProfileFragment() } }<file_sep>package com.horus.travelweather.adapter import android.content.Context import android.graphics.Bitmap import android.support.v4.view.PagerAdapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.horus.travelweather.R import com.horus.travelweather.activity.DetailMyPlace class SlidingImageAdapter(private val context: Context, private val listImage: List<Bitmap>): PagerAdapter() { private val TAG = DetailMyPlace::class.java.simpleName override fun isViewFromObject(view: View, `object`: Any): Boolean { return view == `object` } override fun getCount(): Int { return listImage.size } override fun instantiateItem(container: ViewGroup, position: Int): Any { val imageLayout = LayoutInflater.from(context).inflate(R.layout.sliding_images_layout, container, false) val imageView = imageLayout.findViewById<View>(R.id.image) as ImageView //val ratingBar = imageLayout.findViewById<View>(R.id.rating_bar) as RatingBar // imageView.measure(imageView.measuredWidth, imageView.measuredHeight) //ratingBar.rating=ratingNumber imageView.setImageBitmap(listImage[position]) container.addView(imageLayout, 0) return imageLayout } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { // super.destroyItem(container, position, `object`) } override fun destroyItem(container: View, position: Int, `object`: Any) { // super.destroyItem(container, position, `object`) } }<file_sep>package com.horus.travelweather.model import android.net.Uri class UserDbO(var name: String="", var email: String="", var phone: String = "", var urlPhoto: String = "") { } <file_sep>package com.horus.travelweather.repository import com.horus.travelweather.BuildConfig import com.horus.travelweather.common.TWConstant import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory class Repository { companion object { private var retrofit: Retrofit? = null private var builder: Retrofit.Builder = Retrofit.Builder().baseUrl(TWConstant.Companion.BASE_API_LAYER) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) private val httpClient = OkHttpClient.Builder() fun <S> createService(serviceClass: Class<S>): S { return createService(serviceClass, null) } fun <S> createService(serviceClass: Class<S>, authToken: Map<String, String>?): S { val interceptor = HttpLoggingInterceptor() httpClient.addInterceptor(interceptor) .addInterceptor(HttpLoggingInterceptor() .apply { level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE }) builder.client(httpClient.build()) retrofit = builder.build() return retrofit!!.create(serviceClass) } } class AuthenticationInterceptor(private val authToken: Map<String, String>) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val original = chain.request() val builder = original.newBuilder() for (key in authToken.keys) { builder.header(key, authToken.getValue(key)) } val request = builder.build() return chain.proceed(request) } } }<file_sep>package com.horus.travelweather.model data class TransportationDbO (val id: String, val duration: String) <file_sep>package com.horus.travelweather.database import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy import android.arch.persistence.room.Query import io.reactivex.Flowable @Dao interface PlaceDAO { @Query("SELECT * from placeData") fun getAll() : Flowable<List<PlaceEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insert(placeEntity : PlaceEntity) @Query("DELETE from placeData") fun deleteAll() @Query("DELETE FROM placeData WHERE id = :placeID") fun deleteByPlaceId(placeID : String?) @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAllPlace(placeList : ArrayList<PlaceEntity>) }<file_sep>package com.horus.travelweather.activity import android.Manifest import android.app.ProgressDialog import android.content.Context import android.content.res.Resources import android.graphics.drawable.AnimationDrawable import android.os.AsyncTask import android.os.Bundle import android.support.v4.app.Fragment import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageView import android.widget.ProgressBar import com.google.android.gms.maps.SupportMapFragment import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.* import com.horus.travelweather.R import com.horus.travelweather.R.id.view_pager import com.horus.travelweather.adapter.ViewPagerAdapter import com.horus.travelweather.database.PlaceEntity import com.horus.travelweather.database.TravelWeatherDB import com.tbruyelle.rxpermissions2.RxPermissions import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.observers.DisposableObserver import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_home_fragment.* class HomeFragment : Fragment() { private val TAG = HomeFragment::class.java.simpleName private val compositeDisposable = CompositeDisposable() private val menu : MutableList<PlaceEntity> = mutableListOf() lateinit var database: FirebaseDatabase lateinit var place_list: DatabaseReference lateinit var mAuth: FirebaseAuth //lateinit var progress_loading: ProgressBar override fun onAttach(context: Context?) { super.onAttach(context) } override fun onDestroy() { super.onDestroy() Log.e(TAG,"Destroy Destroy Destroy Destroy Destroy Destroy : ") } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.activity_home_fragment, container, false) database = FirebaseDatabase.getInstance() mAuth = FirebaseAuth.getInstance() place_list = database.getReference("places").child(mAuth.currentUser!!.uid) //progress_loading = view.findViewById(R.id.progress_loading) var progress = ProgressDialog(context) val progress_loading = view.findViewById<ProgressBar>(R.id.progress_loading) as ProgressBar progress_loading.isIndeterminate = true progress_loading.max = 100 progress_loading.visibility = View.VISIBLE // progress.setIndeterminateDrawable(R.drawable.my_progress_indeterminate) //progress.setMessage("Loading....") //progress.setProgressDrawable(resources.getDrawable(R.drawable.bottleloading)) //progress.max = 100 //progress.show() val rxPermissions = RxPermissions(this) rxPermissions .request(Manifest.permission.ACCESS_FINE_LOCATION) .subscribe { granted -> if (granted) { //to read firebase date, we need ValueEventListener place_list.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Log.e(TAG,"Error in HomeFragment: "+p0.message) } override fun onDataChange(dataSnapshot : DataSnapshot) { try { val placeList = ArrayList<PlaceEntity>() // Result will be holded Here for (dsp in dataSnapshot.children) { //add result into array list val item : PlaceEntity? = dsp.getValue(PlaceEntity::class.java) Log.e(TAG,"PlaceEntity : "+item) if (item != null) { placeList.add(item) } } Log.e(TAG,"Size : "+placeList.size) insertAllPlace().execute(placeList) //progress.cancel() progress_loading.visibility = View.GONE //Bind fragments on viewpager } catch (e: NullPointerException) { Log.e(TAG, "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "+e.message) } } }) } else { // Oups permission denied Log.e(TAG, "Access fail") } } return view } companion object { fun newInstance(): HomeFragment = HomeFragment() } private fun getDataFromLocal() { // RxJava là thư viện mã nguồn mở implement ReactiveX trên Java. Có 2 lớp chính là Observable và Subscriber: // Observable là một lớp đưa ra dòng dữ liệu hoặc sự kiện (event). Flow của Observable là đưa ra một // hoặc nhiều các items, sau đó gọi kết thúc thành công hoặc lỗi. // Subscriber lắng nghe flow, thực thi các hành động trên dòng dữ liệu hoặc sự kiện được đưa ra bởi Observable //get all places from database room val getAllPlace = TravelWeatherDB.getInstance(context!!).placeDataDao() // Probably, you already know that all UI code is done on Android Main thread. // RxJava is java library and it does not know about Android Main thread. That is the reason why we use RxAndroid. // RxAndroid gives us the possibility to choose Android Main thread as the thread where our code will be executed. // Obviously, our Observer should operate on Android Main thread. try { compositeDisposable.add(getAllPlace.getAll() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ //excute event Log.e(TAG,"Get data from local : "+it) val adapter = ViewPagerAdapter(childFragmentManager,it) view_pager.adapter = adapter }, { Log.e(TAG, "" + it.message) })) } catch (e: NullPointerException) { Log.e(TAG, "getdatafromlocal lich : "+e.message) } } inner class insertAllPlace() : AsyncTask<ArrayList<PlaceEntity>, Void, Void>() { override fun doInBackground(vararg params : ArrayList<PlaceEntity>): Void? { TravelWeatherDB.getInstance(context!!).placeDataDao().insertAllPlace(params[0]) getDataFromLocal() return null } } }<file_sep>package com.horus.travelweather.activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.text.TextUtils import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.horus.travelweather.R import com.horus.travelweather.common.TWConstant import com.horus.travelweather.model.UserDbO class SignUpActivity : AppCompatActivity() { private val TAG : String = MainActivity::class.toString() lateinit var editEmail: EditText lateinit var editPass: EditText lateinit var editName: EditText lateinit var editPhone: EditText lateinit var btnSignUp: Button lateinit var mAuth : FirebaseAuth lateinit var table_user : DatabaseReference override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_up) val database: FirebaseDatabase = FirebaseDatabase.getInstance() table_user = database.getReference("users") mAuth = FirebaseAuth.getInstance() editEmail = findViewById(R.id.signUpEmail) editName = findViewById(R.id.editName) editPass = findViewById(R.id.editPass) editPhone = findViewById(R.id.editPhone) btnSignUp = findViewById(R.id.btnSignUp) btnSignUp.setOnClickListener { createAccount(editEmail.text.toString(),editPass.text.toString()) } } private fun createAccount(email : String , password : String) { if (!validateForm(email, password)) { return; } mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener { if(it.isSuccessful) { Log.e(TAG, "createAccount: Success!"); val user : FirebaseUser = mAuth.currentUser!! writeNewUser(user.uid,editName.text.toString(), user.email!!,editPhone.text.toString()) Toast.makeText(this@SignUpActivity, getString(R.string.sign_up_successfull), Toast.LENGTH_SHORT).show() finish() } else { //Log.e("AAA", "signUp: Fail!", it.getException()) Toast.makeText(this@SignUpActivity, getString(R.string.already_in_use), Toast.LENGTH_SHORT).show() } } } private fun writeNewUser(userId : String, username : String, email : String, phone : String) { val user = UserDbO(username,email,phone, TWConstant.BASE_URI_PHOTO) table_user.child(userId).setValue(user) } private fun validateForm(email:String , password : String) : Boolean { if (TextUtils.isEmpty(email)) { Toast.makeText(this@SignUpActivity, "Enter email address!", Toast.LENGTH_SHORT).show(); return false; } if (TextUtils.isEmpty(password)) { Toast.makeText(this@SignUpActivity, "Enter password!", Toast.LENGTH_SHORT).show(); return false; } if (password.length < 6) { Toast.makeText(this@SignUpActivity, "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show(); return false; } return true } // inner class insertProfile(): AsyncTask<ProfileEntity, Void, Void>() { // override fun doInBackground(vararg params: ProfileEntity): Void? { // TravelWeatherDB.getInstance(this@SignUpActivity).profileDataDao().insert(params[0]) // return null // } // } } <file_sep>package com.horus.travelweather import android.os.Bundle import android.support.design.widget.BottomNavigationView import android.support.v4.app.Fragment import android.support.v7.app.AppCompatActivity import android.util.Log import android.view.View import com.horus.travelweather.R.id.progress_loading import com.horus.travelweather.activity.* import kotlinx.android.synthetic.main.activity_bottom_navigation.* import kotlinx.android.synthetic.main.fragment_weather_details.* class BottomNavigation : AppCompatActivity() { val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home -> { getSupportActionBar()!!.setTitle("Home") val homeFragment = HomeFragment.newInstance() openFragment(homeFragment) //progress_loading.visibility = View.VISIBLE return@OnNavigationItemSelectedListener true } R.id.navigation_favorite -> { getSupportActionBar()!!.setTitle("Địa Điểm Yêu Thích") val favouriteFragment = FavoritePlaceFragment.newInstance() //progress_loading.visibility = View.GONE openFragment(favouriteFragment) return@OnNavigationItemSelectedListener true } R.id.navigation_direction -> { getSupportActionBar()!!.setTitle("Chỉ Đường") val directionFragment = DirectionsFragment.newInstance("") //progress_loading.visibility = View.GONE openFragment(directionFragment) return@OnNavigationItemSelectedListener true } R.id.navigation_history -> { getSupportActionBar()!!.setTitle("Nhật Ký Hoạt Động") val historyFragment = HistoryFragment.newInstance() //progress_loading.visibility = View.GONE openFragment(historyFragment) return@OnNavigationItemSelectedListener true } R.id.navigation_profile -> { getSupportActionBar()!!.setTitle("Profile") val profileFragment = NewProfileFragment.newInstance() //progress_loading.visibility = View.GONE openFragment(profileFragment) return@OnNavigationItemSelectedListener true } } false } private fun openFragment(fragment: Fragment) { val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.container, fragment) transaction.addToBackStack(null) transaction.commit() } override fun onBackPressed() { super.onBackPressed() navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) navigation.selectedItemId = R.id.navigation_home val homeFragment = HomeFragment.newInstance() openFragment(homeFragment) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_bottom_navigation) getSupportActionBar()!!.setTitle("Home"); val homeFragment = HomeFragment.newInstance() openFragment(homeFragment) navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) } } <file_sep> package com.horus.travelweather.activity import android.app.ProgressDialog import android.content.Context import android.content.Intent import android.graphics.Color import android.graphics.Typeface import android.os.Bundle import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.widget.TextView import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.horus.travelweather.BottomNavigation import com.horus.travelweather.R import com.horus.travelweather.common.TWConstant import com.horus.travelweather.model.UserDbO import com.rengwuxian.materialedittext.MaterialEditText import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.activity_profile.* import uk.co.markormesher.android_fab.SpeedDialMenuAdapter import uk.co.markormesher.android_fab.SpeedDialMenuItem class ProfileActivity : AppCompatActivity() { private val TAG : String = ProfileActivity::class.toString() private val flag = true; private lateinit var progress : ProgressDialog ; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_profile) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) val actionBar1 = supportActionBar if (actionBar1 != null) { //actionBar1.setDisplayHomeAsUpEnabled(true) actionBar1.title = "Thông Tin Cá Nhân" } txt_user_profile_name.text = TWConstant.currentUser.name txt_phone_number.text = TWConstant.currentUser.phone txt_email_user.text = TWConstant.currentUser.email Picasso.with(this).load(TWConstant.currentUser.urlPhoto).into(header_cover_image) fabEdit.speedDialMenuAdapter = speedDialMenuAdapter fabEdit.setContentCoverColour(Color.TRANSPARENT) progress = ProgressDialog(this) progress.setMessage("Loading....") } override fun onOptionsItemSelected(item: MenuItem?): Boolean { val id = item?.itemId if(id == android.R.id.home) { finish() } return super.onOptionsItemSelected(item) } private fun showDialogChangeProfile() { val alterDialog : AlertDialog.Builder = AlertDialog.Builder(this) alterDialog.setTitle("Thay đổi thông tin") /*if (actionBar1 != null) { //actionBar1.setDisplayHomeAsUpEnabled(true) actionBar1.title = "Thông Tin Cá Nhân" }*/ val inflater : LayoutInflater = LayoutInflater.from(this) val dialogView = inflater.inflate(R.layout.edit_profile_layout,null) alterDialog.setView(dialogView) val editName = dialogView.findViewById<View>(R.id.editName) as MaterialEditText val editPhone = dialogView.findViewById<View>(R.id.editPhone) as MaterialEditText editName.setText(TWConstant.currentUser.name) editPhone.setText(TWConstant.currentUser.phone) val database: FirebaseDatabase = FirebaseDatabase.getInstance() val table_user : DatabaseReference = database.getReference("users") val mAuth : FirebaseAuth = FirebaseAuth.getInstance() alterDialog.setPositiveButton("Cập Nhật") { dialog, _ -> val user = UserDbO(editName.text.toString(),TWConstant.currentUser.email,editPhone.text.toString(),TWConstant.currentUser.urlPhoto) table_user.child(mAuth.uid!!).setValue(user).addOnCompleteListener { if(it.isComplete) { val intent = Intent(this, ProfileActivity::class.java) //this activity will be this fragment's father intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) Toast.makeText(this@ProfileActivity,"Thay đổi đã được cập nhật" , Toast.LENGTH_SHORT).show() } } } alterDialog.setNegativeButton("Hủy", { dialog, whichButton -> progress.dismiss() }) alterDialog.create().show() } private fun showDialogChangePassword() { progress.show() val alterDialog : AlertDialog.Builder = AlertDialog.Builder(this) alterDialog.setTitle("Thay đổi mật khẩu") val inflater : LayoutInflater = LayoutInflater.from(this) val dialogView = inflater.inflate(R.layout.edit_password_layout,null) val editPassword = dialogView.findViewById<View>(R.id.editPassword) as MaterialEditText alterDialog.setView(dialogView) editPassword.setText("") alterDialog.setPositiveButton("Cập nhật") { dialog, _ -> if(countOnString(editPassword.text.toString().trim())) { val newUser = FirebaseAuth.getInstance().currentUser val newPassword = editPassword.text.toString() if(newPassword.trim() != "") { newUser?.updatePassword(newPassword)!!.addOnCompleteListener { if(it.isComplete) { progress.dismiss() val intent = Intent(this, ProfileActivity::class.java) //this activity will be this fragment's father intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) Toast.makeText(this@ProfileActivity,"Mật khẩu đã được cập nhật" , Toast.LENGTH_SHORT).show() } } } } } alterDialog.setNegativeButton("Hủy", { dialog, whichButton -> progress.dismiss() }) alterDialog.create().show() } private fun countOnString(text : String) : Boolean { if(text.count() >= 6) { return true } progress.dismiss() Toast.makeText(this@ProfileActivity,"Mật khẩu phải lớn hơn hoặc bằng 6 ký tự" , Toast.LENGTH_LONG).show() return false } private val speedDialMenuAdapter = object: SpeedDialMenuAdapter() { override fun getCount(): Int { return 2 } override fun getMenuItem(context: Context, position: Int): SpeedDialMenuItem = when (position) { 0 -> SpeedDialMenuItem(context, R.drawable.ic_edit_white_24dp, "Chỉnh sửa profile") 1 -> SpeedDialMenuItem(context, R.drawable.ic_vpn_key_white_24dp, "Thay đổi mật khẩu") else -> throw IllegalArgumentException("No menu item: $position") } override fun onPrepareItemLabel(context: Context, position: Int, label: TextView) { // make the first item bold if there are multiple items // (this isn't a design pattern, it's just to demo the functionality) label.setTypeface(label.typeface, Typeface.BOLD) label.setTextColor(Color.WHITE) } override fun onMenuItemClick(position: Int): Boolean { if(position == 0) { showDialogChangeProfile() return true } else if(position == 1) { showDialogChangePassword() return true } return super.onMenuItemClick(position) } // // rotate the "+" icon only // override fun fabRotationDegrees(): Float = if (0 == 0) 135F else 0F } } <file_sep>package com.horus.travelweather.model import java.io.Serializable data class PlaceDbO (var placeId : String="" , var name : String= "" , var address: String="" , var uri : String="") : Serializable<file_sep>package com.horus.travelweather.model import com.google.gson.annotations.SerializedName class WeatherItem{ lateinit var id : String @SerializedName("main") lateinit var nameWeather : String lateinit var icon : String }<file_sep>package com.horus.travelweather.activity import android.Manifest import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.graphics.Color import android.graphics.PointF import android.location.Geocoder import android.location.Location import android.os.AsyncTask import android.os.Build import android.os.Bundle import android.speech.tts.TextToSpeech import android.support.annotation.RequiresApi import android.support.v4.app.ActivityCompat import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.* import android.util.DisplayMetrics import android.util.Log import android.view.* import android.widget.RelativeLayout import android.widget.Toast import com.firebase.ui.database.FirebaseRecyclerAdapter import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.location.LocationListener import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationServices import com.google.android.gms.location.places.AutocompleteFilter import com.google.android.gms.location.places.PlacePhotoMetadataResponse import com.google.android.gms.location.places.PlacePhotoResponse import com.google.android.gms.location.places.Places import com.google.android.gms.location.places.ui.PlaceAutocomplete import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.* import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.OnFailureListener import com.google.android.gms.tasks.OnSuccessListener import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import com.google.firebase.database.* import com.google.firebase.storage.FirebaseStorage import com.horus.travelweather.BottomNavigation import com.horus.travelweather.R import com.horus.travelweather.adapter.HistoryAdapter import com.horus.travelweather.adapter.StepbyStepDirectionsAdapter import com.horus.travelweather.adapter.TransportationAdapter import com.horus.travelweather.common.TWConstant import com.horus.travelweather.database.PlaceEntity import com.horus.travelweather.model.* import kotlinx.android.synthetic.main.activity_directions.* import kotlinx.android.synthetic.main.activity_directions.view.* import kotlinx.android.synthetic.main.eachhistory_layout.view.* import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.io.BufferedReader import java.io.ByteArrayOutputStream import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import java.util.* import kotlin.collections.ArrayList class DirectionsFragment : Fragment(), OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private val TAG = DirectionsFragment::class.java.simpleName private lateinit var adapterTransportation : TransportationAdapter private lateinit var adapterStepbyStepDirections : StepbyStepDirectionsAdapter var PLACE_AUTOCOMPLETE_REQUEST_CODE = 1 var PLACE_AUTOCOMPLETE_REQUEST_CODE2 = 2 private lateinit var mMap:GoogleMap private lateinit var markerPoints:ArrayList<LatLng> private lateinit var mGoogleApiClient:GoogleApiClient private lateinit var mLastLocation:Location private var mCurrLocationMarker: Marker? = null private lateinit var mLocationRequest:LocationRequest var transList = ArrayList<TransportationDbO>() var stepsList = ArrayList<DirectionsStepDbO>() var stepsList_temp = ArrayList<DirectionsStepDbO>() private var count: Int = 1 var currentlocation = LatLng(10.762622, 106.660172) var destlocation = LatLng(10.762622, 106.660172) private lateinit var textToSpeech: TextToSpeech //Saving history when searching private val historyDb = HistoryDbO() lateinit var database: FirebaseDatabase lateinit var history_list: DatabaseReference //temp place private val tempplaceDb = TempPlaceDbO() //for AI lateinit var tempplace_list: DatabaseReference //for AI //temp favplace private val favplaceDb = PlaceDbO() private val tempfavplaceDb = TempFavPlaceDbO() //for AI lateinit var tempfavplace_list: DatabaseReference //for AI // lateinit var city_statistics: DatabaseReference //for statistics lateinit var mAuth: FirebaseAuth lateinit var adapter: FirebaseRecyclerAdapter<HistoryDbO, HistoryAdapter.HistoryViewHolder> var myuser: FirebaseUser? = null var latLngfromFavPlace = "" @SuppressLint("SetTextI18n") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.activity_directions, container, false) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkLocationPermission() } setHasOptionsMenu(true) mAuth = FirebaseAuth.getInstance() myuser = mAuth.currentUser database = FirebaseDatabase.getInstance() history_list = database.getReference("history") tempplace_list = database.getReference("tempplace").child(mAuth.currentUser!!.uid) city_statistics = database.getReference("city_statistics") // Initializing markerPoints = ArrayList<LatLng>() // //val activity = activity as DetailMyPlace? //latLngfromFavPlace = activity!!.getMyData() //val latLngfromFavPlace = (activity!!.intent.getSerializableExtra("MyLatLng") as String) //if(!latLngfromFavPlace.isEmpty()){ latLngfromFavPlace = arguments!!.getString("MyLatLng") if(!latLngfromFavPlace.isEmpty()){ val actionBar1 = (activity as AppCompatActivity).supportActionBar if (actionBar1 != null) { //actionBar1.setDisplayHomeAsUpEnabled(true) actionBar1.title = "Direction" } var lat = "" var lng = "" for(i in 0 until latLngfromFavPlace.length){ if(latLngfromFavPlace[i] == ','){ lat = latLngfromFavPlace.substring(10,i) lng = latLngfromFavPlace.substring(i+1,latLngfromFavPlace.lastIndex) } } Log.e("Place latlng: ",lat+ ',' + lng) destlocation = LatLng(lat.toDouble(),lng.toDouble()) val geocoder = Geocoder(context!!, Locale.getDefault()) try { val addresses = geocoder.getFromLocation(destlocation.latitude, destlocation.longitude, 1) if (addresses != null) { val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } view.edt_destination.setText(addresses.get(0).getAddressLine(0)) Log.e("start location: ",addresses.get(0).getAddressLine(0)) } else { Log.d("a","No Address returned! : ") } } catch (e:IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a","Canont get Address!") } } //currentlocation = currentLocation_latLng!! view.imgView_optionmenu.setOnClickListener{ showPopup(context!!, view.imgView_optionmenu, 0) //Log.e("hientai: ",currentLocation_latLng.toString()) } // textToSpeech = TextToSpeech(context!!, TextToSpeech.OnInitListener { i -> if (i == TextToSpeech.SUCCESS) { //result = textToSpeech.setLanguage(Locale.UK) textToSpeech.speak("", TextToSpeech.QUEUE_FLUSH, null) } else { Toast.makeText(context!!,"Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show() } }) // Obtain the SupportMapFragment and get notified when the map is ready to be used. if(getFragmentManager() != null) { val mMapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment // val mapFragment = getFragmentManager()!! // .findFragmentById(R.id.map) as SupportMapFragment mMapFragment.getMapAsync(this) } // val edt_orgin = this.findViewById<View>(R.id.edt_orgin) as TextView // val edt_destination = this.findViewById<View>(R.id.edt_destination) as TextView // //This btn shows direction (org -> dest) steps // val btn_steps = this.findViewById<View>(R.id.btn_steps) as Button //val recyclerView = this.findViewById<View>(R.id.rv_directionsSteps) as RecyclerView // val behavior = BottomSheetBehavior.from(recyclerView) //val transList = ArrayList<TransportationDbO>() transList.add(TransportationDbO("driving","")) transList.add(TransportationDbO("walking","")) transList.add(TransportationDbO("transit","")) implementLoad(transList,view.rv_transportations) stepsList.add(DirectionsStepDbO(0,"","","","","", currentlocation, TransitDbO("","","","","","",""))) loadingStepbyStep(stepsList,view.rv_directionsSteps) view.clicksteps.setOnClickListener{ numberofclick++ /*if(numberofclick == 1){ layoutParams_temp = scroll_directionsdetail.layoutParams as RelativeLayout.LayoutParams Log.e("ACTION stop=: ",layoutParams_temp!!.topMargin.toString()) numberofclick++ }*/ if(count%2 != 0) { view.rv_directionsSteps.visibility = View.VISIBLE view.linear_orgindest.animate() .translationY(linear_orgindest.height.toFloat()) .alpha(0.0f) .duration = 800 view.rv_transportations.animate() .translationY(rv_transportations.height.toFloat()) .alpha(0.0f) .duration = 800 view.clicksteps.setOnTouchListener(onTouchListener()) view.linear_orgindest.visibility = View.GONE view.rv_transportations.visibility = View.GONE } else{ view.rv_directionsSteps.visibility = View.GONE view.linear_orgindest.animate() .translationY(0F) .alpha(1.0f) .duration = 200 view.rv_transportations.animate() .translationY(0F) .alpha(1.0f) .duration = 200 view.linear_orgindest.visibility = View.VISIBLE view.rv_transportations.visibility = View.VISIBLE } count++ } /*stepsicon.setOnClickListener{ if(count%2 != 0) { rv_directionsSteps.visibility = View.VISIBLE linear_orgindest.visibility = View.GONE rv_transportations.visibility = View.GONE } else{ rv_directionsSteps.visibility = View.GONE linear_orgindest.visibility = View.VISIBLE rv_transportations.visibility = View.VISIBLE } count++ }*/ view.btn_previous.setOnClickListener{ if(thestep > 0 && thestep < stepsList.size){ thestep-- pre_nextstep(thestep) } } view.btn_next.setOnClickListener{ if(thestep >= 0 && thestep < stepsList.size - 1){ thestep++ pre_nextstep(thestep) } } view.imgbtn_updown.setOnClickListener{ val edt_origin_temp = view.edt_orgin.text view.edt_orgin.text = edt_destination.text view.edt_destination.text = edt_origin_temp val currentlocation_temp = currentlocation currentlocation = destlocation destlocation = currentlocation_temp } view.edt_orgin.setOnClickListener { //Filter results by place type (by address: get full address, by establisment: get business address) val typeFilter = AutocompleteFilter.Builder() .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS) .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ESTABLISHMENT) .build() //Use an intent to launch the autocomplete activity (fullscreen mode) //https://developers.google.com/places/android-sdk/autocomplete val intent = PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN) .setFilter(typeFilter) .build(activity) startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE) } view.edt_destination.setOnClickListener { //Filter results by place type (by address: get full address, by establisment: get business address) val typeFilter = AutocompleteFilter.Builder() .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS) .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ESTABLISHMENT) .build() //Use an intent to launch the autocomplete activity (fullscreen mode) //https://developers.google.com/places/android-sdk/autocomplete val intent = PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN) .setFilter(typeFilter) .build(activity) startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE2) } return view } private fun showPopup(context: Context, textView: AppCompatImageButton, position: Int) { var popup: PopupMenu? = null popup = PopupMenu(context, textView) //Add only option (remove) of per img popup.menu.add(0, position, 0, TWConstant.YOURLOCATION1) popup.menu.add(0, position+1, 0, TWConstant.YOURLOCATION2) popup.show() popup.menu.getItem(0).setOnMenuItemClickListener({ currentlocation = currentLocation_latLng val geocoder = Geocoder(context!!, Locale.getDefault()) try { val addresses = geocoder.getFromLocation(currentlocation.latitude, currentlocation.longitude, 1) if (addresses != null) { val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } edt_orgin.setText(addresses.get(0).getAddressLine(0)) Log.e("start location: ",addresses.get(0).getAddressLine(0)) } else { Log.d("a","No Address returned! : ") } } catch (e:IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a","Canont get Address!") } true }) popup.menu.getItem(1).setOnMenuItemClickListener({ //Log.e("Ok nha2:","1") destlocation = currentLocation_latLng val geocoder = Geocoder(context!!, Locale.getDefault()) try { val addresses = geocoder.getFromLocation(destlocation.latitude, destlocation.longitude, 1) if (addresses != null) { val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } edt_destination.setText(addresses.get(0).getAddressLine(0)) Log.e("start location: ",addresses.get(0).getAddressLine(0)) } else { Log.d("a","No Address returned! : ") } } catch (e:IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a","Canont get Address!") } true }) } private fun distance(x1: Float, y1: Float, x2: Float, y2: Float): Float { val dx = x1 - x2 val dy = y1 - y2 val distanceInPx = Math.sqrt((dx * dx + dy * dy).toDouble()).toFloat() return pxToDp(distanceInPx) } private fun pxToDp(px: Float): Float { return px / resources.displayMetrics.density } //MotionEvent.ACTION_UP means you touch sensor fist time //MotionEvent.ACTION_DOWN means that touch sensor does not detect anymore //for example MotionEvent.ACTION_MOVE means that sensor detects some moves (like swipe, scroll etc.) //When u move clicksteps (that top bar above direction steps list) private var xDelta:Int = 0 private var yDelta:Int = 0 //private val CLICK_ACTION_THRESHHOLD = 200 //to determind click event when touchevent is running private val MAX_CLICK_DURATION = 400 private val MAX_CLICK_DISTANCE = 5 private var startClickTime: Long = 0 private var stayedWithinClickDistance:Boolean = false private var x1: Float = 0.toFloat() private var y1: Float = 0.toFloat() private var dx: Float = 0.toFloat() private var dy: Float = 0.toFloat() private var firstclick:Boolean = false private var numberofclick:Int = 0 var layoutParams_temp: RelativeLayout.LayoutParams? = null private fun onTouchListener(): View.OnTouchListener { return View.OnTouchListener { view, event -> // val mainLayout = findViewById<View>(R.id.clicksteps) as RelativeLayout val x = event.rawX.toInt() val y = event.rawY.toInt() val lParams = view.layoutParams as RelativeLayout.LayoutParams when (event.action and MotionEvent.ACTION_MASK) { MotionEvent.ACTION_DOWN -> { if(clicksteps.bottom != directionsID.bottom) { xDelta = x - lParams.leftMargin yDelta = y - lParams.topMargin //to determind click event x1 = event.x y1 = event.y startClickTime = System.currentTimeMillis() stayedWithinClickDistance = true firstclick = true } } MotionEvent.ACTION_UP -> { //if(clicksteps.top != directionsID.top) { // yDelta = y + lParams.topMargin val clickDuration = Calendar.getInstance().timeInMillis - startClickTime dx = event.x - x1 dy = event.y - y1 if (clickDuration < MAX_CLICK_DURATION && dx < MAX_CLICK_DISTANCE && dy < MAX_CLICK_DISTANCE) { Log.v("", "On Item Clicked:: ") view.performClick() } // firstclick = true //} /* if (pressDuration < MAX_CLICK_DURATION && stayedWithinClickDistance) { // Click event has occurred view.performClick() }*/ } MotionEvent.ACTION_MOVE -> { val layoutParams = view.layoutParams as RelativeLayout.LayoutParams //if(clicksteps.bottom != directionsID.bottom){ if (firstclick == true) { layoutParams.topMargin = y - yDelta layoutParams.rightMargin = 0 layoutParams.bottomMargin = 0 //layoutParams_temp = view.layoutParams as RelativeLayout.LayoutParams view.layoutParams = layoutParams Log.e("topmargin: ", (directionsID.bottom).toString()) Log.e("topmargin2: ", (clicksteps.bottom).toString()) firstclick = false } //} /*else if (clicksteps.bottom == directionsID.bottom){ Log.e("ACTION =: ","false") *//*val row = findViewById<View>(R.id.scroll_directionsdetail) as RelativeLayout val rv_directionsSteps_temp = findViewById<View>(R.id.rv_directionsSteps) as RecyclerView val clicksteps_temp = findViewById<View>(R.id.clicksteps) as RelativeLayout row.removeView(clicksteps_temp) row.removeView(rv_directionsSteps_temp) row.addView(clicksteps_temp) row.addView(rv_directionsSteps_temp) row.invalidate()*//* val params = RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT) params.addRule(RelativeLayout.VISIBLE) params.addRule(RelativeLayout.ALIGN_BOTTOM,directionsID.bottom) //clicksteps.top = 900 //params.addRule(RelativeLayout.BELOW, R.id.clicksteps) rv_directionsSteps.layoutParams = params Log.e("ACTION stop1=: ",clicksteps.top.toString()) Log.e("ACTION stop3=: ",rv_directionsSteps.top.toString()) Log.e("ACTION stop2=: ",rv_directionsSteps.top.toString()) Log.e("ACTION stop4=: ",rv_directionsSteps.bottom.toString()) //nhan dang touch len de update chạy code nhu tren, sau do van check tiep de han che dung thanh bottom }*/ stayedWithinClickDistance = false } } // Because we call this from onTouchEvent, this code will be executed for both // normal touch events and for when the system calls this using Accessibility clicksteps.invalidate() true } } override fun onMapReady(googleMap:GoogleMap) { mMap = googleMap setupGoogleMapScreenSettings(googleMap) //Initialize Google Play Services if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if ((ContextCompat.checkSelfPermission(context!!, Manifest.permission.ACCESS_FINE_LOCATION) === PackageManager.PERMISSION_GRANTED)) { buildGoogleApiClient() mMap.isMyLocationEnabled = true } } else { buildGoogleApiClient() mMap.isMyLocationEnabled = true } // Setting onclick event listener for the map // val fab_directions = this.findViewById<View>(R.id.fab_directions) as FloatingActionButton fab_directions.setOnClickListener { AddMarker(currentlocation,destlocation) // Getting URL to the Google Directions API val url = getUrl(currentlocation, destlocation) //val url = getUrl(LatLng(addresses[0].longitude, addresses[0].latitude), myPlace.latLng) Log.d("onMapClick: ", url) val fetchUrl = FetchUrl("driving") Log.d("fetchUrl: ", fetchUrl.toString()) // Start downloading json data from Google Directions API fetchUrl.execute(url) val url2 = getUrl_Walking(currentlocation, destlocation) //val url = getUrl(LatLng(addresses[0].longitude, addresses[0].latitude), myPlace.latLng) Log.d("onMapClick2: ", url2) val fetchUrl2 = FetchUrl_NotPolyline("walking") Log.d("fetchUrl2: ", fetchUrl2.toString()) // Start downloading json data from Google Directions API fetchUrl2.execute(url2) val url3 = getUrl_Transit(currentlocation, destlocation) //val url = getUrl(LatLng(addresses[0].longitude, addresses[0].latitude), myPlace.latLng) Log.d("onMapClick3: ", url3) val fetchUrl3 = FetchUrl_NotPolyline("transit") Log.d("fetchUrl3: ", fetchUrl3.toString()) // Start downloading json data from Google Directions API fetchUrl3.execute(url3) val fetchUrl_present = FetchUrl_ClickonRecycler("driving") fetchUrl_present.execute(url) //move map camera mMap.moveCamera(CameraUpdateFactory.newLatLng(currentlocation)) mMap.animateCamera(CameraUpdateFactory.zoomTo(12F)) } //When myuser click anywhere on maps /*mMap.setOnMapClickListener { point -> // Already two locations if (markerPoints.size > 1) { markerPoints.clear() mMap.clear() } // Adding new item to the ArrayList markerPoints.add(point) // Creating MarkerOptions val options = MarkerOptions() // Setting the position of the marker options.position(point) *//** * For the start location, the color of marker is GREEN and * for the end location, the color of marker is RED. *//* *//** * For the start location, the color of marker is GREEN and * for the end location, the color of marker is RED7. *//* if (markerPoints.size == 1) { options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)) } else if (markerPoints.size == 2) { options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)) } // Add new marker to the Google Map Android API V2 mMap.addMarker(options) // Checks, whether start and end locations are captured if (markerPoints.size >= 2) { val origin = markerPoints[0] val dest = markerPoints[1] Log.d("origin: ", markerPoints[0].toString()) Log.d("dest: ", markerPoints[1].toString()) // Getting URL to the Google Directions API val url = getUrl(origin, dest) Log.d("onMapClick: ", url) val fetchUrl = FetchUrl("1") Log.d("fetchUrl: ", fetchUrl.toString()) // Start downloading json data from Google Directions API fetchUrl.execute(url) *//*val url2 = getUrl_Walking(origin,dest) val fetchUrl2 = FetchUrl2("2") fetchUrl2.execute(url2) val url3 = getUrl_Bicycling(origin,dest) val fetchUrl3 = FetchUrl3("3") fetchUrl3.execute(url3) *//* //move map camera mMap.moveCamera(CameraUpdateFactory.newLatLng(origin)) mMap.animateCamera(CameraUpdateFactory.zoomTo(12F)) } }*/ } // As TransportationAdapter, input: list & id (by one click), if we click any element on rv_transportation private fun implementLoad(list : List<TransportationDbO>,rv_transportations : RecyclerView) { adapterTransportation = TransportationAdapter(list,{ id -> var url = getUrl(currentlocation, destlocation) var vehicle = "driving" when (id) { "driving" -> { } "walking" -> { url = getUrl_Walking(currentlocation, destlocation) vehicle = "walking" } "transit" -> { url = getUrl_Transit(currentlocation, destlocation) vehicle = "transit" } } //AddMarker(currentlocation,destlocation) Log.d("onMapClick: ", url) val fetchUrl = FetchUrl_ClickonRecycler(vehicle) Log.d("fetchUrl: ", fetchUrl.toString()) // Start downloading json data from Google Directions API fetchUrl.execute(url) mMap.moveCamera(CameraUpdateFactory.newLatLng(currentlocation)) mMap.animateCamera(CameraUpdateFactory.zoomTo(12F)) //adapterTransportation.notifyDataSetChanged() }) val layoutManager : RecyclerView.LayoutManager = LinearLayoutManager(context!!, LinearLayoutManager.HORIZONTAL, false) rv_transportations.adapter = adapterTransportation rv_transportations.layoutManager = layoutManager //rv_directionsSteps.setHasFixedSize(true) } var thestep = 0 //step of rv_directionsteps private fun loadingStepbyStep(list : List<DirectionsStepDbO>,rv_directionsSteps : RecyclerView) { adapterStepbyStepDirections = StepbyStepDirectionsAdapter(list,{ id -> pre_nextstep(id.toInt()) //adapterStepbyStepDirections.notifyDataSetChanged() }) val layoutManager2 : RecyclerView.LayoutManager = SmoothLinearLayoutManager(context!!, LinearLayoutManager.VERTICAL, false) rv_directionsSteps.adapter = adapterStepbyStepDirections rv_directionsSteps.layoutManager = layoutManager2 } var options_flat: Boolean = false private var markerName_temp: Marker? = null private fun pre_nextstep(id: Int){ thestep = id.toInt() //val toolbar = this.findViewById<View>(R.id.toolbar) as Toolbar? //setSupportActionBar(toolbar) goto_stepbystep.visibility = View.VISIBLE show_pre_next.visibility = View.VISIBLE scroll_directionsdetail.visibility = View.GONE linear_orgindest.visibility = View.GONE rv_transportations.visibility = View.GONE fab_directions.visibility = View.GONE //val imgView_goto_direction = this.findViewById<View>(R.id.imgView_goto_direction) as AppCompatImageView //val tv_goto_distance9 = this.findViewById<View>(R.id.tv_goto_distance9) as TextView //val tv_goto_instructions = this.findViewById<View>(R.id.tv_goto_instructions) as TextView tv_goto_distance9.text = stepsList[id.toInt()].distance tv_goto_instructions.text = stepsList[id.toInt()].instructions if(stepsList[id.toInt()].direction == "Head" || stepsList[id.toInt()].direction == "Straight"){ imgView_goto_direction.setImageResource(R.drawable.ic24_head) } else if(stepsList[id.toInt()].direction == "turn-left"){ imgView_goto_direction.setImageResource(R.drawable.ic24_turnleft) } else if(stepsList[id.toInt()].direction == "turn-right"){ imgView_goto_direction.setImageResource(R.drawable.ic24_turnright) } else if(stepsList[id.toInt()].direction == "turn-slight-right"){ //chếch sang phải imgView_goto_direction.setImageResource(R.drawable.ic24_turnslightright) } else if(stepsList[id.toInt()].direction == "turn-slight-left"){ imgView_goto_direction.setImageResource(R.drawable.ic24_turnslightleft) }else if(stepsList[id.toInt()].direction == "turn-sharp-right"){ // ngoặc phải imgView_goto_direction.setImageResource(R.drawable.ic24_turnsharpright) } else if(stepsList[id.toInt()].direction == "turn-sharp-left"){ imgView_goto_direction.setImageResource(R.drawable.ic24_turnsharpleft) } else if(stepsList[id.toInt()].direction == "ferry"){ imgView_goto_direction.setImageResource(R.drawable.ic24_ferry) } else if(stepsList[id.toInt()].direction == "ferry-train"){ imgView_goto_direction.setImageResource(R.drawable.ic24_ferry) } else if(stepsList[id.toInt()].direction == "ramp-right"){ //tại nút giao thông imgView_goto_direction.setImageResource(R.drawable.ic24_rampleft) } else if(stepsList[id.toInt()].direction == "ramp-left"){ imgView_goto_direction.setImageResource(R.drawable.ic24_rampleft) } else if(stepsList[id.toInt()].direction == "fork-right"){ //tại nút giao thông imgView_goto_direction.setImageResource(R.drawable.ic24_rampleft) } else if(stepsList[id.toInt()].direction == "fork-left"){ imgView_goto_direction.setImageResource(R.drawable.ic24_rampleft) } else if(stepsList[id.toInt()].direction == "uturn-right"){ imgView_goto_direction.setImageResource(R.drawable.ic24_uturnright) } else if(stepsList[id.toInt()].direction == "uturn-left"){ imgView_goto_direction.setImageResource(R.drawable.ic24_uturnleft) } else if(stepsList[id.toInt()].direction == "merge"){ imgView_goto_direction.setImageResource(R.drawable.ic24_merge) } else if(stepsList[id.toInt()].direction == "roundabout-right"){ imgView_goto_direction.setImageResource(R.drawable.ic24_roundabout) } else if(stepsList[id.toInt()].direction == "roundabout-left"){ imgView_goto_direction.setImageResource(R.drawable.ic24_roundabout) } else if(stepsList[id.toInt()].direction == "keep-right"){ imgView_goto_direction.setImageResource(R.drawable.ic24_keepright) } else if(stepsList[id.toInt()].direction == "keep-left"){ imgView_goto_direction.setImageResource(R.drawable.ic24_keepleft) } else{ imgView_goto_direction.setImageResource(R.drawable.ic24_head) } val actionBar1 = (activity as AppCompatActivity).supportActionBar if (actionBar1 != null) { actionBar1.setDisplayHomeAsUpEnabled(true) actionBar1.title = "Xem trước tuyến đường" } mMap.moveCamera(CameraUpdateFactory.newLatLng(stepsList[id.toInt()].latLng)) mMap.animateCamera(CameraUpdateFactory.zoomTo(18F)) // Setting the position of the marker //val options = MarkerOptions() if(markerName_temp != null) markerName_temp!!.remove() val markerName = mMap.addMarker(MarkerOptions().position(stepsList[thestep].latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))) //options.position(stepsList[id.toInt()].latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)) //options.flat(true) markerName_temp = markerName // Add new marker to the Google Map Android API V2 //mMap.addMarker(options) //options_flat = true if((if (textToSpeech != null) textToSpeech else throw NullPointerException("Expression 'textToSpeech' must not be null")).isSpeaking){ textToSpeech.shutdown() } textToSpeech = TextToSpeech(context!!, TextToSpeech.OnInitListener { i -> if (i == TextToSpeech.SUCCESS) { //result = textToSpeech.setLanguage(Locale.UK) textToSpeech.speak(tv_goto_instructions.text.toString(), TextToSpeech.QUEUE_FLUSH, null) } else { Toast.makeText(context!!,"Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show() } }) } override fun onDestroy() { //Close the Text to Speech Library if (textToSpeech != null) { textToSpeech.stop() textToSpeech.shutdown() Log.d(TAG, "TTS Destroyed") } super.onDestroy() } override fun onOptionsItemSelected(item: MenuItem?):Boolean { when (item?.itemId) { android.R.id.home -> { // todo: goto back activity from here val actionBar1 = (activity as AppCompatActivity).supportActionBar actionBar1!!.title = "Direction" actionBar1.setDisplayHomeAsUpEnabled(false) /*if (actionBar1 != null) { actionBar1.hide() }*/ goto_stepbystep.visibility = View.GONE show_pre_next.visibility = View.GONE linear_orgindest.visibility = View.VISIBLE rv_transportations.visibility = View.VISIBLE scroll_directionsdetail.visibility = View.VISIBLE fab_directions.visibility = View.VISIBLE directionsID.visibility = View.VISIBLE //mMap.animateCamera(CameraUpdateFactory.zoomTo(12F)) thestep = 0 /*if(!latLngfromFavPlace.isEmpty()){ val actionBar1 = (activity as AppCompatActivity).supportActionBar if (actionBar1 != null) { //actionBar1.setDisplayHomeAsUpEnabled(true) actionBar1.title = "Detail Place" fab_directions2.visibility = View.VISIBLE app_bar_layout.visibility = View.VISIBLE } }*/ return true } else -> return super.onOptionsItemSelected(item) } } private fun AddMarker(currentlocation: LatLng, destlocation: LatLng){ // val edt_orgin = this.findViewById<View>(R.id.edt_orgin) as TextView // val edt_destination = this.findViewById<View>(R.id.edt_destination) as TextView if (markerPoints.size > 1) { markerPoints.clear() mMap.clear() } //Add marker -> location markerPoints.add(currentlocation) markerPoints.add(destlocation) // Creating MarkerOptions val options = MarkerOptions() // Setting the position of the marker options.position(currentlocation).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)) mMap.addMarker(options).title = edt_orgin.text.toString() options.position(destlocation).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)) mMap.addMarker(options).title = edt_destination.text.toString() // Add new marker to the Google Map Android API V2 mMap.addMarker(options) } private fun getUrl(origin:LatLng, dest:LatLng):String { // Origin of route val strOrigin = "origin=" + origin.latitude + "," + origin.longitude // Destination of route val strDest = "destination=" + dest.latitude + "," + dest.longitude // Sensor enabled val sensor = "sensor=false" // Building the parameters to the web service val parameters = "${strOrigin.trim()}&${strDest.trim()}&$sensor" // Output format val output = "json" val apikey="<KEY>" // Building the url to the web service val url = "https://maps.googleapis.com/maps/api/directions/$output?$parameters&language=vi&mode=driving&key=$apikey" return url } private fun getUrl_Walking(origin:LatLng, dest:LatLng):String { // Origin of route val strOrigin = "origin=" + origin.latitude + "," + origin.longitude // Destination of route val strDest = "destination=" + dest.latitude + "," + dest.longitude // Sensor enabled val sensor = "sensor=false" // Building the parameters to the web service val parameters = "${strOrigin.trim()}&${strDest.trim()}&$sensor" // Output format val output = "json" val apikey="<KEY>" // Building the url to the web service val url = "https://maps.googleapis.com/maps/api/directions/$output?$parameters&language=vi&mode=walking&key=$apikey" return url } private fun getUrl_Transit(origin:LatLng, dest:LatLng):String { // Origin of route val strOrigin = "origin=" + origin.latitude + "," + origin.longitude // Destination of route val strDest = "destination=" + dest.latitude + "," + dest.longitude // Sensor enabled val sensor = "sensor=false" // Building the parameters to the web service val parameters = "${strOrigin.trim()}&${strDest.trim()}&$sensor" // Output format val output = "json" val apikey="<KEY>" // Building the url to the web service val url = "https://maps.googleapis.com/maps/api/directions/$output?$parameters&language=vi&mode=transit&transit_mode=bus&key=$apikey" return url } @RequiresApi(Build.VERSION_CODES.M) //Step by step fun StepByStep(jObject: JSONObject) { //val routes = ArrayList<List<HashMap<String, String>>>() val jRoutes: JSONArray var jLegs: JSONArray var jSteps: JSONArray var jDuration: JSONObject var jDistance: JSONObject var maneuver = "" var instructions = "" var distance = "" var duration = "" //Coordinator of each step var start_location_lat = "" var start_location_lng = "" var count = 0 try { jRoutes = jObject.getJSONArray("routes") /** Traversing all routes */ for (i in 0 until jRoutes.length()) { jLegs = (jRoutes.get(i) as JSONObject).getJSONArray("legs") //val path = ArrayList<HashMap<String, String>>() jDuration = (jLegs.get(i) as JSONObject).getJSONObject("duration") Log.e("Step duration: ",jDuration.toString()) jDistance = (jLegs.get(i) as JSONObject).getJSONObject("distance") Log.e("Step duration: ",jDistance.toString()) /** Traversing all legs */ for (j in 0 until jLegs.length()) { jSteps = (jLegs.get(j) as JSONObject).getJSONArray("steps") /** Traversing all steps */ stepsList.clear() count = 0 for (k in 0 until jSteps.length()) { maneuver = if(((jSteps.get(k) as JSONObject).has("maneuver")) ){ ((jSteps.get(k) as JSONObject).get("maneuver")) as String } else "Head" Log.e("Step maneuver: ", maneuver) instructions = ((jSteps.get(k) as JSONObject).get("html_instructions")) as String Log.e("Step-0 instructions: ", instructions) //Divide instructions string to instruction9 & attention var instructions9 = instructions var attention = "" // just additional info about that step var flag = false var j = 0 var end = instructions.length - 1 while (j <= end){ // if(instructions[j] == '<' && instructions[j+1] == 'd'){ attention = instructions.substring(j,end+1) instructions9 = instructions.substring(0,j) Log.e("Step1 instructions9: ", instructions9) Log.e("Step1 attention: ", attention) break } j++ } Log.e("Step1 instructions9: ", instructions9) Log.e("Step1 attention: ", attention) var start = 0 var i = 0 while(i < instructions9.length){ if (instructions9[i] == '<') { start = i } if(instructions9[i] == '&' && instructions9[i+1] == 'a' && instructions9[i+2] == 'm' && instructions9[i+3] == 'p' && instructions9[i+4] == ';') { val first = instructions9.substring(0,i+1) val last = instructions9.substring(i+5,instructions9.length) instructions9 = first + last } if (instructions9[i] == '>') { val first = instructions9.substring(0,start) val last = instructions9.substring(i+1) val newins = first + last instructions9 = newins i=0 start = 0 } i++ } var start2 = 0 var i2 = 0 while(i2 < attention.length){ if (attention[i2] == '&' || attention[i2] == '<') { start2 = i2 } if (attention[i2] == ';' || attention[i2] == '>') { var spot = "" if(attention[i2 - 1] == 'v') spot = ". " val first = attention.substring(0,start2) val last = attention.substring(i2+1) val newins = first + spot + last Log.e("Step last: ", last.toString()) attention = newins i2=0 Log.e("Step ins: ", i2.toString()) start2 = 0 } i2++ } Log.e("Step instructions: ", instructions9) distance = ((jSteps.get(k) as JSONObject).get("distance") as JSONObject).get("text") as String Log.e("Step distance: ", distance) duration = ((jSteps.get(k) as JSONObject).get("duration") as JSONObject).get("text") as String Log.e("Step duration: ", duration) start_location_lat = (((jSteps.get(k) as JSONObject).get("start_location") as JSONObject).get("lat") as Double).toString() Log.e("Step duration: ", start_location_lat) start_location_lng = (((jSteps.get(k) as JSONObject).get("start_location") as JSONObject).get("lng") as Double).toString() Log.e("Step duration: ", start_location_lng) Log.e("Step duration2: ", LatLng(start_location_lat.toDouble(),start_location_lng.toDouble()).toString()) stepsList.add(DirectionsStepDbO(count++,maneuver,instructions9,attention,duration,distance, LatLng(start_location_lat.toDouble(),start_location_lng.toDouble()), TransitDbO("","","","","","",""))) getActivity()!!.runOnUiThread { adapterStepbyStepDirections.notifyDataSetChanged() } } } } } catch (e: JSONException) { e.printStackTrace() } catch (e: Exception) { } } @RequiresApi(Build.VERSION_CODES.M) //Step by step fun StepByStep_Transit(jObject: JSONObject) { //val routes = ArrayList<List<HashMap<String, String>>>() val jRoutes: JSONArray var jLegs: JSONArray var jSteps: JSONArray var jDuration: JSONObject var jDistance: JSONObject var maneuver = "" var instructions = "" var distance = "" var duration = "" //Coordinator of each step var start_location_lat = "" var start_location_lng = "" var count = 0 //Transit mode //Bus/... var travelmode = "" var arrival_stop = "" //get name & location var arrival_time = "" //get text (text is time) var departure_stop = "" //get name & location var departure_time = "" //get text (text is time) var line_busname = "" //get line->name (example "name": 19 - Bến Thành - KCX Linh Trung - ĐH Quốc Gia) var headsign = "" //get headsign (name of arrival city) var num_stops = "" //get num_stops (number of stops) //walking in transit var jSteps_child: JSONArray var jDuration_child: JSONObject var jDistance_child: JSONObject var maneuver_child = "" var instructions_child = "" var distance_child = "" var duration_child = "" try { jRoutes = jObject.getJSONArray("routes") /** Traversing all routes */ for (i in 0 until jRoutes.length()) { jLegs = (jRoutes.get(i) as JSONObject).getJSONArray("legs") //val path = ArrayList<HashMap<String, String>>() jDuration = (jLegs.get(i) as JSONObject).getJSONObject("duration") Log.e("Step duration: ",jDuration.toString()) jDistance = (jLegs.get(i) as JSONObject).getJSONObject("distance") Log.e("Step duration: ",jDistance.toString()) /** Traversing all legs */ for (j in 0 until jLegs.length()) { jSteps = (jLegs.get(j) as JSONObject).getJSONArray("steps") /** Traversing all steps */ stepsList.clear() count = 0 for (k in 0 until jSteps.length()) { instructions = ((jSteps.get(k) as JSONObject).get("html_instructions")) as String Log.e("Step-0 instructions: ", instructions) distance = ((jSteps.get(k) as JSONObject).get("distance") as JSONObject).get("text") as String Log.e("Step distance: ", distance) duration = ((jSteps.get(k) as JSONObject).get("duration") as JSONObject).get("text") as String Log.e("Step duration: ", duration) start_location_lat = (((jSteps.get(k) as JSONObject).get("start_location") as JSONObject).get("lat") as Double).toString() Log.e("Step duration: ", start_location_lat) start_location_lng = (((jSteps.get(k) as JSONObject).get("start_location") as JSONObject).get("lng") as Double).toString() Log.e("Step duration: ", start_location_lng) Log.e("Step duration2: ", LatLng(start_location_lat.toDouble(),start_location_lng.toDouble()).toString()) travelmode = ((jSteps.get(k) as JSONObject).get("travel_mode")) as String if (travelmode.toUpperCase() == "TRANSIT"){ maneuver = "transit" } else if(travelmode.toUpperCase() == "WALKING"){ maneuver = "walking" stepsList.add(DirectionsStepDbO(count++,maneuver,instructions,"",duration,distance, LatLng(start_location_lat.toDouble(),start_location_lng.toDouble()), TransitDbO("","","","","","",""))) getActivity()!!.runOnUiThread { adapterStepbyStepDirections.notifyDataSetChanged() } } if (travelmode == "TRANSIT"){ departure_stop = (((jSteps.get(k) as JSONObject).get("transit_details") as JSONObject) .get("departure_stop") as JSONObject).get("name") as String departure_time = (((jSteps.get(k) as JSONObject).get("transit_details") as JSONObject) .get("departure_time") as JSONObject).get("text") as String arrival_stop = (((jSteps.get(k) as JSONObject).get("transit_details") as JSONObject) .get("arrival_stop") as JSONObject).get("name") as String arrival_time = (((jSteps.get(k) as JSONObject).get("transit_details") as JSONObject) .get("arrival_time") as JSONObject).get("text") as String line_busname = (((jSteps.get(k) as JSONObject).get("transit_details") as JSONObject) .get("line") as JSONObject).get("name") as String headsign = ((jSteps.get(k) as JSONObject).get("transit_details") as JSONObject) .get("headsign") as String num_stops = (((jSteps.get(k) as JSONObject).get("transit_details") as JSONObject).get("num_stops") as Int).toString() stepsList.add(DirectionsStepDbO(count++,maneuver,instructions,"",duration,distance, LatLng(start_location_lat.toDouble(),start_location_lng.toDouble()), TransitDbO(departure_stop,departure_time,arrival_stop,arrival_time,line_busname,headsign,num_stops))) getActivity()!!.runOnUiThread { adapterStepbyStepDirections.notifyDataSetChanged() } } else if(travelmode == "WALKING"){ //jSteps_child = (((jSteps.get(k) as JSONObject).get("transit_details") as JSONObject) // .get("departure_stop") as JSONObject).get("name") as String jSteps_child = (jSteps.get(k) as JSONObject).getJSONArray("steps") for (m in 0 until jSteps_child.length()) { maneuver_child = if(((jSteps_child.get(m) as JSONObject).has("maneuver")) ){ ((jSteps_child.get(m) as JSONObject).get("maneuver")) as String } else "Head" Log.e("Step maneuver: ", maneuver_child) instructions_child = ((jSteps_child.get(m) as JSONObject).get("html_instructions")) as String Log.e("Step-0 instructions: ", instructions_child) //Divide instructions string to instruction9 & attention var instructions9 = instructions_child var attention = "" // just additional info about that step var flag = false var j = 0 var end = instructions_child.length - 1 while (j <= end){ // if(instructions_child[j] == '<' && instructions_child[j+1] == 'd'){ attention = instructions_child.substring(j,end+1) instructions9 = instructions_child.substring(0,j) Log.e("Step1 instructions9: ", instructions9) Log.e("Step1 attention: ", attention) break } j++ } Log.e("Step1 instructions9: ", instructions9) Log.e("Step1 attention: ", attention) var start = 0 var i = 0 while(i < instructions9.length){ if (instructions9[i] == '<') { start = i } if(instructions9[i] == '&' && instructions9[i+1] == 'a' && instructions9[i+2] == 'm' && instructions9[i+3] == 'p' && instructions9[i+4] == ';') { val first = instructions9.substring(0,i+1) val last = instructions9.substring(i+5,instructions9.length) instructions9 = first + last } if (instructions9[i] == '>') { val first = instructions9.substring(0,start) val last = instructions9.substring(i+1) val newins = first + last instructions9 = newins i=0 start = 0 } i++ } var start2 = 0 var i2 = 0 while(i2 < attention.length){ if (attention[i2] == '&' || attention[i2] == '<') { start2 = i2 } if (attention[i2] == ';' || attention[i2] == '>') { var spot = "" if(attention[i2 - 1] == 'v') spot = ". " val first = attention.substring(0,start2) val last = attention.substring(i2+1) val newins = first + spot + last Log.e("Step last: ", last.toString()) attention = newins i2=0 Log.e("Step ins: ", i2.toString()) start2 = 0 } i2++ } Log.e("Step instructions: ", instructions9) distance_child = ((jSteps_child.get(m) as JSONObject).get("distance") as JSONObject).get("text") as String Log.e("Step distance: ", distance) duration_child = ((jSteps_child.get(m) as JSONObject).get("duration") as JSONObject).get("text") as String Log.e("Step duration: ", duration) start_location_lat = (((jSteps_child.get(m) as JSONObject).get("start_location") as JSONObject).get("lat") as Double).toString() Log.e("Step duration: ", start_location_lat) start_location_lng = (((jSteps_child.get(m) as JSONObject).get("start_location") as JSONObject).get("lng") as Double).toString() Log.e("Step duration: ", start_location_lng) Log.e("Step duration2: ", LatLng(start_location_lat.toDouble(),start_location_lng.toDouble()).toString()) stepsList.add(DirectionsStepDbO(count++,maneuver_child,instructions9,attention,duration_child,distance_child, LatLng(start_location_lat.toDouble(),start_location_lng.toDouble()), TransitDbO("","","","","","",""))) getActivity()!!.runOnUiThread { adapterStepbyStepDirections.notifyDataSetChanged() } } } } } } } catch (e: JSONException) { e.printStackTrace() } catch (e: Exception) { } } fun getCurrentDateTime(): Date { return Calendar.getInstance().time } //Use an intent to launch the autocomplete activity override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { super.onActivityResult(requestCode, resultCode, data) //autocompleteFragment.onActivityResult(requestCode, resultCode, data); if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { val place = PlaceAutocomplete.getPlace(context, data) Log.e(TAG, "Place ID:" + place.id) val placeDB = PlaceEntity() placeDB.name = place.address.toString() /*placeDB.latitude = place.latLng.latitude placeDB.longitude = place.latLng.longitude placeDB.id = place.id*/ edt_orgin.setText(placeDB.name) currentlocation = place.latLng Log.e("nhiet2",place.latLng.toString()) //history object historyDb.address = place.address.toString() historyDb.name = place.name.toString() //historyDb.placeTypes = place.placeTypes.toString() val mGroupId = history_list.push().getKey() historyDb.historyId = mGroupId!! val date = getCurrentDateTime() val minute = String.format("%1\$tH:%1\$tM", date) Log.e("minute:", minute) historyDb.minute = minute //val c = GregorianCalendar(1995, 12, 23) val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) historyDb.date = currenttime Log.e(TAG, "placeTypes:" + place.name.toString()) uploadDatabase() //add to firebase //data for tempplace latitude_temp = place.latLng.latitude longitude_temp = place.latLng.longitude cityname_temp = place.name.toString() placeid_temp = place.id //data for tempfavplace favplaceDb.name = place.name.toString() favplaceDb.placeId = place.id Log.e(TAG, "Image : " + favplaceDb.uri) //address for tempfavplace val geocoder = Geocoder(context!!, Locale.getDefault()) try { val addresses = geocoder.getFromLocation(place.latLng.latitude, place.latLng.longitude, 1) if (addresses != null) { val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } favplaceDb.address = addresses.get(0).getAddressLine(0) // Log.e("start location: ",addresses.get(0).getAddressLine(0)) } else { Log.d("a", "No Address returned! : ") } } catch (e: IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a", "Canont get Address!") } //uploadTempFavPlace() in this getPhoto getPhoto(place.id) uploadTempplace() uploadCitySatistics() } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) { val status = PlaceAutocomplete.getStatus(context, data) Log.e(TAG, ""+status) } else if (resultCode == Activity.RESULT_CANCELED) { } } else if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE2) { if (resultCode == Activity.RESULT_OK) { val place = PlaceAutocomplete.getPlace(context, data) Log.e(TAG, "Place ID:" + place.id) val placeDB = PlaceEntity() placeDB.name = place.address.toString() /*placeDB.latitude = place.latLng.latitude placeDB.longitude = place.latLng.longitude placeDB.id = place.id*/ edt_destination.setText(placeDB.name) destlocation = place.latLng //history object historyDb.address = place.address.toString() historyDb.name = place.name.toString() //historyDb.placeTypes = place.placeTypes.toString() val mGroupId = history_list.push().getKey() historyDb.historyId = mGroupId!! val date = getCurrentDateTime() val minute = String.format("%1\$tH:%1\$tM", date) Log.e("minute:", minute) historyDb.minute = minute //val c = GregorianCalendar(1995, 12, 23) val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) historyDb.date = currenttime Log.e(TAG, "placeTypes:" + place.placeTypes.toString()) uploadDatabase() //add to firebase //data for tempplace latitude_temp = place.latLng.latitude longitude_temp = place.latLng.longitude cityname_temp = place.name.toString() placeid_temp = place.id //data for tempfavplace favplaceDb.name = place.name.toString() favplaceDb.placeId = place.id Log.e(TAG, "Image : " + favplaceDb.uri) //address for tempfavplace val geocoder = Geocoder(context!!, Locale.getDefault()) try { val addresses = geocoder.getFromLocation(place.latLng.latitude, place.latLng.longitude, 1) if (addresses != null) { val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } favplaceDb.address = addresses.get(0).getAddressLine(0) // Log.e("start location: ",addresses.get(0).getAddressLine(0)) } else { Log.d("a", "No Address returned! : ") } } catch (e: IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a", "Canont get Address!") } getPhoto(place.id) uploadTempplace() uploadCitySatistics() } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) { val status = PlaceAutocomplete.getStatus(context, data) Log.e(TAG, ""+status) } else if (resultCode == Activity.RESULT_CANCELED) { } } } var cityname_temp = "" var placename_temp = "" var placeid_temp = "" var latitude_temp = 0.0 var longitude_temp = 0.0 var numofvisit_temp = 0 var uri_temp = "" var newplace_flag = true var runonce_flag = true var curplace_like_beforeplace = false private fun uploadTempplace() { //get city name val geocoder = Geocoder(context!!, Locale.getDefault()) try { val addresses = geocoder.getFromLocation(latitude_temp, longitude_temp, 1) if (addresses != null) { Log.e("start location : ", addresses.toString()) val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") //val strReturnedAddress = StringBuilder() for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } //Log.e("start location : ", addresses.get(0).subAdminArea) if(addresses.get(0).adminArea != null){ cityname_temp = addresses.get(0).adminArea } else { cityname_temp = "" } } else { Log.d("a","No Address returned! : ") } } catch (e:IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a","Canont get Address!") } //end get city name tempplace_list.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Log.e(TAG, "Error : " + p0.message) } override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()) { // code if data exists // if current place like before place for (dsp in dataSnapshot.children) { //add result into array list val item: TempPlaceDbO? = dsp.getValue(TempPlaceDbO::class.java) if (item != null) { var now_cityname = "" //Log.e("Test AI : ",dsp.key) if (dsp.key == mAuth.currentUser!!.uid && item.name == cityname_temp) { curplace_like_beforeplace = true now_cityname = item.name //Log.e("Test AI : ",placeid_temp + item.name + cityname_temp) //break } if ((cityname_temp == item.name || cityname_temp == "Thành phố " + item.name || cityname_temp == "Thủ Đô " + item.name || cityname_temp == "Tỉnh " + item.name)) { if(item.numofask >= 1 && item.numsearch_after_ask >= 4){ tempplaceDb.numofask=item.numofask - 1 tempplaceDb.numsearch_after_ask = 0 } else if(item.numofask >= 2){ tempplaceDb.numsearch_after_ask=item.numsearch_after_ask+1 tempplaceDb.numofask = item.numofask } else { tempplaceDb.numofask = item.numofask tempplaceDb.numsearch_after_ask=item.numsearch_after_ask } //place_list.child(place.id).setValue(placeDB) //tempplaceDb.numofvisit = item.numofvisit+1 tempplaceDb.latitude = item.latitude tempplaceDb.longitude = item.longitude tempplaceDb.name = item.name tempplaceDb.numofsearch = item.numofsearch + 1 tempplaceDb.numofvisit = item.numofvisit tempplaceDb.id = item.id tempplaceDb.askdate = item.askdate tempplace_list.child(item.id).setValue(tempplaceDb) //update dia diem hien tai gan nhat da ghe qua if(curplace_like_beforeplace){ tempplace_list.child(mAuth.currentUser!!.uid).setValue(tempplaceDb) curplace_like_beforeplace = false } newplace_flag = false } } } /*if(!curplace_like_beforeplace) { for (dsp in dataSnapshot.children) { //add result into array list val item: TempPlaceDbO? = dsp.getValue(TempPlaceDbO::class.java) if (item != null) { } } }*/ } else { if(cityname_temp != ""){ // code if data does not exists tempplaceDb.latitude = latitude_temp tempplaceDb.longitude = longitude_temp tempplaceDb.name = cityname_temp tempplaceDb.numofsearch = 1 tempplaceDb.id = placeid_temp val date = getCurrentDateTime() val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) tempplaceDb.askdate = currenttime tempplace_list.child(tempplaceDb.id).setValue(tempplaceDb) //update dia diem hien tai gan nhat da ghe qua if(curplace_like_beforeplace){ tempplace_list.child(mAuth.currentUser!!.uid).setValue(tempplaceDb) curplace_like_beforeplace = false } newplace_flag = false } } if (newplace_flag && cityname_temp != "") { tempplaceDb.latitude = latitude_temp tempplaceDb.longitude = longitude_temp tempplaceDb.name = cityname_temp tempplaceDb.numofsearch = 1 tempplaceDb.id = placeid_temp val date = getCurrentDateTime() val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) tempplaceDb.askdate = currenttime tempplace_list.child(tempplaceDb.id).setValue(tempplaceDb) //update dia diem hien tai gan nhat da ghe qua if(curplace_like_beforeplace){ tempplace_list.child(mAuth.currentUser!!.uid).setValue(tempplaceDb) curplace_like_beforeplace = false } } // Result will be holded Here //insertAllPlace().execute(placeList) } }) } var newfavplace_flag = true private fun uploadTempfavplace() { database = FirebaseDatabase.getInstance() mAuth = FirebaseAuth.getInstance() tempfavplace_list = database.getReference("tempfavplace").child(mAuth.currentUser!!.uid) newfavplace_flag = true //check tempfavplace data to add/update/ask tempfavplace tempfavplace_list.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Log.e(TAG, "Error : " + p0.message) } override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()) { // code if data exists // if current place like before place for (dsp in dataSnapshot.children) { val item: TempFavPlaceDbO? = dsp.getValue(TempFavPlaceDbO::class.java) if (item != null) { //update tempfavplace (number of search + 1) if user searchs there again if (favplaceDb.name == item.name || favplaceDb.placeId == item.id) { if(item.numofask >= 1 && item.numsearch_after_ask >= 2){ tempfavplaceDb.numofask=item.numofask - 1 tempfavplaceDb.numsearch_after_ask = 0 } else if(item.numofask >= 2){ tempfavplaceDb.numsearch_after_ask=item.numsearch_after_ask+1 tempfavplaceDb.numofask = item.numofask } else { tempfavplaceDb.numofask = item.numofask tempfavplaceDb.numsearch_after_ask=item.numsearch_after_ask } //place_list.child(place.id).setValue(placeDB) //tempplaceDb.numofvisit = item.numofvisit+1 tempfavplaceDb.id = item.id //tempfavplaceDb.latitude = item.latitude // tempfavplaceDb.longitude = item.longitude tempfavplaceDb.name = item.name tempfavplaceDb.uri = item.uri tempfavplaceDb.address = item.address tempfavplaceDb.numofsearch = item.numofsearch + 1 tempfavplaceDb.numofvisit = item.numofvisit tempfavplaceDb.askdate = item.askdate tempfavplace_list.child(item.id).setValue(tempfavplaceDb) newfavplace_flag = false } }// } } else { if (favplaceDb.name != "") { // code if data does not exists tempfavplaceDb.address = favplaceDb.address tempfavplaceDb.uri = favplaceDb.uri tempfavplaceDb.name = favplaceDb.name tempfavplaceDb.numofsearch = 1 tempfavplaceDb.id = favplaceDb.placeId val date = getCurrentDateTime() val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) tempfavplaceDb.askdate = currenttime tempfavplace_list.child(tempfavplaceDb.id).setValue(tempfavplaceDb) newplace_flag = false } } if (newfavplace_flag && favplaceDb.name != "") { tempfavplaceDb.address = favplaceDb.address tempfavplaceDb.uri = favplaceDb.uri tempfavplaceDb.name = favplaceDb.name tempfavplaceDb.numofsearch = 1 tempfavplaceDb.id = favplaceDb.placeId val date = getCurrentDateTime() val currenttime = String.format("%1\$td/%1\$tm/%1\$tY", date) tempfavplaceDb.askdate = currenttime tempfavplace_list.child(tempfavplaceDb.id).setValue(tempfavplaceDb) } // Result will be holded Here //insertAllPlace().execute(placeList) } }) } var citysatistics_flag = true private fun uploadCitySatistics() { //get city name val geocoder = Geocoder(context!!, Locale.getDefault()) try { val addresses = geocoder.getFromLocation(latitude_temp, longitude_temp, 1) if (addresses != null) { Log.e("start location : ", addresses.toString()) val returnedAddress = addresses.get(0) val strReturnedAddress = StringBuilder("Address:\n") //val strReturnedAddress = StringBuilder() for (i in 0 until returnedAddress.getMaxAddressLineIndex()) { strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n") } //Log.e("start location : ", addresses.get(0).subAdminArea) if(addresses.get(0).adminArea != null){ cityname_temp = addresses.get(0).adminArea } else { cityname_temp = "" } Log.e("c location2: ",cityname_temp) } else { Log.d("a","No Address returned! : ") } } catch (e:IOException) { // TODO Auto-generated catch block e.printStackTrace() Log.d("a","Canont get Address!") } //end get city name city_statistics.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Log.e(TAG, "Error : " + p0.message) } var numofsearch_others = 0 override fun onDataChange(dataSnapshot: DataSnapshot) { if (dataSnapshot.exists()) { // code if data exists // if current place like before place for (dsp in dataSnapshot.children) { //add result into array list val item: CitySatisticsDbO? = dsp.getValue(CitySatisticsDbO::class.java) if (item != null) { if(item.name == "Others") numofsearch_others = item.numofsearch if ((cityname_temp == item.name || cityname_temp == "Thành phố " + item.name || cityname_temp == "<NAME> " + item.name || cityname_temp == "Tỉnh " + item.name)) { Log.e("lamquanglich : ",dsp.key) city_statistics.child(dsp.key!!).setValue(CitySatisticsDbO(item.name,item.numofsearch+1)) citysatistics_flag = false } } } } else { // code if data does not exists if(cityname_temp != ""){ if((cityname_temp.toLowerCase() == "hồ chí minh" || cityname_temp == "thành phố hồ chí minh") || (cityname_temp.toLowerCase() == "hà nội" || cityname_temp == "thủ đô hà nội") || (cityname_temp.toLowerCase() == "đà nẵng" || cityname_temp == "thành phố đà nẵng") || (cityname_temp.toLowerCase() == "cần thơ" || cityname_temp == "thành phố cần thơ") ){ city_statistics.push().setValue(CitySatisticsDbO(cityname_temp,1)) } else { city_statistics.child("-Li261TH2CuzJV9lyWvM").setValue(CitySatisticsDbO("Others",numofsearch_others+1)) } citysatistics_flag = false } } if (citysatistics_flag && cityname_temp != "") { if((cityname_temp.toLowerCase() == "hồ chí minh" || cityname_temp == "thành phố hồ chí minh") || (cityname_temp.toLowerCase() == "hà nội" || cityname_temp == "thủ đô hà nội") || (cityname_temp.toLowerCase() == "đà nẵng" || cityname_temp == "thành phố đà nẵng") || (cityname_temp.toLowerCase() == "cần thơ" || cityname_temp == "thành phố cần thơ") ){ city_statistics.push().setValue(CitySatisticsDbO(cityname_temp,1)) } else { city_statistics.child("-Li261TH2CuzJV9lyWvM").setValue(CitySatisticsDbO("Others",numofsearch_others+1)) } } } }) } private fun getPhoto(placeId: String) { //val placeId = "ChIJa147K9HX3IAR-lwiGIQv9i4" val mGeoDataClient = Places.getGeoDataClient(this.context!!) val photoMetadataResponse = mGeoDataClient.getPlacePhotos(placeId) photoMetadataResponse.addOnCompleteListener(OnCompleteListener<PlacePhotoMetadataResponse> { task -> // Get the list of photos. val photos = task.result // Get the PlacePhotoMetadataBuffer (metadata for all of the photos). val photoMetadataBuffer = photos.photoMetadata // Get the first photo in the list. val photoMetadata = photoMetadataBuffer.get(0) // Get a full-size bitmap for the photo. val photoResponse = mGeoDataClient.getPhoto(photoMetadata) //Listener Event compeleted itselt, update to firebase's storage photoResponse.addOnCompleteListener(OnCompleteListener<PlacePhotoResponse> { task -> val photo = task.result val bitmap = photo.bitmap upLoadBitmapToStorage(bitmap) }) }) } //Add that place's photos to storage & that place to firebase private fun upLoadBitmapToStorage(bitmap: Bitmap) { val storage = FirebaseStorage.getInstance() val storageReference = storage.getReference("images") val imageName = UUID.randomUUID().toString() val imageFolder = storageReference.child(imageName) val baos = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos) val data = baos.toByteArray() val uploadTask = imageFolder.putBytes(data) //after add photos to storage, update that place's uri to placeDb -> add to firebase by uploadDatabase() uploadTask.addOnFailureListener(OnFailureListener { // Handle unsuccessful uploads }).addOnSuccessListener(OnSuccessListener<Any> { taskSnapshot -> // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL. imageFolder.downloadUrl.addOnSuccessListener { Log.e(TAG, "Image : " + it.toString()) favplaceDb.uri = it.toString() uploadTempfavplace() } }) } // Fetches data from url passed private inner class FetchUrl(transkind: String) :AsyncTask<String, Void, String>() { override fun doInBackground(vararg url:String):String { Log.d("FetchUrl doInBackground", "vô nè") // For storing data from web service var data = "" try { // Fetching the data from web service data = downloadUrl(url[0]) Log.d("Background Task data", data) } catch (e:Exception) { Log.d("Background Task", e.toString()) } return data } val transKind = transkind override fun onPostExecute(result:String) { Log.d("onPostExecue resute", result) super.onPostExecute(result) val parserTask = ParserTask(transKind,false,true) // Invokes the thread for parsing the JSON data parserTask.execute(result) } } private inner class FetchUrl_ClickonRecycler(transkind: String) :AsyncTask<String, Void, String>() { override fun doInBackground(vararg url:String):String { Log.d("FetchUrl doInBackground", "vô nè") // For storing data from web service var data = "" try { // Fetching the data from web service data = downloadUrl(url[0]) Log.d("Background Task data", data) } catch (e:Exception) { Log.d("Background Task", e.toString()) } return data } val transKind = transkind override fun onPostExecute(result:String) { Log.d("onPostExecue resute", result) super.onPostExecute(result) val parserTask = ParserTask(transKind,true,true) // Invokes the thread for parsing the JSON data parserTask.execute(result) } } private inner class FetchUrl_NotPolyline(transkind: String) :AsyncTask<String, Void, String>() { override fun doInBackground(vararg url:String):String { Log.d("FetchUrl doInBackground", "vô nè") // For storing data from web service var data = "" try { // Fetching the data from web service data = downloadUrl(url[0]) Log.d("Background Task data", data) } catch (e:Exception) { Log.d("Background Task", e.toString()) } return data } val transKind = transkind override fun onPostExecute(result:String) { Log.d("onPostExecue resute", result) super.onPostExecute(result) val parserTask = ParserTask(transKind,true,false) // Invokes the thread for parsing the JSON data parserTask.execute(result) } } /** * A method to download json data from url */ @Throws(IOException::class) private fun downloadUrl(strUrl: String): String { Log.d("downloadUrl", "vô nè") var data = "" var iStream: InputStream? = null var urlConnection: HttpURLConnection? = null try { Log.d("downloadUrl try", "vô nè") val url = URL(strUrl) // Creating an http connection to communicate with url urlConnection = url.openConnection() as HttpURLConnection Log.d("url connection: ", urlConnection.toString()) // Connecting to url urlConnection.connect() // Reading data from url iStream = urlConnection.inputStream Log.d("iStream: ", iStream.toString()) data = iStream.bufferedReader().use(BufferedReader::readText) /*val br = BufferedReader(InputStreamReader(iStream)) //val br = BufferedReader(InputStreamReader(iStream!!)) val sb = StringBuffer() var line = "" while(line !=null){ line = br.readLine() //readLine() read data from file of BufferedReader sb.append(line) } data = sb.toString() Log.d("downloadUrl sb data= ", data.toString())*/ //br.close() } catch (e: Exception) { Log.d("Exception downloadUrl", e.toString()) } finally { iStream!!.close() urlConnection!!.disconnect() } return data } /** * A class to parse the Google Places in JSON format */ private inner class ParserTask(transkind: String, click_rv_trans: Boolean, draw_polyline: Boolean) : AsyncTask<String, Int, List<List<HashMap<String, String>>>>() { val transKind = transkind val click_rv_Trans = click_rv_trans val draw_Polyline = draw_polyline // Parsing the data in non-ui thread @RequiresApi(Build.VERSION_CODES.M) override fun doInBackground(vararg jsonData: String): List<List<HashMap<String, String>>> { val jObject: JSONObject? try { jObject = JSONObject(jsonData[0]) Log.d("ParserTask", jsonData[0]) val parser = DataParser() if(transKind == "transit") { StepByStep_Transit(jObject) } else StepByStep(jObject) Log.d("ParserTask", parser.toString()) // Starts parsing data val routes: List<List<HashMap<String, String>>> = parser.parse(jObject) //parse2: get duration of this all route val duration: String = parser.parse2(jObject)!! Log.d("ParaserTask", "Executing routes") Log.d("ParserTask", routes.toString()) if(click_rv_Trans == false){ ///Add transportations's duration on rv_transportation transList.clear() when (transKind) { "driving" -> { transList.add(TransportationDbO("driving",duration)) } "walking" -> { transList.add(TransportationDbO("walking",duration)) } "transit" -> { transList.add(TransportationDbO("transit",duration)) } } //Error: Only the original thread that created a view hierarchy can touch its views. //If it ain't runOnUiThread, this command know it's running on ParserTask(), not DirectionsActiivty //But, adapterTransportation setted on DirectionsFragment, So this is solution getActivity()!!.runOnUiThread { adapterTransportation.notifyDataSetChanged() } } else if(draw_Polyline == false){ when (transKind) { "driving" -> { transList.add(TransportationDbO("driving",duration)) } "walking" -> { transList.add(TransportationDbO("walking",duration)) } "transit" -> { transList.add(TransportationDbO("transit",duration)) } } //Error: Only the original thread that created a view hierarchy can touch its views. //If it ain't runOnUiThread, this command know it's running on ParserTask(), not DirectionsActiivty //But, adapterTransportation setted on DirectionsFragment, So this is solution getActivity()!!.runOnUiThread { adapterTransportation.notifyDataSetChanged() } } return routes } catch (e: Exception) { Log.d("ParserTask", e.toString()) e.printStackTrace() } val r:List<List<HashMap<String, String>>> = ArrayList<ArrayList<HashMap<String, String>>>() return r } // Executes in UI thread, after the parsing process override fun onPostExecute(result: List<List<HashMap<String, String>>>) { if(draw_Polyline == true) { var points: ArrayList<LatLng> var lineOptions: PolylineOptions? = null // Traversing through all the routes for (i in result.indices) { points = ArrayList<LatLng>() lineOptions = PolylineOptions() // Fetching i-th route val path = result[i] // Fetching all the points in i-th route for (j in path.indices) { val point = path[j] val lat = java.lang.Double.parseDouble(point["lat"]) val lng = java.lang.Double.parseDouble(point["lng"]) val position = LatLng(lat, lng) points.add(position) } // Adding all the points in the route to LineOptions lineOptions.addAll(points) lineOptions.width(12f) lineOptions.color(Color.rgb(70, 155, 253)) Log.d("onPostExecute", "onPostExecute lineoptions decoded") } // Drawing polyline in the Google Map for the i-th route if (lineOptions != null) { mMap.clear() AddMarker(currentlocation, destlocation) mMap.addPolyline(lineOptions) } else { Log.d("onPostExecute", "without Polylines drawn") } } } } private fun uploadDatabase() { history_list.child(myuser!!.uid).push().setValue(historyDb) } private fun setupGoogleMapScreenSettings(mMap:GoogleMap) { mMap.isBuildingsEnabled = true //Turns the 3D buildings layer on mMap.isIndoorEnabled = true //Sets whether indoor maps should be enabled. //mMap.isTrafficEnabled = true //Turns the traffic layer on or off. mMap.mapType = GoogleMap.MAP_TYPE_NORMAL val mUiSettings = mMap.uiSettings //mUiSettings.isZoomControlsEnabled = true //it can be zoom control mUiSettings.isCompassEnabled = true //....compass (la ban) mUiSettings.isMyLocationButtonEnabled = true //Enables or disables the my-location layer. mUiSettings.isScrollGesturesEnabled = true //....cử chỉ scroll mUiSettings.isZoomGesturesEnabled = true //...zoom mUiSettings.isTiltGesturesEnabled = true //...Tilt (nghiêng) mUiSettings.isRotateGesturesEnabled = true //...Rotate mUiSettings.isMapToolbarEnabled = true // It ain't working, CHECKKKKKK } @Synchronized private fun buildGoogleApiClient() { mGoogleApiClient = GoogleApiClient.Builder(context!!) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build() mGoogleApiClient.connect() } override fun onConnected(bundle:Bundle?) { mLocationRequest = LocationRequest() mLocationRequest.interval = 1000 mLocationRequest.fastestInterval = 1000 mLocationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY if ((ContextCompat.checkSelfPermission(context!!, Manifest.permission.ACCESS_FINE_LOCATION) === PackageManager.PERMISSION_GRANTED)) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this) } } override fun onConnectionSuspended(i:Int) { } var currentLocation_latLng: LatLng = LatLng(10.762622, 106.660172) override fun onLocationChanged(location:Location) { mLastLocation = location if (mCurrLocationMarker != null) { mCurrLocationMarker!!.remove() } //Place current location marker val latLng = LatLng(location.latitude, location.longitude) currentLocation_latLng = latLng val markerOptions = MarkerOptions() markerOptions.position(latLng) markerOptions.title("Current Position") markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)) mCurrLocationMarker = mMap.addMarker(markerOptions) //move map camera mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)) mMap.animateCamera(CameraUpdateFactory.zoomTo(11F)) //stop location updates if (mGoogleApiClient != null) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this) } } override fun onConnectionFailed(connectionResult:ConnectionResult) { } private fun checkLocationPermission():Boolean { if ((ContextCompat.checkSelfPermission(context!!, Manifest.permission.ACCESS_FINE_LOCATION) !== PackageManager.PERMISSION_GRANTED)) { // Asking user if explanation is needed if (ActivityCompat.shouldShowRequestPermissionRationale(this.activity!!, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(this.activity!!, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), MY_PERMISSIONS_REQUEST_LOCATION) } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this.activity!!, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), MY_PERMISSIONS_REQUEST_LOCATION) } return false } else { return true } } override fun onRequestPermissionsResult(requestCode:Int, permissions:Array<String>, grantResults:IntArray) { when (requestCode) { MY_PERMISSIONS_REQUEST_LOCATION -> { // If request is cancelled, the result arrays are empty. if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { // permission was granted. Do the // contacts-related task you need to do. if ((ContextCompat.checkSelfPermission(context!!, Manifest.permission.ACCESS_FINE_LOCATION) === PackageManager.PERMISSION_GRANTED)) { if (mGoogleApiClient == null) { buildGoogleApiClient() } mMap.isMyLocationEnabled = true } } else { // Permission denied, Disable the functionality that depends on this permission. Toast.makeText(this.context, "permission denied", Toast.LENGTH_LONG).show() } return } }// other 'case' lines to check for other permissions this app might request. // You can add here other case statements according to your requirement. } companion object { val MY_PERMISSIONS_REQUEST_LOCATION = 99 fun newInstance(latLng_toDirection: String): DirectionsFragment{ val args = Bundle() args.putString("MyLatLng", latLng_toDirection) val fragment = DirectionsFragment() fragment.arguments = args return fragment } } } class SmoothLinearLayoutManager : LinearLayoutManager { private val millisecondsPreInch = 45f //default is 25f (bigger = slower) constructor(context: Context) : super(context, LinearLayoutManager.VERTICAL, false) constructor(context: Context, orientation: Int, reverseLayout: Boolean) : super(context, orientation, reverseLayout) override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State?, position: Int) { val smoothScroller = SmoothScroller(recyclerView.context) smoothScroller.targetPosition = position startSmoothScroll(smoothScroller) } private inner class SmoothScroller(context: Context) : LinearSmoothScroller(context) { override fun computeScrollVectorForPosition(targetPosition: Int): PointF? { return this@SmoothLinearLayoutManager.computeScrollVectorForPosition(targetPosition) } override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?): Float { displayMetrics?.densityDpi?.let { return millisecondsPreInch / it } return super.calculateSpeedPerPixel(displayMetrics) } } }<file_sep>package com.horus.travelweather.model data class CloudsItem (val all:Double = 0.0)
0ddb1ea839780b659e7042274376ea7326149f5a
[ "Kotlin", "Gradle" ]
49
Kotlin
QuangTrungK15/TravelWeather
344c7380766ec8aab5a95917de9bd6c2b2085cf5
49f82bcff4db0573c12575f5f3b3622831a45ed2
refs/heads/master
<file_sep> CWD=`pwd` help: @echo "USAGE:" @echo "make update Updates all of the submodules within the project" @echo "make clean Cleans out all of the generated code within a submodule (mainly docs/tags)" @echo "make add_bundle name=<bundle-name> Symlinks a bundle from bundle_storage to the bundle directory" @echo "make add_snippet name=<snippet-name> Symlinks a snippet from snippet_storage to the snippet directory" @echo "make remove_bundle name=<bundle-name> Removes a bundle symlink from the bundle directory" @echo "make remove_snippet name=<snippet-name> Removes a snippet symlink from the snippet directory" @echo "make install Installs the default set up of Bit Theory's Vim configuration" @echo "make themes Copies the themes directory of Terminal themes to the User's Desktop" update: @git submodule foreach git checkout master @git submodule foreach git clean -f @git submodule foreach git pull --rebase @git status clean: @git submodule foreach git checkout master @git submodule foreach git clean -f @git status add_bundle: @ln -sv $(CWD)/home/.vim/bundle_storage/$(name) $(CWD)/home/.vim/bundle/$(name) add_snippet: @ln -sv $(CWD)/home/.vim/snippets_storage/$(name).snippets $(CWD)/home/.vim/snippets/$(name).snippets remove_bundle: @echo "The remove_bundle task has not been setup" remove_snippet: @rm -v $(CWD)/home/.vim/snippets/$(name).snippets install: themes @./install themes: @cp -rv themes $(HOME)/Desktop/ .PHONY: help update clean add_bundle add_snippet remove_bundle remove_snippet install themes <file_sep>#!/bin/bash default_bundles=( ack.vim actionscript.vim applescript.vim browser-refresh.vim cocoa.vim coffeescript.vim cucumber.vim delimitMate.vim fugitive.vim gist.vim haml.vim html5.vim indexed-search.vim jade.vim javascript.vim json.vim markdown-preview.vim markdown.vim mustache.vim nerdcommenter.vim nerdtree.vim processing.vim rails.vim repeat.vim ruby.vim rvm.vim snipmate.vim statline.vim stylus.vim supertab.vim surround.vim syntastic.vim tabular.vim taglist.vim unimpaired.vim yankring.vim ) CWD=`pwd` echo "Creating directories..." mkdir -p $CWD/home/.vim/bundle mkdir -p $CWD/home/.vim/snippets mkdir -p $CWD/home/.vim/spell mkdir -p $CWD/home/.vim/tmp/swap mkdir -p $CWD/home/.vim/tmp/yankring # Only create the .vimrc.local file if it doesn't exist if [ -e "${HOME}/.vimrc.local" ] then echo "${HOME}/.vimrc.local already exists, not overwriting" else echo "Setting up default vimrc.local..." cp $CWD/templates/.vimrc.local.example $CWD/home/.vimrc.local fi echo "Initializing submodules..." git submodule init git submodule update git submodule foreach git checkout master git submodule foreach git clean -f echo "Symlinking default bundles..." for i in "${default_bundles[@]}"; do ln -sv $CWD/home/.vim/bundle_storage/$i $CWD/home/.vim/bundle/$i done echo "Symlinking default snippets..." for f in `ls $CWD/home/.vim/snippets_storage/`; do ln -sv $CWD/home/.vim/snippets_storage/$f $CWD/home/.vim/snippets/$f done # Make an additional symlink of css for scss ln -sv $CWD/home/.vim/snippets_storage/css.snippets $CWD/home/.vim/snippets/scss.snippets echo "--------------------------------------------------" echo "*** Install Complete ***" echo "--------------------------------------------------" echo "Run the following command to symlink your castle:" echo "homesick symlink ${PWD##*/}" echo "--------------------------------------------------"
fb3ca0dbf1dc694080d669b68097f63bca9bf97d
[ "Makefile", "Shell" ]
2
Makefile
tumes/vimfiles
becfa3103ee837570f1d50749df290da859dcbaa
065f3af95fabb1632068b4d878b334de67260685
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { ServiceService } from '../../services/service.service'; @Component({ selector: 'app-info', templateUrl: './info.component.html', styleUrls: ['./info.component.css'] // tslint:disable-next-line:use-input-property-decorator }) export class InfoComponent implements OnInit { cName = 'India'; cCapital = 'Delhi'; cSubregion = 'Indian Ocean'; cPopulation = 2000000; cRegion = 'Asia'; cArea = '22,999,000 KM'; cCurrency = 'Rupee'; cSymbol = '$'; data: any; constructor(private sharing: ServiceService) { } ngOnInit() { this.data = this.sharing.getData(); } } <file_sep>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; import { RouterModule, Routes } from '@angular/router'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { FilterPipeModule } from 'ngx-filter-pipe'; import { CountriesComponent } from './components/countries/countries.component'; import { InfoComponent } from './components/info/info.component'; import { ServiceService } from './services/service.service'; import { NavbarComponent } from './components/navbar/navbar.component'; import { FavoritesComponent } from './components/favorites/favorites.component'; const appRoutes: Routes = [ { path: 'countries', component: CountriesComponent}, { path: 'countries/info', component: InfoComponent}, { path: 'favorites', component: FavoritesComponent}, { path: '', redirectTo: '/countries', pathMatch: 'full'}, { path: '**', redirectTo: '/countries', pathMatch: 'full'}]; @NgModule({ declarations: [ AppComponent, CountriesComponent, InfoComponent, NavbarComponent, FavoritesComponent ], imports: [ BrowserModule, FilterPipeModule, // Ng2SearchPipeModule, HttpClientModule, FormsModule, RouterModule.forRoot( appRoutes )], providers: [ServiceService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-favorites', templateUrl: './favorites.component.html', styleUrls: ['./favorites.component.css'] }) export class FavoritesComponent implements OnInit { favorites: any; constructor(private http: HttpClient) { } ngOnInit() { this.http.get('http://localhost:3000/favorites/get-favorites') .subscribe((data) => { // console.log(data); this.favorites = data; }); } onFilterChange(country) { // console.log(country); this.http.post('http://localhost:3000/favorites/add-favorites', {country}) .subscribe( res => { // console.log(res); }, err => { console.log('Error occured'); } ); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import {Router} from '@angular/router'; import { ServiceService } from '../../services/service.service'; @Component({ selector: 'app-countries', templateUrl: './countries.component.html', styleUrls: ['./countries.component.css'] }) export class CountriesComponent implements OnInit { title = 'angular-four'; countries: {}; userFilter: any = { name: '', region: '' }; constructor(private http: HttpClient, private router: Router, private sharing: ServiceService) { // tslint:disable-next-line:prefer-const this.http.get('http://localhost:3000/favorites/get-countries') .subscribe((data) => { // console.log(JSON.stringify(data)); this.countries = data; }); } ngOnInit() { } clickCountry(country) { const code = country.alpha3Code; this.http.get('https://restcountries.eu/rest/v2/alpha/' + code + '?fullText=true') .subscribe((oneCountry) => { this.sharing.setData(country); this.router.navigate(['/countries/info'], code); }); } onFilterChange(country) { // console.log(country); this.http.post('http://localhost:3000/favorites/add-favorites', {country}) .subscribe( res => { // console.log(res); }, err => { // console.log('Error occured'); } ); } } // https://restcountries.eu/rest/v2/all // http://localhost:3000/favorites/get-countries
3f4d1593dbc87cd47724fe3cd30856ba314bbcde
[ "TypeScript" ]
4
TypeScript
sanketkarandikar/angular4FrontEnd
028b77eb6a36a1bbc5848ea38d6b85ddf49525f6
ac868d79193af7d8b6487754f9293a0b668aad76
refs/heads/master
<file_sep>package com.bbs; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.ServerResponse.ok; @Configuration public class StaticContentConfig { // https://www.logicbig.com/tutorials/spring-framework/spring-boot/boot-serve-static.html // https://www.baeldung.com/spring-webflux-static-content @Bean public RouterFunction<ServerResponse> htmlRouter(@Value("classpath:/static/index.html") Resource html) { return route( GET("/"), request -> ok() .contentType(MediaType.TEXT_HTML) .syncBody(html) ); } @Bean public RouterFunction<ServerResponse> allRouter() { return RouterFunctions.resources("/**", new ClassPathResource("static/")); } }<file_sep>package com.bbs.communityapi.service; import com.bbs.communityapi.model.Community; import com.bbs.communityapi.model.repository.CommunityRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Service public class CommunityService implements ICommunityService{ @Autowired CommunityRepository communityRepository; public void create(Community e) { communityRepository.save(e).subscribe(); } public Mono<Community> findById(String id) { return communityRepository.findById(id); } public Flux<Community> findAll() { return communityRepository.findAll(); } public Mono<Community> update(Community u) { return communityRepository.save(u); } public Mono<Void> delete(String id) { return communityRepository.deleteById(id); } } <file_sep>package com.bbs.userapi.controller; import com.bbs.userapi.model.User; import com.bbs.userapi.security.JWTUtil; import com.bbs.userapi.security.PBKDF2Encoder; import com.bbs.userapi.security.model.AuthRequest; import com.bbs.userapi.security.model.AuthResponse; import com.bbs.userapi.security.model.Role; import com.bbs.userapi.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; import java.util.Arrays; @RestController public class AuthenticationController { // can not be done without // https://medium.com/@ard333/authentication-and-authorization-using-jwt-on-spring-webflux-29b81f813e78 @Autowired private JWTUtil jwtUtil; @Autowired private PBKDF2Encoder passwordEncoder; @Autowired private UserService userRepository; @RequestMapping(value = "/login", method = RequestMethod.POST) public Mono<ResponseEntity<?>> login(@RequestBody AuthRequest ar) { return userRepository.findByUsername(ar.getUsername()).map((userDetails) -> { if (passwordEncoder.encode(ar.getPassword()).equals(userDetails.getPassword())) { return ResponseEntity.ok(new AuthResponse(jwtUtil.generateToken(userDetails))); } else { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } }).defaultIfEmpty(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build()); } @RequestMapping(value = "/signup", method = RequestMethod.POST) public Mono<ResponseEntity<Object>> signup(@RequestBody AuthRequest ar) { // Just remember my whole afternoon and night // https://stackoverflow.com/questions/54554581/spring-webflux-how-to-get-data-from-request // https://stackoverflow.com/questions/52491405/how-to-combine-flux-and-responseentity-in-spring-webflux-controllers return userRepository.findByUsername(ar.getUsername()) .map((userDetails) -> new ResponseEntity<Object>(HttpStatus.CONFLICT)) .switchIfEmpty(Mono .just(new User( ar.getUsername(), passwordEncoder.encode(ar.getPassword()), null, false, true, Arrays.asList(Role.ROLE_USER))) .flatMap(user -> userRepository.create(user)) .map(user -> ResponseEntity.status(HttpStatus.CREATED).build()) ); } }<file_sep>package com.bbs.postapi.service; import com.bbs.postapi.model.Post; import com.bbs.postapi.model.repository.PostRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Service public class PostService implements IPostService { @Autowired PostRepository postRepository; public void create(Post e) { postRepository.save(e).subscribe(); } public Mono<Post> findById(String id) { return postRepository.findById(id); } public Flux<Post> findAll() { return postRepository.findAll(); } public Mono<Post> update(Post u) { return postRepository.save(u); } public Mono<Void> delete(String id) { return postRepository.deleteById(id); } } <file_sep>package com.bbs.postapi.service; import com.bbs.postapi.model.Post; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public interface IPostService { void create(Post e); Mono<Post> findById(String id); Flux<Post> findAll(); Mono<Post> update(Post e); Mono<Void> delete(String id); } <file_sep>package com.bbs.postapi.exception; public class UserIdNotMatchException extends Exception { public UserIdNotMatchException() { } public UserIdNotMatchException(String message) { super(message); } }<file_sep>rootProject.name = 'DXW_BBS' <file_sep>package com.bbs.userapi.service; import com.bbs.userapi.model.User; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public interface IUserService { Mono<User> create(User e); Mono<User> findById(String id); Mono<User> findByUsername(String username); Flux<User> findByLikeUsername(String username); Flux<User> findAll(); Mono<User> update(User e); Mono<Void> delete(String id); } <file_sep>package com.bbs.userapi.security; import com.bbs.userapi.security.model.Role; import io.jsonwebtoken.Claims; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @Component public class AuthenticationManager implements ReactiveAuthenticationManager { @Autowired private JWTUtil jwtUtil; @Override @SuppressWarnings("unchecked") public Mono<Authentication> authenticate(Authentication authentication) { String authToken = authentication.getCredentials().toString(); String username; try { username = jwtUtil.getUsernameFromToken(authToken); } catch (Exception e) { username = null; } if (username != null && jwtUtil.validateToken(authToken)) { Claims claims = jwtUtil.getAllClaimsFromToken(authToken); List<String> rolesMap = claims.get("role", List.class); List<Role> roles = new ArrayList<>(); for (String rolemap : rolesMap) { roles.add(Role.valueOf(rolemap)); } UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken( username, null, roles.stream().map(authority -> new SimpleGrantedAuthority(authority.name())).collect(Collectors.toList()) ); return Mono.just(auth); } else { return Mono.empty(); } } }<file_sep>package com.bbs.userapi.security; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.Base64; @Component public class PBKDF2Encoder implements PasswordEncoder { @Value("${springbootwebfluxjjwt.password.encoder.secret}") private String secret; @Value("${springbootwebfluxjjwt.password.encoder.iteration}") private Integer iteration; @Value("${springbootwebfluxjjwt.password.encoder.keylength}") private Integer keylength; /** * More info (https://www.owasp.org/index.php/Hashing_Java) * * @param cs password * @return encoded password */ @Override public String encode(CharSequence cs) { try { byte[] result = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512") .generateSecret(new PBEKeySpec(cs.toString().toCharArray(), secret.getBytes(), iteration, keylength)) .getEncoded(); return Base64.getEncoder().encodeToString(result); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { throw new RuntimeException(ex); } } @Override public boolean matches(CharSequence cs, String string) { return encode(cs).equals(string); } }<file_sep># 前端 https://github.com/Frozen-Troll/bbs # API 请自行替换 `http://127.0.0.1:8080` ## 注册 URL|method|header|body example -|-|-|- http://127.0.0.1:8080/signup|POST|Content-Type: application/json|{"username": "test","password": "<PASSWORD>"} ### 返回 Status|HTTP Status Code -|-| 成功注册|201 重复注册|409 ## 登录 URL|method|header|body example -|-|-|- http://127.0.0.1:8080/login|POST|Content-Type: application/json|{"username": "test","password": "<PASSWORD>"} ### 返回 Status|HTTP Status Code|HTTP Responses example -|-|-| 登录成功|201|{"token": "$TOKEN"} 登录失败|401|- ## 获取所有版块 URL|method -|-| http://127.0.0.1:8080/communities|GET| ### 返回举例 ``` data:{"id":"5cb1f17c80a35f37407791ee","name":"main","visibility":true,"managers":["admin"]} data:{"id":"5cb6a063bf94d44e7420aee4","name":"test","visibility":true,"managers":["admin"]} ``` Key|Value -|- id|版块 ID name|版块名 visibility|是否可见 managers|管理员 ## 创建版块 URL|method|header|body example -|-|-|- http://127.0.0.1:8080/communities|POST|Content-Type: application/json Authorization: Bearer $TOKEN|{"name":"test","managers":["admin"]} ### 返回 Status|HTTP Status Code|HTTP Responses example -|-|-| 创建成功|201|{"id":"5cb6a438bf94d44e7420aeea","name":"test","visibility":true,"managers":["admin"]} 创建失败|401|- 返回的数据结构和获取版块的一样 注:创建版块一定要管理员权限,其中`$TOKEN` 为管理员用户登录成功时的返回 ## 修改版块属性 URL|method|header|body example -|-|-|- http://127.0.0.1:8080/communities/$ID|PUT|Content-Type: application/json Authorization: Bearer $TOKEN|{"visibility":true,"managers":["user","admin"]} 注:其中`$ID`为版块 ID,`$TOKEN`为管理员用户登录成功时的返回 ### 返回 Status|HTTP Status Code|HTTP Responses example -|-|-| 修改成功|200|{"id":"5cb6a1b8bf94d44e7420aee9","name":"test","visibility":true,"managers":["admin","user"]} 修改失败|401|- ## 查看某版块的所有贴子 URL|method|说明 -|-|-| http://127.0.0.1:8080/posts?community=$ID|GET|获取非置顶贴 http://127.0.0.1:8080/posts/top?community=$ID|GET|获取置顶贴 可选参数 `page`,获取指定页数 注:其中`$ID`为版块 ID ### 返回举例 ``` data:{"id":"5cb6d920bf94d463b0ec270e","author":"user","content":"first post","parentId":null,"community":"5cb1f17c80a35f37407791ee","top":false,"deleted":false,"initTime":[2019,4,17,15,43,28,209000000],"lastUpdateTime":[2019,4,17,15,43,28,209000000],"title":"first post"} data:{"id":"5cb6d920bf94d463b0ec2712","author":"user","content":"second post","parentId":null,"community":"5cb1f17c80a35f37407791ee","top":false,"deleted":false,"initTime":[2019,4,17,15,43,28,237000000],"lastUpdateTime":[2019,4,17,15,43,28,237000000],"title":"second post"} ``` Key|Value -|- id|贴子 ID author|作者 content|内容 parentId|主贴 community|版块 ID top|是否置顶 deleted|是否已被删除 initTime|创建时间 lastUpdateTime|最近发帖时间 title|标题 ## 发帖 URL|method|header|body example -|-|-|- http://127.0.0.1:8080/posts|POST|Content-Type: application/json Authorization: Bearer $TOKEN|{"title":"$Title","content":"$String","community":"$CID"} 注:其中 `$ID` 为所要跟贴的 ID,`$Title` 为贴子标题,`$String` 为贴子内容,`$CID` 为版块 ID ### 返回 Status|HTTP Status Code|HTTP Responses example -|-|-| 发帖成功|201|{"id":"5cb6eec0bf94d4625804f2c1","author":"admin","content":"something","parentId":null,"community":"5cb1f17c80a35f37407791ee","top":false,"deleted":false,"initTime":[2019,4,17,17,15,44,177000000],"lastUpdateTime":[2019,4,17,17,15,44,177000000],"title":"Title"} 发帖失败|401|- ## 删帖 URL|method|header -|-|-| http://127.0.0.1:8080/posts/$ID|DEL|Authorization: Bearer $TOKEN 注:其中`$ID`为贴子 ID, 其中`$TOKEN` 为用户登录成功时的返回 ### 返回 Status|HTTP Status Code|HTTP Responses example -|-|-| 删除成功|200|{"id":"5cb6d920bf94d463b0ec2712","author":"user","content":"second post","parentId":null,"community":"5cb1f17c80a35f37407791ee","top":false,"deleted":true,"initTime":[2019,4,17,15,43,28,237000000],"lastUpdateTime":[2019,4,17,15,43,28,237000000],"title":"second post"} 无权限删除|401|- 找不到贴子|400|- ## 查看某个贴子 URL|method -|-| http://127.0.0.1:8080/posts/$ID|GET| 可选参数 `page`,获取指定页数 注:其中`$ID`为贴子 ID ### 返回举例 ``` data:{"id":"5cb6d920bf94d463b0ec270f","author":"user","content":"first comment","parentId":"5cb6d920bf94d463b0ec270e","community":"5cb1f17c80a35f37407791ee","top":false,"deleted":false,"initTime":[2019,4,17,15,43,28,237000000],"lastUpdateTime":[2019,4,17,15,43,28,237000000],"title":null} data:{"id":"5cb6d920bf94d463b0ec2710","author":"user","content":"second comment","parentId":"5cb6d920bf94d463b0ec270e","community":"5cb1f17c80a35f37407791ee","top":false,"deleted":false,"initTime":[2019,4,17,15,43,28,237000000],"lastUpdateTime":[2019,4,17,15,43,28,237000000],"title":null} data:{"id":"5cb6d920bf94d463b0ec2711","author":"user","content":"third comment","parentId":"5cb6d920bf94d463b0ec270e","community":"5cb1f17c80a35f37407791ee","top":false,"deleted":false,"initTime":[2019,4,17,15,43,28,237000000],"lastUpdateTime":[2019,4,17,15,43,28,237000000],"title":null} ``` ## 跟贴 URL|method|header|body example -|-|-|- http://127.0.0.1:8080/posts/$ID|POST|Content-Type: application/json Authorization: Bearer $TOKEN|{"content": "$String"} 注:其中 `$ID` 为所要跟贴的 ID,`$String` 为所要发的内容 ### 返回 Status|HTTP Status Code|HTTP Responses example -|-|-| 跟贴成功|201|{"id":"5cb6def5bf94d463b0ec2717","author":"test","content":"comment on something","parentId":"5cb6d920bf94d463b0ec270e","community":null,"top":false,"deleted":false,"initTime":[2019,4,17,16,8,21,651000000],"lastUpdateTime":[2019,4,17,16,8,21,651000000],"title":null} 跟贴失败|401|- ## 置顶某贴 URL|method|header -|-|-| http://127.0.0.1:8080/posts/top/$ID|POST|Authorization: Bearer $TOKEN 注:其中`$ID`为贴子 ID, 其中`$TOKEN` 为管理员或该版块 `MANAGER` 登录成功时的返回 ### 返回 Status|HTTP Status Code|HTTP Responses example -|-|-| 置顶成功|200|{"id":"5cb6d920bf94d463b0ec270e","author":"user","content":"first post","parentId":null,"community":"5cb1f17c80a35f37407791ee","top":true,"deleted":false,"initTime":[2019,4,17,15,43,28,209000000],"lastUpdateTime":[2019,4,17,15,43,28,209000000],"title":"first post"} 无权限置顶|401|- 找不到贴子|404|- ## 取消置顶 URL|method|header|body example -|-|-|-| http://127.0.0.1:8080/posts/top/$ID|DEL|Content-Type: application/json Authorization: Bearer $TOKEN|{"community": "$CID"} 注:其中`$ID`为贴子 ID,`$TOKEN` 为用户登录成功时的返回,`$CID` 为版块 ID ### 返回 Status|HTTP Status Code|HTTP Responses example -|-|-| 取消置顶成功|200|{"id":"5cb6eacdbf94d4625804f2be","author":"user","content":"second post","parentId":null,"community":"5cb1f17c80a35f37407791ee","top":false,"deleted":false,"initTime":[2019,4,17,16,58,53,121000000],"lastUpdateTime":[2019,4,17,16,58,53,121000000],"title":"second post"} 无权限|401|- 找不到贴子|404|- # Usage 配置 `\src\main\resources\application.properties` Example ``` # fvcking application.properties # https://stackoverflow.com/questions/38775194/where-is-the-application-properties-file-in-a-spring-boot-project #Application Configuration #server.port=8090 #Monodb Configuration spring.data.mongodb.database=mongodemo #spring.data.mongodb.username= #spring.data.mongodb.password= spring.data.mongodb.host=127.0.0.1 spring.data.mongodb.port=27017 # https://stackoverflow.com/questions/45428826/reading-values-from-application-properties-spring-boot springbootwebfluxjjwt.password.encoder.secret=xxxxxxx #springbootwebfluxjjwt.password.encoder.secret=bbs_dxw_secret springbootwebfluxjjwt.password.encoder.iteration=33 springbootwebfluxjjwt.password.encoder.keylength=256 springbootwebfluxjjwt.jjwt.secret=xxxxxxx springbootwebfluxjjwt.jjwt.expiration=28800 ``` ## 运行 Mongo 服务器 `docker run --name=mongo -p 27017:27017 -v ~/db:/data/db -d mongo` `~/db` 为自己的 mongo 数据存储目录 <file_sep>package com.bbs.userapi.controller; import com.bbs.userapi.exception.UserNotMatchException; import com.bbs.userapi.model.User; import com.bbs.userapi.security.PBKDF2Encoder; import com.bbs.userapi.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Mono; import java.security.Principal; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userRepository; @Autowired private PBKDF2Encoder passwordEncoder; @GetMapping("{username}") public Mono<ResponseEntity<User>> getUser(@PathVariable String username) { return userRepository .findByUsername(username) .map(ResponseEntity::ok) .defaultIfEmpty(ResponseEntity.notFound().build()); } @PutMapping("{username}") @PreAuthorize("hasRole('ADMIN') or hasRole('USER')") public Mono<ResponseEntity<User>> updateUser(@PathVariable String username, @RequestBody User user_in_request, Mono<Principal> principal) { return principal .map(Principal::getName) .flatMap(username_principal -> userRepository.findByUsername(username_principal)) .flatMap(user -> { if (user.getUsername().equals(user_in_request.getUsername())) { user.setSignature(user_in_request.getSignature()); user.setPassword(passwordEncoder.encode(user_in_request.getPassword())); return userRepository.update(user); } else { return Mono.error(new UserNotMatchException("UserNotMatchException")); } }) .map(ResponseEntity::ok) .onErrorResume(UserNotMatchException.class, e -> Mono.just(ResponseEntity.status(HttpStatus.BAD_REQUEST).build())) .defaultIfEmpty(ResponseEntity.status(HttpStatus.NOT_FOUND).build()); } @DeleteMapping("{username}") @PreAuthorize("hasRole('ADMIN')") public Mono<ResponseEntity<User>> deletePost(@PathVariable String username) { return userRepository .findByUsername(username) .flatMap(user -> { if(user.getLock()==true){ user.setLock(false); }else { user.setLock(true); } return userRepository.update(user); }) .map(ResponseEntity::ok) .defaultIfEmpty(ResponseEntity.status(HttpStatus.NOT_FOUND).build()); } }<file_sep>package com.bbs.communityapi.controller; import com.bbs.communityapi.model.Community; import com.bbs.communityapi.model.repository.CommunityRepository; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.Optional; @RestController @RequestMapping("/communities") public class CommunityController { private CommunityRepository communityRepository; public CommunityController(CommunityRepository communityRepository) { this.communityRepository = communityRepository; } @GetMapping(value = "", produces = MediaType.TEXT_EVENT_STREAM_VALUE) // stream/text-event // https://www.callicoder.com/reactive-rest-apis-spring-webflux-reactive-mongo/ // https://medium.com/@nithinmallya4/processing-streaming-data-with-spring-webflux-ed0fc68a14de public Flux<Community> getCommunities(@RequestParam(value = "page", required = false) Optional<Integer> page) { // TODO: get posts with multithread and pagination // https://zupzup.org/kotlin-webflux-example/ // https://thepracticaldeveloper.com/2017/11/04/full-reactive-stack-with-spring-webflux-and-angularjs/#Pagination return communityRepository .findAllPagination(PageRequest.of(page.orElse(0), 10)); } @GetMapping(value = "{id}") public Mono<ResponseEntity<Community>> getCommunity(@PathVariable String id) { // get method parameters // https://stackoverflow.com/questions/45924505/is-there-any-way-to-implement-pagination-in-spring-webflux-and-spring-data-react return communityRepository.findById(id) .map(ResponseEntity::ok) .defaultIfEmpty(ResponseEntity.notFound().build()); } @PostMapping @PreAuthorize("hasRole('ADMIN')") public Mono<ResponseEntity<Community>> saveCommunity(@RequestBody Community community_in_request) { // format for set in body // https://stackoverflow.com/questions/34789357/how-to-pass-liststring-in-post-method-using-spring-mvc return communityRepository .save(new Community(null, community_in_request.getName(), true, community_in_request.getManagers())) .map(community -> ResponseEntity.status(HttpStatus.CREATED).body(community)) .defaultIfEmpty(ResponseEntity.status(HttpStatus.BAD_REQUEST).build()); } @PutMapping("{id}") @PreAuthorize("hasRole('ADMIN')") public Mono<ResponseEntity<Community>> updatePost(@PathVariable(value = "id") String id, @RequestBody Community community_in_request) { return communityRepository .findById(id) .flatMap(community -> { // we can't delete one of manager in community // HashSet<String> managers_in_request = community_in_request.getManagers(); // HashSet<String> managers = community.getManagers(); // managers.addAll(managers_in_request); community.setManagers(community_in_request.getManagers()); community.setVisibility(community_in_request.getVisibility()); return communityRepository.save(community); }) .map(ResponseEntity::ok) .defaultIfEmpty(ResponseEntity.status(HttpStatus.BAD_REQUEST).build()); } @DeleteMapping("{id}") @PreAuthorize("hasRole('ADMIN')") public Mono<ResponseEntity<Community>> deletePost(@PathVariable(value = "id") String id) { return communityRepository .findById(id) .flatMap(community -> { community.setVisibility(false); return communityRepository.save(community); }) .map(ResponseEntity::ok) .defaultIfEmpty(ResponseEntity.status(HttpStatus.BAD_REQUEST).build()); } } <file_sep>buildscript { ext { springBootVersion = '2.1.3.RELEASE' } repositories { maven { url "http://maven.aliyun.com/nexus/content/groups/public/" } mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' bootJar { // https://stackoverflow.com/questions/46939455/spring-boot-gradle-how-to-build-executable-jar baseName = 'gs-reactive-rest-service' version = '0.1.0' } sourceCompatibility = 1.8 repositories { mavenLocal() maven { url "http://maven.aliyun.com/nexus/content/groups/public/" } mavenCentral() } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive' implementation 'org.springframework.boot:spring-boot-starter-data-redis-reactive' // https://stackoverflow.com/questions/40228036/how-to-turn-off-spring-security-in-spring-boot-application implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-webflux' implementation 'com.fasterxml.jackson.core:jackson-annotations' implementation 'org.projectlombok:lombok' // https://stackoverflow.com/questions/53809244/difficulty-importing-jwt-json-web-token-in-spring-boot-gradle-project compile group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.1' // runtime 'io.jsonwebtoken:jjwt-impl' // runtime 'io.jsonwebtoken:jjwt-jackson' testImplementation ('de.flapdoodle.embed:de.flapdoodle.embed.mongo') testImplementation('org.springframework.boot:spring-boot-starter-test') testImplementation('io.projectreactor:reactor-test') testImplementation 'org.springframework.security:spring-security-test' }
379199a58a804b01096b64d7fe9962bcdb810e34
[ "Markdown", "Java", "Gradle" ]
14
Java
HMBSbige/DXW_BBS
a3d531e25f5c2af824dfb1210aa0766abc3dbd7b
c8196ecdf17223ea8a6700d4e71d9bceb47facf3
refs/heads/master
<repo_name>amanzeekverma/zeek123<file_sep>/settings.gradle include ':app' rootProject.name = "ZeeK123"<file_sep>/app/src/main/java/com/zeek/zeek123/MainActivity.kt package com.zeek.zeek123 import android.media.MediaPlayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.Toast class MainActivity : AppCompatActivity() { private lateinit var mediaPlayer: MediaPlayer override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val img0 = findViewById<ImageView>(R.id.img0) img0.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.zero) mediaPlayer.start() } val img1 = findViewById<ImageView>(R.id.img1) img1.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.one) mediaPlayer.start() } val img2 = findViewById<ImageView>(R.id.img2) img2.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.two) mediaPlayer.start() } val img3 = findViewById<ImageView>(R.id.img3) img3.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.three) mediaPlayer.start() } val img4 = findViewById<ImageView>(R.id.img4) img4.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.four) mediaPlayer.start() } val img5 = findViewById<ImageView>(R.id.img5) img5.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.five) mediaPlayer.start() } val img6 = findViewById<ImageView>(R.id.img6) img6.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.six) mediaPlayer.start() } val img7 = findViewById<ImageView>(R.id.img7) img7.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.seven) mediaPlayer.start() } val img8 = findViewById<ImageView>(R.id.img8) img8.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.eight) mediaPlayer.start() } val img9 = findViewById<ImageView>(R.id.img9) img9.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.nine) mediaPlayer.start() } val img10 = findViewById<ImageView>(R.id.img10) img10.setOnClickListener{ mediaPlayer = MediaPlayer.create(applicationContext,R.raw.ten) mediaPlayer.start() } val quit = findViewById<ImageView>(R.id.quit) quit.setOnClickListener{ this.moveTaskToBack(true); } } }<file_sep>/README.md # zeek123 Kotlin based android game for 1-3 years old. Basically shows 10 images (images 1 to 10) and upon touching the number, the number is read outloud. Quick startup with Kotlin and basic android coding.
7825aa246164a74bfc511dbe362aff1dd82e11bb
[ "Markdown", "Kotlin", "Gradle" ]
3
Gradle
amanzeekverma/zeek123
036eb96dbe44538dd2c2fa19e8b78eb04ec21672
95935ca559fc0fac768584256fdbe067ab77ea80
refs/heads/master
<repo_name>atheJack/lqsUtil<file_sep>/settings.gradle rootProject.name = "ImpTest" include ':app' include ':lqsutil' include ':mylibrary' <file_sep>/mylibrary/src/main/java/com/example/mylibrary/Manager.java package com.example.mylibrary; public class Manager { public static final int CONST_NUM = 1; }
a873326a8f0079d89123988ecda5a506f6516a53
[ "Java", "Gradle" ]
2
Gradle
atheJack/lqsUtil
97fd8a2e0470d050de0e9b1d811846db0216500a
158b4e87b309f4d9b0b9aa5bec8a234df6de9824
refs/heads/main
<repo_name>PinitS/TENT-PAGE-EDITOR<file_sep>/src/pageBuilder/PageBuilder.js import React, { useState } from 'react' import { v4 as uuidv4 } from 'uuid'; import IMG from './components/IMG'; import TextAndYoutube from './components/TextAndYoutube'; import Title from './components/Title'; import Youtube from './components/Youtube'; export default function PageBuilder() { const funnelID = 213; const [registerData, setRegisterData] = useState([]); const [isOpenEditor, setIsOpenEditor] = useState(false); const registerComponent = (e) => { const type = e.target.getAttribute('data'); const register = { type: type, value: {} } console.log('register :>> ', register); setRegisterData([...registerData, register]); console.log('registerData :>> ', registerData); } const getPositionUpByIndex = (index, positon) => { console.log('index :>> ', index); console.log('positon :>> ', positon); console.log('registerData :>> ', registerData); swapPosition(index, positon); } const getPositionDownByIndex = (index, positon) => { console.log('index :>> ', index); console.log('positon :>> ', positon); console.log('registerData :>> ', registerData); swapPosition(index, positon); } const swapPosition = (index, position) => { const casePosition = (position === 'Up' ? 1 : -1); const newStateSwap = [...registerData]; const commentIndex = index; if (commentIndex === 0 && position === 'Up') { console.log('fail :>> '); } else if (commentIndex === newStateSwap.length - 1 && position === 'Down') { console.log('fail :>> '); } else { let tmp = newStateSwap[commentIndex]; newStateSwap[commentIndex] = newStateSwap[commentIndex - casePosition]; newStateSwap[commentIndex - casePosition] = tmp const newSwap = newStateSwap; setRegisterData(newSwap); } } return ( <div> <p>PageBuilder</p> <div> {registerData.map((item, index) => { switch (item.type) { case 'youtube': return <Youtube getPositionDownByIndex={getPositionDownByIndex} getPositionUpByIndex={getPositionUpByIndex} index={index} positionDown={'Down'} positionUp={'Up'} key={index}> </Youtube>; case 'title': return <Title getPositionDownByIndex={getPositionDownByIndex} getPositionUpByIndex={getPositionUpByIndex} index={index} positionDown={'Down'} positionUp={'Up'} key={index}> </Title>; case 'img': return <IMG getPositionDownByIndex={getPositionDownByIndex} getPositionUpByIndex={getPositionUpByIndex} index={index} positionDown={'Down'} positionUp={'Up'} key={index}> </IMG>; case 'TextAndYoutube': return <TextAndYoutube getPositionDownByIndex={getPositionDownByIndex} getPositionUpByIndex={getPositionUpByIndex} index={index} positionDown={'Down'} positionUp={'Up'} key={index}> </TextAndYoutube>; default: } return undefined; })} </div> <div> <button onClick={() => { setIsOpenEditor(!isOpenEditor); }}>OpenEditor</button> </div> {isOpenEditor && <div> editor <button data={"youtube"} onClick={(e) => { registerComponent(e) }} >youtube</button> <button data={"title"} onClick={(e) => { registerComponent(e) }} >title</button> <button data={"img"} onClick={(e) => { registerComponent(e) }} >img</button> <button data={"TextAndYoutube"} onClick={(e) => { registerComponent(e) }} >TextAndYoutube</button> {/* <button onClick={() => { localStorage.setItem("initialElements", JSON.stringify(dataState)); }} >Save </button> */} {/* <button onClick={() => { setDataState(JSON.parse(localStorage.getItem("initialElements"))) }} >Load</button> */} {/* <button onClick={() => { setDataState([]); }} >empty</button> */} </div>} </div> ) } <file_sep>/src/pageBuilder/components/IMG.js import React from 'react' export default function IMG(props) { console.log('props :>> ', props); return ( <div style={{background:"red"}}> <p>{props.index}</p> <p>===============</p> <button onClick={() => { props.getPositionUpByIndex(props.index, props.positionUp) }}>up</button> <button onClick={() => { props.getPositionDownByIndex(props.index, props.positionDown) }}>down</button> <p>IMG</p> <p>===============</p> </div> ) }
90180c992fac5ec3f5970024cd3fe4479c769a2d
[ "JavaScript" ]
2
JavaScript
PinitS/TENT-PAGE-EDITOR
7c04ae37c249cf45a8ea94f1c00b4ad022c46984
add938c1bfb0d2ad6dcf46f2c1c7c347be4bdb64