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,990
2.515625
3
[]
no_license
const { Router } = require("express"); const ItemService = require("../services/ItemService"); const itemService = new ItemService(); const itemRoutes = Router(); itemRoutes.get("/itemlist", async (request, response) => { const {owner} = request.query; const items = await itemService.list(owner); response.json (items); }); itemRoutes.get("/itemlistpag", async (request, response) => { var {page, name, owner} = request.query; const items = await itemService.listpag(page, name, owner); response.json (items); }); itemRoutes.get("/itemidindex", async (request, response) => { const {_id} = request.query; var item = await itemService.idindex(_id); response.json (item); }); itemRoutes.get("/itemparentindex", async (request, response) => { const {parent, owner} = request.query; var items = await itemService.parentindex(parent, owner); response.json (items); }); itemRoutes.get("/itemparentindexpag", async (request, response) => { const {page, parent} = request.query; var {items, parentInfos} = await itemService.parentindexpag(page, parent) response.json ({items, parentInfos}); }); itemRoutes.post("/itemstore", async (request, response) => { const {name, parents, owner} = request.body; var newItem = await itemService.store(name, parents, owner); response.json (newItem); }); itemRoutes.put("/itemidupdate", async (request, response) => { const {_id} = request.query; const {name, parents, owner} = request.body; var newItem = await itemService.idupdate(_id, name, parents, owner); response.json (newItem); }); itemRoutes.delete("/itemiddestroy", async (request, response) => { const {_id} = request.query; const item = await itemService.iddestroy(_id); response.json (item); }); module.exports = itemRoutes;
Java
UTF-8
2,284
2.359375
2
[]
no_license
package com.person.springboot.controller; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class UserInfoController { @Autowired private JdbcTemplate jdbcTemplate; @GetMapping("/list") public List<Map<String, Object>> getUserList() { String sql = "select * from user_info"; List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); return list; } @PostMapping("/addUser") public String addUser(@RequestParam("username") String username, @RequestParam("password") String password) { String sql = "insert into user_info(username, password) values(?, ?)"; Object[] obj = {username, password}; int result = jdbcTemplate.update(sql, obj); if (result > 0) { return "增加成功"; } else { return "增加失败"; } } @PutMapping("/updateUser/{id}") public String updateUser(@PathVariable("id") Integer id, @RequestParam("username") String username, @RequestParam("password") String password) { String sql = "update user_info set username = ?, password = ? where id = ?"; Object[] args = {username, password, id}; int result = jdbcTemplate.update(sql, args); if (result > 0) { return "修改成功"; } else { return "修改失败"; } } @DeleteMapping("/delUser/{id}") public String delUser(@PathVariable("id") Integer id) { String sql = "delete from user_info where id = ?"; Object[] args = {id}; int result = jdbcTemplate.update(sql, args); if (result > 0) { return "删除成功"; } else { return "删除失败"; } } }
Java
UTF-8
202
1.625
2
[]
no_license
package com.devdezyn.mollysclub.auth.dtos; import lombok.*; @Data @NoArgsConstructor @AllArgsConstructor @Builder public class RegisterResponse { private String username; private String email; }
SQL
UTF-8
3,076
3.03125
3
[]
no_license
INSERT INTO fused_recipes(fused_name, date_created, date_modified, fuse_ingredients, fuse_steps, base_cuisine, fuse_cuisine) VALUES ( 'Fruit Crepes', '07/25/2020', '08/15/2020', '1 cup all-purpose flour 2 large eggs 1/2 cup milk 1/2 cup water 1/4 teaspoon salt 2 tablespoons butter, melted 1 can whipped cream 1 lb strawberries, rinsed and tops sliced 1 lb blueberries, rinsed', 'In a large mixing bowl, whisk together the flour and the eggs. Gradually add in the milk and water, stirring to combine. Add the salt and butter; beat until smooth. Heat a lightly oiled griddle or frying pan over medium high heat. Pour or scoop the batter onto the griddle, using approximately 1/4 cup for each crepe. Tilt the pan with a circular motion so that the batter coats the surface evenly. Cook the crepe for about 2 minutes, until the bottom is light brown. Loosen with a spatula, turn and cook the other side. Repeat until all batter is used. Fill each crepe with strawberries, whipped cream, and blueberries. Serve immediately.', 3, NULL ), ( 'Tofu Stir-Fry', '08/01/2020', '08/06/2020', '2 tablespoons vegetable oil 1 pound extra firm tofu, cut into cubes 1 1/2 cups fresh broccoli florets 1 red bell pepper, cut into matchsticks 2 medium carrots, thinly sliced 1 green onion, chopped 1 teaspoon minced garlic 2 tablespoons soy sauce 1 tablespoon hoisin sauce 1 tablespoon mirin or rice cooking wine 2 tablespoons sesame seeds, toasted', 'Heat vegetable oil in a large wok or skillet over medium-high heat, add tofu in a single layer. Once tofu becomes crisp, begin stir frying and moving the tofu quickly but gently. Move tofu to the side of the wok or skillet and add broccoli, bell pepper, carrots, green onion, and garlic to the center; Cook and stir vegetables for 2 minutes. Stir tofu into vegetables and season with soy sauce, hoisin sauce, mirin, and sesame seeds; Cook and stir until vegetables are tender, about 2 more minutes. Serve immediately.', 2, 7 ), ( 'Mexican Grilled Cheese', '08/05/2020', '08/13/2020', '4 slices white bread 3 tablespoons butter, divided 1 cup salsa, liquid drained 3/4 cup Mexican cheese blend 1 medium green pepper, chopped', 'Preheat skillet over medium heat. Add the chopped bell peppers until tender, remove from heat. Generously butter one side of a slice of bread. On the other side, spread on the peppers, salsa, and cheese. In the same skillet, place bread butter-side-down onto skillet. Butter a second slice of bread on one side and place butter-side-up on top of sandwich. Grill until lightly browned and flip over; continue grilling until cheese is melted.', 1, 5 );
Java
UTF-8
1,799
2.359375
2
[]
no_license
package com.thomas.dahouet.controller; import java.util.ArrayList; import com.thomas.dahouet.DAO.proprioDAO; import com.thomas.dahouet.DAO.voilierDAO; import com.thomas.dahouet.GUI.Confirmation; import com.thomas.dahouet.GUI.NavireFrml; import com.thomas.dahouet.GUI.NewProprio; import com.thomas.dahouet.model.Classe; import com.thomas.dahouet.model.Club; import com.thomas.dahouet.model.Proprietaire; import com.thomas.dahouet.model.Serie; import com.thomas.dahouet.model.Voilier; public class Controller { public void initNavireFrml(){ NavireFrml frame1 = new NavireFrml(); frame1.setVisible(true); } public void initNewProprio(){ NewProprio frame2 = new NewProprio(); frame2.setVisible(true); } public void confirmInit(){ Confirmation frame3 = new Confirmation(); frame3.setVisible(true); } public ArrayList<Serie> serieInit(){ ArrayList<Serie> listSerie = new ArrayList<Serie>(); listSerie=voilierDAO.getSerie(); return listSerie; } public ArrayList<Classe> classeInit(Serie serie){ ArrayList<Classe> listClasse = new ArrayList<Classe>(); listClasse=voilierDAO.getClasse(serie); return listClasse; } public ArrayList<Proprietaire> proprioInit(){ ArrayList<Proprietaire> listProprio = new ArrayList<Proprietaire>(); listProprio=proprioDAO.getProprio(); return listProprio; } public ArrayList<Club> clubInit(){ ArrayList<Club> listClub = new ArrayList<Club>(); listClub=proprioDAO.getClub(); return listClub; } public void createProprio(Proprietaire proprio, Club club){ proprioDAO.newProprio(proprio, club); } public void createVoilier (Voilier voilier,Classe classe, Proprietaire proprio){ voilierDAO.newVoilier(voilier, classe, proprio); } }
JavaScript
UTF-8
1,071
2.59375
3
[]
no_license
import $ from 'jquery'; import { GeneralView } from '../chatView/generalView.js' import { ChatView } from '../chatView/chatView.js' import { ChatModel } from '../chatModel/ChatModel.js' export class ChatController { constructor() { this.generalView = new GeneralView(); this.init(); const $app = $('.container') this.chatView = new ChatView({ $container: $app, send: (author, text) => this.send(author, text) }); this.chatModel = new ChatModel({ renderNewMessage: (event) => this.renderNewMessage(event) }); } init() { this.generalView.createContainer() } send(author, text) { this.chatModel.sending(author, text) } renderNewMessage(event) { const message = JSON.parse(event.data); const historyMessage = { author: message.author, text: message.text }; this.chatModel.saveHistory(historyMessage); this.chatView.generateNewElement(message.author, message.text); } }
JavaScript
UTF-8
691
2.53125
3
[]
no_license
import { FETCH_CAT_DATA_START, FETCH_CAT_DATA_SUCCESS, FETCH_CAT_DATA_FAILURE} from "../actions"; const intitialState = { test: "test", isLoading: false, dogs: [], error: '' } export const reducer = (state = intitialState, action) => { switch (action.type){ case FETCH_CAT_DATA_START: return { ...state, isLoading: true, error: '' }; case FETCH_CAT_DATA_SUCCESS: return{ ...state, isLoading: false, error: '', dogs: action.payload, } default: return state; } }
Python
UTF-8
358
2.875
3
[]
no_license
T = int(input()) for tc in range(1, T+1): N = int(input()) M = list(map(int, input().split())) Max = 0 for num, m in enumerate(M): if num == 0: Max = m elif Max < m: Max = m if Max <= M[0]: print(0) else: Sum = 0 for i in M: Sum += Max-i print(Sum)
Java
UTF-8
1,050
1.945313
2
[ "Apache-2.0" ]
permissive
package top.fosin.anan; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import top.fosin.anan.core.banner.AnanBanner; import top.fosin.anan.swagger.annotation.EnableAnanSwagger2; /** * Spring Cloud Gateway * * @author fosin * @date 2019/5/5 */ @SpringCloudApplication @EnableAnanSwagger2 //TODO 因为Swagger暂不支持webflux项目,所以Gateway里不能配置SwaggerConfig,也就是说Gateway无法提供自身API。 //@EnableAnanResourceServer //TODO 由于Oauth2依赖Webmvc模块,这和webflux冲突 @EnableWebSecurity //@EnableWebFluxSecurity //@EnableRedisHttpSession public class CloudGatewayApplication { public static void main(String[] args) { new SpringApplicationBuilder(CloudGatewayApplication.class) .banner(new AnanBanner("AnAn Cloud Gateway")) .logStartupInfo(true) .run(args); } }
Java
UTF-8
551
2.734375
3
[ "MIT" ]
permissive
package net.sf.l2j.log; import java.text.SimpleDateFormat; import java.util.logging.Formatter; import java.util.logging.LogRecord; public class FileLogFormatter extends Formatter { private static final String CRLF = "\r\n"; private static final String SPACE = "\t"; @Override public String format(LogRecord record) { return new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(record.getMillis()) + SPACE + record.getLevel().getName() + SPACE + record.getThreadID() + SPACE + record.getLoggerName() + SPACE + record.getMessage() + CRLF; } }
C++
UTF-8
3,582
3.484375
3
[]
no_license
#include <iostream> #include <cmath> #include <string> #include <sstream> #include <algorithm> #include <iterator> #include <vector> #include <stack> #include <queue> #include "assignment.h" using namespace std; //Function prototypes void ex1_reverse_array(); void ex1_reverse_vector(); void ex1_reverse_stack(); void ex1_ordered_array(); void ex1_ordered_vector(); void ex1_ordered_queue(); //Main function void ex1(){ } void ex1_ordered_queue(){ string userinput; if(!(getline(cin, userinput))) { cin.clear(); cin.ignore(10000,'\n'); cout << "Wrong input, try again.\n"; } queue<string> words; string item; char delim = ' '; istringstream iss(userinput); while (getline(iss, item, delim)) { words.push(item); } while(!words.empty()){ cout << words.front() << " "; words.pop(); } } void ex1_ordered_vector(){ string userinput; if(!(getline(cin, userinput))) { cin.clear(); cin.ignore(10000,'\n'); cout << "Wrong input, try again.\n"; } istringstream iss(userinput); char delim = ' '; string item; vector<string> words; while (getline(iss, item, delim)) { //From slide 331 VG101 words.push_back(item); } for(unsigned long i = 0; i < words.size(); i++){ cout << words[i] << " "; } } void ex1_ordered_array(){ string userinput; if(!(getline(cin, userinput))) { cin.clear(); cin.ignore(10000,'\n'); cout << "Wrong input, try again.\n"; } //Count words in line istringstream iss(userinput); char delim = ' '; string item; int counter = 0; while (getline(iss, item, delim)) { counter++; } //Now create an array large enough to hold all the words and write them string* words = new string[counter]; int filled = 0; istringstream iss2(userinput); while (getline(iss2, item, delim)) { words[filled] = item; filled++; } for(int i = 0; i < counter; i++){ cout << words[i] << " "; } delete[] words; } void ex1_reverse_stack(){ string userinput; if(!(getline(cin, userinput))) { cin.clear(); cin.ignore(10000,'\n'); cout << "Wrong input, try again.\n"; } //Write all the words to a stack stack<string> words; string item; char delim = ' '; istringstream iss(userinput); while (getline(iss, item, delim)) { words.push(item); } while(!words.empty()){ cout << words.top() << " "; words.pop(); } } void ex1_reverse_array() { string userinput; if(!(getline(cin, userinput))) { cin.clear(); cin.ignore(10000,'\n'); cout << "Wrong input, try again.\n"; } //Count words in line istringstream iss(userinput); char delim = ' '; string item; int counter = 0; while (getline(iss, item, delim)) { counter++; } //Now create an array large enough to hold all the words and write them string* words = new string[counter]; int filled = 0; istringstream iss2(userinput); while (getline(iss2, item, delim)) { words[filled] = item; filled++; } //Now reverse all the words in a new array string* reversed = new string[counter]; for(int i = counter-1; i >= 0; i--){ reversed[(counter-1)-i] = words[i]; } for(int i = 0; i < counter; i++){ cout << reversed[i] << " "; } delete[] words; delete[] reversed; } void ex1_reverse_vector() { string userinput; if(!(getline(cin, userinput))) { cin.clear(); cin.ignore(10000,'\n'); cout << "Wrong input, try again.\n"; } istringstream iss(userinput); char delim = ' '; string item; vector<string> words; while (getline(iss, item, delim)) { //From slide 331 VG101 words.push_back(item); } reverse(words.begin(), words.end()); for(unsigned long i = 0; i < words.size(); i++){ cout << words[i] << " "; } }
Python
UTF-8
5,442
2.84375
3
[]
no_license
__author__ = 's' import mysql.connector import numpy as np import datetime as d import copy import sys #establishing database connection cnx = mysql.connector.connect(user='root', password='', host='127.0.0.1', database='thesis') # get a cursor to execute sql queries c = cnx.cursor(buffered= True) # function to calculate the similarity based on longest common subsequences # traj1, traj2 are the two input trajectories. Epsilon is the permittable distance between two points and sigma is the permittable # time gap between two points def similarity_lcss(traj1,traj2) : score = 0 # variables to store trajectories of different days traj1_fri = [] traj1_sat = [] traj1_sun = [] traj1_mon = [] traj1_tue = [] traj1_wed = [] traj1_thu = [] traj2_fri = [] traj2_sat = [] traj2_sun = [] traj2_mon = [] traj2_tue = [] traj2_wed = [] traj2_thu = [] # dividing the user trajectories into different days for row in traj1 : if row[1] == 'Fri' : traj1_fri.append(row) elif row[1] == "Sat" : traj1_sat.append(row) elif row[1] == "Sun" : traj1_sun.append(row) elif row[1] == "Mon" : traj1_mon.append(row) elif row[1] == "Tue" : traj1_tue.append(row) elif row[1] == "Wed" : traj1_wed.append(row) elif row[1] == "Thu" : traj1_thu.append(row) for row in traj2 : if row[1] == 'Fri' : traj2_fri.append(row) elif row[1] == "Sat" : traj2_sat.append(row) elif row[1] == "Sun" : traj2_sun.append(row) elif row[1] == "Mon" : traj2_mon.append(row) elif row[1] == "Tue" : traj2_tue.append(row) elif row[1] == "Wed" : traj2_wed.append(row) elif row[1] == "Thu" : traj2_thu.append(row) if len(traj1_fri)<len(traj2_fri) : score = score + cal_sim(traj1_fri,traj2_fri) else : score = score + cal_sim(traj2_fri,traj1_fri) if len(traj1_sat)<len(traj2_sat) : score = score + cal_sim(traj1_sat,traj2_sat) else : score = score + cal_sim(traj2_sat,traj1_sat) if len(traj1_sun)<len(traj2_sun) : score = score + cal_sim(traj1_sun,traj2_sun) else : score = score + cal_sim(traj2_sun,traj1_sun) if len(traj1_mon)<len(traj2_mon) : score = score + cal_sim(traj1_mon,traj2_mon) else : score = score + cal_sim(traj2_mon,traj1_mon) if len(traj1_tue)<len(traj2_tue) : score = score + cal_sim(traj1_tue,traj2_tue) else : score = score + cal_sim(traj2_tue,traj1_tue) if len(traj1_wed)<len(traj2_wed) : score = score + cal_sim(traj1_wed,traj2_wed) else : score = score + cal_sim(traj2_wed,traj1_wed) if len(traj1_thu)<len(traj2_thu) : score = score + cal_sim(traj1_thu,traj2_thu) else : score = score + cal_sim(traj2_thu,traj1_thu) print "the score is ",score def cal_sim (traj1,traj2) : score = 0 while len(traj1)>0 and len(traj2)>0 : if traj1[len(traj1)-1][2] == traj2[len(traj2)-1][2] and traj1[len(traj1)-1][0] == traj2[len(traj2)-1][0]: score +=1 traj1.pop() traj2.pop() elif traj1[len(traj1)-1][2] > traj2[len(traj2)-1][2] : traj1.pop() elif traj1[len(traj1)-1][2] < traj2[len(traj2)-1][2]: traj2.pop() elif traj1[len(traj1)-1][2] == traj2[len(traj2)-1][2] : i = 2 #print traj1[len1][2],traj1[len1-1][2],traj2[len2][2],len1,len2,traj2[len2-1][2] if traj1[len(traj1)-2][2] == traj2[len(traj2)-1][2] : traj1.pop() elif traj1[len(traj1)-1][2] == traj2[len(traj2)-2][2] : traj2.pop() else : traj1.pop() traj2.pop() return score #the similarity matrix between 8357 users initialized with value 1 similarity=np.ones((8357,8357)) similarity[0][0] # list to store all the user ids lst = [] c.execute("select distinct userid from fulldata") # the time difference between the two data points of two diff trajectories time_diff = 15; # load all the user ids into a list 'lst' for a in c : lst.append(a) len(lst) lst2 = lst user_num=0 user_id =0 traj1 = [] traj2 = [] while (user_num<len(lst)) : for row in lst[user_num] : user_id = row; c.execute("select siteid,weekday,timing from fulldata where userid = " + str(user_id) ); for siteid,weekday,timing in c : tuple = [] tuple.append(siteid) tuple.append(weekday) tuple.append(timing) traj1.append(tuple) next_user = user_num+1 while (next_user < len(lst)) : for row in lst[next_user] : user_id = row; traj2 = [] c.execute("select siteid,weekday,timing from fulldata where userid = " + str(user_id) ); for siteid,weekday,timing in c : tuple = [] tuple.append(siteid) tuple.append(weekday) tuple.append(timing) traj2.append(tuple) print next_user similarity_lcss(traj1,traj2) next_user +=1 #break break cnx.close()
C#
UTF-8
1,702
2.8125
3
[]
no_license
using System; using System.Windows.Forms; namespace Media.Calc.WinFormApp { public partial class GaussForm : Form { public string A { get; set; } public string B { get; set; } public string C { get; set; } public string X { get; set; } public GaussForm() { InitializeComponent(); } private void okButton_Click(object sender, EventArgs e) { A = textBox1.Text; B = textBox2.Text; C = textBox3.Text; X = textBox4.Text; DialogResult = DialogResult.OK; Close(); } private static void AllowPressedKeys(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } // only allow one decimal point if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { AllowPressedKeys(sender, e); } private void textBox2_KeyPress(object sender, KeyPressEventArgs e) { AllowPressedKeys(sender, e); } private void textBox3_KeyPress(object sender, KeyPressEventArgs e) { AllowPressedKeys(sender, e); } private void textBox4_KeyPress(object sender, KeyPressEventArgs e) { AllowPressedKeys(sender, e); } } }
Java
UTF-8
15,375
2.234375
2
[]
no_license
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/narya/ // // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.threerings.util; import java.text.MessageFormat; import java.util.Collection; import java.util.Enumeration; import java.util.MissingResourceException; import java.util.ResourceBundle; import com.samskivert.text.MessageUtil; import com.samskivert.util.StringUtil; import static com.threerings.NaryaLog.log; /** * A message bundle provides an easy mechanism by which to obtain translated message strings from * a resource bundle. It uses the {@link MessageFormat} class to substitute arguments into the * translation strings. Message bundles would generally be obtained via the {@link MessageManager}, * but could be constructed individually if so desired. */ public class MessageBundle { /** * Call this to "taint" any string that has been entered by an entity outside the application * so that the translation code knows not to attempt to translate this string when doing * recursive translations (see {@link #xlate}). */ public static String taint (Object text) { return MessageUtil.taint(text); } /** * Composes a message key with a single argument. The message can subsequently be translated * in a single call using {@link #xlate}. */ public static String compose (String key, Object arg) { return MessageUtil.compose(key, new Object[] { arg }); } /** * Composes a message key with an array of arguments. The message can subsequently be * translated in a single call using {@link #xlate}. */ public static String compose (String key, Object... args) { return MessageUtil.compose(key, args); } /** * Composes a message key with an array of arguments. The message can subsequently be * translated in a single call using {@link #xlate}. */ public static String compose (String key, String... args) { return MessageUtil.compose(key, args); } /** * A convenience method for calling {@link #compose(String,Object[])} with an array of * arguments that will be automatically tainted (see {@link #taint}). */ public static String tcompose (String key, Object... args) { return MessageUtil.tcompose(key, args); } /** * Required for backwards compatibility. Alas. */ public static String tcompose (String key, Object arg) { return MessageUtil.tcompose(key, new Object[] { arg }); } /** * Required for backwards compatibility. Alas. */ public static String tcompose (String key, Object arg1, Object arg2) { return MessageUtil.tcompose(key, new Object[] { arg1, arg2 }); } /** * A convenience method for calling {@link #compose(String,String[])} with an array of * arguments that will be automatically tainted (see {@link #taint}). */ public static String tcompose (String key, String... args) { return MessageUtil.tcompose(key, args); } /** * Returns a fully qualified message key which, when translated by some other bundle, will * know to resolve and utilize the supplied bundle to translate this particular key. */ public static String qualify (String bundle, String key) { return MessageUtil.qualify(bundle, key); } /** * Returns the bundle name from a fully qualified message key. * * @see #qualify */ public static String getBundle (String qualifiedKey) { return MessageUtil.getBundle(qualifiedKey); } /** * Returns the unqualified portion of the key from a fully qualified message key. * * @see #qualify */ public static String getUnqualifiedKey (String qualifiedKey) { return MessageUtil.getUnqualifiedKey(qualifiedKey); } /** * Initializes the message bundle which will obtain localized messages from the supplied * resource bundle. The path is provided purely for reporting purposes. */ public void init (MessageManager msgmgr, String path, ResourceBundle bundle, MessageBundle parent) { _msgmgr = msgmgr; _path = path; _bundle = bundle; _parent = parent; } /** * Obtains the translation for the specified message key. No arguments are substituted into * the translated string. If a translation message does not exist for the specified key, an * error is logged and the key itself is returned so that the caller need not worry about * handling a null response. */ public String get (String key) { // if this string is tainted, we don't translate it, instead we // simply remove the taint character and return it to the caller if (MessageUtil.isTainted(key)) { return MessageUtil.untaint(key); } String msg = getResourceString(key); return (msg != null) ? msg : key; } /** * Adds all messages whose key starts with the specified prefix to the supplied collection. * * @param includeParent if true, messages from our parent bundle (and its parent bundle, all * the way up the chain will be included). */ public void getAll (String prefix, Collection<String> messages, boolean includeParent) { Enumeration<String> iter = _bundle.getKeys(); while (iter.hasMoreElements()) { String key = iter.nextElement(); if (key.startsWith(prefix)) { messages.add(get(key)); } } if (includeParent && _parent != null) { _parent.getAll(prefix, messages, includeParent); } } /** * Adds all keys for messages whose key starts with the specified prefix to the supplied * collection. * * @param includeParent if true, messages from our parent bundle (and its parent bundle, all * the way up the chain will be included). */ public void getAllKeys (String prefix, Collection<String> keys, boolean includeParent) { Enumeration<String> iter = _bundle.getKeys(); while (iter.hasMoreElements()) { String key = iter.nextElement(); if (key.startsWith(prefix)) { keys.add(key); } } if (includeParent && _parent != null) { _parent.getAllKeys(prefix, keys, includeParent); } } /** * Returns true if we have a translation mapping for the supplied key, false if not. */ public boolean exists (String key) { return getResourceString(key, false) != null; } /** * Get a String from the resource bundle, or null if there was an error. */ public String getResourceString (String key) { return getResourceString(key, true); } /** * Get a String from the resource bundle, or null if there was an error. * * @param key the resource key. * @param reportMissing whether or not the method should log an error if the resource didn't * exist. */ public String getResourceString (String key, boolean reportMissing) { try { if (_bundle != null) { return _bundle.getString(key); } } catch (MissingResourceException mre) { // fall through and try the parent } // if we have a parent, try getting the string from them if (_parent != null) { String value = _parent.getResourceString(key, false); if (value != null) { return value; } // if we didn't find it in our parent, we want to fall // through and report missing appropriately } if (reportMissing) { log.warning("Missing translation message", "bundle", _path, "key", key, new Exception()); } return null; } /** * Obtains the translation for the specified message key. The specified arguments are * substituted into the translated string. * * <p> If the first argument in the array is an {@link Integer} object, a translation will be * selected accounting for plurality in the following manner. Assume a message key of * <code>m.widgets</code>, the following translations should be defined: <pre> m.widgets.0 = * no widgets. m.widgets.1 = {0} widget. m.widgets.n = {0} widgets. </pre> * * The specified argument is substituted into the translated string as appropriate. Consider * using: * * <pre> m.widgets.n = {0,number,integer} widgets. </pre> * * to obtain proper insertion of commas and dots as appropriate for the locale. * * <p> See {@link MessageFormat} for more information on how the substitution is performed. If * a translation message does not exist for the specified key, an error is logged and the key * itself (plus the arguments) is returned so that the caller need not worry about handling a * null response. */ public String get (String key, Object... args) { // if this is a qualified key, we need to pass the buck to the // appropriate message bundle if (key.startsWith(MessageUtil.QUAL_PREFIX)) { MessageBundle qbundle = _msgmgr.getBundle(getBundle(key)); return qbundle.get(getUnqualifiedKey(key), args); } // Select the proper suffix if our first argument can be coaxed into an integer String suffix = getSuffix(args); String msg = getResourceString(key + suffix, false); if (msg == null) { // Playing with fire: This only works because it's the same "" reference we return // from getSuffix() // Don't try this at home. Keep out of reach of children. If swallowed, consult // StringUtil.isBlank() if (suffix != "") { // Try the original key msg = getResourceString(key, false); } if (msg == null) { log.warning("Missing translation message", "bundle", _path, "key", key, new Exception()); // return something bogus return (key + StringUtil.toString(args)); } } return MessageFormat.format(MessageUtil.escape(msg), args); } /** * Obtains the translation for the specified message key. The specified arguments are * substituted into the translated string. */ public String get (String key, String... args) { return get(key, (Object[]) args); } /** * A helper function for {@link #get(String,Object[])} that allows us to automatically perform * plurality processing if our first argument can be coaxed to an {@link Integer}. */ public String getSuffix (Object[] args) { if (args.length > 0 && args[0] != null) { try { int count = (args[0] instanceof Integer) ? (Integer)args[0] : Integer.parseInt(args[0].toString()); switch (count) { case 0: return ".0"; case 1: return ".1"; default: return ".n"; } } catch (NumberFormatException e) { // Fall out } } return ""; } /** * Obtains the translation for the specified compound message key. A compound key contains the * message key followed by a tab separated list of message arguments which will be subsituted * into the translation string. * * <p> See {@link MessageFormat} for more information on how the substitution is performed. If * a translation message does not exist for the specified key, an error is logged and the key * itself (plus the arguments) is returned so that the caller need not worry about handling a * null response. */ public String xlate (String compoundKey) { // if this is a qualified key, we need to pass the buck to the appropriate message bundle; // we have to do it here because we want the compound arguments of this key to be // translated in the context of the containing message bundle qualification if (compoundKey.startsWith(MessageUtil.QUAL_PREFIX)) { MessageBundle qbundle = _msgmgr.getBundle(getBundle(compoundKey)); return qbundle.xlate(getUnqualifiedKey(compoundKey)); } // to be more efficient about creating unnecessary objects, we // do some checking before splitting int tidx = compoundKey.indexOf('|'); if (tidx == -1) { return get(compoundKey); } else { String key = compoundKey.substring(0, tidx); String argstr = compoundKey.substring(tidx+1); String[] args = StringUtil.split(argstr, "|"); // unescape and translate the arguments for (int i = 0; i < args.length; i++) { // if the argument is tainted, do no further translation // (it might contain |s or other fun stuff) if (MessageUtil.isTainted(args[i])) { args[i] = MessageUtil.unescape(MessageUtil.untaint(args[i])); } else { args[i] = xlate(MessageUtil.unescape(args[i])); } } return get(key, (Object[]) args); } } @Override public String toString () { return "[bundle=" + _bundle + ", path=" + _path + "]"; } /** The message manager via whom we'll resolve fully qualified translation strings. */ protected MessageManager _msgmgr; /** The path that identifies the resource bundle we are using to obtain our messages. */ protected String _path; /** The resource bundle from which we obtain our messages. */ protected ResourceBundle _bundle; /** Our parent bundle if we're not the global bundle. */ protected MessageBundle _parent; }
JavaScript
UTF-8
2,087
2.984375
3
[ "Apache-2.0" ]
permissive
getDoctorId(); function getDoctorId(){ let selectionOfDoctor = document.getElementById("searchByIdDoctor"); fetch("https://ipc1project2.herokuapp.com/get-id-specific-doctor",{ method:"POST", headers:{ 'Content-Type':'application/json' }, body: JSON.stringify({ "id":localStorage.getItem("id") }) }).then(res => res.json()) .catch(err => { console.log("ha ocurrido un error"+err) }) .then(res => { res.forEach(user => { selectionOfDoctor.innerHTML = selectionOfDoctor.innerHTML + ` <option>${user.id} </option> ` }); }) } try{ let searchMyDataDoc = document.getElementById("searchMyDataD"); searchMyDataDoc.addEventListener("click",getDataOfDoctorById_); } catch (error) { } function getDataOfDoctorById_(){ let id7 = document.getElementById("searchByIdDoctor").value; let name7 = document.getElementById("namedoctor"); let lastName7 = document.getElementById("lastNamedoctor"); let userName7 = document.getElementById("userNamedoctor"); let password7 = document.getElementById("passworddoctor"); let birth7 = document.getElementById("birthdoctor"); fetch("https://ipc1project2.herokuapp.com/get-data-doctor-by-id",{ method:"POST", headers:{ 'Content-Type':'application/json' }, body: JSON.stringify({ "id": id7 }) }).then(res => res.json()) .catch(err => { console.log("ha ocurrido un error"+err) }) .then(res => { res.forEach(user => { let dateArray7 = user.date_of_birth.split("/").reverse(); let finalDate7 = dateArray7[0]+"-"+dateArray7[1]+"-"+dateArray7[2]; name7.value = user.name ; lastName7.value = user.last_name; userName7.value = user.user_name; password7.value = user.password; birth7.value = finalDate7; }); }) }
C++
UTF-8
472
2.875
3
[]
no_license
#pragma once #include <iostream> #include <memory> #include "RuleOf5Resource.h" namespace IGTK { namespace SmartPointerTests { void TestUniquePtr() { std::unique_ptr<RuleOf5Resource> p1 = std::make_unique<RuleOf5Resource>(); if (p1 != nullptr) { std::cout << "p1 is valid \n"; } // code block { std::unique_ptr<RuleOf5Resource> p2 = std::move(p1); } if (p1 == nullptr) { std::cout << "p1 is no longer valid \n"; } } } }
Markdown
UTF-8
3,645
2.671875
3
[ "Apache-2.0" ]
permissive
--- title: "Data on Azure Storage" meta_title: "Azure Storage" meta_description: "Using data on Azure Storage in your Polyaxon experiments and jobs. Polyaxon allows users to connect to one or multiple blobs on Azure Storage to access data directly on your machine learning experiments and jobs." custom_excerpt: "Azure Storage is Microsoft's cloud storage solution. Azure Storage provides storage for data objects that is highly available, secure, durable, massively scalable cloud storage solution." image: "../../content/images/integrations/azure-storage.png" author: name: "Polyaxon" slug: "Polyaxon" website: "https://polyaxon.com" twitter: "polyaxonAI" github: "polyaxon" tags: - data-stores - storage - azure featured: false popularity: 1 visibility: public status: published --- You can use one or multiple blobs on Azure Storage to access data directly on your machine learning experiments and jobs. ## Create an Azure Storage account You should create a storage account (e.g. plx-storage) and a blob (e.g. data). You need to expose information about how to connect to the blob storage, the standard way is to expose these keys: * `AZURE_ACCOUNT_NAME` * `AZURE_ACCOUNT_KEY` * `AZURE_CONNECTION_STRING` ## Create a secret or a config map for storing these keys We recommend using a secret to store your access information json object: ```bash kubectl create secret -n polyaxon generic az-secret --from-literal=AZURE_ACCOUNT_NAME=account --from-literal=AZURE_ACCOUNT_KEY=hash-key ``` ## Use the secret to add a connection ```yaml connections: - name: azure-dataset1 kind: wasb schema: bucket: "wasbs://dataset1@container.blob.core.windows.net/" secret: name: "az-secret" ``` If you want ot access multiple datasets using the same secret: ```yaml persistence: - name: azure-dataset1 kind: wasb schema: bucket: "wasbs://dataset1@container.blob.core.windows.net/" secret: name: "az-secret" - name: azure-dataset2 kind: wasb schema: bucket: "wasbs://dataset2@container.blob.core.windows.net/" secret: name: "az-secret" ``` ## Update/Install Polyaxon CE or Polyaxon Agent deployment You can [deploy/upgrade](/docs/setup/) your Polyaxon CE or Polyaxon Agent deployment with access to data on Azure. ## Access to the dataset in your experiments/jobs To expose the connection secret to one of the containers in your jobs or services: ```yaml run: kind: job connections: [azure-dataset1] ``` Or ```yaml run: kind: job connections: [azure-dataset1, s3-dataset1] ``` ## Use the initializer to load the dataset To use the artifacts initializer to load the dataset ```yaml run: kind: job init: - artifacts: {dirs: [...], files: [...]} connection: "azure-dataset1" ``` ## Access the dataset programmatically This is optional, you can use any language or logic to interact with Azure Blob Storage buckets. For instance you can install `Azure Blob Storage Python SDK` and it will be configured automatically when you request the Azure Blob Storage connection. You can also use Polyaxon's fs library to get a fully resolved [adlfs](https://github.com/fsspec/adlfs) instance: ```bash pip install polyaxon[azure] ``` Creating a sync instance of the adlfs client: ```python from polyaxon.fs.fs import get_fs_from_name ... fs = get_fs_from_name("azure-dataset1") # You can pass additional kwargs to the function ... ``` Creating an async instance of the adlfs client: ```python from polyaxon.fs.fs import get_fs_from_name ... fs = get_fs_from_name("azure-dataset1", asynchronous=True) # You can pass additional kwargs to the function ... ```
Python
UTF-8
555
3.5
4
[ "Apache-2.0" ]
permissive
# Задача 2. Вариант 27. # Напишите программу, которая будет выводить на экран наиболее понравившееся # вам высказывание, автором которого является Овидий. Не забудьте о том, что # автор должен быть упомянут на отдельной строке. # Чернов Михаил Сергеевич # 28.05.2016 print("Верь опыту") print("\n\t\tОвидий") input("\n\nНажмите Enter для выхода.")
Java
UTF-8
199
1.898438
2
[]
no_license
package app.MT102xml; import java.util.List; public interface MT102xmlService { public List<MT102xml> findAll(); public MT102xml save(MT102xml MT102xml); public MT102xml findOne(Long id); }
Markdown
UTF-8
3,877
2.859375
3
[ "MIT" ]
permissive
![go workers](https://raw.githubusercontent.com/catmullet/go-workers/assets/constworker_header_anim.gif) [![Maintainability](https://api.codeclimate.com/v1/badges/402fee86fbd1e24defb2/maintainability)](https://codeclimate.com/github/catmullet/go-workers/maintainability) [![Go Report Card](https://goreportcard.com/badge/github.com/catmullet/go-workers)](https://goreportcard.com/report/github.com/catmullet/go-workers) # Examples * [Quickstart](https://github.com/catmullet/go-workers/blob/master/examples/quickstart/quickstart.go) * [Multiple Go Workers](https://github.com/catmullet/go-workers/blob/master/examples/multiple_workers/multipleworkers.go) * [Passing Fields](https://github.com/catmullet/go-workers/blob/master/examples/passing_fields/passingfields.go) # Getting Started ### Pull in the dependency ```zsh go get github.com/catmullet/go-workers ``` ### Add the import to your project giving an alias helps since go-workers doesn't exactly follow conventions. _(If your using a JetBrains IDE it should automatically give it an alias)_ ```go import ( worker "github.com/catmullet/go-workers" ) ``` ### Create a new worker <img src="https://raw.githubusercontent.com/catmullet/go-workers/assets/constworker.png" alt="worker" width="35"/> The NewWorker factory method returns a new worker. _(Method chaining can be performed on this method like calling .Work() immediately after.)_ ```go worker := worker.NewWorker(ctx, workerFunction, numberOfWorkers) ``` ### Send work to worker Send accepts an interface. So send it anything you want. ```go worker.Send("Hello World") ``` ### Close the worker when done This closes the in channel on the worker and signals to the go functions to stop. ```go worker.Close() ``` ### Wait for the worker to finish and handle errors Any error that bubbles up from your worker functions will return here. ```go if err := worker.Wait(); err != nil { //Handle error } ``` ## Working With Multiple Workers ### Passing work form one worker to the next By using the InFrom method you can tell `workerTwo` to accept output from `workerOne` ```go workerOne := worker.NewWorker(ctx, workerOneFunction, 100).Work() workerTwo := worker.NewWorker(ctx, workerTwoFunction, 100).InFrom(workerOne).Work() ``` ### Accepting output from multiple workers It is possible to accept output from more than one worker but it is up to you to determine what is coming from which worker. ```go workerOne := worker.NewWorker(ctx, workerOneFunction, 100).Work() workerTwo := worker.NewWorker(ctx, workerOneFunction, 100).Work() workerThree := worker.NewWorker(ctx, workerTwoFunction, 100).InFrom(workerOne, workerTwo).Work() ``` ## Passing Fields To Workers ### Adding Field Values Fields can be passed to worker functions as configuration values via the `AddField` method. It accepts a key and a value. If you are passing a struct it should likely be a Pointer. Fields although concurrent safe should only be used for configuration at the start of your worker function. <img src="https://raw.githubusercontent.com/catmullet/go-workers/assets/constworker2.png" alt="worker" width="35"/> **ONLY** use the `Send()` method to get data into your worker. It is not shared memory unlike the fields. ```go worker := worker.NewWorker(ctx, workerFunction, 100).AddField("message", "Hello World") ``` ### Getting Field Values To get the fields in the worker function use the `BindField` method. Only use this function outside of the for loop. Create a variable of the same type you are trying to get out of fields and pass a pointer of it into the `BindField` method along with the key. ```go func workerFunction(w *worker.Worker) error { // Pull in fields outside of for loop only. var message string w.BindField("message", &message) for in := range w.In() { // Use message variable here } return nil } ```
Java
UTF-8
22,393
1.734375
2
[ "Apache-2.0" ]
permissive
package com.base.action; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.security.auth.message.callback.PrivateKeyCallback.Request; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.base.po.ApplyDept; import com.base.po.ApplyList; import com.base.po.BaseInfo; import com.base.po.LandApply_view; import com.base.po.LandInfo; import com.base.po.LandLayout; import com.base.po.Land_Planting; import com.base.po.Land_base; import com.base.po.Layout_InfoView; import com.base.po.RentCollection; import com.base.po.Startplan; import com.base.po.TemperateSave_View; import com.base.serviceImpl.LandApplyServiceImpl; import com.base.utils.CookieUtils; import com.base.utils.ExcelReport; //申请模块的控制层 @Controller("landApplyController") @RequestMapping("/jsp") public class LandApplyController { @Autowired private LandApplyServiceImpl landApplyServiceImpl; // 基地查询 @RequestMapping("/baseInfo.do") public String selectBase(HttpServletRequest request, ModelMap map, HttpServletResponse response) { List<BaseInfo> list = landApplyServiceImpl.getBaseInfos(); response.setContentType("text/html;charset=UTF-8"); try { JSONArray json = JSONArray.fromObject(list); response.getWriter().print(json.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // 基地+部门查询 @RequestMapping("/getBase_deptInfo.do") public String selectBase_deptInfo(HttpServletRequest request, ModelMap map, HttpServletResponse response) { List<BaseInfo> list1 = landApplyServiceImpl.getBaseInfos(); List<ApplyDept> list2 = landApplyServiceImpl.getDepts(); Startplan sp = landApplyServiceImpl.getStartPlan("zl"); String rents = ""; String rente = ""; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; String str = dateFormat.format(Calendar.getInstance().getTime()); int tag = 0; if (sp != null) { rents = sp.getApply_start(); rente = sp.getApply_end(); } int number1 = 0; int number2 = 0; try { date = dateFormat.parse(str); number1 = date.compareTo(dateFormat.parse(rents)); number2 = date.compareTo(dateFormat.parse(rente)); if (number1 >= 0 && number2 <= 0) { tag = 2; } else { tag = 1; } } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JSONObject getObj = new JSONObject(); getObj.put("base", list1); getObj.put("xy", list2); getObj.put("stime", rents); getObj.put("etime", rente); getObj.put("tag", tag); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(getObj.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping("/getInfo.do") public String getInfo(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException { String lid = request.getParameter("lid"); List<Land_base> li = landApplyServiceImpl.getLand_baseView(lid); JSONArray json = JSONArray.fromObject(li); response.setContentType("text/html;charset=UTF-8"); response.getWriter().print(json.toString()); return null; } // 租赁申请时,获取土地布局+土地基本信息+土地现租赁情况+土地租赁历史 @RequestMapping("/getRentCollection.do") public String getRentCollection(HttpServletRequest request, HttpServletResponse response, ModelMap map) { int bid = Integer.valueOf(request.getParameter("bid")); List<RentCollection> list = landApplyServiceImpl.getRentCollection(bid); JSONArray json = JSONArray.fromObject(list); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(json.toString()); // response.getWriter().print(getObj.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // 租赁申请时,提交租赁申请 @RequestMapping("/submitLandApply.do") public String submitLandApply(HttpServletRequest request, HttpServletResponse response, ModelMap map) { String str = request.getParameter("str"); String info_str = request.getParameter("info_str"); String lidList = request.getParameter("lidList"); String userid = request.getParameter("userid"); int flag = landApplyServiceImpl.submitLandApply(userid, lidList, str, info_str); response.setContentType("text/html;charset=UTF-8"); String str1 = "" + flag + '$' + ""; try { response.getWriter().print(str1); // response.getWriter().print(getObj.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // 获取用户个人的申请记录 @RequestMapping("/selfApply.do") public String selfApply(HttpServletRequest request, HttpServletResponse response, ModelMap map) { String bname = request.getParameter("bname"); String desc = request.getParameter("desc"); int length = Integer.valueOf(request.getParameter("length")); int start = Integer.valueOf(request.getParameter("start")); int draw = Integer.valueOf(request.getParameter("draw")); // 从客户端获得length(每页3长度),start()起始页数,draw计数器 int page = start / length + 1; // 当前页数 String applicantId = CookieUtils.getUserid(request); ApplyList al = landApplyServiceImpl.getselfApply(applicantId, bname, desc, page, length); JSONObject getObj = new JSONObject(); getObj.put("draw", draw); getObj.put("recordsFiltered", al.getRecordsTotal()); getObj.put("recordsTotal", al.getRecordsTotal()); getObj.put("data", al.getData()); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(getObj.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping("/myRentdetail.do") public String myRentdetail(HttpServletRequest request, HttpServletResponse response, ModelMap map) { int la_id = Integer.valueOf(request.getParameter("la_id")); List<LandApply_view> list = null; list = landApplyServiceImpl.myRentdetail(la_id); JSONArray json = JSONArray.fromObject(list); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(json.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping("/myRentEdit.do") public String myRentEdit(HttpServletRequest request, HttpServletResponse response, ModelMap map) { int la_id = 21; // int la_id = Integer.valueOf(request.getParameter("la_id")); List<TemperateSave_View> list = landApplyServiceImpl.getTs(la_id); JSONArray json = JSONArray.fromObject(list); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(json.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // 获取用户当年的土地租赁(除了通过,不通过,失效) @RequestMapping("/myRentFont.do") public String myRentFont(HttpServletRequest request, HttpServletResponse response, ModelMap map) { int length = Integer.valueOf(request.getParameter("length")); int start = Integer.valueOf(request.getParameter("start")); int draw = Integer.valueOf(request.getParameter("draw")); // 从客户端获得length(每页3长度),start()起始页数,draw计数器 int page = start / length + 1; // 当前页数 String applicantId = CookieUtils.getUserid(request); ApplyList al = landApplyServiceImpl.myRentFont1(applicantId, page, length); JSONObject getObj = new JSONObject(); getObj.put("draw", draw); getObj.put("recordsFiltered", al.getRecordsTotal()); getObj.put("recordsTotal", al.getRecordsTotal()); getObj.put("data", al.getData()); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(getObj.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping("/myFameCancel1.do") public String myFameCancel1(HttpServletRequest request, HttpServletResponse response, ModelMap map) { int la_id = Integer.valueOf(request.getParameter("la_id")); String info_str = request.getParameter("info_str"); int tag = Integer.valueOf(request.getParameter("flag")); try { int flag = landApplyServiceImpl.myFameCancel1(la_id, info_str, tag); String str = "[{\"flag\":" + flag + "}]"; JSONArray json = JSONArray.fromObject(str); response.getWriter().print(json.toString()); } catch (Exception e) { System.out.println(e); } return null; } @RequestMapping("/myFrameDel1.do") public String myFrameDel1(HttpServletRequest request, HttpServletResponse response, ModelMap map) { int la_id = Integer.valueOf(request.getParameter("la_id")); boolean flag = false; try { landApplyServiceImpl.myFrameDel1(la_id); flag = true; String str = "[{\"flag\":" + flag + "}]"; JSONArray json = JSONArray.fromObject(str); response.getWriter().print(json.toString()); } catch (Exception e) { System.out.println(e); } return null; } @RequestMapping("/myFrameSumbit.do") public String myFrameSumbit(HttpServletRequest request, HttpServletResponse response, ModelMap map) { int la_id = Integer.valueOf(request.getParameter("la_id")); boolean flag = false; try { landApplyServiceImpl.myFrameSubmit(la_id); flag = true; String str = "[{\"flag\":" + flag + "}]"; JSONArray json = JSONArray.fromObject(str); response.getWriter().print(json.toString()); } catch (Exception e) { System.out.println(e); } return null; } @RequestMapping("/exportFile.do") public String exportFile(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException { String fileName = null; int flag = Integer.valueOf(request.getParameter("flag")); if (flag == 1) { fileName = "教学科研用地协议.pdf"; } else if (flag == 2) { fileName = "土地有偿使用协议.docx"; } String filename = fileName.substring(0, fileName.lastIndexOf('.')); String filetype = fileName.substring(fileName.lastIndexOf(".")); // 文件下载 response.setContentType(request.getServletContext().getMimeType( filename)); // 读取目标文件,通过response将目标文件写到客户端 // 获取目标文件的绝对路径 /* * String fullFileName = request.getServletContext().getRealPath( * "file/" + fileName); */ String fullFileName = ExcelReport.getWebRootUrl(request, "/upload/") + fileName; // 设置Content-Disposition /* * response.setHeader("Content-Disposition", "attachment;filename=" + * fileName); */ response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "iso-8859-1") + filetype); // 读取文件 InputStream in = new FileInputStream(fullFileName); OutputStream out = response.getOutputStream(); // 写文件 int b; while ((b = in.read()) != -1) { out.write(b); } in.close(); out.close(); return null; } /* * @RequestMapping("/unionSelect.do") public String * unionSelect(HttpServletRequest request, HttpServletResponse response, * ModelMap map) throws IOException { System.out.println("调用了吗"); String * applicantId = "201440509"; * * String bname = request.getParameter("bname"); String startTime = * request.getParameter("startTime"); String endTime = * request.getParameter("endTime"); String lid = * request.getParameter("lid"); * * System.out.println("我得到的lid是:" + lid); * * String desc = request.getParameter("desc"); * * List<LandApply_view> list = landApplyServiceImpl.getUnionInfo( * applicantId, bname, startTime, endTime, lid, desc); * * JSONObject getObj = new JSONObject(); getObj.put("data", list); * map.addAttribute("flag", 2); * response.setContentType("text/html;charset=UTF-8"); * * try { response.getWriter().print(getObj.toString()); } catch (IOException * e) { // TODO Auto-generated catch block e.printStackTrace(); } return * null; * * } */ @RequestMapping("/updateContent.do") public String updateContent(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException { String lid = request.getParameter("lid"); int dept = Integer.valueOf(request.getParameter("dept")); String planting = request.getParameter("planting"); int la_id = Integer.valueOf(request.getParameter("hide")); String filename = ""; // 上传文件(图片),将文件存入服务器指定路径下,并获得文件的相对路径 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 得到上传的文件 MultipartFile mFile = multipartRequest.getFile("fileResource"); // 得到上传服务器的路径 String path = request.getSession().getServletContext() .getRealPath("/infor/"); // 得到上传的文件的文件名 String fileName = mFile.getOriginalFilename(); if (!fileName.isEmpty()) { filename = new Date().getTime() + "$" + fileName; InputStream inputStream = mFile.getInputStream(); byte[] b = new byte[1048576]; int length = inputStream.read(b); path += "\\" + filename; // 文件流写到服务器端 FileOutputStream outputStream = new FileOutputStream(path); outputStream.write(b, 0, length); inputStream.close(); outputStream.close(); filename = "../infor/" + filename; } String path1 = request.getSession().getServletContext().getRealPath(""); landApplyServiceImpl.updateContent(la_id, lid, dept, planting, filename, path1); return "redirect:myRent.jsp"; } @RequestMapping("/getDept.do") public String getDept(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException { List<ApplyDept> list = landApplyServiceImpl.getDepts(); response.setContentType("text/html;charset=UTF-8"); try { JSONArray json = JSONArray.fromObject(list); response.getWriter().print(json.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping("/getLayout_Info.do") public String getLayout_Info(HttpServletRequest request, HttpServletResponse response, ModelMap map) { List<Layout_InfoView> list = landApplyServiceImpl.getLayout(); /* * JSONObject getObj = new JSONObject(); getObj.put("data", list); */ JSONArray json = JSONArray.fromObject(list); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(json.toString()); // response.getWriter().print(getObj.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping("/getDifferLayout.do") public String getDifferLayout(HttpServletRequest request, HttpServletResponse response, ModelMap map) { int bid = Integer.valueOf(request.getParameter("bid")); List<Layout_InfoView> list = landApplyServiceImpl.getDifferLayout(bid); JSONArray json = JSONArray.fromObject(list); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(json.toString()); // response.getWriter().print(getObj.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping("/uploadImage.do") @ResponseBody public String uploading(HttpServletRequest request, HttpServletResponse response, ModelMap map) { // 上传文件(图片),将文件存入服务器指定路径下,并获得文件的相对路径 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 得到上传的文件 MultipartFile mFile = multipartRequest.getFile("imgfile"); // 有问题 String filename = ""; if (!mFile.isEmpty()) { // 得到上传服务器的路径 String path = ExcelReport.getWebRootUrl(request, "/landImage/"); // 得到上传的文件的文件名 String fileName = mFile.getOriginalFilename(); String fileType = fileName.substring(fileName.lastIndexOf(".")); filename = new Date().getTime() + fileType; InputStream inputStream; try { inputStream = mFile.getInputStream(); byte[] b = new byte[1048576]; int length = inputStream.read(b); path += "/" + filename; // 文件流写到服务器端 FileOutputStream outputStream = new FileOutputStream(path); outputStream.write(b, 0, length); inputStream.close(); outputStream.close(); filename = "../landImage/" + filename; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } JSONObject getObj = new JSONObject(); getObj.put("imgurl", filename); getObj.put("msg", "success"); return getObj.toString(); } @RequestMapping("/updateLayout_Info.do") public String updateLayout_Info(HttpServletRequest request, HttpServletResponse response, ModelMap map) throws IOException { String str = request.getParameter("layinfo"); int bid = Integer.valueOf(request.getParameter("bid")); int tag = Integer.valueOf(request.getParameter("tag")); String path1 = request.getSession().getServletContext().getRealPath(""); List<Layout_InfoView> list = new ArrayList<Layout_InfoView>(); Layout_InfoView view = null; String layoutStr = ""; String landinfoStr = ""; String flagStr = ""; if (tag == 0) { flagStr = landApplyServiceImpl.delLayout_info(bid, path1); } else { JSONArray obj = JSONArray.fromObject(str); for (int i = 0; i < obj.size(); i++) { JSONObject temp = obj.getJSONObject(i); landinfoStr += "('" + temp.getString("id") + "'," // 拼装土地信息 + temp.getInt("bid") + "," + Integer.valueOf(temp.getString("Afford")) + "," + temp.getInt("buildingArea") + "," + temp.getInt("landArea") + ",'" + temp.getString("lname") + "','" + temp.getString("plantingContent") + "','" + temp.getString("college") + "','" + temp.getString("img") + "'"; layoutStr += "(" + temp.getInt("bid") + "," // 拼装土地布局信息 + temp.getInt("height") + "," + temp.getInt("width") + "," + temp.getInt("x") + "," + temp.getInt("y") + ",'" + temp.getString("id") + "'"; if (i == obj.size() - 1) { landinfoStr += ")"; layoutStr += ")"; } else { landinfoStr += "),"; layoutStr += "),"; } } // landApplyServiceImpl.delLayout_info(bid,path1); flagStr = landApplyServiceImpl.updateLayInfo(landinfoStr, layoutStr, bid); } String str1 = "[{\"flag\":'" + flagStr + "'}]"; JSONArray json = JSONArray.fromObject(str1); response.getWriter().print(json.toString()); return null; } // 修改或更新租赁开始时间 @RequestMapping("/updateLandApplyDate.do") public String updateLandApplyDate(HttpServletRequest request, HttpServletResponse response, ModelMap map) { String planstime = request.getParameter("planstime"); String planetime = request.getParameter("planetime"); String rentstime = request.getParameter("rentstime"); String rentetime = request.getParameter("rentetime"); Long limitday = Long.valueOf(request.getParameter("limitday")); Startplan sp = new Startplan("zl", "土地租赁", planstime, planetime, rentstime, rentetime, limitday); landApplyServiceImpl.updateLandApplyDate(sp); JSONObject getObj = new JSONObject(); getObj.put("flag", true); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(getObj.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } // 获取租赁开始时间 @RequestMapping("/getLandApplyDate.do") public String getLandApplyDate(HttpServletRequest request, HttpServletResponse response, ModelMap map) { String plans = ""; String plane = ""; String rents = ""; String rente = ""; String limitday = ""; Startplan sp = landApplyServiceImpl.getStartPlan("zl"); if (sp != null) { plans = sp.getApply_start(); plane = sp.getApply_end(); rents = sp.getRent_start(); rente = sp.getRent_end(); limitday = String.valueOf(sp.getLimitday()); } JSONObject getObj = new JSONObject(); getObj.put("planstime", plans); getObj.put("planetime", plane); getObj.put("rentstime", rents); getObj.put("rentetime", rente); getObj.put("limitday", limitday); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(getObj.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping("/endLandApply.do") public String endLandApply(HttpServletRequest request, HttpServletResponse response, ModelMap map) { landApplyServiceImpl.endStartPlan(); JSONObject getObj = new JSONObject(); getObj.put("flag", true); response.setContentType("text/html;charset=UTF-8"); try { response.getWriter().print(getObj.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
Python
UTF-8
5,057
2.671875
3
[]
no_license
# Load the necessary libraries import numpy as np import json import pandas as pd from functions import similarity_check_Word2Vec, percentage_accuracy, CountFrequency # Deriving the list of random words csv1 = "data/random_single_lemma.csv" df_random_single_lemma = pd.read_csv(csv1) col = ['index', 'list'] df_random_single_lemma.columns = col random_list = df_random_single_lemma['list'] random_list = list(random_list) # Deriving the list of single_lemma_pair file = open('data/single_pair.json', 'r') single_lemma_pair = json.load(file) # Make sure that random list has no NAN value x = pd.Series(random_list) z = x[x.isnull()].index.to_list() for item in z: random_list[item] = random_list[3] # Number of random words generated on the fly for the algorithm and hence its length should be equal to number of words in single_lemma_pair # np.random.seed(412) # r_index = np.random.randint(low=0, high= len(random_list), size= len(single_lemma_pair)) # ohne_phrase = pd.Series(random_list) # random_list = (list(ohne_phrase[r_index])) # def similarity_check(): # """ # 1. This function performs a similarity check between random word and pair of words that belong to the same synset. # 2. This similarity check is performed under the assumption that by removing the "_" or "-" or other separators from the wordnet, # we can formulate a vector that is equivalent to words that map meaning conveued by multi-phrasal words # """ # sim_val_list = list() # nonsim_val_list = list() # counter = -1 # for x,y in zip(single_lemma_pair, random_list): # counter = counter + 1 # temp_1, temp_2 = x[0], x[1] # print(counter,temp_1, temp_2) # temp = temp_1.split("_") # temp.extend(temp_2.split("_")) # # print(temp) # vocab_absence = [0 for item in temp if item not in wv.vocab] # if not vocab_absence: # syn_sim = wv.n_similarity(temp_1.split('_'), temp_2.split('_')) #synset similarity # r_sim_1 = wv.n_similarity(temp_1.split('_'), y.split('_')) # random similarity with 1st word of pair and random word # r_sim_2 = wv.n_similarity(y.split('_'), temp_2.split('_')) # Random similarity between 2nd pair of word and random word # r_sim = r_sim_1 if(r_sim_1 > r_sim_2) else r_sim_2 # select the greater of above two similarity # if (syn_sim > r_sim): # sim_val_list.append(syn_sim) # else: # nonsim_val_list.append(r_sim) # if vocab_absence: # nonsim_val_list.append(-100) # return sim_val_list, nonsim_val_list x = 1 not_in_vocab, correct_pred, false_pred = similarity_check_Word2Vec(single_lemma_pair, random_list) # l=[0.234, 0.04325, 0.43134, 0.315, 0.6322, 0.245, 0.5325, 0.6341, 0.5214, 0.531, 0.124, 0.0252] # k = lambda x: int(x*10) # z = map(k, l) def percentage_per_bin(pred): import matplotlib.pyplot as plt total_size = len(pred) int_conv = lambda x: int(x*10) pred = list(map(int_conv, pred)) freq = {} for item in pred: if (item in freq): freq[item] += 1 else: freq[item] = 1 freq = dict(sorted(freq.items())) freq_val = [] for key, value in freq.items(): freq_val.append(value) percent = lambda x: (x / total_size * 100) percent_freq = list(map(percent, freq_val)) # fig = plt.figure() # ax = fig.add_axes([0, 0, 1, 1]) # x = [i*10 for i in range(1,11)] # ax.bar(x, percent_freq) plt.hist(percent_freq) plt.show() # return percent_freq, import seaborn as sns sns.distplot(correct_pred, color = "dodgerblue", label = "Word2vec") sns.distplot(correct_pred_2_0, color="orange", label="Fasttext") sns.distplot(correct_pred_3_0, color="deeppink", label="Glove") plt.show() percentage_per_bin(correct_pred) percentage_per_bin(false_pred) print("Case 1: When 1st word of pair is *support* and 2nd word is queried along with a random word") # calculating the accuracy in % print("Accuracy for correct predictions is: %.4f" %percentage_accuracy(len(correct_pred), len(false_pred))) print("Number of correct predictions is: %d" %len(correct_pred)) print("Number of incorrect predictions is: %d" %len(false_pred)) print("Number of words in synset pair not found in word2vec model is: %d" %len(not_in_vocab)) print(" ") # Running the analysis now for case 2 not_in_vocab, correct_pred, false_pred = similarity_check_Word2Vec(single_lemma_pair, random_list, 1) print("Case 2: When 2nd word of pair is *support* and 1st word is queried along with a random word") print("Accuracy for correct predictions is: %.4f" %percentage_accuracy(len(correct_pred), len(false_pred))) print("Number of correct predictions is: %d" %len(correct_pred)) print("Number of incorrect predictions is: %d" %len(false_pred)) print("Number of words in sysnset pair not found in word2vec model is: %d" %len(not_in_vocab)) print(" ") print("Task Finished") # x, y = similarity_check_1()
Python
UTF-8
34,906
2.625
3
[ "MIT" ]
permissive
__author__ = 'Todd.Hay' # ------------------------------------------------------------------------------- # Name: BcsReader # Purpose: # # Author: Todd.Hay # Email: Todd.Hay@noaa.gov # # Created: Mar 13, 2015 # License: New BSD # ------------------------------------------------------------------------------- """ This BcsReader class is used to get and parse the Bottom Contact Sensor (BCS) data. Note that there are two versions of the BCS: - AFSC BCS - This contains a single degree of freedom of tilt, with values from 0 to 90 degrees Values outside of this range are considered ???? invalid ???? - NWFSC/FRAM BCS - This contains two degrees of freedom, and X and a Y tilt. The angles range from -180 to 180 degrees, but are reported as 0 > 360 degrees. The NWFSC BCS can store 1MB of data on the datalogger. Given that there are 6 bytes of data per reading (3 for each angle), this yields about 44,000 readings for a full BCS data logger, which, collected at 1Hz, is about 12 hours of data """ import logging import os import re from dateutil import parser, tz from datetime import timedelta, datetime, timezone import time import serial import csv import math from threading import Thread import arrow # from pyCollector.Utilities import TimeConverter # from kivy.event import EventDispatcher # from kivy.logger import Logger BUFFER_LIMIT = 10000000 # class BcsReader(EventDispatcher): class BcsReader: """ Input parameters include: filename: name of the file to reader if file-based, None if otherwise raw_contents: text of the raw contents from a database bcs_type: old / new - specifying from the database whether the text is old style (AFSC) or new style (NWFSC) """ def __init__(self, filename=None, raw_content=None, bcs_type=None, serial_stream=False, position='', **kwargs): super(BcsReader, self).__init__(**kwargs) # TODO Todd Hay - Fix to send signals out # self.register_event_type("on_read_buffer") # self.register_event_type("on_byte_counter") # self.tc = TimeConverter() self.filename = filename self.content_list = [] self.position = position self.raw_content = raw_content self.priority_count = 1 self.is_streaming = False if raw_content: # Raw Content given, should be from the database format = 'database' elif self.filename: # Filename given, must open to retrieve the content self.raw_content = self.load_from_file() format = 'file' elif serial_stream: # Serial stream, open serial connection to get the content # self.raw_content = self.request_data_from_serial() format = 'serial' if self.raw_content is None: # try: # raise Exception('Invalid file type') # except Exception as ex: # print('exception:', ex) # return # TODO What is the proper way to return from the init and close out the file return self.sensor_type = self.validate_sensor_type() self.content_list = self.get_contents_as_list(format=format) @staticmethod def on_read_buffer(*args): pass @staticmethod def on_byte_counter(*args): pass def set_raw_content(self, raw_content=None, position=''): """ Method to reset the raw_content and continue the parsing. This is typically used during a database query operation when possibly multiple BCS files are retrieved from the database :param raw_content: :return: """ if not raw_content: return self.raw_content = raw_content format = 'database' self.position = position self.sensor_type = self.validate_sensor_type() self.content_list = self.get_contents_as_list(format=format) def validate_sensor_type(self): """ Method to check whether the BCS data is from an AFSC-designed sensor of a NWFSC-designed sensor :param contents: :return: """ # base, ext = os.path.splitext(self.filename) # ext = ext.strip('.') # if ext == 'hobo': # return None # try: # ascii = self.raw_content.decode('ascii') # except: # return None try: # Check for NWFSC file type - raw file if re.search('H\d{1,3}\s?L\d{5}', self.raw_content) and \ re.search('FF\d+FF', self.raw_content): # and \ # re.search('EE\d+EEZ{0,2}$', self.raw_content): # if len(self.content_list) == 2 and \ # re.match('^H\d{1,3}\s?L\d{5}', self.content_list[0]) and \ # re.match('^FF\d+FF', self.content_list[1]) and \ # re.search('EE\d+EEZ{0,2}$', self.content_list[1]): # TODO Could add another check to check the data size v. count and these should equal return 'nwfsc_txt' # Check for NWFSC file type - csv formatted file if 'xangle' in self.raw_content.lower() and \ 'yangle' in self.raw_content.lower() and \ 'bcs' in self.raw_content.lower(): return 'nwfsc_csv' # Check for AFSC file type elif 'plot title' in self.raw_content[0:1000].lower() and \ 'bottom' in self.raw_content[0:1000].lower() and \ 'date time' in self.raw_content[0:1000].lower(): # elif len(self.content_list) > 2 and \ # 'plot title' in ''.join([x.lower() for x in self.content_list[0]]) and \ # 'bottom' in ''.join([x.lower() for x in self.content_list[0]]) and \ # 'date time' in ''.join([x.lower() for x in self.content_list[1]]) and \ # len(self.content_list[1]) == len(self.content_list[2]): return 'afsc' return None except: return None def open_serial_connection(self, port=30, baudrate=19200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=False): """ Method to open the serial port connection to the NWFSC BCS shuttle :param baudrate: :param bytesize: :param parity: :param stopbits: :param xonxoff: :return: """ conn = None try: conn = serial.Serial(port=port, baudrate=baudrate, bytesize=bytesize, parity=parity, stopbits=stopbits, xonxoff=xonxoff) return conn except Exception as ex: if conn: conn.close() # self.dispatch('on_read_buffer', 'Error opening shuttle connection: ' + str(ex) + '\n\nThe shuttle has probably gone to sleep or needs to be reset.') return None def request_data_from_serial(self, comport=29, baudrate=19200): """ Method to send a command to the new FRAM BCS to request data to be downloaded :param conn: pyserial connection to the shuttle :return: """ conn = self.open_serial_connection(port=comport, baudrate=baudrate) if not conn: return self.bcs_serial_thread = Thread(target=self.serial_port_thread, kwargs=dict(conn=conn)) self.bcs_serial_thread.start() def validate_serial_port_download(self, byte_size=None): """ Method to validate that the NWFSC BCS that was downloaded is indeed valid :return: """ if self.raw_content is None: print('Failed to download the BCS data') # self.dispatch('on_read_buffer', 'failure', 'Failure - failed to download the BCS data') return footer = re.search('EE\d+EEZ{0,2}$', self.raw_content) status = False try: if footer is not None: if len(footer.group()) > 27: data_counts = int(footer.group()[22:27]) print('Data Counts:', data_counts) print('Stated Byte Size:', byte_size) if data_counts * 6 + 62 == byte_size: self.sensor_type = self.validate_sensor_type() self.content_list = self.get_contents_as_list(format='serial') # self.dispatch('on_read_buffer', 'success', True) print('Success in downloading the data, proceed to upload to DB') else: status = True else: status = True else: status = True except Exception as ex: # self.dispatch('on_read_buffer', 'failure', 'Error - error validating the BCS data size') print('Error validating the BCS final byte size:', ex) if status: # self.dispatch('on_read_buffer', 'failure', 'Error - error validating the BCS data size') print('Error validating the BCS final byte size:', ex) def serial_port_thread(self, conn=None): buffer = '' activate_reading = True is_byte_indicator_found = False is_header_found = False total_bytes = 0 current_byte_count = -1 mod_count = 0 wait_count = 5 time_delay = 0.050 start = time.clock() end = time.clock() is_successful = False self.is_streaming = True try: while True: # self.dispatch('on_byte_counter', len(buffer)-16) if not self.is_streaming: conn.close() break if total_bytes != 0 and current_byte_count >= total_bytes: print('total bytes reached, breaking...') break # if current_byte_count == total_bytes: # TODO Should I do this check? Is it too rigid? # Find the byte indicator of the file to get the overall byte count if not is_byte_indicator_found: byte_indicator = re.search('H\d{1,3}\s?L\d{5}', buffer) if byte_indicator: print('byte indicator:', byte_indicator.group()) total_bytes = self.get_byte_count(byte_string=byte_indicator.group()) print('total bytes:', str(total_bytes)) is_byte_indicator_found = True # self.dispatch('on_read_buffer', 'byte_indicator', total_bytes) # self.dispatch('on_read_buffer', 'byte_indicator_group', byte_indicator.group()) if not is_header_found: header = re.search('FF\d+FF', buffer) if header: # self.dispatch('on_read_buffer', 'header', header.group()) is_header_found = True # footer = re.search('EE\d+EEZ{0,2}$', buffer) footer = re.search('EE\d+EEZ{2}', buffer) if footer: print('successfully reach end of data, breaking...') print('buffer size:', len(buffer)) is_successful = True # self.dispatch('on_read_buffer', 'footer', footer.group()) break if re.search('ZZ', buffer): # If we find the end of the data stream, then break print('end of data reached, breaking...') print('buffer size:', len(buffer)) is_successful = False break if math.floor(current_byte_count / 100) > mod_count: # print('byte_count:', current_byte_count, '>', # 'buffer size:', len(buffer), # 'conn.inWaiting:', conn.inWaiting(), # buffer[current_byte_count-100:current_byte_count]) # self.dispatch('on_read_buffer', 'msg', buffer[current_byte_count-100:current_byte_count]) mod_count += 1 if conn.inWaiting() > BUFFER_LIMIT: # 10 MB file limit print('flushing input') conn.flushInput() if activate_reading: conn.flushInput() for i in range(wait_count): # w - wakes up the BCS device (need for it to have a solid green light conn.write('w'.encode()) time.sleep(time_delay) if 'OK' in conn.read(conn.inWaiting()).decode('ISO-8859-1'): conn.flushInput() # TODO Reset the time based on the computer clock # t - this returns the current time in the NWFSC BCS shuttle - from here one can enter # c to change the time or a space to skip changing the time conn.write('t'.encode()) time.sleep(time_delay) # c - this enters the change mode for the current time conn.write('c'.encode()) time.sleep(time_delay) now = datetime.now() now_date = now.strftime('%m%d%y') now_time = now.strftime('%H%M%S') # update the date in mmddyy format - no return characters needed, it only wants to see 6 numbers conn.write(now_date.encode()) time.sleep(time_delay) # update the time in hhmmss format - no return characters needed, it only wants to see 6 numbers conn.write(now_time.encode()) time.sleep(time_delay) break # conn.write('t'.encode()) # time.sleep(time_delay) # current_time = conn.read(conn.inWaiting()).decode('ISO-8859-1') # print('current time:', current_time) # conn.write(' '.encode()) # time.sleep(time_delay) conn.flushInput() conn.write('r'.encode()) activate_reading = False current_byte_count += conn.inWaiting() # print(current_byte_count) # current_data = conn.read(conn.inWaiting()).decode('ISO-8859-1') # current_data = re.sub(r"[\x01-\x1F\x7F\x80-\x9F]", "", current_data) # buffer += current_data # TODO Check that we only receive \x10\x130-9EFZ characters buffer += conn.read(conn.inWaiting()).decode('ISO-8859-1') conn.close() print('end of buffer:', buffer[-240:]) except Exception as ex: if "codec can't encode character" in str(ex): # self.dispatch('on_read_buffer', 'failure', 'Download interrupted. Please wait for shuttle to finish attempting to download and then try again.') print('Download interrupted. Please wait for shuttle to finish attempting to download and then try again.') else: print('Error downloading serial data:', ex) conn.close() end = time.clock() print('Time to download data:', end-start) self.raw_content = buffer # Call the method to validate that the download was indeed valid self.validate_serial_port_download(byte_size=total_bytes) def get_byte_count(self, byte_string=''): """ Method to return the byte count from the first line of the NWFSC BCS data file that is formatted as: H01 L56412 :param byte_string: :return: """ if byte_string == '': return byte_count_arr = [int(x.strip('\r\nH ')) if isinstance(int(x.strip('\r\nH ')), int) else None for x in byte_string.split('L')] return byte_count_arr[0]*65536 + byte_count_arr[1] def set_bcs_time(self): """ Method to reset the time on the NWFSC BCS shuttle :return: """ def load_from_file(self): """ Method to load the sensor file from disk. Used during the SensorFileUploadScreen :return: """ if not self.filename: return if not os.path.exists(self.filename): return try: f = open(self.filename, 'r') raw_content = f.read() f.close() except UnicodeDecodeError as ex: # print('Unicode Error:', ex) return None except Exception as ex: print('Exception Error:', ex) return None return raw_content def get_contents_as_list(self, format=None, sensor_type=None): """ Method to convert the raw_content into a list. The input parameter, format, will be :param format: file / database / serial - this defines the format of the input self.raw_content :param bcs_type: old / new - whether the format is older style (AFSC BCS) or newer style (NWFSC BCS) :return: """ contents = [] if format == 'file': # Data pulled from a file, so check the filename extension to determine if it a csv format or not base, ext = os.path.splitext(self.filename) if 'csv' in ext: reader = csv.reader(self.raw_content.splitlines(), quoting=csv.QUOTE_ALL, quotechar='"', delimiter=',') for row in reader: contents.append(row) else: try: reader = self.raw_content.splitlines() contents = [line.strip('\n') for line in reader if line.strip('\n') != ''] except AttributeError as ex: return None elif format == 'database': # Get the format from the database to determine if it is BCS OLD or BCS NEW formatted. BCS OLD are csv- # formatted files whereas BCS NEW are simple text files if self.sensor_type == 'afsc' or self.sensor_type == 'nwfsc_csv': reader = csv.reader(self.raw_content.splitlines(), quoting=csv.QUOTE_ALL, quotechar='"', delimiter=',') for row in reader: contents.append(row) elif self.sensor_type == 'nwfsc_txt': reader = self.raw_content.splitlines() contents = [line.strip('\n') for line in reader if line.strip('\n') != ''] elif format == 'serial': reader = self.raw_content.splitlines() contents = [line.strip('\n') for line in reader if line.strip('\n') != ''] return contents def get_raw_content(self): """ Method to return the raw_contents :return: """ return self.raw_content def get_start_datetime(self): """ Method to return the start datetime of the given file/contents :return: """ if self.content_list == []: return if self.sensor_type is None or self.sensor_type == '': return if self.sensor_type == 'afsc': header = self.content_list[1] data = self.content_list[2:len(self.content_list)] datetime_col = -1 for i, item in enumerate(header): if 'date time' in item.lower(): datetime_col = i tzone = item.split(',')[1].strip() offset_hour = '00:00' if 'gmt' in tzone.lower(): offset_hour = tzone.strip('GMT') # TODO Todd Hay - Confirm that I'm getting the correct date in local time zone start_datetime = arrow.get(data[0][datetime_col] + offset_hour) return start_datetime # start_datetime = parser.parse(data[0][datetime_col] + offset_hour) # return self.tc.local_to_utc(local_time=start_datetime) # return self.local_to_utc(local_time=start_datetime) else: continue # Keep looking for the date_time column logging.error('BcsReader: Did not find start "date_time" column in BCS header.') return None elif self.sensor_type == 'nwfsc_csv': return None elif self.sensor_type == 'nwfsc_txt': beginning = re.search('FF\d+FF', self.content_list[1]).group().strip('F') if beginning: if time.daylight: offset_hour = -time.altzone / 3600 else: offset_hour = -time.timezone / 3600 start_datetime = beginning[8:10] + '/' + beginning[10:12] + '/' + beginning[12:14] + \ ' ' + beginning[14:16] + ':' + beginning[16:18] + ':' + beginning[18:20] + \ ' ' + '%02d:00' % offset_hour start_datetime = arrow.get(start_datetime) return start_datetime # start_datetime = parser.parse(start_datetime) # return self.tc.local_to_utc(local_time=start_datetime) return None def get_end_datetime(self): """ Method to return the ending datetime of the data file :return: """ if self.content_list == []: return if self.sensor_type is None or self.sensor_type == '': return if self.sensor_type == 'afsc': header = self.content_list[1] data = self.content_list[2:len(self.content_list)] datetime_col = -1 for i, item in enumerate(header): if 'date time' in item.lower(): datetime_col = i timezone = item.split(',')[1].strip() offset_hour = '00:00' if 'gmt' in timezone.lower(): offset_hour = timezone.strip('GMT') end_datetime = arrow.get(data[len(data)-1][datetime_col] + offset_hour) return end_datetime # end_datetime = parser.parse(data[len(data)-1][datetime_col] + offset_hour) # return self.tc.local_to_utc(local_time=end_datetime) else: continue # Keep looking for the date_time column Logger.error('BcsReader: Did not find end "date_time" column in BCS header.') return None elif self.sensor_type == 'nwfsc_csv': return None elif self.sensor_type == 'nwfsc_txt': ending = re.search('EE\d+EEZ{0,2}', self.content_list[1]).group().strip('EZ') if ending: if time.daylight: offset_hour = -time.altzone / 3600 else: offset_hour = -time.timezone / 3600 end_datetime = ending[8:10] + '/' + ending[10:12] + '/' + ending[12:14] + \ ' ' + ending[14:16] + ':' + ending[16:18] + ':' + ending[18:20] + \ ' ' + '%02d:00' % offset_hour end_datetime = arrow.get(end_datetime) return end_datetime end_datetime = parser.parse(end_datetime) # return self.tc.local_to_utc(local_time=end_datetime) return None def parse_data(self, angles='x'): """ Method to initiate the parsing process. If first gets the contents of the file, then it checks to determine the type of file and passes the contents to the appropriate method based on the file type :param angles: x / xy - whether to return only the x angle or both the x and y angle (for the NWFSC BCS). If just the x angle, it bounds it between -10 <= x <= 100 so it doesn't throw Integrator out of whack when displaying it with the AFSC BCS data that has a range of 0 <= x <= 90 :return: """ if self.content_list == []: return tilt_values = [] if self.sensor_type == 'nwfsc_txt': tilt_values = self.parse_nwfsc_txt_bcs_data(angles=angles) elif self.sensor_type == 'nwfsc_csv': tilt_values = [] elif self.sensor_type == 'afsc': tilt_values = self.parse_afsc_bcs_data() else: print('sensor_type not found:', self.sensor_type) # Reformat the tilt_values into the common structure requested by DataParser tilt_dict = { 'priority': self.priority_count, 'format': 'Degrees', 'file': self.position, 'equipment': self.position, 'data': tilt_values } self.priority_count += 1 return self.position, tilt_dict def parse_afsc_bcs_data(self): """ Method to parse the contents of the AFSC-provided BCS data stream. This data uses the Onset Hoboware U22-001 data logger capability (http://www.onsetcomp.com/). The data is converted from a proprietary format to a csv file using the Hoboware software. The output CSV file has two columns of data consisting of date-time and temperature readings (that are in turn converted to tilt values). :param contents: :return: tilt_values: N x 2 array of date-time + tilt values """ metadata = self.content_list[0] header = self.content_list[1] data = self.content_list[2:len(self.content_list)] offset_hour = '00:00' datetime_col = -1 temp_col = -1 voltage_col = -1 bcs_offset_hack = 0 # hours for i, item in enumerate(header): if 'date time' in item.lower(): datetime_col = i tzone = item.split(',')[1].strip() if 'gmt' in tzone.lower(): offset_hour = tzone.strip('GMT') # FIELD-581 Confirm this fix is still required with newest version of Hoboware if offset_hour == '-08:00': offset_hour = '-07:00' logging.info('\t\t\t\tBCS Parsing. Offset hour switched to -07:00 to overcome Hoboware time zone issue') bcs_offset_hack = 1 # hour elif 'temp' in item.lower(): temp_col = i elif 'voltage' in item.lower(): voltage_col = i tilt_values = [] if datetime_col >= 0: for row in data: # date_time = parser.parse(row[datetime_col] + offset_hour).isoformat() #date_time = self.tc.local_to_utc_as_iso(local_time=parser.parse(row[datetime_col] + offset_hour)) # local_time = parser.parse(row[datetime_col] + offset_hour) + timedelta(hours=bcs_offset_hack) # date_time = self.tc.local_to_utc_as_iso(local_time=local_time) try: date_time = arrow.get(row[datetime_col] + offset_hour, 'MM/DD/YY hh:mm:ss AZZ').shift(hours=bcs_offset_hack).isoformat() except: logging.error(f"BcsReader error parsing date_time: {row[datetime_col]}, {offset_hour}") continue if voltage_col >= 0: try: voltage = float(row[voltage_col]) angle = self.convert_voltage_to_angle(voltage=voltage) except: continue elif temp_col >= 0: try: temp = float(row[temp_col]) angle = self.convert_temp_to_angle(temp=temp) except: continue else: continue if angle is not None: tilt_values.append([date_time, angle]) return tilt_values def convert_voltage_to_angle(self, voltage=None): """ Method to convert voltage readings to angle readings. This was once done when we knew how to directly read the Hoboware BCS voltage readings, but apparently Hoboware has change the format of the proprietary files such that we don't know how to do this anymore :param voltage: :return: """ if not voltage: return try: voltage = float(voltage) except: return if voltage <= 0: angle = 90 elif voltage > 0 and voltage <= 1516: angle = 90 - 0.02676 * voltage - 0.00006232 * math.pow(voltage, 2) elif voltage > 1516 and voltage <= 1530: angle = 477.69 - 0.2919 * voltage elif voltage > 1530 and voltage <= 2000: angle = 130.53 - 0.0650 * voltage elif voltage > 2000: angle = 0 return angle def convert_temp_to_angle(self, temp=None): """ Method to convert temperature readings to angle readings :param temp: :return: """ if not temp: return try: temp = float(temp) except: return # if temp < 75 or temp > 300: # return None if temp <= 79: angle = 0 elif temp <= 300: angle = -276.4028 + \ 5.728313 * temp + \ -0.03567424 * math.pow(temp, 2) + \ 0.0001011321 * math.pow(temp, 3) + \ -0.0000001080326 * math.pow(temp, 4) else: angle = 87 return angle def parse_nwfsc_txt_bcs_data(self, angles='x'): """ Method to parse the contents of the NWFSC/FRAM BCS data stream. The ascii data is passed in as the contents variable :param angles: x / xy - whether to return only the X or X and Y angles :return: tilt_values - N x 3 dimensional array of date-time, X tilt, Y tilt """ # byte_count_arr = [int(x.strip('\r\nH')) if int(x.strip('\r\nH')) else x.strip('\r\nH') # for x in self.content_list[0].split(' L')] # byte_count = byte_count_arr[0]*65536 + byte_count_arr[1] byte_count = self.get_byte_count(byte_string=self.content_list[0]) # print('Total byte size:', byte_count, 'bytes') beginning = re.search('FF\d+FF', self.content_list[1]).group().strip('F') ending = re.search('EE\d+EEZ{0,2}', self.content_list[1]).group().strip('EZ') count = ending[20:25] data = re.search('FF\d+EE', self.content_list[1]).group().strip('FE') # print('File Data:') # print('\tBeginning:', beginning) # print('\tEnding:', ending) # print('\tCount:', count) if time.daylight: offset_hour = -time.altzone / 3600 else: offset_hour = -time.timezone / 3600 # start_datetime = beginning[8:10] + '/' + beginning[10:12] + '/' + beginning[12:14] + \ # ' ' + beginning[14:16] + ':' + beginning[16:18] + ':' + beginning[18:20] + \ # ' ' + '%02d:00' % offset_hour # self.start_datetime = parser.parse(start_datetime) offset_hour = '%02d:00' % offset_hour offset_hour = "-07:00" self.start_datetime = arrow.get(beginning[8:20] + offset_hour, 'MMDDYYHHmmssZZ') # print('\nParsed Results: (Note: parsed times are in ISO format, UTC time zone (7 hours ahead)') # print('\tStart Date-Time:', self.start_datetime.isoformat()) # TODO Convert 2 angle values into 1 angle between 0 and 90 # Iterate through the data, turning it into a N x 3 lis tilt_values = [] current_datetime = self.start_datetime for values in re.findall(".{6}", data): if angles == 'x': value = int(values[0:3]) if 0 <= value < 270: value = 90 - value else: value = 450 - value # If the value is not between 0 <= x <= 359, then it is a bad value, indicate so # TODO # else: # value = 999 # Bad Data # Values have been converted between -179 <= x <= 180 # Set overall boundaries for what will be returned and plotted in Integrator if value < -10: value = -10 elif value > 100: value = 100 # tilt_values.append([current_datetime.astimezone().isoformat(), value]) tilt_values.append([current_datetime.isoformat(), value]) elif angles == 'xy': # tilt_values.append([current_datetime.astimezone().isoformat(), int(values[0:3])-180, int(values[3:6])-180]) tilt_values.append([current_datetime.isoformat(), int(values[0:3])-180, int(values[3:6])-180]) current_datetime.shift(seconds=1) # current_datetime += timedelta(seconds=1) # Format: date-time, X, Y # print(tilt_values) # print('angle:', angles) return tilt_values if __name__ == '__main__': folder = r'..\data\samples' filename = r'bcs_new\03_31_14_test.bin' # filename = r'bcs_new\03_30_14_test.bin' # filename = r'bcs_old\bcs_201403008004p.csv' # filename = r'bcs_old\bcs_201403008004s.csv' filename = os.path.join(folder, filename) # reader = open(file, 'r') # contents = reader.readlines() # reader.close() # bcs_reader = BcsReader(filename=filename) # bcs_reader.request_data_from_serial() bcs_reader = BcsReader(serial_stream=True) bcs_reader.request_data_from_serial() start = bcs_reader.get_start_datetime() end = bcs_reader.get_end_datetime() print(start, ">", end) tilt_values = bcs_reader.parse_data(angles='x') raw_content = bcs_reader.get_raw_content() print('raw content:', raw_content) if tilt_values: for x in tilt_values: print(x) pass print('\ttilt[0]:', tilt_values[0]) print('\ttilt[' + str(len(tilt_values)-1), ']:', tilt_values[len(tilt_values)-1]) print('\ttilt_values count:', len(tilt_values))
JavaScript
UTF-8
2,179
3.5
4
[]
no_license
//blockchain.js 모듈을 이곳에서 가져다 쓰겠다. const Blockchain = require('./blockchain'); //위에서 가져온 모듈의 객체를 만든다. const bitcoin = new Blockchain(); //제네시스 블락 console.log(bitcoin) //제네시스 블락 ! // Blockchain { // chain: // [ { index: 1, // timestamp: 1527475657742, // transactions: [], // nonce: 100, // hash: '0', // previousBlockHash: '0' } ], // pendingTransaction: [] } // const previousBlockHash = "abcdedferefa" // const currentBlockData = [ // { // amount: 10, // sender: 'BACKadffaaf', // recipient: 'HONGllalflks' // }, // { // amount: 20, // sender: 'PACKadffaaf', // recipient: 'HONGllalflks' // }, // { // amount: 30, // sender: 'PACKadffaaf', // recipient: 'HONGllalflks' // } // ] //pow 작업 //console.log(bitcoin.proofOfWork(previousBlockHash,currentBlockData)); //141237 //console.log(bitcoin.hashBlock(previousBlockHash,currentBlockData,141237)) //const nonce = 100; //console.log(bitcoin.hashBlock(previousBlockHash,currentBlockData,nonce)) //ec90a89a8364d8762ec3d365f2c8c91b1547af493e068009c119356b41f9699b /* //새로운 블락 만들기 bitcoin.createNewBlock(1111,"aaaaaaa","1a1a1a1a1a1a"); //새로은 트랜잭션 생성 - (총금액, 보내는이, 받는이) bitcoin.createNewTransaction(100,'PACKadffaaf','HONGllalflks') //새로운 블락 생성 - 채굴후 얻은 블락(마이닝) bitcoin.createNewBlock(2222,"bbbbbbb","2b2b2b2b2b2b"); //새로은 트랜잭션 생성2 - (총금액, 보내는이, 받는이) bitcoin.createNewTransaction(777,'PACKadffaaf','HONGllalflks') //새로은 트랜잭션 생성3 - (총금액, 보내는이, 받는이) bitcoin.createNewTransaction(888,'PACKadffaaf','HONGllalflks') //새로은 트랜잭션 생성4. - (총금액, 보내는이, 받는이) bitcoin.createNewTransaction(999,'PACKadffaaf','HONGllalflks') //새로운 블락 만들기 bitcoin.createNewBlock(3333,"ccccccc","3c3c3c3c3c3c"); //찍어보기 console.log(bitcoin.chain[2]) */
Markdown
UTF-8
4,483
2.625
3
[]
no_license
![Repository Status](https://img.shields.io/badge/Author-Ruben%20Tjok-blue) <h1 align="center">Hi 👋, I'm Ruben Tjok 👋🏼 👨🏻‍💻</h1> <img src="https://github.com/ruben-tjok/ruben-tjok/blob/main/Ruben-Tjok.png?raw=true" alt="banner that says Ruben Tjok - software engineer, content creator."> > A Pro-active minded, capable and committed Software Engineer with a proven ability to meet agreed deadlines and work to defined development methodologies within a structured environment. Focused on any task at hand and able to utilize existing development knowledge and experiences to come up with practical solutions and alternatives to development processes. Negotiating and communicating skills are my tools to provide guidance and advice to both in house and third party development teams. - 🌱 I’m currently learning **React and Flutter** - 👯 I’m looking to collaborate with **other content creators** - ⚡ Fun fact: **Coffee is Life** ☕ - 💼 Contact me on <a href="https://www.linkedin.com/in/tjok417/">LinkedIn</a> <img alt="Night Coding" src="https://raw.githubusercontent.com/AVS1508/AVS1508/master/assets/Night-Coding.gif" align="right"/> ### 🛠 &nbsp;Tech Stack ![Java](https://img.shields.io/badge/-Java-333333?style=flat&logo=Java&logoColor=FFA518)&nbsp; ![JavaScript](https://img.shields.io/badge/-JavaScript-333333?style=flat&logo=javascript)&nbsp; ![PHP](https://img.shields.io/badge/-PHP-333333?style=flat&logo=PHP)&nbsp; ![Laravel](https://img.shields.io/badge/-Laravel-333333?style=flat&logo=Laravel)&nbsp; ![R (Statistics)](https://img.shields.io/badge/-R-333333?style=flat&logo=R&logoColor=276DC3)\ ![React](https://img.shields.io/badge/-React-333333?style=flat&logo=react)&nbsp; ![Flutter](https://img.shields.io/badge/-Flutter-333333?style=flat&logo=Flutter)&nbsp; ![Node.js](https://img.shields.io/badge/-Node.js-333333?style=flat&logo=node.js)&nbsp; ![HTML](https://img.shields.io/badge/-HTML-333333?style=flat&logo=HTML5)&nbsp; ![CSS](https://img.shields.io/badge/-CSS-333333?style=flat&logo=CSS3&logoColor=1572B6)&nbsp; ![Bootstrap](https://img.shields.io/badge/-Bootstrap-333333?style=flat&logo=bootstrap&logoColor=563D7C)\ ![Git](https://img.shields.io/badge/-Git-333333?style=flat&logo=git)&nbsp; ![GitHub](https://img.shields.io/badge/-GitHub-333333?style=flat&logo=github)&nbsp; ![Markdown](https://img.shields.io/badge/-Markdown-333333?style=flat&logo=markdown)&nbsp; ![Visual Studio Code](https://img.shields.io/badge/-Visual%20Studio%20Code-333333?style=flat&logo=visual-studio-code&logoColor=007ACC)&nbsp; ![RStudio](https://img.shields.io/badge/-RStudio-333333?style=flat&logo=rstudio)\ ![Eclipse](https://img.shields.io/badge/-Eclipse-333333?style=flat&logo=eclipse-ide&logoColor=2C2255)&nbsp; ![Illustrator](https://img.shields.io/badge/-Illustrator-333333?style=flat&logo=adobe-illustrator)&nbsp; ![Photoshop](https://img.shields.io/badge/-Photoshop-333333?style=flat&logo=adobe-photoshop)&nbsp; ![InDesign](https://img.shields.io/badge/-InDesign-333333?style=flat&logo=adobe-indesign) ### ⚙️ &nbsp;GitHub Analytics <p align="center"> <a href="https://github.com/Ruben-Tjok"> <img height="180em" src="https://github-readme-stats-eight-theta.vercel.app/api?username=Ruben-Tjok&show_icons=true&theme=react&include_all_commits=true&count_private=true"/> <img height="180em" src="https://github-readme-stats-eight-theta.vercel.app/api/top-langs/?username=Ruben-Tjok&layout=compact&langs_count=8&theme=react"/> </a> </p> ### 🤝🏻 &nbsp;Connect with Me <p align="center"> <a href="https://www.visualboxsolutions.com"><img src="https://img.shields.io/badge/-visualboxsolutions.com-3423A6?style=flat-square&logo=Google-Chrome&logoColor=white"/></a> <a href="https://linkedin.com/in/tjok417"><img src="https://img.shields.io/badge/-tjok417-0077B5?style=flat-square&logo=Linkedin&logoColor=white"/></a> <a href="mailto:ruben_tjok@visualboxsolutions.com"><img src="https://img.shields.io/badge/-ruben_tjok@visualboxsolutions.com-D14836?style=flat-square&logo=Gmail&logoColor=white"/></a> <a href="https://www.instagram.com/visualboxsolutions/"><img src="https://img.shields.io/badge/-@visualboxsolutions-E4405F?style=flat-square&logo=Instagram&logoColor=white"/></a> <a href="https://www.facebook.com/ruben.janine.5/"><img src="https://img.shields.io/badge/-@ruben.janine.5-1877F2?style=flat-square&logo=Facebook&logoColor=white"/></a> </p> ### Visitors Count <img align="left" src = "https://profile-counter.glitch.me/Ruben-Tjok/count.svg" alt ="Loading">
Python
UTF-8
173
3.109375
3
[]
no_license
class Student(object): name = 'i am a student' dan = Student() dan.name='i am dan' print(dan.name) print(Student.name) del dan.name print(dan.name) print(Student.name)
Java
UTF-8
1,098
1.757813
2
[]
no_license
package com.legaoyi.storer.tjsatl.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.legaoyi.storer.dao.GeneralDao; import com.legaoyi.storer.service.GeneralService; import com.legaoyi.storer.util.Constants; @Transactional @Service(Constants.ELINK_MESSAGE_STORER_BEAN_PREFIX + "1212" + Constants.ELINK_MESSAGE_STORER_MESSAGE_SERVICE_BEAN_SUFFIX) public class Tjsatl_1212_MessageServiceImpl implements GeneralService { @Autowired @Qualifier(Constants.ELINK_MESSAGE_STORER_BEAN_PREFIX + "0801" + Constants.ELINK_MESSAGE_STORER_MESSAGE_DAO_BEAN_SUFFIX) private GeneralDao mediaDataDao; @Autowired @Qualifier("deviceUpMessageDao") private GeneralDao deviceUpMessageDao; @Override public void batchSave(List<?> list) throws Exception { mediaDataDao.batchSave(list); deviceUpMessageDao.batchSave(list); } }
C++
UTF-8
1,225
3.34375
3
[]
no_license
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { TreeNode * buildTree(vector<int> &inorder, int l1, int r1, vector<int> &postorder, int l2, int r2) { if (r1 - l1 == 1) { return new TreeNode(inorder[l1]); } else if (r1 == l1) { return NULL; } else { TreeNode * root = new TreeNode(postorder[r2 - 1]); int rootPos; for (int i = l1; i < r1; i++) { if (inorder[i] == postorder[r2 - 1]) { rootPos = i; break; } } root -> left = buildTree(inorder, l1, rootPos, postorder, l2, l2 + rootPos - l1); root -> right = buildTree(inorder, rootPos + 1, r1, postorder, l2 + rootPos - l1, r2 - 1); return root; } } public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { buildTree(inorder, 0, inorder.size(), postorder, 0, postorder.size()); } };
Java
UTF-8
35,290
2.015625
2
[ "MIT" ]
permissive
package com.github.enerccio.vaadin.fontawesome; import com.vaadin.server.FontIcon; import com.vaadin.server.GenericFontIcon; public enum FontAwesome implements FontAwesomeBase { BICYCLE("bicycle", 0xf206), CHURCH("church", 0xf51d), BOOK_READER("book-reader", 0xf5da), LAPTOP_HOUSE("laptop-house", 0xe066), ARROW_CIRCLE_UP("arrow-circle-up", 0xf0aa), HANUKIAH("hanukiah", 0xf6e6), MOON("moon", 0xf186), RESTROOM("restroom", 0xf7bd), GRIN_TONGUE_WINK("grin-tongue-wink", 0xf58b), FOLDER_MINUS("folder-minus", 0xf65d), ARROW_CIRCLE_DOWN("arrow-circle-down", 0xf0ab), MAP_SIGNS("map-signs", 0xf277), INFINITY("infinity", 0xf534), PLAY("play", 0xf04b), INBOX("inbox", 0xf01c), POOP("poop", 0xf619), COCKTAIL("cocktail", 0xf561), MONEY_CHECK_ALT("money-check-alt", 0xf53d), LUGGAGE_CART("luggage-cart", 0xf59d), PEPPER_HOT("pepper-hot", 0xf816), LIST("list", 0xf03a), RSS("rss", 0xf09e), HIPPO("hippo", 0xf6ed), VENUS("venus", 0xf221), HISTORY("history", 0xf1da), RANDOM("random", 0xf074), COLUMNS("columns", 0xf0db), WEIGHT_HANGING("weight-hanging", 0xf5cd), ARCHWAY("archway", 0xf557), EXCLAMATION_TRIANGLE("exclamation-triangle", 0xf071), GRIP_HORIZONTAL("grip-horizontal", 0xf58d), MEH_ROLLING_EYES("meh-rolling-eyes", 0xf5a5), FEATHER("feather", 0xf52d), THEATER_MASKS("theater-masks", 0xf630), PHONE_VOLUME("phone-volume", 0xf2a0), STEP_FORWARD("step-forward", 0xf051), MAIL_BULK("mail-bulk", 0xf674), STAR_HALF_ALT("star-half-alt", 0xf5c0), PENCIL_ALT("pencil-alt", 0xf303), UNLINK("unlink", 0xf127), TAGS("tags", 0xf02c), GRIP_LINES_VERTICAL("grip-lines-vertical", 0xf7a5), COMMENT_DOTS("comment-dots", 0xf4ad), HOLLY_BERRY("holly-berry", 0xf7aa), VOLUME_MUTE("volume-mute", 0xf6a9), PEOPLE_ARROWS("people-arrows", 0xe068), SORT_NUMERIC_DOWN_ALT("sort-numeric-down-alt", 0xf886), MAP("map", 0xf279), PHONE_SQUARE("phone-square", 0xf098), GREATER_THAN_EQUAL("greater-than-equal", 0xf532), CLOUD_UPLOAD_ALT("cloud-upload-alt", 0xf382), DUMBBELL("dumbbell", 0xf44b), UNDO_ALT("undo-alt", 0xf2ea), SKATING("skating", 0xf7c5), TV("tv", 0xf26c), WHEELCHAIR("wheelchair", 0xf193), TTY("tty", 0xf1e4), VIDEO_SLASH("video-slash", 0xf4e2), HOURGLASS_HALF("hourglass-half", 0xf252), PALLET("pallet", 0xf482), SKIING_NORDIC("skiing-nordic", 0xf7ca), HAND_ROCK("hand-rock", 0xf255), LINK("link", 0xf0c1), DRAFTING_COMPASS("drafting-compass", 0xf568), TREE("tree", 0xf1bb), USER_SLASH("user-slash", 0xf506), DOG("dog", 0xf6d3), DICE_TWO("dice-two", 0xf528), FROWN("frown", 0xf119), PENCIL_RULER("pencil-ruler", 0xf5ae), CHEVRON_LEFT("chevron-left", 0xf053), PAINT_BRUSH("paint-brush", 0xf1fc), PHONE_ALT("phone-alt", 0xf879), CALCULATOR("calculator", 0xf1ec), ALLERGIES("allergies", 0xf461), TOOLS("tools", 0xf7d9), TH("th", 0xf00a), SD_CARD("sd-card", 0xf7c2), HOUSE_DAMAGE("house-damage", 0xf6f1), PLAY_CIRCLE("play-circle", 0xf144), NETWORK_WIRED("network-wired", 0xf6ff), DNA("dna", 0xf471), TOILET("toilet", 0xf7d8), STREET_VIEW("street-view", 0xf21d), PLUS("plus", 0xf067), TABLET("tablet", 0xf10a), SHIPPING_FAST("shipping-fast", 0xf48b), DICE_D6("dice-d6", 0xf6d1), CLOUD_SHOWERS_HEAVY("cloud-showers-heavy", 0xf740), THUMBS_DOWN("thumbs-down", 0xf165), SHOPPING_BASKET("shopping-basket", 0xf291), MONEY_BILL_WAVE("money-bill-wave", 0xf53a), CLOUD_MOON_RAIN("cloud-moon-rain", 0xf73c), SLIDERS_H("sliders-h", 0xf1de), SPIDER("spider", 0xf717), CAMERA_RETRO("camera-retro", 0xf083), THERMOMETER("thermometer", 0xf491), QUESTION_CIRCLE("question-circle", 0xf059), MAP_MARKED_ALT("map-marked-alt", 0xf5a0), REDO_ALT("redo-alt", 0xf2f9), DUMPSTER_FIRE("dumpster-fire", 0xf794), PARKING("parking", 0xf540), FIST_RAISED("fist-raised", 0xf6de), DONATE("donate", 0xf4b9), HAT_WIZARD("hat-wizard", 0xf6e8), SORT_NUMERIC_UP_ALT("sort-numeric-up-alt", 0xf887), MICROPHONE_ALT("microphone-alt", 0xf3c9), DHARMACHAKRA("dharmachakra", 0xf655), RULER("ruler", 0xf545), HOCKEY_PUCK("hockey-puck", 0xf453), ETHERNET("ethernet", 0xf796), UNDERLINE("underline", 0xf0cd), RIBBON("ribbon", 0xf4d6), PERCENT("percent", 0xf295), ARROWS_ALT_H("arrows-alt-h", 0xf337), UNIVERSAL_ACCESS("universal-access", 0xf29a), DICE_ONE("dice-one", 0xf525), DEMOCRAT("democrat", 0xf747), LOCK("lock", 0xf023), SCROLL("scroll", 0xf70e), STAR_HALF("star-half", 0xf089), CHESS("chess", 0xf439), GRIN_HEARTS("grin-hearts", 0xf584), GLASS_WHISKEY("glass-whiskey", 0xf7a0), QRCODE("qrcode", 0xf029), CHESS_ROOK("chess-rook", 0xf447), FILE_EXCEL("file-excel", 0xf1c3), REGISTERED("registered", 0xf25d), MASK("mask", 0xf6fa), TIMES("times", 0xf00d), COINS("coins", 0xf51e), COMPACT_DISC("compact-disc", 0xf51f), HAND_HOLDING_MEDICAL("hand-holding-medical", 0xe05c), SNOWMAN("snowman", 0xf7d0), CALENDAR_WEEK("calendar-week", 0xf784), MOBILE("mobile", 0xf10b), REMOVE_FORMAT("remove-format", 0xf87d), SORT_ALPHA_UP("sort-alpha-up", 0xf15e), USER_INJURED("user-injured", 0xf728), SIGNAL("signal", 0xf012), NEWSPAPER("newspaper", 0xf1ea), TEMPERATURE_LOW("temperature-low", 0xf76b), BOLT("bolt", 0xf0e7), DRAW_POLYGON("draw-polygon", 0xf5ee), TINT_SLASH("tint-slash", 0xf5c7), ALIGN_LEFT("align-left", 0xf036), SIGN_OUT_ALT("sign-out-alt", 0xf2f5), BLIND("blind", 0xf29d), INFO("info", 0xf129), BOX("box", 0xf466), SHOPPING_BAG("shopping-bag", 0xf290), DICE("dice", 0xf522), ENVELOPE_SQUARE("envelope-square", 0xf199), SOCKS("socks", 0xf696), DOOR_OPEN("door-open", 0xf52b), RECYCLE("recycle", 0xf1b8), SYNC_ALT("sync-alt", 0xf2f1), SUITCASE("suitcase", 0xf0f2), STORE_ALT_SLASH("store-alt-slash", 0xe070), ID_CARD_ALT("id-card-alt", 0xf47f), MARKER("marker", 0xf5a1), SORT_NUMERIC_UP("sort-numeric-up", 0xf163), USER_ALT("user-alt", 0xf406), SHUTTLE_VAN("shuttle-van", 0xf5b6), MICROPHONE("microphone", 0xf130), ANGLE_UP("angle-up", 0xf106), SWIMMING_POOL("swimming-pool", 0xf5c5), MICROPHONE_SLASH("microphone-slash", 0xf131), CARET_SQUARE_UP("caret-square-up", 0xf151), CONCIERGE_BELL("concierge-bell", 0xf562), ALIGN_JUSTIFY("align-justify", 0xf039), STICKY_NOTE("sticky-note", 0xf249), SMOKING("smoking", 0xf48d), CHILD("child", 0xf1ae), HANDS_WASH("hands-wash", 0xe05e), PAUSE_CIRCLE("pause-circle", 0xf28b), PERCENTAGE("percentage", 0xf541), LAUGH("laugh", 0xf599), TAPE("tape", 0xf4db), MAP_MARKER_ALT("map-marker-alt", 0xf3c5), HAMBURGER("hamburger", 0xf805), GLASS_MARTINI_ALT("glass-martini-alt", 0xf57b), CAR("car", 0xf1b9), TOILET_PAPER_SLASH("toilet-paper-slash", 0xe072), MONUMENT("monument", 0xf5a6), BELL("bell", 0xf0f3), TRUCK_MOVING("truck-moving", 0xf4df), EXPAND("expand", 0xf065), HEAD_SIDE_COUGH("head-side-cough", 0xe061), PLANE_SLASH("plane-slash", 0xe069), BINOCULARS("binoculars", 0xf1e5), ANGLE_DOUBLE_DOWN("angle-double-down", 0xf103), PAW("paw", 0xf1b0), ICONS("icons", 0xf86d), QURAN("quran", 0xf687), TRUCK_LOADING("truck-loading", 0xf4de), PODCAST("podcast", 0xf2ce), INDUSTRY("industry", 0xf275), ANCHOR("anchor", 0xf13d), ID_CARD("id-card", 0xf2c2), BLENDER("blender", 0xf517), HOURGLASS_END("hourglass-end", 0xf253), GHOST("ghost", 0xf6e2), SQUARE("square", 0xf0c8), HAMSA("hamsa", 0xf665), X_RAY("x-ray", 0xf497), PHONE_SQUARE_ALT("phone-square-alt", 0xf87b), CHECK_CIRCLE("check-circle", 0xf058), BATH("bath", 0xf2cd), GRIN_TONGUE_SQUINT("grin-tongue-squint", 0xf58a), SIGNATURE("signature", 0xf5b7), THERMOMETER_EMPTY("thermometer-empty", 0xf2cb), BIRTHDAY_CAKE("birthday-cake", 0xf1fd), USER_SHIELD("user-shield", 0xf505), SAD_TEAR("sad-tear", 0xf5b4), HIKING("hiking", 0xf6ec), PEN_NIB("pen-nib", 0xf5ad), COMPRESS("compress", 0xf066), GRIN_WINK("grin-wink", 0xf58c), VIDEO("video", 0xf03d), CREDIT_CARD("credit-card", 0xf09d), CHALKBOARD("chalkboard", 0xf51b), HELICOPTER("helicopter", 0xf533), FILE_VIDEO("file-video", 0xf1c8), EJECT("eject", 0xf052), LUNGS("lungs", 0xf604), TEXT_HEIGHT("text-height", 0xf034), HOURGLASS_START("hourglass-start", 0xf251), MICROPHONE_ALT_SLASH("microphone-alt-slash", 0xf539), SUITCASE_ROLLING("suitcase-rolling", 0xf5c1), TRASH_RESTORE_ALT("trash-restore-alt", 0xf82a), SAVE("save", 0xf0c7), CHESS_BOARD("chess-board", 0xf43c), ENVELOPE("envelope", 0xf0e0), STOPWATCH_20("stopwatch-20", 0xe06f), PROJECT_DIAGRAM("project-diagram", 0xf542), USER_LOCK("user-lock", 0xf502), HIGHLIGHTER("highlighter", 0xf591), LANDMARK("landmark", 0xf66f), GRADUATION_CAP("graduation-cap", 0xf19d), HOSPITAL("hospital", 0xf0f8), MEH("meh", 0xf11a), HEADSET("headset", 0xf590), CALENDAR_CHECK("calendar-check", 0xf274), PASTE("paste", 0xf0ea), HAND_SCISSORS("hand-scissors", 0xf257), PRINT("print", 0xf02f), PLANE_ARRIVAL("plane-arrival", 0xf5af), SIGN_LANGUAGE("sign-language", 0xf2a7), STAMP("stamp", 0xf5bf), CROP_ALT("crop-alt", 0xf565), USER_PLUS("user-plus", 0xf234), LANGUAGE("language", 0xf1ab), EURO_SIGN("euro-sign", 0xf153), POUND_SIGN("pound-sign", 0xf154), RULER_VERTICAL("ruler-vertical", 0xf548), MARS_STROKE("mars-stroke", 0xf229), PLUS_CIRCLE("plus-circle", 0xf055), AWARD("award", 0xf559), BASEBALL_BALL("baseball-ball", 0xf433), SKIING("skiing", 0xf7c9), COMMENT_SLASH("comment-slash", 0xf4b3), ASSISTIVE_LISTENING_SYSTEMS("assistive-listening-systems", 0xf2a2), LESS_THAN_EQUAL("less-than-equal", 0xf537), SORT_AMOUNT_DOWN("sort-amount-down", 0xf160), MAP_MARKED("map-marked", 0xf59f), VOLUME_OFF("volume-off", 0xf026), HANDSHAKE_SLASH("handshake-slash", 0xe060), LOW_VISION("low-vision", 0xf2a8), HOSPITAL_SYMBOL("hospital-symbol", 0xf47e), FLUSHED("flushed", 0xf579), TASKS("tasks", 0xf0ae), MINUS_SQUARE("minus-square", 0xf146), OTTER("otter", 0xf700), BUSINESS_TIME("business-time", 0xf64a), FONT_AWESOME_LOGO_FULL("font-awesome-logo-full", 0xf4e6), GLASS_MARTINI("glass-martini", 0xf000), STREAM("stream", 0xf550), THUMBS_UP("thumbs-up", 0xf164), STRIKETHROUGH("strikethrough", 0xf0cc), STROOPWAFEL("stroopwafel", 0xf551), CUBES("cubes", 0xf1b3), MONEY_BILL_WAVE_ALT("money-bill-wave-alt", 0xf53b), CHESS_KNIGHT("chess-knight", 0xf441), HOUSE_USER("house-user", 0xe065), SPRAY_CAN("spray-can", 0xf5bd), FILL("fill", 0xf575), REPLY_ALL("reply-all", 0xf122), DOLLAR_SIGN("dollar-sign", 0xf155), DOWNLOAD("download", 0xf019), BACTERIA("bacteria", 0xe059), SWIMMER("swimmer", 0xf5c4), MOTORCYCLE("motorcycle", 0xf21c), WAREHOUSE("warehouse", 0xf494), BABY("baby", 0xf77c), SQUARE_ROOT_ALT("square-root-alt", 0xf698), SATELLITE("satellite", 0xf7bf), PLUS_SQUARE("plus-square", 0xf0fe), VOTE_YEA("vote-yea", 0xf772), FILE_MEDICAL_ALT("file-medical-alt", 0xf478), STORE_SLASH("store-slash", 0xe071), BOOK_DEAD("book-dead", 0xf6b7), HDD("hdd", 0xf0a0), RECORD_VINYL("record-vinyl", 0xf8d9), TIRED("tired", 0xf5c8), TOOTH("tooth", 0xf5c9), STORE_ALT("store-alt", 0xf54f), TH_LARGE("th-large", 0xf009), TRUCK("truck", 0xf0d1), CLOUD_DOWNLOAD_ALT("cloud-download-alt", 0xf381), AT("at", 0xf1fa), KISS_BEAM("kiss-beam", 0xf597), GRIN_STARS("grin-stars", 0xf587), IMAGES("images", 0xf302), GOPURAM("gopuram", 0xf664), FILL_DRIP("fill-drip", 0xf576), CITY("city", 0xf64f), MONEY_BILL("money-bill", 0xf0d6), AMERICAN_SIGN_LANGUAGE_INTERPRETING("american-sign-language-interpreting", 0xf2a3), LEMON("lemon", 0xf094), SERVER("server", 0xf233), VOLUME_UP("volume-up", 0xf028), FOLDER("folder", 0xf07b), LIST_OL("list-ol", 0xf0cb), USER_FRIENDS("user-friends", 0xf500), MOUNTAIN("mountain", 0xf6fc), SATELLITE_DISH("satellite-dish", 0xf7c0), VOLLEYBALL_BALL("volleyball-ball", 0xf45f), COFFEE("coffee", 0xf0f4), RETWEET("retweet", 0xf079), LIRA_SIGN("lira-sign", 0xf195), HEAD_SIDE_MASK("head-side-mask", 0xe063), WINE_GLASS_ALT("wine-glass-alt", 0xf5ce), GRIN_SQUINT("grin-squint", 0xf585), JOURNAL_WHILLS("journal-whills", 0xf66a), USER_TIE("user-tie", 0xf508), WIFI("wifi", 0xf1eb), TROPHY("trophy", 0xf091), SPA("spa", 0xf5bb), ROAD("road", 0xf018), UMBRELLA_BEACH("umbrella-beach", 0xf5ca), GRIN_SQUINT_TEARS("grin-squint-tears", 0xf586), ATLAS("atlas", 0xf558), HAND_LIZARD("hand-lizard", 0xf258), SUBWAY("subway", 0xf239), FILE_POWERPOINT("file-powerpoint", 0xf1c4), THERMOMETER_FULL("thermometer-full", 0xf2c7), FILE_AUDIO("file-audio", 0xf1c7), HRYVNIA("hryvnia", 0xf6f2), HEART_BROKEN("heart-broken", 0xf7a9), HEADING("heading", 0xf1dc), PEN_SQUARE("pen-square", 0xf14b), LONG_ARROW_ALT_UP("long-arrow-alt-up", 0xf30c), GREATER_THAN("greater-than", 0xf531), CAT("cat", 0xf6be), GRIN("grin", 0xf580), GAMEPAD("gamepad", 0xf11b), FIRE_ALT("fire-alt", 0xf7e4), WAVE_SQUARE("wave-square", 0xf83e), POLL_H("poll-h", 0xf682), HAND_POINT_UP("hand-point-up", 0xf0a6), GLOBE("globe", 0xf0ac), FILE_DOWNLOAD("file-download", 0xf56d), PLANE("plane", 0xf072), BRAILLE("braille", 0xf2a1), VIRUS_SLASH("virus-slash", 0xe075), FIGHTER_JET("fighter-jet", 0xf0fb), WALKING("walking", 0xf554), ROCKET("rocket", 0xf135), CALENDAR_ALT("calendar-alt", 0xf073), HARD_HAT("hard-hat", 0xf807), ERASER("eraser", 0xf12d), SEEDLING("seedling", 0xf4d8), THUMBTACK("thumbtack", 0xf08d), USER_EDIT("user-edit", 0xf4ff), BOLD("bold", 0xf032), SNOWPLOW("snowplow", 0xf7d2), CLOUD_MEATBALL("cloud-meatball", 0xf73b), EYE_DROPPER("eye-dropper", 0xf1fb), FILE_WORD("file-word", 0xf1c2), SKULL("skull", 0xf54c), FILE_ARCHIVE("file-archive", 0xf1c6), GRIN_BEAM_SWEAT("grin-beam-sweat", 0xf583), SURPRISE("surprise", 0xf5c2), ENVELOPE_OPEN_TEXT("envelope-open-text", 0xf658), PARACHUTE_BOX("parachute-box", 0xf4cd), HAND_POINTER("hand-pointer", 0xf25a), BORDER_ALL("border-all", 0xf84c), GRIN_TEARS("grin-tears", 0xf588), ARROW_ALT_CIRCLE_RIGHT("arrow-alt-circle-right", 0xf35a), FILTER("filter", 0xf0b0), AIR_FRESHENER("air-freshener", 0xf5d0), CHESS_BISHOP("chess-bishop", 0xf43a), FILE_SIGNATURE("file-signature", 0xf573), RADIATION_ALT("radiation-alt", 0xf7ba), FINGERPRINT("fingerprint", 0xf577), DICE_FIVE("dice-five", 0xf523), CAPSULES("capsules", 0xf46b), USER_ASTRONAUT("user-astronaut", 0xf4fb), TRAFFIC_LIGHT("traffic-light", 0xf637), TOILET_PAPER("toilet-paper", 0xf71e), BOOK("book", 0xf02d), DOLLY_FLATBED("dolly-flatbed", 0xf474), TSHIRT("tshirt", 0xf553), ASTERISK("asterisk", 0xf069), ARROW_UP("arrow-up", 0xf062), AMBULANCE("ambulance", 0xf0f9), LAYER_GROUP("layer-group", 0xf5fd), FEMALE("female", 0xf182), NOTES_MEDICAL("notes-medical", 0xf481), WINDOW_RESTORE("window-restore", 0xf2d2), SHIELD_ALT("shield-alt", 0xf3ed), ARROW_DOWN("arrow-down", 0xf063), COMMENT_MEDICAL("comment-medical", 0xf7f5), TAG("tag", 0xf02b), PRAY("pray", 0xf683), DRUM("drum", 0xf569), PALETTE("palette", 0xf53f), BUS_ALT("bus-alt", 0xf55e), DOLLY("dolly", 0xf472), MOSQUE("mosque", 0xf678), TORAH("torah", 0xf6a0), VENUS_MARS("venus-mars", 0xf228), BACON("bacon", 0xf7e5), FILE_MEDICAL("file-medical", 0xf477), BATTERY_THREE_QUARTERS("battery-three-quarters", 0xf241), REPLY("reply", 0xf3e5), TOGGLE_ON("toggle-on", 0xf205), HAND_HOLDING("hand-holding", 0xf4bd), OUTDENT("outdent", 0xf03b), CARET_SQUARE_RIGHT("caret-square-right", 0xf152), CHESS_PAWN("chess-pawn", 0xf443), WINE_BOTTLE("wine-bottle", 0xf72f), ANGLE_DOUBLE_LEFT("angle-double-left", 0xf100), FUNNEL_DOLLAR("funnel-dollar", 0xf662), SORT("sort", 0xf0dc), LAPTOP("laptop", 0xf109), CART_PLUS("cart-plus", 0xf217), COMMENTS("comments", 0xf086), CARET_SQUARE_DOWN("caret-square-down", 0xf150), GOLF_BALL("golf-ball", 0xf450), CAR_BATTERY("car-battery", 0xf5df), LONG_ARROW_ALT_LEFT("long-arrow-alt-left", 0xf30a), WINDOW_MAXIMIZE("window-maximize", 0xf2d0), DICE_D20("dice-d20", 0xf6cf), ARROW_LEFT("arrow-left", 0xf060), HANDSHAKE_ALT_SLASH("handshake-alt-slash", 0xe05f), HASHTAG("hashtag", 0xf292), COPYRIGHT("copyright", 0xf1f9), CHEVRON_CIRCLE_LEFT("chevron-circle-left", 0xf137), BOOK_MEDICAL("book-medical", 0xf7e6), SLASH("slash", 0xf715), SMOG("smog", 0xf75f), HEAD_SIDE_VIRUS("head-side-virus", 0xe064), USER_NURSE("user-nurse", 0xf82f), USERS_SLASH("users-slash", 0xe073), FILE_UPLOAD("file-upload", 0xf574), KISS_WINK_HEART("kiss-wink-heart", 0xf598), SMILE("smile", 0xf118), STOP_CIRCLE("stop-circle", 0xf28d), CHEVRON_CIRCLE_RIGHT("chevron-circle-right", 0xf138), STAR_OF_DAVID("star-of-david", 0xf69a), FISH("fish", 0xf578), GLOBE_ASIA("globe-asia", 0xf57e), SHOE_PRINTS("shoe-prints", 0xf54b), USER_CHECK("user-check", 0xf4fc), USER_CLOCK("user-clock", 0xf4fd), PILLS("pills", 0xf484), BAND_AID("band-aid", 0xf462), HOT_TUB("hot-tub", 0xf593), HOME("home", 0xf015), USER_CIRCLE("user-circle", 0xf2bd), COOKIE_BITE("cookie-bite", 0xf564), CALENDAR_MINUS("calendar-minus", 0xf272), INDENT("indent", 0xf03c), HAND_SPOCK("hand-spock", 0xf259), HEART("heart", 0xf004), SYNC("sync", 0xf021), KHANDA("khanda", 0xf66d), BALANCE_SCALE("balance-scale", 0xf24e), DOOR_CLOSED("door-closed", 0xf52a), BIBLE("bible", 0xf647), MOBILE_ALT("mobile-alt", 0xf3cd), RUPEE_SIGN("rupee-sign", 0xf156), FILE_CONTRACT("file-contract", 0xf56c), GRIMACE("grimace", 0xf57f), CROP("crop", 0xf125), EQUALS("equals", 0xf52c), CRUTCH("crutch", 0xf7f7), SMILE_BEAM("smile-beam", 0xf5b8), MUSIC("music", 0xf001), DIRECTIONS("directions", 0xf5eb), CARROT("carrot", 0xf787), ADDRESS_CARD("address-card", 0xf2bb), FLASK("flask", 0xf0c3), SMS("sms", 0xf7cd), ALIGN_RIGHT("align-right", 0xf038), SHIP("ship", 0xf21a), METEOR("meteor", 0xf753), TRACTOR("tractor", 0xf722), EXPAND_ALT("expand-alt", 0xf424), ATOM("atom", 0xf5d2), CLOUD_SUN_RAIN("cloud-sun-rain", 0xf743), CUBE("cube", 0xf1b2), OBJECT_GROUP("object-group", 0xf247), FROG("frog", 0xf52e), HORSE_HEAD("horse-head", 0xf7ab), SLEIGH("sleigh", 0xf7cc), CHART_LINE("chart-line", 0xf201), PEOPLE_CARRY("people-carry", 0xf4ce), HORSE("horse", 0xf6f0), TRAIN("train", 0xf238), LESS_THAN("less-than", 0xf536), STEP_BACKWARD("step-backward", 0xf048), LONG_ARROW_ALT_DOWN("long-arrow-alt-down", 0xf309), FEATHER_ALT("feather-alt", 0xf56b), RAINBOW("rainbow", 0xf75b), FROWN_OPEN("frown-open", 0xf57a), CAR_SIDE("car-side", 0xf5e4), COPY("copy", 0xf0c5), COMMENTS_DOLLAR("comments-dollar", 0xf653), COMMENT_ALT("comment-alt", 0xf27a), QUOTE_RIGHT("quote-right", 0xf10e), TABLE("table", 0xf0ce), TEETH_OPEN("teeth-open", 0xf62f), SMILE_WINK("smile-wink", 0xf4da), DESKTOP("desktop", 0xf108), FIRE_EXTINGUISHER("fire-extinguisher", 0xf134), RSS_SQUARE("rss-square", 0xf143), FLAG("flag", 0xf024), BULLSEYE("bullseye", 0xf140), UTENSILS("utensils", 0xf2e7), FILE_IMAGE("file-image", 0xf1c5), UTENSIL_SPOON("utensil-spoon", 0xf2e5), LOCATION_ARROW("location-arrow", 0xf124), BLENDER_PHONE("blender-phone", 0xf6b6), BRIEFCASE("briefcase", 0xf0b1), CALENDAR_PLUS("calendar-plus", 0xf271), HANDS("hands", 0xf4c2), SCREWDRIVER("screwdriver", 0xf54a), ANKH("ankh", 0xf644), LEAF("leaf", 0xf06c), PAPER_PLANE("paper-plane", 0xf1d8), EXCLAMATION("exclamation", 0xf12a), SEARCH("search", 0xf002), PEACE("peace", 0xf67c), SWATCHBOOK("swatchbook", 0xf5c3), FILE("file", 0xf15b), COMPASS("compass", 0xf14e), ARCHIVE("archive", 0xf187), ANGLE_DOWN("angle-down", 0xf107), USER_COG("user-cog", 0xf4fe), QUIDDITCH("quidditch", 0xf458), SHAPES("shapes", 0xf61f), TEXT_WIDTH("text-width", 0xf035), CHEVRON_DOWN("chevron-down", 0xf078), ANGRY("angry", 0xf556), ROUTE("route", 0xf4d7), SPINNER("spinner", 0xf110), ICE_CREAM("ice-cream", 0xf810), GEM("gem", 0xf3a5), FONT("font", 0xf031), DIZZY("dizzy", 0xf567), MICROCHIP("microchip", 0xf2db), BED("bed", 0xf236), ANGLE_RIGHT("angle-right", 0xf105), HANDSHAKE("handshake", 0xf2b5), CHEESE("cheese", 0xf7ef), CARET_UP("caret-up", 0xf0d8), CASH_REGISTER("cash-register", 0xf788), HAND_POINT_LEFT("hand-point-left", 0xf0a5), GLOBE_AMERICAS("globe-americas", 0xf57d), SPLOTCH("splotch", 0xf5bc), VIHARA("vihara", 0xf6a7), GLOBE_EUROPE("globe-europe", 0xf7a2), SORT_UP("sort-up", 0xf0de), VOLUME_DOWN("volume-down", 0xf027), COMMENT_DOLLAR("comment-dollar", 0xf651), SNOWBOARDING("snowboarding", 0xf7ce), HEARTBEAT("heartbeat", 0xf21e), MEDAL("medal", 0xf5a2), WINE_GLASS("wine-glass", 0xf4e3), CLOSED_CAPTIONING("closed-captioning", 0xf20a), SHIELD_VIRUS("shield-virus", 0xe06c), TRADEMARK("trademark", 0xf25c), WRENCH("wrench", 0xf0ad), TRANSGENDER("transgender", 0xf224), WEIGHT("weight", 0xf496), CODE_BRANCH("code-branch", 0xf126), PUZZLE_PIECE("puzzle-piece", 0xf12e), SYRINGE("syringe", 0xf48e), HAND_SPARKLES("hand-sparkles", 0xe05d), DISEASE("disease", 0xf7fa), BATTERY_QUARTER("battery-quarter", 0xf243), DUMPSTER("dumpster", 0xf793), CARAVAN("caravan", 0xf8ff), MICROSCOPE("microscope", 0xf610), PLUG("plug", 0xf1e6), ELLIPSIS_H("ellipsis-h", 0xf141), LIST_ALT("list-alt", 0xf022), WON_SIGN("won-sign", 0xf159), FOOTBALL_BALL("football-ball", 0xf44e), BONE("bone", 0xf5d7), LAPTOP_CODE("laptop-code", 0xf5fc), CHART_BAR("chart-bar", 0xf080), SORT_ALPHA_UP_ALT("sort-alpha-up-alt", 0xf882), USER_GRADUATE("user-graduate", 0xf501), MARS_STROKE_H("mars-stroke-h", 0xf22b), SOAP("soap", 0xe06e), HEADPHONES("headphones", 0xf025), GRIN_BEAM("grin-beam", 0xf582), HAND_HOLDING_USD("hand-holding-usd", 0xf4c0), CHESS_KING("chess-king", 0xf43f), SITEMAP("sitemap", 0xf0e8), FAUCET("faucet", 0xe005), STETHOSCOPE("stethoscope", 0xf0f1), ID_BADGE("id-badge", 0xf2c1), CALENDAR("calendar", 0xf133), YIN_YANG("yin-yang", 0xf6ad), SIGN("sign", 0xf4d9), HAND_MIDDLE_FINGER("hand-middle-finger", 0xf806), TABLETS("tablets", 0xf490), BLOG("blog", 0xf781), BRIEFCASE_MEDICAL("briefcase-medical", 0xf469), DIAGNOSES("diagnoses", 0xf470), POLL("poll", 0xf681), USER("user", 0xf007), BALANCE_SCALE_LEFT("balance-scale-left", 0xf515), FOLDER_PLUS("folder-plus", 0xf65e), BASKETBALL_BALL("basketball-ball", 0xf434), HAND_PAPER("hand-paper", 0xf256), CHECK_SQUARE("check-square", 0xf14a), CIRCLE_NOTCH("circle-notch", 0xf1ce), GRIP_VERTICAL("grip-vertical", 0xf58e), CLIPBOARD_CHECK("clipboard-check", 0xf46c), LAUGH_SQUINT("laugh-squint", 0xf59b), SINK("sink", 0xe06d), CHARGING_STATION("charging-station", 0xf5e7), TEETH("teeth", 0xf62e), CHEVRON_RIGHT("chevron-right", 0xf054), CROSS("cross", 0xf654), TOOLBOX("toolbox", 0xf552), SHOPPING_CART("shopping-cart", 0xf07a), NOT_EQUAL("not-equal", 0xf53e), HANDS_HELPING("hands-helping", 0xf4c4), TRANSGENDER_ALT("transgender-alt", 0xf225), TRUCK_PICKUP("truck-pickup", 0xf63c), FAST_BACKWARD("fast-backward", 0xf049), EDIT("edit", 0xf044), ANGLE_LEFT("angle-left", 0xf104), COMPRESS_ALT("compress-alt", 0xf422), USER_NINJA("user-ninja", 0xf504), MARS("mars", 0xf222), CROW("crow", 0xf520), THERMOMETER_QUARTER("thermometer-quarter", 0xf2ca), GRIN_ALT("grin-alt", 0xf581), HOSPITAL_USER("hospital-user", 0xf80d), BONG("bong", 0xf55c), TRASH_ALT("trash-alt", 0xf2ed), HOURGLASS("hourglass", 0xf254), CHAIR("chair", 0xf6c0), LEVEL_UP_ALT("level-up-alt", 0xf3bf), ANGLE_DOUBLE_UP("angle-double-up", 0xf102), STAR("star", 0xf005), PRESCRIPTION_BOTTLE("prescription-bottle", 0xf485), BOOK_OPEN("book-open", 0xf518), LOCK_OPEN("lock-open", 0xf3c1), FIRE("fire", 0xf06d), PLANE_DEPARTURE("plane-departure", 0xf5b0), PAUSE("pause", 0xf04c), FILE_PRESCRIPTION("file-prescription", 0xf572), DIVIDE("divide", 0xf529), HOSPITAL_ALT("hospital-alt", 0xf47d), TINT("tint", 0xf043), HEADPHONES_ALT("headphones-alt", 0xf58f), DEAF("deaf", 0xf2a4), COMPRESS_ARROWS_ALT("compress-arrows-alt", 0xf78c), HAND_PEACE("hand-peace", 0xf25b), SIM_CARD("sim-card", 0xf7c4), CHECK_DOUBLE("check-double", 0xf560), BEZIER_CURVE("bezier-curve", 0xf55b), BORDER_NONE("border-none", 0xf850), SORT_AMOUNT_UP("sort-amount-up", 0xf161), EGG("egg", 0xf7fb), SMOKING_BAN("smoking-ban", 0xf54d), POWER_OFF("power-off", 0xf011), BOMB("bomb", 0xf1e2), CHECK("check", 0xf00c), SUN("sun", 0xf185), GRIP_LINES("grip-lines", 0xf7a4), BIOHAZARD("biohazard", 0xf780), CROSSHAIRS("crosshairs", 0xf05b), SORT_AMOUNT_UP_ALT("sort-amount-up-alt", 0xf885), HOTEL("hotel", 0xf594), FLAG_CHECKERED("flag-checkered", 0xf11e), PAPERCLIP("paperclip", 0xf0c6), MAP_PIN("map-pin", 0xf276), FUTBOL("futbol", 0xf1e3), TIMES_CIRCLE("times-circle", 0xf057), ARROW_CIRCLE_RIGHT("arrow-circle-right", 0xf0a9), PHOTO_VIDEO("photo-video", 0xf87c), BULLHORN("bullhorn", 0xf0a1), CLOUD_RAIN("cloud-rain", 0xf73d), QUOTE_LEFT("quote-left", 0xf10d), GIFT("gift", 0xf06b), BOXES("boxes", 0xf468), UMBRELLA("umbrella", 0xf0e9), UNDO("undo", 0xf0e2), USER_ALT_SLASH("user-alt-slash", 0xf4fa), ARROW_ALT_CIRCLE_LEFT("arrow-alt-circle-left", 0xf359), FILE_INVOICE_DOLLAR("file-invoice-dollar", 0xf571), ADDRESS_BOOK("address-book", 0xf2b9), FILM("film", 0xf008), EXTERNAL_LINK_SQUARE_ALT("external-link-square-alt", 0xf360), SCHOOL("school", 0xf549), DICE_THREE("dice-three", 0xf527), UNLOCK_ALT("unlock-alt", 0xf13e), PRESCRIPTION_BOTTLE_ALT("prescription-bottle-alt", 0xf486), RULER_HORIZONTAL("ruler-horizontal", 0xf547), HAND_HOLDING_WATER("hand-holding-water", 0xf4c1), HAND_HOLDING_HEART("hand-holding-heart", 0xf4be), JEDI("jedi", 0xf669), PEN_ALT("pen-alt", 0xf305), MUG_HOT("mug-hot", 0xf7b6), ARROW_ALT_CIRCLE_DOWN("arrow-alt-circle-down", 0xf358), VENUS_DOUBLE("venus-double", 0xf226), VECTOR_SQUARE("vector-square", 0xf5cb), SOLAR_PANEL("solar-panel", 0xf5ba), ANGLE_DOUBLE_RIGHT("angle-double-right", 0xf101), SHEKEL_SIGN("shekel-sign", 0xf20b), FILE_EXPORT("file-export", 0xf56e), SEARCH_DOLLAR("search-dollar", 0xf688), AD("ad", 0xf641), REPUBLICAN("republican", 0xf75e), BABY_CARRIAGE("baby-carriage", 0xf77d), GRIN_TONGUE("grin-tongue", 0xf589), ROBOT("robot", 0xf544), TRASH("trash", 0xf1f8), CAMPGROUND("campground", 0xf6bb), BRUSH("brush", 0xf55d), VR_CARDBOARD("vr-cardboard", 0xf729), BEER("beer", 0xf0fc), EYE("eye", 0xf06e), PLACE_OF_WORSHIP("place-of-worship", 0xf67f), DICE_SIX("dice-six", 0xf526), CHEVRON_CIRCLE_UP("chevron-circle-up", 0xf139), COG("cog", 0xf013), FOLDER_OPEN("folder-open", 0xf07c), CART_ARROW_DOWN("cart-arrow-down", 0xf218), CANNABIS("cannabis", 0xf55f), VIRUS("virus", 0xe074), THERMOMETER_HALF("thermometer-half", 0xf2c9), MARS_STROKE_V("mars-stroke-v", 0xf22a), CARET_DOWN("caret-down", 0xf0d7), COGS("cogs", 0xf085), BUG("bug", 0xf188), CLIPBOARD("clipboard", 0xf328), POO("poo", 0xf2fe), USER_MD("user-md", 0xf0f0), TORII_GATE("torii-gate", 0xf6a1), BAN("ban", 0xf05e), CROWN("crown", 0xf521), SHARE_ALT_SQUARE("share-alt-square", 0xf1e1), PASSPORT("passport", 0xf5ab), CERTIFICATE("certificate", 0xf0a3), BATTERY_FULL("battery-full", 0xf240), EXPAND_ARROWS_ALT("expand-arrows-alt", 0xf31e), MEMORY("memory", 0xf538), ELLIPSIS_V("ellipsis-v", 0xf142), TEMPERATURE_HIGH("temperature-high", 0xf769), EXCHANGE_ALT("exchange-alt", 0xf362), POO_STORM("poo-storm", 0xf75a), HOTDOG("hotdog", 0xf80f), MORTAR_PESTLE("mortar-pestle", 0xf5a7), DICE_FOUR("dice-four", 0xf524), LEVEL_DOWN_ALT("level-down-alt", 0xf3be), USER_TIMES("user-times", 0xf235), MITTEN("mitten", 0xf7b5), MEDKIT("medkit", 0xf0fa), PASTAFARIANISM("pastafarianism", 0xf67b), CHART_PIE("chart-pie", 0xf200), CHART_AREA("chart-area", 0xf1fe), NEUTER("neuter", 0xf22c), ADJUST("adjust", 0xf042), BACKWARD("backward", 0xf04a), PROCEDURES("procedures", 0xf487), BAHAI("bahai", 0xf666), TRAM("tram", 0xf7da), FAX("fax", 0xf1ac), GAS_PUMP("gas-pump", 0xf52f), SORT_ALPHA_DOWN("sort-alpha-down", 0xf15d), SNOWFLAKE("snowflake", 0xf2dc), MARS_DOUBLE("mars-double", 0xf227), ITALIC("italic", 0xf033), MAGNET("magnet", 0xf076), CLINIC_MEDICAL("clinic-medical", 0xf7f2), RECEIPT("receipt", 0xf543), BARS("bars", 0xf0c9), SAD_CRY("sad-cry", 0xf5b3), OIL_CAN("oil-can", 0xf613), WIND("wind", 0xf72e), IGLOO("igloo", 0xf7ae), FAN("fan", 0xf863), APPLE_ALT("apple-alt", 0xf5d1), VIALS("vials", 0xf493), GAVEL("gavel", 0xf0e3), COUCH("couch", 0xf4b8), UPLOAD("upload", 0xf093), LIFE_RING("life-ring", 0xf1cd), KISS("kiss", 0xf596), YEN_SIGN("yen-sign", 0xf157), KAABA("kaaba", 0xf66b), KEY("key", 0xf084), PUMP_MEDICAL("pump-medical", 0xe06a), TERMINAL("terminal", 0xf120), AUDIO_DESCRIPTION("audio-description", 0xf29e), STOPWATCH("stopwatch", 0xf2f2), ENVELOPE_OPEN("envelope-open", 0xf2b6), TOGGLE_OFF("toggle-off", 0xf204), KEYBOARD("keyboard", 0xf11c), CLOUD("cloud", 0xf0c2), VOICEMAIL("voicemail", 0xf897), BOWLING_BALL("bowling-ball", 0xf436), MALE("male", 0xf183), SEARCH_PLUS("search-plus", 0xf00e), STAR_AND_CRESCENT("star-and-crescent", 0xf699), FILE_ALT("file-alt", 0xf15c), USER_TAG("user-tag", 0xf507), DRAGON("dragon", 0xf6d5), FAST_FORWARD("fast-forward", 0xf050), PIGGY_BANK("piggy-bank", 0xf4d3), LAPTOP_MEDICAL("laptop-medical", 0xf812), KIWI_BIRD("kiwi-bird", 0xf535), ARROWS_ALT_V("arrows-alt-v", 0xf338), OBJECT_UNGROUP("object-ungroup", 0xf248), GUITAR("guitar", 0xf7a6), MONEY_CHECK("money-check", 0xf53c), CLONE("clone", 0xf24d), MENORAH("menorah", 0xf676), HEAD_SIDE_COUGH_SLASH("head-side-cough-slash", 0xe062), MINUS_CIRCLE("minus-circle", 0xf056), IMAGE("image", 0xf03e), CAMERA("camera", 0xf030), RULER_COMBINED("ruler-combined", 0xf546), PRAYING_HANDS("praying-hands", 0xf684), BALANCE_SCALE_RIGHT("balance-scale-right", 0xf516), UNLOCK("unlock", 0xf09c), LONG_ARROW_ALT_RIGHT("long-arrow-alt-right", 0xf30b), WATER("water", 0xf773), HAND_POINT_DOWN("hand-point-down", 0xf0a7), PERSON_BOOTH("person-booth", 0xf756), CALENDAR_TIMES("calendar-times", 0xf273), CHEVRON_UP("chevron-up", 0xf077), PARAGRAPH("paragraph", 0xf1dd), CAR_ALT("car-alt", 0xf5de), GENDERLESS("genderless", 0xf22d), MERCURY("mercury", 0xf223), SPELL_CHECK("spell-check", 0xf891), STOP("stop", 0xf04d), TAXI("taxi", 0xf1ba), BACKSPACE("backspace", 0xf55a), CLOUD_SUN("cloud-sun", 0xf6c4), BOX_TISSUE("box-tissue", 0xe05b), SORT_DOWN("sort-down", 0xf0dd), HAT_COWBOY("hat-cowboy", 0xf8c0), CARET_SQUARE_LEFT("caret-square-left", 0xf191), REDO("redo", 0xf01e), LIGHTBULB("lightbulb", 0xf0eb), USER_MINUS("user-minus", 0xf503), FILE_CODE("file-code", 0xf1c9), ARROW_RIGHT("arrow-right", 0xf061), CHALKBOARD_TEACHER("chalkboard-teacher", 0xf51c), TH_LIST("th-list", 0xf00b), SKULL_CROSSBONES("skull-crossbones", 0xf714), BURN("burn", 0xf46a), SIGN_IN_ALT("sign-in-alt", 0xf2f6), PHONE("phone", 0xf095), TENGE("tenge", 0xf7d7), PEN_FANCY("pen-fancy", 0xf5ac), USERS_COG("users-cog", 0xf509), CLOCK("clock", 0xf017), GLASS_CHEERS("glass-cheers", 0xf79f), MAGIC("magic", 0xf0d0), FILE_INVOICE("file-invoice", 0xf570), MAP_MARKER("map-marker", 0xf041), SEARCH_LOCATION("search-location", 0xf689), SORT_ALPHA_DOWN_ALT("sort-alpha-down-alt", 0xf881), SHOWER("shower", 0xf2cc), CARET_LEFT("caret-left", 0xf0d9), PAGER("pager", 0xf815), MINUS("minus", 0xf068), H_SQUARE("h-square", 0xf0fd), BROADCAST_TOWER("broadcast-tower", 0xf519), BUILDING("building", 0xf1ad), BIKING("biking", 0xf84a), BATTERY_EMPTY("battery-empty", 0xf244), GIFTS("gifts", 0xf79c), CODE("code", 0xf121), WALLET("wallet", 0xf555), CUT("cut", 0xf0c4), DOT_CIRCLE("dot-circle", 0xf192), SORT_AMOUNT_DOWN_ALT("sort-amount-down-alt", 0xf884), FILE_CSV("file-csv", 0xf6dd), HAMMER("hammer", 0xf6e3), RADIATION("radiation", 0xf7b9), CLOUD_MOON("cloud-moon", 0xf6c3), SEARCH_MINUS("search-minus", 0xf010), RING("ring", 0xf70b), VIRUSES("viruses", 0xe076), PRESCRIPTION("prescription", 0xf5b1), WINDOW_MINIMIZE("window-minimize", 0xf2d1), BUS("bus", 0xf207), CALENDAR_DAY("calendar-day", 0xf783), EXCLAMATION_CIRCLE("exclamation-circle", 0xf06a), SHARE_SQUARE("share-square", 0xf14d), MOUSE("mouse", 0xf8cc), ICICLES("icicles", 0xf7ad), STORE("store", 0xf54e), CANDY_CANE("candy-cane", 0xf786), UNIVERSITY("university", 0xf19c), LAUGH_WINK("laugh-wink", 0xf59c), BORDER_STYLE("border-style", 0xf853), FILE_PDF("file-pdf", 0xf1c1), CHEVRON_CIRCLE_DOWN("chevron-circle-down", 0xf13a), FORWARD("forward", 0xf04e), EYE_SLASH("eye-slash", 0xf070), INFO_CIRCLE("info-circle", 0xf05a), BATTERY_HALF("battery-half", 0xf242), ARROW_CIRCLE_LEFT("arrow-circle-left", 0xf0a8), ARROWS_ALT("arrows-alt", 0xf0b2), JOINT("joint", 0xf595), MEH_BLANK("meh-blank", 0xf5a4), PAINT_ROLLER("paint-roller", 0xf5aa), SUBSCRIPT("subscript", 0xf12c), CAR_CRASH("car-crash", 0xf5e1), BACTERIUM("bacterium", 0xe05a), SYNAGOGUE("synagogue", 0xf69b), TACHOMETER_ALT("tachometer-alt", 0xf3fd), THERMOMETER_THREE_QUARTERS("thermometer-three-quarters", 0xf2c8), BREAD_SLICE("bread-slice", 0xf7ec), SHARE("share", 0xf064), PUMP_SOAP("pump-soap", 0xe06b), CLIPBOARD_LIST("clipboard-list", 0xf46d), BELL_SLASH("bell-slash", 0xf1f6), LUNGS_VIRUS("lungs-virus", 0xe067), COMMENT("comment", 0xf075), VIAL("vial", 0xf492), PIZZA_SLICE("pizza-slice", 0xf818), MOUSE_POINTER("mouse-pointer", 0xf245), HAT_COWBOY_SIDE("hat-cowboy-side", 0xf8c1), LAUGH_BEAM("laugh-beam", 0xf59a), FILE_IMPORT("file-import", 0xf56f), DIGITAL_TACHOGRAPH("digital-tachograph", 0xf566), CARET_RIGHT("caret-right", 0xf0da), TRASH_RESTORE("trash-restore", 0xf829), STAR_OF_LIFE("star-of-life", 0xf621), GLASSES("glasses", 0xf530), DUNGEON("dungeon", 0xf6d9), EXTERNAL_LINK_ALT("external-link-alt", 0xf35d), RUBLE_SIGN("ruble-sign", 0xf158), DATABASE("database", 0xf1c0), SORT_NUMERIC_DOWN("sort-numeric-down", 0xf162), BOX_OPEN("box-open", 0xf49e), BOOKMARK("bookmark", 0xf02e), GLOBE_AFRICA("globe-africa", 0xf57c), LIST_UL("list-ul", 0xf0ca), USERS("users", 0xf0c0), TICKET_ALT("ticket-alt", 0xf3ff), TRUCK_MONSTER("truck-monster", 0xf63b), SPACE_SHUTTLE("space-shuttle", 0xf197), SQUARE_FULL("square-full", 0xf45c), ARROW_ALT_CIRCLE_UP("arrow-alt-circle-up", 0xf35b), BRAIN("brain", 0xf5dc), I_CURSOR("i-cursor", 0xf246), COOKIE("cookie", 0xf563), PEN("pen", 0xf304), TABLE_TENNIS("table-tennis", 0xf45d), FLAG_USA("flag-usa", 0xf74d), MONEY_BILL_ALT("money-bill-alt", 0xf3d1), USER_SECRET("user-secret", 0xf21b), SHARE_ALT("share-alt", 0xf1e0), OM("om", 0xf679), SUPERSCRIPT("superscript", 0xf12b), DRUM_STEELPAN("drum-steelpan", 0xf56a), DOVE("dove", 0xf4ba), WINDOW_CLOSE("window-close", 0xf410), TABLET_ALT("tablet-alt", 0xf3fa), HAND_POINT_RIGHT("hand-point-right", 0xf0a4), CIRCLE("circle", 0xf111), PORTRAIT("portrait", 0xf3e0), RUNNING("running", 0xf70c), QUESTION("question", 0xf128), BARCODE("barcode", 0xf02a), BROOM("broom", 0xf51a), DRUMSTICK_BITE("drumstick-bite", 0xf6d7), ALIGN_CENTER("align-center", 0xf037), FIRST_AID("first-aid", 0xf479), CHESS_QUEEN("chess-queen", 0xf445), TRAILER("trailer", 0xe041), PHONE_SLASH("phone-slash", 0xf3dd); private static final String fontFamily = "FontAwesome5"; private int codepoint; protected String clazz; FontAwesome(String clazz, int codepoint) { this.codepoint = codepoint; this.clazz = clazz; } @Override public String getMIMEType() { throw new UnsupportedOperationException(FontIcon.class.getSimpleName() + " should not be used where a MIME type is needed."); } @Override public String getFontFamily() { return fontFamily; } @Override public int getCodepoint() { return codepoint; } @Override public String getHtml() { return GenericFontIcon.getHtml(fontFamily, codepoint); } public String getHtml(String fontFamily) { return GenericFontIcon.getHtml(fontFamily, codepoint); } @Override public String getIconClass() { return clazz; } }
PHP
UTF-8
631
3.421875
3
[]
no_license
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Documento sin título</title> </head> <body> <?php $referencia=0; // estp Un paso por referencia, un vinculo entre la variable que se envia y a la variable de la funcion function incrementa(&$var) { $var++; return $var; }function incrementa2($var) { $var++; return $var; } echo incrementa2($referencia) .'</br>'; echo $referencia.'</br>'; echo incrementa($referencia) .'</br>'; echo $referencia.'</br>'; echo cambiaMayus("Perrito").'</br>'; function cambiaMayus($palabra) { $palabra= strtolower($palabra); return $palabra; } ?> </body> </html>
PHP
UTF-8
445
2.5625
3
[]
no_license
<?php include 'src/backend/core/Helper.php'; function autoload($class_name) { # List all the class directories in the array. $array_paths = array( 'core/', 'core/Products' ); foreach($array_paths as $path) { $file = sprintf('src/backend/%s/%s.php', $path, $class_name); if(is_file($file)) { include_once $file; } } } spl_autoload_register('autoload');
C++
UTF-8
687
3.421875
3
[]
no_license
//思路是用一个辅助栈,来储存没有输出的元素,然后一直把输出序列跟栈顶比 //相同就输出栈顶,不相同就把下一个元素入栈 class Solution { public: bool IsPopOrder(vector<int> pushV,vector<int> popV) { if(pushV.empty()&&popV.empty()) return true; stack<int> inStack; while(!popV.empty()){ if(!inStack.empty()&&inStack.top()==popV[0]){ inStack.pop(); popV.erase(popV.begin()); } else if(!pushV.empty()){ inStack.push(pushV[0]); pushV.erase(pushV.begin()); } else return false; } return true; } };
Markdown
UTF-8
886
2.78125
3
[]
no_license
# Project 2 Web Programming with Python and JavaScript My implementation has three files: application.py has all of the python and flask code that handles routing and maintaining the channels. index.html is the first page a user visits and tests whether a user has previously visited the site. If so, the user is welcomed by the previously used name and presented with a budget to continue to the channels page. If not, then they are asked to provide a username and provided the button to proceed to the channels. chat.html This contains all of the javascript and html needed to maintain and display all of the channels and messages as they are emitted. My personal touch is a private messaging feature. It allows a user to enter another user's name and a private message and when submitted, a javascript alert will display that message to the intended recipient only.
Java
UTF-8
5,879
2.734375
3
[]
no_license
package com.ko.na.database; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import com.ko.na.Family; import com.ko.na.FamilyTreeWriter; import com.ko.na.Person; public class FamilyTreeFactory extends SqlTable { protected PersonFactory pFact = null; public static final int ANCESTORS = 0; public static final int DESCENDANTS = 1; public FamilyTreeFactory() throws Exception { super(); pFact = new PersonFactory(); } // end constructor public ArrayList<Family> getFamilies(int generation, int id) throws Exception { ArrayList<Family> fam = new ArrayList<Family>(); Person base = null; /* * Locate the Base person for this Family */ ResultSet rs = exec("SELECT * FROM " + SqlTable.DATABASE + ".t_person where id=" + id + ";"); if (rs.first()) { base = pFact.instanceOf(rs); rs.close(); switch (generation) { case DESCENDANTS: /* * Retrieve all spouses of the base person creating a family * with each */ for (Person itm : pFact.getSpouses(base.getId())) { Family f1 = new Family(base, itm); f1.setEffDate(itm.getWorkDate()); fam.add(f1); } // end for break; case ANCESTORS: /* * Retrieve parents of the base person creating a family */ Person[] per = pFact.getParents(base.getId()); if (per.length > 0) { Family f1 = new Family(per[0], per[1]); fam.add(f1); } // end if break; } // end switch return fam; } else { return null; } // end if/else } // end getFamilies() method public Family[] instanceOf(int generation, int id) throws Exception { ArrayList<Family> fam = null; switch (generation) { case ANCESTORS: /* * For Root Person, get the Previous Generation Family */ fam = getFamilies(generation, id); // retrieves the family the root // person grew up in. /* * OnEachParent, insert their Parent's family */ if ((fam != null) && (fam.size() > 0)) { for (Family f1 : fam) { setParents(f1); } // end for } // end if break; case DESCENDANTS: /* * For Root Person, create a list of Current Generation Families */ fam = getFamilies(generation, id); // retrieves all families started // by the Root person. /* * OnEachFamily, insert the Children */ if ((fam != null) && (fam.size() > 0)) { for (Family f1 : fam) { setChildren(f1); } // end for } // end if break; } // end switch if ((fam != null) && (fam.size() > 0)) { return fam.toArray(new Family[fam.size()]); } else { return null; } } // end instanceOf() method public Family[] instanceOf(int generation, String given, String surname) throws Exception { return instanceOf(generation, pFact.getPersonId(given, surname)); } // end instanceOf() method public Family setChildren(Family f1) throws Exception { /* * insert the Children */ Statement stmt = connect.createStatement(); String sql = "select child from " + SqlTable.DATABASE + ".t_family where parents = " + " (select id from " + SqlTable.DATABASE + ".t_couple where person1 = " + f1.getFather().getId() + " and person2 = " + f1.getMother().getId() + ");"; ResultSet rs = exec(stmt, sql); rs.beforeFirst(); while (rs.next()) { f1.setChild(pFact.instanceOf(rs.getInt("child"))); } // end while rs.close(); stmt.close(); /* * OnEachCoupledChild, replace by a Next Family */ for (Person p1 : f1.getChildren()) { for (Family f2 : getFamilies(DESCENDANTS, p1.getId())) { setChildren(f2); f1.setNextFam(f2); } // end for } // end for return f1; } // end setChildren() method public Family setParents(Family f1) throws Exception { /* * insert the Parents */ Person[] par = new Person[2]; par[0] = f1.getFather(); par[1] = f1.getMother(); for (Person p1 : par) { // ForEachParent f1.setChild(p1); } // end for /* * OnEachParent, replace by a Next Family */ for (Person p1 : f1.getChildren()) { if (p1 != null) { for (Family f2 : getFamilies(ANCESTORS, p1.getId())) { setParents(f2); f1.setNextFam(f2); } // end for } // end if } // end for return f1; } public static void main(String[] args) throws Exception { FamilyTreeFactory fact = new FamilyTreeFactory(); FamilyTreeWriter wtr = new FamilyTreeWriter(); Family[] tree = null; boolean showId = true; fact.setDebug(false); if (args.length >= 2) { int generation = (args[0].substring(0, 1).equalsIgnoreCase("A")) ? FamilyTreeFactory.ANCESTORS : FamilyTreeFactory.DESCENDANTS; String pfx = ((generation == FamilyTreeFactory.ANCESTORS) ? "Ancestral " : "Decendant "); if (args.length == 2) { System.out.println(pfx + "Family Tree for Person<" + args[1] + ">\n"); tree = fact.instanceOf(generation, Integer.parseInt(args[1])); } else if (args.length == 3) { System.out.println(pfx + "Family Tree for " + args[1] + " " + args[2] + "\n"); tree = fact.instanceOf(generation, args[1], args[2]); } else { System.out.println(pfx + "Family Tree for " + args[1] + " " + args[2] + " " + args[3] + "\n"); tree = fact.instanceOf(generation, args[1] + " " + args[2], args[3]); } // end if/else if (tree == null) { System.out.println("No one found."); } else { wtr.showLineage(FamilyTreeFactory.DESCENDANTS,tree, showId); } // end if } else { System.out .println("Usage: FamilyTreeFactory [Ancestors|Descendants] [<PersonId> | [<GivenName> <Surname>]]"); } // end if/else // System.out.println(wtr.getJson(tree)); } // end main() method } // end FamilyTree class
C#
UTF-8
8,790
2.671875
3
[]
no_license
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using YzkSoftWare.Data; namespace YzkSoftWare.Database { /// <summary> /// 数据库连接适配器接口 /// </summary> public interface IDatabaseAdptor : IDisposable { /// <summary> /// 开始事务 /// </summary> void BeginTransaction(); /// <summary> /// 开始事务:指定隔离级别 /// </summary> /// <param name="level"></param> void BeginTransaction(IsolationLevel level); /// <summary> /// 提交事务 /// </summary> void CommitTran(); /// <summary> /// 回滚事务 /// </summary> void RollbackTran(); /// <summary> /// 提交到数据库 /// </summary> /// <param name="sql"></param> /// <returns>返回IDataExpress.Computational返回的对象</returns> object CommitToDatabase(ISqlExpress sql); /// <summary> /// 数据库类型名称 /// </summary> string DbTypeName { get; } /// <summary> /// 批量插入数据 /// </summary> /// <typeparam name="D"></typeparam> /// <param name="data"></param> void BulkCopyData<D>(IEnumerable<D> data); } /// <summary> /// 数据库连接适配器接口基础类 /// </summary> public abstract class DatabaseAdptorBase : IDatabaseAdptor { protected DatabaseAdptorBase(string connectstring) { p_ConnectString = connectstring; } private string p_ConnectString; /// <summary> /// 创建数据库连接 /// </summary> /// <param name="connectstring">连接字符串</param> /// <returns></returns> protected abstract IDbConnection CreateDbConnection(string connectstring); private IDbTransaction p_Transe = null; private IDbConnection p_Connect = null; protected IDbConnection Connect { get { if (p_Connect == null) p_Connect = CreateDbConnection(p_ConnectString); return p_Connect; } } private IDbCommand p_Command = null; protected IDbCommand Command { get { if (p_Command == null) { IDbConnection cnnt = Connect; if (cnnt.State == ConnectionState.Closed) cnnt.Open(); p_Command = Connect.CreateCommand(); } return p_Command; } } private void CloseDbConnect() { try { if (p_Connect != null) { p_Connect.Close(); } } catch { } try { if (p_Connect != null) { p_Connect.Dispose(); } } catch { } p_Connect = null; p_Command = null; } void IDatabaseAdptor.BeginTransaction() { BeginTransaction(); } void IDatabaseAdptor.CommitTran() { CommitTran(); } void IDatabaseAdptor.RollbackTran() { RollbackTran(); } object IDatabaseAdptor.CommitToDatabase(ISqlExpress sql) { return CommitToDatabase(sql); } string IDatabaseAdptor.DbTypeName { get { return DbTypeName; } } void IDatabaseAdptor.BulkCopyData<D>(IEnumerable<D> data) { BulkCopyData(data); } void IDisposable.Dispose() { Dispose(); } /// <summary> /// 开始事务 /// </summary> public virtual void BeginTransaction() { IDbCommand cmd = Command; if (p_Transe == null) { p_Transe = Connect.BeginTransaction(); if (cmd.Transaction == null) cmd.Transaction = p_Transe; } } void IDatabaseAdptor.BeginTransaction(IsolationLevel level) { IDbCommand cmd = Command; if (p_Transe == null) { p_Transe = Connect.BeginTransaction(level); if (cmd.Transaction == null) cmd.Transaction = p_Transe; } } /// <summary> /// 提交事务 /// </summary> public virtual void CommitTran() { if (p_Transe != null) { p_Transe.Commit(); p_Transe.Dispose(); p_Transe = null; } } /// <summary> /// 回滚事务 /// </summary> public virtual void RollbackTran() { if (p_Transe != null) { p_Transe.Rollback(); p_Transe.Dispose(); p_Transe = null; } } /// <summary> /// 将sql提交到数据库 /// </summary> /// <param name="sql"></param> /// <returns>返回IDataExpress.Computational返回的对象</returns> public virtual object CommitToDatabase(ISqlExpress sql) { sql.CurrentDbType = DbTypeName; sql.Command = Command; return sql.Computational(); } /// <summary> /// 数据库类型名称 /// </summary> public abstract string DbTypeName { get; } public abstract void BulkCopyData<D>(IEnumerable<D> data); public virtual void Dispose() { CloseDbConnect(); } } /// <summary> /// MS SQL SERVER的数据库连接器 /// </summary> internal sealed class MsSqlDatabaseAdptor : DatabaseAdptorBase { internal MsSqlDatabaseAdptor(string connectstring) : base(connectstring) { } protected override IDbConnection CreateDbConnection(string connectstring) { return new System.Data.SqlClient.SqlConnection(connectstring); } public override string DbTypeName { get { return DatabaseTypeNames.MS_Sql; } } public override void BulkCopyData<D>(IEnumerable<D> data) { YzkSoftWare.DataModel.IDataModel model = typeof(D).GetDataModel(); using (DataTable dt = CreateDataTableSchema(model)) { int columcount = dt.Columns.Count; foreach (var d in data) { DataRow nr = dt.NewRow(); for (int i = 0; i < columcount; i++) { var col = dt.Columns[i]; object fieldvalue = model.Fields[col.ColumnName].GetModelFieldValue(d); nr[col.ColumnName] = fieldvalue; } dt.Rows.Add(nr); } System.Data.SqlClient.SqlBulkCopy bulkCopy = new System.Data.SqlClient.SqlBulkCopy(Connect as System.Data.SqlClient.SqlConnection); try { bulkCopy.DestinationTableName = model.Name; bulkCopy.BatchSize = dt.Rows.Count; if (Connect.State == ConnectionState.Closed) Connect.Open(); if (dt != null && dt.Rows.Count != 0) { bulkCopy.WriteToServer(dt); } } finally { bulkCopy.Close(); } } } private System.Data.DataTable CreateDataTableSchema(YzkSoftWare.DataModel.IDataModel moudle) { System.Data.DataTable dt = new System.Data.DataTable(moudle.Name); foreach (var field in moudle.Fields) { System.Data.DataColumn dc = new System.Data.DataColumn(field.Name, field.GetClrType()); dt.Columns.Add(dc); } return dt; } } }
TypeScript
UTF-8
423
3.421875
3
[ "MIT" ]
permissive
/* @internal */ export class ConcatIterable<T> implements Iterable<T> { constructor( private readonly xs: Iterable<T>, private readonly ys: Iterable<T>, ) {} [Symbol.iterator]() { return concatIters(this.xs, this.ys) } } function* concatIters<T>(xs: Iterable<T>, ys: Iterable<T>) { for (const x of xs) { yield x } for (const y of ys) { yield y } }
Java
UTF-8
330
1.640625
2
[]
no_license
package com.kainos.discoverydiary.views; import com.kainos.discoverydiary.models.Book; import io.dropwizard.views.View; import java.util.List; /** * Created by annem on 03/11/2016. */ public class AdvancedSearchView extends View { public AdvancedSearchView() { super("/Views/books/advancedSearch.ftl"); } }
Java
UTF-8
608
2.515625
3
[]
no_license
package se.ltu.ajl; /** * This is a Temperature service */ public class TemperatureSevice extends Service { private String unit; // should it be a constant? private float value; private int timeStamp; ProviderBehaviour providerBehaviour; public TemperatureSevice(Prosumer system, String serviceType, String name, String uri) { super(system, serviceType, name, uri); providerBehaviour = new SimpleAnalogSensor(); providerBehaviour.registerService(this); } public void updateServiceRegistry() { providerBehaviour.registerService(this); } }
Markdown
UTF-8
5,984
3.25
3
[ "MIT" ]
permissive
### 前言 在学习完灰度、翻转、旋涡、马赛克滤镜后是不是觉得滤镜也就这么回事,今天学习抖音部分滤镜:缩放、灵魂出窍、抖动、闪白、毛刺,其中那个灵魂出窍我最喜欢。 ### 缩放滤镜 ![](http://cloud.minder.mypup.cn/blog/OpenGL%20ES%E6%8A%96%E9%9F%B3%E6%BB%A4%E9%95%9C-%E7%BC%A9%E6%94%BE.gif) 还记得那段时间嘛,满屏都是小姐姐就这样搞了我头晕,这个滤镜的原理以及实现就是改变顶点数据来达到这样的变化,顶点着色器的代码如下: ```c attribute vec4 position; attribute vec2 textureCoordinate; varying lowp vec2 textureCoord; uniform float time; const float PI = 3.1415926; void main(){ // 缩放市场 float duration = 0.6; // 缩放幅度 float amplitude = 0.25; // 周期 float period = mod(time, duration); // 当前幅度 [1, 1.25] float currentAmplitude = 1.0 + amplitude * (sin(time * (PI / duration))); // 纹理坐标 textureCoord = textureCoordinate; gl_Position = vec4(position.x * currentAmplitude, position.y * currentAmplitude, position.z, position.w); } ``` ### 灵魂出窍滤镜 ![](http://cloud.minder.mypup.cn/blog/OpenGL%20ES%20%E6%8A%96%E9%9F%B3%E6%BB%A4%E9%95%9C-%E7%81%B5%E9%AD%82%E5%87%BA%E7%AA%8D.gif) 是不是这个镜头让你趴在抖音里看然后天天被打,我们仔细观看可以知道有一层透明的图像放大,然后消失,再根据我们传时间以及开启定时器让他无限循环就完成了这个效果。这个是改变纹理数据,所以我们需要片段着色器中实现: ````c precision highp float; varying lowp vec2 textureCoord; uniform sampler2D sampler; uniform float time; void main(){ float duration = 0.7; float maxAlpha = 0.4; float maxScale = 1.8; float progress = mod(time, duration) / duration; float alpha = maxAlpha * (1.0 - progress); float scale = 1.0 + progress * (maxScale - 1.0); float sx = 0.5 + (textureCoord.x - 0.5) / scale; float sy = 0.5 + (textureCoord.y - 0.5) / scale; vec2 coord = vec2(sx, sy); vec4 mask = texture2D(sampler, coord); vec4 origin = texture2D(sampler, textureCoord); gl_FragColor = origin * (1.0 - alpha) + mask * alpha; } ```` ### 抖动滤镜 ![](http://cloud.minder.mypup.cn/blog/OpenGL%20ES%E6%8A%96%E9%9F%B3%E6%BB%A4%E9%95%9C-%E6%8A%96%E5%8A%A8.gif) 同学喜欢不喜欢我不知道,反正我不喜欢这个滤镜,看着头晕一点感觉都没得,但是有点刺激的感觉豁,像极了蹦迪时候的你吧😑。仔细观看可以发现有偏移和放大以及蓝色和红色两种颜色闪动,实现这个滤镜也就是这关键的两点以及时间: ```c precision highp float; varying lowp vec2 textureCoord; uniform sampler2D sampler; uniform float time; void main(){ float duration = 0.75; float maxScale = 1.2; float offset = 0.04; float progress = mod(time, duration) / duration; vec2 offsetCoord = vec2(offset, offset) * progress; float scale = 1.0 + (maxScale - 1.0) * progress; vec2 shakeCoord = vec2(0.5, 0.5) + (textureCoord - vec2(0.5, 0.5)) / scale; vec4 maskR = texture2D(sampler, shakeCoord - offsetCoord); vec4 maskB = texture2D(sampler, shakeCoord + offsetCoord); vec4 mask = texture2D(sampler, shakeCoord); gl_FragColor = vec4(maskR.r, mask.g, maskB.b, mask.a); } ``` ### 闪白滤镜 ![](http://cloud.minder.mypup.cn/blog/OpenGL%20ES%20%E6%8A%96%E9%9F%B3%E6%BB%A4%E9%95%9C-%E9%97%AA%E7%99%BD.gif) 呃呃,就不说这个滤镜了,这个滤镜实现很简单,我们观察就能知道有一层白色透明度随时间变化,所以看下代码就行啦: ```c precision highp float; varying lowp vec2 textureCoord; uniform sampler2D sampler; uniform float time; const float PI = 3.1415926; void main(){ float duration = 0.75; float currentTime = mod(time, duration); vec4 whiteMask = vec4(1.0, 1.0, 1.0, 1.0); float amplitude = abs(currentTime * sin(PI / duration)); vec4 mask = texture2D(sampler, textureCoord); gl_FragColor = mask * (1.0 - amplitude) + whiteMask *amplitude; } ``` ### 毛刺滤镜 ![](http://cloud.minder.mypup.cn/blog/OpenGL%20ES%20%E6%8A%96%E9%9F%B3%E6%BB%A4%E9%95%9C-%E6%AF%9B%E5%88%BA.gif) 是不是快看腻了,这个滤镜也是女的用的多,男的少。这个滤镜原理在于随机偏移1像素是否小于设置的最大偏移阈值与幅度的乘积时来撕裂,所以我们看到图像只有一些撕裂的,其他的则是偏移。 ```c precision highp float; varying lowp vec2 textureCoord; uniform sampler2D sampler; uniform float time; const float PI = 3.1415926; float rand(float n) { // fract(x) 返回x的小数部分数值 return fract(sin(n) * 50000.0); } void main(){ float maxJitter = 0.06; float duration = 0.35; float colorROffset = 0.03; float colorBOffset = -0.03; float currentTime = mod(time, duration * 2.0); float amplitude = max(sin(currentTime * (PI / duration)), 0.0); float jitter = rand(textureCoord.y) * 2.0 - 1.0; bool needOffset = abs(jitter) < maxJitter * amplitude; float textureX = textureCoord.x + (needOffset ? jitter : (jitter * amplitude * 0.006)); vec2 textureCoords = vec2(textureX, textureCoord.y); vec4 mask = texture2D(sampler, textureCoords); vec4 maskR = texture2D(sampler, textureCoords + vec2(colorROffset * amplitude, 0.0)); vec4 maskB = texture2D(sampler, textureCoords + vec2(colorBOffset * amplitude, 0.0)); gl_FragColor = vec4(maskR.r, mask.g, maskB.b, mask.a); } ``` ### 总结 感觉以后都看几次抖音后,可以试着去尝试他的思路把模仿出来🤔。**有兴趣的同学可以再这里获取demo: [传送门](https://github.com/oymuzi/OpenGLDocs)**, 如果对你有帮助,帮忙点个star✨,谢谢。
Markdown
UTF-8
544
2.5625
3
[]
no_license
# Article L5556-5 La pension est, le cas échéant, assortie de la bonification pour enfants prévue à l'article L. 5552-22. Elle peut être reversée aux ayants droit survivants dans les conditions fixées aux articles L. 5552-27 à L. 5552-40. **Liens relatifs à cet article** _Anciens textes_: - Loi n°97-1051 du 18 novembre 1997 - art. 16 (Ab), alinéa 3 _Cite_: - Code des transports - art. L5552-22 (V) - Code des transports - art. L5552-27 (V) _Codifié par_: - Ordonnance n°2010-1307 du 28 octobre 2010 - art. (V)
Markdown
UTF-8
8,850
3.453125
3
[ "MIT" ]
permissive
# GeneralizedSuffixTree An implementation of generalized suffix tree using Ukkonen's algorithm. **In this page:** - [The longest common substring problem](#the-longest-common-substring-problem) - [How it works](#how-it-works) - [GST versus Dynamic programming](#gst-versus-dynamic-programming) --- **Inspired by:** Ukkonen, E. On-line construction of suffix trees. Algorithmica 14, 249–260 (1995). https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf --- ## The longest common substring problem Given two or more strings, find the longest common substring of these strings. Concretely, the longest common substring of the two strings *"cacaocac"* and *"ccaooc"* is *"cao"*. This seems like a simple problem, but until today, it still requires a complicated algorithm to be solved in a reasonable time. This repo has implemented an algorithm to solve this problem by constructing a tree called Generalized Suffix Tree (GST). GST is a tree structure which contains sets of suffix strings of the origin string. Usually, the string will be appended a unique character *"$"* for representing "the end", this is to avoid some nodes not splitting due to repeated ending characters. There are 2 algorithms for constructing a GST: **McCreight's algorithm (1976)**, **Ukkonen's algorithm (1995)**. The latter has been implemented here. The visualized GST of *"cacaocac$"* as follows, made in http://brenden.github.io/ukkonen-animation/ : ![GST-for-cacaocac](res/GST4cacaocac.png) ## How it works After cloning this repo, we can get the same result by running these codes in the `Application.py`: ```py tree = STree() tree.build_with_automatic_end(["cacaocac"]) print(tree) ``` and then, something will appear in the console: ``` cacaocac$ ----> ⊥ c ----> cacaocac$ a ----> a c ----> c aocac$ (end) $ (end) ocac$ (end) $ (end) a ----> cacaocac$ c ----> c aocac$ (end) $ (end) ocac$ (end) ocac$ (end) $ (end) ``` `cacaocac$` for root, `⊥` for auxiliary state<sup>\*</sup>, `---->` for suffix link<sup>\*</sup>, and a `[tab]` represents a deeper level in the tree. > <sup>\*</sup>auxiliary state: The dummy status of the root's suffix link, for convenience in programming. > [Page 3 of the paper for details] > > <sup>\*</sup>suffix link: Used during the construction of a suffix tree. > [Page 4 of the paper for details] The method `_update`, `_test_and_split` and `_canonize` of the class `STree` in `STree.py`, are the complete implementation of the procedure of the same name in the page [12] and [13] in the paper, and the method `build` corresponds to the [Algorithm 2.] in the page [14]. But differently, the new `end_idxes` property in the `STree` contains the indexes of all ending characters *"$"*. It avoids effectively the construction bias of the suffix tree when the string contains or is filled with *"$"* symbols. So, back to the topic, how does this tree solve the longest common substring problem? In the `Application.py`, the `lcs2` function find the lcs of two strings. The method `build_with_automatic_end` in the `STree` will concatenate a list of strings with the ending characters *"$"*, and construct a suffix tree. With the help of `end_idxes`, these *"$"* are different and they represent the end of different strings. `STree` will automatically treat these *"$"* as different from other characters, so the character *"$"* itself is just designed for readability of suffix tree printing. The `lcs2` function will traverse the tree and find the deepest non-leaf node that contains the leaf nodes of all string indexes in the string list. Similarly, it can also be demonstrated using the following codes in `Application.py` ```py print(lcs2("cacaocac", "ccaooc")) ``` or ```py print(lcs(["cacaocac", "ccaooc"])) ``` The `lcs` function can find the longest common substring of multiple strings. The last two commands have the same result: ``` cao ``` ## GST versus Dynamic programming Dynamic programming is another way to solve this problem, and there is always said that the dynamic programming costs <img src="https://render.githubusercontent.com/render/math?math=\Theta(mn)">, and the Ukkonen's Algorithm just in linear time. So, let's start an experiment. The code in the `gst_vs_dp.py`, we randomly generated some strings to examine the performance of the two algorithms. `len` is the length range of the strings, `com_len` is the length range of the common part of the strings. `len = (800, 1600)` `com_len = (100, 200)` ``` random string has been generated gst_res: wTE^s>:x,k~%i3pRtdasZ>eLXrU5gbU#ptQF*?$ta,)k~znS*D/Ja:0L}@.X~i~E~{@NsKlK5c#`4v?v.$O]ts&/LNl<m]ww`Z!4G3vPd:@guRfCuz3DSRNHcVu~[r7s8J`X&/uETtiU[$N0p2.$SV2T><WTzqLVm:KkC3uE#2SIj63h?3BZYv;G*bl'PnNYhQ0M dp_res: wTE^s>:x,k~%i3pRtdasZ>eLXrU5gbU#ptQF*?$ta,)k~znS*D/Ja:0L}@.X~i~E~{@NsKlK5c#`4v?v.$O]ts&/LNl<m]ww`Z!4G3vPd:@guRfCuz3DSRNHcVu~[r7s8J`X&/uETtiU[$N0p2.$SV2T><WTzqLVm:KkC3uE#2SIj63h?3BZYv;G*bl'PnNYhQ0M gst_time: 12.598991394042969 ms dp_time: 284.3668460845947 ms ``` `len = (5000, 8000)` `com_len = (250, 800)` ``` random string has been generated gst_res: q3U'GCA9;dw}9nrT#R?"odw~HAK,&l;bd}VQ)h`15TAw6K/I1V]#;OSDj%(XmDp[&i}@$k($Bk8X4c"j(rXff9MK:E#`>B&'SF`CgMP<`XOp!8g%&4fpbq<!Q*o4[9W}TXabj4FTele0?~Cm.S,8~)B(U9<m~[1.9/3XGR/@nIt,X3@k}D"U"h@!/C&92s09RU^DLrqo6[}s}Wlr:,VyYX>f{rx&>8bH`VaZy^3pId.A]XO/zgD@26wN:Y23@t(.>3$T6c8?L'l"ZC?0PK,2tWNqa,S>VTe!!%L^n;;up<:Hw;gUtFp^dD]F8>!'}vg^PNK4K"L7X<w;roH:&<jEzZJJPg5qd'J!SWTP%N!CDDaxr7vBX.4@)9OO!Mg;S;M';VSV]^YZO9ww9k$H;Z^XcXKY@?Naa<jO$LEy`#e1&ywU8Yzq9PNAA^gQ58B?'?)KiKt)$ztM~IrnJ<$;2%%?m"<dme7df>:b?j.A8dM2dH/!K!*o)glG[F><aZ?c`By5{zEICgq[<M:D"LD;*FPJOzo9o,wXxKz@2];:g$oNrDhc/g{M9z9xTP[FllH/r!YrW!KMG!y(.$mO7Wzj31vMF2>YD?Y"I?t7FX!nWL[S>kLN1Ga7YN'XrG*fxylmtBri/R!0nEGQ3ZG`xQ1o[~Z?1<VKMzKn90J^9#5J<:{3diD*o4Fn.WppQJ7>Z#1cQgV2(GX54S*)0@vQvFs^!/fag#p6kHgwB9{5)u:d9R dp_res: q3U'GCA9;dw}9nrT#R?"odw~HAK,&l;bd}VQ)h`15TAw6K/I1V]#;OSDj%(XmDp[&i}@$k($Bk8X4c"j(rXff9MK:E#`>B&'SF`CgMP<`XOp!8g%&4fpbq<!Q*o4[9W}TXabj4FTele0?~Cm.S,8~)B(U9<m~[1.9/3XGR/@nIt,X3@k}D"U"h@!/C&92s09RU^DLrqo6[}s}Wlr:,VyYX>f{rx&>8bH`VaZy^3pId.A]XO/zgD@26wN:Y23@t(.>3$T6c8?L'l"ZC?0PK,2tWNqa,S>VTe!!%L^n;;up<:Hw;gUtFp^dD]F8>!'}vg^PNK4K"L7X<w;roH:&<jEzZJJPg5qd'J!SWTP%N!CDDaxr7vBX.4@)9OO!Mg;S;M';VSV]^YZO9ww9k$H;Z^XcXKY@?Naa<jO$LEy`#e1&ywU8Yzq9PNAA^gQ58B?'?)KiKt)$ztM~IrnJ<$;2%%?m"<dme7df>:b?j.A8dM2dH/!K!*o)glG[F><aZ?c`By5{zEICgq[<M:D"LD;*FPJOzo9o,wXxKz@2];:g$oNrDhc/g{M9z9xTP[FllH/r!YrW!KMG!y(.$mO7Wzj31vMF2>YD?Y"I?t7FX!nWL[S>kLN1Ga7YN'XrG*fxylmtBri/R!0nEGQ3ZG`xQ1o[~Z?1<VKMzKn90J^9#5J<:{3diD*o4Fn.WppQJ7>Z#1cQgV2(GX54S*)0@vQvFs^!/fag#p6kHgwB9{5)u:d9R gst_time: 79.45418357849121 ms dp_time: 10244.915962219238 ms ``` `len = (5000, 8000)` `com_len = (250, 800)` ``` random string has been generated gst_res: Hu4XU.if.j/h9DAT3.2RI"9LVeR6qoG}HOB#V[qdN[TQ!%IG#v7l]'4pTA;.G^zhWt%/B0P4ATaG>FDZj?GNH"V%NW(.uL?O.5tJCv6d7[}e.<$SFXv(C&ww>9a'Con(V}MK<exxZ@1.1<7<Wo%wGyjB0FPpcxPLIy^LRZS@c;eel4sUF:iqcGlhz3]z&M&]qk&.H3]vqI7YG)#&}U3sa"6c6H*y{3>9MiHB!W4N1YwR[,qdn:nw$M"g]Ic6S$*[FIzaOZ[fHT<04<$R$[f#.%MscaTy[6?gJ:Qq dp_res: Hu4XU.if.j/h9DAT3.2RI"9LVeR6qoG}HOB#V[qdN[TQ!%IG#v7l]'4pTA;.G^zhWt%/B0P4ATaG>FDZj?GNH"V%NW(.uL?O.5tJCv6d7[}e.<$SFXv(C&ww>9a'Con(V}MK<exxZ@1.1<7<Wo%wGyjB0FPpcxPLIy^LRZS@c;eel4sUF:iqcGlhz3]z&M&]qk&.H3]vqI7YG)#&}U3sa"6c6H*y{3>9MiHB!W4N1YwR[,qdn:nw$M"g]Ic6S$*[FIzaOZ[fHT<04<$R$[f#.%MscaTy[6?gJ:Qq gst_time: 63.52519989013672 ms dp_time: 6668.108701705933 ms ``` `len = (10000, 20000)` `com_len = (500, 1000)` ``` random string has been generated gst_res: hee!!i$;hIn8&;Y)bU2BC^Bu{Ek]2}}`SvD>Fj!{%XS#pl6wMh#CDKe'zk%N@mAC]r9[k:g{!Q<B0NQ"#"E<P@in$7]^fkn3tO:5q:lb%!Y5N3[rJBd7I@,6Uf{hNv5o$M%~]~9IS4#ho}]3A"~B9yLF!0'`R(}le0KAMF/J7@EG/d&W/m`XcBt[,Bp0M8m6J]%#mh.^":CsZw6~!w6eq[)WdAI/'D`Tq.`*t[H5yVEk3mpRKZv<eMZj'R?*zeA,!goeNt"5th.0^LN2xB$wy.*xP(cCW4)zZv#XS.#<&*"spzHfnG:78~P5z%a`Dn1g3>nF5CZm?;EfbKD/(g$!SIAxSRWce"Qf'WbyceqGrh>uhP45R$:h?fJfEFk]@5P{]n2H/KgDGUA~`Q1'<Z}66!s#V>B%>B1L3cIq?;ytc/E?mDmA2;m5LwdI@8)l3@&ZpdKp0'f{VS@ahmmE!f.)kO(nNcVsU?yGEAzu"I/RH:N6"1xFvp~ipR~$7FJ@NLTs[VW^hng1bfc&!ieEbY.)uYN@Ux$(#~]WSyY/alVsiq1uv0u%tVx'kS>x}dkUN5&lY!xy&Y]:wZU;gIXZ>h)mS7,au dp_res: hee!!i$;hIn8&;Y)bU2BC^Bu{Ek]2}}`SvD>Fj!{%XS#pl6wMh#CDKe'zk%N@mAC]r9[k:g{!Q<B0NQ"#"E<P@in$7]^fkn3tO:5q:lb%!Y5N3[rJBd7I@,6Uf{hNv5o$M%~]~9IS4#ho}]3A"~B9yLF!0'`R(}le0KAMF/J7@EG/d&W/m`XcBt[,Bp0M8m6J]%#mh.^":CsZw6~!w6eq[)WdAI/'D`Tq.`*t[H5yVEk3mpRKZv<eMZj'R?*zeA,!goeNt"5th.0^LN2xB$wy.*xP(cCW4)zZv#XS.#<&*"spzHfnG:78~P5z%a`Dn1g3>nF5CZm?;EfbKD/(g$!SIAxSRWce"Qf'WbyceqGrh>uhP45R$:h?fJfEFk]@5P{]n2H/KgDGUA~`Q1'<Z}66!s#V>B%>B1L3cIq?;ytc/E?mDmA2;m5LwdI@8)l3@&ZpdKp0'f{VS@ahmmE!f.)kO(nNcVsU?yGEAzu"I/RH:N6"1xFvp~ipR~$7FJ@NLTs[VW^hng1bfc&!ieEbY.)uYN@Ux$(#~]WSyY/alVsiq1uv0u%tVx'kS>x}dkUN5&lY!xy&Y]:wZU;gIXZ>h)mS7,au gst_time: 164.72983360290527 ms dp_time: 44179.36301231384 ms ``` Obviously, dynamic programming takes a lot longer time.
Markdown
UTF-8
894
3.4375
3
[ "MIT" ]
permissive
> Developed with [Giuseppe Marino](https://github.com/giuseppe16180) ## Global thresholding This is a heuristic algorithm inspired by [Otsu's method](https://en.wikipedia.org/wiki/Otsu%27s_method). It divides the histogram in two by finding a good threshold value. The solution is obtained iteratively. At first, we split the histogram in two using a fixed value `t`, then we find the mean on both sides, `m1` and `m2`, and finally we choose `t = (mi + m2) / 2` as a new threshold value. The algorithm keeps track of the values that have been used, and if we find one that was already used we stop. ### Usage The implementation works on grayscale images and produces a binary image `out` (logical matrix), and the threshold value `t` that was chosen. ```matlab [out, t] = threshold(img); figure; imshow(out); ``` ![](original.png) <br> Original | ![](threshold.png) <br> Threshold :----:|:----:
Go
UTF-8
841
3.53125
4
[]
no_license
package main /* 散列法:根据各元素的值来确定存储的位置,然后将位置保管在散列表中,从而实现数据的高速搜索 insert(data) T(h(data.key))=data [T为hash table,h为hash函数,data.key 为数据的关键字] search(data) return T(h(data.key)) 函数的返回值要求在0~m-1之间;m 为 哈希表T的大小 例如根据k值求下标 h(k) = k mod m 冲突: 不同k值对应同一个hash值。 开放地址法是解决hash冲突的常用手段之一。双散列结构中使用的开放地址法 H(k) = h(k,i) = (h1(k)+i*h2(k)) mod m h(k,i) 先调用h1(K)计算下标,发生冲突后向后移动h2(k)个单位,直到找到空地址。 注意 : h2(k)要与m互质 方法 : 设置m为质数,h2(k)为小于m的值 例如 h1(k) = k mod m; h2(k) = 1 + (k mod (m-1)) */ func
Java
UTF-8
687
2.0625
2
[]
no_license
package pom_class; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class FlipKart_ShoppingCartPage { @FindBy(xpath="//span[.='Place Order']") private WebElement orderlink; @FindBy(xpath="//a[contains(.,'silkova Casual Cutout Sleeve Solid Women')]/../../../..//button[2]") private WebElement inquan; public FlipKart_ShoppingCartPage(WebDriver driver) { PageFactory.initElements(driver, this); } public void orderProd() { orderlink.click(); } public void increaseQuantity() { inquan.click(); } }
Java
UTF-8
1,085
3.71875
4
[]
no_license
package collections; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class MinOfNumbers { public static void main(String[] args) throws Exception { List<Integer> integerList = getIntegerList(); System.out.println(getMinimum(integerList)); } public static int getMinimum(List<Integer> list) { //Ваш код int min = list.get(0); for(Integer num : list) { min = min > num ? num : min; } return min; } public static List<Integer> getIntegerList() throws IOException { //Ваш код BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Type count of numbers: "); int cntNumbers = Integer.parseInt(reader.readLine()); List<Integer> list = new ArrayList<>(); for (int i = 0; i < cntNumbers; i++) { list.add(Integer.parseInt(reader.readLine())); } return list; } }
Java
UTF-8
1,588
2.109375
2
[]
no_license
package pow.jie.powmoji; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.viewpager.widget.ViewPager; import android.os.Bundle; import com.google.android.material.tabs.TabLayout; import java.util.ArrayList; import java.util.List; import pow.jie.powmoji.adapter.MyPagerAdapter; import pow.jie.powmoji.fragment.MojiFragment; public class MainActivity extends AppCompatActivity { MyPagerAdapter adapter; private List<MojiFragment> fragments = new ArrayList<>(); private List<String> titles = new ArrayList<>(); TabLayout tabLayout; ViewPager viewPager; Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = findViewById(R.id.tb_main); setSupportActionBar(toolbar); viewPager = findViewById(R.id.vp_main); tabLayout = findViewById(R.id.tl_main); fragments.add(MojiFragment.newInstance("happy")); fragments.add(MojiFragment.newInstance("sad")); fragments.add(MojiFragment.newInstance("angry")); fragments.add(MojiFragment.newInstance("doubt")); titles.add("happy"); titles.add("sad"); titles.add("angry"); titles.add("doubt"); adapter = new MyPagerAdapter(getSupportFragmentManager()); adapter.setFragments(fragments); adapter.setTitles(titles); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); } }
Java
UTF-8
259
1.804688
2
[]
no_license
package pro.littleworld.webapp.model; public class Product { int id; String name; String description; double price; // Make this a valid Entity class // Create a ProductController, ProductService // and the form and the list }
Java
UTF-8
751
3.765625
4
[]
no_license
package test18; public class Constructure3 { Constructure3(){ System.out.println("평범한 날 호출하다니.."); } Constructure3(int a){ System.out.println("인트를 넣어야만 날 호출할 수 있다구!!"); } Constructure3(String str){ System.out.println("스트링이 필요해!!"); } /* * 생성자는 메소드와 비슷은함~ * 그래서 overloading이 가능함 * 즉 여러개의 생성자를 만들수 있다는 얘기임. */ public static void main(String[] args) { new Constructure3(); new Constructure3(1); new Constructure3(""); /* * 현재 Constructure3 클래스에는 총3개의 생성자가 있음. * 그래서 위의 20라인부터 22라인의 출력결과는 다 다름! */ } }
Markdown
UTF-8
463
2.875
3
[]
no_license
# flask-jsSankey Sankey Chart using d3.js and Flask. The data source is a static CSV file: no header; each line in the format of _source, target, weight_ ## To run: 1. Make sure you have flask installed 2. `git clone https://github.com/yingchi/flask-jsSankey.git` 3. `cd flask-jsSankey` 4. `python app.py` Now navigate your browser to http://localhost:5000 to see. 5. To run the app on a server address, change the host parameter in `app.run(host='0.0.0.0')`
Python
UTF-8
5,769
3.53125
4
[]
no_license
"""Arvore de busca binaria. classes: No, Arvore implementada por Jonathas F. Silva """ class No(): """No basico para arvore binaria.""" def __init__(self, chave, dados): u"""Classe No é iniciada com: chave e dados. Atributos: pai - no pai chave - identificador de um objeto No, Tipo (inteiro) dados - informaçao armazenada nesse no. esquerdo - filho esquerdo direito - filho direito """ self.__pai = None self.__chave = chave self.__dado = dados self.__esquerdo = None self.__direito = None def __repr__(self): """Plota o dado do no.""" return self.__dado def getPai(self): """Retorna no pai.""" return self.__pai def setPai(self, pai): """Define no pai.""" self.__pai = pai def getChave(self): """Retorna a chave de acesso.""" return self.__chave def setChave(self, chave): """Define um nova chave.""" self.__chave = chave def getDado(self): """Retorna o dado do no.""" return self.__dado def setDado(self, dado): """Define o dado do no.""" self.__dado = dado def getEsquerdo(self): """Retorna o filho esquerdo.""" return self.__esquerdo def setEsquerdo(self, esquerdo): """Define o filho esquerdo.""" self.__esquerdo = esquerdo def getDireito(self): """Retorna o filho direito.""" return self.__direito def setDireito(self, direito): """Define o filho direito.""" self.__direito = direito class Arvore(): """Arvore de busca binaria.""" def __init__(self): """Contrutor da arvore.""" self.__raiz = None def __repr__(self): """Plota o dado do no.""" s = '' no = self.getRaiz() s += str(no.getPai()) + '\n' s += '^' + '\n' s += str(no.getEsquerdo()) + ' <- ' s += str(no.getDado()) + ' -> ' s += str(no.getDireito()) return s def getRaiz(self): """Retorna a raiz da arvore.""" return self.__raiz def setRaiz(self, raiz): """Define raiz da arvore.""" self.__raiz = raiz def minimo(self, no): """Retorna o minimo da arvore.""" if no is not None: while no.getEsquerdo() is not None: no = no.getEsquerdo() return no def maximo(self, no): """Retorna o maximo da arvore.""" if no is not None: while no.getDireito() is not None: no = no.getDireito() return no def antecessor(self, no): """Retorna o antecessor do no.""" if no is not None: if no.getEsquerdo() is not None: return self.maximo(no.getEsquerdo()) else: pai = no.getPai() while pai is not None and no is pai.getEsquerdo(): no = pai pai = no.getPai() return pai def sucessor(self, no): """Retorna o sucessor do no.""" if no is not None: if no.getDireito() is not None: return self.minimo(no.getDireito()) else: pai = no.getPai() while pai is not None and no is pai.getDireito(): no = pai pai = no.getPai() return pai def estaVazia(self): """Retorna True se esta vazia e False se estiver vazia.""" if self.getRaiz() is None: return True else: return False def busca(self, k): """Busca um no na arvore.""" x = self.getRaiz() while x is not None and k != x.getChave(): if k < x.getChave(): x = x.getEsquerdo() else: x = x.getDireito() return x def insere(self, no): """Insere um No na arvore.""" y = None x = self.getRaiz() while x is not None: y = x if no.getChave() < x.getChave(): x = x.getEsquerdo() else: x = x.getDireito() no.setPai(y) if y is None: self.setRaiz(no) elif no.getChave() < y.getChave(): y.setEsquerdo(no) else: y.setDireito(no) def remove(self, z): """Remove um no da arvore.""" if (z.getEsquerdo() is None) or (z.getDireito() is None): y = z else: y = self.sucessor(z) if y.getEsquerdo() is not None: x = y.getDireito() else: x = y.getDireito() if x is not None: x.setPai(y.getPai()) if y.getPai() is None: self.setRaiz(x) else: if y == y.getPai().getEsquerdo(): y.getPai().setEsquerdo(x) else: y.getPai().setDireito(x) if y != z: z.setChave(y.getChave()) return y def emOrdem(self, x): """Plota a arvore em ordem.""" if x is not None: self.emOrdem(x.getEsquerdo()) print(x.getChave(), end = ' ') self.emOrdem(x.getDireito()) def preOrdem(self, x): """Plota a arvore em pre-ordem.""" if x is not None: print(x.getChave(), end = ' ') self.preOrdem(x.getEsquerdo()) self.preOrdem(x.getDireito()) def posOrdem(self, x): """Plota a arvore em pos-ordem.""" if x is not None: self.posOrdem(x.getEsquerdo()) self.posOrdem(x.getDireito()) print(x.getChave(), end = ' ')
Python
UTF-8
5,641
2.859375
3
[]
no_license
# -*- coding: utf-8 -*- from __future__ import print_function, division import sys import os.path import numpy as np import functools import librosa as lf """ Module for waveform effects motivation: audio data augmentation florencia @ 06.09.14 """ ########################################################### ##### waveform manipulations ##### ########################################################### #### WAVEFORM MANIPULATIONS def normalizeWF(waveform): return 1.0 * waveform / np.max(np.abs(waveform)) def tileTillN(arr, N, n0=0): '''returns an arrray of size N (>0) from tiling of arr. n0 is the starting index''' #np.tile(arr, int(n/len(arr))+1)[:n] return arr[np.array([i for i in np.arange(n0, N + n0)%len(arr)])] def addWhiteNoise(y, param=1.0): """ adds white noise with amplitude 'param" to y """ y_ns = np.random.random_sample(len(y))*2 - 1 # white noise return y + param*y_ns def addToSignal(y1, y2, noiseIndex): ''' adds y2 (noise) to the primary signal y1. Returns the sum, keeping the size of y1 ''' return y1 + tileTillN(y2, len(y1), noiseIndex) def freqshift(y, Fs, param=100): """Frequency shift the signal by param """ x = np.fft.rfft(y) T = len(y)/float(Fs) df = 1.0/T nbins = int(param/df) # print T,df,nbins,x.real.shape y = np.roll(x.real,nbins) + 1j*np.roll(x.imag,nbins) z = np.fft.irfft(y) return z def waveformEffectsDictionary(funName=None): ''' Dictionary of waveform effects Parameters: ----------- < funName : effect name (if None) Return: ------- > effect function this functions take the waveform an alteration if the later ''' D = { 'addWhiteNoise' : addWhiteNoise,# param : amplitude of the white noise waveform 'addSignals' : addToSignal, 'freqShift' : freqshift, # y, Fs, fshift=100 'timeStreach' : lf.effects.time_stretch, # time_stretch(y, 1.5) 'pitchshift' : lf.effects.pitch_shift } if funName == None: # returns a list of possible feature names return D.keys() else: return D[funName] #### waveform ensembles def generateWaveformEnsemble(y_template, effectName=None, generate_data_grid=None):#, **kwEffect): ''' Generates an ensemble of signals from y_template using the parameters in generate_data_grid !!! only works for white noise addition Parameters ---------- y_template : waveform (np.array) effect : name of the effect to use (string) generate_data_grid : parameter grid for the effect (np.array) kwEffect : kwargs for the effect Returns ------- Y : waveform ensemble (np.array), one waveform per row ''' if generate_data_grid is None: generate_data_grid = np.ones(1) if effectName is None: effectFun = waveformEffectsDictionary("addWhiteNoise") else: effectFun = waveformEffectsDictionary(effectName) Y = np.zeros((len(generate_data_grid), len(y_template))) for i in range(len(generate_data_grid)): Y[i,:] = effectFun(y_template, param=generate_data_grid[i])#, **kwEffect) return(Y) def generateAddEnsemble(y_template, y_add, intensity_grid=None, normalize=True): ''' generate an ensemble of y_template-signals adding y_add normalizes both signals and adds different amplitudes of y_add to y_template Returns: Y : a matrix, with the sum of y_template and y_add in each row ''' if intensity_grid is None: intensity_grid = np.linspace(0.1, 10, 10) #print(len(intensity_grid), len(y_template)) Y = np.zeros((len(intensity_grid), len(y_template))) if normalize: y_template = normalizeWF(y_template) y_add = normalizeWF(y_add) for i in range(len(intensity_grid)): Y[i,:] = addToSignal(y_template, intensity_grid[i]*y_add, np.random.randint(0,len(y_template))) #y_template + intensity_grid[i]*tileTillN(y_add, len(y_template), np.random.randint(0,len(y_template))) return Y def generatePitchShiftEnsemble(y_template, fs, shift_grid=None): ''' generate an ensemble of y_template-signals shifting the pitch of the original signal normalizes both signals and adds different amplitudes of y_add to y_template Parameters: ----------- shift_grid : 12 steps per octave Returns: Y : a matrix, with the sum of y_template and y_add in each row ''' if shift_grid is None: shift_grid = np.linspace(-2, 2, 5) #print(len(intensity_grid), len(y_template)) Y = np.zeros((len(shift_grid), len(y_template))) for i in range(len(shift_grid)): Y[i,:] = lf.effects.pitch_shift(y_template, fs, shift_grid[i]) #y_template + intensity_grid[i]*tileTillN(y_add, len(y_template), np.random.randint(0,len(y_template))) return Y def generateTimeStreachEnsemble(y_template, streach_grid=None): ''' generate an ensemble of y_template-signals adding y_add normalizes both signals and adds different amplitudes of y_add to y_template Returns: Y : a matrix, with the sum of y_template and y_add in each row ''' if streach_grid is None: streach_grid = np.linspace(0.8, 1.2, 5) #print(len(intensity_grid), len(y_template)) Y = []#np.zeros((len(streach_grid), len(streach_grid))) for i in range(len(streach_grid)): Y.append(lf.effects.time_stretch(y_template, streach_grid[i])) return Y
C
UTF-8
316
3.171875
3
[ "Apache-2.0" ]
permissive
#include<stdio.h> // funcion que crea que comportamiento necesario int numbers(int p1, int p2, int p3, int p4, int p5, int p6, int p7){ if (p7>4){ return p1 + p2 + p3 + p4 - p5 - p6; } else{ return p1 + p2 + p3 + p4 + p5 - p6; } } //main int main () { printf("%d\n", numbers(1,1,1,1,1,1,3)); }
C++
UTF-8
487
2.84375
3
[]
no_license
#include "bits/stdc++.h" using namespace std; int main() { string str1, str2; while(cin >> str1 >> str2) { int Count = 0; for(int i = 0; i < str1.length(); i++) { for(int j = 0; j < str2.length(); j++) { if(str1[i] == str2[j]) { Count++, i++; } } } Count == str1.length() ? cout << "Yes\n" : cout << "No\n"; } return 0; }
C++
UTF-8
945
3.0625
3
[]
no_license
#include "Checksum.h" uint16_t Checksum::crcIn; /* CRC algorithm */ #pragma optimize=none unsigned int crc16_byte(unsigned int crc, unsigned int data) { const unsigned int Poly16=0xA001; unsigned int LSB; crc = ((crc^data) | 0xFF00) & (crc | 0x00FF); for (uint8_t i=0; i<8; i++) { LSB=(crc & 0x0001); crc >>= 1; if(LSB) crc=crc^Poly16; } return crc; } unsigned short Checksum::crc16(const unsigned char *pcBlock, unsigned short len) { unsigned int crc = 0xFFFF; for (int i = 0; i < len; i++) { crc = crc16_byte(crc, pcBlock[i] ); } return crc; } //len - длинна без црц void Checksum::addCrc16(unsigned char * pcBlock, unsigned short len) { unsigned short crc = crc16(pcBlock, len); pcBlock[len++] = crc & 0xff; pcBlock[len] = (crc >> 8) & 0xff; } void Checksum::clearCrc() { crcIn = 0xFFFF; } uint16_t Checksum::calcCrc(uint8_t byte) { crcIn = crc16_byte(crcIn, byte); return crcIn; }
Python
UTF-8
2,872
2.515625
3
[ "MIT" ]
permissive
from tqdm.autonotebook import tqdm import torch import numpy as np from sklearn.neighbors import KDTree import logging class BaseTester: def __init__(self, cfg, models, test_dataset, batch_size, dataloader_num_workers, name="" ): self.models = models self.test_dataset = test_dataset self.batch_size = batch_size self.dataloader_num_workers = dataloader_num_workers self.name = name self.dataloader = None self.losses = {} self.device = torch.device("cuda") self.logger = logging.getLogger(cfg.LOGGER.NAME) self.setup_dataloader() def setup_dataloader(self): self.dataloader = torch.utils.data.DataLoader( self.test_dataset, batch_size=int(self.batch_size), num_workers=self.dataloader_num_workers, shuffle=False, pin_memory=True ) def test(self): self.logger.info("Start Testing") self.set_to_eval() embeddings = self.extract_embeddings() accuracies = {} for K in [1, 5, 10]: acc_k = self.accuracy_at_k(np.array(self.test_dataset.targets), embeddings, K, 200) accuracies[f"{self.name} Accuraccy at {K}"] = acc_k self.logger.info("accuracy@{} = {}".format(K, acc_k)) self.logger.info("End Testing") return accuracies def set_to_eval(self): self.models.eval() @staticmethod def accuracy_at_k(y_true: np.ndarray, embeddings: np.ndarray, K: int, sample: int = None) -> float: kdtree = KDTree(embeddings) if sample is None: sample = len(y_true) y_true_sample = y_true[:sample] indices_of_neighbours = kdtree.query(embeddings[:sample], k=K + 1, return_distance=False)[:, 1:] y_hat = y_true[indices_of_neighbours] matching_category_mask = np.expand_dims(np.array(y_true_sample), -1) == y_hat matching_cnt = np.sum(matching_category_mask.sum(-1) > 0) accuracy = matching_cnt / len(y_true_sample) return accuracy def extract_embeddings(self): embeddings = [] with tqdm(total=len(self.dataloader)) as pbar: with torch.no_grad(): for idx, (data, labels) in enumerate(self.dataloader): embeddings_batch = self.models(data) embeddings.append(embeddings_batch.cpu().detach().numpy()) pbar.update() return np.vstack(embeddings)
Java
UTF-8
1,999
2.640625
3
[]
no_license
package test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Scanner; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; public class HDFSConnector { private Path hdfsPath; private Configuration conf; private FileSystem hdfs; private Parser parser; private BufferedInputStream inBufferedStream; private BufferedOutputStream outBufferedStream; //private BufferedReader bufferedReader; byte[] buffer; public HDFSConnector (Parser parser) throws IOException{ conf = new Configuration(); hdfs = FileSystem.get(conf); this.parser = parser; } public void setHdfsPath(String hdfsPath) throws IOException{ this.hdfsPath = new Path(hdfsPath); if(hdfs.delete(this.hdfsPath, true)){ hdfs.delete(this.hdfsPath, true); } } public void uploadFileToHdfs() throws IOException{ String localPath = parser.getLocalPath(); inBufferedStream = new BufferedInputStream(new FileInputStream(localPath)); outBufferedStream = new BufferedOutputStream(hdfs.create(hdfsPath)); buffer = new byte[1024]; int len = 0; //int firstRowLen = 0; /*if(!parser.getLineOptionFromUser()){ bufferedReader = new BufferedReader(new FileReader(localPath)); firstRowLen = bufferedReader.readLine().getBytes().length; bufferedReader.close(); }*/ while ((len = inBufferedStream.read(buffer)) > 0) { //if(useFirstRow){ outBufferedStream.write(buffer, 0, len); /*}else{ outBufferedStream.write(buffer, firstRowLen, len - firstRowLen); useFirstRow = true; hi }*/ } inBufferedStream.close(); outBufferedStream.close(); } public Path getHdfsPath(){ return hdfsPath; } }
Java
UTF-8
6,506
1.859375
2
[ "MIT" ]
permissive
/** * Copyright (c) 2013 Jose Cruz-Toledo * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package ab.server; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import ab.shared.AptamerBaseSelexSubmitParser; import ab.shared.FreebaseHelper; import ab.shared.lib.AffinityExperiment; import ab.shared.lib.Aptamer; import ab.shared.lib.AptamerTarget; import ab.shared.lib.Interaction; import ab.shared.lib.SelexExperiment; /** * @author Jose Cruz-Toledo * */ public class SelexSubmitParser extends HttpServlet { /** * */ private static final long serialVersionUID = 5714015034095536468L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) { Map<String, String[]> rm = req.getParameterMap(); doGet(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) { JSONObject rm = new JSONObject(); resp.setContentType("text/json"); PrintWriter out = null; String in = null; String fn = null; try { out = resp.getWriter(); in = req.getParameter("se"); fn = req.getParameter("fn"); if (in != null && fn != null) { JSONObject jo = new JSONObject(in); AptamerBaseSelexSubmitParser abssp = new AptamerBaseSelexSubmitParser( jo); // now convert the AptamerBaseSelexSubmitParser into a write // query? SelexExperiment se = abssp.getSelexExperiment(); if (se != null) { int aPmid = se.getPmid(); String doi = se.getDoi(); String ref = se.getReference(); // now check that the experiment has a pmid if (aPmid > 1) { // first check if the PMID exists in freebase String mid = FreebaseHelper.checkPmid(aPmid); if (mid == null) { // start preparing the output // now check the interactions try { JSONArray interactions_arr = this .checkInteractions(abssp, fn); rm.put("\"se\"", se.getJSONObject()); rm.put("\"interactions\"", interactions_arr); out.println(rm); } catch (Exception e) { e.printStackTrace(); } } else { out.println("PMID already in Freebase. Please check submission :" + fn); } } else if (doi != null) { // check if the doi exists in freebase String mid = FreebaseHelper.checkDoi(doi); if (mid == null) { try { JSONArray interactions_arr = this .checkInteractions(abssp, fn); rm.put("\"se\"", se.getJSONObject()); rm.put("\"interactions\"", interactions_arr); out.println(rm); } catch (Exception e) { e.printStackTrace(); } } else { out.println("DOI already in Freebase. Please check submission :" + fn); } } else if (ref != null) { // check if ref exists in freebase String mid = FreebaseHelper.checkReference(ref); if (mid == null) { try { JSONArray interactions_arr = this .checkInteractions(abssp, fn); rm.put("\"se\"", se.getJSONObject()); rm.put("\"interactions\"", interactions_arr); out.println(rm); } catch (Exception e) { e.printStackTrace(); } } else { out.println("This reference is already in Freebase. Please check submission :" + fn); } } else { out.println("No reference details provided. Please check submission: " + fn); } } } else { out.println("Please provide a selex experiment JSON and a filename using the 'se' and 'fn' parameters respectively"); } } catch (JSONException e) { out.println("INVALID JSON"); out.flush(); e.printStackTrace(); } catch (NullPointerException e) { out.println("INVALID JSON error 2"); } catch (IOException e) { e.printStackTrace(); } } protected JSONArray checkInteractions(AptamerBaseSelexSubmitParser abssp, String aFn) throws Exception { List<Interaction> interactions = abssp.getInteractions(); JSONArray rm = new JSONArray(); for (Interaction anInteraction : interactions) { // verify that each interaction has the following things // an aptamer target AptamerTarget at = anInteraction.getAptamer_target(); if (at.getName().length() == 0) { throw new Exception( "No target name provided. Please check submission :" + aFn); } // some affinityExperiments List<AffinityExperiment> ae_list = anInteraction .getAffinityExperiments(); if (ae_list.size() == 0) { throw new Exception( "No affinity experiments provided. Please check submission : " + aFn); } // check that all aptamers have types List<Aptamer> a_list = anInteraction.getAptamers(); if (a_list.size() == 0) { throw new Exception( "No aptamers provided. Please check submission : " + aFn); } else { for (Aptamer anApt : a_list) { if (anApt.getPolymerType().length() == 0) { throw new Exception( "No polymer type provided. Please check submission: " + aFn); } } } // now get the json version for these interactions JSONObject j = anInteraction.getJSONObject(); rm.put(j); } return rm; } }
PHP
UTF-8
489
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace Mikulas\Migrations; use Phinx\Migration\AbstractMigration; abstract class Migration extends AbstractMigration { const RESTRICT = 'RESCTRICT'; public static function restrict() { return [ 'delete' => self::RESTRICT, 'update' => self::RESTRICT ]; } /** * @param string $tableName * @param array $options * @return Table */ public function table($tableName, $options = []) { return new Table($tableName, $options, $this->getAdapter()); } }
Python
UTF-8
806
2.78125
3
[]
no_license
# coding: utf8 import sys import os import MeCab sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from model import Morpheme class MorphologicalAnalysis: sentence = "hello" def __init__(self, sentence): self.sentence = sentence def analysis(self): morpheme_list = [] mecab = MeCab.Tagger('') result = mecab.parse(self.sentence) result_list = result.split("\n") for a_result in result_list: splited_result = a_result.replace("\t", ",").split(",") if (splited_result[0] == 'EOS'): break morpheme = Morpheme.Morpheme( splited_result[0], splited_result[1], splited_result[2], splited_result[3], splited_result[4], splited_result[5], splited_result[6], splited_result[7] ) morpheme_list.append(morpheme) return morpheme_list
Python
UTF-8
1,549
2.640625
3
[]
no_license
# -*- coding:utf-8 -*- def sort_vocab_by_length(vocab): return sorted(vocab, key=lambda x:len(x), reverse=True) keyword_0102 = ["肝", "胆", "胰", "脾", "左肾", "右肾", "甲状腺", "前列腺"] keyword_0102 = sort_vocab_by_length(keyword_0102) keyword_0222 = ["鼻中隔", "鼻甲", "外耳道", "鼓膜", "扁桃体", "其他", "口咽黏膜", "鼻腔黏膜及分泌物"] keyword_0222 = sort_vocab_by_length(keyword_0222) keyword_0409 = ["病史", "既往史", "过敏史", "既往疾病史", "心脏杂音", "腹壁", "心律", "心率", "呼吸音", "肺罗音", "肺啰音"] keyword_0409 = sort_vocab_by_length(keyword_0409) keyword_0539 = ["阴道", "外阴", "子宫", "宫颈", "右侧附件", "左侧附件", "病史"] keyword_0539 = sort_vocab_by_length(keyword_0539) keyword_0709 = ["义齿", "龋齿", "缺齿", "牙周", "牙龈", "其他"] keyword_0709 = sort_vocab_by_length(keyword_0709) description_normal = ["未闻及", "未 闻及", "未见异常", "未减异常", "无异常", "没有异常", "正常", "未见明显异常", "未减明显异常", "无明显异常", "没有明显异常", "弃查", "已告知本人"] description_void = ["无", "未查", "弃查", "exit", "未未及"] description_0124 = ["未见扩张", "无扩张", "没有扩张", "未见明显扩张", "无明显扩张", "没有明显扩张"] description_0206 = ["无压痛", "未见压痛", "没有压痛"] description_0212 = ["无压痛", "未见压痛", "没有压痛"] description_0421 = ["不齐", "早搏"]
Java
UTF-8
1,195
1.84375
2
[]
no_license
package fortscale.spring; import fortscale.common.dataentity.DataEntitiesConfig; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.ClassPathResource; @Configuration public class PresidioUiCommonConfig { @Bean PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer(){ PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(false); propertySourcesPlaceholderConfigurer.setLocalOverride(true); propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("META-INF/entities.properties")); return propertySourcesPlaceholderConfigurer; } @Bean(name = "dataEntitiesConfig") DataEntitiesConfig dataEntitiesConfig(){ return new DataEntitiesConfig(); } }
Python
UTF-8
402
2.671875
3
[]
no_license
from abc import ABC import gym class Env(gym.Env, ABC): def __init__(self, env): self.env = gym.make(env) self.action_dim = self.env.action_space.n self.state_dim = self.env.observation_space.shape[0] def get_action_dim(self): return self.action_dim def get_state_dim(self): return self.state_dim def get_env(self): return self.env
JavaScript
UTF-8
179
2.96875
3
[]
no_license
console.log("Hello World"); function myFunction(a, b) { return a + b; } var x = myFunction(5, 10); console.log(x); console.log("I caused a merge conflict.");
C#
UTF-8
1,073
2.96875
3
[]
no_license
using Microsoft.EntityFrameworkCore; using SchoolMVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SchoolMVC.Repository { public class SchoolRepository : IRepository { public SchoolRepository() : base() { } public SchoolRepository(SchoolDbContext _db) : base (_db) { } public async Task Add(School entity) { await db.AddAsync(entity); } public School FindById(int id) { return db.Schools.Find(id); } public List<School> GetAll() { return db.Schools .OrderByDescending(x => x.Id) .ToList(); } public async Task Remove(int id) { School school = await db.Schools .Include(x => x.Classes) .ThenInclude(x => x.Students) .SingleOrDefaultAsync(x => x.Id == id); foreach(var item in school.Classes) { foreach(var item2 in item.Students) { db.Students.Remove(item2); } db.Classes.Remove(item); } db.Schools.Remove(school); } public async Task Update(School entity) { db.Schools.Update(entity); } } }
Shell
UTF-8
2,567
3.625
4
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash if [[ $# -eq 0 ]] ; then echo "Missing arguments." echo "Usage: bash install_mesos_cluster.bash masterHostname1,workerHostname1,workerHostname2,..." exit 0 fi cluster=$1 eval $(echo $cluster | awk '{split($0, array, ",");for(i in array)print "host_array["i"]="array[i]}') function checkSSH() { echo "Checking SSH connections" for(( i=2;i<=${#host_array[@]};i++)) ; do ssh ${host_array[i]} "hostname" if [ $? -eq 0 ] then echo -e "Can SSH to ${host_array[i]}" else echo -e "Cannot SSH to ${host_array[i]}, please fix." exit 255 fi done } checkSSH ## local_ip replace localhost in config file local_host="`hostname`" local_ip=`curl ifconfig.me` ## current_path replace data_path in config file current_path=`pwd` project_root_path=`cd ${current_path}/../.. && pwd` echo $current_path echo $project_root_path echo ========================================================= echo "Setup Mesos Master" echo ========================================================= echo "Installing and starting mesos-master" sudo ./install_mesos_master.bash $local_ip > /dev/null cd $current_path echo ========================================================= echo "Setting up Mesos Slaves" echo ========================================================= for(( i=2;i<=${#host_array[@]};i++)) ; do echo "Copying mesos files..." rsync -avz $current_path/../../../../SparkFHE-Addon/ ${host_array[i]}:$current_path/../../../../SparkFHE-Addon/ echo "Installing on ${host_array[i]}" echo "Installing and starting mesos-slave" ssh ${host_array[i]} "cd $current_path; sudo ./install_mesos_slave.bash $local_ip > /dev/null" echo "Cleaning up on ${host_array[i]}" ssh ${host_array[i]} "cd $current_path; rm -rf mesos*" done echo "Cleaning on on master" cd $current_path rm -rf mesos* # Start Spark Cluster dispatcher service echo "Starting Spark service" # cp configs/master/spark.service /etc/systemd/system/spark.service systemctl daemon-reload systemctl start spark.service systemctl enable spark systemctl restart zookeeper systemctl restart spark.service systemctl restart mesos-master # Run a sample Spark Job # echo "Running test Spark job" # /spark/bin/spark-submit --name SparkPiTestApp --class org.apache.spark.examples.SparkPi --master mesos://$local_ip:7077 --deploy-mode cluster --executor-memory 1G --total-executor-cores 30 /spark/examples/jars/spark-examples_2.11-2.2.0.jar 100 echo ========================== DONE =============================
C++
UTF-8
514
3.171875
3
[]
no_license
#include "units/Days.h" #include "units/Nanoseconds.h" #include "units/Seconds.h" namespace units { Seconds::Seconds(const Nanoseconds &n) : m_value(double(n.toSeconds())) { } Seconds::Seconds(const Days &n) : m_value(double(n.toSeconds())) { } Nanoseconds Seconds::toNanoseconds() const { return Nanoseconds(static_cast<int64_t>(m_value * 1000000000)); } Days Seconds::toDays() const { return Days(m_value / SECONDS_PER_DAY); } } // namespace
Markdown
UTF-8
321
2.59375
3
[ "MIT" ]
permissive
--- title: js-sort-array date: 2015-10-23 10:12:56 tags: js --- ## #code ``` /** * 对数组根据其首字母进行排序 * * @param arr * @returns {*} */ utils.sortArray = function (arr) { arr.sort(function (a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1; }); return arr; }; ```
Markdown
UTF-8
4,240
2.53125
3
[]
no_license
# LYRASOFT CLI 工具 這是為了 LYRASOFT 日常工作與建立設定檔所開發的方便工具。 ## 快速安裝 ```bash php -r "copy('https://raw.githubusercontent.com/lyrasoft/lyra-cli/master/resources/installer/lyra-cli-installer.php', 'lyra-cli-installer.php');" php lyra-cli-installer.php php -r "unlink('lyra-cli-installer.php');" ``` ## 一般安裝方式 快速安裝無法正確執行時,請依照以下步驟進行: ```bash composer global require lyrasoft/cli ``` 安裝完成後,可在任何地方直接輸入: ```bash lyra <command> ``` 來執行相關指令。 ### Mac / Linux 無法執行時 Mac 必須先將 ~/.composer/vendor/bin 加入到 PATH 環境變數 請參考 https://stackoverflow.com/a/25373254 ```bash echo 'export PATH="$PATH:$HOME/.composer/vendor/bin"' >> ~/.bash_profile source ~/.bash_profile ``` Linux 的路徑比較不一樣 ```bash echo 'export PATH="$PATH:$HOME/.config/composer/vendor/bin"' >> ~/.bashrc source ~/.bashrc ``` ## 自動完成 只要輸入一次 ```shell lyra autocomplete ``` 註冊好自動完成的指令後,之後就可以用 Tab 自動完成指令了 > 只支援 zsh ## 常用功能說明 ### 更新 PhpStorm 設定檔 我們的常用設定檔有三組,分別是 CodeStyle, FileTemplate 與 LiveTemplate 可以用: ```bash lyra pstorm:pull-config -a -g ``` 來更新 PhpStorm 的全域設定檔。也可以用: ```bash lyra pstorm:pull-config -a ``` 單純只更新到現在的專案 如果你要把自己設定好的設定檔更新到我們得 repository 給其他人分享,可以用: ```bash lyra pstorm:push-config -a ``` **注意這個動作不要隨便進行** ### Get PR 現在可以透過 lyra cli 快速取用 PR 來測試,取代以前的 `get-pr` 指令 ```bash lyra pr {number} ``` 預設會拉下來成 `pr-xxx` 的 branch,也可以指定特定的 branch: ```bash lyra pr {number} branch_name ``` 拉下後直接切換 ```bash lyra pr {number} -c ``` 預設是從 `lyra` 的 remote 取用 PR,請按照命名原則設定你的 git remote,也可以自定 remote ```bash lyra pr {number} -r=upstream ``` ### PHP Code Sniffer 先切換到專案目錄(確定已經先用 phpstorm 開啟過這個目錄,有 .idea 資料夾),第一次先執行: ```bash lyra pstorm sniffer -p ``` 就會自動設定好我們的 Sniffer 設定檔,並下載我們的 Code Style 規則。第二次之後可以省略 `-p` 直接啟用 phpstorm 的 sniffer 功能。 ```bash lyra pstorm:sniffer ``` 如果未來我們的 Sniffer 規則有更動,只要再執行第一個指令或者再任何地方執行: ```bash lyra sniffer:sync ``` 就會自動刷新 Sniffer 規則 ## 註冊 GitHub SSH Key lyra-cli 提供了方便的指令直接幫你註冊 GitHub SSH Key. 執行 ``` lyra github:add-ssh ``` 第一次會需要產生 SSH Key ``` Your identification has been saved in C:\Users\Xxx/.ssh/id_rsa. Your public key has been saved in C:\Users\Xxx/.ssh/id_rsa.pub. The key fingerprint is: SHA256:cT7l5fe4kzlKsxQle1jC6/0p4je********** The key's randomart image is: +---[RSA 4096]----+ | | | . | | . . = + | | + o @ o | | S o * B .| | o *.=.| | o E.=+.| | . @.O==+| | .+oB.*=+| +----[SHA256]-----+ ``` SSH Key 產生之後,會問你 GitHub 的登入帳密,輸入後便可自動註冊完成。 ## 完整指令說明 請直接用 `-h` 觀看說明 ## 開發方式 若要增加或修改功能,可以用 `composer global require lyrasoft/cli --prefer-source` ,這樣就會下載 github 上的版本,就可以直接 編輯,然後用 git commit 修改內容。 記得可以先 fork 一份,然後加上你自己的 remote。 編輯位置在 Composer 的 global 目錄: - Windows: `C:\Users\<user_name>\AppData\Roaming\Composer` - Mac: `~/.composer` lyra-cli 的目錄在 `{COMPOSER_HOME}/vendor/lyrasoft/cli` 內。 ### Command 的編寫方式 最上層 Command 請寫好 class 之後,註冊在 `/lyra` 檔案內。 See: https://github.com/lyrasoft/lyra-cli/blob/6c76cacd4a62393337e6c37f49f80dd263bd920d/lyra#L34 之後的寫法請參考: [Windwalker Console](https://github.com/ventoviro/windwalker-console#windwalker-console)
JavaScript
UTF-8
3,002
2.890625
3
[]
no_license
class BankAccounts extends React.Component{ constructor(props){ super(props); this.fetchBankAccounts = this.fetchBankAccounts.bind(this); this.newAccount = this.newAccount.bind(this); this.deleteAccount = this.deleteAccount.bind(this); this.state = { bankAccounts: [], netCalculation: 0 }; } componentDidMount(){ this.fetchBankAccounts(); } fetchBankAccounts(){ $.ajax({ url: '/bank_accounts', type: 'GET' }).success( data => { this.setState( { bankAccounts: data.bankAccounts }); }); $.ajax({ url: '/net_calculation', type: 'GET' }).success( data => { this.setState({ netCalculation: data }); }).error( data => { console.log(data); }); } newAccount(){ $.ajax({ url: '/bank_accounts', type: 'POST', data: { bank_account: {name: this.refs.accountName.value, money: this.refs.accountBalance.value } } }).success( data => { let bankAccounts = this.state.bankAccounts; bankAccounts.unshift(data.bankAccount); this.refs.accountName.value = null; this.refs.accountBalance.value = null; this.setState({ bankAccounts: bankAccounts}); }).error( data => { console.log(data) }); } deleteAccount(id){ $.ajax({ url: '/bank_accounts/' + id, type: 'DELETE' }).success( data =>{ this.fetchBankAccounts(); }).error(data => { console.log(data); }); } break_even(){ const BREAK_EVEN = 0 if (this.state.netCalculation > BREAK_EVEN){ return(<div className='col s10 offset-s1 green'> <h4 className='center'>Net Balance: ${this.state.netCalculation}</h4> </div>); } else { return(<div className='col s10 offset-s1 red'> <h4 className='center'>Net Balance: ${this.state.netCalculation}</h4> </div>); } } render(){ let bankAccounts = this.state.bankAccounts.map( bankAccount => { let key = `bankAccount-${bankAccount.id}`; return (<BankAccount key={key} deleteAccount={this.deleteAccount} fetchBankAccounts={this.fetchBankAccounts} {...bankAccount} />) }); return(<div> {this.break_even()} <div className=''> <div className='col s10 offset-s1 m5 offset-m1'> <form onSubmit={this.newAccount}> <h3 className='center'>Add Account</h3> <input type='text' placeholder="Account Name" ref='accountName' autoFocus={true} /> <input type='number' placeholder='Account Balance' ref='accountBalance' /> <button type='submit' className='btn waves-effect waves-light'>Save</button> </form> <div> </div> <div> <h1 className='center'>Bank Accounts</h1> <hr /> {bankAccounts} </div> </div> </div> </div>); } }
Python
UTF-8
2,715
3.71875
4
[]
no_license
from multiprocessing import Pool def factorial(arr): result = 1 for i in arr: result *= i return result """Breaking input number into chunks and calculating factorial of each chunk""" def main(n, workers): # Creating a process pool with number of processes given when main function is called p = Pool(processes=workers) # Splitting the given number into array consisting of arrays with numbers numbers = range(1, n+1) slices = [numbers[i::workers] for i in range(workers)] # Mapping the slices array to processes where factorial of each chunk is calculated chunks = p.map(factorial, slices) p.close() p.join() # Getting the result result = 1 for c in chunks: result *= c return result print(main(2,1)) '''import threading import math class f(threading.Thread): def __init__(self,num): threading.Thread.__init__(self) self.num = num def run(self): global result temp = math.factorial(self.num) print("%s: calculate %d's factorial is %d" %(self.name,self.num,temp)) result += temp result = 0 threads = [] def test(): for i in range(1,6): t = f(i) threads.append(t) for i in range(5): threads[i].start() for i in range(5): threads[i].join() if __name__ == '__main__': test() print ('The result is %d' %result ) ''' ''' import threading, time, random def somaThread(lista, soma_parcial, id): soma = 0 for i in lista: soma = soma + i soma_parcial[id] = soma N = int(input("Entre com o tamanho do vetor: ")) # Captura tempo inicial t_inicio = float(time.time()) # Gera lista com valores aleatórios lista = [] for i in range(N): lista.append(random.randint(2, 30)) Nthreads = 4 # Número de threads a ser criado # Vetor para salvar a soma parcial de cada thread soma_parcial = Nthreads * [0] lista_threads = [] for i in range(Nthreads): ini = i * int(N/Nthreads) # início do intervalo da lista fim = (i + 1) * int(N/Nthreads) # fim do intervalo da lista t = threading.Thread(target=somaThread, args=(lista[ini:fim],soma_parcial, i)) t.start() # inicia thread lista_threads.append(t) # guarda a thread for t in lista_threads: t.join() # Espera as threads terminarem soma = 0 for i in soma_parcial: soma = soma + i # Captura tempo final t_fim = float(time.time()) # Imprime o resultado e o tempo de execução print(lista) print("Soma:", soma) print("Tempo total:", t_fim - t_inicio) '''
Python
UTF-8
2,089
3.03125
3
[ "MIT" ]
permissive
# built-in import os.path from hashlib import sha256 from urllib.parse import unquote from typing import Optional # app from ._cached_property import cached_property from ._constants import IS_WINDOWS class _PathLink: def __init__(self, link: str): self.short = link.split('#')[0] self.long = link @classmethod def parse(cls, link) -> Optional['_PathLink']: if '@' in link: return None if IS_WINDOWS and link.startswith('file:///'): # cygwin-like absolute paths (file:///c:/foo/bar) link = link[len('file:///'):] elif link.startswith('file://'): link = link[len('file://'):] if '://' in link: return None path = link.replace('/', os.path.sep).split('#')[0] if not cls._check(path): return None return cls(link) @staticmethod def _check(path: str) -> bool: raise NotImplementedError @property def name(self) -> Optional[str]: # get last part of path path = os.path.abspath(self.short.replace('/', os.path.sep)) name = os.path.basename(path) # drop all extensions, because in Python package name has no dots name = name.split('.')[0] # pip can return urlencoded name name = unquote(name) return name or None @cached_property def hash(self) -> str: with open(self.short, 'rb') as stream: content = stream.read() hasher = sha256() hasher.update(content) return 'sha256:' + hasher.hexdigest() def __str__(self) -> str: return self.long def __repr__(self) -> str: return '{}({})'.format(type(self).__name__, str(self)) class FileLink(_PathLink): @staticmethod def _check(path: str) -> bool: if os.path.isfile(path): return True if '://' in path: return False return path.endswith('.py') class DirLink(_PathLink): @staticmethod def _check(path: str) -> bool: return os.path.isdir(path)
TypeScript
UTF-8
1,521
2.609375
3
[]
no_license
import { IContext } from "./lib"; import { userCreate, userJoin } from "../models/user"; import { codeScene } from "./lib/scenes"; import { mainMenuKeyboard, shareCodeKeyboard, retryCodeKeyboard, } from "./lib/keyboards"; export const register = { setup: function (bot: any): void { bot.action("create", triggers.create); bot.action("join", triggers.join); codeScene.on("text", triggers.code); }, }; const triggers = { create: async function (ctx: IContext): Promise<void> { const { code, success } = await userCreate( ctx.from!.id, ctx.from!.first_name ); const message = success ? `You have created a group with code:\n\`${code}\`.` : `You already belong to a group.`; ctx.editMessageText( message, success ? shareCodeKeyboard(code!) : mainMenuKeyboard ); }, join: async function (ctx: IContext): Promise<void> { ctx.scene.enter("code"); ctx.editMessageText( `Please enter the *code* of the group you are joining.`, { parse_mode: "Markdown" } ); }, code: async function (ctx: IContext): Promise<void> { const code = ctx.update.message!.text!.trim(); const { message, success } = await userJoin( ctx.from!.id, ctx.from!.first_name, code ); ctx.scene.leave("code"); if (success) { ctx.reply( `You have successfully joined the group.\n\n` + message, mainMenuKeyboard ); } else { ctx.reply(message, retryCodeKeyboard); } }, };
Python
UTF-8
269
3.921875
4
[ "MIT" ]
permissive
def sum_occurrences(N): count = 0 square_N = N ** 2 for num in range(square_N + 1): for digit in str(num): count += str(N).count(str(digit)) return count # Example usage N = int(input()) result = sum_occurrences(N) print(result)
Java
UTF-8
1,033
2.21875
2
[]
no_license
package com.gkzxhn.wisdom.property.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.gkzxhn.wisdom.property.R; /** * Created by Raleigh.Luo on 17/9/11. */ public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> { private Context context; public MessageAdapter(Context context) { this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view= LayoutInflater.from(context).inflate(R.layout.message_item_layout,null,false); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder holder, int position) { } @Override public int getItemCount() { return 10; } class ViewHolder extends RecyclerView.ViewHolder{ public ViewHolder(View itemView) { super(itemView); } } }
Java
UTF-8
1,510
2.125
2
[]
no_license
package api.pruebas; import java.sql.SQLException; import api.controlador.DAO.Dao_Producto; import api.modelo.Categoria; import api.modelo.Empresa; import api.modelo.Marca; import api.modelo.Producto; import api.modelo.Unidad_Medida; public class Prueba_InsertarProducto { public static void main(String[] args) { // TODO Auto-generated method stub //Producto p1 = new Producto(); Empresa e1 = new Empresa(); Marca m1 = new Marca(); Categoria c1 = new Categoria(); Unidad_Medida u1 = new Unidad_Medida(); e1.setId_empresa(1); u1.setId_UnidadMedida(1); u1.setValorUnidadMedida(1); m1.setId_marca(1); c1.setId_categoria(1); /** p1.setEmpresa(e1); p1.setCategoriaProducto(c1); p1.setMarca(m1); p1.setUnidadMedida(u1); p1.setNombre("Prueba desde eclipse5"); p1.setCantidadDisponible(1); p1.setCantidadMaxima(1); p1.setCantidadMinima(1); //p1.setCodigoBarras(12345); //p1.setCosto(1); //p1.setImpuesto(1); //p1.setPrecio(1); p1.setUrlImagen("none");*/ Producto p1 = new Producto(); p1.setId_producto(2); p1.setNombre("Frijoles Don Pedro"); p1.setEmpresa(e1); p1.setCantidadDisponible(10); p1.setCantidadMaxima(100); p1.setCantidadMinima(30); p1.setCategoriaProducto(c1); p1.setCodigoBarras(12345678); p1.setCosto(1000); p1.setImpuesto(0); p1.setMarca(m1); p1.setPrecio(1100); p1.setUnidadMedida(u1); p1.setUrlImagen("C://url"); Dao_Producto dp = new Dao_Producto(); //dp.editarProducto(p1); dp.desecharProducto(1, 40); } }
PHP
UTF-8
7,997
2.734375
3
[ "MIT" ]
permissive
<?php namespace Tests\Type; use Closure; use Ukon\Math; use Tests\Stubs\Length\Metre; use Tests\Stubs\Length\Length; use Tests\Stubs\Weight\Weight; use PHPUnit\Framework\TestCase; use Tests\Stubs\Length\Centimetre; use Tests\Stubs\Length\Millimetre; use Ukon\Exceptions\DifferentTypeException; class SubtractTest extends TestCase { public function testSubPositiveUnit() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->subMetre(1)->subCentimetre(80)->subMillimetre(50); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(1, new Math(1), new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(-10, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(0, new Math(1)))); }, $length, Length::class)($this); } public function testSubZeroUnit() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->subMetre(0)->subCentimetre(0)->subMillimetre(0); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(2, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(70, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(50, new Math(1)))); }, $length, Length::class)($this); } public function testSubNegativeUnit() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->subMetre(-2)->subCentimetre(-80)->subMillimetre(-40); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(4, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(150, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(90, new Math(1)))); }, $length, Length::class)($this); } public function testSubPositiveType() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->sub((new Length(1))->addMetre(1)->addCentimetre(70)->addMillimetre(80)); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(1, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(0, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(-30, new Math(1)))); }, $length, Length::class)($this); } public function testSubZeroType() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->sub((new Length(1))->addMetre(0)->addCentimetre(0)->addMillimetre(0)); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(2, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(70, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(50, new Math(1)))); }, $length, Length::class)($this); } public function testSubNegativeType() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->sub((new Length(1))->addMetre(-3)->addCentimetre(-20)->addMillimetre(-100)); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(5, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(90, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(150, new Math(1)))); }, $length, Length::class)($this); } public function testSubPositiveDecimalUnit() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->subMetre(1.5)->subCentimetre(80.8)->subMillimetre(50.3); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(0.5, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(-10.8, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(-0.3, new Math(1)))); }, $length, Length::class)($this); } public function testSubZeroDecimalUnit() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->subMetre(0.0)->subCentimetre(0.0)->subMillimetre(0.0); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(2, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(70, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(50, new Math(1)))); }, $length, Length::class)($this); } public function testSubNegativeDecimalUnit() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->subMetre(-2.5)->subCentimetre(-80.8)->subMillimetre(-40.4); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(4.5, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(150.8, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(90.4, new Math(1)))); }, $length, Length::class)($this); } public function testSubPositiveDecimalType() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->sub((new Length(1))->addMetre(1.5)->addCentimetre(70.3)->addMillimetre(80.7)); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(0.5, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(-0.3, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(-30.7, new Math(1)))); }, $length, Length::class)($this); } public function testSubZeroDecimalType() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->sub((new Length(1))->addMetre(0.0)->addCentimetre(0.0)->addMillimetre(0.0)); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(2, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(70, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(50, new Math(1)))); }, $length, Length::class)($this); } public function testSubNegativeDecimalType() { $length = (new Length(1))->addMetre(2)->addCentimetre(70)->addMillimetre(50); $length->sub((new Length(1))->addMetre(-3.3)->addCentimetre(-20.5)->addMillimetre(-100.7)); Closure::bind(function ($self) { $self->assertTrue($this->units[Metre::class]->equalTo(new Metre(5.3, new Math(1)))); $self->assertTrue($this->units[Centimetre::class]->equalTo(new Centimetre(90.5, new Math(1)))); $self->assertTrue($this->units[Millimetre::class]->equalTo(new Millimetre(150.7, new Math(1)))); }, $length, Length::class)($this); } public function testSubDifferentType() { $length = new Length(1); $weight = new Weight(1); $this->expectException(DifferentTypeException::class); $length->sub($weight); } }
C
UTF-8
1,531
2.765625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* l_del.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sladonia <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/02/26 15:45:17 by sladonia #+# #+# */ /* Updated: 2017/02/26 15:45:20 by sladonia ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static void sub_l_del(t_lst **head, void (*f)(void *content)) { t_lst *next; t_lst *tmp; tmp = *head; next = tmp->next; (*f)(tmp->content); free(tmp); *head = next; return ; } void l_del(t_lst **head, t_lst *this, void (*f)(void *content)) { t_lst *prev; t_lst *next; t_lst *tmp; if (!(this && head && (tmp = *head))) return ; if (tmp->content == this->content) { sub_l_del(head, f); return ; } prev = tmp; while (tmp) { if (tmp->content == this->content) { next = tmp->next; (*f)(tmp->content); free(tmp); prev->next = next; return ; } prev = tmp; tmp = tmp->next; } }
PHP
UTF-8
2,113
2.609375
3
[]
no_license
<?php namespace Mediacurrent\CiScripts\Command; trait Theme { /** * Theme Build command. * * theme:build runs the following - * * nvm use * npm install * npm run build * * @param string $pathToTheme Absolute path to the theme directory. * * @return object Result */ public function themeBuild($pathToTheme = null) { $this->taskThemeBuild() ->themeDirectory($pathToTheme) ->nvmUse() ->npmInstall() ->npmRunBuild() ->run(); } /** * Theme Compile command. * * theme:compile runs the following - * * nvm use * npm install * npm run compile * * @param string $pathToTheme Absolute path to the theme directory. * * @return object Result */ public function themeCompile($pathToTheme = null) { $this->taskThemeStyleGuide() ->themeDirectory($pathToTheme) ->nvmUse() ->npmInstall() ->npmRunCompile() ->run(); } /** * Theme Style Guide command. * * theme:style-guide runs the following - * * nvm use * npm install * npm run styleguide * * @param string $pathToTheme Absolute path to the theme directory. * * @return object Result */ public function themeStyleGuide($pathToTheme = null) { $this->taskThemeStyleGuide() ->themeDirectory($pathToTheme) ->nvmUse() ->npmInstall() ->npmRunStyleGuide() ->run(); } /** * Theme Watch command. * * theme:watch runs the following - * * nvm use * npm install * npm run watch * * @param string $pathToTheme Absolute path to the theme directory. * * @return object Result */ public function themeWatch($pathToTheme = null) { $this->taskThemeWatch() ->themeDirectory($pathToTheme) ->nvmUse() ->npmInstall() ->npmRunWatch() ->run(); } }
Shell
UTF-8
536
3.515625
4
[]
no_license
#!/bin/bash if [ $# -ne 1 ]; then echo $(ls ~/.config/bkgs | sed 's/.png//') exit 0 fi if ls ~/.config/bkgs/ | grep -q "$1.png" ; then # The image exists if ! $(themer list | grep -q "$1"); then # no theme yet, generate it echo N | themer -t myi3 generate "$1" ~/.config/bkgs/$1.png > /dev/null fi cp ~/.config/bkgs/$1.png ~/.config/background.png themer activate "$1" xrdb -load ~/.config/themer/current/.Xresources else echo "Could not find $1.png in ~/.config/bkgs!" fi exit 0
Python
UTF-8
591
2.8125
3
[]
no_license
import scipy.io as sio import numpy as np import matplotlib.pylab as plt data = sio.loadmat("data.mat") x = data.get("x") y = data.get("y") u = data.get("u") v = data.get("v") xit = data.get("xit") yit = data.get("yit") velocity_components = np.sqrt(u**2 + v**2) plt.figure() plt.subplot(2, 1, 1) plt.plot(xit, yit, "k*") CS = plt.contourf(x, y, velocity_components, np.linspace(0, 500, 100)) plt.colorbar(CS) plt.subplot(2, 1, 2) plt.plot(xit, yit, "k*") CS2 = plt.contourf(x, y, velocity_components, np.linspace(1000, 5000, 100)) plt.colorbar(CS2) plt.savefig("oppg_b.png") plt.show()
Go
UTF-8
771
2.5625
3
[]
no_license
package handler import ( "github.com/spf13/cobra" "github.com/kzmake/example-uber-go-dig/infrastructure/renderer" "github.com/kzmake/example-uber-go-dig/interface/controller" ) // TaskHandler ... type TaskHandler struct { controller *controller.TaskController renderer *renderer.TaskRenderer } // NewTaskHandler ... func NewTaskHandler( controller *controller.TaskController, renderer *renderer.TaskRenderer, ) *TaskHandler { return &TaskHandler{controller: controller, renderer: renderer} } // CreateTask ... func (h *TaskHandler) CreateTask(cmd *cobra.Command, args []string) error { data, err := cmd.PersistentFlags().GetString("data") if err != nil { return err } o := h.controller.CreateTask(data) h.renderer.CreateTask(cmd, o) return nil }
C++
UTF-8
2,465
2.953125
3
[]
no_license
#ifndef TYPE_HPP #define TYPE_HPP #include "ast.cpp" #include <iostream> Type* check(Context& cxt, Expr* e) { struct V : Expr::Visitor { Context& cxt; Type* r; V(Context& c) : cxt(c) { } void visit(Bool_expr* e) { r = &cxt.bool_type; } void visit(Int_expr* e) { r = &cxt.int_type; } void visit(And_expr* e) { // check that e->e1 is bool // check that e->e2 is bool r = &cxt.bool_type; } void visit(Or_expr* e) { // check that e->e1 is bool // check that e->e2 is bool r = &cxt.bool_type; } void visit(Logical_neg_expr* e) { // check that e->e1 is bool r = &cxt.bool_type; } void visit(Cond_expr* e) { // check that e->e1 is bool } void visit(Equal_expr* e){ // check that e->e1 is bool // check that e->e2 is bool r = &cxt.bool_type; } void visit(Not_Equal_expr* e){ // check that e->e1 is bool // check that e->e2 is bool r = &cxt.bool_type; } void visit(Greater_than_expr* e){ // check that e->e1 is bool // check that e->e2 is bool r = &cxt.bool_type; } void visit(Less_than_expr* e){ // check that e->e1 is bool // check that e->e2 is bool r = &cxt.bool_type; } void visit(Greater_orEqual_expr* e){ // check that e->e1 is bool // check that e->e2 is bool r = &cxt.bool_type; } void visit(Less_orEqual_expr* e){ // check that e->e1 is bool // check that e->e2 is bool r = &cxt.bool_type; } void visit(Add_expr* e){ // check that e->e1 is bool // check that e->e2 is bool r = &cxt.int_type; } void visit(Sub_expr* e){ // check that e->e1 is bool // check that e->e2 is bool r = &cxt.int_type; } void visit(Mult_expr* e){ // check that e->e1 is bool // check that e->e2 is bool r = &cxt.int_type; } void visit(Div_expr* e){ // check that e->e1 is bool // check that e->e2 is bool r = &cxt.int_type; void visit(Arithmetic_neg_expr* e){ r = &cxt.int_type; } void visit(Reference_expr* e) { // check if the reference is a variable or function } void visit(Valuation_expr* e) { // } void visit(Assignment_expr* e) { } void visit(Function_call_expr* e) { } }; V vis(cxt); e->accept(vis); return vis.r; } #endif
Markdown
UTF-8
954
3.09375
3
[ "MIT" ]
permissive
# Getting Started Install the package using npm: ``` npm install --save cmd-ts ``` or if you use Yarn: ``` yarn add cmd-ts ``` ## Using `cmd-ts` All the interesting stuff is exported from the main module. Try writing the following app: ```ts import { command, run, string, positional } from 'cmd-ts'; const app = command({ name: 'my-first-app', args: { someArg: positional({ type: string, displayName: 'some arg' }), }, handler: ({ someArg }) => { console.log({ someArg }); }, }); run(app, process.argv.slice(2)); ``` This app is taking one string positional argument and prints it to the screen. Read more about the different parsers and combinators in [Parsers and Combinators](./parsers.md). > **Note:** `string` is one type that comes included in `cmd-ts`. There are more of these bundled in the [included types guide](./included_types.md). You can define your own types using the [custom types guide](./custom_types.md)
C#
UTF-8
388
2.640625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BridgeDesignPattern.Lab_2.Abstraction { public abstract class MailSenderBase { public void Save() { Console.WriteLine("Message saved..!"); } public abstract void Send(MailStructure mailStructure); } }
Java
UTF-8
667
1.757813
2
[]
no_license
/** * */ package com.offact.salesb.service.history; import java.util.List; import org.json.simple.JSONArray; import com.offact.framework.exception.BizException; import com.offact.salesb.vo.history.SmsHistoryVO; /** * @author 4530 * */ public interface SmsHistoryService { /** * SMS이력 조회 * * @return * @throws BizException */ public List<SmsHistoryVO> getSmsHistoryPageList(SmsHistoryVO work) throws BizException; /** * SMS이력 갯수 * * @return * @throws BizException */ public int getSmsHistoryCnt(SmsHistoryVO work) throws BizException; }
C#
UTF-8
1,301
3.34375
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace bai1 { public class Post : IPost { private int Id; private string Title; private string Content; private string Author; private float AverageRate; public const int MinRating = 1; public const int MaxRating = 5; private const int Count = 3; public int[] Rates = new int[Count]; public int Id1 { get => Id; set => Id = value; } public string Title1 { get => Title; set => Title = value; } public string Content1 { get => Content; set => Content = value; } public string Author1 { get => Author; set => Author = value; } public float AverageRate1 { get => AverageRate; private set => AverageRate = value; } public void CalculatorRate() { float total = 0; foreach (var rate in Rates) { total += rate; } AverageRate = (float)Math.Round(total / Rates.Length, 0); } public void Display() { CalculatorRate(); Console.WriteLine($"ID: {Id}, Tittle: {Title}, Content: {Content}, Author: {Author}, NumberofRate: {Count}, AvegareRate: {AverageRate}"); } } }
C++
UTF-8
1,835
2.53125
3
[]
no_license
#include "gameobject.h" int GameObject::countID = 0; GameObject::GameObject() { } GameObject::GameObject(char *newName) { name = newName; numImages = 0; numFrames = 0; state = DEAD; onScreen = false; countID++; objectID = countID; } GameObject::~GameObject() { } void GameObject::setName(char* n) { name = n; } const char *GameObject::getName() { return name.str(); } void GameObject::setID(int id) { objectID = id; } int GameObject::getID() { return objectID; } void GameObject::setState(gameObjectState s) { state = s; } gameObjectState GameObject::getState() { return state; } void GameObject::setOnScreen(Logical screen) { onScreen = screen; } Logical GameObject::getOnScreen() { return onScreen; } void GameObject::setWidth(double w) { width = w; } double GameObject::getWidth() { return width; } void GameObject::setHeight(double h) { height = h; } double GameObject::getHeight() { return height; } RECT GameObject::getDimension() { RECT rct; rct.left = 1; rct.top = 1; rct.right = getWidth(); rct.bottom = getHeight(); return rct; } void GameObject::setNumImages(int nf) { numImages = nf; } int GameObject::getNumImages() { return numImages; } void GameObject::addImage(ImageInfo image) { images.push_back(image); numImages++; } void GameObject::setNumFrames(int nf) { numFrames = nf; } int GameObject::getNumFrames() { return numFrames; } void GameObject::setCurrentFrame(LPDIRECTDRAWSURFACE7 current) { currentFrame = current; } LPDIRECTDRAWSURFACE7 GameObject::getCurrentFrame() { return currentFrame; } void GameObject::reInitFrameTimer() { frameTimer.init(); } GameFrame GameObject::getFrameTimer() { return frameTimer; }
SQL
UTF-8
1,363
3.765625
4
[]
no_license
CREATE TABLE Executions ( id varchar(36) primary key, source_name varchar(16) not null, trigger_type varchar(32) not null, trigger varchar(512) not null, time_created timestamp not null ); CREATE INDEX Executions_source ON Executions(source_name, trigger_type, time_created); CREATE INDEX Executions_time ON Executions(time_created); CREATE TABLE DocumentEvents ( id varchar(36) primary key, source_name varchar(16) not null, external_id varchar(1024), internal_id varchar(64) not null, stage varchar(32) not null, severity varchar(32) not null, time_created timestamp not null, execution_id varchar(36) not null REFERENCES Executions(id) ); CREATE INDEX DocumentEvents_internal_id ON DocumentEvents(internal_id, execution_id, stage); CREATE INDEX DocumentEvents_external_id ON DocumentEvents(external_id, source_name); CREATE INDEX DocumentEvents_execution ON DocumentEvents(execution_id, time_created); CREATE INDEX DocumentEvents_time ON DocumentEvents(time_created); ALTER TABLE Diagnostics ADD COLUMN documentevent_id varchar(36) null REFERENCES DocumentEvents(id); ALTER TABLE Diagnostics ALTER COLUMN processing_error_id DROP NOT NULL; ALTER TABLE Processingerrors ADD COLUMN documentevent_id varchar(36) null REFERENCES DocumentEvents(id); ALTER TABLE Processingerrors ADD COLUMN execution_id varchar(36) null REFERENCES Executions(id);
C#
UTF-8
1,136
2.578125
3
[]
no_license
using System; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : Page { protected void SubmitButton_Click(object sender, EventArgs e) { // Done: // The SubmitButton_Click event handler of the partial _Default class is modified // so that if the page is valid, the message "Page is valid" is applied to the // ResultLabel control. // If the page is not valid, the message "Page is not valid" is applied to the // control. if (Page.IsValid) ResultLabel.Text = "Page is valid"; else ResultLabel.Text = "Page is not valid"; } protected void UserIDTextValidator_ServerValidate(object source, ServerValidateEventArgs args) { // Do not modify this event handler. if (args.Value.Length > 8 && args.Value == args.Value.ToUpper()) args.IsValid = true; else args.IsValid = false; } protected void LoginNameTextValidator_ServerValidate(object source, ServerValidateEventArgs args) { // Do not modify this event handler. if (string.IsNullOrEmpty(args.Value)) args.IsValid = false; else args.IsValid = DataHelper.DoesLoginNameExist(args.Value); } }
C++
UTF-8
1,364
3.875
4
[]
no_license
#include<bits/stdc++.h> using namespace std; struct node{ int val; node* next; }; node* head=NULL; void push(int key) { struct node* new_node=new node(); new_node->val=key; new_node->next=head; head=new_node; } int search(int key) { struct node* it=head; int pos=1; while(it!=NULL) { if(it->val==key) { return pos; } pos++; it=it->next; } return -1; } void display() { struct node* ptr=head; while(ptr!=NULL) { cout<<ptr->val<<" "; ptr=ptr->next; } } void del_node(int key) { struct node* ptr; struct node* prv; ptr=head; if(ptr!=NULL&&ptr->val==key) { head=ptr->next; delete(ptr); return; } while(ptr!=NULL&&ptr->val!=key) { prv=ptr; ptr=ptr->next; } if(ptr==NULL) { cout<<"Element not present!"<<endl; } prv->next=ptr->next; delete(ptr); } int main() { cout<<"Enter no of values:"; int n,t,k,d; cin>>n; cout<<"Enter the values to insert in singly linked list:"; for(int i=0;i<n;i++) { cin>>t; push(t); } cout<<"Enter value to search in linked list:"<<endl; cin>>k; int res=search(k); if(res==-1) cout<<"Element not found!"; else cout<<"Element found at position "<<res<<endl; cout<<"Enter a value to delete from linked list:"; cin>>d; del_node(d); cout<<"List after deletion is: "; display(); }
Python
UTF-8
87
2.78125
3
[]
no_license
#import turtle as t #t.shape('turtle') #t.forward(100) #t.right(90) #t.forward(200)
C++
UTF-8
7,270
3.671875
4
[]
no_license
#include "puzzle.h" #include <iostream> #include <algorithm> int main(int argc, char* argv[]) { // Test the At function // Puzzle is // a b c // d e f // g h i Puzzle puzzle("abcdefghi", 3); if(puzzle.At({0,0}) != 'a') std::cout << "At((0,0))" << std::endl; if(puzzle.At({0,1}) != 'b') std::cout << "At((0,1))" << std::endl; if(puzzle.At({0,2}) != 'c') std::cout << "At((0,2))" << std::endl; if(puzzle.At({1,0}) != 'd') std::cout << "At((1,0))" << std::endl; if(puzzle.At({1,1}) != 'e') std::cout << "At((1,1))" << std::endl; if(puzzle.At({1,2}) != 'f') std::cout << "At((1,2))" << std::endl; if(puzzle.At({2,0}) != 'g') std::cout << "At((2,0))" << std::endl; if(puzzle.At({2,1}) != 'h') std::cout << "At((2,1))" << std::endl; if(puzzle.At({2,2}) != 'i') std::cout << "At((2,2))" << std::endl; // Test the Set function puzzle.Set({1,2}, 'q'); if(puzzle.At({1,2}) != 'q') std::cout << "Set((1,2))" << std::endl; // Test the WordStart function // Puzzle is // a b c d // e # f g // h j k // l n o Puzzle puzzle2("abcde#fgh jkl no", 4); if(puzzle2.WordStart({0,0}, Direction::DOWN) != std::pair<int, int>({0,0})) std::cout << "WordStart(0,0)" << std::endl; if(puzzle2.WordStart({1,0}, Direction::DOWN) != std::pair<int, int>({0,0})) std::cout << "WordStart(1,0)" << std::endl; if(puzzle2.WordStart({1,3}, Direction::ACROSS) != std::pair<int, int>({1,2})) std::cout << "WordStart(1,3)" << std::endl; // Test the WordAt function. if(puzzle2.WordAt({0,0}, Direction::ACROSS) != "abcd") std::cout << "WordAt(0,0,across)" << std::endl; if(puzzle2.WordAt({0,0}, Direction::DOWN) != "aehl") std::cout << "WordAt(0,0,down)" << std::endl; if(puzzle2.WordAt({1,2}, Direction::ACROSS) != "fg") std::cout << "WordAt(1,2,across)" << std::endl; if(puzzle2.WordAt({2,1}, Direction::DOWN) != " ") std::cout << "WordAt(2,1,down)" << std::endl; if(puzzle2.BlanksInWordAt({0,0}, Direction::ACROSS) != 0) std::cout << "BIWA(0,0,across)" << std::endl; if(puzzle2.BlanksInWordAt({2,0}, Direction::ACROSS) != 1) std::cout << "BIWA(2,0,across)" << std::endl; if(puzzle2.BlanksInWordAt({2,1}, Direction::DOWN) != 2) std::cout << "BIWA(2,1,across)" << std::endl; // Test WordAt with spaces. Puzzle puzzle3("a c", 2); if(puzzle3.WordAt({0,0}, Direction::ACROSS) != "a ") std::cout << "with spaces, WordAt(0,0,across)" << std::endl; if(puzzle3.WordAt({1,0}, Direction::ACROSS) != " c") std::cout << "with spaces, WordAt(1,0,across)" << std::endl; // Test the SetWord function puzzle2.SetWord({3,0}, Direction::ACROSS, "test"); if(puzzle2.WordAt({3,0}, Direction::ACROSS) != "test") std::cout << "SetWord(3,0,across)" << puzzle2.Data() << std::endl; // Test the AllWords function Puzzle all_words_puzzle("ab#cdefghijk#lmn", 4); auto all_words = all_words_puzzle.AllWords(); std::sort(all_words.begin(), all_words.end()); std::vector<std::string> expected_all_words = {"ab", "adh", "beil", "c", "cgkn", "defg", "fjm", "hijk", "lmn"}; if(all_words.size() != expected_all_words.size()) std::cout << "all_words size wrong"; for(int i = 0; i<all_words.size(); ++i) { if(all_words[i] != expected_all_words[i]) std::cout << "i is " << i << "all_words[i] is " << all_words[i] << " but expected_all_words[i] is " << expected_all_words[i]; } // Test Puzzle::Matches with a 3x3 puzzle: // # ? # // ? ? ? // # # # // And the dictionary: [abc, def, xxx, ab, bb, be, a, g] // Vary the singleton letter at the top and query the triple-long one // * singleton:empty, expect abc, def // * singleton:a, expect abc // * singleton:g, expect nothing // Some of the words are put into the "user" vector word finder VectorWordFinder vwf({"abc","xxx","bb","be","a","g"}); VectorWordFinder uvwf({"def", "ab", "g"}); Puzzle matches_puzzle_1("# # ###", 3); Puzzle matches_puzzle_2("#a# ###", 3); Puzzle matches_puzzle_3("#g# ###", 3); Word word({1,0}, Direction::ACROSS); const auto matches_1 = matches_puzzle_1.Matches(word.coords_, word.direction_, &vwf, &uvwf); const auto matches_2 = matches_puzzle_2.Matches(word.coords_, word.direction_, &vwf, &uvwf); const auto matches_3 = matches_puzzle_3.Matches(word.coords_, word.direction_, &vwf, &uvwf); if(matches_1.size() != 2) { std::cout << "matches_1 has bad size " << matches_1.size() << std::endl; for(const auto& match : matches_1) std::cout << match << std::endl; } else if(!((matches_1[0] == "abc" && matches_1[1] == "def") || (matches_1[0]=="def" && matches_1[1] == "abc"))) { std::cout << "matches_1 has right size but bad elements " << matches_1[0] << "," << matches_1[1]; } if (matches_2.size() != 1) { std::cout << "matches_2 has bad size " << matches_2.size(); } else if (matches_2[0] != "abc") { std::cout << "matches_2 has bad element " << matches_2[0]; } if (matches_3.size() != 0) { std::cout << "matches_3 has bad size " << matches_3.size(); } // Test As Graph: 3x3 donut with things on the side like this // a x // b # c x // d x // x x x x Puzzle graph_puzzle(" a xb#cx d xxxxx", 4); PuzzleGraph graph = graph_puzzle.AsGraph(); // TODO: this makes assumptions about the order, which is an implementation detail. fix with real testing framework that can do unordered container content compares or something. bool good_graph = true; if(graph.size() != 4) good_graph = false; Word one_across({0,0}, Direction::ACROSS); Word one_down({0,0}, Direction::DOWN); Word two_down({0,2}, Direction::DOWN); Word three_across({2,0}, Direction::ACROSS); if(graph[one_across].size() != 2 || graph[one_down].size() != 2 || graph[two_down].size() != 2 || graph [three_across].size() != 2) { good_graph = false; } if(good_graph && graph[one_across][0] != one_down) good_graph = false; if(good_graph && graph[one_across][1] != two_down) good_graph = false; if(good_graph && graph[one_down][0] != one_across) good_graph = false; if(good_graph && graph[one_down][1] != three_across) good_graph = false; if(good_graph && graph[two_down][0] != one_across) good_graph = false; if(good_graph && graph[two_down][1] != three_across) good_graph = false; if(good_graph && graph[three_across][0] != one_down) good_graph = false; if(good_graph && graph[three_across][1] != two_down) good_graph = false; if(!good_graph) { std::cout << "Bad graph!" << std::endl;} Puzzle it_puzzle("ab#c#defg", 3); auto iter = PuzzleIterator(it_puzzle); std::vector<std::string> words_from_iterator; for(auto iter = PuzzleIterator(it_puzzle); iter.Valid(); iter.Increment()){ Word location = iter.Get(); words_from_iterator.push_back(it_puzzle.WordAt(location.coords_, location.direction_)); } std::sort(words_from_iterator.begin(), words_from_iterator.end()); if(words_from_iterator.size() != 8) { std::cout << "Bad # of words from iterator: " << words_from_iterator.size() << std::endl; return 1;}; std::vector<std::string> words_expected = {"ab", "ace", "b", "c", "d", "dg", "efg", "f"}; for(int i = 0; i < 8; ++i) { if(words_expected[i] != words_from_iterator[i]) {std::cout << "mismatch, got " << words_from_iterator[i] << " wanted " << words_expected[i] << std::endl;}; } return 0; }
Java
UTF-8
1,082
2.34375
2
[]
no_license
package com.example.finalwork.alarm; import android.content.DialogInterface; import android.media.MediaPlayer; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import com.example.finalwork.R; public class AlarmActivity extends AppCompatActivity { MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alarm); mediaPlayer=MediaPlayer.create(this,R.raw.alarm); mediaPlayer.start(); new AlertDialog.Builder(AlarmActivity.this).setTitle("闹钟").setMessage("张三起床了") .setPositiveButton("关闭闹钟", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { mediaPlayer.stop(); AlarmActivity.this.finish(); } }).show(); } }//闹钟组件的创建
C++
UTF-8
1,201
3.34375
3
[]
no_license
#include "area.hh" //constructor geometry::Area::Area() { } //destructor geometry::Area::~Area() { showResult(surface_area); } double geometry::Area::rectangle(double length, double width) { auto result = static_cast<double>(length * width); return result; } double geometry::Area::square(double side) { auto result = static_cast<double>(side * side); return result; } double geometry::Area::triangle(double a, double b, double c) { //calculate semi-perimeter of the triangle auto p = static_cast<double>(Perimeter::triangle(a, b, c) / 2.0); auto area = sqrt(p * (p - a) * (p - b) * (p - c)); return static_cast<double>(area); } double geometry::Area::polygon(std::vector<int> &sides) { return 1; } void geometry::Area::showResult(double &area) { auto errMsg = "Area calculation failed. Status: "; auto okMsg = "Area calculation finished with status: "; bool ok = 1; if (area) { std::cout << "The area of the figure is: " << area; std::cout << "\n"; std::cout << okMsg << ok; std::cout << "\n"; } else { ok = 0; std::cout << errMsg << ok; std::cout << "\n"; } }
Ruby
UTF-8
2,012
2.546875
3
[]
no_license
require 'test_helper' class EntriesControllerTest < ActionController::TestCase test "index action returns reader's initial entries if no parameters specified" do feed = FactoryGirl.create(:feed) get :index, feed_id: feed.id assert_response :success entries_json = JSON.parse(@response.body)['entries'] assert_proper_entries_json feed.entries.reader_initial, entries_json end test "index action returns feed's entries with id < params[:before] if :before parameter is specified" do feed = FactoryGirl.create(:feed) get :index, feed_id: feed.id, before: 5, limit: 3 assert_response :success entries_json = JSON.parse(@response.body)['entries'] entries = feed.entries.where('id < 5').limit(3).order('id DESC') assert_proper_entries_json(entries, entries_json) end test "index action returns feed's entries with id > params[:after] if :after parameter is specified" do feed = FactoryGirl.create(:feed) get :index, feed_id: feed.id, after: 5, limit: 3 assert_response :success entries_json = JSON.parse(@response.body)['entries'] entries = feed.entries.where('id > 5').limit(3) assert_proper_entries_json(entries, entries_json) end test "set_read_status action sets entries is_read flag" do feed = FactoryGirl.create(:feed) post :set_read_status, feed_id: feed.id, ids: [1, 2, 3], value: true assert_response :success assert true, feed.entries[0].is_read assert true, feed.entries[1].is_read assert true, feed.entries[2].is_read end test "mark_all_as_read action marks all feed's entries as read" do feed = FactoryGirl.create(:feed) post :mark_all_as_read, feed_id: feed.id, before: 10 assert_response :success entries = feed.entries id_less_or_eq_to_10 = entries.select { |e| e.id <= 10 } id_greater_than_10 = entries.select { |e| e.id > 10 } assert id_less_or_eq_to_10.entries.all?(&:is_read) assert id_greater_than_10.entries.none?(&:is_read) end end
JavaScript
UTF-8
1,274
2.859375
3
[]
no_license
/* Express as your framework, MongoDB as the database, and a package called body-parser to help deal with JSON requests. -Nodemon as a dev dependency. It’s a simple little package that automatically restarts your server when files change. */ const express = require('express'); const bodyParser = require('body-parser'); // create express app const app = express(); // parse requests of content-type - application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })) // parse requests of content-type - application/json app.use(bodyParser.json()) // Configuring the database const dbConfig = require('./app/config/database.config.js'); const mongoose = require('mongoose'); mongoose.Promise = global.Promise; // Connecting to the database mongoose.connect(dbConfig.url) .then(() => { console.log("Successfully connected to the database"); }).catch(err => { console.log('Could not connect to the database. Exiting now...'); process.exit(); }); // End configuring/connecting database //require('./app/routes')(app, {}); // Require Notes routes require('./app/routes/note.routes.js')(app); // listen for requests app.listen(3000, () => { console.log("Server is listening on port 3000"); });
Java
UTF-8
244
1.703125
2
[]
no_license
package com.app.utb.springframeworkpetclinic.repositories; import com.app.utb.springframeworkpetclinic.model.Pet; import org.springframework.data.repository.CrudRepository; public interface PetRepository extends CrudRepository<Pet, Long> { }
Java
UTF-8
22,499
1.578125
2
[]
no_license
package com.suusoft.restaurantuser.main; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.suusoft.restaurantuser.AppController; import com.suusoft.restaurantuser.R; import com.suusoft.restaurantuser.base.view.BaseActivity; import com.suusoft.restaurantuser.base.view.SingleListFragment; import com.suusoft.restaurantuser.configs.Constant; import com.suusoft.restaurantuser.main.listFoods.ItemFoodVM; import com.suusoft.restaurantuser.main.listFoods.SearchFoodsVM; import com.suusoft.restaurantuser.main.category.CategoryVM; import com.suusoft.restaurantuser.main.category.ItemCategoryVM; import com.suusoft.restaurantuser.main.myaccount.RootMyAccountFragment; import com.suusoft.restaurantuser.main.myaccount.myorder.OrderDetailsActivity; import com.suusoft.restaurantuser.main.mycart.MyCartActivity; import com.suusoft.restaurantuser.main.mycart.MyCartFragment; import com.suusoft.restaurantuser.main.promotion.ItemPromotionVM; import com.suusoft.restaurantuser.main.promotion.PromotionDetailActivity; import com.suusoft.restaurantuser.main.promotion.PromotionVM; import com.suusoft.restaurantuser.main.search.SearchFragment; import com.suusoft.restaurantuser.main.user.LoginActivity; import com.suusoft.restaurantuser.model.OpenHour; import com.suusoft.restaurantuser.model.Order; import com.suusoft.restaurantuser.model.Promotion; import com.suusoft.restaurantuser.modelmanager.RequestManager; import com.suusoft.restaurantuser.network.ApiResponse; import com.suusoft.restaurantuser.network.BaseRequest; import com.suusoft.restaurantuser.util.AppUtil; import com.suusoft.restaurantuser.util.DialogUtil; import com.suusoft.restaurantuser.util.StringUtil; import com.suusoft.restaurantuser.widgets.dialog.MyProgressDialog; import org.json.JSONArray; import java.util.ArrayList; /** * Created by Suusoft on 14/07/2017. */ public class MainCustomizeActivity extends BaseActivity implements View.OnClickListener ,AppController.IForceLogin{ private static final String TAG_MENU = "TAG_MENU"; private static final String TAG_PROMOTION = "TAG_PROMOTION"; private static final String TAG_SEARCH = "TAG_SEARCH"; private static final String TAG_CART = "TAG_CART"; private static final String TAG_MY_ACCOUNT = "TAG_MY_ACCOUNT"; private SingleListFragment categoryFragment, promotionFragment; private SingleListFragment listFoodsFragment; private RootMyAccountFragment rootMyAccountFragment; private SearchFragment searchFragment; private MyCartFragment myCartFragment; private ImageView imgMenu, imgPromotion, imgSearch, imgCart, imgAccount, imgBack; private TextView tvTitle; private TextView tvNotifiCart; private BroadcastReceiver broadcastCartChange; private BroadcastReceiver broadcastRemoveItem; private Bundle bundleKeyword; private MenuPosition currentMenuPosition = MenuPosition.MENU; private ViewGroup rootBottomBar ; private ViewGroup viewBottom; private Animation animUptoBottomBar; private enum MenuPosition { MENU, PROMOTION, SEARCH, CART, ACCOUNT } @Override protected int getLayoutInflate() { return R.layout.activity_main_reskin; } @Override protected void initView() { AppUtil.logSizeMultiScreen(this); bundleKeyword = new Bundle(); imgMenu = (ImageView) findViewById(R.id.img_menu); imgPromotion = (ImageView) findViewById(R.id.img_promotion); imgSearch = (ImageView) findViewById(R.id.img_search); imgCart = (ImageView) findViewById(R.id.img_cart); imgAccount = (ImageView) findViewById(R.id.img_account); imgBack = (ImageView) findViewById(R.id.img_back); tvTitle = (TextView) findViewById(R.id.tv_title); tvNotifiCart = (TextView) findViewById(R.id.tv_notifi_cart); rootBottomBar = (ViewGroup) findViewById(R.id.root_bottom_bar); viewBottom = (ViewGroup) findViewById(R.id.view_bottom); showMenu(); handleHightLightButtonMenu(imgMenu); broadcastCartChange = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { showNotifiCart(); if (listFoodsFragment != null && currentMenuPosition == MenuPosition.CART) { listFoodsFragment.adapter.notifyDataSetChanged(); } } }; broadcastRemoveItem = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { showNotifiCart(); } }; AppController.getInstance().cartManager.registerReceiverCartChange(broadcastCartChange); AppController.getInstance().cartManager.registerReceiverRemoveItem(broadcastRemoveItem); AppController.getInstance().setForceLoginListener(this); } @Override protected void onViewCreated() { imgMenu.setOnClickListener(this); imgPromotion.setOnClickListener(this); imgSearch.setOnClickListener(this); imgCart.setOnClickListener(this); imgAccount.setOnClickListener(this); imgBack.setOnClickListener(this); handleTapOnNotification(getIntent().getExtras()); } @Override protected void onResume() { super.onResume(); setAnimationShowBottomBar(); } private void setAnimationShowBottomBar() { Log.e("anim", "bottombar" ); viewBottom.setVisibility(View.GONE); animUptoBottomBar = AnimationUtils.loadAnimation(self, R.anim.slide_in_up); animUptoBottomBar.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { Log.e("anim", "onAnimationStart" ); rootBottomBar.setVisibility(View.VISIBLE); } @Override public void onAnimationEnd(Animation animation) { Log.e("anim", "onAnimationEnd" ); viewBottom.setVisibility(View.VISIBLE); } @Override public void onAnimationRepeat(Animation animation) { } }); rootBottomBar.setAnimation(animUptoBottomBar); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); boolean isForceLogin = handleForceLogin(intent); if (isForceLogin) { return; } handleTapOnNotification(intent.getExtras()); } @Override public void cleanSystem() { Intent intent = new Intent(this, MainCustomizeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(Constant.KEY_FORCE_LOGIN, Constant.FORCE_LOGIN); startActivity(intent); } @Override protected ToolbarType getToolbarType() { return ToolbarType.NONE; } @Override protected void onPrepareCreateView() { } @Override public void onClick(View view) { AppUtil.hideSoftKeyboard(this); handleHightLightButtonMenu(view); if (view == imgBack) { handleBackPressed(); } else if (view == imgMenu) { if (currentMenuPosition != MenuPosition.MENU) { currentMenuPosition = MenuPosition.MENU; showMenu(); } } else if (view == imgSearch) { if (currentMenuPosition != MenuPosition.SEARCH) { currentMenuPosition = MenuPosition.SEARCH; showSearch(); } } else if (view == imgPromotion) { if (currentMenuPosition != MenuPosition.PROMOTION) { currentMenuPosition = MenuPosition.PROMOTION; showPromotion(); } } else if (view == imgCart) { if (currentMenuPosition != MenuPosition.CART) { currentMenuPosition = MenuPosition.CART; showMyCart(); } } else if (view == imgAccount) { if (currentMenuPosition != MenuPosition.ACCOUNT) { currentMenuPosition = MenuPosition.ACCOUNT; showMyAccount(); } } } @Override public void onBackPressed() { handleBackPressed(); } @Override protected void onDestroy() { super.onDestroy(); AppController.getInstance().cartManager.unregisterReceiverCartChange(broadcastCartChange); AppController.getInstance().cartManager.unregisterReceiverCartChange(broadcastRemoveItem); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constant.RQ_EXIT_APP && resultCode == Constant.RC_EXIT_APP) { AppUtil.startActivity(this, LoginActivity.class); finish(); } } private void showMenu() { Log.e("show", "showMenu"); setTitle(R.string.menu); categoryFragment = (SingleListFragment) getSupportFragmentManager().findFragmentByTag(TAG_MENU); if (categoryFragment == null) { categoryFragment = SingleListFragment.newInstance(CategoryVM.class, R.layout.item_category_v2, ItemCategoryVM.class); } // categoryFragment = SingleListFragment.newInstance(CategoryVM.class, R.layout.item_category_reskin, ItemCategoryVM.class); replaceFragment(categoryFragment, TAG_MENU); } private void showPromotion() { setTitle(R.string.promotion); promotionFragment = (SingleListFragment) getSupportFragmentManager().findFragmentByTag(TAG_PROMOTION); if (promotionFragment == null) { promotionFragment = SingleListFragment.newInstance(PromotionVM.class, R.layout.item_promotion_v2, ItemPromotionVM.class); } replaceFragment(promotionFragment, TAG_PROMOTION); } private void showMyAccount() { setTitle(R.string.my_account); rootMyAccountFragment = (RootMyAccountFragment) getSupportFragmentManager().findFragmentByTag(TAG_MY_ACCOUNT); if (rootMyAccountFragment == null) { rootMyAccountFragment = RootMyAccountFragment.newInstance(); } replaceFragment(rootMyAccountFragment, TAG_MY_ACCOUNT); } private void showSearch() { setTitle(R.string.search); searchFragment = (SearchFragment) getSupportFragmentManager().findFragmentByTag(TAG_SEARCH); if (searchFragment == null) { searchFragment = SearchFragment.newInstance(); } replaceFragment(searchFragment, TAG_SEARCH); } private void showListFoodSearch(String keyword) { listFoodsFragment = (SingleListFragment) getSupportFragmentManager().findFragmentByTag(TAG_SEARCH); bundleKeyword.putString(Constant.KEY_KEYWORD, keyword); if (listFoodsFragment == null) { listFoodsFragment = SingleListFragment.newInstance(SearchFoodsVM.class, R.layout.item_food, ItemFoodVM.class, bundleKeyword); } replaceFragment(listFoodsFragment, TAG_SEARCH); } // // private void showMyCart() { // if (NetworkUtility.isNetworkAvailable()) { // if (AppController.getInstance().cartManager.countItems() == 0) { // AppUtil.showToast(this, R.string.msg_cart_empty); // } else { // getOpenHours(); // } // } else { // AppUtil.showToast(this, R.string.msg_connection_network_error); // } // } private void showMyCart() { setTitle(R.string.order); myCartFragment = (MyCartFragment) getSupportFragmentManager().findFragmentByTag(TAG_CART); if (myCartFragment == null) { myCartFragment = MyCartFragment.newInstance(); } replaceFragment(myCartFragment, TAG_CART); } private void handleHightLightButtonMenu(View view) { if (view != imgBack) { imgMenu.setColorFilter(AppUtil.getColor(this, R.color.color_nornal_bottom_bar)); imgPromotion.setColorFilter(AppUtil.getColor(this, R.color.color_nornal_bottom_bar)); imgSearch.setColorFilter(AppUtil.getColor(this, R.color.color_nornal_bottom_bar)); imgCart.setColorFilter(AppUtil.getColor(this, R.color.color_nornal_bottom_bar)); imgAccount.setColorFilter(AppUtil.getColor(this, R.color.color_nornal_bottom_bar)); } if (view == imgMenu) { imgMenu.setColorFilter(AppUtil.getColor(this, R.color.color_hight_light_bottom_bar)); } else if (view == imgPromotion) { imgPromotion.setColorFilter(AppUtil.getColor(this, R.color.color_hight_light_bottom_bar)); } else if (view == imgSearch) { imgSearch.setColorFilter(AppUtil.getColor(this, R.color.color_hight_light_bottom_bar)); } else if (view == imgCart) { imgCart.setColorFilter(AppUtil.getColor(this, R.color.color_hight_light_bottom_bar)); } else if (view == imgAccount) { imgAccount.setColorFilter(AppUtil.getColor(this, R.color.color_hight_light_bottom_bar)); } } private void handleBackPressed() { DialogUtil.showAlertDialog(this, R.string.msg_confirm_exit, new DialogUtil.IDialogConfirm() { @Override public void onClickOk() { finish(); } }); } public void replaceFragment(Fragment fragment, String tag, int enter, int out, boolean isAddBackstack) { FragmentManager manager = getSupportFragmentManager(); FragmentTransaction transaction = manager .beginTransaction() .setCustomAnimations(enter, out) .replace(R.id.fr_root_content, fragment); if (isAddBackstack) { transaction.addToBackStack(tag); } transaction.commit(); } public void replaceFragment(Fragment fragment, String tag, boolean isAddBackstack) { replaceFragment(fragment, tag, R.anim.slide_in_left, R.anim.slide_out_left, isAddBackstack); } public void replaceFragment(Fragment fragment, String tag) { replaceFragment(fragment, tag, true); } public void setTitle(String title) { tvTitle.setText(title); } public void setTitle(int idRes) { setTitle(getString(idRes)); } private void showDialogSearch() { setTitle(R.string.search); final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.layout_dialog_search); dialog.getWindow().setBackgroundDrawableResource(R.color.transparent); dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT); dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); dialog.getWindow().setGravity(Gravity.TOP); dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; final EditText edtSearch = (EditText) dialog.findViewById(R.id.edt_search); ImageView imgClose = (ImageView) dialog.findViewById(R.id.img_close); edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) { if (i == EditorInfo.IME_ACTION_SEARCH) { String keyword = edtSearch.getText().toString().trim(); if (StringUtil.isEmpty(keyword)) { AppUtil.showToast(getApplicationContext(), R.string.msg_keyword_required); return true; } else if (keyword.length() < 3) { AppUtil.showToast(getApplicationContext(), R.string.msg_keyword_lenght_required); return true; } showListFoodSearch(keyword); dialog.dismiss(); } return false; } }); imgClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); if (!dialog.isShowing()) { dialog.show(); } } private void showNotifiCart() { int count = AppController.getInstance().cartManager.countItems(); if (count > 0) { tvNotifiCart.setVisibility(View.VISIBLE); tvNotifiCart.setText(String.valueOf(AppController.getInstance().cartManager.countItems())); } else { tvNotifiCart.setVisibility(View.GONE); } } private void getOpenHours() { RequestManager.getOpenHours(new BaseRequest.CompleteListener() { @Override public void onSuccess(ApiResponse response) { if (!response.isError()) { ArrayList<OpenHour> arrOpenHours = (ArrayList<OpenHour>) response.getDataList(OpenHour.class); if (arrOpenHours != null && !arrOpenHours.isEmpty()) { Bundle bundle = new Bundle(); bundle.putParcelableArrayList(Constant.KEY_LIST_OPEN_HOUR, arrOpenHours); JSONArray jsonArray = response.getRoot().optJSONArray(Constant.KEY_RIDER_TIP); double[] listRiderTips = new double[jsonArray.length()]; if (jsonArray != null) { for (int i = 0; i < jsonArray.length(); i++) { listRiderTips[i] = jsonArray.optDouble(i); } } bundle.putDoubleArray(Constant.KEY_RIDER_TIP, listRiderTips); AppUtil.startActivity(MainCustomizeActivity.this, MyCartActivity.class, bundle); AppController.getInstance().cartManager.setDeliveryFee(response.getRoot().optDouble(Constant.KEY_DELIVERY_FEE)); AppController.getInstance().amount_lowest = response.getRoot().optDouble(Constant.KEY_AMOUNT_LOWEST); AppController.getInstance().amount_promtion_lowest = response.getRoot().optDouble(Constant.KEY_AMOUNT_PROMOTION_LOWEST); AppController.getInstance().isChoseAddressDelivery = response.getRoot().optInt(Constant.KEY_CHOSE_ADDRESS_DELIVERY); } } } @Override public void onError(String message) { AppUtil.showToast(getApplicationContext(), message); } }); } private void handleTapOnNotification(Bundle bundle) { if (bundle != null && bundle.containsKey(Constant.KEY_ORDER_ID)) { String id = bundle.getString(Constant.KEY_ORDER_ID); if (id != null && !id.isEmpty()) { getDetailOrder(id); } } if (bundle != null && bundle.containsKey(Constant.KEY_PROMOTION_ID)) { String id = bundle.getString(Constant.KEY_PROMOTION_ID); if (id != null && !id.isEmpty()) { getDetailPromotion(id); } } } private void getDetailOrder(String id) { final MyProgressDialog progressDialog = new MyProgressDialog(this); progressDialog.setCancelable(false); progressDialog.show(); RequestManager.getDetailOrder(id, new BaseRequest.CompleteListener() { @Override public void onSuccess(ApiResponse response) { Order order = response.getDataObject(Order.class); if (order != null) { Bundle bundle = new Bundle(); bundle.putParcelable(Constant.KEY_ORDER, order); AppUtil.startActivity(MainCustomizeActivity.this, OrderDetailsActivity.class, bundle); } progressDialog.dismiss(); } @Override public void onError(String message) { progressDialog.dismiss(); AppUtil.showToast(getApplicationContext(), message); } }); } private void getDetailPromotion(String id) { final MyProgressDialog progressDialog = new MyProgressDialog(this); progressDialog.setCancelable(false); progressDialog.show(); RequestManager.getDetailPromotions(id, new BaseRequest.CompleteListener() { @Override public void onSuccess(ApiResponse response) { Promotion promotion = response.getDataObject(Promotion.class); if (promotion != null) { Bundle bundle = new Bundle(); bundle.putParcelable(Constant.KEY_PROMOTION, promotion); AppUtil.startActivity(self, PromotionDetailActivity.class, bundle); } progressDialog.dismiss(); } @Override public void onError(String message) { progressDialog.dismiss(); } }); } private boolean handleForceLogin(Intent intent) { if (intent.hasExtra(Constant.KEY_FORCE_LOGIN)) { int force_login = intent.getIntExtra(Constant.KEY_FORCE_LOGIN, 0); if (force_login == Constant.FORCE_LOGIN) { AppUtil.startActivity(this, LoginActivity.class); finish(); return true; } else { return false; } } else { return false; } } }
PHP
UTF-8
411
2.578125
3
[]
no_license
<?php namespace app\login\model; use app\common\model\Base; class Admin extends Base{ protected $dateFormat = 'Y-m-d H:i:s'; protected $type = [ 'logintime' => 'timestamp', ]; /** * 根据用户名查询管理员信息 */ static public function adminWithUserName($userName) { $model = Admin::where('username',$userName)->find(); return $model; } }
Java
UTF-8
124
1.9375
2
[]
no_license
package view; import model.Image; import java.util.List; public interface ImageLoader { public List<Image> load(); }