language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
3,967
1.757813
2
[]
no_license
/* * XML Type: CT_EmbeddedFontListEntry * Namespace: http://schemas.openxmlformats.org/presentationml/2006/main * Java type: org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontListEntry * * Automatically generated - do not modify. */ package org.openxmlformats.schemas.presentationml.x2006.main; /** * An XML CT_EmbeddedFontListEntry(@http://schemas.openxmlformats.org/presentationml/2006/main). * * This is a complex type. */ public interface CTEmbeddedFontListEntry extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(CTEmbeddedFontListEntry.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.sE130CAA0A01A7CDE5A2B4FEB8B311707").resolveHandle("ctembeddedfontlistentry48b4type"); /** * Gets the "font" element */ org.openxmlformats.schemas.drawingml.x2006.main.CTTextFont getFont(); /** * Sets the "font" element */ void setFont(org.openxmlformats.schemas.drawingml.x2006.main.CTTextFont font); /** * Appends and returns a new empty "font" element */ org.openxmlformats.schemas.drawingml.x2006.main.CTTextFont addNewFont(); /** * Gets the "regular" element */ org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId getRegular(); /** * True if has "regular" element */ boolean isSetRegular(); /** * Sets the "regular" element */ void setRegular(org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId regular); /** * Appends and returns a new empty "regular" element */ org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId addNewRegular(); /** * Unsets the "regular" element */ void unsetRegular(); /** * Gets the "bold" element */ org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId getBold(); /** * True if has "bold" element */ boolean isSetBold(); /** * Sets the "bold" element */ void setBold(org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId bold); /** * Appends and returns a new empty "bold" element */ org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId addNewBold(); /** * Unsets the "bold" element */ void unsetBold(); /** * Gets the "italic" element */ org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId getItalic(); /** * True if has "italic" element */ boolean isSetItalic(); /** * Sets the "italic" element */ void setItalic(org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId italic); /** * Appends and returns a new empty "italic" element */ org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId addNewItalic(); /** * Unsets the "italic" element */ void unsetItalic(); /** * Gets the "boldItalic" element */ org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId getBoldItalic(); /** * True if has "boldItalic" element */ boolean isSetBoldItalic(); /** * Sets the "boldItalic" element */ void setBoldItalic(org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId boldItalic); /** * Appends and returns a new empty "boldItalic" element */ org.openxmlformats.schemas.presentationml.x2006.main.CTEmbeddedFontDataId addNewBoldItalic(); /** * Unsets the "boldItalic" element */ void unsetBoldItalic(); /** * A factory class with static methods for creating instances * of this type. */ }
Markdown
UTF-8
1,148
2.59375
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
## About ## rsa_tool provides a working example in C of how to use Microsoft Crypto API to digitally sign and verify the integrity of files using the RSA digital signature algorithm. The private and public keys must be stored in PEM (Privacy Exchange Mail) format. Signatures are stored as binary using big-endian convention. See more info about tool and how it works [here](https://stosd.wordpress.com/2017/04/22/capi-openssl/) ## Building ## For Linux/BSD, just type 'make all' For Microsoft Visual Studio, type: 'nmake' If you receive any errors for Linux/BSD like missing headers, it's because libssl-dev is missing. Install with package manager and retry. * **MSVC** cl /DCAPI /O2 /Os rsa_tool.c rsa.c * **Mingw** gcc -DCAPI -O2 -Os rsa_tool.c rsa.c -orsa_tool -lcrypt32 -lshlwapi * **Linux/BSD** gcc -O2 -Os rsa_tool.c rsa.c -orsa_tool -lcrypto ## Usage ## * **Generating RSA Key** ./rsa_tool -s private.pem -v public.pem -g 2048 * **Signing a file** ./rsa_tool -s private.pem rsa_tool -x sig.bin * **Verifying a file** ./rsa_tool -v public.pem rsa_tool -x sig.bin
Markdown
UTF-8
1,526
3.84375
4
[]
no_license
# 1167. Minimum Cost to Connect Sticks You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick. You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only one stick remaining. Return the minimum cost of connecting all the given sticks into one stick in this way. --- In order to find the minimum cost to connect all the given sticks, we need to repeatedly add the two smallest sticks at the moment and return the connected stick back to the pool. The best approach in this case would be using heap since maintaining the heap is a logrithmic in time complexity. --- Java: ```java import java.util.PriorityQueue; class Solution { public int connectSticks(int[] sticks) { PriorityQueue<Integer> pq = new PriorityQueue<>( Arrays.stream(sticks).boxed.collect(Collectors.asList)); int result = 0; while (pq.size() > 1) { int x = pq.remove(); int y = pq.remove(); result += (x + y); pq.add(x + y); } return result; } } ``` Python: ```python import heapq class Solution: def minCost(self, sticks): result = 0 heapify(sticks) while len(sticks) > 1: x, y = heappop(sticks), heappop(sticks) result += x + y heappush(sticks, x + y) return result ```
C++
UTF-8
1,107
3.203125
3
[]
no_license
// 118.pascals-triangle.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <iostream> #include <algorithm> #include <map> #include <unordered_map> #include <unordered_set> #include <vector> #include <queue> #include <set> #include <stack> #include <string> #include <random> #include "..\Common\Common.h" using namespace std; vector<vector<int>> generate(int numRows) { vector<vector<int>> m; for (int i = 1; i <= numRows; i++) { vector<int> n; for (int j = 0; j < i; j++) { if (j == 0 || j == i - 1) n.push_back(1); else n.push_back(m[i - 2][j - 1] + m[i - 2][j]); } m.push_back(n); } return m; } //vector<vector<int>> generate(int numRows) //{ // vector<vector<int>> m; // for (int i = 1; i <= numRows; i++) // { // vector<int> n; // for (int j = 0; j < i; j++) // { // if (j == 0 || j == i - 1) n.emplace_back(1); // else n.emplace_back(m[i - 2][j - 1] + m[i - 2][j]); // } // m.emplace_back(n); // } // return m; //} int main() { vector<vector<int>> matrix = generate(10); printVectorVectorT(matrix); }
Java
UTF-8
1,513
2.203125
2
[]
no_license
package com.atguigu.springcloud; import com.atguigu.springcloud.dao.UserDao; 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.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * 测试 sharding-JDBC 垂直分库 * @author huyang * @date 2020/6/17 15:11 */ @RunWith(SpringRunner.class) @SpringBootTest(classes = {ShardingJabcSimpleBootstrap.class}) public class UserDaoTest { @Autowired private UserDao userDao; @Test public void insertUser() { for (int i = 13; i < 20; i++) { Long id = i + 1L ; userDao.insertUser(id,"姓名" + id); } } /** * 如果既分库又分表了,没有传入分片键的时候,会产生笛卡尔积,同时路由到多个库 */ @Test public void queryUserByIds() { List<Long> userIds = new ArrayList<>(); userIds.add(1L); userIds.add(2L); List<Map> result = userDao.queryOrderByIdsAndUserId(userIds); System.out.println("查询结果: " + result); } @Test public void queryUserInfoByIds(){ List<Long> userIds = new ArrayList<>(); userIds.add(1L); userIds.add(2L); List<Map> result = userDao.queryUserInfoByIds(userIds); System.out.println("查询结果: " + result); } }
C#
UTF-8
649
2.75
3
[]
no_license
using System; using System.Threading; using Akka.Actor; namespace Vj05Examples { public class CollectorActor : ReceiveActor { public CollectorActor() { int br = 0; Receive<Messages.Empty>(x => br++); Receive<Messages.Print>(x => Console.WriteLine($"{Self.Path} obradio: {br} poruka")); } protected override void PreStart() { Console.WriteLine(Self.Path); base.PreStart(); } protected override void PostStop() { Console.WriteLine($"Gašenje: {Self.Path}"); base.PostStop(); } } }
PHP
UTF-8
827
2.5625
3
[ "MIT" ]
permissive
<?php namespace Mibexx\Dependency\Business; use Mibexx\Kernel\Business\Config\ConfigInterface; use Mibexx\Kernel\Business\Locator\Locator; interface ContainerInterface extends \ArrayAccess { /** * @return Locator */ public function getLocator(); /** * @param Locator $locator */ public function setLocator(Locator $locator); /** * @return ConfigInterface */ public function getConfig(); /** * @param ConfigInterface $config */ public function setConfig(ConfigInterface $config); /** * @param string $name * @param callable $callback */ public function setProvidedDependency($name, callable $callback); /** * @param string $name * * @return mixed */ public function getProvidedDependency($name); }
Java
UTF-8
1,375
2.125
2
[]
no_license
package com.mitosis.timesheet.service.impl; import java.util.ArrayList; import java.util.List; import com.mitosis.timesheet.dao.BankReconcileDao; import com.mitosis.timesheet.dao.daoImpl.BankReconcileDaoImpl; import com.mitosis.timesheet.model.CustomerPaymentModel; import com.mitosis.timesheet.model.InvoiceHdrModel; import com.mitosis.timesheet.service.BankReconcileService; public class BankReconcileServiceImpl implements BankReconcileService { BankReconcileDao reconcileDao=new BankReconcileDaoImpl(); @Override public List<CustomerPaymentModel> getReceiptDetails() { List<CustomerPaymentModel> paymentModel=new ArrayList<CustomerPaymentModel>(); paymentModel=reconcileDao.getReceiptDetails(); return paymentModel; } @Override public List<CustomerPaymentModel> getPaymentDetails(String invoiceNumber) { List<CustomerPaymentModel> paymentModel=new ArrayList<CustomerPaymentModel>(); paymentModel=reconcileDao.getPaymentDetails(invoiceNumber); return paymentModel; } @Override public InvoiceHdrModel getInvoiceHdrDetails(String invoiceNum) { InvoiceHdrModel invoiceModel=reconcileDao.getInvoiceHdrDetails(invoiceNum); return invoiceModel; } @Override public boolean insert(CustomerPaymentModel customerPaymentModel) { boolean insert = reconcileDao.insert(customerPaymentModel); return insert; } }
PHP
UTF-8
123
3.03125
3
[]
no_license
<?php class First{ public function __construct(){ echo "Hello from first class"; } } ?>
Java
UTF-8
701
3.5625
4
[]
no_license
public class Stack_Queue_06 { public static int[] solution(int[] prices) { int[] answer = {}; int size = prices.length; answer = new int[size]; //answer[size-1] = 0; for(int i=0; i<size-1; i++) { for(int j=i+1; j<size; j++) { answer[i]++; if(prices[i]>prices[j]) break; } } return answer; } public static void run() { //int[] prices = {1,2,3,2,3};//{4,3,1,1,0} int[] prices = {1,2,3,2,1,3};//{5,3,1,1,1,0} int[] answer = solution(prices); System.out.print("answer = "); for(int i=0;i<answer.length;i++) { System.out.print(answer[i]+" "); } } }
Java
UTF-8
4,731
3.15625
3
[]
no_license
/** * author Maria.Gavrilova * copyright 20.07.2018 © Devellar */ package collections; import java.util.*; public class CollectionsTest { public static void main(String[] args) { //ARRAY LIST // ArrayList<String> list = new ArrayList<>(); // ArrayList<String> listCompare = new ArrayList<>(); // listCompare.add("Masha"); // listCompare.add("Michelle"); // listCompare.add("Lesha"); // list.add("Masha"); // list.add("Lesha"); // list.add("Yaroslava"); // list.add(1, "Michelle"); //// list.remove("Lesha"); // System.out.println(list.containsAll(listCompare)); // listCompare.add("Yaroslava"); // System.out.println(list.equals(listCompare)); // Collections.sort(listCompare); // System.out.println(listCompare); // System.out.println(list); // System.out.println(list.equals(listCompare)); // // LinkedList<Integer> ages = new LinkedList<>(); // ages.add(12); // ages.add(80); // ages.add(5); // ages.add(21); // ages.addFirst(16); // ages.addLast(30); // ages.get(5); // Iterator iterator = ages.iterator(); // for (Iterator it = ages.iterator(); it.hasNext();) { // System.out.println(it.next()); // } // // while (iterator.hasNext()) { // System.out.println(iterator.next()); // iterator.next(); // iterator.hashCode(); // } // // ListIterator listIterator = ages.listIterator(); // while (listIterator.hasNext()) { // System.out.println(listIterator.hasNext()); // System.out.println(listIterator.hasPrevious()); // System.out.println(listIterator.nextIndex()); // System.out.println(listIterator.previousIndex()); // System.out.println("next: " + listIterator.next()); // System.out.println("previous: " + listIterator.previous()); // System.out.println("next: " + listIterator.next()); // } // // String y = "hg"; // System.out.println(y.hashCode()); // Object d = new Object(); // Object w = new Object(); // Object s = d; // System.out.println(d.equals(w)); // System.out.println(s.equals(d)); // System.out.println(s.equals(w)); //HASH MAP // HashMap<String,String> a = new HashMap<>(); // a.put("5","sex"); // a.put("6", "male"); // HashMap<String,String> b = new HashMap<>(); // b.put("6","male"); // b.put("5", "sex"); // System.out.println(a.equals(b)); //true // System.out.println(a.keySet()); // System.out.println(a.entrySet()); // System.out.println(b.entrySet()); // // String s1 = new String("Masha"); // String s2 = new String ("Masha"); // System.out.println(s1.equals(s2)); //QUEUE // Queue<Integer> q = new LinkedList<>(); // q.offer(5); // q.offer(96); // q.offer(78); // while (!q.isEmpty()) { // System.out.println(q.poll()); // } // q.add(8); // System.out.println(q); // q.remove(); // System.out.println(q); // q.remove(96); // System.out.println(q); // PriorityQueue<Integer> pq = new PriorityQueue<>(); // pq.offer(5); // pq.offer(96); // pq.offer(78); // System.out.println(pq); // while (!pq.isEmpty()) { // System.out.println(pq.poll()); // } // System.out.println(pq); //HASH SET // HashSet set = new HashSet(); // set.add("face"); // set.add("book"); // set.add("mum"); // // System.out.println(set); // // HashSet s = new HashSet(); // s.add("face"); // s.add("mum"); // s.add("book"); // // System.out.println(s); // // System.out.println(set.equals(s)); // LinkedHashSet set = new LinkedHashSet(); // set.add("face"); // set.add("book"); // set.add("mum"); // // System.out.println(set); // // LinkedHashSet s = new LinkedHashSet(); // s.add("face"); // s.add("mum"); // s.add("book"); // // System.out.println(s); // // System.out.println(set.equals(s)); // TreeSet set = new TreeSet(); // set.add("face"); // set.add("book"); // set.add("mum"); // // System.out.println(set); // // TreeSet s = new TreeSet(); // s.add("face"); // s.add("mum"); // s.add("book"); // // System.out.println(s); // // System.out.println(set.equals(s)); } }
Markdown
UTF-8
2,224
3.09375
3
[]
no_license
# Fantasy-Ashesi-Basketball-Application Do you know Fantasy Premier League? That is great! If you do not, Fantasy Premier League (FPL) is an extension of the Premier league app which allows the user to stay in touch with his favorite team in terms of statistics, transfers, fixtures, results, etc. FPL enables the user to pick his best 16 players into his team. These players belong to the Barclays Premier League and are analyzed on the gameplay and awarded points within FPL. Therefore, the better a player plays, the higher his points in the game. These points are then tallied to a total score which is then compared to that of other users in a particular region as a competition. Why am I talking about FPL? Because I present to you, Fantasy Ashesi Basketball Association. A program that allows a user to do similar, but with the Ashesi Basketball Association. A user will be able to select his team and based on their performance in the league during the semester; the players are awarded points which are then tallied to an overall score. For now, the program uses a GUI (Graphical User Interface), Tkinter, to show a welcome screen on startup with a button that takes the user to another GUI which reads the ABA's data from their online database and displays it. The user is then required to select 12 players from this window with careful evaluation using the statistics provided and click the button "next." When the button is clicked, the selected players are then projected in the next window (GUI) in a player card on basketball court form which displays the points accumulated by the player and the overall tally at the top. When the player representations are clicked, the player name, stats, image, and team are displayed in another GUI to provide a status report on the player. This display also gathers the information from the online database. Therefore, this program requires an internet connection to function. The welcome screen is produced from the welcomescreen function, the selection required all players window is from the AllPlayers class, and the player on court representation window from the FABA class. ### DISCLAIMER: This is a prototype and not the finished product.
TypeScript
UTF-8
946
4.53125
5
[ "Apache-2.0" ]
permissive
// There are 3 basic types in TypeScript let isDone: boolean = false; let lines: number = 42; let name: string = "Anders"; // But you can omit the type annotation if the variables are derived from explicit literals let isDone = false; let lines = 42; let name = "Anders"; // When it's impossible to know, there is the "Any" type let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean // Use const keyword for constants const numLivesForCat = 9; numLivesForCat = 1; // Error // For collections, there are typed arrays and generic arrays let list: number[] = [1, 2, 3]; // Alternatively, using the generic array type let list: Array<number> = [1, 2, 3]; // For enumerations: enum Color { Red, Green, Blue }; let c: Color = Color.Green; // Lastly, "void" is used in the special case of a function returning nothing function bigHorribleAlert(): void { alert("I'm a little annoying box!"); }
Java
UTF-8
10,038
2
2
[]
no_license
/* * 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 View; import KUspital.*; import java.io.*; import javax.swing.JFileChooser; public class Chat extends javax.swing.JFrame { int uno; MainSystem ms; public Clientthread thread; BufferedWriter bw; SaveChat save; ReadHistory rh; JFileChooser a; public Chat() throws IOException { initComponents(); setTitle("상담 진행"); setVisible(true); this.getRootPane().setDefaultButton(jButton1); jTextArea1.setEditable(false); rh = new ReadHistory(); } // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jTextField1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextField1KeyPressed(evt); } }); jLabel1.setText("상대방 이름"); jButton1.setText("전송"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("정보 보기"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("방 나가기"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("파일 전송"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); 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) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 474, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 476, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(jLabel1)) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(34, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents public void appendText(String text) { this.jTextArea1.append(text + "\n"); } public void getThread(Clientthread thread) { this.thread = thread; } public void saveChat(int uno) { save = new SaveChat(); if(ms.my_type == 0) { save.Save(ms.DBoutput.get_information(uno, "ID") + ms.my_ID + ".txt", jTextArea1.getText()); } else { save.Save(ms.my_ID + ms.DBoutput.get_information(uno, "ID") + ".txt", jTextArea1.getText()); } } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String a= jTextField1.getText(); String b=jTextArea1.getText(); if(a != null) { b = b + ms.my_ID + " : " + a; jTextArea1.setText(b+"\n"); jTextField1.setText(""); thread.giveText(ms.my_ID + " : " + a); } }//GEN-LAST:event_jButton1ActionPerformed private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed }//GEN-LAST:event_jTextField1KeyPressed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed }//GEN-LAST:event_jButton3ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed if(a==null) { a=new JFileChooser(); } int returnValue=0; a.showDialog(this.jPanel1,"열기"); if (returnValue == JFileChooser.APPROVE_OPTION) { thread.sendFile(a.getSelectedFile().getAbsolutePath(), a.getSelectedFile().getName()); } }//GEN-LAST:event_jButton4ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables protected javax.swing.JButton jButton1; protected javax.swing.JButton jButton2; protected javax.swing.JButton jButton3; protected javax.swing.JButton jButton4; protected javax.swing.JLabel jLabel1; protected javax.swing.JPanel jPanel1; protected javax.swing.JScrollPane jScrollPane1; protected javax.swing.JTextArea jTextArea1; protected javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
C++
UTF-8
826
2.59375
3
[]
no_license
#include <iostream> #include <algorithm> #include <set> #include <cstdint> #include <cinttypes> #include <cmath> int main (int argc, char *argv[]) { std::set<uint64_t> s_vals; uint64_t nr, i, j, m, mx3, max_l, v, old_sz; long double x3 = 1.0/3.0, u; std::cin >> max_l; mx3 = 1+std::pow(static_cast<long double>(max_l)/4.0, x3); std::cout << "MX3 = " << mx3 << std::endl; nr = 0; for (i = 2; i <= mx3; i++) { j = i*i*i; u = (long double)max_l / (long double)j; v = std::sqrt(u); nr += v-1; // std::cout << "\t---- I: " << i << ", V: " << v << ", NR: " << nr << std::endl; // std::cout << "\t---- MAX: " << (j*v*v) << std::endl; for (m = 2; m <= v; m++) { s_vals.insert(j*m*m); } } std::cout << "Total elements: " << s_vals.size() << std::endl; return 0; }
C++
UTF-8
767
2.890625
3
[]
no_license
#ifndef HOMEWORK_POLICY_H #define HOMEWORK_POLICY_H #include "iostream" class Policy { char*passport; long serialNumber; char *company; char *policyInformation; public: Policy(char*passport, long serialNumber, char *company, char *policyInformation); Policy(char *passport, long serialNumber,char *company); ~Policy(); char *getPassport(); long getSerialNumber(); char *getPolicyInformation(); char *getCompany(); void setCompany(char *company); void setPolicyInformation(char *policyInformation); friend int countPoliciesBySurname(Policy **policies, int policiesCount, char *surname); virtual void print(); int operator+(int param1); }; #endif //HOMEWORK_POLICY_H
Markdown
UTF-8
62,684
2.71875
3
[]
no_license
[toc] # Spring理解 这篇文章主要是想通过一些问题,加深大家对于 Spring 的理解,所以不会涉及太多的代码!这篇文章整理了挺长时间,下面的很多问题我自己在使用 Spring 的过程中也并没有注意,自己也是临时查阅了很多资料和书籍补上的。网上也有一些很多关于 Spring 常见问题/面试题整理的文章,我感觉大部分都是互相 copy,而且很多问题也不是很汗,有些回答也存在问题。所以,自己花了一周的业余时间整理了一下,希望对大家有帮助。 ### Bean周期和作用范围 生命周期: 1. 实例化 Bean 对象。 1. 设置 Bean 属性。 1. 如果我们通过各种 Aware 接口声明了依赖关系,则会注入 Bean 对容器基础设施层面的依赖。具体包括 BeanNameAware、BeanFactoryAware 和 ApplicationContextAware,分别会注入 Bean ID、Bean Factory 或者 ApplicationContext。 1. 调用 BeanPostProcessor 的前置初始化方法 postProcessBeforeInitialization。 1. 如果实现了 InitializingBean 接口,则会调用 afterPropertiesSet 方法。 1. 调用 Bean 自身定义的 init 方法。 1. 调用 BeanPostProcessor 的后置初始化方法 postProcessAfterInitialization。 1. 创建过程完毕。 1. 调用自身和DispsableBean的destroy方法 Spring Bean 有五个作用域,其中最基础的有下面两种: 1. Singleton(单例) 在整个应用中,只创建bean的一个实例 2. Propotype(原型) 每次注入或者通过Spring应用上下文获取的时候,都会创建一个新 的bean实例。 3. Session(会话) 在Web应用中,为每个会话创建一个bean实例。 4. Request(请求) 在Web应用中,为每个请求创建一个bean实例。 他们是什么时候创建的: 1. 一个单例的bean,而且lazy-init属性为false(默认),在Application Context创建的时候构造 2. 一个单例的bean,lazy-init属性设置为true,那么,它在第一次需要的时候被构造. 3. 其他scope的bean,都是在第一次需要使用的时候创建 他们是什么时候销毁的: 1. 单例的bean始终 存在与application context中, 只有当 application 终结的时候,才会销毁 2. 和其他scope相比,Spring并没有管理prototype实例完整的生命周期,在实例化,配置,组装对象交给应用后,spring不再管理.只要bean本身不持有对另一个资源(如数据库连接或会话对象)的引用,只要删除了对该对象的所有引用或对象超出范围,就会立即收集垃圾. 3. Request: 每次客户端请求都会创建一个新的bean实例,一旦这个请求结束,实例就会离开scope,被垃圾回收. 4. Session: 如果用户结束了他的会话,那么这个bean实例会被GC. ### Spring 的基础机制 至少你需要理解下面两个基本方面。 1. 控制反转(Inversion of Control),或者也叫依赖注入(Dependency Injection),广泛应用于 Spring 框架之中,可以有效地改善了模块之间的紧耦合问题。 从 Bean 创建过程可以看到,它的依赖关系都是由容器负责注入,具体实现方式包括带参数的构造函数、setter 方法或者AutoWired方式实现。 2. AOP,我们已经在前面接触过这种切面编程机制,Spring 框架中的事务、安全、日志等功能都依赖于 AOP 技术,下面我会进一步介绍。 ### Spring 到底是指什么? 我前面谈到的 Spring,其实是狭义的Spring Framework,其内部包含了依赖注入、事件机制等核心模块,也包括事务、O/R Mapping 等功能组成的数据访问模块,以及 Spring MVC 等 Web 框架和其他基础组件。 广义上的 Spring 已经成为了一个庞大的生态系统,例如: - Spring Boot,通过整合通用实践,更加自动、智能的依赖管理等,Spring Boot 提供了各种典型应用领域的快速开发基础,所以它是以应用为中心的一个框架集合。 - Spring Cloud,可以看作是在 Spring Boot 基础上发展出的更加高层次的框架,它提供了构建分布式系统的通用模式,包含服务发现和服务注册、分布式配置管理、负载均衡、分布式诊断等各种子系统,可以简化微服务系统的构建。 - 当然,还有针对特定领域的 Spring Security、Spring Data 等。 上面的介绍比较笼统,针对这么多内容,如果将目标定得太过宽泛,可能就迷失在 Spring 生态之中,我建议还是深入你当前使用的模块,如 Spring MVC。并且,从整体上把握主要前沿框架(如 Spring Cloud)的应用范围和内部设计,至少要了解主要组件和具体用途,毕竟如何构建微服务等,已经逐渐成为 Java 应用开发面试的热点之一。 ### Spring AOP 自身设计和实现的细节。 先问一下自己,我们为什么需要切面编程呢? ==切面编程落实到软件工程其实是为了更好地模块化,而不仅仅是为了减少重复代码。通过 AOP 等机制==,我们可以把横跨多个不同模块的代码抽离出来,让模块本身变得更加内聚,进而业务开发者可以更加专注于业务逻辑本身。从迭代能力上来看,我们可以通过切面的方式进行修改或者新增功能,这种能力不管是在问题诊断还是产品能力扩展中,都非常有用。 在之前的分析中,我们已经分析了 AOP Proxy 的实现原理,简单回顾一下,它底层是基于 JDK 动态代理或者 cglib 字节码操纵等技术,运行时动态生成被调用类型的子类等,并实例化代理对象,实际的方法调用会被代理给相应的代理对象。但是,这并没有解释具体在 AOP 设计层面,什么是切面,如何定义切入点和切面行为呢? Spring AOP 引入了其他几个关键概念: - Aspect,通常叫作方面,它是跨不同 Java 类层面的横切性逻辑。在实现形式上,既可以是 XML 文件中配置的普通类,也可以在类代码中用“@Aspect”注解去声明。在运行时,Spring 框架会创建类似Advisor来指代它,其内部会包括切入的时机(Pointcut)和切入的动作(Advice)。 - Join Point,它是 Aspect 可以切入的特定点,在 Spring 里面只有方法可以作为 Join Point。 - Advice,它定义了切面中能够采取的动作。如果你去看 Spring 源码,就会发现 Advice、Join Point 并没有定义在 Spring 自己的命名空间里,这是因为他们是源自AOP 联盟,可以看作是 Java 工程师在 AOP 层面沟通的通用规范。 Java 核心类库中同样存在类似代码,例如 Java 9 中引入的 Flow API 就是 Reactive Stream 规范的最小子集,通过这种方式,可以保证不同产品直接的无缝沟通,促进了良好实践的推广 ## 什么是 Spring 框架? Spring 是一种轻量级开发框架,旨在提高开发人员的开发效率以及系统的可维护性。Spring 官网:<https://spring.io/>。 我们一般说 Spring 框架指的都是 Spring Framework,它是很多模块的集合,使用这些模块可以很方便地协助我们进行开发。==这些模块是:核心容器、数据访问/集成,、Web、AOP(面向切面编程)、工具、消息和测试模块==。比如:Core Container 中的 Core 组件是Spring 所有组件的核心,Beans 组件和 Context 组件是实现IOC和依赖注入的基础,AOP组件用来实现面向切面编程。 Spring 官网列出的 Spring 的 6 个特征: - **核心技术** :依赖注入(DI),AOP,事件(events),资源,i18n,验证,数据绑定,类型转换,SpEL。 - **测试** :模拟对象,TestContext框架,Spring MVC 测试,WebTestClient。 - **数据访问** :事务,DAO支持,JDBC,ORM,编组XML。 - **Web支持** : Spring MVC和Spring WebFlux Web框架。 - **集成** :远程处理,JMS,JCA,JMX,电子邮件,任务,调度,缓存。 - **语言** :Kotlin,Groovy,动态语言。 用过 Spring 框架的都知道 Spring 能流行是因为它的两把利器:IOC 和 AOP,IOC 可以帮助我们管理对象的依赖关系,极大减少对象的耦合性,而 AOP 的切面编程功能可以更方面的使用动态代理来实现各种动态方法功能(如事务、缓存、日志等)。 而要集成 Spring 框架,必须要用到 XML 配置文件,或者注解式的 Java 代码配置。无论是使用 XML 或者代码配置方式,都需要对相关组件的配置有足够的了解,然后再编写大量冗长的配置代码。 ## 列举一些重要的Spring模块? 下图对应的是 Spring4.x 版本。目前最新的5.x版本中 Web 模块的 Portlet 组件已经被废弃掉,同时增加了用于异步响应式处理的 WebFlux 组件。 ![Spring主要模块](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-6/Spring主要模块.png) - **Spring Core:** 基础,可以说 Spring 其他所有的功能都需要依赖于该类库。主要提供 IOC 依赖注入功能。 - **Spring Aspects** : 该模块为与AspectJ的集成提供支持。 - **Spring AOP** :提供了面向方面的编程实现。 - **Spring JDBC** : Java数据库连接。 - **Spring JMS** :Java消息服务。 - **Spring ORM** : 用于支持Hibernate等ORM工具。 - **Spring Web** : 为创建Web应用程序提供支持。 - **Spring Test** : 提供了对 JUnit 和 TestNG 测试的支持。 ## 谈谈自己对于 Spring IoC 和 AOP 的理解 ## IOC 比如说我们要创建一个绿茶,手动进行new,那么当一段时间之后,我们需要改变需求,把绿茶改成红茶,那么就需要在整个程序中进行修改比较繁琐,那么我们可以委托给Spring的bean工厂进行创建,我们只需要提出要求,那么它自动会通过工厂内的方法创建不同的对象,这边我们绿茶改成红茶,那么工厂内调用getRedTea()就行了。只需要在一个地方进行修改就行了。 控制反转也被成为依赖注入,是一种降低耦合关系的设计:一般分层体系来说,上层依赖下层,当上层需要修改的时候,下层也会全部要改修,通过IOC使得下层依赖上层,完成控制反转,然后通过注入一个实例化对象的方式来进行完成。 IoC(Inverse of Control:控制反转)是一种**设计思想**,就是 **将原本在程序中手动创建对象的控制权,交由Spring框架来管理。** IoC 在其他语言中也有应用,并非 Spirng 特有。 **IoC 容器是 Spring 用来实现 IoC 的载体, IoC 容器实际上就是个Map(key,value),Map 中存放的是各种对象。** 将对象之间的相互依赖关系交给 IOC 容器来管理,并由 IOC 容器完成对象的注入。这样可以很大程度上简化应用的开发,把应用从复杂的依赖关系中解放出来。 **IOC 容器就像是一个工厂一样,当我们需要创建一个对象的时候,只需要配置好配置文件/注解即可,完全不用考虑对象是如何被创建出来的。** 在实际项目中一个 Service 类可能有几百甚至上千个类作为它的底层,假如我们需要实例化这个 Service,你可能要每次都要搞清这个 Service 所有底层类的构造函数,这可能会把人逼疯。如果利用 IOC 的话,你只需要配置好,然后在需要的地方引用就行了,这大大增加了项目的可维护性且降低了开发难度。 就是由spring来负责控制对象的生命周期和对象间的关系: 所有的类的创建、销毁都由 spring来控制,也就是说控制对象生存周期的不再是引用它的对象,而是spring。对于某个具体的对象而言,以前是它控制其他对象,现在是所有对象都被spring控制,所以这叫控制反转。 1. Spring IOC是一种设计模式,使对象不用显示的创建依赖对象,而是将对象创建的过程交给Spring的IOC容器去管理,通过依赖注入的方式,来实现IOC 2. 控制权的转移:应用程序本身不负责依赖对象的创建和维护,而是由外部容器负责创建和维护。 获得依赖对象的过程被反转了。 IOC相当于房屋中介:找中介=找IOC容器,中介介绍房子=容器返回对象,入住=使用对象。 >Sping Core最核心的部分。 IOC支持的功能 - 依赖注入 - 依赖检查 - 自动配装 - 支持集合 - 指定初始化方法和销毁方法 - 支持回调(谨慎) Spring 时代我们一般通过 XML 文件来配置 Bean,后来开发人员觉得 XML 文件来配置不太好,于是 SpringBoot 注解配置就慢慢开始流行起来。 推荐阅读:https://www.zhihu.com/question/23277575/answer/169698662 **Spring IOC的初始化过程:** ![Spring IOC的初始化过程](https://user-gold-cdn.xitu.io/2018/9/22/165fea36b569d4f4?w=709&h=56&f=png&s=4673) IOC源码阅读 - https://javadoop.com/post/spring-ioc ### 依赖注入(DI) 理解DI的关键是:“谁依赖谁,为什么需要依赖,谁注入谁,注入了什么”,那我们来深入分析一下: -   谁依赖于谁:当然是应用程序依赖于IoC容器; -   为什么需要依赖:应用程序需要IoC容器来提供对象需要的外部资源; -   谁注入谁:很明显是IoC容器注入应用程序某个对象,应用程序依赖的对象; -   注入了什么:就是注入某个对象所需要的外部资源(包括对象、资源、常量数据)。   IoC和DI由什么关系呢?其实它们是同一个概念的不同角度描述,由于控制反转概念比较含糊(可能只是理解为容器控制对象这一个层面,很难让人想到谁来维护对象关系),所以2004年大师级人物Martin Fowler又给出了一个新的名字:“依赖注入”,相对IoC 而言,“依赖注入”明确描述了“被注入对象依赖IoC容器配置依赖对象”。 控制反转的一种方式,目的是为了创建对象并且组装对象之间的关系。IOC容器运行期间,动态的将某种依赖注入到对象之中。 ``` A-> B ->C ->D //如果A依赖B,B依赖C,C依赖D,那么当D修改的时候,ABC都会要进行修改 ``` ![](https://raw.githubusercontent.com/binbinbin5/myPics/master/imgs/20190630141512.png) ``` //<- 为注入, A<- B <- C <-D ``` ![](https://raw.githubusercontent.com/binbinbin5/myPics/master/imgs/20190630141447.png) ==我们要使用上层控制下层,而不是下层控制上层,这叫控制反转。用依赖注入来实现控制反转:把底层类作为参数传递给上层类,实现上层对下层的“控制”。== 多个类互不受影响。 ![](https://raw.githubusercontent.com/binbinbin5/myPics/master/imgs/20190630141926.png) > DL 依赖查找 根据框架提供的方法来获取对象,但是现在已经被抛弃了(需要用户自己使用API查找资源 具有侵入性)。 ### 依赖倒置原则 高层模块不应该依赖底层模块。 ![](https://raw.githubusercontent.com/binbinbin5/myPics/master/imgs/20190630144511.png) ### IOC容器 - 避免再各处使用new创建类,并且可以做到统一维护,自动进行初始化 - 创建实例的时候不需要了解其中细节 ![](https://raw.githubusercontent.com/binbinbin5/myPics/master/imgs/20190630144719.png) ## AOP AOP(Aspect-Oriented Programming:面向切面编程)能够将那些与业务无关,**却为业务模块所共同调用的逻辑或责任(例如事务处理、日志管理、权限控制等)封装起来**,便于**减少系统的重复代码**,**降低模块间的耦合度**,并**有利于未来的可拓展性和可维护性**。 **Spring AOP就是基于动态代理的**,如果要代理的对象,实现了某个接口,那么Spring AOP会使用**JDK Proxy**,去创建代理对象,而对于没有实现接口的对象,就无法使用 JDK Proxy 去进行代理了,这时候Spring AOP会使用**Cglib** ,这时候Spring AOP会使用 **Cglib** 生成一个被代理对象的子类来作为代理,如下图所示:我们把过滤器的重复代码抽取出来。 ![](https://raw.githubusercontent.com/binbinbin5/myPics/master/file/50a2b97086e8a20a54b844be2b8c5e6.png) 在日常的软件开发中,拿日志来说,一个系统软件的开发都是必须进行日志记录的,不然万一系统出现什么bug,你都不知道是哪里出了问题。举个小栗子,当你开发一个登陆功能,你可能需要在用户登陆前后进行权限校验并将校验信息(用户名,密码,请求登陆时间,ip地址等)记录在日志文件中,当用户登录进来之后,当他访问某个其他功能时,也需要进行合法性校验。想想看,当系统非常地庞大,系统中专门进行权限验证的代码是非常多的,而且非常地散乱,我们就想能不能将这些权限校验、日志记录等非业务逻辑功能的部分独立拆分开,并且在系统运行时需要的地方(连接点)进行动态插入运行,不需要的时候就不理,因此AOP是能够解决这种状况的思想吧! 当然你也可以使用 AspectJ ,Spring AOP 已经集成了AspectJ ,AspectJ 应该算的上是 Java 生态系统中最完整的 AOP 框架了。 使用 AOP 之后我们可以把一些通用功能抽象出来,在需要用到的地方直接使用即可,这样大大简化了代码量。我们需要增加新功能时也方便,这样也提高了系统扩展性。日志功能、事务管理等等场景都用到了 AOP 。 ### 接口和面向接口编程 接口是用于沟通的中介物的抽象化,实体是提供给外界的抽象化说明,使其能被修改内部而不影响外界。 结构设计中,分清层次以及调用,每层只向外提供一组功能接口,各层仅仅依赖接口而非实现类。 1. 接口实现的变得不影响各层的调用 2. 面向接口编程中的接口适用于隐藏具体实现和实现多态性的组件 ``` public interface Inter{//接口 String hello(String str); } public class ShiXianLei implements Inter{//实现类 String hello(String str){ System.out.println(str); } } public class Test{//使用 public static void main(){ Inter in = new ShiXianlei();//父类指向子类 in.hello("nihao"); } } ``` ## Spring AOP 和 AspectJ AOP 有什么区别? **Spring AOP 属于运行时增强,而 AspectJ 是编译时增强。** Spring AOP 基于代理(Proxying),而 AspectJ 基于字节码操作(Bytecode Manipulation)。 Spring AOP 已经集成了 AspectJ ,AspectJ 应该算的上是 Java 生态系统中最完整的 AOP 框架了。AspectJ 相比于 Spring AOP 功能更加强大,但是 Spring AOP 相对来说更简单, 如果我们的切面比较少,那么两者性能差异不大。但是,当切面太多的话,最好选择 AspectJ ,它比Spring AOP 快很多。 ## Bean配置 在IOC容器中将所有的控制对象称作bean,Spring对于bean的使用有两种方式:基于spring-ioc.xml的配置和注解。 注意xml中关于bean的配置程序段 ``` <bean id="oneInterface(自定义)" class="配置的实现类"></bean> ``` 使用示例: ``` public void test(){ OneInterface interface=super.getBean("oneInterface");//获取bean,不需要new对象 interface.hello();//调用函数 } ``` ### 常用注入方式 Spring注入概念:指在启动Spring容器加载bean配置的时候,完成对变量的复制行为。(扫描xml文件中的bean标签时,实例化对象的同时,完成成员变量的赋值) Spring常用的注入方式: 1. 设值注入:即通过XML中配置bean的依赖类,通过层级property属性,来配置依赖关系,然后Spring通过setter方法,来实现依赖类的注入; 2. 构造器注入:方法同设值注入,不过具体实现的方法是通过显示的创造一个构造方法,构造方法的参数名称要与XML中配置的name名称一致,XML配置的标签为constructor-arg ``` 设值注入:通过一个成员变量的Set方式进行注入 <bean id="injectionService" class="com.imooc.ioc.injection.service.InjectionServiceImpl"> <property name="injectionDAO" ref="injectionDAO"/> </bean> <bean id="injectionDAO" class="com.imooc.ioc.injection.dao.InjectionDAOImpl"> </bean> ``` ``` 构造注入 <bean id="injectionService" class="com.imooc.ioc.injection.service.InjectionServiceImpl"> <constructor-arg name="injectionDAO" ref="injectionDAO"/> </bean> <bean id="injectionDAO" class="com.imooc.ioc.injection.dao.InjectionDAOImpl"> </bean> ``` ### Spring 中的 bean 的作用域有哪些? - BeanDefinition:描述Baen定义 - BeanDefinitionRegistry:提供向IOC容器注册BeanDefinition对象的方法 - singleton : 唯一 bean 实例,Spring 中的 bean 默认都是单例的。 - prototype : 每次请求都会创建一个新的 bean 实例。 - request : 每一次HTTP请求都会产生一个新的bean,该bean仅在当前HTTP request内有效。 - session : 每一次HTTP请求都会产生一个新的 bean,该bean仅在当前 HTTP session 内有效。 - global-session: 全局session作用域,仅仅在基于portlet的web应用中才有意义,Spring5已经没有了。Portlet是能够生成语义代码(例如:HTML)片段的小型Java Web插件。它们基于portlet容器,可以像servlet一样处理HTTP请求。但是,与 servlet 不同,每个 portlet 都有不同的会话 ### Spring 中的单例 bean 的线程安全问题了解吗? 大部分时候我们并没有在系统中使用多线程,所以很少有人会关注这个问题。单例 bean 存在线程问题,主要是因为当多个线程操作同一个对象的时候,对这个对象的非静态成员变量的写操作会存在线程安全问题。 常见的有两种解决办法: 1. 在Bean对象中尽量避免定义可变的成员变量(不太现实)。 2. 在类中定义一个ThreadLocal成员变量,将需要的可变成员变量保存在 ThreadLocal 中(推荐的一种方式)。 ### Spring 中的 bean 生命周期? 简单来讲 - 通过构造器或工厂方法创建Bean实例 - 为Bean的属性设置值和对其它Bean的引用 - 调用Bean的初始化方法 - Bean可以使用了 - 当容器关闭时,调用Bean的销毁方法 这部分网上有很多文章都讲到了,下面的内容整理自:<https://yemengying.com/2016/07/14/spring-bean-life-cycle/> ,除了这篇文章,再推荐一篇很不错的文章 :<https://www.cnblogs.com/zrtqsk/p/3735273.html> 。 - Bean 容器找到配置文件中 Spring Bean 的定义。 - Bean 容器利用 Java Reflection API 创建一个Bean的实例。 - 如果涉及到一些属性值 利用 `set()`方法设置一些属性值。 - 如果 Bean 实现了 `BeanNameAware` 接口,调用 `setBeanName()`方法,传入Bean的名字。 - 如果 Bean 实现了 `BeanClassLoaderAware` 接口,调用 `setBeanClassLoader()`方法,传入 `ClassLoader`对象的实例。 - 如果Bean实现了 `BeanFactoryAware` 接口,调用 `setBeanClassLoader()`方法,传入 `ClassLoade` r对象的实例。 - 与上面的类似,如果实现了其他 `*.Aware`接口,就调用相应的方法。 - 如果有和加载这个 Bean 的 Spring 容器相关的 `BeanPostProcessor` 对象,执行`postProcessBeforeInitialization()` 方法 - 如果Bean实现了`InitializingBean`接口,执行`afterPropertiesSet()`方法。 - 如果 Bean 在配置文件中的定义包含 init-method 属性,执行指定的方法。 - 如果有和加载这个 Bean的 Spring 容器相关的 `BeanPostProcessor` 对象,执行`postProcessAfterInitialization()` 方法 - 当要销毁 Bean 的时候,如果 Bean 实现了 `DisposableBean` 接口,执行 `destroy()` 方法。 - 当要销毁 Bean 的时候,如果 Bean 在配置文件中的定义包含 destroy-method 属性,执行指定的方法。 图示: ![Spring Bean 生命周期](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-9-17/48376272.jpg) 与之比较类似的中文版本: ![Spring Bean 生命周期](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-9-17/5496407.jpg) ## 说说自己对于 Spring MVC 了解? 谈到这个问题,我们不得不提提之前 Model1 和 Model2 这两个没有 Spring MVC 的时代。 - **Model1 时代** : 很多学 Java 后端比较晚的朋友可能并没有接触过 Model1 模式下的 JavaWeb 应用开发。在 Model1 模式下,整个 Web 应用几乎全部用 JSP 页面组成,只用少量的 JavaBean 来处理数据库连接、访问等操作。这个模式下 JSP 即是控制层又是表现层。显而易见,这种模式存在很多问题。比如①将控制逻辑和表现逻辑混杂在一起,导致代码重用率极低;②前端和后端相互依赖,难以进行测试并且开发效率极低; - **Model2 时代** :学过 Servlet 并做过相关 Demo 的朋友应该了解“Java Bean(Model)+ JSP(View,)+Servlet(Controller) ”这种开发模式,这就是早期的 JavaWeb MVC 开发模式。Model:系统涉及的数据,也就是 dao 和 bean。View:展示模型中的数据,只是用来展示。Controller:处理用户请求都发送给 ,返回数据给 JSP 并展示给用户。 Model2 模式下还存在很多问题,Model2的抽象和封装程度还远远不够,使用Model2进行开发时不可避免地会重复造轮子,这就大大降低了程序的可维护性和复用性。于是很多JavaWeb开发相关的 MVC 框架营运而生比如Struts2,但是 Struts2 比较笨重。随着 Spring 轻量级开发框架的流行,Spring 生态圈出现了 Spring MVC 框架, Spring MVC 是当前最优秀的 MVC 框架。相比于 Struts2 , Spring MVC 使用更加简单和方便,开发效率更高,并且 Spring MVC 运行速度更快。 MVC 是一种设计模式,Spring MVC 是一款很优秀的 MVC 框架。Spring MVC 可以帮助我们进行更简洁的Web层的开发,并且它天生与 Spring 框架集成。Spring MVC 下我们一般把后端项目分为 Service层(处理业务)、Dao层(数据库操作)、Entity层(实体类)、Controller层(控制层,返回数据给前台页面)。 **Spring MVC 的简单原理图如下:** ![](https://raw.githubusercontent.com/binbinbin5/myPics/master/file/20190901101601.png) ## SpringMVC 工作原理了解吗? **原理如下图所示:** ![SpringMVC运行原理](http://my-blog-to-use.oss-cn-beijing.aliyuncs.com/18-10-11/49790288.jpg) 上图的一个笔误的小问题:Spring MVC 的入口函数也就是前端控制器 `DispatcherServlet` 的作用是接收请求,响应结果。 **流程说明(重要):** 1. 客户端(浏览器)发送请求,直接请求到 `DispatcherServlet`。 2. `DispatcherServlet` 根据请求信息调用 `HandlerMapping`,解析请求对应的 `Handler`。 3. 解析到对应的 `Handler`(也就是我们平常说的 `Controller` 控制器)后,开始由 `HandlerAdapter` 适配器处理。 4. `HandlerAdapter` 会根据 `Handler `来调用真正的处理器开处理请求,并处理相应的业务逻辑。 5. 处理器处理完业务后,会返回一个 `ModelAndView` 对象,`Model` 是返回的数据对象,`View` 是个逻辑上的 `View`。 6. `ViewResolver` 会根据逻辑 `View` 查找实际的 `View`。 7. `DispaterServlet` 把返回的 `Model` 传给 `View`(视图渲染)。 8. 把 `View` 返回给请求者(浏览器) ## Spring 框架中用到了哪些设计模式? 关于下面一些设计模式的详细介绍,可以看笔主前段时间的原创文章[《面试官:“谈谈Spring中都用到了那些设计模式?”。》](https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247485303&idx=1&sn=9e4626a1e3f001f9b0d84a6fa0cff04a&chksm=cea248bcf9d5c1aaf48b67cc52bac74eb29d6037848d6cf213b0e5466f2d1fda970db700ba41&token=255050878&lang=zh_CN#rd) 。 - **工厂设计模式** : Spring使用工厂模式通过 `BeanFactory`、`ApplicationContext` 创建 bean 对象。 - **代理设计模式** : Spring AOP 功能的实现。 - **单例设计模式** : Spring 中的 Bean 默认都是单例的。 - **模板方法模式** : Spring 中 `jdbcTemplate`、`hibernateTemplate` 等以 Template 结尾的对数据库操作的类,它们就使用到了模板模式。 - **包装器设计模式** : 我们的项目需要连接多个数据库,而且不同的客户在每次访问中根据需要会去访问不同的数据库。这种模式让我们可以根据客户的需求能够动态切换不同的数据源。 - **观察者模式:** Spring 事件驱动模型就是观察者模式很经典的一个应用。 - **适配器模式** :Spring AOP 的增强或通知(Advice)使用到了适配器模式、spring MVC 中也是用到了适配器模式适配`Controller`。 - ...... ## @Component 和 @Bean 的区别是什么? 1. 作用对象不同: `@Component` 注解作用于类,而`@Bean`注解作用于方法。 2. `@Component`通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中(我们可以使用 `@ComponentScan` 注解定义要扫描的路径从中找出标识了需要装配的类自动装配到 Spring 的 bean 容器中)。`@Bean` 注解通常是我们在标有该注解的方法中定义产生这个 bean,`@Bean`告诉了Spring这是某个类的示例,当我需要用它的时候还给我。 3. `@Bean` 注解比 `Component` 注解的自定义性更强,而且很多地方我们只能通过 `@Bean` 注解来注册bean。比如当我们引用第三方库中的类需要装配到 `Spring`容器时,则只能通过 `@Bean`来实现。 `@Bean`注解使用示例: ```java @Configuration public class AppConfig { @Bean public TransferService transferService() { return new TransferServiceImpl(); } } ``` 上面的代码相当于下面的 xml 配置 ```xml <beans> <bean id="transferService" class="com.acme.TransferServiceImpl"/> </beans> ``` 下面这个例子是通过 `@Component` 无法实现的。 ```java @Bean public OneService getService(status) { case (status) { when 1: return new serviceImpl1(); when 2: return new serviceImpl2(); when 3: return new serviceImpl3(); } } ``` ## 将一个类声明为Spring的 bean 的注解有哪些? 我们一般使用 `@Autowired` 注解自动装配 bean,要想把类标识成可用于 `@Autowired` 注解自动装配的 bean 的类,采用以下注解可实现: - `@Component` :通用的注解,可标注任意类为 `Spring` 组件。如果一个Bean不知道属于拿个层,可以使用`@Component` 注解标注。 - `@Repository` : 对应持久层即 Dao 层,主要用于数据库相关操作。 - `@Service` : 对应服务层,主要涉及一些复杂的逻辑,需要用到 Dao层。 - `@Controller` : 对应 Spring MVC 控制层,主要用户接受用户请求并调用 Service 层返回数据给前端页面。 ## Spring 管理事务的方式有几种? 1. 编程式事务,在代码中硬编码。(不推荐使用) 2. 声明式事务,在配置文件中配置(推荐使用) **声明式事务又分为两种:** 1. 基于XML的声明式事务 2. 基于注解的声明式事务 ## Spring 事务中的隔离级别有哪几种? **TransactionDefinition 接口中定义了五个表示隔离级别的常量:** - **TransactionDefinition.ISOLATION_DEFAULT:** 使用后端数据库默认的隔离级别,Mysql 默认采用的 REPEATABLE_READ隔离级别 Oracle 默认采用的 READ_COMMITTED隔离级别. - **TransactionDefinition.ISOLATION_READ_UNCOMMITTED:** 最低的隔离级别,允许读取尚未提交的数据变更,**可能会导致脏读、幻读或不可重复读** - **TransactionDefinition.ISOLATION_READ_COMMITTED:** 允许读取并发事务已经提交的数据,**可以阻止脏读,但是幻读或不可重复读仍有可能发生** - **TransactionDefinition.ISOLATION_REPEATABLE_READ:** 对同一字段的多次读取结果都是一致的,除非数据是被本身事务自己所修改,**可以阻止脏读和不可重复读,但幻读仍有可能发生。** - **TransactionDefinition.ISOLATION_SERIALIZABLE:** 最高的隔离级别,完全服从ACID的隔离级别。所有的事务依次逐个执行,这样事务之间就完全不可能产生干扰,也就是说,**该级别可以防止脏读、不可重复读以及幻读**。但是这将严重影响程序的性能。通常情况下也不会用到该级别。 ## Spring 事务中哪几种事务传播行为? **支持当前事务的情况:** - **TransactionDefinition.PROPAGATION_REQUIRED:** 如果当前存在事务,则加入该事务;如果当前没有事务,则创建一个新的事务。 - **TransactionDefinition.PROPAGATION_SUPPORTS:** 如果当前存在事务,则加入该事务;如果当前没有事务,则以非事务的方式继续运行。 - **TransactionDefinition.PROPAGATION_MANDATORY:** 如果当前存在事务,则加入该事务;如果当前没有事务,则抛出异常。(mandatory:强制性) **不支持当前事务的情况:** - **TransactionDefinition.PROPAGATION_REQUIRES_NEW:** 创建一个新的事务,如果当前存在事务,则把当前事务挂起。 - **TransactionDefinition.PROPAGATION_NOT_SUPPORTED:** 以非事务方式运行,如果当前存在事务,则把当前事务挂起。 - **TransactionDefinition.PROPAGATION_NEVER:** 以非事务方式运行,如果当前存在事务,则抛出异常。 **其他情况:** - **TransactionDefinition.PROPAGATION_NESTED:** 如果当前存在事务,则创建一个事务作为当前事务的嵌套事务来运行;如果当前没有事务,则该取值等价于TransactionDefinition.PROPAGATION_REQUIRED。 # Spring代码演示 Spring作用将对象的创建交给Spring容器在applicationContext.xml配置文件中用bean声明要什么对象 ```xml <!--配置文件 applicationContext.xml中 //class:java类的全限定类名,他是通过全类名使用反射的技术进行创建 //id:给这个对象在整个应用程序上下文当中取一个唯一名字方便区分--> <!--bean是注入--> <!--bean2.xml--> <bean id="girl" class="cn.edu.sict.pojo.girl"> <property name="name" value="范冰冰"></property> <property name="age" value="23"></property> </bean> ``` ```xml <!--bean1.xml--> <bean id="yourgirl" class="cn.edu.sict.pojo.girl"> <property name="name" value="李冰冰"></property> <property name="age" value="23"></property> </bean> ``` ``` //获取该bean @Test public void t1() { //获取上下文对象Spring里面声明对象都需要通过上下文对象获取 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); /*读取多个Spring配置文件*/ ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml", "bean1.xml", "bean2.xml"}); //指定了class,不需要强转 girl girl = applicationContext.getBean("girl",girl.class); System.out.println(girl); girl girl2 = applicationContext.getBean("yourgirl",girl.class); System.out.println(girl2); } ``` 对象产生在配置文件中产生的,而不需要在类中修改。 ### 控制反转IOC 控制反转IOC也被称为依赖注入DI,控制既创建对象彼此关系的权利. 开始控制权在开发人员程序代码中掌控(new 的方式) ==Spring夺取控制权反转给Spring容器==,程序员只需要: - 声明要什么 - 然后Spring容器进行具体控制 容器 ![](https://raw.githubusercontent.com/binbinbin5/myPics/master/imgs/20190718130644.png) - pojos:自己定义的类 - metadata:在Spring的配置文件里面写的这些就是元数据 - 实例化容器:classpath... 将配置文件传入,实例化完毕 ##### 值得注入(DI) ###### setter注入(最常用) - 但是属性必须有对应的setter方法才可以完成 - 通过property 值注入 ``` ​ <property name="name" value="王菲"></property> ``` ###### 构造注入 默认通过无参构造器完成对象的创建的 如果没有无参构造器会报错: ```java //提供构造方法 public Car(String name, Double price, Double speed) { this.name = name; this.price = price; this.speed = speed; } public Car(String name, Double price) { this.name = name; this.price = price; } public Car(Double price, Double speed) { this.price = price; this.speed = speed; } ``` ```xml //构造方式一 name <constructor-arg name="name" value="凯迪拉克"></constructor-arg> <constructor-arg name="price" value="33333333"></constructor-arg> <constructor-arg name="speed" value="200"></constructor-arg> //构造方式二 index 会优先使用后面的构造器(不推荐) <bean id="car2" class="cn.edu.sict.pojo.Car"> <constructor-arg index="0" value="2343"></constructor-arg> <constructor-arg index="1" value="33333333"></constructor-arg> </bean> //构造方式三 type 按照构造函数入参类型自动选择 <bean id="car3" class="cn.edu.sict.pojo.Car"> <constructor-arg type="java.lang.String" value="2343"></constructor-arg> <constructor-arg type="java.lang.Double" value="33333333"></constructor-arg> </bean> ``` ##### bean元素探讨 属性探讨 - abstract=true bean将无法实例化,用于被继承 - parent指明父bean,将会继承父bean的所有内容,通过ID进行指引 如下: ``` <bean class="cn.edu.sict.pojo.Girl" id="yourgirl"></bean> <bean class="cn.edu.sict.pojo.Girl" id="hisgirl" parent="yourgirl"></bean> ``` - destroy-method:指定给bean销毁的时候执行的方法,适合做一下清理型工作,触发条件bean确实销毁,比如: - close - refreah - destory过时的方法 ```java ((ClassPathXmlApplicationContext) applicationContext).close(); close方法销毁容器 ((ClassPathXmlApplicationContext) applicationContext).refresh();refresh方法刷新容器 ((ClassPathXmlApplicationContext) applicationContext).destroy();destroy销毁已过时 ``` - init-method:初始化方法,优先执行方法,适合准备性工作。(比如数据库连接什么的),同一个bean默认单例模式,多个也只初始化一个method。 - name : 别名,可以通过他一样获取bean (多个别名name="g1,g2 g3")支持逗号空格多种分隔符 - scope:指定范围 - 单例模式singleton(默认) ==Spring上下文只有一个实例== - 原型模式:多例模式prototype ==可以不断获取新的==多个对象, - lazy-init: - ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");这句话完成就是上下文完毕,执行构造方法,初始化完毕,bean马上注入。 - true: 延迟初始化 初始化完成容器bean不会初始化,获取该bean初始化,getBean的时候初始化才注入获取。 - 直接初始化程序启动慢一点,内存消耗大一点,好处是使用bean快,延迟初始化则相反启动快,内存少,使用bean慢。 - depends-on 指明一个依赖的bean,如果某一个BEAN严重依赖另一个BEAN就会配置depend on - ref 指明一个bean ```java <bean id="girls" class="cn.edu.sict.pojo.Girl" lazy-init="true" depends-on="dog"> <!--非字面值可以描述的属性使用ref指向bean的ID--> <property name="dog" ref="dog"></property> </bean> <bean id="dog" class="cn.edu.sict.pojo.Dog"> <property name="name" value="哮天犬"></property> </bean> ``` - alias标签指定bean的别名 ```java <alias name="dog" alias="gdog"></alias> <bean id="dog" class="cn.edu.sict.pojo.Dog"> <property name="name" value="哮天犬"></property> </bean> /*bean的别名*/ @Test public void t7() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean3.xml"); //直接通过类类型获取只有一个才可以 Dog Girl1 = applicationContext.getBean( Dog.class); } ``` spring 多个配置文件中的bean是可以互相引用的(被上下文扫描到) #### Spring中各种值的注入 简单值 直接写, 复杂就用内部BEAN。 ``` public class People{ private String name; private int age; private String[] firend; private List<numbers> nums; private List<Cat> nums; private Set<Pig> pigs; private Map<String,User> user; ...setter,getter... } public class Cat{ //名字,类型,... } ``` ##### String[] ``` //第一种可以使用逗号分隔数组元素 <bean id="people" class="cn.edu.sict.pojo.People"> <property name="name" value="阿发"></property> <property name="age" value="66"></property> <property name="firends" value="郭富城,刘德华"></property> </bean> //第二种通过array标签描述数组 <bean id="people" class="cn.edu.sict.pojo.People"> <property name="name" value="阿发"></property> <property name="age" value="66"></property> <property name="firends"> <array> <value>刘德华</value> <value>郭富城</value> </array> </property> </bean> ``` ##### List < Integer>集合 ``` <property name="nums"> <list> <value>8</value> <value>7</value> </list> </property> ``` ##### List< Cat> Cat为一个pojo类 ``` <property name="name" value="阿发"></property> <property name="age" value="66"></property> <property name="cats"> <list><!--内部bean无法引用--> <bean class="cn.edu.sict.pojo.Cat"> <property name="leg" value="2"></property> <property name="skin" value="蓝色"></property> </bean> <bean class="cn.edu.sict.pojo.Cat"> <property name="leg" value="4"></property> <property name="skin" value="青色"></property> </bean> </list> </property> ``` ##### Set< Pig> ``` <property name="pig"> <set> <bean class="cn.edu.sict.pojo.Pig"> <property name="name" value="小花"></property> <property name="sleep" value="88"></property> <property name="kw" value="香辣"></property> </bean> <bean class="cn.edu.sict.pojo.Pig"> <property name="name" value="小宝"></property> <property name="sleep" value="88"></property> <property name="kw" value="酱香"></property> </bean> </set> </property> ``` ##### Map< String,User> ``` <property name="users"> <map> <entry key="user1"> <bean class="cn.edu.sict.pojo.User"> <property name="name" value="韩雪"></property> <property name="address" value="梧桐村"></property> </bean> </entry> <entry key="user2"> <bean class="cn.edu.sict.pojo.User"> <property name="name" value="林青霞"></property> <property name="address" value="台湾"></property> </bean> </entry> </map> </property> ``` ### 自动驻入 ``` public class user{ priavte String name; priavte String address; priavte Pig pig; } ``` autowire - byType 根据数据类型注入属性,在上下文中搜寻bean,有且只有一个注入,多个抛出异常,没有不注入。 - byName 按照bean对应pojo里面的属性名字进行匹配 private Pig pig(这边bean中 name = "pig"); - constructor - 优先按照类型匹配,匹配到一个直接注入,不止一个按照名字注入,名字找不到,注入失败 - default 默认值 - none 不会自动驻入 ``` //byType根据类型进行注入它的属性,此时在上下文当中搜寻Pig这个bean,找到有且仅有一个的情况 //下,注入成功,一个没有,不会注入,不止一个,抛出异常. <bean id="user" class="cn.edu.sict.pojo.User" autowire="byType"> <property name="name" value="陈慧琳"/> <property name="address" value="香港"/> </bean> <bean class="cn.edu.sict.pojo.Pig"> <property name="name" value="大宝"></property> </bean> //当有多个bean时 使用primary定义一个主次 <bean class="cn.edu.sict.pojo.Pig" primary="true"> <property name="name" value="大宝"></property> </bean> <bean class="cn.edu.sict.pojo.Pig" primary="false"> <property name="name" value="巨大宝"></property> </bean> ``` ### Spring注解 从一个文件引入多个配置文件 ```xml <bean > <!--引入所有的spring-开头的xml文件--> <import resource = "classpath:spring/spring-*.xml"> </bean> ``` ```xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd"> <!-- 自动扫描的包名,如果有多个包,请使用逗号隔开 --> <context:component-scan base-package="com.jieyou.*" /> <!-- 默认的注解映射的支持 --> <mvc:annotation-driven /> <!-- 启动对aspectj的支持 --> <aop:aspectj-autoproxy/> <!-- 自动搜索指定包及其子包下的所有Bean类 --> <context:component-scan base-package="com.jieyou.*"> <!-- 排除子包不扫描org.springframework.stereotype.Repository--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"> </context> </bean> ``` - @Configuration定义配置类,可替换xml配置文件,使用AnnotationConfigApplicationContext扫描 - @ComponentScan定义**扫描的路径**从中找出标识了**需要装配**的类自动装配到spring的bean容器中 - @Component 标明一个类为Spring的一个组件,可以被Spring容器管理它是普通组件的语义 - @Service 同上语义上属于服务层 - @Repository同上语义上属于DAO层 - @Controller同上语义上属于控制层 - @ComponentScan:组件扫描,目标在哪个路径 - @Bean在Spring容器中注册一个bean - @Autowired自动驻入组件 ### AOP applicationContext.xml ```xml 1. <!--aop基于自动代理,启动激活--> <aop:aspectj-autoproxy/> 2. 注册切面 <bean></bean> 3. 配置切入点信息 <aop.config></aop.config> ``` #### 简介 面向切面编程: - 面向过程编程由起点到终点解决问题方式很直接,但是期间多次解决类似问题的过程时,期间可能会有几段的重复问题. - 传统方式书写代码是从上到下,而AOP的重点将关注的重点将纵向变为了横向 #### 需要添加的jar包 ```java <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.1.5.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.9.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.2</version> </dependency> ``` #### 属性 ``` import org.aspectj.lang.JoinPoint; JointPoint可以通过该类获取AOP中的一些信息方法名等的一些参数信息 ``` Aspect(切面): 通常是一个类 JointPoint(连接点):程序执行过程中明确的点,一般是方法的调用 Advice(通知): AOP在特定的切入点上执行的增强处理: Pointcut(切入点): 带有通知的连接点,在程序中主要体现为书写切入点表达式 匹配连接点的谓词。建议与切入点表达式相关联,并在切入点匹配的任何连接点处运行(例如,执行具有特定名称的方法)。由切入点表达式匹配的连接点的概念是AOP的核心,Spring默认使用AspectJ切入点表达式语言。 *简介*:代表类型声明其他方法或字段。Spring AOP允许您向任何建议的对象引入新接口(以及相应的实现)。例如,您可以使用简介使bean实现` IsModified` 接口,以简化缓存。(介绍被称为AspectJ社区中的类型间声明。) *目标对象*:由一个或多个方面建议的对象。也称为 *建议*对象。由于Spring AOP是使用运行时代理实现的,因此该对象始终是 *代理*对象。 *AOP代理*:由AOP框架创建的对象,用于实现方面契约(建议方法执行等)。在Spring Framework中,AOP代理将是JDK动态代理(必须实现某个接口在接口情况下)或CGLIB代理。 织入(*Weaving*):最终以何种行为使之生效,该行为就称之为织入. #### 增强类型 - before: 标识一个前置增强方法 - after: 标识一个 后置增强方法 - after-returning 返回结果之后增强 - after-throwing: 异常抛出增强 - around: 环绕增强,添加后需要手动让目标方法执行 #### AOP代理 ##### XML方式 ```xml //执行任何公共方法: //表示任意的类下的任意的方法的任意的参数 //execution(public * *(..)) <!--1.aop基于代理完成,先要激活代理--> <aop:aspectj-autoproxy/> <!--2.注册一个切面具体要使用的类--> <bean id="beforeAdvice" class="cn.edu.sict.advice.BeforeAdvice"></bean> <!--3.配置切入点等等信息--> <aop:config> <aop:aspect id="beforeAspect" ref="beforeAdvice"> <!--aop:before表明是前置通知 method具体使用什么方法来切 pointcut切入点--> <!--<aop:before method="methodBefore" pointcut="execution(* cn.edu.sict.*.*(..))"></aop:before>--> <!-- execution(public * *(..)) 切无参 execution(public * *(java.lang.String)) 切单个参数 execution(public * *(java.lang.String,int)) 多个(基本数据类型和包装类严格区分) --> <aop:before method="methodBefore" pointcut="execution(public * *(..))"></aop:before> </aop:aspect> </aop:config> ``` ```java <!--4.测试类是否增强--> @Test public void t1() { ApplicationContext ctx = new ClassPathXmlApplicationContext("appliectionContext.xml"); ProviderService providerService = ctx.getBean("providerService", ProviderService.class); providerService.add(); } ``` ```xml <!--返回结果后增强,比after先执行--> <aop:aspect ref="afterReturningAdvice"> <aop:after-returning method="afterReturning" returning="returning" pointcut="execution(public * *(..))"/> </aop:aspect> package cn.edu.sict.advice; public class AfterReturningAdvice { public void afterReturning(String returning){ System.out.println("在返回结果之后执行..."); System.out.println("返回值:"+returning); } } package cn.edu.sict.service; public class AfterReturningService { public String msg(){ System.out.println("执行AfterReturningService.msg()"); return "王祖贤"; } } <!-- 对于增强的AfterReturningService.msg()方法可以通过returning="returning" 属性将 增强方法AfterReturningAdvice.afterReturning()中的returning和 要增强的方法AfterReturningService.msg()中return值绑定起来 returning="绑定值"要和AfterReturningAdvice.afterReturning()中的值名称一致--> ``` ## 注解方式 ```xml <!-- 在applicationContext.xml配置--> <!--开启代理--> <aop:aspectj-autoproxy/> <!--配置基础扫描包--> <context:component-scan base-package="cn.edu.sict"></context:component-scan> ``` ##### 多个想同类型增强类之间的执行顺序 可以再类前加入注解@Order(X)指明顺序 BeforeAdvice1 ```java @Order(1)//用于排序,不过推荐使用两个类的@Order()如下2,3 @Aspect //标记为一个切面 @Component("BeforeAdvice1")//标记当前类为Spring的组件,相当于在XML注册一个bean public class BeforeAdvice1 { /** @Order(2)//这样也可以一个类中两个前置切面 @Before("execution(public * *(..))") public void before1() { System.out.println("前置通知2..."); }*/ @Order(1) @Before("execution(public * *(..))") public void before() { System.out.println("前置通知1..."); } ``` BeforeAdvice2 ``` @Order(2)//before和after顺序不一样 @Aspect //标记为一个切面 @Component("BeforeAdvice2")//标记当前类为Spring的组件,相当于在XML注册一个bean public class BeforeAdvice2 { @Before("execution(public * *(..))") public void before() { System.out.println("前置通知2..."); } } ``` BeforeAdvice3 ```java @Order(3) @Aspect //标记为一个切面 @Component("BeforeAdvice3")//标记当前类为Spring的组件,相当于在XML注册一个bean public class BeforeAdvice3 { @Before("execution(public * *(..))") public void before() { System.out.println("前置通知3..."); } ``` ##### 异常抛出增强注解 ``` @Aspect @Component public class AfterThrowingAdvice { @AfterThrowing(value = "execution(public * *(..))",throwing = "throwing") public void exe(JoinPoint joinPoint,Throwable throwing) { System.out.println("抛出异常执行..."); System.out.println("异常之前"+joinPoint.getSignature()); System.out.println("异常之后"+throwing); } } //异常增强类 ``` ##### 环绕增强手动让目标方法执行以及处理异常注意事项 ```java @Aspect @Component public class AroundAdvice { public void AroundAdvices() { System.out.println("环绕增强..."); } @Around("execution(public * *(..))") public Object around(ProceedingJoinPoint pjp) throws Throwable { System.out.println("环绕增强..."); //作用是让目标方法执行 Object proceed = pjp.proceed(); return proceed; } } } //在处理异常时除了上述继承Throwable异常类还有 try/catch方式 public Object around(ProceedingJoinPoint pjp) { System.out.println("环绕增强..."); //作用是让目标方法执行 Object proceed = null; try { proceed = pjp.proceed(); } catch (Throwable throwable) { throwable.printStackTrace(); } return proceed; } //第一种方式遇到异常仍然会抛出 //第二种遇到异常会进入catch内不会抛出异常 //由于没有跑出异常会造成AOP中的异常增强的内容不会奏效 ``` ##### executeion表达式 先写访问修饰符 包的限定 类名 方法名 参数类型 + 组合条件,同事符合两个条件,多个条件和一个都可以。 ``` public com.sz..*.*(java.lang.String,...) 修饰符为public的并且是在sz包下面的或者子包下面的任意类的热议的方法的一个参数为String的方法(后面可以多个参数的)就可以切到 ``` # Spring相关教程/资料 ### 官网相关 - [Spring官网](https://spring.io/) - [Spring系列主要项目](https://spring.io/projects) - [Spring官网指南](https://spring.io/guides) - [Spring Framework 4.3.17.RELEASE API](https://docs.spring.io/spring/docs/4.3.17.RELEASE/javadoc-api/) ## 系统学习教程 ### 文档 - [极客学院Spring Wiki](http://wiki.jikexueyuan.com/project/spring/transaction-management.html) - [Spring W3Cschool教程 ](https://www.w3cschool.cn/wkspring/f6pk1ic8.html) ### 视频 - [网易云课堂——58集精通java教程Spring框架开发](http://study.163.com/course/courseMain.htm?courseId=1004475015#/courseDetail?tab=1&35) - **黑马视频和尚硅谷视频(非常推荐): ## 面试必备知识点 ### SpringAOP,IOC实现原理 AOP实现原理、动态代理和静态代理、Spring IOC的初始化过程、IOC原理、自己实现怎么实现一个IOC容器?这些东西都是经常会被问到的。 推荐阅读: - [自己动手实现的 Spring IOC 和 AOP - 上篇](http://www.coolblog.xyz/2018/01/18/自己动手实现的-Spring-IOC-和-AOP-上篇/) - [自己动手实现的 Spring IOC 和 AOP - 下篇](http://www.coolblog.xyz/2018/01/18/自己动手实现的-Spring-IOC-和-AOP-下篇/) ### AOP AOP思想的实现一般都是基于 **代理模式** ,在JAVA中一般采用JDK动态代理模式,但是我们都知道,**JDK动态代理模式只能代理接口而不能代理类**。因此,Spring AOP 会这样子来进行切换,因为Spring AOP 同时支持 CGLIB、ASPECTJ、JDK动态代理。 - 如果目标对象的实现类实现了接口,Spring AOP 将会采用 JDK 动态代理来生成 AOP 代理类; - 如果目标对象的实现类没有实现接口,Spring AOP 将会采用 CGLIB 来生成 AOP 代理类——不过这个选择过程对开发者完全透明、开发者也无需关心。 推荐阅读: - [静态代理、JDK动态代理、CGLIB动态代理讲解](http://www.cnblogs.com/puyangsky/p/6218925.html) :我们知道AOP思想的实现一般都是基于 **代理模式** ,所以在看下面的文章之前建议先了解一下静态代理以及JDK动态代理、CGLIB动态代理的实现方式。 - [Spring AOP 入门](https://juejin.im/post/5aa7818af265da23844040c6) :带你入门的一篇文章。这篇文章主要介绍了AOP中的基本概念:5种类型的通知(Before,After,After-returning,After-throwing,Around);Spring中对AOP的支持:AOP思想的实现一般都是基于代理模式,在Java中一般采用JDK动态代理模式,Spring AOP 同时支持 CGLIB、ASPECTJ、JDK动态代理, - [Spring AOP 基于AspectJ注解如何实现AOP](https://juejin.im/post/5a55af9e518825734d14813f) : **AspectJ是一个AOP框架,它能够对java代码进行AOP编译(一般在编译期进行),让java代码具有AspectJ的AOP功能(当然需要特殊的编译器)**,可以这样说AspectJ是目前实现AOP框架中最成熟,功能最丰富的语言,更幸运的是,AspectJ与java程序完全兼容,几乎是无缝关联,因此对于有java编程基础的工程师,上手和使用都非常容易。Spring注意到AspectJ在AOP的实现方式上依赖于特殊编译器(ajc编译器),因此Spring很机智回避了这点,转向采用动态代理技术的实现原理来构建Spring AOP的内部机制(动态织入),这是与AspectJ(静态织入)最根本的区别。**Spring 只是使用了与 AspectJ 5 一样的注解,但仍然没有使用 AspectJ 的编译器,底层依是动态代理技术的实现,因此并不依赖于 AspectJ 的编译器**。 Spring AOP虽然是使用了那一套注解,其实实现AOP的底层是使用了动态代理(JDK或者CGLib)来动态植入。至于AspectJ的静态植入,不是本文重点,所以只提一提。 - [探秘Spring AOP(慕课网视频,很不错)](https://www.imooc.com/learn/869):慕课网视频,讲解的很不错,详细且深入 - [spring源码剖析(六)AOP实现原理剖析](https://blog.csdn.net/fighterandknight/article/details/51209822) :通过源码分析Spring AOP的原理 ### IOC Spring IOC的初始化过程: ![Spring IOC的初始化过程](https://user-gold-cdn.xitu.io/2018/5/22/16387903ee72c831?w=709&h=56&f=png&s=4673) - [[Spring框架]Spring IOC的原理及详解。](https://www.cnblogs.com/wang-meng/p/5597490.html) - [Spring IOC核心源码学习](https://yikun.github.io/2015/05/29/Spring-IOC核心源码学习/) :比较简短,推荐阅读。 - [Spring IOC 容器源码分析](https://javadoop.com/post/spring-ioc) :强烈推荐,内容详尽,而且便于阅读。 ## Spring事务管理 - [可能是最漂亮的Spring事务管理详解](https://juejin.im/post/5b00c52ef265da0b95276091) - [Spring编程式和声明式事务实例讲解](https://juejin.im/post/5b010f27518825426539ba38) ### Spring单例与线程安全 - [Spring框架中的单例模式(源码解读)](http://www.cnblogs.com/chengxuyuanzhilu/p/6404991.html):单例模式是一种常用的软件设计模式。通过单例模式可以保证系统中一个类只有一个实例。spring依赖注入时,使用了 多重判断加锁 的单例模式。 ### Spring源码阅读 阅读源码不仅可以加深我们对Spring设计思想的理解,提高自己的编码水品,还可以让自己在面试中如鱼得水。下面的是Github上的一个开源的Spring源码阅读,大家有时间可以看一下,当然你如果有时间也可以自己慢慢研究源码。 - [spring-core](https://github.com/seaswalker/Spring/blob/master/note/Spring.md) - [spring-aop](https://github.com/seaswalker/Spring/blob/master/note/spring-aop.md) - [spring-context](https://github.com/seaswalker/Spring/blob/master/note/spring-context.md) - [spring-task](https://github.com/seaswalker/Spring/blob/master/note/spring-task.md) - [spring-transaction](https://github.com/seaswalker/Spring/blob/master/note/spring-transaction.md) - [spring-mvc](https://github.com/seaswalker/Spring/blob/master/note/spring-mvc.md) - [guava-cache](https://github.com/seaswalker/Spring/blob/master/note/guava-cache.md)
Go
UTF-8
4,327
2.875
3
[]
no_license
package main import ( "github.com/gorilla/websocket" "github.com/gofrs/uuid" "time" "log" "sync" "encoding/json" "net/http" ) type Client struct { id string conn *websocket.Conn sendLock sync.Mutex // sendCallback is callback based on packetID sendCallback map[string]func(req WSPacket) sendCallbackLock sync.Mutex // recvCallback is callback when receive based on ID of the packet recvCallback map[string]func(req WSPacket) Done chan struct{} } type WSPacket struct { ID string `json:"id"` Data string `json:"data"` RoomID string `json:"room_id"` PlayerIndex int `json:"player_index"` TargetHostID string `json:"target_id"` PacketID string `json:"packet_id"` // Globally ID of a session SessionID string `json:"session_id"` } func (c *Client) Send(request WSPacket, callback func(response WSPacket)) { request.PacketID = uuid.Must(uuid.NewV4()).String() data, err := json.Marshal(request) if err != nil { return } // TODO: Consider using lock free // Wrap callback with sessionID and packetID if callback != nil { wrapperCallback := func(resp WSPacket) { defer func() { if err := recover(); err != nil { log.Println("Recovered from err in client callback ", err) } }() resp.PacketID = request.PacketID resp.SessionID = request.SessionID callback(resp) } c.sendCallbackLock.Lock() c.sendCallback[request.PacketID] = wrapperCallback c.sendCallbackLock.Unlock() } c.sendLock.Lock() c.conn.SetWriteDeadline(time.Now().Add(time.Duration(1))) c.conn.WriteMessage(websocket.TextMessage, data) c.sendLock.Unlock() } // Heartbeat maintains connection to server func (c *Client) Heartbeat() { // send heartbeat every 1s timer := time.Tick(time.Second) for range timer { select { case <-c.Done: log.Println("Close heartbeat") return default: } c.Send(WSPacket{ID: "heartbeat"}, nil) } } func (o *Client) WS(w http.ResponseWriter, r *http.Request) { log.Println("Browser connected to overlord") defer func() { if r := recover(); r != nil { log.Println("Warn: Something wrong. Recovered in ", r) } }() c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("[!] WS upgrade:", err) return } defer c.Close() client := NewBrowserClient(c) go client.Cl.Listen() } func NewClient(conn *websocket.Conn) *Client { id := uuid.Must(uuid.NewV4()).String() sendCallback := map[string]func(WSPacket){} recvCallback := map[string]func(WSPacket){} return &Client{ id: id, conn: conn, sendCallback: sendCallback, recvCallback: recvCallback, Done: make(chan struct{}), } } // NewOverlordClient returns a client connecting to browser. This connection exchanges information between clients and server func NewBrowserClient(c *websocket.Conn) *BrowserClient { return &BrowserClient{ Cl: NewClient(c), } } type BrowserClient struct { Cl *Client } func (c *Client) Listen() { for { c.conn.SetReadDeadline(time.Now().Add(time.Duration(1))) _, rawMsg, err := c.conn.ReadMessage() if err != nil { log.Println("[!] read:", err) // TODO: Check explicit disconnect error to break close(c.Done) break } wspacket := WSPacket{} err = json.Unmarshal(rawMsg, &wspacket) if err != nil { log.Println("Warn: error decoding", rawMsg) continue } // Check if some async send is waiting for the response based on packetID // TODO: Change to read lock. //c.sendCallbackLock.Lock() callback, ok := c.sendCallback[wspacket.PacketID] //c.sendCallbackLock.Unlock() if ok { go callback(wspacket) //c.sendCallbackLock.Lock() delete(c.sendCallback, wspacket.PacketID) //c.sendCallbackLock.Unlock() // Skip receiveCallback to avoid duplication continue } // Check if some receiver with the ID is registered if callback, ok := c.recvCallback[wspacket.ID]; ok { go callback(wspacket) } } } func main() { c := &Client{ sendCallback: make(map[string]func(req WSPacket)), recvCallback: make(map[string]func(req WSPacket)), Done: make(chan struct{}), } // browser facing port go func() { http.HandleFunc("/ws", c.WS) }() http.ListenAndServe(":53000", nil) con, _, err := websocket.DefaultDialer.Dial("ws://localhost:9000/wso", nil) if err != nil { panic(err) } c.conn = con }
Java
UTF-8
3,162
2.125
2
[]
no_license
package com.alexzh.tutorial.notificationdemo; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.alexzh.tutorial.notificationdemo.data.DummyData; import com.alexzh.tutorial.notificationdemo.data.model.City; import com.bumptech.glide.Glide; import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.transition.Transition; public class DetailActivity extends AppCompatActivity { public static final String CITY_ID = "city_id"; public static final int INVALID_VALUE = -1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); final Toolbar toolbar = findViewById(R.id.toolbar); final TextView textView = findViewById(R.id.description_textView); final TextView source = findViewById(R.id.source_textView); setupToolbar(toolbar); final long cityId = getIntent().getLongExtra(CITY_ID, INVALID_VALUE); if (cityId != INVALID_VALUE) { final City city = DummyData.getCityById(cityId); if (city != null) { textView.setText(city.getDescription()); Glide.with(this) .load(city.getImageURL()) .into(new SimpleTarget<Drawable>() { @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) { toolbar.setBackground(resource); } }); } } source.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (cityId != INVALID_VALUE) { final City city = DummyData.getCityById(cityId); Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(city.getSource())); startActivity(myIntent); } } }); } private void setupToolbar(@Nullable final Toolbar toolbar) { setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(""); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } }
Java
UTF-8
765
1.5625
2
[]
no_license
import android.graphics.Color; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.view.View; import com.tencent.mobileqq.filemanager.util.FileManagerUtil.TipsClickedInterface; public final class fyj extends ClickableSpan { public fyj(FileManagerUtil.TipsClickedInterface paramTipsClickedInterface) {} public void onClick(View paramView) { this.a.a(paramView); } public void updateDrawState(TextPaint paramTextPaint) { paramTextPaint.setColor(Color.rgb(26, 144, 240)); paramTextPaint.setUnderlineText(false); } } /* Location: L:\local\mybackup\temp\qq_apk\com.tencent.mobileqqi\classes2.jar * Qualified Name: fyj * JD-Core Version: 0.7.0.1 */
C#
UTF-8
1,317
2.578125
3
[]
no_license
using TechTalk.SpecFlow; using NUnit.Framework; using OpenQA.Selenium; using AllureReportSample.PageClass; namespace AllureReportSample.Steps { [Binding] public class LoginSteps { private readonly IWebDriver _driver; private readonly LoginPage loginpage; public LoginSteps(IWebDriver driver) { _driver = driver; loginpage = new LoginPage(_driver); } [Given(@"User launches pluralsight application via ""(.*)""")] public void GivenUserLaunchesPluralsightApplicationVia(string url) { _driver.Navigate().GoToUrl(url); System.Threading.Thread.Sleep(2000); } [When(@"User enters login credentials")] public void WhenUserEntersLoginCredentials(Table table) { loginpage.GetUsername(table.Rows[0][0]); System.Threading.Thread.Sleep(2000); loginpage.GetPassword(table.Rows[0][1]); System.Threading.Thread.Sleep(2000); } [Then(@"User will be navigated to the error page")] public void ThenUserWillBeNavigatedToTheErrorPage() { Assert.That(_driver.Url, Is.EqualTo("https://app.pluralsight.com/id")); System.Threading.Thread.Sleep(2000); } } }
Markdown
UTF-8
582
2.703125
3
[ "BSD-3-Clause" ]
permissive
# instalint.vim Uses Vim's syntax highlighting to instantly bring out trailing whitespaces, tabs, duplicated word or any other regex. ## Installation Assuming you have Pathogen up and running: $ cd ~/.vim/bundle $ git clone git://github.com/adaszko/instalint.vim Add per-filetype configuration to your `.vimrc`: ``` let g:instalint_filetypes = { 'python': ['Tabs', 'TrailingSpaces', 'TrailingSemicolons'] } ``` where `python` is a some valid `'filetype'` option value and the list contains names of highlighting groups. ## Author Adam Szkoda <adaszko@gmail.com> ## License BSD3
C#
UTF-8
2,806
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Summary description for clsEstudiante /// </summary> public class clsEstudiante { public clsEstudiante() { this.IdEstudiante = _idEstudiante; this.Nombre = _nombre; this.Apellido = _apellido; this.Cedula = _cedula; this.Nota = _nota; this.Nota2 = _nota2; this.Nota3 = _nota3; this.NotaTotal = 0; } //Atributos private string _idEstudiante; private string _nombre; private string _apellido; private string _cedula; private double _nota; private double _nota2; private double _nota3; private double _notaTotal; private string _status; //Metodos set y get public string IdEstudiante { get { return _idEstudiante; } set { _idEstudiante = value; } } public double Nota2 { get { return _nota2; } set { _nota2 = value; } } public double Nota3 { get { return _nota3; } set { _nota3 = value; } } public string Nombre { get { return _nombre; } set { _nombre = value; } } public string Apellido { get { return _apellido; } set { _apellido = value; } } public string Cedula { get { return _cedula; } set { _cedula = value; } } public double Nota { get { return _nota; } set { _nota = value; } } public double NotaTotal { get { return _notaTotal; } set { _notaTotal = value; } } public double Suma() { double Suma; Suma = Nota + Nota2; return Suma; } public string Status1 { get { return _status; } set { _status = value; } } public string Status() { String status; if ((Nota + Nota2 >= 14)) { status = Convert.ToString('A'); } else { if ((Nota + Nota2 >= 9 && Nota + Nota2 < 14)) { status = Convert.ToString('F'); } else { status = Convert.ToString('F'); } } return status; } public double SumaSupletorio(string status) { double suma=0; if (String.Compare(status, Convert.ToString("A")) == 0) { suma = Nota + Nota2 + Nota3; } return suma; } public string ActualizarEstadoLuegoSupletorio(double suma) { String status; if (suma >= 24) { status = Convert.ToString('A'); } else { status = Convert.ToString('F'); } return status; } }
Markdown
UTF-8
6,486
3.21875
3
[]
no_license
# CS401 Assignment 1 **Name**: 徐逸飞(Yifei Xu) **SID**: 11611209 ## Notion: ## * Given position: $$\vec P​$$ = (x, y) * GIven field scaling: *K* * The velocity: $$\vec V​$$ * The maximum distance of influence: *R* * The minimum distance of influence: *r* ## Part 1 - Analysis **How to generate uniform, perpendicular, attractive, repulse, tangential forces for a robot and obstacles with known positions?** 1. **Uniform** > $$\vec V = V_{0}​$$ 2. **Perpendicular** >$$\vec V =\vec B_{0} , where\ \vec B_{0} * \vec P = 0 $$ 3. **Attractive** > $$\vec V =\left\{\begin{matrix} > 0& & \vec P < \vec r\\ > -K * \vec P& & \vec r \leqslant \vec P \leqslant \vec R\\ > 0& & \vec P > \vec R > \end{matrix}\right.​$$ 4. **Repulse** > $$\vec V =\left\{\begin{matrix} > 0& & \vec P < \vec r\\ > K * (\vec R - \vec P)& & \vec r \leqslant \vec P \leqslant \vec R\\ > 0& & \vec P > \vec R > \end{matrix}\right.​$$ 5. **Tangential** > $$\vec V = \vec \omega \times \vec P​$$ ## Part 2 - Draw the Field 1. ### Uniform ![Uniform_field.png](./image/Uniform_field.png) --- 2. ### Perparticular ![Perparticular_field.png](./image/Perparticular_field.png) --- 3. ### Attractive ![Attractive.png](./image/Attractive_field.png) --- 4. ### Repulse ![Repulse_field.png](./image/Repulse_field.png) --- 5. ### Tangential ![Tangential_field.png](./image/Tangential_field.png) --- ## Part 3 - Put the Robot In It! 1. ### Uniform ![Uniform_robot.png](./image/Uniform_robot.png) --- 2. ### Perparticular ![Perparticular_robot.png](./image/Perparticular_robot.png) --- 3. ### Attractive ![Attractive_robot.png](./image/Attractive_robot.png) --- 4. ### Repulse ![Repulse_robot.png](./image/Repulse_robot.png) --- 5. ### Tangential ![Tangential_robot.png](./image/Tangential_robot.png) --- ## Part 4 - The CODE ```matlab function test() clc close all clear all %% =========== Set the paramters ======= R = 3; r = 0.5; T=0.01; % Sampling Time k=2; % Sampling counter X(k-1)=1; % initilize the state x Y(k-1)=1; % initilize the state y tfinal=100; % final simulation time t=0; % intilize the time %===================================== %% =========== Main function ======= while(t<=tfinal) t=t+T; % increase the time V=5; % you can change the function here to test different fields. result = perparticular(X(k-1),Y(k-1)); X(k)=V*result(1)*T+X(k-1); % calculating x Y(k)=V*result(2)*T+Y(k-1); % calculating y % you can change the function here to draw different fields. draw_perparticular(X(k),Y(k)); k=k+1; % increase the sampling counter end %===================================== %% =========== Function defination ======= function result = attractive(x,y) if(x<=R && x>=-R&&y<=R&&y>=-R) result = [-x,-y]; else result = [0,0]; end end function result = uniform(x,y) if(x<=R && x>=-R&&y<=R&&y>=-R) result = [1,0]; else result = [0,0]; end end function result = perparticular(x,y) if(x<=R && x>=-R&&y>=0&&y<=R) result = [0,1]; else result = [0,0]; end end function result = repulse(x,y) if(x^2+y^2<r^2) result = [sign(x)*Inf,sign(y)*Inf]; elseif(x^2+y^2>R^2) result = [0,0]; elseif(x==0) result = [0,sign(y)*(R-abs(y))]; else slop = y/x; x2 = R/sqrt(slop^2+1)*sign(x); y2 = abs(slop)*R/sqrt(slop^2+1)*sign(y); result = [x2-x,y2-y]; end end function result = tangential(x,y) if(x<=R && x>=-R&&y<=R&&y>=-R) l = sqrt(y^2+x^2); sita = atan(abs(y)/abs(x)); if(x>=0&&y<0) sita = 2*pi - sita; elseif(x<=0&&y<0) sita = pi + sita; elseif(x<=0&&y>=0) sita = pi - sita; end sita = sita +pi/4; x2 = sqrt(2)*l*cos(sita); y2 = sqrt(2)*l*sin(sita); result = [x2-x,y2-y]; else result = [0,0]; end end function draw_attractive(a,b) hold on plot(0,0,'ro','MarkerFaceColor','r'); [x,y] = meshgrid(-R:.5:R,-R:.5:R); u = -x; v = -y; quiver(x,y,u,v); plot(a,b,'ro','MarkerFaceColor','b'); drawnow hold off end function draw_uniform(a,b) hold on [x,y] = meshgrid(-R:1:R,-R:1:R); u = ones(size(x)); v = zeros(size(y)); quiver(x,y,u,v); plot(a,b,'ro','MarkerFaceColor','b'); drawnow hold off end function draw_perparticular(a,b) hold on rectangle('position',[-R,-R/2,2*R,R/2]); [x,y] = meshgrid(-R:.5:R,0:1:R); u = zeros(size(x)); v = ones(size(y)); quiver(x,y,u,v); plot(a,b,'ro','MarkerFaceColor','b'); drawnow hold off end function draw_repulse(a,b) hold on plot(0,0,'ro','MarkerFaceColor','r'); [x,y] = meshgrid(-R:.5:R,-R:.5:R); [m,n] = size(x); for ii = 1:m for jj = 1:n result = repulse(x(ii,jj),y(ii,jj)); u(ii,jj) = result(1); v(ii,jj) = result(2); end end quiver(x,y,u,v); plot(a,b,'ro','MarkerFaceColor','b'); drawnow hold off end function draw_tangential(a,b) hold on plot(0,0,'ro','MarkerFaceColor','r'); [x,y] = meshgrid(-R:.5:R,R:-.5:-R); [m,n] = size(x); l = sqrt(y.^2+x.^2); sita = atan(abs(y)./abs(x)); for ii = 1:m for jj = 1:n x1 = x(ii,jj); y1 = y(ii,jj); if(x1>=0&&y1<0) sita(ii,jj) = 2*pi - sita(ii,jj); elseif(x1<=0&&y1<0) sita(ii,jj) = pi + sita(ii,jj); elseif(x1<=0&&y1>=0) sita(ii,jj) = pi - sita(ii,jj); end end end sita = sita +pi/4; x2 = sqrt(2)*l.*cos(sita); y2 = sqrt(2)*l.*sin(sita); u = x2-x; v = y2-y; quiver(x,y,u,v); plot(a,b,'ro','MarkerFaceColor','b'); drawnow hold off end %===================================== end ```
Java
UTF-8
4,002
1.921875
2
[]
no_license
package org.apache.maven.plugin; /* * Copyright 2001-2005 The Apache Software Foundation. * * 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 org.apache.maven.model.Plugin; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.codehaus.plexus.component.discovery.ComponentDiscoveryEvent; import org.codehaus.plexus.component.discovery.ComponentDiscoveryListener; import org.codehaus.plexus.component.repository.ComponentSetDescriptor; import org.codehaus.plexus.logging.AbstractLogEnabled; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; public class MavenPluginCollector extends AbstractLogEnabled implements ComponentDiscoveryListener { private Set pluginsInProcess = new HashSet(); private Map pluginDescriptors = new HashMap(); private Map pluginIdsByPrefix = new HashMap(); // ---------------------------------------------------------------------- // Mojo discovery // ---------------------------------------------------------------------- public void componentDiscovered( ComponentDiscoveryEvent event ) { ComponentSetDescriptor componentSetDescriptor = event.getComponentSetDescriptor(); if ( componentSetDescriptor instanceof PluginDescriptor ) { PluginDescriptor pluginDescriptor = (PluginDescriptor) componentSetDescriptor; // TODO: see comment in getPluginDescriptor String key = Plugin.constructKey( pluginDescriptor.getGroupId(), pluginDescriptor.getArtifactId() ); if ( !pluginsInProcess.contains( key ) ) { pluginsInProcess.add( key ); pluginDescriptors.put( key, pluginDescriptor ); // TODO: throw an (not runtime) exception if there is a prefix overlap - means doing so elsewhere // we also need to deal with multiple versions somehow - currently, first wins if ( !pluginIdsByPrefix.containsKey( pluginDescriptor.getGoalPrefix() ) ) { pluginIdsByPrefix.put( pluginDescriptor.getGoalPrefix(), pluginDescriptor ); } } } } public PluginDescriptor getPluginDescriptor( Plugin plugin ) { // TODO: include version, but can't do this in the plugin manager as it is not resolved to the right version // at that point. Instead, move the duplication check to the artifact container, or store it locally based on // the unresolved version? return (PluginDescriptor) pluginDescriptors.get( plugin.getKey() ); } public boolean isPluginInstalled( Plugin plugin ) { // TODO: see comment in getPluginDescriptor return pluginDescriptors.containsKey( plugin.getKey() ); } public PluginDescriptor getPluginDescriptorForPrefix( String prefix ) { return (PluginDescriptor) pluginIdsByPrefix.get( prefix ); } public void flushPluginDescriptor( Plugin plugin ) { pluginsInProcess.remove( plugin.getKey() ); pluginDescriptors.remove( plugin.getKey() ); for ( Iterator it = pluginIdsByPrefix.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); if ( plugin.getKey().equals( entry.getValue() ) ) { it.remove(); } } } }
Markdown
UTF-8
10,320
3.21875
3
[]
no_license
## API ⬆️ [Go to main menu](README.md#laravel-tips) ⬅️ [Previous (Log and debug)](log-and-debug.md) ➡️ [Next (Other)](other.md) - [API Resources: With or Without "data"?](#api-resources-with-or-without-data) - [Conditional Relationship Counts on API Resources](#conditional-relationship-counts-on-api-resources) - [API Return "Everything went ok"](#api-return-everything-went-ok) - [Avoid N+1 queries in API resources](#avoid-n1-queries-in-api-resources) - [Get Bearer Token from Authorization header](#get-bearer-token-from-authorization-header) - [Sorting Your API Results](#sorting-your-api-results) - [Customize Exception Handler For API](#customize-exception-handler-for-api) - [Force JSON Response For API Requests](#force-json-response-for-api-requests) - [API Versioning](#api-versioning) ### API Resources: With or Without "data"? If you use Eloquent API Resources to return data, they will be automatically wrapped in 'data'. If you want to remove it, add `JsonResource::withoutWrapping();` in `app/Providers/AppServiceProvider.php`. ```php class AppServiceProvider extends ServiceProvider { public function boot() { JsonResource::withoutWrapping(); } } ``` Tip given by [@phillipmwaniki](https://twitter.com/phillipmwaniki/status/1445230637544321029) ### Conditional Relationship Counts on API Resources You may conditionally include the count of a relationship in your resource response by using the whenCounted method. By doing so, the attribute is not included if the relationships' count is missing. ```php public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'email' => $this->email, 'posts_count' => $this->whenCounted('posts'), 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]; } ``` Tip given by [@mvpopuk](https://twitter.com/mvpopuk/status/1570480977507504128) ### API Return "Everything went ok" If you have API endpoint which performs some operations but has no response, so you wanna return just "everything went ok", you may return 204 status code "No content". In Laravel, it's easy: `return response()->noContent();`. ```php public function reorder(Request $request) { foreach ($request->input('rows', []) as $row) { Country::find($row['id'])->update(['position' => $row['position']]); } return response()->noContent(); } ``` ### Avoid N+1 queries in API resources You can avoid N+1 queries in API resources by using the `whenLoaded()` method. This will only append the department if it’s already loaded in the Employee model. Without `whenLoaded()` there is always a query for the department ```php class EmployeeResource extends JsonResource { public function toArray($request): array { return [ 'id' => $this->uuid, 'fullName' => $this->full_name, 'email' => $this->email, 'jobTitle' => $this->job_title, 'department' => DepartmentResource::make($this->whenLoaded('department')), ]; } } ``` Tip given by [@mmartin_joo](https://twitter.com/mmartin_joo/status/1473987501501071362) ### Get Bearer Token from Authorization header The `bearerToken()` function is very handy when you are working with apis & want to access the token from Authorization header. ```php // Don't parse API headers manually like this: $tokenWithBearer = $request->header('Authorization'); $token = substr($tokenWithBearer, 7); //Do this instead: $token = $request->bearerToken(); ``` Tip given by [@iamharis010](https://twitter.com/iamharis010/status/1488413755826327553) ### Sorting Your API Results Single-column API sorting, with direction control ```php // Handles /dogs?sort=name and /dogs?sort=-name Route::get('dogs', function (Request $request) { // Get the sort query parameter (or fall back to default sort "name") $sortColumn = $request->input('sort', 'name'); // Set the sort direction based on whether the key starts with - // using Laravel's Str::startsWith() helper function $sortDirection = Str::startsWith($sortColumn, '-') ? 'desc' : 'asc'; $sortColumn = ltrim($sortColumn, '-'); return Dog::orderBy($sortColumn, $sortDirection) ->paginate(20); }); ``` we do the same for multiple columns (e.g., ?sort=name,-weight) ```php // Handles ?sort=name,-weight Route::get('dogs', function (Request $request) { // Grab the query parameter and turn it into an array exploded by , $sorts = explode(',', $request->input('sort', '')); // Create a query $query = Dog::query(); // Add the sorts one by one foreach ($sorts as $sortColumn) { $sortDirection = Str::startsWith($sortColumn, '-') ? 'desc' : 'asc'; $sortColumn = ltrim($sortColumn, '-'); $query->orderBy($sortColumn, $sortDirection); } // Return return $query->paginate(20); }); ``` --- ### Customize Exception Handler For API #### Laravel 8 and below: There's a method `render()` in `App\Exceptions` class: ```php public function render($request, Exception $exception) { if ($request->wantsJson() || $request->is('api/*')) { if ($exception instanceof ModelNotFoundException) { return response()->json(['message' => 'Item Not Found'], 404); } if ($exception instanceof AuthenticationException) { return response()->json(['message' => 'unAuthenticated'], 401); } if ($exception instanceof ValidationException) { return response()->json(['message' => 'UnprocessableEntity', 'errors' => []], 422); } if ($exception instanceof NotFoundHttpException) { return response()->json(['message' => 'The requested link does not exist'], 400); } } return parent::render($request, $exception); } ``` #### Laravel 9 and above: There's a method `register()` in `App\Exceptions` class: ```php public function register() { $this->renderable(function (ModelNotFoundException $e, $request) { if ($request->wantsJson() || $request->is('api/*')) { return response()->json(['message' => 'Item Not Found'], 404); } }); $this->renderable(function (AuthenticationException $e, $request) { if ($request->wantsJson() || $request->is('api/*')) { return response()->json(['message' => 'unAuthenticated'], 401); } }); $this->renderable(function (ValidationException $e, $request) { if ($request->wantsJson() || $request->is('api/*')) { return response()->json(['message' => 'UnprocessableEntity', 'errors' => []], 422); } }); $this->renderable(function (NotFoundHttpException $e, $request) { if ($request->wantsJson() || $request->is('api/*')) { return response()->json(['message' => 'The requested link does not exist'], 400); } }); } ``` Tip given by [Feras Elsharif](https://github.com/ferasbbm) --- ### Force JSON Response For API Requests If you have built an API and it encounters an error when the request does not contain "Accept: application/JSON " HTTP Header then the error will be returned as HTML or redirect response on API routes, so for avoid it we can force all API responses to JSON. The first step is creating middleware by running this command: ```console php artisan make:middleware ForceJsonResponse ``` Write this code on the handle function in `App/Http/Middleware/ForceJsonResponse.php` file: ```php public function handle($request, Closure $next) { $request->headers->set('Accept', 'application/json'); return $next($request); } ``` Second, register the created middleware in app/Http/Kernel.php file: ```php protected $middlewareGroups = [ 'api' => [ \App\Http\Middleware\ForceJsonResponse::class, ], ]; ``` Tip given by [Feras Elsharif](https://github.com/ferasbbm) --- ### API Versioning #### When to version? If you are working on a project that may have multi-release in the future or your endpoints have a breaking change like a change in the format of the response data, and you want to ensure that the API version remains functional when changes are made to the code. #### Change The Default Route Files The first step is to change the route map in the `App\Providers\RouteServiceProvider` file, so let's get started: #### Laravel 8 and above: Add a 'ApiNamespace' property ```php /** * @var string * */ protected string $ApiNamespace = 'App\Http\Controllers\Api'; ``` Inside the method boot, add the following code: ```php $this->routes(function () { Route::prefix('api/v1') ->middleware('api') ->namespace($this->ApiNamespace.'\\V1') ->group(base_path('routes/API/v1.php')); } //for v2 Route::prefix('api/v2') ->middleware('api') ->namespace($this->ApiNamespace.'\\V2') ->group(base_path('routes/API/v2.php')); }); ``` #### Laravel 7 and below: Add a 'ApiNamespace' property ```php /** * @var string * */ protected string $ApiNamespace = 'App\Http\Controllers\Api'; ``` Inside the method map, add the following code: ```php // remove this $this->mapApiRoutes(); $this->mapApiV1Routes(); $this->mapApiV2Routes(); ``` And add these methods: ```php protected function mapApiV1Routes() { Route::prefix('api/v1') ->middleware('api') ->namespace($this->ApiNamespace.'\\V1') ->group(base_path('routes/Api/v1.php')); } protected function mapApiV2Routes() { Route::prefix('api/v2') ->middleware('api') ->namespace($this->ApiNamespace.'\\V2') ->group(base_path('routes/Api/v2.php')); } ``` #### Controller Folder Versioning ``` Controllers └── Api ├── V1 │ └──AuthController.php └── V2 └──AuthController.php ``` #### Route File Versioning ``` routes └── Api │ └── v1.php │ └── v2.php └── web.php ``` Tip given by [Feras Elsharif](https://github.com/ferasbbm)
Python
UTF-8
753
3.484375
3
[]
no_license
# coding=utf-8 """ 数字的格式化输出,使用format()还是挺有意思的 '[<>^]?width[,]?(.digits)?':其中 width 和 digits 为整数,?代表可选部分。 >>> x = 1234.56789 >>> format(x, '0.1f') '1234.6' >>> format(x, '10.1f') ' 1234.6' >>> format(x, '>10.1f') ' 1234.6' >>> format(x, '<10.1f') '1234.6 ' >>> format(x, '*>10.1f') '****1234.6' >>> format(x, '^10.1f') ' 1234.6 ' >>> format(x, ',') '1,234.56789' >>> format(x, '0,.1f') '1,234.6' >>> format(x, ',.1f') '1,234.6' >>> format(x, ',.3f') '1,234.568' >>> format(x, 'e') '1.234568e+03' >>> format(x, 'E') '1.234568E+03' >>> format(x, '0.2E') '1.23E+03' :copyright: (c) 2015 by fangpeng. :license: MIT, see LICENSE for more details. """ __date__ = '1/7/16'
Java
UTF-8
337
1.773438
2
[]
no_license
package com.bb.favoriteplaces.database; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; @Dao public interface FavoritePlacesDAO { @Insert void addFavoritePlaces(FavoritePlacesEntity googlePlacesEntity); @Delete void deleteFavoritePlaces(FavoritePlacesEntity googlePlacesEntity); }
Java
UTF-8
2,382
2.625
3
[]
no_license
import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Test { public static void main(String[] args) throws Exception { testSelect(); //testUpdate(); // testDelete(); // testInsert(); } public static void testInsert() throws Exception { { Class.forName("com.mysql.jdbc.Driver"); Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/DEMOPROJECT", "root", "root"); Statement stmt = conn.createStatement(); int i = stmt.executeUpdate("insert into marksheet value(11,111,'priya','shukla',78,66,66)"); System.out.println(i + "Inserted"); stmt.close(); conn.close(); } } public static void testDelete() throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/DEMOPROJECT", "root", "root"); Statement stmt = conn.createStatement(); int i = stmt.executeUpdate("delete from marksheet where id =4"); System.out.println(i + "Deleted"); stmt.close(); conn.close(); } public static void testUpdate() throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/DEMOPROJECT", "root", "root"); Statement stmt = conn.createStatement(); int i = stmt.executeUpdate("update marksheet set fname='Disha' where id =4"); System.out.println(i + "updated"); stmt.close(); conn.close(); } private static void testSelect() throws Exception { Class.forName("com.mysql.jdbc.Driver"); // TODO Auto-generated method stub Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DEMOPROJECT", "root", "root"); Statement stmt =conn.createStatement(); ResultSet rs =stmt.executeQuery("select* from marksheet"); while (rs.next()) { //System.out.print(rs.getString(1)); //System.out.print("\t" +rs.getString(2)); //System.out.print("\t" +rs.getString(3)); //System.out.print("\t" +rs.getString(4)); //System.out.print("\t" +rs.getString(5)); //System.out.print("\t" +rs.getString(6)); //System.out.print("\t" +rs.getString(7)); //System.out.print("\t" +rs.getString(8)); //System.out.println("\t" +rs.getString(9)); System.out.println("\t" +rs.getString("FNAME")); } stmt.close(); conn.close(); } }
Java
UTF-8
512
2.3125
2
[]
no_license
package com.geniye.wordit.core.dto; import com.geniye.wordit.core.models.User; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor public class UserDTO { private String username; private String email; private String bio; private String image; private String token; public UserDTO(User user) { this.username = user.getUsername(); this.email = user.getEmail(); this.bio = user.getBio(); this.image = user.getImage(); } }
Markdown
UTF-8
3,216
3.40625
3
[ "CC0-1.0" ]
permissive
# 图标与视觉 高质量的视觉设计不仅提升了应用的品质,同时也能传达一定的信息,增强了整体的用户体验。OS X 的用户都习惯了高质量且有意义的视觉设计,他们更愿意使用设计比较优雅的应用。 **所以你要确保你的设计看上去足够专业,足够优雅。** 不要低估这些高质量的视觉设计对用户的价值,渣视觉只能给用户一个很差印象,让用户觉得整个应用的质量都不怎样。为了给用户留下一个不错的印象,在开发的过程中视觉设计必须占有一席之地。 **留心图片在全屏模式下的表现。** 如果你的应用允许使用全屏模式,那么千万不要把直接把拉伸放大,这样图片会变模糊。一般我们可以先从大分辨率开始做视觉设计,然后再缩小成需要的大小,这样会比较科学一点。(译者注:多用 PS 的矢量路径,或者直接用 AI 来做设计会比较好。) **应用图标要足够惊艳。** 图标是一个应用的名片,投入资源在图标的设计上是很有必要的。你要考虑清楚这个图标是使用拟物风格还是纯图形风格,比如系统的 Garage Band 车库音乐应用就采用了一把非常精致的吉他作为图标。 ![image](images/OSX_HIG_001_032.png) **如果你采用了现实材料作为视觉元素,那么整个应用都要保持统一的拟物风格。** 通常现实世界存在的纹理可以提高用户的认同感,比如木纹,皮革效果,金属质感或者纸的光感等等,都是比较高级的纹理。要使用这些拟物质感,请尽量遵循以下要求: - 纹理要足够逼真,足够高级,在任何时候都能保持不错的视觉效果。 - 纹理要和谐融入整个应用的界面,不要生搬硬套。 - 使用纹理的目的在于提高用户体验,帮助用户理解当前情境。如果达不到这种效果,那就是画蛇添足,多此一举了。 **考虑你使用的拟物效果是不是能够帮助用户理解虚拟世界的。** 拟物是为了帮助用户理解,提高可用性,降低学习成本的,如果这个效果帮助用户理解了其中一部分设计,但是却提高了其他部分的认知成本,那就得不偿失了。比如说写信寄信在现实生活中是很常见的行为,但是系统的邮件应用不要增加让用户折信,盖邮戳之类的鸡肋流程。 **没有必要完全照搬现实世界的一切细节,如果调整效果的细节可以让用户更好地理解你的设计,那就放手去改。** 其实是调整或者忽略一些细节是很常见的设计,对细节去芜存菁往往能更好地表达你的想法。 **不要让过多的艺术表达盖过设计的易用性。** 比如说,画一块橡木板,把照片和便签纸钉在上面是个挺不错的拟物效果,但是如果是一个建筑平面图设计软件还用橡木板的形式来展示画板就会显得很奇葩了。也就是说,如果用户看到你的界面还得想一想才知道你要表达的是什么,那这个界面的易用性就算毁了。(这个概念涉及到美学的完整性,可以参见[美学的完整性]()一章。)
Python
UTF-8
1,859
2.75
3
[ "MIT" ]
permissive
import sys import urllib import json import requests class BingApiResult(): def __init__(self, json_result): self.response = json.loads(json_result)['SearchResponse']['Web'] self.total = self.response['Total'] def find_libraries(self): libraries = [] return self.response['Results'] def eof(self): try: self.find_libraries() return False except KeyError as e: return True def bing_search(search_terms, base_url, offset): base_url = base_url + "&Query=" + urllib.quote_plus(search_terms) url = base_url + "&Web.Count=50&Web.Offset=" + str(offset) print str(offset) + " " + url r = requests.get(url) search_result = BingApiResult(r.content) if search_result.eof(): print "EOF" return [] libraries = search_result.find_libraries() print 'Total results ' + str(search_result.total) print 'Current results ' + str(len(libraries)) return libraries def main(): # for example, to search Bing for Horizon libraries: "inanchor:ipac20 account" search_terms = "inanchor:ipac20 -site:si.edu" if len(sys.argv) > 1: search_terms = sys.argv[1] base_url = "http://api.bing.net/json.aspx?AppId=91650C54158D791BE8B89E229B2190C53C83ABE8&Sources=Web&Version=2.0&Market=en-us&Adult=Moderate&Web.Options=DisableQueryAlterations" offset = 0 libraries = [] new_libraries = bing_search(search_terms, base_url, offset) while len(new_libraries) != 0: libraries.extend(new_libraries) offset += len(new_libraries) new_libraries = bing_search(search_terms, base_url, offset) for library in libraries: print library['Title'] + ',' + library['Url'] if __name__ == '__main__': main()
Java
UTF-8
704
2.171875
2
[]
no_license
package org.rgn.ajia.around.actions; import org.rgn.ajia.around.daos.AnotherDao; import org.rgn.ajia.around.daos.MessageDao; import org.rgn.ajia.around.infra.BaseAction; public class ThirdAction extends BaseAction{ public String a; public ThirdAction() { } public void doSomething() { System.out .println("\n================ThirdAction.doSomething()===============================\n"); MessageDao messageDao = new MessageDao(); messageDao.find("Alou, voce!!! - <<<3>>> "); messageDao.insert("Amigo da rede globo <<<3>>>", "ronaldinho fazendo cera!!! <<<3>>>"); System.out .println("\n================ThirdAction.doSomething() - FIM ===============================\n"); } }
TypeScript
UTF-8
2,685
2.671875
3
[]
no_license
import { Injectable } from '@angular/core'; export interface SoccerTeam { team_name: string; goals: number; yellow_cards: number; red_cards: number; offsides: number; } @Injectable({ providedIn: 'root' }) export class MatchService { Teams: SoccerTeam[] = []; stats; results; constructor() { } setTeams(teamA, teamB) { if (this.Teams.length > 0) { this.Teams = []; this.Teams.push({'team_name': teamA, 'goals': 0, 'yellow_cards': 0, 'red_cards': 0, 'offsides': 0}); this.Teams.push({'team_name': teamB, 'goals': 0, 'yellow_cards': 0, 'red_cards': 0, 'offsides': 0}); } else { this.Teams.push({'team_name': teamA, 'goals': 0, 'yellow_cards': 0, 'red_cards': 0, 'offsides': 0}); this.Teams.push({'team_name': teamB, 'goals': 0, 'yellow_cards': 0, 'red_cards': 0, 'offsides': 0}); } } getTeamsStats() { return this.Teams; } addGoal(team) { for (let current_team in this.Teams) { if (this.Teams[current_team]['team_name'] == team) { this.Teams[current_team]['goals'] += 1; } } } deleteGoal(team) { for (let current_team in this.Teams) { if (this.Teams[current_team]['team_name'] == team) { if ( this.Teams[current_team]['goals'] > 0) { this.Teams[current_team]['goals'] -= 1; } } } } giveYellowCard(team) { for (let current_team in this.Teams) { if (this.Teams[current_team]['team_name'] == team) { this.Teams[current_team]['yellow_cards'] += 1; } } } giveRedCard(team) { for (let current_team in this.Teams) { if (this.Teams[current_team]['team_name'] == team) { this.Teams[current_team]['red_cards'] += 1; } } console.log(this.Teams); } giveOffside(team) { for (let current_team in this.Teams) { if (this.Teams[current_team]['team_name'] == team) { this.Teams[current_team]['offsides'] += 1; } } console.log(this.Teams); } finishMatch() { if(this.Teams.length > 0){ this.stats = this.Teams; if (this.Teams[0]['goals'] > this.Teams[1]['goals']) { this.results = [this.Teams[0]['team_name']]; } else if (this.Teams[1]['goals'] > this.Teams[0]['goals']) { this.results = [this.Teams[1]['team_name']]; } else { this.results = [this.Teams[0]['team_name'], this.Teams[1]['team_name']]; } } } getWinner() { if(this.Teams.length > 0){ if (this.results.length == 1) { return 'Winner: ' + this.results[0]; } else { return 'Draw: ' + this.results[0] + ', ' + this.results[1]; } } } }
JavaScript
UTF-8
1,908
2.609375
3
[]
no_license
import React, { useState, useEffect } from "react" import _ from "lodash" import ErrorList from "./ErrorList" const ArticleForm = props => { const [articleRecord, setArticleRecord] = useState({ title: "", content: "" }) const [errors, setErrors] = useState({}) const handleChangeInput = event => { event.preventDefault() setArticleRecord({ ...articleRecord, [event.currentTarget.name]: event.currentTarget.value }) } const validForSubmission = () => { let submitErrors = {} const requiredFields = ["title", "content"] requiredFields.forEach(field => { if (articleRecord[field].trim() === "") { submitErrors = {...submitErrors, [field]:"is blank"} } }) setErrors(submitErrors) return _.isEmpty(submitErrors) } const handleSubmit = event => { event.preventDefault() if (validForSubmission()) { props.addNewArticle(articleRecord) } } const clearForm = event => { event.preventDefault() setArticleRecord({ title: "", content: "" }) setErrors({}) } return ( <form className="new-article-form callout success" onSubmit={handleSubmit}> <ErrorList errors={errors} /> <label> Article Title: <input name="title" id="title" type="text" onChange={handleChangeInput} value={articleRecord.title} /> </label> <label> Article Content: <textarea name="content" id="content" onChange={handleChangeInput} value={articleRecord.content} /> </label> <div className="button-group"> <button className="button" onClick={clearForm}>Clear</button> <input className="button" type="submit" value="Submit" /> </div> </form> ) } export default ArticleForm
Python
UTF-8
346
3.171875
3
[ "MIT" ]
permissive
import tkinter as tk def action_btn_press(): print('Button was pressed') root=tk.Tk() root.title('Widget creation') root.geometry('350x150') lb=tk.Label(text='Label-1') bt1=tk.Button(text='Button') bt2=tk.Button(text='Button') bt=tk.Button(text='ボタン',command=action_btn_press) lb.pack() bt1.pack() bt2.pack() bt.pack() root.mainloop()
C++
UTF-8
303
2.703125
3
[]
no_license
#include <iostream> using namespace std; int main() { int nh[2]; for (int i=0; i<2; i++){ cin >> nh[i]; } int temp, count = 0; for (int i=0; i < nh[0]; i++){ cin >> temp; if (temp > nh[1]){ count += 2; } else{ count++; } } cout << count; return 0; }
C++
UTF-8
2,689
3.234375
3
[]
no_license
/* * main.cpp * * Created on: Nov 14, 2012 * Author: torghele */ #include <iostream> #include <cmath> #include <stdlib.h> #include <errno.h> #include <sys/socket.h> #include <sys/un.h> using namespace std; void server() { int s, s2, len; socklen_t t; struct sockaddr_un local_addr, remote_addr; float number; if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { cerr << strerror(errno) << endl; exit(1); } local_addr.sun_family = AF_UNIX; strcpy(local_addr.sun_path, "socket"); unlink(local_addr.sun_path); len = strlen(local_addr.sun_path) + sizeof(local_addr.sun_family); if (bind(s, (struct sockaddr *)&local_addr, len) == -1) { cerr << strerror(errno) << endl; exit(1); } if (listen(s, 5) == -1) { // max 5 connections in queue cerr << strerror(errno) << endl; exit(1); } while(true) { int done, n; cout << "Waiting for a connection.." << endl; t = sizeof(remote_addr); if ((s2 = accept(s, (struct sockaddr *)&remote_addr, &t)) == -1) { cerr << strerror(errno) << endl; exit(1); } cout << "Connected." << endl; done = 0; do { n = recv(s2, &number, sizeof(number), 0); if (n <= 0) { if (n < 0) cerr << strerror(errno) << endl; done = 1; } if (!done) number = sqrt(number); if (send(s2, &number, n, 0) < 0) { cerr << strerror(errno) << endl; done = 1; } } while (!done); close(s2); } } void client() { int s, t, len; struct sockaddr_un remote_addr; float number; if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { cerr << strerror(errno) << endl; exit(1); } cout << "Trying to connect.." << endl; remote_addr.sun_family = AF_UNIX; strcpy(remote_addr.sun_path, "socket"); len = strlen(remote_addr.sun_path) + sizeof(remote_addr.sun_family); if (connect(s, (struct sockaddr *)&remote_addr, len) == -1) { cerr << strerror(errno) << endl; exit(1); } cout << "connected." << endl; while(true) { cout << "Enter a number:"; if (!(cin >> number)) { cout << "You did not enter a correct number!" << endl; exit(1); } if (send(s, &number, sizeof(number), 0) == -1) { cerr << strerror(errno) << endl; exit(1); } if ((t=recv(s, &number, sizeof(number), 0)) > 0) { cout << number << endl; } else { if (t < 0) cerr << strerror(errno) << endl; else cout << "Server closed connection." << endl; exit(1); } } close(s); } int main() { int type; std::cout << "1: Server" << std::endl; std::cout << "2: Client" << std::endl; std::cout << "Chose: "; std::cin >> type; if ( type == 1 ) server(); else if (type == 2 ) client(); else std::cout << "wrong input.. aborting" << std::endl; return 0; }
Java
UTF-8
956
2.046875
2
[]
no_license
package com.appslab.oracle.atthackthon; import android.app.Application; import android.os.SystemClock; import com.datami.smi.SdState; import com.datami.smi.SdStateChangeListener; import com.datami.smi.SmiResult; import com.datami.smi.SmiSdk; import java.util.concurrent.TimeUnit; /** * Created by Osvaldo Villagrana on 12/23/15. */ public class App extends Application implements SdStateChangeListener { private final String API = "dmi-att-hack-68fcfe5e708bfaa3806c4888912ea6f2ecb446fd"; @Override public void onCreate() { super.onCreate(); SmiSdk.getAppSDAuth(API, getApplicationContext(), "", -1, true); SystemClock.sleep(TimeUnit.SECONDS.toMillis(1)); } @Override public void onChange(SmiResult currentSmiResult) { SdState sdState = currentSmiResult.getSdState(); if (sdState == SdState.SD_AVAILABLE) { } else if (sdState == SdState.SD_NOT_AVAILABLE) { } else if(sdState == SdState.WIFI) { } } }
Markdown
UTF-8
2,776
4.15625
4
[ "MIT" ]
permissive
# Primitive and reference types in JS we have two kinds of types: *primitive* and *reference*. primitive types => stored as simple data types reference types => stored as object **the tricky part is that JS lets you treat primitive types like reference types in order to make the language more consistent for the developer** **JS tracks variable for a particular scope with a *variable object*** Primitive values are stored directly on the variable object, reference values are placed as a pointer in the variable object ### primitive types 1 Boolean 2 Number 3 String 4 Null 5 Undefined variables holding a primitive directly contains the primitive value, rather than a pointer to an object **the best way to identify primitive types is with the *typeof* operator** the tricky part involves null ```js console.log(typeof null); // "object" ``` for this reason, the best way to determine if a value is null, is to compare it against null directly ```js console.log(typeof value === null); // true or false ``` **Despite the fact that they have methods, primitive values themselves are not objects. JavaScript makes them look like objects to provide a consistent experience in the language** ### reference types reference types represent object in JS and are the closest thing to classes **an object is an unordered list of properties consisting of a name and a value** when the value of a property is a function, it's called a *method* **function themselves are actually reference values in JS, so there isn't a lot of difference between a property that contains an array and another that contains a function, except that this second one can be executed** it could help sometimes to think of JS object as hash tables there are a couple of way to instatiate objects in JS, the first is to use the *new* operator with a constructor. A constructor is simply a function that uses new to create an object. By convention, constructor function starts with the first letter capitalized to distinguish them from nonconstructor functions. ```js var object = new Object(); ``` **Reference types do not store the object directly into the variable to which it is assigned, so the object variable in this example doesn’t actually contain the object instance. Instead, it holds a pointer (or reference) to the location in memory where the object exists. This is the primary difference between objects and primitive values, as the primitive is stored directly in the variable.** JS is a **garbage-collected language**, so you don’t need to worry about memory allocations. However, it’s best to **dereference objects that you no longer need** so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null
Python
UTF-8
1,482
3.46875
3
[]
no_license
import unittest from activities import eat, nap, is_funny, laugh class ActivityTests(unittest.TestCase): def test_eat_healthy(self): self.assertEqual( eat("carrots", is_healthy=True), "I'm eating carrots, because they are good" ) def test_eat_unhealthy(self): self.assertEqual( eat("pizza", is_healthy=False), "I'm eating pizza, YOLO" ) def test_eat_healthy_bool(self): """is healthy must be a bool""" with self.assertRaises(ValueError): eat("pizza", is_healthy="who cares") def test_short_nap(self): self.assertEqual( nap(1), "im feeling refreshed after 1 hour nap" ) def test_long_nap(self): self.assertEqual( nap(3), "Im feeling more tired" ) def test_is_funny_tim(self): """tim should not be funny""" self.assertEqual(is_funny("tim"),False) def test_is_funny_anyone_else(self): """anyone else but time should be funny""" self.assertTrue(is_funny("blue"), "blue is funny"), self.assertTrue(is_funny("babes"), "babes is funny"), self.assertTrue(is_funny("annabelle"), "annabelle is funny") def test_laugh(self): self.assertIn(laugh(), ('lol', 'ha', 'tehe')) if __name__ == "__main__": unittest.main() # python3 test.py -v, # adding -v command gives test function names # verbose
Java
UTF-8
1,471
2.65625
3
[]
no_license
package com.sy.hibernatetest; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Set; import com.sy.util.db; public class date { /** * @param args * @throws SQLException */ public static void main(String[] args) throws SQLException { Connection con=db.getConn(); String sql="select id ,Week from opt_ad ;"; ResultSet rs=db.executeQuery(con, sql); sql="update opt_ad set Week=? where id=?;"; PreparedStatement pstm=db.getPStmt(con, sql); while(rs.next()){ pstm.setString(1, changedata(rs.getString(2))); pstm.setInt(2, rs.getInt(1)); pstm.addBatch(); } pstm.executeBatch(); pstm.close(); rs.close(); con.close(); } public static String changedata(String data){ String dd=data.substring(0, 2); String mm=data.substring(2, 5); String yy=data.substring(5, 9); if(mm.equals("JAN")){ mm="01"; } if(mm.equals("FEB")){ mm="02"; } if(mm.equals("MAR")){ mm="03"; } if(mm.equals("APR")){ mm="04"; } if(mm.equals("MAY")){ mm="05"; } if(mm.equals("JUN")){ mm="06"; } if(mm.equals("JUL")){ mm="07"; } if(mm.equals("AUG")){ mm="08"; } if(mm.equals("SEP")){ mm="09"; } if(mm.equals("OCT")){ mm="10"; } if(mm.equals("NOV")){ mm="11"; } if(mm.equals("DEC")){ mm="12"; } return yy+"-"+mm+"-"+dd; } }
PHP
UTF-8
1,437
2.53125
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; /** * Class CreateSlackIntegrationTable * * The Migrations is Defined for Slack. * * PHP version 7.1.3 * * @category Administration * @package Modules\Slack * @author Vipul Patel <vipul@chetsapp.com> * @copyright 2020 Chetsapp Group * @license Chetsapp Private Limited * @version Release: @2.0@ * @link http://chetsapp.com * @since Class available since Release 2.0 */ class CreateSlackIntegrationTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create( config('core.acl.slack_table'), function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id') ->references('id') ->on(config('core.acl.users_table')) ->onDelete('cascade'); $table->text('access_token'); $table->string('team_id'); $table->string('channel_id'); $table->timestamps(); } ); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists(config('core.acl.slack_table')); } }
JavaScript
UTF-8
2,402
2.75
3
[]
no_license
class Tooltip extends HTMLElement { constructor() { super(); this._tooltipVisible = false; this.attachShadow({ mode: 'open' }); this.init(); this.stylesheetPath = ''; } init() { this._tooltipTarget = document.createElement('slot'); this.shadowRoot.appendChild(this._tooltipTarget); this._tooltipTarget.addEventListener('mouseenter', this._showTooltip.bind(this)); this._tooltipTarget.addEventListener('mouseleave', this._hideTooltip.bind(this)); this.tooltipContainer = document.createElement('div'); this.shadowRoot.appendChild(this.tooltipContainer); } set text(text) { if (text) { console.log(text); this.setAttribute('text', text); } else if (this.hasAttribute('text')) { this._tooltipText = this.getAttribute('text') || ''; } else { this._tooltipText = ''; } } get text() { return this.getAttribute('text'); } connectedCallback() { const linkElem = document.createElement('link'); //link for external stylesheet linkElem.setAttribute('rel', 'stylesheet'); linkElem.setAttribute('href', this.stylesheetPath + '/smdui-tooltip/smdui-tooltip.css'); this.shadowRoot.appendChild(linkElem); this._render(); }; attributeChangedCallback(name, oldValue, newValue) { if (oldValue === newValue) { return; } if (name === 'text') { this._tooltipText = newValue; } } static get observedAttributes() { return ['text']; } disconnectedCallback() { this._tooltipTarget.removeEventListener('mouseenter', this._showTooltip); this._tooltipTarget.removeEventListener('mouseleave', this._hideTooltip); } _render() { this.tooltipContainer.textContent = this._tooltipText || ""; if (this._tooltipVisible) { this.tooltipContainer.classList.add('open'); } else { if (this.tooltipContainer) this.tooltipContainer.classList.remove('open'); } } _showTooltip() { this._tooltipVisible = true; this._render(); } _hideTooltip() { this._tooltipVisible = false; this._render(); } } customElements.define('smdui-tooltip-new', Tooltip);
Java
UTF-8
11,809
2.09375
2
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
package com.github.bderancourt.springboot.isolatedrunner.launcher; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.springframework.boot.loader.LaunchedURLClassLoader; import org.springframework.boot.loader.jar.JarFile; import com.github.bderancourt.springboot.isolatedrunner.util.ClassPathUtils; import lombok.extern.slf4j.Slf4j; @Slf4j public class DirDependency implements Dependency { protected static final Pattern JAR_WITH_VERSION_PATTERN = Pattern.compile("(.+(?=\\-\\d))\\-(.+(?=\\.jar))(\\.jar)"); private URL classPathDependencyUrl; private String name; private String mainClass; private Class<?> runnerClass; private Object runnerInstance; public DirDependency(URL classPathDependencyUrl, String name, String mainClass) { this.classPathDependencyUrl = classPathDependencyUrl; this.name = name; this.mainClass = mainClass; } /** * @param args * to pass to the spring-boot app * @throws Exception * if an error occurs during the spring-boot app startup */ public void start(String[] args) throws Exception { Path manifestPath = Paths.get(new File(classPathDependencyUrl.toURI()).toString(), "META-INF", "MANIFEST.MF"); Manifest manifest; try (InputStream is = new FileInputStream(manifestPath.toFile())) { manifest = new Manifest(is); } URL[] classPathUrls = constructClassPath(manifest.getMainAttributes() .getValue(MANIFEST_CLASSPATH), classPathDependencyUrl); log.debug("Loaded isolated classpath for " + name); Arrays.stream(classPathUrls) .map(Objects::toString) .forEach(log::debug); JarFile.registerUrlProtocolHandler(); ClassLoader classLoader = createClassLoader(classPathUrls); runnerClass = classLoader.loadClass(RUNNER_CLASS); Class<?> configClass = classLoader.loadClass(mainClass); Object runner = runnerClass.getDeclaredConstructor(Class.class, String[].class, String.class) .newInstance(configClass, args, name); runnerClass.getMethod("run") .invoke(runner); } public void stop() throws Exception { runnerClass.getMethod("stop") .invoke(runnerInstance); } /** * Create a classloader for the specified URLs. * * @param urls * the URLs * @return the classloader * @throws Exception * if the classloader cannot be created */ protected ClassLoader createClassLoader(URL[] urls) throws Exception { return new LaunchedURLClassLoader(urls, null); } /** * Constructs the spring-boot app classpath. Based on the jar list on the spring-boot app manifest, we need to match * which URL on this application classpath (JVM) is relevant. * * @param manifestClassPath * the list of jars defined in the Class-Path key of the manifest * @param classPathDependencyUrl * the URL to the spring boot app to run * @return spring-boot app classpath * @throws Exception * if an URL don't exists */ protected URL[] constructClassPath(String manifestClassPath, URL classPathDependencyUrl) throws Exception { URLClassLoader systemClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); List<URL> urls = new ArrayList<>(); // We add the spring-boot program itself in the classpath urls.add(classPathDependencyUrl); urls.add(ClassPathUtils.findDependencyURL("spring-boot-isolated-runner")); urls.add(ClassPathUtils.findDependencyURL("org/springframework/boot/spring-boot/")); // In this list, we store all this JVM classpath. List<URL> classPathUrls = new ArrayList<>(); classPathUrls.addAll(Arrays.asList(systemClassLoader.getURLs())); // In this list, we store the jars found in the spring-boot app manifest. List<String> manifestJars = Collections.synchronizedList(new ArrayList<>()); manifestJars.addAll(Arrays.asList(manifestClassPath.split(" "))); log.debug("##### spring-boot dependencies to find #####"); manifestJars.stream().forEach(log::debug); log.debug("##### spring-boot dependencies to find #####"); // First try, find the exact matching between the jar and the program classpath URL // Ex: file:/C:/m2repo/com/google/code/findbugs/jsr305/3.0.2/jsr305-3.0.2.jar matching jsr305-3.0.2.jar log.debug("exact match"); if (!manifestJars.isEmpty()) { for (ListIterator<URL> itUrls = classPathUrls.listIterator(); itUrls.hasNext();) { URL url = itUrls.next(); for (ListIterator<String> it = manifestJars.listIterator(); it.hasNext();) { String jar = it.next(); URL matchingUrl = exactMatch(url, jar); if (matchingUrl != null) { log.debug("adding url {} matching {}", matchingUrl, jar); urls.add(matchingUrl); it.remove(); itUrls.remove(); } } } } // Second try. For dependency management reasons, we potentially have jars in the manifest // that are not exactly on the same version as in the program classpath URLs. // Initialize regex pattern log.debug("version not match"); if (!manifestJars.isEmpty()) { for (ListIterator<URL> itUrls = classPathUrls.listIterator(); itUrls.hasNext();) { URL url = itUrls.next(); for (ListIterator<String> it = manifestJars.listIterator(); it.hasNext();) { String jar = it.next(); URL matchingUrl = matchesButNotTheVersion(url, jar); if (matchingUrl != null) { log.debug("adding url {} matching {}", matchingUrl, jar); urls.add(matchingUrl); it.remove(); itUrls.remove(); } } } } // Third try. If you ran your program in eclipse, eclipse put in classpath the related projects target/classes dirs log.debug("eclipse's related projects"); if (!manifestJars.isEmpty()) { for (ListIterator<URL> itUrls = classPathUrls.listIterator(); itUrls.hasNext();) { URL url = itUrls.next(); for (ListIterator<String> it = manifestJars.listIterator(); it.hasNext();) { String jar = it.next(); URL matchingUrl = matchesEclipseRelatedProject(url, jar); if (matchingUrl != null) { log.debug("adding url {} matching {}", matchingUrl, jar); urls.add(matchingUrl); it.remove(); itUrls.remove(); } } } } // Fourth try, find the jar in the maven local repository log.debug("find jar in maven repo"); if (!manifestJars.isEmpty()) { // retrieve maven local repository path String mvnRepoPath = getMavenRepository(); List<String> jarsToRemove = Collections.synchronizedList(new ArrayList<>()); synchronized (manifestJars) { manifestJars.parallelStream() .forEach(jar -> { Optional<Path> optMvnJarPath = Optional.empty(); try (Stream<Path> walk = Files.walk(Paths.get(mvnRepoPath))) { optMvnJarPath = walk.filter(Files::isRegularFile) .filter(path -> path.getFileName() .toString() .equals(jar)) .findFirst(); if (optMvnJarPath.isPresent()) { URL url = Paths.get(optMvnJarPath.get() .toString()) .toFile() .getCanonicalFile() .toURI() .toURL(); log.debug("adding url {} matching {}", url, jar); urls.add(url); jarsToRemove.add(jar); } } catch (IOException e) { throw new UncheckedIOException(e); } }); manifestJars.removeAll(jarsToRemove); } } if (!manifestJars.isEmpty()) { log.warn("##### residual unload dependencies #####"); manifestJars.stream().forEach(log::warn); log.warn("##### residual unload dependencies #####"); throw new Exception("Unable to load all needed dependencies !"); } return urls.toArray(new URL[0]); } protected static URL exactMatch(URL url, String jar) { if (url.getFile() .contains(jar)) { log.debug("adding url {} matching {}", url, jar); return url; } return null; } protected static URL matchesButNotTheVersion(URL url, String jar) throws MalformedURLException { Matcher matcher = DirDependency.JAR_WITH_VERSION_PATTERN.matcher(jar); if (matcher.find()) { String urlRegex = matcher.replaceFirst("$1-(\\\\d[^/]*)$3") .replace("-", "\\-") .replace(".", "\\."); String exactVersion = matcher.replaceFirst("$2"); Pattern urlPattern = Pattern.compile(urlRegex); Matcher urlMatcher = urlPattern.matcher(FilenameUtils.getName(url.getPath())); if (urlMatcher.matches()) { String notExactVersion = urlMatcher.group(1); log.info( "classpath url {} matches {} but version {} will be replaced by {} to conform to the app classpath", url, jar, notExactVersion, exactVersion); URL modifiedUrl = new URL(url.toString() .replace(notExactVersion, exactVersion)); log.debug("adding url {}", modifiedUrl); return modifiedUrl; } } return null; } protected static URL matchesEclipseRelatedProject(URL url, String jar) { Matcher matcher = DirDependency.JAR_WITH_VERSION_PATTERN.matcher(jar); if (matcher.find()) { String jarNameWithoutVersionAndExtension = matcher.group(1); // we split the part before version of the jar name and we try to find all the words in the remaining // program // classpath urls List<String> jarWordsAndTarget = new ArrayList<>(Arrays.asList(jarNameWithoutVersionAndExtension.split("-"))); jarWordsAndTarget.add("target/classes"); if (jarWordsAndTarget .stream() .allMatch(word -> url.getFile() .contains(word))) { log.debug("adding url {} matching {}", url, jar); return url; } } return null; } protected String getMavenRepository() throws IOException, InterruptedException { List<String> command = new ArrayList<>(); if (System.getProperty("os.name") .toLowerCase() .startsWith("windows")) { command.addAll(Arrays.asList("cmd.exe", "/c")); } else { command.addAll(Arrays.asList("sh", "-c")); } command .addAll(Arrays.asList("mvn", "help:evaluate", "-Dexpression=settings.localRepository", "-q", "-DforceStdout")); ProcessBuilder pb = new ProcessBuilder(command); Process p = pb.start(); if (p.waitFor(30, TimeUnit.SECONDS) && p.exitValue() == 0) { return IOUtils.toString(p.getInputStream(), Charset.defaultCharset()) .trim(); } throw new IOException("Unable to find maven local repository path. Is maven installed in your system ?"); } }
Markdown
UTF-8
6,144
2.84375
3
[ "MIT" ]
permissive
# FAQ - **Why is my `umi_tool group`/`dedup` command taking so long?** The time taken to resolve each position is dependent on how many unique UMIs there are and how closely related they are since these factors will affect how large the network of connected UMIs is. Some of the factors which can affect run time are: 1. UMI length (shorter => fewer possible UMIs => increased connectivity between UMIs => larger networks => longer run time) 2. Sequencing error rate (higher => more error UMIs => larger networks => longer run time) 3. Sequencing depth (higher = greater proportion of possible UMIs observed => larger network => longer run time) 4. Running `umi_tools dedup --output-stats` requires a considerable amount of time and memory to generate the null distributions. If you want these stats, consider obtaining stats for just a single contig, eg. `--chrom=chr22`. 5. If you are doing single-cell RNA-seq and you have reads from more than one cell in your BAM file, make sure you are running with the `--per-cell` swtich. &nbsp; - **Why is my `umi_tool group`/`dedup` command taking so much memory?** There are a few reasons why your command could require an excessive amount of memory: 1. Most of the above factors increasing run time can also increase memory 2. Running `umi_tools dedup` with `chimeric-reads=use` (default) can take a large amount of memory. This is because `dedup` will wait until a whole contig has been deduplicated before re-parsing the reads from the contig and writing out the read2s which match the retained read1s. For chimeric read pairs, the read2s will not be found on the same contig and will be kept in a buffer of "orphan" read2s which may take up a lot of memory. Consider using `chimeric-reads=discard` instead to discard chimeric read pairs. Similarly, use of `--unmapped-reads=use` with `--paired` can also increase memory requirements. &nbsp; - **Can I run `umi_tools` with parallel threads?** Not yet! This is something we have been discussing for a while (see [#203](https://github.com/CGATOxford/UMI-tools/issues/203) & [#257](https://github.com/CGATOxford/UMI-tools/issues/257)) but haven't found the time to actually implement. If you'd like to help us out, get in touch! &nbsp; - **What's the correct regex to use for technique X?** Here is a table of the techniques we have come across that are not easily processed with the basic barcode pattern syntax, and the correct regex's to use with them: | Technique | regex | | --------- | ------ | | inDrop | `(?P<cell_1>.{8,12})(?P<discard_1>GAGTGATTGCTTGTGACGCCTT)(?P<cell_2>.{8})(?P<umi_1>.{6})T{3}.*` | | ddSeq/Sureccell | `(?P<discard_1>.{0,5})(?P<cell_1>.{6})(?P<discard_2>TAGCCATCGCATTGC){e<=1}(?P<cell_2>.{6})(?P<discard_3>TACCTCTGAGCTGAA){e<=1}(?P<cell_3>.{6})(?P<discard_4>ACG)(?P<umi_1>.{8})(?P<discard_5>GAC).*` | | SPLiT-seq | `(?P<umi_1>.{10})(?<cell_1>.{8})(?P<discard_1>GTGGCCGATGTTTCGCATCGGCGTACGACT)(?P<cell_2>.{8})(?<discard_2>ATCCACGTGCTTGAGAGGCCAGAGCATTCG)(?P<cell_3>.{8})` | | BD-Rhapsody | `(?<cell_1>.{9})(?<discard_1>.{12})(?<cell_2>.{9})(?<discard_2>.{13})(?<cell_3>.{9})(?<umi_1>.{8})T+` | If you know of other, please drop us a PR with them! &nbsp; - **Can I use `umi_tools` to determine consensus sequences?** Right now, you can use `umi_tools group` to identify the duplicated read groups. From this, you can then derive consensus sequences as you wish. We have discussed adding consense sequence calling as a separate `umi_tools` command (see [#203](https://github.com/CGATOxford/UMI-tools/issues/181)). If you'd like to help us out, get in touch! &nbsp; - **What do the `--per-gene`, `--gene-tag` and `--per-contig` options do in `umi_tools group`/`dedup`/`count`?** These options are designed to handle samples from sequence library protocols where fragmentation occurs post amplification, e.g CEL-Seq for single cell RNA-Seq. For such sample, mapping coordinates of duplicate reads will no longer be identical and `umi_tools` can instead use the gene to which the read is mapped. This behaviour is switched on with `--per-gene`. `umi_tools` then needs to be told if the reads are directly mapped to a transcriptome (`--per-contig`), or mapped to a genome and the transcript/gene assignment is contained in a read tag (`--gene-tag=[TAG]`). If you have assigned reads to transcripts but want to use the gene IDs to determine UMI groups, there is a further option to provide a file mapping transcript IDs to gene IDs (`--gene-transcript-map`). Finally, for single cell RNA-Seq, you must specify `--per-cell`. See `umi_tools dedup`/`group`/`count --help` for details of further related options and the [UMI-tools single cell RNA-Seq guide](https://github.com/CGATOxford/UMI-tools/blob/%7BTS%7D-AddFAQ/doc/Single_cell_tutorial.md). &nbsp; - **Should I use `--per-gene` with my sequencing from method X?** It can be difficult to work this out sometimes! So far we have come across the following technqies that require the use of `--per-gene`: CEL-seq2, SCRB-seq, 10x Chromium, inDrop, Drop-seq and SPLiT-seq. Let us know if you know of more &nbsp; - **Has the whitelist command been peer-reviewed and compared to alternatives?** No. At the time of the [UMI-tools publication](http://genome.cshlp.org/content/early/2017/01/18/gr.209601.116.abstract`) on 18 Jan '17, the only tools available were `extract`, `dedup` and `group`. The `count` and `whitelist` commands were added later. With `count`, the deduplication part is identical to `dedup`, so it's reasonable to say the underlying agorithm has been peer-reviewed. However, `whitelist` is using an entirely different approach (see [here](https://github.com/CGATOxford/UMI-tools/pull/317) which has not been rigourously tested, compared to alternative algorithms or peer-reviewed. We recommend users to explore other options for whitelisting also. &nbsp; - **Can I use whitelist without UMIs?** Strickly speaking, yes, but only with `--extract-method string`. If you use `--extract-method regex` and don't provide both a UMI and Cell barcode position in the regex, you'll get an error.
Python
UTF-8
1,261
2.640625
3
[ "Apache-2.0" ]
permissive
#! /usr/bin/env python import tensorflow as tf import numpy as np import os import time import datetime import data_helpers from text_cnn import TextCNN from tensorflow.contrib import learn x_text = ['This is a cat','This must be boy', 'This is a a dog zouminminzou'] max_document_length = max([len(x.split(" ")) for x in x_text]) ## Create the vocabularyprocessor object, setting the max lengh of the documents. vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length) ## Transform the documents using the vocabulary. x = np.array(list(vocab_processor.fit_transform(x_text))) ## Extract word:id mapping from the object. vocab_dict = vocab_processor.vocabulary_._mapping ## Sort the vocabulary dictionary on the basis of values(id). ## Both statements perform same task. #sorted_vocab = sorted(vocab_dict.items(), key=operator.itemgetter(1)) sorted_vocab = sorted(vocab_dict.items(), key = lambda x : x[1]) ## Treat the id's as index into list and create a list of words in the ascending order of id's ## word with id i goes at index i of the list. vocabulary = list(list(zip(*sorted_vocab))[0]) print("Vocabulary : ") print(vocabulary) print("Transformed documents : ") print(x) vocab_processor.save(os.path.join("vocab.test"))
C#
UTF-8
1,171
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Entity; namespace ForumSystem { public class ForumDBContext : DbContext { //This class interact with the DB behind the scenes public virtual DbSet<Forum> Forums { get; set; } public virtual DbSet<Member> Members { get; set; } public virtual DbSet<Message> Messages { get; set; } public virtual DbSet<SubForum> SubForums { get; set; } public virtual DbSet<Thread> Threads { get; set; } public class Initializer : DropCreateDatabaseIfModelChanges<ForumDBContext> { protected override void Seed(ForumDBContext context) { //Group root = new Group() { Name = "~" }; //context.Items.Add(root); //Group friends = new Group() { Name = "Friends" }; //root.AddItem(friends); //Person ori = new Person() //{ // FirstName = "Ori", // LastName = "Calvo" //}; //root.AddItem(ori); } } } }
Java
UTF-8
259
1.5
2
[]
no_license
package com.ims.mapper; import com.ims.entity.Teacher; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author admin * @since 2019-12-22 */ public interface TeacherMapper extends BaseMapper<Teacher> { }
C#
UTF-8
1,983
2.6875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Text; using System.Linq; using UnityEngine; using UnityEngine.UI; namespace Ice { public class DebugUI : MonoBehaviour { public Text debugVarsText; private Dictionary<string, Dictionary<string, object>> debugValues = new Dictionary<string, Dictionary<string, object>>(); private void Awake() { DontDestroyOnLoad(gameObject); Refresh(); } public void ShowValueInternal(string category, string key, object val) { if (!debugValues.ContainsKey(category)) { debugValues[category] = new Dictionary<string, object>(); } debugValues[category][key] = val; Refresh(); } public void HideValueInternal(string category, string key) { if (!debugValues.ContainsKey(category)) { return; } debugValues[category].Remove(key); if (debugValues[category].Count < 1) { debugValues.Remove(category); } Refresh(); } public static void ShowValue(string category, string key, object val) { Instance.ShowValueInternal(category, key, val); } public static void HideValue(string category, string key) { Instance.HideValueInternal(category, key); } private void Refresh() { StringBuilder builder = new StringBuilder(); var categories = debugValues.Keys.OrderBy(k => k); foreach (var category in categories) { builder.AppendLine($"[{category}]"); var keys = debugValues[category].Keys.OrderBy(k => k); foreach (var key in keys) { builder.AppendLine($" {key}: {debugValues[category][key]}"); } } debugVarsText.text = builder.ToString(); } // Singleton access. private static DebugUI _instance; private static DebugUI Instance { get { if (_instance == null) { _instance = GameObject.FindObjectOfType<DebugUI>(); } return _instance; } } } }
Markdown
UTF-8
2,269
2.53125
3
[]
no_license
相應部47相應43經/道經(念住相應/大篇/修多羅)(莊春江譯) 起源於舍衛城。 在那裡,世尊召喚比丘們: 「比丘們!這裡,有一次,我住在優樓頻螺,尼連禪河邊牧羊人的榕樹下,初現正覺。比丘們!當我獨處、獨坐時,心中生起了這樣的深思:『為了眾生的清淨、為了愁與悲的超越、為了苦與憂的滅沒、為了方法的獲得、為了涅槃的作證,這是無岔路之道,即:四念住,哪四個呢?比丘能住於在身上隨觀身,熱心、正知、有念,能調伏對於世間的貪婪、憂;或比丘能住於在受上……(中略)或比丘能住於在心上……(中略)或比丘能住於在法上隨觀法,熱心、正知、有念,能調伏對於世間的貪婪、憂。為了眾生的清淨、為了愁與悲的超越、為了苦與憂的滅沒、為了方法的獲得、為了涅槃的作證,這是無岔路之道,即:四念住。』 比丘們!那時,梵王娑婆主以心思量我心中的深思後,猶如有力氣的男子能伸直彎曲的手臂,或彎曲伸直的手臂那樣[快]地在梵天世界消失,出現在我面前。比丘們!那時,梵王娑婆主整理上衣到一邊肩膀,向我合掌鞠躬後,對我這麼說:『正是這樣,世尊!正是這樣,善逝!大德!為了眾生的清淨、為了愁與悲的超越、為了苦與憂的滅沒、為了方法的獲得、為了涅槃的作證,這是無岔路之道,即:四念住,哪四個呢?比丘能住於在身上隨觀身,熱心、正知、有念,能調伏對於世間的貪婪、憂;大德!或比丘能住於在受上……(中略)大德!或比丘能住於在心上……(中略)大德!或比丘能住於在法上隨觀法,熱心、正知、有念,能調伏對於世間的貪婪、憂。為了眾生的清淨、為了愁與悲的超越、為了苦與憂的滅沒、為了方法的獲得、為了涅槃的作證,這是無岔路之道,即:四念住。』 比丘們!這就是梵王娑婆主所說,說此後,又更進一步這麼說: 『看見生的滅盡者、憐愍心者,了知無岔路之道, 在以前以此道渡暴流,他們將來與現在都是。』」
Markdown
UTF-8
938
2.84375
3
[]
no_license
--- title: Teaching and Preaching Tidy Data author: Kevin date: '2018-05-10' slug: data-literacy categories: - R - Tidydata tags: [] description: '' featured: '' featuredalt: '' featuredpath: '' linktitle: '' --- I have been a middle manager in the social service sector for approximately 10 years. In order to manage people both staff and consumers, one has to be able to manage the influx of data that comes to you. The most valuable skill/practice that I have implemented is the practice of keeping tidy data sets and being able to "join" differing data sets. I work with spreadsheet users and I teach and preach tidy data practices all the time. Another critical aspect is teaching users how to use input controls and other data validation tools in spreadsheets to help keep the data clean. The payoff for tidy data practices is the ease of which a pivot table can be generated on the tidy data set. It's a start.
Java
UTF-8
404
2.3125
2
[]
no_license
package oberon0.ast.variables.types; import oberon0.environment.Context; import oberon0.environment.IValue; import oberon0.environment.IntegerValue; public class IntegerType implements IType { @Override public TypeNames getTypeName(Context context) { return TypeNames.INTEGER; } @Override public IValue getDefaultValue(Context context) { return new IntegerValue(0); } }
Java
UTF-8
1,838
2.171875
2
[]
no_license
package io.ticly.mint.mypage.model.dao; import io.ticly.mint.mypage.model.dto.MyPageDTO; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.stereotype.Repository; @Repository public class MyPageDAO { private SqlSessionTemplate sqlSessionTemplate; public MyPageDAO(SqlSessionTemplate sqlSessionTemplate) { this.sqlSessionTemplate = sqlSessionTemplate; } /** * 닉네임 입력창 경고문 출력 * @param mypageDTO * @return */ public int changeNewNickname(MyPageDTO mypageDTO) { int result = sqlSessionTemplate.selectOne("mypageMapper.nickChangeInput", mypageDTO); return result; } /** * 현재 비밀번호 입력창 경고문 출력 * @param mypageDTO * @return */ public int checkPresentPassword(MyPageDTO mypageDTO) { int result = sqlSessionTemplate.selectOne("mypageMapper.presentPasswordInput", mypageDTO); return result; } /** * 닉네임 변경 버튼 클릭 후 출력 * @param mypageDTO * @return */ public int changeButtonNickname(MyPageDTO mypageDTO) { int result = sqlSessionTemplate.update("mypageMapper.nickChangeButton", mypageDTO); return result; } /** * 비밀번호 변경 버튼 클릭 후 출력 * @param mypageDTO * @return */ public int changeButtonPassword(MyPageDTO mypageDTO) { int result = sqlSessionTemplate.update("mypageMapper.passwordChangeButton", mypageDTO); return result; } /** * 탈퇴하기 버튼 클릭 후 출력 * @param mypageDTO * @return */ public int withdrawalButtonId(MyPageDTO mypageDTO) { int result = sqlSessionTemplate.update("mypageMapper.idWithdrawalButton", mypageDTO); return result; } }
TypeScript
UTF-8
1,263
2.65625
3
[ "MIT" ]
permissive
import { isAccessTokenError } from '../../../src/shared/errors/isAccessTokenError'; import { OAuth2Error } from './../../../src/shared/interfaces/OAuth2Error'; import { ACCESS_TOKEN_REVOKED, ACCESS_TOKEN_EXPIRED, ACCESS_TOKEN_INVALID } from './../../../src/shared/errors/constants'; import { expect } from 'chai'; describe('isAccessTokenError', () => { it('should return true if provided error is error of invalid access token', () => { const oAuth2Error: OAuth2Error = ACCESS_TOKEN_INVALID; expect(isAccessTokenError(oAuth2Error)).to.be.true; }); it('should return true if provided error is error of expired access token', () => { const oAuth2Error: OAuth2Error = ACCESS_TOKEN_EXPIRED; expect(isAccessTokenError(oAuth2Error)).to.be.true; }); it('should return true if provided error is error of revoked access token', () => { const oAuth2Error: OAuth2Error = ACCESS_TOKEN_REVOKED; expect(isAccessTokenError(oAuth2Error)).to.be.true; }); it('should return false if provided error is not related to access token', () => { const oAuth2Error: OAuth2Error = { error: 'super_fancy_error', error_description: 'what an error!' }; expect(isAccessTokenError(oAuth2Error)).to.be.false; }); });
Ruby
UTF-8
669
2.765625
3
[]
no_license
class MovieDetailsImporter def call(title) movie = get_movie(title) movie ? prepare_movie_details(movie) : NullMovie.new.details end private def get_movie(title) encoded_title = CGI.escape(title) response = HTTP.get( "https://api.themoviedb.org/3/search/movie?api_key=#{ENV['TMDB_API_KEY']}&language=en-US&query=#{encoded_title}&page=1&include_adult=false" ) JSON.parse(response)["results"].first end def prepare_movie_details(movie) OpenStruct.new( overview: movie["overview"], poster_url: "http://image.tmdb.org/t/p/w185#{movie["poster_path"]}", average_rating: movie["vote_average"] ) end end
JavaScript
UTF-8
3,439
3.4375
3
[]
no_license
/*Mahdollisiman yksinkertinen chatti Socket.io:lla * Socket.io:n toimita perustuu eventteihin. Socket * periin Noden events.eventEmitter -luokan joten se * voi emittoida eventtejä. * * Projektiin pitää asentaa socket.io: npm install socket.io */ let http = require('http'); let fs = require('fs'); let Moniker = require('moniker'); let users = []; let randomNum = (min, max) => { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive } let randNumFirst = randomNum(0, 100000); let randNumSecond = randomNum(0, 100000); let thisGameRand = randNumFirst > randNumSecond ? randomNum(randNumSecond , randNumFirst) : randomNum(randNumFirst, randNumSecond); let numbers = [randNumFirst, randNumSecond]; console.log(thisGameRand); let addUser = () =>{ let user = { name: Moniker.choose(), attempts: 0 } users.push(user); updateUsers(); return user; } let removeUser = (user) => { for(let i=0; i<users.length;i++){ if(user.name === users[i].name) { users.splice(i,1); updateUsers(); return; } } } let updateUsers = () => { let str = ''; for (let i=0; i< users.length; i++) { let user = users[i]; str += user.name + ' <small>(' + user.attempts + ' attempts)</small><br />'; } io.sockets.emit("users", { users: str }); } //http-serveri joka laitetaan muuttujaan app tuottaa sivun client.html let app = http.createServer(function (req, res) { fs.readFile("client.html", 'utf-8', function (error, data) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); res.end(); }); }).listen(3010); console.log('Http server in port 3010'); //Socket-serveri kuuntelee http-serveriä let io = require('socket.io').listen(app); //'connection'-tapahtuma suoritetaan joka kerta kun joku clientin //socket yhdistää serverin socket.io moduliin. Parametrina //oleva muuttuja socket on viittaus clientin socketiin io.sockets.on('connection', function(socket) { let user = addUser(); console.log(user); socket.emit('welcome', user); socket.emit('numbers', numbers) socket.on('disconnect', function () { removeUser(user); }); //Kun clientilta tulee 'message to server' -tapahtuma socket.on('message_to_server', function(data) { //Lähetetään tullut data takaisin kaikille clientin socketeille //emitoimalla tapahtuma 'message_to_client' jolla lähtee JSON-dataa console.log(data.message); if(!Number.isInteger(Number.parseInt(data.message))){ console.log("not a number"); io.sockets.emit("message_to_client",{ message: "Not a number or not an integer, sorry" }); } else{ if(thisGameRand < (Number.parseInt(data.message))){ io.sockets.emit("message_to_client",{ message: data["message"] + " is too big" }); } else if(thisGameRand > (Number.parseInt(data.message))) { io.sockets.emit("message_to_client",{ message: data["message"] + " is too small" }); } else { io.sockets.emit("message_to_client", { message:data["message"] + " This is a Winner number!" }); } } updateUsers(); }); });
JavaScript
UTF-8
3,559
3.203125
3
[]
no_license
class Node { constructor(cellData) { this.weight = cellData.weight; this.isWall = cellData.isWall; } } class Graph { constructor(start, end, cellArr) { this.start = start; this.end = end; this.matrix = {}; this.rows = cellArr.length; this.columns = cellArr[0].length; for (let i = 0; i < this.rows; i++) { for (let j = 0; j < this.columns; j++) { this.matrix[`${i}_${j}`] = new Node(cellArr[i][j]); } } } setWalls(wallsArr) { for (let i = 0; i < wallsArr.length; i++) { let node = wallsArr[i]; this.matrix[node].weight = Infinity; this.matrix[node].isWall = true; } } /* Djikstra methods */ shortestDistanceNode(distances, visited) { let shortest = null; for (let node in distances) { let currentIsShortest = shortest === null || distances[shortest] > distances[node]; if (currentIsShortest && !visited.includes(node)) { shortest = node; } } return shortest; } getChildren(node) { let [i_str, j_str] = node.split('_'); let i = parseInt(i_str); let j = parseInt(j_str); let children = []; let di_dj_arr = [[1, 0], [-1, 0], [0, 1], [0, -1]]; di_dj_arr.forEach(([di, dj]) => { if (i + di >= 0 && j + dj >= 0 && i + di < this.rows && j + dj < this.columns && !this.matrix[`${i + di}_${j + dj}`].isWall) children.push(`${i + di}_${j + dj}`); }) return children; } startAlgorithm() { let distances = {}; // { id(string): distance(number) } // distances[end] = Infinity; let startNodeChildren = this.getChildren(this.start); for (let i = 0; i < startNodeChildren.length; i++) { let child = startNodeChildren[i]; distances[child] = this.matrix[child].weight; } let parents = {}; // parents[end] = null; for (let i = 0; i < startNodeChildren.length; i++) { let child = startNodeChildren[i]; parents[child] = this.start; } let visited = [this.start]; let currNode = this.shortestDistanceNode(distances, visited); while (currNode) { let distance = distances[currNode]; let children = this.getChildren(currNode); for (let i = 0; i < children.length; i++) { let child = children[i]; if (child === this.start) continue; let newDistance = distance + this.matrix[child].weight; if (!distances[child] || distances[child] > newDistance) { distances[child] = newDistance; parents[child] = currNode; } } visited.push(currNode); currNode = this.shortestDistanceNode(distances, visited); if(currNode === this.end) break; } if (parents[this.end] === undefined) { return { path: [], exploredNodes: visited } } let shortestPath = [this.end]; let parent = parents[this.end]; while (parent) { shortestPath.push(parent); parent = parents[parent]; } shortestPath.reverse(); return { path: shortestPath, exploredNodes: visited } } } export default Graph;
C++
UTF-8
916
3.15625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; #include "Sortable.h" class Data { vector<Sortable*> v; public: Data() { } ~Data() { } void add(Sortable* s) { v.push_back(s); } void print() { for (int i = 0; i < v.size(); i++) { //cout << "Circle with radius: " << v[i]->r << endl; } } void sort() { } /* void sort() { int max,num; for (int i = v.size()-1; i >= 1; i--) //For loop to start the sort algorithm { // Minimum to maximum sort max = v[0]; // set max to first slot in array int imax = 0; //index of temporary max for(int j = 1; j <= i; j++) { if (v[j] > v[imax]) { max = v[j]; imax = j; } } if (imax != i) { num = v[i]; // Swaps the current largest number with the last number in the array v[i] = v[imax]; v[imax] = num; } } }*/ };
C++
UTF-8
10,232
3.34375
3
[ "Apache-2.0" ]
permissive
#pragma once #include "XYZ/Core/Ref.h" #include <memory> namespace XYZ { /** * Represents data Components in shader program */ enum class ShaderDataComponent { None = 0, Float, Float2, Float3, Float4, Mat3, Mat4, Int, Int2, Int3, Int4, Bool }; /** * Return size of specified shader data Component * @param[in] Component ShaderDataComponent * @return a size of the Component */ static unsigned int ShaderDataComponentSize(ShaderDataComponent Component) { switch (Component) { case ShaderDataComponent::Float: return 4; case ShaderDataComponent::Float2: return 4 * 2; case ShaderDataComponent::Float3: return 4 * 3; case ShaderDataComponent::Float4: return 4 * 4; case ShaderDataComponent::Mat3: return 4 * 3 * 3; case ShaderDataComponent::Mat4: return 4 * 4 * 4; case ShaderDataComponent::Int: return 4; case ShaderDataComponent::Int2: return 4 * 2; case ShaderDataComponent::Int3: return 4 * 3; case ShaderDataComponent::Int4: return 4 * 4; case ShaderDataComponent::Bool: return 1; } XYZ_ASSERT(false, "Buffer: Unknown ShaderDataComponent"); return 0; } /** * @struct BufferElement * Store information about buffer element * * Each element contains information about it's size in vertex buffer. * The vertex buffers can store only raw data, the buffer element let us use * custom ShaderDataComponent values in the vertex buffers. */ struct BufferElement { /** * Constructor * @param[in] index Index of element in buffer * @param[in] Component Shader data Component * @param[in] name Name of element represented in shader * @param[in] divisior Specify how is data split between instances, default 0 */ BufferElement(uint32_t index, ShaderDataComponent Component, const std::string& name, uint32_t divisor = 0) : Index(index), Component(Component), Divisor(divisor), Size(ShaderDataComponentSize(Component)), Offset(0) {} /** * Split ShaderDataComponent to four byte values and return count * @return a count of four byte values after split */ uint32_t GetComponentCount() const { switch (Component) { case ShaderDataComponent::Bool: return 1; case ShaderDataComponent::Float: return 1; case ShaderDataComponent::Float2: return 2; case ShaderDataComponent::Float3: return 3; case ShaderDataComponent::Float4: return 4; case ShaderDataComponent::Int: return 1; case ShaderDataComponent::Int2: return 2; case ShaderDataComponent::Int3: return 3; case ShaderDataComponent::Int4: return 4; case ShaderDataComponent::Mat3: return 9; case ShaderDataComponent::Mat4: return 16; } XYZ_ASSERT(false, "ShaderDataComponentSize(ShaderDataComponent::None)"); return 0; } ShaderDataComponent Component; uint32_t Size; uint32_t Offset; uint32_t Index; uint32_t Divisor; }; /** * @class BufferLayout * Represents layout of data in buffer. Consists of multiple BufferElements, stored in vector, * let us structure data in the vertex buffer. */ class BufferLayout { public: /** * default Constructor */ BufferLayout() {}; /** * Takes initializer_list of BufferElements. * Generates special Mat4 buffer elements, calcultes offsets and strides in elements * @param[in] elements initializer_list of BufferElements */ BufferLayout(const std::initializer_list<BufferElement>& elements) : m_Elements(elements) { CreateMat4(); CalculateOffsetsAndStride(); } BufferLayout(const std::vector<BufferElement>& elements) : m_Elements(elements) { CreateMat4(); CalculateOffsetsAndStride(); } /** * @return a size of the BufferElements in bytes */ inline const uint32_t& GetStride() const { return m_Stride; } /** * @return a vector of stored BufferElements */ inline const std::vector<BufferElement>& GetElements() const { return m_Elements; } auto begin() { return m_Elements.begin(); } auto end() { return m_Elements.end(); } auto begin() const { return m_Elements.begin(); } auto end() const { return m_Elements.end(); } private: /** * Calculate offsets and strides * * Calculate offset in the vertex buffer for each buffer element, * and size of the BufferElements in bytes */ inline void CalculateOffsetsAndStride() { uint32_t offset = 0; m_Stride = 0; for (auto& element : m_Elements) { element.Offset = offset; offset += element.Size; m_Stride += element.Size; } }; /** * If element Component equals ShaderDataComponent::Mat4 ,it must create three additional elements, * and set for the element and the three additional elements ShaderDataComponent::Float4. */ inline void CreateMat4() { for (auto& element : m_Elements) { if (element.Component == ShaderDataComponent::Mat4) { element.Component = ShaderDataComponent::Float4; element.Size = 4 * 4; BufferElement tmpElement = element; m_Elements.push_back(BufferElement(tmpElement.Index + 1, tmpElement.Component, "", tmpElement.Divisor)); m_Elements.push_back(BufferElement(tmpElement.Index + 2, tmpElement.Component, "", tmpElement.Divisor)); m_Elements.push_back(BufferElement(tmpElement.Index + 3, tmpElement.Component, "", tmpElement.Divisor)); } } } private: std::vector<BufferElement> m_Elements; uint32_t m_Stride = 0; }; /** * Represents usage of the vertex buffer * If Static, the data is not expected to be updated, * if Dynamic, the data is expected to be updated */ enum class BufferUsage { None = 0, Static = 1, Dynamic = 2 }; /** * @interface VertexBuffer * pure virtual (interface) class. * Storage of data for rendering. Send the data to the GPU for further processing. Vertices are rendered by shader program. * VertexArray stores VertexBuffers, must have BufferLayout set before being stored. */ class VertexBuffer : public RefCount { public: virtual ~VertexBuffer() = default; virtual void Bind() const = 0; virtual void UnBind() const = 0; virtual void Update(void* vertices, uint32_t size, uint32_t offset = 0) = 0; virtual void Resize(float* vertices, uint32_t size) = 0; virtual void SetLayout(const BufferLayout& layout) = 0; virtual const BufferLayout& GetLayout() const = 0; virtual uint32_t GetRendererID() const = 0; /** * Create empty VertexBuffer, Buffer usage is Dynamic * @param size Size of the buffer in bytes * @return shared_ptr to VertexBuffer */ static Ref<VertexBuffer> Create(uint32_t size); /** * Create VertexBuffer * @param[in] vertices Pointer to the vertices * @param[in] size Size of the buffer in bytes * @param[in] usage Data in the buffer will be static or dynamic , default Static * @return shared_ptr to VertexBuffer */ static Ref<VertexBuffer> Create(void* vertices, uint32_t size, BufferUsage usage = BufferUsage::Static); }; /** * @interface IndexBuffer * pure virtual (interface) class. * Storage of the indices, send them to the GPU for further processing. * The GPU use stored indices for indexing the vertices in the vertex buffer */ class IndexBuffer : public RefCount { public: virtual ~IndexBuffer() = default; virtual void Bind() const = 0; virtual void UnBind() const = 0; virtual uint32_t GetCount() const = 0; virtual uint32_t GetRendererID() const = 0; /** * Create IndexBuffer * @param[in] indices Pointer to the indices * @param[in] count Count of the indices * @return shared_ptr to IndexBuffer */ static Ref<IndexBuffer> Create(uint32_t* indices, uint32_t count); }; /** * @interface ShaderStorageBuffer * pure virtual (interface) class. * Storage of the data, can be processed by compute shaders. */ class ShaderStorageBuffer : public RefCount { public: virtual ~ShaderStorageBuffer() = default; virtual void BindBase(uint32_t binding) const = 0; virtual void BindRange(uint32_t offset, uint32_t size) const = 0; virtual void Bind() const = 0; virtual void Update(void* vertices, uint32_t size, uint32_t offset = 0) = 0; virtual void Resize(void* vertices, uint32_t size) = 0; virtual void GetSubData(void** buffer, uint32_t size, uint32_t offset = 0) = 0; virtual void SetLayout(const BufferLayout& layout) = 0; virtual const BufferLayout& GetLayout() const = 0; virtual uint32_t GetRendererID() const = 0; /** * Create empty ShaderStorageBuffer, Buffer usage is Dynamic * @param[in] size Size of the buffer in bytes * @return shared_ptr to ShaderStorageBuffer */ static Ref<ShaderStorageBuffer> Create(uint32_t size, uint32_t binding); /** * Create ShaderStorageBuffer * @param[in] vertices Pointer to the vertices * @param[in] size Size of the buffer in bytes * @param[in] usage Data in the buffer will be static or dynamic , default Dynamic * @return shared_ptr to ShaderStoageBuffer */ static Ref<ShaderStorageBuffer> Create(float* vertices, uint32_t size, uint32_t binding, BufferUsage usage = BufferUsage::Dynamic); }; class AtomicCounter : public RefCount { public: virtual ~AtomicCounter() = default; virtual void Reset() = 0; virtual void BindBase(uint32_t index) const = 0; virtual void Update(uint32_t* data, uint32_t count, uint32_t offset) = 0; virtual uint32_t* GetCounters() = 0; virtual uint32_t GetNumCounters() = 0; static Ref<AtomicCounter> Create(uint32_t size, uint32_t binding); }; struct DrawArraysIndirectCommand { uint32_t Count; uint32_t InstanceCount; uint32_t FirstVertex; uint32_t BaseInstance; }; struct DrawElementsIndirectCommand { uint32_t Count; uint32_t InstanceCount; uint32_t FirstIndex; uint32_t BaseVertex; uint32_t BaseInstance; }; class IndirectBuffer : public RefCount { public: virtual ~IndirectBuffer() = default; virtual void Bind() const = 0; virtual void BindBase(uint32_t index) = 0; static Ref<IndirectBuffer> Create(void * drawCommand, uint32_t size, uint32_t binding); }; class UniformBuffer : public RefCount { public: virtual ~UniformBuffer() = default; virtual void Update(const void* data, uint32_t size, uint32_t offset) = 0; static Ref<UniformBuffer> Create(uint32_t size, uint32_t binding); }; }
C#
UTF-8
2,151
2.546875
3
[ "Apache-2.0" ]
permissive
using System; using System.IO; using DevExpress.Web; using Image = System.Drawing.Image; namespace SecurityBestPractices.UploadingFiles { public partial class UploadControl : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // This code is not called by default because uploadControl.FileUploadMode = UploadControlFileUploadMode.BeforePageLoad // To specify validation settings at runtime, set uploadControl.FileUploadMode = UploadControlFileUploadMode.OnPageLoad or // use the uploadControl.Init event uploadControl.ValidationSettings.AllowedFileExtensions = new[] { ".jpg", ".png" }; } protected void uploadControl_FilesUploadComplete(object sender, DevExpress.Web.FilesUploadCompleteEventArgs e) { if(uploadControl.UploadedFiles != null && uploadControl.UploadedFiles.Length > 0) { for(int i = 0; i < uploadControl.UploadedFiles.Length; i++) { UploadedFile file = uploadControl.UploadedFiles[i]; if(file.IsValid && file.FileName != "") { using(var stream = file.FileContent) { // If you need any additional checks, perform them here before saving the file if(!IsValidImage(stream)) { file.IsValid = false; e.ErrorText = "Validation failed!"; } else { string fileName = string.Format("{0}{1}", MapPath("~/UploadingFiles/Images/"), file.FileName); file.SaveAs(fileName, true); } } } } } } static bool IsValidImage(Stream stream) { try { using(var image = Image.FromStream(stream)) { return true; } } catch(Exception) { return false; } } } }
C++
UTF-8
816
2.609375
3
[ "MIT" ]
permissive
/* 1. Connect the input pins of relay module (in this case 4 channel) with 3, 4, 5, and 6 digital pins of Arduino Uno 2. Provide 5V power supply in the Vin of Relay Module. */ const int relay_1_pin = 3; const int relay_2_pin = 4; const int relay_3_pin = 5; const int relay_4_pin = 6; void setup() { pinMode(relay_1_pin, OUTPUT); pinMode(relay_2_pin, OUTPUT); pinMode(relay_3_pin, OUTPUT); pinMode(relay_4_pin, OUTPUT); } void loop() { digitalWrite(relay_1_pin, HIGH); digitalWrite(relay_2_pin, HIGH); digitalWrite(relay_3_pin, HIGH); digitalWrite(relay_4_pin, HIGH); delay(1000); digitalWrite(relay_1_pin, LOW); delay(1000); digitalWrite(relay_2_pin, LOW); delay(1000); digitalWrite(relay_3_pin, LOW); delay(1000); digitalWrite(relay_4_pin, LOW); delay(1000); }
Ruby
UTF-8
587
4.03125
4
[]
no_license
#Seven Ingredients: Ruby #VARIABLES x=10 y="some words" z=false puts x #METHODS (FUNCTIONS) def hr(x=7) d="" x.times do d+="-" end puts d end hr() #CONDITIONALS if (x>10) puts y else puts x end hr() #SETS a=["Luke","Leia","Han"] puts a[0] b={"first"=>"uno", "second"=>"dos"} puts b['first'] hr() #LOOPS a.each{ |n| puts n} hr(3) b.each do |key,val| puts "#{key} is #{val}" end hr(3) 3.times do puts "tres" end hr() #DOCUMENTATION puts "https://www.ruby-lang.org/en/documentation/" #EXECUTION puts "in the terminal type irb or c9.io"
C
UTF-8
289
3.515625
4
[]
no_license
#include<stdio.h> int fib(int n); int main() { int i; for(i=0;i<10;i++) { printf("%d\n",fib(i)); } return 0; } int fib(int n) { int result; if(n==0)return 0; else if(n==1)return 1; else { result=fib(n-1)+fib(n-2); return result; }}
Markdown
UTF-8
7,943
3.375
3
[]
no_license
# Supervised_Learning ## Instructions this project use the imbalanced-learn library to resample the data and build and evaluate logistic regression classifiers using the resampled data. The datasets were inside of the challenge-resources file. This project include two parts: Sampling and Ensemble Learners ## Background Credit risk is an inherently unbalanced classification problem, as the number of good loans easily outnumber the number of risky loans. Therefore, we’ll need to employ different techniques to train and evaluate models with unbalanced classes. we use imbalanced-learn and scikit-learn libraries to build and evaluate models using resampling. ## Dataset: Location: "Challenge/Module-17-Challenge-Resources/LoanStats_2019Q1.csv" The dataset contains the 2019 financial information for individual. Columns include the loan amount, interest rate, home ownership, annual income, loan status.... etc. Overall, we wants to use this information to see does people consider as a potential credit risk person. ## Oversampling & Undersampling ## Oversampling In this section, we will compare two oversampling algorithms to determine which algorithm results in the best performance. You will oversample the data using the naive random oversampling algorithm and the SMOTE algorithm. For each algorithm, be sure to complete the folliowing steps: * View the count of the target classes using Counter from the collections library. * Use the resampled data to train a logistic regression model. * Calculate the balanced accuracy score from sklearn.metrics. * Print the confusion matrix from sklearn.metrics. * Generate a classication report using the imbalanced_classification_report from imbalanced-learn. ## Undersampling In this section, you will test an undersampling algorithms to determine which algorithm results in the best performance compared to the oversampling algorithms above. You will undersample the data using the Cluster Centroids algorithm and complete the folliowing steps: * View the count of the target classes using Counter from the collections library. * Use the resampled data to train a logistic regression model. * Calculate the balanced accuracy score from sklearn.metrics. * Print the confusion matrix from sklearn.metrics. * Generate a classication report using the imbalanced_classification_report from imbalanced-learn. ## Combination Sampling In this section, you will test a combination over- and under-sampling algorithm to determine if the algorithm results in the best performance compared to the other sampling algorithms above. You will resample the data using the SMOTEENN algorithm and complete the folliowing steps: * View the count of the target classes using Counter from the collections library. * Use the resampled data to train a logistic regression model. * Calculate the balanced accuracy score from sklearn.metrics. * Print the confusion matrix from sklearn.metrics. * Generate a classication report using the imbalanced_classification_report from imbalanced-learn. ## Ensemble Learners In this section, you will compare two ensemble algorithms to determine which algorithm results in the best performance. You will train a Balanced Random Forest Classifier and an Easy Ensemble AdaBoost classifier . For each algorithm, be sure to complete the folliowing steps: * Train the model using the training data. * Calculate the balanced accuracy score from sklearn.metrics. * Print the confusion matrix from sklearn.metrics. * Generate a classication report using the imbalanced_classification_report from imbalanced-learn. * For the Balanced Random Forest Classifier onely, print the feature importance sorted in descending order (most important feature to least important) along with the feature score # Findings ## Combination(Over and Undersampling results) ```python pre rec spe f1 geo iba sup 0 0.01 0.70 0.74 0.03 0.72 0.52 87 1 1.00 0.74 0.70 0.85 0.72 0.52 17118 avg / total 0.99 0.74 0.70 0.85 0.72 0.52 17205 ``` ## Precision (Sampling) Compares between undersampling, oversampling and the combination. ALl the model perform bas in the precision. Since the low risk precision is approach to 100% and high risk has only 0.01. THe precision is the measure of the true positive prediction. This result can be due to the True negative has such a big sample. ## Recall Recall is the ability of the classifier to find all the positive samples. All three model has about ~75% of sensitivity . Overall, the best model that has the greatest recall value will be the combination of oversampling and undersampling ## F1 Score The F1 Score does not really tell anything since the precision value for the high risk group is so low. this ccan cause the F1 score to be very low in th high score group. Since the denominator was so small. And for sure the F1 Score for low risk group will be very high. Overall, this result could not tell much things ## Ensemble Learner ```python pre rec spe f1 geo iba sup 0 0.08 0.92 0.95 0.15 0.93 0.87 87 1 1.00 0.95 0.92 0.97 0.93 0.87 17118 avg / total 0.99 0.95 0.92 0.97 0.93 0.87 17205 ``` ## Models’ performance Performance: Random Forest Classifier -True Positive (Acutually =0 and Predict =0), the true positive is 59 -False Negative(Actually =0 and Predict =1), the false negative is 28 -False Positive(Acutally =1 and Predict =0), the false positive is 1821 -True Negative( Actually =1 and Predict =1), The true negative is 15297 ## Precision The precision refering to how many reliable a positive classification is. In the random forest classifier. the precision for high risk is 0.08 and 1 for low risk. From this result we can said this model predict a very poor high risk target. The low precision means large number of false positive. And the 100% precision for low risk means it succefully predict all the true positive for low risk target. In the AdaBoost classifier the precision result is pretty much close wihch is also not ideal ## Recall Recall is the ability of the classifier to find all the positive samples. It can be determined by the ratio. Overall, both model perform a good recall value. A good recall value means there are large amount of true positive and less false negative. ## F1 Score F1 Score is a weight average of true postive rate and precision, both model has low F1 score in high risk and high F1 Score for low risk. The credit risk has two level low_risk and high _risk.In this notebook, we had implemented both Balanced Random Forest Classifier and Adaboost classifier. Based on the summary report we had, we can have some conclusion. Before talking about the result, we needs to clarify the number 0 means high risk and number 1 means low risk. in the random forest classifier, the precision of high risk is almost 0 and the low risk precision is 100%. Apparently, this classifer has an issue in indentifying the low-risk user. In turn of the sensitivity, the low-risk has achieve almost 70% and high risk ~90%, which means the model is really good at finding all the positive samples.The accuracy score for Random Forest classifier is 79% and 93% foe AdaBoost Classiifer. In turn of the accuracy score, the adaboost classifier perform a lot better. However, both model perform very bad in turn of precision. This mean it is very bad in positive classification. Therefore we cannot recommend both model. The major issue from this model is that the prediction of True Negative is too large. this can lead to calculation of precision and the Recall to be biased since the sample number was already been deviated so much.
C#
UTF-8
1,777
2.75
3
[ "CC0-1.0" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PoolManager : MonoBehaviour { #region Serializable Private Fields [SerializeField] private GameObject pooledObject; [SerializeField] private int initialSize; #endregion #region Private Fields private List<GameObject> _objectPool; #endregion #region MonoBehaviour Callbacks // Start is called before the first frame update protected void Start() { InitializePool(); } #endregion #region Protected Methods protected void InitializePool() { _objectPool = new List<GameObject>(); for (int i = 0; i < initialSize; i++) { GameObject createdObject = Instantiate(pooledObject, transform); createdObject.SetActive(false); _objectPool.Add(createdObject); } } #endregion #region Public Methods public virtual GameObject ActivateObject(Vector3 position) { if (_objectPool.Count > 0) { GameObject objectToActivate = _objectPool[0]; objectToActivate.SetActive(true); objectToActivate.transform.parent = null; objectToActivate.transform.position = position; _objectPool.RemoveAt(0); return objectToActivate; } GameObject createdObject = Instantiate(pooledObject, position, Quaternion.identity); return createdObject; } public virtual void DeactivateObject(GameObject objectToDeactivate) { objectToDeactivate.SetActive(false); objectToDeactivate.transform.parent = transform; _objectPool.Add(objectToDeactivate); } #endregion }
Java
UTF-8
166
1.929688
2
[]
no_license
package com.xfhy.flyweight; /** * @author : xfhy * Create time : 2020/1/7 22:38 * Description : 网站接口 */ interface WebSite { void use(User user); }
Markdown
UTF-8
596
2.671875
3
[ "MIT" ]
permissive
# GlibGrade GlibGrade aims to keep users informed by giving rating s to the verifiability of web apps. It gives a verbal feedback from our machine learning algorithm and a community numerical rating so that the user has multiple sources to get input from. ### Example: <strong>Before GlibGrade:</strong><br/> ![News article with no additional information](images/noGlibGrade.png?raw=true) <strong>After GlibGrade:</strong><br/> ![News article with with additional information](images/withGlibGrade.png?raw=true)<br/> ![Displaying the glibgrade features](images/displayGlibGrade.png?raw=true)
Markdown
UTF-8
816
2.546875
3
[]
no_license
# MidiKeys > Uses WebMIDI to pipe MIDI messages into a browser ### NOTES: Built to run in browser with global variable available via `<script>` load. Special setup as follows: * Set entry to './src/midi-keys.js' * Added output options (from: https://www.made-on-mars.com/blog/how-to-create-a-npm-module-that-works-on-browser-with-webpack-2/): * libraryTarget: 'umd' # Built with Webpack Starter > Starter template for web development without a framework To use: --- Run in development mode: ``` npm start ``` _Start a local development server at port 3000. Navigate to http://localhost:3000/ in your browser_ Build for production: ``` npm run build ``` _Build an optimized version for production_ Features --- * Hot reloading in development * SASS support * ES6 support * Autoprefixer for css
Markdown
UTF-8
1,608
2.90625
3
[]
no_license
## [Solo project] cc8-project.continuous-delivery-vue-3 ### This was created during my time as a [Code Chrysalis](https://codechrysalis.io) Student - full stack project to create search website <img src="gmap-with-marker.png" alt="attach:filter" title="attach:filter" width="1000" height="600"> <img src="filter.png" alt="attach:filter" title="attach:filter" width="1000" height="500"> # What we can do for user? - user can see the map with marker of truck stop - user can select States from dropdown in filter # Challenge - set up local dev/production server - create database, insert correct data - reflect data to filter & GoogleMap - Show up marker on GoogleMap # Achievement - Created server - Created database - Inserted correct data - Created Heroku database - Inserted correct data into Heroku database - Access data in database and apply it to dropdown - Show up all truck stop marker on GoogleMap # Things what I learned - Database creattion - Relation of files and flow of data from root to child - async / Promise (Don't forget to apply .then!!) - higher order function is really helpful when we deal data(map, filter, reduce etc...) # Things what I need to remember - When you see Observe in console.log, it is Promise! - Don't forget 'this' when you add any data to provided space.(e.g. this.location, this.stateArray) # Syntax/cli memo for future - heroku database with knex execute by command line - migrate : `heroku run knex migrate:latest --app <heroku app name>` - seed : `heroku run knex run:seed --app <heroku app name>` - app log check : `heroku logs --app <heroku app name>`
Python
UTF-8
772
2.640625
3
[]
no_license
import matplotlib matplotlib.use('TkAgg') import networkx as nx, pylab Dt = 0.01 alpha = 0.1 omega = 0.1 lamb = 0.1 def init(): global g, nextg g = nx.karate_club_graph() for i in g.nodes(): g.node[i]['state'] = pylab.randint(1,11) nextg = g.copy() g.pos = nx.spring_layout(g) def update(): global g, nextg for i in g.nodes(): c = g.node[i]['state'] nextg.node[i]['state'] = c+(1j*omega*c+alpha*(\ sum((g.node[j]['state'])**lamb for j in list(g.neighbors(i)))-g.degree(i)*c))*Dt g, nextg = nextg, g g.pos = nx.spring_layout(g) def observe(): global g pylab.cla() nx.draw(g, node_color = [g.node[i]['state'] for i in list(g.nodes())], pos = g.pos) pylab.show() import pycxsimulator pycxsimulator.GUI().start(func = [init, observe, update])
Ruby
UTF-8
1,866
2.65625
3
[ "MIT" ]
permissive
module StateMachinable module Base extend ActiveSupport::Concern class_methods do def state_class(state) "#{self}::#{state.classify}".constantize rescue NameError nil end end included do include Statesman::Machine state :initial, :initial => true before_transition do |obj, _transition| state_class = obj.state_machine.class.state_class(obj.state_machine.current_state) if state_class.present? && state_class.respond_to?(:exit) state_class.exit(obj) end end after_transition do |obj, transition| state_class = obj.state_machine.class.state_class(transition.to_state) update_hash = {} if state_class.present? && state_class.respond_to?(:pre_enter_updates_to_do) update_hash.merge!(state_class.pre_enter_updates_to_do(obj)) end obj.update(update_hash.merge!(:current_state => transition.to_state)) if state_class.present? && state_class.respond_to?(:enter) state_class.enter(obj) end end def method_missing(name, *args, &block) begin events = "#{self.class}::EVENTS".constantize.dup rescue NameError events = [] end clean_name = name.to_s.chomp('!').to_sym if events.include?(clean_name) state_class = self.class.state_class(self.current_state) if state_class.present? && state_class.respond_to?(clean_name) state_class.send(clean_name, self.object, *args) else if name.to_s.last == '!' raise StateMachinable::EventNotHandledException.new(:event => clean_name, :state => self.current_state) else nil end end else super end end end end end
C#
UTF-8
561
3.5
4
[]
no_license
using System; namespace ConsoleApp1 // Parameterized and non parameterized method { class Method1 { public void method1() { Console.WriteLine(" This is non parameterized method "); } public void method2(int a, int b) { Console.WriteLine(" This is parameterized method"); } static void Main(string[] args) { Method1 m = new Method1(); m.method1(); m.method2(10, 20); Console.ReadKey(); } } }
C++
UTF-8
634
3.375
3
[]
no_license
#include "6.2.h" #include "stack.h" #include <iostream> using namespace std; bool eventLoop(Stack* stack, const string& characters) { for (int i = 0; i < characters.size(); ++i) { if (head(stack) == nullptr || characters[i] == '(' || characters[i] == '[' || characters[i] == '{') { push(stack, characters[i]); } else { char temp = pop(stack); if (characters[i] == ')' && temp != '(' || characters[i] == ']' && temp != '[' || characters[i] == '}' && temp != '{') { return false; } } } return true; }
Python
UTF-8
1,054
2.953125
3
[]
no_license
from braindump import meta def test_string_to_identifier(string_to_identifier): for string, identifier in string_to_identifier.iteritems(): result = meta.recase(unicode(string)) assert result == identifier def test_identifier_to_string(identifier_to_string): for identifier, string in identifier_to_string.iteritems(): result = meta.recase(identifier, 'slug') assert result == unicode(string) def test_splitting(splits): for string, variants in splits.iteritems(): splitter = meta.Split(string) for variant, value in variants.iteritems(): split = getattr(splitter, variant) assert split == value for word in split: assert type(word) is unicode def test_casing(casings): casing = meta.Casing(casings['words']) if 'repr' in casings: assert repr(casing) == casings['repr'] for case, value in casings['cases'].iteritems(): cased = getattr(casing, case) assert cased == value and type(cased) is unicode
SQL
UTF-8
2,645
3.046875
3
[]
no_license
-- MySQL dump 10.13 Distrib 8.0.20, for Win64 (x86_64) -- -- Host: localhost Database: streetview -- ------------------------------------------------------ -- Server version 8.0.20 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!50503 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `userinfo` -- DROP TABLE IF EXISTS `userinfo`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `userinfo` ( `idUserInfo` int NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, `nickName` varchar(45) DEFAULT NULL, `faceID` int NOT NULL DEFAULT '0', `password` varchar(45) DEFAULT NULL, `createDate` datetime DEFAULT NULL, `lastLoginDate` datetime DEFAULT NULL, `score` int NOT NULL DEFAULT '0' COMMENT '用户评分,质量和数量的综合情况', `experience` int DEFAULT '0' COMMENT '经验,接任务就会增长经验', `age` int DEFAULT '0', PRIMARY KEY (`idUserInfo`), UNIQUE KEY `name_UNIQUE` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户信息表'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `userinfo` -- LOCK TABLES `userinfo` WRITE; /*!40000 ALTER TABLE `userinfo` DISABLE KEYS */; INSERT INTO `userinfo` VALUES (1,'zhangs','评分王张',1,'houston12','2020-06-24 13:50:11','2020-06-24 13:50:11',0,0,25),(2,'thw','谭惠文',4,'thw','2020-06-24 13:50:11','2021-01-07 20:52:57',0,15,18),(3,'dwight','dwight',5,'123456','2021-01-06 08:58:09','2021-01-07 21:05:45',0,65,0); /*!40000 ALTER TABLE `userinfo` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2021-01-08 16:31:15
Markdown
UTF-8
3,051
3.125
3
[]
no_license
The run_analysis.R script performs a data tidying process on the dataset provided. First download the dataset. Dataset was downloaded and extracted under the file/folder called UCI HAR Dataset. Variables were assigned to each data. features <- features.txt : 561 rows, 2 columns The features selected for this database come from the accelerometer and gyroscope 3-axial raw signals tAcc-XYZ and tGyro-XYZ activities <- activity_labels.txt : 6 rows, 2 columns List of activities performed when the corresponding measurements were taken and its codes (labels) subject_test <- test/subject_test.txt : 2947 rows, 1 column contains test data of 9/30 volunteer test subjects being observed x_test <- test/X_test.txt : 2947 rows, 561 columns contains recorded features test data y_test <- test/y_test.txt : 2947 rows, 1 columns contains test data of activities’code labels subject_train <- test/subject_train.txt : 7352 rows, 1 column contains train data of 21/30 volunteer subjects being observed x_train <- test/X_train.txt : 7352 rows, 561 columns contains recorded features train data y_train <- test/y_train.txt : 7352 rows, 1 columns contains train data of activities’code labels. Merged the training and the test sets to create one data set. A X dataset of 10299 rows and 561 columns was created by merging x_train and x_test using rbind() function A Y dataset of 10299 rows and 1 column was created by merging y_train and y_test using rbind() function A Subject dataset of 10299 rows and 1 column was created by merging subject_train and subject_test using rbind() function A Merged_Data dataset of 10299 rows and 563 column was created by merging Subject, Y and X using cbind() function. Only the measurements on the mean and standard deviation for each measurement was extracted. A TidyData dataset of 10299 rows, 88 columns was created by subsetting Merged_Data, selecting only columns: subject, code and the measurements on the mean and standard deviation (std) for each measurement. Used descriptive activity names to name the activities in the data set Numbers in code column of the TidyData was replaced with corresponding activity taken from second column of the activities variable. Appropriately labels the data set with descriptive variable names. code column in TidyData renamed into activities All Acc in column’s name was replaced by Accelerometer All Gyro in column’s name was replaced by Gyroscope All BodyBody in column’s was name replaced by Body All Mag in column’s name was replaced by Magnitude All start with character f in column’s name was replaced by Frequency All start with character t in column’s name was replaced by Time. From the data set above create a second, independent tidy data set with the average of each variable for each activity and each subject FinalData dataset of 180 rows, 88 columns was created by sumarizing TidyData taking the means of each variable for each activity and each subject, after groupped by subject and activity. Finally export FinalData into FinalData.txt file.
Markdown
UTF-8
1,852
2.875
3
[]
no_license
# Elm Tetris [![Actions Status](https://github.com/yonigibbs/yaet/workflows/Node.js%20CI/badge.svg)](https://github.com/yonigibbs/yaet/actions) This repo contains a version of Tetris, written in Elm. #### Play the game [here](https://yonigibbs.github.io/yaet/). ## Development To run the project locally clone the repo, run `npm install` (only needed once), then run `npm run serve`. This will start [Parcel](https://parceljs.org/) to serve the app on http://localhost:1234. The entry point to the app is [index.html](src/index.html). This loads [index.js](src/index.js), which in turn loads the Elm app itself. The entry point to the Elm code is [Main.elm](src/Main.elm). This module, like the rest, contains comments at the top that explain a bit about it, and should help you find your way around the code. ## Possible future enhancements * Allow game to be played on more devices * Add buttons to control the game, for devices without keyboards * Make the UI responsive * Prevent default browser behaviour on key presses, otherwise arrow keys can cause the viewport to move if the browser window is small (see https://github.com/elm/browser/issues/89) * Some complex moves currently might not be fully possible: investigate T-spin triple, for example * Let user pause/resume by clicking on game * Add bonus points for hard drop * Improve Game Over animation - drop the "Game Over" message down from top of board * Use `elm-animator` instead of doing animations manually * Add smoother transitions (e.g. fade out/in) between welcome screen and game screen * Minor issues with some corner cases around trapping Enter key on modal dialogs - if the Cancel (or Restore Defaults) button has focus and user presses Enter, what should happen? Is it even normal in web UI to treat Enter as Submit, in modals with no editable controls?
PHP
UTF-8
1,305
2.5625
3
[]
no_license
<?php error_reporting(0); $db_filename = "../db/db.sqlite"; if($db = sqlite_open($db_filename, 0666)) { $user_id = sqlite_escape_string($_GET['user_id']); $query = sqlite_query($db, "SELECT code FROM users WHERE id = '$user_id'"); $user = sqlite_fetch_array($query, SQLITE_ASSOC); sqlite_close($db); } if($user === false) { exit("Error."); } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Personalized Web Search Survey</title> <style> body { text-align: center; background: #DDD; } .content { text-align: left; margin: 0 auto; max-width: 700px; padding: 20px 10px; background: #FFF; border: 1px solid #241522; } h1 { font-size: 400%; margin: 0; } p { font-size: 150%; } .footnote { font-size: 90%; color: #333; } label, input { font-size: 200%; } label { margin-top: 0.5em; display: block; } #name, #email { background: #EFEFEF; border: 1px solid #A3A3A3; } </style> </head> <body> <div class="content"> <p>Thank you for your participation. You code is: <?php echo $user['code'] ?></p> <p>Please arrange a time to meet with the researcher to exchange this code for your renumeration.</p> </div> </body> </html>
Java
UTF-8
2,679
2.328125
2
[]
no_license
package org.uh.hulib.attx.services.ontology; import static spark.Spark.*; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Random; public class OntologyService { public static void main() { int maxThreads = 6; int minThreads = 5; int timeOutMillis = 30000; String apiVersion = "0.2"; port(4305); threadPool(maxThreads, minThreads, timeOutMillis); get("/health", (request, response) -> "Hello World"); post(String.format("/%s/infer", apiVersion), "application/json", (request, response) -> { String content = request.body(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(content); SQLiteConnection data = SQLiteConnection.main(); String result = null; if (jsonNode.has("schemaGraph") && jsonNode.has("dataGraph")) { // Load the main data model String schemaGraph = jsonNode.get("schemaGraph").asText(); String dataGraph = jsonNode.get("dataGraph").asText(); result = OntologyUtils.OntologyInfer(dataGraph, schemaGraph); } else { // FOR NOW DO NOTHING } Random rand = new Random(); int n = rand.nextInt(500000) + 1; data.insert(n, result); response.status(200); // 200 Done response.type("text/turtle"); return result; }); post(String.format("/%s/validate", apiVersion), "application/json", (request, response) -> { String content = request.body(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(content); SQLiteConnection data = SQLiteConnection.main(); String result = null; if (jsonNode.has("schemaGraph") && jsonNode.has("dataGraph")) { // Load the main data model String schemaGraph = jsonNode.get("schemaGraph").asText(); String dataGraph = jsonNode.get("dataGraph").asText(); result = OntologyUtils.ValidityReport(dataGraph, schemaGraph); } else { // FOR NOW DO NOTHING } Random rand = new Random(); int n = rand.nextInt(500000) + 1; data.insert(n, result); response.status(200); // 200 Done response.type("text/turtle"); return result; }); } public void run() { OntologyService.main(); } }
JavaScript
UTF-8
2,208
3.3125
3
[]
no_license
/* 학급 회장(해쉬) 학급 회장을 뽑는데 후보로 기호 A, B, C, D, E 후보가 등록을 했습니다. 투표용지에는 반 학생들이 자기가 선택한 후보의 기호(알파벳)가 쓰여져 있으며 선생님은 그 기호를 발표하고 있습니다. 선생님의 발표가 끝난 후 어떤 기호의 후보가 학급 회장이 되었는지 출력하는 프로그램을 작 성하세요. 반드시 한 명의 학급회장이 선출되도록 투표결과가 나왔다고 가정합니다. ▣ 입력설명 첫 줄에는 반 학생수 N(5<=N<=50)이 주어집니다. 두 번째 줄에 N개의 투표용지에 쓰여져 있던 각 후보의 기호가 선생님이 발표한 순서대로 문자열로 입력됩니다. ▣ 출력설명 학급 회장으로 선택된 기호를 출력합니다. ▣ 입력예제 1 15 BACBACCACCBDEDE ▣ 출력예제 1 C */ const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const input = []; rl.on("line", (line) => { input.push(line); if (input.length === 2) rl.close(); }).on("close", () => { const n = +input[0]; const str = input[1]; // const result = { // A: 0, // B: 0, // C: 0, // D: 0, // E: 0, // }; // for (let s of str) { // result[s] += 1; // } // let max = Number.MIN_SAFE_INTEGER; // let answer = ""; // for (let i in result) { // if (max < result[i]) { // max = result[i]; // answer = i; // } // } // console.log(answer); // const hash = new Map(); // let result = ""; // for (let s of str) { // if (hash.has(s)) hash.set(s, hash.get(s) + 1); // else hash.set(s, 1); // } // let max = Number.MIN_SAFE_INTEGER; // for (let [key, value] of hash) { // if (value > max) { // max = value; // result = key; // } // } // console.log(result); const hash = {}; for (let s of str) { if (hash[s]) hash[s]++; else hash[s] = 1; } let max = Number.MIN_SAFE_INTEGER; let result = ""; for (let key of Object.keys(hash)) { if (max < hash[key]) { max = hash[key]; result = key; } } console.log(result); });
Java
UTF-8
241
1.828125
2
[]
no_license
package com.stackroute.authorizeapp.service; import com.stackroute.authorizeapp.model.UserProfile; public interface UserprofileService { UserProfile addUser(UserProfile usernew); boolean validateUser(String email,String pass); }
Java
UTF-8
2,488
2.59375
3
[]
no_license
package com.cloud.util; import java.util.ArrayList; import java.util.List; import org.apache.commons.mail.EmailAttachment; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.apache.log4j.Logger; public class MailUtil { private static final Logger LOGGER = Logger.getLogger(MailUtil.class); private static String charset = "utf-8"; private String host = ""; private String username = ""; private String password = ""; private String nick = ""; public MailUtil(){ this.host = PropertiesUtil.getValue("mail.host"); this.username = PropertiesUtil.getValue("mail.username"); this.password = PropertiesUtil.getValue("mail.password"); this.nick = PropertiesUtil.getValue("mail.nick"); } public boolean sendMail(List<String> to,String subject,String body,List<String> filepath){ return sendMail(username,password,nick,to,subject,body,filepath); } public boolean sendMail(String username,String password,String nickName,List<String> to,String subject,String body,List<String> filepath){ try { if(body == null){ body = ""; } if(subject == null){ subject = "无主题"; } HtmlEmail email = new HtmlEmail(); email.setSSLOnConnect(true); //SSL加密 email.setStartTLSEnabled(true); //TLS加密 email.setHostName(host); email.setAuthentication(username, password); email.setFrom(username,nickName); if(to != null && to.size() > 0){ for(String address:to){ email.addTo(address); } }else{ return false; } email.setCharset(charset); email.setSubject(subject); email.setHtmlMsg(body); if(filepath != null && filepath.size() > 0){ for(String path:filepath){ //创建附件 String name = path.substring(path.lastIndexOf("/")+1); EmailAttachment attachment = new EmailAttachment(); attachment.setPath(path); attachment.setDescription(EmailAttachment.ATTACHMENT); attachment.setDescription(""); attachment.setName(name); email.attach(attachment); } }else{ System.out.println("no file."); } email.send(); }catch(EmailException e){ LOGGER.error(e); return false; } return true; } public static void main(String[] args) throws EmailException { List<String> to = new ArrayList<String>(); to.add("274925658@qq.com"); MailUtil util = new MailUtil(); boolean flag = util.sendMail(to, "Test Email", "<div>Test Message :中文信息</div>", null); System.out.println(flag); } }
C
UTF-8
785
3.765625
4
[]
no_license
#include <stdio.h> #include "NumClass.h" int main(){ int num1 ,num2; scanf("%d%d",&num1,&num2); if(num1>num2){ int temp=num1; num1=num2; num2=temp; } printf("The Armstrong numbers are:"); for (int i = num1; i < num2; i++) { if(isArmstrong(i)==1){ printf(" %d",i); } } printf("\n"); printf("The Palindromes are:"); for (int i = num1; i < num2; i++) { if(isPalindrome(i)==1){ printf(" %d",i); } } printf("\n"); printf("The Prime numbers are:"); for (int i = num1; i < num2; i++) { if(isPrime(i)==1){ printf(" %d",i); } } printf("\n"); printf("The Strong numbers are:"); for (int i = num1; i < num2; i++) { if(isStrong(i)==1){ printf(" %d",i); } } printf("\n"); return 0; }
Java
UTF-8
128
2.046875
2
[]
no_license
package com.solid.interfaceseg; // Interface Segregation public interface ConvertIntToCharacter { public void intToChar(); }
Python
UTF-8
1,228
2.640625
3
[]
no_license
from django.db import models from django.contrib.auth.models import User class Show(models.Model): """ This class contains the name of the show as well as the id. The id is not defined here as it is added by default to every model """ name = models.CharField(max_length=200) def __unicode__(self): return str(self.id) + ": " + self.name class Meta: """ Add the necessary permissions for the show model """ permissions = ( ("can_have_favs", "Can the user have favourite shows"), ) class GuideEntry(models.Model): """ This class contains the start time, network that it is playing on, and a referance to a show """ start = models.DateTimeField() network = models.CharField(max_length=25) show = models.ForeignKey(Show) def __unicode__(self): return str(str(self.start) + " " + self.network + " " + str(self.show.id) + " " + self.show.name) class UserProfile(models.Model): """ This class 'extends' the user model so that favourites can be linked to a user """ user = models.ForeignKey(User, unique=True) fav_shows = models.ManyToManyField(Show)
Python
UTF-8
1,803
3.015625
3
[]
no_license
import requests from pprint import pprint version = '5.69' access_token = '873fcd36b45b3109194fe20b24e973739bd9b9db170a0a251097c651cf93325eeb49895c8a52e170ae358' def from_list_to_dict(friends_list): friends_dict = dict() for friend in friends_list: try: if friend['deactivated']: continue except: friends_dict[friend['first_name'] + ' ' + friend['last_name']] = friend['id'] return friends_dict def pairs_create(friends): pairs = dict() for num, friend in enumerate(friends): for friend_tmp in friends: if (friend_tmp != friend) and (friend + '-' + friend_tmp not in pairs)\ and (friend_tmp + '-' + friend not in pairs): pairs[friend + '-' + friend_tmp] = str(friends[friend]) + '-' + str(friends[friend_tmp]) return pairs def mutual_friends_find(pairs): mutual_friends = dict() for key, pair in pairs.items(): friends = pair.split('-') friend1 = friends[0] friend2 = friends[1] try: mutual_friends[key] = requests.get('https://api.vk.com/method/friends.getMutual', params={ 'source_uid': friend1, 'target_uid': friend2, 'v': version, 'access_token': access_token }).json()['response'] except: continue return mutual_friends def friend_pairs_create(): params = { 'access_token': access_token, 'v': version, 'fields': 'id' } my_friends_list = requests.get('https://api.vk.com/method/friends.get', params).json()['response']['items'] my_friends_dict = from_list_to_dict(my_friends_list) pairs = pairs_create(my_friends_dict) return pairs pairs = friend_pairs_create() mutual_friends = mutual_friends_find(pairs) pprint(mutual_friends)
Ruby
UTF-8
6,290
2.640625
3
[]
no_license
# frozen_string_literal: true class BatchImport < ApplicationRecord PENDING = 'pending' IN_PROGRESS = 'in_progress' COMPLETED_SUCCESSFULLY = 'completed_successfully' COMPLETE_WITH_FAILURES = 'complete_with_failures' CANCELLED = 'cancelled' STATUSES = [PENDING, IN_PROGRESS, COMPLETED_SUCCESSFULLY, COMPLETE_WITH_FAILURES, CANCELLED].freeze enum priority: { low: 0, medium: 1, high: 2 } serialize :setup_errors, Array before_destroy :ensure_imports_are_complete!, prepend: true after_destroy :delete_associated_file has_many :digital_object_imports, dependent: :destroy belongs_to :user validates :priority, presence: true def delete_associated_file Hyacinth::Config.batch_import_storage.delete(file_location) if file_location.present? end def status return CANCELLED if cancelled total_imports = import_status_count.values.sum if import_count('in_progress').positive? IN_PROGRESS elsif import_count('pending').positive? || total_imports.zero? PENDING elsif import_count('success') == total_imports COMPLETED_SUCCESSFULLY else COMPLETE_WITH_FAILURES end end # This method queries for the count of each status once and caches it. For subsequent requests the same # count will be used, it will not be recalculated. def import_status_count @import_status_count ||= digital_object_imports.group(:status).count end def import_count(status) import_status_count[status] || 0 end # Moves active storage blob into permanent storage, saves location and original filename to batch import. def add_blob(blob) storage = Hyacinth::Config.batch_import_storage location = storage.generate_new_location_uri(SecureRandom.uuid) self.original_filename = blob.filename.to_s self.file_location = location storage.with_writable(location) do |output_file| blob.download { |chunk| output_file << chunk } end end # Returns csv string with successful rows removed. Keeps the original order of the rows. def csv_without_successful_imports raise 'Cannot generate csv without successful rows without file_location' unless file_location # Using set for faster lookup unsuccessful_indices = digital_object_imports.where.not(status: :success).pluck(:index).to_set storage = Hyacinth::Config.batch_import_storage new_csv = '' storage.with_readable(file_location) do |io| csv = CSV.new(io, headers: :first_row, return_headers: true) csv.each_with_index do |row, index| new_csv += CSV.generate_line(row) if row.header_row? || unsuccessful_indices.include?(index + 1) end end new_csv end def self.csv_file_to_hierarchical_json_hash(csv_file) JsonCsv.csv_file_to_hierarchical_json_hash(csv_file.path) do |json_hash_for_row, csv_row_number| # Convert csv-formatted, header-derived json to the expected attribute format BatchImport.import_json_to_digital_object_attribute_format!(json_hash_for_row) yield json_hash_for_row, csv_row_number end end # Reads the csv data from the given blob and performs "pre-validation" on the CSV data. # "Pre-validation" is a non-comprehensive check that's meant to quickly catch common errors # without doing more computationally expensive operations like creating objects or doing extensive # database queries. This method is primarily used for validating a CSV before it's split up and # turned into DigitalObjectImports, which have more extensive checks done as they're processed. # # @return Array(Boolean, String[]) # Sample return value for failed validation: # [false, ['Something went wrong!', 'Something else went wrong!']] # Sample return value for successful validation: # [true, []] def self.pre_validate_blob(blob) pre_validation_errors = [] blob.open do |file| # TODO: Make sure there aren't any duplicate headers csv_file_to_hierarchical_json_hash(file) do |json_hash_for_row, _csv_row_number| # TODO: Make sure that only valid fields are present in the dynamic field data properties # TODO: Make sure that all new object rows have a digital_object_type # TODO: Make sure that all referenced projects exist # TODO: Make sure that all new asset rows minimally have a main # TODO: Make sure that the same UID doesn't appear in more than one row end end [pre_validation_errors.blank?, pre_validation_errors] end # Converts a CSV-header-derived JSON-like hash structure to the expected digital object # attribute format, moving all non-underscore-prefixed top level key-value pairs under # descriptive_metadata and removing the underscore prefix from all top level keys. # Note: This method modifies the passed-in object! def self.import_json_to_digital_object_attribute_format!(import_json) # Add descriptive_metadata hash descriptive_metadata = {} # Move all non-underscore-prefixed keys under descriptive_metadata import_json.delete_if do |key| next false if key.start_with?('_') descriptive_metadata[key] = import_json[key] true end # Assign descriptive_metadata to 'descriptive_metadata' key in import_json import_json['descriptive_metadata'] = descriptive_metadata # Remove leading underscore from all remaining underscore-prefixed keys import_json.transform_keys! { |key| key.start_with?('_') ? key[1..-1] : key } # Return modified hash import_json end private # Callback to check that a batch import can be deleted. A batch import # can only be deleted if it's cancelled and no digital object imports # are in progress or if no digital object imports are 'in_progress' or 'pending' def ensure_imports_are_complete! imports_pending = import_count('pending').positive? imports_in_progress = import_count('in_progress').positive? if cancelled && imports_in_progress errors.add(:base, 'Cannot destroy cancelled batch import while imports are in_progress') throw :abort elsif !cancelled && (imports_in_progress || imports_pending) errors.add(:base, 'Cannot destroy batch import while imports are in_progress or pending') throw :abort end end end
C#
UTF-8
1,925
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AgendaDeContatos.Entidades { public class EntidadePessoa { private int id; private string nome; private string cpf; private DateTime dataNascimento; private string email; public EntidadePessoa() { } public EntidadePessoa(string nome, string cpf, DateTime nascimento, string email) { this.nome = nome; this.cpf = cpf; this.dataNascimento = nascimento; this.email = email; } public virtual int Id { get { return id; } set { id = value; } } public virtual string Nome { get { return nome; } set { if (value != string.Empty) { nome = value; } else { nome = "Nome obrigatorio"; } } } public virtual string CPF { get { return cpf; } set { if (value != string.Empty) { cpf = value; } else { cpf = "Nome obrigatorio"; } } } public virtual DateTime DataNascimento { get { return dataNascimento; } set { dataNascimento = value; } } public virtual string Email { get { return email; } set { if (value != string.Empty) { email = value; } else { email = "Nome obrigatorio"; } } } } }
Java
UTF-8
1,283
2.53125
3
[ "Apache-2.0" ]
permissive
package com.vise.bledemo.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.vise.bledemo.R; import java.util.List; public class OutPutAdapter extends RecyclerView.Adapter<OutPutAdapter.ViewHolder> { private List<String> list; private Context context; public OutPutAdapter(List<String> list, Context context) { this.list = list; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = View.inflate(context, R.layout.out_put_item, null); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { String s = list.get(position); holder.textView.setText(s); } @Override public int getItemCount() { return list.size(); } static class ViewHolder extends RecyclerView.ViewHolder { TextView textView; public ViewHolder(View itemView) { super(itemView); textView = (TextView) itemView.findViewById(R.id.tv_out_item); } } }
Java
UTF-8
5,036
2.84375
3
[ "MIT" ]
permissive
package com.fengwenyi.api_result.entity; import com.fasterxml.jackson.annotation.JsonInclude; import java.io.Serializable; import java.util.Objects; /** * 接口响应实体类 <br> * * <br> * * 属性介绍:<br> * <ul> * <li>success:返回结果标识。true为成功; false为失败</li> * <li>code:响应码,可根据项目业务指定错误码,便于业务处理</li> * <li>message:描述信息,错误时,可以在这里填写错误的详细信息</li> * <li>data:数据,成功并且需要返回数据时,才有该参数</li> * <li>page:分页实体类,接口返回时,会以对象的形式返回</li> * </ul> * * <br> * * 关于泛型的说明:<br> * 响应实体类,用到了两个泛型,分别是响应码(C)和数据(T)。<br> * 响应码(C),可根据业务系统自行指定类型,可以是数字,也可以是字符串。<br> * 数据是一个泛型(T),可以是基本数据类型,Map,对象或是一个数组(数组里面可以包含多个对象)<br> * * <br> * * 另外,该实体类使用了构建者模式,你可以一直set下去,非常方便。 * * @author Erwin Feng * @since 2.1.0 */ @JsonInclude(JsonInclude.Include.NON_NULL) public class ResponseEntity<C, T> implements Serializable { private static final long serialVersionUID = -4186783016544888615L; /** 响应码 */ private C code; /** 响应码描述信息 */ private String message; /** 响应结果状态,{@code true} 表示成功;{@code false} 表示失败 */ private Boolean success; /** 响应数据 */ private T data; /** 分页 */ private ResponsePageEntity page; /** * 获取属性 {@code code} 的值 * @return 获取属性 {@code code} 的值 */ public C getCode() { return code; } /** * 给属性 {@code code} 赋值 * @param code {@code code} * @return {@link ResponseEntity} */ public ResponseEntity<C, T> setCode(C code) { this.code = code; return this; } /** * 获取属性 {@code message} 的值 * @return 获取属性 {@code message} 的值 */ public String getMessage() { return message; } /** * 给属性 {@code message} 赋值 * @param message {@code message} * @return {@link ResponseEntity} */ public ResponseEntity<C, T> setMessage(String message) { this.message = message; return this; } /** * 获取属性 {@code success} 的值 * @return 获取属性 {@code success} 的值 */ public Boolean getSuccess() { return success; } /** * 给属性 {@code success} 赋值 * @param success {@code success} * @return {@link ResponseEntity} */ public ResponseEntity<C, T> setSuccess(Boolean success) { this.success = success; return this; } /** * 获取属性 {@code data} 的值 * @return 获取属性 {@code data} 的值 */ public T getData() { return data; } /** * 给属性 {@code data} 赋值 * @param data {@code data} * @return {@link ResponseEntity} */ public ResponseEntity<C, T> setData(T data) { this.data = data; return this; } /** * 获取属性 {@code page} 的值 * @return 获取属性 {@code page} 的值 */ public ResponsePageEntity getPage() { return page; } /** * 给属性 {@code page} 赋值 * @param page {@code page} * @return {@link ResponseEntity} */ public ResponseEntity<C, T> setPage(ResponsePageEntity page) { this.page = page; return this; } /** * 重写 {@code equals} 方法 * @param o 待比对的对象 * @return 返回两个对象是否是相等,true:相等;false:不相等 */ @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResponseEntity<?, ?> that = (ResponseEntity<?, ?>) o; return Objects.equals(code, that.code) && Objects.equals(message, that.message) && Objects.equals(success, that.success) && Objects.equals(data, that.data) && Objects.equals(page, that.page); } /** * 重写 {@code hashCode} 方法 * @return 返回对象的 hash 值 */ @Override public int hashCode() { return Objects.hash(code, message, success, data, page); } /** * 重写 {@code toString} 方法 * @return 返回由对象各个属性的值拼接的字符串 */ @Override public String toString() { return "ResponseEntity{" + "code=" + code + ", message='" + message + '\'' + ", success=" + success + ", data=" + data + ", page=" + page + '}'; } }
PHP
UTF-8
1,536
2.53125
3
[ "MIT" ]
permissive
<?php require_once('Helpers/CreateTestResource.php'); /** * Class UpdateResourceTest */ class UpdateResourceTest extends TestCase { /** * @var */ protected $testingResource; /** * Test updating a resource * * @return void */ public function testUpdate() { $this->testingResource = new CreateTestResource(); $testModel = app('TestModel'); $testModel->update($this->testingResource->user->id, [ 'email' => 'kenyon.jh@gmail.com' ]); $testResource = $testModel->get($this->testingResource->user->id); $this->testingResource->userData['email'] = 'kenyon.jh@gmail.com'; $this->testingResource->testModelSearchableId = "testmodel:{$this->testingResource->user->id}:{$this->testingResource->user->id}_kenyon.jh@gmail.com_{$this->testingResource->convertedName}_{$this->testingResource->userData['password']}"; $this->assertEquals('kenyon.jh@gmail.com', $testResource->email); $this->assertArraySubset($this->testingResource->userData, Redis::hgetall($this->testingResource->testModelHashId)); $this->assertEquals($this->testingResource->user->id, Redis::get($this->testingResource->testModelSearchableId)); } /** * Delete the keys that were added to the database during the test */ public function tearDown() { parent::tearDown(); Redis::del($this->testingResource->testModelHashId); Redis::del($this->testingResource->testModelSearchableId); Redis::del("testmodels"); } }
Markdown
UTF-8
3,451
2.796875
3
[ "MIT" ]
permissive
--- layout: post title: 191119 TIL 뉴스스탠드개발 미션 permalink: /til/:year/:month/:day/:title/ categories: [1.5막, TIL (Today I Learned), 코드스쿼드, React.js] comments: true --- ### 뉴스스탠드개발 step1 - 비동기로 데이터를 가져오고, 가져온 데이터로 언론사 정보를 뿌리고, 선택된 언론사 정보를 뿌려주는 데까지 구현 ![image](https://user-images.githubusercontent.com/40848630/69159512-64270700-0b2b-11ea-9c93-66f663a367dc.png) - babel, webpack으로 환경 설정 해봄 [참고글](https://velog.io/@pop8682/%EB%B2%88%EC%97%AD-React-webpack-%EC%84%A4%EC%A0%95-%EC%B2%98%EC%9D%8C%EB%B6%80%ED%84%B0-%ED%95%B4%EB%B3%B4%EA%B8%B0) - PressContext API라는 것을 만들어서 사용해보려고 했는데, 뭔가... 효율적인지 잘 모르겠음. 넘 복잡.. 특히 context에서 초기 데이터를 가져와서 state를 설정해주는 포인트가 어려웠음 지금처럼 이렇게 덕지덕지 하는 것이 최선인지...!! - 그리고 지금 dispatch에서는 데이터를 가져오는 함수랑 이벤트 핸들링 하는 함수랑 섞여있어서 좀 정리가 안되는 느낌. context를 아예 나누는 게 좋을지?? - 화살표를 눌렀을 때 다음 언론사로 넘어가게 하기 위해 `nextId`를 context에 설정했는데 아직 어떻게 활용해야할지 고민중... #### context API ```js import React, { useState, useEffect, useReducer, createContext, useContext, useRef } from "react"; const pressReducer = (state, action) => { switch (action.type) { case "LOADING": return { ...state, loading: true, }; case "SUCCESS": return { ...state, loading: false, data: action.data, }; case "ERROR": return { ...state, error: action.error, }; case "CHANGE": return { ...state, showData: state.data[action.index], } default: throw new Error(`unhandled action type : ${action.type}`); } }; const PressStateContext = createContext(); const PressDispatchContext = createContext(); const PressNextIdContext = createContext(); export const PressProvider = ({ children }) => { const [state, dispatch] = useReducer(pressReducer, { loading: false, data: null, error: null, showData: null, }); const fetchData = () => { dispatch({ type: "LOADING" }); fetch("../newsData.json") .then(res => res.json()) .then(res => { dispatch({type: 'SUCCESS', data: res}) }) .catch(e => { dispatch({type: 'ERROR', data: e}) }) }; useEffect(() => { fetchData(); }, []); const nextId = useRef(1); const { loading, data: pressData, error, showData} = state; if (loading) return <div>로딩중</div> if (error) return <div> 에러 </div> if (!pressData) return null; return ( <PressStateContext.Provider value={state}> <PressDispatchContext.Provider value={dispatch}> <PressNextIdContext.Provider value={nextId}> {children} </PressNextIdContext.Provider> </PressDispatchContext.Provider> </PressStateContext.Provider> ); }; export const usePressState = () => useContext(PressStateContext); export const usePressDispatch = () => useContext(PressDispatchContext); export const usePressNextId = () => useContext(PressNextIdContext); ```
TypeScript
UTF-8
8,736
2.75
3
[]
no_license
type Maybe<T> = T | null; enum SurveyCreateQuestionTypeConstraint { question_type_pkey = 'question_type_pkey', question_type_question_type_key = 'question_type_question_type_key', } enum SurveyCreateQuestionTypeUpdateColumn { type = 'type', } enum SurveyCreateQuestionConstraint { question_pkey = 'question_pkey', question_question_id_key = 'question_question_id_key', } enum SurveyCreateQuestionUpdateColumn { choices = 'choices', id = 'id', questionTitle = 'questionTitle', surveyId = 'surveyId', type = 'type', } enum SurveyCreateQuestionTypeEnum { MULTIPLE_CHOICE = 'MULTIPLE_CHOICE', MULTIPLE_SELECT = 'MULTIPLE_SELECT', OPEN_TEXT = 'OPEN_TEXT', YES_OR_NO = 'YES_OR_NO', } enum SurveyCreateSurveyConstraint { survey_pkey = 'survey_pkey', survey_survey_id_key = 'survey_survey_id_key', } enum SurveyCreateSurveyUpdateColumn { coordinatorId = 'coordinatorId', id = 'id', title = 'title', } enum SurveyCreateUserConstraint { user_email_key = 'user_email_key', user_pkey = 'user_pkey', } enum SurveyCreateUserUpdateColumn { coordinator = 'coordinator', email = 'email', name = 'name', } enum SurveyCreateSurveyResponseConstraint { survey_response_pkey = 'survey_response_pkey', } enum SurveyCreateSurveyResponseUpdateColumn { awnser = 'awnser', id = 'id', responder = 'responder', } type InsertSingleUserOutput = { coordinator: boolean; email: string; name: string; }; type CreateSurveyOutput = { coordinatorId: string; title: string; }; type SurveyCreateOutput = { coordinatorId: string; id: number; title: string; }; type InsertSingleUserUserInsertInput = { coordinator?: Maybe<boolean>; email?: Maybe<string>; name?: Maybe<string>; }; type CreateSurveySurveyInsertInput = { coordinatorId?: Maybe<string>; id?: Maybe<number>; title?: Maybe<string>; }; type SurveyCreateSurveyInsertInput = { coordinatorId?: Maybe<string>; id?: Maybe<number>; questions?: Maybe<SurveyCreateQuestionArrRelInsertInput>; title?: Maybe<string>; user?: Maybe<SurveyCreateUserObjRelInsertInput>; }; type SurveyCreateQuestionArrRelInsertInput = { data: Array<SurveyCreateQuestionInsertInput>; on_conflict?: Maybe<SurveyCreateQuestionOnConflict>; }; type SurveyCreateQuestionInsertInput = { choices?: Maybe<string>; id?: Maybe<number>; questionTitle?: Maybe<string>; questionType?: Maybe<SurveyCreateQuestionTypeObjRelInsertInput>; responses?: Maybe<SurveyCreateSurveyResponseArrRelInsertInput>; survey?: Maybe<SurveyCreateSurveyObjRelInsertInput>; surveyId?: Maybe<number>; type?: Maybe<SurveyCreateQuestionTypeEnum>; }; type SurveyCreateQuestionTypeObjRelInsertInput = { data: SurveyCreateQuestionTypeInsertInput; on_conflict?: Maybe<SurveyCreateQuestionTypeOnConflict>; }; type SurveyCreateQuestionTypeInsertInput = { type?: Maybe<string>; }; type SurveyCreateQuestionTypeOnConflict = { constraint: SurveyCreateQuestionTypeConstraint; update_columns: Array<SurveyCreateQuestionTypeUpdateColumn>; where?: Maybe<SurveyCreateQuestionTypeBoolExp>; }; type SurveyCreateQuestionTypeBoolExp = { _and?: Maybe<Array<Maybe<SurveyCreateQuestionTypeBoolExp>>>; _not?: Maybe<SurveyCreateQuestionTypeBoolExp>; _or?: Maybe<Array<Maybe<SurveyCreateQuestionTypeBoolExp>>>; type?: Maybe<SurveyCreateStringComparisonExp>; }; type SurveyCreateStringComparisonExp = { _eq?: Maybe<string>; _gt?: Maybe<string>; _gte?: Maybe<string>; _ilike?: Maybe<string>; _in: Array<string>; _is_null?: Maybe<boolean>; _like?: Maybe<string>; _lt?: Maybe<string>; _lte?: Maybe<string>; _neq?: Maybe<string>; _nilike?: Maybe<string>; _nin: Array<string>; _nlike?: Maybe<string>; _nsimilar?: Maybe<string>; _similar?: Maybe<string>; }; type SurveyCreateSurveyResponseArrRelInsertInput = { data: Array<SurveyCreateSurveyResponseInsertInput>; on_conflict?: Maybe<SurveyCreateSurveyResponseOnConflict>; }; type SurveyCreateSurveyResponseInsertInput = { awnser?: Maybe<string>; id?: Maybe<number>; question?: Maybe<SurveyCreateQuestionObjRelInsertInput>; responder?: Maybe<string>; user?: Maybe<SurveyCreateUserObjRelInsertInput>; }; type SurveyCreateQuestionObjRelInsertInput = { data: SurveyCreateQuestionInsertInput; on_conflict?: Maybe<SurveyCreateQuestionOnConflict>; }; type SurveyCreateQuestionOnConflict = { constraint: SurveyCreateQuestionConstraint; update_columns: Array<SurveyCreateQuestionUpdateColumn>; where?: Maybe<SurveyCreateQuestionBoolExp>; }; type SurveyCreateQuestionBoolExp = { _and?: Maybe<Array<Maybe<SurveyCreateQuestionBoolExp>>>; _not?: Maybe<SurveyCreateQuestionBoolExp>; _or?: Maybe<Array<Maybe<SurveyCreateQuestionBoolExp>>>; choices?: Maybe<SurveyCreateStringComparisonExp>; id?: Maybe<SurveyCreateIntComparisonExp>; questionTitle?: Maybe<SurveyCreateStringComparisonExp>; questionType?: Maybe<SurveyCreateQuestionTypeBoolExp>; responses?: Maybe<SurveyCreateSurveyResponseBoolExp>; survey?: Maybe<SurveyCreateSurveyBoolExp>; surveyId?: Maybe<SurveyCreateIntComparisonExp>; type?: Maybe<SurveyCreateQuestionTypeEnumComparisonExp>; }; type SurveyCreateIntComparisonExp = { _eq?: Maybe<number>; _gt?: Maybe<number>; _gte?: Maybe<number>; _in: Array<number>; _is_null?: Maybe<boolean>; _lt?: Maybe<number>; _lte?: Maybe<number>; _neq?: Maybe<number>; _nin: Array<number>; }; type SurveyCreateSurveyResponseBoolExp = { _and?: Maybe<Array<Maybe<SurveyCreateSurveyResponseBoolExp>>>; _not?: Maybe<SurveyCreateSurveyResponseBoolExp>; _or?: Maybe<Array<Maybe<SurveyCreateSurveyResponseBoolExp>>>; awnser?: Maybe<SurveyCreateStringComparisonExp>; id?: Maybe<SurveyCreateIntComparisonExp>; question?: Maybe<SurveyCreateQuestionBoolExp>; responder?: Maybe<SurveyCreateStringComparisonExp>; user?: Maybe<SurveyCreateUserBoolExp>; }; type SurveyCreateUserBoolExp = { _and?: Maybe<Array<Maybe<SurveyCreateUserBoolExp>>>; _not?: Maybe<SurveyCreateUserBoolExp>; _or?: Maybe<Array<Maybe<SurveyCreateUserBoolExp>>>; coordinator?: Maybe<SurveyCreateBooleanComparisonExp>; email?: Maybe<SurveyCreateStringComparisonExp>; name?: Maybe<SurveyCreateStringComparisonExp>; survey_responses?: Maybe<SurveyCreateSurveyResponseBoolExp>; surveys?: Maybe<SurveyCreateSurveyBoolExp>; }; type SurveyCreateBooleanComparisonExp = { _eq?: Maybe<boolean>; _gt?: Maybe<boolean>; _gte?: Maybe<boolean>; _in: Array<boolean>; _is_null?: Maybe<boolean>; _lt?: Maybe<boolean>; _lte?: Maybe<boolean>; _neq?: Maybe<boolean>; _nin: Array<boolean>; }; type SurveyCreateSurveyBoolExp = { _and?: Maybe<Array<Maybe<SurveyCreateSurveyBoolExp>>>; _not?: Maybe<SurveyCreateSurveyBoolExp>; _or?: Maybe<Array<Maybe<SurveyCreateSurveyBoolExp>>>; coordinatorId?: Maybe<SurveyCreateStringComparisonExp>; id?: Maybe<SurveyCreateIntComparisonExp>; questions?: Maybe<SurveyCreateQuestionBoolExp>; title?: Maybe<SurveyCreateStringComparisonExp>; user?: Maybe<SurveyCreateUserBoolExp>; }; type SurveyCreateQuestionTypeEnumComparisonExp = { _eq?: Maybe<SurveyCreateQuestionTypeEnum>; _in: Array<SurveyCreateQuestionTypeEnum>; _is_null?: Maybe<boolean>; _neq?: Maybe<SurveyCreateQuestionTypeEnum>; _nin: Array<SurveyCreateQuestionTypeEnum>; }; type SurveyCreateUserObjRelInsertInput = { data: SurveyCreateUserInsertInput; on_conflict?: Maybe<SurveyCreateUserOnConflict>; }; type SurveyCreateUserInsertInput = { coordinator?: Maybe<boolean>; email?: Maybe<string>; name?: Maybe<string>; survey_responses?: Maybe<SurveyCreateSurveyResponseArrRelInsertInput>; surveys?: Maybe<SurveyCreateSurveyArrRelInsertInput>; }; type SurveyCreateSurveyArrRelInsertInput = { data: Array<SurveyCreateSurveyInsertInput>; on_conflict?: Maybe<SurveyCreateSurveyOnConflict>; }; type SurveyCreateSurveyOnConflict = { constraint: SurveyCreateSurveyConstraint; update_columns: Array<SurveyCreateSurveyUpdateColumn>; where?: Maybe<SurveyCreateSurveyBoolExp>; }; type SurveyCreateUserOnConflict = { constraint: SurveyCreateUserConstraint; update_columns: Array<SurveyCreateUserUpdateColumn>; where?: Maybe<SurveyCreateUserBoolExp>; }; type SurveyCreateSurveyResponseOnConflict = { constraint: SurveyCreateSurveyResponseConstraint; update_columns: Array<SurveyCreateSurveyResponseUpdateColumn>; where?: Maybe<SurveyCreateSurveyResponseBoolExp>; }; type SurveyCreateSurveyObjRelInsertInput = { data: SurveyCreateSurveyInsertInput; on_conflict?: Maybe<SurveyCreateSurveyOnConflict>; }; type Mutation = { surveyCreate?: Maybe<SurveyCreateOutput>; }; type surveyCreateArgs = { title: string; coordinatorId: string; questions: SurveyCreateQuestionArrRelInsertInput; };
Python
UTF-8
1,225
3
3
[]
no_license
#!/usr/bin/python class Solution: # @param {integer[]} nums # @return {integer} def findlow(self, A, low, high): key = A[low] while low < high: while A[high] >= key and low < high: high -= 1 A[low], A[high] = A[high], A[low] while A[low] <= key and low < high: low += 1 A[low], A[high] = A[high], A[low] return low def Sort(self, A, low, high): if low < high: P = self.findlow(A, low, high) self.Sort(A, low, P - 1) self.Sort(A, P + 1, high) return A def maximumGap(self, nums): if len(nums) < 2: return 0 nums = self.Sort(nums, 0, len(nums) - 1) gap = nums[1] - nums[0] for i in range(1, len(nums) - 1): if nums[i + 1] - nums[i] > gap: gap = nums[i + 1] - nums[i] return gap A = [15252,16764,27963,7817,26155,20757,3478,22602,20404,6739,16790,10588,16521,6644,20880,15632,27078,25463,20124,15728,30042,16604,17223,4388,23646,32683,23688,12439,30630,3895,7926,22101,32406,21540,31799,3768,26679,21799,23740] x = Solution() print(x.maximumGap(A))
Python
UTF-8
428
4.53125
5
[]
no_license
#append,insert, pop, del, letters = ["a", "b", "c","d","e","f"] letters.append("G") print(letters[1]) print(letters) # del letters[2] #dleete the value at the given index # print(letters) # letters.pop(2) # remove the elemet given index and retrun the removed value print(letters) print(letters[::2]) # ['a', 'c', 'e', 'G'] numbers = list(range(20)) print(numbers[::-1]) # print all the element in reverse order
C++
UTF-8
6,841
2.828125
3
[]
no_license
#include <gtest/gtest.h> #include <Config/ServerList.hpp> using namespace Config; struct ServerListTests : public ::testing::Test { class ServerListMock : public ServerList { public: ServerListMock() : ServerList() {} Server &add(Server toAdd) { return ServerList::add(toAdd); } Server const &match(Listen toMatch, std::string const &hostField) const { return ServerList::match(toMatch, hostField); } int matchByHost(std::vector<int> matches, std::string hostName) const { return ServerList::matchByHost(matches, hostName); } }; ServerListMock mock; }; TEST_F(ServerListTests, uniqueListen) { std::vector<Token> tokens{{"8080", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); mock.add(Server()); mock.add(Server()); EXPECT_EQ(1, mock.uniqueListens().size()); mock.add(Server()).set_listen(it); EXPECT_EQ(2, mock.uniqueListens().size()); } TEST_F(ServerListTests, uniqueListen2) { Server zero; Server one; Server two; Server three; Server four; std::vector<Token> tokens{{"{", 0}, {"listen", 0}, {"192.0.0.1", 0}, {";", 0}, {"}", 0}}; std::vector<Token> tokens2{{"{", 0}, {"listen", 0}, {"10.0.0.10:8080", 0}, {";", 0}, {"}", 0}}; std::vector<Token> tokens3{{"{", 0}, {"listen", 0}, {"8080", 0}, {";", 0}, {"}", 0}}; std::vector<Token> tokens4{{"{", 0}, {"listen", 0}, {"6.6.6.6:666", 0}, {";", 0}, {"}", 0}}; std::vector<Token>::iterator it = tokens.begin(); one.server(it); it = tokens2.begin(); two.server(it); it = tokens3.begin(); three.server(it); it = tokens4.begin(); four.server(it); mock.add(zero); mock.add(one); mock.add(two); mock.add(three); mock.add(four); EXPECT_EQ(3, mock.uniqueListens().size()); std::vector<std::pair<in_addr_t, u_int16_t> > res{{inet_addr("0.0.0.0"), htons(80)}, {inet_addr("0.0.0.0"), htons(8080)}, {inet_addr("6.6.6.6"), htons(666)}}; EXPECT_EQ(res, mock.uniqueListens()); } TEST_F(ServerListTests, matching) { Server one; Server two; std::vector<Token> tokens{{"{", 0}, {"server_name", 0}, {"localhost", 0}, {";", 0}, {"listen", 0}, {"8080", 0}, {";", 0}, {"}", 0}}; std::vector<Token> tokens2{{"{", 0}, {"server_name", 0}, {"localhost", 0}, {";", 0}, {"listen", 0}, {"80", 0}, {";", 0}, {"}", 0}}; std::vector<Token>::iterator it = tokens.begin(); std::vector<Token>::iterator it2 = tokens2.begin(); Server three; three.server(it); two.server(it2); mock.add(one); mock.add(two); mock.add(three); EXPECT_FALSE(three.listen() == mock.match(Listen(), "").listen()); EXPECT_EQ(one.listen(), mock.match(Listen(), "").listen()); EXPECT_EQ(three.listen(), mock.match(Listen("0.0.0.0", 8080), "").listen()); EXPECT_EQ(1, mock.matchByHost({0, 1}, "localhost")); } TEST_F(ServerListTests, matchByHost) { Server zero; Server one; Server two; Server three; std::vector<Token> tokens{{"{", 0}, {"server_name", 0}, {"localhost", 0}, {";", 0}, {"}", 0}}; std::vector<Token> tokens2{{"{", 0}, {"server_name", 0}, {"localhost*", 0}, {";", 0}, {"}", 0}}; std::vector<Token> tokens3{{"{", 0}, {"server_name", 0}, {"*localhost", 0}, {";", 0}, {"}", 0}}; std::vector<Token>::iterator it = tokens.begin(); one.server(it); it = tokens2.begin(); two.server(it); it = tokens3.begin(); three.server(it); mock.add(zero); mock.add(one); mock.add(two); mock.add(three); EXPECT_EQ(2, mock.matchByHost({2, 3}, "none")); EXPECT_EQ(3, mock.matchByHost({2, 3}, "www.localhost")); EXPECT_EQ(2, mock.matchByHost({2, 3}, "localhost.com")); EXPECT_EQ(3, mock.matchByHost({2, 3}, "localhost")); EXPECT_EQ(0, mock.matchByHost({0, 2, 3}, "")); EXPECT_EQ(1, mock.matchByHost({0, 1, 2, 3}, "localhost")); EXPECT_EQ(0, mock.matchByHost({0, 1, 2, 3}, "local")); EXPECT_EQ(2, mock.matchByHost({0, 1, 2, 3}, "localhost.com")); } TEST_F(ServerListTests, workers0) { std::vector<Token> tokens{{"workers", 0}, {"0", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); set_workers(++it); EXPECT_EQ(1, Server::WORKER_PROCESSES); EXPECT_EQ(";", it->value_); } TEST_F(ServerListTests, workers2) { std::vector<Token> tokens{{"workers", 0}, {"2", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); set_workers(++it); EXPECT_EQ(2, Server::WORKER_PROCESSES); EXPECT_EQ(";", it->value_); } TEST_F(ServerListTests, workersTooSmall) { std::vector<Token> tokens{{"workers", 0}, {"-1", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); EXPECT_ANY_THROW(set_workers(++it)); } TEST_F(ServerListTests, workersNonNumeric) { std::vector<Token> tokens{{"workers", 0}, {"hej", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); EXPECT_ANY_THROW(set_workers(++it)); } TEST_F(ServerListTests, workersDoubleValue) { std::vector<Token> tokens{{"workers", 0}, {"2", 0}, {"10", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); EXPECT_ANY_THROW(set_workers(++it)); } TEST_F(ServerListTests, workersNoValue) { std::vector<Token> tokens{{"workers", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); EXPECT_ANY_THROW(set_workers(++it)); } TEST_F(ServerListTests, plugins) { Server::PLUGINS["utf-8"] = false; Server::PLUGINS["gzip"] = false; std::vector<Token> tokens{{"utf-8", 0}, {"on", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); set_plugins(it); EXPECT_TRUE(Server::PLUGINS["utf-8"]); EXPECT_FALSE(Server::PLUGINS["gzip"]); } TEST_F(ServerListTests, pluginsOff) { Server::PLUGINS["utf-8"] = false; Server::PLUGINS["gzip"] = false; std::vector<Token> tokens{{"utf-8", 0}, {"off", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); set_plugins(it); EXPECT_FALSE(Server::PLUGINS["utf-8"]); EXPECT_FALSE(Server::PLUGINS["gzip"]); } TEST_F(ServerListTests, pluginsNoValue) { Server::PLUGINS["utf-8"] = false; Server::PLUGINS["gzip"] = false; std::vector<Token> tokens{{"utf-8", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); EXPECT_ANY_THROW(set_plugins(it)); } TEST_F(ServerListTests, pluginsDoubleValue) { Server::PLUGINS["utf-8"] = false; Server::PLUGINS["gzip"] = false; std::vector<Token> tokens{{"utf-8", 0}, {"off", 0}, {"on", 0}, {";", 0}}; std::vector<Token>::iterator it = tokens.begin(); EXPECT_ANY_THROW(set_plugins(it)); }
C++
UTF-8
388
2.734375
3
[]
no_license
#include <stdio.h> #include <math.h> const double PI = acos(-1); int main() { int a, b, c, d, e; long long p, q; double ang, t; while (scanf("%d%d%d%d%d", &a, &b, &c, &d, &e) == 5) { if (a == 0 && b == 0 && c == 0 && d == 0 && e == 0) { break; } p = a*d; q = b*e; ang = atan2(q, p); t = sqrt(p*p+q*q) / c; printf("%.2lf %.2lf\n", ang/PI*180, t); } return 0; }
Markdown
UTF-8
401
2.609375
3
[ "MIT" ]
permissive
## Best practices for Vagrant * If you want to apply a slightly different configuration to many multi-machine machines, you can use a loop to do this. * Overwrite host locale in ssh session Usually, host locale environment variables are passed to guest. It may cause failures if the guest software do not support host locale. * Just read the awesome documentation at https://www.vagrantup.com/docs
C#
UTF-8
1,771
2.5625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace LYH.Infrastructure.Data.Commons.Exceptions { /// <summary> /// 数据访问层异常类,用于封装业务逻辑层引发的异常,以供 UI 层抓取 /// </summary> [Serializable] public class BusinessException : Exception { /// <summary> /// 实体化一个 LYH.Infrastructure.Data.Commons.Exceptions 类的新实例 /// </summary> public BusinessException() { } /// <summary> /// 使用异常消息实例化一个 LYH.Infrastructure.Data.Commons.Exceptions 类的新实例 /// </summary> /// <param name="message">异常消息</param> public BusinessException(string message) : base(message) { } /// <summary> /// 使用异常消息与一个内部异常实例化一个 LYH.Infrastructure.Data.Commons.Exceptions 类的新实例 /// </summary> /// <param name="message">异常消息</param> /// <param name="inner">用于封装在BllException内部的异常实例</param> public BusinessException(string message, Exception inner) : base(message, inner) { } /// <summary> /// 使用可序列化数据实例化一个 LYH.Infrastructure.Data.Commons.Exceptions 类的新实例 /// </summary> /// <param name="info">保存序列化对象数据的对象。</param> /// <param name="context">有关源或目标的上下文信息。</param> protected BusinessException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }