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
C#
UTF-8
1,829
2.609375
3
[]
no_license
using FutureFinancingTriangle.Generator.Input; using FutureFinancingTriangle.Generator.Logic; using FutureFinancingTriangle.Generator.Output; using FutureFinancingTriangle.Generator.Wrappers; using Moq; using System.Collections.Generic; using Xunit; namespace FutureFinancingTriangle.Generator.Tests.Output { public class MangerTests { private Mock<IConsoleReader> _consoleReaderMock; private Mock<IConsoleWrapper> _consoleWrapperMock; private Mock<IFileWritter> _fileWritterMock; private Mock<ITriangleGenerator> _triangleGeneratorMock; private IManager _sut; public MangerTests() { _consoleReaderMock = new Mock<IConsoleReader>(); _consoleWrapperMock = new Mock<IConsoleWrapper>(); _fileWritterMock = new Mock<IFileWritter>(); _triangleGeneratorMock = new Mock<ITriangleGenerator>(); _sut = new Manager(_consoleReaderMock.Object, _consoleWrapperMock.Object, _triangleGeneratorMock.Object, _fileWritterMock.Object); } [Fact] public void DataFromInputArePassedToGeneratorAndSaved() { _consoleReaderMock.SetupSequence(x => x.ReadPositiveIntFromConsole(It.IsAny<string>())) .Returns(10) .Returns(99); _consoleReaderMock.Setup(x => x.ReadBoolFromConsole(It.IsAny<string>())) .Returns(true); var fileName = "aaa.txt"; _consoleReaderMock.Setup(x => x.ReadStringFromConsole(It.IsAny<string>())) .Returns(fileName); _sut.DoIt(); _triangleGeneratorMock.Verify(x => x.Generate(10, 99, true), Times.Once); _fileWritterMock.Verify(x => x.Save(It.IsAny<IEnumerable<IEnumerable<int>>>(), fileName), Times.Once); } } }
Python
UTF-8
4,321
2.734375
3
[]
no_license
#!/usr/bin/python3 import csv import sys import matplotlib.pyplot as plt import numpy as np from constants import * def read_from_csv(filenames, indicies): """ Indicies must be 4 elements """ f_x_vals, f_train, f_test, f_train_var, f_test_var = [], [], [], [], [] for i, filename in enumerate(filenames): x_vals, train, train_var, test, test_var = np.array([]), np.array([]), \ np.array([]), np.array([]), np.array([]) csv_file = open(filename, mode='r') csv_reader = csv.reader(csv_file, delimiter=",") for row in csv_reader: # Confidence interval is computed according to: scale*(std_dev/sqrt(num_sims)) # 90% confidence - scale of 1.6 scale = 1.5 x_vals = np.append(x_vals, float(row[0])) train = np.append(train, float(row[indicies[0]])) train_var = np.append(train_var, scale*(float(row[indicies[1]])/np.sqrt(num_sims))) test = np.append(test, float(row[indicies[2]])) test_var = np.append(test_var, scale*(float(row[indicies[3]])/np.sqrt(num_sims))) f_x_vals.append(x_vals) f_train.append(train) f_train_var.append(train_var) f_test.append(test) f_test_var.append(test_var) return f_x_vals, f_train, f_train_var, f_test, f_test_var def plot(labels, data, plot_var=False): """ Plot the test and train losses and fairness labels are tuple of the following: (plt_name, x_label, fairness_label) data is a tuple of: (x_vals, train, train_var, test_loss, test_loss_var, train_fairness, train_fairness_var, test_fairness, test_fairness_var) """ plt_name, x_label, fairness_label = labels f_x_vals, f_train, f_train_var, f_test, f_test_var = data fig, ax1 = plt.subplots() num_files = len(f_train) colors = ['tab:red', 'tab:blue', 'tab:green', 'tab:orange'] #colors = ['tab:red', 'tab:green', 'tab:grey'] #colors = ['tab:green', 'tab:orange', 'tab:grey'] ax1.set_xlabel(x_label, fontsize=21) ax1.set_ylabel(fairness_label, fontsize=21) labels = ["ERM", "ERM-Welfare", "ERM-Group Envy Free", "ERM-Group Equitable"] #labels = ["ERM", "ERM-Group Envy Free", "ERM-Envy Free"] #labels = ["ERM-Group Envy Free", "ERM-Group Equitable", "ERM-Envy Free"] for i in range(num_files): #ax1.plot(f_x_vals[i], f_train[i], color=colors[i], linewidth=4, label=labels[i]) ax1.plot(f_x_vals[i], f_test[i], color=colors[i], linewidth=4, label=labels[i]) #ax1.semilogy(f_x_vals[i], f_test[i], color=colors[i], linewidth=4, label=labels[i]) if plot_var: #ax1.fill_between(f_x_vals[i], f_train[i]-f_train_var[i], f_train[i]+f_train_var[i], color=colors[i], alpha=0.35) ax1.fill_between(f_x_vals[i], f_test[i]-f_test_var[i], f_test[i]+f_test_var[i], color=colors[i], alpha=0.35) ax1.tick_params(axis='x', labelsize=17) ax1.tick_params(axis='y', labelsize=17) #plt.xticks([25,50,75,100,125,150]) #plt.xticks([30,40,50,60,70,80]) #plt.xticks([2,3,4,5,6,7,8,9]) #plt.yticks([0.15, 0.16, 0.17, 0.18, 0.19, 0.20, 0.21]) plt.legend() plt.grid(False) plt.tight_layout() plt.savefig(plt_name) if __name__ == "__main__": """ Run this file as "./plot_from_csv <csv_file_names> <metric> <plot_label> <x_label> <plot_var true/false Pass in files in this order: erm, erm_welfare, erm_envy, erm_equity """ metrics_dict = {'Avg. Loss':[1,2,3,4], 'Welfare':[5,6,7,8], 'Avg. Group Envy':[9,10,11,12], \ 'Group Envy Vio':[13,14,15,16], 'Avg. Group Inequity':[17,18,19,20], 'Avg. Envy':[25,26,27,28], 'Individual Envy Vio':[29,30,31,32], "Time (s)":[33,34,33,34]} inp_files = [sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]] files = [] for inp_file in inp_files: if inp_file is not "_": files.append(inp_file) metric = sys.argv[5] assert(metric in metrics_dict.keys()) plot_label = sys.argv[6] x_label = sys.argv[7] plot_var = sys.argv[8].lower() == 'true' indicies = metrics_dict[metric] data = read_from_csv(files, indicies) labels = (plot_label, x_label, metric) plot(labels, data, plot_var=plot_var)
Python
UTF-8
5,107
2.59375
3
[]
no_license
###I run this in Google Colab #from __future__ import absolute_import, division, print_function, unicode_literals #try: # %tensorflow_version only exists in Colab. # !pip install -q tf-nightly #except Exception: # pass #import tensorflow as tf # tf.enable_eager_execution() #tf.executing_eagerly() import tensorflow_datasets as tfds import os #You may use your own text file DIRECTORY_URL = ['https://raw.githubusercontent.com/laiyuekiu/Tensorflow-customized-dataset-text-classifcation/master/crime.txt', 'https://raw.githubusercontent.com/laiyuekiu/Tensorflow-customized-dataset-text-classifcation/master/food.txt', 'https://raw.githubusercontent.com/laiyuekiu/Tensorflow-customized-dataset-text-classifcation/master/edu.txt', 'https://raw.githubusercontent.com/laiyuekiu/Tensorflow-customized-dataset-text-classifcation/master/tech.txt'] FILE_NAMES = ['crime.txt', 'food.txt', 'edu.txt', 'tech.txt'] text_dir = [] parent_dir = [] for n in range(len(FILE_NAMES)): text_dir.append(tf.keras.utils.get_file(FILE_NAMES[n], origin=DIRECTORY_URL[n])) parent_dir = os.path.dirname(text_dir[0]) def labeler(example, index): return example, tf.cast(index, tf.int64) labeled_data_sets = [] for i in range(len(FILE_NAMES)): lines_dataset = tf.data.TextLineDataset(os.path.join(parent_dir, FILE_NAMES[i])) labeled_dataset = lines_dataset.map(lambda ex: labeler(ex, i)) labeled_data_sets.append(labeled_dataset) #You may adjust the neural network BUFFER_SIZE = 3000 BATCH_SIZE = 20 TAKE_SIZE = 200 all_labeled_data = labeled_data_sets[0] for labeled_dataset in labeled_data_sets[1:]: all_labeled_data = all_labeled_data.concatenate(labeled_dataset) all_labeled_data = all_labeled_data.shuffle( BUFFER_SIZE, reshuffle_each_iteration=False) for ex in all_labeled_data.take(20): print(ex) tokenizer = tfds.features.text.Tokenizer() vocabulary_set = set() for text_tensor, _ in all_labeled_data: some_tokens = tokenizer.tokenize(text_tensor.numpy()) vocabulary_set.update(some_tokens) vocab_size = len(vocabulary_set) encoder = tfds.features.text.TokenTextEncoder(vocabulary_set, oov_buckets=3) #This will print out the data in tensorflow format # example_text = next(iter(all_labeled_data))[0].numpy() # print(example_text) # encoded_example = encoder.encode(example_text) # print(encoded_example) def encode(text_tensor, label): encoded_text = encoder.encode(text_tensor.numpy()) return encoded_text, label def encode_map_fn(text, label): # py_func doesn't set the shape of the returned tensors. encoded_text, label = tf.py_function(encode, inp=[text, label], Tout=(tf.int64, tf.int64)) # `tf.data.Datasets` work best if all components have a shape set # so set the shapes manually: encoded_text.set_shape([None]) label.set_shape([]) return encoded_text, label all_encoded_data = all_labeled_data.map(encode_map_fn) train_data = all_encoded_data.skip(TAKE_SIZE).shuffle(BUFFER_SIZE) train_data = train_data.padded_batch(BATCH_SIZE) test_data = all_encoded_data.take(TAKE_SIZE) test_data = test_data.padded_batch(BATCH_SIZE) #This will print out a sample from your neural network # sample_text, sample_labels = next(iter(test_data)) # print('Sample text: ', sample_text[0], sample_labels[0]) vocab_size += 1 #The classification model setting model = tf.keras.Sequential([ tf.keras.layers.Embedding(encoder.vocab_size, 128), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(len(FILE_NAMES)) ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) history = model.fit(train_data, epochs=8, validation_data=test_data, validation_steps=25) test_loss, test_acc = model.evaluate(test_data) print('Test Loss: {}'.format(test_loss)) print('Test Accuracy: {}'.format(test_acc)) def pad_to_size(vec, size): zeros = [0] * (size - len(vec)) vec.extend(zeros) return vec #Topic classifcation prediction def sample_predict(sample_pred_text, pad): encoded_sample_pred_text = encoder.encode(sample_pred_text) if pad: encoded_sample_pred_text = pad_to_size(encoded_sample_pred_text, 128) encoded_sample_pred_text = tf.cast(encoded_sample_pred_text, tf.float32) predictions = model.predict(tf.expand_dims(encoded_sample_pred_text, 0)) return (predictions) #This is my testing sample of topic classification sample_pred_text = ('We are having lunch in a Chinese restaurant and we order tea and coffee. The food in there is very yummy. We are full and not feel hungry.') predictions = sample_predict(sample_pred_text, pad=False) print("NO padding text: ", predictions) predictions = sample_predict(sample_pred_text, pad=True) print("With padding text: ", predictions)
PHP
UTF-8
644
2.59375
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Prices extends Model { protected $table = 'prices'; protected $fillable = [ 'product_id', 'price', 'type', ]; protected $hidden = []; protected $dateFormat = 'U'; ////////// public static function listMeasures() { return "agreed,piece,sq-m,ton,meter"; } public static function getMeasures() { return [ 'agreed' => 'agreed', 'piece' => 'piece', 'sq-m' => 'sq-m', 'ton' => 'ton', 'meter' => 'meter', ]; } }
Python
UTF-8
1,569
3.46875
3
[]
no_license
import matematica as m func = [ [], lambda x: m.soma(*x), lambda x: m.somav(*x), lambda x: m.sub(*x), lambda x: m.subv(*x), lambda x: m.multi(*x), lambda x: m.dot(*x), lambda x: m.cross(*x), lambda x: m.produto(*x), lambda x: m.divisao(*x), lambda x: m.power(*x), lambda x: m.logaritmo(*x), lambda x: m.sind(x), lambda x: m.cosd(x), lambda x: m.tg(x), lambda x: m.sqrt(x), lambda x: m.inv(x), lambda x: m.ab(x), lambda x: m.fatorial(x), lambda x: m.permut(*x), lambda x: m.comb(*x), lambda x: m.primo(x), lambda x: m.primosTil(x), lambda x: m.MMC(x), lambda x: m.MDC(*x), ] menuString = """Menu Principal: 0. Sair; 1. soma; 2. somav; 3. sub; 4. subv; 5. multi; 6. dot; 7. cross; 8. produto; 9. divisão; 10. pow; 11. logaritmo; 12. seno(em graus) 13. cosseno(em graus) 14. tangente (graus) 15. sqrt 16. 1/x 17. abs 18. fatorial 19. permutação 20. combinação 21. O número é primo? 22. Números primos até x 23. MMC 24. MDC """ menu = len(func) while 0 < menu <= len(func): print(menuString) menu = int(input("R.: ")) #Lê o comando do menu e assegura que é inteiro if menu == 0: break # O usuário insere os argumento em uma string arguments = str(input("Insira os argumentos separados por vírgula: ")) # A string é avaliada e levada como argumento para a função catalogada print(str(func[menu](eval(arguments))))
PHP
UTF-8
2,988
2.640625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Message; use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class ChatsController extends Controller { public function __construct() { $this->middleware(function ($request, $next) { $this->user = Auth::user(); return $next($request); }); } /** * Render chat view * * @return \Illuminate\Http\Response */ public function index($id) { $user = User::where('id', $id)->get( [ 'name', 'email', 'user_photo' ] ); // User data $userData = array( 'id' => $id, 'name' => $user[0]->name, 'email' => $user[0]->email, 'photo' => $user[0]->user_photo, 'user_type' => 2 ); // Render view return view( 'chat', [ 'userData' => json_decode(json_encode($userData)), 'language' => app()->getLocale(), 'receptor' => json_encode(array("id" => $id, "name" => $userData['name'])), 'view' => 'chat' ] ); } /** * Fetch all messages * * @return Message */ public function fetchMessages($receptor_id) { // Get send messages $searchTo = [ ['user_id', '=', $this->user->id], ['receptor_id', '=', $receptor_id] ]; // Get receiver messages $searchFrom = [ ['user_id', '=', $receptor_id], ['receptor_id', '=', $this->user->id] ]; $messages = Message::where($searchTo)->orWhere($searchFrom)->get(); // Get receptor's name $receptor = User::where('id', $receptor_id)->orderBy('created_at')->get(['name']); // Array for message data $data = array(); // Array for names $arrNames = array( $this->user->id => 'Me', $receptor_id => $receptor[0]->name ); foreach ($messages as $key => $value) { $data[] = array( 'id' => $value->id, 'user_id' => $value->user_id, 'user_name' => $arrNames[$value->user_id], 'created_at' => $value->created_at, 'text' => $value->message ); } return json_encode($data); } /** * Persist message to database * * @param Request $request * @return Response */ public function sendMessage(Request $request) { // Save message $message = Message::create([ 'user_id' => $this->user->id, 'receptor_id' => $request->data['receptor'], 'message' => $request->data['text'] ]); return response()->json('ok'); } }
Java
UTF-8
1,554
2.703125
3
[]
no_license
package com.leaning.KafkaStream; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.processor.TopologyBuilder; import java.util.Properties; public class Application { public static void main(String[] args) { String brokers = "Centos1:9092"; String zookeepers = "Centos1:2181"; // 定义source和sink的主题 String from = "log"; String to = "recommender"; // 定义kafka的配置 Properties settings = new Properties(); settings.put(StreamsConfig.APPLICATION_ID_CONFIG, "logFilter"); settings.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, brokers); settings.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, zookeepers); StreamsConfig config = new StreamsConfig(settings); // 构造流程拓扑器 TopologyBuilder builder = new TopologyBuilder(); // 定义流处理的拓扑结构 // source builder.addSource("SOURCE", from) // Processor // 第二个参数为ProcessorSupplier接口类型的多态子类,重写的方法返回值是Processor对象类型,所以传入的参数可以传入Processor对象 .addProcessor("PROCESSOR", LogProcessor::new, "SOURCE") .addSink("SINK", to, "PROCESSOR"); KafkaStreams kafkaStreams = new KafkaStreams(builder, config); kafkaStreams.start(); System.out.println("kafka streaming start >>>>>>>>>>>>>>>>>>"); } }
Python
UTF-8
721
3.5625
4
[]
no_license
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: l = len(s) if l <= 1: return l left = 0 right = 1 res = 1 while right < l: cur = s[left:right+1] cur_length = len(cur) if self.is_valid_str(cur): if cur_length > res: res = cur_length right += 1 else: left += 1 return res def is_valid_str(self, m: str) -> bool: d = set() for i in m: if i in d: return False d.add(i) return True q = Solution() r = q.lengthOfLongestSubstring("pwwkew") print(r)
Python
UTF-8
2,552
3.078125
3
[]
no_license
import sys, requests # pip install requests import webbrowser global nick # varivel nick como global x = sys.argv # x recebe sys.argv def ajuda(): print(""" ++++++++++++++++++++++++++++++++++++++++++++++++++ + -all => PROCURA TUDO (exceto o -tu) + -f => Facebook + -tw => Twitter + -i => Instagram + -tu => Tumblr + -fi => Filmow ++++++++++++++++++++++++++++++++++++++++++++++++++ --python SNSearch.py mary553 -tu --python SNSearch.py nick_do_user -all """) def abra(url): webbrowser.open(url) def facebook(): url = 'https://m.facebook.com/'+nick r = requests.get(url) # faz a requisiçao checa = r.status_code # varivel para checar o status if checa == 200: # caso o status seja 200 ele retorna FOUND print('[+] FACEBOOK FOUND => {}\n'.format(url)) abra(url) else: print('[-]FACEBOOK NOT FOUND => {}\n'.format(url)) def twitter(): url = 'https://m.twitter.com/'+nick r = requests.get(url) # faz a requisiçao checa = r.status_code # varivel para checar o status if checa == 200: # caso o status seja 200 ele retorna FOUND print('[+] TWITTER FOUND => {}\n'.format(url)) abra(url) else: print('[-]TWITTER NOT FOUND => {}\n'.format(url)) def instagram(): url = 'https://www.instagram.com/'+nick r = requests.get(url) checa = r.status_code if checa == 200: print('[+] INSTAGRAM FOUND => {}\n'.format(url)) abra(url) else: print('[-]INSTAGRAM NOT FOUND => {}\n'.format(url)) def tumblr(): url = 'https://'+nick+'.tumblr.com' r = requests.get(url) checa = r.status_code if checa == 200: print('[+] TUMBLR FOUND => {}\n'.format(url)) abra(url) else: print('[-]TUMBRL NOT FOUND => {}\n'.format(url)) def filmow(): url = 'https://filmow.com/usuario/'+nick r = requests.get(url) checa = r.status_code if checa == 200: print('[+] FILMOW FOUND => {}\n'.format(url)) abra(url) else: print('[-]FILMOW NOT FOUND => {}\n'.format(url)) ########## MAIN if len(x) == 3: nick = x[1] if x[2] == '-f': # Se o argumento 2 for -f chame a funçao facebook facebook() elif x[2] == '-fi': # Se Não se o argumento 2 for -fi chame a funçao filmow filmow() elif x[2] == '-tw': # Se Não se o argumento 2 for -tw chame a funçao twitter twitter() elif x[2] == '-tu': # Se Não se o argumento 2 for -tu chame a funçao tumblr tumblr() elif x[2] == '-all': # Se Não se o argumento 2 for -all chame todas as funçoes facebook() twitter() instagram() filmow() elif x[2] == '-i': # Se Não se o argumento 2 for -i chame a funçao instagram instagram() else: ajuda()
PHP
UTF-8
318
2.53125
3
[]
no_license
<?php Class Login_model extends BaseModel { function __construct () { parent:: __construct(); } function get_user ( $email, $password ) { return $this->db->fetch( 'SELECT `id`, `firstname` FROM `account` WHERE `email` = ? AND `password` = SHA2( ?, 224 );', array( $email, $password ) ); } }
Java
UTF-8
1,050
3.578125
4
[]
no_license
package study.week02; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Date; public class DateAndTime { public static void main(String[] args) { Date nowDate = new Date(); System.out.println(nowDate); SimpleDateFormat formatter = new SimpleDateFormat("yyyy년 MM월 dd일"); String formatDate = formatter.format(nowDate); System.out.println(nowDate); // Wed Aug 18 23:27:47 KST 2021 System.out.println(formatDate); // 2021년 08월 18일 System.out.println(nowDate.getTime()); // 1629297635660 LocalTime time = LocalTime.now(); LocalDate localDate = LocalDate.now(); Instant instant = Instant.now(); System.out.println(time); // 23:27:47.781 System.out.println(localDate); // 2021-08-18 System.out.println(localDate.format(DateTimeFormatter.ofPattern("yyyy년 MM월 dd일"))); //2021년 08월 18일 } }
Java
UTF-8
4,120
2.03125
2
[]
no_license
package com.jindan.jdy.controller.waimao; import com.jindan.jdy.common.pojo.WaimaoDowBankExpend; import com.jindan.jdy.common.pojo.WaimaoDowMarket; import com.jindan.jdy.controller.utils.WorkbookUtils; import com.jindan.jdy.service.waimao.WaimaoDowBankExpendService; import com.jindan.jdy.service.waimao.WaimaoDowMarketService; import com.jindan.jdy.common.utils.api.ResultVo; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.apache.dubbo.config.annotation.Reference; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.web.bind.annotation.*; import io.swagger.annotations.Api; import org.springframework.web.multipart.MultipartFile; import java.util.ArrayList; import java.util.List; /** * * <p>说明: 外贸道氏API接口层</P> * @version: V1.0 * @author: kong * @time 2020年7月29日 * */ @CrossOrigin(origins = "http://118.24.255.51:20201") @Api(tags = "外贸道氏销售信息") @RestController @RequestMapping("/waimaoDowMarket") public class WaimaoDowMarketController{ @Reference(version = "${service.version}", check = false) WaimaoDowMarketService waimaoAreaService; @ApiOperation(value = "外贸道氏道氏销售信息导入", notes = "参数:外贸道氏道氏销售信息导入") @PostMapping("addexcleDowBankExpend") public ResultVo addfahuo(@RequestParam("file") MultipartFile file) throws Exception { // 创建Excel工作薄 Workbook work = WorkbookUtils.getWorkbook(file.getInputStream(),file.getOriginalFilename()); if(null == work){ throw new Exception("创建Excel工作薄为空!"); } System.out.println("work.getNumberOfSheets();"+ work.getNumberOfSheets()); Sheet sheet = work.getSheetAt(0); if(sheet==null){ throw new Exception("创建Excel工作薄为空!"); } List<WaimaoDowMarket> jijiabiaos = new ArrayList<>(); for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++){ Row row = sheet.getRow(j); if(row==null||row.getFirstCellNum()==j){continue;} WaimaoDowMarket jijiabiao = new WaimaoDowMarket(); jijiabiaos.add(jijiabiao); } waimaoAreaService.saveBatch(jijiabiaos); return ResultVo.success(); } @ApiOperation(value = "查询道氏销售信息", notes = "参数:查询道氏销售信息") @PostMapping("/seleteWaimaoDowBankExpend") public ResultVo seleteWaimaoDowBankExpend(@ApiParam(value = "jdyRole", required = false) @RequestBody WaimaoDowMarket jdyRole){ List<WaimaoDowMarket> list = waimaoAreaService.seletelist(jdyRole); return ResultVo.success(list); } @ApiOperation("更新道氏销售信息") @PostMapping("/updateWaimaoDowBankExpend") public ResultVo updateWaimaoDowBankExpend(@ApiParam(value = "jdyRole", required = true) @RequestBody WaimaoDowMarket jdyRole){ boolean b = waimaoAreaService.updateById(jdyRole); if(b){ return ResultVo.success(jdyRole); } return ResultVo.failed(); } @ApiOperation("新增道氏销售信息") @PostMapping("/addWaimaoDowBankExpend") public ResultVo addWaimaoDowBankExpend( @ApiParam(name = "jdyRole", required = true) @RequestBody WaimaoDowMarket jdyRole){ boolean save = waimaoAreaService.save(jdyRole); if(save){ return ResultVo.success(jdyRole); } return ResultVo.failed(); } @ApiOperation("删除道氏销售信息") @DeleteMapping("/deleteWaimaoDowBankExpend/{seid}") public ResultVo deleteTichengXishu(@ApiParam(value = "seid", name = "seid", required = true) @PathVariable String seid){ boolean b = waimaoAreaService.removeById(seid); if(b){ return ResultVo.success(); } return ResultVo.failed(); } }
C++
UTF-8
1,021
3.65625
4
[]
no_license
// // main.cpp // Hypothenuse // // Created by Kevin Racapé on 22/08/2020. // Copyright © 2020 Kevin Racapé. All rights reserved. // #include <iostream> #include <cmath> int main() { float AB{0},AC{0},BC{0},squareBC{0}; std::cout << "Calculation of the Hypothenuse" << std::endl; std::cout << "Hypothesis : It's a right triangle" << std::endl; std::cout << "Formula : BC² = AB² + AC²" << std::endl; std::cout << std::endl; std::cout << "Enter values of AB and AC in centimeter" << std::endl; std::cout << "AB : "; std::cin >> AB; std::cout << "AC : "; std::cin >> AC; std::cout << std::endl; squareBC = (AB * AB) + (AC * AC); BC = sqrt(squareBC); std::cout << "AB = " << AB << "\t" << "AC = " << AC << "\t" << "BC = " << BC << std::endl; std::cout << "Hypothenuse = " << BC << " cm \n" << std::endl; std::cout << "Fonction hypot()" << std::endl; std::cout << "Hypot() = " << hypot(AB,AC) << " cm" << std::endl; return 0; }
C++
UTF-8
2,348
3.96875
4
[ "Apache-2.0" ]
permissive
// C++ program to find maximum path sum between two leaves of // a binary tree #include <iostream> using namespace std; // A binary tree node struct Node { int data; struct Node* left, *right; }; // Utility function to allocate memory for a new node struct Node* newNode(int data) { struct Node* node = new(struct Node); node->data = data; node->left = node->right = NULL; return (node); } // Utility function to find maximum of two integers int max(int a, int b) { return (a >= b)? a: b; } // A utility function to find the maximum sum between any two leaves. // This function calculates two values: // 1) Maximum path sum between two leaves which is stored in res. // 2) The maximum root to leaf path sum which is returned. int maxPathSumUtil(struct Node *root, int &res) { // Base case if (root==NULL) return 0; // Find maximum sum in left and right subtree. Also find // maximum root to leaf sums in left and right subtrees // and store them in lLPSum and rLPSum int lLPSum = maxPathSumUtil(root->left, res); int rLPSum = maxPathSumUtil(root->right, res); // Find the maximum path sum passing through root int curr_sum = max((lLPSum+rLPSum+root->data), max(lLPSum, rLPSum)); // Update res (or result) if needed if (res < curr_sum) res = curr_sum; // Return the maximum root to leaf path sum return max(lLPSum, rLPSum)+root->data; } // The main function which returns sum of the maximum // sum path between two leaves. This function mainly uses // maxPathSumUtil() int maxPathSum(struct Node *root) { int res = 0; maxPathSumUtil(root, res); return res; } // driver program to test above function int main() { struct Node *root = newNode(-15); root->left = newNode(5); root->right = newNode(6); root->left->left = newNode(-8); root->left->right = newNode(1); root->left->left->left = newNode(2); root->left->left->right = newNode(6); root->right->left = newNode(3); root->right->right = newNode(9); root->right->right->right= newNode(0); root->right->right->right->left= newNode(4); root->right->right->right->right= newNode(-1); root->right->right->right->right->left= newNode(10); cout << "Max pathSum of the given binary tree is " << maxPathSum(root); return 0; }
JavaScript
UTF-8
702
2.71875
3
[]
no_license
$(document).ready(function(){ $('.edit-comment').click( function(e){ e.preventDefault(); doALittleAjax(this); }); $('form').on('submit', function(){ var valuesToSubmit = $('.edit_comment').serialize(); alert(valueToSubmit); // $.ajax({ // url: $('#mail-form').attr('action'), //sumbits it to the given url of the form // data: valuesToSubmit, // dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard // }).success(function(json){ // //act on result. // }); }); }); var doALittleAjax = function(thing){ $.ajax({ url: "/comments/1/edit" }).done(function(response) { $(thing).parent().replaceWith(response); }); };
Java
UTF-8
694
1.890625
2
[]
no_license
package com.labwinner.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.labwinner.domain.TeamMomentsLike; import com.labwinner.domain.TeamProjMomentsComment; public interface MomentsCommentDao { public void save(TeamProjMomentsComment momentsComment); public void delete(Integer id); public TeamProjMomentsComment getById(Integer id); public void deleteByMomentsId(@Param("momentsInfoId")Integer momentsInfoId,@Param("momentsType")Integer momentsType); public List<TeamProjMomentsComment> getAll(); public List<TeamProjMomentsComment> getByMomentsId(@Param("momentsType")Integer momentsType,@Param("momentsInfoId")Integer momentsInfoId); }
JavaScript
UTF-8
3,638
2.90625
3
[]
no_license
// API Reference: https://www.wix.com/corvid/reference // “Hello, World!” Example: https://www.wix.com/corvid/hello-world import wixData from 'wix-data'; import {local} from 'wix-storage'; import wixLocation from 'wix-location'; const makeDropdown = "#makeDropdown"; const modelDropdown = "#modelDropdown"; const typeDropdown = "#typeDropdown"; const yearDropdown = "#yearDropdown"; const vehiclesData = wixData.query("Vehicles"); $w.onReady(function () { const searchBtn = "#searchButton"; disableDropdowns(); uniqueDropDown1(); function disableDropdowns(){ $w(modelDropdown).disable() $w(typeDropdown).disable() $w(yearDropdown).disable() } function uniqueDropDown1 (){ vehiclesData .limit(1000) .ascending("name") .distinct("name") .then( (results) => { let distinctList = buildOptions(results.items); $w(makeDropdown).options = distinctList }); } function buildOptions(uniqueList) { return uniqueList.map(curr => { return {label:curr, value:curr}; }); } $w(makeDropdown).onChange( (event) => { vehiclesData .limit(1000) .contains("name", $w(makeDropdown).value) .find() .then( (results) => { const uniqueTitles = getUniqueTitlesForModel(results.items); $w(modelDropdown).options = buildOptions(uniqueTitles); }); $w(modelDropdown).enable() //reseting values of other dropdowns if they are already selected $w(modelDropdown).value = "" $w(typeDropdown).value = "" $w(yearDropdown).value = "" $w(typeDropdown).disable() $w(yearDropdown).disable() }); function getUniqueTitlesForModel(items) { const titlesOnly = items.map(item => item.model); return [...new Set(titlesOnly)]; } $w(modelDropdown).onChange( (event) => { vehiclesData .limit(1000) .contains("model", $w(modelDropdown).value) .find() .then( (results) => { const uniqueTitles = getUniqueTitlesForType(results.items); $w(typeDropdown).options = buildOptions(uniqueTitles); }); $w(typeDropdown).enable() //reseting values of other dropdowns if they are already selected $w(typeDropdown).value = "" $w(yearDropdown ).value = "" $w(yearDropdown).disable() }); function getUniqueTitlesForType(items) { const titlesOnly = items.map(item => item.type); return [...new Set(titlesOnly)]; } $w(typeDropdown).onChange( (event) => { vehiclesData .limit(1000) .contains("type", $w(typeDropdown).value) .find() .then( (results) => { const uniqueTitles = getUniqueTitlesForYear(results.items); $w(yearDropdown).options = buildOptions(uniqueTitles); }); $w(yearDropdown).enable() //reseting values of other dropdowns if they are selected $w(yearDropdown).value = "" }); function getUniqueTitlesForYear(items) { const titlesOnly = items.map(item => item.year); return [...new Set(titlesOnly)]; } }) export async function searchButton_click(event) { var vehicleIDs = await getVehicleIDs(); local.setItem("vehicleIDs", vehicleIDs); wixLocation.to("/search-results") } export async function getVehicleIDs(){ var vehicleIDs = []; await vehiclesData.contains("name", $w(makeDropdown).value) .eq("model", $w(modelDropdown).value) .eq("type", $w(typeDropdown).value) .eq("year", $w(yearDropdown).value) .find() .then( (results) => { results.items.forEach(function(vehicle){ vehicleIDs.push(vehicle._id); }) return vehicleIDs }) .catch( (err) => { let errorMsg = err; console.log(errorMsg); }); return vehicleIDs }
TypeScript
UTF-8
383
2.6875
3
[]
no_license
import { IIngredients } from "../types/burger"; export enum ActionType { ADD_INGREDIENT = "ADD_INGREDIENT", REMOVE_INGREDIENT = "REMOVE_INGREDIENT" } interface Payload { ingredientName: string; } export interface IngredientActionTypes { actionType: ActionType; payload: Payload; } export interface ingredientState { ingredients: IIngredients; totalPrice: number; }
Java
GB18030
822
2.53125
3
[]
no_license
import java.util.ArrayList; import java.util.List; /****************************************************************************** * Copyright (C) 2015 ShenZhen ComTop Information Technology Co.,Ltd * All Rights Reserved. * Ϊڿտơδ˾ʽͬ⣬κθˡ岻ʹá * ơ޸Ļ򷢲. ******************************************************************************/ /** * FIXME עϢ * @author zhaoqunqi * @since 1.0 * @createDate 2015-03-19 */ public class GenericTest { /** * FIXME עϢ * * @param args s */ public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("1"); list.add("2"); } }
Java
UTF-8
8,283
1.914063
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.core.js.modules; import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.HashSet; import im.actor.core.api.ApiFileLocation; import im.actor.core.api.ApiFileUrlDescription; import im.actor.core.api.rpc.RequestGetFileUrl; import im.actor.core.api.rpc.RequestGetFileUrls; import im.actor.core.api.rpc.ResponseGetFileUrl; import im.actor.core.api.rpc.ResponseGetFileUrls; import im.actor.core.js.modules.entity.CachedFileUrl; import im.actor.core.modules.AbsModule; import im.actor.core.modules.ModuleContext; import im.actor.core.modules.Modules; import im.actor.core.util.BaseKeyValueEngine; import im.actor.core.util.ModuleActor; import im.actor.core.network.RpcCallback; import im.actor.core.network.RpcException; import im.actor.runtime.Log; import im.actor.runtime.Storage; import im.actor.runtime.actors.ActorCreator; import im.actor.runtime.actors.ActorRef; import im.actor.runtime.actors.Props; import static im.actor.runtime.actors.ActorSystem.system; /** * File's URL binder */ public class JsFilesModule extends AbsModule { private static final String TAG = "JsFilesModule"; private ActorRef urlLoader; private BaseKeyValueEngine<CachedFileUrl> keyValueStorage; private HashSet<Long> requestedFiles = new HashSet<Long>(); private ArrayList<JsFileLoadedListener> listeners = new ArrayList<JsFileLoadedListener>(); public JsFilesModule(final Modules modules) { super(modules); urlLoader = system().actorOf(Props.create(new ActorCreator() { @Override public FileBinderActor create() { return new FileBinderActor(JsFilesModule.this, modules); } }), "files/url_loader"); keyValueStorage = new BaseKeyValueEngine<CachedFileUrl>(Storage.createKeyValue("file_url_cache")) { @Override protected byte[] serialize(CachedFileUrl value) { return value.toByteArray(); } @Override protected CachedFileUrl deserialize(byte[] data) { try { return CachedFileUrl.fromBytes(data); } catch (IOException e) { Log.e(TAG, e); return null; } } }; } /** * Registering Internal listener for binding updates * * @param listener listener for registration */ public void registerListener(JsFileLoadedListener listener) { if (!listeners.contains(listener)) { listeners.add(listener); } } /** * Unregistering Internal listener for binding updates * * @param listener listener for unregistering */ public void unregisterListener(JsFileLoadedListener listener) { listeners.remove(listener); } /** * Getting URL for file if available * * @param id file's id * @param accessHash file's accessHash * @return url for a file or null if not yet available */ public String getFileUrl(long id, long accessHash) { CachedFileUrl cachedFileUrl = keyValueStorage.getValue(id); if (cachedFileUrl != null) { long urlTime = cachedFileUrl.getTimeout(); long currentTime = im.actor.runtime.Runtime.getCurrentSyncedTime(); if (urlTime <= currentTime) { Log.w("JsFilesModule", "URL #" + id + " timeout (urlTime: " + urlTime + ", current:" + currentTime + ")"); keyValueStorage.removeItem(id); } else { return cachedFileUrl.getUrl(); } } if (!requestedFiles.contains(id)) { requestedFiles.add(id); urlLoader.send(new FileRequest(id, accessHash)); } return null; } private void onFileUrlLoaded(ArrayList<FileResponse> responses) { HashSet<Long> ids = new HashSet<Long>(); ArrayList<CachedFileUrl> cachedFileUrls = new ArrayList<CachedFileUrl>(); for (FileResponse r : responses) { ids.add(r.getId()); requestedFiles.remove(r.getId()); cachedFileUrls.add(new CachedFileUrl(r.getId(), r.getUrl(), r.getTimeout())); } keyValueStorage.addOrUpdateItems(cachedFileUrls); for (JsFileLoadedListener listener : listeners) { listener.onFileLoaded(ids); } } /** * Internal File Url loader */ private static class FileBinderActor extends ModuleActor { private static final long DELAY = 200; private static final int MAX_FILE_SIZE = 50; private boolean isLoading = false; private JsFilesModule filesModule; private ArrayList<FileRequest> filesQueue = new ArrayList<FileRequest>(); public FileBinderActor(JsFilesModule filesModule, ModuleContext context) { super(context); this.filesModule = filesModule; } @Override public void onReceive(Object message) { if (message instanceof FileRequest) { filesQueue.add((FileRequest) message); self().sendOnce(new PerformLoad(), DELAY); } else if (message instanceof PerformLoad) { performLoad(); } else { drop(message); } } private void performLoad() { if (isLoading) { return; } ArrayList<ApiFileLocation> fileLocations = new ArrayList<ApiFileLocation>(); for (int i = 0; i < MAX_FILE_SIZE && filesQueue.size() > 0; i++) { FileRequest request = filesQueue.remove(0); fileLocations.add(new ApiFileLocation(request.getId(), request.getAccessHash())); } if (fileLocations.size() == 0) { return; } isLoading = true; request(new RequestGetFileUrls(fileLocations), new RpcCallback<ResponseGetFileUrls>() { @Override public void onResult(ResponseGetFileUrls response) { // Converting result long currentTime = im.actor.runtime.Runtime.getCurrentSyncedTime(); ArrayList<FileResponse> responses = new ArrayList<FileResponse>(); for (ApiFileUrlDescription u : response.getFileUrls()) { long urlTime = currentTime + u.getTimeout() * 1000L; responses.add(new FileResponse(u.getFileId(), u.getUrl(), urlTime)); } // Notify about loaded filesModule.onFileUrlLoaded(responses); isLoading = false; self().sendOnce(new PerformLoad(), DELAY); } @Override public void onError(RpcException e) { // Setting flag isLoading = false; // Logging error Log.e(TAG, e); isLoading = false; self().sendOnce(new PerformLoad(), DELAY); } }); } private class PerformLoad { } } private static class FileRequest { private long id; private long accessHash; public FileRequest(long id, long accessHash) { this.id = id; this.accessHash = accessHash; } public long getId() { return id; } public long getAccessHash() { return accessHash; } } private static class FileResponse { private long id; private String url; private long timeout; public FileResponse(long id, String url, long timeout) { this.id = id; this.url = url; this.timeout = timeout; } public long getId() { return id; } public String getUrl() { return url; } public long getTimeout() { return timeout; } } }
Java
UTF-8
1,700
2.453125
2
[]
no_license
package com.evertdev.lastfm; import com.evertdev.lastfm.common.DurationConverter; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class DurationConverterUnitTest { static final long FIRST_SECONDS = 360L; static final String FIRST_EXPECTED_RESULT = "6:0"; static final long SECOND_SECONDS = 244L; static final String SECOND_EXPECTED_RESULT = "4:4"; static final long THIRD_SECONDS = 650L; static final String THIRD_EXPECTED_RESULT = "10:50"; static final long FOURTH_SECONDS = 1560L; static final String FOURTH_EXPECTED_RESULT = "26:0"; static final long FIFTH_SECONDS = -10L; static final String FIFTH_EXPECTED_RESULT = "0:0"; static final long SIXTH_SECONDS = 0; static final String SIXTH_EXPECTED_RESULT = "0:0"; @Test public void addition_isCorrect() throws Exception { // assertEquals(4, 2 + 2); assertEquals(DurationConverter.getDurationInMinutesText(FIRST_SECONDS), FIRST_EXPECTED_RESULT); assertEquals(DurationConverter.getDurationInMinutesText(SECOND_SECONDS), SECOND_EXPECTED_RESULT); assertEquals(DurationConverter.getDurationInMinutesText(THIRD_SECONDS), THIRD_EXPECTED_RESULT); assertEquals(DurationConverter.getDurationInMinutesText(FOURTH_SECONDS), FOURTH_EXPECTED_RESULT); assertEquals(DurationConverter.getDurationInMinutesText(FIFTH_SECONDS), FIFTH_EXPECTED_RESULT); assertEquals(DurationConverter.getDurationInMinutesText(SIXTH_SECONDS), SIXTH_EXPECTED_RESULT); } }
Python
UTF-8
1,907
3.40625
3
[]
no_license
#script in Python 3.7 import numpy as np import matplotlib.pyplot as plt import math # S = susceptible individuals # I = infectious individuals # β = infectious rate, controls the rate of spread which represents the probability of transmitting disease between a susceptible and an infectious individual # γ = recovery rate, is determined by the inverse of the average duration of infection # N = S + I totall population (constant) # R = β / γ basic reproduction number #N = int(input("Enter totall population:")) #print("Totall population :" + N) N = 1000 population_S = [] population_S += [N] population_I = [] population_I += [0] beta = np.random.rand() gamma = np.random.rand() print(beta / gamma) for time in range(0,1000): delta_12 = 0 #from Susceptible to Infectious delta_21 = 0 #from Infectious to Susceptible R = beta / gamma #print(beta) if R > 1: print("Need of an intervention (R>1)") #β must dicrise beta = math.exp(-time) R = beta / gamma if 0.87 < R < 0.97: print("The intervention was effective") prob_of_infection = beta*population_S[-1]/N #Susceptible for atoms in range(0,population_S[-1]): if(np.random.rand() < prob_of_infection): delta_12 += 1 prob_of_recovery = gamma #Infectious for atoms in range(0,population_I[-1]): if(np.random.rand() < prob_of_recovery): delta_21 += 1 #calculating new populations N_1 = delta_21 - delta_12 N_2 = delta_12 - delta_21 #adding the populations to their populations population_S += [population_S[-1] + N_1] population_I += [population_I[-1] + N_2] plt.figure(figsize=(16,9)) plt.rc('font', size=22) plt.xlabel('Time') plt.ylabel('Population I, S') plt.plot(population_S, color='green', linestyle='-', linewidth=4) plt.plot(population_I, color='red', linestyle='-', linewidth=4) plt.show()
Markdown
UTF-8
1,041
3.015625
3
[ "MIT" ]
permissive
# Contribution to this project Contributing is not just about code! There is much more to a project. Contributions can include: * **Starring** the project (at the top right) * **Logging** a bug / idea or commenting on an existing ticket (issue) * Fixing a **typo** in the text of the Application / website / documentation * Documentation * and of course committing code ### Issue When creating / commenting on an **Issue**, try and look at it from someone else's perspective - remember then can not see your screen or read your mind. Capture as much useful information as possible while keeping it concise, use diagrams & screenshots to help. ### Branching When creating a **Branch** use [Git Flow](http://nvie.com/posts/a-successful-git-branching-model/) branching & naming conventions For example ``` feature/123-brief-description ``` ### Commiting When writing a **Commit** message, please prepend each commit message with the **Issue** number. For example: ``` [#123] This is my commit message ``` ### Pull Requests Todo.
C
UTF-8
418
3.3125
3
[]
no_license
#include<stdio.h> #include<conio.h> void main() { int a,b,c; clrscr(); for(a=1;a<=5;a++) { for(b=1;b<=5-a;b++) { printf(" "); } for(c=1;c<=a;c++) { printf(" *"); } printf("\n"); } for(a=4;a>=1;a--) { for(b=1;b<=4-a;b++) { printf(" "); } for(c=1;c<=a;c++) { printf(" *"); } printf("\n"); } getch(); }
Java
UTF-8
1,675
2.75
3
[]
no_license
package com.uiFrameworkk.pentland.helper.window; import java.util.Set; import org.apache.log4j.Logger; import org.openqa.selenium.WebDriver; import com.uiFrameworkk.pentland.helper.logger.LoggerHelper; public class WindowHelper { private WebDriver driver; private Logger log = LoggerHelper.getLogger(WindowHelper.class); public WindowHelper(WebDriver driver) { this.driver = driver; } // This method will switch to parent window public void switchToParentWindow() { log.info("Switching to Parent Window..."); driver.switchTo().defaultContent(); } // This method will switch to child window based on index public void switchToWindow(int index) { Set<String> windows = driver.getWindowHandles(); int i=1; for(String window : windows) { if(i==index) { log.info("Switching to : " + index + "Window"); driver.switchTo().window(window); }else { i++; } } } // This method will closed all the tabed window and // switched to main window public void closeALlTabsAndSwitchToMainWindow() { Set<String> windows = driver.getWindowHandles(); String mainwindow = driver.getWindowHandle(); for(String window : windows) { if(!window.equalsIgnoreCase(mainwindow)) { driver.close(); } } log.info("Switching to mainwindow : "); driver.switchTo().window(mainwindow); } // This method will do browser back navigation public void navigateBack() { log.info("Navigating Back"); driver.navigate().back(); } // This method will do browser forward navigation public void navigateForward() { log.info("Navigating forward"); driver.navigate().forward(); } }
SQL
UTF-8
4,676
3.484375
3
[]
no_license
CREATE TABLE job ( id INTEGER PRIMARY KEY AUTOINCREMENT, tag VARCHAR(80) NOT NULL, state CHAR(1) NOT NULL DEFAULT "?", state_prev CHAR(1) NOT NULL DEFAULT "?", location VARCHAR(80) NOT NULL, foreign_id VARCHAR(80) DEFAULT NULL, mode VARCHAR(10) NOT NULL, parameters TEXT DEFAULT "", priority INTEGER NOT NULL DEFAULT 0, task VARCHAR(80) NOT NULL, qa_state CHAR(1) NOT NULL DEFAULT "?" ); CREATE INDEX job_state ON job (state); CREATE UNIQUE INDEX job_tag ON job (tag); CREATE INDEX job_location ON job (location); CREATE INDEX job_foreign_id ON job (foreign_id); CREATE UNIQUE INDEX job_location_id ON job (location, foreign_id); CREATE INDEX job_priority ON job (priority); CREATE INDEX job_task ON job (task); CREATE INDEX job_qa_state ON job (qa_state); CREATE TABLE input_file ( id INTEGER PRIMARY KEY AUTOINCREMENT, job_id INTEGER NOT NULL, filename VARCHAR(80) NOT NULL, FOREIGN KEY (job_id) REFERENCES job (id) ON DELETE RESTRICT ON UPDATE RESTRICT ); CREATE INDEX input_file_job_id ON input_file (job_id); CREATE UNIQUE INDEX input_file_job_file ON input_file (job_id, filename); CREATE TABLE output_file ( id INTEGER PRIMARY KEY AUTOINCREMENT, job_id INTEGER NOT NULL, filename VARCHAR(120) NOT NULL, md5 VARCHAR(40) DEFAULT NULL, FOREIGN KEY (job_id) REFERENCES job(id) ON DELETE RESTRICT ON UPDATE RESTRICT ); CREATE INDEX output_file_job_id ON output_file (job_id); CREATE UNIQUE INDEX output_file_job_file ON output_file (job_id, filename); CREATE TABLE log ( id INTEGER PRIMARY KEY AUTOINCREMENT, job_id INTEGER NOT NULL, datetime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, state_prev CHAR(1) NOT NULL DEFAULT "?", state_new CHAR(1) NOT NULL DEFAULT "?", message TEXT NOT NULL DEFAULT "", host VARCHAR(80) NOT NULL DEFAULT "unknown", username VARCHAR(80) NOT NULL DEFAULT "unknown", FOREIGN KEY (job_id) REFERENCES job(id) ON DELETE RESTRICT ON UPDATE RESTRICT ); CREATE INDEX log_job_id ON log (job_id); CREATE INDEX log_state_new ON log (state_new); CREATE TABLE obsidss ( id INTEGER PRIMARY KEY AUTOINCREMENT, job_id INTEGER NOT NULL, obsid_subsysnr VARCHAR(50) NOT NULL, obsid VARCHAR(48) NOT NULL, subsys INTEGER NOT NULL, FOREIGN KEY (job_id) REFERENCES job(id) ON DELETE RESTRICT ON UPDATE RESTRICT ); CREATE UNIQUE INDEX job_id_obsidss ON obsidss (job_id, obsid_subsysnr); CREATE TABLE tile ( id INTEGER PRIMARY KEY AUTOINCREMENT, job_id INTEGER NOT NULL, tile INTEGER NOT NULL, FOREIGN KEY (job_id) REFERENCES job(id) ON DELETE RESTRICT ON UPDATE RESTRICT ); CREATE UNIQUE INDEX tile_job_tile ON tile (job_id, tile); CREATE INDEX tile_job_id ON tile (job_id); CREATE INDEX tile_tile ON tile (tile); CREATE TABLE qa ( id INTEGER PRIMARY KEY AUTOINCREMENT, job_id INTEGER NOT NULL, datetime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, status CHAR(1) NOT NULL DEFAULT "?", message TEXT NOT NULL DEFAULT "", username VARCHAR(80) NOT NULL DEFAULT "unknown", FOREIGN KEY (job_id) REFERENCES job(id) ON DELETE RESTRICT ON UPDATE RESTRICT ); CREATE INDEX qa_job_id ON qa (job_id); CREATE TABLE task ( id INTEGER PRIMARY KEY AUTOINCREMENT, taskname VARCHAR(80) NOT NULL, etransfer BOOLEAN, starlink VARCHAR(255) DEFAULT NULL, version INTEGER DEFAULT NULL, command_run VARCHAR(255) DEFAULT NULL, command_xfer VARCHAR(255) DEFAULT NULL, raw_output BOOLEAN, command_ingest VARCHAR(255) DEFAULT NULL, log_ingest varchar(255) DEFAULT NULL ); CREATE UNIQUE INDEX task_name ON task (taskname); CREATE TABLE parent ( id INTEGER PRIMARY KEY AUTOINCREMENT, job_id INTEGER NOT NULL, parent INTEGER NOT NULL, filter VARCHAR(80) NOT NULL DEFAULT "", FOREIGN KEY (job_id) REFERENCES job(id) ON DELETE RESTRICT ON UPDATE RESTRICT, FOREIGN KEY (parent) REFERENCES job(id) ON DELETE RESTRICT ON UPDATE RESTRICT ); CREATE INDEX parent_parent on parent (parent); CREATE INDEX parent_job_id on parent (job_id); CREATE UNIQUE INDEX parent_parent_job ON parent (job_id, parent); CREATE TABLE note ( id INTEGER PRIMARY KEY AUTOINCREMENT, job_id INTEGER NOT NULL, datetime TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, message TEXT NOT NULL DEFAULT "", username VARCHAR(80) NOT NULL DEFAULT "unknown", FOREIGN KEY (job_id) REFERENCES job(id) ON DELETE RESTRICT ON UPDATE RESTRICT ); CREATE INDEX note_job_id ON note (job_id); CREATE TABLE obs_preproc ( obsid VARCHAR(48) NOT NULL PRIMARY KEY, recipe VARCHAR(80) NOT NULL );
JavaScript
UTF-8
2,139
2.75
3
[]
no_license
import React, { useState, useMemo } from "react"; import { Button } from ".."; import "./SequenceQuizCard.css"; //https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array function shuffle(a) { for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; } export default ({ solutions, sequence, difs, correctSolution, handleNextClick }) => { const shuffledSolutions = useMemo(() => shuffle(solutions), [solutions]); const [selectedSolution, setSelectedSolution] = useState(0); const [showSolution, setShowSolution] = useState(false); return ( <div className="ltn-de-sqc"> <div className="ltn-de-sqc-sequence"> {sequence.map((num, i) => ( <h2 key={`${num}:${i}`}>{num}</h2> ))} </div> <p>Diese Folge kann mit folgenden Zahlen erweitert werden:</p> <ul> {shuffledSolutions.map(([dif1, dif2], i) => ( <li onClick={() => setSelectedSolution(i)} key={JSON.stringify([dif1, dif2])} > <input type="radio" name="quiz-char" checked={i === selectedSolution} onChange={() => setSelectedSolution(i)} /> [{dif1}, {dif2}] </li> ))} </ul> {showSolution && ( <h3> [{correctSolution[0]}, {correctSolution[1]}] </h3> )} {!showSolution && ( <Button onClick={() => { setShowSolution(true); }} > Lösung </Button> )} {!showSolution && ( <Button onClick={() => { handleNextClick(); }} className="mt-de-sequence-quiz-card-skip-button" > Skip </Button> )} {showSolution && ( <Button onClick={() => { handleNextClick(shuffledSolutions[selectedSolution]); setShowSolution(false); }} > Nächste Folge </Button> )} </div> ); };
C++
UTF-8
470
2.65625
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; int main(){ int t; cin >> t; while(t--){ int n,k; cin >> n >> k; int a[10005]; int dem=0; for(int i=0; i<n; i++) cin >> a[i]; sort(a, a+n); for(int i=0; i<n; i++){ for(int j=i+1; j<n; j++){ if(a[i]+a[j] == k){ dem++; } } } cout << dem << endl; } }
Python
UTF-8
110
3.34375
3
[]
no_license
from math import * x = int(input("Enter x:")) y = ((e**(2*x)*sqrt(x)-((x+1/3)/x))**1/3)*abs(2.5*x) print(y)
JavaScript
UTF-8
5,638
2.796875
3
[]
no_license
function makeAjaxCall(url, cb){ var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200){ //console.log(xhr.response); var responseJson = JSON.parse(xhr.response); cb(responseJson); } } } //makeAjaxCall("https://api.github.com/users/btford"); var btnElem = document.getElementById("getDataBtn"); var userIdElem = document.getElementById("userId"); var usernameElem = document.getElementById("username"); var avatarElem = document.getElementById("avatar"); var nameElem = document.getElementById("name"); var companyElem = document.getElementById("company"); var repoBtnElem = document.getElementById("getRepo"); var tableElem = document.getElementById("repoInfo"); function makeAjaxCall(url, cb){ var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200){ //console.log(xhr.response); var responseJson = JSON.parse(xhr.response); cb(responseJson); } } } //makeAjaxCall("https://api.github.com/users/btford"); var btnElem = document.getElementById("getDataBtn"); var userIdElem = document.getElementById("userId"); var usernameElem = document.getElementById("username"); var avatarElem = document.getElementById("avatar"); var nameElem = document.getElementById("name"); var companyElem = document.getElementById("company"); var repoBtnElem = document.getElementById("getRepo"); var tableElem = document.getElementById("repoInfo"); if(btnElem){ btnElem.addEventListener("click", buttonClickHandler); } function buttonClickHandler(){ var userId = userIdElem.value; var url = "https://api.github.com/users/" + userId; makeAjaxCall(url, renderUserData); } function renderUserData(obj){ usernameElem.innerHTML = obj.login; avatarElem.src = obj.avatar_url; nameElem.innerHTML = obj.name; companyElem.innerHTML = obj.company; } function makeAjaxCall(url, cb){ var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200){ //console.log(xhr.response); var responseJson = JSON.parse(xhr.response); cb(responseJson); } } } //makeAjaxCall("https://api.github.com/users/btford"); var btnElem = document.getElementById("getDataBtn"); var userIdElem = document.getElementById("userId"); var usernameElem = document.getElementById("username"); var avatarElem = document.getElementById("avatar"); var nameElem = document.getElementById("name"); var companyElem = document.getElementById("company"); var repoBtnElem = document.getElementById("getRepo"); var tableElem = document.getElementById("repoInfo"); if(btnElem){ btnElem.addEventListener("click", buttonClickHandler); } function buttonClickHandler(){ var userId = userIdElem.value; var url = "https://api.github.com/users/" + userId; makeAjaxCall(url, renderUserData); } function renderUserData(obj){ usernameElem.innerHTML = obj.login; avatarElem.src = obj.avatar_url; nameElem.innerHTML = obj.name; companyElem.innerHTML = obj.company; } function makeAjaxCall(url, cb){ var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.send(); xhr.onreadystatechange = function(){ if (xhr.readyState === 4 && xhr.status === 200){ //console.log(xhr.response); var responseJson = JSON.parse(xhr.response); cb(responseJson); } } } //makeAjaxCall("https://api.github.com/users/btford"); var btnElem = document.getElementById("getDataBtn"); var userIdElem = document.getElementById("userId"); var usernameElem = document.getElementById("username"); var avatarElem = document.getElementById("avatar"); var nameElem = document.getElementById("name"); var companyElem = document.getElementById("company"); var repoBtnElem = document.getElementById("getRepo"); var tableElem = document.getElementById("repoInfo"); if(btnElem){ btnElem.addEventListener("click", buttonClickHandler); } function buttonClickHandler(){ var userId = userIdElem.value; var url = "https://api.github.com/users/" + userId; makeAjaxCall(url, renderUserData); } function renderUserData(obj){ usernameElem.innerHTML = obj.login; avatarElem.src = obj.avatar_url; nameElem.innerHTML = obj.name; companyElem.innerHTML = obj.company; } repoBtnElem.addEventListener("click", function(){ var url = "https://api.github.com/users/" + userIdElem.value + "/repos"; makeAjaxCall(url, renderRepoData); }); function renderRepoData(data){ var tbodyElem = tableElem.querySelector("tbody"); for (var i=0; i<data.length;i++){ var repoData = data[i]; console.log(repoData); var trElem = document.createElement("tr"); var checkTdElem = document.createElement("td"); var nameTdElem = document.createElement("td"); var descTdElem = document.createElement("td"); var langTdElem = document.createElement("td"); var checkInputElem = document.createElement("input"); var linkElem = document.createElement("a"); checkInputElem.type="checkbox"; linkElem.setAttribute("href", repoData.html_url); linkElem.setAttribute("target", "_blank"); linkElem.innerHTML = repoData.name; descTdElem.innerHTML = repoData.description; langTdElem.innerHTML = repoData.language; checkTdElem.appendChild(checkInputElem); nameTdElem.appendChild(linkElem); trElem.appendChild(checkTdElem); trElem.appendChild(nameTdElem); trElem.appendChild(descTdElem); trElem.appendChild(langTdElem); tbodyElem.appendChild(trElem); } }
JavaScript
UTF-8
561
2.71875
3
[ "MIT" ]
permissive
/* eslint-env mocha */ import "./helper"; import {assert} from "chai"; import Event from "../src/event"; import "../src/util"; describe("class Event", function(){ const event = new Event({ title: "party", where: "kazusuke", note: "酒池肉林", date: new Date() }); it("should have title, where and note", function(){ assert.equal(event.title, "party"); assert.equal(event.where, "kazusuke"); assert.equal(event.note, "酒池肉林"); }); it("should be today", function(){ assert(event.date.isToday()); }); });
Markdown
UTF-8
5,615
3.453125
3
[]
no_license
--- title: オートコンプリートの実装方法 --- # オートコンプリート機能の実装方法 オートコンプリートは使いやすい検索ボックスを作るのに便利な機能です。PGroongaにはオートコンプリートを実装するための機能があります。 次の検索を組み合わせることでオートコンプリートを実現できます。 * 前方一致検索 * 日本語のみ:ヨミガナでのオートコンプリート用に前方一致RK検索 * 緩い全文検索 ## サンプルスキーマとインデックス サンプルのスキーマを示します。 ```sql CREATE TABLE terms ( term text, readings text[] ); ``` オートコンプリート候補の用語は`term`に保存します。`term`のヨミガナは`readings`に保存します。`readings`の型が`text[]`であることからわかるように、`readings`には複数のヨミガナを保存できます。 サンプルのインデックス定義を示します。 ```sql CREATE INDEX pgroonga_terms_prefix_search ON terms USING pgroonga (term pgroonga.text_term_search_ops_v2, readings pgroonga.text_array_term_search_ops_v2); CREATE INDEX pgroonga_terms_full_text_search ON terms USING pgroonga (term pgroonga.text_full_text_search_ops_v2) WITH (tokenizer = 'TokenBigramSplitSymbolAlphaDigit'); ``` 上記のインデックス定義は前方一致検索と全文検索に必要です。 `TokenBigramSplitSymbolAlphaDigit`トークナイザーは緩い全文検索に向いています。 ## 前方一致検索 オートコンプリート機能を実現するシンプルな方法は前方一致検索を使う方法です。 PGroongaは前方一致検索用の演算子として[`&^`演算子][prefix-search-v2]を提供しています。 前方一致検索をするためのサンプルデータを示します。 ```sql INSERT INTO terms (term) VALUES ('auto-complete'); ``` データを挿入したら、`term`に対して`&^`を使って前方一致検索をします。結果は次の通りです。 ```sql SELECT term FROM terms WHERE term &^ 'auto'; -- term -- --------------- -- auto-complete -- (1 rows) ``` オートコンプリート候補の用語として`auto-complete`がヒットしています。 ## 日本語のみ:ヨミガナでのオートコンプリート用に前方一致RK検索 [前方一致RK検索][groonga-prefix-rk-search]は前方一致検索の一種です。これは[ローマ字][wikipedia-romaji]、[ひらがな][wikipedia-hiragana]またはカタカナで[カタカナ][wikipedia-katakana]を検索できます。日本語にはとても便利な機能です。 前方一致RK検索のためのサンプルデータを示します。 ```sql INSERT INTO terms (term, readings) VALUES ('牛乳', ARRAY['ギュウニュウ', 'ミルク']); ``` `readings`にはカタカナのみ追加することに注意してください。これは前方一致RK検索を使ってオートコンプリート候補の用語を検索するのに必要です。 `readings`に対して前方一致RK検索をするために[`&^~`演算子][prefix-rk-search-v2]を使います。前方一致RK検索の例をいくつか示します。 * ローマ字を使った前方一致RK検索 * ひらがなを使った前方一致RK検索 * カタカナを使った前方一致RK検索 前方一致RK検索では「gyu」(ローマ字)で「牛乳」をオートコンプリート候補の用語として検索できます。 ```sql SELECT term FROM terms WHERE readings &^~ 'gyu'; -- term -- ------ -- 牛乳 -- (1 row) ``` 前方一致RK検索では「ぎゅう」(ひらがな)で「牛乳」をオートコンプリート候補として検索できます。 ```sql SELECT term FROM terms WHERE readings &^~ 'ぎゅう'; -- term -- ------ -- 牛乳 -- (1 row) ``` 前方一致RK検索では「ギュウ」(カタカナ)で「牛乳」をオートコンプリート候補の用語として検索できます。 ```sql SELECT term FROM terms WHERE readings &^~ 'ギュウ'; -- term -- ------ -- 牛乳 -- (1 row) ``` より高度な`readings`の使い方があります。同義語の読みを`readings`に入れると、それを使ってオートコンプリート候補の用語を検索することもできます。 ```sql SELECT term FROM terms WHERE readings &^~ 'mi'; -- term -- ------ -- 牛乳 -- (1 row) ``` 「ミルク」は「牛乳」の同義語です。ヨミガナとして「ミルク」を`readings`に追加することで、「mi」で検索したときも「牛乳」をオートコンプリート候補の用語として検索できます。 ## 緩い全文検索 緩い全文検索をするために`term`に対して[`&@`][match-v2]を使います。結果は次の通りです。 ```sql SELECT term FROM terms WHERE term &@ 'mpl'; -- term -- --------------- -- auto-complete -- (1 rows) ``` オートコンプリート候補の用語として`auto-complete`がヒットしています。 [groonga-prefix-rk-search]:http://groonga.org/ja/docs/reference/operations/prefix_rk_search.html [wikipedia-katakana]:https://ja.wikipedia.org/wiki/%E7%89%87%E4%BB%AE%E5%90%8D [wikipedia-romaji]:https://ja.wikipedia.org/wiki/%E3%83%AD%E3%83%BC%E3%83%9E%E5%AD%97 [wikipedia-hiragana]:https://ja.wikipedia.org/wiki/%E5%B9%B3%E4%BB%AE%E5%90%8D [prefix-search-v2]:../reference/operators/prefix-search-v2.html [match-v2]:../reference/operators/match-v2.html [prefix-rk-search-v2]:../reference/operators/prefix-rk-search-v2.html
Java
UTF-8
8,522
1.898438
2
[]
no_license
package net.wit.dao; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Set; import net.wit.Filter; import net.wit.Order; import net.wit.Page; import net.wit.Pageable; import net.wit.entity.*; import net.wit.entity.Tenant.Status; /** * <p> * Title: * </p> * <p> * Description: * </p> * <p> * Copyright: www.insuper.com * </p> * <p> * Company: www.insuper.com * </p> * @author liumx * @version 3.0 2013年7月1日16:37:52 */ public interface TenantDao extends BaseDao<Tenant, Long> { /** * 查找企业 * @param code 企业编码 * @return 企业 */ Tenant findByCode(String code); /** * 查找企业 * @param domain 企业绑定域名 * @return 企业 */ Tenant findByDomain(String domain); Tenant findByTelephone(String telephone); /** * 查找企业 * @param area 城市 * @param name 企业名称 * @param tag 标签 * @param count 数量 * @return 企业 */ List<Tenant> findList(Area area, String name, Tag tag, Integer count); /** * 查找企业 * @param tenantCategory 企业分类 * @param tags 标签 * @param count 数量 * @param filters 筛选 * @param orders 排序 * @return 企业 */ List<Tenant> findList(TenantCategory tenantCategory, List<Tag> tags, Integer count, List<Filter> filters, List<Order> orders); /** * 查找企业 * @param tenantCategory 企业分类 * @param tags 所属地区 * @param area 小区 * @param community 是否查询周边 * @param periferal 标签 * @param count 数量 * @param filters 筛选 * @param orders 排序 * @return 企业 */ List<Tenant> findList(TenantCategory tenantCategory, List<Tag> tags, Area area, Community community, Boolean periferal, Integer count, List<Filter> filters, List<Order> orders); /** * 查找企业 * @param tenantCategory 企业分类 * @param beginDate 起始日期 * @param endDate 结束日期 * @param first 起始记录 * @param count 数量 * @return 企业 */ List<Tenant> findList(TenantCategory tenantCategory, Date beginDate, Date endDate, Integer first, Integer count); /** * 查找企业分页 * @param tenantCategory 企业分类 * @param tags 所属地区 * @param area 小区 * @param community 是否查询周边 * @param periferal 标签 * @param pageable 分页信息 * @return 企业分页 */ Page<Tenant> findPage(Set<TenantCategory> tenantCategorys, List<Tag> tags, Area area, Community community, Boolean periferal, Location location, BigDecimal distance, Pageable pageable); /** * 查找企业分页 * @param tenantCategory 企业分类 * @param tags 标签 * @param pageable 分页信息 * @return 企业分页 */ Page<Tenant> findPage(TenantCategory tenantCategory, List<Tag> tags, Pageable pageable); Page<Tenant> findPage(TenantCategory tenantCategory, Area area,Boolean isPromotion, Pageable pageable); /** * 查找企业 * @param area 城市 * @param name 企业名称 * @param tags 标签 * @param count 数量 * @return 企业 */ Page<Tenant> findPage(Area area, List<Tag> tags, Pageable pageable); Page<Tenant> findAgency(Member member, Status status, Pageable pageable); long count(Member member, Date startTime, Date endTime, Status status); List<ProductCategoryTenant> findRoots(Tenant tenant, Integer count); Page<Tenant> mobileFindPage(Set<TenantCategory> tenantCategorys, List<Tag> tags, Area area, Community community, Boolean periferal, Location location, BigDecimal distatce, Pageable pageable); Page<Tenant> findPage(Set<TenantCategory> tenantCategorys, List<Tag> tags, Area area, Community community, Boolean periferal, Pageable pageable); Page<Tenant> findPage(String keyword, TenantCategory tenantCategory, List<Tag> tags, Area area, ProductCategory productCategory, Brand brand, BrandSeries brandSeries, Pageable pageable); List<Tenant> findList(Set<TenantCategory> tenantCategorys, List<Tag> tags, Area area, Community community, Integer count); List<Tenant> tenantSelect(String q, Boolean b, int i); List<Tenant> findNewest(List<Tag> tags, Integer count); Page<Tenant> findPage(Member member, Pageable pageable); Page<Tenant> findPage(Status status, List<Tag> tags, Pageable pageable); /** * @Title:findMemberFavorite * @Description:会员收藏商铺 * @param member * @param keyword * @param count * @return List<Tenant> */ List<Tenant> findMemberFavorite(Member member, String keyword, Integer count, List<Order> orders); /** * @Title:统计关注我的会员 */ Long countMyFavorite(Tenant tenant); public List<Tenant> findListByAreas(List<Area> areas); /** * @Title:domainExists * @Description:判断域名是否存在 * @param member * @return boolean */ public boolean domainExists(String domain); /** * 检测店铺名称的唯一性 * @param shortName 店铺名称 * @return boolean */ public boolean checkShortName(String shortName); boolean isOwner(Member member); Page<Tenant> findPage(Status status, List<Tag> tags,List<Area> areas,Date beginDate, Date endDate, Pageable pageable); List<Tenant> findList(Status status, List<Tag> tags, Date beginDate, Date endDate); /** * 分页查询商家-管理端 * * @param pageable 用于分页、排序、过滤和查询关键字 * @param area 区域 * @param beginDate, endDate, //时间 * @param tenantCategorys 商家分类 * @param tags 标签筛选 * @param keyword 查询关键字 * @param status 状态 * @param orderType 排序 * @return 商家分页 */ public Page<Tenant> openPage(Pageable pageable, //用于分页、排序、过滤和查询关键字 Area area, //区域 Date beginDate, Date endDate, //时间 Set<TenantCategory> tenantCategorys, //商家分类 List<Tag> tags, //标签筛选 String keyword, //查询关键字 Status status, //状态 Tenant.OrderType orderType, //排序 String qrCodeStatus, // 是否有二维码 1:有0:没有 String marketableSize //商品上架数量,分隔符'%',例子:1%3 代表数量在1到3之间 ); /** * 分页查询商家 * @param pageable 用于分页、排序、过滤和查询关键字 * @param area 区域 * @param tenantCategorys 商家分类 * @param tags 标签筛选 * @param keyword 查询关键字 * @param location 定位坐标 * @param distatce 定位后根据距离搜索商家 * @param orderType 排序 * @return 商家分页 */ Page<Tenant> openPage(Pageable pageable, //用于分页、排序、过滤和查询关键字 Area area, //区域 Set<TenantCategory> tenantCategorys, //商家分类 List<Tag> tags, //标签筛选 String keyword, //查询关键字 Location location, //定位坐标 BigDecimal distatce, //定位后根据距离搜索商家 Community community, //商圈 Tenant.OrderType orderType, //排序 Boolean isPromotion, Boolean isUnion, Union union ); /** * 返回固定条数的商家 * @param count 查询的条数 * @param area 区域 * @param tenantCategorys 商家分类 * @param tags 标签筛选 * @param keyword 查询关键字 * @param location 定位坐标 * @param distatce 定位后根据距离搜索商家 * @param filters 过滤 * @param orderType 排序 * @return 商家集合 */ List<Tenant> openList(Integer count, //查询的条数 Area area, //区域 Set<TenantCategory> tenantCategorys, //商家分类 List<Tag> tags, //标签筛选 String keyword, //查询关键字 Location location, //定位坐标 BigDecimal distatce, //定位后根据距离搜索商家 List<Filter> filters, //过滤 Tenant.OrderType orderType //排序 ); }
C++
UTF-8
519
3.03125
3
[ "MIT" ]
permissive
#include <iostream> #include <algorithm> using namespace std; int knapSack(int W, vector<int> wt, vector<int>val, int n){ if(n==0|| W==0){ return 0; } if(wt[n-1] >W){ return knapSack(W, wt, val, n-1); } else return max(val[n-1]+ knapSack(W-wt[n-1], wt, val, n-1), knapSack(W, wt, val, n-1)); } int main() { vector<int> val={60,100,120}; vector<int> wt={10,20,30}; int W=50; int n=sizeof(val)/sizeof(val[0]); cout<<"the result is:"<<knapSack(W, wt, val, n); return 0; }
Python
UTF-8
461
3.765625
4
[]
no_license
l = [] n = int(input("Enter no of elements to be added in list : ")) i = 0 while i < n: get_num = int(input("Enter Value: ")) l.append(get_num) i += 1 value = int(input("Enter value to be found : ")) l.append(value) def sentinal(l, value): j = 0 while True: if l[j] == value: break j += 1 return j search = sentinal(l, value) if search < n: print("Element Found") else: print("Element not found")
Python
UTF-8
1,933
2.828125
3
[]
no_license
import struct import os from tarfile import _FileInFile as __FileInFile import tarfile import lzma class _FileInFile(__FileInFile): def seek(self, position, mode=0): """Seek to a position in the file. """ if mode == 0: self.position = position elif mode == 1: self.position += position elif mode == 2: self.position = self.size - position def seekable(self): return True class ArFile: def __init__(self, fileObj): self.fileObj = fileObj self.files = {} self.indexFiles() def indexFiles(self): self.files = {} fileObj = self.fileObj fileObj.seek(8) #skip header while fileObj.tell() != os.fstat(fileObj.fileno()).st_size: entry = ArFileEntry(self) self.files[entry.ar_name] = entry def getFile(self, name): return self.files[name] def open(self, name): return self.files[name].open() class ArFileEntry: ar_name = '' ar_date = '' ar_uid = '' ar_gid = '' ar_mode = '' ar_size = '' ar_fmag = '' def __init__(self, arfile): self.arfile = arfile f = arfile.fileObj self.ar_name = str.rstrip(f.read(16).decode()) self.ar_date = str.rstrip(f.read(12).decode()) self.ar_uid = str.rstrip(f.read(6).decode()) self.ar_gid = str.rstrip(f.read(6).decode()) self.ar_mode = str.rstrip(f.read(8).decode()) self.ar_size = int(str.rstrip(f.read(10).decode())) self.ar_fmag = str.rstrip(f.read(2).decode()) self.offset = f.tell() phys_size = self.ar_size if self.ar_size % 2 != 0: phys_size = self.ar_size + 1 f.seek(phys_size, 1) def open(self): return _FileInFile( self.arfile.fileObj, self.offset, self.ar_size, None )
Java
UTF-8
3,547
1.8125
2
[]
no_license
/** * AUTO GENERATED - DO NOT EDIT */ package com.vmail.service.support.delegate; import com.jwApps.collection.*; import com.jwApps.service.*; import com.jwApps.template.*; import com.jwApps.time.*; import com.jwApps.utility.*; import com.vmail.db.base.*; import com.vmail.model.*; import com.vmail.model.base.*; import com.vmail.model.core.*; import com.vmail.service.*; import com.vmail.service.support.*; import com.vmail.servlet.menu.*; import com.vmail.vo.*; /** * I provide a convenient implementation that delegates all methods. * This is used for subclasses that need to implement the full serviceIF * but only specialize a few methods. */ public abstract class AcResultServiceDelegate implements AcResultServiceIF { //################################################## //# constructor //##################################################// public AcResultServiceDelegate(AcResultServiceIF delegate) { _delegate = delegate; } //################################################## //# variables //##################################################// public AcResultServiceIF _delegate; //################################################## //# accessing //##################################################// public AcResultServiceIF getDelegate() { return _delegate; } //################################################## //# delegation //##################################################// public void release() { _delegate.release(); } public AcResult getResult(Long id) { return _delegate.getResult(id); } public AcResult getResult(AcResultPkIF pk) { return _delegate.getResult(pk); } public boolean resultExists(Long id) { return _delegate.resultExists(id); } public boolean resultExists(AcResultPkIF pk) { return _delegate.resultExists(pk); } public AcResult getResultByWebKey(String webKey) { return _delegate.getResultByWebKey(webKey); } public JwList<AcResult> getAll() { return _delegate.getAll(); } public JwList<AcResult> getAllAvailable() { return _delegate.getAllAvailable(); } public JwList<AcResult> getAllWhere(String whereClause, Integer rowLimit) { return _delegate.getAllWhere(whereClause, rowLimit); } public JwList<AcResult> getAllByActionId(Integer actionId) { return _delegate.getAllByActionId(actionId); } public JwList<AcResult> getAllByBatchId(Integer batchId) { return _delegate.getAllByBatchId(batchId); } public Long insert(AcResult result) { return _delegate.insert(result); } public void update(AcResult result) { _delegate.update(result); } public void delete(Long id) { _delegate.delete(id); } public JwList<AcResult> getAllByItemId(Integer itemId) { return _delegate.getAllByItemId(itemId); } public AcResult getFirstByItemId(Integer itemId) { return _delegate.getFirstByItemId(itemId); } public AcResult getLastByItemId(Integer itemId) { return _delegate.getLastByItemId(itemId); } public AcResult getLastLoadResultOnFlightId(Integer flightId) { return _delegate.getLastLoadResultOnFlightId(flightId); } public AcResult getDepart(Integer flightId) { return _delegate.getDepart(flightId); } }
C#
UTF-8
947
2.5625
3
[ "MIT" ]
permissive
namespace Cofoundry.Domain; /// <summary> /// Message published when properties that affect the URL /// of a page has changed (e.g. PageDirectoryId, UrlSlug, /// LocaleId etc). This message is not triggered if the URL /// indirectly changes e.g. if a parent directory changes. /// </summary> public class PageUrlChangedMessage : IPageContentUpdatedMessage { /// <summary> /// Id of the page that has the url updated /// </summary> public int PageId { get; set; } /// <summary> /// True if the page was in a published state when it was updated /// </summary> public bool HasPublishedVersionChanged { get; set; } /// <summary> /// The original full (relative) url of the page before the change was made. /// The url is formatted with the leading slash, but excluding the trailing /// slash e.g. "/my-directory/example-page". /// </summary public string OldFullUrlPath { get; set; } }
Python
UTF-8
530
2.875
3
[ "BSD-3-Clause" ]
permissive
# Authors: # Loic Gouarin <loic.gouarin@polytechnique.edu> # Benjamin Graille <benjamin.graille@math.u-psud.fr> # # License: BSD 3 clause """ Example of a square in 2D with a circular hole with a D2Q13 """ import pylbm dico = { "box": {"x": [0, 1], "y": [0, 1], "label": 0}, "elements": [pylbm.Circle((0.5, 0.5), 0.2, label=1)], "space_step": 0.05, "schemes": [{"velocities": list(range(13))}], } dom = pylbm.Domain(dico) dom.visualize(view_bound=True, scale=0.25) dom.visualize(view_distance=True, scale=0.25) dom.visualize(view_normal=True, scale=0.25, label=[1])
Java
GB18030
3,132
2.171875
2
[]
no_license
package com.huaixuan.network.biz.dao.express; import java.util.List; import java.util.Map; import com.huaixuan.network.biz.domain.express.Express; import com.huaixuan.network.biz.domain.express.query.FreightStatisticsQuery; import com.huaixuan.network.biz.query.QueryPage; /** * * @version 3.2.0 */ public interface ExpressDao { void addExpress(Express express); void editExpress(Express express); void removeExpress(Long expressId); Express getExpress(Long expressId); List<Express> getExpresss(); /** * ƲϢ(Ʋظlist.sizeֻΪ1) * * @param expressName * String * @return List * @author chenyan 2009/08/07 */ List<Express> getExpressByName(String expressName); /** * Ϣ * * @param expressName * String * @return List * @author fanyj 2009/12/07 */ List<Express> getExpressByCode(String expressCode); /** * Ϣ * * @param parMap * Map * @return int * @author chenyan 2009/08/10 */ int getExpressCountByCond(Map<String, String> parMap); /** * Ϣ * * @param parMap * Map * @param page * Page * @return QueryPage * @author chenyan 2009/08/10 */ QueryPage listExpressByCond(Map parMap, int currentPage, int pageSize); /** * IDϢ״̬ * * @param status * String * @param id * Long * @return int * @author chenyan 2009/08/10 */ int updateExpressStatusById(String status, Long id); /** * * @author chenhang 2011-5-5 * @description ID޸Աͬ * @param id * @return */ String getInterfaceExpressCodeByExpressId(Long id); /** * * @author chenhang 2011-5-17 * @description * @param id * @return */ Express getExpressIdByInterfaceExpressCode(String interfaceExpressCode); /** * * @author chenhang 2011-5-18 * @description * @param id * @return */ Express getExpressIdByExpressCode(String expressCode); /** * ״̬ȡϢ * * @param status * String * @return List * @author chenyan 2009/08/17 */ List<Express> listExpressByStatus(String status); /** * ͳ * * @param parMap * @author zhangwy * @return */ int getFreightCountByParameterMap(Map<String, String> parMap); /** * б * * @param parMap * @author zhangwy * @param QueryPage * @return */ QueryPage getFreightListsByParameterMap( FreightStatisticsQuery freightStatisticsQuery, int currentPage, int pageSize); /** * ܷ * * @param parMap * @return */ double getFreightAmountByParameterMap( FreightStatisticsQuery freightStatisticsQuery); /** * ȡƷ˾ * * @param parMap * @return */ List<Express> getGoodsExpressRelation(Map parMap); /** * ȡƷ˾ * * @param parMap * @return */ List<Express> getNotGoodsExpressRelation(Map parMap); }
Python
UTF-8
1,444
3.125
3
[ "MIT" ]
permissive
# _*_ coding: utf-8 _*_ # from linked_list import LinkedList import pytest def test_dll_init(): from src.double_linked_list import DblList test_list = DblList() assert test_list def test_dll_insert(): from src.double_linked_list import DblList test_list = DblList(['mom', '32', 43, [1, 2]]) test_list.insert(3) assert test_list.head.data == 3 def test_dll_append(): from src.double_linked_list import DblList test_list = DblList(['mom', '32', 43, [1, 2]]) test_list.append(3) assert test_list.tail.data == 3 def test_dll_pop(): from src.double_linked_list import DblList test_list = DblList(['mom', '32', 43, [1, 2]]) head = test_list.head assert test_list.pop() == head.data def test_dll_shift(): from src.double_linked_list import DblList test_list = DblList(['mom', '32', 43, [1, 2]]) tail = test_list.tail assert test_list.shift() == tail.data # def test_dll_remove(): # from src.double_linked_list import DblList # this_list = DblList([1]) # this_list.insert(2) # this_list.insert(4) # this_list.insert('bob') # search = this_list.search(4) # this_list.remove(search) # assert this_list.size() == 3 # def test_dll_remove2(): # from src.double_linked_list import DblList # this_list = DblList([1]) # search = this_list.search(4) # with pytest.raises(AttributeError): # this_list.remove(search)
JavaScript
UTF-8
1,596
2.53125
3
[ "BSD-3-Clause" ]
permissive
import createVariants from '../createVariants'; describe('createVariants', () => { function test(withBase, withCallback) { // these are stupid examples but enough to prove transformation works const baseConfig = { name: 'bundle.base' }; const variants = { rtl: [true, false], debug: [true, false], features: [0, 1, 2] }; const callback = (x) => { const ret = Object.assign({}, x); ret.name = `bundle.${x.rtl ? 'rtl' : 'no-rtl'}.${x.debug ? 'dbg': 'no-debug'}.${x.features}.js`; return ret; }; let result; if (withBase && withCallback) { result = createVariants(baseConfig, variants, callback); } else if (withBase && !withCallback) { result = createVariants(baseConfig, variants); } else if (!withBase && withCallback) { result = createVariants(variants, callback); } else { //!withBase && !withCallback result = createVariants(variants); } expect(result).toMatchSnapshot(); } it('should generate configs with "baseConfig, variants, configCallback" as params', () => { test(true, true); }); it('should generate configs with "variants, configCallback" as params', () => { test(false, true); }); it('should generate configs with "variants" as params', () => { test(false, false); }); it('should generate configs with baseConfig and variants', () => { test(true, false); }); });
JavaScript
UTF-8
430
2.734375
3
[]
no_license
const tail = require("../tail.js"); const assertEqual = require("../assertEqual.js"); const assert = require("chai").assert; describe("#tail", () => { const result = tail(["Hello","Lighthouse","Labs"]); it("returns true if the first element is Lightouse", () => { assert.deepEqual(result[0],"Lighthouse"); }); it("returns true if the second element is Labs", () => { assert.deepEqual(result[1],"Labs"); }); });
C++
UTF-8
1,493
2.828125
3
[]
no_license
/** * @file cromosoma.h * @brief Definici&oacute;n de la clase Cromosoma. * @author Mar&iacute;a Andrea Cruz Bland&oacute;n * @date 09/2013, 11/2013 * **/ #ifndef CROMOSOMA_H #define CROMOSOMA_H #include <igraph.h> #include <vector> #include <unordered_set> using namespace std; class Cromosoma { private: vector< vector<bool> > matrizX; vector< unordered_set<int> > configuracion; double modularidad; float proporcionClusters; bool calculoModularidad; int nodos; int cantClustersInicial; int cantClustersFinal; igraph_vector_t tamanioClusters; bool mutarDosBits; double calcularFraccionAristasInternas(vector<unordered_set<int> >& listaAdyacencia, int clusterA, int clusterB, int aristas); double calcularFraccionAristasExternas(vector<unordered_set<int> >& listaAdyacencia, int clusterA, int aristas); public: Cromosoma(); Cromosoma(vector<vector<bool> >& matrizXInicial, vector<unordered_set <int> > configuracionInicial, bool mutarDosBits, int nodos, int cantClustersInicial, int nodo, int cluster); ~Cromosoma(); void calcularModularidad(vector<unordered_set<int> >& listaAdyacencia, int aristas); void calcularProporcionClusters(); double getModularidad(); double getProporcionClusters(); void mutar(int nodosMutar[], int clustersMutar[]); vector<unordered_set<int> > getConfiguracionClustering(); bool getCalculoModularidad(); int getCantidadClustersFinal(); }; #endif // CROMOSOMA_H
JavaScript
UTF-8
632
2.5625
3
[]
no_license
import React,{useEffect,useState} from 'react'; import axios from 'axios' import './App.css'; import DisplayPokemon from './components/DisplayPokemon' function App() { const[pokemon,setPokemon] = useState([]) const getPokemon = ()=>{ axios.get("https://pokeapi.co/api/v2/pokemon/") .then(response => { console.log(response); setPokemon(response.data.results) }) .catch(err =>{ console.log(err); },[]) } useEffect(()=> { getPokemon(); }) return ( <div className="App"> <DisplayPokemon pokemon={pokemon} /> </div> ); } export default App;
Java
UTF-8
2,645
2.9375
3
[]
no_license
package com.main; import java.sql.SQLException; import java.util.Scanner; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.bean.InvalidAgeException; import com.bean.Student; import com.dao.StudentDao; public class MainClass { public static void main(String[] args) throws SQLException, InvalidAgeException { ApplicationContext ctx = new ClassPathXmlApplicationContext("com/res/Spring-conf.xml"); StudentDao dao = ctx.getBean("studentDao", StudentDao.class); MainClass main = new MainClass(); while (true) { System.out.println("Enter choice : "); Scanner sc = new Scanner(System.in); int choice = Integer.parseInt(sc.nextLine()); switch (choice) { case 1: System.out.println("1. Login Student :: "); main.login(); break; case 2: System.out.println("2. Add student :: "); main.addStudent(); break; // case 3: // System.out.println("update Student :: "); // System.out.println("enter id : "); // int id = Integer.parseInt(sc.nextLine()); // dao.updateStudent(id); // System.exit(0); // case 4: // System.out.println("delete Student :: "); // System.out.println("enter id : "); // int id1 = Integer.parseInt(sc.nextLine()); // dao.deleteStudent(id1); // break; default: System.out.println("wrong choice "); break; } } } public void addStudent() throws SQLException, InvalidAgeException { Scanner sc = new Scanner(System.in); System.out.println("Id : "); int id = Integer.parseInt(sc.nextLine()); System.out.println("name : "); String name = sc.nextLine(); System.out.println("age : "); int age = Integer.parseInt(sc.nextLine()); System.out.println("subject : "); String subject = sc.nextLine(); ApplicationContext ctx = new ClassPathXmlApplicationContext("com/res/Spring-conf.xml"); StudentDao dao = ctx.getBean("studentDao", StudentDao.class); Student s = ctx.getBean("student", Student.class); s.setId(id); s.setName(name); s.setAge(age); s.setSubject(subject); if(s.isValidAge()){ //dao.addStudentData(s); } } private void login() throws SQLException { Scanner sc = new Scanner(System.in); System.out.println("Id : "); int id = Integer.parseInt(sc.nextLine()); System.out.println("name : "); String name = sc.nextLine(); ApplicationContext ctx = new ClassPathXmlApplicationContext("com/res/Spring-conf.xml"); StudentDao dao = ctx.getBean("studentDao", StudentDao.class); dao.loginStudent(id, name); } }
Java
UTF-8
996
3.71875
4
[]
no_license
package com.leetcode.arrays; /** * https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ * * @author prabhakaran.nivanil * */ public class BuyAndSellStockOnce { public static void main(String[] args) { BuyAndSellStockOnce buySellStock = new BuyAndSellStockOnce(); int[] prices = new int[] { 7, 6, 4, 3, 1 }; System.out.println(buySellStock.maxProfit(prices)); } public int maxProfit(int[] prices) { int leftMin[] = new int[prices.length]; int rightMax[] = new int[prices.length]; int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; for (int i = 0; i < leftMin.length; i++) { if (min > prices[i]) min = prices[i]; leftMin[i] = min; } for (int i = rightMax.length - 1; i >= 0; i--) { if (max < prices[i]) max = prices[i]; rightMax[i] = max; } int diff = Integer.MIN_VALUE; for (int i = 0; i < prices.length; i++) { diff = Math.max(rightMax[i] - leftMin[i], diff); } if (diff < 0) return 0; return diff; } }
PHP
UTF-8
6,941
2.671875
3
[]
no_license
<?php if (!defined('BASE_PATH')) exit('Access Denied!'); /** * * Freedl_Service_Cugd * @author fanch * */ class Freedl_Service_Cugd extends Common_Service_Base{ /** * 按条件检索单条记录 * @param array $params * @param array $orderBy * @return */ public static function getBy($params, $orderBy = array()){ if (!is_array($params)) return false; return self::_getDao()->getBy($params, $orderBy); } /** * 按条件检索单条记录 * @param array $params * @param array $orderBy * @return */ public static function getsBy($params, $orderBy = array()){ if (!is_array($params)) return false; return self::_getDao()->getsBy($params, $orderBy); } /** * 检查游戏id是否是指定活动中专区免流量类型的游戏 * @param int $gameid * @return bool */ public static function checkFreedlGame($gameid){ //联通内容库上线同时游戏内容库也是上线的 $ret = self::_getDao()->getBy(array('cu_status' => array('IN', array(2, 4)) , 'game_status'=>1 , 'game_id'=>$gameid)); return $ret['id'] ? true : false; } /** * 获取列表数据 * Enter description here ... * @param array $params * @param int $page * @param int $limit * @param array $orderBy * @return array */ public static function getList($page = 1, $limit = 10, $params = array(), $orderBy = array('id'=>'DESC')) { if ($page < 1) $page = 1; $start = ($page - 1) * $limit; $ret = self::_getDao()->getList($start, $limit, $params, $orderBy); $total = self::_getDao()->count($params); return array($total, $ret); } /** * * 更新联通免流量游戏内容库 * @param array $data * @param array $params */ public static function updateCugd($data, $params) { if (!is_array($data)) return false; $data = self::_cookData($data); return self::_getDao()->updateBy($data, $params); } /** * * 添加联通免流量游戏内容库资源 * @param array $data */ public static function addCugd($data) { if (!is_array($data)) return false; $data = self::_cookData($data); return self::_getDao()->insert($data); } /** * * 删除联通免流量游戏内容库数据 * @param array $data */ public static function deleteCugd($data) { if (!is_array($data)) return false; return self::_getDao()->deleteBy($data); } /** * 填充资源数据 * @param unknown $game * @return array * * 1073 掌上网游 * 1074 其他 * 1075 休闲游戏 * 1076 益智游戏 * 1077 棋牌游戏 * 1078 体育运动 * 1079 动作射击 */ public static function fillData($game){ $default = array('1074','其他'); //测试站类型对接配置 // $game_cutype = array( // '15'=> array('1077','棋牌游戏'), //'扑克棋牌' // '16'=> array('1076','益智游戏'), //'塔防游戏' // '18'=> array('1073','掌上网游'), //'大型网游', // '19'=> array('1075','休闲游戏'), //'经营养成', // '20'=> array('1078','体育运动'), //'竞速游戏', // '21'=> array('1075','休闲游戏'), //'休闲益智', // '30'=> array('1079','动作射击'), //'动作冒险', // '43'=> array('1079','动作射击'), //'飞行射击', // '44'=> array('1073','掌上网游'), // ); //正式站类型对接配置 $game_cutype = array( '1'=> array('1075','休闲游戏'), //'休闲益智' '3'=> array('1079','动作射击'), //'动作冒险' '4'=> array('1077','棋牌游戏'), //'扑克棋牌' '5'=> array('1076','益智游戏'), //'塔防游戏' '8'=> array('1075','休闲游戏'), //'模拟经营' '13'=> array('1073','掌上网游'), //'角色扮演' '32'=> array('1073','掌上网游'), //'手机网游' '35'=> array('1079','动作射击'), //'飞行射击' '36'=> array('1078','体育运动'), //'跑酷竞速' '151'=> array('1077','棋牌游戏'), //'卡牌游戏' '152'=> array('1074','其他'), //'免费游戏' '154'=> array('1078','体育运动'), //'体育竞技' '155'=> array('1076','益智游戏'), //'消除游戏' '156'=> array('1075','休闲游戏'), //'音乐游戏' '157'=> array('1074','其他'), //'破解游戏' ); //提交游戏数据整理 $tmp = $data = array(); if($game['gimgs']) { foreach ($game['gimgs'] as $value){ $tmp[] = array('url'=> $value, 'scope'=>'all', 'createTime' => date('Y-m-d\TH:i:s')); } } $data = array( 'contentName' => html_entity_decode($game['name']), 'description' => preg_replace('/\<br(\s*)?\/?\>/i', "\n", html_entity_decode($game['descrip'])), 'typeId' => isset($game_cutype[$game['category_id']]) ? intval($game_cutype[$game['category_id']][0]) : intval($default[0]), 'typeName' => isset($game_cutype[$game['category_id']]) ? $game_cutype[$game['category_id']][1] : $default[1], 'providerId'=>'108', //提供商Id 'providerName'=>'金立', //提供商名称 'providerPid'=> $game['id'], //提供商资源Id 'createTime'=> $game['create_time'] ? date('Y-m-d\TH:i:s', $game['create_time']): date('Y-m-d\TH:i:s'), 'updateTime'=> $game['online_time']? date('Y-m-d\TH:i:s', $game['online_time']): date('Y-m-d\TH:i:s'), 'price'=> 0, 'logos'=>array( array('url'=> $game['img'], 'scope'=>'all', 'createTime' => date('Y-m-d\TH:i:s')) ), 'screenshots'=> $tmp, 'files'=> array( array('url'=>$game['link'], 'platform'=>'android', 'format' => '.apk', 'size'=> strval(ceil($game['size']*1024)), 'version'=> $game['version'], 'updateTime'=> date('Y-m-d\TH:i:s')) ), 'platform'=>'android', 'ext'=> array( array('name' => 'language','value' => $game['language']), array('name' => 'developers','value' => $game['developer'] ? $game['developer'] : '互联网'), ), 'parentTypeId'=> '2', 'parentTypeName'=> '游戏', 'free'=> '免费' ); return $data; } /** * * Enter description here ... * @param array $data */ private static function _cookData($data) { $tmp = array(); if(isset($data['id'])) $tmp['id'] = intval($data['id']); if(isset($data['game_id'])) $tmp['game_id'] = $data['game_id']; if(isset($data['app_id'])) $tmp['app_id'] = $data['app_id']; if(isset($data['version'])) $tmp['version'] = $data['version']; if(isset($data['version_code'])) $tmp['version_code'] = $data['version_code']; if(isset($data['content_id'])) $tmp['content_id'] = $data['content_id']; if(isset($data['cu_status'])) $tmp['cu_status'] = $data['cu_status']; if(isset($data['online_flag'])) $tmp['online_flag'] = $data['online_flag']; if(isset($data['cu_online_time'])) $tmp['cu_online_time'] = $data['cu_online_time']; if(isset($data['game_status'])) $tmp['game_status'] = $data['game_status']; if(isset($data['create_time'])) $tmp['create_time'] = $data['create_time']; return $tmp; } /** * * @return Freedl_Dao_Cugd */ private static function _getDao() { return Common::getDao("Freedl_Dao_Cugd"); } }
Java
UTF-8
589
1.632813
2
[]
no_license
package br.gov.pbh.desif.model.pojo; import br.gov.pbh.desif.model.pojo.base.AbstractRelatorioEstaticoApuracaoIssqnVO; import java.util.Date; public class RelatorioEstaticoApuracaoIssqnVO extends AbstractRelatorioEstaticoApuracaoIssqnVO { public RelatorioEstaticoApuracaoIssqnVO() { } public RelatorioEstaticoApuracaoIssqnVO(String nomeMunicipio, String nomeInstituicao, String iniCNPJ, String fimCNPJ, Date dataIniCompetencia, Short tipoConsolidacao) { super(nomeMunicipio, nomeInstituicao, iniCNPJ, fimCNPJ, dataIniCompetencia, tipoConsolidacao); } }
Java
UTF-8
1,536
2.09375
2
[ "Apache-2.0" ]
permissive
/* * GeoAPI - Java interfaces for OGC/ISO standards * Copyright © 2005-2023 Open Geospatial Consortium, Inc. * http://www.geoapi.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengis.geometry.coordinate; import org.opengis.annotation.UML; import static org.opengis.annotation.Specification.*; /** * A {@linkplain GriddedSurface gridded surface} given as a family of circles whose positions * vary along a set of parallel lines, keeping the cross sectional horizontal curves of a constant * shape. Given the same working assumptions as in {@linkplain GriddedSurface gridded surface}, a * cylinder can be given by two circles, giving us control points of the form * * &lt;&lt;P1, P2, P3&gt;, &lt;P4, P5, P6&gt;&gt;. * * @version <A HREF="http://www.opengeospatial.org/standards/as">ISO 19107</A> * @author Martin Desruisseaux (IRD) * @since GeoAPI 2.0 */ @UML(identifier="GM_Cylinder", specification=ISO_19107) public interface Cylinder extends GriddedSurface { }
Java
UTF-8
2,732
3.3125
3
[ "Apache-2.0" ]
permissive
package com.lucidworks.analysis; import java.util.ArrayList; import static java.lang.System.arraycopy; /** * Utility functions for working with character arrays. */ public class CharArrayUtil { public static boolean equals(char[] buffer, char[] phrase) { if (buffer == null || phrase == null) return false; if (phrase.length != buffer.length) return false; for (int i = 0; i < phrase.length; i++) { if (buffer[i] != phrase[i]) return false; } return true; } public static boolean startsWith(char[] buffer, char[] phrase) { if (buffer == null || phrase == null) return false; if (phrase.length > buffer.length) return false; for (int i = 0; i < phrase.length; i++) { if (buffer[i] != phrase[i]) return false; } return true; } public static boolean endsWith(char[] buffer, char[] phrase) { if (buffer == null || phrase == null) return false; if (phrase.length > buffer.length) return false; for (int i = 1; i < phrase.length + 1; ++i) { if (buffer[buffer.length - i] != phrase[phrase.length - i]) return false; } return true; } public static char[] replaceWhitespace(char[] token, Character replaceWhitespaceWith) { char[] replaced = new char[token.length]; int sourcePosition, destinationPosition; for (sourcePosition = 0, destinationPosition = 0; sourcePosition < token.length; sourcePosition++) { if (token[sourcePosition] == ' ') { if (replaceWhitespaceWith == null) { continue; } replaced[destinationPosition++] = replaceWhitespaceWith; } else { replaced[destinationPosition++] = token[sourcePosition]; } } if (sourcePosition != destinationPosition){ char[] shorterReplaced = new char[destinationPosition]; System.arraycopy(replaced, 0, shorterReplaced, 0, destinationPosition); return shorterReplaced; } return replaced; } public static boolean isSpaceChar(char ch) { return " \t\n\r".indexOf(ch) >= 0; } public static char[] getFirstTerm(char[] phrase) { if (phrase.length == 0) return new char[] {}; int index = 0; while (index < phrase.length) { if (CharArrayUtil.isSpaceChar(phrase[index++])) { break; } } if (index == phrase.length) return phrase; char[] firstTerm = new char[index - 1]; arraycopy(phrase, 0, firstTerm, 0, index - 1); return firstTerm; } }
Java
UTF-8
5,479
1.945313
2
[]
no_license
package fr.lekiosque; import io.appium.java_client.MobileElement; import io.appium.java_client.android.Connection; import org.junit.AfterClass; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.WebDriverWait; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOfElementLocated; /** * Created by FatimaZahra on 31/01/2017. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class NewsstandTest { static AndroidConfigClass d = new AndroidConfigClass(); WebDriverWait wait = new WebDriverWait(d.getDriver(), 10); //Check that blocks are visible @Test public void testACheckBlocksVisibility() throws Exception { wait.until(visibilityOfElementLocated(By.id("android:id/up"))); wait.until(visibilityOfElementLocated(By.id("CDNewsstandUICarousel"))); Assert.assertTrue(d.getDriver().findElement(By.id("CDNewsstandUICarousel")).isDisplayed()); Assert.assertTrue(d.getDriver().findElement(By.id("CDNewsstandUIHorizontalListView")).isDisplayed()); Assert.assertTrue(d.getDriver().findElement(By.id("menu_newsstand_action_categories")).isDisplayed()); } //Change category and check that blocks are visible @Test public void testBChangeCategory() throws Exception { wait.until(visibilityOfElementLocated(By.id("menu_newsstand_action_categories"))); d.getDriver().findElement(By.id("menu_newsstand_action_categories")).click(); wait.until(visibilityOfElementLocated(By.id("CDCategoryUIIssueCoverActualité"))); Assert.assertTrue(d.getDriver().findElement(By.id("CDCategoryUIIssueCoverQuotidiens")).isDisplayed()); Assert.assertTrue(d.getDriver().findElement(By.id("CDCategoryUIIssueCoverInternationaux")).isDisplayed()); d.getDriver().findElement(By.id("CDCategoryUIIssueCoverActualité")).click(); wait.until(visibilityOfElementLocated(By.id("CDCategoryIssueUICover"))); Assert.assertEquals("Actualité", this.d.getDriver().findElement(By.id("CDCategoryIssueSubTitleUIText")).getText()); Assert.assertTrue(d.getDriver().findElement(By.id("CDCategorySubCategoryUIMenuBar")).isDisplayed()); d.getDriver().findElement(By.id("android:id/up")).click(); d.getDriver().findElement(By.id("android:id/up")).click(); wait.until(visibilityOfElementLocated(By.id("menu_newsstand_action_categories"))); } //switch store and check that elements are present @Test public void testCSwitchStore() throws Exception { wait.until(visibilityOfElementLocated(By.id("menu_newsstand_action_categories"))); d.getDriver().findElement(By.id("android:id/up")).click(); wait.until(visibilityOfElementLocated(By.id("CDMenuCountryUIButton"))); d.getDriver().findElement(By.id("CDMenuCountryUIButton")).click(); MobileElement listItem = (MobileElement) d.getDriver().findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().className(\"android.widget.FrameLayout\")).scrollIntoView(new UiSelector().text(\"United Kingdom\"));"); //GenericClass.scroll("android.widget.FrameLayout","United Kingdom"); //TODO: do not escape slash caracter or try a different locator d.getDriver().findElement(By.id("android:id/up")).click(); wait.until(visibilityOfElementLocated(By.id("CDNewsstandUICarousel"))); Assert.assertTrue(d.getDriver().findElement(By.id("CDNewsstandUICarousel")).isDisplayed()); Assert.assertTrue(d.getDriver().findElement(By.id("CDNewsstandUIHorizontalListView")).isDisplayed()); d.getDriver().findElement(By.id("android:id/up")).click(); wait.until(visibilityOfElementLocated(By.id("CDMenuCountryUIButton"))); d.getDriver().findElement(By.id("CDMenuCountryUIButton")).click(); GenericClass.scroll("android.widget.FrameLayout", "France"); wait.until(visibilityOfElementLocated(By.id("android:id/up"))); d.getDriver().findElement(By.id("android:id/up")).click(); } //switch product category BD or MAG @Test public void testDSwitchProductCategory() throws Exception { wait.until(visibilityOfElementLocated(By.id("android:id/up"))); Assert.assertTrue(d.getDriver().findElement(By.id("CDNewsstandMenuProductTypeUISpinner")).isDisplayed()); d.getDriver().findElement(By.id("CDNewsstandMenuProductTypeUISpinner")).click(); d.getDriver().findElement(By.id("CDNewsstandMenuProductTypeUITextBD")).click(); wait.until(visibilityOfElementLocated(By.id("CDNewsstandUICarousel"))); Assert.assertEquals("Les BD ", d.getDriver().findElement(By.id("CDNewsstandBlockTitleUIText")).getText()); Assert.assertTrue(d.getDriver().findElement(By.id("CDNewsstandUIHorizontalListView")).isDisplayed()); } //Turn off internet connection and check that the butom bar is displayed @Test public void testEOfflineMode() throws Exception { d.getDriver().setConnection(Connection.AIRPLANE); wait.until((visibilityOfElementLocated(By.id("menu_newsstand_action_categories")))); Assert.assertTrue(d.getDriver().findElement(By.id("CDNewsstandNoConnectionUIBar")).isDisplayed()); d.getDriver().setConnection(Connection.ALL); } @AfterClass public static void tearDown() { d.getDriver().quit(); } }
Java
UTF-8
1,338
2.125
2
[]
no_license
package iiitb.ebay.users.model; public class UserAddress { private int userID; private int userAddressID; private String address1; private String contactName; private String city; private String state; private int pinCode; public String getContactName() { return contactName; } public void setContactName(String contactName) { this.contactName = contactName; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public int getPinCode() { return pinCode; } public void setPinCode(int pinCode) { this.pinCode = pinCode; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } private String country; public int getUserID() { return userID; } public void setUserID(int userID) { this.userID = userID; } public int getUserAddressID() { return userAddressID; } public void setUserAddressID(int userAddressID) { this.userAddressID = userAddressID; } public String getAddress1() { return address1; } public void setAddress1(String address1) { this.address1 = address1; } }
Ruby
UTF-8
377
3.53125
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Dog attr_accessor :owner, :mood attr_reader :name #when reading a book you are not changing it, when you are writing a book it is constantly changing @@all = [] def initialize(name, owner) @name = name @owner = owner @mood = "nervous" @@all << self end def self.all @@all end end #object = Owner.new("Irene") #Dog.new("lucky", object)
Python
UTF-8
6,552
2.515625
3
[]
no_license
import numpy as np import cv2 from scipy.spatial import distance as dist def mouse_handler(event, x, y, flags, param): #마우스로 좌표 알아내기 if event == cv2.EVENT_LBUTTONUP: clicked = [x, y] print(clicked) def grab_cut(resized): mask_img = np.zeros(resized.shape[:2], np.uint8) #초기 마스크를 만든다. #grabcut에 사용할 임시 배열을 만든다. bgdModel = np.zeros((1,65), np.float64) fgdModel = np.zeros((1,65), np.float64) #rect = (130, 51, 885-130, 661-51) #mouse_handler로 알아낸 좌표 / card1일때 rect = (150, 150, 800, 750) #card2 일 때 cv2.grabCut(resized, mask_img, rect, bgdModel, fgdModel, 3, cv2.GC_INIT_WITH_RECT) #grabcut 실행 mask_img = np.where((mask_img==2)|(mask_img==0), 0, 1).astype('uint8') #배경인 곳은 0, 그 외에는 1로 설정한 마스크를 만든다. img = resized*mask_img[:,:,np.newaxis] #이미지에 새로운 마스크를 곱해 배경을 제외한다. background = resized - img background[np.where((background >= [0, 0, 0]).all(axis = 2))] = [0, 0, 0] img_grabcut = background + img cv2.imshow('grabcut', img_grabcut) return img_grabcut #에지 검출 def edge_detection(img_grabcut): gray = cv2.cvtColor(img_grabcut, cv2.COLOR_BGR2GRAY) _, gray = cv2.threshold(gray, 120, 255, cv2.THRESH_TOZERO) gray = cv2.GaussianBlur(gray, (7, 7), 0) gray = cv2.bilateralFilter(gray, 9, 75, 75) gray = cv2.edgePreservingFilter(gray, flags=1, sigma_s=45, sigma_r=0.2) edged = cv2.Canny(gray, 75, 200, True) #cv2.imshow("grayscale", gray) cv2.imshow("edged", edged) return edged def contours(edged): (cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5] #contourArea : contour가 그린 면적 largest = max(cnts, key=cv2.contourArea) rect = cv2.minAreaRect(largest) r = cv2.boxPoints(rect) box = np.int0(r) size = len(box) # 2.A 원래 영상에 추출한 4 변을 각각 다른 색 선분으로 표시한다. cv2.line(resized, tuple(box[0]), tuple(box[size-1]), (255, 0, 0), 3) for j in range(size-1): color = list(np.random.random(size=3) * 255) cv2.line(resized, tuple(box[j]), tuple(box[j+1]), color, 3) #4개의 점 다른색으로 표시 boxes = [tuple(i) for i in box] cv2.line(resized, boxes[0], boxes[0], (0, 0, 0), 15) #검 cv2.line(resized, boxes[1], boxes[1], (255, 0, 0), 15) #파 cv2.line(resized, boxes[2], boxes[2], (0, 255, 0), 15) #녹 cv2.line(resized, boxes[3], boxes[3], (0, 0, 255), 15) #적 cv2.imshow("With_Color_Image", resized) return boxes def order_dots(pts): p = np.array(pts) xSorted = p[np.argsort(p[:, 0]), :] leftMost = xSorted[:2, :] rightMost = xSorted[2:, :] leftMost = leftMost[np.argsort(leftMost[:, 1]), :] (a, c) = leftMost D = dist.cdist(a[np.newaxis], rightMost, "euclidean")[0] (b, d) = rightMost[np.argsort(D), :] return a, b, c, d def transformation(resized, pts): p = np.array(pts) rect = np.zeros((4, 2), dtype="float32") s = p.sum(axis=1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] diff = np.diff(pts, axis=1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] a, b, c, d = rect w1 = abs(c[0] - d[0]) w2 = abs(a[0] - b[0]) h1 = abs(b[1] - c[1]) h2 = abs(a[1] - d[1]) w = max([w1, w2]) h = max([h1, h2]) dst = np.float32([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]]) M = cv2.getPerspectiveTransform(rect, dst) result = cv2.warpPerspective(resized, M, (w, h)) cv2.imshow("transformation", result) return result def wait(): wait = cv2.waitKey(0) while (wait != 32): wait = cv2.waitKey(0) print(wait) class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"[{self.x} {self.y}]" #y절편 구하기 def get_intercepts(ordered_dots): slopes = get_slopes(ordered_dots) a, b, c, d = [Point(*coord) for coord in ordered_dots] left = -a.x * slopes[0] + a.y right = -b.x * slopes[1] + b.y top = -a.x * slopes[2] + a.y bottom = -c.x * slopes[3] + c.y return left, right, top, bottom #기울기 구하기 def get_slopes(ordered_dots): a, b, c, d = [Point(*coord) for coord in ordered_dots] left = (a.y - c.y) / (a.x - c.x) right = (b.y - d.y) / (b.x - d.x) top = (a.y - b.y) / (a.x - b.x) bottom = (c.y - d.y) / (c.x - d.x) return left, right, top, bottom if __name__ == "__main__": filename = input('Enter Filename: ') img = cv2.imread(filename) if img.shape[0] * img.shape[1] > 1000 ** 2: resized = cv2.resize(img, dsize=(0, 0), fx=0.25, fy=0.25, interpolation=cv2.INTER_LINEAR) else: resized = cv2.resize(img, dsize=(0, 0), fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR) cut = grab_cut(resized) wait() edges = edge_detection(cut) wait() pts = contours(edges) wait() res = transformation(resized, pts) dots = order_dots(pts) a, b, c, d = dots # 각각의 점에 a,b,c,d 표시해놓았음. font = cv2.FONT_HERSHEY_COMPLEX fontScale = 1.2 img_dots = cv2.line(resized, tuple(a), tuple(a), (0, 0, 255), 20) img_dots = cv2.putText(resized, 'a', tuple(a), font, fontScale, (0, 0, 255), 2) img_dots = cv2.line(resized, tuple(b), tuple(b), (0, 0, 255), 20) img_dots = cv2.putText(resized, 'b', tuple(b), font, fontScale, (0, 0, 255), 2) img_dots = cv2.line(resized, tuple(c), tuple(c), (0, 0, 255), 20) img_dots = cv2.putText(resized, 'c', tuple(c), font, fontScale, (0, 0, 255), 2) img_dots = cv2.line(resized, tuple(d), tuple(d), (0, 0, 255), 20) img_dots = cv2.putText(resized, 'd', tuple(d), font, fontScale, (0, 0, 255), 2) print("2-B 추출된 네변(선분), (즉, 좌, 우, 상, 하단 )의 기울기, y 절편, 양끝점의 좌표을 각각 출력할 것.\n") print("기울기 :") print(get_slopes(dots)) print("\n") print("y절편 :") print(get_intercepts(dots)) print("\n") print("양끝점 :") print(a, c) print(b, d) print(a, b) print(c, d) #cv2.imshow("resized", resized) print("\n") print("3-C. 네 꼭지점(좌상, 좌하, 우상, 우하 코너)의 좌표를 출력한다") print(a) print(b) print(c) print(d) wait()
PHP
UTF-8
1,286
2.5625
3
[ "MIT" ]
permissive
<?php namespace Magnum\Output\Render; use PHPUnit\Framework\TestCase; class MutableContextTest extends TestCase { public function testArrayInConstructor() { $payload = ['test' => 'context']; $mc = new MutableContext($payload); self::assertEquals($payload, $mc->provide('test')); } public function provideGetValues() { return [ ['context', ['test' => 'context']], ['kakaw', [], 'kakaw'], [null, []] ]; } /** * @dataProvider provideGetValues */ public function testGet($expected, $payload, $alt = null) { $mc = new MutableContext($payload); self::assertEquals($expected, $mc->get('test', $alt)); } public function testSet() { $mc = new MutableContext(); $mc->set('test', 'context'); self::assertEquals(['test' => 'context'], $mc->provide('test')); } public function testAcceptsAnything() { $mc = new MutableContext(); self::assertTrue($mc->accepts('')); self::assertTrue($mc->accepts(null)); self::assertTrue($mc->accepts('test')); } public function testProvidesReturnsArray() { $payload = ['test' => 'context']; $mc = new MutableContext($payload); self::assertEquals($payload, $mc->provide('')); self::assertEquals($payload, $mc->provide(null)); self::assertEquals($payload, $mc->provide('test')); } }
PHP
UTF-8
3,375
3.0625
3
[]
no_license
<?php require_once('../object/DBConnect.php'); require_once('../object/Question.php'); require_once ('../object/Choice.php'); class QuestionDao { private $dbConnect; function __construct() { $this->dbConnect = new DBConnect(); } public function getAllQuestions() { $AllQuestions = array(); $this->dbConnect->connectDB(); //$questions = $this->dbConnect->executeSQL("SELECT * FROM Questionnaire Where id<=10"); $questionsAndAnswers = $this->dbConnect->executeSQL("SELECT jc_Choix.id as id_choix, jc_Choix.id_question as id_question, jc_Choix.reponse as choix_reponse, jc_Questionnaire.id_correction as id_correction, jc_Questionnaire.question as subject FROM jc_Questionnaire LEFT JOIN jc_Choix ON jc_Questionnaire.id = jc_Choix.id_question where jc_Questionnaire.id<=10 order by jc_Questionnaire.id"); $x = 1; $y = 0; $choices = array(); foreach($questionsAndAnswers as $row) { if($row['id_question'] == $x) { $y++; $choice = new Choice; $choice->setSubject($row['choix_reponse']); $choice->setId($row['id_choix']); $choice->setQuestionId($row['id_question']); array_push($choices, $choice); } if($y==4) { $x++; $y = 0; $question = new Question; $question->setId($row['id_question']); $question->setAnswer($row['id_correction']); $question->setSubject($row['subject']); $question->setChoices($choices); $choices = array(); array_push($AllQuestions, $question); } } /* foreach ($questions as $row) { $question = new Question; $question->setId($row['Questionnaire.id']); $question->setAnswer($row['id_correction']); $question->setSubject($row['question']); $choices = array(); $reponses = $this->dbConnect->prepareAndExecuteSQL("SELECT * FROM Choix where id_question = ?", array($row['id'])); while ($row2 = $reponses->fetch()) { $choice = new Choice; $choice->setSubject($row2['reponse']); $choice->setId($row2['id']); $choice->setQuestionId($row2['id_question']); array_push($choices, $choice); } $question->setChoices($choices); array_push($AllQuestions, $question); }*/ $this->dbConnect->closeConnection(); //convert result to a list of question objects //charge those choices return $AllQuestions; } public function getPersonId($nom,$email) { $this->dbConnect->connectDB(); $Person =$this->dbConnect->executeSQL("SELECT * FROM jc_Personne Where nom = '$nom' and email = '$email'"); $this->dbConnect->closeConnection(); return $Person; } }
Python
UTF-8
498
2.8125
3
[]
no_license
import math zonas_wifi=[['2.698','-76.680','63'],['2.724','-76.693','20'],['2.606','-76.742','680'],['2.698','-76.690','15']] coordenadas= [[2.697,-76.681],[2.697, -76.741],[2.695, -76.691]] latitud=float(coordenadas[0][0]) longitud=float(coordenadas[1][0]) r=6372.795477598 a=(latitud-float(zonas_wifi[0][0]))/2 b=math.cos(float(latitud)) f=a+b c=math.cos(float(zonas_wifi[0][1])) d=(longitud-float(zonas_wifi[1][0]))/2 e=math.sqrt(float(f*c*d)) dist_1= 2*float(r)*math.asin(e) print(str(dist_1))
Python
UTF-8
4,762
2.53125
3
[]
no_license
# -*- coding: utf-8 -*- ERRORMSGZH = { 99: "服务器繁忙,稍后再试", 100: "消息格式错误", 101: "非法操作", 102: "找不的此角色", 103: "功能未开放", 104: "操作太快", 105: "你的帐号在别处登录,请重新登录", 110: "此功能只对VIP开放", 111: "VIP等级不够", 120: "金币不足", 121: "元宝不足", 122: "等级不足 ", 123: "官职不足", 130: "装备不够", 131: "宝石不够", 132: "材料不够", 133: "卡魂不够", 134: "通用卡魂不够", 140: "武将不存在", 141: "装备不存在", 142: "宝石不存在", 143: "道具不存在", 144: "此道具不能使用", 150: "此帐号已注册", 151: "密码错误", 152: "帐号不存在", 153: "帐号被冻结,无法登录", 154: "登录失败,请重试", 155: "所选服务器不存在", 160: "角色名已经被占用", 161: "角色名太长", 162: "请重新选择合适的名字", 163: " 所在服已经有角色,无法重复建立", 169: "建立角色失败,请重试", 300: "装备已经到最高等级,无法升级", 301: "装备等级不能高于主公等级,无法强化", 302: "装备已经到最高阶,无法升阶", 303: "装备镶嵌宝石,镶嵌错误", 304: "装备取下宝石错误", 305: "装备在阵法中,无法出售", 320: "宝石无法合成", 400: "武将到最高i阶,无法升阶", 401: "卡魂不够,无法升阶", 410: "已经拥有武将,无法招募", 500: "阵法错误,不存在的插槽", 501: "阵法错误,装备类型放错", 502: "阵法错误,武将在多个插槽中", 503: "阵法错误,同名武将不能上阵", 504: "阵法错误,每军必须有武将", 505: "阵法错误,插槽没有武将", 506: "阵法错误,插槽数量不匹配", 600: "关卡不存在", 601: "角色等级小于关卡需求等级,无法进入", 602: "关口为达到开启条件,无法进入", 700: "无法同时进行多个挂机", 701: "当日挂机时间已经用完", 702: "不存在的挂机", 703: "挂机已经结束,无法取消", 704: "当日挂机时间已经用完", 705: "挂机中,无法战斗", 800: "精英关卡不存在", 801: " 精英关卡没有开启", 802: "此精英关卡当日次数已经用完", 803: "精英关卡总次数已用完", 805: "精英关卡总次数已用完", 806: "此关卡重置次数已用完", 807: "总重置次数已用完", 850: "此活动关卡没有开启", 851: "活动关卡总次数已用完", 852: "此活动关卡不存在", 1000: "翻卡错误,不存在的插槽", 1001: "翻卡错误,对应位置已经翻开了", 1002: "翻卡次数已经用完,需要使用元宝", 1003: "当前武将都已经开启,无法再点将", 1100: "要掠夺的对象不在掠夺列表中", 1101: "今日掠夺次数已经用完", 1102: "掠夺没有目标玩家,无法领取奖励", 1103: "掠夺获取奖励,对应奖励类型已经获取过", 1104: "掠夺获取奖励,但是积分不够", 1105: "今日掠夺次数已经用完", 1200: "囚犯不存在", 1201: "囚犯无法再获取", 1300: "不存在的任务", 1301: "任务没有完成", 1302: "此任务已经领过奖励,无法重复领奖", 1400: "不存在的邮件", 1401: "邮件没有附件", 1500: "今日竞技场次数已经用完", 1501: "今日竞技场次数已经用完", 1600: "成就没有完成", 1601: "成就不存在", 2000: "不存在的奖励", 2100: "今日已经签到过了", 2101: "没有官职不能领奖", 2102: "当日已经领取过官职奖励", 2200: "今日征收次数已经用完", 2201: "今日征收次数已经用完", 3000: "商城物品不存在", 3001: "商城物品有等级限制,无法购买", 3002: "商城物品有VIP限制,无法购买", 3003: "商品剩余数量不足", 3004: "商品达到每人每天限购,无法购买", 3005: "商城购买失败", 3100: "好友已满,无法再加好友", 3101: "对方已经是你的好友", 3102: "对方不是你的好友", 3103: "没有向对方发出好友申请", 3104: "对方没有向你发送好友申请", 3105: "好友已满,无法再加好友", 3200: "聊天消息太长", 4000: "激活码不存在", 4001: "此激活码已经使用过", 4002: "此激活码已经达到可用次数限制", 4003: "此激活码已经过期", 4004: "此激活码不能使用", 4005: "此激活码还未到使用时间", }
Java
UTF-8
3,889
2.4375
2
[]
no_license
package com.example.c4q.materialcrossword.crossword.view; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.example.c4q.materialcrossword.Mvp; import com.example.c4q.materialcrossword.R; import com.example.c4q.materialcrossword.crossword.adapters.CrosswordAdapter; import com.example.c4q.materialcrossword.crossword.model.Cell; import com.example.c4q.materialcrossword.crossword.model.Crossword; import java.util.List; /** * Created by C4Q on 10/21/16. */ public class CellViewHolder implements Mvp.View, View.OnClickListener{ public TextView cellViewText; public TextView numberTV; private String letter; private CrosswordAdapter crosswordAdapter; private String acrossHint; private String downHint; public TextView currentCellView; private Cell cell; public CellViewHolder(View itemView, CrosswordAdapter crosswordAdapter) { this.crosswordAdapter = crosswordAdapter; cellViewText = (TextView) itemView.findViewById(R.id.text_view); numberTV = (TextView) itemView.findViewById(R.id.number_tv); itemView.setOnClickListener(this); cellViewText.setOnClickListener(this); cellViewText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(s.length() > 1){ s = s.subSequence(s.length() - 1, s.length()); cellViewText.clearFocus(); } } @Override public void afterTextChanged(Editable s) { cellViewText.clearFocus(); } }); } public void bindLetter(String c){ bindLetter(c, false); } public void bindLetter(String c, boolean reveal) { if (c == null) return; if (c.equals(".")) { currentCellView = cellViewText; cellViewText.setBackgroundResource(android.R.color.black); } this.letter = c; if(reveal) cellViewText.setText(c); } public void revealLetter() { if (letter != null) { cellViewText.setText("" + letter); } } public void bindHint(Crossword crossword, int number) { if (number != 0) { numberTV.setText("" + number); List<String> acrosses = crossword.getClues().getAcross(); this.acrossHint = getHint(number, acrosses); List<String> downs = crossword.getClues().getDown(); this.downHint = getHint(number, downs); } } private String getHint(int number, List<String> acrossOrDown) { for (String hint : acrossOrDown) { if (number == getNumber(hint)) { return hint; } } return null; } private int getNumber(String hint) { int idx = hint.indexOf("."); String num = ""; for (int i = 0; i < idx; i++) { num += hint.charAt(i); } return Integer.parseInt(num); } public void bindCell(Cell cell) { if(cell == null) return; this.cell = cell; if(cell.isSelected()){ cellViewText.setBackgroundResource(R.drawable.blk_border); }else{ restoreBackgroundColor(); } if(cell.getNumber() != 0) numberTV.setText("" + cell.getNumber()); } public void restoreBackgroundColor() { cellViewText.setBackgroundResource(android.R.color.transparent); } @Override public void onClick(View v) { cellViewText.setBackgroundResource(R.color.yellow); } }
Java
UTF-8
1,199
2.609375
3
[]
no_license
package ru.anr.base.tests.multithreading; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.test.context.ContextConfiguration; import ru.anr.base.ApplicationException; import ru.anr.base.tests.BaseTestCase; import java.util.Set; /** * Description ... * * @author Alexey Romanchuk * @created Jul 3, 2015 */ @ContextConfiguration(classes = ThreadExecutorTest.class) public class ThreadExecutorTest extends BaseTestCase { /** * Test for 2 threads */ @Test public void test() { ThreadExecutor exec = new ThreadExecutor(); exec.add(new ThreadJob(x -> { // do nothing sleep(20); })); exec.add(new ThreadJob(x -> { throw new ApplicationException("Message"); })); // Let's start ... exec.start(); Assertions.assertFalse(exec.waitNoErrors()); // Must be an error Assertions.assertTrue(exec.isError()); Set<ThreadJob> jobs = exec.getJobs(); Assertions.assertEquals("Message", jobs.stream() .filter(j -> j.getError() != null) .findFirst().orElseThrow().getError()); } }
Java
UTF-8
1,341
2.390625
2
[]
no_license
package com.wb.springcloud.fallback; import com.wb.springcloud.entities.Dept; import com.wb.springcloud.service.DeptClientService; import feign.hystrix.FallbackFactory; import org.springframework.stereotype.Component; import java.util.Arrays; import java.util.List; /** * 自定义针对DeptClientService所有的方法的服务降级 * 需要实现FallbackFactory接口。 * 指定泛型为需要降级的接口 * 需要将该组件加入容器中 */ @Component public class DeptFallbackFactory implements FallbackFactory<DeptClientService> { @Override public DeptClientService create(Throwable throwable) { return new DeptClientService() { @Override public Dept get(Long id) { return new Dept() .setDeptno(id) .setDname("服务降级[id: " + id + "对应的信息不存在!]") .setDb_source("No DataSource Exists!"); } @Override public List<Dept> list() { return Arrays.asList(new Dept() .setDeptno((long) -1) .setDname("no list") .setDb_source("no data")); } @Override public boolean add(Dept dept) { return false; } }; } }
PHP
UTF-8
1,102
2.96875
3
[]
no_license
<?php // print_r($_FILES); /* 把上传回来的文件,保存到服务端 */ // 获取上传回来的文件 $file = $_FILES['file']; // 生成一个不会重复的文件名 /* 我们在服务端,为了保证上传的文件名不会同名 时间戳 + 随机数 + 后缀名 */ // 先得到文件的后缀名 // strrchr(字符串,符号) 得到的是某个符号最后一次出现在字符串的位置开始到字符串结尾的所有字符 $ext = strrchr($file['name'],"."); $fileName = time() . rand(10000,99999) . $ext; // 把文件保存到指定的目录 $bool = move_uploaded_file($file['tmp_name'],"../../static/uploads/" . $fileName); // 如果图片上传成功,返回图片的路径,让前端页面可以预览 $response = ['code'=>0,'msg'=>"操作失败"]; if($bool){ $response['code'] = 1; $response['msg'] = '操作成功'; // 把上传的图片的路径带回前端 $response['src'] = '/static/uploads/' . $fileName; } // 以json格式返回 header("content-type: application/json"); echo json_encode($response); ?>
Python
UTF-8
877
3.5625
4
[]
no_license
#Take in list of points, returns left and right most points from list import numpy as np def getLR(approx): try: L = approx[0][0][0] R = approx[0][0][0] lp = approx[0][0] rp = approx[0][0] point = None print ("[getLR.py]: Showing iterative data:") for i in range(1,len(approx)): point = [approx[i][0][0], approx[i][0][1]] if point[0] < L: L = point[0] lp = point if point[0] > R: R = point[0] rp = point print (" point = %s | L = %s | R = %s | lp = %s | rp = %s" % (point, L, R, lp, rp)) print ("[getLR.py]: Successfully returned points") return lp, rp except: print ("[getLR.py]: No points found!") return None, None
C#
UTF-8
2,458
2.9375
3
[ "MIT" ]
permissive
using System; using System.Diagnostics; namespace N8Engine { internal static class GameLoop { public static event Action<float> OnPreUpdate; public static event Action<float> OnEarlyUpdate; public static event Action<float> OnUpdate; public static event Action<float> OnPostUpdate; public static event Action<float> OnPhysicsUpdate; public static event Action<float> OnLateUpdate; public static event Action OnPreRender; public static event Action OnRender; public static event Action OnPostRender; public static int TargetFramerate { get; set; } = 48; public static int FramesPerSecond { get; private set; } private static float UpdateRate => 1f / TargetFramerate; public static void Run(Action onNextFrameCallback) { const float milliseconds_to_seconds = 1000f; const float one_second = 1f; var frames = 0; var timer = 0f; var previousTimeInMilliseconds = 0.0; var stopwatch = new Stopwatch(); stopwatch.Start(); while (true) { var currentTimeInMilliseconds = stopwatch.ElapsedMilliseconds; var timePassed = (float) (currentTimeInMilliseconds - previousTimeInMilliseconds) / milliseconds_to_seconds; if (timePassed >= UpdateRate) { frames++; timer += timePassed; if (timer >= one_second) { onNextFrameCallback?.Invoke(); FramesPerSecond = frames; frames = 0; timer = 0f; } previousTimeInMilliseconds = currentTimeInMilliseconds; InvokeEventsForCurrentFrame(timePassed); } } } private static void InvokeEventsForCurrentFrame(float deltaTime) { OnPreUpdate?.Invoke(deltaTime); OnEarlyUpdate?.Invoke(deltaTime); OnUpdate?.Invoke(deltaTime); OnPostUpdate?.Invoke(deltaTime); OnPhysicsUpdate?.Invoke(deltaTime); OnLateUpdate?.Invoke(deltaTime); OnPreRender?.Invoke(); OnRender?.Invoke(); OnPostRender?.Invoke(); } } }
JavaScript
UTF-8
6,104
2.796875
3
[]
no_license
//let targetFcts = require('./targetFunctions.js') let ExtractTargetColorsWorker = require("./workers/extractTargetColors.w.js") class Target { constructor(imageSrcData, callback, initialNumColRow, progressCallback, globalParams) { this.ready = false this.imageSrcData = imageSrcData this.imageElement = new Image() this.maxImgLongSide = 600 this.width = -1 // Size of loaded image after resizing (maximglongside * ...) this.height = -1 this.actualWidth = -1 // Actual width of target image used for tiles this.actualHeight = -1 this.defaultNumColRow = 50 this.numColRow = initialNumColRow ? initialNumColRow : this.defaultNumColRow this.numCol = 0 this.numRow = 0 this.tileSize = 0 this.pixSampling = 2 this.matchSize = 4 this.colorData = [] this.params = globalParams this.edgeImage = undefined this.canvas = document.createElement('canvas') this.context = this.canvas.getContext('2d') this.imageElement.onload = () => { console.log('img loaded') this.width = this.imageElement.width this.height = this.imageElement.height if (this.width > this.maxImgLongSide || this.height > this.maxImgLongSide) { if (this.width > this.height) { let ratio = this.height / this.width this.width = this.maxImgLongSide this.height = Math.ceil(this.maxImgLongSide * ratio) } else { let ratio = this.width / this.height this.width = Math.ceil(this.maxImgLongSide * ratio) this.height = this.maxImgLongSide } } this.canvas.width = this.width this.canvas.height = this.height this.context.drawImage(this.imageElement, 0, 0, this.width, this.height) this.changeNumColRow(this.numColRow, progressCallback).then( () => callback()) } //console.log(imageSrcData) this.imageElement.src = imageSrcData } changeNumColRow(ncr, progressCallback) { return new Promise( (resolve, reject) => { this.setNumColRow(ncr) let pixels = this.context.getImageData(0, 0, this.actualWidth, this.actualHeight) let worker = new ExtractTargetColorsWorker() worker.postMessage({cmd: 'start', pixels : pixels, numCol : this.numCol, numRow : this.numRow, tileSize : this.tileSize, matchSize : this.matchSize, pixSampling : this.pixSampling}) worker.addEventListener("message", (event) => { if (event.data.type === 'progress') { progressCallback(event.data.percent) } else if (event.data.type === 'result') { this.colorData = event.data.data worker.postMessage({cmd: 'edges', pixels : pixels, width: this.width, height: this.height, edgesFactor: this.params.edgesFactor}) //this.ready = true //resolve() } else if (event.data.type === 'edge_result') { let imgData = event.data.data // Create fucking tmp canvas instead of using THIS let tmpcanvas = document.createElement('canvas') tmpcanvas.width = this.actualWidth tmpcanvas.height = this.actualHeight tmpcanvas.getContext('2d').putImageData(imgData, 0, 0) let tempimg = new Image() tempimg.src = tmpcanvas.toDataURL("image/png") //document.body.appendChild(tempimg) this.edgeImage = tempimg this.ready = true resolve() } }) }) } setNumColRow(ncr) { this.numColRow = ncr this.numCol = this.width > this.height ? this.numColRow : Math.round(this.numColRow * (this.width / this.height)) this.numRow = this.width <= this.height ? this.numColRow : Math.round(this.numColRow * (this.height / this.width)) const longSide = this.width > this.height ? this.width : this.height this.tileSize = Math.floor(longSide / this.numColRow) this.actualWidth = this.tileSize * this.numCol this.actualHeight = this.tileSize * this.numRow this.colorData = new Array(this.numCol * this.numRow) console.log(`Target initial(${this.width}, ${this.height}) actual(${this.actualWidth}, ${this.actualHeight})`) } extractColorInfo() { for (var i=0; i<this.numCol; i++) { for (var j=0; j<this.numRow; j++) { this.colorData[i + j*this.numCol] = this.extractTile(i,j) } } console.log('Extracted ' + this.colorData.length + ' regions from target image') } extractTile(i,j) { let colors = [] const subsize = Math.round(this.tileSize / this.matchSize) const x = i * this.tileSize const y = j * this.tileSize let avgrgb = {r:0,g:0,b:0} let count = 0 for (var dx=0; dx<this.matchSize; dx++) { for (var dy=0; dy<this.matchSize; dy++) { const c = this.extractRegion( x + (dx*subsize),y + (dy * subsize),subsize) if (c !== 0) { colors.push(c) avgrgb.r += c.r avgrgb.g += c.g avgrgb.b += c.b count++ } } } // Averaging avgrgb.r = ~~(avgrgb.r/count) avgrgb.g = ~~(avgrgb.g/count) avgrgb.b = ~~(avgrgb.b/count) let res = {nbsub:this.matchSize*this.matchSize, avg: avgrgb, colors: colors} return res } extractRegion(x,y, subsize) { let data = this.context.getImageData(x, y, subsize, subsize) let rgb = {r:0,g:0,b:0} let count = 0 const length = data.data.length; let ii = this.pixSampling * 4 while ( ii < length ) { ++count rgb.r += data.data[ii] rgb.g += data.data[ii+1] rgb.b += data.data[ii+2] ii += this.pixSampling * 4 } // Averaging rgb.r = ~~(rgb.r/count) rgb.g = ~~(rgb.g/count) rgb.b = ~~(rgb.b/count) //if (rgb.r === 0 && rgb.g === 0 && rgb.b === 0) console.error('Problem in region (' + x + ',' + y + ') of size ' + subsize) return rgb } } export default Target
Ruby
UTF-8
1,053
2.8125
3
[]
no_license
module GradesHelper def display_assessment_items(course) if params[:action] == "edit" course.assessment_items.pluck(:name, :id) else [] end end def display_courses(user) if params[:action] == "edit" user.courses.pluck(:name, :id) else [] end end def compute_overall_grade #E.g. given three assessments Midterm 25%, Project 35%, Final Exam # 40% and respective grades 80, 70, 90 the overall computed grade is # the weighted average 0.25×80 + 0.35×70 + 0.40×90 = 80.5 grades = current_user.grades.group_by { |grade| grade.course_id } response = "<ul class='list-group list-group-flush'>" grades.each do | key, values| total = 0.0 values.each do |g| assessment_item_weight = g.assessment_item.weight score = g.score total += assessment_item_weight * score end response += "<li class='list-group-item'> #{values[0].course.name.capitalize}: #{total} </li>" end response += "</ul>" response.html_safe end end
Markdown
UTF-8
1,487
4.09375
4
[]
no_license
------ Created by Michael R. Year : 2021 - 20/02/2021 Personal learning courses ------ ## My solution ```javascript let dog = { name: "Spot", numLegs: 4, sayLegs: function() {return "This dog has " + this.numLegs + " legs.";} }; dog.sayLegs(); ``` --- ## Problem Make Code More Reusable with the this Keyword The last challenge introduced a method to the duck object. It used duck.name dot notation to access the value for the name property within the return statement: sayName: function() {return "The name of this duck is " + duck.name + ".";} While this is a valid way to access the object's property, there is a pitfall here. If the variable name changes, any code referencing the original name would need to be updated as well. In a short object definition, it isn't a problem, but if an object has many references to its properties there is a greater chance for error. A way to avoid these issues is with the this keyword: ``` let duck = { name: "Aflac", numLegs: 2, sayName: function() {return "The name of this duck is " + this.name + ".";} }; ``` this is a deep topic, and the above example is only one way to use it. In the current context, this refers to the object that the method is associated with: duck. If the object's name is changed to mallard, it is not necessary to find all the references to duck in the code. It makes the code reusable and easier to read. Modify the dog.sayLegs method to remove any references to dog. Use the duck example for guidance.
Python
UTF-8
4,027
2.8125
3
[]
no_license
import matplotlib.pyplot as plt from matplotlib import figure import numpy as np from sklearn.manifold import TSNE def seedsdataset(): X=[] Y=[] with open("seeds_dataset.txt","r") as f: for lines in f: lines=lines.replace("\n","") values=lines.split("\t") Y.append(int(values[-1])) temp=[] for i in range(len(values)-1): try: temp.append(float(values[i])) except: pass X.append(temp) X_embedded = TSNE(n_components=2).fit_transform(X) plt.title("seeds dataset") plt.scatter(X_embedded[:,0],X_embedded[:,1] , c=Y) #plt.colorbar(ticks=range(10)) #plt.clim(-0.5, 9.5) #plt.savefig(args.plots_save_dir) plt.show() def vertribalcolumn(): X=[] Y=[] with open("column_3C.dat","r") as f: for lines in f: lines=lines.replace("\n","") values=lines.split(" ") Y.append((values[-1])) temp=[] for i in range(len(values)-1): try: temp.append(float(values[i])) except: pass X.append(temp) label=[] for i in Y: if i=='DH': label.append(1) elif i =='SL': label.append(2) else: label.append(3) X_embedded = TSNE(n_components=2).fit_transform(X) #print X_embedded plt.title("vertebral column") plt.scatter(X_embedded[:,0],X_embedded[:,1] , c=label) #plt.colorbar(ticks=range(10)) #plt.clim(-0.5, 9.5) #plt.savefig(args.plots_save_dir) plt.show() def segmentationdata(): X=[] Y=[] with open("segmentation.data","r") as f: for lines in f: lines=lines.replace("\n","") values=lines.split(",") Y.append((values[:1])) temp=[] for i in range(1,len(values)): try: temp.append(float(values[i])) except: pass X.append(temp) #print Y label=[] for i in Y: if i==['BRICKFACE']: label.append(1) elif i ==['SKY']: label.append(2) elif i==['FOLIAGE']: label.append(3) elif i==['CEMENT']: label.append(4) elif i==['WINDOW']: label.append(5) elif i==['PATH']: label.append(6) else: label.append(7) X_embedded = TSNE(n_components=2).fit_transform(X) #print label #print X_embedded plt.title("segmentation data") plt.scatter(X_embedded[:,0],X_embedded[:,1] , c=label) #plt.colorbar(ticks=range(10)) #plt.clim(-0.5, 9.5) #plt.savefig(args.plots_save_dir) plt.show() def irisdata(): X=[] Y=[] with open("iris.data","r") as f: for lines in f: lines=lines.replace("\n","") values=lines.split(",") Y.append((values[-1])) temp=[] for i in range(len(values)-1): try: temp.append(float(values[i])) except: pass X.append(temp) #print Y label=[] for i in Y: if i=='Iris-setosa': label.append(1) elif i =='Iris-versicolor': label.append(2) elif i=='Iris-virginica': label.append(3) X_embedded = TSNE(n_components=2).fit_transform(X) #print label #print X_embedded plt.title("iris data") plt.scatter(X_embedded[:,0],X_embedded[:,1] , c=label) #plt.colorbar(ticks=range(10)) #plt.clim(-0.5, 9.5) #plt.savefig(args.plots_save_dir) plt.show() #seedsdataset() #vertribalcolumn() #segmentationdata() irisdata()
PHP
UTF-8
3,131
2.8125
3
[]
no_license
<?php namespace Salesfire; use Salesfire\Types\Transaction; use Salesfire\Types\Product; class Formatter { /** * @var array The site identifier */ public $uuid; /** * @var array The events to format */ public $events = array(); /** * @param string The site identifier * @return \Salesfire\Formatter */ public function __construct($uuid) { $this->uuid = $uuid; return $this; } /** * @return string */ public function getUuid() { return $this->uuid; } /** * @param string $platform * @return \Salesfire\Formatter */ public function addPlatform($platform) { if (! isset($this->events['salesfire'])) { $this->events['salesfire'] = array(); } $this->events['salesfire']['platform'] = $platform; return $this; } /** * @param \Salesfire\Types\Transaction $transaction * @return \Salesfire\Formatter */ public function addTransaction(Transaction $transaction) { if (! isset($this->events['ecommerce'])) { $this->events['ecommerce'] = array(); } $this->events['ecommerce']['purchase'] = $transaction->toArray(); return $this; } /** * @param \Salesfire\Types\Product $product * @return \Salesfire\Formatter */ public function addProductView(Product $product) { if (! isset($this->events['ecommerce'])) { $this->events['ecommerce'] = array(); } $this->events['ecommerce']['view'] = $product->toArray(); return $this; } /** * @param \Salesfire\Types\Product $product * @return \Salesfire\Formatter */ public function addBasketAdd(Product $product) { if (! isset($this->events['ecommerce'])) { $this->events['ecommerce'] = array(); } $this->events['ecommerce']['add'] = $product->toArray(); return $this; } /** * @param \Salesfire\Types\Product $product * @return \Salesfire\Formatter */ public function addBasketRemove(Product $product) { if (! isset($this->events['ecommerce'])) { $this->events['ecommerce'] = array(); } $this->events['ecommerce']['remove'] = $product->toArray(); return $this; } public function __toArray() { return $this->events; } /** * @return string */ public function toJson() { return json_encode($this->events, JSON_PRETTY_PRINT); } /** * @return string */ public function toScriptTag() { $script = ''; if (! empty($this->events)) { $script .= "<script>\n"; $script .= "sfDataLayer = window.sfDataLayer || [];\n"; $script .= "sfDataLayer.push(" . $this->toJson() . ");\n"; $script .= "</script>\n"; } $script .= "<script async src='https://cdn.salesfire.co.uk/code/" . $this->getUuid() . ".js'></script>\n"; return $script; } }
JavaScript
UTF-8
763
2.609375
3
[]
no_license
/** * Created by QiHan Wang on 2017/5/27. */ // SearchParams 查询段转为object /*function searchs(search) { let obj = {}; const params = (search.split('?')[1]).split('&'); for (let i = 0; i < params.length; i++) { let param = params[i].split('='); obj[param[0]] = decodeURIComponent(param[1]); } return obj; }*/ function searchs(url) { return url.match(/([^?=&]+)(=([^&]*))/g).reduce((a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {}) } // 根据名称获取查询字段值 function searchName(attr, search) { let match = new RegExp(`[?&]${attr}=([^&]*)`).exec(search || window.location.href); return match && decodeURIComponent(match[1].replace(/\+/g, ' ')); } export default { searchs, searchName }
Python
UTF-8
1,509
3.234375
3
[]
no_license
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @Time : 2018-11-13 21:20 @Author : jianjun.wang @Email : alanwang6584@gmail.com """ import numpy as np import cv2 as cv img = np.zeros((320, 320, 3), np.uint8) #生成一个空灰度图像 print img.shape # 输出:(320, 320, 3) # 绘制一个红色椭圆 ptCenter = (160, 160) # 中心点位置 axesSize = (100, 45) # 长轴半径为 90,短轴半径为 60 rotateAngle = 90 # 旋转角度为 90 startAngle = 0 endAngle = 360 point_color = (0, 0, 255) # BGR thickness = 1 lineType = 4 cv.ellipse(img, ptCenter, axesSize, rotateAngle, startAngle, endAngle, point_color, thickness, lineType) # 绘制一个绿色椭圆 ptCenter = (160, 160) # 中心点位置 axesSize = (90, 60) # 长轴半径为 90,短轴半径为 60 rotateAngle = 0 # 旋转角度为 0 startAngle = 0 endAngle = 360 point_color = (0, 255, 0) # BGR thickness = 1 lineType = 4 cv.ellipse(img, ptCenter, axesSize, rotateAngle, startAngle, endAngle, point_color, thickness, lineType) # 绘制一个蓝色上半椭圆 ptCenter = (160, 60) # 中心点位置 axesSize = (100, 45) # 长轴半径为 90,短轴半径为 60 rotateAngle = 0 # 旋转角度为 90 startAngle = 180 endAngle = 360 point_color = (255, 0, 0) # BGR thickness = 1 lineType = 4 cv.ellipse(img, ptCenter, axesSize, rotateAngle, startAngle, endAngle, point_color, thickness, lineType) cv.namedWindow("AlanWang") cv.imshow('AlanWang', img) cv.waitKey (10000) # 显示 10000 ms 即 10s 后消失 cv.destroyAllWindows()
Python
UTF-8
541
2.546875
3
[]
no_license
import os from pymongo import MongoClient import urllib class MongoDriver: def __init__(self): with open(os.environ['MONGO_USERNAME'], 'r') as user_secret: self.mongo_username = user_secret.read().strip() with open(os.environ['MONGO_PASSWORD'], 'r') as pass_secret: self.mongo_password = pass_secret.read().strip() def db_connection(self): client = MongoClient('mongodb://%s:%s@speedtest-db/speedtest' % (self.mongo_username, self.mongo_password)) return client
Java
UTF-8
1,211
2.4375
2
[]
no_license
package com.example.nitin.desichain.Contents; import java.io.Serializable; /** * Created by ashis on 6/20/2017. */ public class ProductHorizontal implements Serializable { private String mProductName,mProductNoOfReviews,mProductRating; private String mProductImageId; int DISCOUNT; int mProductCost; public int getDISCOUNT() { return DISCOUNT; } public ProductHorizontal(String mProductName, int mProductCost, String mProductImageId, String mProductNoOfReviews, String mProductRating, int DISCOUNT) { this.mProductName = mProductName; this.mProductCost = mProductCost; this.mProductImageId = mProductImageId; this.mProductNoOfReviews = mProductNoOfReviews; this.mProductRating = mProductRating; this.DISCOUNT=DISCOUNT; } public String getmProductName() { return mProductName; } public int getmProductCost() { return mProductCost; } public String getmProductImageId() { return mProductImageId; } public String getmProductNoOfReviews() { return mProductNoOfReviews; } public String getmProductRating() { return mProductRating; } }
JavaScript
UTF-8
872
3
3
[]
no_license
const personnel = [ { id: 5, name: 'Brian Mason', pilotingScore: 100, shootingScore: 36, isDeltaPilot: true }, { id: 82, name: 'Pauline Saunders', pilotingScore: 83, shootingScore: 91, isDeltaPilot: false }, { id: 22, name: 'Carry Beaman', pilotingScore: 34, shootingScore: 150, isDeltaPilot: false }, { id: 15, name: 'Frank Johnson', pilotingScore: 23, shootingScore: 201, isDeltaPilot: true }, { id: 11, name: 'Caleb Dume', pilotingScore: 71, shootingScore: 85, isDeltaPilot: true } ]; //Get the combined total scores (both piloting and shooting together) of all Delta Pilots. const totalJediScore = personnel .filter(person => person.isDeltaPilot) .map(jedi => jedi.pilotingScore + jedi.shootingScore) .reduce((acc, score) => acc + score, 0); console.log(totalJediScore);
Markdown
UTF-8
1,414
2.671875
3
[]
no_license
--- name: "Walnut and Flax Seed Trail Mix Recipe With Figs and Honey" slug: "walnut-and-flax-seed-trail-mix-recipe-with-figs-and-honey" layout: 'RecipeLayout' prepTime: "25" cuisine: "Continental" cuisineSlug: "continental" image: "https://www.archanaskitchen.com/images/archanaskitchen/1-Author/Shyma_Menon/Walnut_and_Flax_Seeds_Trail_Mix_Recipe_With_Figs_and_Honey-3_1600.jpg" excerpt: "To begin making the Walnut and Flax Seed Trail Mix Recipe With Figs Honey, in a mixing bowl, combine the walnuts, figs, flax seeds, honey, roasted peanuts and the cinnamon powder" --- ### Ingredients - 1/3 cup Flax seeds. - 1 cup Dried Figs. - 1 cup Walnuts. - 1 teaspoon Cinnamon Powder (Dalchini). - 1/3 cup Honey. - 1/2 cup Roasted Peanuts (Moongphali). ### Instructions 1. To begin making the Walnut and Flax Seed Trail Mix Recipe With Figs & Honey, in a mixing bowl, combine the walnuts, figs, flax seeds, honey, roasted peanuts and the cinnamon powder. 1. Preheat an oven to 190 degree celsius. 1. Transfer the Walnut and Flax Seed Trail Mix onto a baking tray and bake for 12 to 15 minutes until they are crisp. 1. Remove the tray from the oven. 1. Allow the Walnut and Flax Seed Trail Mix to cool and transfer to an airtight jar and store. 1. Serve Walnut and Flax Seed Trail Mix Recipe With Figs & Honey along with Watermelon Smoothie Recipe as an after school snack for your kids.
Java
UTF-8
3,436
2.015625
2
[ "Apache-2.0" ]
permissive
/*Copyright ©2016 TommyLemon(https://github.com/TommyLemon/APIJSON) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ package apijson.framework; import java.util.Arrays; import java.util.List; import apijson.JSONResponse; import apijson.orm.JSONRequest; import apijson.orm.Visitor; import apijson.orm.model.Access; import apijson.orm.model.Column; import apijson.orm.model.Document; import apijson.orm.model.ExtendedProperty; import apijson.orm.model.Function; import apijson.orm.model.PgAttribute; import apijson.orm.model.PgClass; import apijson.orm.model.Request; import apijson.orm.model.Script; import apijson.orm.model.SysColumn; import apijson.orm.model.SysTable; import apijson.orm.model.Table; import apijson.orm.model.TestRecord; /**APIJSON 常量类 * @author Lemon */ public class APIJSONConstant { public static String KEY_DEBUG = "debug"; public static final String DEFAULTS = "defaults"; public static final String USER_ = "User"; public static final String PRIVACY_ = "Privacy"; public static final String VISITOR_ID = "visitorId"; public static final String ID = JSONRequest.KEY_ID; public static final String USER_ID = JSONRequest.KEY_USER_ID; public static final String TAG = JSONRequest.KEY_TAG; public static final String VERSION = JSONRequest.KEY_VERSION; public static final String FORMAT = JSONRequest.KEY_FORMAT; public static final String CODE = JSONResponse.KEY_CODE; public static final String MSG = JSONResponse.KEY_MSG; public static final String COUNT = JSONResponse.KEY_COUNT; public static final String TOTAL = JSONResponse.KEY_TOTAL; public static final String ACCESS_; public static final String COLUMN_; public static final String DOCUMENT_; public static final String EXTENDED_PROPERTY_; public static final String FUNCTION_; public static final String SCRIPT_; public static final String PG_ATTRIBUTE_; public static final String PG_CLASS_; public static final String REQUEST_; public static final String SYS_COLUMN_; public static final String SYS_TABLE_; public static final String TABLE_; public static final String TEST_RECORD_; public static final String VISITOR_; public static final List<String> METHODS; static { ACCESS_ = Access.class.getSimpleName(); COLUMN_ = Column.class.getSimpleName(); DOCUMENT_ = Document.class.getSimpleName(); EXTENDED_PROPERTY_ = ExtendedProperty.class.getSimpleName(); FUNCTION_ = Function.class.getSimpleName(); SCRIPT_ = Script.class.getSimpleName(); PG_ATTRIBUTE_ = PgAttribute.class.getSimpleName(); PG_CLASS_ = PgClass.class.getSimpleName(); REQUEST_ = Request.class.getSimpleName(); SYS_COLUMN_ = SysColumn.class.getSimpleName(); SYS_TABLE_ = SysTable.class.getSimpleName(); TABLE_ = Table.class.getSimpleName(); TEST_RECORD_ = TestRecord.class.getSimpleName(); VISITOR_ = Visitor.class.getSimpleName(); METHODS = Arrays.asList("get", "head", "gets", "heads", "post", "put", "delete"); } }
C++
UTF-8
1,309
2.734375
3
[]
no_license
class Solution { public: bool isboundary(int x,int y,int n,int m) { if(x>=0 && x<n && y>=0 && y<m) return true; return false; } struct path{ int x,y; }; int shortestPathBinaryMatrix(vector<vector<int>>& grid) { int n=grid.size(),m=grid[0].size(); if(grid[0][0]==1) return -1; queue<pair<path,int>>q; q.push({{0,0},1}); bool visited[n][m]; memset(visited,false,sizeof(visited)); visited[0][0]=true; int val=grid[0][0]; int xdir[]={0,0,1,-1,1,1,-1,-1}; int ydir[]={1,-1,0,0,1,-1,1,-1}; while(!q.empty()) { int x=q.front().first.x; int y=q.front().first.y; int cost=q.front().second; q.pop(); if(x==n-1 && y==m-1) { return cost; } for(int i=0;i<8;i++) { int a=x+xdir[i]; int b=y+ydir[i]; if(isboundary(a,b,n,m) && visited[a][b]==false && grid[a][b]==val) { visited[a][b]=true; q.push({{a,b},cost+1}); } } } return -1; } };
JavaScript
UTF-8
493
2.65625
3
[]
no_license
function openCatalogDesktop() { let $catalogButton = document.querySelector('.catalog-button'); let catalogButtonActive = 'catalog-button--active'; let $catalogDesktop = document.querySelector('.header-catalog'); let catalogDesktopActive = 'header-catalog--active'; $catalogButton.addEventListener('click', () => { $catalogButton.classList.toggle(catalogButtonActive); $catalogDesktop.classList.toggle(catalogDesktopActive); }); } openCatalogDesktop();
Java
UTF-8
1,747
2
2
[]
no_license
package vmc.javafxui.proxies; import java.util.List; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.ResponseEntity; 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.RequestBody; import vmc.javafxui.beans.BuildingCityBean; import vmc.javafxui.beans.BuildingUserBean; import vmc.javafxui.beans.UserBean; @FeignClient (name = "user", url = "localhost:9002") public interface UserProxy { @GetMapping(value = "/user") public List<UserBean> listUsers(); @GetMapping(value = "/building") public List<BuildingUserBean> getAllBuildingUser(); @GetMapping(value = "/user/{id}") public UserBean getOneUser(@PathVariable(name = "id") int id); @GetMapping(value = "/building/{id}") public BuildingUserBean getOneBuildingUserById(@PathVariable("id") int id); @PostMapping(value = "/user") public ResponseEntity<Void> addUser (@RequestBody UserBean user); @PostMapping(value = "/building") public BuildingUserBean addBuildingUser(@RequestBody BuildingUserBean buildingUser); @PutMapping(value = "/user") public UserBean updateUser(@RequestBody UserBean user); @PutMapping(value = "/building") public BuildingUserBean updateBuildingUser(@RequestBody BuildingUserBean buildingUser); @DeleteMapping(value = "/user/{id}") public void removeUser(@PathVariable(name = "id") int id); @DeleteMapping(value = "/building/{id}") public void removeBuildingUser(@PathVariable("id") int id); }
Java
UTF-8
595
1.820313
2
[ "MIT" ]
permissive
package ru.xander.etl.graph.graph.xml; import lombok.Getter; import lombok.Setter; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.util.List; /** * @author Alexander Shakhov */ @Getter @Setter @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GraphParametersType", propOrder = {"graphParameterList"}) public class GraphParameters { @XmlElement(name = "GraphParameter", required = true) private List<GraphParameter> graphParameterList; }
PHP
UTF-8
1,093
2.765625
3
[]
no_license
<?php declare(strict_types = 1); namespace App\Repositories\Resources\Users; use App\Exceptions\NotFoundInRepositoryException; use App\Repositories\Resources\DatabaseResourceRepository; use App\Resources\User; /** * Class DatabaseUsersRepository * @package App\Repositories\Resources\Users */ class DatabaseUsersRepository extends DatabaseResourceRepository implements UsersRepositoryInterface { /** * @var string */ protected static $table = 'users'; /** * @param int $provider * @param int $providerId * * @return User * @throws NotFoundInRepositoryException * @throws \InvalidArgumentException */ public function getByProviderId($provider, $providerId) { $data = $this->connection ->table(static::$table) ->where('provider', $provider) ->where('provider_id', $providerId) ->first(); if (null === $data) { throw new NotFoundInRepositoryException('User not found'); } return $this->hydrator->hydrate((array)$data); } }
Python
UTF-8
720
2.859375
3
[]
no_license
import urllib.request import urllib.parse from urllib.error import URLError,HTTPError url='https://api.weibo.com/oauth2/access_token' values={'client_id':'339837652', #key 'client_secret':'92299b8986fbc70e2c67d5f14075a3bc',#secret 'grant_type':'authorization_code', 'redirect_uri':'www.baidu.com',#回执网页 'code':'1ecb3d82b39ead686dc8d842e44da491'}#回执代码 url_values=urllib.parse.urlencode(values) print(url_values) url_values=url_values.encode(encoding='UTF8') full_url=urllib.request.Request(url,url_values) try: response=urllib.request.urlopen(full_url) print(response.read()) except HTTPError as e: print('Error code:',e.code) except URLError as e: print('Reason',e.reason)
Java
UTF-8
569
1.96875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates.commands.rollers; import edu.wpi.first.wpilibj.command.CommandGroup; /** * * @author AtidSpikes */ public class ScoreTubesRollerArm extends CommandGroup { public ScoreTubesRollerArm() { addParallel(new RollRollers()); addSequential(new ArmUp()); addSequential(new ReleaseTubes()); } }
Java
UTF-8
592
3.8125
4
[]
no_license
package com.opps.polymorphism; class ABC15 { void methodABC() { System.out.println(111); } void methodABC(int i) { System.out.println(222); } } class XYZ15 extends ABC15 { @Override void methodABC(int i) { System.out.println(333); } @Override void methodABC() { System.out.println(444); } } public class MainClass15 { public static void main(String[] args) { ABC15 abc = new XYZ15(); abc.methodABC(10); abc.methodABC(); } }
SQL
UTF-8
12,983
3.84375
4
[]
no_license
/* This table describes the properties of a supplier with supplier id, supplier name and zip code for potential distance calculations. */ CREATE TABLE Supplier( sid varchar2(35), sname varchar2(35), zipcode varchar2(6), PRIMARY KEY (sid) ); /* This table describes properties of items throughout the logistic chain, including product id, product name, dimensions, weight, handling instructions, customer rating and complaints filed against it. The supplier's storage quota for its products are also labelled. */ CREATE TABLE Item( pid varchar2(35), pname varchar2(35), length INTEGER, width INTEGER, height INTEGER, weight FLOAT, handling varchar2(35), rating FLOAT, complaint VARCHAR2(35), mfgspaceavai INTEGER, mfgspaceused INTEGER, PRIMARY KEY (pid), CHECK (mfgspaceavai>=0 and mfgspaceused>=0) ); /* This table records contracts signed between a supplier and the retailer for a certain product, including contract id, supplier id, product id, quantity, price and estimated date of delivery. */ CREATE TABLE Contract( cid varchar2(35), sid varchar2(35) NOT NULL, pid varchar2(35) NOT NULL, quantity INTEGER, price FLOAT, deliverdate DATE, PRIMARY KEY (cid), FOREIGN KEY (sid) REFERENCES Supplier, FOREIGN KEY (pid) REFERENCES Item, CHECK (quantity>0) ); /* This table depicts the management of transportation resources, including the ids of vehicle stations, with its location, name of manager, operating hours and phone number. */ CREATE TABLE TranspMgmt( stnid varchar2(35), location varchar2(35), stnmgr varchar2(35), ophour varchar2(35), phone varchar2(35), PRIMARY KEY (stnid) ); /* This table tracks status of vehicle fleets during transportation, including fleet id, station id that the fleet belongs to, the type of vehicle possessed by this fleet, the total number of vehicles and the number of vehicles that are sent out. */ CREATE TABLE Fleet( fid varchar2(35), stnid varchar2(35) NOT NULL, vehicletype varchar2(35), vehiclenum INTEGER, vehiclesent INTEGER, PRIMARY KEY (fid), FOREIGN KEY (stnid) REFERENCES TranspMgmt ON DELETE CASCADE ); /* This table tracks status of labor in terms of squads during transportation, including squad id, station id that the squad belongs to, the type of labor that makes the squad, the total number of labors and the number of labors sent out. */ CREATE TABLE Squad( sqid varchar2(35), stnid varchar2(35) NOT NULL, labortype varchar2(35), labornum INTEGER, laborsent INTEGER, PRIMARY KEY (sqid), FOREIGN KEY (stnid) REFERENCES TranspMgmt ON DELETE CASCADE ); /* This table stores information about a storage site which could be either a warehouse or a retail store, including storage id, its location, the number of employees, name of the manager and phone number.*/ CREATE TABLE Storage( stoid varchar2(35), location varchar2(35), zipcode varchar2(6), numemployee INTEGER, manager varchar2(35), phone varchar2(35), PRIMARY KEY (stoid) ); /* This table records status of a warehouse-type storage site, including storage id, shelf id and description which distinguishes locations for different types of goods stored (e.g. clothes, electronics, referagerated foods etc), the space available for each shelf and the space already used. */ CREATE TABLE Warehouse( stoid varchar2(35), shelfid varchar2(35), shelfdesc varchar2(35), spaceavai INTEGER, spaceused INTEGER, PRIMARY KEY (stoid, shelfid), FOREIGN KEY (stoid) REFERENCES Storage ON DELETE CASCADE, CHECK (spaceavai>=0 and spaceused>=0) ); /* This table records individual retailer information besides those properties listed in the storage table, such as storage id, available and used space in store, and average volume of customers it serves. */ CREATE TABLE Retailer( stoid varchar2(35), spaceavai INTEGER, spaceused INTEGER, customervol INTEGER, PRIMARY KEY (stoid), FOREIGN KEY (stoid) REFERENCES Storage ON DELETE CASCADE, CHECK (spaceavai>=0 and spaceused>=0) ); /* This table keeps record of every transportation from suppliers to warehouses, containing delivery id, supplier id, warehouse storage id, date of delivery and arrival, number of vehicles used and from which fleet, number of labor and the squad they are from, and overall transportation costs. */ CREATE TABLE SupplierDelivery( did varchar2(35), sid varchar2(35), stoid varchar2(35), deliverdate DATE, arrivedate DATE, vehiclenum INTEGER, fid varchar2(35), labornum INTEGER, sqid varchar2(35), cost FLOAT, PRIMARY KEY (did), FOREIGN KEY (sid) REFERENCES Supplier, FOREIGN KEY (stoid) REFERENCES Storage, FOREIGN KEY (fid) REFERENCES Fleet, FOREIGN KEY (sqid) REFERENCES Squad ); /* This table records every transportation that happens between warehouses, containing delivery id, from and to warehouse storage ids, with other fields similar to the previous table. */ CREATE TABLE WarehouseTransit( did varchar2(35), fromstoid varchar2(35), tostoid varchar2(35), deliverdate DATE, arrivedate DATE, vehiclenum INTEGER, fid varchar2(35), labornum INTEGER, sqid varchar2(35), cost FLOAT, PRIMARY KEY (did), FOREIGN KEY (fromstoid) REFERENCES Storage(stoid), FOREIGN KEY (tostoid) REFERENCES Storage(stoid), FOREIGN KEY (fid) REFERENCES Fleet, FOREIGN KEY (sqid) REFERENCES Squad ); /* This table keeps record of transportation from warehouses to retailers, containing delivery id, warehouse storage id, retailer storage id, etc. */ CREATE TABLE WtoR( did varchar2(35), fromstoid varchar2(35), tostoid varchar2(35), deliverdate DATE, arrivedate DATE, vehiclenum INTEGER, fid varchar2(35), labornum INTEGER, sqid varchar2(35), cost FLOAT, PRIMARY KEY (did), FOREIGN KEY (fromstoid) REFERENCES Storage(stoid), FOREIGN KEY (tostoid) REFERENCES Storage(stoid), FOREIGN KEY (fid) REFERENCES Fleet, FOREIGN KEY (sqid) REFERENCES Squad ); /* This table records every transportation that happens between retailer stores. */ CREATE TABLE RetailerTransit( did varchar2(35), fromstoid varchar2(35), tostoid varchar2(35), deliverdate DATE, arrivedate DATE, vehiclenum INTEGER, fid varchar2(35), labornum INTEGER, sqid varchar2(35), cost FLOAT, PRIMARY KEY (did), FOREIGN KEY (fromstoid) REFERENCES Storage(stoid), FOREIGN KEY (tostoid) REFERENCES Storage(stoid), FOREIGN KEY (fid) REFERENCES Fleet, FOREIGN KEY (sqid) REFERENCES Squad ); /* This table depicts the smallest unit of goods that is involved during transportation, having unique bid for each batch of each type of item, with the contract id that is related with delivery of this batch of item, the date of expiration (if applicable), quantity of items in this batch, and current location plus all transportation references. */ CREATE TABLE Batch( bid varchar2(35), pid varchar2(35) NOT NULL, cid varchar2(35) NOT NULL, expiration DATE, quantity INTEGER, stoid varchar2(35), intransit INTEGER, sold INTEGER, did1 VARCHAR(20) NOT NULL, did2 VARCHAR(20), did3 VARCHAR(20), did4 VARCHAR(20), UNIQUE(cid), PRIMARY KEY (bid), FOREIGN KEY (pid) REFERENCES Item, FOREIGN KEY (cid) REFERENCES Contract, FOREIGN KEY (did1) REFERENCES SupplierDelivery(did), FOREIGN KEY (did2) REFERENCES WarehouseTransit(did), FOREIGN KEY (did3) REFERENCES WtoR(did), FOREIGN KEY (did4) REFERENCES RetailerTransit(did), CHECK (intransit=0 or intransit = 1), CHECK (sold=0 or sold = 1), CHECK (quantity>0) ); /* The table stores data about customers who purchase products from retail stores, including name, sex, age, and zip code. */ CREATE TABLE Customer( cuid varchar2(20), name varchar2(35), sex varchar2(6), age INTEGER, zipcode varchar2(6), PRIMARY KEY (cuid), CHECK (sex='M' or sex='F' or sex='U'), CHECK (age>10 and age<100) ); /* This table records each purchase history, including customer id, batch id of the product, date of purchase and quantity. */ CREATE TABLE Purchase( cuid varchar2(20), bid varchar2(35), datepur DATE, quantity INTEGER, PRIMARY KEY (cuid,bid,datepur), FOREIGN KEY (cuid) REFERENCES Customer, FOREIGN KEY (bid) REFERENCES Batch, CHECK (quantity>0) ); /* This table records a product being returned to a retail store due to some complaints, together with customer id, batch id, date and quantity. */ CREATE TABLE Return( cuid varchar2(20), bid varchar2(35), daterec DATE, quantity INTEGER, complaint varchar2(35), stoid varchar2(35), PRIMARY KEY (cuid,bid,daterec), FOREIGN KEY (cuid) REFERENCES Customer, FOREIGN KEY (bid) REFERENCES Batch, FOREIGN KEY (stoid) REFERENCES Retailer, CHECK (quantity>0) ); /* This table records products that are sent to retail store and then to supplier for repairing, including customer id, batch id, date the store received, quantity, problem with the item, date sent to the supplier and the date sent back to the store. */ CREATE TABLE Repair( cuid varchar2(20), bid varchar2(35), daterec DATE, quantity INTEGER, problem varchar2(35) NOT NULL, datetosupplier DATE, dateretrieve DATE, PRIMARY KEY (cuid,bid,daterec), FOREIGN KEY (cuid) REFERENCES Customer, FOREIGN KEY (bid) REFERENCES Batch, CHECK (quantity>0) ); /* This table shows when a product is being recycled from a customer, how the condition of the article leads to different processing decisions and the date of execution. */ CREATE TABLE Recycler( cuid varchar2(20), bid varchar2(35), daterec DATE, quantity INTEGER, condition varchar2(35), decision varchar2(35), execdate DATE, PRIMARY KEY (cuid,bid,daterec), FOREIGN KEY (cuid) REFERENCES Customer, FOREIGN KEY (bid) REFERENCES Batch, CHECK (decision='disassemble' or decision='refurbish' or decision='discard'), CHECK (quantity>0) ); /* THis table shows a list of raw materials and parts provided to a supplier with price, unit dimensions and weight. The table also contains the information on how much space is used and available in the supplier's inventory. */ CREATE TABLE MatlSto( mid varchar2(35), matltype varchar2(35), price FLOAT, length FLOAT, width FLOAT, height FLOAT, weight FLOAT, spaceavai INTEGER, spaceused INTEGER, PRIMARY KEY (mid), CHECK (spaceavai>=0 and spaceused>=0) ); /* This table describes how a product is disassembled into usable raw materials and parts with respective quantities. */ CREATE TABLE Disassemble( pid varchar2(35), mid varchar2(35), quantity FLOAT, PRIMARY KEY (pid,mid), FOREIGN KEY (pid) REFERENCES Item, FOREIGN KEY (mid) REFERENCES MatlSto, CHECK (quantity>0) ); /* This table shows how a supplier manages raw material and parts demands based on product and corresponding contract to determine the amount needed. */ CREATE TABLE MfgPlan( pid varchar2(35), cid varchar2(35), mid varchar2(35), quantity INTEGER, PRIMARY KEY (pid,cid,mid), FOREIGN KEY (pid) REFERENCES Item ON DELETE CASCADE, FOREIGN KEY (cid) REFERENCES Contract ON DELETE CASCADE, FOREIGN KEY (mid) REFERENCES MatlSto, CHECK (quantity>0) ); /* This table summarizes the material demand for a supplier, namely the date and quantity for each type of material or part. */ CREATE TABLE StockPlan( mid varchar2(35), dateneed DATE, quantity INTEGER, PRIMARY KEY (mid,dateneed), FOREIGN KEY (mid) REFERENCES MatlSto ON DELETE CASCADE, CHECK (quantity>0) ); /* This table stores the history of raw material/part delivery to the supplier, including delivery id, material id, quantity, deliver date, arrival date, number of vehicles used and the fleet they belong to, number of labors involved and their squad id, finally the cost of delivery. */ CREATE TABLE StockDelivery ( did varchar2(35), mid varchar2(35), quantity INTEGER, deliverdate DATE, arrivedate DATE, vehiclenum INTEGER, fid varchar2(35), labornum INTEGER, sqid varchar2(35), cost FLOAT, PRIMARY KEY (did), FOREIGN KEY (mid) REFERENCES MatlSto, FOREIGN KEY (fid) REFERENCES Fleet, FOREIGN KEY (sqid) REFERENCES Squad, CHECK (quantity>0) );
Go
UTF-8
7,900
3.1875
3
[ "Apache-2.0" ]
permissive
package pubsub import ( "os" "sync" "time" ) // Subscriber .... type Subscriber interface { OnPublish(interface{}) error } // Topic ... type Topic interface { Publish(interface{}) error Subscribe(Subscriber) error Unsubscribe(Subscriber) error Destroy() error IsEmpty() bool } // MultiTopic ... type MultiTopic interface { Publish(id, value interface{}) error Subscribe(id interface{}, suber Subscriber) error Unsubscribe(id interface{}, suber Subscriber) error Destroy(id interface{}, topic Topic) error DestroyAll() error PublishAll(value interface{}) error Range(f func(id interface{}, topic Topic) bool) Len() int } type TopicManager interface { Get(interface{}) (Topic, bool) GetOrCreate(interface{}) (Topic, error) Delete(interface{}, Topic) Range(func(interface{}, Topic) bool) Len() int Clear() } type SmartTopic interface { Topic Get() Topic } // NewSynctopic : topic realized by sync.Map func NewSyncTopic() Topic { return &syncTopic{} } // TopicMaker ... type TopicMaker func(id interface{}) (Topic, error) type SmartTopicMaker func(interface{}, TopicManager) (Topic, error) // NewTopicManager ... func NewTopicManager(maker SmartTopicMaker) TopicManager { if maker == nil { maker = NewSmartTopicMaker(nil, 0) } return newTopicManager(maker) } // NewMultiTopicWithManager : // if maker == nil, will use the safeTopic // if idleTime < 0, the topic will destroy the topic when which is empty // if idleTime > 0, the topic will check and destroy the topic witch is empty func NewMultiTopic(maker TopicMaker, delayTime time.Duration) MultiTopic { return NewMultiTopicWithManager(NewTopicManager(NewSmartTopicMaker(maker, delayTime))) } func NewMultiTopicWithManager(manager TopicManager) MultiTopic { if manager == nil { manager = NewTopicManager(nil) } return newMultiTopic(manager) } func SyncTopicMaker(id interface{}) (Topic, error) { return NewSyncTopic(), nil } func NewSmartTopic(id interface{}, manager TopicManager, maker TopicMaker, delayTime time.Duration) SmartTopic { if maker == nil { maker = SyncTopicMaker } return newSmartTopic(id, manager, maker, delayTime) } func NewSmartTopicMaker(maker TopicMaker, delayTime time.Duration) SmartTopicMaker { return func(id interface{}, manager TopicManager) (Topic, error) { return NewSmartTopic(id, manager, maker, delayTime), nil } } type syncTopic struct { subers sync.Map } func (p *syncTopic) Publish(v interface{}) (err error) { var e error p.subers.Range(func(key, value interface{}) bool { e = key.(Subscriber).OnPublish(v) if e != nil { err = e } return true }) return nil } func (p *syncTopic) Subscribe(s Subscriber) (err error) { _, ok := p.subers.LoadOrStore(s, struct{}{}) if ok { err = os.ErrExist } return } func (p *syncTopic) Unsubscribe(s Subscriber) (err error) { p.subers.Delete(s) return } func (p *syncTopic) Destroy() error { p.subers = sync.Map{} return nil } func (p *syncTopic) IsEmpty() bool { ok := true p.subers.Range(func(key, value interface{}) bool { ok = false return false }) return ok } type topicManager struct { sync.RWMutex maker SmartTopicMaker topics sync.Map } func newTopicManager(maker SmartTopicMaker) *topicManager { return &topicManager{ maker: maker, } } func (p *topicManager) Get(id interface{}) (topic Topic, ok bool) { v, ok := p.topics.Load(id) if !ok { return } topic = v.(Topic) return } func (p *topicManager) GetOrCreate(id interface{}) (topic Topic, err error) { var ok bool topic, ok = p.Get(id) if ok { return } p.Lock() defer p.Unlock() topic, ok = p.Get(id) if ok { return } topic, err = p.maker(id, p) if err != nil { return } p.topics.Store(id, topic) return } func (p *topicManager) Delete(id interface{}, topic Topic) { p.Lock() old, ok := p.Get(id) if ok && old.(Topic) == topic { p.topics.Delete(id) } p.Unlock() } func (p *topicManager) Range(f func(interface{}, Topic) bool) { p.topics.Range(func(k, v interface{}) bool { return f(k, v.(Topic)) }) } func (p *topicManager) Len() int { n := 0 p.topics.Range(func(k, v interface{}) bool { n++ return true }) return n } func (p *topicManager) Clear() { p.Lock() p.topics = sync.Map{} p.Unlock() } type multiTopic struct { manager TopicManager } func newMultiTopic(manager TopicManager) *multiTopic { return &multiTopic{manager: manager} } func (p *multiTopic) Publish(id, value interface{}) error { topic, ok := p.manager.Get(id) if !ok { return nil } return topic.Publish(value) } func (p *multiTopic) Subscribe(id interface{}, suber Subscriber) error { topic, err := p.manager.GetOrCreate(id) if err != nil { return err } return topic.Subscribe(suber) } func (p *multiTopic) Unsubscribe(id interface{}, suber Subscriber) error { topic, ok := p.manager.Get(id) if !ok { return nil } return topic.Unsubscribe(suber) } func (p *multiTopic) Destroy(id interface{}, topic Topic) error { err := topic.Destroy() p.manager.Delete(id, topic) return err } func (p *multiTopic) Range(f func(interface{}, Topic) bool) { p.manager.Range(f) } func (p *multiTopic) DestroyAll() error { p.manager.Range(func(id interface{}, topic Topic) bool { _ = topic.Destroy() return true }) p.manager.Clear() return nil } func (p *multiTopic) PublishAll(v interface{}) error { p.manager.Range(func(id interface{}, topic Topic) bool { _ = topic.Publish(v) return true }) return nil } func (p *multiTopic) Len() int { return p.manager.Len() } type smartTopic struct { sync.RWMutex topic Topic id interface{} manager TopicManager maker TopicMaker delayTime time.Duration timer *time.Timer destroyed bool } func newSmartTopic( id interface{}, manager TopicManager, maker TopicMaker, delayTime time.Duration) *smartTopic { return &smartTopic{ id: id, manager: manager, maker: maker, delayTime: delayTime, } } func (p *smartTopic) destroy() { if p.destroyed { return } p.destroyed = true p.manager.Delete(p.id, p) if p.topic != nil { _ = p.topic.Destroy() } if p.timer != nil { p.timer.Stop() } } func (p *smartTopic) expire() { if p.delayTime < 0 { return } if p.delayTime == 0 { p.destroy() return } if p.timer != nil { p.timer.Reset(p.delayTime) return } p.timer = time.AfterFunc(p.delayTime, func() { p.Lock() defer p.Unlock() if !p.topic.IsEmpty() { return } p.destroy() }) } func (p *smartTopic) stopExpire() { if p.delayTime <= 0 || p.timer == nil { return } p.timer.Stop() } func (p *smartTopic) Subscribe(suber Subscriber) (err error) { p.Lock() defer p.Unlock() if p.destroyed { tp, e := p.manager.GetOrCreate(p.id) if e != nil { err = e return } err = tp.Subscribe(suber) return } if p.topic == nil { p.topic, err = p.maker(p.id) if err != nil { p.destroy() return } err = p.topic.Subscribe(suber) if err != nil { p.destroy() return } return } err = p.topic.Subscribe(suber) p.stopExpire() return } func (p *smartTopic) Unsubscribe(suber Subscriber) (err error) { p.Lock() defer p.Unlock() if p.topic == nil || p.destroyed { return } err = p.topic.Unsubscribe(suber) if err != nil { return } if !p.topic.IsEmpty() { return } p.expire() return } func (p *smartTopic) Destroy() (err error) { p.Lock() defer p.Unlock() p.destroy() return } func (p *smartTopic) IsEmpty() bool { p.RLock() empty := p.topic == nil || p.topic.IsEmpty() p.RUnlock() return empty } func (p *smartTopic) Publish(v interface{}) (err error) { p.RLock() topic := p.topic destroyed := p.destroyed p.RUnlock() if topic != nil { err = topic.Publish(v) } if destroyed { tp, ok := p.manager.Get(p.id) if !ok { return } _ = tp.Publish(v) } return } func (p *smartTopic) Get() Topic { p.RLock() topic := p.topic p.RUnlock() return topic }
JavaScript
UTF-8
1,495
2.546875
3
[]
no_license
import React from 'react'; import fantasy from '../data/fantasy.json'; import history from '../data/history.json'; import horror from '../data/horror.json'; import romance from '../data/romance.json'; import scifi from '../data/scifi.json'; import {Container, Row, Col} from 'react-bootstrap'; const Books = (props) =>{ console.log('Books', props.category); let currentItem; if(props.category === 'fantasy') currentItem = fantasy; else if(props.category === 'history') currentItem = history; else if(props.category === 'horror') currentItem = horror; else if(props.category === 'romance') currentItem = romance; else if(props.category === 'scifi') currentItem = scifi; console.log('current item: ', currentItem); let imgStyle = { width: '200px', height: '200px', objectFit: 'cover', marginBottom: '3rem', cursor: 'pointer', boxShadow: '4px 4px 20px #444' } return ( <Container fluid> <Row justify-content-center> {currentItem.map((item) => ( <Col xs={10} sm={6} md={4} lg={3} key={item.asin}> <img className="d-block" src={item.img} style={imgStyle} /> </Col> ))} </Row> <br /> <hr /> </Container> ); } export default Books;
Java
UTF-8
2,485
2.828125
3
[]
no_license
package source.mdtn.comm; import source.mdtn.bundle.Bundle; import source.mdtn.server.Server; import source.mdtn.server.Service; /** * Classe che rappresenta un BundleProtocol. */ public class BundleProtocol { /** modalità operativa (0=server, 1=client)*/ private int operativeMode; /** * Costruttore del protocollo. * @param operativeMode modalità operativa da usare. <br>0 = server <br>1 = client */ public BundleProtocol(int operativeMode){ this.operativeMode=operativeMode; } /** * Processa il bundle. * @param toBeProcessed il bundle da processare. * @return un bundle di risposta, oppure null. */ public Bundle processBundle(Bundle toBeProcessed){ if(operativeMode==0){ return serverProcessBundle(toBeProcessed); } else if(operativeMode==1){ return clientProcessBundle(toBeProcessed); } else{ return null; } } /** * Metodo interno che processa il bundle in modalità <b>client</b>. * @param toBeProcessed il bundle da processare. * @return un bundle di risposta. */ private Bundle clientProcessBundle(Bundle toBeProcessed){ //Attualmente, non è necessario nessun process lato client che sia platform-independent. return null; } /** * Metodo interno che processa il bundle in modalità <b>server</b>. * @param toBeProcessed il bundle da processare. * @return un bundle di risposta. */ private Bundle serverProcessBundle(final Bundle toBeProcessed){ //Se è un pacchetto informativo, non serve salvare nulla if(toBeProcessed.getPayload().getType().equals("DISCOVERY")){ //EIDclient=newBundle.getPrimary().getSource(); } //Richiesta di aggiornamento lista else if(toBeProcessed.getPayload().getType().equals("UPDATE_LIST")){ return Service.updateListBundle(toBeProcessed.getPrimary().getSource()); } //Richiesta di eliminazione risorsa else if(toBeProcessed.getPayload().getType().equals("DELETE")){ Service.removeResource(toBeProcessed); //return Service.updateListBundle(toBeProcessed.getPrimary().getSource()); } //Richiesta di download else if(toBeProcessed.getPayload().getType().equals("DOWNLOAD")){ //TODO Thread handle= new Thread(){ public void run(){ Service.uploadFile(toBeProcessed); } }; handle.start(); } else{//Altrimenti, salvataggio persistente del bundle su disco (RFC5050). if(!toBeProcessed.store(Server.getBundlePath()))System.out.println("Errore di storage"); } return null; } }
PHP
UTF-8
1,064
2.9375
3
[]
no_license
<?php /*ouverture de la connexion à la base de données */ $objetPdo = new PDO('mysql:host=localhost;dbname=agenda','root',''); /*Requette d'insertion (sql)*/ $pdoStat = $objetPdo->prepare('INSERT INTO contact VALUES (NULL, :nom, :prenom, :tel, :mel)'); //*on lie chaque marqeur à une valeur */ $pdoStat->bindValue(':nom', $_POST['LastName'], PDO::PARAM_STR); $pdoStat->bindValue(':prenom', $_POST['firstName'], PDO::PARAM_STR); $pdoStat->bindValue(':tel', $_POST['phone'], PDO::PARAM_STR); $pdoStat->bindValue(':mel', $_POST['mail'], PDO::PARAM_STR); //*éxécution de la requete préparée */ $insertIsOk = $pdoStat->execute(); if($insertIsOk){ $message = 'Le contact a été ajouté dans la bdd'; } else{ $message = 'Echech de l\'insertion'; } ?> <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Insertion des contacts</h1> <p><?php echo $message; ?></p> </body> </html>
JavaScript
UTF-8
5,637
2.984375
3
[]
no_license
var Graphics = {}; var layers = new Array(); var checkImagesLoaded = null; var background = new Image(); var guideAnimation = null; var guideSprite = new Image(); Graphics.circleRadius = 10; Graphics.thinLineThickness = 1; Graphics.boldLineThickness = 5; Graphics.lineStrokeStyle = "#cfc"; Graphics.imagesLoaded = false; $(function () { "use strict"; loadImages(); checkImagesLoaded = setInterval(checkImagesLoaded, 1); // prepare layers layers[0] = $("#bg")[0].getContext("2d"); layers[1] = $("#guide")[0].getContext("2d"); layers[2] = $("#game")[0].getContext("2d"); layers[3] = $("#ui")[0].getContext("2d"); }); loadImages = function () { guideSprite = imageLoader.load("Images/guide_sprite.png"); background = imageLoader.load("Images/board.png"); }; checkImagesLoaded = function () { if (imageLoader.loaded === true) { clearInterval(checkImagesLoaded); Graphics.imagesLoaded = true; imagesLoaded(); } }; imagesLoaded = function () { guideAnimation = new Animation(guideSprite, 80, 0); guideAnimation.setFirstFrame(1); guideAnimation.setLastFrame(5); guideAnimation.setSpeed(400); guideAnimation.start(); }; clear = function (context) { "use strict"; context.clearRect(0, 0, context.canvas.width, context.canvas.height); }; Graphics.Circle = function (x, y) { "use strict"; this.x = x; this.y = y; }; Graphics.Line = function (startPoint, endPoint, thickness) { "use strict"; this.startPoint = startPoint; this.endPoint = endPoint; this.thickness = thickness !== undefined ? thickness : Graphics.thinLineThickness; }; Graphics.drawLayerBackground = function () { "use strict"; var context = layers[0]; clear(context); // draw background Graphics.drawBackgroundGradient(); // draw the loading text Graphics.drawLoadingBackgroundText(); // load the background image Graphics.drawBackgroundImage(); }; Graphics.drawAnimations = function () { "use strict"; var context = layers[1]; clear(context); context.drawImage( guideAnimation.getImage(), guideAnimation.getFrameX(), guideAnimation.getFrameY(), 80, 130, 325, 130, 80, 130); }; Graphics.stopAnimations = function() { guideAnimation.stop(); }; Graphics.drawLayerGame = function (lines, circles) { "use strict"; var context = layers[2]; clear(context); // draw all remembered line $.each(lines, function (index, line) { var startPoint = line.startPoint; var endPoint = line.endPoint; var thickness = line.thickness; Graphics.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, thickness); }); // draw all remembered circles $.each(circles, function (index, circle) { Graphics.drawCircle(circle.x, circle.y); }); }; Graphics.drawLayerUi = function (progressPercentage) { "use strict"; var context = layers[3]; clear(context); // draw text Graphics.drawText(progressPercentage); }; Graphics.drawLine = function (x1, y1, x2, y2, thickness) { "use strict"; var context = layers[0]; context.beginPath(); context.moveTo(x1, y1); context.lineTo(x2, y2); context.lineWidth = thickness; context.strokeStyle = Graphics.lineStrokeStyle; context.stroke(); }; Graphics.drawCircle = function (x, y) { "use strict"; var context = layers[0]; // prepare the radial gradients fill style var circleGradient = context.createRadialGradient(x - 3, y - 3, 1, x, y, Graphics.circleRadius); circleGradient.addColorStop(0, "#fff"); circleGradient.addColorStop(1, "#cc0"); context.fillStyle = circleGradient; // draw path context.beginPath(); context.arc(x, y, Graphics.circleRadius, 0, Math.PI * 2, true); context.closePath(); // actually fill the circle context.fill(); }; Graphics.drawText = function (progressPercentage) { "use strict"; var context = layers[0]; // draw the title text context.font = "26px 'WellFleet'"; context.textAlign = "center"; context.fillStyle = "#ffffff"; // draw the level progress text context.textAlign = "left"; context.textBaseline = "bottom"; context.fillText("Puzzle " + progressPercentage + "%", 60, context.canvas.height - 100); }; Graphics.drawBackgroundGradient = function () { "use strict"; var context = layers[0]; // draw gradients background var bgGradient = context.createLinearGradient(0, 0, 0, context.canvas.height); bgGradient.addColorStop(0, "#000000"); bgGradient.addColorStop(1, "#555555"); context.fillStyle = bgGradient; context.fillRect(0, 0, context.canvas.width, context.canvas.height); }; Graphics.drawLoadingBackgroundText = function () { "use strict"; var context = layers[0]; // draw the loading text context.font = "34px 'Rock Salt'"; context.textAlign = "center"; context.fillStyle = "#333333"; context.fillText("loading...", context.canvas.width / 2, context.canvas.height / 2); }; Graphics.drawBackgroundImage = function () { "use strict"; var context = layers[0]; clear(context); context.drawImage(background, 0, 0); }; Graphics.lineIsBold = function (line) { "use strict"; line.thickness = Graphics.boldLineThickness; };
Java
UTF-8
3,059
2.328125
2
[]
no_license
package com.mobike.android_architecture.service; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.support.annotation.Nullable; import android.util.Log; import com.mobike.android_architecture.MainActivity; import com.mobike.android_architecture.R; /** * 我的服务 * Created by yangdehao@xiaoyouzi.com on 2019-05-07 19:21 */ public class MyService extends Service { private static final String TAG = MyService.class.getSimpleName(); public MyBinder myBinder; Handler mHandler = new Handler(); @Override public void onCreate() { super.onCreate(); Log.d(TAG, "MyService onCreate"); myBinder = new MyBinder(); // 创建前台进程 //添加下列代码将后台Service变成前台Service //构建"点击通知后打开MainActivity"的Intent对象 Intent notificationIntent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); //新建Builer对象 Notification.Builder builer = new Notification.Builder(this); builer.setContentTitle("前台服务通知的标题");//设置通知的标题 builer.setContentText("前台服务通知的内容");//设置通知的内容 builer.setSmallIcon(R.mipmap.ic_launcher);//设置通知的图标 builer.setContentIntent(pendingIntent);//设置点击通知后的操作 Notification notification = builer.getNotification();//将Builder对象转变成普通的notification startForeground(1, notification);//让Service变成前台Service,并在系统的状态栏显示出来 } @Override public int onStartCommand(Intent intent, int flags, int startId) { Log.d(TAG, "MyService onStartCommand"); mHandler.sendMessageDelayed(new Message(), 2000); return super.onStartCommand(intent, flags, startId); } @Nullable @Override public IBinder onBind(Intent intent) { Log.d(TAG, "MyService onBind"); if (myBinder == null) { myBinder = new MyBinder(); } return myBinder; } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "MyService onStartCommand"); } @Override public boolean onUnbind(Intent intent) { Log.d(TAG, "MyService onUnbind"); return super.onUnbind(intent); } public class MyBinder extends Binder { public void service_connect_Activity() { Log.d(TAG, "Service关联了Activity,并在Activity执行了Service的方法"); } } // IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() { // @Override // public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { // // } // // // }; }
PHP
UTF-8
3,445
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\modules\work\models; use Yii; /** * This is the model class for table "work_progress". * * @property integer $id * @property integer $work_id * @property integer $physical * @property integer $financial * @property string $dateofprogress * @property string $remarks * @property double $expenditure * * @property Work $work */ class WorkProgress extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'work_progress'; } /** * @inheritdoc */ public function rules() { return [ [['work_id', 'physical', 'financial'], 'integer'], [['dateofprogress'], 'safe'], [['remarks'], 'string'], [['expenditure'], 'number'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'work_id' => Yii::t('app', 'Work'), 'physical' => Yii::t('app', 'Physical'), 'financial' => Yii::t('app', 'Financial'), 'dateofprogress' => Yii::t('app', 'Date of Progress'), 'remarks' => Yii::t('app', 'Remarks'), 'expenditure' => Yii::t('app', 'Expenditure'), ]; } /** * @return \yii\db\ActiveQuery */ public function getWork() { return $this->hasOne(Work::className(), ['id' => 'work_id']); } /* *@return form of individual elements */ public function showForm($form,$attribute) { switch ($attribute) { case 'id': return $form->field($this,$attribute)->textInput(); break; case 'work_id': return $form->field($this,$attribute)->dropDownList(\yii\helpers\ArrayHelper::map(Work::find()->asArray()->all(),"id","name_".Yii::$app->language)); break; case 'physical': return $form->field($this,$attribute)->textInput(); break; case 'financial': return $form->field($this,$attribute)->textInput(); break; case 'dateofprogress': return $form->field($this, "dateofprogress")->widget(\kartik\date\DatePicker::classname(), [ 'options' => ['placeholder' => 'Enter'. $this->attributeLabels()["dateofprogress"]." ..."], 'pluginOptions' => [ 'autoclose'=>true ] ]); break; case 'remarks': return $form->field($this,$attribute)->textInput(); break; case 'expenditure': return $form->field($this,$attribute)->textInput(); break; default: break; } } /* *@return form of individual elements */ public function showValue($attribute) { $name='name_'.Yii::$app->language; switch ($attribute) { case 'id': return $this->id; break; case 'work_id': return Work::findOne($this->work_id)->$name; break; case 'physical': return $this->physical; break; case 'financial': return $this->financial; break; case 'dateofprogress': return $this->dateofprogress; break; case 'remarks': return $this->remarks; break; case 'expenditure': return $this->expenditure; break; default: break; } } }
Markdown
UTF-8
1,063
3.125
3
[ "MIT" ]
permissive
# Basic React Decentralised Application (Hardhat Development environment) ## Contract 1 The 1st contract is a simple *Greeter* contract that is deployed with an initial greeting. Once deployed, the deployed greeting can be seen (without any gas) and it can also be changed/updated which incurs some fee. Here are some screenshots of the first contract functioning: ![Hello Hardhat! was the initial greeting](readme_images/C1P1.jpg) ![Updated a message](readme_images/C1P2.jpg) ![Updated the greeting again](readme_images/C1P3.jpg) ## Contract 2 The 2nd contract is the most basic and ofcourse unsafe implementation of a cryptocurrency. This was written for some Solidity practice and for serious projects, `openzeppelin` ERC 20 standards must be implemented. I've created a token called *Amarendra Bahubali Token* with the symbol *ABHBL* with the total supply of 1 crore tokens (1,00,00,000 ABHBL). Here are some screenshots of the second contract functioning: ![Getting self balance](readme_images/C2P1.jpg) ![Transfering 50 lakh Tokens](readme_images/C2P2.jpg)
Java
UTF-8
7,703
1.765625
2
[]
no_license
package org.sistcoop.cooperativa.services.resources.admin; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateless; import javax.inject.Inject; import javax.ws.rs.PathParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.sistcoop.cooperativa.admin.client.resource.TransaccionEntidadBovedaResource; import org.sistcoop.cooperativa.admin.client.resource.TransaccionesEntidadBovedaResource; import org.sistcoop.cooperativa.models.DetalleTransaccionEntidadBovedaProvider; import org.sistcoop.cooperativa.models.EntidadModel; import org.sistcoop.cooperativa.models.EntidadProvider; import org.sistcoop.cooperativa.models.HistorialBovedaModel; import org.sistcoop.cooperativa.models.HistorialBovedaProvider; import org.sistcoop.cooperativa.models.ModelDuplicateException; import org.sistcoop.cooperativa.models.ModelReadOnlyException; import org.sistcoop.cooperativa.models.TransaccionEntidadBovedaModel; import org.sistcoop.cooperativa.models.TransaccionEntidadBovedaProvider; import org.sistcoop.cooperativa.models.search.SearchCriteriaFilterOperator; import org.sistcoop.cooperativa.models.search.SearchCriteriaModel; import org.sistcoop.cooperativa.models.search.SearchResultsModel; import org.sistcoop.cooperativa.models.utils.ModelToRepresentation; import org.sistcoop.cooperativa.models.utils.RepresentationToModel; import org.sistcoop.cooperativa.representations.idm.HistorialBovedaRepresentation; import org.sistcoop.cooperativa.representations.idm.TransaccionEntidadBovedaRepresentation; import org.sistcoop.cooperativa.representations.idm.search.PagingRepresentation; import org.sistcoop.cooperativa.representations.idm.search.SearchCriteriaRepresentation; import org.sistcoop.cooperativa.representations.idm.search.SearchResultsRepresentation; import org.sistcoop.cooperativa.services.ErrorResponse; import org.sistcoop.cooperativa.services.resources.producers.TransaccionesEntidadBoveda_Entidad; @Stateless @TransaccionesEntidadBoveda_Entidad public class TransaccionesEntidadBovedaResourceImpl_Entidad implements TransaccionesEntidadBovedaResource { @PathParam("idEntidad") private String idEntidad; @Inject private EntidadProvider entidadProvider; @Inject private HistorialBovedaProvider historialBovedaProvider; @Inject private TransaccionEntidadBovedaProvider transaccionEntidadBovedaProvider; @Inject private DetalleTransaccionEntidadBovedaProvider detalleTransaccionEntidadBovedaProvider; @Inject private RepresentationToModel representationToModel; @Context private UriInfo uriInfo; @Inject private TransaccionEntidadBovedaResource transaccionEntidadBovedaResource; private EntidadModel getEntidadModel() { return entidadProvider.findById(idEntidad); } @Override public TransaccionEntidadBovedaResource transaccion(String transaccion) { return transaccionEntidadBovedaResource; } @Override public Response create(TransaccionEntidadBovedaRepresentation rep) { HistorialBovedaRepresentation historialBovedaRepresentation = rep.getHistorialBoveda(); EntidadModel entidad = getEntidadModel(); HistorialBovedaModel historialBovedaModel = historialBovedaProvider .findById(historialBovedaRepresentation.getId()); if (!entidad.getEstado()) { return ErrorResponse.exists("Entidad inactiva, no se pueden realizar transacciones"); } if (!historialBovedaModel.getEstado() || !historialBovedaModel.isAbierto()) { return ErrorResponse.exists("Historial Boveda destino cerrado y/o no activo"); } try { TransaccionEntidadBovedaModel model = representationToModel.createTransaccionEntidadBoveda(rep, getEntidadModel(), rep.getDetalle(), historialBovedaModel, transaccionEntidadBovedaProvider, detalleTransaccionEntidadBovedaProvider); return Response.created(uriInfo.getAbsolutePathBuilder().path(model.getId()).build()) .header("Access-Control-Expose-Headers", "Location") .entity(ModelToRepresentation.toRepresentation(model)).build(); } catch (ModelReadOnlyException e) { return ErrorResponse.exists("Entidad o Boveda de caja inactivos"); } catch (ModelDuplicateException e) { return ErrorResponse.exists("Transaccion ya existente"); } } @Override public List<TransaccionEntidadBovedaRepresentation> getAll() { List<TransaccionEntidadBovedaModel> models = transaccionEntidadBovedaProvider.getAll(getEntidadModel()); List<TransaccionEntidadBovedaRepresentation> result = new ArrayList<>(); models.forEach(model -> result.add(ModelToRepresentation.toRepresentation(model))); return result; } /* * @Override public * SearchResultsRepresentation<TransaccionEntidadBovedaRepresentation> * search(LocalDateTime desde, LocalDateTime hasta, String origen, String * tipo, Boolean estado, Integer page, Integer pageSize) { * * // add paging PagingModel paging = new PagingModel(); * paging.setPage(page); paging.setPageSize(pageSize); * * SearchCriteriaModel searchCriteriaBean = new SearchCriteriaModel(); * searchCriteriaBean.setPaging(paging); * * // add filter if (desde != null) { searchCriteriaBean.addFilter("fecha", * desde.toLocalDate(), SearchCriteriaFilterOperator.gte); * searchCriteriaBean.addFilter("hora", desde.toLocalTime(), * SearchCriteriaFilterOperator.gte); } if (hasta != null) { * searchCriteriaBean.addFilter("fecha", hasta.toLocalDate(), * SearchCriteriaFilterOperator.lte); searchCriteriaBean.addFilter("hora", * hasta.toLocalTime(), SearchCriteriaFilterOperator.lte); } * * if (origen != null) { searchCriteriaBean.addFilter("origen", origen, * SearchCriteriaFilterOperator.eq); } if (tipo != null) { * searchCriteriaBean.addFilter("tipo", tipo, * SearchCriteriaFilterOperator.eq); } if (estado != null) { * searchCriteriaBean.addFilter("estado", estado, * SearchCriteriaFilterOperator.bool_eq); } * * EntidadModel entidadmoModel = getEntidadModel(); * SearchResultsModel<TransaccionEntidadBovedaModel> results = * transaccionEntidadBovedaProvider .search(entidadmoModel, * searchCriteriaBean); * * // search // search * SearchResultsRepresentation<TransaccionEntidadBovedaRepresentation> rep = * new SearchResultsRepresentation<>(); * List<TransaccionEntidadBovedaRepresentation> items = new ArrayList<>(); * results.getModels().forEach(model -> * items.add(ModelToRepresentation.toRepresentation(model))); * rep.setItems(items); rep.setTotalSize(results.getTotalSize()); return * rep; } */ @Override public SearchResultsRepresentation<TransaccionEntidadBovedaRepresentation> search( SearchCriteriaRepresentation criteria) { SearchCriteriaModel criteriaModel = new SearchCriteriaModel(); // set filter and order criteria.getFilters().forEach(filter -> criteriaModel.addFilter(filter.getName(), filter.getValue(), SearchCriteriaFilterOperator.valueOf(filter.getOperator().toString()))); criteria.getOrders().forEach(order -> criteriaModel.addOrder(order.getName(), order.isAscending())); // set paging PagingRepresentation paging = criteria.getPaging(); criteriaModel.setPageSize(paging.getPageSize()); criteriaModel.setPage(paging.getPage()); SearchResultsModel<TransaccionEntidadBovedaModel> results = transaccionEntidadBovedaProvider .search(getEntidadModel(), criteriaModel); SearchResultsRepresentation<TransaccionEntidadBovedaRepresentation> rep = new SearchResultsRepresentation<>(); List<TransaccionEntidadBovedaRepresentation> items = new ArrayList<>(); results.getModels().forEach(model -> items.add(ModelToRepresentation.toRepresentation(model))); rep.setItems(items); rep.setTotalSize(results.getTotalSize()); return rep; } }
Python
UTF-8
4,503
2.59375
3
[]
no_license
#!/usr/bin/env python # -*- coding: UTF-8 -*- # # Copyright (c) 2018 ASMlover. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list ofconditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materialsprovided with the # distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. import math import sys from bisect import bisect if sys.version_info >= (2, 5): import hashlib md5_constructor = hashlib.md5 else: import md5 md5_constructor = md5.new class HashRing(object): def __init__(self, nodes=None, weights=None): self.ring = {} self._sorted_keys = [] self.nodes = nodes if not weights: weights = {} self.weights = weights self._generate_circle() def _generate_circle(self): total_weight = 0 for node in self.nodes: total_weight += self.weights.get(node, 1) for node in self.nodes: weight = 1 if node in self.weights: weight = self.weights.get(node) factor = int(math.floor((40 * len(self.nodes) * weight) / total_weight)) for j in xrange(factor): b_key = self._hash_digest('%s@%s' % (node, j)) for i in xrange(3): key = self._hash_value(b_key, lambda x: x + i * 4) self.ring[key] = node self._sorted_keys.append(key) self._sorted_keys.sort() def _hash_digest(self, key): m = md5_constructor() m.update(key) return map(ord, m.digest()) def _hash_value(self, b_key, entry_fn): return ((b_key[entry_fn(3)] << 24) | (b_key[entry_fn(2)] << 16) | (b_key[entry_fn(1)] << 8) | b_key[entry_fn(0)]) def gen_key(self, key): b_key = self._hash_digest(key) return self._hash_value(b_key, lambda x: x) def get_node_pos(self, string_key): if not self.ring: return None key = self.gen_key(string_key) nodes = self._sorted_keys pos = bisect(nodes, key) if pos == len(nodes): return 0 else: return pos def get_node(self, string_key): pos = self.get_node_pos(string_key) if pos is None: return None return self.ring[self._sorted_keys[pos]] def iternodes(self, string_key, distinct=True): if not self.ring: yield None, None returned_values = set() def __distinct_filter(value): if str(value) not in returned_values: returned_values.add(str(value)) return value pos = self.get_node_pos(string_key) for key in self._sorted_keys[pos:]: val = __distinct_filter(self.ring[key]) if val: yield val for i, key in enumerate(self._sorted_keys): if i < pos: val = __distinct_filter(self.ring[key]) if val: yield val def main(): nodes = [ 'ShardStub@1', 'ShardStub@2', 'ShardStub@3', 'ShardStub@4', 'ShardStub@5', ] hr = HashRing(nodes) print hr.get_node('1') print hr.get_node('2') print hr.get_node('3') print hr.get_node('4') print hr.get_node('5') if __name__ == '__main__': main()
Python
UTF-8
80
3.3125
3
[]
no_license
st = 7 sp = 0 while st > 0: print(" "*sp + "*"*st) st -= 2 sp += 1
JavaScript
UTF-8
3,668
2.921875
3
[]
no_license
const players = { PLAYER_1: 1, PLAYER_2: 2, }; module.exports = { getAvailableGame: function (games) { for (const [key, value] of games) { const game = games.get(key); if (!game.player1 || !game.player2) { return game; } } return null; }, createNewGame: function () { const newGame = { board: [ [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], ], colHeights: [0, 0, 0, 0, 0, 0, 0], player1: false, player2: false, currentPlayer: players.PLAYER_1, id: this.newUid(), }; return newGame; }, newUid: function () { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function ( c ) { var r = (Math.random() * 16) | 0, v = c == "x" ? r : (r & 0x3) | 0x8; return v.toString(16); }); }, moveEnabled: (game, x) => x > 0 && x <= 7 && game.colHeights[x - 1] < 7, win: function (board) { return this.checkXAndYAxes(board) || this.checkDiagonals(board) || 0; }, checkXAndYAxes: function (board) { var currentPlayerHori = 0; var currentPlayerVerti = 0; var cumulVerti = 0; var cumulHori = 0; for (var i = 0; i < 7; i++) { for (var j = 0; j < 7; j++) { // check columns if (board[i][j] != currentPlayerVerti) { cumulVerti = 0; currentPlayerVerti = board[i][j]; } if (currentPlayerVerti != 0) { cumulVerti++; if (cumulVerti == 4) { return currentPlayerVerti; } } // check lines if (board[j][i] != currentPlayerHori) { cumulHori = 0; currentPlayerHori = board[j][i]; } if (currentPlayerHori != 0) { cumulHori++; if (cumulHori == 4) { return currentPlayerHori; } } } cumulHoriz = 0; comulVerti = 0; currentPlayerVerti = 0; currentPlayerHori = 0; } }, checkDiagonals: function (board) { var currentPlayerDiag1 = 0; var currentPlayerDiag2 = 0; var cumulDiag1 = 0; var cumulDiag2 = 0; for (var k = 0; k < 6; k++) { for (var l = 6; l >= 0; l--) { // check diag 1 for (var i = k, j = l; i < 7 && j >= 0; i++, j--) { if (board[i][j] != currentPlayerDiag1) { cumulDiag1 = 0; currentPlayerDiag1 = board[i][j]; } if (currentPlayerDiag1 != 0) { cumulDiag1++; if (cumulDiag1 == 4) { return currentPlayerDiag1; } } } //check diag 2 for (var i = k, j = l; i < 7 && j < 7; i++, j++) { if (board[i][j] != currentPlayerDiag2) { cumulDiag2 = 0; currentPlayerDiag2 = board[i][j]; } if (currentPlayerDiag2 != 0) { cumulDiag2++; if (cumulDiag2 == 4) { return currentPlayerDiag2; } } } cumulDiag1 = 0; comulDiag2 = 0; currentPlayerDiag1 = 0; currentPlayerDiag2 = 0; } } }, resetBoard: function (game) { game.board = [ [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], ]; game.colHeights = [0, 0, 0, 0, 0, 0, 0]; game.currentPlayer = players.PLAYER_1; return game; }, };
Ruby
UTF-8
3,618
2.59375
3
[]
no_license
# require "awesome_print" # include SlotsHelper class Card < ActiveRecord::Base extend SlotsHelper has_and_belongs_to_many :slots has_many :card_keywords # TODO: fix to assign to slot def self.search(queries_string, slot) return [] if queries_string.blank? query_array = queries_string.to_s.split formatted_queries = format_multi_char_queries(query_array) matches = get_matches(formatted_queries) # FIXME: Better way to cull matches that don't have hit with all queries? matches = matches.select{|_,v| v[:terms].length >= query_array.length} matches.group_by { |_, v| v[:columns] } end private_class_method def self.format_multi_char_queries(arr) result = [] arr.each do |elem| if numeric?(elem) result << elem else result << format_string_query(elem) end end return result end private_class_method def self.format_string_query(query) return query if(query.length < 2) formatted_query = '.*' query.split('').each do |ch| formatted_query += (ch + ".*") end return formatted_query end private_class_method def self.get_matches(subqueries) match_data = {} subqueries.each do |query| result = get_card_subset(query, match_data) match_data = result == nil ? match_data : result end match_data end # TODO: Split this into separate methods private_class_method def self.get_card_subset(query, match_data) new_match_data = {} if(match_data.empty?) card_set = Card.all else card_set = Card.where(name: match_data.keys) end if numeric?(query) matched_cards = card_set.where(cost: query) matched_cards.each do |card| merge_match_data(match_data, new_match_data, card, 'Cost', query) end else matched_cards = card_set.where('name ~* :pat', pat: query).distinct matched_cards.each do |card| merge_match_data(match_data, new_match_data, card, 'Name', card[:name]) end if new_match_data.any? match_data = new_match_data end match_data = (new_match_data.any? ? new_match_data : match_data) keyword_set = CardKeyword.where(CardKeyword.arel_table[:card_id].in card_set.pluck(:id) ).distinct keyword_matches = keyword_set.where('name ~* :pat', pat: query).distinct keyword_matches.each do |kw| merge_match_data(match_data, new_match_data, kw.card, kw.category, kw.name) end end return new_match_data end # FIXME move to helper? private_class_method def self.numeric?(str) str.to_s.delete('%').match(/\A[+-]?\d+?(\.\d+)?\Z/) != nil end # FIXME move to helper? private_class_method def self.merge_match_data(match_data, new_match_data, card, column, query) new_match_data[card.name] = new_match_data[card.name]!=nil ? new_match_data[card.name] : {} new_match_data[card.name][:card] = card new_match_data[card.name][:columns] = merge_result_hash(match_data, card.name, :columns, column) new_match_data[card.name][:terms] = merge_result_hash(match_data, card.name, :terms, query) end # FIXME move to helper? private_class_method def self.merge_result_hash(hsh, key, sub_key, new_elem) if hsh[key].nil? return [new_elem] else if hsh[key][sub_key].nil? return [new_elem] else return (hsh[key][sub_key].include?(new_elem) ? hsh[key][sub_key] : hsh[key][sub_key].push(new_elem)) end end return nil end end
Java
UTF-8
945
3.203125
3
[]
no_license
import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class Manold { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t=Integer.parseInt(sc.nextLine()); for(int x=1;x<=t;x++){ int len=Integer.parseInt(sc.nextLine()); int[] n=new int[len]; String s=sc.nextLine(); StringTokenizer st=new StringTokenizer(s); for(int i=0;i<n.length;i++){ n[i]=Integer.parseInt(st.nextToken()); } Arrays.sort(n); if(n[0]==n[1]){ System.out.println("Case #"+x+": "+n[len-1]); } else if(n[len-1]==n[len-2]){ System.out.println("Case #"+x+": "+n[0]); } } } }