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
Swift
UTF-8
310
2.703125
3
[]
no_license
// hurdleRace func hurdleRace(k: Int, height: [Int]) -> Int { let highestJump = height.max() var portionNeeded = 0 if let highestJump = highestJump { let gap = k - highestJump if gap >= 0 { portionNeeded = 0 } else { portionNeeded = abs(gap) } } return portionNeeded }
C++
UTF-8
852
2.8125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; vector<vector<int> > diagonal(vector<vector<int> > &A) { if(A.size()==0) { return A; } int n=A.size(); int s = 2*A.size()-1; vector<vector<int> >ans(s); for(int j=0;j<=n-1;j++) { int idx=j; for(int i=0;i<=j;i++) { ans[j].push_back(A[i][idx]); idx--; } } if(A.size()==1) return ans; int i=1; int idx2=A.size(); int x = n-1; while(x--) { int j=n-1; for(int idx=i;idx<=n-1;idx++) { ans[idx2].push_back(A[idx][j]); j--; } idx2++; i++; } return ans; } int main() { int n; cin>>n; vector<vector<int> >v(n,vector<int>(n)); for(int i=0;i<n;i++){ for(int j=0;j<n;j++) { cin>>v[i][j]; } } vector<vector<int> >ans = diagonal(v); return 0; }
Java
UTF-8
120
2
2
[]
no_license
package prototype; /** * 抽象原型类 * @author ShenSha */ public interface Prototype { Prototype clone(); }
C++
UTF-8
1,852
3.671875
4
[]
no_license
#ifndef AGENDA_H #define AGENDA_H #include "data.h" #include "contacto.h" #include <vector> #include <memory> #include <functional> template<typename T> class Agenda { private: std::vector<std::shared_ptr<Data<T>>>datos; public: Agenda(); void inserta(std::shared_ptr<Data<T> > a); void elimina(std::string const& nombre); std::shared_ptr<Data<T> > find(const std::function<bool(std::shared_ptr<Data<T> >)> &op)const; std::vector<std::shared_ptr<Data<T> > > getDatos() const; }; template<typename T> Agenda<T>::Agenda() { } template<typename T> void Agenda<T>::inserta(std::shared_ptr<Data<T> > a) { //el nombre al nos ser unico no hace falta comprobar que no se repite datos.push_back(a); } template<typename T> void Agenda<T>::elimina(const std::string &nombre) { for(unsigned int long i{0}; i < datos.size(); i++){ if(datos.at(i)->getNombre() == nombre){ datos.erase(datos.begin()+i); return; } } throw std::string{"No existe el contacto que quieres borrar"}; } template<typename T> std::shared_ptr<Data<T> > Agenda<T>::find(std::function<bool (std::shared_ptr<Data<T> >)> const & op) const { for(auto n:datos){ if(op(n))return n; } return nullptr; } template<typename T> std::vector<std::shared_ptr<Data<T> > > Agenda<T>::getDatos() const { return datos; } template<typename T> std::ostream & operator<<(std::ostream & os, Agenda<T> const & l){ for(auto n: l.getDatos()){ os<<*n<<"\n"; } os<<"\n"; return os; } template<typename T> Agenda<T> operator+(Agenda<T> const& s, Agenda<T> const & l){ Agenda<T> result = s; for(auto n: l.getDatos()){ result.inserta(n); } return result; } #endif // AGENDA_H
Java
GB18030
1,814
2.53125
3
[]
no_license
package cn.newer.adapter; import cn.newer.R; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView.FindListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class MyAdapter extends BaseAdapter { private Context mContext ; private int[] mImage ; private String[] mData ; private LayoutInflater mlayoutinflater; public MyAdapter(Context context , int[] image, String[] Data) { // TODO Auto-generated constructor stub mContext = context ; mImage = image ; mData = Data ; mlayoutinflater = LayoutInflater.from(mContext); } @Override public int getCount() { // TODO Auto-generated method stub return mData.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return mData[position]; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View view = convertView ; HolderView holder ; if(view ==null){ view = mlayoutinflater.inflate(R.layout.drawer_list_item,null) ; // xmlѰҺͽʱ holder = new HolderView() ; holder.iv =(ImageView) view.findViewById(R.id.iv_drawer) ; holder.tv = (TextView)view.findViewById(R.id.drawer_item_name) ; view.setTag(holder); }else{ holder = (HolderView) view.getTag() ; } holder.iv.setImageResource(mImage[position]); holder.tv.setText(mData[position]); return view; } private class HolderView{ ImageView iv ; TextView tv ; } }
C++
UTF-8
1,017
3.796875
4
[]
no_license
//O(N^2) #include<bits/stdc++.h> using namespace std; //A blue print of what tree will contain struct node{ //a variable to store data int data; //left and right named user defined pointers to point to it's child nodes. node *left, *right; //user defined function to create a node. node(int data) { this->data = data; left = right = NULL; } }; bool isBalanced(node *root, int &height) { int lh = 0; int rh = 0; int lb=0, rb=0; if(root==NULL) { height = 0; return 1; } lb = isBalanced(root->left, lh); rb = isBalanced(root->right, rh); height = (lh>rh?lh:rh)+1; if(abs(lh-rh)>=2) { return 0; } else { return lb && rb; } } int main() { node *root = new node(1); root->left = new node(2); root->right = new node(3); root->left->left = new node(4); root->left->right = new node(5); root->left->left->left = new node(8); int height = 0; int ans = isBalanced(root, height); cout<<ans<<endl; }
C
UTF-8
578
2.9375
3
[]
no_license
#include <stdio.h> #include <string.h> #include <time.h> #include <sys/time.h> int main() { FILE *fp_read, *fp_write; fp_read = fopen("./test.txt", "r"); fp_write = fopen("./test_getc.txt", "w+"); if (fp_read == NULL) { printf("Cannot open file test.txt\n"); } if (fp_write == NULL) { printf("Cannot open file test_fread_fwrite.txt\n"); } char buf; buf = fgetc(fp_read); while (buf != EOF) { fputc(buf, fp_write); buf = fgetc(fp_read); } fclose(fp_read); fclose(fp_write); return 0; }
C++
UTF-8
1,271
3.34375
3
[]
no_license
#include<iostream> int gGT(int, int); int kuerzen(int, int, int, int); int main(){ int n1, n2, z1, z2, n, z, x, i = 0; std::cout << "Bitte geben Sie den Zaehler der ersten Zahl an: "; std::cin >> z1; std::cout << "Bitte geben Sie den Nenner der ersten Zahl an: "; std::cin >> n1; std::cout << "Bitte geben Sie den Zaehler der zweiten Zahl an: "; std::cin >> z2; std::cout << "Bitte geben Sie den Nenner der zweiten Zahl an: "; std::cin >> n2; n = n1 * n2; if(n == 0) return main(); z1 = z1 * n2; z2 = z2 * n1; z = z1 + z2; std::cout << "Das Zwischen-Ergebnis lautet: " << z << " / " << n << "." << std::endl << "Errechne ggT ..." << std::endl; if(n > z){ x = gGT(n, z); }else{ x = gGT(z, n); } std::cout << "Somit lautet also der ggT aus den oben stehenden Zahlen: " << x << std::endl << "Kuerze ..." << std::endl; n = kuerzen(x, n, z, i); i++; z = kuerzen(x, n, z, i); std::cout << "Das End-Ergebnis lautet: " << z << " / " << n << "." << std::endl; system("Pause"); return 0; } int kuerzen(int x, int n, int z, int i){ if(i == 0){ n = n / x; return n; }else{ z = z / x; return z; } } int gGT(int n, int z){ if(n == 0){ return z; }else{ return gGT(z % n, n); } }
Python
UTF-8
723
3.765625
4
[]
no_license
# Příklad na použití fronty - rozpočítávadlo. # # Děti v kruhu, rozpočítávadlo má $m$ slabik, začíná se prvním. # Na koho padne poslední slabika, vypadává. # Hraje se, dokud nevypadne poslední. # Děti reprezentujeme pomocí fronty, budeme přesouvat ze začátku na konec. # # Jan Kybic, 2016 from knuthqueue import Queue def rozpocitej(jmena,m): q=Queue() for j in jmena: # ulož jména do fronty q.enqueue(j) while q.size()>1: for i in range(m-1): q.enqueue(q.dequeue()) print("Vypadl(a): ",q.dequeue()) return q.dequeue() # vrať vítěze if __name__=="__main__": v=rozpocitej(["Adam","Bára","Cyril","David","Emma","Franta","Gábina"],3) print("Vyhrál(a): ",v)
Java
UTF-8
1,773
3.515625
4
[]
no_license
package hiho521; import java.util.Scanner; /** * Created by thd on 2017/5/21. * 题目4 : 逃离迷宫3 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi被坏女巫抓进一座由无限多个格子组成的矩阵迷宫。 小Hi一开始处于迷宫中央(0, 0)的位置。他发现每个格子都印有一个大写字母。并且从(0, 0)开始,按照A-Z的顺序,沿着顺时针螺旋循环排列,如下图所示(向右是X正方向,向上是Y正方向): 0 ... CXYZABCDE BWZABCDEF AVYJKLMFG ZUXIBCNGH 0 ...YTWHADOHI... XSVGFEPIJ WRUTSRQJK VQPONMLKL UTSRQPONM ... 小Hi发现每次他可以移动到上下左右相邻的格子中,但是代价是心智受到1点伤害。此外他还可以移动到印有相同字母的格子中,无论两个格子相距多远,代价也是心智受到1点伤害。 给定迷宫出口的位置(X, Y),小Hi想知道离开迷宫最少受到多少点伤害。 输入 第一行包含一个整数N,表示测试数据的组数。(1 <= N <= 12) 以下N行每行包含两个整数X和Y,代表出口位置。 对于30%的数据,-100 <= X, Y <= 100 对于100%的数据, -1000000 <= X, Y <= 1000000 输出 对于每组数据输出一个整数表示答案。 每组数据单独一行。 样例输入 3 1 2 -4 2 4 1 样例输出 3 1 2 * */ public class Main4 { public static void main(String[] args){ Scanner sc = new Scanner(System.in); while(sc.hasNext()) { int n = sc.nextInt(); int[] x = new int[n]; int[] y = new int[n]; int np = 0; for (int i = 0; i < n; i++) { x[i] = sc.nextInt(); y[i] = sc.nextInt(); } } } }
TypeScript
UTF-8
700
3.0625
3
[]
no_license
import {Pipe,PipeTransform} from '@angular/core'; @Pipe({name: 'formatoHora'}) export class FormatoHoraPipe implements PipeTransform{ //coge el parametro pasado y lo pone en formato hora (requiere 4 dígitos) //dato | calculadora: otroDato //param1 param2 transform(value:any){ var cadena = value.toString(); var resultado; if(cadena.charAt(0) != '0' && cadena.charAt(0) != '1' && cadena.charAt(0) != '2') { resultado = '0'+cadena.charAt(0)+":"+cadena.charAt(1)+cadena.charAt(2); } else { resultado = cadena.charAt(0)+cadena.charAt(1)+":"+cadena.charAt(2)+cadena.charAt(3); } return resultado; } }
C#
UTF-8
2,698
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; internal static class ExtensionMethods { /// <summary> /// /// </summary> /// <exception cref="SocketException"/> //[DebuggerStepThrough] public static Exception ToException(this SocketError socketError) { return new SocketException((int)socketError); } public static ValueTask<SocketReceiveResult> ReceiveBlockAsync(this ManagedTcpSocket managedTcp, Memory<byte> buffer, CancellationToken cancellationToken = default) { int count = buffer.Length; while (buffer.Length > 0) { ValueTask<SocketReceiveResult> t = managedTcp.ReceiveAsync(buffer, cancellationToken); if (t.IsCompletedSuccessfully) { SocketReceiveResult result = t.Result; if (result.BytesReceived > 0 && result.ErrorCode == SocketError.Success) { // Уменьшить буфер на столько, сколько приняли. buffer = buffer.Slice(result.BytesReceived); } else return new ValueTask<SocketReceiveResult>(result); } else { return WaitForReceiveBlockAsync(t, count, managedTcp, buffer, cancellationToken); } } // Всё выполнено синхронно. return new ValueTask<SocketReceiveResult>(new SocketReceiveResult(count, SocketError.Success)); static async ValueTask<SocketReceiveResult> WaitForReceiveBlockAsync(ValueTask<SocketReceiveResult> t, int count, ManagedTcpSocket managedTcp, Memory<byte> buffer, CancellationToken cancellationToken) { SocketReceiveResult result = await t.ConfigureAwait(false); if (result.BytesReceived > 0 && result.ErrorCode == SocketError.Success) { // Уменьшить буфер на сколько приняли. buffer = buffer.Slice(result.BytesReceived); if (buffer.Length == 0) { return new SocketReceiveResult(count, SocketError.Success); } else // Прочитали всё что необходимо. { return await ReceiveBlockAsync(managedTcp, buffer, cancellationToken).ConfigureAwait(false); } } else return result; } } }
Java
UTF-8
1,365
2.609375
3
[]
no_license
package com.kaicom.work; import java.io.IOException; import java.util.concurrent.TimeoutException; import com.kaicom.utils.ConnectionUtils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.DefaultConsumer; public class Recv2 { private static final String QUEUE_NAME = "test-work-queue"; public static void main(String[] args) throws IOException, TimeoutException { //获取连接 Connection connection = ConnectionUtils.getConnection(); //获取通道 Channel channel = connection.createChannel(); //声名队列 channel.queueDeclare(QUEUE_NAME, false, false, false, null); //定义一个消费者 DefaultConsumer defaultConsumer = new DefaultConsumer(channel){ //消息到达触发这个方法 @Override public void handleDelivery(String consumerTag, com.rabbitmq.client.Envelope envelope, com.rabbitmq.client.AMQP.BasicProperties properties, byte[] body) throws IOException { String msg = new String(body,"utf-8"); System.out.println("消费者2 接受的消息"+msg); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("done"); } } }; boolean autoAck = true ; channel.basicConsume(QUEUE_NAME, autoAck, defaultConsumer); } }
C
UTF-8
448
3.3125
3
[]
no_license
void bubblesort(int arraysize, double * unsorted_array, int * flag_array) { for (int x = 0; x < arraysize; x++) { for (int y = 0; y < arraysize - 1; y++) { if (unsorted_array[y] > unsorted_array[y + 1]) { int temp = unsorted_array[y + 1]; unsorted_array[y + 1] = unsorted_array[y]; unsorted_array[y] = temp; int temp2 = flag_array[y + 1]; flag_array[y + 1] = flag_array[y]; flag_array[y] = temp2; } } } }
C#
UTF-8
1,904
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using Belatrix.MoneyExchange.Data; using Moq; namespace Belatrix.MoneyExchange.Tests { public static class UnifOfWorkExtensions { public static Mock<IUnitOfWork> SetupDbSet<TEntity>( this Mock<IUnitOfWork> self, IEnumerable<TEntity> data) where TEntity : class { self.SetupDbSetInternal(new DbSetMock<TEntity>(data)); return self; } public static Mock<IUnitOfWork> SetupDbSet<TEntity>( this Mock<IUnitOfWork> self, IEnumerable<TEntity> data, Func<TEntity, object[], bool> find) where TEntity : class { self.SetupDbSetInternal(new DbSetMock<TEntity>(data, find)); return self; } public static Mock<IUnitOfWork> SetupEmptyDbSet<TEntity>(this Mock<IUnitOfWork> self) where TEntity : class => self.SetupDbSet(Enumerable.Empty<TEntity>()); private static void SetupDbSetInternal<TEntity>( this Mock<IUnitOfWork> self, DbSetMock<TEntity> set) where TEntity : class { self.Setup(c => c.Set<TEntity>()).Returns(set); self.Setup(x => x.FindAsync<TEntity>(It.IsAny<object[]>())).Returns<object[]>(keys => set.FindAsync(keys)); self.Setup(x => x.Add(It.IsAny<TEntity>())).Returns<TEntity>(x => set.Add(x)); self.Setup(x => x.AddRange(It.IsAny<IEnumerable<TEntity>>())).Returns<IEnumerable<TEntity>>(x => set.AddRange(x)); self.Setup(x => x.Remove(It.IsAny<TEntity>())).Returns<TEntity>(x => set.Remove(x)); self.Setup(x => x.RemoveRange(It.IsAny<IEnumerable<TEntity>>())).Returns<IEnumerable<TEntity>>(x => set.RemoveRange(x)); } } }
Java
UTF-8
939
2.171875
2
[]
no_license
package wangjie.asynctask; import wangjie.http.HttpDownloader; import wangjie.infotypes.BasicPageType; import wangjie.parser.HotBookParser; import wangjie.parser.PageParser; import wangjie.testactbar.HotBookFragment; import android.os.AsyncTask; public class FetchHotBookTask extends AsyncTask<String, Void, BasicPageType>{ private HotBookFragment hbf; public FetchHotBookTask(HotBookFragment hb) { hbf = hb; } @Override protected BasicPageType doInBackground(String... params) { HttpDownloader hd = new HttpDownloader(); String content = hd.getPage(params[0]); BasicPageType ret = null; if (content != null && !content.isEmpty()) { PageParser parser = new HotBookParser(content); ret = parser.parseContent(); } return ret; } @Override protected void onPostExecute(BasicPageType result) { // TODO Auto-generated method stub super.onPostExecute(result); hbf.setRankList(result); } }
Java
UTF-8
1,485
2.40625
2
[ "Apache-2.0" ]
permissive
package cn.rdtimes.imp.mq.rocket; import cn.rdtimes.impl.mq.rocket.BRocketMessage; import cn.rdtimes.mq.BMQException; import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.common.message.MessageExt; import java.util.List; /** * @description: * @author: BZ * @create: 2020/2/13 */ public class BMessage extends BRocketMessage { private String content; private Message message; @Override public Message getMessage(String topic, String tag) throws BMQException { try { Message msg = new Message(topic /* Topic */, tag /* Tag */, content.getBytes() /* Message body */); return msg; } catch (Exception e) { throw new BMQException(e); } } private List<MessageExt> msgList; @Override public void setMessage(List<MessageExt> msgList) { this.msgList = msgList; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String toString() { if (msgList == null) return ""; StringBuilder sb = new StringBuilder(128); sb.append("count:" + msgList.size()); sb.append("\r\n"); for (MessageExt msg : msgList) { sb.append("id:" + msg.getMsgId() + ",body:" + new String(msg.getBody())); sb.append("\r\n"); } return sb.toString(); } }
Java
UTF-8
371
1.632813
2
[]
no_license
package com.lgz.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Blogger { private int id; private String userName; private String password; private String profile; private String nickName; private String sign; private String imageName; }
Java
UTF-8
2,482
1.882813
2
[ "Apache-2.0" ]
permissive
package com.centanet.hk.aplus.bean.login; /** * Created by yangzm4 on 2018/3/13. */ public class DomainUser { private String CityCode; private String StaffNo; private String CnName; private String DeptName; private String DomainAccount; private String Mobile; private String Title; private String Email; private String AgentUrl; private String CompanyName; public void setCityCode(String cityCode) { CityCode = cityCode; } public void setStaffNo(String staffNo) { StaffNo = staffNo; } public void setCnName(String cnName) { CnName = cnName; } public void setDeptName(String deptName) { DeptName = deptName; } public void setDomainAccount(String domainAccount) { DomainAccount = domainAccount; } public void setMobile(String mobile) { Mobile = mobile; } public void setTitle(String title) { Title = title; } public void setEmail(String email) { Email = email; } public void setAgentUrl(String agentUrl) { AgentUrl = agentUrl; } public void setCompanyName(String companyName) { CompanyName = companyName; } public String getCityCode() { return CityCode; } public String getStaffNo() { return StaffNo; } public String getCnName() { return CnName; } public String getDeptName() { return DeptName; } public String getDomainAccount() { return DomainAccount; } public String getMobile() { return Mobile; } public String getTitle() { return Title; } public String getEmail() { return Email; } public String getAgentUrl() { return AgentUrl; } public String getCompanyName() { return CompanyName; } @Override public String toString() { return "DomainUser{" + "CityCode='" + CityCode + '\'' + ", StaffNo='" + StaffNo + '\'' + ", CnName='" + CnName + '\'' + ", DeptName='" + DeptName + '\'' + ", DomainAccount='" + DomainAccount + '\'' + ", Mobile='" + Mobile + '\'' + ", Title='" + Title + '\'' + ", Email='" + Email + '\'' + ", AgentUrl='" + AgentUrl + '\'' + ", CompanyName='" + CompanyName + '\'' + '}'; } }
Java
UTF-8
1,531
2.484375
2
[]
no_license
package com.zodiackillerciphers.constraints; import java.util.List; import com.zodiackillerciphers.ciphers.Ciphers; import com.zodiackillerciphers.corpus.SearchConstraints; import com.zodiackillerciphers.io.FileUtil; public class NGramsTest { public static void test1() { String cipher = Ciphers.cipher[1].cipher; List<String> list = FileUtil.loadFrom("docs/test3.txt"); for (String line : list) { String[] split = line.split(","); int pos = Integer.valueOf(split[1].substring(1)); String sub = split[2].substring(1); String plain = split[3].substring(1); Info info1 = new Info(sub, pos); info1.plaintext = plain; float score1 = SearchConstraints.score(info1, cipher, false, false); float score2 = SearchConstraints.score(info1, cipher, false, true); float score3 = SearchConstraints.score(info1, cipher, true, false); float score4 = SearchConstraints.score(info1, cipher, true, true); //System.out.println(score1 + ", " + score2 + ", " + score3 + ", " + score4 + ", " + info1); } } public static void test2() { String cipher = Ciphers.cipher[1].cipher; List<String> list = FileUtil.loadFrom("docs/constraint-search-408-new-3-results.txt"); for (String line : list) { if (!line.contains("- Info:")) continue; String[] split = line.split(","); float prob = Float.valueOf(split[5]); float score = Float.valueOf(split[8]); float val = score/prob; System.out.println(val + ", " + line); } } public static void main(String[] args) { test2(); } }
Java
UTF-8
144
1.828125
2
[]
no_license
package com.jianghu.winter.query.cache; /** * @author daniel.hu */ @FunctionalInterface public interface CacheInvoker<T> { T invoke(); }
Ruby
UTF-8
2,878
4.375
4
[]
no_license
# below, we are creating and defining a method - cheese_and_crackers def cheese_and_crackers(cheese_count, boxes_of_crackers) # calling on our cheese_and_crackers method, pulling a cheese_count, and printing the following string puts "You have #{cheese_count} cheeses!" # calling on our cheese_and_crackers method, pulling a boxes_of_crackers number, and printing the following string puts "You have #{boxes_of_crackers} boxes of crackers!" # printing the following string puts "Man that's enough for a party!" # printing the following string puts "Get a blanket.\n" end # calling on our cheese_and_crackers method and printing the following string. This time, we are assigning our own integers to cheese_count and boxes_of_crackers puts "We can just give the function numbers directly:" cheese_and_crackers(20, 30) # we are printing the following string, and then assigning intgers to amount_of_cheese and amount_of_crackers # question: are we in any way calling on our cheese_and_crackers method here? Isn't this similar to just creating and assigning new vaeriables? puts "OR, we can use variables from our script:" amount_of_cheese = 10 amount_of_crackers = 50 cheese_and_crackers(amount_of_cheese, amount_of_crackers) # calling on our cheese_and_crackers method, and printing the following string. To obtain a cheese_count, as well as a boxes_of_crackers count, we are asking Ruby to do the math. The first part of the equation in the parentheses refers to the cheese_count, while the second part refers to boxes_of_crackers puts "We can even do math inside too:" cheese_and_crackers(10 + 20, 5 + 6) # calling on our cheese_and_crackers method. This time, we are pulling data from above, where we defined amount_of_cheese and amount_of_crackers separately. We are asking Ruby to pull those values, and also do some math. Add 100 to our amount_of_cheese integer, and then add 1000 to our amount_of_crackers integer. Both will result in new intger values puts "And we can combine the two, variables and math:" cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) def starbursts_and_jolly_ranchers(starbursts_count, jolly_ranchers_count) puts "You have #{starbursts_count} starbursts! Lucky!" puts "You have #{jolly_ranchers_count} jolly ranchers! So lucky!" puts "That's enough candy for all of us." puts "Will you share your candy with everyone?" end starbursts_and_jolly_ranchers(12, 12) amount_of_starbursts = 120 amount_of_jolly_ranchers = 80 starbursts_and_jolly_ranchers(amount_of_starbursts, amount_of_jolly_ranchers) starbursts_and_jolly_ranchers(12 + 120, 12 + 80) starbursts = 40 jolly_ranchers = 40 starbursts_and_jolly_ranchers(starbursts, jolly_ranchers) starbursts_and_jolly_ranchers(500 / 10, 1200 / 60) starbursts_and_jolly_ranchers(2 * 2, 200 * 2) Not finished yet. Add in more ways to run this function
Markdown
UTF-8
905
3.234375
3
[ "MIT" ]
permissive
# is-reg > Regular expressions usually used > 常用的正则特殊需求表达式判断 ## Usage ``` bash npm i is-reg ``` ``` js const { isEmail } = require('is-reg') isEmail('csheng.dude@gmail.com') //true isEmail('hello.com') // false ``` ## API ### `isEmail(arg: string): boolean` 判断一个给定字符串是否是一个email格式的字符串 ### `isPhone(arg: string): boolean` 判断一个给定字符串是否是个电话号码 eg: ```js isPhone('17809247855') // true ``` ### `isPassword(arg: string): boolean` 判断一个给定字符串是否是个密码, 注:(该函数判断以字母开头,长度在6~18之间,只能包含字母、数字和下划线的密码) ### `isStrongPassword(arg: string): boolean` 判断一个给定字符串是否是个强密码, 注:(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在 8-10 之间)
Python
UTF-8
1,251
3.203125
3
[]
no_license
import serial from colour import Color from time import sleep import atexit class seriaLED: def __init__(self, num_leds, wait=True): self.ser = serial.Serial('COM4', 57600, timeout = 1) self.leds = [0] * (num_leds * 3) self.num_leds = num_leds atexit.register(self.close) if wait: sleep(2) # enforced wait for everything to start working. # if there isn't a small wait then some commands can get lost. # can optionally be skipped, which may be appropriate for some use cases. def write(self): self.ser.write(bytes([65] + self.leds)) sleep(0.005) def put(self, color, pixel, write=True): self.leds[pixel * 3] = int(color.red * 255) self.leds[pixel * 3 + 1] = int(color.green * 255) self.leds[pixel * 3 + 2] = int(color.blue * 255) if write: self.ser.write(bytes([80, pixel, int(color.red * 255), int(color.green * 255), int(color.blue * 255)])) sleep(0.005) def fill(self, color, write=True): self.leds = [int(color.red * 255), int(color.green * 255), int(color.blue * 255)] * self.num_leds if write: self.ser.write(bytes([70, int(color.red * 255), int(color.green * 255), int(color.blue * 255)])) sleep(0.005) def close(self): self.fill(Color('black')) self.write() self.ser.close()
Java
UTF-8
424
2.25
2
[]
no_license
package com.example.academia.helper; import android.util.Base64; public class Codification { public static String codificacaoData(String infomation ){ return Base64.encodeToString(infomation.getBytes(), Base64.DEFAULT).replaceAll("(\\n|\\r)", ""); } public static String decodificationData (String dataCodificated){ return new String(Base64.decode(dataCodificated, Base64.DEFAULT)); } }
C++
UTF-8
5,521
2.796875
3
[]
no_license
// // Created by kir55rus on 04.01.17. // #include <iostream> #include <cstring> #include <netdb.h> #include <unistd.h> #include <fstream> #include "HttpTask.h" #include "../Utils.h" #include "../Converter.h" HttpTask::HttpTask() :m_downloadedChecksum(0), m_serverAddrInfo(NULL), m_socket(-1), m_lastModifiedDate(0) { } HttpTask::~HttpTask() { freeaddrinfo(m_serverAddrInfo); } int HttpTask::Init(const std::string &url, const std::string &downloadPath) { Log("Init"); m_url = url; m_downloadPath = downloadPath; size_t firstPos = url.find("http://"); if (firstPos == std::string::npos) { return -1; } firstPos += strlen("http://"); size_t secondPos = url.find("/", firstPos); if (secondPos == std::string::npos) { secondPos = url.size(); } std::string domain = url.substr(firstPos, secondPos - firstPos); addrinfo hints; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; int code = getaddrinfo(domain.c_str(), "http", &hints, &m_serverAddrInfo); if (code == -1) { perror("Can't get addr info"); return -1; } return 0; } int HttpTask::CreateSocket() { Log("Create socket"); m_socket = socket(m_serverAddrInfo->ai_family, m_serverAddrInfo->ai_socktype, m_serverAddrInfo->ai_protocol); if (m_socket == -1) { perror("Can't open socket"); return -1; } int code = connect(m_socket, m_serverAddrInfo->ai_addr, m_serverAddrInfo->ai_addrlen); if (code == -1) { perror("Can't connect"); return -1; } return 0; } int HttpTask::StartSession() { return 0; } int HttpTask::Update() { Log("Update"); int code = CreateSocket(); if (code < 0) { return -1; } code = Send("HEAD " + m_url + " HTTP/1.0\r\n\r\n"); if(code < 0) { Log("Can't send HEAD"); close(m_socket); return -1; } std::string answer; code = Recv(answer); if(code < 0) { Log("Can't recv HEAD"); close(m_socket); return -1; } close(m_socket); time_t lastModifiedDate = GetLastModifiedTime(answer); if(lastModifiedDate < 0) { Log("Head doesn't have last modified time"); return DownloadData(); } Log("Head has last modified time"); if(m_lastModifiedDate >= lastModifiedDate) { Log("It's old file"); return 0; } Log("It's new file"); code = DownloadData(); if (code < 0) { Log("Can't download file"); return -1; } m_lastModifiedDate = lastModifiedDate; return 0; } int HttpTask::DownloadData() { Log("Download data"); int code = CreateSocket(); if (code < 0) { return -1; } code = Send("GET " + m_url + " HTTP/1.0\r\n\r\n"); if(code < 0) { Log("Can't send GET"); close(m_socket); return -1; } std::string answer; code = Recv(answer); if(code < 0) { Log("Can't recv GET"); close(m_socket); return -1; } close(m_socket); size_t dataPos = answer.find("\r\n\r\n"); if (dataPos == std::string::npos) { Log("Can't find data"); return -1; } dataPos += strlen("\r\n\r\n"); const char *dataPtr = answer.c_str() + dataPos; size_t dataSize = answer.size() - dataPos; checksum_t newDataChecksum = GetChecksum(dataPtr, dataSize); if(newDataChecksum == m_downloadedChecksum) { Log("Old file"); return 0; } Log("New file"); code = SaveFile(dataPtr, dataSize); if (code < 0) { Log("Can't save file"); return -1; } m_downloadedChecksum = newDataChecksum; return 0; } int HttpTask::EndSession() { return 0; } int HttpTask::Send(const std::string &msg) { return Utils::Send(m_socket, msg); } int HttpTask::Recv(std::string &res, const std::string &endSymbols) { return Utils::Recv(m_socket, res, endSymbols); } void HttpTask::Log(const std::string &msg) { printf("Http (%s): %s\n", m_url.c_str(), msg.c_str()); } int HttpTask::SaveFile(const std::string &data) { return SaveFile(data.c_str(), data.size()); } int HttpTask::SaveFile(const char *data, size_t size) { Log("Save file"); std::ofstream out; out.open(m_downloadPath, std::ofstream::out); if(!out.is_open() || !out.good()) { return -1; } out.write(data, size); if (!out.good()) { out.close(); return -1; } out.close(); return 0; } HttpTask::checksum_t HttpTask::GetChecksum(const std::string &data) { return GetChecksum(data.c_str(), data.size()); } HttpTask::checksum_t HttpTask::GetChecksum(const char *data, size_t size) { checksum_t result = 0; for(size_t i = 0; i < size; ++i) { result = (result + data[i]) & 0xFF; } result = ((result ^ 0xFF) + 1) & 0xFF; return result; } time_t HttpTask::GetLastModifiedTime(const std::string &head) { size_t linePos = head.find("Last-Modified: "); if(linePos == std::string::npos) { return -1; } linePos += strlen("Last-Modified: "); size_t newLinePos = head.find("\r\n", linePos); if (newLinePos == std::string::npos) { return -1; } std::string dateStr = head.substr(linePos, newLinePos - linePos); time_t date = Converter::convertDate(dateStr); return date; } int HttpTask::Noop() { return 0; }
C#
UTF-8
3,804
2.640625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ShopKeeper { public partial class frmProductList : Form { SqlConnection cn = new SqlConnection(); SqlCommand cm = new SqlCommand(); SqlDataReader dr; DbConnection dbcon = new DbConnection(); public frmProductList() { InitializeComponent(); cn = new SqlConnection(dbcon.MyConnection()); LoadRecords(); } public void LoadRecords() { int i = 0; productListGridView.Rows.Clear(); cn.Open(); cm = new SqlCommand("SELECT p.pcode, p.barcode, p.pdescription, b.brand, c.category, p.price, p.reorder FROM tblProduct as p INNER JOIN tblBrand AS b on b.id = p.brand_id INNER JOIN tblCategory AS c ON c.id=p.category_id WHERE p.pdescription LIKE '" + txtSearch.Text+"%'", cn); dr = cm.ExecuteReader(); while (dr.Read()) { i += 1; productListGridView.Rows.Add(i, dr[0].ToString(), dr[1].ToString(), dr[2].ToString(), dr[3].ToString(), dr[4].ToString(), dr[5].ToString(), dr[6].ToString()); } dr.Close(); cn.Close(); } private void btnAddView_Click(object sender, EventArgs e) { frmProduct frm = new frmProduct(this); frm.btnSave.Enabled = true; frm.btnUpdate.Enabled = false; frm.LoadBrand(); frm.LoadCategory(); frm.ShowDialog(); } private void txtSearch_TextChanged(object sender, EventArgs e) { LoadRecords(); } private void productListGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) { string colName = productListGridView.Columns[e.ColumnIndex].Name; if (colName=="Edit") { frmProduct frm = new frmProduct(this); frm.btnSave.Enabled = false; frm.btnUpdate.Enabled = true; frm.txtCode.Text = productListGridView.Rows[e.RowIndex].Cells[1].Value.ToString(); frm.txtBarcode.Text = productListGridView.Rows[e.RowIndex].Cells[2].Value.ToString(); frm.txtDescription.Text = productListGridView.Rows[e.RowIndex].Cells[3].Value.ToString(); frm.cboBrand.Items.Add(productListGridView.Rows[e.RowIndex].Cells[4].Value.ToString()); //frm.cboBrand.Text = productListGridView.Rows[e.RowIndex].Cells[4].Value.ToString(); frm.cboCategory.Items.Add(productListGridView.Rows[e.RowIndex].Cells[5].Value.ToString()) ; //frm.cboCategory.Text = productListGridView.Rows[e.RowIndex].Cells[5].Value.ToString(); frm.txtPrice.Text = productListGridView.Rows[e.RowIndex].Cells[6].Value.ToString(); frm.txtReOrder.Text = productListGridView.Rows[e.RowIndex].Cells[7].Value.ToString(); frm.ShowDialog(); } else { if (MessageBox.Show("Are you sure to delete this record ?","Delete Record",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)==DialogResult.Yes) { cn.Open(); cm = new SqlCommand("DELETE FROM tblProduct WHERE pcode LIKE '"+ productListGridView.Rows[e.RowIndex].Cells[1].Value.ToString()+ "'",cn); cm.ExecuteNonQuery(); cn.Close(); LoadRecords(); } } } } }
C#
UTF-8
1,740
2.703125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DiceBot { public partial class DonateBox : Form { public DonateBox() { InitializeComponent(); } string currency = ""; public decimal amount { get; set; } decimal _Amount = 00; public DialogResult ShowDialog(decimal Amount, string currency, decimal defaultAmount) { this.currency = currency; _Amount = Amount; numericUpDown1.Value = (decimal)defaultAmount; lblmount.Text = ((decimal)_Amount * (numericUpDown1.Value / 100m)).ToString(); label1.Text = label1.Text.Replace("xx.xxxxxxxx", Amount.ToString("0.00000000")); label1.Text = label1.Text.Replace("yyy", currency); return this.ShowDialog(); } private void numericUpDown1_ValueChanged(object sender, EventArgs e) { lblmount.Text = ((decimal)_Amount * (numericUpDown1.Value / 100m)).ToString(); } private void btnCancel_Click(object sender, EventArgs e) { amount = (decimal)((decimal)_Amount * (numericUpDown1.Value / 100m)); DialogResult = DialogResult.Cancel; this.Close(); } private void btnDonate_Click(object sender, EventArgs e) { amount = (decimal)((decimal)_Amount * (numericUpDown1.Value / 100m)); DialogResult = DialogResult.Yes; this.Close(); } } }
C++
UTF-8
1,686
3.359375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <queue> using namespace std; int to_val(const string& s) { switch (s[0]) { case 'J': return 11; case 'Q': return 12; case 'K': return 13; case 'A': return 14; default: return stoi(s.substr(0, s.length() - 1)); } } int main() { int n, m; queue<int> q1, q2; string tmp; cin >> n; for (int i = 0; i < n; i++) { cin >> tmp; q1.push(to_val(tmp)); } cin >> m; for (int i = 0; i < m; i++) { cin >> tmp; q2.push(to_val(tmp)); } int roundCounter = 0; while (q1.size() > 0 && q2.size() > 0) { vector<int> warPile1, warPile2; warPile1.push_back(q1.front()); warPile2.push_back(q2.front()); q1.pop(); q2.pop(); while (warPile1.back() == warPile2.back()) { if (q1.size() < 4 || q2.size() < 4) { cout << "PAT"; return 0; } for (int i = 0; i < 4; ++i) { warPile1.push_back(q1.front()); warPile2.push_back(q2.front()); q1.pop(); q2.pop(); } } if (warPile1.back() > warPile2.back()) { for (auto& c : warPile1) q1.push(c); for (auto& c : warPile2) q1.push(c); } else { for (auto& c : warPile1) q2.push(c); for (auto& c : warPile2) q2.push(c); } roundCounter++; } cout << (q1.size() > 0 ? '1' : '2') << ' ' << roundCounter << endl; }
Java
UTF-8
2,847
2.203125
2
[]
no_license
/******************************************************************************* * Copyright (c) 2008 Chris Aniszczyk and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Chris Aniszczyk <caniszczyk@gmail.com> - initial API and implementation *******************************************************************************/ package org.eclipse.facebook.internal.ui.dialogs; import org.eclipse.facebook.internal.core.IConstants; import org.eclipse.facebook.internal.core.TracingUtil; import org.eclipse.facebook.internal.core.session.SessionFactory; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.browser.LocationEvent; import org.eclipse.swt.browser.LocationListener; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; public class FacebookLoginDialog extends TitleAreaDialog { public FacebookLoginDialog(Shell parentShell) { super(parentShell); } @Override protected Control createContents(Composite parent) { Control contents = super.createContents(parent); setHelpAvailable(false); setTitle("Log-in"); setMessage("Please log-in to facebook."); return contents; } @Override protected Control createDialogArea(Composite parent) { Composite composite = (Composite) super.createDialogArea(parent); composite.setLayout(new GridLayout()); // create browser to login to facebook application Browser browser = new Browser(composite, SWT.NONE); browser.setUrl(IConstants.URL_LOGIN); browser.setSize(550, 425); browser.addLocationListener(new LocationListener() { public void changing(LocationEvent event) { String location = event.location; System.out.println(location); if(location.indexOf("auth_token") != -1) { close(); int i = location.indexOf("="); String token = location.substring(i + 1, location.length()); if (TracingUtil.isTracing()) { System.out.println("Logged into facebook with token: " + token); } SessionFactory factory = SessionFactory.INSTANCE; factory.createSession(token); } } public void changed(LocationEvent event) { } }); return composite; } @Override protected void createButtonsForButtonBar(Composite parent) { // we only need to create a cancel button createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } }
C#
UTF-8
1,208
2.6875
3
[]
no_license
// ----------------------------------------------------------------------- // <copyright file="Singleton.cs" company="Microsoft"> // TODO: Update copyright text. // </copyright> // ----------------------------------------------------------------------- namespace WindsorMvc.Framework { using System; using System.Collections.Generic; using System.Linq; using System.Text; /// <summary> /// TODO: Update summary. /// </summary> public class Singleton { static readonly IDictionary<Type, object> allSingletons; static Singleton() { allSingletons = new Dictionary<Type, object>(); } public static IDictionary<Type, object> AllSingletons { get { return allSingletons; } } } /// <summary> /// TODO: Update summary. /// </summary> /// <typeparam name="T"></typeparam> public class Singleton<T> : Singleton { static T instance; public static T Instance { get { return instance; } set { instance = value; AllSingletons[typeof(T)] = value; } } } }
Java
UTF-8
218
1.976563
2
[]
no_license
package vn.com.vndirect.lib.commonlib.text; import org.jsoup.Jsoup; public class HtmlTagCleanerImpl implements HtmlTagCleaner { @Override public String clean(String html) { return Jsoup.parse(html).text(); } }
Python
UTF-8
19,816
3.390625
3
[ "MIT" ]
permissive
"""Utility functions. """ import functools import operator import itertools import time import sys from collections.abc import Iterable import tqdm import numpy as np class XYZError(Exception): pass def isiterable(obj): return isinstance(obj, Iterable) def prod(it): """Product of an iterable. """ return functools.reduce(operator.mul, it) def unzip(its, zip_level=1): """Split a nested iterable at a specified level, i.e. in numpy language transpose the specified 'axis' to be the first. Parameters ---------- its: iterable (of iterables (of iterables ...)) 'n-dimensional' iterable to split zip_level: int level at which to split the iterable, default of 1 replicates ``zip(*its)`` behaviour. Example ------- >>> x = [[(1, True), (2, False), (3, True)], [(7, True), (8, False), (9, True)]] >>> nums, bools = unzip(x, 2) >>> nums ((1, 2, 3), (7, 8, 9)) >>> bools ((True, False, True), (True, False, True)) """ def _unzipper(its, zip_level): if zip_level > 1: return (zip(*_unzipper(it, zip_level - 1)) for it in its) else: return its return zip(*_unzipper(its, zip_level)) if zip_level else its def flatten(its, n): """Take the n-dimensional nested iterable its and flatten it. Parameters ---------- its : nested iterable n : number of dimensions Returns ------- flattened iterable of all items """ if n > 1: return itertools.chain(*(flatten(it, n - 1) for it in its)) else: return its def _get_fn_name(fn): """Try to inspect a function's name, taking into account several common non-standard types of function: dask, functools.partial ... """ if hasattr(fn, "__name__"): return fn.__name__ # try dask delayed function with key elif hasattr(fn, "key"): return fn.key.partition('-')[0] # try functools.partial function syntax elif hasattr(fn, "func"): return fn.func.__name__ else: raise ValueError("Could not extract function name from {}".format(fn)) def progbar(it=None, nb=False, **kwargs): """Turn any iterable into a progress bar, with notebook option Parameters ---------- it: iterable Iterable to wrap with progress bar nb: bool Whether to display the notebook progress bar **kwargs: dict-like additional options to send to tqdm """ defaults = {'ascii': True, 'smoothing': 0.0} # Overide defaults with custom kwargs settings = {**defaults, **kwargs} if nb: # pragma: no cover return tqdm.tqdm_notebook(it, **settings) return tqdm.tqdm(it, **settings) def getsizeof(obj): """Compute the real size of a python object. Taken from https://stackoverflow.com/a/30316760/5640201 """ import sys from types import ModuleType, FunctionType from gc import get_referents # Custom objects know their class. # Function objects seem to know way too much, including modules. # Exclude modules as well. excluded = type, ModuleType, FunctionType if isinstance(obj, excluded): raise TypeError( 'getsize() does not take argument of type: {}'.format(type(obj))) seen_ids = set() size = 0 objects = [obj] while objects: need_referents = [] for obj in objects: if not isinstance(obj, excluded) and id(obj) not in seen_ids: seen_ids.add(id(obj)) size += sys.getsizeof(obj) need_referents.append(obj) objects = get_referents(*need_referents) return size class Timer: """A very simple context manager class for timing blocks. Examples -------- >>> from xyzpy import Timer >>> with Timer() as timer: ... print('Doing some work!') ... Doing some work! >>> timer.t 0.00010752677917480469 """ def __enter__(self): self.start = time.time() return self def __exit__(self, *args): self.end = time.time() self.t = self.time = self.interval = self.end - self.start def _auto_min_time(timer, min_t=0.2, repeats=5, get='min'): tot_t = 0 number = 1 while True: tot_t = timer.timeit(number) if tot_t > min_t: break number *= 2 results = [tot_t] + timer.repeat(repeats - 1, number) if get == 'mean': return sum(results) / (number * len(results)) return min(t / number for t in results) def benchmark(fn, setup=None, n=None, min_t=0.1, repeats=3, get='min', starmap=False): """Benchmark the time it takes to run ``fn``. Parameters ---------- fn : callable The function to time. setup : callable, optional If supplied the function that sets up the argument for ``fn``. n : int, optional If supplied, the integer to supply to ``setup`` of ``fn``. min_t : float, optional Aim to repeat function enough times to take up this many seconds. repeats : int, optional Repeat the whole procedure (with setup) this many times in order to take the minimum run time. get : {'min', 'mean'}, optional Return the minimum or mean time for each run. starmap : bool, optional Unpack the arguments from ``setup``, if given. Returns ------- t : float The minimum, averaged, time to run ``fn`` in seconds. Examples -------- Just a parameter-less function: >>> import xyzpy as xyz >>> import numpy as np >>> xyz.benchmark(lambda: np.linalg.eig(np.random.randn(100, 100))) 0.004726233000837965 The same but with a setup and size parameter ``n`` specified: >>> setup = lambda n: np.random.randn(n, n) >>> fn = lambda X: np.linalg.eig(X) >>> xyz.benchmark(fn, setup, 100) 0.0042192734545096755 """ from timeit import Timer if n is None: n = "" if setup is None: setup_str = "" stmnt_str = "fn({})".format(n) else: setup_str = "X=setup({})".format(n) stmnt_str = "fn(*X)" if starmap else "fn(X)" timer = Timer(setup=setup_str, stmt=stmnt_str, globals={'setup': setup, 'fn': fn}) return _auto_min_time(timer, min_t=min_t, repeats=repeats, get=get) class Benchmarker: """Compare the performance of various ``kernels``. Internally this makes use of :func:`~xyzpy.benchmark`, :func:`~xyzpy.Harvester` and xyzpys plotting functionality. Parameters ---------- kernels : sequence of callable The functions to compare performance with. setup : callable, optional If given, setup each benchmark run by suppling the size argument ``n`` to this function first, then feeding its output to each of the functions. names : sequence of str, optional Alternate names to give the function, else they will be inferred. benchmark_opts : dict, optional Supplied to :func:`~xyzpy.benchmark`. data_name : str, optional If given, the file name the internal harvester will use to store results persistently. Attributes ---------- harvester : xyz.Harvester The harvester that runs and accumulates all the data. ds : xarray.Dataset Shortcut to the harvester's full dataset. """ def __init__(self, kernels, setup=None, names=None, benchmark_opts=None, data_name=None): import xyzpy as xyz self.kernels = kernels self.names = [f.__name__ for f in kernels] if names is None else names self.setup = setup self.benchmark_opts = {} if benchmark_opts is None else benchmark_opts def time(n, kernel): fn = self.kernels[self.names.index(kernel)] return xyz.benchmark(fn, self.setup, n, **self.benchmark_opts) self.runner = xyz.Runner(time, ['time']) self.harvester = xyz.Harvester(self.runner, data_name=data_name) def run(self, ns, kernels=None, **harvest_opts): """Run the benchmarks. Each run accumulates rather than overwriting the results. Parameters ---------- ns : sequence of int or int The sizes to run the benchmarks with. kernels : sequence of str, optional If given, only run the kernels with these names. harvest_opts Supplied to :meth:`~xyzpy.Harvester.harvest_combos`. """ if not isiterable(ns): ns = (ns,) if kernels is None: kernels = self.names combos = {'n': ns, 'kernel': kernels} self.harvester.harvest_combos(combos, **harvest_opts) @property def ds(self): return self.harvester.full_ds def lineplot(self, **plot_opts): """Plot the benchmarking results. """ plot_opts.setdefault('xlog', True) plot_opts.setdefault('ylog', True) return self.ds.xyz.lineplot('n', 'time', 'kernel', **plot_opts) def ilineplot(self, **plot_opts): """Interactively plot the benchmarking results. """ plot_opts.setdefault('xlog', True) plot_opts.setdefault('ylog', True) return self.ds.xyz.ilineplot('n', 'time', 'kernel', **plot_opts) def format_number_with_error(x, err): """Given ``x`` with error ``err``, format a string showing the relevant digits of ``x`` with two significant digits of the error bracketed, and overall exponent if necessary. Parameters ---------- x : float The value to print. err : float The error on ``x``. Returns ------- str Examples -------- >>> print_number_with_uncertainty(0.1542412, 0.0626653) '0.154(63)' >>> print_number_with_uncertainty(-128124123097, 6424) '-1.281241231(64)e+11' """ # compute an overall scaling for both values x_exponent = max( int(f'{x:e}'.split('e')[1]), int(f'{err:e}'.split('e')[1]) + 1, ) # for readability try and show values close to 1 with no exponent hide_exponent = ( # nicer showing 0.xxx(yy) than x.xx(yy)e-1 (x_exponent in (0, -1)) or # also nicer showing xx.xx(yy) than x.xxx(yy)e+1 ((x_exponent == +1) and (err < abs(x / 10))) ) if hide_exponent: suffix = "" else: x = x / 10**x_exponent err = err / 10**x_exponent suffix = f"e{x_exponent:+03d}" # work out how many digits to print # format the main number and bracketed error mantissa, exponent = f'{err:.1e}'.split('e') mantissa, exponent = mantissa.replace('.', ''), int(exponent) return f'{x:.{abs(exponent) + 1}f}({mantissa}){suffix}' class RunningStatistics: # pragma: no cover """Running mean & standard deviation using Welford's algorithm. This is a very efficient way of keeping track of the error on the mean for example. Attributes ---------- mean : float Current mean. count : int Current count. std : float Current standard deviation. var : float Current variance. err : float Current error on the mean. rel_err: float The current relative error. Examples -------- >>> rs = RunningStatistics() >>> rs.update(1.1) >>> rs.update(1.4) >>> rs.update(1.2) >>> rs.update_from_it([1.5, 1.3, 1.6]) >>> rs.mean 1.3499999046325684 >>> rs.std # standard deviation 0.17078252585383266 >>> rs.err # error on the mean 0.06972167422092768 """ def __init__(self): self.count = 0 self.mean = 0.0 self.M2 = 0.0 def update(self, x): """Add a single value ``x`` to the statistics. """ self.count += 1 delta = x - self.mean self.mean += delta / self.count delta2 = x - self.mean self.M2 += delta * delta2 def update_from_it(self, xs): """Add all values from iterable ``xs`` to the statistics. """ for x in xs: self.update(x) def converged(self, rtol, atol): """Check if the stats have converged with respect to relative and absolute tolerance ``rtol`` and ``atol``. """ return self.err < rtol * abs(self.mean) + atol @property def var(self): if self.count == 0: return np.inf return self.M2 / self.count @property def std(self): if self.count == 0: return np.inf return self.var**0.5 @property def err(self): if self.count == 0: return np.inf return self.std / self.count**0.5 @property def rel_err(self): if self.count == 0: return np.inf return self.err / abs(self.mean) def __repr__(self): if self.count == 0: # mean and error are undefined return "RunningStatistics(mean=None, count=0)" return ( f"RunningStatistics(" f"mean={format_number_with_error(self.mean, self.err)}, " f"count={self.count}"")" ) class RunningCovariance: # pragma: no cover """Running covariance class. """ def __init__(self): self.count = 0 self.xmean = 0.0 self.ymean = 0.0 self.C = 0.0 def update(self, x, y): self.count += 1 dx = x - self.xmean dy = y - self.ymean self.xmean += dx / self.count self.ymean += dy / self.count self.C += dx * (y - self.ymean) def update_from_it(self, xs, ys): for x, y in zip(xs, ys): self.update(x, y) @property def covar(self): """The covariance. """ return self.C / self.count @property def sample_covar(self): """The covariance with "Bessel's correction". """ return self.C / (self.count - 1) class RunningCovarianceMatrix: def __init__(self, n=2): self.n = n self.rcs = {} for i in range(self.n): for j in range(i, self.n): self.rcs[i, j] = RunningCovariance() def update(self, *x): for i in range(self.n): for j in range(i, self.n): self.rcs[i, j].update(x[i], x[j]) def update_from_it(self, *xs): for i in range(self.n): for j in range(i, self.n): self.rcs[i, j].update_from_it(xs[i], xs[j]) @property def count(self): return self.rcs[0, 0].count @property def covar_matrix(self): covar_matrix = np.empty((self.n, self.n)) for i in range(self.n): for j in range(self.n): if j >= i: covar_matrix[i, j] = self.rcs[i, j].covar else: covar_matrix[i, j] = self.rcs[j, i].covar return covar_matrix @property def sample_covar_matrix(self): covar_matrix = np.empty((self.n, self.n)) for i in range(self.n): for j in range(self.n): if j >= i: covar_matrix[i, j] = self.rcs[i, j].sample_covar else: covar_matrix[i, j] = self.rcs[j, i].sample_covar return covar_matrix def to_uncertainties(self, bias=True): """Convert the accumulated statistics to correlated uncertainties, from which new quantities can be calculated with error automatically propagated. Parameters ---------- bias : bool, optional If False, use the sample covariance with "Bessel's correction". Return ------ values : tuple of uncertainties.ufloat The sequence of correlated variables. Examples -------- Estimate quantities of two perfectly correlated sequences. >>> rcm = xyz.RunningCovarianceMatrix() >>> rcm.update_from_it((1, 3, 2), (2, 6, 4)) >>> x, y = rcm.to_uncertainties(rcm) Calculated quantities like sums have the error propagated: >>> x + y 6.0+/-2.4494897427831783 But the covariance is also taken into account, meaning the ratio here can be estimated with zero error: >>> x / y 0.5+/-0 """ import uncertainties means = [self.rcs[i, i].xmean for i in range(self.n)] if bias: covar = self.covar_matrix else: covar = self.sample_covar_matrix return uncertainties.correlated_values(means, covar) def estimate_from_repeats(fn, *fn_args, rtol=0.02, tol_scale=1.0, get='stats', verbosity=0, min_samples=5, max_samples=1000000, **fn_kwargs): """ Parameters ---------- fn : callable The function that estimates a single value. fn_args, optional Supplied to ``fn``. rtol : float, optional Relative tolerance for error on mean. tol_scale : float, optional The expected 'scale' of the estimate, this modifies the aboslute tolerance near zero to ``rtol * tol_scale``, default: 1.0. get : {'stats', 'samples', 'mean'}, optional Just get the ``RunningStatistics`` object, or the actual samples too, or just the actual mean estimate. verbosity : { 0, 1, 2}, optional How much information to show: - ``0``: nothing - ``1``: progress bar just with iteration rate, - ``2``: progress bar with running stats displayed. min_samples : int, optional Take at least this many samples before checking for convergence. max_samples : int, optional Take at maximum this many samples. fn_kwargs, optional Supplied to ``fn``. Returns ------- rs : RunningStatistics Statistics about the random estimation. samples : list[float] If ``get=='samples'``, the actual samples. Examples -------- Estimate the sum of ``n`` random numbers: >>> import numpy as np >>> import xyzpy as xyz >>> def fn(n): ... return np.random.rand(n).sum() ... >>> stats = xyz.estimate_from_repeats(fn, n=10, verbosity=3) 59: 5.13(12): : 58it [00:00, 3610.84it/s] RunningStatistics(mean=5.13(12), count=59) """ rs = RunningStatistics() repeats = itertools.count() if verbosity >= 1: repeats = progbar(repeats) if get == 'samples': xs = [] try: for i in repeats: x = fn(*fn_args, **fn_kwargs) if get == 'samples': xs.append(x) rs.update(x) if verbosity >= 2: repeats.set_description( f"{rs.count}: {format_number_with_error(rs.mean, rs.err)}" ) # need at least min_samples to check convergence if (i > min_samples): if rs.converged(rtol, tol_scale * rtol): break # reached the maximum number of samples to try if i >= max_samples - 1: break except KeyboardInterrupt: # allow user to cleanly interupt sampling with keyboard pass finally: if verbosity >= 1: repeats.close() if verbosity >= 1: sys.stderr.flush() print(rs) if get == 'samples': return rs, xs if get == 'mean': return rs.mean return rs
Python
UTF-8
227
2.59375
3
[]
no_license
from socket import * c = socket(AF_INET,SOCK_DGRAM) while True: msg = input('>>:').strip() c.sendto(msg.encode('utf-8'),('127.0.0.1',9999)) data,server_addr = c.recvfrom(1024) print(data,server_addr) c.close()
C
UTF-8
3,385
3.09375
3
[]
no_license
//Acomoda el numero #include <stdio.h> int main(int argc, char *argv[]){ int M,C; int L=0; scanf("%i",&M); struct numero{ int p; }numero[M]; for(int i=0;i<M;i++){ scanf("%i",&numero[i].p); } C=0; do{ if(numero[0].p > numero[C].p) L++; C++; }while(C!=M); printf("%i",L); } //fizz bozz #include <stdio.h> int main(int argc, char *argv[]) { int c; scanf("%d",&c); int v[c]; for(int i=0;i<c;i++){ scanf("%d",&v[i]); } for(int i=0;i<=c-1;i++) { if(v[i]%3==0&&v[i]%5==0){ printf("FizzBozz\n"); }else{ if(v[i]%5==0){ printf("Bozz\n"); }else{ if(v[i]%3==0){ printf("Fizz\n"); }else{ if(v[i]%3!=0&&v[i]%5!=0){ printf("NoFizzBozz\n"); } } } } } return 0; } //Numeros locos #include <stdio.h> int main(int argc, char *argv[]) { int a,b,i,c,s; int d=0; scanf("%d",&a); scanf("%d",&b); int v[b]; for(i=1;i<=b;i++){ scanf("%d",&c); v[i]=c; } for(i=1;i<=b;i++){ if (i<b) s=v[i]+v[i+1]; else{ s=v[i]+v[1]; } if (s%a==0) d=d+1; } printf("%d",d); return 0; } //Apilando digitos #include <stdio.h> #include <stdlib.h> int main (int argc, char** argv) { int x,y,z=0,i; scanf ("%d",&x); scanf ("%d",&y); int v[x]; for (i=0;i<x;i++){ scanf ("%d",&v[i]); } for (i=0;i<x;i++){ if (v[i]==y){ z++; } } printf ("%d",z); return 0; } // Alicia #include <stdio.h> #include <stdlib.h> /* * */ int a,c; int main(){ scanf("%i", &a); int lol[100001]; for(int i=0;i<100002;++i)lol[i]=0; for(int i=0;i<a;++i)scanf("%i", &c),lol[c]=i+1; scanf("%i", &a); for(int i=0;i<a;++i)scanf("%i", &c),printf("%i ", lol[c]); return 0; } //Contar lapices #include <stdio.h> #include <stdlib.h> int main (int argc, char** argv) { int x,y,z=0,i; scanf ("%d",&x); scanf ("%d",&y); int v[x]; for (i=0;i<x;i++){ scanf ("%d",&v[i]); } for (i=0;i<x;i++){ if (v[i]==y){ z++; } } printf ("%d",z); return 0; } //A Pares y nones #include <stdio.h> #include <stdlib.h> int main (int argc, char** argv) { int x,y,z,c,j,k,i; scanf ("%d\n",&x); z=0; c=0; j=0; k=0; int v[x]; for (i=0;i<x;i++){ scanf ("%d",&v[i]); } for (i=0;i<x;i++){ y=v[i]%2; if (y==0){ z+=v[i]; j++; } else { c+=v[i]; k++; } } z/=j; c/=k; if (z==c){ printf ("EMPATE!"); } else if (z<c){ printf ("NONILA"); } else if (z>c){ printf ("APARICIO"); } return 0; } //Pitagoras #include <stdio.h> #include <math.h> int main (int argc, char** argv) { int i,j,k,d=0,x,y; scanf ("%d %d",&x,&y); for (i=x;i<=y;i++){ for (j=x;j<=y;j++){ float c= (float) sqrt(pow(i,2)+pow(j,2)); int aux = floor(c); if (c>=x && c<=y && i<=j && c-aux==0){ d++; } } } printf ("%d",d); return 0; }
JavaScript
UTF-8
558
2.515625
3
[]
no_license
const jwt = require('jsonwebtoken'); require('dotenv').config(); //*** Validate JWT ***/ exports.verify = (req) => { var token = req.headers['authorization'] || req.headers['x-access-token']; if (token.startsWith('Bearer ')) { token = token.slice(7, token.length); } if (!token) return { auth: false, message: 'No token provided.' }; try { const decoded = jwt.verify(token, process.env.SECRET); return { auth: true, message: 'Authenticated.' }; } catch { return { auth: false, message: 'Failed to authenticate token.' }; } }
PHP
UTF-8
1,140
2.875
3
[]
no_license
<?php /* Attempt MySQL server connection. Assuming you are running MySQL server with default setting (user 'root' with no password) */ $link = mysqli_connect('ec2-52-14-244-154.us-east-2.compute.amazonaws.com', 'ec2-user', 'group20database','group20'); // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } // Print host information echo "Connect Successfully. Host info: " . mysqli_get_host_info($link); // Close connection mysqli_close($link); ?> <?php // Created by Professor Wergeles for CS2830 at the University of Missouri // $dbhost = 'ec2-52-14-244-154.us-east-2.compute.amazonaws.com'; // Your MySQL database hostname on Amazon EC2 (Should be same as mine unless you changed it) // $dbuser = ‘ec2-user’; // Your MySQL database username on Amazon EC2 (Should be same as mine unless you changed it) // $dbpass = 'group20database'; // Your MySQL database password on Amazon EC2 (Remember this otherwise you will not be able to access your database) // $dbname = 'group20'; //The name of your MySQL database (Should be same as mine unless you changed it ?>
Java
UTF-8
2,777
1.789063
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright 2009-2018 Exactpro (Exactpro Systems Limited) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.exactprosystems.jf.actions.text; import com.exactprosystems.jf.actions.AbstractAction; import com.exactprosystems.jf.actions.ActionAttribute; import com.exactprosystems.jf.actions.ActionFieldAttribute; import com.exactprosystems.jf.actions.ActionGroups; import com.exactprosystems.jf.api.common.i18n.R; import com.exactprosystems.jf.api.error.ErrorKind; import com.exactprosystems.jf.common.evaluator.AbstractEvaluator; import com.exactprosystems.jf.common.report.ReportBuilder; import com.exactprosystems.jf.documents.config.Context; import com.exactprosystems.jf.documents.matrix.parser.Parameters; import com.exactprosystems.jf.functions.Text; @ActionAttribute( group = ActionGroups.Text, constantGeneralDescription = R.TEXT_SET_VALUE_GENERAL_DESC, additionFieldsAllowed = false, constantExamples = R.TEXT_SET_VALUE_EXAMPLE, seeAlsoClass = {TextReport.class, TextAddLine.class, TextLoadFromFile.class, TextCreate.class, TextSaveToFile.class, TextPerform.class} ) public class TextSetValue extends AbstractAction { public static final String textName = "Text"; public static final String lineName = "Line"; public static final String indexName = "Index"; @ActionFieldAttribute(name = textName, mandatory = true, constantDescription = R.TEXT_SET_VALUE_TEXT) protected Text text; @ActionFieldAttribute(name = lineName, mandatory = true, constantDescription = R.TEXT_SET_VALUE_LINE) protected String line; @ActionFieldAttribute(name = indexName, mandatory = true, constantDescription = R.TEXT_SET_VALUE_INDEX) protected Integer index; @Override public void doRealAction(Context context, ReportBuilder report, Parameters parameters, AbstractEvaluator evaluator) throws Exception { if (index < 0 || index >= this.text.size()) { super.setError(String.format("Index '%s' is out of bounds", this.index), ErrorKind.WRONG_PARAMETERS); return; } this.text.set(this.index, this.line); super.setResult(null); } }
TypeScript
UTF-8
1,460
3.296875
3
[ "MIT" ]
permissive
import { pipe, toArray, zip, take, range, chunk } from './' it('should be possible to zip data together', () => { let program = pipe( [ [0, 1, 2, 3], ['A', 'B', 'C', 'D'], ], zip(), toArray() ) expect(program()).toEqual([ [0, 'A'], [1, 'B'], [2, 'C'], [3, 'D'], ]) }) it('should be possible to zip data together from a generator', () => { let program = pipe(range(0, 1_000), chunk(4), take(5), zip(), take(5), toArray()) expect(program()).toEqual([ [0, 4, 8, 12, 16], [1, 5, 9, 13, 17], [2, 6, 10, 14, 18], [3, 7, 11, 15, 19], ]) }) it('should drop non matchable values', () => { // If array A has 3 items and array B has 4 items, the last item of array B // will be dropped. let program = pipe( [ [0, 1, 2, 3], ['A', 'B', 'C'], ], zip(), toArray() ) expect(program()).toEqual([ [0, 'A'], [1, 'B'], [2, 'C'], ]) }) it('should be chainable with a take so that only a few items are zipped', () => { let program = pipe( [ [0, 1, 2, 3], ['A', 'B', 'C'], ], zip(), take(2), toArray() ) expect(program()).toEqual([ [0, 'A'], [1, 'B'], ]) }) it('should zip multiple iterators together', () => { let program = pipe([range(0, 999), range(999, 0)], zip(), take(5), toArray()) expect(program()).toEqual([ [0, 999], [1, 998], [2, 997], [3, 996], [4, 995], ]) })
Python
UTF-8
2,540
2.953125
3
[]
no_license
import time import random ttri = [] ttrii = [] ttriii = [] tttri = [] tttrii = [] tttriii = [] ttttri = [] ttttrii = [] ttttriii = [] maxVal = 2**14 #nVal = 5 valx = [2**i for i in range (1,10)] #listeNombres = random.choices(range(maxVal),k=nVal) def triSelection(l: list)-> list: n = len(l) for i in range(0,n-1): indiceMini = i for j in range (i,n): if l[j]<l[indiceMini]: #print (l) indiceMini = j temps = l[i] l[i]= l[indiceMini] l[indiceMini]= temps #print(l) return def triInsertion(l: list)-> list: n = len(l) for i in range (1,n): vt = l[i] j=i-1 while j>=0 and vt<l[j]: l[j+1]=l[j] j=j-1 l[j+1]=vt return l #listeNombresTriee = triSelection(listeNombres) # trie la liste #print(listeNombresTriee) from matplotlib.pyplot import* for nVal in valx: listeNombres = random.choices(range(maxVal),k=nVal) t1 = time.time() triSelection(listeNombres) t2 = time.time() t3 = (t2-t1) ttri.append(t3) t11 = time.time() triInsertion(listeNombres) t22 = time.time() t33 = (t22-t11) ttrii.append(t33) t111 = time.time() sorted(listeNombres) t222 = time.time() t333 = (t222-t111) ttriii.append(t333) ''' ''' listeNombres = sorted(listeNombres) tt1 = time.time() triSelection(listeNombres) tt2 = time.time() tt3 = (tt2-tt1) tttri.append(tt3) tt11 = time.time() triInsertion(listeNombres) tt22 = time.time() tt33 = (tt22-tt11) tttrii.append(tt33) tt111 = time.time() sorted(listeNombres) tt222 = time.time() tt333 = (tt222-tt111) tttriii.append(tt333) ''' ''' listeNombres = sorted(listeNombres,reverse = True) ttt1 = time.time() triSelection(listeNombres) ttt2 = time.time() ttt3 = (ttt2-ttt1) ttttri.append(ttt3) ttt11 = time.time() triInsertion(listeNombres) ttt22 = time.time() ttt33 = (ttt22-ttt11) ttttrii.append(ttt33) ttt111 = time.time() sorted(listeNombres) ttt222 = time.time() ttt333 = (ttt222-ttt111) ttttriii.append(ttt333) yyy1 = ttttri yyy11 = ttttrii yyy111 = ttttriii yy1 = tttri yy11 = tttrii yy111 = tttriii y1 = ttri x = valx y11 = ttrii y111 = ttriii ''' semilogy(x,y11,"x-b",x,y1,"x-g",x,y111,"x-r") semilogy(x,yy1,"x--g",x,yy11,"x--b",x,yy111,"x--r") semilogy(x,yyy1,":g",x,yyy11,":b",x,yyy111,":r") ''' plot(x,y111,"x-r") plot(x,yy111,"x--r") plot(x,yyy111,":r") show() #liste2 = [10,3,7,5,6,1] #print(triInsertion(liste2))
Java
UTF-8
1,982
1.789063
2
[]
no_license
package kr.kosmo.jobkorea.manageA.model; public class ExsubjectMgtDtlModel { //게시판 글번호 private int row_num; // private int no; //과정명 private String title; //구분-재시험 private String re; //대상자수 private String cnt; //로그인 아이디 private String loginID; //시험점수 private String mainscore; //재시험점수 private String rescore; //출석 private String attend; //시퀀스 private String seq; //통과여부 메세지 private String passmsg; public String getPassmsg() { return passmsg; } public void setPassmsg(String passmsg) { this.passmsg = passmsg; } public String getMainscore() { return mainscore; } public void setMainscore(String mainscore) { this.mainscore = mainscore; } public String getRescore() { return rescore; } public void setRescore(String rescore) { this.rescore = rescore; } public String getCnt() { return cnt; } public void setCnt(String cnt) { this.cnt = cnt; } public String getSeq() { return seq; } public void setSeq(String seq) { this.seq = seq; } public String getLoginID() { return loginID; } public void setLoginID(String loginID) { this.loginID = loginID; } public String getAttend() { return attend; } public void setAttend(String attend) { this.attend = attend; } public int getRow_num() { return row_num; } public void setRow_num(int row_num) { this.row_num = row_num; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getRe() { return re; } public void setRe(String re) { this.re = re; } public String getloginID() { return loginID; } public void setloginID(String loginID) { this.loginID = loginID; } }
Markdown
UTF-8
1,671
3.03125
3
[]
no_license
# Indigo Slate Coding Challenge ## Development ### Challenge Requirements Use the video as a base to launch from, you do not need to match colors, recreate the logo, etc. You are also welcome to present an alternative to the classic Hamburger Menu. Also, please limit the use of Bootstrap or any other CSS framework while taking the challenge and make it fun. Be sure to account for the idea of a larger multi-tiered navigation! We look forward to seeing… 1. Is it comfortable to interact with, does it feel well thought out? 2. How you have you made use of animations to enhance the experience 3. How did you approach the development (Code structure, creative solutions, complexity, etc) ### Technologies Used 1. HTML5 2. CSS3/Bootstrap 3. Jquery 4. Javascript 5. Keyframe/CSS Animations ### Approach Taken I wanted to build a navigation menu that was made with mostly CSS to ensure accurate, timely functionality to create the best user experience possible. I started with building out a small portion of the multi tiered navigation to test out it's animation and jquery functionality. Once I styled the navbar in the way I wanted, I continued to add the rest of the menu items and checked each one along the way. With a little bit of Jquery, CSS Animations and Keyframe Animations, I coded smooth, timely transitions when opening each menu/submenu. ## What did I learn? 1. How to create a multi tier navigation without completely relying on a CSS Framework! It was a great experience learning how to style it and add in functionality without using strictly Javascript as well. 2. How to properly nest multiple menus inside of one another.
Markdown
UTF-8
1,845
2.8125
3
[ "MIT" ]
permissive
--- layout: about title: About Us permalink: /about/ description: We bring together a team of graphic, developers, SEO experts, Servers Engenieers & Security experts for each project, ensuring you get the best mixture of talent and experience. priority: 0.9 --- <div class="container mtb"> <div class="row"> <div class="col-lg-6"> <img class="img-responsive" src="{{ "/assets/img/about.jpg" | prepend: site.baseurl }}" alt=""> </div> <div class="col-lg-6"> <p>{{ site.title }} brings together a team of graphic, developers, SEO experts, Servers Engenieers & Security experts for each project, ensuring you get the best mixture of talent and experience.</p> <p>The team at {{ site.title }} have been working with big companies for over 15 years. We believe help and support is vital in this computer orientated, non human world. We like to believe we are intelligent and social and this reflects in our team spirit.</p> <p>We love challenging projects and to help out on the most menial support tasks ! We love to help it’s part of how we work with customers.</p> <p>{{ site.title }} is a company focused on consulting and services aimed at Open Source where there is a passionate community which followed the long years.</p> <p>We think and develop techniques to address the major challenges of our customers, we try to get the best market technology in the open source community so we can meet those who seek a quality solution.</p> <p>Our main concern is to support the client through technologies that meet this need.</p> <p><br/><a href="/contact/" class="btn btn-theme">Contact-us</a></p> </div> </div> </div> {% include members-en.html %} {% include testimonial.html %} {% include clients-en.html %}
JavaScript
UTF-8
333
3.515625
4
[]
no_license
console.log(7/0) //infinity console.log("10" / 2) //vai funcionar!!! console.log("Show!" * 2) //não vai funcionar!!! console.log(0.1 + 0.7) //pela fraca tipagem, a soma não vai ser precisa, vai dar 0.799999999999 //console.log(10.toString()) //não funciona console.log((10.345).toFixed(2)) // console.log((10).toFixed(2)) //
Java
UTF-8
340
2.609375
3
[]
no_license
package Observer_pattern; import java.util.ArrayList; public abstract class Customer { ArrayList<CustomerListener> listener = new ArrayList<CustomerListener>(); public void attach(CustomerListener l) { listener.add(l); } public void dettach(CustomerListener l) { listener.remove(l); } public abstract void catchAttention(); }
Go
UTF-8
1,208
2.5625
3
[]
no_license
package main import ( "context" "fmt" "log" "net/http" "os" "os/signal" "syscall" "time" _ "github.com/go-sql-driver/mysql" "github.com/justpoypoy/go-base/infrastructure" ) var timeout = 30 * time.Second func main() { logger := infrastructure.NewLogger() infrastructure.Load(logger) sqlHandler, err := infrastructure.NewSQL() if err != nil { logger.LogError("%s", err) } var port = os.Getenv("APP_PORT") if port == "" { port = "8088" } server := infrastructure.Dispatch( fmt.Sprintf(":%s", port), logger, sqlHandler, ) go func() { if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatalf("failed listen server on: %s\n", err) } }() graceShutdown(server) } func graceShutdown(srv *http.Server) { quit := make(chan os.Signal, 1) signal.Notify(quit, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) <-quit log.Println("Shutting down server...") ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatal("Server forced to shutdown:", err) } log.Println("Server exiting") os.Exit(0) }
Java
UTF-8
851
2.40625
2
[]
no_license
package cn.withstars.chatroom; import cn.withstars.chatroom.util.Constants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created with IntelliJ IDEA. * Description: * User: withstars * Date: 2018-03-31 * Time: 17:19 * Mail: withstars@126.com */ public class Main { private static final Logger logger = LoggerFactory.getLogger(Main.class); public static void main(String[] args){ final Server server = new Server(Constants.DEFAULT_PORT); server.init(); server.start(); // 注册进程钩子,在jvm进程关闭前释放资源 Runtime.getRuntime().addShutdownHook(new Thread(){ @Override public void run() { server.shutdown(); logger.warn("=== jvm shutdown ==="); System.exit(0); } }); } }
Ruby
UTF-8
2,586
2.609375
3
[ "MIT" ]
permissive
# frozen_string_literal: true require_dependency "#{Rails.root}/lib/importers/article_importer" require_dependency "#{Rails.root}/lib/replica" require_dependency "#{Rails.root}/lib/utils" #= Updates records for revisions that were moved or deleted on Wikipedia class ModifiedRevisionsManager def initialize(wiki) @wiki = wiki end def move_or_delete_revisions(revisions=nil) # NOTE: All revisions passed to this method should be from the same @wiki. revisions ||= Revision.where(wiki_id: @wiki.id) return if revisions.empty? synced_revisions = fetch_existing_revisions_from(revisions) synced_rev_ids = synced_revisions.map { |r| r['rev_id'].to_i } deleted_rev_ids = revisions.pluck(:mw_rev_id) - synced_rev_ids update_deleted_revisions(deleted_rev_ids) update_nondeleted_revisions(synced_rev_ids) moved_ids = synced_rev_ids - deleted_rev_ids update_moved_revisions(synced_revisions, moved_ids) end private def fetch_existing_revisions_from(revisions) Utils.chunk_requests(revisions, 100) do |block| Replica.new(@wiki).get_existing_revisions_by_id block end end def update_moved_revisions(synced_revisions, moved_ids) moved_revisions = synced_revisions.reduce([]) do |moved, rev| moved.push rev if moved_ids.include? rev['rev_id'].to_i end moved_revisions.each do |moved| handle_moved_revision moved end end def update_deleted_revisions(rev_ids) # rubocop:disable Rails/SkipsModelValidations Revision.where(wiki_id: @wiki.id, mw_rev_id: rev_ids).update_all(deleted: true) # rubocop:enable Rails/SkipsModelValidations end def update_nondeleted_revisions(rev_ids) # rubocop:disable Rails/SkipsModelValidations Revision.where(wiki_id: @wiki.id, mw_rev_id: rev_ids).update_all(deleted: false) # rubocop:enable Rails/SkipsModelValidations end def handle_moved_revision(moved) mw_page_id = moved['rev_page'] unless Article.exists?(wiki_id: @wiki.id, mw_page_id:) ArticleImporter.new(@wiki).import_articles([mw_page_id]) end article = Article.find_by(wiki_id: @wiki.id, mw_page_id:, deleted: false) # Don't update the revision to point to a new article if there isn't one. # This may happen if the article gets moved and then deleted, and there's # some inconsistency or timing delay in the update process. return unless article revision = Revision.find_by(wiki_id: @wiki.id, mw_rev_id: moved['rev_id']) return unless revision revision.update(article_id: article.id, mw_page_id:) end end
Markdown
UTF-8
7,590
3.125
3
[]
no_license
# School_District_Analysis ## Project Overview An employee for the Education District has been tasked with getting key metrics from School District grades. The analysis was completed by performing calculations to get sums, averages, and percentages in the School District data for high school grades. ## Challenge Overview After the school district committee reviewed the result, the school district suspected that the standardized test scores for ninth grade students at Thomas High School were somehow tampered or manipulated in some manner and they requested for the analysis to be repeated only this time excluding the grades for 9th graders in Thomas High School but the students would remain for that grade in order not to skew the other numbers in regards to budget, school size, budget per student and ## Resources - Data Source: schools_complete.csv students_complete.csv - Software: Jupyter Notebook, Python 3.9.0 ## Summary ### District School Analysis - Complete Data Below are the results for the initial ananlysis for the school district summary. The high-level snapshot of the key metrics is as follows: - Total number of students 39,170 - Total number of schools 15 - Total budget $24,649,428 - Average math score 79.0 (78.98537146) - Average reading score 81.9 (81.87750517) - Percentage of students who passed math 75% - Percentage of students who passed reading 86% - Overall passing percentage 65% ![alt text](https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/Disctrict_School_Analysis_Final.png ) ### School District Analysis - Excluding data Below are the results for the second ananlysis performed for the school district summary after the grades for Thomas High School 9th Graders were removed from the data. This is a high-level snapshot of the district's key metrics: - Total number of students 38,709 - Total number of schools 15 - Total budget $24,649,428 - Average math score 79.0 (78.93053295) - Average reading score 81.9 (81.85579581) - Percentage of students who passed math 75% - Percentage of students who passed reading 86% - Overall passing percentage 65% ![alt text](https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/Challenge_District_Summary.png ) ## Results Below is a more detailed analysis performed and the explanation of how they differ with the initial analysis of the data. Both math and reading scores were replaced with "NaN", which represents a "Not-a-Number" value. As a result of this change, 461 student grades were removed for math and reading respectively. Although it may seem a large number, compared to the total amount of students, the 461 only represents 1.2% of the total grades that were analyzed. ### District Summary The District summary was minimally affected due to the fact that when rounding the values up the changes were so minimally that they were not reflected in the formatted data. - District Summary Analysis Complete Data ![alt text](https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/Disctrict_School_Analysis_Final.png ) - District Summary Analysis Excluded Data ![alt text](https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/Challenge_District_Summary.png ) ### School Summary The School Summary was affected by changing the grades for Thomas High School for math and reading. This ended up improving Thomas High School grades by 25%-30% when the 9th graders were removed compared to their math and reading scores in the initial analysis. Thomas High School now has some of the highest passing scores compared to other schools. Below are the images for both of the results: - School Summary Analysis Complete Data ![alt text](https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/Per_School_Summary.png ) - School Summary Analysis Excluded Data ![alt text](https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/Challenge_School_Summary.png ) ### Math and reading scores by Grade The Math and Reading scores by grade were not affected. This is due to the fact that this number is calculated as an average of all the values within the school. ### Math and Reading Passing Percentages The passing percentages were affected by removing the 9th graders grades for Thomas High School for math and reading. This ended up improving Thomas High School passing percentages from 25%-30%. This improved the performance of the high school by close to 30%. Below are the images for a better understanding of the changes that occurred: - Math and Reading Passing Percentages Complete Data ![alt text](https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/Thomas_HS_results_Complete_Data.png ) - Math and Reading Passing Percentages Excluded Data ![alt text](https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/Thomas_HS_Removed_Data.png ) ### 5 Top Schools and 5 Bottom Schools The biggest changed observed after removing the 9th graders grades for Thomas High School was that it became the 2nd Top school with an overall passing score of 90.6% compared to being in the 7th place with an overall passing score of 65.1%. Below are the images for both analysis for the 5 top Schools - Top Schools Complete Data - Thomas High School shows as 7th place ![alt text]( https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/Top_5_Schools_THS_7th_complete_Data.png) - Top Schools Excluded Data - Thomas High School shows as 2nd place ![alt text]( https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/Challenge_Top_5_Schools.png) ### Scores by school spending There was no change observed for this metric because the number of students did not change, only the grades for math and reading were removed for the 9th graders at Thomas High School. Thomas High school remained in the $630-644 ranges per student in both analysis. ### Scores by school size There was no change observed for this metric because the number of students did not change, only the grades for math and reading were removed for the 9th graders at Thomas High School. Thomas High school remained a Medium size School in both analysis. ### Scores by school type The scores by school type were also affected by removing the 9th graders grades for Thomas High School for math and reading. This ended up improving the charter school passing percentages from by 3-4 points higher compared to the intial review. This is du to Thomas High School being a Charter school. Below are the images that show the initial numbers and the ones after. - Scores by school type Complete Data ![alt text](https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/School_Type_Summary_Complete_Data.png ) - Scores by school type Excluded Data ![alt text](https://github.com/sandramcardona/School_District_Analysis/blob/main/Resources/School_Type_Summary_Removed_Data.png ) After finishing the review, it was concluded that by removing the 9th graders grades for Thomas High School for math and reading made a significance improvement. The Summary of School shows that the school now ranks some of the highest passing scores. For the passing percentages for math, reading and overall passing scores it shows a 25-30% increase compared to the original scores. It now ranks 2nd instead of 7th among all the other schools based on these scores. Lastly, it improved the Charter schools overall passing percentges compared to the District schools.
Markdown
UTF-8
5,216
2.6875
3
[]
no_license
--- description: "Easiest Way to Prepare Super Quick Homemade Ray&amp;#39;s&amp;#39; banana buttercream" title: "Easiest Way to Prepare Super Quick Homemade Ray&amp;#39;s&amp;#39; banana buttercream" slug: 1550-easiest-way-to-prepare-super-quick-homemade-ray-and-39-s-and-39-banana-buttercream date: 2020-07-30T06:49:24.238Z image: https://img-global.cpcdn.com/recipes/5830698552262656/751x532cq70/rays-banana-buttercream-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/5830698552262656/751x532cq70/rays-banana-buttercream-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/5830698552262656/751x532cq70/rays-banana-buttercream-recipe-main-photo.jpg author: Nancy Lamb ratingvalue: 3.3 reviewcount: 5 recipeingredient: - "1 cup crisco shortening" - "3/4 cup heavy cream" - "1 pinch salt" - "3 tsp banana extract" - "8 cup powder sugar" - "1/2 cup cornstarch" - "1 cup butter" recipeinstructions: - "start by creaming together your softened butter till you get a lighter silky texture (about 3-5 min)" - "now add your shortening and whip for about 1 minute or so on high speed" - "now slowly start adding your salt and 1 cup at a time of powdered sugar, stopping your mixer ever minute or so to scrape sides continue to add your powder sugar." - "once it thickens start added your heavy cream, extract and the last powder sugar and cornstarch till a nice consistency." - "your buttercream should stick to the spatula if its still to loose add 1/2 cup more powder sugar, and tspn at a time of cornstarch." - "I like to set in fridgerator overnight covered in a Tupperware container for best results. enjoy!" categories: - Recipe tags: - rays - banana - buttercream katakunci: rays banana buttercream nutrition: 246 calories recipecuisine: American preptime: "PT32M" cooktime: "PT38M" recipeyield: "2" recipecategory: Lunch --- ![Ray&#39;s&#39; banana buttercream](https://img-global.cpcdn.com/recipes/5830698552262656/751x532cq70/rays-banana-buttercream-recipe-main-photo.jpg) Hello everybody, I hope you're having an incredible day today. Today, we're going to prepare a distinctive dish, ray&#39;s&#39; banana buttercream. It is one of my favorites food recipes. For mine, I am going to make it a bit tasty. This will be really delicious. This is a quick and simple fresh banana buttercream frosting and filling. It is a sweet American-style frosting. This buttercream can be piped to form. Ray&#39;s&#39; banana buttercream is one of the most popular of recent trending meals in the world. It's enjoyed by millions every day. It's simple, it's fast, it tastes delicious. Ray&#39;s&#39; banana buttercream is something that I have loved my whole life. They are nice and they look fantastic. To get started with this recipe, we must first prepare a few ingredients. You can cook ray&#39;s&#39; banana buttercream using 7 ingredients and 6 steps. Here is how you cook that. <!--inarticleads1--> ##### The ingredients needed to make Ray&#39;s&#39; banana buttercream: 1. Make ready 1 cup crisco shortening 1. Prepare 3/4 cup heavy cream 1. Make ready 1 pinch salt 1. Prepare 3 tsp banana extract 1. Take 8 cup powder sugar 1. Prepare 1/2 cup cornstarch 1. Get 1 cup butter Reviews for: Photos of Banana and Vanilla Cupcakes with Buttercream Frosting. Bananas: The New Buttercream. by Jessica Goldman Foung. Apparently, with enough patience and powdered sugar, you can make a buttercream glaze for cookies, cakes, and of course, banana bread. Filled with banana cream, topped with peanut butter buttercream, and drizzled with chocolate, these cupcakes are outrageously rich. <!--inarticleads2--> ##### Steps to make Ray&#39;s&#39; banana buttercream: 1. start by creaming together your softened butter till you get a lighter silky texture (about 3-5 min) 1. now add your shortening and whip for about 1 minute or so on high speed 1. now slowly start adding your salt and 1 cup at a time of powdered sugar, stopping your mixer ever minute or so to scrape sides continue to add your powder sugar. 1. once it thickens start added your heavy cream, extract and the last powder sugar and cornstarch till a nice consistency. 1. your buttercream should stick to the spatula if its still to loose add 1/2 cup more powder sugar, and tspn at a time of cornstarch. 1. I like to set in fridgerator overnight covered in a Tupperware container for best results. enjoy! Our delicious banana cake with cinnamon, nutmeg, and allspice, has a banana buttercream It&#39;s a two layer cake with a banana buttercream frosting. Try making this the next time you plan on going. A step-by-step tutorial for creating the perfect St. Patrick&#39;s Day inspired buttercream rainbows on a buttercream covered cake. Add bananas, eggs, melted butter, and vanilla to the dry ingredients and mix until just combine. So that is going to wrap this up with this exceptional food ray&#39;s&#39; banana buttercream recipe. Thanks so much for your time. I am confident that you can make this at home. There is gonna be more interesting food in home recipes coming up. Remember to bookmark this page on your browser, and share it to your loved ones, colleague and friends. Thanks again for reading. Go on get cooking!
PHP
UTF-8
1,265
2.515625
3
[]
no_license
<?php use yii\db\Migration; use app\modules\v1\models\TaxRate; use app\modules\settings\models\Zip; /** * Class m210525_130617_add_tax_to_zip */ class m210525_130617_add_tax_to_zip extends Migration { /** * {@inheritdoc} */ public function safeUp() { $this->addColumn('zip', 'tax', $this->float()); $path = \Yii::getAlias('@app/zip'); $array = scandir($path); array_shift($array); array_shift($array); foreach($array as $value) { if(($handle = fopen($path . '/' . $value, "r")) !== false) { $flag = true; //find or create store while(($data = fgetcsv($handle, 1000000, ',')) !== false) { if($flag) { $flag = false; continue; } $zip = Zip::findOne(['zipcode' => trim($data[1])]); if($zip){ $zip->tax = Yii::$app->formatter->asDecimal(((float)$data[4] * 100), 2); $zip->save(); } } } } } /** * {@inheritdoc} */ public function safeDown() { echo "m210525_130617_add_tax_to_zip cannot be reverted.\n"; return true; } /* // Use up()/down() to run migration code without a transaction. public function up() { } public function down() { echo "m210525_130617_add_tax_to_zip cannot be reverted.\n"; return false; } */ }
Java
UTF-8
32,519
1.929688
2
[]
no_license
package zookeeper.configStation.servlet; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.jar.Manifest; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.tomcat.util.http.fileupload.FileItemIterator; import org.apache.tomcat.util.http.fileupload.FileItemStream; import org.apache.tomcat.util.http.fileupload.FileUploadException; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import com.google.gson.Gson; /** * Servlet implementation class LoadTree */ @WebServlet("/LoadTree") public class LoadTree extends HttpServlet { private static final long serialVersionUID = 1L; // ����log4j����־ʵ�� private final static String VERSIONNAME = "Manifest-Version"; private final static String relativeWARPath = "/META-INF/MANIFEST.MF"; private static Logger LOG = Logger.getLogger(ConfigServlet.class); private String logConfig = "./log4j.properties"; private String webRealPath = ""; private String zkhost = "127.0.0.1:2181"; private ZooKeeper myzk = null; private boolean isConnectZk = false; private Gson gson = new Gson(); static class TreeNode{ String nodeName; String nodePath; boolean hasChild; ArrayList<TreeNode> childNodes; TreeNode(){ nodeName = null; nodePath = null; hasChild = false; childNodes = new ArrayList<TreeNode>(); } } public class ZkWatcher implements Watcher { //private static CountDownLatch connectedSemaphore = new CountDownLatch(1); @Override public void process(WatchedEvent event) { // TODO Auto-generated method stub if (KeeperState.SyncConnected == event.getState()) { if(isConnectZk == false) { isConnectZk = true; LOG.info("connect zkhost success!"); } } else if(KeeperState.Disconnected == event.getState()) { if(isConnectZk == true) { isConnectZk = false; LOG.info("disconnect from zkhost!"); } } } } /** * @see HttpServlet#HttpServlet() */ public LoadTree() { super(); // TODO Auto-generated constructor stub } //链接 private void zookeeperConnect() { try { if(myzk != null) { myzk.close(); myzk = null; } zkhost = getServletContext().getInitParameter("zkhost"); myzk = new ZooKeeper(zkhost, 3000, new ZkWatcher()); int wait = 500; while(wait-- > 0 && !isConnectZk) { Thread.sleep(10); } LOG.info("connect to zkhost: " + zkhost); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); myzk = null; LOG.error("Close connect to zkhost: " + zkhost + " error[" + e.getMessage() + "]"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); myzk = null; LOG.error("connect to zkhost: " + zkhost + " error[" + e.getMessage() + "]"); } } private boolean createConfig(String curpath, String filename, StringBuffer result) { boolean ret = true; String cPath = ""; List<String> cfgInfo = Common.readLines(webRealPath+"/files/import.conf"); if(cfgInfo.isEmpty()) { result.reverse(); result.append("config file is empty"); return false; } Map<Integer,String> mainPath = new HashMap<Integer,String>(); for(String line : cfgInfo) { line = line.trim(); if(line.isEmpty()) continue; if(line.startsWith("#")) { int num = Common.getFlagNum(line); for(int i=num; i<=mainPath.size(); i++) { mainPath.remove(i); } String tpath = ""; if(num == 1) { String rootName = curpath; if(curpath.equals("/")) { rootName = "/"; } else { int idx = curpath.lastIndexOf("/"); if(idx >= 0) { rootName = curpath.substring(idx + 1, curpath.length()); } } LOG.info("line: "+line.replace("#", "")+ " rootName: "+rootName); if(!line.replace("#", "").equals(rootName)) { result.reverse(); result.append("root path is not match"); ret = false; break; } tpath = curpath; } else { String pPath = mainPath.get(num-1); if(pPath == null || pPath.equals("")) { result.reverse(); result.append("path node is not inorder"); ret = false; break; } if(pPath.equals("/")) { tpath = pPath+line.replace("#", ""); } else { tpath = pPath + "/" + line.replace("#", ""); } try { if(myzk.exists(tpath, false) == null) { String data = "1"; myzk.create(tpath,data.getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); } } catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); result.reverse(); result.append("createConfig: " + tpath + " error: "+e.getMessage()); LOG.error("createConfig " + tpath + " KeeperException: "+e.getMessage()); ret = false; break; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); result.reverse(); result.append("createConfig " + tpath + " error: "+e.getMessage()); LOG.error("createConfig " + tpath + " InterruptedException: "+e.getMessage()); ret = false; break; } } if(!tpath.equals("")) { mainPath.put(num, tpath); } cPath = tpath; } else { String[] kv = line.split("=", 2); if(kv.length != 2) continue; String tpath = ""; if(cPath.equals("/")) { tpath = cPath + kv[0].trim(); } else { tpath = cPath + "/" + kv[0].trim(); } try { if(myzk.exists(tpath, false) == null) { myzk.create(tpath,kv[1].trim().getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); } else { myzk.setData(tpath,kv[1].trim().getBytes(),-1); } } catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); result.reverse(); result.append("createConfig: " + tpath + " error: "+e.getMessage()); LOG.error("createConfig " + tpath + " KeeperException: "+e.getMessage()); ret = false; break; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); result.reverse(); result.append("createConfig " + tpath + " error: "+e.getMessage()); LOG.error("createConfig " + tpath + " InterruptedException: "+e.getMessage()); ret = false; break; } } } return ret; } private boolean getSubNode(TreeNode node) throws IOException { boolean retEnd = false; try { Stat stat = new Stat(); myzk.getData(node.nodePath, new ZkWatcher(), stat); if(stat.getNumChildren() > 0) { node.hasChild = true; List<String> result = myzk.getChildren(node.nodePath, false); if(result.size() > 0) { ArrayList<TreeNode> ret = new ArrayList<TreeNode>(); for(int i=0; i<result.size(); i++) { TreeNode tmp = new TreeNode(); tmp.nodeName = result.get(i); if(node.nodePath.equals("/")) { tmp.nodePath = node.nodePath + result.get(i); } else { tmp.nodePath = node.nodePath + "/" + result.get(i); } getSubNode(tmp); ret.add(tmp); } node.childNodes = ret; } } else { node.hasChild = false; node.childNodes = new ArrayList<TreeNode>();; } retEnd = true; } catch (KeeperException e) { // TODO Auto-generated catch block throw new IOException(e); } catch (InterruptedException e) { // TODO Auto-generated catch block throw new IOException(e); } return retEnd; } private String getConfig(String curpath, int index) throws IOException { String result = ""; try { Stat stat = new Stat(); byte[] data = myzk.getData(curpath, new ZkWatcher(), stat); if(stat.getNumChildren() == 0) { String nodename = curpath; int idx = nodename.lastIndexOf("/"); if(idx != 0) { nodename = nodename.substring(idx + 1, nodename.length()); } result += nodename+" = "+new String(data) + "<br/>"; } else { String nodename = curpath; int idx = nodename.lastIndexOf("/"); if(!nodename.equals("/")) { nodename = nodename.substring(idx + 1, nodename.length()); } result += "<br/>"; for(int i=0; i<=index; i++) { result += "#"; } result += nodename + "<br/>"; index++; List<String> ret = myzk.getChildren(curpath, false); for(int i=0; i<ret.size(); i++) { String tmppath = ""; if(curpath.equals("/")) { tmppath = curpath + ret.get(i); } else { tmppath = curpath + "/" + ret.get(i); } result += getConfig(tmppath,index); } } }catch (KeeperException e) { // TODO Auto-generated catch block throw new IOException(e); } catch (InterruptedException e) { // TODO Auto-generated catch block throw new IOException(e); } catch (IOException e) { throw new IOException(e); } return result; } private void delSubNode(String curpath) throws IOException { try { Stat stat = myzk.exists(curpath,false); if(stat != null) { if(stat.getNumChildren() != 0) { List<String> ret = myzk.getChildren(curpath, false); for(int i=0; i<ret.size(); i++) { String tmppath = ""; if(curpath.equals("/")) { tmppath = curpath + ret.get(i); } else { tmppath = curpath + "/" + ret.get(i); } delSubNode(tmppath); } } myzk.delete(curpath,-1); } else { LOG.info("stat is null : "+curpath); } }catch (KeeperException e) { // TODO Auto-generated catch block throw new IOException(e); } catch (InterruptedException e) { // TODO Auto-generated catch block throw new IOException(e); } catch (IOException e) { throw new IOException(e); } } private static TreeNode getcurNode(TreeNode jsobj,String nodename) { TreeNode retobj = null; if(jsobj.nodeName.equals(nodename)) retobj = jsobj; else { ArrayList<TreeNode> jsarr = jsobj.childNodes; if(jsarr != null) { for(int i=0; i<jsarr.size(); i++) { TreeNode tobj = jsarr.get(i); if(tobj.nodeName.equals(nodename)) { retobj = tobj; break; } } } } return retobj; } private static TreeNode getTreeNode(TreeNode node,String path,int type) { String[] patharray = path.split("/"); TreeNode tobj = node; TreeNode pnode = node; for(int i=0; i<patharray.length; i++) { if(patharray[i].equals("")) continue; pnode = tobj; tobj = getcurNode(pnode,patharray[i]); if(tobj == null) break; } if(type == 2) tobj = pnode; return tobj; } private void loadTree(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String resultstr = ""; String curpath = request.getParameter("curpath").trim(); LOG.info("curpath: "+curpath); try { TreeNode root = new TreeNode(); root.nodeName = curpath; root.nodePath = curpath; Stat stat = new Stat(); myzk.getData(curpath, new ZkWatcher(), stat); if(stat.getNumChildren() > 0) { root.hasChild = true; List<String> result = myzk.getChildren(curpath, false); if(result.size() > 0) { ArrayList<TreeNode> ret = new ArrayList<TreeNode>(); for(int i=0; i<result.size(); i++) { TreeNode tmp = new TreeNode(); tmp.nodeName = result.get(i); if(root.nodePath.equals("/")) { tmp.nodePath = root.nodePath + result.get(i); } else { tmp.nodePath = root.nodePath + "/" + result.get(i); } getSubNode(tmp); ret.add(tmp); } root.childNodes = ret; } } else { root.hasChild = false; root.childNodes = new ArrayList<TreeNode>(); } resultstr = gson.toJson(root); } catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); LOG.error("loadTree KeeperException: "+e.getMessage()); resultstr = "loadTree KeeperException: "+e.getMessage(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); LOG.error("loadTree InterruptedException: "+e.getMessage()); resultstr = "loadTree InterruptedException: "+e.getMessage(); } catch (IOException e) { e.printStackTrace(); LOG.error("loadTree IOException: "+e.getMessage()); resultstr = "loadTree IOException: "+e.getMessage(); } response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); PrintWriter out = response.getWriter(); out.append(URLEncoder.encode(resultstr,"UTF-8")); out.flush(); out.close(); } private void getData(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String curpath = request.getParameter("curpath").trim(); LOG.info("curpath: "+curpath); String result = ""; try { Stat stat = new Stat(); byte[] data = myzk.getData(curpath, new ZkWatcher(), stat); result += "<ul>\n"; if(data != null) { result += "<li style='word-wrap:break-word;'>data = "+new String(data)+"</li>"; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); //result += "<li>cZxid = "+stat.getCzxid()+"</li>"; Date createData = new Date(stat.getCtime()); result += "<li>ctime = "+sdf.format(createData)+"</li>"; //result += "<li>mZxid = "+stat.getMzxid()+"</li>"; Date modData = new Date(stat.getMtime()); result += "<li>mtime = "+sdf.format(modData)+"</li>"; //result += "<li>pZxid = "+stat.getPzxid()+"</li>"; //result += "<li>cversion = "+stat.getCversion()+"</li>"; result += "<li>dataVersion = "+stat.getVersion()+"</li>"; //result += "<li>aclVersion = "+stat.getAversion()+"</li>"; //result += "<li>ephemeralOwner = "+stat.getEphemeralOwner()+"</li>"; result += "<li>dataLength = "+stat.getDataLength()+"</li>"; result += "<li>numChildren = "+stat.getNumChildren()+"</li></ul>"; result += "<text style='word-break:keep-all;white-space:nowrap;'><===========SUBNODE CONFIG===========><br/>"; int index = 0; result += getConfig(curpath,index)+"</text>"; }catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); result += "<h1>get "+curpath+" data is error: "+e.getMessage()+"</h1>"; LOG.error("getData KeeperException: "+e.getMessage()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); result += "<h1>get "+curpath+" data is error: "+e.getMessage()+"</h1>"; LOG.error("getData InterruptedException: "+e.getMessage()); } catch (IOException e) { e.printStackTrace(); result += "<h1>get "+curpath+" data is error: "+e.getMessage()+"</h1>"; LOG.error("getData IOException: "+e.getMessage()); } response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); PrintWriter out = response.getWriter(); out.append(URLEncoder.encode(result,"UTF-8")); out.flush(); out.close(); } private void addNode(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String curpath = request.getParameter("curpath").trim(); String nodename = request.getParameter("nodename").trim(); String nodedata = request.getParameter("nodedata").trim(); BufferedReader br = request.getReader(); String str, treelist = ""; while((str = br.readLine()) != null){ treelist += str; } treelist = URLDecoder.decode(treelist,"UTF-8").trim(); String resultstr = treelist; LOG.info("curpath: "+curpath); LOG.info("nodename: "+nodename); LOG.info("nodedata: "+nodedata); //LOG.info("treelist: "+treelist); try { Stat stat = new Stat(); myzk.getData(curpath, new ZkWatcher(), stat); TreeNode tree = gson.fromJson(treelist, TreeNode.class); TreeNode parantNode = getTreeNode(tree,curpath,1); ArrayList<TreeNode> childs = parantNode.childNodes; String newpath = ""; if(curpath.equals("/")) { newpath = curpath + nodename; } else { newpath = curpath + "/" + nodename; } newpath = myzk.create(newpath,nodedata.getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); TreeNode newNode = new TreeNode(); newNode.nodeName = nodename; newNode.nodePath = newpath; newNode.hasChild = false; childs.add(newNode); parantNode.hasChild = true; resultstr = gson.toJson(tree); }catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); resultstr = "addNode error: "+e.getMessage(); LOG.error("addNode KeeperException: "+e.getMessage()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); resultstr = "addNode error: "+e.getMessage(); LOG.error("addNode InterruptedException: "+e.getMessage()); } response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); PrintWriter out = response.getWriter(); out.append(resultstr); out.flush(); out.close(); } private void delNode(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String curpath = request.getParameter("curpath").trim(); BufferedReader br = request.getReader(); String str, treelist = ""; while((str = br.readLine()) != null){ treelist += str; } treelist = URLDecoder.decode(treelist,"UTF-8").trim(); String resultstr = treelist; LOG.info("curpath: "+curpath); try { Stat stat = myzk.exists(curpath, false); if(stat != null) { if(curpath.equals("/") || curpath.equals("")) { resultstr = "can not del: "+curpath; } else if(stat.getNumChildren() > 0) { delSubNode(curpath); resultstr = "del "+ curpath +" is over"; } else { TreeNode tree = gson.fromJson(treelist, TreeNode.class); TreeNode parantNode = getTreeNode(tree,curpath,2); ArrayList<TreeNode> childs = parantNode.childNodes; myzk.delete(curpath,-1); String[] patharray = curpath.split("/"); for(int i=0; i<childs.size(); i++) { if(childs.get(i).nodeName.equals(patharray[patharray.length-1])) { childs.remove(i); break; } } if(childs.size() > 0) { parantNode.hasChild = false; } resultstr = gson.toJson(tree); } } else { resultstr = "path: "+curpath+ " is not exists"; LOG.error("delNode path: "+curpath+ " is not exists"); } }catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); resultstr = "delNode error: "+e.getMessage(); LOG.error("delNode KeeperException: "+e.getMessage()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); resultstr = "delNode error: "+e.getMessage(); LOG.error("delNode InterruptedException: "+e.getMessage()); } response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); PrintWriter out = response.getWriter(); out.append(URLEncoder.encode(resultstr,"UTF-8")); out.flush(); out.close(); } private void setNode(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String curpath = request.getParameter("curpath").trim(); BufferedReader br = request.getReader(); String str, nodedata = ""; while((str = br.readLine()) != null){ nodedata += str; } nodedata = URLDecoder.decode(nodedata,"UTF-8").trim(); LOG.info("curpath: "+curpath); LOG.info("nodedata: "+nodedata); response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); PrintWriter out = response.getWriter(); String result = ""; try { myzk.setData(curpath,nodedata.getBytes(),-1); Stat stat = new Stat(); byte[] data = myzk.getData(curpath, new ZkWatcher(), stat); result += "<ul>\n"; if(data != null) { result += "<li>data = "+new String(data)+"</li>"; } result += "<li>cZxid = "+stat.getCzxid()+"</li>\n"; result += "<li>ctime = "+stat.getCtime()+"</li>\n"; result += "<li>mZxid = "+stat.getMzxid()+"</li>\n"; result += "<li>mtime = "+stat.getMtime()+"</li>\n"; result += "<li>pZxid = "+stat.getPzxid()+"</li>\n"; result += "<li>cversion = "+stat.getCversion()+"</li>\n"; result += "<li>dataVersion = "+stat.getVersion()+"</li>\n"; result += "<li>aclVersion = "+stat.getAversion()+"</li>\n"; result += "<li>ephemeralOwner = "+stat.getEphemeralOwner()+"</li>\n"; result += "<li>dataLength = "+stat.getDataLength()+"</li>\n"; result += "<li>numChildren = "+stat.getNumChildren()+"</li>\n"; result += "</ul>\n"; }catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); result += "<h1>get "+curpath+" data is error: "+e.getMessage()+"</h1>"; LOG.error("setNode KeeperException: "+e.getMessage()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); result += "<h1>get "+curpath+" data is error: "+e.getMessage()+"</h1>"; LOG.error("setNode InterruptedException: "+e.getMessage()); } out.append(URLEncoder.encode(result,"UTF-8")); out.flush(); out.close(); } private void importFile(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { StringBuffer result = new StringBuffer(); String curpath = request.getParameter("curpath").trim(); LOG.info("import curpath : "+curpath); ServletFileUpload fileUpload = new ServletFileUpload(); FileItemIterator iter = null; FileItemStream item = null; InputStream is = null; try { iter = fileUpload.getItemIterator(request); while (iter.hasNext()){ item = iter.next();//获取文件流 if(!item.isFormField()){ //这里主要针对图片来写的,因为我用到的是转成图片,获取图片属性。 is = item.openStream(); if(is.available()>0){ BufferedInputStream fileIn = new BufferedInputStream(is); byte[] buf = new byte[1024]; File fOut = new File(webRealPath+"/files/import.conf"); BufferedOutputStream fileOut = new BufferedOutputStream(new FileOutputStream(fOut)); while (true) { // 读取数据 int bytesIn = fileIn.read(buf, 0, 1024); if (bytesIn == -1) { break; } else { fileOut.write(buf, 0, bytesIn); } } fileIn.close(); fileOut.flush(); fileOut.close(); LOG.info("upload file: " + fOut.getAbsolutePath() +" Over"); result.reverse(); result.append("import file upload OK"); break; } } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); result.reverse(); result.append("upload file error: "+e.getMessage()); } if(!createConfig(curpath, webRealPath+"/files/import.conf", result)) { LOG.error("createConfig error: " + result); } response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); PrintWriter out = response.getWriter(); out.append(URLEncoder.encode(result.toString(),"UTF-8")); out.flush(); out.close(); } private void exportFile(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String curpath = request.getParameter("curpath").trim(); int index = 0; String result = null; try{ result = getConfig(curpath,index); if(result == null || result.equals("")) { LOG.warn("export File is null"); result = "export File is null"; } else { result = result.replace("<br/>","\r\n"); File fOut = new File(webRealPath+"/files/export.conf"); FileWriter fileWriter = new FileWriter(fOut); fileWriter.write(result); fileWriter.close(); // 关闭数据流 if(fOut.exists()){ FileInputStream fis = new FileInputStream(fOut); String filename=URLEncoder.encode(fOut.getName(),"utf-8"); //解决中文文件名下载后乱码的问题 byte[] b = new byte[fis.available()]; fis.read(b); response.setCharacterEncoding("utf-8"); response.setContentLength((int) fOut.length()); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment; filename="+filename+""); //获取响应报文输出流对象 ServletOutputStream out = response.getOutputStream(); //输出 out.write(b); out.flush(); out.close(); fis.close(); LOG.info("export File is success"); return; } else { LOG.warn("export File is not exist"); result = "export File is not exist"; } } } catch (IOException e) { e.printStackTrace(); LOG.error("exportFile IOException: "+e.getMessage()); result = "exportFile IOException: "+e.getMessage(); } response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); PrintWriter out = response.getWriter(); out.append(URLEncoder.encode(result,"UTF-8")); out.flush(); out.close(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String func = request.getParameter("func").trim(); LOG.info("get doGet, func = "+ func); if(func == null) { response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); PrintWriter out = response.getWriter(); LOG.error("doGet func is null!"); out.append(URLEncoder.encode("<h1>404, NOT FOUND!</h1>","UTF-8")); out.flush(); out.close(); return; } if(!isConnectZk) { zookeeperConnect(); } if(func.equals("loadtree")) { loadTree(request,response); } else if(func.equals("getdata")) { getData(request,response); } else if(func.equals("addnode")) { addNode(request,response); } else if(func.equals("delnode")) { delNode(request,response); } else if(func.equals("setnode")) { setNode(request,response); } else if(func.equals("uploadfile")) { importFile(request,response); } else if(func.equals("downloadfile")) { exportFile(request,response); } else { response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); PrintWriter out = response.getWriter(); out.append(URLEncoder.encode("<alter>func is not access!</alter>","UTF-8")); LOG.error("doGet func is not access!"); out.flush(); out.close(); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub LOG.info("get loadtree doPost"); doGet(req, resp); } @Override public void destroy() { // TODO Auto-generated method stub try { if(myzk != null) { myzk.close(); myzk = null; } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } LOG.info("servlet is stoped!!"); super.destroy(); } @Override public void init() throws ServletException { // TODO Auto-generated method stub super.init(); webRealPath = getServletContext().getRealPath("/"); logConfig = webRealPath+"/"+getServletContext().getInitParameter("logConfig"); // log4j配置 PropertyConfigurator.configure(logConfig); try { InputStream input = getServletContext().getResourceAsStream(relativeWARPath); Manifest mainfest; mainfest = new Manifest(input); String version = mainfest.getMainAttributes().getValue(VERSIONNAME); LOG.info("configStation Version : V"+version); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); LOG.error("Can't get Version from: "+relativeWARPath); } LOG.info("logPath: " + logConfig); zookeeperConnect(); } public static void main(String args[]) { String str = "/"; int idx = str.lastIndexOf("/"); str = str.substring(idx + 1, str.length()); System.out.println(str); long ti = 1511939860088L; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date d = new Date(ti); System.out.println("format time : "+sdf.format(d)); /*Gson gson = new Gson(); TreeNode treelist = gson.fromJson("{'nodeName':'/','nodePath':'/','childNodes':[{'nodeName':'data','nodePath':'/data','childNodes':[]}]}", TreeNode.class); String curpath = "/"; String nodename = "mia"; TreeNode parantNode = getTreeNode(treelist,curpath,2); String newpath = ""; if(curpath.equals("/")) { newpath = curpath + nodename; } else { newpath = curpath + "/" + nodename; } //newpath = myzk.create(newpath,nodedata.getBytes(),Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); TreeNode newNode = new TreeNode(); newNode.nodeName = nodename; newNode.nodePath = newpath; newNode.hasChild = false; if(parantNode != null) parantNode.childNodes.add(newNode); String json = gson.toJson(treelist); System.out.println("TreeNode: "+json);*/ } }
Markdown
UTF-8
1,752
2.65625
3
[]
no_license
--- layout: post category : thoughts tagline: "It is manageable!" tags : [visualized, loopy, management] title: Customer satisfaction and developer stress visualized --- {% include JB/setup %} Here is a causal loop diagram showing a model relating customer satisfaction to developer stress. It is taken (and slightly modified) from "How Software is Built" [[Weinberg, 2014]]. Use the up and down arrows in the nodes in the model to: * Decrease customer satisfaction a bit; * Make the developer stress level a lot lower; * Increase quality reality. <iframe width="700" height="440" frameborder="0" src="{% include loopy_url %}?embed=1&data=[[[11,270,490,0.5,%22Customer%2520Satisfaction%22,3],[12,664,469,0.5,%22...%2520Functions%22,4],[13,842,464,0.5,%22...%2520Schedule%22,4],[14,749,318,0.5,%22Workload%22,4],[15,200,110,0.5,%22Quality%2520Reality%22,4],[16,752,110,0.5,%22Developer%2520Stress%22,0],[17,375,107,0.5,%22Schedule%2520Reality%22,4],[18,274,299,0.5,%22System%2520Quality%22,3]],[[11,12,130,-1,0],[11,13,-58,-1,0],[16,17,94,-1,0],[16,15,-60,-1,0],[15,18,-16,1,0],[17,18,17,1,0],[18,11,-2,1,0],[12,14,46,1,0],[13,14,-26,1,0],[14,16,-3,1,0]],[[464,458,%22Let%2520us%2520pressure%2520the%2520developers%250Awith%2520respect%2520to%2520...%22],[556,132,%22Let's%2520pretend%2520we%2520%250Acan%2520deliver%2520fast%250Awith%2520same%2520quality.%22]],18%5D"></iframe> What happens when we make the schedule match reality a bit more? Why not add a little pressure on the developers? What can you do as a manager to make this a more healthy system? Any structural changes? Could adapting to Scrum help? {% include on-causal-loops.md %} --- [loopy]: http://ncase.me/loopy/ [Weinberg, 2014]: https://leanpub.com/howsoftwareisbuilt
Rust
UTF-8
1,275
3.5625
4
[]
no_license
fn main(){ let mut a = 2i32; let b = &mut a; //let c = b; //c,move occurs because `b` has type `&mut i32`,这里是模式匹配,转移所有权 let c:&mut i32 = &mut (*b); //编译通过,种种迹象表明这里是借用b也是借用*b //let c = &mut (*b); //println!("{:p}",&b);//cannot borrow `b` as immutable because it is also borrowed as mutable //*b = 1; *c = 3;//种种迹象表明,c含着b的引用 println!("{:p}",&b); *b = 5; /*let b = &a; let c = b;//编译通过*/ //println!("{:p},{:p}",&b,&c);//cannot assign to `*b` because it is borrowed println!("{}",a); //println!("{}",c);//cannot borrow `b` as immutable because it is also borrowed as mutable //cannot assign to `*b` because it is borrowed //唯一解释的通的就是 let mut a = 2i32; let b = &mut a; println!("{:p}",b); let c = b; println!("{:p}",c); let mut a = 2i32; let b = &mut a; println!("{:p}",b); let c:&mut i32 = b; println!("{:p}",c); let mut a = 2; let b = &mut a; //let c = b; //这里值move给了c 这里是模式匹配,下面是赋值? let c:&mut i32 = b;//说明啥,:不单单是类型说明 println!("{}",b);//虽然这里不能同时输出c,b }
Java
UTF-8
2,842
2.328125
2
[]
no_license
package com.ting.androidexample.ui.activities; import android.app.Activity; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.os.Bundle; import android.telephony.SmsManager; import android.util.Log; public class PendingIntentActivity extends Activity { private static final String TAG = "PendingIntentActivity"; //获得发送报告 private static final String SENT_SMS_ACTION = "com.baidu.sumeru.SENT_SMS_ACTION"; //获得接收报告 private static final String DELIVERY_SMS_ACTION = "com.baidu.sumeru.DELIVERY_SMS_ACTION"; //接收短信 private static final String RECEIVE_SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED"; private BroadcastReceiver mSmsReceiver = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); createReceiver(this); SmsManager smsManager = SmsManager.getDefault(); Intent intent = new Intent(SENT_SMS_ACTION); intent.putExtra("uri", "content://intent/test"); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); smsManager.sendTextMessage("13811200985", null, "test", pendingIntent, null); Intent intent1 = new Intent(SENT_SMS_ACTION); intent.putExtra("uri", "content://intent/testtest"); PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this, 0, intent1, 0); smsManager.sendTextMessage("13811200985", null, "testtest", pendingIntent1, null); } private void createReceiver(Context context) { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(SENT_SMS_ACTION); intentFilter.addAction(DELIVERY_SMS_ACTION); intentFilter.addAction(RECEIVE_SMS_ACTION); intentFilter.setPriority(1000); mSmsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "action:" + action); if(action.equals(SENT_SMS_ACTION)) { //接收到发送报告 Log.d(TAG, "sms is sent by " + intent.getStringExtra("uri")); } else if (action.equals(DELIVERY_SMS_ACTION)) { //表示对方成功收到短信 Log.d(TAG, "sms is deliveried by " + intent.getStringExtra("uri")); } else if (action.equals(RECEIVE_SMS_ACTION)) { //接收到短信后处理 Log.d(TAG, "receive sms!"); } } }; context.registerReceiver(mSmsReceiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mSmsReceiver); } }
Java
UTF-8
593
2.09375
2
[]
no_license
package tests; import base.BaseUtil; import org.testng.annotations.Test; import pages.LoginPage; import utils.RetryAnalyzer; import static org.testng.AssertJUnit.assertTrue; /** * Created by Gadotey on 2/25/2020 */ public class LoginPageTest extends BaseUtil { //RetryAnalyzer will make the test run again in case if fails @Test(retryAnalyzer = RetryAnalyzer.class) public void testing() { LoginPage logPage = new LoginPage(driver); logPage.Username1("Admin"); logPage.Password("Admin123"); assertTrue(logPage.isOnResuiltPage()); } }
Shell
UTF-8
2,001
2.546875
3
[ "MIT" ]
permissive
echo "------------------------------------------------------------------------------------------------------" echo " BEGIN: tensorflow_compile.sh" echo "------------------------------------------------------------------------------------------------------" echo "------------------------------------------------------------------------------------------------------" echo " --- Compiling Tensorflow for Python 2 whell" echo "------------------------------------------------------------------------------------------------------" cd ${disk_mnt_point}/tmp/ git clone --branch r1.13 --single-branch https://github.com/tensorflow/tensorflow.git cd tensorflow git checkout tags/v1.13.0-rc0 cp ${disk_mnt_point}/tmp/tf_bazel_config.p2 ${disk_mnt_point}/tmp/tensorflow/.tf_configure.bazelrc echo -e "export PYTHON_BIN_PATH=\"/usr/bin/python\"" > ./tools/python_bin_path.sh bazel build --config=opt --config=cuda --config=mkl --verbose_failures //tensorflow/tools/pip_package:build_pip_package ./bazel-bin/tensorflow/tools/pip_package/build_pip_package ${disk_mnt_point}/tmp/ echo "------------------------------------------------------------------------------------------------------" echo " --- Compiling Tensorflow for Python 3 whell" echo "------------------------------------------------------------------------------------------------------" cd ${disk_mnt_point}/tmp/ cd tensorflow cp ${disk_mnt_point}/tmp/tf_bazel_config.p3 ${disk_mnt_point}/tmp/tensorflow/.tf_configure.bazelrc echo -e "export PYTHON_BIN_PATH=\"/usr/bin/python3\"" > ./tools/python_bin_path.sh bazel build --config=opt --config=cuda --config=mkl --verbose_failures //tensorflow/tools/pip_package:build_pip_package ./bazel-bin/tensorflow/tools/pip_package/build_pip_package ${disk_mnt_point}/tmp/ pip install ${disk_mnt_point}/tmp/tensorflow*cp2*.whl pip3 install ${disk_mnt_point}/tmp/tensorflow*cp3*.whl echo " END: tensorflow_compile.sh --------------------------------------------------------------------------"
Python
UTF-8
10,819
2.515625
3
[]
no_license
from clean_tweet import clean from keras.utils import to_categorical from keras.models import Sequential from keras.models import Model from keras.layers import Dense, Dropout, Embedding, LSTM, Input, Conv2D, MaxPooling2D, Bidirectional, Reshape, Flatten from keras.layers.merge import concatenate from keras.preprocessing.text import Tokenizer from keras.preprocessing import sequence from keras.callbacks import EarlyStopping from keras.models import load_model import numpy as np from numpy import array from numpy import asarray from numpy import zeros import os import pandas as pd import re from wordcloud import STOPWORDS #All Text Cleaning Credit: Gunes Evitan #Ty sir, this is alot of hours you have saved me and others train = pd.read_csv('./../data/train.csv') test = pd.read_csv('./../data/test.csv') #shuffle and reset index state = 24 train_df = train.sample(frac=1,random_state=state) test_df = test.sample(frac=1,random_state=state) train_df.reset_index(inplace=True, drop=True) test_df.reset_index(inplace=True, drop=True) #cleaning def preprocessor2(text): text = text.replace('%20',' ') emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)',text) text = (re.sub('[^a-zA-Z0-9_]+', ' ', text.lower()) + ' '.join(emoticons).replace('-', '')) return text #more cleaning def remove_url(raw_str): clean_str = re.sub(r'http\S+', '', raw_str) return clean_str #more cleaning def preprocessor3(text): text = re.sub(r'^washington d c ', "washington dc", text) text = re.sub(r'^washington +[\w]*', "washington dc", text) text = re.sub(r'^new york +[\w]*', "new york", text) text = re.sub(r'^nyc$', "new york", text) text = re.sub(r'^chicago +[\w]*', "chicago", text) text = re.sub(r'^california +[\w]*', "california", text) text = re.sub(r'^los angeles +[\w]*', "los angeles", text) text = re.sub(r'^san francisco +[\w]*', "san francisco", text) text = re.sub(r'^london +[\w]*', "london", text) text = re.sub(r'^usa$', "united states", text) text = re.sub(r'^us$', "united states", text) text = re.sub(r'^uk$', "united kingdom", text) return text #more cleaning def preprocessor4(text): abb = ['ak', 'al', 'az', 'ar', 'ca', 'co', 'ct', 'de', 'dc', 'fl', 'ga', 'hi', 'id', 'il', 'in', 'ia', 'ks', 'ky', 'la', 'me', 'mt', 'ne', 'nv', 'nh', 'nj', 'nm', 'ny', 'nc', 'nd', 'oh', 'ok', 'or', 'md', 'ma', 'mi', 'mn', 'ms', 'mo', 'pa', 'ri', 'sc', 'sd', 'tn', 'tx', 'ut', 'vt', 'va', 'wa', 'wv', 'wi', 'wy'] for i in abb: text = re.sub(r' {0}$'.format(i), '', text) return text train_df['text'] = train_df['text'].apply(lambda x:remove_url(x)) train_df['keyword_cleaned'] = train_df['keyword'].copy().apply(lambda x : clean(str(x))).apply(lambda x : preprocessor2(x)) train_df['location_cleaned'] = train_df['location'].copy().apply(lambda x : clean(str(x))).apply(lambda x : preprocessor2(x)) train_df['text_cleaned'] = train_df['text'].copy().apply(lambda x : clean(x)).apply(lambda x : preprocessor2(x)) test_df['text'] = test_df['text'].apply(lambda x:remove_url(x)) test_df['keyword_cleaned'] = test_df['keyword'].copy().apply(lambda x : clean(str(x))).apply(lambda x : preprocessor2(x)) test_df['location_cleaned'] = test_df['location'].copy().apply(lambda x : clean(str(x))).apply(lambda x : preprocessor2(x)) test_df['text_cleaned'] = test_df['text'].copy().apply(lambda x : clean(x)).apply(lambda x : preprocessor2(x)) print(f'train_df columns: {train_df.columns}') #actually callign as the cleaning functions train_df['location_cleaned'] = train_df['location_cleaned'].copy().apply( lambda x : preprocessor3(x)).apply(lambda x : preprocessor4(x)) train_df['text_cleaned'] = train_df['text_cleaned'].copy().apply( lambda x : preprocessor3(x)).apply(lambda x : preprocessor4(x)) test_df['location_cleaned'] = test_df['location_cleaned'].copy().apply( lambda x : preprocessor3(x)).apply(lambda x : preprocessor4(x)) test_df['text_cleaned'] = test_df['text_cleaned'].copy().apply( lambda x : preprocessor3(x)).apply(lambda x : preprocessor4(x)) #stop words, testing if these help or not stopwords = list(STOPWORDS)+['will','may','one','now','nan','don'] train_df['text_cleaned'] = train_df['text_cleaned'].apply( lambda x: ' '.join([word for word in x.split() if word not in (stopwords)])) test_df['text_cleaned'] = test_df['text_cleaned'].apply( lambda x: ' '.join([word for word in x.split() if word not in (stopwords)])) temp_df1 = list(zip(train_df.target,train_df.keyword_cleaned, train_df.location_cleaned,train_df.text_cleaned)) temp_df2 = list(zip(train_df.target,train_df.keyword_cleaned, train_df.location_cleaned,train_df.text_cleaned)) x = pd.DataFrame(temp_df1, columns = ['target','keyword_cleaned','location_cleaned','text_cleaned']) y = pd.DataFrame(temp_df2, columns = ['target','keyword_cleaned','location_cleaned','text_cleaned']) z = pd.concat([train_df,x,y], axis=0, join='outer', ignore_index=False, keys=None, sort = False) z = z[['id','keyword_cleaned','location_cleaned','text_cleaned','target']].copy() z.reset_index(inplace=True, drop=True) train_df = z test_df = test_df[['id','keyword_cleaned','location_cleaned','text_cleaned']].copy() #Randomization state = 1 train_df = train_df.sample(frac=1,random_state=state) train_df.reset_index(inplace=True, drop=True) #tokenizing, and eventually embedding top_word = 35000 tok = Tokenizer(num_words=top_word) tok.fit_on_texts((train_df['text_cleaned']+train_df['keyword_cleaned']+train_df['location_cleaned'])) text_lengths = [len(x.split()) for x in (train_df.text_cleaned)] max_words = max(text_lengths) + 1 max_words_ky = max([len(x.split()) for x in (train_df.keyword_cleaned)]) + 1 max_words_lc = max([len(x.split()) for x in (train_df.location_cleaned)]) + 1 #Training set val_value = 5000 X_train_tx = tok.texts_to_sequences(train_df['text_cleaned']) X_train_ky = tok.texts_to_sequences(train_df['keyword_cleaned']) X_train_lc = tok.texts_to_sequences(train_df['location_cleaned']) X_test_tx = tok.texts_to_sequences(test_df['text_cleaned']) X_test_ky = tok.texts_to_sequences(test_df['keyword_cleaned']) X_test_lc = tok.texts_to_sequences(test_df['location_cleaned']) #categorical for keras Y_train = train_df['target'] Y_train = to_categorical(Y_train) X_train_tx = sequence.pad_sequences(X_train_tx, maxlen=max_words) X_train_ky = sequence.pad_sequences(X_train_ky, maxlen=max_words_ky) X_train_lc = sequence.pad_sequences(X_train_lc, maxlen=max_words_lc) X_test_tx = sequence.pad_sequences(X_test_tx, maxlen=max_words) X_test_ky = sequence.pad_sequences(X_test_ky, maxlen=max_words_ky) X_test_lc = sequence.pad_sequences(X_test_lc, maxlen=max_words_lc) embeddings_index = dict() f = open(os.path.join('/Users/fariszahrah/Data/glove.twitter.27B/', 'glove.twitter.27B.200d.txt')) for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefs f.close() embedding_dim = 200 embedding_matrix = zeros((top_word, embedding_dim)) for word, index in tok.word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[index] = embedding_vector input1 = Input(shape=(max_words,)) embedding_layer1 = Embedding(top_word, 200, weights=[embedding_matrix], input_length=max_words, trainable=False)(input1) dropout1 = Dropout(0.2)(embedding_layer1) lstm1_1 = LSTM(128,return_sequences = True)(dropout1) lstm1_2 = LSTM(128,return_sequences = True)(lstm1_1) lstm1_2a = LSTM(128,return_sequences = True)(lstm1_2) lstm1_3 = LSTM(128)(lstm1_2a) dropout = Dropout(0.8)(lstm1_3) flat1 = Dense(256, activation='relu')(dropout) print('compiled tweet text layers') input2 = Input(shape=(max_words_ky,)) embedding_layer2 = Embedding(top_word, 200, weights=[embedding_matrix], input_length=max_words_ky, trainable=False)(input2) lstm2_1 = Bidirectional(LSTM(100, return_sequences=True,dropout = 0.2))(embedding_layer2) lstm2_1a = Bidirectional(LSTM(100, return_sequences=True,dropout = 0.2))(lstm2_1) lstm2_1b = Bidirectional(LSTM(100, return_sequences=True,dropout = 0.2))(lstm2_1a) res2 = Reshape((-1, X_train_ky.shape[1], 100))(lstm2_1b) conv2 = Conv2D(100, (3,3), padding='same',activation="relu")(res2) pool2 = MaxPooling2D(pool_size=(2,2))(conv2) flat2 = Flatten()(pool2) input3 = Input(shape=(max_words_lc,)) embedding_layer3 = Embedding(top_word, 200, weights=[embedding_matrix], input_length=max_words_lc, trainable=False)(input3) lstm3_1 = Bidirectional(LSTM(100, return_sequences=True,dropout = 0.2))(embedding_layer3) lstm3_1a = Bidirectional(LSTM(100, return_sequences=True,dropout = 0.2))(lstm3_1) lstm3_1b = Bidirectional(LSTM(100, return_sequences=True,dropout = 0.2))(lstm3_1a) res3 = Reshape((-1, X_train_lc.shape[1], 100))(lstm3_1b) conv3 = Conv2D(100, (3,3), padding='same',activation="relu")(res3) pool3 = MaxPooling2D(pool_size=(2,2))(conv3) flat3 = Flatten()(pool3) merge = concatenate([flat1, flat2, flat3]) dropout = Dropout(0.4)(merge) dense1 = Dense(256, activation='relu')(dropout) dense2 = Dense(128, activation='relu')(dense1) output = Dense(2, activation='softmax')(dense2) model = Model(inputs=[input1,input2,input3], outputs=output) model.summary() model.compile(loss="binary_crossentropy", optimizer="adadelta", metrics=["accuracy"]) es = EarlyStopping(monitor='val_loss', mode='min',verbose=1, patience = 4) history = model.fit([X_train_tx,X_train_ky,X_train_lc], Y_train, validation_split=0.2, epochs=30, batch_size=64, verbose=2, callbacks=[es]) def result_eva (loss,val_loss,acc,val_acc): import matplotlib.pyplot as plt epochs = range(1,len(loss)+1) plt.plot(epochs, loss,'b-o', label ='Training Loss') plt.plot(epochs, val_loss,'r-o', label ='Validation Loss') plt.title("Training and Validation Loss") plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show() epochs = range(1, len(acc)+1) plt.plot(epochs, acc, "b-o", label="Training Acc") plt.plot(epochs, val_acc, "r-o", label="Validation Acc") plt.title("Training and Validation Accuracy") plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend() plt.show() Y_pred = model.predict([X_test_tx,X_test_ky,X_test_lc], batch_size=64, verbose=2) Y_pred = np.argmax(Y_pred,axis=1) pred_df = pd.DataFrame(Y_pred, columns=['target']) result = pd.concat([test_df,pred_df], axis=1, join='outer', ignore_index=False, keys=None, sort = False) result = result[['id','target']] result.to_csv('../submissions/lstm_text_kw_loc_submission.csv',index=False)
Java
UTF-8
1,472
2.75
3
[]
no_license
package edu.byu.cs.familymapserver.databaseTests; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import edu.byu.cs.familymapserver.database.Database; import edu.byu.cs.familymapserver.model.Event; import static org.junit.Assert.assertEquals; /** * Created by christian on 3/7/17. */ public class EventsDAOTest { private Database db; private Event event; private Event event1; private Event event2; private List<Event> events = new ArrayList<>(); @Before public void setUp() throws Exception { db = new Database(); db.openConnection("testdb.sqlite"); db.clear(); event = new Event(); event1 = new Event("pickle","desc","pers",(float)2.0,(float)2.0,"canada","dumbtown","gay","2001"); event2 = new Event("pickle2","desc2","pers2",(float)3.0,(float)3.0,"c@nada","fagville","homo","2003"); events.add(event); events.add(event1); events.add(event2); } @After public void tearDown() throws Exception { db.closeConnection(false); db = null; } @Test public void testAddEvent() throws Exception { System.out.print("Testing EventDAO..."); db.eventDAO.addEvent(event1); db.eventDAO.addEvent(event2); assertEquals(db.eventDAO.getEvent("pickle").getEventID(),event1.getEventID()); System.out.println("PASSED"); } }
JavaScript
UTF-8
1,798
2.53125
3
[]
no_license
module.exports = class TarefasDao { constructor(bancoDados){ this.bancoDados = bancoDados; } listaTarefas(){ return new Promise((resolve,reject)=>{ this.bancoDados.all("SELECT * FROM TAREFAS;", (err, rows)=> { if(err) reject("Erro ao consultar a tabela"); else resolve(rows); }); }); }; insereTarefas(ID,TITULO,DESCRICAO,STATUS,DATACRIACAO,IDUSUARIO){ return new Promise((resolve,reject)=>{ this.bancoDados.run(`INSERT INTO TAREFAS VALUES (?,?,?,?,?,?)`,[ID,TITULO,DESCRICAO,STATUS,DATACRIACAO,IDUSUARIO], (err,rows)=>{ if(err) reject(`Erro ao inserir tarefa: ${err}`); else resolve(rows); }) }); }; buscaTarefa(STATUS){ return new Promise((resolve,reject)=>{ this.bancoDados.all(`SELECT * FROM TAREFAS WHERE STATUS = (?) ;`,[STATUS], (err, rows)=> { if(err) reject("Erro ao consultar a tabela"); else resolve(rows); }); }); }; deletaTarefa(TITULO){ return new Promise((resolve,reject)=>{ this.bancoDados.run(`DELETE FROM TAREFAS WHERE TITULO = (?);`,[TITULO], (err, rows)=> { if(err) reject("Erro ao consultar a tabela"); else resolve(rows); }); }); }; atualizaTarefa(STATUS,ID){ return new Promise((resolve,reject)=>{ this.bancoDados.run(`UPDATE TAREFAS SET STATUS = (?) WHERE ID = (?)`,[STATUS,ID], (err, rows)=> { if(err) reject("Erro ao consultar a tabela"); else resolve(rows); }); }); } }
Python
UTF-8
698
3.3125
3
[]
no_license
import time import ordenamiento_burbuja as ob import random as r import ordenamiento_insercion as oi lista = [] for i in range (1200): lista.append (r.randint(1,10000)) listaCopia = lista.copy () listaCopia2 = lista.copy () #Inicio Burbuja inicio = time.time() #Instrucciones ob.ordenamientoBurbuja (lista) #Delta deltaOb = time.time () - inicio #Inicio Sort inicio = time.time() #Instrucciones listaCopia.sort () #Delta deltaSort = time.time() - inicio #Inicio Insercion inicio = time.time() #Instrucciones oi.ordenamientoInsercion (lista) #Delta deltaOi = time.time () - inicio print (deltaSort) print (deltaOb) print (deltaOi) print (deltaSort >= deltaOb) print (deltaSort >= deltaOb)
Rust
UTF-8
827
3.546875
4
[ "WTFPL" ]
permissive
fn grade(a: u32, b: u32, c: u32) -> String { let mean = (a + b + c) / 3; let letter = match dbg!(mean) { _ if (90..=100).contains(&mean) => "A", _ if (80..90).contains(&mean) => "B", _ if (70..80).contains(&mean) => "C", _ if (60..70).contains(&mean) => "D", _ if (0..60).contains(&mean) => "F", _ => unreachable!("mean ({}) can't be < 0", mean), }; let sign = if mean % 10 < 5 { "-" } else { "+" }; format!("{}{}", letter, sign) } #[cfg(test)] mod tests { use super::*; #[test] fn test_grade_c_minus() { assert_eq!("C-", grade(64, 55, 92)); } #[test] fn test_grade_a_minus() { assert_eq!("A-", grade(99, 89, 93)); } #[test] fn test_grade_c_plus() { assert_eq!("C+", grade(33, 99, 95)); } }
Java
UTF-8
1,174
2.4375
2
[]
no_license
package com.qa.orangeHRM.dataprovider; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.testng.annotations.DataProvider; import com.qa.orangeHRM.config.gblConstants; public class DataProviders { public static XSSFWorkbook book; public static XSSFSheet sheet; public static XSSFRow row; public static XSSFCell cell; @DataProvider public Object[][] EmpDetails() throws IOException { //Read the data from Excel File file= new File(gblConstants.URL); FileInputStream fis = new FileInputStream(file); book = new XSSFWorkbook(fis); sheet = book.getSheet("Data"); int rowcount = sheet.getLastRowNum(); int colcount = sheet.getRow(1).getLastCellNum(); Object[][] empdata = new Object[rowcount][colcount]; for(int i=1;i<=rowcount;i++) { row = sheet.getRow(i); for(int j=0;j<colcount;j++) { cell =row.getCell(j); empdata[i-1][j]= cell.getStringCellValue(); } } return empdata; } }
Java
UTF-8
629
2.578125
3
[]
no_license
package Model.GameObject.Item.Items.Takables; import Model.Effects.Effect; import Model.GameObject.Item.Items.Takable; import Model.Location; import Model.Requirement; /** * Created by Wimberley on 2/25/16. */ // A usable item can be added to the inventory and used at some point during the game. // this item inherits all attributes and methods from Takable and Item public class Usable extends Takable { public Usable(int id, String name, String description, int value, Location location, Requirement requirement, Effect effect) { super(id, name, description, value, location, requirement, effect); } }
Java
UTF-8
2,169
2.359375
2
[]
no_license
package com.cilamp; import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GuiSpike extends JFrame { private static final long serialVersionUID = -8849927121852293707L; public GuiSpike() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { super("Gui Spike"); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.setSize(300, 200); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); Container mainPanel = this.getContentPane(); mainPanel.setLayout(new BorderLayout()); JPanel northPanel = new JPanel(); JPanel centerPanel = new JPanel(); mainPanel.add(northPanel, BorderLayout.NORTH); mainPanel.add(centerPanel, BorderLayout.CENTER); JLabel appTitle = new JLabel("<html><b>Continuous Integration Lamp"); northPanel.add(appTitle); centerPanel.setLayout(new BorderLayout()); JPanel actionsPanel = new JPanel(); JPanel buildStatusPanel = new JPanel(); centerPanel.add(actionsPanel, BorderLayout.NORTH); centerPanel.add(buildStatusPanel, BorderLayout.CENTER); actionsPanel.setBorder(BorderFactory.createTitledBorder("Actions")); actionsPanel.add(new JButton("Build FAILED"), BorderLayout.NORTH); actionsPanel.add(new JButton("Build SUCCESS")); buildStatusPanel.setLayout(new GridLayout(1, 1)); buildStatusPanel .setBorder(BorderFactory.createTitledBorder("Build Status")); JLabel lastBuild = new JLabel("Last build: Successfull"); lastBuild.setVerticalAlignment(JLabel.TOP); buildStatusPanel.add(lastBuild); this.setVisible(true); } public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { new GuiSpike(); } }
TypeScript
UTF-8
959
2.6875
3
[ "MIT" ]
permissive
import { DefinitionBuilder } from '../src/definitionBuilder'; import { Hl7Message } from '../src/models/hl7message.model'; import { Element } from '../src/models/element.model'; describe("Definition Builder", () => { let definitionBuilder = new DefinitionBuilder(); it("Should throw error if no hl7Message is provided", () =>{ expect(() => {definitionBuilder.addDefinitionToHl7Message(null)}).toThrow( new Error("hl7Message is not provided or incorrect hl7Message is provided")); }); it("Should add definition to hl7Message", () =>{ let hl7Message = new Hl7Message(); hl7Message.children = Array<Element>(); hl7Message.children[0] = new Element("ACC-1", "11/20/2017"); definitionBuilder.addDefinitionToHl7Message(hl7Message); expect(hl7Message.children[0].definition.description).toBe("Accident Date/Time"); expect(hl7Message.children[0].definition.length).toBe(24); }); })
Java
UTF-8
16,332
2.75
3
[]
no_license
package ecs.impl; import ecs.HashRing; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import com.google.gson.reflect.TypeToken; import ecs.ECSNode; import ecs.IECSNode; import java.lang.reflect.Type; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import static ecs.IECSNode.ECSNodeFlag.*; public class HashRingImpl extends HashRing { /** * For serialization/deserialization purposes */ private Type ringType = new TypeToken<TreeMap<Hash, ECSNode>>() {}.getType(); private Type serversType = new TypeToken<Map<String, ECSNode>>() {}.getType(); private Gson HASH_RING_GSON = new GsonBuilder() .enableComplexMapKeySerialization() .excludeFieldsWithoutExposeAnnotation() .create(); private class SerializedHashRing { @Expose String serializedRing; @Expose String serializedServers; } public HashRingImpl() { super( new TreeMap<Hash, ECSNode>(), new HashMap<String, ECSNode>() ); } /** * Works like a findAndRemove function, except on the list of servers * in the HashRing. * <p> * Example: The following predicate function would return all * servers in the HashRing with serverStatusType == 'STOPPED'. * * <pre> * HashRing.filterServer( * (KVServerMetadata server) -> { * return server.serverStatusType == 'STOPPED' * } * ); * </pre> * * @param pred A predicate. If return true, then the evaluating * object is included in the output list. * @return A list of filtered KVServerMetadata. */ @Override public List<ECSNode> filterServer(Predicate<ECSNode> pred) { List<ECSNode> result = new ArrayList<>(); ECSNode server; for (Map.Entry<String, ECSNode> entry : servers.entrySet()) { server = entry.getValue(); if (pred.test(server)) { result.add(server); } } return result; } @Override public void forEachServer(Consumer<ECSNode> consumer) { for (Map.Entry<String, ECSNode> entry : servers.entrySet()) { consumer.accept(entry.getValue()); } } @Override public ECSNode findServer(Predicate<ECSNode> pred) { ECSNode server; for (Map.Entry<String, ECSNode> entry : servers.entrySet()) { server = entry.getValue(); if (pred.test(server)) { return server; } } return null; } @Override public int getNumServersOnRing() { return ring.size(); } @Override public int getNumServers() { return servers.size(); } @Override public int getNumActiveServers() { return filterServer( node -> !node.getEcsNodeFlag().equals(SHUT_DOWN) && !node.getEcsNodeFlag().equals(IDLE) ).size(); } /** * {@link #getServerByHash(Hash)} * Gets nearest server -> traverse HashRing in CW order. * {@link #getServerByName(String)} * Gets server by its server name * {@link #getServerByObjectKey(String)} * Hashes objectKey using MD5, then takes the computed hash * and gets nearest server traversing CW order around HashRing * * @param hash */ @Override public ECSNode getServerByHash(Hash hash) { ECSNode ecsNode = ring.get(hash); Map.Entry<Hash, ECSNode> entry; if (Objects.isNull(ecsNode)) { entry = ring.higherEntry(hash); /* * Check wrap-around (ring) logic. If the hash presented is * greater than any entry in the ring, then wrap-around * to the first entry. Else, return the immediately greater * ECSNode following the hash position. */ if (Objects.nonNull(entry)) { ecsNode = entry.getValue(); } else if (ring.size() > 0) { entry = ring.firstEntry(); assert(Objects.nonNull(entry)); ecsNode = entry.getValue(); } else { ecsNode = null; } } return ecsNode; } @Override public ECSNode getServerByName(String serverName) { return servers.get(serverName); } @Override public ECSNode getServerByObjectKey(String objectKey) { Hash hash = new Hash(objectKey); return getServerByHash(hash); } /** * {@link #removeServerByHash(Hash)} * Remove the server at the exact position of the hash. * Note that this is contrary to {@link #getServerByHash(Hash)}, * where the hash matches with the nearest server. * {@link #removeServerByName(String)} * Removes the server by its server name * {@link #addServer(ECSNode)} * Computes the hash for the server, then adds the server * to the HashRing according to ascending hash order. * * @param hash */ @Override public void removeServerByHash(Hash hash) { ECSNode server = ring.get(hash); if (Objects.isNull(server)) { return; } removeServer(server); } @Override public void removeServerByName(String serverName) { ECSNode server = servers.get(serverName); if (Objects.isNull(server)) { return; } removeServer(server); } @Override public void removeServer(ECSNode server) { server.setEcsNodeFlag(START_STOP); } @Override public void shutdownServer(ECSNode server) { server.setEcsNodeFlag(START_SHUT_DOWN); } @Override public void addServer(ECSNode server) { ECSNode _server = servers.get(server.getNodeName()); if (Objects.nonNull(_server)) { return; } servers.put(server.getNodeName(), server); } private void recomputeHashRanges() { ECSNode server; Iterator<Map.Entry<Hash, ECSNode>> it = ring.entrySet().iterator(); while (it.hasNext()) { server = it.next().getValue(); HashRange range = getServerHashRange(server); assert(Objects.nonNull(range)); server.setNodeHashRange(range.toArray()); } } @Override public void updateRing() { /* * Step 1: * (a) Add all ECSNode's that are in IDLE_START state * to hashRing * (b) Set ECSNode state to START * (c) After all is done, recompute the hashRange of * every server in the HashRing */ { ECSNode server; Iterator<Map.Entry<String, ECSNode>> it = servers.entrySet().iterator(); IECSNode.ECSNodeFlag flag; Hash hash; while (it.hasNext()) { server = it.next().getValue(); flag = server.getEcsNodeFlag(); if (flag.equals(IECSNode.ECSNodeFlag.IDLE_START)) { /* IMPORTANT: put to ring */ hash = new Hash(server.getUuid()); ring.put(hash, server); } } recomputeHashRanges(); } /* * Step 2: * (a) Remove all ECSNode's that are in START_STOP state * from hashRing (do not touch the servers) * (b) Set ECSNode state to STOP * (c) After all is done, recompute the hash ranges * of all servers in the HashRing. */ { ECSNode server; Iterator<Map.Entry<String, ECSNode>> it = servers.entrySet().iterator(); IECSNode.ECSNodeFlag flag; while (it.hasNext()) { server = it.next().getValue(); flag = server.getEcsNodeFlag(); if (flag.equals(START_STOP) || flag.equals(START_SHUT_DOWN)) { /* IMPORTANT: remove from ring */ ECSNode removed = ring.remove(new Hash(server.getUuid())); if (flag.equals(START_STOP)) { server.setEcsNodeFlag(STOP); } else { server.setEcsNodeFlag(SHUT_DOWN); } server.setNodeHashRange(null); assert(removed.getUuid().equals(server.getUuid())); } } recomputeHashRanges(); } } /** * {@link #getSuccessorServer(ECSNode)} * Gets the server immediately succeeding the current * server in the HashRing (look "ahead of" the current server) * {@link #getPredecessorServer(ECSNode)} * Gets the server immediately preceding the current * server in the HashRing (look "behind" the current server) * * @param server */ @Override public ECSNode getSuccessorServer(ECSNode server) { Hash hash = new Hash(server.getUuid()); assert(ring.get(hash).getNodeName().equals(server.getNodeName())); /* * There are 3 cases: * (1) Current server is the largest server in the ring * -> Wrap-around * (2) Current server is the only server in the ring * -> No successor * (3) Current server is in the "middle" (or smallest) of the ring * -> Return successor */ ECSNode successor; Map.Entry<Hash, ECSNode> entry = ring.higherEntry(hash); if (Objects.isNull(entry)) { // (1) if (ring.size() > 1) { entry = ring.firstEntry(); successor = entry.getValue(); assert(!successor.getNodeName().equals(server.getNodeName())); } // (2) else { assert(ring.size() == 1); successor = null; } } // (3) else { successor = entry.getValue(); } return successor; } @Override public ECSNode getPredecessorServer(ECSNode server) { Hash hash = new Hash(server.getUuid()); assert(ring.get(hash).getNodeName().equals(server.getNodeName())); /* * There are 3 cases: * (1) Current server is the smallest server in the ring * -> Wrap-around * (2) Current server is the only server in the ring * -> No predecessor * (3) Current server is in the "middle" (or largest) in the ring * -> Return predecessor */ ECSNode predecessor; Map.Entry<Hash, ECSNode> entry = ring.lowerEntry(hash); if (Objects.isNull(entry)) { // (1) if (ring.size() > 1) { entry = ring.lastEntry(); predecessor = entry.getValue(); assert(!predecessor.getNodeName().equals(server.getNodeName())); } // (2) else { assert(ring.size() == 1); predecessor = null; } } // (3) else { predecessor = entry.getValue(); } return predecessor; } @Override public List<ECSNode> getReplicas(ECSNode server) { List<ECSNode> replicas = new ArrayList<>(); ECSNode replica; /* * Only supports 2 replicas by convention. */ Function<ECSNode, ECSNode> getReplica = s -> { ECSNode _s = s; do { _s = getSuccessorServer(_s); } while (_s.isRecovering() && !_s.isSameServer(s)); return !_s.isSameServer(s) ? _s : null; }; if (Objects.nonNull(replica = getReplica.apply(server))) { replicas.add(replica); if (Objects.nonNull(replica = getReplica.apply(replica))) { replicas.add(replica); } } return replicas; } /** * {@link #getServerHashRange(ECSNode)} * Gets the HashRange for the specified server given * the server object * {@link #getServerHashRange(String)} * Gets the HashRange for the specified server given * the name of the server * * @param server */ @Override public HashRange getServerHashRange(ECSNode server) { ECSNode predecessor = getPredecessorServer(server); if (Objects.isNull(predecessor)) { predecessor = server; } Hash lower = new Hash(predecessor.getUuid()); Hash upper = new Hash(server.getUuid()); return new HashRange(lower, upper); } @Override public HashRange getServerHashRange(String serverName) { ECSNode server = getServerByName(serverName); if (Objects.isNull(server)) { return null; } return getServerHashRange(server); } /** * {@link #serialize()} * Serializes this class so that it can be passed through the * network. * {@link #deserialize(String)} * Deserializes this class. First create an empty instance, then * call this function with the JSON string. This will populate * HashRing by deserializing the data in the JSON. */ @Override public String serialize() { SerializedHashRing serialized = new SerializedHashRing(); serialized.serializedRing = HASH_RING_GSON.toJson(this.getRing()); serialized.serializedServers = HASH_RING_GSON.toJson(this.getServers()); String str = HASH_RING_GSON.toJson(serialized); return Base64.getEncoder().encodeToString(str.getBytes()); } @Override public HashRing deserialize(String b64str) { String json = new String(Base64.getDecoder().decode(b64str)); SerializedHashRing serialized = HASH_RING_GSON.fromJson( json, SerializedHashRing.class ); this.ring = HASH_RING_GSON.fromJson(serialized.serializedRing, ringType); this.servers = HASH_RING_GSON.fromJson(serialized.serializedServers, serversType); return this; } @Override public TreeMap<Hash, ECSNode> getRing() { return this.ring; } @Override public Map<String, IECSNode> getServers() { Map<String, IECSNode> serversCpy = new HashMap<>(); for (Map.Entry<String, ECSNode> entry : this.servers.entrySet()) { serversCpy.put(entry.getKey(), entry.getValue()); } return serversCpy; } @Override public void print() { StringBuilder sb = new StringBuilder(); sb.append("=============HASH-RING================\n"); { Iterator<Map.Entry<Hash, ECSNode>> it = ring.entrySet().iterator(); Map.Entry<Hash, ECSNode> entry; ECSNode ecsNode; String[] hashRange; Hash hash; int i = 0; while (it.hasNext()) { entry = it.next(); hash = entry.getKey(); ecsNode = entry.getValue(); hashRange = ecsNode.getNodeHashRange(); sb.append(String.format("%3d: %s: %s => %s | RANGE=%s | %s\n", i, ecsNode.getNodeName(), ecsNode.getUuid(), hash.toHexString(), new HashRange(hashRange).toString(), ecsNode.getEcsNodeFlag()) ); i++; } } sb.append("=============ALL-SERVERS============\n"); { Iterator<Map.Entry<String, ECSNode>> it = servers.entrySet().iterator(); Map.Entry<String, ECSNode> entry; ECSNode ecsNode; while (it.hasNext()) { entry = it.next(); ecsNode = entry.getValue(); sb.append(String.format("%s: %s => %s | %s\n", ecsNode.getNodeName(), ecsNode.getUuid(), new Hash(ecsNode.getUuid()).toHexString(), ecsNode.getEcsNodeFlag()) ); } } System.out.print(sb.toString()); } }
C#
UTF-8
1,426
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json; namespace fun_bank_api_client.ApiClient.Models { public class Customer : Model { [JsonProperty("Hash")] public string Hash; [JsonProperty("username", Required = Required.Always)] public string Username; [JsonProperty("password", Required = Required.Always)] public string PasswordHash; [JsonProperty("name")] public CustomerName Name; [JsonProperty("dateOfBirth")] public long DateOfBirthMS; public DateTime DateOfBirth { get { return new DateTime(1970, 1, 1).AddMilliseconds(Convert.ToDouble(DateOfBirthMS)); } } [JsonProperty("address")] public CustomerAddress Address; } public class CustomerName { [JsonProperty("first")] public string First; [JsonProperty("last")] public string Last; } public class CustomerAddress { [JsonProperty("country")] public string Country; [JsonProperty("city")] public string City; [JsonProperty("postcode")] public string Postcode; [JsonProperty("street")] public string Street; [JsonProperty("houseNumber")] public string HouseNumber; } }
PHP
UTF-8
2,593
2.8125
3
[ "MIT" ]
permissive
<?php namespace Blade\Orm\Test\Model; use Blade\Orm\Model; use Blade\Orm\Value\DateTime; class TransformSettersTestModel extends Model { protected $allowGetterMagic = true; protected $transformers = [ 'colTrimSetter' => 'trim', 'colObjectSetter' => DateTime::class, ]; protected $forceSetters = [ 'colTrimSetter' => 'setValue', 'colObjectSetter' => 'setObject', ]; public function setValue($value) { $this->_set_update('colTrimSetter', $value . '123'); } public function setObject(DateTime $value) { $value = clone $value; $value->modify('+1 day'); $this->_set_update('colObjectSetter', $value); } } /** * Работа трансформеров вместе с сеттерами + конструктор * * @see Model */ class TransformSettersTest extends \PHPUnit\Framework\TestCase { /** * Одноверменный вызов трансформера и сеттера */ public function testTransformerWithSetterCall() { $m = new TransformSettersTestModel; $this->assertTrue($m->set('colTrimSetter', ' val '), 'Значение было изменено'); $this->assertSame('val123', $m->colTrimSetter, 'trim transformer + 123 with setter'); $this->assertTrue($m->isModified('colTrimSetter')); // Вызов через конструктор $m = new TransformSettersTestModel([ 'colTrimSetter' => ' val ', ]); $this->assertSame('val123', $m->colTrimSetter, 'trim transformer + 123 with setter'); $this->assertTrue($m->isModified('colTrimSetter')); } /** * Передача объекта */ public function testObject() { $origValue = new DateTime(); $m = new TransformSettersTestModel; $this->assertTrue($m->set('colObjectSetter', $origValue), 'Значение было изменено'); $this->assertEquals($origValue->modify('+1 day'), $m->colObjectSetter, 'transformer + setter'); $this->assertTrue($m->isModified('colObjectSetter')); // Вызов через конструктор $m = new TransformSettersTestModel([ 'colObjectSetter' => new DateTime, ]); $this->assertInstanceOf(DateTime::class, $m->colObjectSetter); $this->assertEquals(date_create('+1 day')->format(DATE_ISO8601), $m->colObjectSetter->format(DATE_ISO8601), 'transformer + setter'); $this->assertTrue($m->isModified('colObjectSetter')); } }
JavaScript
UTF-8
1,037
2.78125
3
[]
no_license
const fs = require('fs'); const listarEstInscritos = (listaEstInscritos) => { let texto = ''; if (listaEstInscritos != null && Object.keys(listaEstInscritos).length != 0) { texto = texto + "<table class='table table-striped'>"+ "<thead class='thead-dark'>"+ "<th>Documento</th>"+ "<th>Nombre</th>"+ "<th>Correo</th>"+ "<th>Telefono</th>"+ "<th>Eliminar</th>"+ "</thead>"+ "<tbody>"; listaEstInscritos.forEach(inscrito => { texto = texto + '<tr>'+ '<td>'+ inscrito.documento + '</td>' + '<td>'+ inscrito.nombre + '</td>' + '<td>'+ inscrito.correo + '</td>' + '<td>'+ inscrito.telefono + '</td>'+ "<td><a href='/eliminar?documento="+ inscrito.documento +"&id_curso="+ inscrito.id_curso +"' class='btn btn-danger' role='button' aria-pressed='true'>Eliminar</a></td>"+ '</tr>'; }); texto = texto + "</tbody> </table>"; } else { texto = "<div class='alert alert-warning' role='alert'>No hay inscritos</div>"; } return texto; }; module.exports = { listarEstInscritos }
Ruby
UTF-8
1,052
2.640625
3
[ "Apache-2.0" ]
permissive
module Categories CHRISTIAN = "stuff" COMEDY = "comedy" CONCERT = "concert" CONFERENCES = "conferences" COUPLES = "couples" DANCE = "dance" EXHIBITS = "exhibits" FAMILY = "family" FESTIVALS = "festivals" GALLERIES = "galleries" JEWISH = "jewish" LATE_NIGHT = "late_night" LGBT = "lgbt" MARKETS = "markets" MUSLIM = "muslim" OPENINGS = "openings" READINGS = "readings" SINGLES = "singles" SPORTS = "sports" THEATRE = "theatre" TOURS = "tours" def self.all [ Categories::CHRISTIAN, Categories::COMEDY, Categories::CONCERT, Categories::CONFERENCES, Categories::COUPLES, Categories::DANCE, Categories::EXHIBITS, Categories::FAMILY, Categories::FESTIVALS, Categories::GALLERIES, Categories::JEWISH, Categories::LATE_NIGHT, Categories::LGBT, Categories::MARKETS, Categories::MUSLIM, Categories::OPENINGS, Categories::READINGS, Categories::SINGLES, Categories::SPORTS, Categories::THEATRE, Categories::TOURS, ].sort end end
C#
UTF-8
26,773
2.65625
3
[]
no_license
using Newtonsoft.Json; using System.Collections.Generic; using System.Text; using System; using System.IO; namespace LinnworksAPI { public class ProcessedOrdersController : BaseController, IProcessedOrdersController { public ProcessedOrdersController(ApiContext apiContext) : base(apiContext) { } /// <summary> /// Use this call to add a new note to an order /// </summary> /// <param name="pkOrderID">The order id</param> /// <param name="noteText">The note text</param> /// <param name="isInternal">True if the note should be internal, False if it shouldn't</param> /// <returns>The id of the new note</returns> public Guid AddOrderNote(Guid pkOrderID,String noteText,Boolean isInternal) { var response = GetResponse("ProcessedOrders/AddOrderNote", "pkOrderID=" + pkOrderID + "&noteText=" + System.Net.WebUtility.UrlEncode(noteText) + "&isInternal=" + isInternal + ""); return JsonFormatter.ConvertFromJson<Guid>(response); } /// <summary> /// Use this call to add a new return category. /// </summary> /// <param name="categoryName">The name of the category to add.</param> /// <returns>A return category object containing details of the new category.</returns> public OrderReturnCategory AddReturnCategory(String categoryName) { var response = GetResponse("ProcessedOrders/AddReturnCategory", "categoryName=" + System.Net.WebUtility.UrlEncode(categoryName) + ""); return JsonFormatter.ConvertFromJson<OrderReturnCategory>(response); } /// <summary> /// Edit an existing order note /// </summary> /// <param name="pkOrderNoteId">Primary key for order note</param> /// <param name="noteText">New note message</param> /// <param name="isInternal">Whether the note is an internal note</param> /// <param name="noteTypeId">Set the type of note</param> public void ChangeOrderNote(Guid pkOrderNoteId,String noteText,Boolean isInternal,Byte? noteTypeId = null) { GetResponse("ProcessedOrders/ChangeOrderNote", "pkOrderNoteId=" + pkOrderNoteId + "&noteText=" + System.Net.WebUtility.UrlEncode(noteText) + "&isInternal=" + isInternal + "&noteTypeId=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(noteTypeId)) + ""); } /// <summary> /// Checks if order was fully returned /// </summary> /// <param name="pkOrderId">Primary key for an order</param> public Boolean CheckOrderFullyReturned(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/CheckOrderFullyReturned", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<Boolean>(response); } /// <param name="pkOrderId">The order id</param> /// <param name="exchangeItems">A list of items to be exchanged, including quantity, scrap, refund, etc.</param> /// <param name="despatchLocation">The id of the location to despatch replacement items from</param> /// <param name="returnLocation">The id of the location to return stock to</param> /// <param name="channelReason">Channel reason - required if a refund on the channel is required</param> /// <param name="channelSubReason">Channel subreason - required if a refund on the channel is required.</param> /// <param name="category">The refund category</param> /// <param name="reason">The reason for the reason</param> /// <param name="isBooking">True if it is a exchange booking, False if it is a new exchange</param> /// <param name="ignoredValidation">True if failed validation has been ignored (see IsRefundValid). Otherwise, false. When set to true, refunds will not be automatically actioned on the channel. Ignored if creating a booking as a refund is not created at this stage.</param> /// <returns>Returns information about the new exchanges</returns> public List<ReturnInfo> CreateExchange(Guid pkOrderId,List<RowQty> exchangeItems,Guid despatchLocation,Guid returnLocation,String channelReason,String channelSubReason,String category,String reason,Boolean isBooking,Boolean ignoredValidation) { var response = GetResponse("ProcessedOrders/CreateExchange", "pkOrderId=" + pkOrderId + "&exchangeItems=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(exchangeItems)) + "&despatchLocation=" + despatchLocation + "&returnLocation=" + returnLocation + "&channelReason=" + System.Net.WebUtility.UrlEncode(channelReason) + "&channelSubReason=" + System.Net.WebUtility.UrlEncode(channelSubReason) + "&category=" + System.Net.WebUtility.UrlEncode(category) + "&reason=" + System.Net.WebUtility.UrlEncode(reason) + "&isBooking=" + isBooking + "&ignoredValidation=" + ignoredValidation + ""); return JsonFormatter.ConvertFromJson<List<ReturnInfo>>(response); } public List<ReturnInfo> CreateFullResend(Guid pkOrderId,Guid despatchLocation,String category,String reason,Double additionalCost) { var response = GetResponse("ProcessedOrders/CreateFullResend", "pkOrderId=" + pkOrderId + "&despatchLocation=" + despatchLocation + "&category=" + System.Net.WebUtility.UrlEncode(category) + "&reason=" + System.Net.WebUtility.UrlEncode(reason) + "&additionalCost=" + additionalCost + ""); return JsonFormatter.ConvertFromJson<List<ReturnInfo>>(response); } /// <summary> /// Creates a resend /// </summary> /// <param name="pkOrderId">Order ID that needs to be resend</param> /// <param name="resendItems">Resend items information</param> /// <param name="despatchLocation">Location ID where from resend be despatched</param> /// <param name="category">Category</param> /// <param name="reason">Resond reason</param> /// <param name="additionalCost">Order-level additional cost</param> public List<ReturnInfo> CreateResend(Guid pkOrderId,List<RowQty> resendItems,Guid despatchLocation,String category,String reason,Double additionalCost) { var response = GetResponse("ProcessedOrders/CreateResend", "pkOrderId=" + pkOrderId + "&resendItems=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(resendItems)) + "&despatchLocation=" + despatchLocation + "&category=" + System.Net.WebUtility.UrlEncode(category) + "&reason=" + System.Net.WebUtility.UrlEncode(reason) + "&additionalCost=" + additionalCost + ""); return JsonFormatter.ConvertFromJson<List<ReturnInfo>>(response); } /// <summary> /// Use this call to create a new return /// </summary> /// <param name="pkOrderId">The order id</param> /// <param name="returnitems">A list of items to be returned, including quantity, scrap, refund, etc.</param> /// <param name="returnLocation">The id of the location to return stock to</param> /// <param name="channelReason">Channel reason - required if a refund on the channel is required</param> /// <param name="channelSubReason">Channel subreason - required if a refund on the channel is required.</param> /// <param name="category">The refund category</param> /// <param name="reason">The reason for the reason</param> /// <param name="isReturnBooking">True if it is a return booking, False if it is a new return</param> /// <param name="ignoredValidation">True if failed validation has been ignored (see IsRefundValid). Otherwise, false. When set to true, refunds will not be automatically actioned on the channel. Ignored if creating a booking as a refund is not created at this stage.</param> /// <returns>Returns information about the new returns</returns> public List<ReturnInfo> CreateReturn(Guid pkOrderId,List<RowQty> returnitems,Guid returnLocation,String channelReason,String channelSubReason,String category,String reason,Boolean isReturnBooking,Boolean ignoredValidation) { var response = GetResponse("ProcessedOrders/CreateReturn", "pkOrderId=" + pkOrderId + "&returnitems=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(returnitems)) + "&returnLocation=" + returnLocation + "&channelReason=" + System.Net.WebUtility.UrlEncode(channelReason) + "&channelSubReason=" + System.Net.WebUtility.UrlEncode(channelSubReason) + "&category=" + System.Net.WebUtility.UrlEncode(category) + "&reason=" + System.Net.WebUtility.UrlEncode(reason) + "&isReturnBooking=" + isReturnBooking + "&ignoredValidation=" + ignoredValidation + ""); return JsonFormatter.ConvertFromJson<List<ReturnInfo>>(response); } /// <summary> /// Delete an existing order note /// </summary> /// <param name="pkOrderNoteId">Primary key for order note</param> public void DeleteOrderNote(Guid pkOrderNoteId) { GetResponse("ProcessedOrders/DeleteOrderNote", "pkOrderNoteId=" + pkOrderNoteId + ""); } /// <summary> /// Use this call to delete an existing return category. /// </summary> /// <param name="pkItemId">The id of the category to delete.</param> public void DeleteReturnCategory(Int32 pkItemId) { GetResponse("ProcessedOrders/DeleteReturnCategory", "pkItemId=" + pkItemId + ""); } /// <summary> /// Download Processed Orders to CSV /// </summary> /// <param name="request">Request parameter populated with search criteria for the file download</param> /// <param name="cancellationToken">Request parameter populated with search criteria for the file download</param> public DownloadOrdersToCSVResponse DownloadOrdersToCSV(DownloadOrdersToCSVRequest request) { var response = GetResponse("ProcessedOrders/DownloadOrdersToCSV", "request=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(request)) + ""); return JsonFormatter.ConvertFromJson<DownloadOrdersToCSVResponse>(response); } /// <summary> /// Use this call to get a list of valid channel refund reasons for a given order. These are needed for channel refunds. /// </summary> /// <param name="pkOrderId">The order id to get reasons for</param> /// <returns>A list of reasons and subreasons. Null if channel refunds have not been implemented for the order's channel.</returns> public List<ChannelRefundReason> GetChannelRefundReasons(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetChannelRefundReasons", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<ChannelRefundReason>>(response); } /// <summary> /// Use this call to retrieve detailed information about a processed order (header level). /// </summary> /// <param name="pkOrderId">The id of the order.</param> /// <returns>Detailed order information</returns> public ProcessedOrderWeb GetOrderInfo(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetOrderInfo", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<ProcessedOrderWeb>(response); } /// <summary> /// Use this call to retrieve detailed TrackingURL for orders Vendor and TrackingNumber. /// </summary> /// <param name="request">The request for TrackingURL.</param> /// <returns>Tracking information</returns> public GetOrderTrackingURLsResponse GetOrderTrackingURLs(GetOrderTrackingURLsRequest request) { var response = GetResponse("ProcessedOrders/GetOrderTrackingURLs", "request=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(request)) + ""); return JsonFormatter.ConvertFromJson<GetOrderTrackingURLsResponse>(response); } /// <summary> /// Use this call to get split packaging information for an order /// </summary> /// <param name="pkOrderId">The order id</param> /// <returns>A list of items and their corresponding bins</returns> public List<SplitPackaging> GetPackageSplit(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetPackageSplit", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<SplitPackaging>>(response); } /// <summary> /// Use this call to get an order's audit trail information /// </summary> /// <param name="pkOrderId">The order id</param> /// <returns>A list of audit entries</returns> public List<AuditEntry> GetProcessedAuditTrail(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetProcessedAuditTrail", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<AuditEntry>>(response); } /// <summary> /// Use this call to retrieve a list of order-level extended properties. /// </summary> /// <param name="pkOrderId">The order id</param> /// <returns>A list of extended properties and their values</returns> public List<OrderExtendedProperty> GetProcessedOrderExtendedProperties(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetProcessedOrderExtendedProperties", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<OrderExtendedProperty>>(response); } /// <summary> /// Use this call to get a list of order notes for a given order /// </summary> /// <param name="pkOrderId">The order id</param> /// <returns>List of order notes</returns> public List<ProcessedOrderNote> GetProcessedOrderNotes(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetProcessedOrderNotes", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<ProcessedOrderNote>>(response); } /// <summary> /// Use this call to get a list of related orders. /// </summary> /// <param name="pkOrderId">The order id</param> /// <returns>A list of related orders</returns> public List<ProcessedOrderRelation> GetProcessedRelatives(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetProcessedRelatives", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<ProcessedOrderRelation>>(response); } /// <summary> /// Use this call to get a list of service items which can be refunded. /// </summary> /// <param name="pkOrderId">The id of the order which the service items belong to.</param> /// <returns>A list of service items which can be refunded</returns> public List<ServiceItem> GetRefundableServiceItems(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetRefundableServiceItems", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<ServiceItem>>(response); } /// <summary> /// Gets all refund order items for an order /// </summary> /// <param name="pkOrderId">Primary key for order</param> /// <returns>List of refund order items</returns> public List<RefundInfo> GetRefunds(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetRefunds", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<RefundInfo>>(response); } /// <summary> /// Use this call to get information about manual/automated refunds (which kinds of refunds are possible) for a given order. /// </summary> /// <param name="pkOrderId">The id of the order</param> /// <returns>Refund information</returns> public RefundScreenOptions GetRefundsOptions(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetRefundsOptions", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<RefundScreenOptions>(response); } /// <summary> /// Use this call to retrieve a list of return categories. Used for refunds, resends and exchanges. /// </summary> /// <returns>A list of return categories.</returns> public List<OrderReturnCategory> GetReturnCategories() { var response = GetResponse("ProcessedOrders/GetReturnCategories", ""); return JsonFormatter.ConvertFromJson<List<OrderReturnCategory>>(response); } /// <summary> /// Use this call to get a list of all items on an order, including return quantities and resend quantities. The information can be used to calculate how many items has already been returned. /// </summary> /// <param name="pkOrderId">The order id to get the returns for</param> /// <returns>A list of items including returns/resends</returns> public List<OrderItemReturnInfo> GetReturnItemsInfo(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetReturnItemsInfo", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<OrderItemReturnInfo>>(response); } /// <summary> /// Use this call to get basic information about a processed order (e.g. source, subsource, address) as seen on the Returns/Refunds screens. /// </summary> /// <param name="pkOrderId">The id of the order.</param> /// <param name="includeRefundLink">Is a refund link required (not available for all channels).</param> /// <returns>Basic order information</returns> public ReturnOrderHeader GetReturnOrderInfo(Guid pkOrderId,Boolean includeRefundLink) { var response = GetResponse("ProcessedOrders/GetReturnOrderInfo", "pkOrderId=" + pkOrderId + "&includeRefundLink=" + includeRefundLink + ""); return JsonFormatter.ConvertFromJson<ReturnOrderHeader>(response); } /// <summary> /// Use this call to get a basic list of returns, exchanges and resends for an order. /// </summary> /// <param name="pkOrderId">The order id to get the returns for</param> /// <returns>A list of returns</returns> public List<ReturnInfo> GetReturnsExchanges(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/GetReturnsExchanges", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<ReturnInfo>>(response); } /// <summary> /// Use this call to retrieve the total value of refunds against an order. /// </summary> /// <param name="pkOrderId">The id of the order</param> /// <param name="includeBookings">If true, pending refunds against return bookings and exchange bookings will be included. (Optional, default is false.)</param> /// <returns>Returns the total refund amount as retrieved based on the parameters.</returns> public ExistingRefundTotal GetTotalRefunds(Guid pkOrderId,Boolean? includeBookings = null) { var response = GetResponse("ProcessedOrders/GetTotalRefunds", "pkOrderId=" + pkOrderId + "&includeBookings=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(includeBookings)) + ""); return JsonFormatter.ConvertFromJson<ExistingRefundTotal>(response); } /// <summary> /// Use this call to determine if the refunds in a given return set are valid. /// </summary> /// <param name="pkOrderId">The id of the order to validate the refund with</param> /// <param name="refundItems">The refund rows</param> /// <returns>The validation result and, if provided, additional information</returns> public ValidationResult IsRefundValid(Guid pkOrderId,List<RefundItem> refundItems) { var response = GetResponse("ProcessedOrders/IsRefundValid", "pkOrderId=" + pkOrderId + "&refundItems=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(refundItems)) + ""); return JsonFormatter.ConvertFromJson<ValidationResult>(response); } /// <summary> /// Use this call to determine if validation of refunds or returns/exchanges with refund components is required for a given order. /// </summary> /// <param name="pkOrderId">The order id of the order which requires validation</param> /// <returns>True if validation is required, false if it is not.</returns> public Boolean IsRefundValidationRequiredByOrderId(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/IsRefundValidationRequiredByOrderId", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<Boolean>(response); } /// <summary> /// Use this call to update pending manual refunds to the actioned state. /// </summary> /// <param name="pkOrderId">The id of the order to action refunds on.</param> public void MarkManualRefundsAsActioned(Guid pkOrderId) { GetResponse("ProcessedOrders/MarkManualRefundsAsActioned", "pkOrderId=" + pkOrderId + ""); } /// <summary> /// Use this call to add or update a free text refund. This method can also be used to change the refund amount for any pending manual refund. Please check any automated refunds are valid prior to calling this method. /// </summary> /// <param name="pkOrderId">The id of the order to add/update refunds for</param> /// <param name="refundItems">The new/altered refund items</param> /// <returns>Any new/modified refund rows</returns> public List<RefundInfo> RefundFreeText(Guid pkOrderId,List<RefundItem> refundItems) { var response = GetResponse("ProcessedOrders/RefundFreeText", "pkOrderId=" + pkOrderId + "&refundItems=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(refundItems)) + ""); return JsonFormatter.ConvertFromJson<List<RefundInfo>>(response); } /// <summary> /// Use this call to refund one or more services on an order. Please check that any automated refunds are valid prior to calling this method. /// </summary> /// <param name="pkOrderId">The id of the order to refund services for.</param> /// <param name="refundItems">Refunds for service items</param> /// <returns>A list of new refunds</returns> public List<RefundInfo> RefundServices(Guid pkOrderId,List<RefundItem> refundItems) { var response = GetResponse("ProcessedOrders/RefundServices", "pkOrderId=" + pkOrderId + "&refundItems=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(refundItems)) + ""); return JsonFormatter.ConvertFromJson<List<RefundInfo>>(response); } /// <summary> /// Use this call to refund shipping for an order. Please check the refund options to ensure that a shipping refund is possible. /// </summary> /// <param name="pkOrderId">The id of the order whose shipping needs to be refunded</param> /// <returns>The new refund row</returns> public List<RefundInfo> RefundShipping(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/RefundShipping", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<List<RefundInfo>>(response); } /// <summary> /// Use this call to rename an existing return category. /// </summary> /// <param name="pkItemId">The id of the category to be renamed.</param> /// <param name="newName">The new name for the category.</param> public void RenameReturnCategory(Int32 pkItemId,String newName) { GetResponse("ProcessedOrders/RenameReturnCategory", "pkItemId=" + pkItemId + "&newName=" + System.Net.WebUtility.UrlEncode(newName) + ""); } /// <summary> /// Search Processed Orders /// </summary> /// <param name="request">Search parameters consisting of keyword, dates, filters and sorting.</param> /// <param name="cancellationToken"></param> /// <returns>Paged list of processed orders.</returns> public SearchProcessedOrdersResponse SearchProcessedOrders(SearchProcessedOrdersRequest request) { var response = GetResponse("ProcessedOrders/SearchProcessedOrders", "request=" + System.Net.WebUtility.UrlEncode(JsonFormatter.ConvertToJson(request)) + ""); return JsonFormatter.ConvertFromJson<SearchProcessedOrdersResponse>(response); } /// <summary> /// Use this call to search for processed orders. /// </summary> /// <param name="from">The lower end of the date range to search. Can be null if searching for 'all dates'. Maximum range is 3 months.</param> /// <param name="to">The upper end of the date range to search. Can be null if searching for 'all dates'. Maximum range is 3 months.</param> /// <param name="dateType">The search type (e.g. ALLDATES)</param> /// <param name="searchField">The field to search by. Can be found by calling GetSearchTypes.</param> /// <param name="exactMatch">Set to true if an exact match is required for the search data.</param> /// <param name="searchTerm">The term which you are searching for.</param> /// <param name="pageNum">The page number of the request.</param> /// <param name="numEntriesPerPage">The number of entries required on a page. Maximum 200.</param> /// <returns>Returns the requested list of processed orders. The columns returned can be changed through the SetColumns method.</returns> public GenericPagedResult<ProcessedOrderWeb> SearchProcessedOrdersPaged(DateTime? from,DateTime? to,SearchDateType dateType,String searchField,Boolean exactMatch,String searchTerm,Int32 pageNum,Int32 numEntriesPerPage) { var response = GetResponse("ProcessedOrders/SearchProcessedOrdersPaged", "from=" + System.Net.WebUtility.UrlEncode(from.HasValue ? from.Value.ToString("yyyy-MM-dd HH:mm:ss") : "null") + "&to=" + System.Net.WebUtility.UrlEncode(to.HasValue ? to.Value.ToString("yyyy-MM-dd HH:mm:ss") : "null") + "&dateType=" + dateType.ToString() + "&searchField=" + System.Net.WebUtility.UrlEncode(searchField) + "&exactMatch=" + exactMatch + "&searchTerm=" + System.Net.WebUtility.UrlEncode(searchTerm) + "&pageNum=" + pageNum + "&numEntriesPerPage=" + numEntriesPerPage + ""); return JsonFormatter.ConvertFromJson<GenericPagedResult<ProcessedOrderWeb>>(response); } /// <summary> /// Use this call to check if it is possible to do an automated full-order refund. /// </summary> /// <param name="pkOrderId">The id of the order</param> /// <returns>A result indicating if an automated full-order refund is possible.</returns> public ValidationResult ValidateCompleteOrderRefund(Guid pkOrderId) { var response = GetResponse("ProcessedOrders/ValidateCompleteOrderRefund", "pkOrderId=" + pkOrderId + ""); return JsonFormatter.ConvertFromJson<ValidationResult>(response); } } }
Python
UTF-8
165
3.078125
3
[]
no_license
n = int(input()) a = '' if n<=1000: for i in range(n): for j in range(i+1): a += str(1) if i!=j: a += ' '+'1'+' ' a += '\n' print(a)
Rust
UTF-8
23,029
2.65625
3
[ "Apache-2.0" ]
permissive
//! Single-threaded Monte Carlo tree search on directed acyclic graphs. pub mod backprop; pub mod game; pub mod graph; pub mod rollout; pub mod simulation; pub mod statistics; pub mod ucb; #[cfg(test)] pub(crate) mod tictactoe; use crate::backprop::BackpropSelector; use crate::game::{Game, State}; use crate::graph::{EdgeData, VertexData}; use crate::rollout::RolloutSelector; use crate::simulation::Simulator; use std::convert::From; use std::result::Result; use log::trace; use rand::Rng; /// Wraps a decision made by the UCB rollout policy. /// /// This is distinct from other types in the `ucb` module to provide a /// representation of the decision of UCB rollout that is not bound to the /// lifetime of a `search_graph` structure. #[derive(Clone, Debug)] pub enum UcbValue { /// Select a game state because it has not yet been explored (and so no /// finite UCB policy value is available). Select, /// Select a game state with the given UCB policy value. Value(f64), } impl<'a> From<&ucb::UcbSuccess<'a>> for UcbValue { fn from(success: &ucb::UcbSuccess<'a>) -> Self { match *success { ucb::UcbSuccess::Select(_) => UcbValue::Select, ucb::UcbSuccess::Value(_, v) => UcbValue::Value(v), } } } /// Statistics for a specific game action. /// /// This type is used for reporting summary statistics for the next decision to /// make after executing search. #[derive(Clone, Debug)] pub struct ActionStatistics<G: Game> { /// The action. pub action: G::Action, /// The action's expected payoff. pub payoff: G::Payoff, /// The result of UCB rollout for that action (used for debugging MCTS with /// a UCB rollout policy). pub ucb: Result<UcbValue, ucb::UcbError>, } /// Creates a new search graph suitable for Monte Carlo tree search through the /// state space of the game `G`. pub fn new_search_graph<G: Game>() -> search_graph::Graph<G::State, VertexData, EdgeData<G>> { search_graph::Graph::<G::State, VertexData, EdgeData<G>>::new() } /// Settings for a round of Monte Carlo tree search. #[derive(Clone, Copy, Debug)] pub struct SearchSettings { /// The number of simulations to run when estimating payout of a new game state. pub simulation_count: u32, /// The maximum number of threads to execute at once when simulating payout of a new game state. pub simulation_thread_limit: u32, /// The exploration bias term to use for the UCB policy. pub explore_bias: f64, } /// Recursively traverses the search graph to find a game state from which to /// perform payoff estimates. pub struct RolloutPhase<'a, 'id, R: Rng, G: Game> { rng: R, settings: SearchSettings, graph: search_graph::view::View<'a, 'id, G::State, VertexData, EdgeData<G>>, root_node: search_graph::view::NodeRef<'id>, } impl<'a, 'id, R: Rng, G: Game> RolloutPhase<'a, 'id, R, G> { pub fn initialize( rng: R, settings: SearchSettings, root_state: G::State, mut graph: search_graph::view::View<'a, 'id, G::State, VertexData, EdgeData<G>>, ) -> Self { trace!("initializing rollout phase to state: {:?}", root_state); let root_node = match graph.find_node(&root_state) { Some(n) => n, None => graph.append_node(root_state.clone(), VertexData::default()), }; RolloutPhase { rng, settings, graph, root_node, } } pub fn rollout<S: RolloutSelector>( mut self, ) -> Result<ScoringPhase<'a, 'id, R, G>, rollout::RolloutError<G, S::Error>> { let result = rollout::rollout( &self.graph, self.root_node, S::from(&self.settings), &mut self.rng, ); trace!("rollout finds result {:?}", result); result.map(|node| { trace!("rollout result has target node: {:?}", node); trace!( "rollout result has state: {:?}", self.graph.node_state(node) ); ScoringPhase { rng: self.rng, settings: self.settings, graph: self.graph, root_node: self.root_node, rollout_node: node, } }) } pub fn root_node(&self) -> search_graph::view::NodeRef<'id> { self.root_node } pub fn recover_components( self, ) -> ( R, search_graph::view::View<'a, 'id, G::State, VertexData, EdgeData<G>>, ) { (self.rng, self.graph) } } /// Computes an estimate of the score for a game state selected during rollout. pub struct ScoringPhase<'a, 'id, R: Rng, G: Game> { rng: R, settings: SearchSettings, graph: search_graph::view::View<'a, 'id, G::State, VertexData, EdgeData<G>>, root_node: search_graph::view::NodeRef<'id>, rollout_node: search_graph::view::NodeRef<'id>, } impl<'a, 'id, R: Rng, G: Game> ScoringPhase<'a, 'id, R, G> { pub fn root_node(&self) -> search_graph::view::NodeRef<'id> { self.root_node } pub fn rollout_node(&self) -> search_graph::view::NodeRef<'id> { self.rollout_node } pub fn score<S: Simulator>(mut self) -> Result<BackpropPhase<'a, 'id, R, G>, S::Error> { let payoff = match G::payoff_of(self.graph.node_state(self.rollout_node())) { Some(p) => { trace!("direct payoff found: {:?}", p); p } None => { trace!("simulating to find payoff"); let simulator = S::from(&self.settings); simulator.simulate::<G, R>(self.graph.node_state(self.rollout_node()), &mut self.rng)? } }; trace!("scoring phase finds payoff {:?}", payoff); Ok(BackpropPhase { rng: self.rng, settings: self.settings, graph: self.graph, root_node: self.root_node, rollout_node: self.rollout_node, payoff, }) } } /// Performs backprop of a known payoff from a node selected during rollout. /// /// The strategy for finding the game-state statistics to update during backprop /// is determined by `BackpropSelector`. pub struct BackpropPhase<'a, 'id, R: Rng, G: Game> { rng: R, settings: SearchSettings, graph: search_graph::view::View<'a, 'id, G::State, VertexData, EdgeData<G>>, root_node: search_graph::view::NodeRef<'id>, rollout_node: search_graph::view::NodeRef<'id>, payoff: G::Payoff, } impl<'a, 'id, R: Rng, G: Game> BackpropPhase<'a, 'id, R, G> { pub fn backprop<S: BackpropSelector<'id>>(mut self) -> ExpandPhase<'a, 'id, R, G> { backprop::backprop( &self.graph, self.rollout_node, &self.payoff, &S::from(&self.settings), &mut self.rng, ); ExpandPhase { rng: self.rng, settings: self.settings, graph: self.graph, root_node: self.root_node, rollout_node: self.rollout_node, } } } /// Expands a node in the search graph. /// /// This is done by playing out each of the legal moves at the node's game /// state, adding them to the graph if they don't already exist, and then /// creating an edge from the original node to the node for the resulting game /// state. pub struct ExpandPhase<'a, 'id, R: Rng, G: Game> { rng: R, settings: SearchSettings, graph: search_graph::view::View<'a, 'id, G::State, VertexData, EdgeData<G>>, root_node: search_graph::view::NodeRef<'id>, rollout_node: search_graph::view::NodeRef<'id>, } impl<'a, 'id, R: Rng, G: Game> ExpandPhase<'a, 'id, R, G> { pub fn expand(mut self) -> RolloutPhase<'a, 'id, R, G> { if self.graph.node_data(self.rollout_node).mark_expanded() { trace!("rollout node was already marked as expanded; ExpandPhase does nothing"); } else { let parent_state = self.graph.node_state(self.rollout_node).clone(); for action in parent_state.actions() { trace!("ExpandPhase adds edge for action {:?}", action); let mut child_state = parent_state.clone(); trace!("ExpandState old state: {:?}", child_state); child_state.do_action(&action); trace!("ExpandState new state: {:?}", child_state); let child = match self.graph.find_node(&child_state) { Some(n) => { trace!("ExpandState expanded to existing game state"); n } None => { trace!("ExpandState expanded to new game state"); self.graph.append_node(child_state, Default::default()) } }; self .graph .append_edge(self.rollout_node, child, EdgeData::new(action)); } } RolloutPhase { rng: self.rng, settings: self.settings, graph: self.graph, root_node: self.root_node, } } } #[cfg(test)] mod test { use crate::graph::{EdgeData, VertexData}; use crate::ucb; use crate::{ backprop, simulation, tictactoe, BackpropPhase, ExpandPhase, RolloutPhase, ScoringPhase, SearchSettings, }; use rand::SeedableRng; use rand_pcg; fn default_rng() -> rand_pcg::Pcg64 { rand_pcg::Pcg64::from_seed([0; 32]) } fn default_game_state() -> tictactoe::State { Default::default() } fn default_settings() -> SearchSettings { SearchSettings { simulation_count: 1, simulation_thread_limit: 1, explore_bias: 1.0, } } type Graph = search_graph::Graph<tictactoe::State, VertexData, EdgeData<tictactoe::ScoredGame>>; #[test] fn rollout_init() { let mut graph = Graph::new(); search_graph::view::of_graph(&mut graph, |view| { RolloutPhase::initialize( default_rng(), default_settings(), default_game_state(), view, ); }); let node = graph.find_node(&default_game_state()); assert!(node.is_some()); let node = node.unwrap(); assert!(node.is_leaf()); assert!(node.is_root()); assert_eq!(default_game_state(), *node.get_label()); } #[test] fn integration_test() { let mut graph = Graph::new(); search_graph::view::of_graph(&mut graph, |view| { // Rollout. let rollout_phase = RolloutPhase::initialize( default_rng(), default_settings(), default_game_state(), view, ); let rollout_target = crate::rollout::rollout( &rollout_phase.graph, rollout_phase.root_node, ucb::Rollout::from(&default_settings()), &mut default_rng(), ) .unwrap(); assert_eq!(rollout_phase.root_node(), rollout_target); assert_eq!( tictactoe::State::default(), *rollout_phase.graph.node_state(rollout_target) ); // Scoring. let scoring_phase: ScoringPhase<'_, '_, _, tictactoe::ScoredGame> = rollout_phase.rollout::<ucb::Rollout>().unwrap(); assert_eq!(scoring_phase.rollout_node(), rollout_target); assert_eq!(scoring_phase.root_node(), rollout_target); // Backprop. let backprop_phase: BackpropPhase<'_, '_, _, tictactoe::ScoredGame> = scoring_phase .score::<simulation::RandomSimulator>() .unwrap(); // Expand. let expand_phase: ExpandPhase<'_, '_, _, tictactoe::ScoredGame> = backprop_phase.backprop::<backprop::FirstParentSelector>(); expand_phase.expand(); }); { // Search graph should consist of root, edges for each possible move, and // leaves for the result of each move. let node = graph.find_node(&Default::default()).unwrap(); assert!(node.is_root()); assert!(!node.is_leaf()); assert_eq!(9, node.get_child_list().len()); for child in node.get_child_list().iter() { assert_eq!(0, child.get_data().statistics.visits()); assert_eq!( 0, child .get_data() .statistics .score(crate::statistics::two_player::Player::One) ); assert_eq!( 0, child .get_data() .statistics .score(crate::statistics::two_player::Player::Two) ); assert!(child.get_target().is_leaf()); assert!(!child.get_target().is_root()); } } search_graph::view::of_graph(&mut graph, |view| { RolloutPhase::initialize( default_rng(), default_settings(), default_game_state(), view, ) .rollout::<ucb::Rollout>() .unwrap() .score::<simulation::RandomSimulator>() .unwrap() .backprop::<backprop::FirstParentSelector>() .expand(); }); { // Two levels of should be expanded. assert_eq!(18, graph.vertex_count()); assert_eq!(17, graph.edge_count()); let node = graph.find_node(&Default::default()).unwrap(); assert!(node.is_root()); assert!(!node.is_leaf()); assert_eq!(9, node.get_child_list().len()); for (i, child) in node.get_child_list().iter().enumerate() { if i == 7 { assert_eq!(1, child.get_data().statistics.visits()); assert_eq!( 0, child .get_data() .statistics .score(crate::statistics::two_player::Player::One) ); assert_eq!( 1, child .get_data() .statistics .score(crate::statistics::two_player::Player::Two) ); } else { assert_eq!(0, child.get_data().statistics.visits()); assert_eq!( 0, child .get_data() .statistics .score(crate::statistics::two_player::Player::One) ); assert_eq!( 0, child .get_data() .statistics .score(crate::statistics::two_player::Player::Two) ); } } } search_graph::view::of_graph(&mut graph, |view| { RolloutPhase::initialize( default_rng(), default_settings(), default_game_state(), view, ) .rollout::<ucb::Rollout>() .unwrap() .score::<simulation::RandomSimulator>() .unwrap() .backprop::<backprop::FirstParentSelector>() .expand(); }); } #[test] fn integration_test_first_parent_selector() { let mut graph = Graph::new(); search_graph::view::of_graph(&mut graph, |view| { let mut rollout = RolloutPhase::initialize( default_rng(), default_settings(), default_game_state(), view, ); for _ in 0..10000 { let score = rollout.rollout::<ucb::Rollout>().unwrap(); let backprop = score.score::<simulation::RandomSimulator>().unwrap(); let expand = backprop.backprop::<backprop::FirstParentSelector>(); rollout = expand.expand(); } }); assert_eq!(3295, graph.vertex_count()); assert_eq!(5361, graph.edge_count()); let child_statistics: Vec<&crate::statistics::two_player::ScoredStatistics<_>> = graph .find_node(&default_game_state()) .unwrap() .get_child_list() .iter() .map(|c| &c.get_data().statistics) .collect(); assert_eq!(108, child_statistics[0].visits()); assert_eq!(28, child_statistics[0].score(crate::statistics::two_player::Player::One)); assert_eq!(78, child_statistics[0].score(crate::statistics::two_player::Player::Two)); assert_eq!(209, child_statistics[1].visits()); assert_eq!(153, child_statistics[1].score(crate::statistics::two_player::Player::One)); assert_eq!(50, child_statistics[1].score(crate::statistics::two_player::Player::Two)); assert_eq!(754, child_statistics[2].visits()); assert_eq!(557, child_statistics[2].score(crate::statistics::two_player::Player::One)); assert_eq!(178, child_statistics[2].score(crate::statistics::two_player::Player::Two)); assert_eq!(2023, child_statistics[3].visits()); assert_eq!(1548, child_statistics[3].score(crate::statistics::two_player::Player::One)); assert_eq!(459, child_statistics[3].score(crate::statistics::two_player::Player::Two)); assert_eq!(2105, child_statistics[4].visits()); assert_eq!(834, child_statistics[4].score(crate::statistics::two_player::Player::One)); assert_eq!(1181, child_statistics[4].score(crate::statistics::two_player::Player::Two)); assert_eq!(1172, child_statistics[5].visits()); assert_eq!(574, child_statistics[5].score(crate::statistics::two_player::Player::One)); assert_eq!(590, child_statistics[5].score(crate::statistics::two_player::Player::Two)); assert_eq!(953, child_statistics[6].visits()); assert_eq!(483, child_statistics[6].score(crate::statistics::two_player::Player::One)); assert_eq!(282, child_statistics[6].score(crate::statistics::two_player::Player::Two)); assert_eq!(806, child_statistics[7].visits()); assert_eq!(382, child_statistics[7].score(crate::statistics::two_player::Player::One)); assert_eq!(410, child_statistics[7].score(crate::statistics::two_player::Player::Two)); assert_eq!(1869, child_statistics[8].visits()); assert_eq!(678, child_statistics[8].score(crate::statistics::two_player::Player::One)); assert_eq!(913, child_statistics[8].score(crate::statistics::two_player::Player::Two)); } #[test] fn integration_test_random_parent_selector() { let mut graph = Graph::new(); search_graph::view::of_graph(&mut graph, |view| { let mut rollout = RolloutPhase::initialize( default_rng(), default_settings(), default_game_state(), view, ); for _ in 0..10000 { let score = rollout.rollout::<ucb::Rollout>().unwrap(); let backprop = score.score::<simulation::RandomSimulator>().unwrap(); let expand = backprop.backprop::<backprop::RandomParentSelector>(); rollout = expand.expand(); } }); assert_eq!(5795, graph.vertex_count()); assert_eq!(13874, graph.edge_count()); let child_statistics: Vec<&crate::statistics::two_player::ScoredStatistics<_>> = graph .find_node(&default_game_state()) .unwrap() .get_child_list() .iter() .map(|c| &c.get_data().statistics) .collect(); assert_eq!(1204, child_statistics[0].visits()); assert_eq!(708, child_statistics[0].score(crate::statistics::two_player::Player::One)); assert_eq!(347, child_statistics[0].score(crate::statistics::two_player::Player::Two)); assert_eq!(790, child_statistics[1].visits()); assert_eq!(396, child_statistics[1].score(crate::statistics::two_player::Player::One)); assert_eq!(266, child_statistics[1].score(crate::statistics::two_player::Player::Two)); assert_eq!(983, child_statistics[2].visits()); assert_eq!(553, child_statistics[2].score(crate::statistics::two_player::Player::One)); assert_eq!(249, child_statistics[2].score(crate::statistics::two_player::Player::Two)); assert_eq!(829, child_statistics[3].visits()); assert_eq!(471, child_statistics[3].score(crate::statistics::two_player::Player::One)); assert_eq!(258, child_statistics[3].score(crate::statistics::two_player::Player::Two)); assert_eq!(2015, child_statistics[4].visits()); assert_eq!(1224, child_statistics[4].score(crate::statistics::two_player::Player::One)); assert_eq!(388, child_statistics[4].score(crate::statistics::two_player::Player::Two)); assert_eq!(795, child_statistics[5].visits()); assert_eq!(449, child_statistics[5].score(crate::statistics::two_player::Player::One)); assert_eq!(242, child_statistics[5].score(crate::statistics::two_player::Player::Two)); assert_eq!(1035, child_statistics[6].visits()); assert_eq!(578, child_statistics[6].score(crate::statistics::two_player::Player::One)); assert_eq!(287, child_statistics[6].score(crate::statistics::two_player::Player::Two)); assert_eq!(1002, child_statistics[7].visits()); assert_eq!(581, child_statistics[7].score(crate::statistics::two_player::Player::One)); assert_eq!(271, child_statistics[7].score(crate::statistics::two_player::Player::Two)); assert_eq!(1346, child_statistics[8].visits()); assert_eq!(798, child_statistics[8].score(crate::statistics::two_player::Player::One)); assert_eq!(399, child_statistics[8].score(crate::statistics::two_player::Player::Two)); } #[test] fn integration_test_best_parent_selector() { let mut graph = Graph::new(); search_graph::view::of_graph(&mut graph, |view| { let mut rollout = RolloutPhase::initialize( default_rng(), default_settings(), default_game_state(), view, ); for _ in 0..10000 { let score = rollout.rollout::<ucb::Rollout>().unwrap(); let backprop = score.score::<simulation::RandomSimulator>().unwrap(); let expand = backprop.backprop::<ucb::BestParentBackprop>(); rollout = expand.expand(); } }); assert_eq!(4471, graph.vertex_count()); assert_eq!(10889, graph.edge_count()); let child_statistics: Vec<&crate::statistics::two_player::ScoredStatistics<_>> = graph .find_node(&default_game_state()) .unwrap() .get_child_list() .iter() .map(|c| &c.get_data().statistics) .collect(); assert_eq!(229, child_statistics[0].visits()); assert_eq!(138, child_statistics[0].score(crate::statistics::two_player::Player::One)); assert_eq!(53, child_statistics[0].score(crate::statistics::two_player::Player::Two)); assert_eq!(73, child_statistics[1].visits()); assert_eq!(33, child_statistics[1].score(crate::statistics::two_player::Player::One)); assert_eq!(30, child_statistics[1].score(crate::statistics::two_player::Player::Two)); assert_eq!(322, child_statistics[2].visits()); assert_eq!(203, child_statistics[2].score(crate::statistics::two_player::Player::One)); assert_eq!(83, child_statistics[2].score(crate::statistics::two_player::Player::Two)); assert_eq!(90, child_statistics[3].visits()); assert_eq!(44, child_statistics[3].score(crate::statistics::two_player::Player::One)); assert_eq!(32, child_statistics[3].score(crate::statistics::two_player::Player::Two)); assert_eq!(9033, child_statistics[4].visits()); assert_eq!(7693, child_statistics[4].score(crate::statistics::two_player::Player::One)); assert_eq!(945, child_statistics[4].score(crate::statistics::two_player::Player::Two)); assert_eq!(74, child_statistics[5].visits()); assert_eq!(34, child_statistics[5].score(crate::statistics::two_player::Player::One)); assert_eq!(35, child_statistics[5].score(crate::statistics::two_player::Player::Two)); assert_eq!(118, child_statistics[6].visits()); assert_eq!(62, child_statistics[6].score(crate::statistics::two_player::Player::One)); assert_eq!(43, child_statistics[6].score(crate::statistics::two_player::Player::Two)); assert_eq!(98, child_statistics[7].visits()); assert_eq!(49, child_statistics[7].score(crate::statistics::two_player::Player::One)); assert_eq!(36, child_statistics[7].score(crate::statistics::two_player::Player::Two)); assert_eq!(180, child_statistics[8].visits()); assert_eq!(104, child_statistics[8].score(crate::statistics::two_player::Player::One)); assert_eq!(41, child_statistics[8].score(crate::statistics::two_player::Player::Two)); } }
SQL
UTF-8
18,598
3.125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 3.5.1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Feb 12, 2015 at 02:18 PM -- Server version: 5.5.24-log -- PHP Version: 5.4.3 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!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 */; /*!40101 SET NAMES utf8 */; -- -- Database: `project_management` -- CREATE DATABASE `project_management` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `project_management`; -- -------------------------------------------------------- -- -- Table structure for table `backlog` -- CREATE TABLE IF NOT EXISTS `backlog` ( `name` varchar(50) NOT NULL, `user_name` varchar(50) NOT NULL, `sprint_name` varchar(50) NOT NULL, `description` varchar(150) DEFAULT NULL, `priority` int(10) DEFAULT NULL, `comment` varchar(150) DEFAULT NULL, PRIMARY KEY (`name`,`sprint_name`), KEY `user_name` (`user_name`), KEY `sprint_name` (`sprint_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `scrum` -- CREATE TABLE IF NOT EXISTS `scrum` ( `name` varchar(50) NOT NULL, `description` varchar(150) DEFAULT NULL, PRIMARY KEY (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `scrum_member` -- CREATE TABLE IF NOT EXISTS `scrum_member` ( `id` int(10) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) NOT NULL, `scrum_name` varchar(50) NOT NULL, PRIMARY KEY (`id`), KEY `user_name` (`user_name`), KEY `scrum_name` (`scrum_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `spr_submission` -- CREATE TABLE IF NOT EXISTS `spr_submission` ( `spr_no` int(10) NOT NULL, `l03` enum('YES','NO','N/A','IDLING','REOPENED') DEFAULT NULL, `p10` enum('YES','NO','N/A','IDLING','REOPENED') DEFAULT NULL, `p20` enum('YES','NO','N/A','IDLING','REOPENED') DEFAULT NULL, `P30` enum('YES','NO','N/A','IDLING','REOPENED') DEFAULT NULL, `comment` varchar(500) DEFAULT NULL, PRIMARY KEY (`spr_no`), KEY `spr_no` (`spr_no`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `spr_submission` -- INSERT INTO `spr_submission` (`spr_no`, `l03`, `p10`, `p20`, `P30`, `comment`) VALUES (2133120, 'N/A', 'N/A', 'N/A', 'N/A', ''), (2221013, 'NO', 'NO', 'NO', 'NO', ''), (2226914, 'NO', 'NO', 'NO', 'NO', ''), (2244774, 'NO', 'NO', 'NO', 'NO', ''), (2249565, 'NO', 'NO', 'NO', 'YES', ''); -- -------------------------------------------------------- -- -- Table structure for table `spr_tracking` -- CREATE TABLE IF NOT EXISTS `spr_tracking` ( `spr_no` int(10) NOT NULL, `user_name` varchar(50) NOT NULL, `type` enum('SPR','REGRESSION','OTHERS') NOT NULL, `status` enum('NONE','INVESTIGATING','NOT AN ISSUE','SUBMITTED','RESOLVED','PASS FOR TESTING','CLOSED','ON HOLD','TESTING COMPLETE','PASS TO CORRESPONDING GROUP','NEED MORE INFO','OTHERS') DEFAULT NULL, `comment` varchar(1500) DEFAULT NULL, `session` int(10) DEFAULT NULL, `build_version` varchar(25) NOT NULL, `commit_build` varchar(25) NOT NULL, `respond_by_date` date DEFAULT NULL, PRIMARY KEY (`spr_no`), KEY `user_name` (`user_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `spr_tracking` -- INSERT INTO `spr_tracking` (`spr_no`, `user_name`, `type`, `status`, `comment`, `session`, `build_version`, `commit_build`, `respond_by_date`) VALUES (1101609, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '2015-01-06'), (1126558, 'anath', 'SPR', 'CLOSED', 'Hi Roland,I’m investigating SPR 1126558 (The TITLE_INFO check does not report any errors/warnings, even if there are entries in tables (title bl', 2012, 'L03,P10,P20', '', '2015-01-06'), (1185049, 'anath', 'SPR', 'ON HOLD', ' Add a missing "Post Regeneration" relation.', 2012, 'L03,P10,P20', '', '2015-01-06'), (1192881, 'anath', 'REGRESSION', 'NONE', '', 2014, 'P20', '', '0000-00-00'), (1198281, 'anath', 'REGRESSION', 'NONE', '', 2015, 'P10', '', '2015-02-15'), (1585365, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (1842746, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2031382, 'anath', 'SPR', 'PASS TO CORRESPONDING GROUP', 'Assigning this SPR back to Assembly group as our team no more working on Assembly SPRs.', 2012, 'L03,P10,P20', '', '0000-00-00'), (2035003, 'anath', 'SPR', 'NOT AN ISSUE', 'In case of ''STD_PRT_INFO_FILE'', external text file does not support ''PRT_PARAMETER'' & ''PRT_LAYER''. Its only support ''PRT_MODEL_NAME'', ''PRT_PARAM_NOTE_', 2012, 'L03,P10,P20', '', '0000-00-00'), (2035552, 'anath', 'SPR', 'NOT AN ISSUE', 'In case of ''STD_ASM_INFO_FILE'', external text file does not support ''ASM_PARAMETER'' & ''ASM_LAYER''. Its only support ''ASM_MODEL_NAME'', ''ASM_PARAM_NOTE_', 2012, 'L03,P10,P20', '', '0000-00-00'), (2059037, 'anath', 'SPR', 'PASS TO CORRESPONDING GROUP', 'Pass to corresponding group and mail it to ''Mark''. Defect is closed by corresponding group.', 2012, 'L03,P10,P20', '', '0000-00-00'), (2066734, 'anath', 'SPR', 'SUBMITTED', 'Send mail to Irina and passed her the defect. In the mail described her how problem caused by creating a toolkit App.- Hi Irina,Thanks for the file.', 2012, 'L03,P10,P20', '', '0000-00-00'), (2080495, 'anath', 'SPR', 'PASS FOR TESTING', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2080509, 'anath', 'SPR', 'PASS FOR TESTING', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2081059, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2082181, 'anath', 'SPR', 'SUBMITTED', 'From: Nath, Abhishek \r\nSent: 29 August 2013 05:26 PM\r\nTo: Ender, Matthew\r\nCc: Singh, Kuldeep; Gupta, Arvind\r\nSubject: SPR 2082181\r\n\r\nHi Matthew,\r\n\r\nIâ', 2012, 'L03,P10,P20', '', '0000-00-00'), (2082658, 'anath', 'SPR', 'NOT AN ISSUE', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2092140, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2093441, 'anath', 'SPR', 'NEED MORE INFO', 'Doesn''t understand what to do? According to the mail threads, ''DETAIL_USERPARAM'' this feature is not supported, then what should we do?\r\n- Close the d', 2012, 'L03,P10,P20', '', '0000-00-00'), (2093672, 'anath', 'SPR', 'NOT AN ISSUE', 'Sent a mail to ''Michael Youkelzon'' regarding how to reproduce the issue.\r\nClosed by Michael.', 2012, 'L03,P10,P20', '', '0000-00-00'), (2101422, 'anath', 'SPR', 'NONE', 'ggg', 2015, 'P10,P20', '', '2014-12-05'), (2108488, 'anath', 'SPR', 'NOT AN ISSUE', 'Sent mail to Urs to inform that issue is not reproducing L-03-50 and follow version.Hi Urs,I?ve checked the SPR 2108488 with L-03-50 (M160). And I fou', 2012, 'L03,P10,P20', '', '0000-00-00'), (2119697, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2121988, 'anath', 'SPR', 'NOT AN ISSUE', 'Abhijit sent mail to tech support to thell them it’s the boundary of the product. And also explain why so.', 2012, 'L03,P10,P20', '', '0000-00-00'), (2125042, 'anath', 'SPR', 'PASS FOR TESTING', '', 2012, 'P20', '', '0000-00-00'), (2126775, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2128804, 'anath', 'SPR', 'NOT AN ISSUE', 'Hi Abderrazzaq,\r\nI forgot to mentioned that I’m closing the issue.\r\n\r\n\r\nThanks and best regards\r\nAbhishek\r\n\r\nFrom: Nath, Abhishek \r\nSent: 17 June 20', 2012, 'L03,P10,P20', '', '0000-00-00'), (2129403, 'anath', 'SPR', 'NOT AN ISSUE', 'Close the defect. Have not get any reply from Thomas and we explained him every thing.', 2012, 'L03,P10,P20', '', '0000-00-00'), (2131809, 'anath', 'SPR', 'SUBMITTED', 'Hi Pallab,\r\n\r\nI’m investigating SPR 2131809 ([SC_P10_REGREBUILD] User unable to add missing comments from model check browser.)\r\nIn Relation, when t', 2012, 'L03,P10,P20', '', '0000-00-00'), (2133120, 'anath', 'SPR', 'NONE', '', 2015, 'L03,P10,P20', '', '2012-06-04'), (2139597, 'anath', 'SPR', 'SUBMITTED', 'Submitted on P-10-24, L-03-54', 2012, 'L03,P10,P20', '', '0000-00-00'), (2147150, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2148229, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2149869, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2150446, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2150796, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2151067, 'anath', 'SPR', 'NOT AN ISSUE', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2151188, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2151193, 'anath', 'SPR', 'NOT AN ISSUE', 'Sent mail to ''Serge'' and describe why it is not a defect.', 2012, 'L03,P10,P20', '', '0000-00-00'), (2157154, 'anath', 'SPR', 'NOT AN ISSUE', 'Have to write a mail to tech support that its not a defect and wrong behavior due to ''REGEN_*'' related checks. If you remove all those checks then pro', 2012, 'L03,P10,P20', '', '0000-00-00'), (2162137, 'anath', 'SPR', 'SUBMITTED', 'Unable to reproduce the defect. Need more info, I have to investigate more.\r\nProblem resolved. \r\nProblem caused due to the mismatch of tabname(CUSTUM/', 2012, 'L03,P10,P20', '', '0000-00-00'), (2169019, 'anath', 'SPR', 'PASS TO CORRESPONDING GROUP', 'Its an enhancement. Pass the defect to Rosemary. ', 2012, 'L03,P10,P20', '', '0000-00-00'), (2169393, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2169984, 'anath', 'SPR', 'NONE', 'Ask Abhijit about the proper msg.', 2012, 'L03,P10,P20', '', '0000-00-00'), (2171226, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2178525, 'anath', 'SPR', 'NOT AN ISSUE', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2179114, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2180784, 'anath', 'SPR', 'PASS TO CORRESPONDING GROUP', 'Problem cause in the function ''ProMdlcheckGetModelmcdata(...)''. Inside this funciton modelCHECK collect ''Creation Date''. So, I have to pass this to co', 2012, 'L03,P10,P20', '', '0000-00-00'), (2181006, 'anath', 'SPR', 'SUBMITTED', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2186181, 'anath', 'SPR', 'NONE', 'This is the same issue as SPR 2181006.\r\nSo, maked its as duplicate.', 2012, 'L03,P10,P20', '', '0000-00-00'), (2186281, 'anath', 'SPR', 'NOT AN ISSUE', 'Hi Amit,\r\n\r\nAccording to the SPR, in P-10, the only ModelCHECK report difference is ‘Drawing Detail Setup’.\r\nNow if we click ‘Drawing Detail Set', 2012, 'L03,P10,P20', '', '0000-00-00'), (2189973, 'anath', 'SPR', 'SUBMITTED', 'Hi Erich/Rico,\r\n\r\nThis functionality is not a bug.\r\nBy default, circular references are supposed to be reported for all levels in the assembly.\r\nWe ha', 2013, 'L03,P10,P20', '', '0000-00-00'), (2191768, 'anath', 'SPR', 'NONE', '', 2012, 'L03,P10,P20', '', '0000-00-00'), (2192761, 'anath', 'SPR', 'NONE', 'Hi Rico,\r\n\r\nSPR 2192761 having a TAN (106836) and customer severity having low impact.\r\nSPR needs substantial changes and its will also change the out', 2012, 'L03,P10,P20', '', '0000-00-00'), (2193022, 'anath', 'SPR', 'CLOSED', 'It''s a MC gatekeeper problem, while MC is not applicable for bulk item, then gatekeeper must not check for it.', 2012, 'L03,P10,P20', '', '0000-00-00'), (2218565, 'anath', 'SPR', 'SUBMITTED', 'Submitted on P-10-32.Creating a subroutine using MULTAX and copy CL output produces operation CL data containing Rapid feed instead of FEDRAT', 2015, 'P10,P20', 'P-10-32', '2015-01-06'), (2220422, 'anath', 'SPR', 'NONE', '', 2013, 'P20', '', '0000-00-00'), (2221013, 'anath', 'SPR', 'NEED MORE INFO', 'Hi Mahesh,Me and Prashant (QA) tried to reproduce the issue by playing trail files or manually, but we are unable to reproduce the issue.Trail files are not working properly and manually it’s not reproducing.My request to you, can you please provide trail file with proper model.It would be better if you provide a video which cover the crash.I mark this SPR as need info.Thanks and best regardsAbhishek', 2015, 'P10,P20', '', '0000-00-00'), (2226914, 'anath', 'SPR', 'SUBMITTED', 'Submitted on P-10-32.Wrong Toolpath for Area turning NC sequence in Creo Parametric when the NC sequence parameter "STEP_DEPTH_COMPUTATION" is set to "BY_AREA".', 2015, 'P10,P20,P30', 'P-10-32', '0000-00-00'), (2227587, 'anath', 'SPR', 'SUBMITTED', 'If model is not associated with input tool then API ProToolModelMdlnameGet() returns E_NOT_FOUND (ie 4) instead or returning PRO_TK_E_NOT_FOUND (-4). ', 2013, 'P20', 'P-20-60', '0000-00-00'), (2239054, 'anath', 'SPR', 'SUBMITTED', 'In a classic face milling sequence CUT_ANGLE seems to be incorrect: instead of 180 (as in parameters) it produces.', 2013, 'P10,P20', 'P-10-32', '0000-00-00'), (2240004, 'anath', 'SPR', 'NONE', 'FLASH tools are unexpectedly in standard orientation when Material Removal is ran in Vericut from Creo Parametric 3.0.', 2015, 'P20', '', '0000-00-00'), (2241145, 'anath', 'SPR', 'NOT AN ISSUE', 'Feed is not correctly updated when changing the number of flutes when using the option mm/tooth', 2015, 'P10,P20', '', '0000-00-00'), (2244774, 'anath', 'SPR', 'NONE', 'Stock allowance setting is not keeping along the whole turn profile for turning sequence "1SP_SCHAUFELN_VORDREHEN"', 2015, 'P10,P20', 'P-10-33', '0000-00-00'), (2246120, 'anath', 'SPR', 'NONE', 'Response by date 15-Dec.Remove material works incorrectly in turning operation', 2015, 'P10,P20', 'P-10-33', '0000-00-00'), (2246227, 'anath', 'SPR', 'INVESTIGATING', 'Entry & Exit conditions do not behave as expected in Profile Wire EDM Sequences in Creo Parametric 2.0', 2015, 'P10,P20', 'P-10-33', '2015-01-06'), (2249565, 'anath', 'SPR', 'SUBMITTED', 'Submitted on P-20-64.Automatic simulation for multiple operations with different csys in Vericut. Ability to simulate the complete process: Top and bottom machining of par', 2015, 'P10,P20', 'P-20-64', '2015-01-07'), (2249748, 'anath', 'SPR', 'NONE', 'ResponseSimilar kind of problem in SPR 1837193.ask Bill.Hasenjaeger@cgtech.com corporate.Support@cgtech.com', 2015, 'P10,P20', '', '2015-01-06'), (2250972, 'anath', 'SPR', 'NONE', '', 2015, 'P10,P20', 'P-10-34', '2015-01-05'), (2251260, 'anath', 'SPR', 'NONE', 'Respond by 07-Jan-2014', 2015, 'P10,P20', '', '2015-01-07'), (2252032, 'anath', 'SPR', 'NONE', '', 2015, 'P10,P20', '', '2015-01-26'), (2253386, 'anath', 'SPR', 'NONE', '', 2015, 'P10,P20,P30', 'P-10-34', '2015-02-02'), (2254103, 'anath', 'SPR', 'NONE', '', 2015, 'P20, P30', 'P-20-66', '2015-02-09'), (2254166, 'anath', 'SPR', 'NONE', '', 2015, 'P20,P30', '', '2015-03-09'); -- -------------------------------------------------------- -- -- Table structure for table `sprint` -- CREATE TABLE IF NOT EXISTS `sprint` ( `scrum_name` varchar(50) NOT NULL, `name` varchar(50) NOT NULL, `duration` varchar(45) NOT NULL, `perday` int(10) NOT NULL, PRIMARY KEY (`name`,`scrum_name`), KEY `scrum_name` (`scrum_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `sprint_member` -- CREATE TABLE IF NOT EXISTS `sprint_member` ( `id` int(10) NOT NULL AUTO_INCREMENT, `user_name` varchar(50) NOT NULL, `sprint_name` varchar(50) NOT NULL, `working_day` int(10) DEFAULT NULL, `buffer_time` int(10) DEFAULT NULL, PRIMARY KEY (`id`), KEY `user_name` (`user_name`), KEY `sprint_name` (`sprint_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `task` -- CREATE TABLE IF NOT EXISTS `task` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `sprint_name` varchar(50) NOT NULL, `estimated_time` int(10) DEFAULT NULL, `spent_time` int(10) DEFAULT NULL, `status` enum('BLOCK','IN-PROCESS','COMPLETE') DEFAULT NULL, `comment` varchar(150) DEFAULT NULL, PRIMARY KEY (`id`), KEY `sprint_name` (`sprint_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE IF NOT EXISTS `user` ( `user_name` varbinary(100) NOT NULL, `password` varbinary(100) DEFAULT NULL, `first_name` varbinary(100) DEFAULT NULL, `last_name` varbinary(100) DEFAULT NULL, `gender` enum('Female','Male') DEFAULT NULL, `title` varbinary(100) DEFAULT NULL, `department` varbinary(100) DEFAULT NULL, `email` varbinary(100) DEFAULT NULL, `alt_email` varbinary(100) DEFAULT NULL, `manager` varbinary(100) DEFAULT NULL, PRIMARY KEY (`user_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `user` -- INSERT INTO `user` (`user_name`, `password`, `first_name`, `last_name`, `gender`, `title`, `department`, `email`, `alt_email`, `manager`) VALUES ('anath', 'sankarin', 'Abhishek', 'Nath', 'Male', 'Tech Lead', 'MCAD', 'anath@ptc.com', '', 'agupta'), ('rtripathi', 'abc', 'Rishabh', 'Tripathi', 'Male', 'Tech Lead', 'MCAD', 'rtripathi@ptc.com', '', 'agupta'); -- -------------------------------------------------------- -- -- Table structure for table `work_tracker` -- CREATE TABLE IF NOT EXISTS `work_tracker` ( `id` int(10) NOT NULL AUTO_INCREMENT, `day` date NOT NULL, `user_name` varchar(25) NOT NULL, `task` varchar(50) NOT NULL, `category` enum('SPR','REG FIX','REGRESSION TEST','SF','REG CLEAN-UP','CONSULTATION','PROJECT','MISC','OTHERS') DEFAULT NULL, `time` double DEFAULT NULL, `comment` varchar(1500) DEFAULT NULL, PRIMARY KEY (`id`), KEY `user_name` (`user_name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ; -- -- Dumping data for table `work_tracker` -- INSERT INTO `work_tracker` (`id`, `day`, `user_name`, `task`, `category`, `time`, `comment`) VALUES (1, '2014-12-22', 'anath', '2226914', 'SPR', 3, 'Commit Build P-10-32'), (2, '2014-12-22', 'anath', 'project management', 'OTHERS', 1, 'kk'), (15, '2014-12-29', 'anath', '66', 'SPR', 9, ''), (28, '2015-01-16', 'anath', '3333', 'SPR', 2, ''), (31, '2015-01-16', 'anath', '44', 'SPR', 2, ''), (33, '2015-01-22', 'anath', '4444', 'SPR', 2, ''); /*!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 */;
Python
UTF-8
5,985
2.6875
3
[ "Apache-2.0" ]
permissive
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*- import struct from .bitwise_word import bitwise_word class bitwise_unpack(object): LE = '<' BE = '>' _INT_UNPACK_FORMATS = { LE: { 1: '<B', 2: '<H', 4: '<I', 8: '<Q', }, BE: { 1: '>B', 2: '>H', 4: '>I', 8: '>Q', }, } _INT_PACK_FORMATS = { LE: { 1: '< B', 2: '< H', 4: '< I', 8: '< Q', }, BE: { 1: '> B', 2: '> H', 4: '> I', 8: '> Q', }, } _REAL_UNPACK_FORMATS = { LE: { 4: '<f', 8: '<d', }, BE: { 4: '>f', 8: '>d', }, } _REAL_PACK_FORMATS = { LE: { 4: '< f', 8: '< d', }, BE: { 4: '> f', 8: '> d', }, } DEFAULT_ENDIAN = LE @classmethod def unpack(clazz, data, size, endian = DEFAULT_ENDIAN): assert size in [ 1, 2, 4, 8 ] return struct.unpack(clazz._INT_UNPACK_FORMATS[endian][size], data)[0] @classmethod def unpack_real(clazz, data, size, endian = DEFAULT_ENDIAN): assert size in [ 4, 8 ] return struct.unpack(clazz._REAL_UNPACK_FORMATS[endian][size], data)[0] @classmethod def unpack_float(clazz, data, endian = DEFAULT_ENDIAN): return clazz.unpack_real(data, 4, endian = endian) @classmethod def unpack_double(clazz, data, endian = DEFAULT_ENDIAN): return clazz.unpack_real(data, 8, endian = endian) @classmethod def unpack_bits(clazz, data, size, slices, endian = DEFAULT_ENDIAN): assert size in [ 1, 2, 4, 8 ] num_bits = size * 8 validated_slices = clazz.validate_slices(slices, num_bits) if not validated_slices: raise RuntimeError('Invalid slice sequence: %s' % (str(slices))) word = bitwise_word(clazz.unpack(data, size, endian = endian), num_bits) result = [] for s in validated_slices: result.append(word[s]) return tuple(result) @classmethod def unpack_u8(clazz, data, endian = DEFAULT_ENDIAN): return clazz.unpack(data, 1, endian = endian) @classmethod def unpack_u16(clazz, data, endian = DEFAULT_ENDIAN): return clazz.unpack(data, 2, endian = endian) @classmethod def unpack_u32(clazz, data, endian = DEFAULT_ENDIAN): return clazz.unpack(data, 4, endian = endian) @classmethod def unpack_u64(clazz, data, endian = DEFAULT_ENDIAN): return clazz.unpack(data, 64, endian = endian) @classmethod def unpack_float(clazz, data, endian = DEFAULT_ENDIAN): return clazz.unpack(data, 64, endian = endian) @classmethod def unpack_u8_bits(clazz, data, slices, endian = DEFAULT_ENDIAN): return clazz.unpack_bits(data, 1, slices, endian = endian) @classmethod def unpack_u16_bits(clazz, data, slices, endian = DEFAULT_ENDIAN): return clazz.unpack_bits(data, 2, slices, endian = endian) @classmethod def unpack_u32_bits(clazz, data, slices, endian = DEFAULT_ENDIAN): return clazz.unpack_bits(data, 4, slices, endian = endian) @classmethod def unpack_u64_bits(clazz, data, slices, endian = DEFAULT_ENDIAN): return clazz.unpack_bits(data, 8, slices, endian = endian) @classmethod def pack(clazz, i, size, endian = DEFAULT_ENDIAN): assert size in [ 1, 2, 4, 8 ] format = clazz._INT_PACK_FORMATS[endian][size] result = struct.Struct(format).pack(i) return result @classmethod def pack_real(clazz, r, size, endian = DEFAULT_ENDIAN): assert size in [ 4, 8 ] format = clazz._REAL_PACK_FORMATS[endian][size] result = struct.Struct(format).pack(r) return result @classmethod def pack_bits(clazz, size, slices, values, endian = DEFAULT_ENDIAN): assert size in [ 1, 2, 4, 8 ] num_bits = size * 8 validated_slices = clazz.validate_slices(slices, num_bits) if not validated_slices: raise RuntimeError('Invalid slice sequence: %s' % (str(slices))) if not isinstance(values, ( list, tuple )): raise RuntimeError('values should be a list or tuple: ' % (str(values))) if len(values) != len(slices): raise RuntimeError('values and slices should be the same length') word = bitwise_word(0x0, num_bits) for s, value in zip(validated_slices, values): word[s] = value return clazz.pack(word.word, size, endian = endian) @classmethod def pack_u8(clazz, i, endian = DEFAULT_ENDIAN): return clazz.pack(i, 1, endian = endian) @classmethod def pack_u16(clazz, i, endian = DEFAULT_ENDIAN): return clazz.pack(i, 2, endian = endian) @classmethod def pack_u32(clazz, i, endian = DEFAULT_ENDIAN): return clazz.pack(i, 4, endian = endian) @classmethod def pack_u64(clazz, i, endian = DEFAULT_ENDIAN): return clazz.pack(i, 8, endian = endian) @classmethod def pack_u8_bits(clazz, slices, values, endian = DEFAULT_ENDIAN): return self.pack_bits(1, slices, values, endian = endian) @classmethod def pack_u16_bits(clazz, slices, values, endian = DEFAULT_ENDIAN): return self.pack_bits(2, slices, values, endian = endian) @classmethod def pack_u32_bits(clazz, slices, values, endian = DEFAULT_ENDIAN): return self.pack_bits(4, slices, values, endian = endian) @classmethod def pack_u64_bits(clazz, slices, values, endian = DEFAULT_ENDIAN): return self.pack_bits(8, slices, values, endian = endian) # FIXME: move validation methods to bitwise_word @classmethod def validate_slice(clazz, s, size): if isinstance(s, ( list, tuple )): if len(s) != 2: return None s = slice(s[0], s[1]) if not isinstance(s, slice): return None if s.start >= 0 and s.stop <= size and s.step in [ None, 1 ]: return s return None @classmethod def validate_slices(clazz, l, size): if not isinstance(l, ( tuple, list )): return None result = [ clazz.validate_slice(i, size) for i in l ] if None in result: return None return result
Shell
UTF-8
490
3.328125
3
[]
no_license
#!/bin/bash # Show versions # echo "tools:" # docker --version # docker-machine --version # docker-compose --version # echo "" if [ -z ${MACHINE_NAME+x} ] then echo -n "" else # Configure Docker endpoint echo "setting up environment for '$MACHINE_NAME':" eval $(docker-machine env --shell bash $MACHINE_NAME) # fix ssh key permissions chown 600 "/root/.docker/machine/machines/${MACHINE_NAME}/id_rsa" # Show info docker info fi # Execute CMD exec "$@"
Java
UTF-8
3,410
3.09375
3
[]
no_license
//Given a non-empty array of digits representing a non-negative integer, plus on //e to the integer. // // The digits are stored such that the most significant digit is at the head of //the list, and each element in the array contain a single digit. // // You may assume the integer does not contain any leading zero, except the numb //er 0 itself. // // Example 1: // // //Input: [1,2,3] //Output: [1,2,4] //Explanation: The array represents the integer 123. // // // Example 2: // // //Input: [4,3,2,1] //Output: [4,3,2,2] //Explanation: The array represents the integer 4321. // Related Topics 数组 package leetcode.editor.cn; import com.sun.org.apache.xalan.internal.xsltc.util.IntegerArray; import java.util.ArrayList; import java.util.List; //Java:加一 public class P66PlusOne { public static void main(String[] args) { Solution solution = new P66PlusOne().new Solution(); // TO TEST int[] ints = new int[]{4, 3, 2, 1}; for (int i : solution.plusOne(ints)) { System.out.printf(i + "\n"); } System.out.printf("\n"); ints = new int[]{9}; for (int i : solution.plusOne(ints)) { System.out.printf(i + "\n"); } System.out.printf("\n"); ints = new int[]{9, 9, 9, 9}; for (int i : solution.plusOne(ints)) { System.out.printf(i + "\n"); } System.out.printf("\n"); ints = new int[]{2, 9, 9, 9, 9}; for (int i : solution.plusOne(ints)) { System.out.printf(i + "\n"); } System.out.printf("\n"); ints = new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; for (int i : solution.plusOne(ints)) { System.out.printf(i + "\n"); } } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int[] plusOne(int[] digits) { if (digits == null || digits.length == 0) { return digits; } int i = digits.length - 1; while (i >= 0) { if (digits[i] == 9) { digits[i] = 0; } else { digits[i]++; return digits; } i--; } digits = new int[digits.length + 1]; digits[0] = 1; return digits; // Integer t = 0; // for (int i = 0; i < digits.length; i++) { // t = t * 10 + digits[i]; // } // t++; // List<Integer> integerList = new ArrayList<Integer>(); // while (t > 0) { // integerList.add(t % 10); // t = t / 10; // } // digits = new int[integerList.size()]; // for (int i = 0; i < digits.length; i++) { // digits[digits.length - i - 1] = integerList.get(i); // } // return digits; // if (digits[digits.length - 1] == 9) { // int[] d1 = new int[digits.length+1]; // for (int i = 0; i < digits.length-1; i++) { // d1[i] = digits[i]; // } // d1[digits.length - 1] = 1; // d1[digits.length] = 0; // }else digits[digits.length - 1]++; // return digits; } } //leetcode submit region end(Prohibit modification and deletion) }
Java
UTF-8
2,057
2.171875
2
[]
no_license
package ua.nic.Cursova.view.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import ua.nic.Cursova.model.BmpEntity; import ua.nic.Cursova.service.IEntityService; import javax.validation.Valid; @Controller public class BmpViewController { @Autowired private IEntityService bmpService; @GetMapping("/bmpList") public String getAllBmp (Model model) { model.addAttribute("bmpList", bmpService.getAll()); model.addAttribute("bmpEntity", new BmpEntity()); return "bmpList.html"; } @RequestMapping(value = "/bmpList", method = RequestMethod.POST, params = "action=delete") ModelAndView deleteBmp ( ModelAndView modelAndView, @Valid BmpEntity bmpEntity, BindingResult result) { bmpService.delete(bmpEntity.getId()); modelAndView.setViewName("redirect:/bmpList"); return modelAndView; } @RequestMapping(value = "/bmpList", method = RequestMethod.POST, params = "action=add") ModelAndView addBmp ( ModelAndView modelAndView, @Valid BmpEntity bmpEntity, BindingResult result) { bmpService.save(bmpEntity); modelAndView.setViewName("redirect:/bmpList"); return modelAndView; } @RequestMapping(value = "/bmpList", method = RequestMethod.POST, params = "action=save") ModelAndView updateBmp ( ModelAndView modelAndView, @Valid BmpEntity bmpEntity, BindingResult result) { if (!result.hasErrors()) { bmpService.delete(bmpEntity.getId()); bmpService.save(bmpEntity); modelAndView.getModel().put("bmp", bmpEntity); modelAndView.setViewName("redirect:/bmpList"); } return modelAndView; } }
C
UTF-8
275
2.5625
3
[]
no_license
/* ** EPITECH PROJECT, 2020 ** generator ** File description: ** error.c */ #include "../include/all_includes.h" void my_put_error_str(char *str) { int i = 0; for (i = 0; str[i]; i++); write(2, "\033[31m", 5); write(2, str, i); write(2, "\033[0m", 4); }
C#
UTF-8
3,716
2.515625
3
[]
no_license
using CMSSample.DomainModel; using CMSSample.DomainModel.ViewModels; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; namespace CMSSample.DA.Repository { public class TaskRepository : ITaskRepository { private CMSSampleDAContext _context; public TaskRepository(CMSSampleDAContext cmssampledacontext) { this._context = cmssampledacontext; } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { _context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public IEnumerable<TaskDisplayViewModel> GetTasks() { using (_context) { List<Task> tasks = new List<Task>(); tasks = _context.Task.AsNoTracking() .Include(x => x.ODZCase) .Include(x => x.User) .Include(x => x.TaskType) .ToList(); if (tasks != null) { List<TaskDisplayViewModel> tasksDisplay = new List<TaskDisplayViewModel>(); foreach (var x in tasks) { var taskDisplay = new TaskDisplayViewModel() { TaskId = x.TaskId, TaskTypeId = x.TaskTypeID, TaskTypeName = x.TaskType.TaskTypeName, TaskDescription = x.TaskDescription, ODZCaseReference = x.ODZCase.ODZCaseReference, CompletedDate = Convert.ToString(x.CompletedDate), CreatedDate = Convert.ToString(x.CreatedDate), UserName = x.User.UserName, UserId = x.User.UserId, ODZCaseID = x.ODZCase.ODZCaseID }; tasksDisplay.Add(taskDisplay); } return tasksDisplay; } return null; } } public TaskEditViewModel GetTaskByID(int taskid) { var tasktypeRepo = new TaskTypeRepository(_context); var tsk = _context.Task.Where(x => x.TaskId == taskid).FirstOrDefault(); var tskedt = new TaskEditViewModel() { TaskId = tsk.TaskId, TaskTypeId = tsk.TaskTypeID, TaskDescription = tsk.TaskDescription, ODZCaseID = tsk.ODZCaseID, CreatedDate = tsk.CreatedDate, CompletedDate = tsk.CompletedDate, UserId = tsk.UserId, TaskTypes = tasktypeRepo.GetTaskTypes() }; return tskedt; } public void Delete(object id) { Task tsk = new Task(); tsk = _context.Task.Find(id); _context.Task.Remove(tsk); Save(); } public void InsertTask(Task task) { _context.Task.Add(task); Save(); } public void Save() { _context.SaveChanges(); } public void UpdateTask(Task task) { _context.Entry(task).State = EntityState.Modified; Save(); } } }
Shell
UTF-8
1,671
2.859375
3
[]
no_license
#!/bin/bash EVM_HOME=~/repos/EVidenceModeler-1.1.1/ genome=/uru/Data/Nanopore/projects/moth/2020_analysis/assemblies/racon_3d_dna/moth_canu_nanopolish_racon1.FINAL.fasta stringtie_gff3=/uru/Data/Nanopore/projects/moth/2020_analysis/sra_rna_data/stringtie2/stringtie2_merge/transcripts.fasta.transdecoder.genome.gff3 bam=/uru/Data/Nanopore/projects/moth/2020_analysis/sra_rna_data/bam genepred_gff3=/uru/Data/Nanopore/projects/moth/2020_analysis/annotation/masked_annotations/braker_masked/augustus.hints.gff3 out=/uru/Data/Nanopore/projects/moth/2020_analysis/annotation/masked_annotations/EVM protein_gff=/uru/Data/Nanopore/projects/moth/2020_analysis/annotation/braker/prothint.gff if [ "$1" == "partition" ] then $EVM_HOME/EvmUtils/partition_EVM_inputs.pl --genome $genome \ --gene_predictions $genepred_gff3 \ --transcript_alignments $stringtie_gff3 \ --segmentSize 100000 --overlapSize 10000 --partition_listing ${out}/partitions_list.out fi if [ "$1" == "run" ] then $EVM_HOME/EvmUtils/write_EVM_commands.pl --genome $genome --weights `pwd`/weights.txt \ --gene_predictions $genepred_gff3 \ --transcript_alignments $stringtie_gff3 \ --output_file_name evm.out --partitions ${out}/partitions_list.out > ${out}/commands.list fi if [ "$1" == "execute" ] then $EVM_HOME/EvmUtils/execute_EVM_commands.pl ${out}/commands.list | tee run.log $EVM_HOME/EvmUtils/recombine_EVM_partial_outputs.pl --partitions ${out}/partitions_list.out --output_file_name evm.out $EVM_HOME/EvmUtils/convert_EVM_outputs_to_GFF3.pl --partitions ${out}/partitions_list.out --output evm.out --genome $genome find . -regex ".*evm.out.gff3" -exec cat {} \; > EVM.all.gff3 fi
Markdown
UTF-8
744
2.625
3
[]
no_license
--- layout: post title: "Mac OSX 命令行快捷键" description: "Mac OSX Terminal Home End 快捷键" category: Mac_OS tags: [KeyBoardShortCuts] --- {% include JB/setup %} `系统:OSX 10.9.4` 1. 将光标移动到行首:ctrl + a 2. 将光标移动到行尾:ctrl + e 3. 清除屏幕: ctrl + l 4. 搜索以前使用命令:ctrl + r 5. 清除当前行: ctrl + u 6. 清除至当前行尾: ctrl + k 7. 单词为单位移动: option + 方向键 8. 新开命令行窗口: cmd + N 9. 新开命令行标签: cmd + T 10. 激活其他命令行窗口:cmd + 方向键左右 11. 激活命令行标签窗口:cmd + shift + 方向键左右 12. 关闭命令行窗口或标签:cmd + W 13. 退出命令行程序:cmd + Q
Python
UTF-8
714
2.90625
3
[]
no_license
from functools import reduce class Solution: def productExceptSelf(self, nums: List[int]) -> List[int]: from_left = nums[:] from_right = nums[:] for i in range(1, len(from_left)): curr = from_left[i] prev = from_left[i-1] from_left[i] = curr * prev for i in range(len(from_right)-2, -1, -1): curr = from_right[i] prev = from_right[i+1] from_right[i] = curr * prev for i in range(len(nums)): left = from_left[i-1] if i > 0 else 1 right = from_right[i+1] if i < len(nums)-1 else 1 nums[i] = left * right return nums
TypeScript
UTF-8
1,621
2.796875
3
[]
no_license
import {Field, ObjectType, registerEnumType} from 'type-graphql'; import { BaseEntity, Column, Entity, ManyToOne, PrimaryGeneratedColumn, } from 'typeorm'; import {ClosePrice} from './ClosePrice'; import {Instrument} from './Instrument'; export enum PositionState { OPEN = 'open', CLOSED = 'closed', DELETED = 'deleted', } export enum PositionType { SELL = 'sell', BUY = 'buy', } registerEnumType(PositionState, { name: 'PositionState', }); registerEnumType(PositionType, { name: 'PositionType', }); @ObjectType() @Entity() export class Position extends BaseEntity { @Field() @PrimaryGeneratedColumn() id: number; @Field() @Column('decimal', {precision: 19, scale: 8}) amount: number; @Field() @Column('decimal', {precision: 19, scale: 4}) price: number; // 3 letter abbreviation @Field() @Column('varchar', {length: 3, default: 'USD'}) currency: string; @Field() @Column('decimal', {precision: 19, scale: 4, default: 0}) commission: number; @Field(() => PositionState) @Column({type: 'enum', enum: PositionState, default: PositionState.OPEN}) state: PositionState; @Field() @Column('timestamp with time zone', { nullable: false, default: () => 'CURRENT_TIMESTAMP', }) date: Date; @Field(() => PositionType) @Column({type: 'enum', enum: PositionType, default: PositionType.BUY}) type: PositionType; @Field(() => Instrument) @ManyToOne(() => Instrument, {onDelete: 'CASCADE', eager: true}) instrument: Instrument; @Column() owner: string; @Field(() => ClosePrice, {nullable: true}) closePrice?: ClosePrice; }
Python
UTF-8
920
3.34375
3
[]
no_license
def print_floor(floor, i, j): for l in range(len(floor)): for m in range(len(floor[l])): if i == l and j == m: print('_ ', end="") else: print(str(floor[l][m]) + " ", end="") print() print() def clean(floor): for i in range(len(floor)): if i % 2 == 0: for j in range(len(floor[i])): if floor[i][j] == 1: floor[i][j]=0 print_floor(floor, i, j) else: for j in range(len(floor[i])-1, -1, -1): if floor[i][j] == 1: floor[i][j]=0 print_floor(floor, i, j) R = int(input("Enter the number of rows:")) floor = [] for i in range(0,R): a = list(map(int,input().split(" "))) floor.append(a) print("\n") print_floor(floor, -1, -1) clean(floor)
JavaScript
UTF-8
596
3.890625
4
[]
no_license
// http://www.codewars.com/kata/duplicate-arguments function solution (...args) { for (let i = 0; i < args.length - 1; i++) { if (args.findIndex((item, index) => item === args[i] && index > i) !== - 1) { return true; } } return false; } // http://www.codewars.com/kata/last function last (...list) { if (list.length > 1) { return list[list.length - 1]; } if (typeof list[0] === 'string') { const chars = list[0].split(''); return chars[chars.length - 1]; } if (Array.isArray(list[0])) { return list[0][list[0].length - 1]; } return list[0]; }
Java
UTF-8
906
3.375
3
[]
no_license
public class PalindromePermutation { public static boolean canPermutePalindrome(String s) { int[] sArray = new int[26]; char[] ch = s.toCharArray(); int countO = 0; String str = ""; for (int i = s.length() - 1; i >= 0; i--) { str += s.charAt(i); } if (str.equalsIgnoreCase(s)) { return true; } for (int i = 0; i < ch.length; i++) { sArray[ch[i] - 'a']++; } for (int i = 0; i < sArray.length; i++) { if (s.length() % 2 == 0) { if (sArray[i] % 2 != 0) { return false; } } if (s.length() % 2 != 0) { if (sArray[i] % 2 != 0) { countO++; } } } if (ch.length % 2 == 1 && countO != 1) { return false; } return true; } public static void main(String[] args) { boolean res = canPermutePalindrome("aabbccc"); System.out.print(res); } }
C++
UTF-8
238
2.546875
3
[]
no_license
#include "TextEditor.h" int main() { try { TextEditor* textEditor = new TextEditor("test.txt"); textEditor->run(); } catch (std::string s) { std::cout << s << std::endl; } catch (...) { std::cout << "Error"; } return 0; }
C#
UTF-8
582
2.828125
3
[ "MIT" ]
permissive
namespace ExtendedXmlSerializer.Core.Sources { /// <summary> /// A general purpose selection component that accepts a value and returns a value. /// </summary> /// <typeparam name="TParameter">The type to accept.</typeparam> /// <typeparam name="TResult">The return type.</typeparam> public interface IParameterizedSource<in TParameter, out TResult> { /// <summary> /// Performs the selection. /// </summary> /// <param name="parameter">The parameter to accept.</param> /// <returns>A value of the return type.</returns> TResult Get(TParameter parameter); } }
Java
UTF-8
296
1.773438
2
[]
no_license
package com.epam.demo.spring.dbaccess.repo; import com.epam.demo.spring.dbaccess.entities.Session; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface SessionRepo extends CrudRepository<Session, Integer> { }
Python
UTF-8
4,230
2.828125
3
[]
no_license
import math import requests import pandas as pd from persistence import PickleWrapper # Geopy from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent="my-application") # Distances are measured in miles. # Longitudes and latitudes are measured in degrees. # Earth is assumed to be perfectly spherical. earth_radius = 3963.0 degrees_to_radians = math.pi/180.0 radians_to_degrees = 180.0/math.pi geopy_results = PickleWrapper("./geopy_results.p") query_to_geocode = geopy_results.load() def get_location(query): # To limit usage, cache results. # https: // operations.osmfoundation.org/policies/nominatim/ if query in query_to_geocode: geocode = query_to_geocode[query] else: geocode = geolocator.geocode(query) query_to_geocode[query] = geocode geopy_results.dump(query_to_geocode) return (geocode.latitude, geocode.longitude) def gmaps_get_location(query): # Google APIs # Source: https://stackoverflow.com/questions/25888396/how-to-get-latitude-longitude-with-python response = requests.get( 'https://maps.googleapis.com/maps/api/geocode/json?address=' + query.replace(" ", "+")) resp_json_payload = response.json() loc = resp_json_payload['results'][0]['geometry']['location'] return (loc["latitude"], loc["longitude"]) def change_in_latitude(miles): """Given a distance north, return the change in latitude. Source: https://www.johndcook.com/blog/2009/04/27/converting-miles-to-degrees-longitude-or-latitude/ """ return (miles/earth_radius)*radians_to_degrees def change_in_longitude(latitude, miles): """Given a latitude and a distance west, return the change in longitude. Source: https://www.johndcook.com/blog/2009/04/27/converting-miles-to-degrees-longitude-or-latitude/ """ # Find the radius of a circle around the earth at given latitude. r = earth_radius*math.cos(latitude*degrees_to_radians) return (miles/r)*radians_to_degrees def get_bbox(location=(0, 0), lat_span_miles=2, lng_span_miles=2): lat, long = location lat_diff = change_in_latitude(lat_span_miles) / 2. long_diff = change_in_longitude(lat, lng_span_miles) / 2. return lat - lat_diff, lat + lat_diff, long - long_diff, long + long_diff def filter_region_points(data, address_query, lat_span_miles, lng_span_miles, lat_col="latitude", lng_col="longitude"): """Crop dataframe centered at @address_query. Returns: Filtered dataframe and bounding box coordinates. """ lat, lng = get_location(address_query) lat_min, lat_max, long_min, long_max = get_bbox( (lat, lng), lat_span_miles, lng_span_miles) return data[(data[lat_col] > lat_min) & (data[lat_col] < lat_max) & (data[lng_col] > long_min) & (data[lng_col] < long_max)], dict(lat_min=lat_min, lat_max=lat_max, long_min=long_min, long_max=long_max) def filter_region_trips(data, address_query, lat_span_miles, lng_span_miles, lat_col="latitude", lng_col="longitude", trip_col="trip_id"): """Crop dataframe centered at @address_query. Returns: Filtered dataframe and bounding box coordinates. """ lat, lng = get_location(address_query) return df_crop_trips(data, lat, lng, lat_span_miles, lng_span_miles, lat_col, lng_col, trip_col) def df_crop_trips(data, lat, lng, lat_span_miles,lng_span_miles, lat_col="latitude", lng_col="longitude", trip_col="trip_id"): lat_min, lat_max, long_min, long_max = get_bbox( (lat, lng), lat_span_miles, lng_span_miles) n_trips = 0 r_trips = 0 in_region_trips = [] for trip_id, df_trip in data.groupby(trip_col): n_trips += 1 if df_trip["latitude"].min() >= lat_min and df_trip["latitude"].max() <= lat_max \ and df_trip["longitude"].min() >= long_min and df_trip["longitude"].max() <= long_max: r_trips += 1 in_region_trips.append(df_trip) print("Trips cropped: {}/{}".format(r_trips, n_trips)) return pd.concat(in_region_trips), dict(lat_min=lat_min, lat_max=lat_max, long_min=long_min, long_max=long_max)
Markdown
UTF-8
7,479
2.578125
3
[]
no_license
# Corsair Bragi Protocol Version ?? Based on [this](https://github.com/ckb-next/ckb-next/wiki/Corsair-Protocol), and some Wireshark captures from M55 RGB PRO. ## Guidance If bytes are omitted from the response, it means that we don't think they matter. If we aren't sure what a command does, we'll put the dubious command in *italics*. ## What we know so far All packets have a 64 byte payload, padded with zeroes. <s>The first four bytes of the command are echoed in the response packet.</s> <s>The protocol is poll based - the mouse may reply to an `0e` command with an arbitrary amount of `01` events terminated with an `03` event before replying.</s>(TODO check if this holds true here) The protocol uses USB URB interrupts - URB control packets work on only tested device (M55 RGB PRO). All responses from the device starts with 00 and echoes back 2nd byte of the request, so all packets with responses longer than 2 should be for reading back data from mouse? If I forgot about response assume it's just these two bytes and nothing more * 00 * 02 XX device -> host, pressed buttons * * 08 host -> device * 01 -set * 02 - get * 06 * 00 06 00 00 00 ff- logo color * 00 - send payload, first packet, possibly only in firmware mode * 07 - send payload all pakcets except 1st one * ## Host to device ## `08` fields ### `08` - Everything? Almost all commands sent to the device starts with 08, except one used when flashing firmware ### *`08 01` - Control/set mouse settings* ## `08 01 01 00 XX` - polling rate * 1 - 125Hz * 2 - 250Hz * 3 - 400Hz * 4 - 1000Hz ## `08 01 02 00 XX XX` - mouse brightness * 0 * 330, little endian * 660 - 66% * 1000 - 100% ## `08 01 52 00 xx` - handeness * 01 - left hand * 00 - right hand ### `08 01 03 00 XX` - Set mode * 01 - hardware mode * This is the only command iCUE sends when it closes, changing control from software to hardware * 02 - software mode * 03 - firmware update mode? ## *`08 02` - get* ### `08 02 01` - ? ### `08 02 03` - mode * response `00 02 XX` * 1 - hardware mode * 2 - software mode * 3 - *firmware update mode?* ### `08 02 11` - vendor id ### `08 02 12` - product id ### `08 02 13` - firmware version Returned as `00 02 00 Major minor patch` For v.4.6.22 it's `00 02 00 04 06 16` ### `08 02 14` - bootloader version ### `08 02 52` - ? ### `08 02 5f` - ? ## 08 - lights, DPI ### *`08 18` - `08 2f` - DPI* When changing DPI values iCUE always sends 13 packets, 1 at the start, 2*5modes (DPI and color) and 2 at the end. This mouse has 5 DPI modes, but iCUE also defines "sniper" mode with yellow light and stiff, I haven't seen packets for that yet. DPI is Litte indian, probably 2 bytes (could be 3), color is BGR, 1 byte per color ``` 08 01 20 00 20 03 - Set default DPI 08 01 18 00 20 03 (1st mode) 08 01 2f 00 00 00 ff (RED) 08 01 19 00 40 06 (2nd mode dpi) 08 01 30 00 ff ff ff (white) 08 01 1a 00 b8 0b (3rd mode, 300dpi) 08 01 31 00 00 ff 00 (GREEN) 08 01 1b 00 70 17 (4th mode dpi) 08 01 32 00 80 00 80 (ugly pink) 08 01 1c 00 28 23 (5th mode, 9000) 08 01 33 00 ff bf 00(color, light blue) 08 01 1f 00 1f 00 00 80 00 00 - enabled modes ^^ 1000 0000 - 0x80 - all (5?) modes active 0000 1111 - 0x0f - 5th disabled 0001 1101 - 0x1d- 2nd disabled 08 01 1e 00 00 00 00 ?? ``` `08 01 18` - `08 01 ??` - DPI value for each mode (max 20 but it seems to have special meaning?) `08 01 2f` - `08 01 ??` - color settings for each DPI mode (max 33??) 1st mode uses `08 01 18` to set value and `08 01 2f` to set color, 2nd uses `19` and `30` etc. ### `08 06 00 06 00 00 00 RD RL GD GL BD BL OL` - Change color This command changes logo color, RL GL BL is 8bit color value, OL is opacity 00-FF DPI color is RD, GD, BD ## Device to host ### `00 02 XX` - buttons pressed down, padded with 00 to 64 XX bits from MSB: * DPI * right side top * right side bottom * left side top * left side bottom * scroll button * left * right So 82 would be DPI + left mouse buttons held down these are sned as stander HID messages, nevermind then * <s> `00 00 00 00 00 00 00 00 ff`- Scroll up</s> * <s> `00 00 00 00 00 00 00 00 01`- Scroll down</s> ## Software Thisgs that seems to be handled completely insoftwarte (no USB packets with that data): * sniper mode (although after change it sends all DPI data for modes 1-5 anyway, might be GUI thing) * enable all side buttons ## WHen iCUE kicks in * send, many (all?) packets can be in different order, iCUE also rearranges them or doesn't send some of them if they are set correctly already (polling rate?) * R returned by mouse * `08 02 03` - **get mode** * R `00 02 00 01` - hardware mode * `08 01 03 00 02` - **set software mode** * R `00 01` * `08 02 03` - **get mode** * R `00 02 00 02` - software * `08 02 5f` (37) * R `00 02 05` * `08 02 01` * R `00 02 00 01` * `08 02 03`- **get mode** * R `00 02 00 02` * `08 02 11` - **product id** * R `00 02 00 1c 1b` - 1b1c - Corsair * `08 02 12` - **product id** * R `00 02 00 70 1b` 1b70 - M55 * `08 02 13` - **get firmware version** * R `00 02 00 04 06 16` - 4.6.22 * `08 02 14` - **get bootloader version** * R `00 02 00 04 05 0d` 4.5.13 * `08 01 03 00 02` - **set software mode** * R `00 01` * `08 01 02 00 e8 03` - **brightness** 100.0% * R `00 01` * `08 02 52` * R `00 02` * `08 01 52 00 01` - this was sent just once over all 15 tries, never again, weird... * R `00 01` * `08 0d 00 02 ` * R `00 0d` * `08 06 00 08 00 00 00 01 01 01 00 00 01 01` * R `00 06` * `08 05 01` * R `00 05` * `08 01 20 00 dc 05` **default DPI, 9000** * R `00 01` * `08 0d 00 01` * R `00 0d` * `08 06 00 06 00 00 00 ff 00 ff 03 ff ff` - **DPI and logo colors** * R `00 06` * `08 0d 01 02` * R `00 0d` * `08 06 01 08 00 00 00 01 01 01` * R `00 06` * `08 05 01 01 00 04` * R `00 05` Sidenote * `08 06 00 06 00 00 00 RD RL GD GL BD BL OL` * RD, GD, BD - DPI colors * RL, GL, BL - logo colors * OL - logo opcaity ### Firmware update See firmware.pcapng * `08 01 03 00 01` **set hardware mode** * gets decriptor after that, including BP00 and serial number * `08 02 03` - **get mode** * R`00 02 00 01` - firmware?? mode * `00 01 03 00 03` *set firmware update mode?* * then it reboots, probably in firmware update mode * mouse sends over: * 128 `00 00 00 00 00 00 00 00 00 ca a4 03 00 f8 ff ff 00 00 00 00 00 00 00 00 20 4b 00 00 00 00 00 00 5f 4b 00 00 00 00 00 00 07 00 00 00 00 00 00 84` * over endpoint 3?? All CUE packets so long travelled over endpoint 4 * 130 `00 02 00 01` * 132 `00 01` * 134 `00 00 00 00 00 00 00 00 00 ca a4 03 00 f8 ff ff 00 00 00 00 00 00 00 00 10 4f 00 00 00 00 00 00 4f 4f 00 00 00 00 00 00 03 00 00 00 00 00 00 84` * over endpoint 3?? All CUE packets so long travelled over endpoint 4 * 140 `00 02 00 01` * 142 `00 01` * then it reboots, possibly in firmware update mode --- AFTER REBOOT OR WHATEVER: * 181 `08 0d 00 03` ?? * R `00 0d` * 185 `08 06 00 XX XX 00 00 PL ... PL` - first package of the payload * XX is size, little endian, then 57 bytes of payload * `08 07 00 PL ... PL` - 61 bytes of payload * last payload is padded with 00 * `08 05 01` ?? * `00 10` ?? * strangest OUTGOING packet, first one that doesn't start with 08 * then mouse returns just `40 00` (64 in dec, no 00 at the start!) and reboots *
Java
UTF-8
377
1.789063
2
[]
no_license
package com.bai.dao; import com.bai.Video; import org.springframework.stereotype.Repository; @Repository public interface VideoDao { //上传视频 int addVideo(Video video); //删除视频 int deleteVideo(int id); //修改视频 int updateVideo(Video video); //查询上传视频 Video selUpVideo(int userId); //查询收藏视频 }
C#
UTF-8
1,074
2.78125
3
[ "MIT" ]
permissive
using System; using System.Linq.Expressions; using System.Text.RegularExpressions; using System.Xml; namespace Highway.Data.OData.Parser.Readers { internal class DateTimeExpressionFactory : ValueExpressionFactoryBase<DateTime> { private static readonly Regex DateTimeRegex = new Regex(@"datetime['\""](\d{4}\-\d{2}\-\d{2}(T\d{2}\:\d{2}\:\d{2}(.\d+)?)?(?<z>Z)?)['\""]", RegexOptions.Compiled | RegexOptions.IgnoreCase); public override ConstantExpression Convert(string token) { var match = DateTimeRegex.Match(token); if (match.Success) { var dateTime = match.Groups["z"].Success ? XmlConvert.ToDateTime(match.Groups[1].Value, XmlDateTimeSerializationMode.Utc) : DateTime.SpecifyKind(DateTime.Parse(match.Groups[1].Value), DateTimeKind.Unspecified); return Expression.Constant(dateTime); } throw new FormatException("Could not read " + token + " as DateTime."); } } }
Python
UTF-8
1,409
2.984375
3
[]
no_license
import tkinter as tk from tkinter import filedialog from PyPDF2 import PdfFileMerger class pdfmerger: def __init__(self, window_width, window_height): self.root = tk.Tk() self.root.title("PDF merger") center_x = int(self.root.winfo_screenwidth() / 2 - window_width / 2) center_y = int(self.root.winfo_screenheight() / 2 - window_height / 2) self.root.resizable(False, False) self.filenames= [] self.root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}') def UI(self): self.listbox = tk.Listbox(self.root) self.listbox.pack() self.choose_button = tk.Button(self.root, text="Choose Files", command=self.choose_files) self.choose_button.pack() self.merge_button = tk.Button(self.root, text="Merge Files", command=self.merge_files) self.merge_button.pack() def choose_files(self): FILEOPENOPTIONS = dict(defaultextension=".pdf", initialdir="/Users/maciejprzydatek/Desktop", filetypes=[('pdf file', '*.pdf')]) self.filenames = filedialog.askopenfilenames(**FILEOPENOPTIONS) for i in range(0,len(self.filenames)): self.listbox.insert(i,self.filenames[i]) print(self.filenames) def merge_files(self): pass def program_start(self): self.UI() self.root.mainloop()
Java
UTF-8
635
1.789063
2
[ "Apache-2.0" ]
permissive
package io.quarkus.stork; import java.util.Map; import io.quarkus.runtime.annotations.ConfigGroup; import io.smallrye.config.WithParentName; @ConfigGroup public interface StorkServiceRegistrarConfiguration { /** * Configures service registrar type, e.g. "consul". * A ServiceRegistrarProvider for the type has to be available * */ String type(); /** * Service Registrar parameters. * Check the documentation of the selected registrar type for available parameters * */ // @ConfigItem(name = ConfigItem.PARENT) @WithParentName Map<String, String> parameters(); }
Java
UTF-8
1,691
2.15625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2019 JSquad AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.jsquad.authorization; import se.jsquad.qualifier.Log; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @Path("") public class Authorization { @Inject @Log private Logger logger; @Context private HttpServletRequest request; @Context private HttpServletResponse response; public boolean isAuthorized() throws IOException, ServletException { logger.log(Level.FINE, "authenticateUser(), request: {0}, response: {1}", new Object[] {request, response}); return request.authenticate(response); } public boolean isUserInRole(String role) { logger.log(Level.FINE, "isUserInRole(role: {0})", new Object[] {role}); return request.isUserInRole(role); } public void logout() throws ServletException { request.logout(); } }
Ruby
UTF-8
646
4.0625
4
[]
no_license
=begin The British Empire adopted the Gregorian Calendar in 1752, which was a leap year. Prior to 1752, the Julian Calendar was used. Under the Julian Calendar, leap years occur in any year that is evenly divisible by 4. Using this information, update the method from the previous exercise to determine leap years both before and after 1752. =end def leap_year?(year) if year > 1752 return true if year % 4 == 0 unless year % 100 == 0 return false unless year % 400 == 0 return true else return true if year % 4 == 0 return false end end leap_year?(2016) == true leap_year?(2015) == false leap_year?(2100) == false
Markdown
UTF-8
3,349
2.78125
3
[]
no_license
--- title: MetroChange url: metrochange comments: false layout: project largeimages: ["https://c2.staticflickr.com/8/7002/6549641145_1072356ce0_b.jpg","https://c2.staticflickr.com/8/7148/6549640559_aef3ed99ca_b.jpg","https://c2.staticflickr.com/8/7144/6495568579_147f3e3ba4_b.jpg"] largeimagecaptions: ["The MetroChange kiosk","The value of the card is read, and added to a total value. The user is asked to discard their Metrocard for recycling.","Inside the MetroChange kiosk."] smallimage: /g/work-metrochange.jpg indeximage: /g/metrochange.jpg writeup: type: device, service year: 2011 categories: [work] is_primary: false tags: [metrochange, philanthropy] date: 30-12-2011 strapline: Donate your unused subway cards to charity. description: In 2011, Genevieve Hoffman, Stepan Boltalin and I proposed MetroChange, a micro-donation platform that would allow users of the New York City transit systems to donate the small amounts of remaining value on their Metrocards to charity. video: <iframe src="https://player.vimeo.com/video/33804080" width="700" height="394" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> references: ["http://www.fastcocreate.com/1679328/how-they-did-it-the-high-and-low-tech-behind-metrochange","http://www.good.is/post/spare-change-for-social-change-can-wasted-subway-fees-be-used-for-public-good/","https://www.flickr.com/photos/paulmmay/albums/72157627902422144"] referencetitles: ["How They Did It: The High And Low Tech Behind MetroChange - Fast Company Co-Create","MetroChange Could Turn Wasted Subway Fees Into Public Good - GOOD Magazine","More photos of MetroChange, the process, and prototypes"] --- When the project started, we knew (anecdotally) that it was common for Metrocards to be discarded with small amounts of remaining value. We wondered what this waste meant at scale, and what factors in the design of the Metrocard system lead to waste. We tackled this project from a number of different angles. We did cent by cent analysis of the NYC subway fare system, and an evaluation of the HCI of Metrocard vending machines. We saw that some price points highlighted for "quick purchase" in the Metrocard vending machine UI resulted in the most amount of wasted value on Metrocards. We found a reliable source that estimated the value of waste left on discarded Metrocards at over $50m each year. Spurred on by these findings, we proposed an alternative to this waste; a micro-donation service that would see remaining value diverted to charities. We built a magnetic card reader capable of decoding the data stored New York City Metrocards, including the remaining value stored on the card in dollars and cents. Technically, this was very challenging, since the physical design of Metrocards differs from many magnetic stripe designs. We built prototype after prototype, until we had a working system. We brought a fully working Metrochange kiosk out onto the streets of New York, and tested it with passers by. We met with city officials to discuss the project, as well as potential charity parters. The project received widespread press coverage, and prompted a real conversation about the design of the Metrocard system. Ultimately, we recognized that there was no way the MTA would agree to donate or divert $50m of revenue, but we had a lot of fun posing the question.