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
|
|---|---|---|---|---|---|---|---|
JavaScript
|
UTF-8
| 1,825
| 2.84375
| 3
|
[] |
no_license
|
// Условия задачи
// Добавьте в шаблон страницы home список со свойством name из следующего массива:
// ```
// var people = [{name: 'Vasya', age: 20, email: 'vasya@mail.ru', employed: false},
// {name: 'Masha', age: 25, email: 'm@m', employed: true},
// {name: 'Petya', age: 27, email: 'petya@stuff', employed: true},
// {name: 'John', age: 36, email: 'johnDoe@mail', employed: true},
// {name: 'Jane', age: 28, email: 'janeDoe@mail', employed: false}]
// ```
// Добавьте на страницу поддержку htm5Mode.
myModule.controller ('MainCtrl', MainCtrl);
myModule.controller ('HomeCtrl', HomeCtrl);
myModule.config (Routes);
Routes.$inject = ['$routeProvider','$locationProvider'];
function Routes($routeProvider,$locationProvider) {
$routeProvider
.when ('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl'
})
.when ('/contact', {
templateUrl: 'views/contact.html',
})
.otherwise ({
redirectTo: '/'
});
// $locationProvider.html5Mode (true);
// $locationProvider.hashPrefix('!');
$locationProvider.html5Mode({
enabled: true,
requireBase: true
});
}
//============== CONTROLLER ===============
MainCtrl.$inject = ['$scope'];
function MainCtrl($scope) {
}
HomeCtrl.$inject = ['$scope'];
function HomeCtrl($scope) {
$scope.people = [
{name: 'Vasya', age: 20, email: 'vasya@mail.ru', employed: false},
{name: 'Masha', age: 25, email: 'm@m', employed: true},
{name: 'Petya', age: 27, email: 'petya@stuff', employed: true},
{name: 'John', age: 36, email: 'johnDoe@mail', employed: true},
{name: 'Jane', age: 28, email: 'janeDoe@mail', employed: false}
]
}
|
C#
|
UTF-8
| 1,044
| 2.59375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ShegzstuffPC.Models
{
class WhatsappUrl : INotifyPropertyChanged
{
private string zewhatsappurl;
public WhatsappUrl()
{
}
public WhatsappUrl(string zewhatsappurl)
{
ZeWhatsappUrl = zewhatsappurl;
}
public string ZeWhatsappUrl
{
set
{
if (zewhatsappurl != value)
{
zewhatsappurl = value;
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs("ZeWhatsappUrl"));
}
}
}
get
{
return zewhatsappurl;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
|
Java
|
UTF-8
| 2,940
| 3.8125
| 4
|
[] |
no_license
|
///name: date:
//first program on queues.
import java.io.*;
import java.util.*;
public class SongQueue
{
private static Scanner infile;
private static Queue<String> songQueue;
public static void main(String[] args) throws Exception
{
fillPlayList();
printSongList();
infile = new Scanner(System.in);
String prompt = "\tAdd song (A), Play song (P), Delete song (D), Quit (Q): ";
System.out.print(prompt);
String str = infile.next().toUpperCase();
while(!str.equals("Q"))
{
processRequest( str );
System.out.print(prompt);
str = infile.next().toUpperCase();;
}
System.out.println();
System.out.println("No more music for you today. Goodbye!");
infile.close();
}
public static void fillPlayList()throws IOException
{
songQueue = new LinkedList<String>();
Scanner sc = new Scanner(new File("songs.txt"));
while(sc.hasNext())
{
songQueue.add(sc.nextLine());
}
}
public static void processRequest(String str)
{
if(str.equalsIgnoreCase("A"))
{
add();
}
else if(str.equalsIgnoreCase("P"))
{
play();
}
else if(str.equalsIgnoreCase("D"))
{
delete();
}
else
{
String prompt = "\tAdd song (A), Play song (P), Delete song (D), Quit (Q): ";
System.out.print("Not a valid command." + prompt);
}
}
public static void add() //ADD A SONG
{
Scanner sc = new Scanner(System.in);
System.out.print("Song to add?");
String s = sc.nextLine();
songQueue.add(s);
printSongList();
}
public static void play() //PRINT CURRENT SONG
{
String song = songQueue.poll();
System.out.println("Now playing: " + song);
printSongList();
}
public static void delete() //DELETE A SONG
{
Scanner sc = new Scanner(System.in);
System.out.print("Song to delete (exact match): ");
String cfius = sc.next();
Queue<String> q = new LinkedList();
while(songQueue.peek() != null)
{
String s = songQueue.poll();
q.add(s);
}
while(q.peek() != null)
{
String str = q.poll();
if(!str.equals(cfius))
songQueue.add(str);
}
printSongList();
}
public static void printSongList() ///PRINT SONGS
{
Queue<String> temp = new LinkedList<String>();
System.out.print("Your music queue: [");
String queue = "";
while(songQueue.peek() != null)
{
String s = songQueue.poll();
temp.add(s);
queue += s + ", ";
}
queue = queue.substring(0, queue.length()-2);
System.out.println(queue + "]");
while(temp.peek()!=null)
{
songQueue.add(temp.poll());
}
}
}
|
Java
|
UTF-8
| 799
| 3.015625
| 3
|
[] |
no_license
|
package com.sergeev.task1.creator;
import com.sergeev.task1.entity.IntArrayWrapper;
import com.sergeev.task1.exception.IntArrayWrapperException;
import java.util.Random;
public class ArrayRandomCreator {
private static final int RANDOM_NUMBER_OF_ARRAY = 900;
private static final Random random = new Random();
public IntArrayWrapper createRandomIntArrayWrapper(int maxSizeOfArray) throws IntArrayWrapperException {
if (maxSizeOfArray < 1) {
throw new IntArrayWrapperException("Invalid size");
}
int length = random.nextInt(maxSizeOfArray);
int[] array = new int[length];
for (int i = 0; i < length; i++) {
array[i] = random.nextInt(RANDOM_NUMBER_OF_ARRAY);
}
return new IntArrayWrapper(array);
}
}
|
C#
|
UTF-8
| 2,622
| 2.890625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CsvHelper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace OutputFormatterSample.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PersonsController : ControllerBase
{
[HttpPost]
public ActionResult<object> Post(
[ModelBinder(binderType: typeof(PersonsCsvBinder))]
IEnumerable<Person> persons)
{
return new
{
ItemsRead = persons.Count(),
Persons = persons
};
}
}
[ModelBinder(BinderType = typeof(PersonsCsvBinder))]
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string EmailAddress { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Phone { get; set; }
}
public class PersonsCsvBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var modelName = bindingContext.ModelName;
if (String.IsNullOrEmpty(modelName))
{
modelName = bindingContext.OriginalModelName;
}
if (String.IsNullOrEmpty(modelName))
{
return Task.CompletedTask;
}
// Try to fetch the value of the argument by name
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var value = valueProviderResult.FirstValue;
// Check if the argument value is null or empty
if (String.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
var stringReader = new StringReader(value);
var reader = new CsvReader(stringReader);
var model = reader.GetRecords<Person>().ToList();
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;
}
}
}
|
C++
|
UTF-8
| 4,014
| 3.296875
| 3
|
[] |
no_license
|
#include <iostream>
#include <cstdbool>
#include <vector>
#include <queue> //queue and priority queue
#include <map>
#include <utility> //for pairs
using namespace std;
//GRAPH-------------------
#define INF INT_MAX
typedef pair<int, int> ii; // vertex, weight
typedef map<int, vector<ii> > GRAPH; //graph contains no negative-weight edges,
void add_edge(GRAPH& g, int src, int dest, int wt);
void dfs_graph(GRAPH& g, int src, vector<bool>& visited);
void bfs_graph(GRAPH& g, int src);
void print_graph(GRAPH& g);
void create_graph(GRAPH& g);
void dijkstra(GRAPH& g, int src); //single-source shortest paths
//------------------------
void create_graph(GRAPH& g){
add_edge(g, 0, 1, 50); // u-------wt------v
add_edge(g, 0, 2, 100);
add_edge(g, 0, 3, 75);
add_edge(g, 1, 0, 50);
add_edge(g, 1, 4, 60);
add_edge(g, 1, 5, 80);
add_edge(g, 2, 0, 100);
add_edge(g, 2, 6, 200);
add_edge(g, 3, 0, 75);
add_edge(g, 3, 7, 120);
add_edge(g, 4, 1, 60);
add_edge(g, 4, 7, 55);
add_edge(g, 5, 1, 80);
add_edge(g, 5, 7, 78);
add_edge(g, 6, 2, 200);
add_edge(g, 6, 7, 30);
add_edge(g, 7, 3, 120);
add_edge(g, 7, 6, 30);
add_edge(g, 7, 4, 55);
add_edge(g, 7, 5, 78);
}
int main(){
GRAPH g;
create_graph(g);
cout << "GRAPH: \n"; print_graph(g); cout << endl;
vector<bool> visited;
for(int i=0; i < g.size(); i++){
visited.push_back(false);
}
cout << "DFS: "; dfs_graph(g, 0, visited); cout << endl;
cout << "BFS: "; bfs_graph(g, 0); cout << endl;
cout << "\nDijkstra: ";
dijkstra(g, 0);
cout << endl;
return 0;
}
void add_edge(GRAPH& g, int src, int dest, int wt){
g[src].push_back(make_pair(dest, wt));
}
void print_graph(GRAPH& g){
GRAPH:: iterator itr;
for(itr=g.begin(); itr != g.end(); itr++){
cout << itr->first << ": ";
vector<ii>& v = itr->second; //neighbours of a vertex
for(int i=0; i<v.size(); i++){
cout << v[i].first << "|"<< v[i].second << " -> ";
}
cout << endl;
}
}
void dfs_graph(GRAPH& g, int src, vector<bool>& visited){
visited[src] = true;
cout << src << "->";
vector<ii>& v = g[src];
for(int i=0; i<v.size(); i++){
if(!visited[v[i].first]){
dfs_graph(g, v[i].first, visited);
}
}
}
void bfs_graph(GRAPH& g, int src){
vector<bool> visited;
for(int i=0; i<g.size(); i++){
visited.push_back(false);
}
queue<int> q;
q.push(src);
visited[src] = true;
while(!q.empty()){
int curr = q.front(); q.pop ();
cout << curr << "->";
vector<ii>& v = g[curr];
for(int i=0;i <v.size(); i++){
if(!visited[v[i].first]){
visited[v[i].first] = true;
q.push(v[i].first);
}
}
}
}
void dijkstra(GRAPH& g, int src){
vector<int> distance;
for(int i=0; i<g.size(); i++){
distance.push_back(INF);
}
distance[src] = 0;
//NOTE: make sure, wt is the first element in pair for pq,
// since we want MIN-Heap according to wt
priority_queue<ii, vector<ii>, greater<ii> > pq; //min_heap of pair
pq.push(make_pair(0, src)); //wt as first element in pair
while(!pq.empty()){
int u = pq.top().second; //min distance vertex, //initially src only
pq.pop();
vector<ii>& adj = g[u]; //take its neighbours // u(curr_src)-------wt------v
for(int i=0; i<adj.size(); i++){
int v = adj[i].first;
int wt = adj[i].second;
if(distance[v] > distance[u] + wt){
distance[v] = distance[u] + wt;
pq.push(make_pair(distance[v], v)); //push it to pq as distance is now not INF
}
}
}
cout << "Source: " << src << endl;
cout << "vertex \tdistance" << endl;
for(int i=0; i<g.size(); i++){
cout << i << "\t" << distance[i] << endl;
}
}
|
Java
|
UTF-8
| 4,929
| 2.640625
| 3
|
[] |
no_license
|
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.StringTokenizer;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
//이영준
public class ChatClient extends JFrame implements ActionListener, Runnable{
//JFrame-center
JPanel centerPane = new JPanel(new BorderLayout());
JPanel connPane = new JPanel(new BorderLayout());
JTextField connTf = new JTextField();
JButton connBtn = new JButton("접속");
JTextArea msgTa = new JTextArea();
JScrollPane msgSp = new JScrollPane(msgTa);
JPanel sendPane = new JPanel(new BorderLayout());
JTextField sendTf = new JTextField();
JButton sendBtn = new JButton("보내기");
//JFrame-East
JPanel eastPane = new JPanel(new BorderLayout());
JLabel listTitle = new JLabel(" 접속자리스트 ");
DefaultListModel<String> nameModel = new DefaultListModel<String>();
JList<String> nameList = new JList<String>(nameModel);
JScrollPane nameListSp = new JScrollPane(nameList);
JLabel connCountLbl = new JLabel("현재원 : 0명");
Socket s;
PrintWriter pw;
BufferedReader br;
public ChatClient() {
//JFrame-center
add(centerPane);
centerPane.add("North", connPane);
connPane.add(connTf);
connPane.add("East",connBtn);
centerPane.add(msgSp);
msgTa.setBackground(Color.LIGHT_GRAY);
centerPane.add("South", sendPane);
sendPane.add(sendTf);
sendPane.add("East", sendBtn);
///////Border ///////////////////
LineBorder lineBorder = new LineBorder(Color.GREEN);
TitledBorder tBorder = new TitledBorder(lineBorder, "Message", TitledBorder.CENTER, TitledBorder.ABOVE_TOP);
centerPane.setBorder(tBorder);
/////////////////////////////////
//JFrame-East
add("East", eastPane);
eastPane.add("North",listTitle);
nameModel.addElement("");
eastPane.add(nameListSp);
eastPane.add("South", connCountLbl);
setSize(700,500);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//이벤트 등록
connTf.addActionListener(this);
connBtn.addActionListener(this);
sendTf.addActionListener(this);
sendBtn.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
Object eObj = ae.getSource();
if(eObj == connTf || eObj == connBtn) {
//서버연결
serverConnection();
}else if(eObj == sendTf || eObj == sendBtn) {
//문자보내기
if(sendTf.getText().equals("")) {
JOptionPane.showMessageDialog(this, "메세지를 입력 후 보내기를 선택하세요.");
}else {
pw.println(sendTf.getText());
pw.flush();
sendTf.setText("");
}
}
}
//통신 메소드
public void serverConnection() {
if(connTf.getText().equals("")) {
JOptionPane.showMessageDialog(this, "ip를 입력 후 접속하세요.");
}else {
try {
InetAddress ia = InetAddress.getByName(connTf.getText());
s = new Socket(ia,15000);
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
//이미 연결되면 다시 접속못하도록 접속을 비활성화
connTf.setEnabled(false);
connBtn.setEnabled(false);
Thread t = new Thread(this);
t.start();
}catch(Exception e) {
}
}
}
public synchronized void run() {
while(true) {
try {
String inData = br.readLine();
if(inData != null) {
String header = inData.substring(0,6);
if(header.equals("$$NG##")) {//접속자정보알림
msgTa.append(inData.substring(6)+"\n");//6번쨰 index부터 끝까지
}else if(header.equals("!&CN!&")) {//인원수
connCountLbl.setText("현재원 : "+inData.substring(6) +"명");
}else if(header.equals("@@Cl$%")) {//접속자목록
//192.168.55.126/192.168.5.4/와 같이 목록출력
setConnectionListReset(inData.substring(6));
}else if(header.equals("$#MG^%")) {
msgTa.append(inData.substring(6)+"\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void setConnectionListReset(String nameList) {
StringTokenizer st = new StringTokenizer(nameList, "/");
nameModel.removeAllElements();//기존 목록 제거
while(st.hasMoreTokens()) {
nameModel.addElement(st.nextToken());
}
}
public static void main(String[] args) {
new ChatClient();
}
}
|
Java
|
UTF-8
| 1,870
| 3.640625
| 4
|
[] |
no_license
|
public class ListApp {
public static void main(String[] args){
FirstList<String> stringFirstList = new FirstList<>(7);
FirstList<Square> squareFirstList = new FirstList<>();
FirstList<PointClass> point3dFirstList = new FirstList<>(4);
stringFirstList.addItem("Nathan Johnson");
stringFirstList.addItem("Dylan Diedrich");
stringFirstList.addItem("JimBob");
stringFirstList.addItem("Chris Evans");
stringFirstList.addItem("Colin");
stringFirstList.addItem("Chris");
stringFirstList.addItem("Jonathan");
squareFirstList.addItem(new Square(6));
squareFirstList.addItem(new Square(14));
squareFirstList.addItem(new Square(9));
squareFirstList.addItem(new Square(27));
squareFirstList.addItem(new Square(13));
squareFirstList.addItem(new Square(45));
squareFirstList.addItem(new Square(77));
squareFirstList.addItem(new Square(15));
squareFirstList.addItem(new Square(23));
squareFirstList.addItem(new Square(6));
point3dFirstList.addItem(new PointClass(5,3,9));
point3dFirstList.addItem(new PointClass(4,6,8));
point3dFirstList.addItem(new PointClass(1,5,3));
point3dFirstList.addItem(new PointClass(6,0,4));
System.out.println("print string list");
for (int i = 0; i < stringFirstList.size(); i++) {
System.out.println(stringFirstList.getItem(i));
}
System.out.println("\nprint square list");
for (int i = 0; i < squareFirstList.size(); i++) {
System.out.println(squareFirstList.getItem(i).toString());
}
System.out.println("\nprint 3d point list");
for (int i = 0; i < point3dFirstList.size(); i++) {
System.out.println(point3dFirstList.getItem(i).toString());
}
}
}
|
Java
|
UTF-8
| 2,041
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package models;
import java.util.List;
import javax.persistence.*;
import play.data.validation.Constraints.Required;
import play.db.ebean.Model;
import play.db.ebean.Model.Finder;
@Entity
public class Location extends Model {
static Finder<Integer, Location> find = new Finder<Integer, Location>(Integer.class, Location.class);
static Finder<Integer, Restaurant> findRestaurnt = new Finder<Integer, Restaurant>(Integer.class, Restaurant.class);
@Id
public Integer id;
@Required
public String city;
@Required
public String street;
@Required
public String number;
@OneToOne
public User user;
public Location( String city,String street, String number){
this.city = city;
this.street = street;
this.number = number;
}
public static boolean create(int id, String city, String street, String number){
Location location = find.byId(id);
if(location != null){
return false;
} else {
new Location(city, street, number).save();
}
return true;
}
public void createLocation(String city, String street, String number){
new Location(city, street, number).save();
}
public static boolean create(Location l){
Location location = find.findUnique();
if(location != null){
return false;
} else {
l.save();
}
return true;
}
public static boolean delete(int id){
Location l = Location.findByID(id);
l.delete();
if (findByID(id)!=null){
return false;
}
return true;
}
public static Location findByID(int id){
return find.byId(id);
}
public static Location findByCity(String city){
return find.where().eq("city", city).findUnique();
}
public static List<Location> all(){
return find.all();
}
public static List<Location> all(int id){
return find.where().eq("id", id).findList();
}
public static List<Location> all(Restaurant restaurant){
return find.where().eq("restaurant", restaurant).findList();
}
public static List <Restaurant> all(String city){
return findRestaurnt.where().eq("city", city).findList();
}
}
|
C++
|
UTF-8
| 2,491
| 2.53125
| 3
|
[] |
no_license
|
// 题意:把一个图,添加一些边,变成一个大环
//shuangde
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <cstring>
#include <string>
#include <map>
#include <set>
#define MP make_pair
#define SQ ((x)*(x))
#define CLR(a,b) memset(a, (b), sizeof(a))
#define cmax(a,b) a=max(a, (b))
#define cmin(a,b) a=max(a, (b))
#define rep(i, n) for(int i=0;i<n;++i)
#define ff(i, n) for(int i=1;i<=n;++i)
using namespace std;
typedef pair<int, int >PII;
typedef long long int64;
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
const double eps = 1e-8;
const int N = 60;
int n, m, deg[N], f[N];
bool vis[N];
PII E[2600];
inline void init () { for (int i = 1; i <= n; ++i) f[i] = i; }
int find(int x) {return x==f[x]?x:f[x]=find(f[x]);}
bool merge(int x, int y) {
int a = find(x), b = find(y);
if (a==b) return false;
f[a] = b;
return true;
}
int check() {
if (m > n) return -1;
init();
CLR(vis, 0);
CLR(deg, 0);
int cnt = 0;
for (int i = 0; i < m; ++i) {
if (++deg[E[i].first] > 2 || ++deg[E[i].second]>2) return -1;
if (deg[E[i].first] == 2 && !vis[E[i].first]) vis[E[i].first]=true, ++cnt;
if (deg[E[i].second] == 2 && !vis[E[i].second]) vis[E[i].second]=true, ++cnt;
if (!merge(E[i].first, E[i].second)) {
if (cnt == n) return 1;
else return -1;
}
}
return 0;
}
int main() {
while (~scanf("%d%d", &n, &m)) {
rep(i, m) {
int u, v;
scanf("%d%d", &u, &v);
E[i] = MP(u, v);
}
int ret = check();
if (ret == -1) {
puts("NO");
continue;
}
if (ret == 1) {
puts("YES\n0");
continue;
}
puts("YES");
if (n==1 && !m) {
puts("1\n1 1");
continue;
}
vector<PII>ans;
priority_queue<int, vector<int>, greater<int> >Q;
for (int i = 1; i <= n; ++i)
if (deg[i] < 2) Q.push(i);
for (int i = m+1; i <= n; ++i) {
int a = Q.top(); Q.pop();
if (i<n && find(a) == find(Q.top()) ) {
int tmp = Q.top(); Q.pop();
int b = Q.top(); Q.pop();
ans.push_back(MP(a, b));
merge(a, b);
++deg[a]; ++deg[b];
if (deg[a] < 2) Q.push(a);
if (deg[b] < 2) Q.push(b);
Q.push(tmp);
} else {
int b = Q.top(); Q.pop();
ans.push_back(MP(a, b));
merge(a, b);
++deg[a]; ++deg[b];
if (deg[a] < 2) Q.push(a);
if (deg[b] < 2) Q.push(b);
}
}
printf("%d\n", ans.size());
for (int i = 0; i < ans.size(); ++i)
printf("%d %d\n", ans[i].first, ans[i].second);
}
return 0;
}
|
Java
|
UTF-8
| 377
| 3.046875
| 3
|
[] |
no_license
|
public class SubwayClub extends Salad {
public SubwayClub(SubwaySub newSubwich){
super(newSubwich);
//System.out.println("Adding Subway Club");
}
public String getDescription(){
return subwich.getDescription()+super.getDescription() + "Subway Club";
}
public double getCost() {
System.out.println("Cost of Subway Club: 9.00");
return subwich.getCost()+9.00;
}
}
|
Go
|
UTF-8
| 1,986
| 3.015625
| 3
|
[] |
no_license
|
package main
/*
* @lc app=leetcode id=1307 lang=golang
*
* [1307] Verbal Arithmetic Puzzle
*
* https://leetcode.com/problems/verbal-arithmetic-puzzle/description/
*
* algorithms
* Hard (37.72%)
* Likes: 152
* Dislikes: 52
* Total Accepted: 4.5K
* Total Submissions: 11.9K
* Testcase Example: '["SEND","MORE"]\n"MONEY"'
*
* Given an equation, represented by words on left side and the result on right
* side.
*
* You need to check if the equation is solvable under the following
* rules:
*
*
* Each character is decoded as one digit (0 - 9).
* Every pair of different characters they must map to different digits.
* Each words[i] and result are decoded as one number without leading
* zeros.
* Sum of numbers on left side (words) will equal to the number on right side
* (result).
*
*
* Return True if the equation is solvable otherwise return False.
*
*
* Example 1:
*
*
* Input: words = ["SEND","MORE"], result = "MONEY"
* Output: true
* Explanation: Map 'S'-> 9, 'E'->5, 'N'->6, 'D'->7, 'M'->1, 'O'->0, 'R'->8,
* 'Y'->'2'
* Such that: "SEND" + "MORE" = "MONEY" , 9567 + 1085 = 10652
*
* Example 2:
*
*
* Input: words = ["SIX","SEVEN","SEVEN"], result = "TWENTY"
* Output: true
* Explanation: Map 'S'-> 6, 'I'->5, 'X'->0, 'E'->8, 'V'->7, 'N'->2, 'T'->1,
* 'W'->'3', 'Y'->4
* Such that: "SIX" + "SEVEN" + "SEVEN" = "TWENTY" , 650 + 68782 + 68782 =
* 138214
*
* Example 3:
*
*
* Input: words = ["THIS","IS","TOO"], result = "FUNNY"
* Output: true
*
*
* Example 4:
*
*
* Input: words = ["LEET","CODE"], result = "POINT"
* Output: false
*
*
*
* Constraints:
*
*
* 2 <= words.length <= 5
* 1 <= words[i].length, result.length <= 7
* words[i], result contains only upper case English letters.
* Number of different characters used on the expression is at most 10.
*
*
*/
// @lc code=start
func isSolvable(words []string, result string) bool {
}
// @lc code=end
|
JavaScript
|
UTF-8
| 1,891
| 3.65625
| 4
|
[] |
no_license
|
//resize input to be as large as possible on the 500x500 canvas with a 5px margin (so 490x490)
//takes a binarized input
function resizeInput(ctx,data){
//get an image of the input cropped as tightly as possible
var lowerCoords = []; //[x,y]
var upperCoords = []; //[x,y]
//get lower x boundary
outerLoop: //label used so can break out of both loops at same time
for(var x=0; x<500; x++){
for(var r=0; r<500; r++){
if(data[r][x] === 1){
lowerCoords[0] = x;
break outerLoop;
}
}
}
//get lower y boundary
outerLoop:
for(var y=0; y<500; y++){
for(var c=0; c<500; c++){
if(data[y][c] === 1){
lowerCoords[1] = y;
break outerLoop;
}
}
}
//get upper x boundary
outerLoop:
for(var x=499; x>=0; x--){
for(var r=0; r<500; r++){
if(data[r][x] === 1){
upperCoords[0] = x;
break outerLoop;
}
}
}
//get upper y boundary
outerLoop:
for(var y=499; y>=0; y--){
for(var c=0; c<500; c++){
if(data[y][c] === 1){
upperCoords[1] = y;
break outerLoop;
}
}
}
//get width and height of input, and scale factor
var width = upperCoords[0] - lowerCoords[0];
var height = upperCoords[1] - lowerCoords[1];
var scaleFactor = Math.min(490/width, 490/height);
//extract image, store it to an outside image object
var imageObject = new Image();
imageObject.src = canvas.toDataURL();
imageObject.onload = function(){ //when image has loaded the canvas data...
//clear canvas and draw resized input
ctx.clearRect(0,0,500,500);
ctx.drawImage(imageObject,lowerCoords[0],lowerCoords[1],width,height,5,5,width*scaleFactor,height*scaleFactor);
//ctx.drawImage(image,sourceX,sourceY,sourceWidth,sourceHeight,destX,destY,destWidth,destHeight) - dest=destination
//'source' args have to do with extracting the pixels to draw from 'image'
}
//data = binarizeCanvas(ctx);
return "Scaled by: "+scaleFactor;
}
|
C#
|
UTF-8
| 3,302
| 2.640625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MilleniumApplication.Models;
namespace MilleniumApplication.Controllers
{
[Produces("application/json")]
[FormatFilter]
[Route("api/test")]
[ApiController]
public class ItemsController : ControllerBase, IDisposable
{
private readonly ItemsContext _context;
//private readonly ILogger _logger;
public ItemsController(ItemsContext context)
{
_context = context;
//_logger = logger;
}
[HttpGet("{getAllElements}.{format?}")]
public IEnumerable<Item> GetAllElements() =>
_context.Items.ToList();
[HttpGet("getElement/{id}.{format?}")]
public Item GetElement(int Id)
{
return _context.Items.First(x => x.Id == Id);
//try
//{
// var element = _context.Items.First(x => x.Id == Id);
// var resultObj = Ok(element);
// if (element == null)
// throw new Exception("Element not found.");
// return resultObj;
//}
//catch (Exception ex)
//{
// return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
//}
}
[Route("updateElement")]
[HttpPost]
public IActionResult UpdateElement(Item element)
{
try
{
var updateElement = _context.Items.FirstOrDefault(x => x.Id == element.Id);
if (updateElement == null)
throw new Exception("Element not found.");
updateElement.Name = element.Name;
updateElement.Price = element.Price;
updateElement.Description = element.Description;
_context.SaveChanges();
return Ok();
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[Route("saveElement")]
[HttpPut]
public IActionResult SaveElement(Item element)
{
try
{
_context.Add(element);
return Ok(element);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
[Route("deleteElement")]
[HttpDelete]
public IActionResult DeleteElement(int elementId)
{
try
{
var deleteElement = _context.Items.Find(elementId);
if (deleteElement == null)
throw new Exception("You try to delete not existing element.");
_context.Remove(deleteElement);
return Ok();
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
}
}
public void Dispose()
{
_context.Dispose();
}
}
}
|
Shell
|
UTF-8
| 1,320
| 3.765625
| 4
|
[
"MIT"
] |
permissive
|
#!/bin/sh
### BEGIN INIT INFO
# Provides: mangosd
# Required-Start: $local_fs $remote_fs $network $syslog $named
# Required-Stop: $local_fs $remote_fs $network $syslog $named
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# X-Interactive: false
# Short-Description: mangosd service
### END INIT INFO
. /etc/init.d/functions
BASENAME=mangosd
EXEC=/opt/mangos/bin/$BASENAME
USER=mangos
start() {
local pid=$(pidof $BASENAME)
if [ -z $pid ] ; then
echo "Starting $BASENAME..."
daemon --user=$USER "screen -dmS $BASENAME $EXEC"
else
echo "$BASENAME is already running: $pid"
exit 2;
fi
}
stop() {
local pid=$(pidof $BASENAME)
if [ -z $pid ] ; then
echo "$BASENAME is not running."
exit 2;
else
echo "Stopping $BASENAME..."
killproc $EXEC 9
fi
}
status() {
local pid=$(pidof $BASENAME)
if [ -z $pid ] ; then
echo "$BASENAME is not running."
else
echo "$BASENAME is running as pid $pid."
fi
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart|reload|force-reload)
stop
start
;;
status)
status
;;
*)
echo "Usage: $0 {start|stop|reload|force-reload|restart|status}"
exit 1
esac
exit 0
|
C++
|
UTF-8
| 619
| 3.15625
| 3
|
[] |
no_license
|
#ifndef PLAYER_H
#define PLAYER_H
#include "All.h"
class Player
{
private:
Board *pboard; //Pointer to the current board
marker symbol; //The symbol this player plays as, either cross or knot
bool isAI; //Decides if the players are AIs or humans
public:
Player(Board *board, marker symbol, bool isAI = false);
~Player(); // Deletes created players at end of game to prevent memory leaks
marker getSymbol(); //returns the symbol of the current player
int choice(); //returns the position that the player last played in
void play(int square); //Plays a cross on the specified square 1-9
};
#endif //PLAYER_H
|
Python
|
UTF-8
| 2,058
| 3.5
| 4
|
[] |
no_license
|
from Crypto.Hash import MD5
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class MyHashSet:
def __init__(self, capacity=5):
self.capacity = capacity
self.data = [None] * capacity
def encrypt(self,key): #加密
h=MD5.new()
h.update(key.encode("utf-8"))
x=h.hexdigest()
x=int(h.hexdigest(),16)
return x
def get(self,node,key): #增加並確認
if node.next:
return self.get(node.next,key)
else:
node.next=ListNode(key)
def add(self, key):
x=self.encrypt(key)
y=x%self.capacity
#print(y) #不小心加的print
if self.data[y]==None: #若一開始為空,則直接加入
newnode=ListNode(key)
self.data[y]=newnode
else:
newnode=self.get(self.data[y],key)
def remove(self, key):
x=self.encrypt(key)
y=x%self.capacity
node=self.data[y]
if node.val==key:
self.data[y]=node.next
return None
i=None
while node:
if node.val==key:
i.next=node.next
return None
else:
i=node
node=node.next
def contains(self, key): #是否存在
x=self.encrypt(key)
y=x%self.capacity
#print(y) #不小心加的print
node=self.data[y]
while node:
if node.val==key: #如果再,就回傳True
return True
else:
node=node.next #如果不再,就往下找
return False #不存在,則回傳False
#參考資料:老師課堂投影片
|
Java
|
UTF-8
| 1,521
| 2.203125
| 2
|
[] |
no_license
|
package io.egen.entity;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.UUID;
@Entity
@NamedQueries({
@NamedQuery(
name="Alert.fetchHighAlertsWithinLast2Hours",
query="select a from Alert a where a.priority='HIGH' and a.timestamp<=NOW()and a.timestamp>=:pastTime order by a.timestamp desc"
),
@NamedQuery(
name="Alert.fetchByVin",
query="select a from Alert a where a.vin=:paramVin"
)
})
public class Alert {
@Id
private String id;
@ManyToOne
private Reading reading;
private String vin;
private Timestamp timestamp;
private String priority;
public Alert() {
this.id = UUID.randomUUID()
.toString();
}
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Reading getReading() {
return reading;
}
public void setReading(Reading reading) {
this.reading = reading;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
}
|
C++
|
UTF-8
| 358
| 2.5625
| 3
|
[] |
no_license
|
#pragma once
#include <vector>
#include <gl_object.h>
#include "gl_graphic_buffer.h"
class VertexArray : GLObject {
private:
unsigned int id;
GLGraphicBuffer* elementBuffer;
std::vector<GLGraphicBuffer*> buffers;
public:
VertexArray(std::vector<int>* const indicesData, std::vector<float>* const verticesData);
void init();
void clean();
};
|
Python
|
UTF-8
| 776
| 4.4375
| 4
|
[] |
no_license
|
#Emily Addison
#104553525
#Assignment 3
# Function to decipher if the number is prime or composite
def prime_or_composite(n):
has_divisor = False
i =2
for i in range(2, n):
if ((n % i) == 0):
has_divisor = True
break
if(has_divisor == True):
print(n,"is composite")
else:
print(n, "n is prime")
#Main function that asks the user to enter in an integer and calls the function to decipher if its a prime or composite number
user_num = int(input("Enter an integer greater than 1: "))
if (user_num>1):
numbers = []
for count in range (2,user_num+1):
numbers.append(count)
for i in range(0, len(numbers)):
prime_or_composite(numbers[i])
|
C++
|
UHC
| 3,715
| 2.640625
| 3
|
[] |
no_license
|
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<stack>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<ctime>
using namespace std;
int arr[502][502] = { 0, };
int main() {
int N, M;
cin >> N >> M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++)
scanf("%d", &arr[i][j]);
}
int max = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (i < N - 1 && j < M - 1) { // 簢
int sum = arr[i][j] + arr[i + 1][j] + arr[i][j + 1] + arr[i + 1][j + 1];
if (max < sum) max = sum;
}
if (i < N && j < M - 3) { //
int sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i][j + 3];
if (max < sum) max = sum;
}
if (i < N - 3 && j < M) { //
int sum = arr[i + 1][j] + arr[i + 2][j] + arr[i + 3][j] + arr[i][j];
if (max < sum) max = sum;
}
if (i < N - 1 && j < M - 1 && j > 0) { // ť
int sum = arr[i][j] + arr[i + 1][j] + arr[i + 1][j - 1] + arr[i + 1][j + 1];
if (max < sum) max = sum;
}
if (i < N - 2 && j < M - 1) { //90 ȸ ť
int sum = arr[i][j] + arr[i + 1][j] + arr[i + 2][j] + arr[i + 1][j + 1];
if (max < sum) max = sum;
}
if (i < N - 1 && j < M - 2) { //180 ȸ ť
int sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1];
if (max < sum) max = sum;
}
if (i < N - 2 && j < M && j > 0) { //270 ȸ ť
int sum = arr[i][j] + arr[i + 1][j] + arr[i + 2][j] + arr[i + 1][j - 1];
if (max < sum) max = sum;
}
if (i < N - 2 && j < M - 1) { //
int sum = arr[i][j] + arr[i + 1][j] + arr[i + 1][j + 1] + arr[i + 2][j + 1];
if (max < sum) max = sum;
}
if (i < N - 1 && j < M - 1 && j > 0) { //90 ȸ
int sum = arr[i][j] + arr[i][j + 1] + arr[i + 1][j] + arr[i + 1][j - 1];
if (max < sum) max = sum;
}
if (i < N - 2 && j < M && j > 0) { //¿Ī
int sum = arr[i][j] + arr[i + 1][j] + arr[i + 1][j - 1] + arr[i + 2][j - 1];
if (max < sum) max = sum;
}
if (i < N - 1 && j < M - 2) { //Ʒ Ī
int sum = arr[i][j] + arr[i][j + 1] + arr[i + 1][j + 1] + arr[i + 1][j + 2];
if (max < sum) max = sum;
}
if (i < N - 2 && j < M - 1) { //
int sum = arr[i][j] + arr[i][j + 1] + arr[i + 1][j + 1] + arr[i + 2][j + 1];
if (max < sum) max = sum;
}
if (i < N && i > 0 && j < M - 2) { //90 ȸ
int sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i - 1][j + 2];
if (max < sum) max = sum;
}
if (i < N - 2 && j < M - 1) { //180 ȸ
int sum = arr[i][j] + arr[i + 1][j] + arr[i + 2][j] + arr[i + 2][j + 1];
if (max < sum) max = sum;
}
if (i < N - 1 && j < M - 2) { //270 ȸ
int sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j];
if (max < sum) max = sum;
}
if (i < N - 2 && j < M - 1) { // ¿Ī
int sum = arr[i][j] + arr[i][j + 1] + arr[i + 1][j] + arr[i + 2][j];
if (max < sum) max = sum;
}
if (i < N - 1 && j < M - 2) { //90 ȸ ¿Ī
int sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 2];
if (max < sum) max = sum;
}
if (i < N - 2 && j > 0 && j < M) { //180 ȸ ¿Ī
int sum = arr[i][j] + arr[i + 1][j] + arr[i + 2][j] + arr[i + 2][j - 1];
if (max < sum) max = sum;
}
if (i < N - 1 && j < M - 2) { //270 ȸ ¿Ī
int sum = arr[i][j] + arr[i + 1][j] + arr[i + 1][j + 1] + arr[i + 1][j + 2];
if (max < sum) max = sum;
}
}
}
printf("%d", max);
}
|
Shell
|
UTF-8
| 1,933
| 3.796875
| 4
|
[] |
no_license
|
#!/bin/sh
mem_limit="100"
sch_str="epg_dir"
file_url="http://epg_archive_source/"
file_name="epg.tar.gz"
file_conf="/var/tuxbox/config/neutrino.conf"
if [ -d /tmp ]
then
tmp_dir="/tmp"
fi
if [ -d /temp ]
then
tmp_dir="/temp"
fi
echo `cat $file_conf | grep $sch_str` > $tmp_dir/conf
source $tmp_dir/conf
psize=${#epg_dir}
if [ $psize -eq 0 ]
then
echo "EPG path variable not set or not found, aborting!"
exit
fi
if [ ! -d $epg_dir ]
then
echo "EPG path not found, aborting!"
exit
fi
free_mem=`df -m $epg_dir | tail -1 | awk '{print $4}'`
if [ $free_mem -lt $mem_limit ]
then
echo "Not enough space for EPG files, aborting!"
exit
fi
echo "Getting new file from server..."
wget -qO $tmp_dir/$file_name $file_url$file_name
if [ ! -f $tmp_dir/$file_name ]
then
echo "EPG data file not found, aborting!"
exit
fi
if [ ! -d $epg_dir$tmp_dir ]
then
mkdir $epg_dir$tmp_dir
fi
echo "Removing old files..."
rm $epg_dir/*.*
rm $epg_dir$tmp_dir/*.*
echo "Unpacking..."
cd $epg_dir$tmp_dir
tar -xzf $tmp_dir/$file_name
rm $tmp_dir/$file_name
# Heavily depend on Neutrino internal stuff - may break at any moment
echo "Getting channels list..."
bq=`pzapit | grep ther | cut -d: -f1`
wget -q -O $tmp_dir/channels http://127.0.0.1/y/cgi?execute=func:get_channels_as_dropdown%20$bq
for f in `cut -c19-30 $tmp_dir/channels`; do
echo $f".xml" >> $tmp_dir/files
done
echo "Moving actual data..."
for f in `cat $tmp_dir/files`; do
mv $epg_dir$tmp_dir/$f $epg_dir > /dev/null 2>&1
done
echo "Generating index file..."
cd $epg_dir
ls -p | grep -v / > $tmp_dir/files
echo '<?xml version="1.0" encoding="UTF-8"?>' > index.xml
echo "<dvbepgfiles>" >> index.xml
for f in `cat $tmp_dir/files`; do
echo "<eventfile name=\""$f"\"/>" >> index.xml
done
echo "</dvbepgfiles>" >> index.xml
echo "Clean up..."
rm $epg_dir$tmp_dir/*.*
echo "Start reloading EPG data, this can take some time..."
sectionsdcontrol --readepg $epg_dir
echo "Done!"
exit
|
PHP
|
UTF-8
| 2,049
| 2.84375
| 3
|
[] |
no_license
|
<?php
namespace App\Services;
use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Swoole\Http\Request;
use Swoole\WebSocket\Server;
use Swoole\WebSocket\Frame;
/**
* @see https://wiki.swoole.com/wiki/page/400.html
*/
class WebSocketService implements WebSocketHandlerInterface
{
/**
* 实例化的对象
* @var
*/
public $obj;
/**
* URL参数
* @var array
*/
public $data = [];
/**
* 声明没有参数的构造函数
* WebSocketService constructor.
*/
public function __construct()
{
}
/**
* 实例化指定对象类
* @param Request $request
*/
private function setObj($request)
{
// 处理参数
$params = explode('&', $request->server['query_string']);
$params_arr = [];
foreach ($params as $item) {
$params_arr[] = explode(':', $item);
}
$this->data = array_column($params_arr, 1, 0);
if ($this->data['type'] == 1) {
$this->obj = new ChatSocketService;
} else {
exit;
}
}
/**
* 监听WebSocket连接打开事件,连接成功后,触发open事件
* @param \swoole_websocket_server $server
* @param \swoole_http_request $request
*/
public function onOpen(Server $server, Request $request)
{
$this->setObj($request);
$this->obj->open($server, $request, $this->data);
}
/**
* 监听WebSocket消息事件,客户端向服务端发送消息时,触发message事件
* @param \swoole_websocket_server $server
* @param \swoole_websocket_frame $frame
*/
public function onMessage(Server $server, Frame $frame)
{
$this->obj->message($server, $frame);
}
/**
* 监听WebSocket连接关闭事件
* @param \swoole_websocket_server $server
* @param $fd
* @param $reactorId
*/
public function onClose(Server $server, $fd, $reactorId)
{
$this->obj->close($server, $fd);
}
}
|
TypeScript
|
UTF-8
| 3,466
| 3.359375
| 3
|
[] |
no_license
|
import { IPlayer } from "./player";
import { ScoreCardV2 } from "./scorecardV2";
enum JudgementPhase {
NotStarted,
Started,
Finished
}
/**
* JudgementPhaseManager - Ensures everyone has set judgement correctly
* 1. Start with currentPlayer = startPlayer
* 2. Wait for judgement from currentPlayer
* 3. If that player gives judgement then update currentPlayer to the next player
* 4. Repeat until all players set judgement
* 5. End judgement phase
*
* Interface
* -> SetJudgement
*
* <- Update scores (judgement part)
*/
export class JudgementPhaseManager {
public getCurrentPlayerId() {
return this._currentPlayerId;
}
private _players: IPlayer[];
private _onJudgementPhaseDoneCallback: () => void;
private _startPlayerId: number;
private _currentPlayerId: number;
private _totalHandsToPlay: number;
private _totalPredictionHands: number
private _scoreCard: ScoreCardV2;
private _state: JudgementPhase = JudgementPhase.NotStarted;
constructor(players: IPlayer[], scoreCard: ScoreCardV2, onJudgementPhaseDone: () => void) {
this._players = players;
this._scoreCard = scoreCard;
this._onJudgementPhaseDoneCallback = onJudgementPhaseDone;
}
public startJudgementPhase(startPlayerId: number, totalHands: number) {
this._startPlayerId = startPlayerId;
this._currentPlayerId = startPlayerId;
this._totalHandsToPlay = totalHands;
this._totalPredictionHands = 0;
this._state = JudgementPhase.Started;
}
private canTakeAction(playerId: number) {
if (this._state !== JudgementPhase.Started) {
throw new Error('cannot setJudgement not yet started!');
}
return playerId === this._currentPlayerId;
}
public setJudgement(playerId: number, prediction: number) {
if (this._state !== JudgementPhase.Started) {
throw new Error(`Judgement phase not yet started. HandState: ${this._state}`);
}
if (!this.canTakeAction(playerId)) {
throw new Error('Player took set judgement action out of turn!');
}
// Last player to set judgement
if (this.nextTurnPlayerId(playerId) === this._startPlayerId && this._totalPredictionHands + prediction === this._totalHandsToPlay) {
throw new Error(`Can't set prediction! Choose other prediction value`);
}
// Perform action
this._scoreCard.setJudgement(playerId, prediction);
this._totalPredictionHands = this._totalPredictionHands + prediction;
// Update current player
this._currentPlayerId = this.nextTurnPlayerId(this._currentPlayerId);
// All players done
if (this._currentPlayerId === this._startPlayerId) {
this._state = JudgementPhase.Finished;
this._onJudgementPhaseDoneCallback();
}
}
private nextTurnPlayerId(playerId: number): number {
const nextPlayerIndex = this.nextTurnPlayerIndex(playerId);
return this._players[nextPlayerIndex].id;
}
private nextTurnPlayerIndex(playerId: number): number {
const playerIndex = this.playerIndexById(playerId);
const nextPlayerIndex = (playerIndex + 1) % this._players.length;
return nextPlayerIndex;
}
private playerIndexById(playerId: number): number {
return this._players.findIndex(player => player.id === playerId);
}
}
|
Python
|
UTF-8
| 906
| 2.765625
| 3
|
[] |
no_license
|
#!/usr/bin/env python
''' Posts info from Google Finance to Notification Center '''
import argparse
import sys
import googlefinance
import pync
def get_quotes(symbol):
"""Get a quote and notify"""
quote = googlefinance.getQuotes(symbol)[0]
url = 'https://www.google.com/finance?q=' + symbol
subtitle = quote['LastTradePrice']
text = quote.get('Change') or quote['LastTradeTime']
pync.Notifier.notify(text, title=symbol.upper(),
subtitle=subtitle, sender='com.apple.stocks',
activate='com.apple.Safari', open=url)
def main():
''' Parses command-line arguments '''
parser = argparse.ArgumentParser()
parser.add_argument('symbol', metavar='KEYWORD', nargs=1,
help='ticker symbol')
args = parser.parse_args()
get_quotes(args.symbol[0])
if __name__ == "__main__":
sys.exit(main())
|
Markdown
|
UTF-8
| 3,803
| 2.9375
| 3
|
[
"Apache-2.0"
] |
permissive
|
# 概述
**抽象工厂模式(Abstract Factory)**,提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。
# UML

## 解析
`AbstractProductA` 和 `AbstractProductB` 是两个抽象产品,之所有为抽象,是因为它们都有可能有两种不同的实现,例如 `ProductA1` 、 `ProductA2` 和 `ProductB1` 、 `ProductB2` 就是对两个抽象产品的具体实现。
`IFactory` 是一个抽象工厂接口,里面包含了所有的产品创建的抽象方法。
通常是在运行时刻再创建一个 `ConcreteFactory` 类的实例,这个具体的工厂再创建具有特定实现的产品对象,也就是说,为创建不同的产品对象,客户端应使用不同的具体工厂。
## 优点与缺点
好处:
1. 易于交换产品系列,由于具体工厂类,在一个应用中只需要在初始化的时候出现一次,这就使得改变一个应用的具体工厂变得非常容易,它只需要改变具体工厂即可使用不同的配置。
2. 它让具体的创建实例过程与客户端分离,客户端通过它们的抽象接口操作实例,产品的具体类名也被具体工厂的实现分离,不会出现客户端代码中。
缺点:
增加功能的时候,需要修改 `Product`、`Factory`等。
# Talk is cheap,just coding
## Java
### base
```java
interface AbstractProductA {
void execute();
}
interface AbstractProductB {
void run();
}
class ProductA1 implements AbstractProductA {
@Override
public void execute() {
System.out.println("ProductA1");
}
}
class ProductA2 implements AbstractProductA {
@Override
public void execute() {
System.out.println("ProductA2");
}
}
class ProductB1 implements AbstractProductB {
@Override
public void run() {
System.out.println("ProductB1");
}
}
class ProductB2 implements AbstractProductB {
@Override
public void run() {
System.out.println("ProductB2");
}
}
interface AbstractFactory {
AbstractProductA createProductA();
AbstractProductB createProductB();
}
class ConcreteFactory1 implements AbstractFactory {
@Override
public AbstractProductA createProductA() {
return new ProductA1();
}
@Override
public AbstractProductB createProductB() {
return new ProductB1();
}
}
class ConcreteFactory2 implements AbstractFactory {
@Override
public AbstractProductA createProductA() {
return new ProductA2();
}
@Override
public AbstractProductB createProductB() {
return new ProductB2();
}
}
@Test
public void test() {
AbstractFactory abstractFactory = new ConcreteFactory1();
AbstractProductA productA = abstractFactory.createProductA();
AbstractProductB productB = abstractFactory.createProductB();
productA.execute();
productB.run();
}
```
### Java SPI Support
> 非 dubbo SPI
>
> http://dubbo.apache.org/zh-cn/docs/source_code_guide/dubbo-spi.html
在 `resource` 下创建 `META-INF/services` 创建一个文件,名称为 类 `AbstractFactory` 的全量名 `com.example.demo.design.abstractfactory.AbstractFactory` ,文件内容为实现类的全量名
```java
com.example.demo.design.abstractfactory.ConcreteFactory1
# com.example.demo.design.abstractfactory.ConcreteFactory2
```
```java
@Test
public void test1() {
ServiceLoader<AbstractFactory> load = ServiceLoader.load(AbstractFactory.class);
load.forEach(e -> {
e.createProductA().execute();
e.createProductB().run();
System.out.println("------------------------");
});
}
// ProductA1
// ProductB1
// ------------------------
// ProductA2
// ProductB2
// ------------------------
```
## go
> todo
|
Java
|
UTF-8
| 425
| 2.265625
| 2
|
[] |
no_license
|
package com.example.threadclassloader;
public class ThreadClassLoaderTest {
public static void main(String[] args) {
testThreadContext();
}
public static void testThreadContext(){
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
// currentThread.setContextClassLoader(cl);
System.out.println(contextClassLoader.getClass().getName());
}
}
|
Python
|
UTF-8
| 656
| 4.375
| 4
|
[] |
no_license
|
"""Write a funtion named uses_only taht takes a word and a string of
letters, and that returns True if the word contains only the letters
in the list. Can you make a sentence using only the letters
"acefhlo"? (other than "Hoe alfalfa"?)"""
def uses_only(word, letters):
for letter in word:
if letter not in letters:
return False
return True
# To answer question:
def uses_only_test(letters):
fin = open('words.txt')
for line in fin:
word = line.strip()
if uses_only(word, letters):
print(line)
#uses_only_test("acefhlo")
print(uses_only("abstemious", "aeiou" ))
|
Java
|
UTF-8
| 817
| 2.5
| 2
|
[] |
no_license
|
package eir.world.environment.nav;
import com.badlogic.gdx.math.Vector2;
import eir.world.environment.Anchor;
import eir.world.environment.Asteroid;
import eir.world.unit.Unit;
public class SurfaceNavNode extends NavNode implements Anchor
{
/**
* index of the asteroid containing this nav node
*/
final int aIdx;
/**
* Normal angle
*/
float angle;
SurfaceNavNode( final NavNodeDescriptor descriptor, final Vector2 point, final int idx, final int aIdx )
{
super( descriptor, point, idx );
this.aIdx = aIdx;
this.angle = Float.NaN;
int navIdx = getDescriptor().getIndex();
Asteroid asteroid = (Asteroid)getDescriptor().getObject();
}
@Override
public float getAngle() { return angle; }
@Override
public Unit getParent() { return getDescriptor().getObject(); }
}
|
C#
|
UTF-8
| 2,480
| 3.84375
| 4
|
[
"MIT"
] |
permissive
|
namespace _1_3.StudentExercises
{
using System;
class StudentExercises
{
static void Main()
{
// Make two instance of the class "Student"
Student pesho = new Student("Pesho", "Peshov", "Peshev", 8203173804, "Sofia city", 0888334455,
"pesho@mail.bg", 3, UniversitySpecialty.DotNetNinja, University.MIT, Faculty.EngineeringAndTechnology);
Student gosho = null;//new Student("Gosho", "Goshov", "Goshev", 8410092185, "Sofia city", 0888667788,
//"pesho@mail.bg", 3, UniversitySpecialty.CSharpProgrammer, University.MIT, Faculty.EngineeringAndTechnology);
// Print student with overriden "ToString()". There is no need to explicitly call ".ToString()"
Console.WriteLine(pesho);
Console.WriteLine(gosho);
// Check if students are equal with overriden "Equals(Object obj)"
Console.WriteLine("Pesho equals Gosho: {0}", pesho.Equals(gosho));
// Check if students are equal with overriden operator "=="
Console.WriteLine("Pesho == Gosho: {0}", pesho == gosho);
// Check if students are not equal with overriden operator "!="
Console.WriteLine("Pesho != Gosho: {0}", pesho != gosho);
// Get hash code with overriden "GetHashCode()"
Console.WriteLine("Pesho's hash code: {0}", pesho.GetHashCode());
// Clone Student "Pesho" and print its values with overriden method "ToString()". There is no need to explicitly call ".ToString()"
Student peshoClone = pesho.Clone();
Console.WriteLine("Pesho's clone: {0}", peshoClone);
// Compare Pesho and Gosho with our method ComapreTo
Console.WriteLine("Pesho compare to Gosho: {0}", pesho.CompareTo(gosho));
// Compare Pesho with its clone
Console.WriteLine("Pesho compare to Pesho's clone: {0}", pesho.CompareTo(peshoClone));
// Add students into array
Student[] students = new Student[] { pesho, gosho, peshoClone };
// Sort the students. Array.Sort() use IComparable(CompareTo) to sort
Array.Sort(students);
// Print all students, to see if they are properly sorted
Console.WriteLine("Sorted studetns:");
for (int i = 0; i < students.Length; i++)
{
Console.WriteLine(students[i]);
}
}
}
}
|
Java
|
UTF-8
| 442
| 2.21875
| 2
|
[] |
no_license
|
package lsp.poligonos;
import lsp.Poligono;
public class Retangulo extends Poligono {
private Integer largura;
private Integer altura;
public Integer getLargura() {
return largura;
}
public void setLargura(Integer largura) {
this.largura = largura;
}
public Integer getAltura() {
return altura;
}
public void setAltura(Integer altura) {
this.altura = altura;
}
}
|
Python
|
UTF-8
| 104
| 3.15625
| 3
|
[] |
no_license
|
s = raw_input()
def f(s):
for u,v in zip(s,s[1:]):
if u == v:return 'Bad'
return 'Good'
print f(s)
|
C++
|
UTF-8
| 2,085
| 3.34375
| 3
|
[] |
no_license
|
/**
* @brief a segment tree, or a fenwick tree
* @tparam Monoid (commutativity is not required)
*/
template <class Monoid>
struct segment_tree {
typedef typename Monoid::underlying_type underlying_type;
int n;
vector<underlying_type> a;
const Monoid mon;
segment_tree() = default;
segment_tree(int a_n, underlying_type initial_value = Monoid().unit(), Monoid const & a_mon = Monoid()) : mon(a_mon) {
n = 1; while (n < a_n) n *= 2;
a.resize(2 * n - 1, mon.unit());
fill(a.begin() + (n - 1), a.begin() + ((n - 1) + a_n), initial_value); // set initial values
REP_R (i, n - 1) a[i] = mon.append(a[2 * i + 1], a[2 * i + 2]); // propagate initial values
}
void point_set(int i, underlying_type z) { // 0-based
assert (0 <= i and i <= n);
a[i + n - 1] = z;
for (i = (i + n) / 2; i > 0; i /= 2) { // 1-based
a[i - 1] = mon.append(a[2 * i - 1], a[2 * i]);
}
}
underlying_type range_concat(int l, int r) { // 0-based, [l, r)
assert (0 <= l and l <= r and r <= n);
underlying_type lacc = mon.unit(), racc = mon.unit();
for (l += n, r += n; l < r; l /= 2, r /= 2) { // 1-based loop, 2x faster than recursion
if (l % 2 == 1) lacc = mon.append(lacc, a[(l ++) - 1]);
if (r % 2 == 1) racc = mon.append(a[(-- r) - 1], racc);
}
return mon.append(lacc, racc);
}
};
struct plus_monoid {
typedef int underlying_type;
int unit() const { return 0; }
int append(int a, int b) const { return a + b; }
};
template <int mod>
struct modplus_monoid {
typedef int underlying_type;
int unit() const { return 0; }
int append(int a, int b) const { int c = a + b; return c < mod ? c : c - mod; }
};
struct max_monoid {
typedef int underlying_type;
int unit() const { return INT_MIN; }
int append(int a, int b) const { return max(a, b); }
};
struct min_monoid {
typedef int underlying_type;
int unit() const { return INT_MAX; }
int append(int a, int b) const { return min(a, b); }
};
|
PHP
|
UTF-8
| 2,749
| 2.6875
| 3
|
[] |
no_license
|
<?php
session_start();
if(!isset($_SESSION['login'])){
$_SESSION['login']="incorreto";
}
if($_SESSION['login']== "correto" && isset($_SESSION['login'])){
if($_SERVER['REQUEST_METHOD']=="GET"){
if(!isset($_GET['obra']) || !is_numeric($_GET['obra'])){
echo '<script>alert("Erro ao abrir");</script>';
echo 'Aguarde um momento.A reencaminhar pagina';
header("refresh:5; url=index.php");
exit();
}
$idObra=$_GET['obra'];
$con=new mysqli("localhost","root","","museus");
if($con->connect_error!=0){
echo 'Ocorreu um erro no acesso a base de dados <br>'.$con->connect_error;
exit();
}
else{
$sql='select * from obras where id_obra=?';
$stm=$con->prepare($sql);
if($stm!=false){
$stm->bind_param('i',$idObra);
$stm->execute();
$res=$stm->get_result();
$obra=$res->fetch_assoc();
$stm->close();
}
else{
echo '<br>';
echo ($con->error);
echo'<br>';
echo"Aguarde um momento.A reencaminhar pagina";
echo'<br>';
header("refresh:5; url=index.php");
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Detalhes</title>
<link rel="stylesheet" type='text/css' href="style.css">
<body>
<h1 style="text-align: center">Detalhes do Obra</h1>
<p style='text-align:center; font-size: 20px'>
<?php
if(isset($obra)){
echo '<br><br>';
echo "Obra: ";
echo $obra['titulo'];
echo '<br><br>';
echo "Ano: ";
echo $obra['ano'];
echo '<br><br>';
echo '<br><br>';
echo '<a href="obras_edit.php?obra='.$obra['id_obra']. '">Editar</a><br>';
echo '<a href="obras_delete.php?obra='.$obra['id_obra']. '">Eliminar</a><br>';
}
else{
echo '<h2>Parece que a obra selecionado não existe</h2>';
}
?>
</body>
</html>
<?php
}
else {
echo "Precisa estar logado. <br>" ;
echo "Irá ser redirecionado para uma página de login" ;
header("refresh: 5; url = login.php");
}
?>
|
C++
|
UTF-8
| 4,219
| 3.0625
| 3
|
[] |
no_license
|
#ifndef UTILITIES_HPP
#define UTILITIES_HPP
#include <iostream>
#include <sstream>
#include <functional>
#include <algorithm>
#include <random>
#include <unistd.h>
template <class V> auto idxs(V const &v) {
std::vector<int> result;
for (int i = 0; i < v.size(); ++i)
result.push_back(i);
return result;
}
template<class T, class Compare>
constexpr const T& clamp( const T& v, const T& lo, const T& hi, Compare comp ) {
return assert( !comp(hi, lo) ), comp(v, lo) ? lo : comp(hi, v) ? hi : v;
}
template<class T>
constexpr const T& clamp( const T& v, const T& lo, const T& hi ) {
return clamp( v, lo, hi, std::less<T>() );
}
inline double lin_interp( double ratio, double lo, double hi ) {
return lo + ratio*(hi-lo);
}
inline std::default_random_engine &get_random_engine() {
std::random_device rd;
static std::default_random_engine eng(rd());
return eng;
}
inline double rand_uniform (double min, double max) {
std::uniform_real_distribution<double> randomGenerator(min, max);
return randomGenerator(get_random_engine());
}
template <typename T> T parse(std::string const &str) {
T val;
std::istringstream sstr(str);
sstr >> val;
return val;
}
template <class F>
struct OnDtor {
F f_;
OnDtor(F f) : f_(f) { }
~OnDtor() {f_();}
};
template <class F>
OnDtor<F> makeOnDtor(F f) {
return OnDtor<F>(f);
}
template <class T>
std::string Ttos(T t) {
std::stringstream ss;
ss << t;
return ss.str();
}
inline double sq(double x) {
return x*x;
}
template <class Collection> void print_v (Collection const &v) {
for (auto const &el : v) {
std::cout << el << ", " << std::endl;
}
}
template <class C, class... Args>
void push_back(C &c, Args const &...args) {
using val_type = typename std::remove_reference<decltype(*c.begin())>::type;
val_type val {args...};
c.push_back(val);
}
inline void delay( unsigned long ms ) {
usleep( ms * 1000 );
}
struct RandGenerator {
std::random_device rd_;
std::mt19937 gen_;
RandGenerator() : rd_{}, gen_{rd_()} {}
};
template <class DistributionT>
class DistributionGenerator
{
public:
DistributionGenerator(DistributionT const &d)
: rand_gen{}, distribution{d}
{
}
auto operator() () {
return distribution(rand_gen.gen_);
}
private:
RandGenerator rand_gen;
DistributionT distribution;
};
template <class DT>
auto makeDistributionGenerator(DT const &d) {
return DistributionGenerator<DT> (d);
}
namespace func {
template <typename CollectionTo, typename CollectionFrom, typename unop>
CollectionTo map(CollectionFrom const &col, unop op) {
CollectionTo to;
std::transform(col.begin(), col.end(), std::back_inserter(to), op);
return to;
}
template <typename From, typename unop>
auto v_map(std::vector<From> const &col, unop op) ->
std::vector<decltype(op(col.front()))>
{
std::vector<decltype(op(col.front()))> to;
std::transform(col.begin(), col.end(), std::back_inserter(to), op);
return to;
}
template <class Collection>
auto max_element(Collection const &in) -> decltype(in.begin()){
return std::max_element(in.begin(), in.end());
}
template <class Collection>
auto min_element(Collection const &in) -> decltype(in.begin()){
return std::min_element(in.begin(), in.end());
}
template <class Collection, class F>
auto min_element(Collection const &in, F &&op) -> decltype(in.begin()){
return std::min_element(in.begin(), in.end(), op);
}
template <class Collection, class F>
Collection filter(Collection const &in, F &&op) {
Collection to;
std::copy_if(in.begin(), in.end(), std::back_inserter(to), op);
return to;
}
template <class CollectionFrom, class CollectionCmp, class F>
CollectionFrom filter(CollectionFrom const &from,
CollectionCmp const &cmp, F &&op) {
CollectionFrom to;
for (int i = 0; i < from.size(); ++i) {
if (op(cmp[i]))
{ to.push_back(from[i]); }
}
return to;
}
template<typename T>
std::vector<T> flatten(const std::vector<std::vector<T>> &orig)
{
std::vector<T> ret;
for(const auto &v: orig)
ret.insert(ret.end(), v.begin(), v.end());
return ret;
}
}
#endif // UTILITIES_HPP
|
Python
|
UTF-8
| 307
| 3.421875
| 3
|
[] |
no_license
|
number_one = int(input("number 1: "))
number_two = int(input("number 2: "))
number_three = int(input("number 3: "))
if number_one + number_two == number_three or number_one + number_three == number_two or number_two + number_three == number_one:
print("this works")
else:
print("this doesn't work")
|
Python
|
UTF-8
| 773
| 2.71875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
import re
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/_calculate')
def calculate():
number1 = request.args.get('number1', '0')
operator = request.args.get('operator', '+')
number2 = request.args.get('number2')
m = re.match('-?\d+', number1)
n = re.match('-?\d+', number2)
if m is None or n is None or operator not in '+-*/':
return jsonify(result='I Catch a BUG!')
if operator == '/':
result = eval(number1 + operator + str(float(number2)))
else:
result = eval(number1 + operator + number2)
return jsonify(result=result)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run()
|
JavaScript
|
UTF-8
| 3,719
| 2.515625
| 3
|
[] |
no_license
|
import React from 'react';
import { RouteHandler } from 'react-router';
import jQuery from 'jquery';
// Only include Bootstrap & Google Maps if run in the browser
if(typeof window !== "undefined"){
window.jQuery = jQuery;
var Bootstrap = require('bootstrap');
var GoogleMapsLoader = require('google-maps');
}
import Header from './Header.jsx';
import Setup from './Setup.jsx';
import ThreadStore from '../../stores/ThreadStore.js';
var threads = require('json!../../data/threads.json').threads;
var localStorage = (typeof window !="undefined") ? window.localStorage : null;
var navigator = (typeof window !="undefined") ? window.navigator : null;
// Shim geolocation and localstorage if the app is run on the server
if(typeof window == "undefined"){
var localStorage = {
data: {},
setItem: function(key, value){
this.data[key] = value;
},
getItem: function(key){
return this.data[key] ? this.data[key] : false;
}
}
var navigator = {};
navigator.geolocation = {};
navigator.geolocation.getCurrentPosition = function(callback, error){
var dummyLocation = {"timestamp":1429100674214,"coords":{"speed":null,"heading":null,"altitudeAccuracy":null,"accuracy":150,"altitude":null,"longitude":9.999,"latitude":46.999}};
callback(dummyLocation);
}
} else {
var GoogleMapsLoader = require('google-maps');
}
// App
let App = React.createClass({
getInitialState(){
return {
username: localStorage.getItem("loco-username") ? localStorage.getItem("loco-username") : null,
location: localStorage.getItem("loco-location") ? JSON.parse(localStorage.getItem("loco-location")) : null,
}
},
componentWillMount(){
this.threadStore = new ThreadStore(threads);
console.log(this.state)
},
componentDidMount(){
if(typeof window == "undefined") return;
GoogleMapsLoader.load(function(google) {
this.google = google;
this.getUserLocation();
}.bind(this));
},
setUsername(username){
if(this.usernameIsValid(username)){
var newState = this.state;
newState.username = username;
this.setState(newState);
localStorage.setItem("loco-username", username);
} else {
console.warn("Username invalid!", username);
}
},
usernameIsValid(username){
return username ? !!(username.length > 5) : false; //Username needs at least 6 characters
},
getUserLocation(){
console.log("Checking for user's location");
// Get the user's location
navigator.geolocation.getCurrentPosition(function(position){
console.log(JSON.stringify(position))
var location = position.coords;
console.log("User's location", location);
var newState = this.state;
newState.location = location;
this.setState(newState);
localStorage.setItem("loco-location", JSON.stringify(location));
}.bind(this), function(){
console.warn('User\'s location unavailable.');
alert("Threre was an error retreiving your location!");
var newState = this.state;
newState.location = null;
this.setState(newState);
localStorage.setItem("loco-location", null);
});
},
render() {
var props = {
threads: this.threadStore,
username: this.state.username,
usernameIsValid: this.usernameIsValid,
setUsername: this.setUsername,
location: this.state.location
};
var usernameOk = this.usernameIsValid(this.state.username);
var locationOk = !!this.state.location;
return (
<div className="nav">
<Header />
{ (!usernameOk || !locationOk) ? <Setup {...props}/> : <RouteHandler {...props}/> }
</div>
);
}
});
export default App;
|
Java
|
UTF-8
| 1,508
| 3.640625
| 4
|
[] |
no_license
|
package com.haripadisetti.java8;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
class Product{
private int id;
private String name;
private double price;
public Product(int id, String name, double price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
public class FilterCollectionTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Product> list = new ArrayList<Product>();
list.add(new Product(1,"Abc",100));
list.add(new Product(2,"Abc2",200));
list.add(new Product(3,"Abc3",300));
list.add(new Product(4,"Abc4",400));
list.add(new Product(5,"Abc5",500));
// using lambda to filter data
Stream<Product> filteredProdData = list.stream().filter(product -> product.getPrice() >300);
// using lambda to iterate through collection
filteredProdData.forEach(product -> System.out.println(product.getName() + ":"+ product.getPrice()));
}
}
|
Java
|
UTF-8
| 299
| 2.546875
| 3
|
[] |
no_license
|
package com.codingdojo.calculator2;
public class Calculator2Test {
public static void main(String[] args) {
Calculator2 calc = new Calculator2();
calc.performOperation(10.5);
calc.performOperation("*");
calc.performOperation(5.2);
calc.performOperation("=");
calc.getResults();
}
}
|
Java
|
UTF-8
| 151
| 1.539063
| 2
|
[] |
no_license
|
package ee.itcollege.team11;
import java.io.Serializable;
public abstract class BaseEntity implements Serializable, Creatable, Updatable {
}
|
Python
|
UTF-8
| 1,429
| 3.859375
| 4
|
[] |
no_license
|
def swap(a,b):
temp=a
a=b
b=temp
def quicksort(array):
key=array[len(array)-1]
k=0
if len(array)!=0:
for i in range(0,len(array)-1):
if(array[i]<key):
temp=array[i]
array[i]=array[k]
array[k]=temp
k+=1
if(i==len(array)):
temp=array[len(array)-1]
array[len(array)-1]=array[k]
array[k]=temp
quicksort(array[:k-1])
quicksort(array[k+1:])
a=[2,3,4,5,6,7,8,1,23,4,512,32,4,43,54,65,7,66,54,3,43,54,345,35]
quicksort(a)
for i in range(0,len(a)):
print(a[i])
def partition(arr,low,high):
i = ( low-1 ) # index of smaller element
pivot = arr[high] # pivot
for j in range(low , high):
# If current element is smaller than or
# equal to pivot
if arr[j] <= pivot:
# increment index of smaller element
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
# The main function that implements QuickSort
# arr[] --> Array to be sorted,
# low --> Starting index,
# high --> Ending index
# Function to do Quick sort
def quickSort(arr,low,high):
if low < high:
# pi is partitioning index, arr[p] is now
# at right place
pi = partition(arr,low,high)
# Separately sort elements before
# partition and after partition
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
|
Python
|
UTF-8
| 1,347
| 3.6875
| 4
|
[
"MIT"
] |
permissive
|
import string
import unittest
from collections import Counter
from main import extract_characters, generate_password
class TestPasswordGenerator(unittest.TestCase):
def setUp(self):
self.length = 10
self.alphabets = 3
self.digits = 7
def test_extract_characters(self):
"""test if character slicing extracts within given range"""
letters = extract_characters(string.ascii_letters, start="a", end="z")
self.assertEqual(letters, list(string.ascii_lowercase))
def test_generated_password_length(self):
"""test if length of password match length specified"""
password = generate_password(self.length, self.alphabets, self.digits)
self.assertEqual(len(password), self.length)
def test_generated_password_valid(self):
"""test if number of alphabets and digits specified is present in generated password"""
password = generate_password(self.length, self.alphabets, self.digits)
digits_count = sum(Counter(list(filter(lambda item: str.isdigit(item), password))).values())
alphabets_count = sum(Counter(list(filter(lambda item: str.isalpha(item), password))).values())
self.assertEqual(alphabets_count, self.alphabets)
self.assertEqual(digits_count, self.digits)
if __name__ == '__main__':
unittest.main()
|
Java
|
UTF-8
| 2,347
| 3.21875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
public class Day17 {
private static MessageDigest digest;
private static final boolean[] OPEN = { false, false, false, false, false, false, false, false, false, false, false, true,
true, true, true, true };
static class Point {
int x;
int y;
String code;
Point(int x, int y, String code) {
this.x = x;
this.y = y;
this.code = code;
}
}
public static String part1(String input, final int endX, final int endY) {
Queue<Point> positions = new ArrayBlockingQueue<>(50);
positions.add(new Point(0, 0, input));
while (!positions.isEmpty()) {
Point p = positions.poll();
if (p.x == endX && p.y == endY) {
return p.code.substring(input.length());
}
addPoints(endX, endY, positions, p);
}
// no path
return null;
}
public static int part2(String input, final int endX, final int endY) {
Queue<Point> positions = new ArrayBlockingQueue<>(500);
positions.add(new Point(0, 0, input));
int max = -1;
while (!positions.isEmpty()) {
Point p = positions.poll();
if (p.x == endX && p.y == endY) {
max = Math.max(max, p.code.length());
}
else {
addPoints(endX, endY, positions, p);
}
}
return max - input.length();
}
private static void addPoints(int endX, int endY, Queue<Point> positions, Point p) {
byte[] hash = digest.digest(p.code.getBytes());
// up
if (p.x > 0 && OPEN[(hash[0] >> 4) & 0xf]) {
positions.add(new Point(p.x - 1, p.y, p.code + 'U'));
}
// down
if (p.x < endX && OPEN[hash[0] & 0x0f]) {
positions.add(new Point(p.x + 1, p.y, p.code + 'D'));
}
// left
if (p.y > 0 && OPEN[(hash[1] >> 4) & 0xf]) {
positions.add(new Point(p.x, p.y - 1, p.code + 'L'));
}
// right
if (p.y < endY && OPEN[hash[1] & 0x0f]) {
positions.add(new Point(p.x, p.y + 1, p.code + 'R'));
}
}
public static void main(String[] args) {
try {
digest = MessageDigest.getInstance("MD5");
System.out.println(part2("pslxynzg", 3, 3));
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
|
Java
|
UTF-8
| 2,753
| 2.28125
| 2
|
[
"MIT"
] |
permissive
|
package mcjty.rftoolscontrol.blocks.vectorart;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.nbt.NBTTagCompound;
import org.lwjgl.opengl.GL11;
public class GfxOpLine extends GfxOp {
private int x1;
private int y1;
private int x2;
private int y2;
private int color;
public GfxOpLine() {
}
public GfxOpLine(int x1, int y1, int x2, int y2, int color) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.color = color;
}
@Override
public void render() {
float f3 = (color >> 24 & 255) / 255.0F;
float f = (color >> 16 & 255) / 255.0F;
float f1 = (color >> 8 & 255) / 255.0F;
float f2 = (color & 255) / 255.0F;
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder vertexbuffer = tessellator.getBuffer();
GlStateManager.enableBlend();
GlStateManager.disableTexture2D();
GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);
GlStateManager.color(f, f1, f2, f3);
vertexbuffer.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION);
vertexbuffer.pos(x1, y1, 0.0D).endVertex();
vertexbuffer.pos(x2, y2, 0.0D).endVertex();
tessellator.draw();
GlStateManager.enableTexture2D();
GlStateManager.disableBlend();
}
@Override
public GfxOpType getType() {
return GfxOpType.OP_LINE;
}
@Override
protected void readFromNBTInternal(NBTTagCompound tag) {
x1 = tag.getByte("x1");
y1 = tag.getByte("y1");
x2 = tag.getByte("x2");
y2 = tag.getByte("y2");
color = tag.getInteger("color");
}
@Override
protected void writeToNBTInternal(NBTTagCompound tag) {
tag.setByte("x1", (byte) x1);
tag.setByte("y1", (byte) y1);
tag.setByte("x2", (byte) x2);
tag.setByte("y2", (byte) y2);
tag.setInteger("color", color);
}
@Override
protected void readFromBufInternal(ByteBuf buf) {
x1 = buf.readByte();
y1 = buf.readByte();
x2 = buf.readByte();
y2 = buf.readByte();
color = buf.readInt();
}
@Override
protected void writeToBufInternal(ByteBuf buf) {
buf.writeByte(x1);
buf.writeByte(y1);
buf.writeByte(x2);
buf.writeByte(y2);
buf.writeInt(color);
}
}
|
Python
|
UTF-8
| 7,466
| 3.421875
| 3
|
[] |
no_license
|
import enchant
from random import randint
"""
FUTURE NOTES
Does not support punctuation
Does not work efficiently on long inserts for the subsitution decoder (nor does it return the correct answer on small ones)
Caesar cipher works perfectly fine
GOALS
connect to a web app
"""
class Answers():
def __init__(self, c, default = ['e', 't', 'a', 'o', 'i', 'n', 's', 'r', 'h', 'd', 'l', 'u', 'c', 'm', 'f', 'y', 'w', 'g', 'p', 'b', 'v', 'k', 'x', 'q', 'j', 'z'], o = False):
self.code = c.lower()
self.alphabet = default
self.has_spaces = False
self.dictionary = self.create_dict()
def create_dict(self):
"""Return a list that has each alphabet letter in code ordered by frequency """
d = {}
for char in self.code:
if char.isspace():
self.has_spaces = True
continue
elif char not in d:
d[char] = 1
else:
d[char] += 1
return d
def next(self):
""" Spit's out next most likely guess """
try:
return next(self.spitter)
except:
return False
class Substution(Answers):
def __init__(self, c, default = ['e', 't', 'a', 'o', 'i', 'n', 's', 'r', 'h', 'd', 'l', 'u', 'c', 'm', 'f', 'y', 'w', 'g', 'p', 'b', 'v', 'k', 'x', 'q', 'j', 'z'], o = False):
Answers.__init__(self, c, default)
if o == False:
self.ordered = self.sort_dict()
else:
self.ordered = o
self.spitter = self.spit()
def all_but(self, i, lst):
return lst[:i] + lst[i + 1:]
def sort_dict(self):
sorted_items = sorted(self.dictionary.items(), key = lambda a: a[1], reverse = True)
return [item[0] for item in sorted_items]
def which_changed(self, code_pop, alpha_pop):
def f(char):
if (char == code_pop):
return True
else:
return False
return [f(i) for i in self.code]
def final_ans(self, changed_bools, changed_answer, alpha_pop):
def f(i):
if changed_bools[i]:
return alpha_pop
else:
return changed_answer[i]
new_ans = [f(i) for i in range(len(changed_answer))]
return "".join(new_ans)
def all_outputs(self, i):
one = self.all_but(i, self.alphabet)
two = self.alphabet[i]
three = self.ordered[1:]
four = self.ordered[0]
return one, two, three, four
def spit(self):
""" Generator that yields all possible interpretations """
if not self.code:
return
if not self.ordered:
yield self.code
return
for i in range(len(self.alphabet)):
new_alphabet, alpha_pop, new_ordered, code_pop = self.all_outputs(i)
next_ans = Substution(self.code, new_alphabet, new_ordered)
for changed_answer in next_ans.spit():
changed_bools = self.which_changed(code_pop, alpha_pop)
yield self.final_ans(changed_bools, changed_answer, alpha_pop)
class Caesar(Answers):
def __init__(self, c):
Answers.__init__(self, c)
self.spitter = self.spit()
def spit(self):
""" Spits out the 26 potential answers in order of most likely """
max_elem = ord(max(self.dictionary.items(), key = lambda a: a[1])[0])
for index in range(26):
shift = ord(self.alphabet[index]) - max_elem #check if the most popular was this one
yield self.shifted_by(shift)
def shifted_by(self, diff):
ans = []
for char in self.code:
if char.isspace():
ans.append(char)
else:
letter = ord(char) + diff
if letter < 97:
letter = 123 - (97 - letter)
elif letter > 122:
letter = letter % 123 + 97
ans.append(chr(letter))
return "".join(ans)
class Decoder:
def __init__(self, instance, num = None):
self.webster = enchant.Dict('en_US')
self.instance = instance # Needs to be some Answers instance
if num == None:
self.num_words = len(self.instance.code)
else:
self.num_words = num
self.answer_gen = self.answers()
def next(self):
""" Spit's out next most likely guess """
try:
return next(self.answer_gen)
except:
return False
def answers(self):
return self.get_answers(self.num_words)
def get_answers(self, num_words):
""" A Generator that yields all potential answers """
word = ""
while word is not False:
word = self.instance.next()
if self.instance.has_spaces:
yield from self.dissect_spaces(word)
else:
yield from self.dissect(word, num_words)
def dissect(self, word, num):
""" We want to see if any words can be constructed from this string """
if not num or not word or len(word) < 2:
return
if self.webster.check(word):
yield word
for i in range(1, len(word)):
first, rest = word[:i], word[i:]
if len(first) >= 2 or first == 'i' or first == 'a':
if self.webster.check(first):
for answer in self.dissect(rest, num - 1):
yield first + " " + answer
def dissect_spaces(self, word):
""" Check if the given string is a sentence """
if not word:
return
text = word.split()
for w in text:
if not self.webster.check(w):
return
yield word
class Encode_Caesar():
def __init__(self, word):
self.alphabet = ['e', 't', 'a', 'o', 'i', 'n', 's', 'r', 'h', 'd', 'l', 'u', 'c', 'm', 'f', 'y', 'w', 'g', 'p', 'b', 'v', 'k', 'x', 'q', 'j', 'z']
self.word = word.lower()
self.shift = randint(0, len(self.alphabet) - 1)
self.encoded = self.encode()
def encode(self):
ans = []
for char in self.word:
if char.isspace():
ans.append(char)
else:
letter = ord(char) + self.shift
if letter < 97:
letter = 123 - (97 - letter)
elif letter > 122:
letter = letter % 123 + 97
ans.append(chr(letter))
return "".join(ans)
class Encode_Substution():
def __init__(self, word):
self.alphabet = ['e', 't', 'a', 'o', 'i', 'n', 's', 'r', 'h', 'd', 'l', 'u', 'c', 'm', 'f', 'y', 'w', 'g', 'p', 'b', 'v', 'k', 'x', 'q', 'j', 'z']
self.word = word
self.d = self.dictionize()
self.encoded = self.encode()
def dictionize(self):
d = {}
for char in self.word:
if char not in d:
d[char] = self.random_char()
return d
def encode(self):
return "".join([self.d[char] for char in self.word])
def random_char(self):
return self.alphabet.pop(randint(0, len(self.alphabet) - 1))
def test(word):
e = Encode_Caesar(word)
print(e.encoded)
s = Caesar(e.encoded)
d = Decoder(s, 1)
print(list(d.answer_gen))
test("butterfly")
|
Java
|
UTF-8
| 1,693
| 2.1875
| 2
|
[
"MIT"
] |
permissive
|
/*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.services.impl.placeholder.standard;
import io.github.nucleuspowered.nucleus.services.interfaces.IPermissionService;
import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.placeholder.PlaceholderContext;
import org.spongepowered.api.text.placeholder.PlaceholderParser;
import org.spongepowered.api.text.serializer.TextSerializers;
import java.util.Optional;
public class OptionPlaceholder implements PlaceholderParser {
private final IPermissionService permissionService;
public OptionPlaceholder(IPermissionService permissionService) {
this.permissionService = permissionService;
}
@Override
public Text parse(PlaceholderContext placeholderContext) {
Optional<Subject> subjectOptional = placeholderContext.getAssociatedObject().filter(x -> x instanceof Subject).map(x -> (Subject) x);
if (subjectOptional.isPresent() && placeholderContext.getArgumentString().isPresent()) {
return this.permissionService
.getOptionFromSubject(subjectOptional.get(), placeholderContext.getArgumentString().get())
.map(TextSerializers.FORMATTING_CODE::deserialize)
.orElse(Text.EMPTY);
}
return Text.EMPTY;
}
@Override
public String getId() {
return "nucleus:option";
}
@Override
public String getName() {
return "Nucleus Permission Option Placeholder";
}
}
|
Python
|
UTF-8
| 757
| 2.671875
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
from ln.backend import interpolation
from ln.backend.datatype import Datatype
import numpy as np
import pytest
def test_none():
a = [1, 3, None, 4, None]
assert interpolation.none(a, None, None) == a
def test_zero():
d = Datatype('int32')
a = [1, 3, None, 4, None]
result = interpolation.zero(a, d, None)
assert np.array_equal(result, [1, 3, 0, 4, 0])
def test_previous():
d = Datatype('int32')
a = [1, 3, None, 4, None]
result = interpolation.previous(a, d, None)
assert np.array_equal(result, [1, 3, 3, 4, 4])
@pytest.mark.xfail
def test_linear():
d = Datatype('float32')
a = [1.0, 3.0, None, 4.0, None]
assert np.array_equal(interpolation.linear(a, d, None),
[1.0, 3.0, 3.5, 4.0, 4.0])
|
Python
|
UTF-8
| 372
| 4.28125
| 4
|
[] |
no_license
|
print('Faizan Jamil')
names = ['Susan', 'James', 'Roger', 'Bryan', 'Jacob']
print('Size of list is: ' + str(len(names)))
ages = [16, 18, 22, 21, 20]
i = 0
j = 0
for x in names:
print(x)
for y in ages:
print(str(y))
while i < len(names):
while j < len(ages):
print('Name: ' + names[i] + ' Age: ' + str(ages[j]))
i+=1
j+=1
break
|
C++
|
UTF-8
| 1,225
| 2.96875
| 3
|
[] |
no_license
|
#pragma once
#include "point.h"
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
class Shape
{ protected:
Point Centre;
Point Vertex[4];
string Color;
public:
static int ID;
int Id;
Shape()
{ cout << "Создана фигура ";
Centre=(0,0);Vertex[0]=(1,1);Vertex[1]=(-1,1);Vertex[2]=(-1,-1);Vertex[3]=(1,-1);
Color="Белый";
Id = ID;
ID++;
}//конструктор фигуры
void printShape();//вывод информации
void move(const double& x,const double& y);//перемещение
void Mahtab(const double& P);// маштабирование
void Turn(const double& R);//поворот
void SetColorFigure(const string &color);//установка цвета
string GetColorFigure();//вывод цвета
bool CommonSide(const Shape& shape2);//функция. определяющая, содержатся ли стороны одной фигуры в другой
//вначале сравним уравнения прямых,
virtual ~Shape() { cout << "Удалена фигура ";}//деструктор фигуры
};
|
Ruby
|
UTF-8
| 700
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
require 'httparty'
module ConvertKit
class Client
include HTTParty
attr_reader :key, :uri, :version
def initialize(key, uri="https://api.convertkit.com")
@key = key
@uri = uri
@version = 2
end
def form(id)
form = ConvertKit::Form.new(id)
form.client = self
form
end
def get_request(path)
json = self.class.get("#{@uri}#{path}?k=#{@key}&v=#{@version}")
JSON.parse(json.body)
end
def post_request(path, params)
url = "#{@uri}#{path}"
json = self.class.post(url, body: {
k: @key,
v: @version,
}.merge(params))
JSON.parse(json.body)
end
end
end
|
Python
|
UTF-8
| 586
| 3.125
| 3
|
[] |
no_license
|
# lent = int(input())
import random
list = []
# for i in range(1000): list.append(int(input()))
for i in range(1): list.append(random.randint(1,10**11))
print(list)
# b = 0
for i in list:
if i % 2 == 0 or i % 3 == 0 or i % 5 == 0 or i % 7 == 0 or i % 13 == 0 or i % 11 == 0:
print("true", i)
# elif i % 3 ==0:
# print("true", i)
# a = 1
# elif i % 5 ==0:
# # print("true", i)
# a = 1
# elif i == 1 or:
# a = 1
# elif i == 17:
# a = 1
# else:
# print("пиздец", i)
# b +=1
# print(b)
|
Java
|
UTF-8
| 1,003
| 2.25
| 2
|
[] |
no_license
|
package com.omar.maxellforesttest.Common.network;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* Created by omz on 27/5/18
*/
public class OkHttpClientFactory {
public static OkHttpClient getOkHttpClient() {
return getOkHttpClientBuilder().build();
}
private static OkHttpClient.Builder getOkHttpClientBuilder() {
return new OkHttpClient.Builder()
.readTimeout(ServerSettings.Domain.OKHTTP_CLIENT_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(ServerSettings.Domain.OKHTTP_CLIENT_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.addInterceptor(getLoggingInterceptor());
}
private static HttpLoggingInterceptor getLoggingInterceptor() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(ServerSettings.Domain.HTTP_LOG_LEVEL);
return loggingInterceptor;
}
}
|
JavaScript
|
UTF-8
| 900
| 2.625
| 3
|
[] |
no_license
|
export default class JSONHelper {
readTemplate(filename){
var fs = window.require('fs');
var json_return = JSON.parse(fs.readFileSync(`./public/data/templates/${filename}.json`, 'utf8'));
return json_return;
}
readClass(filename){
var fs = window.require('fs');
var json_return = JSON.parse(fs.readFileSync(`./public/data/classes/${filename}.json`, 'utf8'));
return json_return;
}
readGeneric(filename, type){
var fs = window.require('fs');
var json_return = JSON.parse(fs.readFileSync(`./public/data/${type}/${filename}.json`, 'utf8'));
return json_return;
}
sumObjectKeys(...objs){
return objs.reduce((a, b) => {
for (let k in b) {
if (b.hasOwnProperty(k))
a[k] = (a[k] || 0) + b[k];
}
return a;
}, {});
}
}
|
Python
|
UTF-8
| 2,373
| 3.09375
| 3
|
[] |
no_license
|
import unittest
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../script')
import gradient_descent
class TestGradientDescent(unittest.TestCase):
##### set up points #####
def setUp(self):
self.points = [[1, 2], [2,4], [1,2]]
########## test get_gradient_descent ##############
def test_get_gradient_descent_should_raise_ValueError_when_file_name_isempty(self):
file_name = ""
with self.assertRaises(ValueError) as error:
gradient_descent.get_gradient_descent(file_name, 0.0001, ",", 1000)
self.assertEqual(error.exception.args[0], 'file_name should not be null or empty')
def test_get_gradient_descent_should_raise_ValueError_when_file_name_isnot_valid(self):
file_name = 123
with self.assertRaises(ValueError) as error:
gradient_descent.get_gradient_descent(11, 0.0001, ",", 1000)
self.assertEqual(error.exception.args[0], 'file_name not a valid string')
def test_get_gradient_descent_should_raise_ValueError_when_iterations_arenot_valid(self):
iterations = ""
with self.assertRaises(ValueError) as error:
gradient_descent.get_gradient_descent("filename", 0.0001, ",", iterations)
self.assertEqual(error.exception.args[0], 'iterations must be a valid number')
########## test get_points ##############
def test_get_points_should_raise_IOError_when_file_not_found(self):
file_name = "filedoesnotexisits.txt"
with self.assertRaises(IOError) as error:
gradient_descent.get_points(file_name, ",")
self.assertEqual(error.exception.args[0], file_name + " not found")
def test_get_points_should_raise_ValueError_when_delimiter_not_valid(self):
delimiter = ""
with self.assertRaises(ValueError) as error:
gradient_descent.get_points("filename", delimiter)
self.assertEqual(error.exception.args[0], "delimiter not valid (',' , '.')")
####### test abline #######
def test_abline(self):
result = gradient_descent.abline(self.points, 1, 1)
self.assertEqual(result , [2, 3, 2])
###### test get_column ####(
def test_get_column(self):
results = gradient_descent.get_column(self.points, 0)
self.assertEqual(results, [1, 2, 1])
|
Java
|
UTF-8
| 1,505
| 3.359375
| 3
|
[] |
no_license
|
package leetcode;
public class _1061_LexicographicallySmallestEquivalentString {
public static void main(String[] args) {
_1061_LexicographicallySmallestEquivalentString obj = new _1061_LexicographicallySmallestEquivalentString();
// String s1 = "dccaccbdafgeabeeghbigbhicggfbhiccfgbechdicbhdcgahi";
// String s2 = "igfcigeciahdafgegfbeddhgbacaeehcdiehiifgbhhehhccde";
// String baseStr = "igfcigeciahdafgegfbeddhgbacaeehcdiehiifgbhhehhccde";
String s1 = "leetcode", s2 = "programs", baseStr = "sourcecode";
System.out.println(obj.smallestEquivalentString(s1,s2,baseStr));
}
public String smallestEquivalentString(String s1, String s2, String baseStr) {
int[] p = new int[26];
for (int i = 0; i < 26; ++i) {
p[i] = i;
}
for (int i = 0; i < s1.length(); ++i) {
int a = s1.charAt(i) - 'a', b = s2.charAt(i) - 'a';
int pa = find(a, p), pb = find(b, p);
if (pa < pb) {
p[pb] = pa;
} else {
p[pa] = pb;
}
}
StringBuilder sb = new StringBuilder();
for (char a : baseStr.toCharArray()) {
char b = (char) (find(a - 'a', p) + 'a');
sb.append(b);
}
return sb.toString();
}
/*
union- find
*/
private int find(int x, int[] p) {
if (p[x] != x) {
p[x] = find(p[x], p);
}
return p[x];
}
}
|
Java
|
UTF-8
| 929
| 2.40625
| 2
|
[] |
no_license
|
package se.modlab.generics.sstruct.procedurecall;
public class UntypedAliasing {
private String typename;
private String varname;
private boolean isReferenced;
private boolean isArray;
private String filename;
private int line;
private int column;
public UntypedAliasing(String _typename, String _varname, boolean _isReferenced, boolean _isArray, String _filename, int _line, int _column) {
typename = _typename;
varname = _varname;
isReferenced = _isReferenced;
isArray = _isArray;
filename = _filename;
line = _line;
column = _column;
}
public String getTypename() {
return typename;
}
public String getVarname() {
return varname;
}
public boolean isReferenced() {
return isReferenced;
}
public boolean isArray() {
return isArray;
}
public String getPlaceString() {
return "in file "+filename+", line "+line+", column "+column;
}
}
|
Java
|
UTF-8
| 1,896
| 1.953125
| 2
|
[] |
no_license
|
package com.google.android.gms.internal.gtm;
import com.google.android.gms.common.internal.Preconditions;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public final class zzok extends zzoa<Map<String, zzoa<?>>> {
private static final Map<String, zzgz> zzaug;
private boolean zzaut = false;
public zzok(Map<String, zzoa<?>> map) {
this.zzaud = (Map) Preconditions.checkNotNull(map);
}
public final Iterator<zzoa<?>> zzmf() {
return zzmg();
}
public final zzoa<?> zzco(String str) {
zzoa<?> zzco = super.zzco(str);
return zzco == null ? zzog.zzaum : zzco;
}
public final boolean zzcp(String str) {
return zzaug.containsKey(str);
}
public final zzgz zzcq(String str) {
if (zzcp(str)) {
return zzaug.get(str);
}
StringBuilder sb = new StringBuilder(String.valueOf(str).length() + 51);
sb.append("Native Method ");
sb.append(str);
sb.append(" is not defined for type ListWrapper.");
throw new IllegalStateException(sb.toString());
}
public final void zzmi() {
this.zzaut = true;
}
public final boolean isImmutable() {
return this.zzaut;
}
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof zzok) {
return this.zzaud.entrySet().equals(((Map) ((zzok) obj).value()).entrySet());
}
return false;
}
public final String toString() {
return this.zzaud.toString();
}
public final /* synthetic */ Object value() {
return this.zzaud;
}
static {
HashMap hashMap = new HashMap();
hashMap.put("hasOwnProperty", zzja.zzark);
zzaug = Collections.unmodifiableMap(hashMap);
}
}
|
Java
|
UTF-8
| 292
| 1.617188
| 2
|
[] |
no_license
|
package br.com.caloteiro.ws.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.caloteiro.ws.model.Cliente;
@Repository
public interface ClienteRepository extends JpaRepository<Cliente,Integer> {
}
|
C#
|
UTF-8
| 1,376
| 2.734375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
namespace DDD
{
class TakarabakoKi : Character
{
private bool isOpen2 = false;
private bool isKiGet = false;
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="input">入力オブジェクト</param>
public TakarabakoKi(Vector2 position, ICharacterMediator mediator)
: base("takarabako", position, 16.0f, mediator)
{
}
/// <summary>
/// 初期化処理
/// </summary>
/// <summary>
/// 更新処理
/// </summary>
public override void Update()
{
}
/// <summary>
/// 描画処理
/// </summary>
/// <param name="renderer">描画オブジェクト</param>
///
public override void Hit(Character character)
{
}
public bool IsOpen2()
{
return isOpen2;
}
public bool IsKiGet()
{
return isKiGet;
}
public void Open2()
{
isOpen2 = true;
name = "takarabakoki";
}
public void KiGet()
{
isKiGet = true;
name = "takarabakoaku";
}
}
}
|
TypeScript
|
UTF-8
| 2,182
| 2.90625
| 3
|
[] |
no_license
|
import { ICollectionUser } from "../types/collections-user";
import {
collectionUserActionTypes,
FETCH_COLLECTIONS_USER_FAILURE,
FETCH_COLLECTIONS_USER_REQUEST,
FETCH_COLLECTIONS_USER_SUCCESS,
ADD_COLLECTIONS_USER,
EDIT_COLLECTIONS_USER
} from "../types/actions-collections-user";
import { ICollection } from "../types/collection";
export interface IStateCollectionsUser {
collections:ICollectionUser[];
isLoading: boolean;
error:null|string;
}
const collectionsReducerDefaultState: IStateCollectionsUser = {
collections: [],
isLoading:true,
error: null
};
const updateCollections = (arr: ICollectionUser[], collection:ICollection ):ICollectionUser[] => {
const newArr:ICollectionUser[] = arr.map(item => {
if (item.id === collection.id) {
// return {
// id: item.id,
// name: collection.name,
// type: collection.type,
// questions: collection.questions,
// active: collection.active,
// use: item.use,
// edit: item.edit,
// own: item.own
// }
return {...item, ...collection}
}
return item;
})
return newArr
}
export const collectionsUserReducer = (
state = collectionsReducerDefaultState,
action: collectionUserActionTypes
): IStateCollectionsUser => {
switch (action.type) {
case FETCH_COLLECTIONS_USER_REQUEST:
return {...state,
collections:[],
isLoading: true,
error: null
};
case FETCH_COLLECTIONS_USER_SUCCESS:
return {...state,
collections: action.payload,
isLoading: false,
error: null
};
case FETCH_COLLECTIONS_USER_FAILURE:
return {...state,
collections: [],
isLoading: false,
error: action.payload
};
case ADD_COLLECTIONS_USER:
return {...state,
collections: [...state.collections, action.payload],
isLoading: false,
error: null
};
case EDIT_COLLECTIONS_USER:
return {...state,
collections: updateCollections(state.collections, action.payload),
isLoading: false,
error: null
};
default:
return state;
}
};
|
Java
|
UTF-8
| 1,942
| 2.21875
| 2
|
[] |
no_license
|
package org.kercoin.magrit.services.utils;
import java.io.IOException;
import java.io.StringReader;
import java.security.AccessControlException;
import java.util.Properties;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.kercoin.magrit.Configuration;
import org.kercoin.magrit.Context;
import org.kercoin.magrit.utils.GitUtils;
import org.kercoin.magrit.utils.UserIdentity;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class UserIdentityServiceImpl implements UserIdentityService {
private final GitUtils gitUtils;
private final Configuration configuration;
private final Properties data;
private Repository datasource;
private ObjectId lastVersion;
@Inject
public UserIdentityServiceImpl(Context ctx) {
gitUtils = ctx.getGitUtils();
configuration = ctx.configuration();
data = new Properties();
}
private void open() throws IOException {
if (this.datasource == null) {
this.datasource = Git.open(
configuration.getPublickeyRepositoryDir()
).getRepository();
}
}
@Override
public UserIdentity find(String login) throws AccessControlException {
try {
open();
ObjectId v = datasource.resolve("HEAD:users.properties");
if (v == null) {
throw new AccessControlException(String.format("User '%s' not found in authentication database.", login));
}
if (!v.equals(lastVersion)) {
data.clear();
data.load(new StringReader(gitUtils.show(datasource, "HEAD:users.properties")));
}
String email = data.getProperty(String.format("user.%s.email", login));
String name = data.getProperty(String.format("user.%s.name", login));
if (email != null && name != null) {
return new UserIdentity(email, name);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return new UserIdentity(login + "@localhost", login);
}
}
|
C++
|
UTF-8
| 549
| 3.046875
| 3
|
[] |
no_license
|
#pragma once
#ifndef __BKR_UTILS__
#define __BKR_UTILS__
#include <string.h>
namespace Utils {
void copy(float* ary, float* src);
void copy(float* ary, float r, float g, float b, float a);
void copy(float* ary, float r, float g, float b);
}
// Functor for deleting pointers in vector.
template<class T> class DeleteVector
{
public:
// Overloaded () operator.
// This will be called by for_each() function.
bool operator()(T x) const
{
// Delete pointer.
delete x;
return true;
}
};
#endif
|
PHP
|
UTF-8
| 2,413
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Splash\Tests\Tools\Fields;
/**
* @abstract DateTime Field : Date & Time as Text (Format Y-m-d G:i:s)
*
* @example 2016-12-25 12:25:30
*/
class oodatetime extends oovarchar
{
//==============================================================================
// Structural Data
//==============================================================================
const FORMAT = 'DateTime';
//==============================================================================
// DATA VALIDATION
//==============================================================================
/**
* Verify given Raw Data is Valid
*
* @param string $Data
*
* @return bool True if OK, Error String if KO
*/
static public function validate($Data)
{
//==============================================================================
// Verify Data is not Empty
if ( empty($Data) ) {
return True;
}
//==============================================================================
// Verify Data is a DateTime Type
if ( \DateTime::createFromFormat(SPL_T_DATETIMECAST, $Data) !== False ) {
return True;
}
return "Field Data is not a DateTime with right Format (" . SPL_T_DATETIMECAST . ").";
}
//==============================================================================
// FAKE DATA GENERATOR
//==============================================================================
/**
* Generate Fake Raw Field Data for Debugger Simulations
*
* @param array $Settings User Defined Faker Settings
*
* @return string
*/
static public function fake($Settings)
{
//==============================================================================
// Generate a random DateTime
$date = new \DateTime("now");
$date->modify( '-' . mt_rand(1,10) . ' months' );
$date->modify( '-' . mt_rand(1,60) . ' minutes' );
$date->modify( '-' . mt_rand(1,60) . ' seconds' );
//==============================================================================
// Return DateTime is Right Format
return $date->format(SPL_T_DATETIMECAST);
}
}
|
JavaScript
|
UTF-8
| 559
| 4
| 4
|
[] |
no_license
|
function leadingSubstrings(str) {
let substr = [];
[...str].reduce((prev, char) => {
prev += char;
substr.push(prev);
return prev;
}, '');
return substr;
}
// for loop
// function substrings(str) {
// let subStr = [];
// for (let index = 0; index < str.length; index += 1) {
// subStr = subStr.concat(leadingSubstrings(str.slice(index)));
// }
// return console.log(subStr);
// }
// map
function substrings(str) {
return ([...str]
.flatMap((_, index) => leadingSubstrings(str.slice(index))));
}
substrings('abcde');
|
Markdown
|
UTF-8
| 5,032
| 2.953125
| 3
|
[] |
no_license
|
## Step 1
I made bamazon.sql with the following code
```
DROP DATABASE IF EXISTS bamazon;
CREATE database bamazon;
USE bamazon;
CREATE TABLE products(
position INT NOT NULL,
item_id INT NULL,
product_name VARCHAR(100) NULL,
department_name VARCHAR(100) NULL,
price DECIMAL(10,2) NULL,
stock_quantity INT NULL,
PRIMARY KEY (position)
);
SELECT * FROM products;
```
## Step 2
I added the following code to mySQL workbench

After selecting you see this

## Step 3
#### Import Csv file I created
```
1,9891,Television,Electronics,4000,20
2,5452,Xbox One,Electronics,499,34
3,2145,Playstation 4,Electronics,499,35
4,2589,Sweater,Clothes,50,200
5,1423,Dark Blue Jeans,Clothes,45,2000
6,1673,Shirt,Clothes,15,9000
7,1738,Rap CD,Music,20,400
8,9999,Vinyl,Music,30,5
9,4758,Ipod,Electronics,300,50
10,1010,laptop,Electronics,5000,28
```
Then you click this

Then you will see this

## Step 4
Write some Javascript code to display options in terminal
```
var mysql = require("mysql");
var inquirer = require("inquirer");
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "password",
database: "bamazon"
});
connection.connect(function(err){
if(err) throw err;
displayProducts();
});
function displayProducts(){
var query = "SELECT position,item_id,product_name,department_name,price,stock_quantity FROM products";
connection.query(query, function(err, res){
if(err) throw err;
console.log(res);
console.log(query);
for(var i = 0; i < res.length; i++){
console.log(
`Item #${res[i].position}, item id: ${res[i].item_id}, product name: ${res[i].product_name}, department name: ${res[i].department_name}, price: $${res[i].price}, stock: ${res[i].stock_quantity}`
);
}
console.log(res);
connection.end();
})
}
```
###### In the terminal remember to do npm install, npm install inquirer, npm install mysql etc...
## Step 5
Run node in the terminal

## Step 6
Write a function that lets the client select a product by inserting product id number
```
//main function---------------------------------------------------------------------------
function options(){
connection.query("SELECT * FROM products", function(err, results){
if(err) throw err;
inquirer
.prompt([
{
name: "choice",
type: "input",
message: "Enter the product ID number of the item you'd like to buy!"
}
])
.then(function(answer){
console.log(`This is number you typed in ${answer.choice}`);
for(var i = 0; i< results.length; i++){
if(parseInt(results[i].item_id) === parseInt(answer.choice)){
chosenItem = results[i];
}
}
console.log(`${chosenItem.stock_quantity} available in stock`)
unitsNeeded();
});
});
}
//--------------------------------------------------------------------------------------------
```
## Step 7
Add a function that asks how many units you need to buy!
1. Ask how many you need to buy
2. Check and see if the store has enough in stock
3. If not let them know there is an insufficient quantity
4. List the price total
```
//This function allows the client to pick number of products they want to buy -------------
function unitsNeeded(){
inquirer
.prompt([
{
name: "units",
type: "input",
message: "Enter the number of units you'd like to buy!"
}
])
.then(function(answer){
if(parseInt(chosenItem.stock_quantity) >= parseInt(answer.units)){
console.log(`You are now the owner of ${answer.units} ${chosenItem.product_name}(s)!!!`);
total = parseInt(chosenItem.price)* parseInt(answer.units);
console.log(`Your total price is $${total}!`)
stock = parseInt(chosenItem.stock_quantity) - parseInt(answer.units);
console.log(`this is the stock leftover ${stock}`);
updateStock();
options();
//update stock function
}
else{
console.log(`There is not enough in stock for that`);
options();
}
});
}
//---------------------------------------------------------------------------------------------
```
## Step 8
Update the database quantities
```
//Update after a purchase
function updateStock(){
connection.query(
"UPDATE products SET ? WHERE ?",
[
{
stock_quantity: stock
},
{
item_id: chosenItem.item_id
}
],
function(error){
if(error) throw err;
console.log(`stock updated!`)
}
);
}
//------------------------------------------------------------------------------------------------
```
## Finish
Run node in the terminal!





# Quick Video Run Through
Please click the image to view the youtube video!

(https://www.youtube.com/watch?v=hSB_gJuO8s4)
|
Java
|
UTF-8
| 4,103
| 3.453125
| 3
|
[] |
no_license
|
package model;
/*
* Name: Blaine Jacques
* CSCI2466 HW2: Freedonia Olympic Athlete Bean
*/
import edu.saintpaul.csci2466.foam.model.Athlete;
import static edu.saintpaul.csci2466.foam.model.Athlete.INVALID_DATE;
import static edu.saintpaul.csci2466.foam.model.Athlete.OLYMPIC_OPENING_DATE;
import static edu.saintpaul.csci2466.foam.model.Athlete.UNSET_DATE;
import java.time.*;
/**
* This Bean is built for the Freedonia Olympic Committee to manage it's
* athletes. Freedonia Olympic athlete Management System (FOAM). The FOAM System
* is a web based application that will allow users to view, add, edit, and
* delete athletes from the roster. This bean implements the Athlete interface
* and provides setters and getters for the athlete's NationalID, FirstName,
* LastName, and DateOfBirth which helps calculate an athlete's age.
*
* @author Blaine Jacques
*/
//implements serializable via Athlete
public class AthleteBean implements Athlete {
//Properties
private String NationalID; //Athletes NationalID
private String FirstName; //Athletes First Name
private String LastName; //Athletes Last Name
private LocalDate DateOfBirth; //Athletes Date of Birth
/**
* Default no-arg constructor
*/
public AthleteBean() {
}
/**
* Getter for the Athletes National ID
*
* @return the National ID of the Athlete.
*/
@Override
public String getNationalID() {
return NationalID;
}
/**
* Setter for the Athletes National ID
*
* @param NationalID the National ID of the Athlete.
*/
public void setNationalID(String NationalID) {
this.NationalID = NationalID;
}
/**
* Getter for the Athlete's first name.
*
* @return the first name of the Athlete.
*/
@Override
public String getFirstName() {
return FirstName;
}
/**
* Setter for the Athlete's first name.
*
* @param FirstName the first name of the Athlete.
*/
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
/**
* Getter for the last name
*
* @return the last name of the Athlete.
*/
@Override
public String getLastName() {
return LastName;
}
/**
* Setter for the Athlete's last name.
*
* @param LastName the last name of the Athlete.
*/
public void setLastName(String LastName) {
this.LastName = LastName;
}
/**
* Getter for the Athlete's Date of birth
*
* @return the athlete's date of birth
*/
@Override
public LocalDate getDateOfBirth() {
return DateOfBirth;
}
/**
* Setter for the Athlete's Date of birth
*
* @param DateOfBirth the Athlete's date of birth
*/
public void setDateOfBirth(LocalDate DateOfBirth) {
this.DateOfBirth = DateOfBirth;
}
/**
* Getter for the Age, calculates the age via the birth date and the number
* of years between them. If the date of birth is left empty it returns
* UNSET_DATE, and if the date is after the date Olympic Opening date, then
* the Athlete wouldn't even be born yet, which returns INVALID_DATE.
*
* @return the age calculated via the Athlete's date of birth, if not
* provided, it returns UNSET_DATE. If date of birth is entered after the
* date of the Olympics opening, then it returns INVALID_DATE.
*/
@Override
public int getAge() {
/* the dateOfBirth is null, the date is unset;
if the date isn't null, then check if it's after the opening date,
if he
*/
return DateOfBirth == null ? UNSET_DATE
: DateOfBirth.isAfter(OLYMPIC_OPENING_DATE) ? INVALID_DATE
: DateOfBirth.until(OLYMPIC_OPENING_DATE).getYears();
}
@Override
public String toString() {
return "AthleteBean{" + "NationalID=" + NationalID + ", FirstName=" +
FirstName + ", LastName=" + LastName + ", DateOfBirth=" +
DateOfBirth + '}';
}
}
|
Java
|
UTF-8
| 3,380
| 2.203125
| 2
|
[] |
no_license
|
package com.numier.numierpda.Dialogs;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import com.numier.numierpda.Activities.Cash;
import com.numier.numierpda.Fragments.CashFragment;
import com.numier.numierpda.Models.Product;
import com.numier.numierpda.R;
import com.numier.numierpda.Tools.ConversionTools;
import com.numier.numierpda.Tools.IntakeTools;
public class DialogFilterSearch extends DialogFragment {
private EditText campoBusqueda;
private ListView listadoProductos;
private List <Product> productosTemp;
private List <String> cadenas;
ArrayAdapter<String> adaptadorClasico;
Product productoElegido;
String numOrden;
private Activity context;
public DialogFilterSearch (List <Product> productos, String numOrden, Activity context){
this.productosTemp = productos;
this.numOrden = numOrden;
cadenas = new ArrayList <String>();
this.context = context;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Dialog dialogo = new Dialog(getActivity());
dialogo.setCanceledOnTouchOutside(false);
dialogo.setTitle(R.string.search_product);
dialogo.getWindow().setGravity(Gravity.CENTER);
View vista = getActivity().getLayoutInflater().inflate(R.layout.dialog_filter_product, null);
campoBusqueda = (EditText) vista.findViewById(R.id.inputDialogFilterSearch);
listadoProductos = (ListView) vista.findViewById(R.id.listFilterProducts);
for (Product producto: productosTemp){
this.cadenas.add(producto.getName()+" - "+ ConversionTools.getFormatPrice(producto.getRate1(), false));
}
adaptadorClasico = new ArrayAdapter <String>(getActivity(), android.R.layout.simple_list_item_1, this.cadenas);
listadoProductos.setAdapter(adaptadorClasico);
campoBusqueda.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence str, int start, int before, int count) {
adaptadorClasico.getFilter().filter(str);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
listadoProductos.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
String nombre = (String) listadoProductos.getItemAtPosition(position);
for (Product producto: productosTemp){
String name = producto.getName()+" - "+ConversionTools.getFormatPrice(producto.getRate1(), false);
if (name.equals(nombre)) {
productoElegido = producto;
}
}
IntakeTools.generateIntake(getActivity(), productoElegido, Cash.getCashFragment().getQuantity(), Cash.getCashFragment().getButtonMenus().getText().toString());
getDialog().cancel();
}
});
dialogo.setContentView(vista);
dialogo.show();
return dialogo;
}
}
|
Java
|
UTF-8
| 2,644
| 2.40625
| 2
|
[] |
no_license
|
package controller;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.mail.MessagingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.sendEmail;
/**
* Servlet implementation class forgotPasswordController
*/
@WebServlet(description = "takes email id and sends change password link to email id", urlPatterns = { "/forgotPassword" })
public class forgotPasswordController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String recovery_email[] = {request.getParameter("recovery_email")};
String rec_email = recovery_email[0];
ResultSet rs;
boolean indicator = false;
String content = "<!DOCTYPE html><html><head></head><body><center><h1 style='color:red;'>BUMpy</h1>"
+ "<h3>Click the link below to change your account passsword</h3>"
+ "<a href=\"http://localhost:8080/BUMpy/changePassword?q=" + rec_email +"\">Click here to change your account password now</a><br /><br /></center></body></html>";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/socialnet","root","");
Statement st= (Statement) con.createStatement();
rs = st.executeQuery("SELECT email from users WHERE email='" + rec_email + "'");
if(rs.next()){
indicator=true;
}
else{
indicator=false;
}
} catch (Exception e){System.out.println("Hello forgotController : " + e.getMessage());}
if(indicator){
try {
sendEmail.sendEmailTo(recovery_email,"BUMpy - Change Password Link",content);
} catch (MessagingException e) {
// TODO Auto-generated catch block
System.out.println("error forgot Password : " + e.getMessage());
}
RequestDispatcher rd=request.getRequestDispatcher("checkYourEmail.html");
rd.forward(request, response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("incorrect-recovery-email-error.html");
rd.forward(request, response);
}
}
}
|
Python
|
UTF-8
| 14,469
| 3.328125
| 3
|
[
"MIT"
] |
permissive
|
import numpy as np
from numpy import linalg as LA
import numpy as np
np.set_printoptions(suppress=True, precision=4)
import matplotlib.pyplot as plt
from collections import OrderedDict
# used by histograms_overlap
def histogram_bins_centered(data, nbins):
""" helper function for numpy histograms, to generate bins that are centered, similar to the MATLAB hist
for python, nbins are specified by n+1 numbers, marking the boundaries of the bins
this allows for uneven spaced bins """
# np.ptp is "peak-to-peak," or range
# bin_width = np.ptp(data) / (nbins - 1)
# bins = np.linspace(np.min(data) - bin_width / 2, np.max(data) + bin_width / 2, nbins + 1)
bins = np.linspace(np.min(data), np.max(data), nbins + 1)
# bins now has nbins+1 values, and ranges across the data
return bins
def histogram_bins_centered_test():
""" simple test """
# bins = histogram_bins_centered(series, nbins=5)
# print(bins)
pass
# svd_like_matlab used by histograms overlap
def svd_like_matlab(A):
""" The MATLAB and python SVDs return different values
this function uses the python libraries, but the return values are
those specfied in MATLAB https://www.mathworks.com/help/matlab/ref/double.svd.html
[U,S,V] = svd(A)
performs a singular value decomposition of matrix A, such that
A = U*S*V'
IN PYTHON,
u, s, vh = np.linalg.svd(A)
Factors the matrix a as
u @ np.diag(s) @ v
where u and v are unitary and s is a 1d array of a's singular values
note that Python uses @ for matrix multiplication, and .T for transpose"""
# U, S, V = svd(A)
# use lowercase variable names for the python call
u, s, vh = np.linalg.svd(A)
# MATLAB users expect
# U, S, V = svd(A)
# rename MATLAB like variable here
# note that Python and MATLAB algos effectively flip U and V
U = u # no need to transpose!
S = np.diag(s) # in MATLAB, S is a diagonal matrix
V = vh.T
# print(U.shape)
# print(S.shape)
# print(V.shape)
return U, S, V
def svd_like_matlab_test():
""" test """
# MATLAB equivalent:
# A = [[0 1 2];[3 4 5]]
# [U, S, V] = svd(A)
A = np.array([[0, 1, 2], [3, 4, 5]])
print(A)
[U, S, V] = svd_like_matlab(A)
print('U\n' + str(U))
print('S\n' + str(S))
print('V\n' + str(V))
# eigs_like_matlab used by embeddings
def eigs_like_matlab(A, k=None):
""" like matlab's
d = eigs(A,k)
https://www.mathworks.com/help/matlab/ref/eigs.html
returns the k biggest (???) eigenvectors """
if k is None:
k = A.shape[0]
# this is how eig is usually called in python
w, v = LA.eig(A)
D = np.diag(w[:k]) # MATLAB returns a diagonal matrix
# NOTE - do I need to sort these first, or are they automatically largerst?
# (check by looking at D?)
V = v[:, :k] # rename, and remove later eigenvectors
# TODO - we are not sorting the vectors according to eigenvalues? (check?)
return V, D
def eigs_like_matlab_test():
""" code, and make sure it looks like the MATLAB """
# Python eigenvalaues
# https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html
#
# w,v = eig(a)
#
# v[:,i] is the RIGHT eigenvector corresponding to values w[i]
#
# (appears that in python, w[0] ≈ 1,
# meaning eigenvectors have been normed and sorted)
#
# MATLAB eigs
# https://www.mathworks.com/help/matlab/ref/eigs.html
# [V, D] = eigs(A,k)
#
# (to make matters more confusing, they use [V, E] = eigs(W2,10))
#
# V[:,i] and D[i,i]
# V columns are eigenvectors
# D is the diagonal matrix of the eigen values
#
# returns the k biggest (???) eigenvectors """
a = np.random.rand(3, 3)
V, E = eigs_like_matlab(a, 2)
print('\n original matrix a:\n' + str(a))
print('\n V:\n' + str(V))
print('\n E:\n' + str(E))
# w, v = LA.eig(a)
# print('\n w (as diags):\n' + str(np.diag(w)))
# print('\n v\n' + str(v))
# i = 0
# eigvec = v[:,i]
# eigval = w[i]
# print('\n eigval\n' + str(w[i]))
# print('\n eigvec\n' + str(eigvec))
# print('A * eigvec / eigval ')
# print('\n multilpy:' + str(a @ eigvec / eigval))
import pandas as pd
def simplify_data(z_shape=(8, 87660)):
""" takes in a datastream of data, z, and makes a simple version
specifically, z should be [(8, 87660)] """
# set at era to me about 200*5 points ...
# this will give about 10 eras over 10k points,
# which can be downsampled by 5, and viewed as 2000 points
era = 1000 # how long is each sub-section (cos, gaussian noise, etc.)
total_length = z_shape[1] # total length of the z (and z_mod)
# create a datastructure, containing low-level noise, to contain the data
z_mod = 1e-3 * np.random.randn(z_shape[0], z_shape[1]) # fill with low-level noise
# this will hold the actual signal (only for the first row)
sig = np.array([])
while (sig.size < total_length):
# print('appending some more data ...')
sig_zero = np.zeros(era)
# gaussian noise
sig_gauss = np.random.randn(era)
# uniform noise
sig_unif = np.random.rand(era)
# cos, 10 cycles over the era
sig_cos = np.cos(2 * np.pi * np.arange(era) / era * 10.)
# sin, 5 cycles over the era
sig_sin = .1 * np.sin(2 * np.pi * np.arange(era) / era * 5.)
sig_root_sin = np.sqrt(np.abs(np.sin((2 * np.pi * np.arange(era) / era * 10.))))
# append all together ...
sig = np.concatenate((sig, sig_zero, sig_gauss, sig_unif, sig_cos, sig_sin, sig_root_sin))
# signal may be too long, cut to correct length
sig = sig[:total_length]
# fade in and out each section, usin a cosine wave
sin_mask = np.sin(2 * np.pi * np.arange(total_length) / (2*era))
sig = sig * sin_mask
# add to the final dataset
z_mod[0, :] += sig
z_mod[1, :-1] += np.diff(sig) # add the diff to the second row
# optional? Normalize each row from 0 to 1
z_mod = z_mod - np.min(z_mod, axis=1).reshape(-1, 1)
z_mod = z_mod / np.max(z_mod, axis=1).reshape(-1, 1)
z_mod = np.round(z_mod, 6)
# the fmt command suppress scientific notation / small number-junk
np.savetxt("data/simple_data2.csv", z_mod, delimiter=',', fmt='%1.6f')
return z_mod
from scipy.stats import norm, kurtosis
from scipy import stats
from scipy.stats import skew
def test_moms():
""" look at numpy's calculation of higher order momets (through kurtosis), see
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skew.html#scipy.stats.skew
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosis.html#scipy.stats.kurtosis
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.moment.html
"""
# create some test data
x = np.random.randn(100) + (.1 + .2 * np.random.rand(100))
print('*** calculating moments, using numpy')
print('np.mean(x)', np.mean(x))
print('np.var(x)', np.var(x))
print('*** higher moments, using scipy')
print('skew', skew(x))
print('kurtosis (Fisher is default)', kurtosis(x))
print('scipy describe', stats.describe((x)))
#des = stats.describe(x)
# note, all the values are the same, except var, which is 1/(n-1) in describe, but 1/n for numpy ... weird ...
def get_log_spaced_bins(max_value=350.1):
""" generate the bin boundaries for use with np.histogram, with log spacing
the CENTER bin values will be 1,2,5,10,20, etc
the BOUNDARY values will be 0, 1.5,2.5,7.5,15, etc.
"""
assert max_value > 0, 'max_value must be positive'
bin_values = [0]
mult = 1
while (True):
bin_values.append(mult * 1)
if bin_values[-1] > max_value * 10: break
bin_values.append(mult * 2)
if bin_values[-1] > max_value * 10: break
bin_values.append(mult * 5)
if bin_values[-1] > max_value * 10: break
mult *= 10
bin_values = np.array(bin_values)
# [0 1 2 5 10 20 50 100 200 500]
bin_boundaries = np.diff(bin_values) / 2 + bin_values[:-1]
# [0.5 1.5 3.5 7.5 15. 35. 75. 150. 350.]
bin_boundaries[0] = 0
# [0 1.5 3.5 7.5 15. 35. 75. 150. 350.]
# made extra bins - now, cut down the bin boundaries so that the data just fits
while (bin_boundaries[-2] > max_value):
bin_boundaries = bin_boundaries[:-1] # cut out last element
# cut down the bin values, to match
# (do not need first element, which is zero, and should be one less elements that the bin_boundaries
bin_values = bin_values[1:bin_boundaries.size]
print(bin_values)
print(bin_boundaries)
import collections
def count_cluster_lengths(x):
""" takes an array in, x, which contains a series of cluster labels,
and returns the result in a dictionary
"""
# find the unique values (these are the cluster names)
keys = np.unique(x)
np.sort(keys) # happens in place
print('cluster names (keys)', keys)
# create dictionary of 'cluster_lengths' with empty lists
cluster_lens = collections.OrderedDict()
for key in keys:
cluster_lens[key] = []
# find the matching values
# loop through the sequence
i = 0
while (i < x.size):
this_val = x[i]
d = np.where(x[i:] != this_val)[0] # find where the value changes
if d.size > 0:
# now know how many points, before the value changes
this_len = d[0] # first location that is not this_val
else:
this_len = x.size - i # this was the last cluster, goes to the end
# this_val is the custer
# this_len is the length of that cluster
# ... store it!
cluster_lens[this_val].append(this_len)
# print(str(this_val),str(this_len))
# print(d)
i += this_len
return cluster_lens
# for key in keys:
# # also, sort the lists here
# cluster_lens[key].sort() # on the list, happens in place
# print('key', key, 'value', cluster_lens[key], '\n')
def print_cluster_lens(cluster_lens):
""" prints out the dictionary object created, that stores cluster lengths """
for key in cluster_lens.keys():
# also, sort the lists here
cluster_lens[key].sort() # on the list, happens in place
print('key', key, 'value', cluster_lens[key], '\n')
def show_cluster_lens(cluster_lens):
""" plots the lengths of the clusters, as determined above """
keys = list(cluster_lens.keys())
nkeys = len(keys)
plt.figure()
fig, axes = plt.subplots(nkeys, 1, sharex=True, sharey=True, figsize=[7, nkeys*1 + 1])
# loop through, and make all the histograms, as subplots
for k in range(nkeys):
key = keys[k]
different_lengths_this_cluster = np.unique(cluster_lens[key])
for l in different_lengths_this_cluster:
number_of_occurrences = np.sum(np.where(cluster_lens[key] == l)[0])
# print('length', l, 'number_of_occurrences', number_of_occurrences)
# plot as a vertical bar
axes[k].plot([l, l], [0, number_of_occurrences])
axes[k].set_ylabel('cl ' + str(k))
plt.tight_layout()
plt.suptitle('cluster length histograms')
plt.xlabel('cluster lengths')
plt.show()
def test_count_cluster_lengths():
""" lol """
a = np.array([0, 0, 0, 5, 5, 0, 0, 1, 1, 4])
cluster_lens = count_cluster_lengths(a)
print_cluster_lens(cluster_lens)
###
### transition matrix
###
def make_transition_matrix(states):
""" transition matrix of a bunch of states (like IDX)"""
states_max = np.max(states)
tmat = np.zeros((states_max + 1, states_max + 1))
# note, transition matrix is written with the
# STATES AS COLUMNS, as in quantum mechanics / physics
#
# evolution is then:
# |state+1> = tmat @ |state>
#
# (but need to normalize tmat)
#
for i in range(states.size - 1):
# states[i+1] is valid
state_from = states[i]
state_to = states[i + 1]
tmat[state_to, state_from] += 1
return tmat
def make_matrix_markov(A):
""" takes a matrix, and normalizes so that each column sums to one
(assumes matrix values are already positive!)"""
# makes more sense to normalize so that the columns sum to one
col_sum = np.sum(A, axis=0).reshape(1, -1)
# print(col_sum)
A_markov = A / col_sum # col_sum will broadcast
return A_markov
# A = np.random.randn(3,3)
# print(A)
# print(make_matrix_markov(A))
def image_M(data, vmax=None):
""" t for transition matrix"""
plt.figure(figsize=(7, 7))
# create scaled data
if vmax is None:
vmax = np.max(np.abs(data))
# cmap = 'gist_heat'
# cmap = 'bone'
cmap = 'hot'
# cmap = 'binary'
plt.imshow(data, vmin=0, vmax=vmax, cmap=cmap)
plt.grid(b=None)
plt.xlabel('from')
plt.ylabel('to')
plt.colorbar()
plt.title('transition matrix')
plt.show()
def reorder_cluster(IDX, M):
""" renames the clusters, so the diagonal elements of M will be in decreasing order
note, M must be regenerated from the new_IDX that is returned"""
print('NOTE, need to fix bug, sometimes orders backwards')
idx_freq = M.diagonal()
new_idx = np.zeros_like(IDX)
# sort the values of the index, from largest to smallest
new_order = np.argsort(idx_freq)
# so weird ... new_order is alternately lowest-to-highest, and highest-to-lowest
# just reorder, if needed
# if idx_freq[new_order[-1]] > idx_freq[new_order[-1]]:
# # frequency INCREASES at the end ... reorder!
# print('yup!')
# new_order = new_order[::-1]
# else:
# print('nerp!!')
new_order = new_order[::-1]
for i in range(len(new_order)):
# find all the locations matching next index needed
loc = np.where(IDX == new_order[i])
new_idx[loc] = i # reorder, starting with i
return new_idx
|
Markdown
|
UTF-8
| 2,403
| 3.3125
| 3
|
[] |
no_license
|
# User Guide
Ponyo is a desktop app for managing your todos, optimised for use via a Command Line Interface (CLI) while still having the benefits of a Graphical User Interface (GUI).
**💡 Notes about the command format:**
* Words in `UPPER_CASE` are the parameters to be supplied by the user.
e.g. in `todo TASK`, `TASK` is a parameter which can be used as `todo english homework`.
## Features
### Adding a todo: `todo`/`t`
Adds a todo to the task list.
*Format:* `todo TASK` / `t TASK`
*Examples:*
* `todo math homework`
* `t math homework`
### Adding a deadline: `deadline`/`d`
Adds a deadline to the task list.
*Format:* `deadline TASK /by DATE` / `d TASK /by DATE`
*Examples:*
* `deadline apply for scholarship /by 2020-09-20`
* `d apply for scholarship /by 2020-09-20`
### Adding an event: `event`/`e`
Adds an event to the task list.
*Format:* `event EVENT /at DATE` / `e EVENT /at DATE`
*Examples:*
* `event club meeting /at 2020-10-01`
* `e club meeting /at 2020-10-01`
### Listing all tasks: `list`/`l`
Lists all completed and uncompleted tasks.
*Format:* `list`/`l`
### Marking a task as done: `done`
Marks a task as done.
*Format:* `done INDEX`
* Marks the task as done at the specified `INDEX`
* The index refers to the index number shown in the displayed task list.
* The index **must be a positive integer** 1, 2, 3, ...
*Examples:*
* `list` followed by `done 1` marks the 1st task as done in the address book.
### Delete a task `delete`/`del`
Deletes the specified task from the task list.
*Format:* `delete INDEX` / `del INDEX`
* Deletes the task at the specified `INDEX`
* The index refers to the index number shown in the displayed task list.
* The index **must be a positive integer** 1, 2, 3, ...
*Examples:*
* `list` followed by `delete 1` deletes the 1st task in the address book.
* `l` followed by `del 1` deletes the 1st task in the address book.
### Locating a task by name: `find`/`f`
Finds persons whose names contain any of the given keywords.
*Format:* `find KEYWORD` / `f KEYWORD`
* Half-words, full words, single letters will all be matched.
*Examples:*
* `find soccer` returns `soccer training`
### Exiting the program: `exit`/`bye`
Exits the program.
*Format:* `exit` / `bye`
### Saving the data
Ponyo's tasks data are saved in the hard disk automatically after any command that changes the data. There is no need to save manually.
|
Java
|
UTF-8
| 6,786
| 2.125
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright (C) 2017 Ignite Realtime Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.container;
import java.net.URL;
import java.nio.file.Path;
import org.jivesoftware.util.JavaSpecVersion;
import org.jivesoftware.util.Version;
/**
* A bean-like representation of the metadata of a plugin.
*
* @author Guus der Kinderen, guus.der.kinderen@gmail.com
*/
public class PluginMetadata
{
/**
* Human readable name of the plugin.
*/
private final String name;
/**
* Canonical name of the plugin.
*/
private final String canonicalName;
/**
* Description of the plugin as specified in plugin.xml.
*/
private final String description;
/**
* The version of the plugin.
*/
private final Version version;
/**
* Author of the plugin as specified in plugin.xml.
*/
private final String author;
/**
* Icon's location of the plugin.
*/
private final URL icon;
/**
* Changelog location of the latest version of the plugin.
*/
private final URL changelog;
/**
* ReadMe location of the latest version of the plugin.
*/
private final URL readme;
/**
* Type of license of the plugin.
*/
private final String license;
/**
* Minimum server version (inclusive) required by this plugin as specified in plugin.xml.
*/
private final Version minServerVersion;
/**
* Maximum server version (exclusive) required by this plugin as specified in plugin.xml.
*/
private final Version priorToServerVersion;
/**
* Minimum Java (specification) version (inclusive) required by this plugin as specified in plugin.xml.
*/
private final JavaSpecVersion minJavaVersion;
/**
* Indicates if the plugin supports standard CSRF protection
*/
private final boolean csrfProtectionEnabled;
/**
* Constructs a metadata object based on a plugin.
*
* The plugin must be installed in Openfire.
*
* @param pluginDir the path of the plugin directory (cannot be null)
* @return Metadata for the plugin (never null).
*/
public static PluginMetadata getInstance( Path pluginDir )
{
return new PluginMetadata(
PluginMetadataHelper.getName( pluginDir ),
PluginMetadataHelper.getCanonicalName( pluginDir ),
PluginMetadataHelper.getDescription( pluginDir ),
PluginMetadataHelper.getVersion( pluginDir ),
PluginMetadataHelper.getAuthor( pluginDir ),
PluginMetadataHelper.getIcon( pluginDir ),
PluginMetadataHelper.getChangelog( pluginDir ),
PluginMetadataHelper.getReadme( pluginDir ),
PluginMetadataHelper.getLicense( pluginDir ),
PluginMetadataHelper.getMinServerVersion( pluginDir ),
PluginMetadataHelper.getPriorToServerVersion( pluginDir ),
PluginMetadataHelper.getMinJavaVersion( pluginDir ),
PluginMetadataHelper.isCsrfProtectionEnabled( pluginDir )
);
}
/**
* Constructs a metadata object based on a plugin.
*
* The plugin must be installed in Openfire.
*
* @param plugin The plugin (cannot be null)
* @return Metadata for the plugin (never null).
*/
public static PluginMetadata getInstance( Plugin plugin )
{
return new PluginMetadata(
PluginMetadataHelper.getName( plugin ),
PluginMetadataHelper.getCanonicalName( plugin ),
PluginMetadataHelper.getDescription( plugin ),
PluginMetadataHelper.getVersion( plugin ),
PluginMetadataHelper.getAuthor( plugin ),
PluginMetadataHelper.getIcon( plugin ),
PluginMetadataHelper.getChangelog( plugin ),
PluginMetadataHelper.getReadme( plugin ),
PluginMetadataHelper.getLicense( plugin ),
PluginMetadataHelper.getMinServerVersion( plugin ),
PluginMetadataHelper.getPriorToServerVersion( plugin ),
PluginMetadataHelper.getMinJavaVersion( plugin ),
PluginMetadataHelper.isCsrfProtectionEnabled( plugin )
);
}
public PluginMetadata( String name, String canonicalName, String description, Version version, String author,
URL icon, URL changelog, URL readme, String license,
Version minServerVersion, Version priorToServerVersion, JavaSpecVersion minJavaVersion, boolean csrfProtectionEnabled)
{
this.name = name;
this.canonicalName = canonicalName;
this.description = description;
this.version = version;
this.author = author;
this.icon = icon;
this.changelog = changelog;
this.readme = readme;
this.license = license;
this.minServerVersion = minServerVersion;
this.priorToServerVersion = priorToServerVersion;
this.minJavaVersion = minJavaVersion;
this.csrfProtectionEnabled = csrfProtectionEnabled;
}
public String getName()
{
return name;
}
public String getCanonicalName()
{
return canonicalName;
}
public String getDescription()
{
return description;
}
public Version getVersion()
{
return version;
}
public String getAuthor()
{
return author;
}
public URL getIcon()
{
return icon;
}
public URL getChangelog()
{
return changelog;
}
public URL getReadme()
{
return readme;
}
public String getLicense()
{
return license;
}
public Version getMinServerVersion()
{
return minServerVersion;
}
public Version getPriorToServerVersion()
{
return priorToServerVersion;
}
public JavaSpecVersion getMinJavaVersion()
{
return minJavaVersion;
}
public String getHashCode() {
return String.valueOf( hashCode() );
}
public boolean isCsrfProtectionEnabled() {
return csrfProtectionEnabled;
}
}
|
Java
|
UTF-8
| 794
| 2.15625
| 2
|
[] |
no_license
|
package com.crossover.ws.vo;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "list", namespace = "http://crossoverws.com")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "list", namespace = "http://crossoverws.com")
public class ListFilesVO {
@XmlElement(name = "file", namespace = "")
private List<String> files;
public ListFilesVO() {
super();
this.files = new ArrayList<String>();
}
public List<String> getFiles() {
return files;
}
public void setFiles(List<String> files) {
this.files = files;
}
}
|
C
|
UTF-8
| 2,965
| 3.984375
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
// COROUTINES HELPER FUNCTIONS AND VARIABLES
// Co Routines Variables
#define length 5 // Number of coroutines
pthread_t tid[length]; // Thread for each player
long int tcnt = 0;
pthread_mutex_t tlocks[length]; // Creating lock for each thread
pthread_mutex_t lock; // Main lock for critical section
char mesg[1024] = "\0"; // Message to be sent
// Co Routine helper function
// Initializing all mutex
void cr_init(){
int i = 0;
for(i = 0; i < length; i++){
pthread_mutex_init(&(tlocks[i]), NULL); // Initialising all the thread_locks
pthread_mutex_lock(&(tlocks[i])); // Locking all the threads so that game cant be played till all players are created
}
pthread_mutex_init(&lock, NULL); // Initializing the critical section lock
pthread_mutex_lock(&lock); // Locking the critical section lock
}
// Create a co-routine by passing function pointer
int cr_create(void *(*f)(void *)){
pthread_create(&(tid[tcnt++]), NULL, f, NULL); // Creating each thread
pthread_mutex_lock(&lock); // Critical section so that the game function initializes
return tcnt - 1;
}
// Send data to a co routine and continue execution(handle.send function)
void cr_send(int cr_id, char *msg){
strcpy(mesg, msg); // Copying message to global variable
pthread_mutex_unlock(&(tlocks[cr_id])); // Unlocking the thread so that the player could play the game
pthread_mutex_lock(&lock); // Critical section so that only one player can play at a time
}
// Breakpoints within functions (Yeild in python)
void cr_yeild(int cr_id){
pthread_mutex_unlock(&lock); // Allowing the unlocked player to play the game
pthread_mutex_lock(&(tlocks[cr_id])); // Locking the player so that it could play only once
}
// Killing a co routine (closing the handle in python)
void cr_kill(int cr_id){
pthread_cancel(tid[cr_id]); // Killing the thread
pthread_mutex_destroy(&(tlocks[cr_id])); // Killing the mutex lock
}
// A simple message printing Co Routine function
void* print_mesage(void *arg)
{
int cr_id = tcnt - 1;
while(1){
cr_yeild(cr_id);
printf("Seng\n");
printf("Message sent by: %d and the message is: %s\n", cr_id, mesg);
}
return NULL;
}
// MAIN
int main(void)
{
// Init
cr_init();
// Create some co routines
printf("Seg\n");
int cr1 = cr_create(&print_mesage);
int cr2 = cr_create(&print_mesage);
// Sending messages to co routines
cr_send(cr1, "Hi This is Pranav");
cr_send(cr1, "This is a simple CoRoutine Implementaion");
cr_send(cr2, "This is second co routinee");
cr_send(cr2, "This is also from second coroutine");
// Killing the routine
cr_kill(cr1);
cr_kill(cr2);
return 0;
}
|
Java
|
UTF-8
| 777
| 3.359375
| 3
|
[] |
no_license
|
package com.main.learn.threads.geek.part1;
/**
* @Description Test
* @Author sunlei19
* @Date 2020/12/5 20:19
* @Version 1.0
*/
public class Test {
private Long count = 0L;
private void add10K() {
int idx = 0;
while (idx++ < 10000) {
synchronized (count) {
count += 1;
}
}
}
public long calc() throws InterruptedException {
// 创建两个线程,执行add()操作
Thread th1 = new Thread(() -> {
this.add10K();
});
Thread th2 = new Thread(() -> {
this.add10K();
});
th1.start();
th2.start();
th1.join();
th2.join();
return count;
}
}
|
C++
|
UTF-8
| 3,389
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#pragma once
template <class T>
class JitExpandArray
{
CompAllocator m_alloc;
T* m_data = nullptr;
unsigned m_size = 0;
unsigned m_minSize;
void EnsureSize(unsigned size)
{
assert(size >= m_size);
unsigned oldSize = m_size;
T* oldData = m_data;
unsigned newSize = Max(size, Max(m_minSize, oldSize * 2));
T* newData = m_alloc.allocate<T>(newSize);
if (oldData != nullptr)
{
for (unsigned i = 0; i < oldSize; i++)
{
newData[i] = oldData[i];
}
m_alloc.deallocate(oldData);
}
for (unsigned i = oldSize; i < newSize; i++)
{
newData[i] = T();
}
m_data = newData;
m_size = newSize;
}
public:
JitExpandArray(CompAllocator alloc, unsigned minSize) : m_alloc(alloc), m_minSize(minSize)
{
}
T& operator[](unsigned i)
{
if (i >= m_size)
{
EnsureSize(i + 1);
}
return m_data[i];
}
};
template <class T>
class JitVector
{
CompAllocator m_alloc;
T* m_data = nullptr;
unsigned m_size = 0;
unsigned m_capacity = 0;
void EnsureCapacity(unsigned newCapacity)
{
assert(newCapacity >= m_capacity);
newCapacity = Max(newCapacity, Max(m_capacity * 2, 4u));
T* oldData = m_data;
T* newData = m_alloc.allocate<T>(newCapacity);
if (oldData != nullptr)
{
for (unsigned i = 0; i < m_size; i++)
{
newData[i] = oldData[i];
}
m_alloc.deallocate(oldData);
}
m_data = newData;
m_capacity = newCapacity;
}
public:
JitVector(CompAllocator alloc) : m_alloc(alloc)
{
}
unsigned Size() const
{
return m_size;
}
bool Empty() const
{
return m_size == 0;
}
void Clear()
{
m_size = 0;
}
T& operator[](unsigned i)
{
assert(i < m_size);
return m_data[i];
}
const T& operator[](unsigned i) const
{
assert(i < m_size);
return m_data[i];
}
void Reserve(unsigned capacity)
{
if (capacity > m_capacity)
{
EnsureCapacity(capacity);
}
}
void Add(const T& value)
{
if (m_size == m_capacity)
{
EnsureCapacity(m_capacity + 1);
}
m_data[m_size++] = value;
}
template <typename... Args>
void Emplace(Args&&... args)
{
if (m_size == m_capacity)
{
EnsureCapacity(m_capacity + 1);
}
new (&m_data[m_size++]) T(std::forward<Args>(args)...);
}
void Remove(unsigned i)
{
assert(i < m_size);
for (unsigned j = i + 1; j < m_size; j++)
{
m_data[j - 1] = m_data[j];
}
m_size--;
}
T* begin()
{
return m_data;
}
const T* begin() const
{
return m_data;
}
T* end()
{
return m_data + m_size;
}
const T* end() const
{
return m_data + m_size;
}
};
|
Java
|
UTF-8
| 2,295
| 2.015625
| 2
|
[] |
no_license
|
package brytskyi.week6_7.sql.notebook_shop.services;
import brytskyi.week6_7.sql.notebook_shop.model.exceptions.dao_exceptions.NullFieldException;
import brytskyi.week6_7.sql.notebook_shop.model.production.*;
import brytskyi.week6_7.sql.notebook_shop.model.selling.Prodaja;
import brytskyi.week6_7.sql.notebook_shop.model.users.Buyer;
import brytskyi.week6_7.sql.notebook_shop.model.users.Seller;
import java.util.Date;
import java.util.List;
/**
* Created by alexandr on 08.11.16.
*/
public interface IAdminService extends IGetProductionService {
NotebookModel addNotebookModel(NotebookModel model);
NotebookModel getNoteBookModelById(int id);
NotebookModel removeNotebookModel(int id);
Processor addProcessor(Processor processor);
Processor getProcessorById(int id);
Processor removeProcessor(int id);
HardMemory addHardMemory(HardMemory hardMemory);
HardMemory getHardMemoryById(int id);
HardMemory removeHardMemory(int id);
OperativeMemory addOperativeMemory(OperativeMemory operativeMemory);
OperativeMemory removeOperativeMemory(int id);
OperativeMemory getOperativeMemoryById(int id);
VideoMemory addVideoMemory(VideoMemory videoMemory);
VideoMemory removeVideoMemory(int id);
VideoMemory getVideoMemoryById(int id);
Display addDisplay(Display display);
Display removeDisplay(int id);
Display getDisplayById(int id);
Partiya priniatPartiyu(List<NotebookForSail> notebooks, int notebookTypeId) throws NullFieldException;
NotebookType createNoteBookType(String desc, double price, int modelId, int processoId, int hardMemId, int operMemId, int videoMemId, int displayId) throws NullFieldException;
NotebookType getNotebookTypeById(int id);
NotebookType removeNotebookType(int id);
NotebookForSail spisatNotebook(int id) throws NullFieldException;
List<NotebookForSail> getSelledNotebooks(Date start, Date end);
List<NotebookForSail> getSpisaniNotebooks(Date start, Date end);
Buyer addBuyer(Buyer buyer) throws NullFieldException;
List<Buyer> getBuyers();
List<Seller> getSellers(boolean working);
List<Prodaja> getNoteBooksSelled(int buyer, Date begin, Date end);
List<Prodaja> getNoteBooksBuyed(int seller, Date begin, Date end);
}
|
PHP
|
UTF-8
| 272
| 3.390625
| 3
|
[] |
no_license
|
<?php declare(strict_types = 1);
namespace Gaua;
class Rounder
{
public function up(float $amount) : float
{
return ceil($amount * 100) / 100;
}
public function down(float $amount) : float
{
return floor($amount * 100) / 100;
}
}
|
TypeScript
|
UTF-8
| 2,760
| 2.546875
| 3
|
[] |
no_license
|
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { ITour } from '../itour';
import { IUser } from '../iuser';
import { UsersService } from '../services/users.service';
import { ToursService } from './tours.service';
export class Credentials {
email: string = '';
password: string = '';
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
usersRoles = new Map<string, string[]>();
userData: IUser;
constructor(private afAuth: AngularFireAuth, private usersService: UsersService, private toursService: ToursService) {
this.usersService.getUserRoles().subscribe(roles => {
roles.forEach(userRole => {
this.usersRoles.set(userRole.email, userRole.roles);
});
});
this.afAuth.authState.subscribe(user => {
console.log(user);
if ( user ){
this.userData = user;
if (this.usersRoles.get(user.email) == null){
console.log('Add new user');
usersService.addUser(user);
usersService.setUserWithEmail(user.email);
} else {
usersService.setUserWithEmail(user.email);
}
} else{
this.userData = null;
}
});
}
// get user(): User | null {
// return this.afAuth.currentUser;
// }
private checkAuthorization(allowedRoles: string[]): boolean{
if (this.userData == null) { return false; }
const roles = this.usersRoles.get(this.userData.email);
if (roles == null) { return false; }
for (const role of allowedRoles){
// console.log(role);
if (roles.includes(role)) { return true; }
}
return false;
}
isUserAdmin(): boolean {
return this.checkAuthorization(['admin']);
}
canEdit(): boolean {
return this.checkAuthorization(['admin', 'editor']);
}
isVIP(): boolean{
return this.checkAuthorization(['VIP','admin','editor']);
}
// tslint:disable-next-line:typedef
isLoggedIn() {
return this.userData != null;
}
// tslint:disable-next-line:typedef
login({ email, password }: Credentials) {
return this.afAuth.signInWithEmailAndPassword(email, password).then(() => { //this.usersService.setUserWithEmail(email);
} );
}
// tslint:disable-next-line:typedef
register({ email, password }: Credentials) {
return this.afAuth.createUserWithEmailAndPassword(email, password);
}
// tslint:disable-next-line:typedef
logout() {
return this.afAuth.signOut();
}
canShow(tour: ITour) : boolean {
if( this.canEdit() ) return true;
if( tour.dateStart > Date.now()) {
if( this.isVIP() ) { return true; }
else if( this.isLoggedIn() && tour.availablePlaces > 1 ){
return true;
}
}
return false;
}
}
|
C++
|
UTF-8
| 1,067
| 3.59375
| 4
|
[] |
no_license
|
//
// Chapter 04. Divide-and-Conquer
//
// Maximum-Subarray Problem (P68~74): O(n) Complexity (P75)
//
// Hao Wu, 04/18/2014
//
// Reference 1: http://en.wikipedia.org/wiki/Maximum_subarray_problem
// Reference 2: http://goo.gl/mMA0LZ
//
#include <stdio.h>
#include <stdlib.h> // malloc() and free()
//
///
//
inline int max(int x, int y)
{
return x < y ? y : x;
}
//
int find_maximum_subarray(int* a, int n)
{
//
// b[j]: best solution in a[0..j].
// c[j]: best solution in a[0..j], whose right edge is exactly at j.
//
int* b = (int*)malloc(n * sizeof(int));
int* c = (int*)malloc(n * sizeof(int));
b[0] = a[0];
c[0] = a[0];
for (int i = 1; i < n; i++) {
c[i] = max(c[i - 1] + a[i], a[i]);
b[i] = max(b[i - 1], c[i]);
}
int s = b[n - 1];
free(b);
free(c);
return s;
}
//
///
//
int main()
{
//int a[] = {5, 2, 4, 6, 1, 3};
int a[] = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7,
12, -5, -22, 15, -4, 7};
int n = 16;
int sum = find_maximum_subarray(a, n);
printf("%d\n", sum);
}
//
///
////
///
//
|
C#
|
UTF-8
| 1,079
| 2.546875
| 3
|
[] |
no_license
|
using FitApp.Services;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace FitApp.Pages
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SignUpPage : ContentPage
{
public SignUpPage()
{
InitializeComponent();
}
async void ImgSignup_Tapped(object sender, EventArgs e)
{
ApiServices apiServices = new ApiServices();
bool response = await ApiServices.RegisterUser(EntName.Text,EntEmail.Text, EntPassword.Text, Convert.ToDouble(EntWeight.Text), Convert.ToDouble(EntHeight.Text));
if (!response)
{
await DisplayAlert("Alert", "Information entered incorrectly", "Cancel");
}else
{
await DisplayAlert("Success", "Your account has been created", "Ok");
await Navigation.PopToRootAsync();
}
}
private void ImgBack_Tapped(object sender, EventArgs e)
{
Navigation.PushAsync(new LoginPage());
}
}
}
|
Markdown
|
UTF-8
| 3,854
| 2.859375
| 3
|
[] |
no_license
|
---
description: "Simple Way to Make Award-winning Banana, spinach and blueberry smoothie"
title: "Simple Way to Make Award-winning Banana, spinach and blueberry smoothie"
slug: 1657-simple-way-to-make-award-winning-banana-spinach-and-blueberry-smoothie
date: 2022-01-21T15:17:55.683Z
image: https://img-global.cpcdn.com/recipes/8e4b04722bb950b1/680x482cq70/banana-spinach-and-blueberry-smoothie-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/8e4b04722bb950b1/680x482cq70/banana-spinach-and-blueberry-smoothie-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/8e4b04722bb950b1/680x482cq70/banana-spinach-and-blueberry-smoothie-recipe-main-photo.jpg
author: Jeanette Walton
ratingvalue: 4.7
reviewcount: 17741
recipeingredient:
- "2 pieces Banana"
- "50 grams Spinach leaves"
- "100 g Blueberries"
- " Ice"
recipeinstructions:
- "Mix all ingredients in a blender."
categories:
- Recipe
tags:
- banana
- spinach
- and
katakunci: banana spinach and
nutrition: 289 calories
recipecuisine: American
preptime: "PT25M"
cooktime: "PT46M"
recipeyield: "3"
recipecategory: Lunch
---

Hey everyone, it's Brad, welcome to our recipe page. Today, I'm gonna show you how to make a distinctive dish, banana, spinach and blueberry smoothie. It is one of my favorites food recipes. For mine, I will make it a little bit tasty. This is gonna smell and look delicious.
Banana, spinach and blueberry smoothie is one of the most well liked of current trending meals in the world. It's enjoyed by millions daily. It is easy, it is fast, it tastes delicious. Banana, spinach and blueberry smoothie is something which I've loved my entire life. They're nice and they look wonderful.
Place the blueberries, spinach, and banana in a blender or food processor and blend until just combined. Add in the ice and continue to blend until the mixture is smooth. This blueberry banana spinach smoothie recipe is creamy scrumptiousness! It's also a fun way to get more fruits and vegetables in your diet.
To get started with this particular recipe, we have to prepare a few ingredients. You can have banana, spinach and blueberry smoothie using 4 ingredients and 1 steps. Here is how you cook it.
<!--inarticleads1-->
##### The ingredients needed to make Banana, spinach and blueberry smoothie:
1. Make ready 2 pieces Banana
1. Take 50 grams Spinach leaves
1. Prepare 100 g Blueberries
1. Get Ice
One of the first things to know about this green. Spinach, blueberries, bananas, wheat germ, flax and almond butter zipped up with almond milk… The combination of fresh spinach, blueberries and bananas in this smoothie is pretty perfect. Feel free to play around with the quantities of each if one is more palatable than another. This blueberry banana spinach smoothie is the perfect summer smoothie blend.
<!--inarticleads2-->
##### Steps to make Banana, spinach and blueberry smoothie:
1. Mix all ingredients in a blender.
Feel free to play around with the quantities of each if one is more palatable than another. This blueberry banana spinach smoothie is the perfect summer smoothie blend. It is so creamy and very refreshing to combat the summer heat. The berry flavor is balanced so well with the creaminess of the banana. Mix all ingredients in a blender.
So that's going to wrap this up with this special food banana, spinach and blueberry smoothie recipe. Thank you very much for your time. I am confident that you will make this at home. There's 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, friends and colleague. Thanks again for reading. Go on get cooking!
|
Markdown
|
UTF-8
| 1,233
| 2.78125
| 3
|
[] |
no_license
|
---
description: >-
Lets you export data to a datawarehouse or similar, so that you can do deep
analyses.
---
# Data Exports
{% hint style="info" %}
Need help setting up data exports and dashboards? We can help you! Contact us at [support@adnuntius.com](mailto:support@adnuntius.com) for more information.
{% endhint %}
You can set up as many exports as you want, to Amazon S3, S3 compatible buckets, Google Cloud and/or to Azure. You can also download logs at sftp://data.adnuntius.com:8164, using your Adnuntius username and password to authenticate. 
<figure><img src="../../../.gitbook/assets/202210 Exports.png" alt=""><figcaption><p>Example export.</p></figcaption></figure>
**Event types** lets you choose whether to export all events (in which case you may incur higher cost for data storage) or just some. 
Below you will see the fields to be filled in when exporting to S3, S3 compatible buckets, Google Cloud and to Azure. 
<figure><img src="../../../.gitbook/assets/202207 Exports - S3.png" alt=""><figcaption><p>Export to S3</p></figcaption></figure>
<figure><img src="../../../.gitbook/assets/202210 Exports - S3 Compatible (1).png" alt=""><figcaption><p>Export to S3 compatible bucket</p></figcaption></figure>
 
|
Python
|
UTF-8
| 1,133
| 3.78125
| 4
|
[] |
no_license
|
class Array(object):
def __init__(self, *items):
if items:
self.__array = [item for item in items]
else:
self.__array = []
def __len__(self):
return len(self.__array)
def append(self, item):
self.__array.append(item)
def __getitem__(self, index):
return self._array[index]
def extend(self, items):
self.__array.extend(items)
def contains(self, item):
return self.__array.index(item)
def remove(self, index):
if index < 0 or index > len(self.__array):
return -1
newArray = []
for i in range(len(self.__array)):
if i == index:
item = self.__array[index]
newArray.append(self.__array[i])
self.__array = newArray
return item
def __repr__(self):
return "Array({!r})".format(*self.__array)
def __str__(self):
string = ",".join(map(str, self.__array))
return "[{}]".format(string,)
if __name__ == '__main__':
arr = Array(1, 2, 3, 4, 5)
arr.append(6)
arr.extend((90, 34))
print(arr)
|
Shell
|
UTF-8
| 6,183
| 3.75
| 4
|
[
"BSD-3-Clause"
] |
permissive
|
#! /bin/sh
# send mail messages about new per-user DCC log files
# This script can be run by the daily DCC cron job after it has been
# 1. changed to contain the URL of the local DCC CGI scripts,
# 2. changed to use a locally suitable command to send mail
# 3. copied to the DCC libexec directory,
# 4. and made executable.
# It is remotely possible that the default values in this script are
# suitable and that you could use this script directly by putting
# the following in the libexec directory:
# #! /bin/sh
# sh /var/dcc/cgi-bin/webuser-notify -d $*
#
# This script expects to be called by the standard DCC cron job to read a
# series of user names on stdin, each of which has a new log file.
# Each user name must be prefixed with the appropriate subdirectory such
# as "local/". The single argument to this script must be the
# DCCM_USERDIRS or DCCIFD_USERDIRS_directory made into an absolute path.
# Copyright (c) 2010 by Rhyolite Software, LLC
#
# This agreement is not applicable to any entity which sells anti-spam
# solutions to others or provides an anti-spam solution as part of a
# security solution sold to other entities, or to a private network
# which employs the DCC or uses data provided by operation of the DCC
# but does not provide corresponding data to other users.
#
# Permission to use, copy, modify, and distribute this software without
# changes for any purpose with or without fee is hereby granted, provided
# that the above copyright notice and this permission notice appear in all
# copies and any distributed versions or copies are either unchanged
# or not called anything similar to "DCC" or "Distributed Checksum
# Clearinghouse".
#
# Parties not eligible to receive a license under this agreement can
# obtain a commercial license to use DCC by contacting Rhyolite Software
# at sales@rhyolite.com.
#
# A commercial license would be for Distributed Checksum and Reputation
# Clearinghouse software. That software includes additional features. This
# free license for Distributed ChecksumClearinghouse Software does not in any
# way grant permision to use Distributed Checksum and Reputation Clearinghouse
# software
#
# THE SOFTWARE IS PROVIDED "AS IS" AND RHYOLITE SOFTWARE, LLC DISCLAIMS ALL
# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL RHYOLITE SOFTWARE, LLC
# BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
# OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
# ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# Rhyolite Software DCC 1.3.138-1.13 $Revision$
# http or https; prefer https.
HTTPS="https"
# URL of the CGI scripts
# you will probably need to change this
BASE=`hostname`
BASE=`expr "$BASE" : '.*\.\([^.]*\.[^.]*$\)' \| "$BASE"`
BASE="www.$BASE/DCC-cgi-bin"
SWITCH='#webuser mail-notify'
USAGE="`basename $0`: [-x] -d userdirs"
USERDIRS=
while getopts "xd:" c; do
case $c in
x) set -x;;
d) USERDIRS=$OPTARG;;
*) ;;
esac
done
shift `expr $OPTIND - 1 || true`
if test "$#" -ne 0 -o "$USERDIRS" = ""; then
echo "$USAGE" 1>&2
exit 1
fi
if test ! -d "$USERDIRS"; then
echo "userdir $1 is not a directory" 1>&2
exit 1
fi
while read NM; do
# ignore users that are not configured to use the machinery
if test ! -f "$USERDIRS/$NM/whiteclnt"; then
continue;
fi
DIR="$USERDIRS/$NM"
UNAME=`expr "$NM" : 'local/\(.*\)' \| "$NM"`
OK=no
BOX="$UNAME"
eval `sed -n -e '/^[^#]/q' \
-e "s/^$SWITCH=on mailbox=$/OK=yes;/p" \
-e "s/^$SWITCH=on mailbox=\(.*\)/BOX=\1;OK=yes;/p" \
-e "s/^$SWITCH=off.*/OK=no;/p" $USERDIRS/$NM/whiteclnt`
if test "$OK" != yes; then
# forget it if notifications are turned off for this user
continue
fi
# Don't send a notification of messages older than this file,
# because the user has already check them through the CGI scripts.
MARKER=notify.marker
# Postpone notifications until this file is current to avoid sending
# daily notes that the user is ignoring.
BLOCK=notify.block
# Send a notification when this file is current
PENDING=notify.pending
FND="find $DIR -follow"
if test -f $DIR/$PENDING; then
# Because `find -mtime -0` sometimes means `find -mtime -1`
# or vice versa, use this to see if $DIR/$PENDING is finally ready.
rm -f $DIR/$MARKER
touch $DIR/$MARKER
if test "`$FND -name $PENDING -newer $DIR/$MARKER`" != ""; then
continue;
fi
rm $DIR/$PENDING
else
if test -f $DIR/$MARKER; then
if test "`$FND -name 'msg.*' -newer $DIR/$MARKER \
| head -1`" = ""; then
# there are no messages the user has not seen
continue
fi
fi
# We have at least one new message. If we are blocked by having
# sent a notification within the past week, make a pending message.
rm -f $DIR/$MARKER
touch $DIR/$MARKER
if test "`$FND -name $BLOCK -newer $DIR/$MARKER`" != ""; then
mv $DIR/$BLOCK $DIR/$PENDING
continue;
fi
fi
# browsers don't tolerate '/' or '@' in usernames and passwords in URLs
URL_UNAME="`expr "$UNAME@" : '\([^/@]*@$\)' || true`$BASE"
####################################################################
# Modify the following message to taste.
MAIL_SUBJECT="bulk mail notification for $UNAME"
if test "`basename /usr/sbin/sendmail`" = sendmail; then
HEADERS="Subject: $MAIL_SUBJECT
Precedence: bulk
"
CMD="/usr/sbin/sendmail $BOX"
else
HEADERS=
CMD="/usr/sbin/sendmail -s '$MAIL_SUBJECT' $BOX"
fi
eval $CMD <<EOF
$HEADERS
Recently logged bulk messages for $UNAME can be viewed at
$HTTPS://$URL_UNAME/list-log
Edit your whitelist at
$HTTPS://$URL_UNAME/edit-whiteclnt
if any of those are solicited bulk messages instead of spam
or to stop or redirect these messages.
The user name for both web pages is $UNAME
EOF
# no more of this mail for a week
NWEEK=`/usr/bin/perl -e 'use POSIX;
print strftime("%y%m%d%H%M", localtime(time()+7*24*60*60))'`
rm -f $DIR/$BLOCK
touch -t "$NWEEK" $DIR/$BLOCK
done
|
Java
|
UTF-8
| 208
| 1.765625
| 2
|
[] |
no_license
|
package org.bozan.traincontrol.device.mqtt;
import org.bozan.traincontrol.device.TrainControlDevice;
public class MqttDevice extends TrainControlDevice {
public MqttDevice(int id) {
super(id);
}
}
|
Python
|
UTF-8
| 404
| 2.765625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
__author__ = 'buzz'
__date__ = '2018/7/22 下午3:53'
from sklearn.mixture import GaussianMixture
def trainModel(data, clusterNum):
"""
使用混合高斯模型 + EM 算法对数据进行聚类
:param data:
:param clusterNum:
:return:
"""
model = GaussianMixture(n_components=clusterNum, covariance_type="full")
model.fit(data)
return model
|
Java
|
UTF-8
| 7,299
| 2.0625
| 2
|
[] |
no_license
|
/*
* Copyright (C) 2013 Luca Veltri - University of Parma - Italy
*
* This file is part of MjSip (http://www.mjsip.org)
*
* MjSip is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MjSip is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MjSip; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author(s):
* Luca Veltri (luca.veltri@unipr.it)
*/
package org.mjsip.sip.provider;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import org.mjsip.sip.address.NameAddress;
import org.mjsip.sip.address.SipURI;
import org.zoolu.net.IpAddress;
/** Connected SIP provider.
* It pre-establishes semi-permanent transport connections to the outbound proxy.
* <br>
* It establishes one connection per each connection-oriented transport protocol.
* <p>
* Methods getContactAddress() returns a contact address that refer to the
* pre-establishes semi-permanent transport connections (if any).
*/
public class ConnectedSipProvider extends SipProvider {
/** The semi-permanet connections, one for each connection-oriented porotocol (Hastable<String proto, SipTransportConnection transport_connection>) */
Hashtable connections=new Hashtable();
/** Creates a new ConnectedSipProvider.
* @param via_addr SIP local via address
* @param host_port SIP local port
* @param outbound_proxy the URI of the outbound proxy */
public ConnectedSipProvider(String via_addr, int host_port, SipURI outbound_proxy) throws IOException {
super(via_addr,host_port);
setOutboundProxy(outbound_proxy);
setForceRport(true);
connect();
}
/** Creates a new SipProvider.
* @param via_addr SIP local via address
* @param host_port SIP local port
* @param transport_protocols array of active transport protocols
* @param outbound_proxy the URI of the outbound proxy */
public ConnectedSipProvider(String via_addr, int host_port, String[] transport_protocols, SipURI outbound_proxy) throws IOException {
super(via_addr,host_port,transport_protocols);
setOutboundProxy(outbound_proxy);
setForceRport(true);
connect();
}
/** Creates a new ConnectedSipProvider.
* @param via_addr SIP local via address
* @param transport_protocols array of active transport protocols
* @param transport_ports array of transport ports used for the corresponding transport protocols
* @param outbound_proxy the URI of the outbound proxy */
public ConnectedSipProvider(String via_addr, int host_port, String[] transport_protocols, int[] transport_ports, SipURI outbound_proxy) throws IOException {
super(via_addr,host_port,transport_protocols,transport_ports);
setOutboundProxy(outbound_proxy);
setForceRport(true);
connect();
}
/** Creates a new ConnectedSipProvider.
* @param file file where all configuration parameters are read from
* @param outbound_proxy the URI of the outbound proxy */
public ConnectedSipProvider(String file, SipURI outbound_proxy) throws IOException {
super(file);
setOutboundProxy(outbound_proxy);
setForceRport(true);
connect();
}
/** Connects to the Oubound Proxy. */
private void connect() throws IOException {
if (sip_transports==null || outbound_proxy==null) return;
// else
IpAddress proxy_addr=IpAddress.getByName(outbound_proxy.getHost());
int proxy_port=outbound_proxy.getPort();
if (proxy_port<=0) proxy_port=5060;
String proxy_proto=(outbound_proxy.hasTransport())? outbound_proxy.getTransport() : null;
for (Enumeration i=sip_transports.elements(); i.hasMoreElements(); ) {
try {
SipTransportCO sip_transport=(SipTransportCO)i.nextElement();
sip_transport.setForceSentBy(true);
String proto=sip_transport.getProtocol();
if (proxy_proto==null || proxy_proto.equals(proto)) {
// establish connection
SipTransportConnection conn=sip_transport.addConnection(proxy_addr,(isSecureTransport(proto))? proxy_port+1 : proxy_port);
if (conn!=null) connections.put(sip_transport.getProtocol(),conn);
}
}
catch (Exception e) {}
}
}
/** Adds a semi-permanent transport connection.
* Pre-establishes a transport connection to a remote socket address.
* @param proto transport protocol
* @param remote_addr remote address
* @param remote_port remote port
* @return the transport connection (if succeded in finding the corresponding SIP transport service), or null (if failed) */
/*public SipTransportConnection addTransportConnection(String proto, String remote_addr, int remote_port) throws IOException {
SipTransportCO sip_transport=null;
sip_transport=(SipTransportCO)sip_transports.get(proto.toLowerCase());
if (sip_transport==null) throw new IOException("Protocol '"+proto+"' is not supported by this SIP provider");
// else
return sip_transport.addConnection(new IpAddress(remote_addr),remote_port);
}*/
/** Adds a pre-established transport connection.
* @param conn the pre-established trasport connection */
/*public void addTransportConnection(SipTransportConnection conn) throws IOException {
SipTransportCO sip_transport=null;
String proto=conn.getProtocol().toLowerCase();
sip_transport=(SipTransportCO)sip_transports.get(proto);
if (sip_transport==null) throw new IOException("Protocol '"+proto+"' is not supported by this SIP provider");
// else
sip_transport.addConnection(conn);
}*/
/** Removes a semi-permanent transport connection. */
/*public void removeTransportConnection(String proto, String remote_addr, int remote_port) throws IOException {
SipTransportCO sip_transport=(SipTransportCO)sip_transports.get(proto.toLowerCase());
if (sip_transport==null) throw new IOException("Protocol '"+proto+"' is not supported by this SIP provider");
// else
sip_transport.removeConnection(new ConnectionId(proto,new IpAddress(remote_addr),remote_port));
}*/
/** Gets a valid SIP or SIPS contact address.
* @param secure whether returning a SIPS or SIP URI (true=SIPS, false=SIP)
* @param user local user's name
* @return a SIP or SIPS contact URI for this SIP provider */
public NameAddress getContactAddress(String user, boolean secure) {
for (Enumeration i=connections.elements(); i.hasMoreElements(); ) {
SipTransportConnection conn=(SipTransportConnection)i.nextElement();
String proto=conn.getProtocol();
if (secure==isSecureTransport(proto)) {
String local_addr=conn.getLocalAddress().toString();
int local_port=conn.getLocalPort();
if (secure) local_port--;
SipURI contact_uri=new SipURI(user,local_addr,local_port);
if (secure) contact_uri.setSecure(true);
else if (!proto.equalsIgnoreCase(SipProvider.PROTO_UDP)) contact_uri.addTransport(proto);
return new NameAddress(contact_uri);
}
}
// else
return super.getContactAddress(user,secure);
}
}
|
Markdown
|
UTF-8
| 404
| 2.65625
| 3
|
[] |
no_license
|
# Style #21
## Constraints:
* Every single procedure and function checks the sanity of its arguments and refuses to continue when the arguments are unreasonable
* All code blocks check for all possible errors, possibly print out context-specific messages when errors occur, and pass the errors up the function call chain
## Possible names:
* Tantrum
* Design by contract
* Mental breakdown
|
Java
|
UTF-8
| 2,404
| 2.875
| 3
|
[] |
no_license
|
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Teams{
public Map <Integer, String> eastMatchups, westMatchups, midwestMatchups, southMatchups;
private String bracketSite = "https://www.ncaa.com/interactive-bracket/basketball-men/d1";
public static ArrayList<String> ncaaNames;
private static Map<Integer, String> getRegionMatchups(Elements gameArea){
Map<Integer, String> teamList = new TreeMap<Integer, String>();
for(int i = 0; i < 8; i ++) {
Element game = gameArea.get(i);
Elements topCell = game.select("div.team-info.info-top");
Elements bottomCell = game.select("div.team-info.info-bottom");
String topCellName = topCell.select("div.team-name").text();
int topCellSeed = Integer.parseInt(topCell.select("div.team-seed").text());
ncaaNames.add(topCellName);
String bottomCellName = bottomCell.select("div.team-name").text();
int bottomCellSeed = Integer.parseInt(bottomCell.select("div.team-seed").text());
ncaaNames.add(bottomCellName);
teamList.put(topCellSeed, topCellName);
teamList.put(bottomCellSeed, bottomCellName);
}
return teamList;
}
public Teams() {
ncaaNames = new ArrayList<String>();
Document doc;
try {
doc = Jsoup.connect(bracketSite).get();
Element eastRegion = doc.getElementById("bracket-top-right");
Element southRegion = doc.getElementById("bracket-top");
Element westRegion = doc.getElementById("bracket-bottom");
Element midwestRegion = doc.getElementById("bracket-bottom-right");
Elements eastGames = eastRegion.select("div.game-cell");
Elements southGames = southRegion.select("div.game-cell");
Elements westGames = westRegion.select("div.game-cell");
Elements midwestGames = midwestRegion.select("div.game-cell");
eastMatchups = getRegionMatchups(eastGames);
southMatchups = getRegionMatchups(southGames);
westMatchups = getRegionMatchups(westGames);
midwestMatchups = getRegionMatchups(midwestGames);
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
e.printStackTrace();
}
Collections.sort(ncaaNames);
System.out.println("Created round matchups for each region.");
}
}
|
Java
|
UTF-8
| 3,943
| 2.03125
| 2
|
[] |
no_license
|
package com.keji50.zhucexiaadmin.web.controller;
import java.sql.Timestamp;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.keji50.zhucexiaadmin.dao.po.CustomerPo;
import com.keji50.zhucexiaadmin.dao.po.SysUserPo;
import com.keji50.zhucexiaadmin.service.CustomerService;
import com.keji50.zhucexiaadmin.web.utils.PageUtils;
import com.keji50.zhucexiaadmin.web.utils.WebUtils;
@Controller
@RequestMapping(value = "/customer")
public class CustomerController {
@Resource(name = "customerService")
private CustomerService customerService;
@RequestMapping(value = "/index")
public String index(HttpServletRequest request) {
return "customer/list";
}
@RequestMapping(value = "/add")
public String add(HttpServletRequest request) {
return "customer/add";
}
@RequestMapping(value = "/getCustomerList", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> listByCondition(HttpServletRequest request,HttpServletResponse response) {
String requestJson = WebUtils.getRequestPayload(request);
Map<String, Object> conditions = JSONObject.parseObject(requestJson);
Page<CustomerPo> page = customerService.getCustomerByConditions(conditions);
//System.out.println("执行查询"+page.s);
/* for (CustomerPo customerPo : page) {
System.out.println("修改时间"+customerPo.getUpdateTime());
}*/
return PageUtils.pageToMap(page);
}
@RequestMapping(value = "/deletecustomer", method = RequestMethod.POST)
@ResponseBody
public JSONObject deletecustomer(HttpServletRequest request) {
int id=Integer.valueOf(request.getParameter("sno"));
int result=customerService.deletecustomer(id);
JSONObject json;
if(result>0){
json=JSONObject.parseObject("{'message':'删除成功'}");
}else{
json=JSONObject.parseObject("{'message':'删除失败'}");
}
return json;
}
@RequestMapping(value = "/newcus", method = RequestMethod.POST)
@ResponseBody
public int newcus(HttpServletRequest request,HttpServletResponse response,CustomerPo cust) {
Boolean flag = customerService.checkCustomer(cust);
int i = 0;
if(flag){
SysUserPo sysUserPo = (SysUserPo)request.getSession().getAttribute("sysUserpo");
String userName = sysUserPo.getUsername();
cust.setCreateBy(userName);
Timestamp time = new Timestamp(System.currentTimeMillis());
cust.setCreateTime(time);
int result=customerService.addcustomer(cust);
if(result>0){
i=0;
}else{
i=1;
}
}else{
i=2;
}
return i;
}
@RequestMapping(value = "/getcustomer", method = RequestMethod.POST)
public String getcustomer(HttpServletRequest request) {
int id=Integer.valueOf(request.getParameter("id"));
CustomerPo cus=customerService.getCustomer(id);
request.setAttribute("customer", cus);
return "customer/update";
}
@RequestMapping(value = "/updatecustomer")
@ResponseBody
public int updatecustomer(HttpServletRequest request,CustomerPo cust) {
Boolean flag = customerService.checkCustomer(cust);
int i = 0;
if(flag){
SysUserPo sysUserPo = (SysUserPo)request.getSession().getAttribute("sysUserPo");
String userName = sysUserPo.getUsername();
cust.setUpdateBy(userName);
Timestamp time = new Timestamp(System.currentTimeMillis());
cust.setUpdateTime(time);
int result=customerService.updatecustomer(cust);
if(result>0){
i=0;
}else{
i=1;
}
}else{
i=2;
}
return i;
}
}
|
TypeScript
|
UTF-8
| 408
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
// https://github.com/tim-kos/node-retry/tree/b316bfc196a89504fa348bcb97b20eb55509a295#retrytimeoutsoptions
export const calculateDelay = (
attempt: number,
minTimeout: number,
maxTimeout: number,
factor: number,
randomize: boolean,
): number => {
const random = randomize ? Math.random() + 1 : 1
return Math.min(
Math.round(random * minTimeout * factor ** attempt),
maxTimeout,
)
}
|
JavaScript
|
UTF-8
| 776
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
// avoiding navigation bar coverage when anchor locating
// function locateAt(x) {
// x = document.getElementById(e);
// var y = x.offsetTop;
// while (x=x.offsetParent) {
// y += x.offsetTop;
// }
// y -= 70;
// window.scrollTo(0,y);
// }
// scroll smoothly when anchor locating
var $root = $('html, body');
// excluding carousel arrows
$('a[href^="#"]:not(a[href="#my-slider"])').click(function () {
$root.animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
return false;
});
// for mobile device: show/hide web content when menu hamburger clicked
function showHide(checked) {
if (checked == true) {
$("#to-be-hidden").fadeOut();
}
else {
$("#to-be-hidden").fadeIn();
}
}
|
C++
|
UTF-8
| 1,783
| 3.4375
| 3
|
[] |
no_license
|
#include <iostream>
#include <queue>
#include <string>
#include <vector>
#include <map>
using namespace std;
struct Point{
int x;
int y;
};
bool isLegal(int x,int y){
if(x<=7&&x>=0&&y<=7&&y>=0){
return true;
}
return false;
}
int main(void){
int count;
string begin,end;
bool visit[8][8];
int dist[8][8];
int begin_1,begin_2;
int end_1,end_2;
int d[8][2]={{2,1},{2,-1},{1,2},{1,-2},{-1,2},{-1,-2},{-2,1},{-2,-1}};
cin>>count;
while(count-->0){
queue<Point> q;
for(int i=0;i<8;++i){
for(int j=0;j<8;++j){
visit[i][j]=false;
dist[i][j]=-1;
}
}
cin>>begin>>end;
begin_1=begin[0]-'a';
begin_2=begin[1]-'1';
end_1=end[0]-'a';
end_2=end[1]-'1';
Point p;
int temp_x,temp_y;
p.x=begin_1;
p.y=begin_2;
q.push(p);
visit[begin_1][begin_2]=true;
dist[begin_1][begin_2]=0;
while(!q.empty()){
p=q.front();
q.pop();
temp_x=p.x;
temp_y=p.y;
if(temp_x==end_1&&temp_y==end_2){
break;
}
for(int i=0;i<8;++i){
int next_x=temp_x+d[i][0];
int next_y=temp_y+d[i][1];
if(isLegal(next_x,next_y)&&visit[next_x][next_y]==false){
dist[next_x][next_y]=dist[temp_x][temp_y]+1;
visit[next_x][next_y]=true;
p.x=next_x;
p.y=next_y;
q.push(p);
}
}
}
cout<<"To get from "<<begin<<" to "<<end<<" takes "<<dist[end_1][end_2]<<" knight moves."<<endl;
}
return 0;
}
|
JavaScript
|
UTF-8
| 6,120
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
function dSearchLocShow(tHeaderValue){
if(tHeaderValue == '함께출퇴근해요'){
var html = "";
html += '<label>도착 장소</label><br>';
html += ' <input type="text" id="searchLoc2" name="dAddress" value="" class="form-control" /><input type="button" id="searchBtn2" onclick="PostCode2()" value="주소 검색" class="btn btn-primary"/>';
html += '<div id="map2"></div>';
html += '<input type="hidden" id="dLocX" name="dLocX" value="" />';
html += '<input type="hidden" id="dLocY" name="dLocY" value="" />';
$('#dSearchLoc').html(html);
$('#map2').css('display', 'none');
}else{
var html = "";
$('#dSearchLoc').html(html);
}
}
function loadFile(event){
var uploadWrap = event.target.parentNode;
var reader = new FileReader();
reader.onload = function(event) {
var newImg = document.createElement("img");
uploadWrap.appendChild(newImg);
newImg.setAttribute("src", event.target.result);
newImg.setAttribute("class", "image_preview");
};
reader.readAsDataURL(event.target.files[0]);
console.log(event.target.id);
//기존 파일 명, 사진, 값 제거
if(event.target.id == 'uploadFile1'){
$('#tPicHidden1').remove();
$('#befoFile1').remove();
$('#tPic1').remove();
}else if(event.target.id == 'uploadFile2'){
$('#tPicHidden2').remove();
$('#befoFile2').remove();
$('#tPic2').remove();
}
}
function PostCode() {
/*우편번호 찾기 */
const tLocX = document.getElementById('tLocX');
const tLocY = document.getElementById('tLocY');
var mapContainer = document.getElementById('map'), // 지도를 표시할 div
mapOption = {
center: new daum.maps.LatLng(37.537187, 127.005476), // 지도의 중심좌표
level: 5 // 지도의 확대 레벨
};
//지도를 미리 생성
var map = new daum.maps.Map(mapContainer, mapOption);
//주소-좌표 변환 객체를 생성
var geocoder = new daum.maps.services.Geocoder();
//마커를 미리 생성
var marker = new daum.maps.Marker({
position: new daum.maps.LatLng(37.537187, 127.005476),
map: map
});
new daum.Postcode({
oncomplete: function(data) {
var addr = data.address; // 최종 주소 변수
console.log(addr);
// 주소 정보를 해당 필드에 넣는다.
document.getElementById("searchLoc1").value = addr;
// 주소로 상세 정보를 검색
console.log(geocoder);
geocoder.addressSearch(data.address, function(results, status) {
// 정상적으로 검색이 완료됐으면
if (status === daum.maps.services.Status.OK) {
var result = results[0]; //첫번째 결과의 값을 활용
console.log(result);
// 해당 주소에 대한 좌표를 받아서
var coords = new daum.maps.LatLng(result.y, result.x);
console.log(result.y);
// 태그에 좌표값을 넣어준다.
tLocX.setAttribute("value",result.y);
tLocY.setAttribute("value",result.x);
// 지도를 보여준다.
mapContainer.style.display = "block";
map.relayout();
// 지도 중심을 변경한다.
map.setCenter(coords);
// 마커를 결과값으로 받은 위치로 옮긴다.
marker.setPosition(coords)
}
});
}
}).open();
}
function PostCode2() {
var dLocX = document.getElementById('dLocX');
var dLocY = document.getElementById('dLocY');
var mapContainer2 = document.getElementById('map2'), // 지도를 표시할 div
mapOption = {
center: new daum.maps.LatLng(37.537187, 127.005476), // 지도의 중심좌표
level: 5 // 지도의 확대 레벨
};
//지도를 미리 생성
var map2 = new daum.maps.Map(mapContainer2, mapOption);
//주소-좌표 변환 객체를 생성
var geocoder = new daum.maps.services.Geocoder();
//마커를 미리 생성
var marker = new daum.maps.Marker({
position: new daum.maps.LatLng(37.537187, 127.005476),
map: map2
});
new daum.Postcode({
oncomplete: function(data) {
var addr = data.address; // 최종 주소 변수
console.log(addr);
// 주소 정보를 해당 필드에 넣는다.
document.getElementById("searchLoc2").value = addr;
// 주소로 상세 정보를 검색
console.log(geocoder);
geocoder.addressSearch(data.address, function(results, status) {
// 정상적으로 검색이 완료됐으면
if (status === daum.maps.services.Status.OK) {
var result = results[0]; //첫번째 결과의 값을 활용
console.log(result);
// 해당 주소에 대한 좌표를 받아서
var coords = new daum.maps.LatLng(result.y, result.x);
console.log(result.y);
// 태그에 좌표값을 넣어준다.
dLocX.setAttribute("value",result.y);
dLocY.setAttribute("value",result.x);
// 지도를 보여준다.
mapContainer2.style.display = "block";
map2.relayout();
// 지도 중심을 변경한다.
map2.setCenter(coords);
// 마커를 결과값으로 받은 위치로 옮긴다.
marker.setPosition(coords)
}
});
}
}).open();
}
|
Java
|
UTF-8
| 79
| 2.390625
| 2
|
[] |
no_license
|
package scheduler;
public interface Task {
abstract void doWork(int time);
}
|
JavaScript
|
UTF-8
| 22,999
| 2.921875
| 3
|
[] |
no_license
|
/*
onload = function()
{
oesconderijo = document.getElementById('esconderijo');
ordenadores = oesconderijo.getElementsByTagName('div');
inicializaOrdenadores(ordenadores);
}
function inicializaOrdenadores(ordenadores)
{
for( i=0 ; i<ordenadores.length ; i++ )
{
//alert(ordenadores[i].name);
if( ordenadores[i].className == 'conteudo' )
{
ordenadores[i].onclick = function()
{
this.parentNode.setAttribute( 'conteudo_id' , this.getAttribute('conteudo_id') );
ordenador = document.getElementById( 'ordenador' + this.getAttribute('menu_id') );
conteudos = ordenador.getElementsByTagName( 'div' );
ordenador.setAttribute('conteudo','');
for( i=0 ; i<conteudos.length ; i++ )
{
if( conteudos[i].getAttribute('conteudo_id') == this.getAttribute('conteudo_id') )
{
ordenador.setAttribute('conteudo_id',conteudos[i].getAttribute('conteudo_id'));
conteudos[i].style.backgroundColor = '#FFFFFF';
}
else
{
conteudos[i].style.backgroundColor = '#C6CBD0';
}
}
}
}
else if( ordenadores[i].name == 'ordenador_menu' )
{
ordenadores[i].onclick = function()
{
this.parentNode.setAttribute( 'menu_id' , this.getAttribute('menu_id') );
ordenador = this.parentNode;
conteudos = ordenador.getElementsByTagName( 'div' );
for( i=0 ; i<conteudos.length ; i++ )
{
if(conteudos[i].name != 'ordenador_menu') continue;
if( conteudos[i].getAttribute('menu_id') == this.getAttribute('menu_id') )
{
ordenador.setAttribute('menu_id',conteudos[i].getAttribute('menu_id'));
conteudos[i].style.backgroundColor = '#FFFFFF';
}
else
{
conteudos[i].style.backgroundColor = '#C6CBD0';
}
}
}
//break;
}
imgs = ordenadores[i].getElementsByTagName('img');
for( j=0 ; j<imgs.length ; j++ )
{
//alert(imgs[j].name);
if(imgs[j].name == 'sobe_menu')
{
imgs[j].onmouseover = function()
{
this.src = 'images/ord_cima_over.jpg';
}
imgs[j].onmouseout = function()
{
this.src = 'images/ord_cima.jpg';
}
imgs[j].onclick = function()
{
sobe_menu(this);
}
imgs[j].ondblclick = function()
{
this.click();
}
}
if(imgs[j].name == 'desce_menu')
{
imgs[j].onmouseover = function()
{
this.src = 'images/ord_baixo_over.jpg';
}
imgs[j].onmouseout = function()
{
this.src = 'images/ord_baixo.jpg';
}
imgs[j].onclick = function()
{
desce_menu(this);
}
imgs[j].ondblclick = function()
{
this.click();
}
}
if(imgs[j].name == 'sobe')
{
imgs[j].onmouseover = function()
{
this.src = 'images/ord_cima_over.jpg';
}
imgs[j].onmouseout = function()
{
this.src = 'images/ord_cima.jpg';
}
imgs[j].onclick = function()
{
sobe(this);
}
imgs[j].ondblclick = function()
{
this.click();
}
}
if(imgs[j].name == 'desce')
{
imgs[j].onmouseover = function()
{
this.src = 'images/ord_baixo_over.jpg';
}
imgs[j].onmouseout = function()
{
this.src = 'images/ord_baixo.jpg';
}
imgs[j].onclick = function()
{
desce(this);
}
imgs[j].ondblclick = function()
{
this.click();
}
}
if(imgs[j].name == 'editar')
{
imgs[j].onmouseover = function()
{
this.src = 'images/editar_over.jpg';
}
imgs[j].onmouseout = function()
{
this.src = 'images/editar.jpg';
}
imgs[j].onclick = function mostra_esconde_ordenador()
{
//location = php_self + '?tela=' + tela + '&id=' + this.parentNode.getAttribute('conteudo_id');
if(this.getAttribute('mostrando'))
{
esconde_ordenador(this);
}
else
{
mostra_ordenador(this);
}
}
imgs[j].ondblclick = function()
{
this.click();
}
}
}
}
}
function showContextIdioma( obj_clicado )
{
document.detachEvent('onclick',hideContextIdioma);
document.detachEvent('oncontextmenu',hideContextIdioma);
contextmenu = document.getElementById('contextMenuIdioma');
img = obj_clicado.getElementsByTagName('img')[0];
menu_editar = document.getElementById('editar_idioma');
novo_idioma = obj_clicado.getElementsByTagName('input')[3];
if( novo_idioma.name == 'novo[idioma][]' )
{
novo_idioma.onclick = null;
novo_idioma.className = 'disabled';
}
else
{
novo_idioma.onclick = function(){ editaMenu(this) };
novo_idioma.className = '';
}
obj_clicado.appendChild(contextmenu);
contextmenu.style.left = event.x + document.body.scrollLeft;
contextmenu.style.top = event.y + document.body.scrollTop;
var timer = setTimeout("document.attachEvent('oncontextmenu',hideContextIdioma);",10);
var timer = setTimeout("document.attachEvent('onclick',hideContextIdioma);",10);
return false;
}
function hideContextIdioma()
{
contextmenu = document.getElementById('contextMenuIdioma');
contextmenuconteiner = document.getElementById('contextMenuConteiner');
contextmenuconteiner.appendChild(contextmenu);
document.detachEvent('oncontextmenu',hideContextIdioma);
document.detachEvent('onclick',hideContextIdioma);
return true;
}
function showContextMenuHome( obj_clicado )
{
document.detachEvent('onclick',hideContextMenuHome);
document.detachEvent('oncontextmenu',hideContextMenuHome);
contextmenu = document.getElementById('contextMenuMenuHome');
img = obj_clicado.getElementsByTagName('img')[0];
menu_habilitar = document.getElementById('habilitar_menu');
menu_editar = document.getElementById('editar_menu');
novo_menu = obj_clicado.getElementsByTagName('input')[3];
if(img.style.display=='none')
{
menu_habilitar.innerHTML = "<img src='images/estrutura/habilitar.jpg' /> Habilitar Sub-menu";
if( novo_menu.name == 'novo[menu][]' )
{
menu_editar.onclick = null;
menu_editar.className = 'disabled';
}
else
{
menu_editar.onclick = function(){ editaMenu(this) };
menu_editar.className = '';
}
}
else
{
menu_habilitar.innerHTML = "<img src='images/estrutura/desabilitar.jpg' /> Desabilitar Sub-menu";
menu_editar.onclick = null;
menu_editar.className = 'disabled';
}
obj_clicado.appendChild(contextmenu);
contextmenu.style.left = event.x + document.body.scrollLeft;
contextmenu.style.top = event.y + document.body.scrollTop;
var timer = setTimeout("document.attachEvent('oncontextmenu',hideContextMenuHome);",10);
var timer = setTimeout("document.attachEvent('onclick',hideContextMenuHome);",10);
return false;
}
function showContextMenu( obj_clicado )
{
document.detachEvent('onclick',hideContextMenu);
document.detachEvent('oncontextmenu',hideContextMenu);
contextmenu = document.getElementById('contextMenuMenu');
img = obj_clicado.getElementsByTagName('img')[0];
menu_habilitar = document.getElementById('habilitar_menu');
menu_editar = document.getElementById('editar_menu');
novo_menu = obj_clicado.getElementsByTagName('input')[3];
if(img.style.display=='none')
{
menu_habilitar.innerHTML = "<img src='images/estrutura/habilitar.jpg' /> Habilitar Sub-menu";
if( novo_menu.name == 'novo[menu][]' )
{
menu_editar.onclick = null;
menu_editar.className = 'disabled';
}
else
{
menu_editar.onclick = function(){ editaMenu(this) };
menu_editar.className = '';
}
}
else
{
menu_habilitar.innerHTML = "<img src='images/estrutura/desabilitar.jpg' /> Desabilitar Sub-menu";
menu_editar.onclick = null;
menu_editar.className = 'disabled';
}
obj_clicado.appendChild(contextmenu);
contextmenu.style.left = event.x + document.body.scrollLeft;
contextmenu.style.top = event.y + document.body.scrollTop;
var timer = setTimeout("document.attachEvent('oncontextmenu',hideContextMenu);",10);
var timer = setTimeout("document.attachEvent('onclick',hideContextMenu);",10);
return false;
}
function hideContextMenu()
{
contextmenu = document.getElementById('contextMenuMenu');
contextmenuconteiner = document.getElementById('contextMenuConteiner');
contextmenuconteiner.appendChild(contextmenu);
document.detachEvent('oncontextmenu',hideContextMenu);
document.detachEvent('onclick',hideContextMenu);
return true;
}
function hideContextMenuHome()
{
contextmenu = document.getElementById('contextMenuMenuHome');
contextmenuconteiner = document.getElementById('contextMenuConteiner');
contextmenuconteiner.appendChild(contextmenu);
document.detachEvent('oncontextmenu',hideContextMenu);
document.detachEvent('onclick',hideContextMenu);
return true;
}
function showContextMenuConteudo( obj_clicado )
{
document.detachEvent('onclick',hideContextMenuConteudo);
document.detachEvent('oncontextmenu',hideContextMenuConteudo);
contextmenu = document.getElementById('contextMenuConteudo');
document.body.appendChild(contextmenu);
contextmenu.setAttribute( 'conteudo_id' , obj_clicado.getAttribute( 'conteudo_id' ) );
td = obj_clicado.parentNode;
contextmenu.setAttribute( 'menu_id' , td.getAttribute( 'menu_id' ) );
conteudo_editar = document.getElementById('editar_conteudo');
novo_conteudo = obj_clicado.getElementsByTagName('input')[3];
if( novo_conteudo.name == 'novo[conteudo][]' )
{
conteudo_editar.onclick = null;
conteudo_editar.className = 'disabled';
}
else
{
conteudo_editar.onclick = function(){ editaConteudo(this) };
conteudo_editar.className = '';
}
contextmenu.style.left = event.x + document.body.scrollLeft;
contextmenu.style.top = event.y + document.body.scrollTop;
var timer = setTimeout("document.attachEvent('oncontextmenu',hideContextMenuConteudo);",10);
var timer = setTimeout("document.attachEvent('onclick',hideContextMenuConteudo);",10);
return false;
}
function hideContextMenuConteudo()
{
contextmenu = document.getElementById('contextMenuConteudo');
contextmenuconteiner = document.getElementById('contextMenuConteiner');
contextmenuconteiner.appendChild(contextmenu);
document.detachEvent('oncontextmenu',hideContextMenuConteudo);
document.detachEvent('onclick',hideContextMenuConteudo);
return true;
}
function editaMenu(chamador)
{
div = chamador.parentNode;
td = div.parentNode;
tr = td.parentNode;
tbody = tr.parentNode;
table = tbody.parentNode;
location = php_self + '?tela=estrutura_menus&id=' + table.parentNode.getAttribute('menu_id') ;
}
function editaConteudo(chamador)
{
div = chamador.parentNode;
location = php_self + '?tela=estrutura_artigos&id=' + div.getAttribute('conteudo_id') ;
}
function editaIdioma(chamador)
{
div = chamador.parentNode;
td = div.parentNode;
location = php_self + '?tela=edicoes&id=' + td.getAttribute('edicao_id') ;
/*
*/
}
function sobe_menu(setinha)
{
ordenador = document.getElementById( 'ordena_edicao' + setinha.getAttribute('edicao_id') );
selecionado = ordenador.getAttribute('menu_id');
conteudos = ordenador.getElementsByTagName( 'div' );
if(selecionado) for( i=0 ; i<conteudos.length ; i++ )
{
if(conteudos[i].name != 'ordenador_menu') continue;
if( conteudos[i].getAttribute('menu_id') == selecionado )
{
try
{
if(conteudos[i].previousSibling.name=='ordenador_menu')
{
conteudos[i].swapNode(conteudos[i].previousSibling);
}
}catch(e){}
}
}
}
function desce_menu(setinha)
{
ordenador = document.getElementById( 'ordena_edicao' + setinha.getAttribute('edicao_id') );
selecionado = ordenador.getAttribute('menu_id');
conteudos = ordenador.getElementsByTagName( 'div' );
if(selecionado) for( i=conteudos.length-1 ; i>=0 ; i-- )
{
if(conteudos[i].name != 'ordenador_menu') continue;
if( conteudos[i].getAttribute('menu_id') == selecionado )
{
try
{
conteudos[i].swapNode(conteudos[i].nextSibling);
}catch(e){}
}
}
}
function sobe(setinha)
{
ordenador = document.getElementById( 'ordenador' + setinha.getAttribute('menu_id') );
selecionado = ordenador.getAttribute('conteudo_id');
conteudos = ordenador.getElementsByTagName( 'div' );
for( i=0 ; i<conteudos.length ; i++ )
{
if( conteudos[i].getAttribute('conteudo_id') == selecionado )
{
try
{
conteudos[i].swapNode(conteudos[i].previousSibling);
}catch(e){}
}
}
}
function desce(setinha)
{
ordenador = document.getElementById( 'ordenador' + setinha.getAttribute('menu_id') );
selecionado = ordenador.getAttribute('conteudo_id');
conteudos = ordenador.getElementsByTagName( 'div' );
for( i=conteudos.length-1 ; i>=0 ; i-- )
{
if( conteudos[i].getAttribute('conteudo_id') == selecionado )
{
try
{
conteudos[i].swapNode(conteudos[i].nextSibling);
}catch(e){}
}
}
}
var theMenuId = 0;
function esconde_ordenador_id()
{
imgs = document.getElementsByName('editar');
for( i=0 ; i<imgs.length ; i++ )
{
if( imgs[i].getAttribute('menu_id')==theMenuId )
{
esconde_ordenador(imgs[i]);
break;
}
}
}
function mostra_ordenador(elemento)
{
esconde_ordenador_id();
document.detachEvent('oncontextmenu',esconde_ordenador_id);
document.detachEvent('onclick',esconde_ordenador_id);
theMenuId = elemento.getAttribute('menu_id');
ordenador = document.getElementById( 'ordenador' + elemento.getAttribute('menu_id') );
ordenador.onclick = function(){
document.detachEvent('oncontextmenu',esconde_ordenador_id);
document.detachEvent('onclick',esconde_ordenador_id);
var timer = setTimeout("document.attachEvent('oncontextmenu',esconde_ordenador_id);",10);
var timer = setTimeout("document.attachEvent('onclick',esconde_ordenador_id);",10);
} ;
ordenador.oncontextmenu = function(){
document.detachEvent('oncontextmenu',esconde_ordenador_id);
document.detachEvent('onclick',esconde_ordenador_id);
var timer = setTimeout("document.attachEvent('oncontextmenu',esconde_ordenador_id);",10);
var timer = setTimeout("document.attachEvent('onclick',esconde_ordenador_id);",10);
} ;
conteudos = ordenador.getElementsByTagName( 'div' );
ordenador.setAttribute('conteudo','');
for( i=0 ; i<conteudos.length ; i++ )
{
conteudos[i].style.backgroundColor = '#C6CBD0';
}
ordenador.style.display = 'block';
elemento.setAttribute('mostrando',1);
var timer = setTimeout("document.attachEvent('oncontextmenu',esconde_ordenador_id);",10);
var timer = setTimeout("document.attachEvent('onclick',esconde_ordenador_id);",10);
}
function esconde_ordenador(elemento)
{
ordenador = document.getElementById( 'ordenador' + elemento.getAttribute('menu_id') );
ordenador.style.display = 'none';
elemento.setAttribute('mostrando',0);
}
function highlight(elemento)
{
elemento.src = 'images/ordenador_over.jpg';
}
function unhighlight(elemento)
{
elemento.src = 'images/ordenador.jpg';
}
function incrementaMenu(semente)
{
menu_id++;
semente.setAttribute('id','ordenador_menu' + menu_id );
semente.setAttribute('menu_id',menu_id);
semente.getElementsByTagName('div')[0].setAttribute('id', 'ordenador' + menu_id );
//alert(semente.getElementsByTagName('div')[0].getAttribute('id'));
images = semente.getElementsByTagName('img');
images[0].setAttribute('menu_id',menu_id);
images[1].setAttribute('menu_id',menu_id);
images[2].setAttribute('menu_id',menu_id);
inputs = semente.getElementsByTagName('INPUT');
inputs[0].outerHTML = '<input class=sutil name=menu[' + menu_id + ']>';
inputs[1].outerHTML = '<input type=hidden name=menu_antigo[' + menu_id + ']>';
inputs[2].value = menu_id; // <input type="hidden" name="ordena[menu][<?=$row_idioma['edicao_id']?>][]" value="<?=$row_menu['menu_id']?>" />
inputs[3].value = menu_id; // <input type="hidden" name="novo[menu][]" value="<?=$row_menu['menu_id']?>" />
inputs[4].outerHTML = '<input type="hidden" name="abredireto[' + menu_id + ']" value="1" />';
inputs[5].outerHTML = '<input type="hidden" name="tipo[' + menu_id + ']" value="artigos" />';
//alert(semente.outerHTML);
}
function habilitaSubMenu(span)
{
div = span.parentNode;
td = div.parentNode;
tr = td.parentNode;
tbody = tr.parentNode;
table = tbody.parentNode;
otradiv = table.parentNode;
img = otradiv.getElementsByTagName('img')[0];
inputs = otradiv.getElementsByTagName('INPUT');
if(img.style.display == 'none')
{
img.style.display = 'block';
inputs[4].value = '';
}
else
{
img.style.display = 'none';
inputs[4].value = '1';
}
//alert(inputs[4].outerHTML);
}
function adicionaMenu(span)
{
div = span.parentNode;
td = div.parentNode;
tr = td.parentNode;
tbody = tr.parentNode;
table = tbody.parentNode;
otradiv = table.parentNode;
seila = otradiv.parentNode;
semente_menu = document.getElementById('ordenador_menu'+menu_id);
replica_menu = semente_menu.cloneNode(true);
//replica.getElementsByTagName('img')[2].onclick = null;
replica_menu.getElementsByTagName('img')[0].style.display = 'none';
replica_menu.getElementsByTagName('input')[2].outerHTML = '<input type=hidden value=' + menu_id
+ ' name=ordena[menu][' + seila.getAttribute('edicao_id') + '][]>';
// incio - adiciona o primeiro contedo do sub_menu
semente_conteudo = document.getElementById('conteudo'+conteudo_id);
replica_conteudo = semente_conteudo.cloneNode(true);
recebe_conteudo = replica_menu.getElementsByTagName('div')[0].getElementsByTagName('td')[1];
recebe_conteudo.setAttribute( 'menu_id' , menu_id );
replica_conteudo.setAttribute( 'menu_id' , menu_id );
replica_conteudo.getElementsByTagName('input')[2].outerHTML = '<input type=hidden value=' + conteudo_id
+ ' name=ordena[conteudo][' + menu_id + '][]>';
recebe_conteudo.appendChild(replica_conteudo);
//depura(replica_conteudo);
conteiner = new Array();
conteiner[0] = replica_conteudo;
inicializaOrdenadores(conteiner);
incrementaConteudo(semente_conteudo);
// fim - adiciona o primeiro contedo do sub_menu
try
{
seila.insertBefore(replica_menu, otradiv.nextSibling);
}
catch(e)
{
seila.appendChild(replica_menu);
}
conteiner = new Array();
conteiner[0] = replica_menu;
inicializaOrdenadores(conteiner);
replica_menu.click();
replica_menu.getElementsByTagName('input')[0].focus();
incrementaMenu(semente_menu);
//alert(replica_menu.outerHTML);
}
function varre(obj)
{
resp = '';
for( i in obj )
{
resp += '' + i + ' = ' + obj[i] + '\n';
}
return resp;
}
function depura(obj)
{
janelinha = window.open('','','width=400,height=300,scrollbars=yes');
janelinha.document.write( '<pre>' + varre(obj) + '/<pre>' );
janelinha.focus();
}
function removeMenu(span)
{
div = span.parentNode;
td = div.parentNode;
tr = td.parentNode;
tbody = tr.parentNode;
table = tbody.parentNode;
otradiv = table.parentNode;
seila = otradiv.parentNode;
inputs = otradiv.getElementsByTagName('INPUT');
inputs[0].outerHTML = '<input type=hidden name=remove[menu][] value=' + otradiv.getAttribute('menu_id') + '>';
semente = document.getElementById('ordenador_menu'+menu_id);
semente.parentNode.appendChild(inputs[0]);
hideContextMenu(); // tira o menu de contexto antes de remover
if( otradiv.nextSibling || otradiv.previousSibling )
{
seila.removeChild(otradiv);
}
}
function incrementaConteudo(semente)
{
conteudo_id++;
semente.setAttribute('id','conteudo' + conteudo_id );
semente.setAttribute('conteudo_id',conteudo_id);
//semente.getElementsByTagName('img')[0].setAttribute('conteudo_id',conteudo_id);
inputs = semente.getElementsByTagName('INPUT');
inputs[0].outerHTML = '<input class=sutil2 name=conteudo[' + conteudo_id + ']>';
inputs[1].outerHTML = '<input type=hidden name=conteudo_antigo[' + conteudo_id + ']>';
inputs[2].value = conteudo_id; // <input type="hidden" name="ordena[conteudo][<?=$menu_id?>][]" value="<?=$conteudo_id?>" />
inputs[3].value = conteudo_id; // <input type="hidden" name="novo[conteudo][]" value="<?=$conteudo_id?>" />
//alert(semente.outerHTML);
}
function adicionaConteudo(span)
{
div = span.parentNode;
nomediv = 'conteudo' + div.getAttribute('conteudo_id');
otradiv = document.getElementById(nomediv);
seila = otradiv.parentNode;
semente = document.getElementById('conteudo'+conteudo_id);
replica = semente.cloneNode(true);
replica.setAttribute( 'menu_id' , div.getAttribute('menu_id') );
replica.getElementsByTagName('input')[2].outerHTML = '<input type=hidden value=' + conteudo_id
+ ' name=ordena[conteudo][' + div.getAttribute('menu_id') + '][]>';
conteiner = new Array();
conteiner[0] = replica;
inicializaOrdenadores(conteiner);
//alert(replica.outerHTML)
//depura(replica_conteudo);
//alert(otradiv.outerHTML);
try
{
seila.insertBefore(replica, otradiv.nextSibling);
}
catch(e)
{
seila.appendChild(replica);
}
replica.click();
replica.getElementsByTagName('input')[0].focus();
incrementaConteudo(semente);
}
function removeConteudo(span)
{
div = span.parentNode;
nomediv = 'conteudo' + div.getAttribute('conteudo_id');
otradiv = document.getElementById(nomediv);
if( otradiv.nextSibling || otradiv.previousSibling )
{
seila = otradiv.parentNode;
inputs = otradiv.getElementsByTagName('INPUT');
inputs[0].outerHTML = '<input type=hidden name=remove[conteudo][] value=' + otradiv.getAttribute('conteudo_id') + '>';
semente = document.getElementById('ordenador_menu'+menu_id);
semente.parentNode.appendChild(inputs[0]);
seila.removeChild(otradiv);
}
}
function incrementaIdioma(semente)
{
edicao_id++;
semente.setAttribute( 'id','edicao' + edicao_id );
semente.setAttribute( 'edicao_id' , edicao_id );
inputs = semente.getElementsByTagName('INPUT');
inputs[0].outerHTML = '<input class=sutil2 name=idioma[' + edicao_id + ']>';
inputs[1].outerHTML = '<input type=hidden name=idioma_antigo[' + edicao_id + ']>';
inputs[2].value = edicao_id; // <input type="hidden" name="ordena[idioma][]" value="<?=$edicao_id?>" />
inputs[3].value = edicao_id; // <input type="hidden" name="novo[idioma][]" value="<?=$edicao_id?>" />
imgs = semente.getElementsByTagName('IMG');
imgs[0].setAttribute( 'edicao_id' , edicao_id );
imgs[1].setAttribute( 'edicao_id' , edicao_id );
}
function adicionaIdioma(span)
{
div = span.parentNode;
td = div.parentNode;
aedicao = document.getElementById( 'edicao' + td.getAttribute('edicao_id') );
seila = aedicao.parentNode
sementeIdioma = document.getElementById( 'edicao' + edicao_id );
replicaIdioma = sementeIdioma.cloneNode(true);
try
{
seila.insertBefore(replicaIdioma, aedicao.nextSibling);
}
catch(e)
{
seila.appendChild(replicaIdioma);
}
sementeMenu = document.getElementById( 'ordenador_menu' + menu_id );
replicaMenu = sementeMenu.cloneNode(true);
recebeMenu = replicaIdioma.getElementsByTagName('td')[2].firstChild;
recebeMenu.appendChild(replicaMenu);
sementeConteudo = document.getElementById( 'conteudo' + conteudo_id );
replicaConteudo = sementeConteudo.cloneNode(true);
recebeConteudo = replicaMenu.getElementsByTagName('div')[0].getElementsByTagName('td')[1];
recebeConteudo.appendChild(replicaConteudo);
conteiner = new Array();
conteiner[0] = replicaIdioma;
inicializaOrdenadores(conteiner);
incrementaIdioma(sementeIdioma);
incrementaMenu(sementeMenu);
incrementaConteudo(sementeConteudo);
}
function removeIdioma(span)
{
}
*/
|
Python
|
UTF-8
| 657
| 2.953125
| 3
|
[] |
no_license
|
import csv
def get_TestScript():
Script_Raw = []
Script_Output = []
Script_File = open('text.csv', 'r')
for line in Script_File:
Script_Raw.append(line.strip('\n'))
for i in range(1, len(Script_Raw)):
Script_Output.append(Script_Raw[i].split(''))
for i in range(0, len(Script_Output)):
for j in range(0, len(Script_Output[i])):
Script_Output[i][j] = Script_Output[i][j].strip()
return Script_Output
Script = get_TestScript()
print(Script[1])
#print(Script)
#for i in range(0, len(Script)) :
# if i < 30 :
# for j in range(0, len(Script[i])):
# print(Script[i][j])
|
Java
|
UTF-8
| 2,799
| 2.28125
| 2
|
[] |
no_license
|
package ba.unsa.etf.rpr.project.controller;
import ba.unsa.etf.rpr.project.database.AppDAO;
import ba.unsa.etf.rpr.project.enums.StageName;
import ba.unsa.etf.rpr.project.enums.content.LoginMessages;
import ba.unsa.etf.rpr.project.model.User;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Control;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.ResourceBundle;
public class HomeController {
private AppDAO dao;
public Button btnLogin;
public Button btnSignup;
private ResourceBundle bundle = ResourceBundle.getBundle("Translation");
public HomeController(){
dao=AppDAO.getInstance();
}
@FXML
public void initialize(){
btnLogin.setText(LoginMessages.LOG_IN.toString());
btnSignup.setText(LoginMessages.SIGN_UP.toString());
}
public void loginAction(ActionEvent actionEvent) throws IOException {
Stage loginStage=new Stage();
Parent root=null;
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/login.fxml"),bundle);
LoginController loginController = new LoginController(null, dao.users(),dao);
loader.setController(loginController);
root = loader.load();
loginStage.setTitle(StageName.LOGIN.toString());
loginStage.setScene(new Scene(root, Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE));
Image icon=new Image(getClass().getResourceAsStream("/img/login-icon.png"));
loginStage.getIcons().add(icon);
loginStage.setResizable(false);
loginStage.show();
}
public void registrationAction(ActionEvent actionEvent) throws IOException {
Stage registrationStage=new Stage();
Parent root=null;
FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/register.fxml"),bundle);
RegisterController registerController = new RegisterController(null, dao.users(),dao);
loader.setController(registerController);
root = loader.load();
registrationStage.setTitle(StageName.SIGNUP.toString());
registrationStage.setScene(new Scene(root, Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE));
Image icon=new Image(getClass().getResourceAsStream("/img/login-icon.png"));
registrationStage.getIcons().add(icon);
registrationStage.setResizable(false);
registrationStage.show();
registrationStage.setOnHiding( event -> {
User user = registerController.getUser();
if (user != null) {
dao.addUser(user);
}
} );
}
}
|
C++
|
UTF-8
| 2,292
| 2.796875
| 3
|
[] |
no_license
|
#pragma once
#include <stdarg.h>
namespace GameDev2D
{
class Log
{
public:
//Verbosity log levels
enum Verbosity
{
Verbosity_None = 0,
Verbosity_Debug = 1,
Verbosity_Application = 2,
Verbosity_Input_Keyboard = 4,
Verbosity_Input_Mouse = 8,
Verbosity_Input_GamePad = 16,
Verbosity_Input = Verbosity_Input_Keyboard | Verbosity_Input_Mouse | Verbosity_Input_GamePad,
Verbosity_Graphics = 32,
Verbosity_Resources = 64,
Verbosity_Shaders = 128,
Verbosity_Audio = 256,
Verbosity_UI = 512,
Verbosity_Profiling = 1024,
Verbosity_Memory = 2048,
Verbosity_All = Verbosity_Debug | Verbosity_Application | Verbosity_Input | Verbosity_Graphics | Verbosity_Resources | Verbosity_Shaders | Verbosity_Audio | Verbosity_UI | Verbosity_Profiling | Verbosity_Memory
};
//Calling Init() will ensure that the log file is properly created on the hard drive
static void Init();
//Used to Log a message with a variable amount of arguments, the
//verbosity level for these logs is debug (VerbosityLevel_Debug).
//If the LOG_TO_FILE to file preproc is enabled then this method
//will log to a file in addition to the output window.
static void Message(std::string message, ...);
//Same as the Message() function above, except you can specify the
//verbosity of the log messages.
static void Message(Verbosity verbosity, std::string message, ...);
//Same as the Message() function above, except you can specify the
//verbosity of the log messages.
//static void Message(void* address, const char* label, Verbosity verbosity, const char* message, ...);
//Used to specically log errors, it has no verbosity level, and can
//throw an exception.
static void Error(bool throwException, Verbosity verbosity, std::string message, ...);
private:
//Conveniance method used to log messages
static void Output(bool error, Verbosity verbosity, const char* aOutput, va_list aArgumentsList);
//Member variables
static bool s_IsInitialized;
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.