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 | 2,386 | 3.015625 | 3 | [] | no_license | // -*- C++ -*-
// $RCSfile: circlestack.h,v $
// $Revision: 1.4 $
// $Author: langer $
// $Date: 2000-10-24 14:35:17 $
/* This software was produced by NIST, an agency of the U.S. government,
* and by statute is not subject to copyright in the United States.
* Recipients of this software assume all responsibilities associated
* with its operation, modification and maintenance. However, to
* facilitate maintenance we ask that before distributing modifed
* versions of this software, you first contact the authors at
* oof_manager@ctcms.nist.gov.
*/
// A finite stack which accepts limitless items. Later items override
// earlier ones if the stack is full.
#ifndef CIRCLESTACK_H
#define CIRCLESTACK_H
template <class TYPE> class CircleStack;
// Iterator for looping over all entries in the stack, from bottom to top:
// for(CircleStackIterator iter(stack); !iter.end(); ++iter)
// do something with stack[iter]
template <class TYPE>
class CircleStackIterator {
private:
const CircleStack<TYPE> &stack;
int which;
bool done;
public:
CircleStackIterator(const CircleStack<TYPE>&);
bool end() const { return done; }
void operator++();
friend class CircleStack<TYPE>;
};
template <class TYPE>
class CircleStack {
private:
TYPE *data;
int size;
int ndata;
int currentpos; // current value
int bottom; // oldest datum
int top; // next spot to be filled
void (*overwrite)(TYPE &);
void clear(int lo, int hi); // apply overwrite() to entries i, lo <= i < hi
public:
CircleStack(int rollover, void (*overwrite)(TYPE&));
CircleStack(int rollover);
~CircleStack();
TYPE ¤t() const;
void push(const TYPE&); // insert after current value
bool prev(); // go to previous value
bool next(); // go to next value
void first() { currentpos = bottom; }
void last() { currentpos = (top + size - 1)%size; }
void clear(); // apply overwrite() to all entries
int capacity() const { return ndata; }
void set_rollover(int); // sets maximum number of entries
int get_rollover() const { return size; }
// set current position to given distance from top of stack.
void set_current_depth(int);
int get_current_depth() const;
// sequential access without changing the stack pointers
const TYPE &operator[](const CircleStackIterator<TYPE>&) const;
friend class CircleStackIterator<TYPE>;
};
#include "circlestack.C"
#endif
|
JavaScript | UTF-8 | 488 | 2.5625 | 3 | [
"MIT"
] | permissive | /*
* Author: maeek
* Description: No history simple websocket chat
* Github: https://github.com/maeek/vv-chat
* Version: 1.1.1
*
* You can generate password from command line
* Usage: node passwordHash.js password
*
*/
const bcrypt = require('bcrypt-nodejs');
const args = process.argv.slice(2);
var salt = bcrypt.genSaltSync();
for (let i = 0; i < args.length; i++) {
bcrypt.hash(args[i], salt, function(err, hash) {
console.log(hash + '\n');
});
} |
Markdown | UTF-8 | 2,475 | 2.84375 | 3 | [
"MIT"
] | permissive | # GUI Programming with C++ [Video]
This is the code repository for [GUI Programming with C++ [Video]](https://www.packtpub.com/application-development/gui-programming-c-video?utm_source=github&utm_medium=repository&utm_campaign=9781789139464), published by [Packt](https://www.packtpub.com/?utm_source=github). It contains all the supporting project files necessary to work through the video course from start to finish.
## About the Video Course
C++ has come a long way and has now been adopted in several contexts. Its key strengths are its software infrastructure and resource-constrained applications. The C++ 17 release will change the way developers write code, and this video course will help you master your developing skills with C++. With real-world, practical examples explaining each concept, the course will begin by introducing you to the latest features in C++ 17. It encourages clean code practices in C++ in general and demonstrates GUI app-development options in C++.
By the end of the course, you'll have an in-depth understanding of the language and its various facets.
<H2>What You Will Learn</H2>
<DIV class=book-info-will-learn-text>
<UL>
<LI>Write modular C++ applications in terms of existing and newly introduced features
<LI>Identify code-smells and clean up and refactor legacy C++ applications
<LI>Get acquainted with the new C++17 features
<LI>Develop GUI applications in C++ </LI></UL></DIV>
## Instructions and Navigation
### Assumed Knowledge
To fully benefit from the coverage included in this course, you will need:<br/>
Solid understanding of the C++ language is mandatory
### Technical Requirements
This course has the following software requirements:<br/>
C++ 7
## Related Products
* [Salesforce Certified Administrator - Revision Guide [Video]](https://www.packtpub.com/business/salesforce-certified-administrator-revision-guide-video?utm_source=github&utm_medium=repository&utm_campaign=9781838550813)
* [Hands-On Protocol Oriented Programming with Swift 4.x [Video]](https://www.packtpub.com/application-development/hands-protocol-oriented-programming-swift-4x-video?utm_source=github&utm_medium=repository&utm_campaign=9781789610307)
* [AWS Certified Solutions Architect Associate - Exam Prep Guide [Video]](https://www.packtpub.com/virtualization-and-cloud/aws-certified-solutions-architect-associate-exam-prep-guide-video?utm_source=github&utm_medium=repository&utm_campaign=9781789535433)
|
Java | UTF-8 | 909 | 2.015625 | 2 | [] | no_license | package com.thoughtworks.i1.commons.test;
import com.thoughtworks.i1.commons.util.DBUtils;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.slf4j.LoggerFactory;
public class TransactionalDomainTestRunner extends AbstractTestRunner {
public TransactionalDomainTestRunner(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
protected void beforeAllTestsRun() {
startServer();
}
@Override
protected void afterAllTestsRun() {
closeServer();
}
protected void beforeRunChild(FrameworkMethod method) {
super.beforeRunChild(method);
entityManager.getTransaction().begin();
}
protected void afterRunChild() {
super.afterRunChild();
DBUtils.rollBackQuietly(entityManager.getTransaction());
}
}
|
JavaScript | UTF-8 | 927 | 2.515625 | 3 | [
"MIT"
] | permissive | function Method(options, system) {
this.construct(options, system, 'extended');
}
Method.prototype.types = {
extended: function (options) {
this.include(options, {
method: undefined
});
this.notifyUndefined(['method']);
if (typeof this.method == 'string') {
this.method = eval('(' + this.method + ')');
}
if (typeof this.method == 'function') {
this.parentSystem[this.id] = this.method;
}
}
};
Method.prototype.toJSON = function () {
var json = utils.deepCopy(this._options);
json.method = "" + this.method;
delete json.id;
delete json.group;
return json;
};
Method.prototype.destroy = function () {
try {
delete this.parentSystem[this.id];
} catch (e) {
console.log(this.group, this.id, e.message || e);
throw e;
}
};
extend(Method, Component);
Component.prototype.maker.method = Method;
Component.prototype.defaultType.method = 'extended';
|
Python | UTF-8 | 2,707 | 3.34375 | 3 | [] | no_license | import streamlit as st
import pandas as pd
from PIL import Image
# Importacion de Archivos
image = Image.open('Description.jpg')
st.title('Energy in Place')
# Variables de ingreso
st.info('Cálculo de calor almacenado y potencial de generación geoeléctrica usando método volumétrico y valores de parámetros ajustados')
st.warning('''Ecuaciones de energía:
Energía en roca y fluido: Qt = Qr + Qf
Energía en roca: Qr = A * h * (rhor * Cr * (1 -phi) *(Ti - Ta))
Energía en fluidos: Qf = A * h * (rhof * Cf * phi * (Ti - Ta))
Potencia de la planta: P = (Qt * Rf * Ce) / (Pf * t)
''')
with st.expander('Variables description'):
st.image(image)
with st.expander('Parámetros del Campo Geotérmico:'):
columna_1 , columna_2 , columna_3 = st.columns(3)
with columna_1:
A = st.number_input('Area [Km2]',5.00,12.00,6.25)
h = st.number_input('Espesor del reservrio [m]',min_value=0, max_value=2000, value=60 )
Cr = st.number_input('Calor específico de la roca [kJ/kg °C]',min_value=0.0, max_value=10.0, value=0.9 )
with columna_2:
Cf = st.number_input('Calor específico del fluido [kJ/kg °C]',min_value=0.0, max_value=10.0, value=4.2 )
phi = st.number_input('Porosidad de la roca [-]',min_value=0.07, max_value=0.15, value=0.1 )
Ti = st.number_input('Temperatura media del reservorio [°C]',min_value=140.00, max_value=290.00, value=160.00 )
with columna_3:
Ta = st.number_input('Temperatura de abandono del reservorio [°C]',min_value=0.00, max_value=290.00, value=50.00 )
rhor = st.number_input('Densidad de la roca [kg/m3]',min_value=140.00, max_value=4000.00, value=2700.00 )
rhof = st.number_input('Densidad del fluido [kg/m3]',min_value=0.00, max_value=4000.00, value=997.00 )
Qr = A*1000000*h*(rhor*Cr*(1-phi)*(Ti-Ta))
Qf= A*1000000*h*(rhof*Cf*phi*(Ti-Ta))
Qt= Qr+Qf
st.write('Calor almacenado en la roca:', format(Qr,'.4E'))
st.write('Calor almacennado en el fluido:', format(Qf,'.4E'))
st.write('Calor total:', format(Qt,'.4E'))
with st.expander('Parámetros de la Planta Geotérmica:'):
columna_4 , columna_5 , columna_6 = st.columns(3)
with columna_4:
Rf = st.number_input('Factor de recuperación de calor [-]',min_value=0.10, max_value=0.25, value=0.15 )
Ce = st.number_input('Eficiencia de conversión [-]',min_value=0.00, max_value=2.00, value=0.10 )
with columna_5:
Pf = st.number_input('Factor de Planta [-]',min_value=0.00, max_value=2.00, value=0.90 )
with columna_6:
t = st.number_input('Tiempo [years]',min_value=0.00, max_value=100.00, value=30.00 )
P = Qt*Rf*Ce/(1000*Pf*t*31557600)
st.success('Potencial de energía: {} Mwe'.format(round(P,4)))
|
Java | UTF-8 | 3,100 | 1.859375 | 2 | [] | no_license | package shangri.example.com.shangri.ui.adapter;
import android.content.Context;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.fyales.tagcloud.library.TagBaseAdapter;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import shangri.example.com.shangri.R;
import shangri.example.com.shangri.UserConfig;
import shangri.example.com.shangri.base.BaseListAdapter;
import shangri.example.com.shangri.model.bean.response.MyTaskBean;
import shangri.example.com.shangri.model.bean.response.ParticipationTaskBean;
import shangri.example.com.shangri.util.DensityUtil;
import shangri.example.com.shangri.util.TimeUtil;
import shangri.example.com.shangri.util.ViewHolder;
/**
* Created by Administrator on 2018/1/3.
*/
public class PartcipationAdapter extends BaseListAdapter<ParticipationTaskBean.AnchorsBean> {
private final String mRole;
private final Map<Integer, Boolean> mList;
private Context mContext;
private Animation mLikeAnim;
private TagBaseAdapter mAdapter, mAdapter1;
private boolean isOpen = true;
public PartcipationAdapter(Context context, int layoutId, List<ParticipationTaskBean.AnchorsBean> datas) {
super(context, layoutId, datas);
mRole = UserConfig.getInstance().getRole();
mContext = context;
mList = new HashMap<>();
mLikeAnim = AnimationUtils.loadAnimation(context, R.anim.anim_like);
}
@Override
public void convert(final ViewHolder helper, ParticipationTaskBean.AnchorsBean pageDataBean) {
TextView tv_name_guild = helper.getView(R.id.tv_name_guild);
TextView tv_text2 = helper.getView(R.id.tv_text2);
TextView tv_comment2 = helper.getView(R.id.tv_comment2);
TextView baifenbi = helper.getView(R.id.baifenbi);
ProgressBar progress = helper.getView(R.id.progress);
ImageView carimage = helper.getView(R.id.carimage);
tv_name_guild.setText(pageDataBean.getAnchor_name());
tv_text2.setText(pageDataBean.getSelf_aims());
tv_comment2.setText(String.valueOf(pageDataBean.getTotal_aims()));
double p = Double.valueOf(pageDataBean.getTotal_aims()) / Double.valueOf(pageDataBean.getSelf_aims());
int p1 = (int) p;
progress.setProgress(p1);
baifenbi.setText(p1 + "%");
int pro1 = (int) (180 * (Double.valueOf(p1) / 100));
int pro = DensityUtil.dip2px(mContext, pro1);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(pro, 0, 0, 0);//4个参数按顺序分别是左上右下
carimage.setLayoutParams(layoutParams);
}
@Override
public void convert(ViewHolder helper, ParticipationTaskBean.AnchorsBean pageDataBean, List<Object> payloads) {
}
}
|
JavaScript | UTF-8 | 3,453 | 3.875 | 4 | [] | no_license | window.onload = function() {
// list of possible words
var wordBank = ["computer", "program", "mouse", "keyboard", "javascript", "css", "html", "website"];
var randomWord = wordBank[Math.floor(Math.random() * wordBank.length)]; // randomly selects a word from wordBank
var underscores = [];
for (var i = 0; i < randomWord.length; i++) {
underscores.push('_ ');
}
var wrongLettersArray = [];
var rightLettersArray = [];
var wrongGuess = 0;
console.log(randomWord);
console.log(wrongGuess);
console.log(wrongLettersArray);
console.log(rightLettersArray);
$('#word').append(underscores);
$('#submit').on('click', function() { // takes player input and compares to string
var guessedLetter = $('#guessInput').val(); // to determin if there is a match
if (!wrongLettersArray.includes(guessedLetter) && !rightLettersArray.includes(guessedLetter)){ // checks if letter has been guessed
if (!randomWord.includes(guessedLetter)) {
alert('INCORRECT'); // if guess is guess is wrong
wrongGuess++; // alert "INCORRECT"
wrongLettersArray.push(guessedLetter); // and add letter to the incorrect guess array
console.log(wrongGuess);
console.log(wrongLettersArray);
$('#incorrect').append(guessedLetter);
if (wrongGuess === 1) {
$('#image0').hide();
$('#image1').show();
}
if (wrongGuess === 2) {
$('#image1').hide();
$('#image2').show();
}
if (wrongGuess === 3) {
$('#image2').hide();
$('#image3').show();
}
if (wrongGuess === 4) {
$('#image3').hide();
$('#image4').show();
}
if (wrongGuess === 5) {
$('#image4').hide();
$('#image5').show();
}
if (wrongGuess === 6) {
$('#image5').hide();
$('#image6').show();
}
if (wrongGuess === 7) {
$('#image6').hide();
$('#image7').show();
}
if (wrongGuess === 8) {
$('#image7').hide();
$('#image8').show();
}
if (wrongGuess === 9) {
$('#image8').hide();
$('#image9').show();
}
if (wrongGuess === 9) { // if you guess wrong 9 times you lose.
alert('You are dead!');
}
}
else {
alert('CORRECT');
for (var i = 0; i < randomWord.length; i++) { // cycles through each letter of the current word
if (randomWord[i] === guessedLetter) { // and if a match is found
rightLettersArray.push(guessedLetter); // adds the letter to the correct guess array
underscores[i] = guessedLetter;
console.log(underscores);
}
}
$('#word').empty();
$('#word').append(underscores);
if (rightLettersArray.length === randomWord.length) { // if .length of array === .length of word
alert('You survived!'); // alert "You survived!"
}
}
}
else {
alert('You have already guessed that letter'); // if letter has been guess display this
}
});
$('#incorrect').append(wrongLettersArray);
$('#correct').append(rightLettersArray);
};
// for(var i = 0; i < randomWord.length; i++) {
// if (randomWord[i] === guessedLettter) {
// // console.log(word[i].indexOf(choice));
// underscores[i] = guessedLetter;
// // console.log(arr);
// }
// }
// console.log(underscores);
|
C++ | UTF-8 | 2,580 | 2.8125 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* This file is part of the source code of the software program
* Vampire. It is protected by applicable
* copyright laws.
*
* This source code is distributed under the licence found here
* https://vprover.github.io/license.html
* and in the source directory
*/
/**
* @file FormulaVarIterator.hpp
* Defines a class FormulaVarIterator that iterates
* over free variables in a formula or a term.
*
* @since 06/01/2004, Manchester
* @since 02/09/2009 Redmond, reimplemented to work with non-rectified
* formulas and return each variable only once
* @since 15/05/2015 Gothenburg, FOOL support added
*/
#ifndef __FormulaVarIterator__
#define __FormulaVarIterator__
#include "Lib/MultiCounter.hpp"
#include "Lib/Stack.hpp"
#include "Kernel/Term.hpp"
#include "Kernel/Formula.hpp"
using namespace Lib;
namespace Kernel {
/**
* Implements an iterator over free variables of a
* formula, a term or a list of terms.
*
* Any argument may contain $let and $ite expressions.
*
* @since 06/01/2004, Manchester
* @since 02/09/2009 Redmond, reimplemented to work with non-rectified
* formulas and return each variable only once
* @since 15/05/2015 Gothenburg, FOOL support added
*/
class FormulaVarIterator
{
public:
DECL_ELEMENT_TYPE(unsigned);
explicit FormulaVarIterator(const Formula*);
explicit FormulaVarIterator(const Term*);
explicit FormulaVarIterator(const TermList*);
bool hasNext();
unsigned next();
private:
/** instruction of what to process next */
enum Instruction {
/** process formula */
FVI_FORMULA,
/** process term */
FVI_TERM,
/** process term list */
FVI_TERM_LIST,
/** bind variables bound by quantifier or $let */
FVI_BIND,
/** unbind variables bound by quantifier or $let */
FVI_UNBIND,
};
/** If true then _nextVar contains the next variable */
bool _found;
/** The variable to be returned by next() */
unsigned _nextVar;
/** Counter used to store bound variables, together with the number of times they are bound */
MultiCounter _bound;
/** To store previously found free variables */
MultiCounter _free;
/** Stack of formulas to be processed */
Stack<const Formula*> _formulas;
/** Stack of terms to process */
Stack<const Term*> _terms;
/** Stack of term lists to process */
Stack<TermList> _termLists;
/** Stack of instructions telling what to do next */
Stack<Instruction> _instructions;
/** Stack of lists of variables to process */
Stack<const VList*> _vars;
}; // class FormulaVarIterator
}
#endif // __FormulaVarIterator__
|
Python | UTF-8 | 1,660 | 2.734375 | 3 | [] | no_license | import os
from os import walk
from nltk.tokenize import RegexpTokenizer
from gensim.models import Word2Vec
def gen_formatted_review(data_dir, tokenizer = RegexpTokenizer(r'\w+') ):
data = []
for filename in os.listdir(data_dir):
file = os.path.join(data_dir, filename)
with open(file,encoding='utf-8') as f:
content = f.readline().lower()
content_formatted = tokenizer.tokenize(content)
data.append(content_formatted)
return data
if __name__ == "__main__":
working_dir = "../data/aclImdb"
train_dir = os.path.join(working_dir, "train")
train_pos_dir = os.path.join(train_dir, "pos")
train_neg_dir = os.path.join(train_dir, "neg")
test_dir = os.path.join(working_dir, "test")
test_pos_dir = os.path.join(test_dir, "pos")
test_neg_dir = os.path.join(test_dir, "neg")
train = gen_formatted_review(train_pos_dir)
train2 = gen_formatted_review(train_neg_dir)
train.extend(train2)
test = gen_formatted_review(test_pos_dir)
test2 = gen_formatted_review(test_neg_dir)
test.extend(test2)
train.extend(test)
embedding_size = 50
fname = os.path.join(working_dir, "imdb_embedding")
if os.path.isfile(fname):
embedding_model = Word2Vec.load(fname)
else:
embedding_model = Word2Vec(train, size=embedding_size, window=5, min_count=5)
embedding_model.save(fname)
word1 = "great"
word2 = "horrible"
print("similar words of {}:".format(word1))
print(embedding_model.most_similar('great'))
print("similar words of {}:".format(word2))
print(embedding_model.most_similar('horrible'))
pass
|
Java | UTF-8 | 1,629 | 2.359375 | 2 | [] | no_license | package com.datalife.controller;
import com.datalife.entities.User;
import com.datalife.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Controller class that handles the password related requests
*
* Created by supriya gondi on 11/24/2014.
*/
@Controller
@RequestMapping(value = "/password")
public class PasswordController {
@Autowired
UserRepository userRepository;
@RequestMapping(value = "/{uuid}",method = RequestMethod.GET)
public String changePassword(@PathVariable String uuid,ModelMap modelMap) {
String page = null;
if (uuid != null && !uuid.isEmpty()) {
User u = userRepository.searchByUuid(uuid);
if (u != null) {
page = "resetPassword";
if(u.getUserName() != null){
modelMap.put("userName",u.getUserName());
modelMap.put("userId",u.getUserId());
}
}else{
page = "changePassword";
}
}
return page;
}
/**
*
* @param modelMap
* @return view if user clicks on forgot Password
*/
@RequestMapping(value = "/afterResetPassword",method = RequestMethod.GET)
public String afterResetPassword(ModelMap modelMap)
{
return "changePassword";
}
}
|
PHP | UTF-8 | 2,942 | 2.515625 | 3 | [] | no_license | <?php
class Like extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->CI =& get_instance();
$this->load->model('comment_model');
$this->load->model('news_model');
$this->load->model('like_model');
if (ENVIRONMENT === 'production') {
die('Access denied!');
}
}
/*
* Like Comment
*
* Method: POST
* Headers: Content-Type: application/json
* Body:
* form-data
* key = comment_id or news_id
*/
public function like()
{
$uid = $_SERVER['REMOTE_ADDR'];
if ($comment_id = $this->input->post(Comment_model::API_KEY_COMMENT_ID)) {
$like = Like_model::find_by_params(null, $uid, null, $comment_id);
$comment = Comment_model::get_one_comment_by_id($comment_id);
if (!$comment->get_id()) {
return $this->response_error("Comment id=" . $comment_id . " not found!");
}
if (!$like) {
$data[Comment_model::API_KEY_COMMENT_ID] = $comment_id;
$data[Like_model::API_KEY_UID] = $uid;
$like = Like_model::create($data);
return $this->response_success();
}
return $this->response_error("Like already exists!");
}
if ($news_id = $this->input->post(News_model::API_KEY_NEWS_ID)) {
$like = Like_model::find_by_params(null, $uid, $news_id, null);
try {
$news = News_model::get_one_news_by_id($news_id);
} catch (Exception $e) {
return $this->response_error($e);
}
if (!$news->get_id()) {
return $this->response_error("News id=" . $news_id . " not found!");
}
if (!$like) {
$data[News_model::API_KEY_NEWS_ID] = $news_id;
$data[Like_model::API_KEY_UID] = $uid;
$like = Like_model::create($data);
return $this->response_success();
}
return $this->response_error("Like already exists!");
}
}
/*
* Unlike Comment
* Method: POST
* Headers: Content-Type: application/json
* Body:
* form-data
* key = like_id
*/
public function unlike()
{
if ($like_id = $this->input->post(Like_model::API_KEY_LIKE_ID)) {
$uid = $_SERVER['REMOTE_ADDR'];
$like = Like_model::find_by_params($like_id, null, null, null);
if (!$like) {
return $this->response_error("Like id = " . $like_id . " not found!");
}
try {
$deleted = Like_model::deleted_by_id($like_id);
} catch (Exception $e) {
return $this->response_error($e);
}
return $this->response_success();
}
}
} |
Markdown | UTF-8 | 8,296 | 2.828125 | 3 | [
"CC-BY-4.0",
"MIT"
] | permissive | ---
title: "Type List (Visual Basic) | Microsoft Docs"
ms.date: "2015-07-20"
ms.prod: ".net"
ms.reviewer: ""
ms.suite: ""
ms.technology:
- "devlang-visual-basic"
ms.topic: "article"
f1_keywords:
- "StructureConstraint"
- "vb.StructureConstraint"
- "ClassConstraint"
- "vb.ClassConstraint"
dev_langs:
- "VB"
helpviewer_keywords:
- "class constraint"
- "constraints, Visual Basic generic types"
- "generic parameters"
- "generics [Visual Basic], constraints"
- "generics [Visual Basic], type list"
- "structure constraint"
- "constraints, in type parameters"
- "generics [Visual Basic], generic types"
- "parameters, type"
- "constraints, Structure keyword"
- "type parameters, constraints"
- "types [Visual Basic], generic"
- "parameters, generic"
- "generics [Visual Basic], type parameters"
- "type parameters"
- "constraints, Class keyword"
ms.assetid: 56db947a-2ae8-40f2-a70a-960764e9d0db
caps.latest.revision: 33
author: "stevehoag"
ms.author: "shoag"
caps.handback.revision: 33
---
# Type List (Visual Basic)
[!INCLUDE[vs2017banner](../../../visual-basic/developing-apps/includes/vs2017banner.md)]
Specifica i *parametri di tipo* per un elemento di programmazione *generico*. Nel caso di più parametri, è possibile separarli mediante virgole. Di seguito è riportata la sintassi di un parametro di tipo.
## Sintassi
```
[genericmodifier] typename [ As constraintlist ]
```
## Parti
|||
|-|-|
|Termine|Definizione|
|`genericmodifier`|Parametro facoltativo. Può essere utilizzato solo in interfacce e delegati generici. È possibile dichiarare una covariante del tipo utilizzando la parola chiave [Out](../../../visual-basic/language-reference/modifiers/out-generic-modifier.md) oppure una controvariante utilizzando la parola chiave [In](../../../visual-basic/language-reference/modifiers/in-generic-modifier.md). Vedere [Covarianza e controvarianza](../Topic/Covariance%20and%20Contravariance%20\(C%23%20and%20Visual%20Basic\).md).|
|`typename`|Obbligatorio. Nome del parametro di tipo. Si tratta di un segnaposto da sostituire con un tipo definito specificato dall'argomento di tipo corrispondente.|
|`constraintlist`|Parametro facoltativo. Elenco di requisiti che vincolano il tipo di dati che è possibile specificare per `typename`. In presenza di più vincoli è possibile racchiuderli tra parentesi graffe \(`{ }`\) e separarli con virgole. L'elenco dei vincoli deve essere introdotto dalla parola chiave [As](../../../visual-basic/language-reference/statements/as-clause.md). `As` viene utilizzata una sola volta all'inizio dell'elenco.|
## Note
Ogni elemento di programmazione generico deve accettare almeno un parametro di tipo. Tale parametro è un segnaposto per uno specifico tipo, ossia un *elemento costruito*, specificato dal codice client al momento della creazione di un'istanza del tipo generico. È possibile definire una classe, una struttura, un'interfaccia, una routine o un delegato generico.
Per ulteriori informazioni sul momento in cui definire un tipo generico, vedere [Tipi generici in Visual Basic](../../../visual-basic/programming-guide/language-features/data-types/generic-types.md). Per ulteriori informazioni sui nomi dei parametri di tipo, vedere [Declared Element Names](../../../visual-basic/programming-guide/language-features/declared-elements/declared-element-names.md).
## Regole
- **Parentesi.** Se si specifica un elenco di parametri di tipo, è necessario racchiuderlo tra parentesi e farlo precedere dalla parola chiave [Of](../../../visual-basic/language-reference/statements/of-clause.md). `Of` viene utilizzata una sola volta all'inizio dell'elenco.
- **Vincoli.** Un elenco di *vincoli* definiti su un parametro di tipo può includere qualsiasi combinazione dei seguenti elementi:
- Un numero qualsiasi di interfacce. Il tipo specificato deve implementare ogni interfaccia dell'elenco.
- Al massimo una classe. Il tipo specificato deve ereditare da tale classe.
- Parola chiave `New`. Il tipo specificato deve esporre un costruttore senza parametri a cui possa accedere il tipo generico. Questa caratteristica risulta utile se si vincola un parametro di tipo tramite una o più interfacce. Un tipo che implementa interfacce non espone necessariamente un costruttore. A seconda del livello di accesso del costruttore, è pertanto possibile che il codice all'interno del tipo generico non sia in grado di accedere a tale costruttore.
- La parola chiave `Class` o `Structure`. La parola chiave `Class` vincola un parametro di tipo generico forzandolo a richiedere che qualsiasi argomento di tipo passato sia un tipo di riferimento, ad esempio una stringa, una matrice, un delegato o un oggetto creato da una classe. La parola chiave `Structure` vincola un parametro di tipo generico forzandolo a richiedere che qualsiasi argomento di tipo passato sia un tipo di valore, ad esempio una struttura, un'enumerazione o un tipo di dati elementare. Non è possibile includere `Class` e `Structure` nella stessa parte `constraintlist`.
Il tipo specificato deve soddisfare tutti i requisiti inclusi in `constraintlist`.
I vincoli definiti su ciascun parametro di tipo sono indipendenti da quelli definiti sugli altri parametri di tipo.
## Comportamento
- **Sostituzione in fase di compilazione.** Quando si crea un tipo costruito da un elemento di programmazione generico, viene specificato un tipo definito per ciascun parametro di tipo. Il compilatore Visual Basic sostituisce il tipo specificato per ogni ricorrenza di `typename` all'interno dell'elemento generico.
- **Assenza di vincoli.** Se non si specifica alcun vincolo su un parametro di tipo, il codice è limitato alle operazioni e ai membri supportati dal [Object Data Type](../../../visual-basic/language-reference/data-types/object-data-type.md) per tale parametro.
## Esempio
Nell'esempio riportato di seguito viene illustrata la definizione di base di una classe dizionario generica, che comprende una funzione di base per l'aggiunta di una nuova voce al dizionario.
[!code-vb[VbVbalrStatements#3](../../../visual-basic/language-reference/error-messages/codesnippet/VisualBasic/type-list_1.vb)]
## Esempio
Poiché `dictionary` è generico, il codice che lo utilizza può creare a partire da tale elemento una vasta gamma di oggetti, ciascuno con le stesse funzionalità ma con effetto su tipi di dati diversi. Nell'esempio riportato di seguito viene illustrata una riga di codice che crea un oggetto `dictionary` con voci `String` e chiavi `Integer`.
[!code-vb[VbVbalrStatements#4](../../../visual-basic/language-reference/error-messages/codesnippet/VisualBasic/type-list_2.vb)]
## Esempio
Nell'esempio riportato di seguito viene illustrata la definizione di base equivalente generata dall'esempio precedente.
[!code-vb[VbVbalrStatements#5](../../../visual-basic/language-reference/error-messages/codesnippet/VisualBasic/type-list_3.vb)]
## Vedere anche
[Of](../../../visual-basic/language-reference/statements/of-clause.md)
[New Operator](../../../visual-basic/language-reference/operators/new-operator.md)
[Access Levels in Visual Basic](../../../visual-basic/programming-guide/language-features/declared-elements/access-levels.md)
[Object Data Type](../../../visual-basic/language-reference/data-types/object-data-type.md)
[Function Statement](../../../visual-basic/language-reference/statements/function-statement.md)
[Structure Statement](../../../visual-basic/language-reference/statements/structure-statement.md)
[Sub Statement](../../../visual-basic/language-reference/statements/sub-statement.md)
[Procedura: utilizzare una classe generica](../../../visual-basic/programming-guide/language-features/data-types/how-to-use-a-generic-class.md)
[Covarianza e controvarianza](../Topic/Covariance%20and%20Contravariance%20\(C%23%20and%20Visual%20Basic\).md)
[In](../../../visual-basic/language-reference/modifiers/in-generic-modifier.md)
[Out](../../../visual-basic/language-reference/modifiers/out-generic-modifier.md) |
Java | UTF-8 | 1,341 | 2.34375 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Dao;
import Modelo.Estadocivil;
import Modelo.Nivelhabilitacao;
import conexao.Conexao;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author MASSINGUE
*/
public class EstadocivilDao {
private Connection conexao;
public EstadocivilDao() throws SQLException{
conexao= Conexao.getConexao();
}
public List<Estadocivil> prencherstadocivil() throws SQLException{
CallableStatement stmt= this.conexao.prepareCall("call prencherestado()");
//stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
List<Estadocivil> divolve = new ArrayList<Estadocivil>();
if (rs!=null) {
while (rs.next()) {
Estadocivil ec=new Estadocivil();
ec.setIdestadocivil(rs.getInt(1));
ec.setEstado(rs.getString(2));
divolve.add(ec);
}
return divolve;
}else{
return null;
}
}
}
|
C# | UTF-8 | 1,937 | 2.5625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Assets.Scripts.Magic;
using UnityEngine;
using UnityEngine.Assertions;
namespace Assets.Scripts.Map
{
public class MapModel : MonoBehaviour
{
public List<TileModel> Tiles { get; set; }
private Dictionary<MyHexPosition, MagicType> _residentMagicMap = new Dictionary<MyHexPosition, MagicType>();
public bool HasTileAt(MyHexPosition position)
{
return Tiles.Where(c => c.Position.Equals(position)).Any(c => !c.IsDisabled);
}
public TileModel GetTileAt(MyHexPosition position)
{
return Tiles.First(c => c.Position.Equals(position));
}
public MapModel Clone()
{
return new MapModel()
{
Tiles = Tiles.Select(c => c.Clone()).ToList()
};
}
public void Reset()
{
_residentMagicMap = new Dictionary<MyHexPosition, MagicType>();
Tiles.ForEach(c => c.MyReset());
}
public void DisableAt(MyHexPosition position)
{
GetTileAt(position).IsDisabled = true;
}
public void AddResidentMagic(MyHexPosition position, MagicType magic)
{
Assert.IsFalse(_residentMagicMap.ContainsKey(position),$"There is arleady magic at ${position}");
Assert.IsTrue(HasTileAt(position));
_residentMagicMap[position] = magic;
GetTileAt(position).ApplyWindMagic(); //todo TL1
}
public bool IsRepeatField(MyHexPosition target) //todo technical loan TL1
{
return _residentMagicMap.ContainsKey(target) && _residentMagicMap[target] == MagicType.Wind;
}
public bool HasProjectileableTileAt(MyHexPosition position)
{
return Tiles.Any(c => c.Position.Equals(position));
}
}
}
|
Python | UTF-8 | 3,651 | 2.78125 | 3 | [] | no_license | import datetime
import pandas as pd
import random
LABEL_UNKNOWN = 'Unknown'
LABEL_OTHER = 'Other'
class ClassificationModel:
def __init__(self, train_df, test_df, output_label):
self.train_df = train_df
self.test_df = test_df
self.output_label = output_label
self.category_encode = None
self.seed = 28
@property
def features(self):
return self.train_df[[c for c in self.train_df.columns if c != self.output_label]]
@property
def output(self):
return self.train_df[self.output_label]
def get_type_features(self, dtype):
return [f for f, t in self.features.dtypes.items() if t == dtype]
def drop_feature(self, feature):
self.train_df.drop(feature, axis=1, inplace=True)
def get_uncorrelated_features(self, candidates):
timestamp_print('Computing correlations')
corr_df = self.train_df[candidates].corr()
corrs_info = get_correlated_columns_info(corr_df)
while len(corrs_info) > 0:
corrs_info = corrs_info.sort_values(['n_corr', 'avg_corr'], ascending=False)
to_remove = corrs_info.index[0]
timestamp_print('Removing %s' % to_remove)
corr_df = corr_df.drop(to_remove, axis=0).drop(to_remove, axis=1)
candidates.remove(to_remove)
corrs_info = get_correlated_columns_info(corr_df)
return candidates
def split_train(self, validation_pct=0.2, how='random', sort=True):
if how != 'random':
raise NotImplementedError()
n_val = int(len(self.train_df) * validation_pct)
random.seed(self.seed)
val_idx = random.sample(self.train_df.index, n_val)
train_idx = [i for i in self.train_df.index if i not in val_idx]
train_df = self.train_df.loc[train_idx]
val_df = self.train_df.loc[val_idx]
if sort:
train_df = train_df.sort_index()
val_df = val_df.sort_index()
train_out = train_df[self.output_label]
train = train_df.drop(self.output_label, axis=1)
val_out = val_df[self.output_label]
val = val_df.drop(self.output_label, axis=1)
return train, train_out, val, val_out
@property
def x_train(self):
train_features = [c for c in self.train_df.columns if c != self.output_label]
return self.train_df[train_features].as_matrix()
@property
def y(self):
return self.train_df[self.output_label].as_matrix()
@property
def x_test(self):
return self.test_df.as_matrix()
def timestamp_print(msg):
print ('[%s] %s' % (get_current_timestamp().replace(microsecond=0), msg))
def get_current_timestamp():
return datetime.datetime.now()
def one_hot_encode(df, category_encode):
timestamp_print('Encoding features')
for c, enc in category_encode.items():
df[c] = df[c].apply(lambda x: enc.get(x, LABEL_OTHER))
new_features = pd.get_dummies(df)
# Remove Other columns
cols = [c for c in new_features.columns if '_'+LABEL_OTHER not in c]
# Join to DataFrame
df = new_features[cols]
return df
def get_correlated_columns_info(corr_df):
corr_df_s = abs(corr_df.stack())
# Get correlated features
corr_threshold = 0.9
corrs = corr_df_s.loc[[i for i in corr_df_s.index if i[0] != i[1]]]
corrs = corrs[corrs > corr_threshold]
corrs_info = {
f: {'n_corr': len(corrs.loc[f]), 'avg_corr': corrs.loc[f].mean()}
for f in corrs.index.levels[0]
}
corrs_info = pd.DataFrame.from_dict(corrs_info, orient='index')
return corrs_info[corrs_info['n_corr'] > 0]
|
C++ | UTF-8 | 4,526 | 3.015625 | 3 | [] | no_license | #include "TXLib.h"
const int PAUSE = 0;
const int SUIT_SPADES = 0,
SUIT_HEARTS = 1,
SUIT_CLUBS = 2,
SUIT_DIAMONDS = 3,
SUIT_FACE1 = 4,
SUIT_FACE2 = 5,
TOP_SPACE = 50;
const int N = 13;
struct Page {
int page_X;
int page_Y;
HDC page_img;
};
void create_arr (int *a);
void output_arr (int *a, Page* p, bool open);
void swap_card (int *a, Page* p, int card1, int card2);
int main() {
txCreateWindow (1200, 400);
txSetFillColor (TX_GREEN);
txClear();
HDC page_img = txLoadImage ("page_small.bmp");
int pageX = txGetExtentX (page_img);
int pageY = txGetExtentY (page_img);
Page page = {pageX, pageY, page_img};
HDC card_img = txLoadImage ("Cards.bmp");
int cardX = txGetExtentX (card_img);
int cardY = txGetExtentY (card_img);
Page card = {cardX, cardY, card_img};
int a [N];
create_arr (a);
output_arr (a, &card, true);
output_arr (a, &card, false);
bool perestanovka = true;
while (perestanovka) {
output_arr (a, &card, false);
perestanovka = false;
for (int i = 0; i<N-1; i++){
swap_card (a, &card, i, i+1);
if (a[i] > a[i+1]) {
perestanovka = true;
std::swap( a[i], a[i+1]);
};
}
}
txDeleteDC (card_img);
return 0;
}
void create_arr (int *b){
for (int i = 0; i<N; i++){
b[i] = rand()%N;
}
}
void output_arr (int *a, Page* p, bool open){
int card_suit = SUIT_FACE2;
if (open) {
card_suit = SUIT_DIAMONDS;
}
int card_range = 0;
for (int i = 0; i<N; i++) {
if (open) {
card_range = a[i];
}
else {
card_range = 2;
}
txSleep(100);
txAlphaBlend (txDC(), 20+i*90, TOP_SPACE, p -> page_X / 13, p -> page_Y / 6, p -> page_img, (p -> page_X / 13)*card_range, (p -> page_Y / 6)*card_suit );
}
//$x (p -> page_X);
txSleep (10);
}
void swap_card (int *a, Page* p, int card1, int card2){
int card_suit = SUIT_DIAMONDS;
int card_range = a[card1];
txAlphaBlend (txDC(), 20+card1*90, TOP_SPACE, p -> page_X / 13, p -> page_Y / 6, p -> page_img, (p -> page_X / 13)*card_range, (p -> page_Y / 6)*card_suit );
card_range = a[card2];
txAlphaBlend (txDC(), 20+card2*90, TOP_SPACE, p -> page_X / 13, p -> page_Y / 6, p -> page_img, (p -> page_X / 13)*card_range, (p -> page_Y / 6)*card_suit );
txSleep (1000);
if (a[card1] > a[card2]) {
card_range = a[card1];
for ( int i = TOP_SPACE; i <= TOP_SPACE + 120; i++ ) {
txSetColor (TX_GREEN);
txSetFillColor (TX_GREEN);
txRectangle (20+card1*90, i-1, 20+card1*90 + 90, i+120);
txAlphaBlend (txDC(), 20+card1*90, i, p -> page_X / 13, p -> page_Y / 6, p -> page_img, (p -> page_X / 13)*card_range, (p -> page_Y / 6)*card_suit );
txSleep (PAUSE);
}
card_range = a[card2];
for ( int i = 20+card2*90; i >= 20+card1*90; i-- ) {
txSetColor (TX_GREEN);
txSetFillColor (TX_GREEN);
txRectangle (i, TOP_SPACE, i + 90, TOP_SPACE+120);
txAlphaBlend (txDC(), i, TOP_SPACE, p -> page_X / 13, p -> page_Y / 6, p -> page_img, (p -> page_X / 13)*card_range, (p -> page_Y / 6)*card_suit );
txSleep (PAUSE);
}
card_range = a[card1];
for ( int i = 20+card1*90; i <= 20+card2*90; i++ ) {
txSetColor (TX_GREEN);
txSetFillColor (TX_GREEN);
txRectangle (i-1, TOP_SPACE+120, i + 90, TOP_SPACE+120+120);
txAlphaBlend (txDC(), i, TOP_SPACE+120, p -> page_X / 13, p -> page_Y / 6, p -> page_img, (p -> page_X / 13)*card_range, (p -> page_Y / 6)*card_suit );
txSleep (PAUSE);
}
card_range = a[card1];
for ( int i = TOP_SPACE+120; i > TOP_SPACE; i-- ) {
txSetColor (TX_GREEN);
txSetFillColor (TX_GREEN);
txRectangle (20+card2*90, i-1, 20+card2*90 + 90, i+120);
txAlphaBlend (txDC(), 20+card2*90, i, p -> page_X / 13, p -> page_Y / 6, p -> page_img, (p -> page_X / 13)*card_range, (p -> page_Y / 6)*card_suit );
txSleep (PAUSE);
}
}
return ;
}
|
C++ | UTF-8 | 4,463 | 2.625 | 3 | [] | no_license | /* DUO VERSION
=================================================================================
XBEE 868Mhz - RS485 Node Transparent Mode - With RX/TX and power LEDs
=================================================================================
- Pin 20 used for RS485 direction control
- Pin 13 turned off
- Pin A1 LED blinks when data is transmitted
- Pin A0 LED blinks when data is received
- Pin A2 Software power indicator LED
=================================================================================
Written for the Arduino DUO Board.
Richard Wilson
AKVA Group Scotland Ltd
Software Revision 5.0.0 Released
Parity Version (868Mhz Xbee) with commands
=================================================================================
*/
#define XBEE_RX 16 // Serial Receive pin (RS485 R Pin)
#define XBEE_TX 17 // Serial Transmit pin (RS485 D Pin)
#define SSerialTxControl 20 // RS485 Direction control (Pin 20)
#define RS485Transmit HIGH // define constant HIGH
#define RS485Receive LOW // define constant LOW
#define Pin13LED 13 // define flag pin
#define RX_LED A0 // define receive LED pin (BLUE)
#define TX_LED A1 // define transmit LED pin (GREEN)
#define PowerLED A2 // define software power LED pin (RED)
#define IsMaster 12 // Master / Slave Jumper HIGH = Slave Mode
byte byteFromXBEE;
byte byteFromRS485;
byte Send2Xbee;
byte Send2RS485;
int PingFlag = 0;
int i = 0;
bool skipThisSend = false;
int DayCounter = 0;
unsigned long milliSeconds;
void LoopLEDs()
{
for (i=0; i < 10; i++)
{
digitalWrite(TX_LED, 1);
delay(200);
digitalWrite(TX_LED, 0);
delay(200);
digitalWrite(RX_LED, 1);
delay(200);
digitalWrite(RX_LED, 0);
delay(200);
digitalWrite(PowerLED, 1);
delay(200);
digitalWrite(PowerLED, 0);
delay(200);
}
digitalWrite(TX_LED, 0);
digitalWrite(RX_LED, 0);
digitalWrite(PowerLED, 1);
}
void setup()
{
pinMode(Pin13LED, OUTPUT); // setup IO pins
pinMode(RX_LED, OUTPUT);
pinMode(TX_LED, OUTPUT);
pinMode(PowerLED, OUTPUT);
pinMode(SSerialTxControl, OUTPUT);
pinMode(IsMaster,INPUT_PULLUP); // LOW = Master (default HIGH using no jumper with pullups)
// Serial.begin(9600); // P USB Port
Serial1.begin(9600,SERIAL_8E1); // RS485 Port (Sensor)
Serial2.begin(9600); // XBEE Port (XBEE)
digitalWrite(SSerialTxControl, RS485Receive); // Set RS485 Testing only
digitalWrite(PowerLED,HIGH); // Turn on power LED
digitalWrite(TX_LED,LOW); // Turn off power LED
digitalWrite(RX_LED,LOW); // Turn off power LED
digitalWrite(Pin13LED,LOW); // Turn off Pin 13 LED
LoopLEDs(); // LT Leds and wait for connections to stabilise
}
void loop() {
// Each character takes 104 microseconds to transmit
delayMicroseconds(500); // MUST BE 500 for AKVA CONNECT !!!
// RS485 Port Read ==============================================
if (Serial1.available())
{
Send2Xbee = Serial1.read(); // Read the byte
digitalWrite(RX_LED, HIGH); // Show activity
delayMicroseconds(80);
Serial2.write(Send2Xbee);
//delayMicroseconds(1200); // was 80
digitalWrite(RX_LED, LOW);
}
// XBee Port Read ===============================================
if (Serial2.available())
{
digitalWrite(TX_LED, HIGH);
digitalWrite(SSerialTxControl, RS485Transmit); // Disable RS485 Transmit
Send2RS485 = Serial2.read(); // Read the byte
//delayMicroseconds(1200);
Serial1.write(Send2RS485); // Send btye to RS485
delayMicroseconds(2000); // <<< -- Vital must be at least 2000 (AKVA COPNNECT)
digitalWrite(SSerialTxControl, RS485Receive); // reset RS485 to receive
digitalWrite(TX_LED, LOW);
}
else
{
digitalWrite(SSerialTxControl, RS485Receive); // reset RS485 to receive
delayMicroseconds(2000); // <<< -- Vital must be at least 2000 (AKVA COPNNECT)
}
}
|
Shell | UTF-8 | 855 | 3.5 | 4 | [] | no_license | #!/bin/bash
default_action="s"
action=${1:-$default_action}
if [ $action == "s" ]; then
#запускаем скрипт start.sh
start-stop-daemon -Sbmp /var/www/html/mainpid -x /var/www/html/modules/start.sh
echo 'Для завершения записи необходим параметр: e';
elif [ $action == "e" ]; then
#запускаем скрипт end.sh
pid=`cat /var/www/html/mainpid`
if [ $pid == 0 ]; then
echo 'Приложение не запущено'
exit;
fi
php /var/www/html/modules/end.php
date=`date +%Y-%m-%d:%H:%M:%S`
start-stop-daemon -Kp /var/www/html/mainpid
#rm /var/www/html/mainpid
echo '0' > /var/www/html/mainpid
echo '<p><font color=red>'${date}' Приложение завершено. Процесс: '${pid}'</font></p>'>>/var/www/html/log.txt
echo 'Приложение завершает работу.';
fi
|
Markdown | UTF-8 | 11,570 | 2.578125 | 3 | [] | no_license | # -树莓派智能安防摄像头(Smart security camera for home use by Raspberry-Pi)

## -目录(Catalogue)
- [-描述(Description)](#-描述description)
- [-详细功能(detailed function)](#-详细功能detailed-function)
- [-为什么使用树莓派(Why Raspberry Pi?)](#-为什么使用树莓派why-raspberry-pi)
- [- 如何使用(How to do)](#--如何使用how-to-do)
- [step1-准备工具(tool)](#step1-准备工具tool)
- [step2-配置Raspberry Pi(deploy)](#step2-配置raspberry-pideploy)
- [step3-测试相机(To test the camera)](#step3-测试相机to-test-the-camera)
- [1) 现在让我们用树莓派拍一张照片吧~](#1-现在让我们用树莓派拍一张照片吧)
- [2) 现在让我们用一段简单的代码测试一下吧](#2-现在让我们用一段简单的代码测试一下吧)
- [step4-移动物体目标检测(Moving object detection)](#step4-移动物体目标检测moving-object-detection)
- [step5-人脸检测(MTCNN)](#step5-人脸检测mtcnn)
- [step6-人脸识别(Face Recognition)](#step6-人脸识别face-recognition)
- [step7-定时录像(Regular mail)](#step7-定时录像regular-mail)
- [step8-非家庭成员入侵发邮件报警(Stanger call the police)](#step8-非家庭成员入侵发邮件报警stanger-call-the-police)
- [step9-ShuffleNet轻量级模型](#step9-shufflenet轻量级模型)
- [-性能描述](#-性能描述)
## -描述(Description)
RPi-AI-Camera是一款智能AI摄像头,具有人形侦查预警器。
通过识别移动的物体,抓取人脸图像对比家庭成员信息来判别出外人入侵的情况,从而做到邮件预警的功能
## -详细功能(detailed function)
* 移动物体的追踪定位框选
* 通过人脸识别技术,对非家庭成员入侵邮件预警预警
* 实时录像以减轻内存负担
* 对摔倒行为发送警告邮件
**GitHub仓库:** [yuaaaaaa/RPi-AI-CAMERA](https://github.com/yuaaaaaa/RPi-AI-CAMERA.git)
## -为什么使用树莓派(Why Raspberry Pi?)
树莓派是一个只有信用卡大小的微型电脑,可以完成各种任务,基于他体型小的特点,可以用于家用微型摄像仪的载体。
这款Linux系统的计算机可以在低耗的情况下完成各种预期功能。
[了解更多](https://baike.so.com/doc/6240059-6453436.html)
## - 如何使用(How to do)
### step1-准备工具(tool)
* **硬件设备**
* 树莓派(Raspberry-Pi)
* 树莓派搭载摄像头(Raspberry Pi camera module)
* **软件设备**
* Python3
* openCV
### step2-配置Raspberry Pi(deploy)
* 确认openCV模块安装
```
进入Raspberry Pi命令界面
进入Python编译器
>> python
测试opencv模块是否安装成功
>> import cv2
```
安装成功就可以进入下一步啦,如果出现了错误[点击这里](https://blog.csdn.net/kyokozan/article/details/79192646)
* 确认camera模块启动
```
// 尝试以下命令
ls -al /dev/ | grep video
// 当看到'video0 device'时表明摄像头模块已启动
```
### step3-测试相机(To test the camera)
#### 1) 现在让我们用树莓派拍一张照片吧~
```
// 拍摄一张照片 并命名为image.jpg存到本地
raspistill -o image.jpg
```
#### 2) 现在让我们用一段简单的代码测试一下吧
首先打开你的树莓派编译器,然后输入以下代码
```py
import cv2
cap = cv2.VideoCapture(0)
// 设置窗口的宽和高
cap.set(3,640)
cap.set(4,480)
while(True):
ret, frame = cap.read()
if ret:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', frame)
cv2.imshow('gray', gray)
k = cv2.waitKey(30) & 0xff
if k == 27: # press 'ESC' to quit
break
cap.release()
cv2.destroyAllWindows()
```
执行以上代码以后会出现两个运行窗口,frame和gray
在这里我们添加gray窗口是为了后续便于方便计算

### step4-移动物体目标检测(Moving object detection)
[代码仓库地址](https://github.com/yuaaaaaa/RPi-AI-CAMERA/blob/main/Project/%E9%99%88%E9%9B%A8%E6%99%B4/%E8%BF%90%E5%8A%A8%E7%89%A9%E4%BD%93%E6%A3%80%E6%B5%8B%E6%A1%86%E9%80%89.ipynb)

**tips:**
* 高斯模糊
高斯模糊是一种广泛使用的图形软件的方法,通常会减少图像噪声和减少细节,适用于很多的场合和情景;
高斯模糊的核心就是取中心点周围所有像素点的均值作为自己的像素值,以此来达到平滑效果;
在本例中使用高斯模糊对的原因:每个输入的视频都会因自然震动、光照变化或者摄像头本身等原因而产生噪声。对噪声进行平滑是为了避免在运动和跟踪时将其检测出来。
* 二值化阈值处理
二值化阈值处理就是将图像上的像素点的灰度值设置为0或255,也就是将整个图像呈现出明显的只有黑和白的视觉效果。
在本例中对于每个从背景之后读取的帧都会计算其与背景之间的差异,并得到一个差分图(different map),
还需要应用阈值来得到一幅黑白图像,并通过下面代码来膨胀(dilate)图像,
从而对孔(hole)和缺陷(imperfection)进行归一化处理。
### step5-人脸检测(MTCNN-多任务卷积神经网络)
[代码仓库地址](https://github.com/yuaaaaaa/Raspberry-FaceRecognition-SecurityCamera/blob/main/Project/net/mtcnn.py)

**tips:**
* P-Net:构造是一个全卷积网络,这一部分的基本思想是使用较为浅层、较为简单的CNN快速生成人脸候选窗口。
* R-Net:构造是一个卷积神经网络增加了一个全连接层,相对于P-Net更复杂的网络结构来对P-Net生成的可能是人脸区域区域窗口进行进一步选择和调整,从而达到高精度过滤和人脸区域优化的效果。
* O-Net:基本结构是一个较为复杂的卷积神经网络,相对于R-Net来说多了一个卷积层.使用更复杂的网络对模型性能进行优化.
### step6-人脸识别(Face Recognition)
[数据集:该数据集包含了来自500个人的2500张亚洲人脸图片,非限制场景下的人脸识别。提取码:o0ty](http://pan.baidu.com/s/1bpIvkLp)
[代码仓库地址](https://github.com/yuaaaaaa/Raspberry-FaceRecognition-SecurityCamera/blob/main/Project/net/inception.py)

**tips:**
* 通过ShuffleNet卷积神经网络将检测到的人脸图像转换为128维人脸特征向量,与标准库内已知家庭人脸进行比对。
### step7-定时录像(Regular mail)
[代码仓库地址](https://github.com/yuaaaaaa/RPi-AI-CAMERA/blob/main/Project/%E8%AE%B8%E4%BA%A6%E6%9D%A8/%E5%AE%9E%E7%8E%B0%E5%BD%95%E5%83%8F.ipynb)
```python
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
#创建VideoWrite对象,10是fps(每秒读取的帧数),(640,480)是屏幕大小
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('./cameraoutput.avi', fourcc, 25, (640,480))
video_len = 250
if cap.isOpened():
while(video_len>0):
'''
cv2.VideoCapture(0).read()
功能:读取一帧的图片
参数:无
返回值:1.(boolean值)是否读取到图片
2.一帧图片
'''
ret, frame = cap.read()
#保存写入这一帧图像frame:
out.write(frame)
#显示这一帧图像frame:
cv2.imshow("capture", frame)
#当按下'q'键时退出:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_len -= 1
cap.release()
out.release()
cv2.destroyAllWindows()
```
**tip:**
* 定时录像
当画面静止时间超过6s时,该摄像系统将不再录像记录,以达到节省本地内存的优点
### step8-非家庭成员入侵发邮件报警(Stanger call the police)
[代码仓库地址](https://github.com/yuaaaaaa/RPi-AI-CAMERA/blob/main/Project/%E8%AE%B8%E4%BA%A6%E6%9D%A8/%E9%82%AE%E4%BB%B6%E5%8F%91%E9%80%81%EF%BC%88%E6%91%84%E5%83%8F%E5%A4%B4%E6%8B%8D%E6%91%84%E7%85%A7%E7%89%87%E5%8F%91%E9%80%81%EF%BC%89.ipynb)
```python
"""
Created on Sun Nov 29 17:16:14 2020
@author: 32991
"""
import cv2
import smtplib
import sys
import os
import time
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#设置参数:
smtpserver = '3299115821@qq.com' # smtp服务器
username = '3299115821@qq.com' # 发件邮箱账号
password = 'ndudpbtzsczddcac' # 邮箱登录密码
sender = '3299115821@qq.com' # 发件人
addressee = '3299115821@qq.com' # 收件人
exit_count = 10 # 尝试联网次数
path = os.getcwd() #获取图片保存路径
'''
os.getcwd() 方法
用于返回当前工作目录,无参数
'''
#构造邮件内容:
def setMsg(): # 下面依次为邮件类型,主题,发件人和收件人。
msg = MIMEMultipart('mixed')
msg['Subject'] = '出现非家庭成员!'
msg['From'] = '3299115821@qq.com <3299115821@qq.com>'
msg['To'] = addressee
text = "主人,出现非家庭成员!照片如下!" # 下面为邮件的正文
text_plain = MIMEText(text, 'plain', 'utf-8')
msg.attach(text_plain)
sendimagefile = open(path+'/person.jpg', 'rb').read() # 构造图片链接
image = MIMEImage(sendimagefile)
image["Content-Disposition"] = 'attachment; filename="people.png"' # 下面一句将收件人看到的附件照片名称改为people.png。
msg.attach(image)
return msg.as_string()
#实现邮件发送:
def sendEmail(msg):
#发送邮件
smtp = smtplib.SMTP()
smtp.connect('smtp.qq.com')
smtp.login(username, password)
smtp.sendmail(sender, addressee, msg)
smtp.quit()
msg = setMsg()
sendEmail(msg)
```
**效果渲染**
```邮件接收```

```不属于家庭成员情况```

```属于家庭成员情况```

```确认为家庭成员```

### step9-ShuffleNet轻量级模型
[代码仓库](https://github.com/yuaaaaaa/Raspberry-FaceRecognition-SecurityCamera/blob/main/Project/net/ShuffleNet2.py)

**tips:**
* GConv :组卷积,减少计算量
* 3*3 DWConv(S = 2):步长为2的深度可分离卷积,减少计算量
* Concat :连接层
* Channel Shuffle:来增强通道之间的相关性
### step9-摔倒识别(canny 边缘检测)

**tips:**
* 使用高斯滤波器,平滑图像,除燥
* 计算像素点的梯度强度和方向
* 应用非极大值抑制,消除边缘检测带来的杂散响应
* 应用双阈值检测来确定真实的边缘 推荐高低阈值比 T2/T1 =3:1 or2:1
* 通过抑制孤立的弱边缘,来最终完成边缘检测
* 根据人体比例判断状态:Walking,Falling,Fallen
## -性能描述
| | 移动物体识别 | 人脸识别 | 邮件发送 | 定时录像 | 摔倒识别 |
|-------------| ---------- | ------- | ------ | ------- | ------- |
|联想 YOGA i7 8G| 31.27 | 49.98 | 1564.65 | 3732.48 | 78.74 |
|Raspberry ZeroW| 93.81 | 149.94 | 1428.20 | 22.18 | 198.63 |
|
Java | UTF-8 | 2,850 | 2.390625 | 2 | [] | no_license | package ru.mirea.app.schedule;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by Senik on 12.03.2015.
*/
public class ScheduleAdapter extends android.support.v4.widget.CursorAdapter {
public boolean useNowLayout = true;
public int VIEW_TYPES = 2;
public int VIEW_TYPE_DEF = 0;
public int VIEW_TYPE_CURRENT = 1;
// Running smoothly
public static class ListItemViewHolder {
public final TextView subjectView;
public final TextView durationView;
public final TextView roomView;
public final TextView posView;
public ListItemViewHolder(View v) {
subjectView = (TextView) v.findViewById(R.id.list_item_subject);
durationView = (TextView) v.findViewById(R.id.list_item_duration);
roomView = (TextView) v.findViewById(R.id.list_item_room);
posView = (TextView) v.findViewById(R.id.list_item_pos);
}
}
public ScheduleAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ListItemViewHolder viewHolder = (ListItemViewHolder) view.getTag();
String className = cursor.getString(ScheduleFragment.COLUMN_CLASS_NAME);
String classPos = Integer.toString(cursor.getInt(ScheduleFragment.COLUMN_CLASS_POS));
String duration = Utility.getDurationForPos(cursor.getInt(ScheduleFragment.COLUMN_CLASS_POS));
String room = cursor.getString(ScheduleFragment.COLUMN_ROOM);
viewHolder.subjectView.setText(className);
viewHolder.durationView.setText(duration);
viewHolder.roomView.setText(room);
viewHolder.posView.setText(classPos);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int viewtype = getItemViewType(cursor.getInt(ScheduleFragment.COLUMN_CLASS_POS));
int layout = -1;
layout = viewtype == VIEW_TYPE_CURRENT ? R.layout.schedule_listview_item_current : R.layout.schedule_listview_item;
View view = LayoutInflater
.from(context)
.inflate(layout, parent, false);
ListItemViewHolder viewHolder = new ListItemViewHolder(view);
view.setTag(viewHolder);
return view;
}
public void setUseNowLayout(boolean use) {
useNowLayout = use;
}
@Override
public int getItemViewType(int classPos) {
return (classPos == Utility.getClassPosNow() && useNowLayout && Utility.getClassPosNow() != 0) ? VIEW_TYPE_CURRENT : VIEW_TYPE_DEF;
}
@Override
public int getViewTypeCount() {
return VIEW_TYPES;
}
}
|
Markdown | UTF-8 | 12,452 | 3.171875 | 3 | [] | no_license | ---
title: 网络时代,基督徒凡事都要规规矩矩地照着次序行
author: sweditor3
type: post
date: 2018-11-29T02:38:26+00:00
url: /2018/11/29/网络时代基督徒凡事都要规规矩矩地照着次序行/
categories:
- 《@守望》第120期——面对数字化产品
---
<p style="text-align: center;">
<span style="font-size: 12pt;">文/晓峰 牧师</span>
</p>
**<span style="font-size: 12pt;">经文:</span>**
**<span style="font-size: 12pt;">哥林多前书14:40 凡事都要规规矩矩地按着次序行。</span>**
<span style="font-size: 12pt;">这一节经文主要的词语有两个,一个是“次序”,一个是“规规矩矩”。“次序”这个词的涵义就是圣经里面所说的那个“按照班次”的“班次”,也就是我们平时所理解的“秩序,顺序”的意思。这个词在教会内,我们就可以把它理解成是我们在处理教会事务时所遵循的事先的约定、规则和先后的顺序。其实任何一个团体都有次序,不存在无次序的团体。任何一个教会都有他的治理模式和决策方式,不存在无治理模式的教会。一个教会的“次序”,大致有三种形态,第一种形态是惯例,就是约定俗成,虽然没有明确各自的分工、职责,但在历史中大家都已经这么认为了;第二种形态是没有书面的约定,但有口头明确的彼此约定,第三种形态就是有成文书面的明确治理约定和方式,就是章程。</span>
<span style="font-size: 12pt;">秩序的本质是什么呢?秩序的本质就是约,就是我们事先通报、商量、达成一致,就成为一个彼此之间的约定,这是次序的本质。人类社会的任何团体,人与人之间的关系,包括上帝跟人之间的关系,都是靠约来进行的,没有约就叫混乱,我们的神不是混乱的神。所以我刚才一直说任何一个教会都有他特有的治理模式,不是有和没有的区别,而是好与不好的区别。那这跟圣灵在教会当中的带领有冲突吗?有时候我们一谈起圣灵的工作,似乎圣灵的工作都是那种个人化的、突如其来的、不可捉摸的,甚至有时候我们会有一种想法,教会里面一旦有预先定好的规则,是不是就限制了圣灵的工作,好像规则、次序这些事物跟圣灵的工作是有冲突和矛盾的,其实不然,秩序就是神所设立的,圣灵的工作也不会跟秩序相冲突,反而圣灵的工作常常是在秩序当中进行的。就像我们教会的章程,我们凭着信心说这是圣灵在我们教会带领我们制定出来,适合我们这个群体在这个特定时代里面所采用的治理模式和议事规则,这里面有圣灵的带领。因此圣灵在教会当中的工作,常常是靠着职分、分工、模式、次序来进行的。最典型的例子就是摩西在旷野的时候,他一个人治理这两百万人,所有的事情都提交到他这里,最终还是他的岳父叶忒罗跟他说“你这样不行,太累了,不单你累,百姓也累,效率极低”,所以给摩西的建议就是选出那些有智慧、敬畏神、又有能力的人来做官长,其实相当于开始分权和分工,每个人有不同的职分和责任,这样的话,不单使摩西的治理变得轻松了,而且在那个时刻,上帝的百姓从一个混乱的乌合之众的状态成为了真正在上帝面前开始有秩序来侍奉神的群体了,到后来你会发现,连他们的会幕、扎营的次序和方位在圣经里面都有非常条理的记录,到了所罗门在位的时候,所罗门更是有非常严谨成体系化的治理模式。在新约的时候,当教会出现一些在饮食方面的问题的时候,也是用选立了七位执事的方式来解决这个问题,更不用说选立长老和监督是保罗一直让提摩太和提多在各教会去推动的事情。圣灵的工作和秩序之间没有冲突,相反,如果一个人号称他有从圣灵来的感动,却破坏了秩序,不照着次序行事,即使真的是圣灵的感动也会造成负面的影响。</span>
<span style="font-size: 12pt;">我们来看“规矩“这个词的意思是什么。这里面的”规规矩矩“这个词,就是保罗在《罗马书》里面所用的“端正”那个词(罗马书13:13 行事为人要端正,好像行在白昼),所以这句经文在吕振中译本里面就直接翻译为“一切都要端端正正按次序行”,它的意思就是要用正确的、端庄的、合宜的方式照着次序行。“次序”说明的是在教会当中治理的模式和做事的顺序,而“规规矩矩”所表明的是我们对于秩序的尊重,但不仅是对于秩序的尊重,你还要透彻地知道那个秩序是什么,你才可能真的尊重它。不单单是心态,这时候就上升到另一个层面了,就是我得去了解那个规矩到底是什么。而且,还有内心里面的坦荡和光明,我所行的不是出于我自己的私欲。有时候人对于规则,表面上看起来他没有违反,实际上他利用了这个规则,他利用规则达到了他个人的目的,这个事实上也是对于规则的破坏。公然地违反规则,这就不是规规矩矩了,利用规则更不是规规矩矩。</span>
<span style="font-size: 12pt;">网络时代的特点是信息的即时性,过去的传统媒体达不到这样的效果,传统的媒体,有一件事情要传到你耳中,总得经过一段时间,网络可不是这样,信息在极短的时间内就可以让大范围的人群知晓,立刻就可以变为一个公共发言了,这对于我们今天的时代是一个非常大的挑战,我们很多人或许还没有准备好自己来使用如此快捷的信息发布工具。因为它快,所以很多时候你可能想得没有那么周全,因为它快,所以我们内心当中很多人性的软弱就会如此轻易地被暴露出来,也因为它特别快,所以它暴露出来之后所影响的范围、蔓延的速度是你不能够控制的,甚至那个后果可能都是你没有想到的。网络时代对于基督徒群体的挑战在哪呢?就是我们应该规规矩矩地照着次序行,用这样的方式来处理就可能会避免很多问题。比如说我们有一个什么样的想法,我们必须知道我们处在一个群体中,你不是一个单独的个体,你不是可以任意行事的一个个体,你必须考虑到你说的话和你做的事对于周围跟你有密切关系的人是有极大影响的,这是我们必须意识到的。如果你心里真的有一个想法,你想做一件事,建议你先跟身边熟悉和信任的弟兄姊妹沟通一下,要祷告,如果你一分享,你熟悉的弟兄姊妹跟你说“这事我们也把握不准”,就可以跟教会的牧者之间有沟通。可能大家会觉得,岂不是我们又回到过去传统的媒体时代了吗?是的,我们必须用传统的方式来应对今天的网络时代。用圣经里古老的智慧来处理今世的事情。不要那么快速地就向全世界来广播,你要知道,广播之后的后果是你不可把握的,而且广播之后的后果反过来会对你有影响,这就是我们人性当中的特点。有时候你把话说了,你发现收不回来了,哪怕你觉得不妥,但就因为你已经说了,所以你说出去的那个立场反过来就影响了你,你就开始为那个立场来辩护了,于是你越发在一个你都觉得不妥当的立场上被坚定了,不是因为它对,只是因为你说了,而别人也知道了,这就是网络的即时性所带来的负面的效果。你要知道,人性的特点是不容易道歉,人是不容易认错的。</span>
<span style="font-size: 12pt;">网络时代信息的另一个特点叫个人化和碎片化,所谓的个人化和碎片化,就是很多时候它是一个人内心里面的感受,很多时候它是一个主观性的东西,它不具有客观性,也不整全。所以你会发现,有时候一个事情发生之后,网上出来的那个对信息的披露跟事实本身之间有非常大的差距,甚至有人是故意误导,人性的恶在网络上有一个特点就是不用负责任,虽然说造谣是要负法律责任的,但是那个追究成本有时可能很高,说完之后他立刻就消失了,反正他说完之后也不用负责任,人内心当中的恶在网络上有时候更容易被显露出来。几年以前,王怡牧师曾经说过“如果你要是让听你说话的那个人没有意识到你是一个基督徒,那你就不要在网上发言”。这是他对网络时代的一个建议,他针对的正是那个可以不用负责任,可以任意地把内心当中的猜测、想法给说出来,还会带来很多负面影响的发言者。网络就把人性中那种一吐为快和引导舆论的快感和操纵感给放大了。网络时代的这种碎片化和情绪化,基本上对人是负面影响。</span>
<span style="font-size: 12pt;">怎么来处理这个问题呢?圣经的原则也很清楚,依然是“规规矩矩地按着次序行”。你不要只听那一个人说的,旧约里面说“如果有人犯了必死的罪,你总要治死他,但是不可凭一个人的见证,要凭两三个人的见证”。到了新约,保罗在《提摩太前书》里面就特别论到说“控告长老的呈子,非有两三个见证人就不要收”。你要知道,任何事情只要往公众层面一放就是大事,因为它影响面很大,所以,不要只听一面之词,心里要有一个谨慎和分辨的想法。</span>
<span style="font-size: 12pt;">圣经的原则,除了我们今天所讲的“规规矩矩地按着次序行”,还有一个人与人之间的关联的层面,尤其是在教会当中,你必须要考虑到你在这个群体里面。所以任何事情,我的建议是先在我们群体当中,先跟你熟悉的人,不行的话可以放在小组的层面分享,大家一起来祷告,再不行的话可以放在教会的牧者层面去沟通,如果先在我们教会内达成一致了,这个声音以教会层面来发声更好,如果教会层面觉得个人发声更好,那就个人来发声。但是,今天这个时代的特点,网络加强了个人主义,我们有时候把个人跟一个团体完全分开了,应对的策略就是在一个群体内的次序中来处理自己的发声。在这里我把这个“规规矩矩”做了一点点扩展,第一个就是,我们必须要意识到我们每一个人身份的归属,你的身份很多的时候就决定了你说话的方式和界限,你的身份就决定了有些话你可以说,有些话你不能讲,所以,我们要想到我们所属的这个群体。第二个,用《传道书》的经文就是“你到神的殿要谨慎脚步,神在天上,你在地下,所以你的言语要寡少”,说话要谨慎,尽量少说话。第三个原则是我们今天这个时代不容易处理的,就是不要把感觉当成事实。我们分不清我们的感受和事实之间的关系,我不是说感受不重要,也不是说你的感受不真实,感受很重要,感受也是真的,但你就停在这儿就可以了,因为你的感受不一定是事实。你可以说你的感受,你说“我现在真的很难过,真的很愤怒”,这都是真的,但人家可能没做错事,你就处理你的愤怒就行了。而我们现在的特点是,我只要一愤怒,我就要去处理他,因为是他说了一句话让我愤怒了,但人家说那句话不一定有错。所以,我们要学会分清感觉和事实。甚至,可能很多时候你的感觉是准确的,但感觉不能作为判定一件事情的最终凭据。在不伤害另一个人的前提下,你凭着感觉做选择没有什么太大的问题,但是一旦涉及到了另外一个人的利益、名声和福祉,你的感觉就不能作数了。</span>
<span style="font-size: 12pt;">惟愿神赐给我们在这个特殊时代里面敬虔生活的智慧,不被这个时代的洪流所挟裹。</span>
* * *
<span style="font-size: 12pt;">(本文是2018年11月17日晓峰牧师在小组长会议上的分享,根据录音整理)</span> |
Shell | UTF-8 | 2,024 | 3.890625 | 4 | [
"Apache-2.0"
] | permissive | #!/usr/bin/env bash
function devices {
bluetoothctl devices
}
function paired_devices {
bluetoothctl paired-devices
}
function connect_mouse_mx {
connect_device "MX Master"
}
function connect_mouse_ultrathin {
connect_device "Ultrathin Touch Mouse"
}
function connect_keyboard {
connect_device "Keyboard K380"
}
function connect_headphones {
connect_device "MOMENTUM TW"
}
function connect_speaker {
connect_device "JBL Charge 3"
}
function connect_device {
mac_address=$(bluetoothctl devices | grep "$1" | awk '{print $2}')
bluetoothctl connect $mac_address
}
function scan {
bluetoothctl scan on
}
function on {
bluetoothctl power on
}
function off {
bluetoothctl power off
}
function help {
echo "
bluetooth.sh is a simple wrapper for bluetoothctl for bluetooth management
usage:
help shows help
devices shows devices
paired_devices shows paired devices
connect_mouse_mx connects mx mouse
connect_mouse_ultrathin connects ultrathin mouse
connect_headphones connects headphones
connect_speaker connects speaker
scan starts scanning
on turns bt on
off turns bt off
"
}
function main {
if [ -z "$1" ] || [ "$1" == "help" ] ; then
help
exit
fi
if [ "$1" == "status" ]; then
info
exit
fi
if [ "$1" == "devices" ]; then
devices
exit
fi
if [ "$1" == "paired_devices" ]; then
paired_devices
exit
fi
if [ "$1" == "connect_mouse_mx" ]; then
connect_mouse_mx
exit
fi
if [ "$1" == "connect_mouse_ultrathin" ]; then
connect_mouse_ultrathin
exit
fi
if [ "$1" == "connect_headphones" ]; then
connect_headphones
exit
fi
if [ "$1" == "connect_speaker" ]; then
connect_speaker
exit
fi
if [ "$1" == "scan" ]; then
scan
fi
if [ "$1" == "on" ]; then
on
fi
if [ "$1" == "off" ]; then
off
fi
}
main "$@"
|
JavaScript | UTF-8 | 389 | 3.21875 | 3 | [] | no_license | const inputText = document.querySelector('input#name-input');
const outputText = document.querySelector('span#name-output');
inputText.addEventListener('input', e => {
// outputText.textContent = e.target.value || "незнакомец";
if (e.target.value === '') {
outputText.textContent = 'незнакомец';
} else {
outputText.textContent = e.target.value;
}
});
|
Python | UTF-8 | 560 | 2.6875 | 3 | [] | no_license | import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
import re
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
url = 'http://py4e-data.dr-chuck.net/comments_738328.html'
html = urllib.request.urlopen(url,context = ctx).read()
soup = BeautifulSoup(html, 'html.parser')
tags = soup('span')
sumval = 0
countval = 0
for tag in tags :
sumval = sumval + int(tag.contents[0])
countval = countval + 1;
print('Count :', countval)
print('Sum :', sumval)
|
C | UTF-8 | 1,459 | 2.59375 | 3 | [] | no_license | #include <gba_console.h>
#include <gba_video.h>
#include <gba_interrupt.h>
#include <gba_systemcalls.h>
#include <gba_sio.h>
#include <gba_input.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define JOY_WRITE (1 << 1)
#define JOY_READ (1 << 2)
// REG_HS_CTRL = JOYCNT
// REG_JSTAT = JOYSTAT
static void dump_regs(void)
{
printf("RCNT %04X JOYCNT %04X\n"
"JOYRE %08X JOYTR %08x\n"
"JSTAT %08x\n",
(u16)REG_RCNT, (u16)REG_HS_CTRL,
(unsigned int)REG_JOYRE, (unsigned int)REG_JOYTR,
(unsigned int)REG_JSTAT);
}
int main(int argc, char **argv)
{
u32 sendVal = 0;
irqInit();
irqEnable(IRQ_VBLANK);
consoleDemoInit();
puts("JOYBUS TEST");
while (1)
{
scanKeys();
u16 pressed = keysDown();
if (REG_HS_CTRL & JOY_WRITE)
{
printf("<<< recv 0x%08X\n", (unsigned int)REG_JOYRE);
REG_HS_CTRL |= JOY_WRITE;
}
if (REG_HS_CTRL & JOY_READ)
REG_HS_CTRL |= JOY_READ;
if (pressed & KEY_START)
{
puts("Registers:");
dump_regs();
}
if (pressed & KEY_A) // Send message
{
REG_JOYTR = sendVal;
printf(">>> send 0x%08X\n", (unsigned int)sendVal);
}
if (pressed & KEY_UP)
sendVal++;
if (pressed & KEY_DOWN)
sendVal--;
VBlankIntrWait();
}
}
|
Markdown | UTF-8 | 649 | 2.96875 | 3 | [] | no_license | # Crossroads Web Help
This site is where we'll be documenting how to work with and edit the [Crossroads of Arlington website](https://www.crossroadsofarlington.org). Keep in mind, this help site is a work in progress. If there's something you need documented, please let us know.
## Available Help Docs
1. ==__[Working with images on the site](working-with-images.md)__== has the specs for various image sizes used throughout the site, and it includes important general tips about saving your images for the web.
2. ==__[Uploading podcasts](podcasts.md)__== has details on how to save your files, name them properly, and upload them on the site.
|
Java | UTF-8 | 2,097 | 2.1875 | 2 | [] | no_license | package com.jwtauth2.pratice.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.jwtauth2.pratice.dto.JwtRequest;
import com.jwtauth2.pratice.dto.JwtResponse;
import com.jwtauth2.pratice.dto.UserDto;
import com.jwtauth2.pratice.impl.JwtUserDetailsService;
import com.jwtauth2.pratice.util.JwtTokenUtil;
@RestController
@CrossOrigin
public class JwtUsersAuthenticationController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired
JwtUserDetailsService userDetailService;
@Autowired
JwtTokenUtil jwtToken;
@RequestMapping(value = "/authenticate",method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtRequest authRequest) throws Exception
{
try {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
authRequest.getUserName(),
authRequest.getPassword()
)
);
}
catch(BadCredentialsException ex)
{
throw new Exception("WRONG_CREDENTIALS", ex);
}
final UserDetails USER = userDetailService.loadUserByUsername(authRequest.getUserName());
final String token = jwtToken.generateToken(USER);
return ResponseEntity.ok(new JwtResponse(token));
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<?> registerUser(@RequestBody UserDto user)
{
return ResponseEntity.ok(userDetailService.addUser(user));
}
}
|
Go | UTF-8 | 802 | 2.9375 | 3 | [] | no_license | package sort
import (
"algorithms/result"
)
func SelectionSort(intSlice *[]int,order string) result.Result {
switch order {
case "ascending":
for i := 0; i < len(*intSlice); i++ {
minIndex := i
for j := i + 1; j < len(*intSlice); j++ {
if (*intSlice)[j] < (*intSlice)[minIndex] {
minIndex = j
}
}
(*intSlice)[i], (*intSlice)[minIndex] = (*intSlice)[minIndex], (*intSlice)[i]
}
case "descending":
for i := 0; i < len(*intSlice); i++ {
minIndex := i
for j := i + 1; j < len(*intSlice); j++ {
if (*intSlice)[j] > (*intSlice)[minIndex] {
minIndex = j
}
}
(*intSlice)[i], (*intSlice)[minIndex] = (*intSlice)[minIndex], (*intSlice)[i]
}
}
return result.Result{BestCase: "O[N^2]", AverageCase: "O[N^2]", WorstCase: "O[N^2]", Space: "O[1]"}
}
|
Java | UTF-8 | 311 | 2.03125 | 2 | [] | no_license | package com.vainolo.jjtv5.model;
import org.eclipse.gef.requests.CreationFactory;
public class NodeFactory implements CreationFactory {
@Override
public Object getNewObject() {
return new Node();
}
@Override
public Object getObjectType() {
return Node.class;
}
}
|
Java | UTF-8 | 685 | 1.898438 | 2 | [] | no_license | package com.caton.mvvmdemo.ui.login;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.ViewModel;
import android.arch.lifecycle.ViewModelProvider;
import android.content.Context;
import android.databinding.ObservableField;
import android.widget.Toast;
import com.caton.mvvmdemo.app.MyApplication;
/**
* Created by saisai on 2019/4/22 0022.
*/
public class LoginViewModel extends ViewModel {
public ObservableField<String> username = new ObservableField<>();
public ObservableField<String> password = new ObservableField<>();
public void login() {
Toast.makeText(MyApplication.app, "login", Toast.LENGTH_SHORT).show();
}
}
|
Java | UTF-8 | 508 | 1.992188 | 2 | [] | no_license | package site.newvalue.dao;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import site.newvalue.domain.User;
import java.util.List;
public interface IUserDao {
@Select("select * from user")
public List<User> findAll();
@Select("select * from user where id=#{id}")
User findById(Integer id);
@Update("update user set username=#{username},password=#{password},sex=#{sex},age=#{age},email=#{email} where id=#{id}")
void update(User user);
} |
Java | UTF-8 | 1,169 | 2.0625 | 2 | [] | no_license | package com.developcollect.commonpay.pay.wxpay;
import com.developcollect.commonpay.PayPlatform;
import com.developcollect.commonpay.config.GlobalConfig;
import com.developcollect.commonpay.config.WxPayConfig;
import com.developcollect.commonpay.pay.wxpay.sdk.WXPayConfig;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.InputStream;
/**
* 微信sdk配置
* @author zak
* @since 1.0.0
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class DefaultWXPayConfig extends WXPayConfig {
private String appId;
private String mchId;
private String key;
@Override
public String getAppID() {
return appId;
}
@Override
public String getMchID() {
return mchId;
}
@Override
public String getKey() {
return key;
}
/**
* 微信支付证书
*
* @return 流
* @author zak
* @since 1.0.0
*/
@Override
public InputStream getCertStream() {
// 将证书配置通过配置传入
WxPayConfig payConfig = GlobalConfig.getPayConfig(PayPlatform.WX_PAY);
return payConfig.getCertInputStreamSupplier().get();
}
}
|
Java | UTF-8 | 860 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | package com.ppang.randomLinkedListSort;
import java.util.*;
public class Solution {
class Comp implements Comparator<RandomListNode> {
public int compare(RandomListNode a, RandomListNode b) {
return a.val - b.val;
}
}
public RandomListNode sortRandom(RandomListNode root) {
if (root==null || root.next==null) {
return root;
}
List<RandomListNode> list = new ArrayList<RandomListNode>();
RandomListNode cur = root;
while (cur!=null) {
list.add(cur);
cur = cur.next;
}
Collections.sort(list, new Comp());
RandomListNode prev = list.get(0);
RandomListNode head = list.get(0);
for (int i=1; i<list.size(); i++) {
cur = list.get(i);
prev.random = cur;
prev = cur;
}
return head;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
Python | UTF-8 | 822 | 2.90625 | 3 | [] | no_license | import os
import glob
path_a = "C:\\Users\\pisharamsomarajanh\\Desktop\\Excel_Exports\\MP_10msec"
os.chdir(path_a)
a = glob.glob('*.xlsx')
path_b = "C:\\Users\\pisharamsomarajanh\\Desktop\\Excel_Exports\\Main\\MP\\MP_10ms"
os.chdir(path_b)
b = glob.glob('*.xlsx')
a_only = []
b_only = []
print("Only in '" + path_a + "'\n" + "=============================")
for fna in a:
a_flag = 1
for fnb in b:
if fna == fnb:
a_flag = 0
break
if a_flag == 1:
a_only.append(fna)
print(fna)
print("\nOnly in '" + path_b + "'\n" + "=============================")
for fnb in b:
b_flag = 1
for fna in a:
if fna == fnb:
b_flag = 0
break
if b_flag == 1:
b_only.append(fnb)
print(fnb)
|
Python | UTF-8 | 3,796 | 2.5625 | 3 | [] | no_license | from app import db
from flask.ext.login import UserMixin
from sqlalchemy import UniqueConstraint
import random # FIXME: remove it when rating calculation is implemented
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
login = db.Column(db.String(64), index=True, unique=True)
def __repr__(self):
return '<User %r>' % self.login
def laws_to_vote(self):
"""Returns all laws from the database. In future, it is expected that
laws proposed to be voted by a user will be chosen according to
some algorithm"""
return Law.query.all()
def get_votes_count(self):
""" returns nb of votes done by the user """
return UserVote.query.filter(UserVote.user_id==self.id).count()
authorship = db.Table('authorship',
db.Column('law_id', db.Integer, db.ForeignKey('law.id')),
db.Column('author_id', db.Integer, db.ForeignKey('deputy.id'))
)
class Deputy(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
group = db.Column(db.String(64))
def __repr__(self):
return '<Deputy %s (%s)>' % (self.name, self.group)
def get_rating(self, user):
# FIXME
return random.uniform(0, 5)
def vote(self, law, option, attempt=1):
vote = DeputyVote(deputy_id = self.id, law_id = law.id,
attempt=attempt, option = option)
db.session.add(vote)
db.session.commit()
def support(self, law, attempt = 1):
self.vote(law, 1, attempt)
def reject(self, law, attempt = 1):
self.vote(law, 2, attempt)
def abstain(self, law, attempt = 1):
self.vote(law, 3, attempt)
def do_not_vote(self, law, attempt = 1):
self.vote(law, 4, attempt)
def set_absent(self, law, attempt = 1):
self.vote(law, 5, attempt)
class Law(db.Model):
id = db.Column(db.Integer, primary_key=True)
code = db.Column(db.String(16), unique=True)
title = db.Column(db.String(1024))
authors = db.relationship('Deputy',
secondary = authorship,
#primaryjoin=(followers.c.follower_id == id),
#secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('laws', lazy='dynamic'),
lazy='dynamic')
def __repr__(self):
return '<Law %s: "%s">' % (self.code, self.title)
class DeputyVote(db.Model):
deputy_id = db.Column(db.Integer, db.ForeignKey('deputy.id'), primary_key=True)
law_id = db.Column(db.Integer, db.ForeignKey('law.id'), primary_key=True)
# one law can be voted several times: this is vote attempt number
attempt = db.Column(db.SmallInteger, primary_key=True)
# Deputy vote options
# 1 = support
# 2 = reject
# 3 = abstained
# 4 = did not vote
# 5 = absent
option = db.Column(db.SmallInteger)
__table_args__ = (UniqueConstraint('deputy_id', 'law_id', 'attempt',
name='_deputy_vote_for_law'),)
class UserVote(db.Model):
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True)
law_id = db.Column(db.Integer, db.ForeignKey('law.id'), primary_key=True)
# Deputy vote options
# 1 = support
# -1 = reject
# 0 = ignore
option = db.Column(db.SmallInteger)
user = db.relationship('User', backref=db.backref('votes', lazy='dynamic'))
law = db.relationship('Law', backref=db.backref('votes', lazy='dynamic'))
__table_args__ = (UniqueConstraint('user_id', 'law_id',
name='_user_vote_for_law'),)
|
JavaScript | UTF-8 | 2,109 | 2.703125 | 3 | [] | no_license | import React, { Component } from 'react';
import '../styling/Metronome.css';
import click1 from '../sounds/click1.wav';
import click2 from '../sounds/click2.wav';
import { Button } from 'shards-react';
class Metronome extends Component {
constructor(props) {
super(props);
this.state = {
playing : false,
count : 0,
bpm : 100,
beatsPerMeasure : 4,
};
this.click1 = new Audio(click1);
this.click2 = new Audio(click2);
}
handleBpmChange = event => {
const bpm = event.target.value;
if (this.state.playing) {
//Stop the old timer and start a new one
clearInterval(this.timer);
this.timer = setInterval(this.playClick, 60 / bpm * 1000);
//Set the new BPM, and reset the beat counter
this.setState({
count : 0,
bpm,
});
} else {
//Otherwise just update the BPM
this.setState({ bpm });
}
};
playClick = () => {
const { count, beatsPerMeasure } = this.state;
//The first beat will have a different sound than the others
if (count % beatsPerMeasure === 0) {
this.click2.play();
} else {
this.click1.play();
}
//Keeps track of which beat we are on
this.setState(state => ({
count : (state.count + 1) % state.beatsPerMeasure,
}));
};
startStop = () => {
if (this.state.playing) {
//Stop the timer
clearInterval(this.timer);
this.setState({
playing : false,
});
} else {
//Start a timer with the current BPM
this.timer = setInterval(this.playClick, 60 / this.state.bpm * 1000);
this.setState(
{
count : 0,
playing : true,
//Play a click "immediately" (after setState finishes)
},
this.playClick,
);
}
};
render() {
const { playing, bpm } = this.state;
return (
<div className='metronome'>
<div className='bpm-slider'>
<h6>{bpm} BPM</h6>
<input type='range' min='60' max='240' value={bpm} onChange={this.handleBpmChange} />
</div>
<Button pill theme='success' size='lg' onClick={this.startStop}>
{playing ? 'Stop' : 'Start'}
</Button>
</div>
);
}
}
export default Metronome;
|
C++ | UTF-8 | 2,161 | 2.609375 | 3 | [
"MIT"
] | permissive | //==============================================================================
// CheckSimulation.cxx
// This program produces histograms using data
// from a LArSoft-simulated ROOT file
//
// Gleb Sinev, 2016, gleb.v.sinev@gmail.com
//==============================================================================
#include "CheckSimulation.h"
int main(int argc, char *argv[])
{
std::cout << "Starting check-simulation.\n";
int numberOfArguments = 1;
if (argc != (numberOfArguments + 1))
{
std::cerr << "Usage: check-simulation inputFile.root.\n";
return 1;
}
std::vector< std::string > fileNames{ std::string(argv[1]) };
std::string outputFileName("output.root");
TFile outputFile(outputFileName.c_str(), "RECREATE");
if (outputFile.IsZombie())
{
std::cerr << "Unable to open " << outputFileName << ", exiting...\n";
return 1;
}
TTree tree("GeneratorTree", "Generator-level information");
if (tree.IsZombie())
{
std::cerr << "Unable to create " << tree.GetName() << ", exiting...\n";
return 1;
}
int eventID;
int NParticles;
std::vector< float > PDGVector;
std::vector< float > energyVector;
tree.Branch("EventID", &eventID, "EventID/I" );
tree.Branch("NParticles", &NParticles, "NParticles/I");
tree.Branch("PDGVector", &PDGVector );
tree.Branch("EnergyVector", &energyVector);
art::InputTag generatorTag { "generator" };
for (gallery::Event event(fileNames); !event.atEnd(); event.next())
{
eventID = event.eventEntry();
auto const& MCTruths =
*event.getValidHandle< std::vector < simb::MCTruth > >(generatorTag);
if (!MCTruths.empty()) {
NParticles = MCTruths[0].NParticles();
PDGVector .reserve(NParticles);
energyVector.reserve(NParticles);
for (int index = 0; index < NParticles; ++index)
{
auto const& particle = MCTruths[0].GetParticle(index);
PDGVector .emplace_back(particle.PdgCode());
energyVector.emplace_back(particle.E() );
}
}
tree.Fill();
PDGVector .clear();
energyVector.clear();
}
outputFile.Write();
outputFile.Close();
return 0;
}
|
C++ | UTF-8 | 439 | 2.734375 | 3 | [
"LicenseRef-scancode-public-domain",
"MIT"
] | permissive | #pragma once
#include "Core/Colour.h"
struct CircleRendererComponent
{
Colour colour{ 1.0f, 1.0f, 1.0f, 1.0f };
float radius = 0.5f;
float thickness = 1.0f;
float fade = 0.005f;
CircleRendererComponent() = default;
CircleRendererComponent(const CircleRendererComponent&) = default;
private:
friend cereal::access;
template<typename Archive>
void serialize(Archive& archive)
{
archive(colour, radius, thickness, fade);
}
}; |
Markdown | UTF-8 | 1,818 | 2.75 | 3 | [] | no_license | ---
title: Units & Dimensions
weight: 10
---
## Builder Units
All units used by the builder are in Millimeters (`mm`). That includes dimensions, coordinates and output. Unfortunately, the current library I am using for exporting DXF files does not support specifying the units in the file format. Because of this, the dimensions are in `mm` in the drawing, but no units are exported with the DXF file. Make sure your CAD program is set to `mm` when you open the DXF because it will assume your default units. If you need a file with units defined for your laser cutter, you will want to open the file in LibreCAD (or some other CAD software), make sure the drawing units are set to `mm`, and then save as a `DXF 2007` file format. The `DXF 2007` format will save the units as well as the dimension in the resulting DXF file. [Detailed instructions can be found here...](/pro-tips/#save-a-dxf-with-units)
## Key Sizing & Spacing
Each key drawn by the builder is based on a multiple of a `key unit`, which has a shorthand of `u`. A `key unit` is defined to be the amount of space a single 1x1 unit key takes up on a keyboard. Two 1u keys will be 1u from center to center, which is a constant of `19.05mm`. Each key on a keyboard can be defined as a multiple of a `key unit`, so a standard Space Bar would be 6.25u, and a Right Shift would be 2.75u.
For the most part, you will not have to worry too much about the key sizing since the <a href="http://www.keyboard-layout-editor.com/" target="_blank">keyboard-layout-editor.com</a> (KLE) has presets for most of the common layouts. Keep in mind that KLE may not have the right amount of space between the different key clusters on some layouts, so if you are working from a PCB for a TKL or 104 layout, you will want to verify the spacing KLE specifies. |
PHP | UTF-8 | 4,240 | 2.984375 | 3 | [] | no_license | <?php
class EasyPDO_Table {
private $db;
private $name = NULL;
public $cols = NULL;
function __construct($DataBase, $table) {
$this->db = $DataBase;
$this->name = $table;
}
public function all() {
return $this->db->query("SELECT * FROM `" . $this->name . "` ");
}
public function select($where = '', $vals = NULL) {
if ($this->cols != NULL) {
$comma = '';
$cols = '';
foreach ($this->cols as $cols2) {
$cols .= $comma . '`' . $cols2 . '`';
$comma = ',';
}
} else {
$cols = '*';
}
if ($vals != NULL) {
$r = $this->db->prepare("SELECT " . $cols . " FROM `" . $this->name . "`" . $where);
$r->execute($vals);
} else {
$r = $this->db->query("SELECT " . $cols . " FROM `" . $this->name . "`" . $where);
}
return $r;
}
public function insert($vals, $security = false) {
if ($security) {
$comma = '';
$colsText = '';
$valLoc = '';
foreach ($this->cols as $cols2) {
$colsText .= $comma . '`' . $cols2 . '`';
$valLoc .= $comma . '?';
$comma = ',';
}
$r = $this->db->prepare("INSERT INTO `" . $this->name . "`(" . $colsText . ") VALUES(" . $valLoc . ")");
$r->execute($vals);
} else {
$comma = '';
$colsText = '';
$valsText = '';
$i = 0;
foreach ($this->cols as $cols2) {
$colsText .= $comma . '`' . $cols2 . '`';
$valsText .= $comma . '"' . $vals[$i] . '"';
$i++;
$comma = ',';
}
$r = $this->db->query("INSERT INTO `" . $this->name . "`(" . $colsText . ") VALUES(" . $valsText . ")");
}
return $r;
}
public function LastId(){
return (int)$this->db->query("SELECT MAX(ID) FROM ".$this->name)->fetch()[0];
}
public function delete($where = '', $vals = NULL) {
if ($vals != NULL) {
$r = $this->db->prepare("DELETE FROM `" . $this->name . "`" . $where);
$r->execute($vals);
} else {
$r = $this->db->query("DELETE FROM `" . $this->name . "`" . $where);
}
return $r;
}
public function update($where = '', $vals, $security = false) {
if ($security) {
$comma = '';
$colsText = '';
foreach ($this->cols as $cols2) {
$colsText .= $comma . '`' . $cols2 . '`=?';
$comma = ',';
}
$r = $this->db->prepare("UPDATE `" . $this->name . "` SET " . $colsText . $where);
$r->execute($vals);
} else {
$comma = '';
$colsText = '';
$i = 0;
foreach ($this->cols as $cols2) {
$colsText .= $comma . "`" . $cols2 . "`='" . $vals[$i] . "'";
$i++;
$comma = ',';
}
$r = $this->db->query("UPDATE `" . $this->name . "` SET " . $colsText . $where);
}
return $r;
}
public function total($where = '') {
$data = $this->db->query("SELECT COUNT(*) as `totaldata` FROM `" . $this->name . "` " . $where)->fetch(PDO::FETCH_ASSOC);
return $data['totaldata'];
}
public function totalPage($limit = 10, $where = '') {
$data = $this->db->query("SELECT COUNT(*) as `totaldata` FROM `" . $this->name . "` " . $where)->fetch(PDO::FETCH_ASSOC);
return ceil($data['totaldata'] / $limit);
}
public function getPage($page, $limit = 10, $where = '') {
if ($this->cols != NULL) {
$comma = '';
$cols = '';
foreach ($this->cols as $cols2) {
$cols .= $comma . '`' . $cols2 . '`';
$comma = ',';
}
} else {
$cols = '*';
}
$data = $this->db->query("SELECT " . $cols . " FROM `" . $this->name . "` " . $where . " LIMIT " . ($page - 1) * $limit . "," . $limit);
return $data;
}
}
|
Java | UTF-8 | 1,036 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package me.pesehr.trustconnection.app;
import com.squareup.okhttp.OkHttpClient;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
/**
* Created by pesehr on 23/08/2015.
*/
public final class HttpsClient extends OkHttpClient {
public HttpsClient(SSLSocketFactory factory,HostnameVerifier hv){
setSslSocketFactory(factory);
setHostnameVerifier(hv);
}
public HttpsClient(SSLSocketFactory factory){
setSslSocketFactory(factory);
setHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier());
}
public HttpsClient(SSLSocketFactory factory, final String Url){
setSslSocketFactory(factory);
setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return HttpsURLConnection.getDefaultHostnameVerifier(). verify(Url,sslSession);
}
});
}
}
|
Python | UTF-8 | 230 | 2.53125 | 3 | [] | no_license | a = int(input())
n = list(map(int,input().split()))[1:]
m = list(map(int,input().split()))[1:]
l = n + m
s = set(l)
s.remove(0) if 0 in s else s
if a==len(s):
print("I become the guy.")
else:
print("Oh, my keyboard!")
|
C# | UTF-8 | 2,032 | 2.671875 | 3 | [] | no_license | using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
namespace BuckRogers.Interface
{
class EmptyMessageListView : ListView
{
public EmptyMessageListView()
{
SetStyle(ControlStyles.ResizeRedraw, true);
}
private bool _gridLines = false;
///
/// Handle GridLines on our own because base.GridLines has to be switched on
/// and off depending on the amount of items in the ListView.
///
[DefaultValue(false)]
public new bool GridLines
{
get { return _gridLines; }
set { _gridLines = value; Invalidate(); }
}
private string _noItemsMessage = "There are no items to show in this view";
///
/// To be able to localize the message it must not be hardcoded
///
[DefaultValue("There are no items to show in this view")]
public string NoItemsMessage
{
get { return _noItemsMessage; }
set { _noItemsMessage = value; Invalidate(); }
}
const int WM_ERASEBKGND = 0x14;
protected override void WndProc(ref Message m)
{
base.WndProc (ref m);
if (m.Msg == WM_ERASEBKGND)
{
#region Handle drawing of "no items" message
if (Items.Count==0 && Columns.Count>0)
{
if (this.GridLines)
{
base.GridLines = false;
}
int w = 0;
foreach (ColumnHeader h in this.Columns)
w += h.Width;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
Rectangle rc = new Rectangle(0, (int)(this.Font.Height * 3), w, this.Height);
using (Graphics g = this.CreateGraphics())
{
g.FillRectangle(SystemBrushes.Window, 0, 0, this.Width, this.Height);
g.DrawString(NoItemsMessage, this.Font, SystemBrushes.ControlText, rc, sf);
}
}
else
{
base.GridLines = this.GridLines;
}
#endregion
}
}
}
}
|
Python | UTF-8 | 282 | 3 | 3 | [] | no_license | class DEBUG():
ENABLED = True
def ON(self):
self.ENABLED = True
print(self.ENABLED)
def OFF(self):
self.ENABLED = False
print(self.ENABLED)
def MSG(self, NME, PROS, CMD, MSG):
if self.ENABLED == True:
print(f'| {str(NME)}: {str(PROS)}: { str(CMD)}: {str(MSG)}') |
JavaScript | UTF-8 | 2,645 | 2.609375 | 3 | [
"MIT"
] | permissive | require('babel-polyfill');
const React = require('react');
const ReactDOM = require('react-dom');
const Datepicker = require('../');
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
events: [],
defaultValue: '2019-03-01'
}
}
onSelect(date) {
this.state.events.unshift(date);
this.forceUpdate();
}
render() {
return (
<React.Fragment>
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="/">react-datepicker</a>
<button className="navbar-toggler" type="button"
data-toggle="collapse" data-target="#navbarSupportedContent">
<span className="navbar-toggler-icon"/>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
<li className="nav-item active">
<a className="nav-link" href="/">Home <span className="sr-only">(current)</span></a>
</li>
</ul>
</div>
</nav>
<div className="container">
<div className="row">
<div className="col-12 mt-3">
<h3>Without default values.</h3>
<hr/>
<form className="form-inline">
<div className="form-group">
<Datepicker className="form-control"/>
</div>
</form>
</div>
<div className="col-12 mt-3">
<h3>With default value "2019-03-01" and event "onSelect()".</h3>
<hr/>
<div className="row">
<div className="col-md-3">
<form className="form-inline">
<div className="form-group">
<Datepicker date={this.state.defaultValue}
onSelect={this.onSelect.bind(this)}
className="form-control"/>
</div>
</form>
</div>
<div className="col-md-9">
<div className="card">
<div className="card-body">
{this.state.events.map((event, index) => {
return <p key={`event-${index}`}>Selected: {event}</p>
})}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</React.Fragment>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
|
JavaScript | UTF-8 | 1,711 | 2.71875 | 3 | [] | no_license | var sodium = require('sodium-native')
// ECDH
// x25519
// Create Alice keypair
var AlicePublicKey = sodium.sodium_malloc(sodium.crypto_box_PUBLICKEYBYTES)
var AlicePrivateKey = sodium.sodium_malloc(sodium.crypto_box_SECRETKEYBYTES)
sodium.crypto_box_keypair(AlicePublicKey, AlicePrivateKey)
console.log(`Alice ${sodium.crypto_box_PUBLICKEYBYTES}-byte public key is: ${AlicePublicKey.toString('hex')}`)
console.log(`Alice ${sodium.crypto_box_SECRETKEYBYTES}-byte private key is: ${AlicePrivateKey.toString('hex')}`)
// Create Bob keypair
var BobPublicKey = sodium.sodium_malloc(sodium.crypto_box_PUBLICKEYBYTES)
var BobPrivateKey = sodium.sodium_malloc(sodium.crypto_box_SECRETKEYBYTES)
sodium.crypto_box_keypair(BobPublicKey, BobPrivateKey)
console.log(`Bob ${sodium.crypto_box_PUBLICKEYBYTES}-byte public key is: ${BobPublicKey.toString('hex')}`)
console.log(`Bob ${sodium.crypto_box_SECRETKEYBYTES}-byte private key is: ${BobPrivateKey.toString('hex')}`)
// Alice to create secret using her private key and bob's public key
var AliceSharedSecret = sodium.sodium_malloc(sodium.crypto_scalarmult_BYTES)
sodium.sodium_memzero(AliceSharedSecret)
sodium.crypto_scalarmult(AliceSharedSecret, AlicePrivateKey, BobPublicKey)
console.log(`Alice created ${sodium.crypto_scalarmult_BYTES}-byte secret: ${AliceSharedSecret.toString('hex')}`)
// Bob to create secret using his private key and alice's public key
var BobSharedSecret = sodium.sodium_malloc(sodium.crypto_scalarmult_BYTES)
sodium.sodium_memzero(BobSharedSecret)
sodium.crypto_scalarmult(BobSharedSecret, BobPrivateKey, AlicePublicKey)
console.log(`Bob created ${sodium.crypto_scalarmult_BYTES}-byte secret: ${BobSharedSecret.toString('hex')}`)
|
Java | UTF-8 | 10,875 | 2.421875 | 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 osprojectthree;
import java.util.*;
import java.lang.*;
import java.io.*;
/**
*
* @author deadoggy
*/
public class FileManagement {
public FileManagement() {
FCBTable = new ArrayList<FCB>();
// FCB T = new FCB(0,"root",0);
//FCBTable.add(T);
StorageTable = new StorageBlock[BlockSize];
StorageState = new boolean[BlockSize];
SBSize = BlockSize;
for (int i = 0; i < BlockSize; i++) {
StorageTable[i] = new StorageBlock();
StorageTable[i].setIndex(i);
StorageState[i] = false;
}
FCBSize = 0;
}
public void format(int fileid) //格式化
{
FCB fcb = FileManagement.getFCB(fileid);
FCBSize -= fcb.getSubFiles().size();
fcb.clear(StorageTable, FCBTable, StorageState);
}
public int getFCBSize() {
return FCBSize;
}
public void createFolder(String filename, int fileid) {
FCB NewFile = new FCB(fileid, filename, CurrentFolder.getFileID());
NewFile.setFileType(1);
FCBTable.add(NewFile);
CurrentFolder.addSubFile(NewFile);
FCBSize++;
}
public void createFile(String filename, int fileid) {
FCB NewFile = new FCB(fileid, filename, CurrentFolder.getFileID());
NewFile.setFileType(0);
FCBTable.add(NewFile);
CurrentFolder.addSubFile(NewFile);
FCBSize++;
}
public void deleteFile(int fileid) {
FCB file = FileManagement.getFCB(fileid);
ArrayList<Integer> SubFiles = CurrentFolder.getSubFiles();
for (int i = 0; i < SubFiles.size(); i++) {
if (file.getFileID() == SubFiles.get(i).intValue()) {
SubFiles.remove(i);
break;
}
}
file.clear(StorageTable, FCBTable, StorageState);
FCBTable.remove(file);// remove from global index
FCBSize--;
}
public String readFile(int fileid) {
FCB file = FileManagement.getFCB(fileid);
StringBuilder text = new StringBuilder();
ArrayList<Integer> SBT = file.getStorageBlockTable();
int end = SBT.size();
for (int i = 0; i < end; i++) {
text.append(StorageTable[SBT.get(i)].read());
}
return text.toString();
}
public int getFreeBlock() {
for (int i = 0; i < BlockSize; i++) {
if (false == StorageState[i]) {
return i;
}
}
return -1;
}
public boolean writeFile(FCB file, String text) {
int i;
ArrayList<Integer> sbt = file.getStorageBlockTable();
int end_sb = sbt.size();
if(0==text.length())
{
i = -1;
}
else
{
for (i = 0; i < end_sb; i++) {
text = StorageTable[sbt.get(i)].write(text);
if (0 == text.length()) {
break;
}
}
}
if (i == end_sb) {
int block = getFreeBlock();
int externsize = 0;
while (-1 != block) {
file.getStorageBlockTable().add(block);
text = StorageTable[block].write(text);
StorageTable[block].setFileObj(file);
StorageState[block] = true;
externsize++;
if (0 == text.length()) {
file.addSize(externsize);
return true;
}
block = getFreeBlock();
}
return false;
} else {
int less = i + 1 - end_sb;
if (0 == less) {
return true;
}
for (int j = 1; j <= -less; j++) {
StorageTable[sbt.get(1 + i)].changeState();
StorageState[sbt.get(1 + i)] = false;
sbt.remove(i + 1);
}
file.addSize(less);
return true;
}
}
public void load() {
//load storage block
for (int i = 0; i < BlockSize; i++) {
File file = new File("disk/StorageBlocks/" + i + ".bin");
if (true == file.exists()) {
try {
StringBuilder sb = new StringBuilder();
StorageState[i] = true;
Reader reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while (-1 != (tempchar = reader.read())) {
sb.append((char) tempchar);
}
StorageTable[i].write(sb.toString());
reader.close();
} catch (Exception e) {
return;
}
}
}
//load fcb
load_fcb();
}
public void store() {
//Write fcb
try {
File file = new File("disk/FCBFile/FCB.bin");
if (false == file.exists()) {
boolean res = file.mkdir();
}
Writer fw = new OutputStreamWriter(new FileOutputStream(file));
int end = FCBTable.size();
for (int i = 0; i < end; i++) {
FCB fcb = FCBTable.get(i);
//File name
fw.write(fcb.getFileName() + "\n");
//ID
Integer temp = new Integer(fcb.getFileID());
fw.write(temp.toString() + '\n');
//file parent
int pare = fcb.getParent();
if (-1 != pare) {
temp = new Integer(pare);
fw.write(temp.toString() + '\n');
} else {
fw.write("-1\n");
}
//file type
if (0 == fcb.getFileType()) {
fw.write("text" + '\n');
} else {
fw.write("folder" + '\n');
}
//file size
temp = new Integer(fcb.getFileSize());
fw.write(temp.toString() + '\n');
//subfiles
ArrayList<Integer> subfiles = fcb.getSubFiles();
if (null != subfiles) {
int end_sub = subfiles.size();
temp = new Integer(fcb.getSubFiles().size());
fw.write(temp.toString() + '\n');
for (int j = 0; j < end_sub; j++) {
temp = new Integer(subfiles.get(j));
fw.write(temp.toString() + '\n');
}
}
//storage block
ArrayList<Integer> storage = fcb.getStorageBlockTable();
if (null != storage) {
int end_sb = storage.size();
temp = new Integer(fcb.getStorageBlockTable().size());
fw.write(temp.toString() + '\n');
for (int j = 0; j < end_sb; j++) {
temp = new Integer(StorageTable[storage.get(j)].getIndex());
fw.write(temp.toString() + '\n');
}
}
}
fw.close();
} catch (Exception e) {
return;
}
//write storage block
//first delete all existed file
//then write
for (int i = 0; i < BlockSize; i++) {
File file = new File("disk/StorageBlocks/", Integer.toString(i) + ".bin");
if (true == file.exists()) {
file.delete();
}
if (true == StorageState[i]) {
try {
file.createNewFile();
Writer fw = new OutputStreamWriter(new FileOutputStream(file));
fw.write(StorageTable[i].read());
fw.close();
} catch (Exception e) {
return;
}
}
}
}
public static FCB getFCB(Integer ID) {
for (int i = 0; i < FCBTable.size(); i++) {
if (ID == FCBTable.get(i).getFileID()) {
return FCBTable.get(i);
}
}
return null;
}
public FCB getCurrentFolder() {
return CurrentFolder;
}
public void setCurrentFolder(FCB fcb) {
CurrentFolder = fcb;
}
private void load_fcb() {
FCB ret = null;
File file = new File("disk/FCBFile/FCB.bin");
try {
Reader reader = new InputStreamReader(new FileInputStream(file));
BufferedReader br = new BufferedReader(reader);
//get fcb name
String temp = null;
int fcbsize = 0;
while (null != (temp = br.readLine())) {
fcbsize++;
int id = Integer.parseInt(br.readLine());
int pare = Integer.parseInt(br.readLine());
//initialize a fcb
FCB fcb = new FCB(id, temp, pare);
//get type
int type;
String ex = br.readLine();
if (ex.equalsIgnoreCase("text")) {
type = 0;
} else {
type = 1;
}
fcb.setFileType(type);
//get size
int size = Integer.parseInt(br.readLine());
fcb.setSize(size);
//get subfiles
int lines = Integer.parseInt(br.readLine());
for (int i = 0; i < lines; i++) {
fcb.getSubFiles().add(Integer.parseInt(br.readLine()));
}
//get storage blocks
lines = Integer.parseInt(br.readLine());
for (int i = 0; i < lines; i++) {
fcb.getStorageBlockTable().add(Integer.parseInt(br.readLine()));
}
FCBTable.add(fcb);
temp = null;
}
FCBSize = fcbsize;
reader.close();
} catch (Exception e) {
return;
}
}
private static final int BlockSize = 1024;
private FCB CurrentFolder;
private static ArrayList<FCB> FCBTable;
private StorageBlock[] StorageTable;
private boolean[] StorageState;
private int FCBSize;
private static int SBSize;
}
|
Java | UTF-8 | 537 | 1.75 | 2 | [
"MIT"
] | permissive | package br.com.publicacao.springboot.api.service;
import br.com.publicacao.springboot.api.dto.PublicacaoDTO;
import br.com.publicacao.springboot.api.model.Publicacao;
import org.springframework.http.ResponseEntity;
import java.util.List;
public interface IPublicacaoService {
ResponseEntity<List<PublicacaoDTO>> listar();
ResponseEntity<Publicacao> adicionarLike(Long id);
ResponseEntity<Publicacao> adicionarPostagem(PublicacaoDTO publicacao);
ResponseEntity<Publicacao> deletarPostagem(PublicacaoDTO publicacao);
}
|
C# | UTF-8 | 1,193 | 3.0625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using recipefinder.Classes;
using Xamarin.Forms;
namespace recipefinder
{
public partial class DisplayRecipePage : ContentPage
{
string stepsToMake = "";
public DisplayRecipePage(Recipe recipeToDisplay, string type)
{
InitializeComponent();
//Change UI according to Recipe passed in, this a template page
RecipeNameLabel.Text = recipeToDisplay.name;
RecipeImage.Source = recipeToDisplay.image;
//Go through every step in the recipe
for(int i = 0; i < recipeToDisplay.instructions.Count; i++)
{
stepsToMake = stepsToMake + recipeToDisplay.instructions[i] + System.Environment.NewLine;
}
StepsToMakeLabel.Text = stepsToMake;
if (type == "recommended")
{
IngredientsListView.ItemTemplate = null;
IngredientsListView.ItemsSource = recipeToDisplay.ingredientNames;
}
else
{
IngredientsListView.ItemsSource = recipeToDisplay.ingredients;
}
}
}
}
|
C++ | UTF-8 | 609 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>>
using namespace std;
int main()
{
// Max先记录最小的数字,然后慢慢赋值变大
// x表示输入的数字
// temp比较大小
int n, Max = -9999, x, temp = 0;
cin >> n;
for(int i = 0; i < n; i++)
{
// 循环输入
cin >> x;
// 每次都是前一个数和后一个数的和 与 后一个数比大小
// 大的记录起来
temp = max(temp + x, x);
// temp 和 Max比较,记录大的数字
Max = max(temp, Max);
}
// 打印
cout << Max<<endl;
return 0;
}
|
JavaScript | UTF-8 | 448 | 2.65625 | 3 | [] | no_license | class InfoBox {
constructor(AuthorBox) {
this.cntx = AuthorBox.getContext('2d');
this.x = 300;
this.y = 300;
}
draw(cntx, score) {
this.cntx.font = '50px Arial';
this.cntx.fillStyle = 'black';
this.cntx.fillText(
`BAD SKY CAB`,
this.x,
this.y
);
this.cntx.strokeStyle = "red";
this.cntx.strokeText(
`BAD SKY CAB`,
this.x,
this.y
);
}
}
export default InfoBox
|
Java | UTF-8 | 2,349 | 2.078125 | 2 | [
"MIT"
] | permissive | package com.mediscreen.notes.mock;
import com.mediscreen.notes.api.model.Note;
import com.mediscreen.notes.persistence.entity.NoteEntity;
import com.mediscreen.notes.persistence.mapper.NoteMapper;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class NoteMockData {
private final NoteMapper noteMapper;
public UUID getNoteIdA() {
return UUID.fromString("d6501cf4-2fd2-448b-8dd6-3997dd3c1963");
}
public UUID getPatientIdA() {
return UUID.fromString("b650a2bf-08e1-43ea-965d-f0b87ac21bfb");
}
public Note getNoteModelA() {
return Note.builder()
.id(getNoteIdA())
.patientId(getPatientIdA())
.createdAt(ZonedDateTime.of(2020, 1, 2, 3, 4, 5, 0, ZoneOffset.UTC))
.updatedAt(ZonedDateTime.of(2020, 2, 3, 4, 5, 6, 0, ZoneOffset.UTC))
.content("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
.build();
}
public NoteEntity getNoteEntityA() {
return noteMapper.fromModel(getNoteModelA());
}
public UUID getNoteIdB() {
return UUID.fromString("6c8a639c-f509-486b-8e33-190719431894");
}
public UUID getPatientIdB() {
return UUID.fromString("23f40323-d9b7-4b75-bad7-670ed1187d5a");
}
public Note getNoteModelB() {
return Note.builder()
.id(getNoteIdB())
.patientId(getPatientIdB())
.createdAt(ZonedDateTime.of(2021, 11, 12, 13, 14, 15, 0, ZoneOffset.UTC))
.updatedAt(null)
.content("Morbi laoreet fringilla dui vitae hendrerit.\nOrci varius natoque penatibus et magnis.")
.build();
}
public NoteEntity getNoteEntityB() {
return noteMapper.fromModel(getNoteModelB());
}
public List<Note> getNoteModels() {
return new ArrayList<>(Arrays.asList(getNoteModelA(), getNoteModelB()));
}
public List<NoteEntity> getNoteEntities() {
return new ArrayList<>(Arrays.asList(getNoteEntityA(), getNoteEntityB()));
}
}
|
Java | UTF-8 | 5,723 | 1.9375 | 2 | [
"Apache-2.0"
] | permissive | /*******************************************************************************
* Copyright 2017 Albert Shun-Dat Chan
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*******************************************************************************/
package com.github.javalbert;
import java.sql.SQLException;
import com.github.javalbert.EntityByIdBenchmark.RetrievalHibernateStatelessSessionState;
import com.github.javalbert.EntityByIdBenchmark.RetrievalJdbcState;
import com.github.javalbert.EntityByIdBenchmark.RetrievalJooqState;
import com.github.javalbert.EntityByIdBenchmark.RetrievalSql2oState;
import com.github.javalbert.EntityByIdBenchmark.RetrievalSqlbuilderOrmState;
import com.github.javalbert.hibernate.DataTypeHolderHibernate;
public class EntityByIdNonJMH {
public long hibernateGetByIdTime;
public long hibernateQueryByIdTime;
public long jdbcTime;
public long jooqTime;
public long sql2oTime;
public long sqlbOrmGetByIdTime;
public long sqlbOrmQueryByIdTime;
private EntityByIdBenchmark benchmark = new EntityByIdBenchmark();
public void run() {
// Shut down Hibernate logging
// CREDIT: http://stackoverflow.com/a/18323888
java.util.logging.Logger.getLogger("org.hibernate").setLevel(java.util.logging.Level.OFF);
System.out.println("Warmup started");
for (int i = 0; i < 1000; i++) {
testHibernateGetById();
testHibernateQueryById();
testJdbc();
testJooq();
testSql2o();
testSqlbOrmGetById();
testSqlbOrmQueryById();
}
hibernateGetByIdTime = 0L;
hibernateQueryByIdTime = 0L;
jooqTime = 0L;
jdbcTime = 0L;
sql2oTime = 0L;
sqlbOrmGetByIdTime = 0L;
sqlbOrmQueryByIdTime = 0L;
try {
Thread.sleep(1000L);
System.out.println("Warmup ended");
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 1000; i++) {
testHibernateGetById();
testHibernateQueryById();
testJdbc();
testJooq();
testSql2o();
testSqlbOrmGetById();
testSqlbOrmQueryById();
}
print("Hibernate (get by ID)", hibernateGetByIdTime);
print("Hibernate (query by ID)", hibernateQueryByIdTime);
print("JDBC", jdbcTime);
print("jOOQ", jooqTime);
print("Sql2o", sql2oTime);
print("SqlbORM (get by ID)", sqlbOrmGetByIdTime);
print("SqlbORM (query by ID)", sqlbOrmQueryByIdTime);
}
public DataTypeHolderHibernate testHibernateGetById() {
RetrievalHibernateStatelessSessionState hibernateState = new RetrievalHibernateStatelessSessionState();
hibernateState.doSetup();
long start = System.nanoTime();
DataTypeHolderHibernate holder = benchmark.testRetrievalHibernateGetById(hibernateState);
hibernateGetByIdTime += System.nanoTime() - start;
hibernateState.doTearDown();
return holder;
}
public DataTypeHolderHibernate testHibernateQueryById() {
RetrievalHibernateStatelessSessionState hibernateState = new RetrievalHibernateStatelessSessionState();
hibernateState.doSetup();
long start = System.nanoTime();
DataTypeHolderHibernate holder = benchmark.testRetrievalHibernateQueryById(hibernateState);
hibernateQueryByIdTime += System.nanoTime() - start;
hibernateState.doTearDown();
return holder;
}
public DataTypeHolder testJdbc() {
try {
RetrievalJdbcState jdbcState = new RetrievalJdbcState();
jdbcState.doSetup();
long start = System.nanoTime();
DataTypeHolder holder = benchmark.testRetrievalJdbc(jdbcState);
jdbcTime += System.nanoTime() - start;
jdbcState.doTearDown();
return holder;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public DataTypeHolderHibernate testJooq() {
RetrievalJooqState jooqState = new RetrievalJooqState();
jooqState.doSetup();
long start = System.nanoTime();
DataTypeHolderHibernate holder = benchmark.testRetrievalJooq(jooqState);
jooqTime += System.nanoTime() - start;
jooqState.doTearDown();
return holder;
}
public DataTypeHolder testSql2o() {
RetrievalSql2oState sql2oState = new RetrievalSql2oState();
sql2oState.doSetup();
long start = System.nanoTime();
DataTypeHolder holder = benchmark.testRetrievalSql2o(sql2oState);
sql2oTime += System.nanoTime() - start;
sql2oState.doTearDown();
return holder;
}
public DataTypeHolder testSqlbOrmGetById() {
try {
RetrievalSqlbuilderOrmState sqlbOrmState = new RetrievalSqlbuilderOrmState();
sqlbOrmState.doSetup();
long start = System.nanoTime();
DataTypeHolder holder = benchmark.testRetrievalSqlbOrmGetById(sqlbOrmState);
sqlbOrmGetByIdTime += System.nanoTime() - start;
sqlbOrmState.doTearDown();
return holder;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public DataTypeHolder testSqlbOrmQueryById() {
try {
RetrievalSqlbuilderOrmState sqlbOrmState = new RetrievalSqlbuilderOrmState();
sqlbOrmState.doSetup();
long start = System.nanoTime();
DataTypeHolder holder = benchmark.testRetrievalSqlbOrmQueryById(sqlbOrmState);
sqlbOrmQueryByIdTime += System.nanoTime() - start;
sqlbOrmState.doTearDown();
return holder;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private void print(String library, long time) {
System.out.println(library + ": " + String.format("%.2f", time / 1000000.0));
}
}
|
C# | UTF-8 | 3,306 | 2.703125 | 3 | [
"MIT"
] | permissive | using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using GraphQL;
namespace CoreSharp.GraphQL.Configuration
{
public class TypeConfiguration<TType> : TypeConfiguration, ITypeConfiguration<TType>
{
public TypeConfiguration() : base(typeof(TType))
{
base.FieldName = typeof(TType).Name.ToCamelCase();
}
public ITypeConfiguration<TType> ForMember<TProperty>(Expression<Func<TType, TProperty>> propExpression, Action<IFieldConfiguration<TType, TProperty>> action)
{
var propName = propExpression.GetFullPropertyName();
var propInfo = ModelType.GetProperty(propName);
if (propInfo == null)
{
throw new NullReferenceException(string.Format("Type '{0}' does not contain a property with name '{1}'.", ModelType, propName));
}
IFieldConfiguration fieldConfiguration;
if (MemberConfigurations.ContainsKey(propName))
{
fieldConfiguration = MemberConfigurations[propName];
}
else
{
fieldConfiguration = new FieldConfiguration<TType, TProperty>(propInfo);
MemberConfigurations[propName] = fieldConfiguration;
}
if (action != null)
{
action((IFieldConfiguration<TType, TProperty>)fieldConfiguration);
}
return this;
}
public ITypeConfiguration<TType> Ignore()
{
Ignored = true;
return this;
}
public ITypeConfiguration<TType> Input(bool value)
{
base.Input = value;
return this;
}
public ITypeConfiguration<TType> Output(bool value)
{
base.Output = value;
return this;
}
public ITypeConfiguration<TType> ImplementInterface(Func<Type, bool> predicate)
{
base.ImplementInterface = predicate;
return this;
}
public ITypeConfiguration<TType> FieldName(string fieldName)
{
base.FieldName = fieldName;
return this;
}
}
public class TypeConfiguration : ITypeConfiguration
{
public Dictionary<string, object> Data { get; private set; }
public Type ModelType { get; set; }
public string FieldName { get; set; }
public Dictionary<string, IFieldConfiguration> MemberConfigurations { get; set; }
public bool? Ignored { get; set; }
public bool? Input { get; set; }
public bool? Output { get; set; }
public Func<Type, bool> ImplementInterface { get; set; }
protected TypeConfiguration(Type type)
{
Data = new Dictionary<string, object>();
MemberConfigurations = new Dictionary<string, IFieldConfiguration>();
ModelType = type;
FieldName = type.Name.ToCamelCase();
}
public IFieldConfiguration GetFieldConfiguration(string propertyName)
{
if (MemberConfigurations.ContainsKey(propertyName))
{
return MemberConfigurations[propertyName];
}
return null;
}
}
}
|
JavaScript | UTF-8 | 2,202 | 2.546875 | 3 | [] | no_license | const router = require('express').Router();
let RojakPoem = require('../models/rojakPoem.model');
let ActualPoem = require('../models/actualPoem.model');
let NewSauce = require('../models/newSauce.model');
router.route('/getRojakPoems').get((req, res) => {
RojakPoem.find().sort({ _id: -1 })
.then(poems => res.json(poems))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/getActualPoem').get((req, res) => {
ActualPoem.find()
.then(poems => res.json(poems))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/addRojakPoem').post((req, res) => {
const projectName = req.body.projectName;
const author = req.body.author;
const rojakPoem = req.body.rojakPoem;
const projectDescription = req.body.projectDescription
const newRojakPoem = new RojakPoem({
projectName,
author,
rojakPoem,
projectDescription
})
newRojakPoem.save()
.then(() => res.json('Poem added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/addActualPoem').post((req, res) => {
const title = req.body.title
const author = req.body.author;
const actualPoem = req.body.actualPoem;
const newActualPoem = new ActualPoem({
title,
author,
actualPoem,
})
newActualPoem.save()
.then(() => res.json('Poem added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/addSauce').post((req, res) => {
const poetName = req.body.poetName
const poemTitle = req.body.poemTitle;
const poem = req.body.poem;
const translation = req.body.translation
const newSauce = new NewSauce({
poetName,
poemTitle,
poem,
translation,
})
newSauce.save()
.then(() => res.json('Saunce uploaded!'))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/view/:id').get((req, res) => {
RojakPoem.findById(req.params.id)
.then(rojakPoem => res.json(rojakPoem))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
|
Python | UTF-8 | 109 | 2.8125 | 3 | [] | no_license | # -*- coding: cp1252 -*-
kierros = 0
while kierros < 5:
print("Olemme kierroksella",kierros)
kierros += 1 |
C | UTF-8 | 642 | 2.5625 | 3 | [] | no_license | #ifndef LISTAS
#define LISTAS
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
//Estruturas de dados
typedef struct tipoCelulah* apontador;
typedef struct{
int chave;
} tipoNo;
typedef struct tipoCelulah{
tipoNo no;
apontador prox;
} tipoCelula;
typedef struct {
apontador inicio;
apontador fim;
} tipoLista;
//Assinaturas das funcoes
void ImprimeNo(tipoNo no);
void InicializaNoSentinela(tipoNo* eNo);
void CriaListaVazia(tipoLista* eLista);
int EstaVazia(tipoLista lista);
void Insere(tipoLista* eLista, tipoNo noNovo);
//void Remove(tipoLista* eLista);
void ImprimeLista (tipoLista lista);
#endif
|
Java | UTF-8 | 1,205 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | package edu.neu.coe.info6205.union_find;
import java.util.Random;
public class UF_Client {
public static int count(int n){
//variable for no. of connections
int connections = 0;
UF_HWQUPC uf = new UF_HWQUPC(n);
Random r = new Random();
while (uf.components() > 2) {
connections++;
//Generating random pairs
int i = r.nextInt(n-1);
int j = r.nextInt(n-1);
if(uf.connected(i, j)) continue;
//When union is called the counter variable returned by uf.components() from UF_HWQUPC class decreases by 1.
uf.union(i, j);
}
return connections;
}
public static void main(String[] args) {
System.out.printf("%6s %6s %16s\n","n","m","(n*lg(n))/2");
System.out.printf("---------------------------------\n");
for (int n = 1000; n < 1000000; n *= 2) {
int count = 0;
for (int i = 0; i < 10; i++)
count += UF_Client.count(n);
System.out.printf("%7d | %7d | %8d |\n", n, count / 10, (int) (n*Math.log(n)/2));
}
}
}
|
JavaScript | UTF-8 | 1,175 | 4.3125 | 4 | [
"MIT"
] | permissive | // Exercise 1
function Car(name) {
this.name = name;
this.acceleration = 0;
this.honk = function() {
console.log("Toooooooooot!");
};
this.accelerate = function(speed) {
this.acceleration = this.acceleration + speed;
}
}
var car = new Car("BMW");
car.honk();
console.log(car.acceleration);
car.accelerate(10);
console.log(car.acceleration);
// Exercise 2
var baseObject = {
width: 0,
length: 0
};
var rectangle = Object.create(baseObject);
rectangle.width = 5;
rectangle.length = 2;
rectangle.calcSize = function() {
return this.width * this.length;
};
console.log(rectangle.calcSize());
// Exercise 3
var person = {
_firstName: ""
};
Object.defineProperty(person, "firstName", {
get: function () {
return this._firstName;
},
set: function (value) {
if (value.length > 3) {
this._firstName = value;
}
else {
this._firstName = "";
}
},
enumerable: true,
configurable: true
});
console.log(person.firstName);
person.firstName = "Ma";
console.log(person.firstName);
person.firstName = "Maximilian";
console.log(person.firstName);
|
Python | UTF-8 | 730 | 3.875 | 4 | [] | no_license | class MovingAverage:
def __init__(self, size: int):
"""
Initialize your data structure here.
"""
self.size = size
self.store = collections.deque()
self.sum = 0
self.full = False
def next(self, val: int) -> float:
self.store.append(val)
self.sum += val
if self.full:
head = self.store.popleft()
self.sum -= head
elif len(self.store) == self.size:
self.full = True
return float(self.sum/self.size) if self.full else float(self.sum/len(self.store))
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val) |
JavaScript | UTF-8 | 187 | 3.828125 | 4 | [] | no_license | let lista = [10, 58, 68, 88, 25, 45]
let soma = 0
for(let i = 0; i < lista.length; i++){
lista[i] = Math.pow(lista[i], 3)
soma += lista[i]
}
console.log(lista)
console.log(soma) |
TypeScript | UTF-8 | 1,022 | 2.84375 | 3 | [] | no_license | 'use strict';
const canvas = document.querySelector('.main-canvas') as HTMLCanvasElement;
const ctx = canvas.getContext('2d');
function drawTwoLines(startVertical: number, startHorizontalLeft: number, startHorizontalRight: number, color: string) {
ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(canvas.width / 2, startVertical);
ctx.lineTo(startHorizontalLeft, canvas.height / 2);
ctx.moveTo(canvas.width / 2, startVertical);
ctx.lineTo(startHorizontalRight, canvas.height / 2);
ctx.stroke();
}
function drawEnvelopeStar(stepFrequency: number, colorTop: string, colorBottom: string) {
let maxWidth = canvas.width / 2;
let maxWidth2 = canvas.width / 2;
for (let i = 0; i < canvas.width / 2 / stepFrequency; i++) {
drawTwoLines(i * stepFrequency, maxWidth, maxWidth2, colorTop);
drawTwoLines(canvas.width - i * stepFrequency, maxWidth, maxWidth2, colorBottom);
maxWidth += stepFrequency;
maxWidth2 -= stepFrequency;
}
}
drawEnvelopeStar(6, 'aquamarine', 'indianred' );
|
Java | UTF-8 | 1,874 | 3.375 | 3 | [] | no_license | import java.io.*;
public class Main {
public static void main(String[] args) {
String str = "MAKS hello BOBBY Sesuriti";
int a = str.indexOf("A");
int b = str.lastIndexOf("B");
System.out.println("Первое вхождение символа (А) в строке -> " + a);
System.out.println("Последнее вхождение символа (В) в строке -> " + b);
char byff[] = new char [b+1 - a ];//или str = str.substring(a,b);
str.getChars(a,b+1,byff,0);
System.out.print("Вырезанная подстрока из строки " + str +" начиная с первого вхождения символа(А) до,последнего вхождения сивола(B) -> " );
System.out.println( byff);
char nach = str.charAt(0);
char kon = str.charAt(3);
System.out.print("После замены всех вхождений символа стоящего в позиции (3) на сивол стоящий в позиции (0) -> ");
System.out.println(str.replace(kon,nach));
try(BufferedReader reader =new BufferedReader(new InputStreamReader(new FileInputStream("text.txt")));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("out.txt"))))
{
String line,line2 ;
while ((line = reader.readLine()) != null){
line2 = line.toLowerCase();
StringBuffer stringBuffer = new StringBuffer(line2);
stringBuffer.reverse();
if (line2.contentEquals(stringBuffer) && line.length() > 1){
writer.write(line);
writer.newLine();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
JavaScript | UTF-8 | 2,277 | 3.1875 | 3 | [] | no_license | class CartCard {
get stock() {
return this.card.stock.innerText;
}
set stock(stock) {
this.card.stock.innerText = stock;
}
constructor(name, price, stock, image) {
this.card = document.createElement('div');
this.card.classList.add('cart-card');
this.card.dataDiv = document.createElement('div');
this.card.dataDiv.classList.add('cart-card-data');
this.card.image = document.createElement('img');
this.card.image.classList.add('cart-card-image');
this.card.image.src = image;
this.card.removeButton = document.createElement('p');
this.card.removeButton.classList.add('cart-card-remove-button');
this.card.removeButton.innerText = 'X';
this.card.removeButton.addEventListener('click', () => {
this.card.parentNode.removeChild(this.card);
cart.items.forEach((item, index) => {
if(item.name === this.title.textContent) cart.items.splice(index, 1);
});
cart.cartCards.forEach((item, index) => {
if(item.title.textContent === this.title.textContent) cart.cartCards.splice(index, 1);
});
sessionStorage.setItem('cart', JSON.stringify({"items": cart.items}));
});
this.card.dataDiv.appendChild(this.card.removeButton);
this.title = document.createElement('p');
this.title.classList.add('cart-card-title');
this.title.appendChild(document.createTextNode(name));
this.card.dataDiv.appendChild(this.title);
this.card.price = document.createElement('p');
this.card.price.classList.add('cart-card-price');
this.card.price.appendChild(
document.createTextNode(
`$ ${parseInt(price) * parseInt(stock)}`
));
this.card.dataDiv.appendChild(this.card.price);
this.card.stock = document.createElement('p');
this.card.stock.classList.add('cart-card-stock');
this.card.stock.innerText = `quantity: ${stock}`;
this.card.dataDiv.appendChild(this.card.stock);
}
render() {
this.card.appendChild(this.card.image);
this.card.appendChild(this.card.dataDiv);
return this.card;
}
} |
JavaScript | UTF-8 | 2,224 | 4.0625 | 4 | [] | no_license | function LinkedList() {
this.head = null;
this.tail = null;
this.size = 0;
}
//Insert element in contant time O(1)
LinkedList.prototype.add = function(value) {
var node = {
value: value,
next: null
};
this.size++;
//List is empty, make head = tail = node O(1)
if(this.head==null)
return this.head = this.tail = node;
//Otherwise, Make node to be the next element of tail and re-make tail O(1)
this.tail.next = node;
return this.tail = node
};
//Given a node element, remove it from the list in linear time O(n).
LinkedList.prototype.remove = function(node) {
if(this.head !== null) {
if(this.head === node) {
this.size--;
this.head = this.head.next;
this.tail = (node === this.tail)?this.head:this.tail;
return node.value;
}
var current = this.head;
while(current.next) {
if(current.next === node) {
this.size--;
current.next = node.next;
this.tail = (node === this.tail)?current.next:this.tail;
return node.value;
}
current = current.next;
}
}
return null;
};
LinkedList.prototype.containsValue = function(value) {
if(this.head != null) {
if(this.head.value == value)
return true;
var current = this.head;
while(current.next) {
current = current.next;
if (current.value == value)
return true;
}
}
return false;
};
LinkedList.prototype.contains = function(node) {
if(this.head != null) {
if(this.head === node)
return true;
var current = this.head;
while(current.next) {
current = current.next;
if (current === node)
return true;
}
}
return false;
};
LinkedList.prototype.getAt = function(index) {
if(this.head !== null && this.size > index) {
var node = this.head;
for(var i=0;i<index;i++)
node = node.next;
return node;
}
return null;
};
LinkedList.prototype.count = function()
{return this.size;}; |
C# | UTF-8 | 2,209 | 3.421875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TpPooCSharp
{
class Program
{
private static Random random = new Random();
static void Main(string[] args)
{
DisplayMenu();
ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(true);
while(consoleKeyInfo.Key != ConsoleKey.D1 && consoleKeyInfo.Key != ConsoleKey.D2
&& consoleKeyInfo.Key != ConsoleKey.NumPad1 && consoleKeyInfo.Key != ConsoleKey.NumPad2)
{
DisplayMenu();
consoleKeyInfo = Console.ReadKey(true);
}
if (consoleKeyInfo.Key == ConsoleKey.D1 || consoleKeyInfo.Key == ConsoleKey.NumPad1)
Game();
else
Game2();
}
private static void DisplayMenu()
{
Console.Clear();
Console.WriteLine("Choose a game:");
Console.WriteLine("\t1: Against the monsters ");
Console.WriteLine("\t2: Against the Boss");
}
private static void Game()
{
Player gaia = new Player(150);
int cptEasy= 0;
int cptHard = 0;
while (gaia.IsAlive)
{
EasyMonster cuteMonster = MonsterFactory();
while (cuteMonster.IsAlive && gaia.IsAlive)
{
gaia.Attack(cuteMonster);
if (cuteMonster.IsAlive)
cuteMonster.Attack(gaia);
}
if (gaia.IsAlive)
{
if (cuteMonster is HardMonster)
cptHard++;
else
cptEasy++;
}
else
{
Console.WriteLine("oh nooo!, you are dead -_-");
break;
}
}
Console.WriteLine("Yeah!!! You killed {0} easy monsters and {1} hard monsters. You won {2} points.", cptEasy, cptHard, cptEasy + cptHard * 2);
}
private static EasyMonster MonsterFactory()
{
if (random.Next(2) == 0)
return new EasyMonster();
else
return new HardMonster();
}
private static void Game2()
{
Player veganUnicorn = new Player(150);
BossMonster boss = new BossMonster(250);
while (veganUnicorn.IsAlive && boss.IsAlive)
{
veganUnicorn.Attack(boss);
if (boss.IsAlive)
boss.Attack(veganUnicorn);
}
if (veganUnicorn.IsAlive)
Console.WriteLine("Yeah! You saved the princess unicorn!");
else
Console.WriteLine("Oh no no no! Game Over -_-");
}
}
}
|
Java | UTF-8 | 511 | 2.171875 | 2 | [] | no_license | package com.example.demo;
import org.springframework.data.jdbc.repository.query.Modifying;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.Optional;
public interface StudentRepository extends CrudRepository<Student, String> {
@Query("SELECT id,name,sex,classroom FROM student WHERE name=:name")
Optional<Student> findByName(@Param("name") String name);
}
|
Java | UTF-8 | 2,164 | 2.484375 | 2 | [] | no_license | package com.prankit.contactmanager.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.prankit.contactmanager.Model.CallLogModel;
import com.prankit.contactmanager.R;
import java.util.ArrayList;
public class CallLogAdapter extends RecyclerView.Adapter<CallLogAdapter.ViewHolder> {
private Context context;
private ArrayList<CallLogModel> callLogArrayList;
public CallLogAdapter(Context context, ArrayList<CallLogModel> callLogArrayList) {
this.context = context;
this.callLogArrayList = callLogArrayList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_contact_view, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.show_name.setVisibility(View.GONE);
holder.show_num.setVisibility(View.GONE);
holder.name.setText(callLogArrayList.get(position).getNumber());
holder.number.setText(callLogArrayList.get(position).getTime() + " " +
callLogArrayList.get(position).getType() + " " + callLogArrayList.get(position).getDate()+"/"+
callLogArrayList.get(position).getMonth()+"/"+callLogArrayList.get(position).getYear());
}
@Override
public int getItemCount() {
return callLogArrayList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder{
TextView name, number, show_name, show_num;
public ViewHolder(@NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.show_name);
number = itemView.findViewById(R.id.show_mobile);
show_name = itemView.findViewById(R.id.show_name_textView);
show_num = itemView.findViewById(R.id.show_number_textView);
}
}
}
|
Python | UTF-8 | 421 | 3.046875 | 3 | [] | no_license | dct = {"L": (-1, 0), "R": (1, 0), "U": (0, 1), "D": (0, -1)}
def prog(dat):
d = {}
x, y = 0, 0
val = 0
d[(0, 0)] = 0
for ch in dat:
val += 1
dx, dy = dct[ch]
x += dx
y += dy
if (x, y) in d:
return "BUG"
d[(x, y)] = val
for ch1 in "LRUD":
dx, dy = dct[ch1]
if (x + dx, y + dy) in d and d[(x + dx, y + dy)] < val - 1:
return "BUG"
return "OK"
dat = raw_input()
#print dat
print prog(dat)
|
Java | UTF-8 | 713 | 2.046875 | 2 | [] | no_license | package pe.com.interbank.pys.aperturatcv2.microservices.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
public class DatosCliente {
private Cliente cliente;
private ListaIntegranteType integrantes;
public DatosCliente(@JsonProperty("cliente") Cliente cliente,
@JsonProperty("integrantes") ListaIntegranteType integrantes) {
this.cliente = cliente;
this.integrantes = integrantes;
}
public Cliente getCliente() {
return cliente;
}
public void setCliente(Cliente cliente) {
this.cliente = cliente;
}
public ListaIntegranteType getIntegrantes() {
return integrantes;
}
public void setIntegrantes(ListaIntegranteType integrantes) {
this.integrantes = integrantes;
}
}
|
Markdown | UTF-8 | 5,147 | 2.546875 | 3 | [] | no_license | ---
description: "Recipe of Perfect Red lobster cheddar bay biscuit Finale"
title: "Recipe of Perfect Red lobster cheddar bay biscuit Finale"
slug: 430-recipe-of-perfect-red-lobster-cheddar-bay-biscuit-finale
date: 2020-08-30T15:10:39.597Z
image: https://img-global.cpcdn.com/recipes/5650084866293760/751x532cq70/red-lobster-cheddar-bay-biscuit-finale-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/5650084866293760/751x532cq70/red-lobster-cheddar-bay-biscuit-finale-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/5650084866293760/751x532cq70/red-lobster-cheddar-bay-biscuit-finale-recipe-main-photo.jpg
author: Jose Fields
ratingvalue: 4.3
reviewcount: 15
recipeingredient:
- "1 box of red lobster cheddar bay biscuit"
- "1 can rotel"
- "1 shredded cheese to ur liking"
- "1 blue chees crumbles"
- "2 jiffy cornbread"
recipeinstructions:
- "Follow mixing directions for both red lobster biscuits and cornbread"
- "Cook ground beef as normal..add rotel when cooked and mix with spices to ur liking"
- "Preheat oven to 425"
- "Use normal baking pan or dish for cornbread"
- "Pour just enough cornbread mix in bottom of pan to cover bottom"
- "Pour ground beef mixture on top of cornbread layer evenly"
- "Top with cheese to liking"
- "Pour rest of cornbread mix on top...add more cheese"
- "Top off with red lobster biscuit mix in multiple sections .try to even out"
- "Put in oven for 20-25 min or until golden brown"
- "Midway too with blue cheese crumbles and shredded cheese"
- "Pour red lobster butter mix on top when done..let it soak in..then enjoy 😎😎😎"
categories:
- Recipe
tags:
- red
- lobster
- cheddar
katakunci: red lobster cheddar
nutrition: 251 calories
recipecuisine: American
preptime: "PT35M"
cooktime: "PT56M"
recipeyield: "1"
recipecategory: Dinner
---

Hey everyone, it is me again, Dan, welcome to my recipe site. Today, I'm gonna show you how to prepare a special dish, red lobster cheddar bay biscuit finale. It is one of my favorites. This time, I will make it a bit unique. This will be really delicious.
Follow mixing directions for both red lobster biscuits and cornbread. Cook ground beef as normal. add rotel when cooked and mix with spices to ur liking. And these cheddar bay biscuits are no exception.
Red lobster cheddar bay biscuit Finale is one of the most well liked of current trending foods in the world. It's simple, it's quick, it tastes delicious. It's enjoyed by millions every day. Red lobster cheddar bay biscuit Finale is something which I've loved my whole life. They are fine and they look wonderful.
To get started with this recipe, we must first prepare a few components. You can cook red lobster cheddar bay biscuit finale using 5 ingredients and 12 steps. Here is how you can achieve that.
<!--inarticleads1-->
##### The ingredients needed to make Red lobster cheddar bay biscuit Finale:
1. Make ready 1 box of red lobster cheddar bay biscuit
1. Take 1 can rotel
1. Make ready 1 shredded cheese (to ur liking)
1. Prepare 1 blue chees crumbles
1. Get 2 jiffy cornbread
Spoon butter mixture over hot biscuits. Red Lobster Cheddar Bay Biscuits Recipe - These cheesy, soft biscuits have a hint of garlic and are topped with melted butter and fresh parsley. It's easy to make your favorite Red Lobster cheese biscuits at home from scratch! These biscuits could not be easier.
<!--inarticleads2-->
##### Instructions to make Red lobster cheddar bay biscuit Finale:
1. Follow mixing directions for both red lobster biscuits and cornbread
1. Cook ground beef as normal..add rotel when cooked and mix with spices to ur liking
1. Preheat oven to 425
1. Use normal baking pan or dish for cornbread
1. Pour just enough cornbread mix in bottom of pan to cover bottom
1. Pour ground beef mixture on top of cornbread layer evenly
1. Top with cheese to liking
1. Pour rest of cornbread mix on top...add more cheese
1. Top off with red lobster biscuit mix in multiple sections .try to even out
1. Put in oven for 20-25 min or until golden brown
1. Midway too with blue cheese crumbles and shredded cheese
1. Pour red lobster butter mix on top when done..let it soak in..then enjoy 😎😎😎
Quite possibly the easiest biscuit I have ever made! There is a trick to really replicating the beauty This recipe is technically a copycat of Red Lobster's Cheddar Bay Biscuit! Soft, buttery, salty and cheesy… it is the perfect compliment to dinner! Red Lobster Cheddar Bay Biscuits are easier AND tastier than a box mix! You may have noticed a lack of seafood recipes on this site.
So that's going to wrap this up for this special food red lobster cheddar bay biscuit finale recipe. Thanks so much for reading. I'm confident that you can make this at home. There's gonna be more interesting food in home recipes coming up. Remember to save this page on your browser, and share it to your loved ones, colleague and friends. Thanks again for reading. Go on get cooking!
|
Python | UTF-8 | 1,327 | 3.21875 | 3 | [] | no_license | from collections import deque
from discord_bot.discord_interface.config import config
from discord_bot.discord_interface.audioelements.dummy import Dummy
class Playlist:
"""Stores the youtube links of songs to be played and already played and offers basic operation on the queues"""
def __init__(self):
# Stores the ytlinks os the songs in queue and the ones already played
self.playque = deque()
self.playhistory = deque()
def __len__(self):
return len(self.playque)
def add(self, track):
self.playque.append(track)
def next(self):
if len(self.playque) == 0:
return None
song_played = self.playque.popleft()
if not isinstance(song_played, Dummy):
self.playhistory.append(song_played)
if len(self.playhistory) > config.MAX_HISTORY_LENGTH:
self.playhistory.popleft()
if len(self.playque) == 0:
return None
return self.playque[0]
def prev(self):
if len(self.playhistory) == 0:
dummy = Dummy()
self.playque.appendleft(dummy)
return dummy
self.playque.appendleft(self.playhistory.pop())
return self.playque[0]
def empty(self):
self.playque.clear()
self.playhistory.clear()
|
Java | UTF-8 | 394 | 2.84375 | 3 | [] | no_license | package com.freedom.composite;
/**
* 叶子对象,叶子对象不再包含其他对象
*
* @author liuf
* date: 2020-02-05
*/
public class Leaf extends Component {
private String name = "";
/**
* 示意方法,子叶子对象的操作
*/
@Override
public void printStruct(String preStr) {
System.out.println("叶子对象的操作" + preStr);
}
}
|
Java | UTF-8 | 8,061 | 2.328125 | 2 | [
"Apache-2.0"
] | permissive | package net.minestom.server.listener;
import net.minestom.server.MinecraftServer;
import net.minestom.server.data.Data;
import net.minestom.server.entity.Entity;
import net.minestom.server.entity.GameMode;
import net.minestom.server.entity.Player;
import net.minestom.server.event.player.PlayerBlockInteractEvent;
import net.minestom.server.event.player.PlayerBlockPlaceEvent;
import net.minestom.server.event.player.PlayerUseItemOnBlockEvent;
import net.minestom.server.instance.Chunk;
import net.minestom.server.instance.Instance;
import net.minestom.server.instance.block.Block;
import net.minestom.server.instance.block.BlockFace;
import net.minestom.server.instance.block.BlockManager;
import net.minestom.server.instance.block.CustomBlock;
import net.minestom.server.instance.block.rule.BlockPlacementRule;
import net.minestom.server.inventory.PlayerInventory;
import net.minestom.server.item.ItemStack;
import net.minestom.server.item.Material;
import net.minestom.server.network.packet.client.play.ClientPlayerBlockPlacementPacket;
import net.minestom.server.utils.BlockPosition;
import net.minestom.server.utils.Direction;
import net.minestom.server.utils.chunk.ChunkUtils;
import net.minestom.server.utils.validate.Check;
import java.util.Set;
public class BlockPlacementListener {
private static final BlockManager BLOCK_MANAGER = MinecraftServer.getBlockManager();
public static void listener(ClientPlayerBlockPlacementPacket packet, Player player) {
final PlayerInventory playerInventory = player.getInventory();
final Player.Hand hand = packet.hand;
final BlockFace blockFace = packet.blockFace;
final BlockPosition blockPosition = packet.blockPosition;
final Direction direction = blockFace.toDirection();
final Instance instance = player.getInstance();
if (instance == null)
return;
// Prevent outdated/modified client data
if (!ChunkUtils.isLoaded(instance.getChunkAt(blockPosition))) {
// Client tried to place a block in an unloaded chunk, ignore the request
return;
}
final ItemStack usedItem = player.getItemInHand(hand);
// Interact at block
final boolean cancel = usedItem.onUseOnBlock(player, hand, blockPosition, direction);
PlayerBlockInteractEvent playerBlockInteractEvent = new PlayerBlockInteractEvent(player, blockPosition, hand, blockFace);
playerBlockInteractEvent.setCancelled(cancel);
playerBlockInteractEvent.setBlockingItemUse(cancel);
player.callCancellableEvent(PlayerBlockInteractEvent.class, playerBlockInteractEvent, () -> {
final CustomBlock customBlock = instance.getCustomBlock(blockPosition);
if (customBlock != null) {
final Data data = instance.getBlockData(blockPosition);
final boolean blocksItem = customBlock.onInteract(player, hand, blockPosition, data);
if (blocksItem) {
playerBlockInteractEvent.setBlockingItemUse(true);
}
}
});
if (playerBlockInteractEvent.isBlockingItemUse()) {
return;
}
final Material useMaterial = usedItem.getMaterial();
// Verify if the player can place the block
{
if (useMaterial == Material.AIR) { // Can't place air
return;
}
if (player.getGameMode().equals(GameMode.ADVENTURE)) { // Can't place in adventure mode
return;
}
}
// Get the newly placed block position
final int offsetX = blockFace == BlockFace.WEST ? -1 : blockFace == BlockFace.EAST ? 1 : 0;
final int offsetY = blockFace == BlockFace.BOTTOM ? -1 : blockFace == BlockFace.TOP ? 1 : 0;
final int offsetZ = blockFace == BlockFace.NORTH ? -1 : blockFace == BlockFace.SOUTH ? 1 : 0;
blockPosition.add(offsetX, offsetY, offsetZ);
final Chunk chunk = instance.getChunkAt(blockPosition);
Check.stateCondition(!ChunkUtils.isLoaded(chunk),
"A player tried to place a block in the border of a loaded chunk " + blockPosition);
// The concerned chunk will be send to the player if an error occur
// This will ensure that the player has the correct version of the chunk
boolean refreshChunk = false;
if (useMaterial.isBlock()) {
if (!chunk.isReadOnly()) {
final Block block = useMaterial.getBlock();
final Set<Entity> entities = instance.getChunkEntities(chunk);
// Check if the player is trying to place a block in an entity
boolean intersect = false;
if (block.isSolid()) {
for (Entity entity : entities) {
intersect = entity.getBoundingBox().intersect(blockPosition);
if (intersect)
break;
}
}
if (!intersect) {
// BlockPlaceEvent check
PlayerBlockPlaceEvent playerBlockPlaceEvent = new PlayerBlockPlaceEvent(player, block, blockPosition, packet.hand);
playerBlockPlaceEvent.consumeBlock(player.getGameMode() != GameMode.CREATIVE);
player.callEvent(PlayerBlockPlaceEvent.class, playerBlockPlaceEvent);
if (!playerBlockPlaceEvent.isCancelled()) {
// BlockPlacementRule check
final Block resultBlock = Block.fromStateId(playerBlockPlaceEvent.getBlockStateId());
final BlockPlacementRule blockPlacementRule = BLOCK_MANAGER.getBlockPlacementRule(resultBlock);
final short blockStateId = blockPlacementRule == null ? resultBlock.getBlockId() :
blockPlacementRule.blockPlace(instance, resultBlock, blockFace, blockPosition, player);
final boolean placementRuleCheck = blockStateId != BlockPlacementRule.CANCEL_CODE;
if (placementRuleCheck) {
// Place the block
final short customBlockId = playerBlockPlaceEvent.getCustomBlockId();
if (customBlockId != 0) {
instance.setSeparateBlocks(blockPosition, blockStateId, customBlockId);
} else {
instance.setBlockStateId(blockPosition, blockStateId);
}
// Block consuming
if (playerBlockPlaceEvent.doesConsumeBlock()) {
// Consume the block in the player's hand
final ItemStack newUsedItem = usedItem.consume(1);
if (newUsedItem != null) {
playerInventory.setItemInHand(hand, newUsedItem);
}
}
} else {
refreshChunk = true;
}
} else {
refreshChunk = true;
}
} else {
refreshChunk = true;
}
} else {
refreshChunk = true;
}
} else {
// Player didn't try to place a block but interacted with one
PlayerUseItemOnBlockEvent event = new PlayerUseItemOnBlockEvent(player, hand, usedItem, blockPosition, direction);
player.callEvent(PlayerUseItemOnBlockEvent.class, event);
refreshChunk = true;
}
// Refresh chunk section if needed
if (refreshChunk) {
chunk.sendChunkSectionUpdate(ChunkUtils.getSectionAt(blockPosition.getY()), player);
}
player.getInventory().refreshSlot(player.getHeldSlot());
}
}
|
Java | UTF-8 | 1,060 | 2 | 2 | [] | no_license | package com.intuit.demo.model;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Data
@Table(name = "Player")
public class Player
{
@Id
@Column
private String playerID;
@Column
private String birthYear;
@Column
private String birthMonth;
@Column
private String birthDay;
@Column
private String birthCountry;
@Column
private String birthState;
@Column
private String birthCity;
@Column
private String deathYear;
private String deathMonth;
private String deathDay;
private String deathCountry;
private String deathState;
private String deathCity;
private String nameFirst;
private String nameLast;
private String nameGiven;
private String weight;
private String height;
private String bats;
private String throwsDone;
private String debut;
private String finalGame;
private String retroID;
private String bbrefID;
}
|
Java | UTF-8 | 786 | 3.203125 | 3 | [] | no_license |
public class PalindromeNumber {
public boolean isPalindrome(int x) {
if(x < 0)
{
return false;
}
int head = x;
int tail;
int count = 0;
while(head >= 10)
{
head = head/10;
count++;
}
while (count >= 1)
{
tail = x%10;
head = x;
for (int i = 0; i < count; i++)
{
head = head/10;
}
if(head != tail)
{
return false;
}
for (int i = 0; i < count; i++)
{
head = head*10;
}
x = x-head;
x = x/10;
count = count-2;
}
return true;
}
}
|
C++ | UTF-8 | 929 | 2.734375 | 3 | [] | no_license | int vermelho=8;
int verde=10;
int amarelo=6;
char leitura;
void setup() {
Serial.begin(9600);
pinMode(vermelho,OUTPUT);
pinMode(verde,OUTPUT);
pinMode(amarelo,OUTPUT);
Serial.println("digite uma tecla");
}
void loop() {
if(Serial.available()>0){
leitura=Serial.read();
Serial.print("Tecla digitada => ");
Serial.println(leitura);
if(leitura=='R'){
digitalWrite(vermelho,1);
}
if(leitura=='r'){
digitalWrite(vermelho,0);
}
if(leitura=='G'){
digitalWrite(verde,1);
}
if(leitura=='g'){
digitalWrite(verde,0);
}
if(leitura=='Y'){
digitalWrite(amarelo,1);
}
if(leitura=='y'){
digitalWrite(amarelo,0);
}
if(leitura=='A' || leitura== 'a'){
digitalWrite(vermelho,1);
digitalWrite(verde,1);
digitalWrite(amarelo,1);
}
if(leitura=='C' || leitura== 'c'){
digitalWrite(vermelho,0);
digitalWrite(verde,0);
digitalWrite(amarelo,0);
}
}
}
|
Swift | UTF-8 | 1,976 | 3.234375 | 3 | [] | no_license | import UIKit
import HanziPinyin
extension String {
subscript (i: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return String(self[start..<end])
}
subscript (r: ClosedRange<Int>) -> String {
let start = index(startIndex, offsetBy: r.lowerBound)
let end = index(startIndex, offsetBy: r.upperBound)
return String(self[start...end])
}
func removeWhitespace() -> String {
return replacingOccurrences(of: " ", with: "")
}
}
extension String {
func stripNonNumericsFromString() -> Int {
let stringArray = self.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
if let number = Int(item) {
return number
}
}
return 0
}
}
extension String {
func toneNumber() -> Int {
guard self.hasChineseCharacter else { return 0 }
let outputFormat = PinyinOutputFormat(toneType: .toneNumber, vCharType: .vCharacter, caseType: .lowercased)
let toneNumber = self.toPinyin(withFormat: outputFormat, separator: " ").stripNonNumericsFromString()
return toneNumber
}
}
extension String {
func transformToPinYin() -> String {
let mutableString = NSMutableString(string: self)
//把汉字转为拼音
CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
//去掉拼音的音标
CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
let string = String(mutableString)
//去掉空格
return string.replacingOccurrences(of: " ", with: "")
}
}
|
TypeScript | UTF-8 | 411 | 3.75 | 4 | [
"MIT"
] | permissive | /**
* @category 字符 string
* @function 数字补零操作
* @param {unknown} value 值
* @return {boolean}
* @example
* isString(5) => false
* @example
* isString('111') => true
*/
export function isString(value: unknown): boolean {
const _toString = Object.prototype.toString
const type: string = _toString.call(value).split(' ')[1].replace(']', '')
return type.toLowerCase() === 'string'
}
|
Markdown | UTF-8 | 4,040 | 2.625 | 3 | [] | no_license | ---
description: "Recipe of Any-night-of-the-week Sundubu Jjigae (Spicy Tofu Stew)"
title: "Recipe of Any-night-of-the-week Sundubu Jjigae (Spicy Tofu Stew)"
slug: 341-recipe-of-any-night-of-the-week-sundubu-jjigae-spicy-tofu-stew
date: 2020-08-09T14:37:33.239Z
image: https://img-global.cpcdn.com/recipes/2620365_de4984ab25228a5b/751x532cq70/sundubu-jjigae-spicy-tofu-stew-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/2620365_de4984ab25228a5b/751x532cq70/sundubu-jjigae-spicy-tofu-stew-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/2620365_de4984ab25228a5b/751x532cq70/sundubu-jjigae-spicy-tofu-stew-recipe-main-photo.jpg
author: Cornelia Flores
ratingvalue: 5
reviewcount: 9
recipeingredient:
- "1 pack soft tofu"
- "100 g meats 100 g seafood clams prawns mussels crab squid etc you can choose what your favorite item"
- " Green onions"
- "1 Onion minced"
- "3-4 cloves garlic minced"
- "1 Chili minced"
- "1 tsp soy saucefish sauce"
- "4 tsp chili powder"
- "2 tsp sesame oil"
- "2 slices kombu dashi for stock"
- "250 ml water"
- "1 egg"
recipeinstructions:
- "Make the kombu stock, just boil water with kombu/dashi for 5 minutes."
- "Heat the hot pot and put sesame oil, minced garlics, minced onions, and chili powder, stir for 5 minutes until mix well."
- "Put the stock and soy sauce, mix well."
- "When the stock boils, put the remaining ingredients like green onions, meats/seafood, and tofu, cooking for 5 minutes and the lastly put egg on the top."
categories:
- Recipe
tags:
- sundubu
- jjigae
- spicy
katakunci: sundubu jjigae spicy
nutrition: 150 calories
recipecuisine: American
preptime: "PT38M"
cooktime: "PT53M"
recipeyield: "4"
recipecategory: Lunch
---

Hey everyone, it's me again, Dan, welcome to my recipe site. Today, I will show you a way to prepare a special dish, sundubu jjigae (spicy tofu stew). One of my favorites food recipes. This time, I am going to make it a little bit tasty. This is gonna smell and look delicious.
Sundubu Jjigae (Spicy Tofu Stew) is one of the most favored of current trending meals in the world. It's simple, it's fast, it tastes delicious. It is appreciated by millions daily. Sundubu Jjigae (Spicy Tofu Stew) is something which I've loved my whole life. They're nice and they look fantastic.
To get started with this particular recipe, we must prepare a few components. You can cook sundubu jjigae (spicy tofu stew) using 12 ingredients and 4 steps. Here is how you cook that.
<!--inarticleads1-->
##### The ingredients needed to make Sundubu Jjigae (Spicy Tofu Stew):
1. Make ready 1 pack soft tofu
1. Make ready 100 g meats / 100 g seafood (clams, prawns, mussels, crab, squid, etc), you can choose what your favorite item
1. Take Green onions
1. Get 1 Onion, minced
1. Take 3-4 cloves garlic, minced
1. Take 1 Chili, minced
1. Make ready 1 tsp soy sauce/fish sauce
1. Prepare 4 tsp chili powder
1. Prepare 2 tsp sesame oil
1. Take 2 slices kombu/ dashi for stock
1. Prepare 250 ml water
1. Prepare 1 egg
<!--inarticleads2-->
##### Instructions to make Sundubu Jjigae (Spicy Tofu Stew):
1. Make the kombu stock, just boil water with kombu/dashi for 5 minutes.
1. Heat the hot pot and put sesame oil, minced garlics, minced onions, and chili powder, stir for 5 minutes until mix well.
1. Put the stock and soy sauce, mix well.
1. When the stock boils, put the remaining ingredients like green onions, meats/seafood, and tofu, cooking for 5 minutes and the lastly put egg on the top.
So that's going to wrap it up for this exceptional food sundubu jjigae (spicy tofu stew) recipe. Thank you very much for reading. I'm sure you can make this at home. There's gonna be interesting food in home recipes coming up. Remember to save this page on your browser, and share it to your loved ones, colleague and friends. Thanks again for reading. Go on get cooking!
|
Python | UTF-8 | 1,889 | 2.703125 | 3 | [] | no_license | from fonction_reference import reference
import cv2
import time
import numpy as np
nom_fichier = "videos_test/video_rasp_1.avi"
capture = cv2.VideoCapture(nom_fichier)#Ouverture du fichier vidéo
while cv2.waitKey(15)!=27:
debut = time.clock()
has_frame, img_init = capture.read()
if not has_frame:
capture.release()#Si on est arrivé à la fin de la vidéo, on la ferme puis la relance
capture = cv2.VideoCapture(nom_fichier)
has_frame, img_init = capture.read()
n_image=1
if not has_frame:
print("error reading the frame")
break
img_init = cv2.flip(img_init, -1)#remet dans le bon sens l'image issue de la caméra du Raspberry pi
ok, point1, point2, point3, point4 = reference(img_init)
if ok == 0:
#il y a eu une erreur
img_init = cv2.putText(img_init, "ERREUR", (img_init.shape[1]//10,img_init.shape[0]//3), cv2.FONT_HERSHEY_PLAIN, 4, 255, thickness=4)
else:
img_init = cv2.circle(img_init, point1, 10, [255,0,255], 3)
img_init = cv2.circle(img_init, point2, 10, [0,0,255], 3)
img_init = cv2.circle(img_init, point3, 10, [255,0,0], 3)
img_init = cv2.circle(img_init, point4, 10, [0,255,0], 3)
img_init = cv2.putText(img_init, "temps total d'execution : "+str(int((time.clock()-debut)*1000))+" ms", (8,30), cv2.FONT_HERSHEY_PLAIN, 2, 255, thickness=2)
img_init = cv2.putText(img_init, "point1", (8,60), cv2.FONT_HERSHEY_PLAIN, 2, [255,0,255], thickness=2)
img_init = cv2.putText(img_init, "point2", (8,90), cv2.FONT_HERSHEY_PLAIN, 2, [0,0,255], thickness=2)
img_init = cv2.putText(img_init, "point3", (8,120), cv2.FONT_HERSHEY_PLAIN, 2, [255,0,0], thickness=2)
img_init = cv2.putText(img_init, "point4", (8,150), cv2.FONT_HERSHEY_PLAIN, 2, [0,255,0], thickness=2)
cv2.imshow("resultat", img_init)
|
C++ | UTF-8 | 1,062 | 3.3125 | 3 | [] | no_license | #ifndef Rectangle_HEADER
#define Rectangle_HEADER
/**
* File : Rectangle.h
* Author : Kazune Takahashi
* Created : 8/21/2019, 3:57:01 PM
* Powered by Visual Studio Code
*/
#include <iostream>
#include <string>
#include <sstream>
#include "Shape.h"
#include "TwoDimensional.h"
class Rectangle : public Shape, public TwoDimensional
{
int width, height;
public:
Rectangle(int w, int h) : width{w}, height{h} {}
Rectangle *clone() const
{
return new Rectangle(width, height);
}
void draw() const
{
for (auto i = 0; i < height; i++)
{
for (auto j = 0; j < width; j++)
{
std::cout << '*';
}
std::cout << std::endl;
}
}
std::string to_string() const
{
std::ostringstream ss{};
ss << "Rectangle(width: " << width << ", height:" << height << ")";
return ss.str();
}
void debug() const
{
Shape::debug();
std::cout << "width: " << width << ", height:" << height << std::endl;
}
double get_area() const
{
return width * height;
}
};
#endif // Rectangle_HEADER |
Java | UTF-8 | 1,027 | 2.15625 | 2 | [] | no_license | package dionysus.wine.vo;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class Customer {
private int customerId;
private String customerRrn;
private String customerAddress;
private String customerName;
private String customerTel;
private String customerGender;
private String customerAccountNo;
private String customerJob;
private String customerActivated;
private int basicInfoId;
public Customer(String customerRrn, String customerAddress, String customerName, String customerTel,
String customerGender, String customerAccountNo, String customerJob, int basicInfoId) {
super();
this.customerRrn = customerRrn;
this.customerAddress = customerAddress;
this.customerName = customerName;
this.customerTel = customerTel;
this.customerGender = customerGender;
this.customerAccountNo = customerAccountNo;
this.customerJob = customerJob;
this.basicInfoId = basicInfoId;
}
}
|
Markdown | UTF-8 | 1,503 | 3.703125 | 4 | [] | no_license | # TimeWarp
## Time ranges from natural language
TimeWarp makes describing recurring time ranges easy! It has **no external dependencies** and is useful for articulating dates, times, and recurrances for natural language processing.
## Usage
```go
import (
"bytes"
"github.com/takeinitiative/timewarp"
)
func main() {
// initialize the range to filter from
in := timewarp.TimeRange{
Start: time.Now().AddDate(0, -1, 0),
End: time.Now().AddDate(0, 1, 0),
}
// define the recurrance that we want to parse (every Tuesday)
p := timewarp.NewParser(bytes.NewParser("DAY TUESDAY"))
// get the filter function
filter, err := p.Parse()
if err != nil {
panic(err)
}
// print all the time ranges
times := filter(in)
for _, t := range times {
fmt.Println(t.Start, t.End)
}
}
```
## Parser Syntax
TimeWarp uses a basis syntax parser to procedurally generate functions that will find all time ranges that apply to the input timerange.
### Example: The second Tuesday of March from 12-2p
Syntax: `DAY TUESDAY OF 2 MONTH MARCH IN TIME 1200 1400`
### Example: Fridays through Sundays and Wednesdays
Syntax: `DAY FRIDAY SUNDAY AND WEDNESDAY`
### Example: July 15, 2008
Syntax: `DAY 15 OF MONTH JULY IN YEAR 2008`
### Example: Weekdays from 5-11a except Tuesdays
Syntax: `DAY MONDAY FRIDAY IN TIME 0500 1100 AND NOT DAY TUESDAY`
### Example: Every other Saturday
Syntax: `DAY SATURDAY OF 2 WEEK SATURDAY`
|
C++ | UTF-8 | 359 | 2.59375 | 3 | [] | no_license | #ifndef SUBJECT_HPP
#define SUBJECT_HPP
#include <vector>
#include <list>
#include "Observer.hpp"
class Subject
{
//Lets keep a track of all the shops we have observing
std::vector<Observer*> list;
public:
void attach(Observer *product);
void detach(Observer *product);
void notify(int room, float temp);
};
#endif |
Java | UTF-8 | 1,163 | 2.140625 | 2 | [] | no_license | package pe.oh29oh29.develogm.controller.main;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import pe.oh29oh29.develogm.model.Post;
import pe.oh29oh29.develogm.model.request.PostReq;
import pe.oh29oh29.develogm.model.response.PostRes;
import pe.oh29oh29.develogm.service.PostService;
@RestController
@RequestMapping("/post")
public class MPostController {
@Autowired
PostService postService;
@PostMapping("")
public ResponseEntity<Post> addPost(@RequestBody Post post) {
return ResponseEntity.ok(postService.savePost(post));
}
@GetMapping("")
public ResponseEntity<PostRes> getPosts(PostReq postReq) {
return ResponseEntity.ok(postService.getPosts(postReq));
}
@GetMapping("/detail")
public ResponseEntity<PostRes> getPost(PostReq postReq) {
return ResponseEntity.ok(postService.getPost(postReq));
}
@DeleteMapping("")
public ResponseEntity deletePost(PostReq postReq) {
postService.deletePost(postReq);
return ResponseEntity.ok().build();
}
}
|
Markdown | UTF-8 | 1,884 | 3.5 | 4 | [] | no_license | # 一、题目
你的任务是计算 a^b 对 1337 取模,a 是一个正整数,b 是一个非常大的正整数且会以数组形式给出。
**示例 1:**
```
输入:a = 2, b = [3]
输出:8
```
**示例 2:**
```
输入:a = 2, b = [1,0]
输出:1024
```
**示例 3:**
```
输入:a = 1, b = [4,3,3,8,5,2]
输出:1
```
**示例 4:**
```
输入:a = 2147483647, b = [2,0,0]
输出:1198
```
**提示:**
- 1 <= a <= 2^31 - 1
- 1 <= b.length <= 2000
- 0 <= b[i] <= 9
- b 不含前导 0
来源:力扣(LeetCode)
链接:[https://leetcode-cn.com/problems/super-pow](https://leetcode-cn.com/problems/super-pow)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# 二、分析及代码
## 1. 遍历
### (1)思路
结合快速幂算法,对指数从高位至低位(或从低位至高位)依次计算,详细分析可见[官方题解](https://leetcode-cn.com/problems/super-pow/solution/chao-ji-ci-fang-by-leetcode-solution-ow8j/)。
### (2)代码
```cpp
class Solution {
const int MOD = 1337;
int pow(int base, int exp) {//快速幂
int res = 1;
while (exp > 0) {
if (exp & 1) {
res = (long)res * base % MOD;
}
exp >>= 1;
base = (long)base * base % MOD;
}
return res;
}
public:
int superPow(int a, vector<int>& b) {
int ans = 1;
for (int i = 0; i < b.size(); i++) {//从高位至低位依次计算
ans = (long)pow(ans, 10) * pow(a, b[i]) % MOD;
}
return ans;
}
};
```
### (3)结果
执行用时 :8 ms,在所有 C++ 提交中击败了 86.98% 的用户;
内存消耗 :11.4 MB,在所有 C++ 提交中击败了 56.08% 的用户。
# 三、其他
暂无。
|
Python | UTF-8 | 2,671 | 4.03125 | 4 | [] | no_license | """Sua organização acaba de contratar um estagiário para trabalhar no Suporte de Informática, com a intenção de fazer
um levantamento nas sucatas encontradas nesta área. A primeira tarefa dele é testar todos os cerca de 200 mouses que
se encontram lá, testando e anotando o estado de cada um deles, para verificar o que se pode aproveitar deles.
Foi requisitado que você desenvolva um programa para registrar este levantamento. O programa deverá receber um número i
ndeterminado de entradas, cada uma contendo: um número de identificação do mouse o tipo de defeito:
- necessita da esfera;
- necessita de limpeza; a.necessita troca do cabo ou conector; a.quebrado ou inutilizado Uma identificação igual a zero
encerra o programa. Ao final o programa deverá emitir o seguinte relatório:
Quantidade de mouses: 100
Situação Quantidade Percentual
1- necessita da esfera 40 40%
2- necessita de limpeza 30 30%
3- necessita troca do cabo ou conector 15 15%
4- quebrado ou inutilizado 15 15%
"""
esfera = limpeza = cabo_conector = quebrado = quant_mouses = 0
while True:
condicao = str(input("1- necessita da esfera \n"
"2- necessita de limpeza \n"
"3- necessita troca do cabo ou conector \n"
"4- quebrado ou inutilizado \n"
"0- zero para sair\n"
"Digite a condicao do mouse: "))
if condicao == "0":
print("Programa encerrado! Obrigado!")
break
elif condicao not in ("1", "2", "3", "4"):
print("Condicao Invalida!, tente novamente!\n\n")
continue
else:
if condicao == "1":
esfera += 1
elif condicao == "2":
limpeza += 1
elif condicao == "3":
cabo_conector += 1
elif condicao == "4":
quebrado += 1
quant_mouses += 1
print("Obrigado pelo seu voto!")
print("*** Resulatdos ***")
print("1 - necessita da esfera - {} - {:.2%}\n"
"2 - necessita de limpeza - {} - {:.2%} \n"
"3 - necessita troca do cabo ou conector - {} - {:.2%}\n"
"4 - quebrado ou inutilizado - {} - {:.2%}\n"
.format(esfera, (esfera / quant_mouses), limpeza,
(limpeza / quant_mouses), cabo_conector, (cabo_conector / quant_mouses), quebrado,
(quebrado / quant_mouses)))
print("Total de mouses = {}".format(quant_mouses))
"""Falta apenas formatar as strings. Ler sobre isso. Fazer formatação manual.""" |
TypeScript | UTF-8 | 509 | 2.640625 | 3 | [
"MIT"
] | permissive | import { ISpecification } from '../specification/specification.interface';
import { IDbSet, IQueryable } from './interfaces';
export type DeepPartial<T> = {
[P in keyof T]?: T[P] extends (infer U)[]
? DeepPartial<U>[]
: T[P] extends ReadonlyArray<infer U2>
? ReadonlyArray<DeepPartial<U2>>
: DeepPartial<T[P]>;
};
export interface IInternalDbSet<T extends object>
extends IDbSet<T> {
asSpecification(): ISpecification<T>;
fromSpecification(spec: ISpecification<T>): IQueryable<T>;
}
|
Python | UTF-8 | 393 | 3.5 | 4 | [] | no_license | #!/bin/python
counter = 0
while True:
try:
s = str(input())
o = ''
for i in range(len(s)):
if s[i] == '"':
if counter % 2 == 0:
o += '``'
else:
o += '\'\''
counter += 1
else:
o += s[i]
print(o)
except EOFError:
break
|
C++ | UTF-8 | 1,237 | 3.609375 | 4 | [] | no_license | #include <stdio.h>
#include <string.h>
#include "Matrix.h"
// macro to access value using ptr to matrix
#define MATRIX_VAL(matrix, row, col) (*((int *)matrix->pMatrix + (row * matrix->num_col) + col))
/*
* Function to print a matrix of any size
*/
void Matrix_print(Matrix_instance_t *matrix) {
int row, col;
printf("\nsize: %d X %d:", matrix->num_row, matrix->num_col);
for (row = 0; row < matrix->num_row; row++) {
printf("\n | ");
for (col = 0; col < matrix->num_col; col++)
printf("%3d ", *((int *)matrix->pMatrix + (row * matrix->num_col) + col));
printf("|");
}
printf("\n");
}
/*
* Function to compare two matrix and return true/false.
* This is needed for test functions
*/
bool Matrix_compare(Matrix_instance_t* matrix_a,
Matrix_instance_t* matrix_b) {
int i, j;
// matrix size should be same
if ((matrix_a->num_row != matrix_b->num_row) ||
(matrix_a->num_col != matrix_b->num_col)) {
return false;
}
// compare the 2 matrices
for (i = 0; i < matrix_a->num_row; i++) {
for (j = 0; j < matrix_a->num_col; j++) {
if (MATRIX_VAL(matrix_a, i, j) != MATRIX_VAL(matrix_b, i, j)) {
return false;
}
}
}
return true;
}
|
Go | UTF-8 | 849 | 2.765625 | 3 | [] | no_license | package connectors
import (
)
// define interface for auto-updating of resources. all connectors
// implement the CollectData() function, which ingests a collection
// of BusinessMetadata instances and returns a serious of BusinessUpdate
// items that contain updated business information
//
// Additionally, each connector should implement the Name() function,
// which is used to identify the connector and the data source in
// various places
type AutoUpdateDataConnector interface{
// function used to collect data from connector source
CollectData(businesses []BusinessMetadata) ([]BusinessUpdate, error)
Name() string
}
type StreamedAutoUpdateDataConnector interface{
// function used to collect data from connector source
StreamData(updates chan BusinessUpdate, businesses []BusinessMetadata) error
Name() string
} |
Python | UTF-8 | 712 | 2.90625 | 3 | [] | no_license | import sys
sys.stdin = open('격자판의숫자이어붙이기.txt','r')
def dfs(r, c, num):
if len(num) == 7:
if num not in result:
result.append(num)
return
dr = [1, -1, 0, 0]
dc = [0, 0, 1, -1]
for x in range(4):
nr = r + dr[x]
nc = c + dc[x]
if 0 <= nr < len(arr) and 0 <= nc < len(arr):
dfs(nr, nc, num+str(arr[nr][nc]))
T = int(input())
for test_case in range(1, T+1):
arr = [list(map(int, input().split())) for _ in range(4)]
result = []
for r in range(len(arr)):
for c in range(len(arr)):
dfs(r, c, str(arr[r][c]))
print(result)
print('#{} {}'.format(test_case, len(result))) |
TypeScript | UTF-8 | 2,027 | 2.671875 | 3 | [] | no_license | import * as ws from 'ws';
import * as express from "express";
import {Player, PlayerRegistry} from "../player";
class ConnectionHandler {
playerRegistry: PlayerRegistry;
player?: Player;
socket: ws;
constructor(playerRegistry: PlayerRegistry, socket: ws) {
this.playerRegistry = playerRegistry;
this.socket = socket;
socket.on("message", this.onMessage.bind(this));
socket.on("close", this.onDisconnect.bind(this));
}
onMessage(msg: string) {
if (this.player == null) {
let player = this.playerRegistry.getByName(msg);
if (player != null
&& player.relaySocket == null
&& player.lobby != null
&& player.lobby.state == "CONNECTION_WAIT") {
this.player = player;
this.player.relaySocket = this.socket;
this.socket.send("ok");
this.player.ready = true;
this.player.lobby!.refreshReady()
} else {
this.socket.send("error: invalid token")
}
return
}
if (this.player.lobby == null) {
this.socket.send("error: no lobby joined");
return
}
if (this.player.lobby.state != "PLAYING") {
this.socket.send("error: wrong lobby state");
return
}
let other: Player;
for (other of this.player.lobby.players) {
if (other != this.player && other.relaySocket != null) {
other.relaySocket.send(msg)
}
}
}
onDisconnect() {
if (this.player != null) {
this.player.relaySocket = undefined
}
}
}
export class GameRelay {
playerRegistry: PlayerRegistry;
constructor(playerRegistry: PlayerRegistry) {
this.playerRegistry = playerRegistry;
}
connectionHandler(ws: ws, req: express.Request): void {
new ConnectionHandler(this.playerRegistry, ws);
}
}
|
Java | UTF-8 | 692 | 1.789063 | 2 | [] | no_license | package org.banyan.gateway.helios.data.jpa.repository.channel;
import org.banyan.gateway.helios.data.jpa.domain.channel.InterfaceConfig;
import org.banyan.gateway.helios.data.jpa.domain.pk.InterfaceConfigPk;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
import java.util.Set;
/**
* Copyright (C), 2018, Banyan Network Foundation
* InterfaceConfigRepository
*
* @author Kevin Huang
* @since version
* 2018年04月19日 15:33:00
*/
public interface InterfaceConfigRepository extends CrudRepository<InterfaceConfig, InterfaceConfigPk> {
Set<InterfaceConfig> findByIface(String iface);
List<InterfaceConfig> findByIfaceIn(List<String> ifaces);
}
|
Markdown | UTF-8 | 2,786 | 3.015625 | 3 | [] | no_license | ###### telegraph_arduino_temboo
#Arduino Telegraph - Code System project from Systems class @CCA

###YouTube Videos
[Final Demo 1](https://youtu.be/Q5agbIDerKQ)
[Final Demo 2](https://youtu.be/oKgJvz0VeJY)
[Early Prototype](https://youtu.be/BHRiO0pCflk) (no SMS, just serial control)
###The Project
In our Systems design class at California College of the Arts (taught by Hugh Dubberly) we were trying to understand communication systems by building one of our own. We were abstracting each of the processes and layers, diagramming and visualizing.
The first step in learning this was to build a communication device - a basic telegraph made out of a wooden board, a nail, wire and two batteries.

The second step was the creation of a code (which isn't Morse code) to which we'll encode our messages to send them to each other. The code I used was built as a sort of three-dimensional cube created together with my classmate Danielle Forward.
###Key

After testing the codes we made, we were asked to improve the input or the output of this basic telegraph to allow for easier & faster communication.
I wanted to remove knowing the code we dev of the code as a prerequisite to sending a message so I connected the circuit through an Arduino controlled relay and created a code that encodes strings to the series of clicks representing the message in the code system created earlier.
That worked ok for the class but for our yearly show I wanted it to be wireless, accessible to visitors and also opaque - de-emphasize the technology enabling it as it wasn't the emphasis for the show.
Hence the Text-to-Telegraph integration:
######SMS -> twilio -> Temboo -> Arduino Yun -> Telegraph.

One visitor texts a message to a twilio number, the Arduino runs a Temboo call every 10 seconds to check the message queue for a message that begins with the word "telegraph" and if it's different than the last message it transcodes each letter to its corresponding series of clicks in the code we devised, bookended with an initialization sound (Shave and a Haircut).


The second visitor listens to the clicks and transcribes the message back to English.

|
C# | UTF-8 | 710 | 2.609375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace suma
{
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
float primerNumero = float.Parse(valor1.Text);
float segudoNumero = float.Parse(valor2.Text);
float resultado = primerNumero + segudoNumero;
this.resultado.Text = primerNumero + "+" + segudoNumero + "=" + resultado;
}
}
}
|
Java | UTF-8 | 4,193 | 2.765625 | 3 | [] | no_license | import java.util.ArrayList;
public class serializeStringToArray {
// Aufgabe unklar - es wird nicht deultlich erklärt, ob nur zeilenweise oder aber auch zeilenübergreifend zu suchen ist. Letzteres ist der Fall (input2 & adjacent2)
public static void main(String[] args) {
int count = 13;
String splitString = "/n";
String input =
"73167176531330624919225119674426574742355349194934/n" +
"96983520312774506326239578318016984801869478851843/n" +
"85861560789112949495459501737958331952853208805511/n" +
"12540698747158523863050715693290963295227443043557/n" +
"66896648950445244523161731856403098711121722383113/n" +
"62229893423380308135336276614282806444486645238749/n" +
"30358907296290491560440772390713810515859307960866/n" +
"70172427121883998797908792274921901699720888093776/n" +
"65727333001053367881220235421809751254540594752243/n" +
"52584907711670556013604839586446706324415722155397/n" +
"53697817977846174064955149290862569321978468622482/n" +
"83972241375657056057490261407972968652414535100474/n" +
"82166370484403199890008895243450658541227588666881/n" +
"16427171479924442928230863465674813919123162824586/n" +
"17866458359124566529476545682848912883142607690042/n" +
"24219022671055626321111109370544217506941658960408/n" +
"07198403850962455444362981230987879927244284909188/n" +
"84580156166097919133875499200524063689912560717606/n" +
"05886116467109405077541002256983155200055935729725/n" +
"71636269561882670428252483600823257530420752963450/n";
String input2 =
"73167176531330624919225119674426574742355349194934" +
"96983520312774506326239578318016984801869478851843" +
"85861560789112949495459501737958331952853208805511" +
"12540698747158523863050715693290963295227443043557" +
"66896648950445244523161731856403098711121722383113" +
"62229893423380308135336276614282806444486645238749" +
"30358907296290491560440772390713810515859307960866" +
"70172427121883998797908792274921901699720888093776" +
"65727333001053367881220235421809751254540594752243" +
"52584907711670556013604839586446706324415722155397" +
"53697817977846174064955149290862569321978468622482" +
"83972241375657056057490261407972968652414535100474" +
"82166370484403199890008895243450658541227588666881" +
"16427171479924442928230863465674813919123162824586" +
"17866458359124566529476545682848912883142607690042" +
"24219022671055626321111109370544217506941658960408" +
"07198403850962455444362981230987879927244284909188" +
"84580156166097919133875499200524063689912560717606" +
"05886116467109405077541002256983155200055935729725" +
"71636269561882670428252483600823257530420752963450";
// System.out.println(serialize(split(input,splitString)[19])[1]);
// System.out.println(serialize(input2)[368]);
// System.out.println(adjacent(input, splitString, count));
System.out.println(adjacent2(input2, splitString, count));
}
public static String[] split(String input, String splitString){
String[] splitts = input.split(splitString);
return splitts;
}
public static String[] serialize(String input){
String[] serialized = input.split("|");
return serialized;
}
public static long adjacent2(String input, String splitString, int count){
long heightest = 0;
String[] seriInput = serialize(input);
for (int i = 1; i < seriInput.length - (count+1); i++){
long cHeightest = 1;
for (int offset = 0; offset < count; offset++){
cHeightest *= Integer.parseInt(seriInput[i+offset]);
}
if (cHeightest > heightest){
heightest = cHeightest;
System.out.println(i);
}
}
return heightest;
}
public static long adjacent(String input, String splitString, int count){
long heighest = 0;
for (int i = 0; i <= 19; i++){
for (int offset = 0; offset < 49-count; offset++){
long cHeighest = 1;
for (int k = 1; k <= count; k++){
// cHeighest *= Integer.parseInt(serialize(split(input,splitString)[i])[k+offset]);
}
if (cHeighest > heighest){
heighest = cHeighest;
}
}
}
return heighest;
}
}
|
Python | UTF-8 | 3,674 | 3.984375 | 4 | [] | no_license | #!/usr/bin/env python
# 140211 Raoul Meuldijk
# http://en.wikipedia.org/wiki/Mandelbrot_set
def mandel(x0, y0):
""" Iterate the Mandelbrot function, returns the number of
iterations until x^2 + y^2 > 4 or 200 iterations.
"""
x = 0
y = 0
iteration = 0
max_iteration = 200
while ( x*x + y*y <= (2*2) and iteration < max_iteration ):
xtemp = x*x - y*y + x0
y = 2*x*y + y0
x = xtemp
iteration += 1
if (iteration == max_iteration):
iterations = max_iteration
else:
iterations = iteration
return(iterations)
# Set up variables and lists.
amin = -2.25 # axis ranges:
amax = 1.25 # a horizontal, real part
bmin = -1.75 # b vertical, imaginary part
bmax = 1.75
windowWidth = 300 # in pixels
windowHeight = 300
iterlist=[] # list of coordinates (a,bi) and number of iters on that point
tup=() # tuple with (a, bi, iterations) for extending iterList
a_axis = [] # points on the a-axis
b_axis = [] # points on the bi-axis
# project range on window
# a_axis is list of coordinates -2.0 .. 2.0 divided over 300 pixels
step_a = (amax - amin) / windowWidth # step size of coordinates between each pixel
step_b = (bmax - bmin) / windowHeight
u = amin
while u < amax:
a_axis = a_axis + [u]
u += step_a
u = bmin
while u < bmax:
b_axis = b_axis + [u]
u += step_b
print 'Mandelbrot with python, February 2011.'
# Do the math.
# Fill a list of (a , b, iterations) from top left to bottom right in the window.
present_iterations = set() # Which numbers of iterations are present, is useful for deciding the colour scale.
for j in range(len(b_axis)):
k = len(b_axis) - (j+1)
for i in range(len(a_axis)):
iters = mandel(a_axis[i],b_axis[k])
tup=()
tup = (a_axis[i],b_axis[k],iters) # a, b, iters
iterlist.append(tup)
if iters not in present_iterations:
present_iterations.add(iters)
highest_iteration = max(present_iterations) # highest and lowest iteration numbers
lowest_iteration = min(present_iterations)
colourStep = int(255/(highest_iteration-lowest_iteration)) # divide 255 colours linearly over the found iteration range
iter_range = (highest_iteration-lowest_iteration)
# Draw picture.
from math import * # only used for log() in colour scaling
from Tkinter import * # Python's access to the Tcl/Tk GUI
top = Tk()
C = Canvas(top, bg="yellow", bd=0, height=windowHeight, width=windowWidth)
# Iterlist is one-dimensional, so the end of each line of pixels needs to be found.
a_previous = amin # To keep track of the end of a pixel line in the window
a_current = 0
# Tk Canvas coordinates have a strangely big offset.
x=2 # x is 1 lower than offset here, because first loop step adds 1
y=3
# point[0] is a
# point[1] is bi
# point[2] is number of iterations
# Loop iterlist
for point in iterlist:
a_current = point[0]
if a_current >= a_previous: # if a_current is getting bigger, still on same line
x += 1
numberOfIters = point[2]
else: # else, new line starts
x = 3
y += 1
numberOfIters = point[2]
a_previous = a_current
aDot = [x, y, x, y]
# Some experiments in distributing colours.
#colour = (numberOfIters-(lowest_iteration+1)) * colourStep # nice if iters 17 to 48
colour = log(numberOfIters, iter_range) * 255 # nice if lowest_iteration = 2; log(x, base)
colour = int(colour)
if colour > 255:
colour = 255
#colour = 255 - colour # invert picture
tk_rgb = "#%02x%02x%02x" % (128, colour, colour)
#tk_rgb = "#%02x%02x%02x" % (colour, colour, colour) # grey scale, lighter means more iterations
pixel = C.create_rectangle(aDot, fill=tk_rgb, outline="darkblue", width=0)
print 'Iteration numbers present in the picture: ', present_iterations
C.pack()
top.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.