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
3,534
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Diction_Master___Library; namespace Diction_Master___Library.UserControls { /// <summary> /// Interaction logic for LevelSelection.xaml /// </summary> public partial class LevelSelection : UserControl { private Diction_Master___Library.EducationalLevelType SelectedEducationalLevel; private string Icon; private bool levelSelected; private Component _selectedGrade; private List<Component> _availableLevels; public LevelSelection() { _availableLevels = new List<Component>(); InitializeComponent(); } internal void SetAvailableLevels(List<Component> components) { _availableLevels.Clear(); foreach (EducationalLevel item in components) { _availableLevels.Add(item); if (item.Level == EducationalLevelType.Nursery) { Nursery.Visibility = Visibility.Visible; } if (item.Level == EducationalLevelType.Primary) { Primary.Visibility = Visibility.Visible; } if (item.Level == EducationalLevelType.Secondary) { Secondary.Visibility = Visibility.Visible; } } } private void Nursery_OnClick(object sender, RoutedEventArgs e) { SelectedEducationalLevel = EducationalLevelType.Nursery; Nursery.Opacity = 1; Primary.Opacity = 0.6; Secondary.Opacity = 0.6; levelSelected = true; button.IsEnabled = true; Icon = ImageNursery.Source.ToString(); _selectedGrade = _availableLevels.Find(x => (x as EducationalLevel).Level == EducationalLevelType.Nursery); } private void Primary_OnClick(object sender, RoutedEventArgs e) { SelectedEducationalLevel = EducationalLevelType.Primary; Nursery.Opacity = 0.6; Primary.Opacity = 1; Secondary.Opacity = 0.6; levelSelected = true; button.IsEnabled = true; Icon = ImagePrimary.Source.ToString(); _selectedGrade = _availableLevels.Find(x => (x as EducationalLevel).Level == EducationalLevelType.Primary); } private void Secondary_OnClick(object sender, RoutedEventArgs e) { SelectedEducationalLevel = EducationalLevelType.Secondary; Nursery.Opacity = 0.6; Primary.Opacity = 0.6; Secondary.Opacity = 1; levelSelected = true; button.IsEnabled = true; Icon = ImageSecondary.Source.ToString(); _selectedGrade = _availableLevels.Find(x => (x as EducationalLevel).Level == EducationalLevelType.Secondary); } public Component GetSelectedComponent() { return _selectedGrade; } public EducationalLevelType GetSelectedEducationalLevel() { return SelectedEducationalLevel; } } }
Shell
UTF-8
275
3.140625
3
[ "MIT" ]
permissive
#!/bin/sh name=${NAME:-$UNOPROJ} echo travis_fold:start:android uno build -tAndroid -DGRADLE ${UNOPROJ}.unoproj -v exitcode=$? echo travis_fold:end:android if [ $exitcode -ne 0 ]; then echo "uno android $name - FAIL" else echo "uno android $name - PASS" fi exit $exitcode
Python
UTF-8
477
3.203125
3
[]
no_license
# Leetcode 693: # # https://leetcode.com/problems/binary-number-with-alternating-bits/ # Runtime: 36 ms # Memory Usage: N/A class Solution: def hasAlternatingBits(self, n): """ :type n: int :rtype: bool """ if n == 1: return True pre = n & 1 while n > 0: n = n >> 1 curr = n & 1 if pre == curr: return False pre = curr return True
JavaScript
UTF-8
1,010
2.53125
3
[ "MIT" ]
permissive
import axios from "axios"; import { without } from "lodash" export default { namespaced: true, state : { likes : [] }, getters : { likes (state) { return state.likes } }, mutations : { PUSH_LIKES ( state, data ) { state.likes.push(...data); }, PUSH_LIKE ( state, id ) { state.likes.push(id); }, POP_LIKE ( state, id ) { state.likes = without( state.likes, id ); }, }, actions : { async likeTweet (_, tweet) { return await axios.post(`api/tweets/${tweet.id}/likes`) }, async unlikeTweet (_, tweet) { return await axios.delete(`api/tweets/${tweet.id}/likes`) }, syncLike ( { commit, state }, id ) { if( state.likes.includes( id ) ) { commit( 'POP_LIKE', id ); return; } commit('PUSH_LIKE', id); } } }
JavaScript
UTF-8
1,455
2.828125
3
[ "MIT" ]
permissive
$('document').ready( function() { // highlight checked sources selectImages(); // toggle check on checkbox when image is clicked checkUncheck(); $('#news-sources-container').off('click'); // without this, click event will fire twice $('#news-sources-container').on('click', '.form-image', function(){ var checkbox = $(this).next(); // select checkbox that follows the clicked image checkbox.trigger('click'); if( checkbox.is(':checked') ) { // toggle checked-image class $(this).addClass('checked-image'); } else { $(this).removeClass('checked-image'); } checkUncheck(); }); // close overlay on click $('.close-overlay').click( function() { $('#overlay-outer').hide(); }); }); // add checked-image class to selected sources function selectImages() { $('input[type="checkbox"]:checked').prev().addClass('checked-image'); } function checkUncheck() { // uncheck when checked is clicked var xCircle = $('<i class="fa fa-times-circle-o"></i>'); // fontawesome x var unchecked = $('.form-image').not('.checked-image').next(); // select unchecked checkboxes unchecked.next().remove(); // remove checkmark xCircle.insertAfter(unchecked); // add x // check when unchecked is clicked var vCircle = $('<i class="fa fa-check-circle-o"></i>'); // fontawesome checkmark var checked = $('.form-image.checked-image').next(); checked.next().remove(); vCircle.insertAfter(checked); }
C++
UTF-8
2,367
3.546875
4
[]
no_license
// // Created by Duncan Marget on 6/9/21. // #include "Bureaucrat.hpp" Bureaucrat::Bureaucrat() {} Bureaucrat::Bureaucrat(std::string const &name, int grade) :_name(name), _grade(grade) { if (_grade < 1) throw Bureaucrat::GradeTooHighException(); else if (_grade > 150) throw Bureaucrat::GradeTooLowException(); } Bureaucrat::Bureaucrat(Bureaucrat const &copy) :_name(copy._name), _grade(copy._grade) { if (_grade < 1) throw Bureaucrat::GradeTooHighException(); else if (_grade > 150) throw Bureaucrat::GradeTooLowException(); } void Bureaucrat::signForm(Form &form) const { if (form.getSigned()) { std::cout << *this << "Can't sign\n" << form; std::cout << "Cause the form already signed." << std::endl; } else if (form.getSign() < _grade) std::cout << *this << "Can't sign" << form << "Cause it's grade is low." << std::endl; else std::cout << *this << "Signs" << std::endl << form << std::endl; form.beSigned(*this); } void Bureaucrat::executeForm(Form const &form) const { if (!form.getSigned()) { std::cout << *this << "Can't execute\n" << form; std::cout << "Cause the form is unsigned." << std::endl; } else if (form.getExec() < this->_grade) { std::cout << *this << "Can't execute " << form; std::cout << "Cause it's grade is too low." << std::endl; } else { std::cout << *this << "Executes " << std:: endl << form << std::endl; } form.execute(*this); } Bureaucrat::~Bureaucrat() {} Bureaucrat &Bureaucrat::operator = (Bureaucrat const &copy) { _name = copy._name; _grade = copy._grade; return *this; } const char* Bureaucrat::GradeTooLowException::what() const throw() { return "Bureaucrat exception: to low grade."; } const char* Bureaucrat::GradeTooHighException::what() const throw() { return "Bureaucrat exception: to high grade."; } int Bureaucrat::getGrade() const { return _grade; } std::string const &Bureaucrat::getName() const { return _name; } void Bureaucrat::inc(int n) { _grade = _grade - n; _grade < 1 ? throw Bureaucrat::GradeTooHighException() : 0; } void Bureaucrat::dec(int n) { _grade = _grade + n; _grade > 150 ? throw Bureaucrat::GradeTooLowException() : 0; } std::ostream &operator << (std::ostream &out, Bureaucrat const &bureaucrat) { out << "I'm " << bureaucrat.getName(); out << " I have a " << bureaucrat.getGrade() << " grade." << std::endl; return out; }
Markdown
UTF-8
1,284
2.703125
3
[]
no_license
# Achievers Intro_to_SE Project | Role | Name |NetID | GitHub Username | |:-----------:|:-----------------:|:-----:|:-------------------:| |Team Leader |Felicity Harvard |fah78 |FelicityHarvard | |Team Member1 |Caleb Mills |ctm364 |CTMills | |Team Member2 |Eddie Caveness |ewc65 |SaltyWizard22 | |Team Member3 |Darius Wheeler |dlw605 |dlwheeler5199 | |Team Member4 |Dalton Pruitt |dp987 |daltonrpruitt | **(Tentive)** Languages we plan on using: php, html, javascript **(Tentive)** Techniques we plan to use: TBD ###Description We aim to create a social media platform that will allow a social bridge to be formed between users regardless of geographic location or background. Everyone will be allowed to share their opinions equally and freely so long as they abide by general social standards and respect other users. This will a safe and encouraging environment that will promote public discussions that can be joined by anyone. Individual users will be able to follow other users should they please. This will allow them to see an active feed of their posts which they will be allowed to like to show support for. They will also be able to leave comments underneath sharing their opinion on the topic or just a general response to the post.
PHP
UTF-8
844
2.578125
3
[]
no_license
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDailyTasksTable extends Migration { public $connection='masterDB'; public function up() { if (!Schema::hasTable('dailytasks')) { Schema::create('dailytasks', function (Blueprint $table) { $table->increments('id')->unsigned()->comment('每日任务id'); $table->string('name','30')->comment('每日任务名称'); $table->smallInteger('scheduleTotle')->unsigned()->comment('总共需要的进度'); $table->smallInteger('price')->unsigned()->comment('奖励的价格'); }); } } public function down() { //Schema::dropIfExists('daily_tasks'); } }
PHP
UTF-8
3,377
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Model\GoodsModel; use DB; use App\Model\CartModel; use Illuminate\Http\Request; use Session; class CartController extends Controller { //加入购物车 public function cartadd(){ $g_id = request()->g_id; $goodsWhere = [ 'g_id' => $g_id, ]; $goodsInfo = DB::table('goods')->where($goodsWhere)->first(); $info = [ 'goods_id' => $g_id, ]; $u_id=Session::get('u_id'); $goodsInfo = DB::table('user')->where('u_id',$u_id)->first(); $info = [ 'goods_id' => $g_id, 'u_id'=>$u_id ]; $res = DB::table('cart')->insert($info); if ($res) { return ['code' => 1, 'res' => '加入购物车成功']; } else { return ['code' => 0, 'res' => '加入购物车失败']; } } //购物车首页 public function cart() { $cartinfo = DB::table('cart') ->join('goods','cart.goods_id','=','goods.g_id') ->first(); $u_id=Session::get('u_id'); $goodsInfo = DB::table('user')->where('u_id',$u_id)->first(); if($goodsInfo==''){ return redirect('/login'); } $cartinfo = DB::table('cart') ->join('goods','cart.goods_id','=','goods.g_id') ->where('u_id',$u_id) ->get(); return view('index/cart',['cartinfo'=>$cartinfo]); } //更改购买数量 public function cartbuynum(Request $request) { $g_id = $request->g_id; $buy_num = $request->buy_num; $res = $this->checkgoodsnumber($g_id,$buy_num); if($res){ $where=[ 'goods_id'=>$g_id, ]; $updateInfo=[ 'buy_num'=>$buy_num, ]; $result=DB::table('cart')->where($where)->update($updateInfo); if($result){ return ['code' => 1, 'res' => '修改数量成功']; }else{ return ['code' => 0, 'res' => '修改数量失败']; } }else{ $g_number = GoodsModel::where('g_id',$g_id)->get()->toArray(); $aa = $g_number[0]; $num = $aa['g_number']; $where=[ 'goods_id'=>$g_id, ]; $updateInfo=[ 'buy_num'=>$num, ]; CartModel::where($where)->update($updateInfo); return ['code' => 00, 'res' => '超出库存']; } } /** 检测库存*/ public function checkgoodsnumber($g_id,$buy_num,$number=0) { //根据商品id 查询商品库存 $g_number=DB::table('goods')->where("g_id",$g_id)->value("g_number"); if($buy_num+$number>$g_number){ return false; }else{ return true; } } public function total() { $u_id=Session::get('u_id'); $info=DB::table('cart as c') ->select('buy_num','price') ->join("goods as g",'c.goods_id','=','g.g_id') ->where('u_id',$u_id) ->get(); $count=0; foreach($info as $k=>$v){ $count+=$v->price*$v->buy_num; } return $count; } public function gettotal() { $g_id=request()->g_id; if(empty($g_id)){ return 0;exit; } $goodsWhere=[ ['g_id','=',$g_id] ]; $price=DB::table('goods')->where($goodsWhere)->value('price'); //获取商品购买数量 $cartWhere=[ ['goods_id','=',$g_id], ]; $buy_num=DB::table('cart')->where($cartWhere)->value('buy_num'); return $price*$buy_num; } public function del() { $g_id=request()->g_id; $u_id=Session::get('u_id'); $where=[ 'goods_id'=>$g_id, 'u_id'=>$u_id ]; $res=CartModel::where($where)->delete(); if($res){ return response(['code'=>00,'msg'=>"删除成功","data"=>[]]); }else{ return response(['code'=>11,'msg'=>"删除失败","data"=>[]]); } } }
C
UTF-8
574
3.375
3
[]
no_license
#include "bit_operations.h" #include <stdio.h> #include <stdlib.h> //--------------------------------------------- int get_bit(int A, int x){ //Renvoie le xième bit de A return (A >> x) & 1; } //--------------------------------------------- int set_bit(int A, int x){ // renvoie A où son xième bit a été mis à 1 int B = 1; B = (B << x); A = A | B; return A; } //--------------------------------------------- int clr_bit(int A, int x){ // renvoie A où son xième bit a été mis à 0 int B = 1; B = (B << x); B = ~B; A = A & B; return A; }
Ruby
UTF-8
1,845
3.40625
3
[]
no_license
require_relative './dragon' require_relative './blue_dragon' require_relative './red_dragon' describe 'Dragon' do it 'should create a dragon' do name = 'Dolly' owner_name = 'Babi' pet = Dragon.new(name,owner_name) expect(pet.name).to eq name expect(pet.owner_name).to eq owner_name end it 'should let dragon walks and test if stuff_in_intestine is zero' do name = 'Dolly' owner_name = 'Babi' pet = Dragon.new(name,owner_name) pet.walk expect(pet.stuff_in_intestine).to eq(0) end it 'should feed the dragon and tests variables in feed method' do name = 'Dolly' owner_name = 'Babi' pet = Dragon.new(name,owner_name) pet.feed expect(pet.stuff_in_belly).to eq(9) expect(pet.stuff_in_intestine).to eq(1) end it 'should make the baby asleep' do name = 'Dolly' owner_name = 'Babi' pet = Dragon.new(name,owner_name) pet.put_to_bed expect(pet.asleep).to eq(false) end it 'should toss the baby dragon' do name = 'Dolly' owner_name = 'Babi' pet = Dragon.new(name,owner_name) pet.toss end it 'should rock the baby dragon and test variable asleep' do name = 'Dolly' owner_name = 'Babi' pet = Dragon.new(name,owner_name) pet.rock expect(pet.asleep).to eq(false) end it 'should create a new baby blue dragon and test his own methods' do name = 'Dolly' owner_name = 'Babi' pet = Blue_dragon.new(name, owner_name) pet.swim pet.feed expect(pet.name).to eq name expect(pet.owner_name).to eq owner_name end it 'should create a new baby red dragon and test his own methods' do name = 'Dolly' owner_name = 'Babi' pet = Red_dragon.new(name, owner_name) pet.spit_fire pet.feed expect(pet.name).to eq name expect(pet.owner_name).to eq owner_name end end
Java
UTF-8
804
2.078125
2
[]
no_license
package com.tiny.model; import java.util.Date; public class Like { private String providerUserId; private Integer documentId; // true : like // false : dislike private Boolean isLike; private Date regDate; public String getProviderUserId() { return providerUserId; } public void setProviderUserId(String providerUserId) { this.providerUserId = providerUserId; } public Integer getDocumentId() { return documentId; } public void setDocumentId(Integer documentId) { this.documentId = documentId; } public Boolean getIsLike() { return isLike; } public void setIsLike(Boolean isLike) { this.isLike = isLike; } public Date getRegDate() { return regDate; } public void setRegDate(Date regDate) { this.regDate = regDate; } }
C++
UTF-8
3,725
3.03125
3
[ "MIT", "CC-BY-4.0" ]
permissive
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #pragma once #include "carla/Debug.h" #include <array> namespace carla { namespace geom { /// Describes a Cubic Polynomial so: /// f(x) = a + bx + cx^2 + dx^3 class CubicPolynomial { public: // ========================================================================= // -- Constructors --------------------------------------------------------- // ========================================================================= CubicPolynomial() = default; CubicPolynomial(const CubicPolynomial &) = default; CubicPolynomial( const double &a, const double &b, const double &c, const double &d) : _v{ {a, b, c, d} } {} CubicPolynomial( const double &a, const double &b, const double &c, const double &d, const double &s) // lateral offset : _v{ {a - b * s + c * s * s - d * s * s * s, b - 2 * c * s + 3 * d * s * s, c - 3 * d * s, d} } {} // ========================================================================= // -- Getters -------------------------------------------------------------- // ========================================================================= double GetA() const { return _v[0]; } double GetB() const { return _v[1]; } double GetC() const { return _v[2]; } double GetD() const { return _v[3]; } // ========================================================================= // -- Evaluate methods ----------------------------------------------------- // ========================================================================= /// Evaluates f(x) = a + bx + cx^2 + dx^3 double Evaluate(const double &x) const { // return _v[0] + _v[1] * (x) + _v[2] * (x * x) + _v[3] * (x * x * x); return _v[0] + x * (_v[1] + x * (_v[2] + x * _v[3])); } /// Evaluates the tangent using df/dx = b + 2cx + 3dx^2 double Tangent(const double &x) const { return _v[1] + x * (2 * _v[2] + x * 3 * _v[3]); } // ========================================================================= // -- Arithmetic operators ------------------------------------------------- // ========================================================================= CubicPolynomial &operator+=(const CubicPolynomial &rhs) { for (auto i = 0u; i < _v.size(); ++i) { _v[i] += rhs._v[i]; } return *this; } friend CubicPolynomial operator+(CubicPolynomial lhs, const CubicPolynomial &rhs) { lhs += rhs; return lhs; } CubicPolynomial &operator*=(const double &rhs) { for (auto i = 0u; i < _v.size(); ++i) { _v[i] *= rhs; } return *this; } friend CubicPolynomial operator*(CubicPolynomial lhs, const double &rhs) { lhs *= rhs; return lhs; } friend CubicPolynomial operator*(const double &lhs, CubicPolynomial rhs) { rhs *= lhs; return rhs; } private: // ========================================================================= // -- Private data members ------------------------------------------------- // ========================================================================= // a - elevation // b - slope // c - vertical curvature // d - curvature change std::array<double, 4> _v = {0.0, 0.0, 0.0, 0.0}; }; } // namespace geom } // namespace carla
Swift
UTF-8
1,783
2.90625
3
[ "MIT" ]
permissive
// // CollectionViewAdapter.swift // GitHub Client // // Created by Alexander Vinogradov on 26.08.2021. // import UIKit protocol CollectionViewAdapter: UICollectionViewDataSource { func register(_ collectionView: UICollectionView) func update(_ items: [Any]) } final class CollectionViewAdapterImpl: NSObject { private let cellManager: CollectionCellManager private var items: [Any] = [] init(with cellManager: CollectionCellManager) { self.cellManager = cellManager } } // MARK: - CollectionViewAdapter extension CollectionViewAdapterImpl: CollectionViewAdapter { func register(_ collectionView: UICollectionView) { cellManager.register(collectionView: collectionView) } func update(_ items: [Any]) { self.items = items } } // MARK: - UICollectionViewDataSource extension CollectionViewAdapterImpl { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = items[indexPath.row] let cell = cellManager.dequeueReusableCell(collectionView: collectionView, for: indexPath) cell.populate(viewModel: item) return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard let collectionView = collectionView as? CollectionView else { return CollectionFooterView() } return collectionView.collectionView(kind, at: indexPath) } }
Python
UTF-8
4,934
3.28125
3
[]
no_license
import random import sys def posValida(i,j): if i >= 0 and j >= 0 and i < num and j < num: if tableroVisible[i][j] == 0 or tableroVisible[i][j] == 1 or tableroVisible[i][j] == 2: return True else: return False else: return False def generaAleatorio(): for i in range (0, num): for j in range(0,num): rndm = random.randint(0, 1) tableroVisible[i][j] = rndm printTablero() menu() def generaBlanco(): for i in range (0,num): for j in range(0,num): tableroVisible[i][j]= 0 printTablero() menu() def compruebaBicho(i,j): contadorBichos = 0 for x in range (i-1,i+2): if posValida(x,j-1): if tableroVisible[x][j-1] == 1: contadorBichos = contadorBichos + 1 if posValida(i,j-1): if tableroVisible[i][j-1] == 1: contadorBichos = contadorBichos + 1 if posValida(i,j+1): if tableroVisible[i][j+1] == 1: contadorBichos = contadorBichos + 1 for x in range (i-1,i+2): if posValida(x,j+1): if tableroVisible[x][j+1] == 1: contadorBichos = contadorBichos + 1 #Y ahora actúa: if contadorBichos <=1 or contadorBichos >= 4: muereBicho(i,j) elif contadorBichos == 3: naceBicho(i,j) def muereBicho(i,j): if tableroVisible[i][j] == 1: tableroOculto[i][j] = 0 def naceBicho(i,j): if tableroVisible[i][j] == 0: tableroOculto[i][j] = 1 def menu(): select = int(input("¿Qué desea hacer a continuación?\n" "1) Generar nuevo tablero aleatorio\n" "2) Generar nuevo tablero en blanco\n" "3) Nuevo bicho en coordenadas a indicar\n" "4) Borrar bicho en coordenadas a indicar\n" "5) Simular determinado número de generaciones\n" "6) Salir\n")) if select == 1: tamañoTablero() generaAleatorio() elif select == 2: tamañoTablero() generaBlanco() elif select == 3: col = int(input("¿En qué fila? ")) fil = int(input("¿En qué columna? ")) if posValida(fil-1, col-1): naceBicho(fil-1, col-1) printTablero() menu() else: print("Posición no existente") menu() elif select == 4: fil = int(input("¿En qué fila? ")) col = int(input("¿En qué columna? ")) if posValida(fil-1, col-1): muereBicho(fil-1, col-1) printTablero() menu() else: print("Posición no existente") menu() elif select == 5: veces = int(input("¿Cuantas generaciones quieres mostrar? ")) for i in range(0, veces): for i in range(0, num): for j in range(0, num): compruebaBicho(i,j) print("\n", "Gen ", i+1) printTablero() menu() elif select == 6: sys.exit() def printTablero(): for i in range(0, num): for j in range(0, num): tableroVisible[i][j] = tableroOculto[i][j] print(tableroVisible[i][j],end= "") print() def tamañoTablero(): global num global tableroVisible global tableroOculto num = int(input("¿Tamaño del tablero? ")) while num > 20: print("Tamaño máximo 20") num = int(input("¿Tamaño del tablero? ")) tableroVisible = [[0 for x in range(num)] for y in range(num)] tableroOculto = tableroVisible select = int(input("¿Qué desea hacer a continuación?\n" "1) Generar nuevo tablero aleatorio\n" "2) Generar nuevo tablero en blanco\n")) tamañoTablero() if select == 1: generaAleatorio() elif select == 2: generaBlanco()
Markdown
UTF-8
1,347
2.609375
3
[]
no_license
--- layout: post title: 提出公務員加薪2.5% 楊何蓓恩強調非向商界傾斜 date: 2022-07-06 09:22:25.000000000 +08:00 link: https://news.rthk.hk/rthk/ch/component/k2/1656391-20220706.htm categories: rthk --- 公務員事務局局長楊何蓓茵表示,提出各級公務員劃一加薪2.5%,不是容易的決定,認為已平衡各項因素,形容今年是特殊的一年,作出審慎的決定會較安全。 楊何蓓恩在本台節目《千禧年代》表示,明白公務員在過去一年工作艱難,但也要考慮本港經濟及政府財政狀況,失業率高,今年赤字預算,加上外圍經濟前景不明朗。她透露,當局有考慮過不同方案,包括凍薪及較高的加幅,而減薪並非選項,在平衡天秤兩邊後得出這個數字,並沒有一個方程式計算。 楊何蓓恩又說,所有決定都要考慮外界觀感,強調有考慮公務員感受,不同意向商界傾斜。 對於加幅低於工會的期望,她說明白工會立場希望爭取最高加幅,她對公務員的士氣及日後工作有信心,過去幾十年來的薪酬加幅有上有落,試過有滿意的加幅,也有試過對加幅有落差,但對公務員非常有信心,不會「放軟手腳」。她今日會與工會見面進一步解釋,希望明白政府的決定。
C++
UTF-8
773
2.59375
3
[]
no_license
// Author: rl3107 // computes sine (sin(x)) // Rename this file to xllsin.cpp and implement XLL.SIN which calls sin // Add documentation and a test function that runs in debug mode. #include "xllfloat.h" #ifndef CATEGORY #define CATEGORY _T("Float") #endif using namespace xll; static AddIn xai_sin( Function(XLL_DOUBLE, _T("?xll_sin"), _T("XLL.SIN")) .Arg(XLL_DOUBLE, _T("x"), _T("is a floating number.")) .FunctionHelp(_T("Returns sin(x)")) .Category(CATEGORY) .Documentation(LR"( Evaluates the sin(x) using the Horner method. )") ); double WINAPI xll_sin(double x) { #pragma XLLEXPORT return sin(x); } #ifdef _DEBUG xll::test test_xll_sin([]() { double presult; double x = 0; presult = xll_sin(x); ensure(presult == 0); }); #endif // _DEBUG
Java
UTF-8
5,019
1.96875
2
[]
no_license
package com.huawei.mms.util; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Configuration; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.OnScaleGestureListener; import android.view.View; import android.widget.TextView; import cn.com.xy.sms.sdk.ui.popu.util.ContentUtil; import com.android.mms.ui.PreferenceUtils; import com.huawei.mms.ui.SpandTextView; import java.util.List; @SuppressLint({"NewApi"}) public class MmsScaleSupport implements OnScaleGestureListener { private Context mContext; private float mCurrentScale = ContentUtil.FONT_SIZE_NORMAL; private long mLastScale = 0; private SacleListener mListener; private float mScaleLarge = 3.0f; private float mScaleSmall = 0.7f; public interface SacleListener { void onScaleChanged(float f); } public static class MmsScaleHandler { private ScaleGestureDetector mDetector; private MmsScaleSupport mListener; private MmsScaleHandler(ScaleGestureDetector detector, MmsScaleSupport listener) { this.mDetector = detector; this.mListener = listener; } public float getFontScale() { return this.mListener.mCurrentScale; } public void setFontScale(float scale) { this.mListener.mCurrentScale = scale; } public boolean onTouchEvent(MotionEvent event) { return this.mDetector.onTouchEvent(event); } public static MmsScaleHandler create(Context context, SacleListener slistener) { MmsScaleSupport listener = new MmsScaleSupport(context, slistener); return new MmsScaleHandler(new ScaleGestureDetector(context, listener), listener); } } public static class ScalableTextView { private float mOriginFontSzie = 0.0f; private TextView mRefTextView; public ScalableTextView(TextView r) { this.mRefTextView = r; this.mOriginFontSzie = r.getTextSize(); } public static ScalableTextView create(View r) { return new ScalableTextView((TextView) r); } public TextView get() { return this.mRefTextView; } public void setText(CharSequence text) { this.mRefTextView.setText(text); } public void setText(CharSequence text, List<TextSpan> textSpan) { if (this.mRefTextView instanceof SpandTextView) { ((SpandTextView) this.mRefTextView).setText(text, (List) textSpan); } } public void setVisibility(int visibility) { this.mRefTextView.setVisibility(visibility); } public void setPressed(boolean pressed) { this.mRefTextView.setPressed(pressed); } public void setTextSize(float size) { this.mOriginFontSzie = size; this.mRefTextView.setTextSize(size); } public CharSequence getText() { return this.mRefTextView.getText(); } } public MmsScaleSupport(Context context, SacleListener listener) { this.mContext = context; this.mListener = listener; this.mCurrentScale = PreferenceUtils.getPreferenceFloat(context, "pref_key_sms_font_scale", ContentUtil.FONT_SIZE_NORMAL); onConfigurationChanged(context.getResources().getConfiguration()); } public boolean onScaleBegin(ScaleGestureDetector detector) { return true; } public void onScaleEnd(ScaleGestureDetector detector) { } public boolean onScale(ScaleGestureDetector detector) { if (this.mListener == null) { return true; } float scChange = detector.getScaleFactor(); if (scChange > 1.1f) { scChange = 1.1f; } else if (scChange < 0.9f) { scChange = 0.9f; } if (Math.abs(scChange - ContentUtil.FONT_SIZE_NORMAL) < 0.04f) { return false; } long current = System.currentTimeMillis(); if (((float) this.mLastScale) + 300.0f > ((float) current)) { return false; } this.mLastScale = current; this.mCurrentScale *= scChange; if (this.mCurrentScale > this.mScaleLarge) { this.mCurrentScale = this.mScaleLarge; } else if (this.mCurrentScale < this.mScaleSmall) { this.mCurrentScale = this.mScaleSmall; } else if (Float.isNaN(this.mCurrentScale)) { this.mCurrentScale = ContentUtil.FONT_SIZE_NORMAL; } this.mListener.onScaleChanged(this.mCurrentScale); PreferenceUtils.saveFontScale(this.mContext, this.mCurrentScale); return true; } public void onConfigurationChanged(Configuration config) { float scale = config.fontScale; this.mScaleLarge = 3.0f / scale; this.mScaleSmall = 0.7f / scale; } }
Python
UTF-8
150
2.53125
3
[ "BSD-3-Clause" ]
permissive
# Define you tests here """ import unittest class MlaskExampleTest(unittest.TestCase): def test_mlask_sum(self): self.assertEqual(1 + 1, 2) """
Markdown
UTF-8
8,811
2.75
3
[]
no_license
# parse-server-example Example project using the [parse-server](https://github.com/ParsePlatform/parse-server) module on Express. Read the full Parse Server guide here: https://github.com/ParsePlatform/parse-server/wiki/Parse-Server-Guide ### For Local Development * Make sure you have at least Node 4.3. `node --version` * Clone this repo and change directory to it. * `npm install` * Install mongo locally using http://docs.mongodb.org/master/tutorial/install-mongodb-on-os-x/ * Run `mongo` to connect to your database, just to make sure it's working. Once you see a mongo prompt, exit with Control-D * Uses dotenv to load environment variables: `cp .env-example .env`, then edit .env to include your Parse AppId, MasterKey and your CleverTap Account ID and CleverTap Account Passcode. * Run the server with: `npm start` * By default it will use a path of /parse for the API routes. To change this, or use older client SDKs, run `export PARSE_MOUNT=/1` before launching the server. * You now have a database named "dev" that contains your Parse data * Install ngrok and you can test with devices ### Usage With CleverTap Push Notifications * The CleverTap Node.js module will be installed during npm install. You can use it in your cloud code (cloud/main.js) to send push like this: ```javascript const CleverTap = require("clevertap"); const clevertap = CleverTap.init(process.env.CLEVERTAP_ACCOUNT_ID, process.env.CLEVERTAP_ACCOUNT_PASSCODE); Parse.Cloud.define('push', function(req, res) { /** * Send an immediate push to users subscribed to the specified channels * */ const channels = req.params.channels; if (!channels) { res.error("channels not present"); return; } const payload = { "name": "test push " + Math.round(new Date().getTime()/1000), "when": "now", "where": { "common_profile_prop": { "profile_fields": [{"name": "channels", "value": channels}] } }, "content": { "title":"Hello!", "body":"Just testing" }, "devices": ["ios", "android"] } clevertap.targets(clevertap.TARGET_CREATE, payload, {"debug":1}).then((r) => { res.success(r); }); }); Parse.Cloud.afterSave('GameScore', function(req) { /** * Send all users an immediate push notifiying them of a new Game Score. * */ const gameScore = req.object; const body = (gameScore) ? `New Game Score: ${gameScore.get("playerName")} ${gameScore.get("score")}` : "New Game Score"; const payload = { "name": "test push " + Math.round(new Date().getTime()/1000), "when": "now", "segment":"all", "content": { "title": "Hey There!", "body": body, }, "devices": ["ios", "android"] } clevertap.targets(clevertap.TARGET_CREATE, payload, {"debug":1}).then((r) => { console.log(r); }); }); ``` [Learn more about getting started with CleverTap Push Notifications here](https://support.clevertap.com/migration/parse/). ### Getting Started With Heroku + Mongolab Development #### With the Heroku Button [![Deploy](https://www.herokucdn.com/deploy/button.png)](https://heroku.com/deploy) #### Without It * Clone the repo and change directory to it * Log in with the [Heroku Toolbelt](https://toolbelt.heroku.com/) and create an app: `heroku create` * Use the [MongoLab addon](https://elements.heroku.com/addons/mongolab): `heroku addons:create mongolab:sandbox` * By default it will use a path of /parse for the API routes. To change this, or use older client SDKs, run `heroku config:set PARSE_MOUNT=/1` * Deploy it with: `git push heroku master` ### Getting Started With AWS Elastic Beanstalk #### With the Deploy to AWS Button <a title="Deploy to AWS" href="https://console.aws.amazon.com/elasticbeanstalk/home?region=us-west-2#/newApplication?applicationName=ParseServer&solutionStackName=Node.js&tierName=WebServer&sourceBundleUrl=https://s3.amazonaws.com/elasticbeanstalk-samples-us-east-1/eb-parse-server-sample/parse-server-example.zip" target="_blank"><img src="http://d0.awsstatic.com/product-marketing/Elastic%20Beanstalk/deploy-to-aws.png" height="40"></a> #### Without It * Clone the repo and change directory to it * Log in with the [AWS Elastic Beanstalk CLI](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html), select a region, and create an app: `eb init` * Create an environment and pass in MongoDB URI, App ID, and Master Key: `eb create --envvars DATABASE_URI=<replace with URI>,APP_ID=<replace with Parse app ID>,MASTER_KEY=<replace with Parse master key>` ### Getting Started With Microsoft Azure App Service #### With the Deploy to Azure Button [![Deploy to Azure](http://azuredeploy.net/deploybutton.png)](https://azuredeploy.net/) #### Without It A detailed tutorial is available here: [Azure welcomes Parse developers](https://azure.microsoft.com/en-us/blog/azure-welcomes-parse-developers/) ### Getting Started With Google App Engine 1. Clone the repo and change directory to it 1. Create a project in the [Google Cloud Platform Console](https://console.cloud.google.com/). 1. [Enable billing](https://console.cloud.google.com/project/_/settings) for your project. 1. Install the [Google Cloud SDK](https://cloud.google.com/sdk/). 1. Setup a MongoDB server. You have a few options: 1. Create a Google Compute Engine virtual machine with [MongoDB pre-installed](https://cloud.google.com/launcher/?q=mongodb). 1. Use [MongoLab](https://mongolab.com/google/) to create a free MongoDB deployment on Google Cloud Platform. 1. Modify `app.yaml` to update your environment variables. 1. Delete `Dockerfile` 1. Deploy it with `gcloud preview app deploy` A detailed tutorial is available here: [Running Parse server on Google App Engine](https://cloud.google.com/nodejs/resources/frameworks/parse-server) ### Getting Started With Scalingo #### With the Scalingo button [![Deploy to Scalingo](https://cdn.scalingo.com/deploy/button.svg)](https://my.scalingo.com/deploy) #### Without it * Clone the repo and change directory to it * Log in with the [Scalingo CLI](http://cli.scalingo.com/) and create an app: `scalingo create my-parse` * Use the [Scalingo MongoDB addon](https://scalingo.com/addons/scalingo-mongodb): `scalingo addons-add scalingo-mongodb free` * Setup MongoDB connection string: `scalingo env-set DATABASE_URI='$SCALINGO_MONGO_URL'` * By default it will use a path of /parse for the API routes. To change this, or use older client SDKs, run `scalingo env-set PARSE_MOUNT=/1` * Deploy it with: `git push scalingo master` # Using it Before using it, you can access a test page to verify if the basic setup is working fine [http://localhost:1337/test](http://localhost:1337/test). Then you can use the REST API, the JavaScript SDK, and any of our open-source SDKs: Example request to a server running locally: ```curl curl -X POST \ -H "X-Parse-Application-Id: myAppId" \ -H "Content-Type: application/json" \ -d '{"score":1337,"playerName":"Sean Plott","cheatMode":false}' \ http://localhost:1337/parse/classes/GameScore curl -X POST \ -H "X-Parse-Application-Id: myAppId" \ -H "Content-Type: application/json" \ -d '{}' \ http://localhost:1337/parse/functions/hello ``` Example using it via JavaScript: ```javascript Parse.initialize('myAppId','unused'); Parse.serverURL = 'https://whatever.herokuapp.com'; var obj = new Parse.Object('GameScore'); obj.set('score',1337); obj.save().then(function(obj) { console.log(obj.toJSON()); var query = new Parse.Query('GameScore'); query.get(obj.id).then(function(objAgain) { console.log(objAgain.toJSON()); }, function(err) {console.log(err); }); }, function(err) { console.log(err); }); ``` Example using it on Android: ```java //in your application class Parse.initialize(new Parse.Configuration.Builder(getApplicationContext()) .applicationId("myAppId") .clientKey("myClientKey") .server("http://myServerUrl/parse/") // '/' important after 'parse' .build()); ParseObject testObject = new ParseObject("TestObject"); testObject.put("foo", "bar"); testObject.saveInBackground(); ``` Example using it on iOS (Swift): ```swift //in your AppDelegate Parse.initializeWithConfiguration(ParseClientConfiguration(block: { (configuration: ParseMutableClientConfiguration) -> Void in configuration.server = "https://<# Your Server URL #>/parse/" // '/' important after 'parse' configuration.applicationId = "<# Your APP_ID #>" configuration.clientKey = "<# Your CLIENT_KEY #>" })) ``` You can change the server URL in all of the open-source SDKs, but we're releasing new builds which provide initialization time configuration of this property.
Markdown
UTF-8
4,145
2.609375
3
[]
no_license
--- title: spring restTemplate调用提供者方法 date: 2019-12-17 9:00:00 category: Learn tags: - springcloud - restTemplate --- > RestTemplate 简化了发起HTTP请求以及处理响应的过程,并且支持REST <!-- more --> 只需要引入spring-web包即可 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` --- 先配置 `RestTemplate` 的 configuration 文件, 还要进行中文乱码的配置。 `@LoadBalanced` 声明 该 restTemplate 开启负载均衡 ```java package com.example.springclient.configuration; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.List; @Configuration public class RestTemplateConfig { @LoadBalanced @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplateBuilder() .setConnectTimeout(Duration.ofSeconds(1)) .setReadTimeout(Duration.ofSeconds(1)) .build(); // 防止RestTemplate获取的中文乱码 restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter()); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(StandardCharsets.UTF_8); stringHttpMessageConverter.setWriteAcceptCharset(true); List<MediaType> mediaTypeList = new ArrayList<>(); mediaTypeList.add(MediaType.ALL); for (int i = 0; i < restTemplate.getMessageConverters().size(); i++) { if (restTemplate.getMessageConverters().get(i) instanceof StringHttpMessageConverter) { restTemplate.getMessageConverters().remove(i); restTemplate.getMessageConverters().add(i, stringHttpMessageConverter); } if(restTemplate.getMessageConverters().get(i) instanceof MappingJackson2HttpMessageConverter){ try{ ((MappingJackson2HttpMessageConverter) restTemplate.getMessageConverters().get(i)).setSupportedMediaTypes(mediaTypeList); }catch(Exception e){ e.printStackTrace(); } } } return restTemplate; } } ``` `Controller`控制器 ```java package com.example.springclient.controllers; import com.example.springclient.consumers.OpenClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.Map; /** * @author Administrator * @data 2019/12/12 * @time 15:45 */ @RestController @RequestMapping("open") public class OpenController { @Autowired private RestTemplate restTemplate; @PostMapping("test") public String test(String name, String age){ MultiValueMap<String, Object> map = new LinkedMultiValueMap(); map.add("name", name); map.add("age", age); String response = restTemplate.postForObject("http://SERVER-01/open/index", map, String.class); return response; } } ``` - RestTemplate的post参数不能使用MultiValueMap而不能使用HashMap - SERVER-01 是服务提供者的服务名 - 还实现了**简单轮询负载均衡(RoundRobin)**
Markdown
UTF-8
27,036
3.1875
3
[ "CC-BY-SA-4.0", "MIT" ]
permissive
--- title: Using Laravel resource controller with AngularJS ngResource kind: article created_at: '2014-12-02 00:00:00 +0800' slug: using-laravel-resource-controller-with-angularjs-ngresource abstract: 'An example of a RESTful API-based web app using Laravel 4.2 resource controller and AngularJS 1.4 NgResource' --- Laravel provides a simplified workflow to create a RESTful application namely RESTful Resource Controllers. It allows you to generate a set of standardized controller and route RESTful interface efficiently. Meanwhile AngularJS also has a module for facilitating RESTful resource exchange. In this article we will build a simplistic quoting (i.e. record what someone said) web app called *OneLine* which looks like this: <div style="text-align: center;"> <img src="./screenshot.png" title="And now for something completely different - Monty Python" /> <br /> <small><em>Img.</em> <strong>Not quite, though</strong></small> </div> Source Code: __<a href="https://github.com/tommyku/oneline">on GitHub</a>__ ### The Structure The back end is simple, there is only one object of interest per se namely "Quote". | Quote | |----------------| |+ id: integer | |+ quote: string | |+ author: string| |+ image: string | That means in Laravel, we will implement the logics (controller, model, database table and routes) around this "Quote" object. We will get down to the implementations soon. The front end can get quite structured and easy to understand when ngResource, ui-router and $broadcast are used. In *OneLine*, there are 3 views: Quote list, View quote and Write quote. | Quote list | View quote | Write quote | |------------|-------------|------------| |<img src="./5b2fc7bb-d30a-420b-9eb6-47205052c9f1.png" title="screenshot of quote list screen" />|<img src="./aef04f18-c5fb-4408-ad7b-7e634a14aa50.png" title="screenshot of viewing quote, basically text overlay over an backdrop image" />|<img src="./dd7f44cd-ae8f-4531-bfd0-37e90b9e482a.png" title="screenshot of posting quote, 3 input textbox and a submit button" />| Each of these views, or *states* are defined with ui-router and the "Quote" object are exchanged with the server via a RESTful interface using ngResource. The operation may seem trivial when looking at the views separately, but when joining the views together the transaction can get a little bit complex as it involves exchange of "Quote" object across views. Having introduced the front/back end, what is left is the RESTful API. I wasn't lying about the convenience of using Laravel's resource controller. According to [Laravel documentation](http://laravel.com/docs/4.2/controllers#restful-resource-controllers) a standardized RESTful API can be defined only by one line of code. ~~~ php Route::resource('qoute','QuoteController'); ~~~ Or 3 lines if you insist. ~~~ php Route::resource( 'quote', 'QuoteController' ); ~~~ Using 1 (or 3) lines of code we have already defined a set of routes as follows: |Verb|Path|Action|Route Name| |----|----|------|----------| |GET|/quote|**index**|quote.index| |GET|/quote/create|create|quote.create| |POST|/quote|**store**|quote.store| |GET|/quote/{quote}|show|quote.show| |GET|/quote/{quote}/edit|edit|quote.edit| |PUT/PATCH|/quote/{quote}|update|quote.update| |DELETE|/quote/{quote}|destroy|quote.destroy| We only need 2: *index* and *store*. We will get to the part excluding other routes and just take these 2. ### The Laravel part <img src="./laravel-text-logo.png" alt="laravel logo" width="250px" style="margin: 0;" /> 1. [Resource controller](#resource-controller) 2. [Routes](#routes) 3. [Migration files](#migration) 4. [Model](#model) 5. [Putting them together](#putting-them-together) For Laravel setup, please refer to [a previous tutorial](http://blog.tommyku.com/blog/create-simple-contact-list-application-with-laravel-and-openshift-integration-part-1) which is a good place to getting started with Laravel. #### <a name="resource-controller"></a> Resource controller Normally we create a controller under `app/controllers/` by extending the *BaseController* class already defined there. To define a resource controller, we use `artisan`. Under Laravel root, ~~~ bash php artisan controller:make QuoteController --only=index,store ~~~ Note `--only=index,store` restricts the generator to generate only 2 respective methods inside *QuoteController*. ~~~ php <?php /* app/controllers/QuoteController.php */ class QuoteController extends \BaseController { /** * Display a listing of the resource. * * @return Response */ public function index() { // } /** * Store a newly created resource in storage. * * @return Response */ public function store() { // } } ~~~ As for the implementations, we will leave them as is for the moment and come back later after writing migrations and model of the "Quote" object. #### <a name="routes"></a> Routes ~~~ php <?php /* app/routes.php */ Route::get('/', function() { return View::make('app'); }); Route::resource( 'quote', 'QuoteController', ['only' => ['store', 'index']] ); ~~~ I insist to make use 4 lines for the resource route. The 3rd parameter restricts what route to be defined as we need only *store* and *index*. At least, it saves us the trouble of conceiving the route names and controller method names. The ordinary `GET /` route up there is the entry point of our web app, where the AngularJS web app itself is delivered to the client. #### <a name="migration"></a> Migration files [Migration and seeding](http://laravel.com/docs/4.2/migrations) is a great way to deploy your app to a new environment by running `artisan migrate` command. Laravel migration has other awesome features for you to discover. In this tutorial, we just focus on building database tables. Before actually doing that, make sure you have `app/config/database.php` well configured. First we need to create a migration: ~~~ bash php artisan migrate:make create_quotes_table --table=quotes ~~~ Open the migration file in `app/database/migrations/DATE_OF_YOUR_MIGRATION_create_quotes_table.php`, and write things like: ~~~ php <?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateQuotesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('ol_quotes', function(Blueprint $t) { $t->increments('id'); $t->string('quote'); $t->string('author'); $t->string('image'); $t->timestamps(); $t->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('ol_quotes'); } } ~~~ The method *up()* defines what should be done when running this migration, and *down()* reverts it. With migrations you do not even have to write SQL, just call the functions as in *up()*. You may refer to [Laravel Schema Builder](http://laravel.com/docs/4.2/schema) for creating fields of other data types. To run the migration, we use `artisan`. ~~~ bash php artisan migrate ~~~ #### <a name="model"></a> Model Laravel 4.2 does not come with a model generator, though someone has [implemented and open sourced it](https://github.com/JeffreyWay/Laravel-4-Generators). In this tutorial, we stick to the basic Laravel, thus we need to write the model ourselves. "Quote" object is on its own, without clumsy hasOne/hasMany/belongsTo relations, so its model should look simple. ~~~ php <?php /* app/models/Quote.php */ use Illuminate\Database\Eloquent\SoftDeletingTrait; class Quote extends Eloquent { use SoftDeletingTrait; protected $dates = ['deleted_at']; protected $table = 'ol_quotes'; protected $hidden = ['created_at', 'updated_at', 'deleted_at']; protected $fillable = ['quote', 'author', 'image']; } ~~~ The model does look simple. Easily you can map the respective fields with the columns in the database table. #### <a name="putting-them-together"></a> Putting them together Now we have had everything needed to get the back end running, it is time to go back to *QuoteController*. ~~~ php <?php /* app/controllers/QuoteController.php */ class QuoteController extends \BaseController { /** * Display a listing of the resource. * * @return Response */ public function index() { // $sp means how many posts to skip, // use this for infinite scrolling if (!Input::has('sp')) { $sp = 0; } else { $sp = intval(Input::get('sp')); } return Response::json([ 'sp' => intval($sp)+10, 'quotes' => Quote::orderBy('created_at', 'desc')->skip($sp)->take(10)->get() ]); } /** * Show the form for creating a new resource. * * @return Response */ public function store() { // validate input if (!Input::has('quote')) { return Response::make('Bad Request', 400); } // write records // 'John Doe' said it if nobody said it, // stub the backdrop image if no image is given $quote = Quote::create([ 'quote' => Input::get('quote'), 'author' => (Input::has('author')) ? Input::get('author') : 'John Doe', 'image' => (Input::has('image')) ? Input::get('image') : asset('res/stub.png') ]); // done return Response::make($quote); } } ~~~ The workflow suggested about tries to minimize the time required to introduce a resource to the system. This setup above will make more sense when you get to handle a bigger system, where multiple RESTful resources are to be handled. ### The AngularJS part <img src="./AngularJS_logo.png" alt="angularjs logo" width="250px" style="margin: 0;" /> 0. [Prerequisites](#ngprerequisites) 1. [Routes](#ngroutes) 2. [Resource](#ngresource) 3. [Views](#ngviews) 1. [Quote list](#ngquotelist) 2. [View quote](#ngviewquote) 3. [Write quote](#ngwritequote) Unlike Laravel I have not talked about Angular JS in this blog before. Grab a tutorial or two if you feel confused in the following part. Little secret, the two colors <span style="color: #d91d15 ;">Fire Engine Red</span> and <span style="color: #a3130c">Sangria</span> used in the app's header actually came from Angular's logo. #### <a name="ngprerequisites"></a> Prerequisites *OneLine* makes use of a couple AngularJS libraries and JQuery, to get them properly, I suggest that you use bower ([grab bower](http://bower.io/)). To get all our dependencies ready, run ~~~ bash bower install angular angular-resource jquery ngInfiniteScroll angular-ui-router ~~~ Don't forget to include them in your `app/views/app.php`, this is the app's entry point when user first visit the site. ~~~ html <!DOCTYPE html> <!-- app/view/app.php --> <html ng-app="link"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <title>Quote - random quote for your inspiration</title> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" /> <meta name="description" content="Light-weight search engine for stored links" /> <script type="text/javascript" src="js/jquery/dist/jquery.min.js"></script> <script type="text/javascript" src="js/angular/angular.min.js"></script> <script type="text/javascript" src="js/angular-ui-router/release/angular-ui-router.min.js"></script> <script type="text/javascript" src="js/angular-resource/angular-resource.min.js"></script> <script type="text/javascript" src="js/ngInfiniteScroll/build/ng-infinite-scroll.min.js"></script> <script type="text/javascript" src="js/app.js"></script> <link rel="shortcut icon" href="" /> <link rel="apple-touch-icon" href="" /> <link rel="stylesheet" href="css/base.css" /> <link rel="stylesheet" href="css/animate.css" /> </head> <body ui-view> </body> </html> ~~~ #### <a name="ngroutes"></a> Routes Like Laravel's `route.php`, AngularJS has its way of defining paths and they can be seens as `Activity` in Android apps. The `<body>` tag containing the directive `ui-view` serves as a container of content provided by each path, where their templates defined in a separate folder `/partials` To define the paths, or states, it looks something like this. ~~~ javascript var app = angular.module("link", ['ui.router', 'ngResource', 'infinite-scroll', 'monospaced.elastic']); /* js/app.js */ /* something else :p */ app.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('main', { url: '/', templateUrl: 'partials/main.html', controller: 'mainCtrl' }) .state('post', { url: '/post', templateUrl: 'partials/post.html', controller: 'postCtrl' }) .state('view', { url: '/view/?params', templateUrl: 'partials/view.html', controller: 'viewCtrl' }); // defaul route $urlRouterProvider.otherwise('/'); }); /* something else :p */ ~~~ Breaking each state down, we have. ~~~ javascript // define a new state $stateProvider .state('main', { url: '/', // this is shown on the location bar templateUrl: 'partials/main.html', // url to template of the view // each view has its own controller // passing data across controllers can be trickly, more later controller: 'mainCtrl' }) ~~~ I do not see the need of explaining what is inside `partials/main.html` so I am just posting its content as an example. <!-- I should really get a syntax hightlighter --> ~~~ html <header id="header"> <div id="app-name"> Quote <span class="header-btn pull-right" ui-sref="post">Post</span> </div> </header> <ul class="main-list"> <li class="link-block animated fadeInUp" ng-repeat="item in pack" style="-webkit-animation-delay:{{$index%10*0.1}}s; animation-delay:{{$index%10*0.1}}s;" ng-click="goToView(item)"> <a title="{{item.author}}"> <div class="data-wrapper"> <div class="quote" data-ldquo="&ldquo;" data-rdquo="&rdquo;">{{item.quote}}</div> <div class="author ng-binding" style="padding-left: 0; margin-top: 0.2em;">{{item.author}}</div> </div> </a> </li> </ul> <div infinite-scroll="fetch()" infinite-scroll-distance="3"></div> ~~~ #### <a name="ngresource"></a> Resource ngResource provides an inteface for manipulating a resource using RESTful API provided by the back end. In *OneLine*, there is only one resource, Quote object. We want to define it in a factory so it is reusable across controllers. ~~~ javascript /* js/app.js */ /* something else :p */ app.factory('Quote', function($resource) { return $resource( 'quote', null, { 'get': { 'method': "GET", 'params': { 'sp': '0' } } } ); }); /* something else :p */ ~~~ ngResource's documentation and examples are rather insufficient so you may need to experiment with it serveral time before getting it work. In the factory, a resource is simply returned, first parameter being the URL to the resource, second parameter is an object defining the default paramters, the third parameter is an object for extra methods and routes. To use a resource created by a factory, see the following examples. __Getting a list of quotes, skip elements by *sp*__ ~~~ javascript var quote = new Quote(); quote.$get({'sp': $scope.sp}) .then(function(response) { $scope.sp = response.sp; console.log(response); $scope.pack = $scope.pack.concat(response.quotes); $rootScope.$broadcast('fetch-done'); if (response.quotes.length == 0) { $rootScope.$broadcast('fetch-nomore'); } }) .catch(function(response) { $rootScope.$broadcast('fetch-fail'); }); ~~~ __Posting a quote__ ~~~ javascript var quote = new Quote($scope.quote); // $scope.quote contains the parameters to be passed quote.$save() .then(function(response) { console.log(response); $rootScope.$broadcast('post-done'); }) .catch(function(response) { console.log(response); $rootScope.$broadcast('post-fail'); }); ~~~ The general working is like: (1) instantiate a resource object; (2) set parameter; (3) invoke the respective method to make a RESTful call; (4) process the result or catch if there is an error (like success and error handlers in jQuery) #### <a name="ngviews"></a> Views Lastly, we need to link things up. In this part we will look at the templates and the controllers for each view, and how user navigate from one to another. It feels like using `Intent` to move between views, but much simplier and possible a bit more troublesome in passing data. Scroll down to learn more. ##### <a name="ngquotelist"></a> Quote list <center> <img src="./5b2fc7bb-d30a-420b-9eb6-47205052c9f1.png" style="width: 100%; max-width: 400px;" title="screenshot of quote list screen" /> </center> ~~~ <!-- In partials/main.html --> <header id="header"> <div id="app-name"> Quote <span class="header-btn pull-right" ui-sref="post">Post</span> </div> </header> <ul class="main-list"> <li class="link-block animated fadeInUp" ng-repeat="item in pack" style="-webkit-animation-delay:{{$index%10*0.1}}s; animation-delay:{{$index%10*0.1}}s;" ng-click="goToView(item)"> <a title="{{item.author}}"> <div class="data-wrapper"> <div class="quote" data-ldquo="&ldquo;" data-rdquo="&rdquo;">{{item.quote}}</div> <div class="author ng-binding" style="padding-left: 0; margin-top: 0.2em;">{{item.author}}</div> </div> </a> </li> </ul> <div infinite-scroll="fetch()" infinite-scroll-distance="3"></div> ~~~ List items are inserted into the list by the useful and common `ng-repeat`, which references to a variable `pack` within the scope. At the bottom there is a tag calling the method `fetch()` whenever the user scroll near that &lt;div>, serving the purpose of infinite scrolling. Now, the controller. ~~~ javascript app.controller("mainCtrl", function($scope, Quote, $rootScope, $state) { $scope.sp = 0; $scope.nomore = false; $scope.loading = false; $scope.pack = []; $scope.fetch = function() { if ($scope.nomore || $scope.loading) { return; } $rootScope.$broadcast('fetch-initiate'); var quote = new Quote(); quote.$get({'sp': $scope.sp}) .then(function(response) { $scope.sp = response.sp; console.log(response); $scope.pack = $scope.pack.concat(response.quotes); $rootScope.$broadcast('fetch-done'); if (response.quotes.length == 0) { $rootScope.$broadcast('fetch-nomore'); } }) .catch(function(response) { $rootScope.$broadcast('fetch-fail'); }); }; $scope.goToView = function(item) { var param = angular.toJson(item); $state.go('view', {params: param}); }; $scope.$on('fetch-initiate', function(e, data) { $scope.loading = true; console.log('fetch initiated'); }); $scope.$on('fetch-done', function(e, data) { $scope.loading = false; console.log('fetch done'); }); $scope.$on('fetch-fail', function(e, data) { console.log('fetch failed'); }); $scope.$on('fetch-nomore', function(e, data) { $scope.nomore = true; console.log('fetch nomore'); }); }); ~~~ Note that in the parameter list, `function($scope, Quote, $rootScope, $state)`, `Quote` has been injected, along with `$rootScope` and `$state`. The usage of `Quote` has been stated [above](#ngresource). Here we are looking at two interesting things: `$rootScope` and `$state`. `$rootScope` allows you to define a custom "event" that you are broadcasting like throwing exceptions, but it works backwards, from the top of scope tree to the bottom. It feels like defining functions for specific occasions yet it makes more sense this way as the call will be "broadcasted" throughtout the scope tree. `$state` here is primarily for transitioning to another state. `$state.go('view', {params: param})` leads the user to the "View quote" state and passes some parameters along the way. This is a easier way to pass unsensitive and simple data across states in AngularJS and there is a more elegant way not covered in this article. Scroll down to the appendix [use service singleton to pass parameters across controllers](#servicesingleton) to view it. ##### <a name="ngviewquote"></a> View quote <center> <img src="./aef04f18-c5fb-4408-ad7b-7e634a14aa50.png" style="width: 100%; max-width: 400px;" title="screenshot of viewing quote, basically text overlay over an backdrop image" /> </center> ~~~ html <!-- partials/view.html --> <div class="animated fadeIn fullScreen fullScreen-bg" style="background-image:url({{quote.image}});"> <div class="centerQuote"> <h1 class="quote" data-ldquo="&ldquo;" data-rdquo="&rdquo;">{{quote.quote}}</h1> <em class="author">{{quote.author}}</em> </div> </div> ~~~ When a user select a quote from the main view or post a new quote, the user will be directed to this "view" state. Parameters to this page are the `image`, `quote` and `author` presented in this template respectively. How do we get the parameters? ~~~ javascript app.controller("viewCtrl", function($scope, $rootScope, $stateParams) { $scope.quote = angular.fromJson($stateParams.params); }); ~~~ One simply reads them from `$stateParams`. Note that this example omits validations for simplexity. In the appendix there is a more elegant way [using angular service](#servicesingleton). ##### <a name="ngwritequote"></a> Write quote <center> <img src="./dd7f44cd-ae8f-4531-bfd0-37e90b9e482a.png" style="width: 100%; max-width: 400px;" title="screenshot of posting quote, 3 input textbox and a submit button" /> </center> ~~~ html <!-- partials/post.html --> <header id="header"> <div id="app-name"> <span class="header-btn pull-left" ui-sref="main">Back</span> Quote <span class="header-btn pull-right" ng-click="post()">Submit</span> </div> </header> <div class="content"> <div class="link-block"> <input type="text" ng-model="quote.quote" placeholder="QUOTE" class="msd-elastic" ng-disabled="disabled" /> </div> <div class="link-block"> <input type="text" ng-model="quote.author" placeholder="BY" class="ng-pristine ng-valid ng-touched" ng-disabled="disabled"> </div> <div class="link-block"> <input type="text" ng-model="quote.image" placeholder="BACKDROP" class="ng-pristine ng-valid ng-touched" ng-disabled="disabled"> </div> <div class="clearfix"></div> </div> ~~~ To move from one state to another, there is a directive called `ui-sref` in the Back button above so you can move to another state without passing any parameter, but if you do you will need to define a function under the scope like `ng-click="post()"` to capture the values and pass it with `$state.go()`. ~~~ javascript app.controller("postCtrl", function($scope, Quote, $rootScope, $state) { $scope.disabled = false; $scope.quote = { 'quote': '', 'author': '', 'image': '' }; $scope.post = function() { $rootScope.$broadcast('post-start'); var quote = new Quote($scope.quote); quote.$save() .then(function(response) { console.log(response); $rootScope.$broadcast('post-done'); }) .catch(function(response) { console.log(response); $rootScope.$broadcast('post-fail'); }); }; $scope.$on('post-start', function(e, data) { $scope.disabled = true; }); $scope.$on('post-done', function(e, data) { // done and go to see the detail $state.go('view', {params: angular.toJson($scope.quote)}); }); $scope.$on('post-fail', function(e, data) { // enable the input $scope.disabled = false; }); }); ~~~ Note the line `$state.go('view', {params: angular.toJson($scope.quote)});`, one cannot simply go to another state by using `ui-sref` if one needs to pass some parameters. ### Conclusion This article aims to helping one getting started with Larvel resource controller and AngularJS ngResource because they are great ways to save time in developing RESTful interactions. The practices used are not necessarily the best implementations as I am also still learning, kindly please correct me in the comment section if I am wrong. In the next planned article I am getting into Laravel Auth and Blade templating, so stay tuned! ### References 1. [Laravel - The PHP Framework For Web Artisans. (RESTful Resource Controllers)](http://laravel.com/docs/4.2/controllers#restful-resource-controllers) 2. [Laravel - The PHP Framework For Web Artisans. (Migrations & Seeding)](http://laravel.com/docs/4.2/migrations) 2. [AngularJS Documentation for ngResource](https://docs.angularjs.org/api/ngResource) ### Appendix #### <a name="servicesingleton"></a> Use service singleton to pass parameters across controllers When passing parameters among AngularJS controllers, they cannot be simply passed. One way to do so is to define a service singleton which has the same state across all its instances. Defining a service feels like defining a class, one defines its attributes and methods, and return a reference to itself. ~~~ javascript app.service("PostService", function() { var post = {}; var setPost = function(obj) { post = obj; }; var getPost = function() { return post; }; return { setPost: setPost, getPost: getPost }; }); ~~~ This example constructs a simple service for passing a "Post" across controllers, with one attribute containing the post itself, and a mutator and accessor for that object. To make the changes to the object effective, though, we need to put them into the scope under the controller. ~~~ javascript /* inside a controller */ $scope.$PostService = PostService; ~~~ Then you can convenient call the mutator and accessor of the `PostService` knowing its change will reflect in any other controller. ~~~ javascript /* in one controller*/ $scope.$PostService = PostService; $scope.$PostService.setPost({"title": "hello", "content": "world"}); console.log($scope.$PostService.getPost()); // gives {"title": "hello", "content": "world"} ~~~ ~~~ javascript /* in another controller*/ $scope.$PostService = PostService; console.log($scope.$PostService.getPost()); // also gives {"title": "hello", "content": "world"} ~~~ As an appendix I am not going to further details than just making it work, but if you are interested, [someone has written a great article explaining the use of service](https://rclayton.silvrback.com/passing-state-via-services). Stay tuned to [my blog](https://blog.tommyku.com) as I may will post more Laravel/AngularJS articles very soon!
Java
UTF-8
2,260
2.28125
2
[ "MIT" ]
permissive
package top.viewv.controller; /* * 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. */ import java.io.IOException; import java.net.URL; import java.util.Objects; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import top.viewv.api.Gravatar; /** * * @author oXCToo */ // !Thank you very much! oXCToo! public class newhomeController implements Initializable { public ImageView userIcon; @FXML private VBox pnl_scroll; @FXML private void handleButtonAction() { refreshNodes(); } @Override public void initialize(URL url, ResourceBundle rb) { refreshNodes(); setUserIcon(); } private void setUserIcon(){ userIcon.setImage(Gravatar.imageFromMail("zxnnet@gmail.com")); } private void refreshNodes() { pnl_scroll.getChildren().clear(); Node [] nodes = new Node[15]; Node node; for(int i = 0; i<5; i++) { try { FXMLLoader loader = new FXMLLoader(Objects.requireNonNull( Thread.currentThread(). getContextClassLoader(). getResource("data/ProductItem.fxml"))); node = loader.load(); //调用下面的函数可以得到控制器 ProductItemController productItemController = loader.getController(); productItemController.setLabPrice("170"); //node = FXMLLoader.load(Objects.requireNonNull(Thread.currentThread().getContextClassLoader().getResource("data/ProductItem.fxml"))); nodes[i] = node; pnl_scroll.getChildren().add(nodes[i]); } catch (IOException ex) { Logger.getLogger(newhomeController.class.getName()).log(Level.SEVERE, null, ex); } } } }
Java
UTF-8
5,183
2.109375
2
[ "Apache-2.0" ]
permissive
package com.example.crops; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; public class ResultActivity extends Activity { private ImageButton imageButton2; private ImageButton imageButton3; public static String APP_ID="10112138"; public static String SECRET_ID="AKIDShgQu7Sj8JEtHPmsDH5csra2FBqFJFqB"; public static String SECRET_KEY="C8rKYYnoa8QTGo7B0av0pOkrjMjGbhZC"; public static String USER_ID="876899938"; private Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { TextView tv = (TextView) findViewById(R.id.textView4); tv.setText(msg.obj.toString()); } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.resultactivity); imageButton2= (ImageButton) findViewById(R.id.imageButton2); imageButton3= (ImageButton) findViewById(R.id.imageButton3); String path=getIntent().getStringExtra("PicturePath"); ImageView imageview=(ImageView) findViewById(R.id.picture); imageButton2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position=0; Intent intent=new Intent(); intent.setAction("huang"); intent.addCategory("android.intent.category.DEFAULT"); Bundle bundle=new Bundle(); bundle.putInt("position",position); intent.putExtras(bundle); ResultActivity.this.startActivity(intent); } }); imageButton3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position=0; Intent intent=new Intent(ResultActivity.this,donghua.class); Bundle bundle=new Bundle(); bundle.putInt("position",position); intent.putExtras(bundle); startActivity(intent); } }); //由于这样稚嫩获得横屏,所以我们要使用流的形式来转换 // Bitmap bitmap=BitmapFactory.decodeFile(path); // imageview.setImageBitmap(bitmap); final FileInputStream fis; try { fis = new FileInputStream("/storage/emulated/0/Pictures/abc.png"); Bitmap bitmap=BitmapFactory.decodeStream(fis); /*Matrix matrix=new Matrix(); matrix.setRotate(90); bitmap=Bitmap.createBitmap(bitmap, 0,0, bitmap.getWidth() ,bitmap.getHeight(),matrix,true);*/ imageview.setImageBitmap(bitmap); new Thread(){ public void run(){ Bitmap bitmap=BitmapFactory.decodeStream(fis); Youtu faceYoutu = new Youtu(APP_ID, SECRET_ID, SECRET_KEY, Youtu.API_YOUTU_END_POINT); JSONObject respose; try { respose = faceYoutu.DetectFace(bitmap,0); Message msg = new Message(); msg.obj = respose; handler.sendMessage(msg); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }.start(); /*Youtu faceYoutu = new Youtu(APP_ID, SECRET_ID, SECRET_KEY, Youtu.API_YOUTU_END_POINT); JSONObject respose; try { respose = faceYoutu.DetectFace(bitmap,0); Message msg = new Message(); msg.obj = respose; handler.sendMessage(msg); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); }*/ } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Markdown
UTF-8
4,781
3.390625
3
[ "MIT" ]
permissive
# Wrangle and Analyze Data # Introduction This project focused on wrangling data from the WeRateDogs Twitter account using Python, documented in a Jupyter Notebook (wrangle_act.ipynb). This Twitter account rates dogs with humorous commentary. The rating denominator is usually 10, however, the numerators are usually greater than 10. [They’re Good Dogs Brent](http://knowyourmeme.com/memes/theyre-good-dogs-brent) wrangle WeRateDogs Twitter data to create interesting and trustworthy analyses and visualizations. WeRateDogs has over 4 million followers and has received international media coverage. WeRateDogs downloaded their Twitter archive and sent it to Udacity via email exclusively for us to use in this project. This archive contains basic tweet data (tweet ID, timestamp, text, etc.) for all 5000+ of their tweets as they stood on August 1, 2017 ## The Data ### Enhanced Twitter Archive The WeRateDogs Twitter archive contains basic tweet data for all 5000+ of their tweets, but not everything. One column the archive does contain though: each tweet's text, which I used to extract rating, dog name, and dog "stage" (i.e. doggo, floofer, pupper, and puppo) to make this Twitter archive "enhanced.".We manually downloaded this file manually by clicking the following link: [twitter_archive_enhanced.csv](https://d17h27t6h515a5.cloudfront.net/topher/2017/August/59a4e958_twitter-archive-enhanced/twitter-archive-enhanced.csv) ### Additional Data via the Twitter API Back to the basic-ness of Twitter archives: retweet count and favorite count are two of the notable column omissions. Fortunately, this additional data can be gathered by anyone from Twitter's API. Well, "anyone" who has access to data for the 3000 most recent tweets, at least. But we, because we have the WeRateDogs Twitter archive and specifically the tweet IDs within it, can gather this data for all 5000+. And guess what? We're going to query Twitter's API to gather this valuable data. ### Image Predictions File he tweet image predictions, i.e., what breed of dog (or other object, animal, etc.) is present in each tweet according to a neural network. This file (image_predictions.tsv) hosted on Udacity's servers and we downloaded it programmatically using python Requests library on the following (URL of the file: https://d17h27t6h515a5.cloudfront.net/topher/2017/August/599fd2ad_image-predictions/image-predictions.tsv) ## Key Points Key points to keep in mind when data wrangling for this project: * We only want original ratings (no retweets) that have images. Though there are 5000+ tweets in the dataset, not all are dog ratings and some are retweets. * Fully assessing and cleaning the entire dataset requires exceptional effort so only a subset of its issues (eight (8) quality issues and two (2) tidiness issues at minimum) need to be assessed and cleaned. * Cleaning includes merging individual pieces of data according to the rules of tidy data. * The fact that the rating numerators are greater than the denominators does not need to be cleaned. This unique rating system is a big part of the popularity of WeRateDogs. * We do not need to gather the tweets beyond August 1st, 2017. We can, but note that we won't be able to gather the image predictions for these tweets since we don't have access to the algorithm used. # Project Details Fully assessing and cleaning the entire dataset would require exceptional effort so only a subset of its issues (eight quality issues and two tidiness issues at minimum) needed to be assessed and cleaned. The tasks for this project were: * Data wrangling, which consists of: * Gathering data * Assessing data * Cleaning data * Storing, analyzing, and visualizing our wrangled data * Reporting on 1) our data wrangling efforts and 2) our data analyses and visualizations ## Installing * Install Jupyter Notebook to run `wrangle_act.ipynb`. * Need consumer_key, consumer_secret, access_token, access_secret to query from Twitter API. * Require the following libraries installed. * numpy * pandas * requests * tweepy * json * matplotlib.pyplot ## Files * `act_report`: Communicates the insights and displays the Visualizations produced from the wrangled data. * `./Data/image_prediction.tsv`: Data downloaded using Requests library and URL. * `./Data/tweet_json.txt`: Data gathered from twitter API. * `./Data/twitter-archive-enhanced.csv`: File downloaded from Udacity. * `./Data/twitter_archive_master.csv`: The clean DataFrame 1. * `./Data/twitter_image_predictions.csv`: The clean DataFrame 2. * `wrangle_act.ipynb`: The main file containing all the gathering, wrangling and analyzing work. * `wrangle_report`: Briefly describes my wrangling efforts. ## Resources * Twitter API * Files downloaded from Udacity
Markdown
UTF-8
1,280
3.28125
3
[]
no_license
# Full-Stack-Software-Journey A repository to hold all the relevant files for my journey to become a Software Engineer. This repository will delve into HTML, CSS, JavaScript (ES6), and the MEAN stack. # Phase 1: Foundation The first phase of the boot camp, Foundation, equips you with the fundamental concepts of web development, covering front end technologies like HTML, CSS, and JavaScript, as well as command line fundamentals and API consumption. Ruby Data Structures and Algorithms (Ruby/JavaScript) HTML/CSS Git Bootstrap JavaScript jQuery APIs AJAX # Phase 2: Technical In the second phase, Technical, you learn the skills necessary to engineer a full stack web application, working with servers, databases, and other back end technologies, and connecting them to the front end. Node Express servers MySQL Handlebars Sequelize Testing Error Handling Heroku # Phase 3: Performance The last phase, Performance, has a dual meaning in that you acquire skills to optimize your web applications for speed and efficiency as well as prepare yourself for the transition to a career in web development. MongoDB Progressive Web Apps (PWAs) React MERN Computer Science Portfolios
Python
UTF-8
133
3.796875
4
[]
no_license
x=input("请输入一个5位数字:") if x==x[::-1]: print("这是一个回文数") else: print("这不是一个回文数")
PHP
UTF-8
450
3.5625
4
[]
no_license
<?php class car { private $matricule; public function __construct() {; } //GETTERS SETTERS public function getMatricule() { return $this->matricule; } public function setMatricule($value) { $this->matricule = $value; } //For Display public function render() { echo $this->getMatricule(); } } $Renault = new car(); $Renault->setMatricule("B-765237653-D-76876347863"); ?> <h3><?= $Renault->render(); ?></h3>
Markdown
UTF-8
1,917
3.484375
3
[]
no_license
# 选择结构 - if ``` (1)------------ if(条件) { //代码块 } 注: 只有一条语句时,建议不省略{} (2)------------ && || ! (3)------------ if(条件){ //代码块1 }else{ //代码块2 } (4)------------ 多重if选择结构 : if(条件){ //代码块1 }else if(条件){ //代码块2 }else{ //代码块3 } (5)------------ if嵌套 ``` - switch ``` switch(表达式){ case 常量1: 语句; break; case 常量2: 语句; break; ... default: 语句; break; } ``` ``` 例: package mypackage; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); if(input.hasNextInt()){ int mingCi = input.nextInt(); switch(mingCi){ case 1: System.out.println("参加麻省理工大学组织的夏令营"); break; case 2: System.out.println("奖励惠普笔记本一部"); break; case 3: System.out.println("奖励移动硬盘一个"); break; default: System.out.println("没有任何奖励"); } }else{ System.out.println("请输入正确的数字"); } } } 运行结果: 3 奖励移动硬盘一个 ``` - 知识点补充 ``` 1. 产生随机数(0~9)的方法: package mypackage; public class Test { public static void main(String[] args) { int randomNum = (int)(Math.random()*10); System.out.println(randomNum); } } 输出结果: 6 2. 通过键盘获取输入: Scanner input = new Scanner(System.in); 3. 通过hasNextlnt()判断输入的是否是数字: Scanner input = new Scanner(System.in); if(input.hasNextlnt()){ ... } else{ System.out.println("请输入正确的数字"); } ```
Java
UTF-8
464
2.75
3
[]
no_license
package Uebung1_Komplexitaet; public class Uebung142 { public static void main(String[] args) { int n = 1000000000; int i; int j; int sum = 0; long start = System.currentTimeMillis(); for (i=0; i<n; i++) { for (j=0; j<n; j++) { sum++; } } long stop = System.currentTimeMillis(); long zeit = stop - start; System.out.println(zeit); } }
Python
UTF-8
947
3.921875
4
[]
no_license
#!/usr/bin/python GRID_SIZE = 21 # Ludicrously slow method! def traverse_grid(path, x, y, count): path.append((x, y)) # End of the grid! if x == GRID_SIZE - 1 and \ y == GRID_SIZE - 1: #print path return count + 1 else: # You can move right. Do it! if (x + 1) <= (GRID_SIZE - 1): count = traverse_grid(path, x + 1, y, count) # You can move down. Do it! if (y + 1) <= (GRID_SIZE - 1): count = traverse_grid(path, x, y + 1, count) return count #print traverse_grid([], 0, 0, 0) # Super fast method! # The number of lattice paths from the origin (0, 0) to a point (a, b) is the # binomial coefficient: (a + b / a ) # http://mathworld.wolfram.com/BinomialCoefficient.html def factorial(n): if n > 1: return n * factorial(n - 1) else: return 1 n = 40 k = 20 print factorial(n) / (factorial(n - k) * factorial(k))
Java
UTF-8
2,865
2.34375
2
[ "BSD-2-Clause" ]
permissive
package at.o2xfs.xfs.api; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import at.o2xfs.memory.databind.annotation.MemoryPropertyOrder; import at.o2xfs.memory.databind.annotation.Pointer; @MemoryPropertyOrder({ "logicalName", "workstationName", "appId", "description", "version" }) public final class VersionError { public static class Builder { private String logicalName; private String workstationName; private String appId; private byte[] description; private WfsVersion version; public Builder logicalName(String logicalName) { this.logicalName = logicalName; return this; } public Builder workstationName(String workstationName) { this.workstationName = workstationName; return this; } public Builder appId(String appId) { this.appId = appId; return this; } public Builder description(byte[] description) { this.description = description; return this; } public Builder version(WfsVersion version) { this.version = version; return this; } public VersionError build() { return new VersionError(this); } } private final String logicalName; private final String workstationName; private final String appId; private final byte[] description; @Pointer private final WfsVersion version; private VersionError(Builder builder) { logicalName = builder.logicalName; workstationName = builder.workstationName; appId = builder.appId; description = builder.description; version = builder.version; } public String getLogicalName() { return logicalName; } public String getWorkstationName() { return workstationName; } public String getAppId() { return appId; } public byte[] getDescription() { return description.clone(); } public WfsVersion getVersion() { return version; } @Override public int hashCode() { return new HashCodeBuilder() .append(logicalName) .append(workstationName) .append(appId) .append(description) .append(version) .toHashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof VersionError) { VersionError versionError = (VersionError) obj; return new EqualsBuilder() .append(logicalName, versionError.logicalName) .append(workstationName, versionError.workstationName) .append(appId, versionError.appId) .append(description, versionError.description) .append(version, versionError.version) .isEquals(); } return false; } @Override public String toString() { return new ToStringBuilder(this) .append("logicalName", logicalName) .append("workstationName", workstationName) .append("appId", appId) .append("description", description) .append("version", version) .toString(); } }
Markdown
UTF-8
832
2.59375
3
[]
no_license
--- title: "Anacardiaceae Spondias dulcis" family: "Anacardiaceae" species: "Spondias dulcis" genus: "Spondias" sp1: "dulcis" author1: "Parkinson" rank1: "" sp2: "" author2: "" vernacular: "Kedondong, Great Hog Plum, Golden Apple, Otaheite Apple, Yellow Plum, Jew Plum, Ambrarella" ecology: "Dry or secondary vegetation to 500 m." distribution: "Only known from cultivation, probably arose in tropical Asia." uses: "Fruits are edible, eaten raw or cooked. When green, the fruit is crisp and slightly acidic. Young leaves are also edible as salad or cooked." date: 2019-11-13T09:35:09.310Z --- Small evergreen or deciduous tree 6-20 m tall. Leaves compound, 20-60 cm long, 9-25 leaflets with terminal leaflet. Flowers small, white, inconspicuous in terminal cluster. Fruits 6-9 cm long, ovoid, green turning golden-yellow when ripen.
JavaScript
GB18030
4,601
2.5625
3
[]
no_license
/** * author: zhongting.zy * ʹDracularʾǿjs */ window.onload = function() { //趨ó var width = $(document).width(); //ȥĿ var height = $(document).height(); document.getElementById('canvas').style.width = width + 'px'; document.getElementById('canvas').style.height = height + 'px'; //̶ɫ,չ var colorArray = new Array("#D76565", "#15ACCB", "#feb"); resizeOfBody = function() { //alert('resizeOfBody:' + width); width = $(document).width(); height = $(document).height(); document.getElementById('canvas').style.width = width + 'px'; document.getElementById('canvas').style.height = height + 'px'; } /** * ʾҵӦ * @param value ѡӦõ * @param selectDate ѡ */ showDependOnMe = function(value, selectDate, optType) { var actionUrl = contextPath + "/checkupdepend.do?method=showMeDependGraph"; //var value = $('#appNameSelect').val(); //var selectDate = $('#selectDate').val(); $.getJSON( actionUrl, { opsName: value, selectDate: selectDate, optType: optType }, function(json){ if(json.message == "failure") { clearGraph(); parent.alert("û"); return; } showGraph(json.meDepNodeList); } ); } /** * ʾӦ * @param path ǰ· */ clearGraph = function() { try { $('#canvas').empty(); width = $(document).width(); height = $(document).height(); document.getElementById('canvas').style.width = width + 'px'; document.getElementById('canvas').style.height = height + 'px'; }catch(err) { //alert(err.description); } } /** * */ seperateString = function(str) { var numberOfLine = 10; //ַȴnumberOfLineС var times = Math.floor(str.length / numberOfLine); for(i=0; i<times; i++) { str = str.substring(0, (i+1)*numberOfLine + i) + "\n" + str.substring((i+1)*numberOfLine + i); } return str; } /** * ʾͼ * @param jsonObj */ showGraph = function(jsonArray) { //ͼǰDIVݣֹظ clearGraph(); var g = new Graph(); g.edgeFactory.template.style.directed = true; //ʹüͷ var render = function(r, n) { var color = n.appType == "center" ? colorArray[0] : colorArray[1]; //ͬӦʹɫ var appName = seperateString(n.lable); var set = r.set().push(r.rect(n.point[0]-30, n.point[1]-13, 60, 44).attr({"fill": color, r : "12px", "stroke-width" : n.distance == 0 ? "3px" : "1px" })).push( r.text(n.point[0], n.point[1] + 10, appName)); //set.mouseover(function(){alert(n.lable) }); //ȡӦõʵƣȻһ̨ return set; }; var groupMap ={}; //ӽڵ for(i=0; i < jsonArray.length; i++) { groupMap[jsonArray[i].id] = jsonArray[i]; g.addNode(jsonArray[i].id,{ lable: jsonArray[i].name, appType: jsonArray[i].appType, //һappTyperender //parentId: jsonArray[i].parentId, //һparentIdrender render : render }); } for(i=0; i<jsonArray.length; i++) { var tempArray = jsonArray[i].childIds; if(tempArray.length != 0) { for(j=0; j<tempArray.length; j++) { //ϵӽڵȷ var tempNode = groupMap[tempArray[j]]; if(tempNode.state == "strong") { g.addEdge(jsonArray[i].id, tempArray[j],{ stroke : "#bfa" , fill : "#56f" }); } else { //, {label : ''} //ӱǩͨlabel g.addEdge(jsonArray[i].id, tempArray[j]); } } } } // //var layouter = new Graph.Layout.Ordered(g, topological_sort(g)); var layouter = new Graph.Layout.Spring(g); var renderer = new Graph.Renderer.Raphael('canvas', g, width, height); renderer.draw(); }; //ҳʾ if(opsName != "null" && selectDate != "null") { //ֻдʱ򣬲Žвѯ showDependOnMe(opsName, selectDate, optType); } // var paper = Raphael('canvas', 320, 200); // // Creates circle at x = 50, y = 40, with radius 10 // var circle = paper.circle(50, 40, 10); // // Sets the fill attribute of the circle to red (#f00) // circle.attr("fill", "#f00"); // // Sets the stroke attribute of the circle to white // circle.attr("stroke", "#fff"); // circle.mouseover(function () { // alert('where amazing happens!'); // }); }
Shell
UTF-8
416
2.59375
3
[]
no_license
#!/bin/bash touch /tmp/.rankmirrors rankmirrors -n 5 /etc/pacman.d/mirrorlist > /tmp/.ranked-mirrorlist 2>&1 echo "# Fastest mirrors selected during installation" > /tmp/.tmp-mirrorlist 2>&1 tail -n 5 /tmp/.ranked-mirrorlist >> /tmp/.tmp-mirrorlist 2>&1 cat /tmp/.tmp-mirrorlist /etc/pacman.d/mirrorlist > /tmp/.mirrorlist cp /tmp/.mirrorlist /etc/pacman.d/mirrorlist 2>&1 rm /tmp/.rankmirrors
C++
UTF-8
6,872
2.796875
3
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2012 BMW Car IT GmbH * * 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. */ #include <gtest/gtest.h> #include "capu/os/Thread.h" class ThreadTest : public capu::Runnable { public: static int32_t variable; ThreadTest(int32_t val) { variable = 0; mVal = val; } void run() { //0.1 second delay EXPECT_EQ(capu::CAPU_OK, capu::Thread::Sleep(100)); variable = mVal; } private: int32_t mVal; }; class IncrementerThreadTest : public capu::Runnable { public: static int32_t variable; IncrementerThreadTest() { variable = 0; } void run() { do { variable++; EXPECT_EQ(capu::CAPU_OK, capu::Thread::Sleep(100)); } while (!isCancelRequested()); } }; class ThreadTest2 : public capu::Runnable { public: ThreadTest2() { } void run() { capu::Thread::Sleep(1000); return; } }; class ThreadTestCancel : public capu::Runnable { public: ThreadTestCancel() { } void run() { while (!isCancelRequested()) { capu::Thread::Sleep(10); } } }; int32_t ThreadTest::variable = 0; int32_t IncrementerThreadTest::variable = 0; TEST(Thread, canSetAndGetThreadName) { //CREATE THREAD capu::Thread thread("test name of thread"); EXPECT_STREQ("test name of thread", thread.getName()); } TEST(Thread, startAndJoinTest) { ThreadTest _test(6); ThreadTest2 _test2; //CREATE THREAD capu::Thread* CAPU_thread = new capu::Thread(); CAPU_thread->start(_test); //WAIT UNTIL IT FINISH EXPECT_EQ(capu::CAPU_OK, CAPU_thread->join()); //CHECK THE VALUE CALCULATED IN THREAD EXPECT_EQ(6, ThreadTest::variable); delete CAPU_thread; capu::Thread* CAPU_thread2 = new capu::Thread(); CAPU_thread2->start(_test2); EXPECT_EQ(capu::CAPU_OK, CAPU_thread2->join()); // multiple join is not ok EXPECT_EQ(capu::CAPU_ERROR, CAPU_thread2->join()); delete CAPU_thread2; } TEST(Thread, reuseThread) { ThreadTest runnable1(1); ThreadTest runnable2(42); { capu::Thread thread; EXPECT_EQ(capu::TS_NEW, thread.getState()); EXPECT_EQ(capu::CAPU_OK, thread.start(runnable1)); // start with another runnable should fail until joined EXPECT_NE(capu::CAPU_OK, thread.start(runnable2)); EXPECT_EQ(capu::CAPU_OK, thread.join()); EXPECT_EQ(capu::TS_TERMINATED, thread.getState()); EXPECT_EQ(1, ThreadTest::variable); EXPECT_EQ(capu::CAPU_OK, thread.start(runnable2)); EXPECT_NE(capu::TS_TERMINATED, thread.getState()); } // thread should be joined EXPECT_EQ(42, ThreadTest::variable); } TEST(Thread, startAndCancelTest) { ThreadTestCancel runnable; capu::Thread* thread = new capu::Thread(); thread->start(runnable); thread->cancel(); // test blocks forever if cancel didn't work EXPECT_EQ(capu::CAPU_OK, thread->join()); delete thread; } TEST(Thread, reuseCancelledThread) { IncrementerThreadTest runnable; { capu::Thread thread; EXPECT_EQ(capu::TS_NEW, thread.getState()); EXPECT_EQ(capu::CAPU_OK, thread.start(runnable)); // start with another runnable should fail until joined EXPECT_NE(capu::CAPU_OK, thread.start(runnable)); thread.cancel(); EXPECT_EQ(capu::CAPU_OK, thread.join()); EXPECT_EQ(capu::TS_TERMINATED, thread.getState()); EXPECT_LT(0, IncrementerThreadTest::variable); // should have run at least once until now int32_t previousValue = IncrementerThreadTest::variable; // restart without reset only runs first part of code EXPECT_EQ(capu::CAPU_OK, thread.start(runnable)); EXPECT_EQ(capu::CAPU_OK, thread.join()); EXPECT_EQ(previousValue + 1, IncrementerThreadTest::variable); previousValue = IncrementerThreadTest::variable; // restart with reset EXPECT_EQ(capu::CAPU_OK, thread.start(runnable)); thread.cancel(); EXPECT_EQ(capu::CAPU_OK, thread.join()); EXPECT_LT(previousValue, IncrementerThreadTest::variable); } } TEST(Thread, joinWithoutStartingIsOK) { ThreadTestCancel runnable; capu::Thread* thread = new capu::Thread(); // join without having started EXPECT_EQ(capu::CAPU_ERROR, thread->join()); delete thread; } TEST(Thread, startAndDestructorTest) { int32_t newval = 6; ThreadTest _test(newval); capu::Thread* CAPU_thread = new capu::Thread(); CAPU_thread->start(_test); delete CAPU_thread; EXPECT_EQ(newval, ThreadTest::variable); } TEST(Thread, sleepTest) { int32_t newval = 5; ThreadTest _test(newval); //CREATE THREAD capu::Thread* CAPU_thread = new capu::Thread(); CAPU_thread->start(_test); //WAIT UNTIL IT FINISH EXPECT_EQ(capu::CAPU_OK, CAPU_thread->join()); EXPECT_EQ(newval, ThreadTest::variable); delete CAPU_thread; } TEST(Thread, contextTest) { int32_t newval = 4; ThreadTest _test(newval); { capu::Thread thread; thread.start(_test); } EXPECT_EQ(newval, ThreadTest::variable); } TEST(Thread, getState) { ThreadTestCancel r1; capu::Thread thread; capu::ThreadState state = thread.getState(); EXPECT_EQ(capu::TS_NEW, state); thread.start(r1); state = thread.getState(); EXPECT_NE(capu::TS_TERMINATED, state); thread.cancel(); thread.join(); state = thread.getState(); EXPECT_EQ(capu::TS_TERMINATED, state); } class IdTester : public capu::Runnable { public: capu::uint_t m_id; void run() { capu::Thread::Sleep(500); m_id = capu::Thread::CurrentThreadId(); } }; TEST(Thread, getId) { capu::uint_t id1 = capu::Thread::CurrentThreadId(); IdTester idTester1; IdTester idTester2; capu::Thread t1; t1.start(idTester1); capu::Thread t2; t2.start(idTester2); t1.join(); t2.join(); capu::uint_t id2 = idTester1.m_id; capu::uint_t id3 = idTester2.m_id; EXPECT_NE(id1, id2); EXPECT_NE(id2, id3); EXPECT_NE(id1, id3); } TEST(Thread, cancelWithoutRunnable) { capu::Thread thread; thread.cancel(); // no test as just no crash is expected }
Java
UTF-8
514
2.09375
2
[]
no_license
package starter.trades; import net.serenitybdd.rest.SerenityRest; import net.thucydides.core.annotations.Step; import starter.WebServiceEndPoints; public class RecordNewTrade { @Step("Record a new trade") public void withDetails(String trade) { SerenityRest.given() .contentType("application/json") .header("Content-Type", "application/json") .body(trade) .when() .post(WebServiceEndPoints.TRADE.getUrl()); } }
C++
UTF-8
2,759
3.0625
3
[]
no_license
/* CHANGELOG * Written by Josh Grooms on 20160922 */ #pragma once #include "TypeDefinitions.h" #include "UtilitiesAPI.h" namespace Cyclone { namespace Utilities { template<typename T> class ICollectionIterator; template<typename T> class ICollection { public: /// <summary> Gets the total number of elements present in the collection. </summary> virtual uint Count() const = 0; /// <summary> Gets whether the collection is currently empty. </summary> virtual bool IsEmpty() const { return Count() == 0; } /// <summary> Destroys any resources that are specially allocated by the collection. </summary> virtual ~ICollection() { } /** OPERATORS **/ //virtual Iterator begin() = 0; //virtual Iterator end() = 0; /// <summary> Performs linear indexing of the elements of an array-like collection. </summary> /// <returns> A constant reference to the data element that resides at the inputted array index. </returns> /// <param name="idx"> The numeric index of the desired element within the collection. </param> virtual const T& operator ()(uint index) const = 0; protected: struct Iterator { public: /** PROPERTIES **/ virtual uint Index() const { return _index; } /** DESTRUCTOR **/ Iterator(uint index, ICollection<T>* collection) : _index(index), Collection(collection) { } virtual ~Iterator() { } /** OPERATORS **/ virtual const T& operator *() const { return (*Collection)(Index()); } virtual Iterator& operator ++() { _index++; return *this; } virtual Iterator& operator ++(int) { return operator ++(); } virtual bool operator ==(const Iterator& other) const { return (Index() == other.Index()) && (Collection == other.Collection); } virtual bool operator !=(const Iterator& other) const { return !operator ==(other); } private: uint _index; ICollection<T>* Collection; }; }; } }
Python
UTF-8
457
3.875
4
[]
no_license
# file handling # opening file for appending f = open('demofile.txt','a') # writing in the file f.write('what is your name?') #closing the file f.close() # writing in a file fp2 = open('demofile3.txt','w') fp2.write('Now the file has more content!') # open and read the file after the appending fp2.write('what up') fp2.close() # check if file exist if os.path.exists('demofile3.txt'): print('it exists') else: print('it doesn not exist')
Java
UTF-8
421
2.625
3
[]
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 com.samjin.JavaFeature; /** * * @author Sam */ public class Son2 extends Father { Son2(int x) { super(x); } public void sing(){ System.out.println( "Son is singing"); } }
Java
UTF-8
1,567
2.25
2
[ "Apache-2.0" ]
permissive
package com.dyhpoon.fodex.fodexView; import android.content.Context; import android.database.Cursor; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.dyhpoon.fodex.R; import com.dyhpoon.fodex.data.actual.FodexContract; /** * Created by darrenpoon on 8/3/15. */ public class SearchViewCursorAdapter extends CursorAdapter { private String mAppendedString; public SearchViewCursorAdapter(Context context, Cursor c, String appendedString) { super(context, c, true); mAppendedString = appendedString; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.list_item_search, parent, false); view.setTag(new SearchViewHolder(view)); return view; } @Override public void bindView(View view, Context context, Cursor cursor) { SearchViewHolder holder = (SearchViewHolder) view.getTag(); String suggestion = mAppendedString + " " + cursor.getString(cursor.getColumnIndex(FodexContract.TagEntry.COLUMN_TAG_NAME)); holder.textview.setText(suggestion); } private class SearchViewHolder { public TextView textview; public SearchViewHolder(View view) { textview = (TextView) view.findViewById(R.id.text_view); } } }
Python
UTF-8
218
2.859375
3
[]
no_license
#! /usr/bin/env python def public_government(str_arg): point(str_arg) print('other_thing_and_year') def point(str_arg): print(str_arg) if __name__ == '__main__': public_government('woman_or_place')
C++
UTF-8
747
2.828125
3
[]
no_license
#include<stdio.h> #include<conio.h> #include<alloc.h> int main() { clrscr(); int *pp,n=10,i,j,*qq; pp=(int *)malloc(n*sizeof(int)); qq=(int *)calloc(10,sizeof(int)); n=0; for(i=0;i<10;i++) { scanf("%d",(pp+i)); } for(i=0;i<10;i++) { scanf("%d",(qq+i)); } printf("this is loops"); for(i=0;i<9;i++) { for(j=i+1;j<10;j++) { if(*(pp+i)<*(pp+j)) { n=*(pp+i); *(pp+i)=*(pp+j); *(pp+j)=n; } } } for(i=0;i<9;i++) { for(j=i+1;j<10;j++) { if(*(qq+i)<*(qq+j)) { n=*(qq+i); *(qq+i)=*(qq+j); *(qq+j)=n; } } } printf("this is the lops"); for(i=0;i<10;i++) { printf("%d\n",*(pp+i)); } free(pp); for(i=0;i<10;i++) { printf("%d\n",*(qq+i)); } free(qq); return 0; }
Python
UTF-8
390
3.140625
3
[]
no_license
import math import numpy as np import matplotlib.patches as patches class Marker(object): def __init__(self, x, y): self.x = x self.y = y def intensity_at(self, x, y): return np.array([abs(self.x - x), abs(self.y - y)]) def draw(self, ax): circle = patches.Circle((self.x, self.y), 0.1, linewidth=1, color='g') ax.add_patch(circle)
Java
UTF-8
16,315
1.703125
2
[]
no_license
package com.lfk.drawapictiure.Activity; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Bundle; import android.os.Message; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.SpannableStringBuilder; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import com.lfk.drawapictiure.Datebase.SQLHelper; import com.lfk.drawapictiure.Info.UserInfo; import com.lfk.drawapictiure.R; import com.lfk.drawapictiure.Tools.PdfMaker; import com.lfk.drawapictiure.Tools.PicUtils; import com.lfk.drawapictiure.Tools.SPUtils; import com.lfk.drawapictiure.View.MarkDown.MDReader; import com.lfk.drawapictiure.View.ZoomTextView; import com.lowagie.text.DocumentException; import com.mingle.entity.MenuEntity; import com.mingle.sweetpick.DimEffect; import com.mingle.sweetpick.RecyclerViewDelegate; import com.mingle.sweetpick.SweetSheet; import com.orhanobut.logger.Logger; import com.readystatesoftware.systembartint.SystemBarTintManager; import com.rengwuxian.materialedittext.MaterialEditText; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class NoteActivity extends AppCompatActivity implements View.OnClickListener { private MaterialEditText editText; private static boolean THEFIRSTTIME = false; private static SQLiteDatabase database; private static String oldstring; private ZoomTextView mMarkDownView; private MDReader markdown = null; private boolean MARKDOWN = false; private SweetSheet mSweetSheet; private ScrollView mRootView; private ProgressDialog progressDialog = null; private boolean firstInto = true; private Snackbar snackbar; private Toolbar toolbar; private SpannableStringBuilder sb = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_note); SystemBarTintManager tintManager = new SystemBarTintManager(this); tintManager.setStatusBarTintEnabled(true); tintManager.setNavigationBarTintEnabled(true); tintManager.setTintColor(getResources().getColor(R.color.darkblue)); toolbar = (Toolbar) findViewById(R.id.note_toolbar); toolbar.setTitle(""); String build = getIntent().getStringExtra("build"); if (build != null) { ((TextView) findViewById(R.id.note_cre)).setText(build); THEFIRSTTIME = true; } else { THEFIRSTTIME = false; String title = getIntent().getStringExtra("timeMin"); String subtitle = getIntent().getStringExtra("time"); if (title != null || subtitle != null) { ((TextView) findViewById(R.id.note_first)).setText(title); ((TextView) findViewById(R.id.note_second)).setText(subtitle); } } setSupportActionBar(toolbar); editText = (MaterialEditText) findViewById(R.id.note_edit); findViewById(R.id.note_markdown).setOnClickListener(this); findViewById(R.id.note_menu).setOnClickListener(this); mMarkDownView = (ZoomTextView) findViewById(R.id.markdown); mMarkDownView.setVisibility(View.INVISIBLE); mRootView = (ScrollView) findViewById(R.id.root_view); findViewById(R.id.note_back_button).setOnClickListener(this); mRootView.setVisibility(View.INVISIBLE); mMarkDownView.setVisibility(View.INVISIBLE); oldstring = getIntent().getStringExtra("content"); if (oldstring != null) { editText.setText(oldstring); } initSweetSheet(); database = SQLiteDatabase.openOrCreateDatabase(SQLHelper.NAME, null); } @Override protected void onResume() { super.onResume(); // 第一次进入 首次编辑 字数小于1000 if (firstInto && !THEFIRSTTIME && editText.getText().length() < 1000) { firstInto = false; // markDown(); markdown = new MDReader(editText.getText().toString()); new Thread(() -> { sb = markdown.getFormattedContent(); }).start(); } } /** * 菜单 */ private void initSweetSheet() { ArrayList<MenuEntity> menuEntities = new ArrayList<>(); MenuEntity share_menuEntity = new MenuEntity("分享便签", R.drawable.iconfont_share, "share"); MenuEntity text_menuEntity = new MenuEntity("保存为文本", R.drawable.iconfont_txt, "txt"); MenuEntity jpg_menuEntity = new MenuEntity("保存为图片", R.drawable.iconfont_jpg, "pic"); MenuEntity md_menuEntity = new MenuEntity("保存为MarkDown文件", R.drawable.iconfont_md, "md"); MenuEntity pdf_menuEntity = new MenuEntity("导出为pdf文件", R.drawable.iconfont_pdf, "pdf"); menuEntities.add(text_menuEntity); menuEntities.add(jpg_menuEntity); menuEntities.add(md_menuEntity); menuEntities.add(pdf_menuEntity); menuEntities.add(share_menuEntity); mSweetSheet = new SweetSheet((RelativeLayout) findViewById(R.id.note_relative)); mSweetSheet.setMenuList(menuEntities); mSweetSheet.setBackgroundEffect(new DimEffect(8)); mSweetSheet.setDelegate(new RecyclerViewDelegate(true)); mSweetSheet.setOnMenuItemClickListener((position, menuEntity) -> { // 根据返回值, true 会关闭 SweetSheet ,false 则不会. switch (menuEntity.id) { case "share": Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, editText.getText().toString()); sendIntent.setType("text/plain"); startActivity(Intent.createChooser(sendIntent, "发送便签")); break; case "txt": saveAsRawContent(); break; case "pic": saveAsBitmap(); break; case "md": saveAsMarkdown(); break; case "pdf": saveAsPdf(); break; } return true; }); } private void snackMake(View view, String text) { snackbar = Snackbar.make(view, text, Snackbar.LENGTH_LONG); snackbar.setActionTextColor(Color.WHITE); Snackbar.SnackbarLayout ve = (Snackbar.SnackbarLayout) snackbar.getView(); ve.setBackgroundColor(getResources().getColor(R.color.blue)); snackbar.show(); } /** * 导出(不包含格式) */ public void saveAsRawContent() { if (!UserInfo.TextPath.exists()) { UserInfo.TextPath.mkdirs(); } if (markdown == null) markdown = new MDReader(editText.getText().toString()); String filepath = UserInfo.TextPath.getPath() + "/" + System.currentTimeMillis() + ".txt"; try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filepath), "UTF-8")); writer.write(markdown.getRawContent()); writer.close(); } catch (IOException e) { e.printStackTrace(); } snackMake(toolbar, "成功保存到:" + filepath); // Toast.makeText(this, "成功保存到:" + filepath, Toast.LENGTH_LONG).show(); } /** * 导出(pdf) */ public void saveAsPdf() { if (!UserInfo.TextPath.exists()) { UserInfo.TextPath.mkdirs(); } String filepath = UserInfo.TextPath.getPath() + "/" + System.currentTimeMillis() + ".pdf"; if (!MARKDOWN) { markDown(); } new Thread(() -> { try { PdfMaker.makeIt(NoteActivity.this, filepath, PicUtils.createBitmap(this, mRootView)); } catch (DocumentException | IOException e) { e.printStackTrace(); } }).start(); snackMake(toolbar, "成功保存到:" + filepath); // Toast.makeText(this, "成功保存到:" + filepath, Toast.LENGTH_LONG).show(); } /** * 导出(图片,大小为至少一个屏幕大小) */ public void saveAsBitmap() { if (!UserInfo.TextPath.exists()) { UserInfo.TextPath.mkdirs(); } if (!MARKDOWN) { markDown(); } String filepath = UserInfo.TextPath.getPath() + "/" + System.currentTimeMillis() + ".jpg"; if (MARKDOWN) { try { FileOutputStream stream = new FileOutputStream(filepath); Bitmap bitmap = PicUtils.createBitmap(this, mRootView); if (bitmap != null) { bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); // Toast.makeText(this, "成功保存到:" + filepath, Toast.LENGTH_LONG).show(); snackMake(toolbar, "成功保存到:" + filepath); } stream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 导出MarkDown文件 */ public void saveAsMarkdown() { if (!UserInfo.TextPath.exists()) { UserInfo.TextPath.mkdirs(); } if (markdown == null) markdown = new MDReader(editText.getText().toString()); String filepath = UserInfo.TextPath.getPath() + "/" + System.currentTimeMillis() + ".md"; try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filepath), "UTF-8")); writer.write(markdown.getContent()); writer.close(); } catch (IOException e) { e.printStackTrace(); } snackMake(toolbar, "成功保存到:" + filepath); // Toast.makeText(this, "成功保存到:" + filepath, Toast.LENGTH_LONG).show(); } /** * 结束Activity,包含处理数据库,不包含上传 */ private void finishTheActivity() { final ContentValues values = new ContentValues(); final Date d = new Date(); final java.text.DateFormat format = new SimpleDateFormat("dd/MM/yyyy"); final java.text.DateFormat format_time = new SimpleDateFormat("HH:mm"); if (!editText.getText().toString().equals("")) { if (THEFIRSTTIME) { long name_time = System.currentTimeMillis(); values.put("_name", name_time + ""); values.put("_time", format_time.format(d)); values.put("_pic", format.format(d)); values.put("_content", editText.getText().toString()); values.put("_username", (String) SPUtils.get(NoteActivity.this, "username", UserInfo.PUBLIC_ID)); values.put("_type", 1); database.insert("note", null, values); database.close(); // Logger.d("save tent"); getResultIntent(editText.getText().toString(), name_time + "", format.format(d)); } else { if (oldstring.length() != editText.getText().toString().length()) { database.execSQL("update note set _time = " + "\"" + format_time.format(d) + "\"" + ", _content=" + "\"" + editText.getText().toString() + "\"" + ", _pic = " + "\"" + format.format(d) + "\"" + " where _name =" + "\"" + getIntent().getStringExtra("name") + "\"" + " and _username=" + "\"" + SPUtils.get(NoteActivity.this, "username", UserInfo.PUBLIC_ID) + "\""); // Log.e("update note", getIntent().getStringExtra("name")); database.close(); getResultIntent(editText.getText().toString(), getIntent().getStringExtra("name"), format.format(d)); } } } finish(); } private void getResultIntent(String content, String name, String pic) { Intent intent = new Intent(NoteActivity.this, MenuActivity.class); intent.putExtra("content", content); intent.putExtra("cache", pic); intent.putExtra("name", name); intent.putExtra("type", 1); setResult(RESULT_OK, intent); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.note_back_button: if (MARKDOWN) { markDown(); mMarkDownView.dismiss(); } else { finishTheActivity(); } break; case R.id.note_menu: mMarkDownView.dismiss(); if (mSweetSheet.isShow()) { mSweetSheet.dismiss(); } mSweetSheet.toggle(); break; case R.id.note_markdown: markDown(); break; } } /** * 切换MarkDown状态 */ private void markDown() { progressDialog = ProgressDialog.show(this, "请等待", "正在转码...", true); if (MARKDOWN) { markdown = new MDReader(editText.getText().toString()); mMarkDownView.setVisibility(View.INVISIBLE); mRootView.setVisibility(View.INVISIBLE); editText.setVisibility(View.VISIBLE); MARKDOWN = false; mMarkDownView.dismiss(); ((ImageView) findViewById(R.id.note_markdown)). setImageDrawable(getResources().getDrawable(R.drawable.icon_markdown)); progressDialog.dismiss(); } else { markdown = new MDReader(editText.getText().toString()); if (sb != null) { mMarkDownView.setTextKeepState(sb, TextView.BufferType.SPANNABLE); sb = null; } else { // new Thread(() -> { sb = markdown.getFormattedContent(); mMarkDownView.setTextKeepState(sb, TextView.BufferType.SPANNABLE); // }); } progressDialog.dismiss(); editText.setVisibility(View.INVISIBLE); mRootView.setVisibility(View.VISIBLE); mMarkDownView.setVisibility(View.VISIBLE); oldstring = editText.getText().toString(); ((ImageView) findViewById(R.id.note_markdown)). setImageDrawable(getResources().getDrawable(R.drawable.icon_markdown1)); MARKDOWN = true; } } private android.os.Handler handler = new android.os.Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); // switch (msg.what){ // } } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mSweetSheet.isShow()) { mSweetSheet.dismiss(); } else { if (MARKDOWN) { markDown(); mMarkDownView.dismiss(); } else { finishTheActivity(); } } break; } return true; } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { mMarkDownView.dismiss(); Logger.e("接受点击"); } return true; } }
Python
UTF-8
2,534
3.03125
3
[]
no_license
import numpy as np import pandas as pd def f(x, y): # optimization function return((1 - x)**2) + (100 * ((y - x**2)**2)) def c(x, y):#Inequality Contraints c1 = max(0, ((x * x) + (x - y) + 1.5)) c2 = max(0, (10 - (x * y))) return (c1,c2) def constraint(x, y):#Fitness function with constraints penalty fit = f(x, y) + 15*sum(c(x, y)) return(fit) nBit = 10 XU,XL,YU,YL = 1, 0, 13, 0 popln = 20 ;Pc = 0.7 ; Pm = 1/popln act_bit = int(nBit/2) def CreatePopulation(popln, nBit): popl_binary = [] for i in range(popln): binr1 = np.random.choice([0, 1], size=nBit) popl_binary.append(binr1) return popl_binary Init_popl = pd.DataFrame(CreatePopulation(popln, nBit)) for k in range(50): X, Y = [], [] #value of X fit = [] #fitness for i in range(popln): xx,yy = [], [] for j in range(act_bit): xx.append(Init_popl.iloc[i][j] * (2 ** j)) yy.append(Init_popl.iloc[i][act_bit+j] * (2 ** j)) XX = XL +( (XU - XL) / ((2**act_bit)-1) ) * sum(xx) YY = YL +( (YU - YL) / ((2**act_bit)-1) ) * sum(yy) X.append(XX);Y.append(YY) fit.append(constraint(XX,YY)) a1 = fit.index(min(fit)) print("X = {}".format(X[a1])) print("Y = {}".format(Y[a1])) #Tournament selection tourn_popl = [] for j in range(popln): ran1, ran2 = np.random.randint(0,popln-1,2) #Generating random int between 0 to 9 of size 2 n = [fit[ran1],fit[ran2]] if n[0] < n[1]: tourn_popl.append(list(Init_popl.iloc[ran1])) else: tourn_popl.append(list(Init_popl.iloc[ran2])) tourn_popl = pd.DataFrame(tourn_popl) #Crossover cross_popl = [] for i in range(int(popln/2)): ran1, ran2 = np.random.randint(0,popln-1,2) crX1, crX2 = list(tourn_popl.iloc[ran1]), list(tourn_popl.iloc[ran2]) for j in range(nBit): rn = np.random.uniform(0,1) if rn < Pc: break crossX1, crossX2 = crX1[0:j] + crX2[j:], crX2[0:j] + crX1[j:] cross_popl.append(crossX1), cross_popl.append(crossX2) cross_popl = pd.DataFrame(cross_popl) #Mutation for i in range(popln): mute = cross_popl.loc[i] for j in range(nBit): rnd_no = np.random.uniform(0,1) if rnd_no < Pm: if mute[j] == 0: mute[j] = 1;break else: mute[j] = 0;break Init_popl = cross_popl
Java
UTF-8
1,372
3.765625
4
[]
no_license
public class RGB { public short red; public short green; public short blue; public RGB() { red = 0; green = 0; blue = 0; } public RGB(short red, short green, short blue) { this.red = red; this.green = green; this.blue = blue; } public short getColor(String color) { if (color.equals("red")) { return red; } else if (color.equals("green")) { return green; } else { return blue; } } public short getRed() { return red; } public short getGreen() { return green; } public short getBlue() { return blue; } public String toString() { return "(" + getRed() + "," + getGreen() + "," +getBlue() + ")"; } public static void main(String[] args) { RGB rgb = new RGB(); System.out.println(rgb.red + " " + rgb.green + " " + rgb.blue); short red, green, blue; red = 100; green = 200; blue = 240; RGB rgb2 = new RGB(red, green, blue); System.out.println(rgb2.red + " " + rgb2.green + " " + rgb2.blue); RGB[] rgb3 = new RGB[2]; rgb3[0] = rgb; rgb3[1] = rgb2; for (RGB color : rgb3) { System.out.println(color.red + " " + color.green + " " + color.blue); } System.out.println("rgb2's green is " + rgb2.getColor("green")); try { System.out.println(rgb3[-1].red); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(rgb3[0].red); } System.out.println(rgb2); } }
PHP
UTF-8
894
2.515625
3
[]
no_license
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; /** * Class FinancialDetail. * * @package namespace App\Models; */ class FinancialDetail extends Model { use SoftDeletes; protected $table = 'financial_detail'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'financial_id', 'money', 'title', 'projects_id', 'reason', 'repayment_date', 'projects_condition', 'limit_price', 'is_control' ]; /** * 不能被批量赋值的属性 * * @var array */ protected $guarded = [ "id" ]; protected $hidden = [ 'deleted_at' ]; public function getProjectsConditionAttribute($value) { return json_decode($value,true); } }
Python
UTF-8
174
2.75
3
[]
no_license
# Create loglog plot of histogram data in xy style - python matplotlib x = sorted( degree_frequencies.keys( ) ) y = [ degree_frequencies[ k ] for k in x ] plt.loglog( x, y )
Python
UTF-8
115
3.25
3
[]
no_license
def increment(i): i += 1 # switch v = i # switch return v a = 0 b = increment(a) print(a) print(b)
PHP
UTF-8
991
2.546875
3
[]
no_license
<?php $servername = "localhost"; $username = "monitor"; $password = "1234"; $dbname = "srDB"; //create DB connection $conn = new mysqli($servername,$username,$password,$dbname); //check DB connection if($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //Fetch data to DB $sql = "SELECT TIMESTAMP(dt) AS 'time'," . " srVAC AS 'srVAC', srVBat AS 'srVBat', srIBat AS 'srIBat', srILoad AS 'srILoad'," . " sr6V5 AS 'sr6V5', sr12V AS 'sr12V', sr13V5 AS 'sr13V5', sr19V5 AS 'sr19V5'," . " sr24V AS 'sr24V', sr48V_A AS 'sr48V_A', sr48V_B AS 'sr48V_B', srTemp AS 'srTemp'" . " FROM srHistory" . " ORDER BY time DESC LIMIT 1000"; $arr = array(); if ($result = mysqli_query($conn, $sql)) { /* fetch associative array */ while ($row = mysqli_fetch_assoc($result)) { array_push($arr, $row ); } /* free result set */ mysqli_free_result($result); } echo json_encode($arr); $conn->close(); ?>
Java
UTF-8
2,562
2.5625
3
[ "Apache-2.0" ]
permissive
package top.caoxuan.tortoiseserver.websocket; import com.alibaba.fastjson.JSON; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import top.caoxuan.tortoiseserver.entity.Message; import java.util.ArrayList; import java.util.List; /** * @author CX * @date 2020/10/21 11:14 */ public class WebSocketHandler extends TextWebSocketHandler { private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class); public static final List<WebSocketSession> SESSION_LIST = new ArrayList<>(); @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { super.afterConnectionEstablished(session); SESSION_LIST.add(session); } @Override protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception { super.handleTextMessage(session, textMessage); logger.info(textMessage.getPayload()); String payload = textMessage.getPayload(); Message message; try { message = JSON.parseObject(payload, Message.class); } catch (Exception e) { e.printStackTrace(); logger.error("消息格式转换失败"); session.close(CloseStatus.NOT_ACCEPTABLE); return; } switch (message.getType()) { case Message.Type.TEXT: for (WebSocketSession webSocketSession : SESSION_LIST) { if (webSocketSession != session) { webSocketSession.sendMessage(new TextMessage(payload)); logger.info("转发成功!messageId=" + message.getId()); } } break; case Message.Type.IMG: logger.warn("暂不支持图片"); break; default: session.close(CloseStatus.POLICY_VIOLATION); logger.warn("未知的消息类型:" + message.getType()); break; } } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { super.afterConnectionClosed(session, status); SESSION_LIST.remove(session); logger.warn(session.getId() + "已断开连接"); } }
JavaScript
UTF-8
2,138
3.515625
4
[]
no_license
function MilitaryResource(type, maxHealth, maxDistance) { this.type = type; this.health = health = maxHealth; this.maxHealth = maxHealth; this.distance = distance = maxDistance; this.maxDistance = maxDistance; } MilitaryResource.prototype.isReadyToMove = function() { return this.distance > 0; }; MilitaryResource.prototype.isReadyToFight = function() { return this.health > 0; }; MilitaryResource.prototype.restore = function() { this.health = this.maxHealth; this.distance = this.maxDistance; return this; }; MilitaryResource.prototype.clone = function () { return this; }; var warrior = new MilitaryResource('warrior', 200, 150); var archer = new MilitaryResource('archer', 150, 100) // console.log(warrior.isReadyToMove()); // console.log(warrior.clone()); // console.log(archer.clone()); function Squad(defaultResources) { this.squad = []; if (defaultResources) this.combineResources(defaultResources); } Squad.prototype.isReadyToMove = function() { return this.squad.every(function(self) { return self.distance > 0; }); }; Squad.prototype.isReadyToFight = function() { return this.squad.every(function(self) { return self.health > 0; }); }; Squad.prototype.restore = function() { return this.squad.map(function(self){ self.health = self.maxHealth; self.distance = self.maxDistance; return self; }); }; Squad.prototype.getReadyToMoveResources = function() { }; Squad.prototype.combineResources = function(defaultResources) { return this.squad = this.squad.concat(defaultResources); }; Squad.prototype.cloneResource = function() { return this.squad.slice(); }; var squad = new Squad(); squad.combineResources([warrior, archer]) console.log(squad.squad); console.log(squad.isReadyToMove()); console.log(squad.isReadyToFight()); console.log(squad.restore()); console.log(squad.cloneResource()); console.log(squad.getReadyToMoveResources());
Swift
UTF-8
3,691
2.71875
3
[]
no_license
// // L5ViewController.swift // LearnOpenGL // // Created by xurunkang on 2019/7/10. // import Foundation import GLKit class L5ViewController: BaseViewController { // 注意: effect 的初始化需要在设置 EAGLContext.setCurrent 后 private lazy var effect: L5BaseEffect = { let effect = L5BaseEffect("l5vertex.vsh", "l5fragment.fsh") effect.setTexture("L5.JPG") return effect }() // vertex buffer object private var VBO: GLuint = 0 // 顶点数组 private let vertices: [L5Vertex] = [ L5Vertex(position: (-1, -1, 0), color: (1, 0, 0, 1), texCoord: (0, 0)), L5Vertex(position: (1, -1, 0), color: (0, 1, 0, 1), texCoord: (1, 0)), L5Vertex(position: (1, 1, 0), color: (0, 0, 1, 1), texCoord: (1, 1)), L5Vertex(position: (1, 1, 0), color: (0, 0, 1, 1), texCoord: (1, 1)), L5Vertex(position: (-1, 1, 0), color: (0, 1, 0, 1), texCoord: (0, 1)), L5Vertex(position: (-1, -1, 0), color: (1, 0, 0, 1), texCoord: (0, 0)) ] override func viewDidLoad() { super.viewDidLoad() setupBuffer() setupVertexAttributes() } override func glkView(_ view: GLKView, drawIn rect: CGRect) { glClearColor(1, 1, 1, 1) glClear(GLenum(GL_COLOR_BUFFER_BIT)) effect.prepareToDraw() // 传入变换矩阵 effect.modelMatrix = modelMatrix() glDrawArrays(GLenum(GL_TRIANGLES), 0, GLsizei(vertices.count)) } } private extension L5ViewController { private func modelMatrix() -> GLKMatrix4 { var modelMatrix = GLKMatrix4Identity modelMatrix = GLKMatrix4Translate(modelMatrix, 0.5, -0.5, 0) // 平移 modelMatrix = GLKMatrix4Scale(modelMatrix, 0.5, 0.5, 1) // 缩放 let radians = linearRadians() modelMatrix = GLKMatrix4Rotate(modelMatrix, radians, 0, 1, 0) // 旋转, 沿 Y 轴旋转 45° return modelMatrix } private func linearRadians() -> Float { return sinf(Float(CACurrentMediaTime())/2.0) * Float.pi } private func setupBuffer() { // 再次三部曲 glGenBuffers(1, &VBO) glBindBuffer(GLenum(GL_ARRAY_BUFFER), VBO) glBufferData( GLenum(GL_ARRAY_BUFFER), vertices.elementsSize, vertices, GLenum(GL_STATIC_DRAW) ) } private func setupVertexAttributes() { // 这里需要注意,因为我们已经切换为自定义的 BaseEffect,所以对应的顶点属性指也记得要修改 glEnableVertexAttribArray(VertexAttrib.position.rawValue) // 传输坐标 glVertexAttribPointer( VertexAttrib.position.rawValue, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<L5Vertex>.stride), UnsafeRawPointer(bitPattern: 0) ) glEnableVertexAttribArray(VertexAttrib.color.rawValue) // 传输颜色 glVertexAttribPointer( VertexAttrib.color.rawValue, 4, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<L5Vertex>.stride), UnsafeRawPointer(bitPattern: 3 * MemoryLayout<GLfloat>.size) ) glEnableVertexAttribArray(VertexAttrib.textureCoordinate.rawValue) // 传输纹理坐标 glVertexAttribPointer( VertexAttrib.textureCoordinate.rawValue, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(MemoryLayout<L5Vertex>.stride), UnsafeRawPointer(bitPattern: (3 + 4) * MemoryLayout<GLfloat>.size) ) } }
C++
UTF-8
2,699
2.65625
3
[]
no_license
#include <iostream> #include <csignal> #include "LOG.h" #include "Device.h" #include "ProcessImage.h" #include <getopt.h> Device device; ProcessImage processImage; //static const char short_options[] = "c:d:f:F:hmo:rs:uz"; static const char short_options[] = "d:g:s:h"; static const struct option long_options[] = { {"device", required_argument, NULL, 'd'}, {"gain", required_argument, NULL, 'g'}, {"shutter", required_argument, NULL, 's'}, {"help", no_argument, NULL, 'h'}, {0, 0, 0, 0} }; std::string devName = "/dev/video0"; int gain = 50; int shutter = 5000; void usage(int argc, char **argv) { std::cout << "Usage: " << argv[0] << "[options]\n\n" "Options:\n" "-d | --device name \tVideo device name (default: " << devName << ")\n" "-g | --gain value \tSet gain (default: " << gain << ", min: 1, max 480)\n" "-s | --shutter value \tSet shutter (default: " << shutter << ", min: 29, max 15110711)\n" "-h | --help \t\tPrint help\n"; } void getopt(int argc, char **argv) { for (;;) { int index; int c; c = getopt_long(argc, argv, short_options, long_options, &index); if (-1 == c) break; switch (c) { case 0: /* getopt_long() flag */ break; case 'd': devName = optarg; break; case 'g': gain = atoi(optarg); break; case 's': shutter = atoi(optarg); break; case 'h': usage(argc, argv); exit(EXIT_SUCCESS); default: usage(argc, argv); exit(EXIT_FAILURE); } } } void SigintHandler(int dummy) { LOG_INFO("Stop device"); device.Stop(); exit(EXIT_SUCCESS); } int main(int argc, char **argv) { LOG_INFO("Start device"); signal(SIGINT, SigintHandler); getopt(argc, argv); device.Init(devName); processImage.Init("Imx296"); device.SetCallProcessImage(processImage.Processing); device.SetCallDrawImage(processImage.DrawImage); device.SetGain(gain); device.SetShutter(shutter); device.Start(); device.Join(); return 0; }
Java
UTF-8
1,213
2.046875
2
[]
no_license
package com.hsbc.group.iip.x.leavedao.dao.impl; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import com.hsbc.group.iip.x.common.model.PersonalAvailableLeave; import com.hsbc.group.iip.x.leavedao.dao.LeaveDao; import com.hsbc.group.iip.x.leavedao.model.Leave; @Service public class LeaveDaoImpl implements LeaveDao { @Override public Map<String, PersonalAvailableLeave> getAvailableLeaveByUserId(String csStaffId) { if(StringUtils.isEmpty(csStaffId)){ return null; } Map<String, PersonalAvailableLeave> availableLeaves = new HashMap<String, PersonalAvailableLeave>(); PersonalAvailableLeave nLeave = new PersonalAvailableLeave(); nLeave.setLeaveType("NLeave"); nLeave.setAvialableTime("40"); nLeave.setStaffId(csStaffId); availableLeaves.put("NLeave", nLeave); PersonalAvailableLeave tLeave = new PersonalAvailableLeave(); tLeave.setLeaveType("TLeave"); tLeave.setAvialableTime("24"); tLeave.setStaffId(csStaffId); availableLeaves.put("TLeave", tLeave); return availableLeaves; } @Override public void saveLeave(Leave leave) { // TODO Auto-generated method stub } }
TypeScript
UTF-8
565
2.953125
3
[]
no_license
import { LikesAction, SET_LIKES, SET_DISLIKES } from 'store/actions/like'; export type Preference = { likes: number[]; dislikes: number[]; }; const initialState: Preference = { likes: [], dislikes: [], }; const likesReducer = (state = initialState, action: LikesAction) => { switch (action.type) { case SET_LIKES: return { ...state, likes: [...state.likes, action.payload] }; case SET_DISLIKES: return { ...state, dislikes: [...state.dislikes, action.payload] }; default: return state; } }; export default likesReducer;
C++
UTF-8
1,686
3.53125
4
[]
no_license
#ifndef MEMORYPOOL_H #define MEMORYPOOL_H #include <sys/types.h> #include <string> #define POOLSIZE 32 using namespace std; //Linked List to store next memory location struct heapList { heapList* next; }; // A Custom memory manager, that improves performance by working on preallocated chunks of memory // rather an incremental allocations to the heap. Memory pool size will keep increasing as it becomes required. class MemoryPool { private: void expandPool(size_t size = 0); void cleanUp(); heapList* headNode; public: MemoryPool(){ headNode = nullptr; } ~MemoryPool(){ cleanUp(); } void* allocate(size_t); void free(void*); }; void* MemoryPool::allocate(size_t size) { if(headNode == nullptr) expandPool(size); heapList* head = headNode; headNode = head->next; return head; } void MemoryPool::free(void *deleted) { heapList* head = static_cast<heapList*> (deleted); head->next = headNode; headNode = head; } void MemoryPool::expandPool(size_t size) { size_t sizeofHeapList = sizeof(heapList*); size_t new_size = (size > sizeofHeapList) ? size : sizeofHeapList; heapList* head = reinterpret_cast<heapList*> (new char[new_size]); headNode = head; for(int i = 0; i < POOLSIZE; i++){ head->next = reinterpret_cast<heapList*>(new char[new_size]); head = head->next; } head->next = nullptr; } void MemoryPool::cleanUp() { heapList* nextPtr = headNode; for(; nextPtr; nextPtr = headNode){ headNode = headNode->next; delete[] nextPtr; } } #endif // MEMORYPOOL_H
C
UTF-8
1,701
3
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "pokemon.h" #include "gotoxy.h" #include "menu.h" void inic_HPBAR(char* ps, int dim); void inicMascara(char* mascara, int dim); int calcularPorcHP(int psActual, int psTotal, int dimArreglo); void printHPBAR(char* HPBAR, int posFinal); void printHPMascara(char* mascara, int dim, int posArran); void HPBAR(int psActual, int psTotal, char* ps, char* mascara, int dimension); int main() { char mascara[20]; char ps[20]; inicMascara(mascara, 20); inic_HPBAR(ps, 20); int psActual = 163; int psTotal = 325; HPBAR(psActual, psTotal, ps, mascara, 20); return 0; } void inicMascara(char* mascara, int dim){ for(int i = 0; i < dim; i++){ mascara[i] = 0; } } void inic_HPBAR(char* ps, int dim){ for(int i = 0; i < dim; i++){ ps[i] = 35; } } int calcularPorcHP(int psActual, int psTotal, int dimArreglo){ int parteEntera; parteEntera = (psActual * dimArreglo) / psTotal; return parteEntera; } void printHPBAR(char* HPBAR, int posFinal){ for(int i = 0; i < posFinal; i++){ printf("%c", HPBAR[i]); } } void printHPMascara(char* mascara, int dim, int posArran){ for(int i = posArran; i < dim; i++){ printf("%c", mascara[i]); } } void HPBAR(int psActual, int psTotal, char* ps, char* mascara, int dimension){ int dimHPBAR; int porcentaje; porcentaje = calcularPorcHP(psActual, psTotal, 100); dimHPBAR = calcularPorcHP(psActual, psTotal, dimension); printf("["); printHPBAR(ps, dimHPBAR); printHPMascara(mascara, dimension, dimHPBAR); printf("]\n"); printf("%4d/%4d %d%%", psActual, psTotal, porcentaje); }
C#
UTF-8
490
3.109375
3
[]
no_license
using System; using System.Collections.Generic; namespace LibraryApp { public class User : IEquatable<User> { public string Name { get;private set; } public User (string name) { if (!string.IsNullOrWhiteSpace(name)) Name = name; } public bool Equals (User other) { if (this.Name == other.Name) return true; else return false; } } }
JavaScript
UTF-8
3,016
2.546875
3
[]
no_license
const {Todo, User} = require('../models'); class TodoController { static createTodo(req, res, next) { Todo.create({ title: req.body.title, description: req.body.description, status: false, due_date: req.body.due_date, UserId: req.decoded.id }) .then(todo => { res.status(201).json({ data: todo, message: 'Adding Todo Success' }) }) .catch(err => { next(err) }) } static findAll(req, res, next) { Todo.findAll({ where: { UserId: req.decoded.id }, order: [["due_date", "ASC"]] }) .then(todos => { res.status(200).json({ data: todos, message: 'Todo data found' }) }) .catch(err => { next(err) }) } static findOne(req, res, next) { Todo.findByPk(req.params.id) .then(todo => { if(todo === null) { next({ name: "DataNotFound", errors: `Todo with id ${req.params.id} not found` }) } else { res.status(200).json({ data: todo, message: 'One todo found' }) } }) .catch(err => { next(err) }) } static update(req, res, next) { Todo.update({ title: req.body.title, description: req.body.description, status: req.body.status, due_date: req.body.due_date }, { where: { id: req.params.id }, returning: true, plain: true }) .then(todo => { if(todo === null || todo === undefined) { next({ name: "DataNotFound", errors: `Todo with id ${req.params.id} not found` }) } else { res.status(200).json({ data: todo, message: 'Todo data has updated successfully' }) } }) .catch(err => { next(err) }) } static delete(req, res, next) { Todo.destroy({ where: { id: req.params.id } }) .then(data => { res.status(200).json({ data: deleteData, message: 'Todo data has been deleted successfully' }) }) .catch(err => { next(err) }) } } module.exports = TodoController;
PHP
UTF-8
747
2.65625
3
[ "MIT" ]
permissive
<?php namespace Vormkracht10\Seo\Traits; use Illuminate\Http\Client\Response; use Readability\Readability; use Symfony\Component\DomCrawler\Crawler; trait Actions { private function getTextContent(Response $response, Crawler $crawler): string { $body = $response->body(); if ($this->useJavascript) { $body = $crawler->filter('body')->html(); } $readability = new Readability($body); $readability->init(); return $readability->getContent()->textContent; } private function extractPhrases(string $content): array { // Get phrases seperate by new line, dot, exclamation mark or question mark return preg_split('/\n|\.|\!|\?/', $content); } }
Java
UTF-8
371
2.671875
3
[]
no_license
import java.awt.*; import java.applet.*; public class num extends Applet { public void paint(Graphics g) { int v1=4,v2=4,sum; sum = v1+v2; String s = "summation:" +String.valueOf(sum); g.drawString(s,100,100); } } /* <html> <body> <applet width="400" height="400" codebase="." code="num.class"> </applet> </body> </html> */
Markdown
UTF-8
855
3.28125
3
[]
no_license
## 1.1 Uniform convergence and continuity, integration and differentiation One of the main questions in relation to convergence of sequences and series is whether important properties of the functions $f_k$, like continuity, integrability and differentiability, are preserved in the limit process. Also, what is the relation between $f’_k$ and $f’$, or between the integral of $f_k$ and the integral of $f$? First of all, the uniform limit of continuous functions $f_k:[a,b]\to \R$ is continuous. On the other hand, pointwise convergence does not preserve continuity. (See Example 1) [[Theorem 1.8]] [[Remark 1.9]] [[Theorem 1.10]] [[Remark 1.11]] [[Corollary 1.12]] [[Example 4]] [[Theorem 1.13]] [[Remark 1.14]] [[Remark 1.15]] [[Theorem 1.16]] [[Remark 1.17]] [[Definition 1.18]] [[Definition 1.19]] [[Lemma 1.20]] [[Theorem 1.21]]
Python
UTF-8
4,438
2.828125
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- import csv import json import math def loadCsv(filename): lines = csv.reader(open(filename, "r")) dataset = list(lines) for i in range(len(dataset)): dataset [i] = [str(x) for x in dataset[i]] return dataset def categorize_data(data): categorized = {} for i in data: label = i[-1] if label not in categorized: categorized[label]=[] categorized[label].append(i[:-1]) return categorized def calc_cond_prob(data): data_length = len(data[0]) cond_prob = [] for each in data: temp = {} for item in each: if item in temp: temp[item] = temp[item] + 1 else: temp[item] = 1 for item in temp: temp[item] = float(temp[item])/data_length cond_prob.append(temp) return cond_prob def calc_log_cond_prob(data, scale, attributes): data_length = len(data[0]) cond_prob = [] c = -int(math.log(3.7e-4)*10) for i in range(len(data)): each = data[i] temp = {} for item in each: if item in temp: temp[item] = temp[item] + 1 else: temp[item] = 1 att = attributes[i] for value in att: if value in temp: temp[value] = int(((math.log(temp[value]/data_length) * 10) + c)/c*scale) else: temp[value] = 0 cond_prob.append(temp) return cond_prob def calc_model(data, scale, attributes = []): cond_prob = {} if attributes: for i in data: #class result = calc_log_cond_prob(list(zip(*data[i])), scale, attributes) cond_prob[i] = result else: for i in data: #class result = calc_cond_prob(list(zip(*data[i]))) cond_prob[i] = result return cond_prob def run(infofile, trainfile, outname): train = loadCsv(trainfile) print('Loaded data file {0} with {1} rows'.format(trainfile, len(train))) dataInfo = loadCsv(infofile) class_names = dataInfo[0] attribute_values = dataInfo[1:] print("Loaded information on data set") print("Probabilities will be represented as an integer from 0 to N.") print("Please input N.") scale = int(input()) categorized_train = categorize_data(train) class_prob = {} for key in categorized_train: class_prob[key] = len(categorized_train[key])/len(train) # Trains a model that is not logged or scaled. For testing performance of regular model trained_model={} trained_model['class_prob']=class_prob trained_model['cond_prob'] = calc_model(categorized_train, scale) modelFilename = outname + '_model_orig.json' with open(modelFilename, 'w') as outfile: json.dump(trained_model, outfile, indent=4) # Trains a model that is logged, scaled then represented as integers intModel = {} intClassProb = {} c = -int(math.log(3.7e-4)*10) # Value later used to "lift" the logged probabilities so that they will be positive for key in categorized_train: temp = len(categorized_train[key])/len(train) intClassProb[key] = int(((math.log(temp) * 10) + c)/c*scale) intModel['class_prob'] = intClassProb intModel['cond_prob'] = calc_model(categorized_train, scale, attribute_values) # For checking performance and accuracy of the trained model over plaintext with open(outname + '_model.json', 'w') as outfile: json.dump(intModel, outfile, indent=4) # What will actually be encrypted by FHE with open(outname + '_model.csv', 'w') as csvfile: f = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL) f.writerow([intModel['class_prob'][i] for i in class_names]) cond_prob = intModel['cond_prob'] for c in class_names: f.writerow([]) for i in range(len(cond_prob[c])): f.writerow([cond_prob[c][i][value] for value in attribute_values[i]]) if __name__ == '__main__': import argparse ap = argparse.ArgumentParser(description=u"train") ap.add_argument("-i", "--infofile", help="info filepath") ap.add_argument("-t", "--trainfile", help="train filepath") ap.add_argument("-o", "--outname", default="sample", help="output name") args = ap.parse_args() run(args.infofile, args.trainfile, args.outname)
Java
UTF-8
328
1.835938
2
[]
no_license
package com.mone.server.casemanagergenerator.config; /** * @Description * 生成策略 * SIMPLE 生成最基本的代码 * SINGLE 生成单表操作代码 * ALL 生成所有的代码 * @Classname GeneratorStrategy * @auther motao * @create 2020-06-30 16:19 */ public enum GeneratorStrategy { SIMPLE, SINGLE, ALL }
Java
UTF-8
871
3.078125
3
[ "Apache-2.0" ]
permissive
package util; import java.util.List; public final class Node implements util.Tree { public final int label; public final List<Tree> subtrees; @Override public int hashCode() { return java.util.Objects.hash(label, subtrees); } @Override public boolean equals(Object other) { return defaultEquals(other); } public Node(int label, util.Tree... children) { this.label = label; this.subtrees = java.util.Arrays.asList(children); } @Override public java.util.Optional<Node> asNode() { return java.util.Optional.of(this); } @Override public String toString() { return "Node{" + "label=" + label + ", subtrees=" + subtrees.stream().map(Tree::toString).collect(java.util.stream.Collectors.joining(",", "[", "]")) + '}'; } }
Java
UTF-8
504
1.835938
2
[]
no_license
package net.orcades.gwt.spring.demo.shared.rpc; import net.customware.gwt.dispatch.shared.Action; public class ZozoAction implements Action<ZozoResult> { /** * */ private static final long serialVersionUID = 1L; private String message; @SuppressWarnings("unused") private ZozoAction() { } public ZozoAction(String value) { this.message = value; } public void setMessage(String message) { this.message = message; } public String getMessage() { return message; } }
Java
UTF-8
832
3.109375
3
[]
no_license
package sort; public class Sort { public static void main(String[] args) { int arr[]={7,19,15,1,2,6,1,15,15,1}; int i=0; int sum=0; int repeat=0; int num=0; int size=10; int indexes=9; while (i<=indexes){ num=arr[i]; for(int index=0;index<=indexes;index++){ if (num<arr[index]){ sum=sum+1; }else if(num==arr[index]){ repeat=repeat+1; } } int newsize=size-repeat; if(sum==newsize) { break; } sum=0; repeat=0; i++; } System.out.println("Smallest value is "+num); } }
Java
UTF-8
2,397
2.328125
2
[]
no_license
package app.recruiter.intellingent.intellicruiter; import android.app.Activity; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; public class ClientList extends ArrayAdapter<Client> { private Activity context; List<Client> clients; public ClientList(Activity context, List<Client> clients) { super(context, R.layout.layout_client_list, clients); this.context = context; this.clients = clients; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View listViewItem = inflater.inflate(R.layout.layout_client_list, null, true); TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName); TextView textViewEmail = (TextView) listViewItem.findViewById(R.id.textViewEmail); TextView textViewIndustry = (TextView) listViewItem.findViewById(R.id.textViewIndustry); ImageView mImage = (ImageView) listViewItem.findViewById(R.id.mImage); Client client = clients.get(position); textViewName.setText(client.getClientName()); textViewEmail.setText(client.getClientEmail()); textViewIndustry.setText(client.getClientIndustry()); switch (client.getClientName()){ case "SAP":{ mImage.setImageResource(R.drawable.sap); break; } case "ALLSTATE":{ mImage.setImageResource(R.drawable.allstates); break; } case "USA AIRFORCE":{ mImage.setImageResource(R.drawable.usairforce); break; } case "INTEL":{ mImage.setImageResource(R.drawable.intel); break; } case "TARGET":{ mImage.setImageResource(R.drawable.target); break; } case "IIT":{ mImage.setImageResource(R.drawable.iit); break; } default: mImage.setImageResource(R.drawable.logo); } return listViewItem; } }
C#
UTF-8
1,207
2.890625
3
[ "MIT" ]
permissive
using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Nuke.GitHub { public static class ChangeLogExtensions { public static string GetCompleteChangeLog(string changeLogFile) { var fileContent = File.ReadAllText(changeLogFile); var lines = Regex.Split(fileContent, "\r\n?|\n"); var changeLogLines = lines .SkipWhile(l => !l.StartsWith("##")); var stringBuilder = new StringBuilder(); foreach (var changeLogLine in changeLogLines) { stringBuilder.AppendLine(changeLogLine); } var releaseNotes = stringBuilder.ToString(); return releaseNotes; } public static string EscapeStringPropertyForMsBuild(this string source) { // TODO Check MSBuild docs -> Is this just a regular Url escaping? return source .Replace(";", "%3B") .Replace(",", "%2C") .Replace(" ", "%20") .Replace("\r", "%0D") .Replace("\n", "%0A") .Replace("\"", "%22"); } } }
Python
UTF-8
2,250
2.5625
3
[ "MIT" ]
permissive
# Import Configuration from config import config output_dir = config["OUTPUT"]["DIRECTORY"] # Import External import re import cairo import matplotlib from graph_tool.all import * from os import listdir from os.path import isfile, join from halo import Halo # MAIN #Print all vertices def display_vertices(vertices, graph): types = ['subject', 'journal', 'paper', 'author', 'user'] for v in vertices: print(f"Type: {types[graph.vp.type[v]]}; ID: {graph.vp.id[v]}; Name: {graph.vp.name[v]}") #Get vertex by id def find_vertex_by_id(item_id, graph): for v in graph.get_vertices(): if graph.vp.id[v] == item_id: return graph.vertex(v) # Get graph from file def get_graph_from_folder(): files = [f for f in listdir(output_dir) if isfile(join(output_dir,f)) and re.search(r"(.*\.gt)", f)] print("Graph Files Available") for i in range(len(files)): print(str(i) + " - " + files[i]) file_to_load = files[int(input("Enter file number: "))] with Halo(text='Loading graph file...', spinner='dots'): graph = load_graph(output_dir + file_to_load) return graph # Convert graph file in output dir def convert_filetype(): graph = get_graph_from_folder() filename = input("Filename to convert to: ") graph.save(output_dir + filename) # Create standard graph visual def draw_plain_visual(graph, filename, include_id = False, type_size = False): if include_id: vertex_text = graph.vp.id else: vertex_text = "" if type_size: vertex_size = graph.vp.size else: vertex_size = 1 #pos = graphviz_draw(graph, vsize=10, overlap=False, output=None) with Halo(text='Drawing visuals...', text_color = "red", spinner='bouncingBall'): graph_draw(graph, #pos = pos, edge_pen_width = 0.1, vertex_text = vertex_text, vorder = graph.vp.type, vertex_aspect = 1, vertex_text_position = 1, vertex_text_color = "black", vertex_font_family = "sans", vertex_font_size = 0.2, vertex_font_weight = cairo.FONT_WEIGHT_NORMAL, vertex_fill_color = graph.vp.type, vertex_size = vertex_size, output = output_dir + filename ) def plain_visual_routine(type_size = False): graph = get_graph_from_folder() draw_plain_visual(graph, input("Plain visual filename: "), type_size = type_size)
JavaScript
UTF-8
537
3.734375
4
[]
no_license
function solve(crews) { crews.map(Number); let dailyCostArr = []; while (!crews.every(x => x === 30)) { let dailyCost = 0; for (let i = 0; i < crews.length; i++) { if (crews[i] !== 30) { crews[i]++; dailyCost += 195; } } dailyCostArr.push(dailyCost); } console.log(dailyCostArr.join(', ')); let finalCost = dailyCostArr.reduce((a, b) => a + b) * 1900; console.log(`${finalCost} pesos`); } solve([17, 22, 17, 19, 17]);
C#
UTF-8
998
3.609375
4
[]
no_license
using System; using System.Reflection.Metadata; namespace TicTacToeGame { class Program { static void Main(string[] args) { Console.WriteLine("Welcome to Tic Tac Toe Game"); TicTacToe tic = new TicTacToe(); // To create a new board char [] board = tic.CreateBoard(); // To show board tic.ShowBoard(board); tic.Toss(); // To choose a letter by a user char userLetter = tic.ChooseLetter(); char computerLetter = (userLetter == 'X') ? 'O' : 'X'; // To move desired location int userMove = tic.getUserMove(board); tic.makeMove(board, userMove, userLetter); tic.ShowBoard(board); //Computer Move int computerMove = tic.getComputerMove(board, computerLetter, userLetter); Console.WriteLine("Check if Won: " + tic.isWinner(board, userLetter)); } } }
Shell
UTF-8
407
2.9375
3
[]
no_license
mkdir -p data/align/$1 for file in `ls $1` do out_file=`echo $file | sed 's/_/-/g' | sed 's/.html//'` echo $out_file python python/scrapper_soupparser.py $1/$file | grep '^\[O\]' | sed -e 's/^\[O\][^A-Za-z]*//' > data/align/$1/${out_file}_original.snt python python/scrapper_soupparser.py $1/$file | grep '^\[M\]' | sed -e 's/^\[M\][^A-Za-z]*//' > data/align/$1/${out_file}_modern.snt done
JavaScript
UTF-8
470
2.53125
3
[ "MIT" ]
permissive
import {ADD_GENERATED_CALENDAR, CLEAR_GENERATED_CALENDAR, DELETE_GENERATED_CALENDAR} from '../constants'; export default function GeneratedCalendarsReducer(state = [], action) { const { calendar, index } = action; switch (action.type) { case ADD_GENERATED_CALENDAR: return [...state, calendar]; case DELETE_GENERATED_CALENDAR: state.splice(index,1); return state; case CLEAR_GENERATED_CALENDAR: return []; default: return state; } }
TypeScript
UTF-8
715
2.875
3
[]
no_license
import { Constructor } from './constructor'; import { HasElementRef } from './types'; /** Possible size palette values. */ export declare type ElementSize = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '3xl' | 'body' | undefined; /** @docs-private */ export interface CanSize { /** Theme size palette for the component. */ size: ElementSize; /** Default size to fall back to if no value is set. */ defaultSize: ElementSize | undefined; } /** @docs-private */ export declare type CanSizeCtor = Constructor<CanSize>; /** Mixin to augment a directive with a `size` property. */ export declare function mixinSize<T extends Constructor<HasElementRef>>(base: T, defaultSize?: ElementSize): CanSizeCtor & T;
Python
UTF-8
22,481
3.484375
3
[ "MIT" ]
permissive
import re from graphFromText.fxnFromText.fxnGraph import getSymbolGraphMulti ##################### Will map x + y = z + u as {'x':['z','u','y']} ########################## def graphByEquals2(Text): #"tokenize" or parse according to newline character, \n listOfEquations = re.split(r'\n',Text) # strip whitespace, remove tabs and remove blank entries for k, eq in enumerate(listOfEquations): eq.strip() eq.replace("\t","") listOfEquations[k]= eq.replace(" ","") while ('' in listOfEquations): listOfEquations.remove('') #### Create a graphOfLeft and a graphOfRight based upon the equations in listOfEquations #### # #The graphOfLeft will make all symbols on the right hand side point to the left hand symbol #The graphOfRight will do the opposite and the left hand symbol will point to all right #hand symbols. # #An example: #From the equation a=b+c, the graphOfLeft would have 'a':['b','c']. This would be #interpreted as 'b' and 'c' affect 'a'. The graphOfRight would be 'b':['a'] and 'c':['a']. #This would be interpreted as 'a' depends upon 'b' and also 'a' depends upon 'c'. graphOfLeft = dict() graphOfRight = dict() inputError=None for k, eq in enumerate(listOfEquations): result = re.split(r'={1}', eq) # split into LHS and RHS by exactly one equals sign # Left Hand Side (LHS) is every word to the left of exactly one equals sign # Right Hand Side (RHS) is every word to the right of exactly one equals sign # print("LHS:",result[0]," RHS:",result[1]," len=",len(result)) # if there is a LHS and RHS, then it is an assignment or equation. Otherwise, it is not. # Also, filter out the cases where a <= or >= is found in the result if (len(result) == 2 and result[0].find("<") == -1 \ and result[0].find(">") == -1 and result[1].find("<") == -1 \ and result[1].find(">") == -1): #LHS = re.findall(r'\w+', result[0]) #RHS = re.findall(r'\w+', result[1]) foundLeft = re.findall(r'\w+', result[0]) LHS=[] for expr in foundLeft: leftMatch = re.match(r'^[a-zA-Z]+[0-9a-zA-Z_]*',expr) if (leftMatch is None \ and re.match(r'^[0-9]+[a-zA-Z_]+', expr) is not None): inputError = ValueError('\nillegal expression:\n' + expr) elif (leftMatch is not None): LHS.append(leftMatch.group(0)) foundRight = re.findall(r'\w+', result[1]) RHS=[] for expr in foundRight: rightMatch = re.match(r'^[a-zA-Z]+[0-9a-zA-Z_]*',expr) if (rightMatch is None \ and re.match(r'^[0-9]+[a-zA-Z_]+', expr) is not None): inputError = ValueError('\nillegal expression:\n' + expr) elif (rightMatch is not None): RHS.append(rightMatch.group(0)) ###### special case for numbers only on RHS ###### if ( len(result[1]) != 0 and len(RHS) == 0 ): crazy = r'[+-]?\d+\.?\d*[eE][+-]?\d+|[-]?\d+\.\d+|[-]?\d+' numberMatch = re.findall(crazy, result[1]) if (len(numberMatch) != 0): for expr in numberMatch: RHS.append(expr) if (LHS and RHS): #If there is more than one entry in the LHS, move LHS[1], LHS[2], etc. over #to RHS array, leaving LHS[0] alone if (len(LHS) > 1): for k in range(1,len(LHS)): RHS.append(LHS[k]) del LHS[1:len(LHS)] if (LHS[0] not in graphOfLeft): graphOfLeft[LHS[0]] = RHS.copy() else: for item in RHS: graphOfLeft[LHS[0]].append(item) inputError=ValueError('\nconflicting definition in line:\n' + eq) for key in RHS: # print(key,LHS[0]) if (key is not None) and (LHS[0] is not None): if (key not in graphOfRight): graphOfRight[key] = [LHS[0]] else: graphOfRight[key].append(LHS[0]) else: inputError=ValueError('incomplete equation expression found in line:\n' + eq) else: inputError=ValueError('non-equation expression found in line:\n' + eq) return graphOfLeft, inputError ##################### Will map x + y = z + u as {'x':['z','u','y'],'y':['z','u','x']} ##################### def graphByEquals3(Text): listOfEquations = re.split(r'\n',Text) #strip whitespace and remove blank entries # strip whitespace and remove blank entries for k, eq in enumerate(listOfEquations): listOfEquations[k]= eq.replace(" ","") #print(len(listOfEquations[k])) while ('' in listOfEquations): listOfEquations.remove('') #print(listOfEquations) graphOfLeft = dict() graphOfRight = dict() inputError=None for k, eq in enumerate(listOfEquations): result = re.split(r'={1}', eq) # split into LHS and RHS by exactly one equals sign # Left Hand Side (LHS) is every word to the left of exactly one equals sign # Right Hand Side (RHS) is every word to the right of exactly one equals sign # print("LHS:",result[0]," RHS:",result[1]," len=",len(result)) # if there is a LHS and RHS, then it is an assignment or equation. Otherwise, it is not. # Also, filter out the cases where a <= or >= is found in the result if (len(result) == 2 and result[0].find("<") == -1 \ and result[0].find(">") == -1 and result[1].find("<") == -1 \ and result[1].find(">") == -1): #LHS = re.findall(r'\w+', result[0]) #RHS = re.findall(r'\w+', result[1]) foundLeft = re.findall(r'\w+', result[0]) LHS=[] for expr in foundLeft: leftMatch = re.match(r'^[a-zA-Z]+[0-9a-zA-Z_]*',expr) if (leftMatch is None \ and re.match(r'^[0-9]+[a-zA-Z_]+', expr) is not None): inputError = ValueError('\nillegal expression:\n' + expr) elif (leftMatch is not None): LHS.append(leftMatch.group(0)) foundRight = re.findall(r'\w+', result[1]) RHS=[] for expr in foundRight: rightMatch = re.match(r'^[a-zA-Z]+[0-9a-zA-Z_]*',expr) if (rightMatch is None \ and re.match(r'^[0-9]+[a-zA-Z_]+', expr) is not None): inputError = ValueError('\nillegal expression:\n' + expr) elif (rightMatch is not None): RHS.append(rightMatch.group(0)) ###### special case for numbers only on RHS ###### if ( len(result[1]) != 0 and len(RHS) == 0 ): crazy = r'[+-]?\d+\.?\d*[eE][+-]?\d+|[-]?\d+\.\d+|[-]?\d+' numberMatch = re.findall(crazy,result[1]) if (len(numberMatch) != 0): for expr in numberMatch: RHS.append(expr) if (LHS and RHS): for k, key in enumerate(LHS): if (key not in graphOfLeft): graphOfLeft[key] = RHS.copy() #print('key = ' + key + ', RHS = ', RHS) else: for item in RHS: if (item not in graphOfLeft[key]): graphOfLeft[key].append(item) #inputError=ValueError('conflicting definition in line:\n' + eq) #print('before adding other left:\n',graphOfLeft) for kk, otherkey in enumerate(LHS): if (key is not None) and (otherkey is not None)\ and (key != otherkey)\ and (otherkey not in graphOfLeft[key]): #print('key = ' + key + ', otherkey = ' + otherkey) graphOfLeft[key].append(otherkey) #print(graphOfLeft[key]) #print('it\'s a multi-expression eq.: ' + key + ',' + otherkey + '\n') for key in RHS: # print(key,LHS[0]) if (key is not None) and (LHS[0] is not None): if (key not in graphOfRight): graphOfRight[key] = [LHS[0]] else: graphOfRight[key].append(LHS[0]) else: inputError=ValueError('incomplete equation expression found in line:\n' + eq) else: inputError=ValueError('non-equation expression found in line:\n' + eq) return graphOfLeft, inputError ##################### Will map x + y = z + u as {'x':['z','u'],'y':['z','u']} ########################## def graphByEquals4(Text): listOfEquations = re.split(r'\n',Text) #strip whitespace and remove blank entries #strip whitespace and remove blank entries for k, eq in enumerate(listOfEquations): listOfEquations[k]= eq.replace(" ","") #print(len(listOfEquations[k])) while ('' in listOfEquations): listOfEquations.remove('') #print(listOfEquations) graphOfLeft = dict() graphOfRight = dict() inputError=None for k, eq in enumerate(listOfEquations): result = re.split(r'={1}', eq) # split into LHS and RHS by exactly one equals sign # Left Hand Side (LHS) is every word to the left of exactly one equals sign # Right Hand Side (RHS) is every word to the right of exactly one equals sign # print("LHS:",result[0]," RHS:",result[1]," len=",len(result)) # if there is a LHS and RHS, then it is an assignment or equation. Otherwise, it is not. # Also, filter out the cases where a <= or >= is found in the result if (len(result) == 2 and result[0].find("<") == -1 \ and result[0].find(">") == -1 and result[1].find("<") == -1 \ and result[1].find(">") == -1): #LHS = re.findall(r'\w+', result[0]) #RHS = re.findall(r'\w+', result[1]) foundLeft = re.findall(r'\w+', result[0]) LHS=[] for expr in foundLeft: leftMatch = re.match(r'^[a-zA-Z]+[0-9a-zA-Z_]*',expr) if (leftMatch is None \ and re.match(r'^[0-9]+[a-zA-Z_]+', expr) is not None): inputError = ValueError('\nillegal expression:\n' + expr) elif (leftMatch is not None): LHS.append(leftMatch.group(0)) foundRight = re.findall(r'\w+', result[1]) RHS=[] for expr in foundRight: rightMatch = re.match(r'^[a-zA-Z]+[0-9a-zA-Z_]*',expr) if (rightMatch is None \ and re.match(r'^[0-9]+[a-zA-Z_]+', expr) is not None): inputError = ValueError('\nillegal expression:\n' + expr) elif (rightMatch is not None): RHS.append(rightMatch.group(0)) ###### special case for numbers only on RHS ###### if ( len(result[1]) != 0 and len(RHS) == 0 ): crazy = r'[+-]?\d+\.?\d*[eE][+-]?\d+|[-]?\d+\.\d+|[-]?\d+' numberMatch = re.findall(crazy, result[1]) if (len(numberMatch) != 0): for expr in numberMatch: RHS.append(expr) if (LHS and RHS): for k, key in enumerate(LHS): if (key not in graphOfLeft): graphOfLeft[key] = RHS.copy() #print('key = ' + key + ', RHS = ', RHS) else: for item in RHS: if (item not in graphOfLeft[key]): graphOfLeft[key].append(item) #inputError=ValueError('conflicting definition in line:\n' + eq) #print('before adding other left:\n',graphOfLeft) #for kk, otherkey in enumerate(LHS): #if (key is not None) and (otherkey is not None)\ #and (key != otherkey)\ #and (otherkey not in graphOfLeft[key]): #print('key = ' + key + ', otherkey = ' + otherkey) #graphOfLeft[key].append(otherkey) #print(graphOfLeft[key]) #print('it\'s a multi-expression eq.: ' + key + ',' + otherkey + '\n') for key in RHS: # print(key,LHS[0]) if (key is not None) and (LHS[0] is not None): if (key not in graphOfRight): graphOfRight[key] = [LHS[0]] else: graphOfRight[key].append(LHS[0]) else: inputError=ValueError('incomplete equation expression found in line:\n' + eq) else: inputError=ValueError('non-equation expression found in line:\n' + eq) return graphOfLeft, inputError ##################### Will map z = f(x,y) + u as {'z':['f','u'],'f':['x',y']}, figuratively ############### ##################### Note that the actual graph items are tuples, like ('f',4,'fxn',0,0) ################# ##################### The tuples are the following format: (symbolName,character,type,fxnLevel,eqNum) ##### def graphByEqualsFxn1(Text): listOfEquations = re.split(r'\n', Text) # strip whitespace and remove blank entries for k, eq in enumerate(listOfEquations): listOfEquations[k] = eq.replace(" ", "") while ('' in listOfEquations): listOfEquations.remove('') # print(listOfEquations) inputError = None leftHandLinesOfText = [] rightHandLinesOfText = [] for k, eq in enumerate(listOfEquations): result = re.split(r'={1}', eq) # split into LHS and RHS by exactly one equals sign # Left Hand Side (LHS) is every word to the left of exactly one equals sign # Right Hand Side (RHS) is every word to the right of exactly one equals sign # print("LHS:",result[0]," RHS:",result[1]," len=",len(result)) # if there is a LHS and RHS, then it is an assignment or equation. Otherwise, it is not. # Also, filter out the cases where a <= or >= is found in the result if (len(result) == 2 and result[0].find("<") == -1 \ and result[0].find(">") == -1 and result[1].find("<") == -1 \ and result[1].find(">") == -1): # LHS = re.findall(r'\w+', result[0]) # RHS = re.findall(r'\w+', result[1]) foundLeft = re.findall(r'\w+', result[0]) for expr in foundLeft: leftMatch = re.match(r'^[a-zA-Z]+[0-9a-zA-Z_]*', expr) if (leftMatch is None \ and re.match(r'^[0-9]+[a-zA-Z_]+', expr) is not None): inputError = ValueError('\nillegal expression:\n' + expr) #elif (leftMatch is not None): #LHS.append(leftMatch.group(0)) foundRight = re.findall(r'\w+', result[1]) for expr in foundRight: rightMatch = re.match(r'^[a-zA-Z]+[0-9a-zA-Z_]*', expr) if (rightMatch is None \ and re.match(r'^[0-9]+[a-zA-Z_]+', expr) is not None): inputError = ValueError('\nillegal expression:\n' + expr) #elif (rightMatch is not None): #RHS.append(rightMatch.group(0)) ##### check RHS for unbalanced parenthesis ##### parenCnt = 0 for char in result[1]: if char == '(': parenCnt+=1 elif char == ')': parenCnt-=1 if ( parenCnt != 0 ): inputError = ValueError('\nunbalanced parenthesis:\n' + eq) # issue with error message fix, 4/11/2021 #inputError = ValueError('\nunbalanced parenthesis:\n' + expr) ###### special case for numbers only on RHS ###### #if (len(result[1]) != 0 and len(RHS) == 0): #crazy = r'[+-]?\d+\.?\d*[eE][+-]?\d+|[-]?\d+\.\d+|[-]?\d+' #numberMatch = re.findall(crazy, result[1]) #if (len(numberMatch) != 0): #for expr in numberMatch: #RHS.append(expr) if (inputError is None): for k, left in enumerate(foundLeft): leftHandLinesOfText.append(left) rightHandLinesOfText.append(result[1]) #else statement commented out on 4/9/2021 #else: #inputError = ValueError('incomplete equation expression found in line:\n' + eq) else: inputError = ValueError('non-equation expression found in line:\n' + eq) #### LHS and RHS are populated #### if (inputError is None): symbolGraphMulti = getSymbolGraphMulti(leftHandLinesOfText, rightHandLinesOfText) else: symbolGraphMulti = dict() return symbolGraphMulti, inputError ''' ##################### Will map x + y = z + u as {'x':['z','u'],'y':['z','u']} ########################## def graphByEquals4(Text): listOfEquations = re.split(r'\n',Text) #strip whitespace and remove blank entries # strip whitespace and remove blank entries for k, eq in enumerate(listOfEquations): listOfEquations[k]= eq.replace(" ","") #print(len(listOfEquations[k])) while ('' in listOfEquations): listOfEquations.remove('') #print(listOfEquations) graphOfLeft = dict() graphOfRight = dict() inputError=None for k, eq in enumerate(listOfEquations): result = re.split(r'={1}', eq) # split into LHS and RHS by exactly one equals sign # Left Hand Side (LHS) is every word to the left of exactly one equals sign # Right Hand Side (RHS) is every word to the right of exactly one equals sign # print("LHS:",result[0]," RHS:",result[1]," len=",len(result)) # if there is a LHS and RHS, then it is an assignment or equation. Otherwise, it is not. # Also, filter out the cases where a <= or >= is found in the result if (len(result) == 2 and result[0].find("<") == -1 \ and result[0].find(">") == -1 and result[1].find("<") == -1 \ and result[1].find(">") == -1): #LHS = re.findall(r'\w+', result[0]) #RHS = re.findall(r'\w+', result[1]) foundLeft = re.findall(r'\w+', result[0]) LHS=[] for expr in foundLeft: leftMatch = re.match(r'^[a-zA-Z]+[0-9a-zA-Z_]*',expr) if (leftMatch is None \ and re.match(r'^[0-9]+[a-zA-Z_]+', expr) is not None): inputError = ValueError('\nillegal expression:\n' + expr) elif (leftMatch is not None): LHS.append(leftMatch.group(0)) #### Under development #### fxnOnRight=re.search(r'(\w+)\((.*)\)', result[1]) if (fxnOnRight is not None): fxnName = fxnOnRight.groups(0) else: foundRight = re.findall(r'\w+', result[1]) RHS=[] for expr in foundRight: rightMatch = re.match(r'^[a-zA-Z]+[0-9a-zA-Z_]*',expr) if (rightMatch is None \ and re.match(r'^[0-9]+[a-zA-Z_]+', expr) is not None): inputError = ValueError('\nillegal expression:\n' + expr) elif (rightMatch is not None): RHS.append(rightMatch.group(0)) ###### special case for numbers only on RHS ###### if ( len(result[1]) != 0 and len(RHS) == 0 ): num_regex = r'[+-]?\d+\.?\d*[eE][+-]?\d+|[-]?\d+\.\d+|[-]?\d+' numberMatch = re.findall(num_regex, result[1]) if (len(numberMatch) != 0): for expr in numberMatch: RHS.append(expr) if (LHS and RHS): for k, key in enumerate(LHS): if (key not in graphOfLeft): graphOfLeft[key] = RHS.copy() #print('key = ' + key + ', RHS = ', RHS) else: for item in RHS: if (item not in graphOfLeft[key]): graphOfLeft[key].append(item) #inputError=ValueError('conflicting definition in line:\n' + eq) #print('before adding other left:\n',graphOfLeft) #for kk, otherkey in enumerate(LHS): #if (key is not None) and (otherkey is not None)\ #and (key != otherkey)\ #and (otherkey not in graphOfLeft[key]): #print('key = ' + key + ', otherkey = ' + otherkey) #graphOfLeft[key].append(otherkey) #print(graphOfLeft[key]) #print('it\'s a multi-expression eq.: ' + key + ',' + otherkey + '\n') for key in RHS: # print(key,LHS[0]) if (key is not None) and (LHS[0] is not None): if (key not in graphOfRight): graphOfRight[key] = [LHS[0]] else: graphOfRight[key].append(LHS[0]) else: inputError=ValueError('incomplete equation expression found in line:\n' + eq) else: inputError=ValueError('non-equation expression found in line:\n' + eq) return graphOfLeft, inputError '''
Python
UTF-8
563
3.296875
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt def AND(x1, x2): x = np.array([x1, x2]) w = np.array([0.5, 0.5]) b = -0.7 y = np.sum(x * w) + b if y <= 0: return 0 else: return 1 def step_function(x): return np.array(x > 0, dtype=np.int) def sigmoid(x): return 1 / (1 + np.exp(-x)) #print(AND(0, 1)) x = np.arange(-5.0, 5.0, 0.1) y1 = step_function(x) y2 = sigmoid(x) plt.plot(x, y1) plt.plot(x, y2) plt.ylim(-0.1, 1.1) plt.xlabel("x") plt.ylabel("y") plt.title("激活函数") plt.legend() plt.show()
Java
UTF-8
2,305
2.546875
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package jester; import java.io.*; import java.util.Properties; public class RealConfiguration implements Configuration { public static final String DEFAULT_CONFIGURATION_FILENAME = "jester.cfg"; private Logger myLogger = new RealLogger(); private Properties myProperties; public RealConfiguration(String configFileName, PrintStream errorStream) throws IOException { super(); myProperties = new Properties(); InputStream configPropertyFile = ClassLoader.getSystemResourceAsStream(configFileName); if (configPropertyFile == null) { configPropertyFile = getClass().getResourceAsStream(configFileName); } if (configPropertyFile != null) { myProperties.load(configPropertyFile); }else{ errorStream.println("Warning - could not find "+DEFAULT_CONFIGURATION_FILENAME+" so using default configuration values."); } } public RealConfiguration(String configFileName) throws IOException { this(configFileName, System.err); } public String compilationCommand() { return stringProperty("compilationCommand", "javac"); } private boolean isTrue(String value) { return value.toLowerCase().equals("true"); } private boolean isTrueProperty(String propertyName, boolean defaultValue) { String propertyValue = myProperties.getProperty(propertyName); if(propertyValue==null){ return defaultValue; } return isTrue(propertyValue); } public boolean shouldReportEagerly() { return isTrueProperty("shouldReportEagerly", false); } public String sourceFileExtension() { return stringProperty("sourceFileExtension", ".java"); } private String stringProperty(String propertyName, String defaultValue) { String result = myProperties.getProperty(propertyName); if (result == null) { return defaultValue; } return result; } public String testRunningCommand() { return stringProperty("testRunningCommand", "java jester.TestRunnerImpl"); } public String testsPassString() { return stringProperty("testsPassString", "PASSED"); } public Logger getLogger() { return myLogger; } public String xmlReportFileName() { return stringProperty("xmlReportFileName", "jesterReport.xml"); } public boolean closeUIOnFinish() { return isTrueProperty("closeUIOnFinish", true); } }
JavaScript
UTF-8
1,009
2.796875
3
[]
no_license
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.jd.com/'); const hrefArr = await page.evaluate(() => { let arr = []; const aNodes = document.querySelectorAll('.cate_menu_lk'); aNodes.forEach(function (item) { arr.push(item.href) }) return arr }); let arr = []; for (let i = 0; i < hrefArr.length; i++) { const url = hrefArr[i]; console.log(url) //这里可以打印 await page.goto(url); const result = await page.evaluate(() => { //这个方法内部console.log无效 return $('title').text(); //返回每个界面的title文字内容 }); arr.push(result) //每次循环给数组中添加对应的值 } console.log(arr) //得到对应的数据 可以通过Node.js的 fs 模块保存到本地 await browser.close() })()
SQL
UTF-8
1,650
3.03125
3
[]
no_license
-- MySQL Script generated by MySQL Workbench -- Thu Jul 26 13:43:27 2018 -- Model: New Model Version: 1.0 -- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; -- ----------------------------------------------------- -- Schema protocolo -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema protocolo -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `protocolo` DEFAULT CHARACTER SET utf8 ; USE `protocolo` ; -- ----------------------------------------------------- -- Table `protocolo`.`Protocolo` -- ----------------------------------------------------- DROP TABLE IF EXISTS `protocolo`.`Protocolo` ; CREATE TABLE IF NOT EXISTS `protocolo`.`Protocolo` ( `idProtocolo` INT NOT NULL AUTO_INCREMENT, `cod` INT NULL, `tipo` INT NULL, `data` DATETIME NULL, `certidao` TINYINT NULL, `peticao` TINYINT NULL, `escritura` TINYINT NULL, `inventariado` VARCHAR(400) NULL, `advogado` VARCHAR(300) NULL, `valor` DOUBLE NULL, `paralizado` TINYINT NULL, `documentos` TINYINT NULL, `itcd` TINYINT NULL, `dae` TINYINT NULL, `certQuitacao` TINYINT NULL, `certNegativa` TINYINT NULL, `textoPronto` TINYINT NULL, `assinaturas` TINYINT NULL, `pronto` TINYINT NULL, PRIMARY KEY (`idProtocolo`)) ENGINE = InnoDB; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
JavaScript
UTF-8
3,262
3.203125
3
[]
no_license
const holdL = document.querySelector("#countForL"); const holdS = document.querySelector("#countForS"); const output = document.querySelector("#output"); const input = document.querySelector("#gameInput"); const startButton = document.querySelector("#startBtn"); const pressL = document.querySelector("#pressForL"); const pressS = document.querySelector("#pressForS"); const containerForS=document.querySelector('#containerForS'); const containerForL=document.querySelector('#containerForL'); let sectionPress=document.querySelector('#keyPressSection') const restartBtnDiv = document.createElement("div"); const restartButton = document.createElement("button"); const restartSection = document.querySelector("#addRestart"); restartBtnDiv.classList.add("restart-button"); restartButton.innerHTML = "Start a new Game"; const startBtnDiv = document.querySelector("#startBtnDiv"); startButton.innerHTML = "Start game"; pressL.innerHTML = "Press L"; pressS.innerHTML = "Press S"; let countL = 0; let countS = 0; const handlePress = (e) => { let key = e.key.toLowerCase(); if (key == "s".toLowerCase()) { holdS.innerHTML = countS++; } if (key == "l".toLowerCase()) { holdL.innerHTML = countL++; } }; const getWinner = () => { if (countL < countS) { output.innerHTML = "Game over ,S clicked highest with a score of " + (countS - 1); containerForS.classList.add('animate-S') document.body.classList.add("animate"); containerForL.style.visibility='hidden' } if (countL > countS) { output.innerHTML = "Game over ,L clicked highest with a score of " + (countL - 1); document.body.classList.add("animate"); containerForL.classList.add('animate-L') containerForS.style.visibility='hidden' } if (countL == countS) { output.innerHTML = "Game over,Draw with score of " + (countS - 1); document.body.classList.add("animate"); } if (countL == 0 && countS == 0) { output.innerHTML = "Game over,No key pressed"; sectionPress.style.visibility='hidden' } }; const getOutput = () => { document.removeEventListener("keypress", handlePress); restartBtnDiv.appendChild(restartButton); restartSection.appendChild(restartBtnDiv); startBtnDiv.style.display = "none"; getWinner(); }; const startNewGame = () => { output.innerHTML = ""; holdL.innerHTML=''; holdS.innerHTML=''; countS = 0; countL = 0; containerForL.classList.remove('animate-L') containerForS.classList.remove('animate-S') sectionPress.style.visibility='visible' containerForL.style.visibility='visible' containerForS.style.visibility='visible' document.body.classList.remove("animate"); renderGameOver(); }; function renderGameOver() { if(input.value){ document.addEventListener("keypress", handlePress); setTimeout(getOutput, input.value * 1000); }else{ output.innerHTML='Set your timer' } } startButton.addEventListener("click", renderGameOver); restartButton.addEventListener("click", startNewGame);
Java
UTF-8
697
1.601563
2
[]
no_license
package com.miui.yellowpage.ui; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.miui.yellowpage.base.utils.Log; /* compiled from: BaseWebFragment */ class cV extends BroadcastReceiver { final /* synthetic */ bw this$0; cV(bw bwVar) { this.this$0 = bwVar; } public void onReceive(Context context, Intent intent) { Log.d("BaseWebFragment", "mWebResBroadcastReceiver onReceive"); bw.INJECTED_JS_CONTENT = null; if (this.this$0.mWebView != null) { this.this$0.mWebView.clearCache(true); this.this$0.loadUrl(this.this$0.mWebView.getUrl()); } } }
Java
UTF-8
4,530
2.28125
2
[]
no_license
package pl.gihon.fdd.poi.localisator.google; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; import java.util.stream.Collectors; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import pl.gihon.fdd.poi.exception.PoiException; import pl.gihon.fdd.poi.localisator.Localisator; import pl.gihon.fdd.poi.model.LocatedPlace; import pl.gihon.fdd.poi.model.Place; @Component public class GoogleLocalisator implements Localisator { private static final Object GEOCODING_URL = "https://maps.googleapis.com/maps/api/geocode/json?"; @Value("${google.geocoding.sleep}") private int sleepTime; @Value("${GOOGLE_API_KEY}") private String googleApiKey; private static Logger logger = LoggerFactory.getLogger(GoogleLocalisator.class); private LocationCache locationCache; @Autowired public GoogleLocalisator(LocationCache locationCache) { super(); this.locationCache = locationCache; } @Override public List<LocatedPlace> locate(List<Place> places) { return places.stream().map(p -> locate(p)).collect(Collectors.toList()); } public String getStartOfApiKey() { return googleApiKey.substring(0, 5); } private LocatedPlace locate(Place place) { try { String locationText = ""; String key = place.getFullAddress(); if (!locationCache.containsKey(key)) { logger.debug("Querying api for {}", place.getFullAddress()); locationText = queryApiForText(place); Thread.sleep(sleepTime); } else { logger.debug("Found {} in cache", key); locationText = locationCache.getValue(key).get(); } GeocodingResponse response = mapResponse(locationText); if (!response.getStatus().equals("OK")) { logger.error("status not OK, {}", response); throw new GoogleLocalisatorException(place, response); } if (response.getResults().size() < 1) { logger.error("no results found for {}", place); throw new GoogleLocalisatorException(place, "no results found"); } if (!locationCache.containsKey(key)) { locationCache.put(place.getFullAddress(), locationText); } Location location = response.getResults().get(0).getGeometry().getLocation(); return new LocatedPlace(location.getLat(), location.getLng(), place); } catch (IOException | InterruptedException e) { throw new PoiException(e); } } private GeocodingResponse mapResponse(String responseText) throws JsonProcessingException, IOException { ObjectMapper mapper = new ObjectMapper(); ObjectReader reader = mapper.reader().forType(GeocodingResponse.class); Object readValue = reader.readValue(responseText); return (GeocodingResponse) readValue; } private String queryApiForText(Place place) throws IOException, UnsupportedEncodingException, ClientProtocolException { String addressValues = URLEncoder.encode(String.format("%s, %s", place.getCity(), place.getStreetAndFlat()), "UTF-8"); StringBuilder sb = new StringBuilder(); sb.append(GEOCODING_URL).append("address=").append(addressValues).append("&key=").append(googleApiKey); CloseableHttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(sb.toString()); logger.debug("going to query api with request {}", request); CloseableHttpResponse response = client.execute(request); logger.debug("api returns response {}", response); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String inputLine; StringBuffer responseTextBuffer = new StringBuffer(); while ((inputLine = in.readLine()) != null) { responseTextBuffer.append(inputLine); } in.close(); String responseText = responseTextBuffer.toString(); return responseText; } public int cacheSize() { return locationCache.getSize(); } public void clearCache() { locationCache.clear(); } }
C#
UTF-8
1,620
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Text; using Moq; using WordFrequencyCounter.Core.ChunkProcessing; using Xunit; namespace WordFrequencyCounter.Tests { public class ChunkWordFrequencyCounterTests { [Theory] [InlineData("../../../../../samples/aaa200.txt", "aaa:200")] [InlineData("../../../../../samples/aaa100bbb50ccc10.txt", "aaa:100,bbb:50,ccc:10")] public void ShouldProcessFile(string inputFile, string expectedData) { // arrange var expected = expectedData.ToDictionary(); var chunkReader = new SimpleChunkFileReader(); var chunkProcessor = new ChunkProcessor(); var chunkMerger = new ChunkResultMerger(); var wordCounter = new ChunkWordFrequencyCounter(chunkReader, chunkProcessor, chunkMerger); // act var actual = wordCounter.Process(inputFile); // assert Assert.Equal(expected, actual); } [Fact] public void ShouldThrow_WhenInputFileNotFound() { // arrange var chunkReader = new SimpleChunkFileReader(); var chunkProcessor = new ChunkProcessor(); var chunkMerger = new ChunkResultMerger(); var wordCounter = new ChunkWordFrequencyCounter(chunkReader, chunkProcessor, chunkMerger); // act & assert Assert.Throws<FileNotFoundException>(() => wordCounter.Process("not.existed")); } } }
Python
UTF-8
379
3.390625
3
[]
no_license
import random M = input() op = ['+','-','*','/'] #s = random.random(op) s = input(random.choice(op)) N = input() if s == '+': A = eval('M + N') print("{:.2f}".format(A)) elif s == '-': B = eval('M - N') print("{:.2f}".format(B)) elif s == '*': C = eval('M * N') print("{:.2f}".format(C)) elif s == '/': D = eval('M / N') print("{:.2f}".format(D))
JavaScript
UTF-8
1,709
2.625
3
[]
no_license
/** * Created by miracle on 16-11-14. */ (function () { var url = "http://127.0.0.1:3000/list"; window.onload=function () { $.post(url,{},function (data, status) { for(var i=0;i<data.length;i++){ addDiv(); var imgs = document.getElementsByClassName('imgs')[0]; var p=imgs.getElementsByTagName('p'); var span=imgs.getElementsByTagName('span'); var pics =imgs.getElementsByTagName('img'); var name=document.createTextNode(data[i].goodname); var price=document.createTextNode('¥'+data[i].price); span[i].appendChild(name); p[i].appendChild(price); pics[i].setAttribute('src',data[i].src); } }) function addDiv() { var imgs=document.getElementsByClassName('imgs')[0]; var buttons=imgs.getElementsByClassName('buttons')[0]; var list_img=document.createElement('div'); var a1=document.createElement('a'); var good_cons=document.createElement('div'); var p1=document.createElement('p'); var a_img=document.createElement('img'); var spans=document.createElement('span'); list_img.appendChild(a1); list_img.appendChild(good_cons); list_img.appendChild(p1); a1.setAttribute('href','./car.html'); a1.appendChild(a_img); list_img.setAttribute('class','list_img'); good_cons.setAttribute('class','good_cons'); good_cons.appendChild(spans); imgs.insertBefore(list_img,buttons); } } })()
Markdown
UTF-8
7,549
3.28125
3
[]
no_license
# Configuration ## Overview Configuration provides you ability to customize your app with set of attributes. These attributes contain information required by application and used across program code. The whole structure of config data is defined in a base configuration file. In addition, your app can be configured by specifying [environment variables](#setting-config-values-using-environment-variables) or [command-line arguments](#setting-config-values-using-cli-arguments), by changing the local or specific config files, conventionally located in the `config/` folder of app projects. In terms of code perspective, work with configuration is encapsulated in [ConfigurationManagement](https://github.com/dynamic-talks/ui-platform-core/blob/master/lib/configuration-manager/modules/ConfigurationManager.js) class. It provides an interface for getting specific config data. Nested object data can be obtain with dot notation (.e.g `api.endpoint.baseUrl`). See [Accessing config in app](#accessing-config-in-app) for more details. During app lifecycle there are 2 type of configuration managers: server and client. Server config is an instance of [ServerConfigurationManager](https://github.com/dynamic-talks/ui-platform-core/blob/master/lib/configuration-manager/modules/ServerConfigurationManager.js), which initialized on server bootstraping and contains whole configuration data object. On the other hand client config is an instance of [ConfigurationManager](https://github.com/dynamic-talks/ui-platform-core/blob/master/lib/configuration-manager/modules/ConfigurationManager.js), which initialized on client apps and contains configuration data object with set of keys defined in `clientProps` of server configuration object. ## Configuration files All configuration files should be placed into `config/` folder. There 3 types of files, which have to be taken into account: - _Base config_ - define whole shape and default values of configuration. Filename - `config/base.<ext>`; - _Specific config_ - intended for defining configuration of specific app instance or environment. Such type of config data is going to override values defined by _Base config_. The filename should be passed with `-c` command-line argument as relative path to project folder on app launch (e.g. `NODE_ENV=staging node ./bin/www -c config/staging.yaml`). In case of filename is not provided, then just _Base config_ is going to be used. - _Local config_ - such type of config is intended to configure app for your local environment (e.g. your laptop). Filename `config/local.<ext>`. Since they're intended only for local use, they should not be put under VCS (in case of `git` it should be included in `.gitignore` file for that reason). `YAML` and `JSON` formats are supported for storing configuration data in files. Which format to use depends on file extension. If _Base config_ is provided in both formats (2 files) then YAML take precedence over JSON. ## Setting config values using environment variables In addition to using configuration files, you can set individual config values on the command line when you launch app by prefixing the config key names with `config_`, and separating nested key names with double-underscores (`__`). Any environment variable formatted this way will be parsed as JSON (if possible). For example, you could do the following to set the `europe.payment.supportedCreditCard` to `["Visa", "MasterCard"]` on the command line: ```bash config_europe__payment__supportedCreditCard='["Visa", "MasterCard"]' ./bin/www -c config/dev.yaml ``` > Note the use of double-quotes to indicate strings within the JSON-encoded value, and the single quotes surrounding the whole value so that it is parsed correctly. This value will be in effect only for the lifetime of this particular app instance, and will override any values in the configuration files. ## Setting config values using CLI arguments For situations where setting an environment variable on the command line may not be practical (such as some Windows systems), you can use regular command-line arguments to set configuration options. To do so, specify the name of the option prefixed by two dashes and `config.` string (`--config.`), with nested key names separated by dots. All config specific CLI arguments should be be ```bash # Set API base endpoint ./bin/www --config.api.endpint='https://apiserver.com/api/2.0' # Below argument value will be parsed as array ./bin/www --config.europe.payment.supportedCreditCard='["Visa", "MasterCard"]' ``` ## Accessing config in app Instance of `ConfigurationManager` is availabe in [IoC container](./dependency-injection.md) on both client and server environments. ### Server route example In case of server routes, you have an access to [`ServerUiApplication`](https://github.com/dynamic-talks/ui-platform-core/blob/master/lib/ui-application/server.ui-application.js) via `req.$app`. This instance has an appropriate getter for configuration: ```javascript // ..... router.get('/:productId', function(req, res) { // is ads enbaled in cofniguration // this flag is defined in `{ ads: enabled: bool }` coinfig data // so we can get that from `req.$app.config` const isAdsEnabled = req.$app.config.get('ads.enabled'); let scripts = []; if (isAdsEnabled) { scriptList.push('/js/ads.bundle.js'); } res.renderApp({ scripts }); } ``` ### React Component example In order to pass config instance from IoC container to React component as prop you can archieve it with [`connectWithIoC`](https://github.com/dynamic-talks/ui-platform-core/blob/master/lib/react-enhancers/connectWithIoC.js) enhancer: ```jsx import React from 'react'; import { ConfigurationManager } from 'ui-platform-core/lib/configuration-manager/ConfigurationManager'; import { connectWithIoC } from 'ui-platform-core/lib/react-enhancers/connectWithIoC'; const PromoMessage => ({ message }) => ( <p className="promo-msg">{message}</p> ); class PromoBlock extends React.Component { static propTypes = { config: PropTypes.instanceOf(ConfigurationManager), } render() { const messageList = this.config.get('markeing.campaigns.promos'); return ( <div className="promo-block"> {messageList.map(messageItem => <PromoMessage message={messageItem} /> )} </div> ) } } export default connectWithIoC(['config'])(PromoBlock); ``` ## Order of precedence for configuration (Cascading) The order presented from highest to lowest priority: 1. command line arguments, prefixed with `--config.` (e.g. `./bin/www --config.api.endpint='https://apiserver.com/api/2.0'`) 2. Environment variables prefixed with `config_`, and using double underlines to indicate dots (e.g. `config__api__endpint='https://apiserver.com/api/2.0' ./bin/www`) 3. Local config, which is defined in `config/local.<ext>` file. 4. Specific config file, which filename is passed with `-c` command-line argument as relative path to project folder (e.g. `NODE_ENV=staging node ./bin/www -c config/staging.yaml`) 5. Base config, which is defined in `config/base.<ext>` file. ## Reserved keys in configuration data object - `clientProps` - list of properties, which should be exposed to client configuration data object by server config manager. This key is required by `ConfigurationManager` and throw exception in case of it's absence. ## TODO - Implement logic with `local` config files - Finish implementation of reading config data from env vars and cli based on convention - Dynamic reconfiguration
Java
UTF-8
686
3.984375
4
[]
no_license
public class DisplayPatterns { public static void main(String args []) { patternA(6); patternB(6); } private static void patternA(int length) { System.out.println("\n-----------Pattern A---------------"); for (int r = 0; r < length + 1; r++) { for (int c = 1; c <= r; c++) { System.out.print(c + " "); } System.out.println(); } } private static void patternB(int length) { System.out.println("\n-----------Pattern B---------------"); for (int r = length; r > 0; r--) { for (int c =1; c <= r; c++) { System.out.print(c + " "); } System.out.println(); } } }
JavaScript
UTF-8
443
2.71875
3
[]
no_license
console.log('Lista de reproducción') alert('Creación de playlist de música') const nombrePlaylist = prompt('Ingresa el nombre de la playlist'); const cancionUno = prompt('Ingresa una canción'); const cancionDos = prompt('Ingresa una canción'); const cancionTres = prompt('Ingresa una canción'); alert(`Se ha creado la playlist '${nombrePlaylist}' con las canciones: ${cancionUno}, ${cancionDos}, ${cancionTres}. `)
Java
UTF-8
759
2.453125
2
[]
no_license
package com.company.Server; public enum Command { DELETE, SHOW, CHANGE_LOGIN, QUIT, MESSAGE, TRANSFER_FILE, HELP, SHOW_ALL_NAME, SHOW_ALL_DATE; public static Command fromString(String str){ switch (str){ case "SHOW": return Command.SHOW; case "DELETE": return Command.DELETE; case "CHANGE_LOGIN": return Command.CHANGE_LOGIN; case "QUIT": return Command.QUIT; case "TRANSFER_FILE": return Command.TRANSFER_FILE; case "HELP": return Command.HELP; case "SHOW_ALL_NAME": return Command.SHOW_ALL_NAME; case "SHOW_ALL_DATE": return Command.SHOW_ALL_DATE; default: return Command.MESSAGE; } } }
Java
UTF-8
1,989
2.53125
3
[]
no_license
package bonus.commands; import bonus.catalog.Catalog; import bonus.items.ItemsList; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import java.awt.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; /** * Class that describes the play command in our shell. */ public class ReportCommand implements isExecutable { private static final Logger logger = Logger.getLogger(ReportCommand.class.getName()); @Override public void executeCommand(List<String> args, Catalog catalog, ItemsList itemsList) throws IOException, TemplateException { File f = new File(System.getProperty("user.dir").toString() + "\\" + "project_resources" + "\\" + "source.htm"); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); /* Create and adjust the configuration singleton */ Configuration cfg = new Configuration(Configuration.VERSION_2_3_29); cfg.setDirectoryForTemplateLoading(new File("C:\\Users\\vlada\\IdeaProjects\\PALab5\\src\\main\\resources\\templates")); // Recommended settings for new projects: cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); cfg.setWrapUncheckedExceptions(true); cfg.setFallbackOnNullLoopVariable(false); Map<String, Object> root = new HashMap<>(); root.put("user", "vlad"); root.put("items",catalog.getItems()); root.put("title",catalog.getName()); root.put("path",catalog.getPath()); Template template = cfg.getTemplate("report.ftl"); template.process(root, bw); Desktop.getDesktop().browse(f.toURI()); } }
TypeScript
UTF-8
1,017
2.53125
3
[ "Apache-2.0" ]
permissive
import { Component } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; interface ComboboxItem { displayedValue: string; value: string; } @Component({ selector: 'fd-combobox-forms-example', templateUrl: 'combobox-forms-example.component.html', styleUrls: ['combobox-forms-example.component.scss'] }) export class ComboboxFormsExampleComponent { customForm = new FormGroup({ item: new FormControl(null), itemOnDropdownMode: new FormControl(null) }); dropdownValues: ComboboxItem[] = [ { displayedValue: 'Apple', value: 'AppleValue' }, { displayedValue: 'Apple', value: 'AppleValue2' }, { displayedValue: 'Banana', value: 'BananaValue' }, { displayedValue: 'Kiwi', value: 'KiwiValue' }, { displayedValue: 'Strawberry', value: 'StrawberryValue' }, { displayedValue: 'Tomato', value: 'TomatoValue' } ]; myDisplayFunction = (item: ComboboxItem): string => item?.displayedValue ?? ''; }
Markdown
UTF-8
25,351
3.140625
3
[ "MIT" ]
permissive
--- title: 途游面试 tags: - 面试 categories: - 💻 工作 - 面试 date: 2020-05-26 12:27:56 permalink: /pages/b4654d/ --- 1. python 生成器,迭代器,装饰器 [Python 面试 | 别院牧志](/python/interview/#迭代器和生成器) 2. strip/lstrip/rstrip 用法 strip: 用来去除头尾字符、空白符(包括\n、\r、\t、' ',即:换行、回车、制表符、空格) lstrip:用来去除开头字符、空白符(包括\n、\r、\t、' ',即:换行、回车、制表符、空格) rstrip:用来去除结尾字符、空白符(包括\n、\r、\t、' ',即:换行、回车、制表符、空格) - 当字符为空时 ```python >>> str = ' ab cd ' >>> str ' ab cd ' >>> str.strip() #删除头尾空格 'ab cd' >>> str.lstrip() #删除开头空格 'ab cd ' >>> str.rstrip() #删除结尾空格 ' ab cd' ``` - 当切割字符不为空 ```plain >>> str2 = '1a2b12c21' >>> str2.strip('12') #删除头尾的1和2 'a2b12c' >>> str2.lstrip('12') #删除开头的1和2 'a2b12c21' >>> str2.rstrip('12') #删除结尾的1和2 '1a2b12c' ``` 3. map/reduce/filter 用法 [Python 面试](/python/interview/#python-%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B) 4. 解释并实现单例模式 [Python 面试 | 别院牧志](/python/interview/#单例模式) 5. 查看 linux 版本如何查看,几种方法 ```bash cat /etc/redhat-release /proc/version uname -r ``` 6. 如何查看 linux 系统的配置?什么时候生效的? ```bash # cpu cat /proc/cpuinfo # memory cat /proc/meminfo # disk lsblk ``` 7. 说下 python 中的生成器如何实现的? 生成器其实是一种特殊的迭代器,不过这种迭代器更加优雅。它不需要再像类一样写 `__iter__()`和 `__next__()`方法了,只需要一个 `yiled` 关键字。 生成器一定是迭代器(反之不成立),因此任何生成器也是以一种懒加载的模式生成值。 列表生成式,range,yield [Python 面试 | 别院牧志](https://wiki.masantu.com/wiki/%F0%9F%92%BB%E5%B7%A5%E4%BD%9C/%F0%9F%90%8DPython/%E9%9D%A2%E8%AF%95/interview-of-python/#%E8%BF%AD%E4%BB%A3%E5%99%A8%E5%92%8C%E7%94%9F%E6%88%90%E5%99%A8) 8. yield 如何实现的,是什么? [Python yield 关键字在 C 层面是如何实现的](https://www.sund.site/posts/py-yield/) 我们先看一个 python 生成器函数的例子: ```python from dis import dis def func(): i = 4 yield i print i dis(func) a =func() a.next() a.next() ``` 使用 python 的库 dis 可以直接查看 python 虚拟机运行的字节码。`dis(func)`的打印如下: ```plain 6 0 LOAD_CONST 1 (4) 3 STORE_FAST 0 (i) 7 6 LOAD_FAST 0 (i) 9 YIELD_VALUE 10 POP_TOP 8 11 LOAD_FAST 0 (i) 14 PRINT_ITEM 15 PRINT_NEWLINE 16 LOAD_CONST 0 (None) 19 RETURN_VALUE ``` 我们猜测其中第二列(代表字节码偏移量)为 9 的指令`YIELD_VALUE`就是 yield 关键字的执行代码,进入 Python2.7.12 源码目录,在解释器执行字节码的主函数`PyEval_EvalFrameEx`中找到了下面一段: ```c TARGET_NOARG(YIELD_VALUE) { retval = POP(); f->f_stacktop = stack_pointer; why = WHY_YIELD; // 跳转到fast_yield处。fast_yield里处理了一下状态位然后返回结果 goto fast_yield; } ``` 其中`TARGET_NOARG`为封装了`case`语句的宏,这句话的意思是,如果字节码是`YIELD_VALUE`,就把栈顶元素赋值给`retval`,然后跳转到`fast_yield`处,`fast_yield`处代码进行了一些状态判断后直接返回了`retval`。 ### 生成器是如何记录代码返回位置的 显然,如果这时候调用代码`a.next()`就会直接返回 yield 后边的表达式结果。这对应了上面 C 代码的`fast_yield`部分,那生成器怎么记录上次执行的位置并在下一次调用`a.next()`的时候从上次的位置继续执行的呢? Python 在解释代码时,是将代码块加载为一个叫 PyFrameObject 的对象,这个对象代表了当前运行的栈帧。PyFrameObject 里有个`f_lasti`变量用于保存代码当前执行到了字节码的哪个位置。在第二次执行`a.next()`时,生成器对象把之前携带了`f_lasti`的 PyFrameObject 当参数传给`PyEval_EvalFrameEx`,在`PyEval_EvalFrameEx`里的执行一个 JUMPTO 就直接跳转到了上一次结束生成器时的字节码位置: ```c PyObject * PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) { ... #define FAST_DISPATCH() \ { \ if (!lltrace && !_Py_TracingPossible) { \ f->f_lasti = INSTR_OFFSET(); \ goto *opcode_targets[*next_instr++]; \ } \ // 跳转到fast_next_opcode处 goto fast_next_opcode; \ } ... fast_next_opcode: f->f_lasti = INSTR_OFFSET(); /* line-by-line tracing support */ if (_Py_TracingPossible && tstate->c_tracefunc != NULL && !tstate->tracing) { ... /* Reload possibly changed frame fields */ // 按照f->f_lasti中的偏移量跳转字节码 JUMPTO(f->f_lasti); } ``` 其中`INSTR_OFFSET`宏正是字节码的偏移量。 ```c #define INSTR_OFFSET() ((int)(next_instr - first_instr)) // co->co_code里保存的是字节码 first_instr = (unsigned char*) PyString_AS_STRING(co->co_code); next_instr = first_instr + f->f_lasti + 1; ``` 所以生成器对象每次执行结束都把字节码的偏移量记录下来,并把运行状态保存在 PyFrameObject 里,下一次运行时生成器时,python 解释器直接按照偏移量寻找下一个字节码指令。 9. 说下你如何存放用户头像的,数据库中如何存放的,字段是什么? 数据库对图片文件以 SHA512 作为 primary key,数据库里只存储 SHA512,然后在线存储的时候文件名使用 SHA512。 之所以选这么个方案原因如下: 1. 我们用 AWS S3 存储。(key-value 存储) 2. 假设是对于用户头像这类文件,文件名不重要,扩展名也不重要,因为显示在页面上唯一依赖的就是 URL 和 S3 服务器返回的 content-type header,而后者在上传的时候已经建立。 3. 要维持一致性,变量越少越好。比如说如果你要维持 1.jpg 和 `https://s3.bucket.com/1.jpg` 就没有维持 1.jpg 容易。对于 S3 来说,URL 大部分都是确定的,因此真正会变化的部分只是文件名(key 名)。 4. 因为扩展名不重要,所以维持 1.jpg 不如维持 1。 5. 因为文件名不重要,所以维持 1 不如维持文件指纹,也就是 MD5/SHA512 之类的。 6. 使用 SHA512 直接作为数据库主键、S3 Key 可以最小化需要一致性的变量。 7. 使用 SHA512 的更大的好处是免除了维持一致性的必要,因为 SHA512 的特性几乎可以认为一个特别的 SHA512 对应了一个特别的文件,因此算法天然保证了在任何地方对应同一个文件都有一致性,无论是 S3 Key,数据库还是别的地方。 事实上我们的系统使用这个方案存储所有文件,不只是用户头像。因为 SHA512 几乎与文件一一对应的特性从而天然维持了一致性,实在是太方便了。比如用这种存储如果两个用户上传了同一个图片做头像,那你就直接避免了重复存储的问题(它们会有相同的键值)。_代价是对于删除处理你需要采用别的策略判断依赖性,比如只有在一个文件不被任何地方引用的时候才能删除。_ 参见:[数据库字段应该如何储存用户头像 URL? - 知乎](https://www.zhihu.com/question/333821544) 10. 你的 uwsgi 怎么用的多线程实现的 11. 手写个代码 :迷宫问题 12. 关联查询 join 什么时候用? JOIN 在内连接时,可以不使用,其它类型连接必须使用。如: ```sql SELECT * FROM TABLEA INNER JOIN TABLEB ON A.ID=B.ID ``` 可以这样写: ```sql SELECT * FROM TABLEA,TABLEB WHERE A.ID=B.ID ``` JOIN 有以下几种类型: ### INNER(内连接) 指定返回每对匹配的行。废弃两个表中不匹配的行。如果未指定联接类型,则这是默认设置。 ### FULL(全连接) 指定在结果集中包含左表或右表中不满足联接条件的行,并将对应于另一个表的输出列设为 NULL。这是对通常由 INNERJOIN 返回的所有行的补充。 ### LEFT(左连接) 指定在结果集中包含左表中所有不满足联接条件的行,且在由内联接返回所有的行之外,将另外一个表的输出列设为 NULL。 ### RIGHT(右连接) 指定在结果集中包含右表中所有不满足联接条件的行,且在由内联接返回的所有行之外,将与另外一个表对应的输出列设为 NULL。 ### CROSS JOIN(交叉连接) 得到连接表符合 WHERE 子句的条件的记录数的乘积,即第一个表的每一个记录都与别一个表的所有记录连接出一个新的记录。 交叉连接不带 ON 子句,其它连接必须有 ON 子句。 13. 存储过程是怎么实现的? ```plain procedure 英[prəˈsiːdʒə(r)] 美[prəˈsiːdʒər] ``` 我们常用的操作数据库语言 SQL 语句在执行的时候需要要先编译,然后执行,而存储过程(Stored Procedure)是一组为了完成特定功能的 SQL 语句集,经编译后存储在数据库中,用户通过指定存储过程的名字并给定参数(如果该存储过程带有参数)来调用执行它。 一个存储过程是一个可编程的函数,它在数据库中创建并保存。它可以有 SQL 语句和一些特殊的控制结构组成。当希望在不同的应用程序或平台上执行相同的函数,或者封装特定功能时,存储过程是非常有用的。数据库中的存储过程可以看做是对编程中面向对象方法的模拟。它允许控制数据的访问方式。 存储过程通常有以下优点: 1. 存储过程增强了 SQL 语言的功能和灵活性。存储过程可以用流控制语句编写,有很强的灵活性,可以完成复杂的判断和较复杂的运算。 2. 存储过程允许标准组件是编程。存储过程被创建后,可以在程序中被多次调用,而不必重新编写该存储过程的 SQL 语句。而且数据库专业人员可以随时对存储过程进行修改,对应用程序源代码毫无影响。 3. 存储过程能实现较快的执行速度。如果某一操作包含大量的 Transaction-SQL 代码或分别被多次执行,那么存储过程要比批处理的执行速度快很多。因为存储过程是预编译的。在首次运行一个存储过程时查询,优化器对其进行分析优化,并且给出最终被存储在系统表中的执行计划。而批处理的 Transaction-SQL 语句在每次运行时都要进行编译和优化,速度相对要慢一些。 4. 存储过程能过减少网络流量。针对同一个数据库对象的操作(如查询、修改),如果这一操作所涉及的 Transaction-SQL 语句被组织程存储过程,那么当在客户计算机上调用该存储过程时,网络中传送的只是该调用语句,从而大大增加了网络流量并降低了网络负载。 5. 存储过程可被作为一种安全机制来充分利用。系统管理员通过执行某一存储过程的权限进行限制,能够实现对相应的数据的访问权限的限制,避免了非授权用户对数据的访问,保证了数据的安全。 ### 语法 ```plain CREATE [DEFINER = { user | CURRENT_USER }]  PROCEDURE sp_name ([proc_parameter[,...]]) [characteristic ...] routine_body proc_parameter: [ IN | OUT | INOUT ] param_name type characteristic: COMMENT 'string' | LANGUAGE SQL | [NOT] DETERMINISTIC | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA } | SQL SECURITY { DEFINER | INVOKER } routine_body:   Valid SQL routine statement [begin_label:] BEGIN   [statement_list]     …… END [end_label] ``` - [MySQL 存储过程详解 mysql 存储过程 - crazyYong - 开发者的网上家园](https://www.cnblogs.com/crazylqy/p/4235566.html) - [MySQL 存储过程 | 菜鸟教程](https://www.runoob.com/w3cnote/mysql-stored-procedure.html) 1. 索引如何实现的?什么时候用索引,什么时候不用索引? 2. 简单做下自我介绍,  3. 说一下你开发过的项目,挑一个说下你都做了什么模块与功能   4. 你了解过我们公司吗? 我们公司开发的游戏,你玩过吗?   5. 如果你需要学习一种新技术,你会怎么做?  1. 分析问题,确定要学习的内容(最重要的部分) 2. 重复练习 3. 与已知知识找相关联性 4. 文档、书籍、论坛…… 5. 实践、分享 6. 你之前的公司几点上班? 有加班吗?   7. 你会前端吗? 你公司前后端分离吗?   8. 你常用的数据库有哪些?   9. 你开发的这个项目上线了吗? 每天的访问量是多少? 数据库中有多少用户?  10. python 的数据类型?   str,Number(数字)Python3 支持 int、float、bool、complex(复数),list,set,tuple,dict  [Python3 基本数据类型 | 菜鸟教程](https://www.runoob.com/python3/python3-data-type.html) 9. 你之前的项目是在什么开发环境上进行开发的? 怎么进行部署的?   10. 说一下你的某个项目中,数据库中有哪些表? 举例说明表与表是怎么进行关联的? 11. 你有什么问题想要问我的吗? --- 1. 网络的七层协议、HTTP、TCP、IP 各在哪一层? ![七层模型](https://cdn.jsdelivr.net/gh/masantu/statics/images/OSI-figure_1.png)  来源:[科来网络通讯协议图免费下载](http://www.colasoft.com.cn/download/protocols_map.php) ![文字版](https://cdn.jsdelivr.net/gh/masantu/statics/images/OSI-7-layers.jpg)     IP 协议位于网络层,TCP/UDP 协议位于传输层,HTTP 位于应用层。 1. HTTP 与 TCP 的区别? TPC/IP 协议是传输层协议,主要解决数据如何在网络中传输;而 HTTP 是应用层协议,主要解决如何包装数据。  3. restful 风格   Representational State Transfer:(资源)表现层状态转移 3. 假如你的数据库版本是 1.0 的,一张表的字段个数为 10 个。那么现在用的版本是 1.1 的,想要在表中进行增删改查,有哪些方式? (我当时懵了,直接说了句我修改了数据库脚本,然后人家就问我除了这种方式,还有呢?)   4. redis 中有哪些数据类型? hash 类型怎么设置值?   [Redis | 别院牧志](https://wiki.masantu.com/wiki/%F0%9F%92%BB%E5%B7%A5%E4%BD%9C/%E6%95%B0%E6%8D%AE%E5%BA%93/Redis) 5. 非关系型数据库,例如 Mongodb,怎么去关联两张表?   6. 什么是解释器? 什么是编译器? 7. 你用过 Python 的哪些版本?说一下 2.x 与 3.x 的不同   [Python 2 和 Python 3 有哪些主要区别? - 知乎](https://www.zhihu.com/question/19698598) [Python2.x 与 3.x 版本区别 | 菜鸟教程](https://www.runoob.com/python/python-2x-3x.html) 8. C++了解吗?   9. 你怎样理解 Python 面向对象? 举例说明什么是多态?   说一下你是怎么实现 python 的封装的?   10. 你在设计接口的时候,需要考虑哪些问题?  [接口设计需要考虑哪些方面_weixin_34414196 的博客-CSDN 博客](https://blog.csdn.net/weixin_34414196/article/details/92105613)  11. 你做过类似优化的工作吗? (我当时顺口说了句数据库的优化),那么您是怎么进行数据库的优化的?  多线程  12. 在多个用户同时发起对同一个商品的下单请求时,先查询商品库存,再修改商品库存,会出现资源竞争问题,导致库存的最终结果出现异常。 例如:id 为 16 的商品的库存为 10,两人同时购买,每人买 5 件,如果产生并发问题,两人下单都成功,但是库存变成了 5。怎么解决这个问题?  13. GET 与 POST 的区别?   POST 方法可以获取到数据吗?    body 与 form 表单、data 的区别?   14. 你用过的常见的算法有哪些? 15. 什么是装饰器? 利用装饰器的好处? 手写一个装饰器 16. 手写一个单例模式   16. 你打印过 HTTP 吗? 17. 你是怎么处理高并发问题的? 18. 你的项目是怎么部署的?说一下一个项目部署的步骤 (根据简历的实际情况,我的是,Django+Nginx+Uwsgi)   a. 说一下 Nginx 的特点    b. 一个请求进来的时候,你是怎么保证你的服务器是开启的?   c.如果你的服务器是开启的,但是执行 sql 语句的代码发生了问题,会怎么样? 会发生什么? 19. 对比一下 Django 和 Flask 有什么优缺点? ## 本人面试题目 - 基础知识 1. tuple 和 list 区别并举例 2. 深拷贝和浅拷贝的区别并举例 3. 列表推导式 内字典列表将字典的 value 组成新列表 4. Python2 与 Python3 的区别 - shell 1. 查找含有指定字符的文件名 2. 查找含有指定字符内容的文件 ```shell # 查找当前目录下含有指定字符串的文件 find . -type f -print |xargs grep "python" ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/test_utils_md4.py:# test pure-python MD4 implementation ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/test_utils.py: # confirmed for: cpython 2.7.9, cpython 3.4, pypy, pypy3, pyston ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/test_totp.py:# XXX: python 3 changed what error base64.b16decode() throws, from TypeError to base64.Error(). ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/test_totp.py: # Workaround for python 3.6.0 issue -- ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/test_totp.py: # (Appears to be bug http://bugs.python.org/issue29100) ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/test_handlers.py: # https://github.com/bdd/fshp-is-not-secure-anymore/blob/master/python/test.py ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/backports.py: # python 2.7 and python 3.2 both have unittest2 features (at least, the ones we use) ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/test_crypto_builtin_md4.py:# test pure-python MD4 implementation ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/test_crypto_builtin_md4.py: # not supported - ssl probably missing (e.g. ironpython) ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/test_crypto_builtin_md4.py: # Temporarily make lookup_hash() use builtin pure-python implementation, ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/tests/test_crypto_scrypt.py: # (46s under pypy, ~5m under cpython) ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/passlib/_data/wordsets/eff_prefixed.txt:python # 查找指定文件中含有特定字符串的行 find . | grep config.xml | xargs grep "specified field" ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/flask/json/tag.py: def to_python(self, value): ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/flask/json/tag.py: def to_python(self, value): ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/flask/json/tag.py: def to_python(self, value): ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/flask/json/tag.py: def to_python(self, value): ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/flask/json/tag.py: return self.tags[key].to_python(value[key]) Binary file ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/flask/json/__pycache__/tag.cpython-37.pyc matches Binary file ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/flask/__pycache__/app.cpython-37.pyc matches Binary file ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/flask/__pycache__/cli.cpython-37.pyc matches Binary file ./.virtualenvs/iyblog-_wyXyExX/lib/python3.7/site-packages/flask/__pycache__/helpers.cpython-37.pyc matches # 查找当前目录中包含指定字段的所有文件(返回带颜色标识) grep -RnI "specified field" . --color ./.virtualenvs/iyblog/lib/python3.7/encodings/cp950.py:2:# cp950.py: Python Unicode Codec for CP950 ./.virtualenvs/iyblog/lib/python3.7/encodings/euc_jis_2004.py:2:# euc_jis_2004.py: Python Unicode Codec for EUC_JIS_2004 ./.virtualenvs/iyblog/lib/python3.7/encodings/euc_jisx0213.py:2:# euc_jisx0213.py: Python Unicode Codec for EUC_JISX0213 ./.virtualenvs/iyblog/lib/python3.7/encodings/euc_jp.py:2:# euc_jp.py: Python Unicode Codec for EUC_JP ./.virtualenvs/iyblog/lib/python3.7/encodings/euc_kr.py:2:# euc_kr.py: Python Unicode Codec for EUC_KR ./.virtualenvs/iyblog/lib/python3.7/encodings/gb18030.py:2:# gb18030.py: Python Unicode Codec for GB18030 ./.virtualenvs/iyblog/lib/python3.7/encodings/gb2312.py:2:# gb2312.py: Python Unicode Codec for GB2312 ./.virtualenvs/iyblog/lib/python3.7/encodings/gbk.py:2:# gbk.py: Python Unicode Codec for GBK ./.virtualenvs/iyblog/lib/python3.7/encodings/hex_codec.py:1:"""Python 'hex_codec' Codec - 2-digit hex content transfer encoding. ./.virtualenvs/iyblog/lib/python3.7/encodings/hp_roman8.py:1:""" Python Character Mapping Codec generated from 'hp_roman8.txt' with gencodec.py. ``` - 编程 6.内字典列表中字典的指定 key 按照顺序排列(使用 lambda) ```python a_list.sort(key=lambda x:x.get('name')) ``` 1. 装饰器及其两种调用方式 - 数据库和 sql 1. redis 的存储类型及应用举例 2. 用户充值表 pay_tb(uid,payment,time) 查询 2018 年充值金额总额小于 1 万元的用户的 uid 及其充值总额前 10 的数据 3. 查询数据库电话号码并且将中间四位用**代替 ```sql CREATE TABLE users ( id varchar(300), name varchar(300), phone varchar(255) ); INSERT INTO users ( id , name , phone ) VALUES ('1', 'tom', '001-901-128-0479'), ('2', 'peter', '590-367-4360'), ('3', 'sam', '6716586922'), ('4', 'hans', '+1-319-510-3818-4500'); mysql> select * from users; +------+-------+----------------------+ | id | name | phone | +------+-------+----------------------+ | 1 | tom | 001-901-128-0479 | | 2 | peter | 590-367-4360 | | 3 | sam | 6716586922 | | 4 | hans | +1-319-510-3818-4500 | +------+-------+----------------------+ 4 rows in set (0.00 sec) # REPLACE + SUBSTR 方式 mysql> select id,name,REPLACE(phone,SUBSTR(phone,4,4),'****') as tel from users; +------+-------+----------------------+ | id | name | tel | +------+-------+----------------------+ | 1 | tom | 001****-128-0479 | | 2 | peter | 590****-4360 | | 3 | sam | 671****922 | | 4 | hans | +1-****510-3818-4500 | +------+-------+----------------------+ 4 rows in set (0.00 sec) # INSERT 方式 mysql> select id,name,INSERT(phone,4,4,'****') as tel from users; +------+-------+----------------------+ | id | name | tel | +------+-------+----------------------+ | 1 | tom | 001****-128-0479 | | 2 | peter | 590****-4360 | | 3 | sam | 671****922 | | 4 | hans | +1-****510-3818-4500 | +------+-------+----------------------+ 4 rows in set (0.01 sec) ``` 表达式解释:select+字段名+insert(手机号字段名,从第几位开始,替换几位,替换字符) as phoneNum from +表名; 参见:[mysql sql 语句隐藏手机号码中间四位的方法_Mysql_脚本之家](https://www.jb51.net/article/106816.htm) 4. 索引原则及 MySQL 除了 innoDB 之外的引擎并对比
Markdown
UTF-8
380
3.265625
3
[]
no_license
--- layout: post title: Set union date: '2010-02-17T08:12:48+01:00' tags: - ruby - beginner tumblr_url: http://rubyquicktips.com/post/394315590/set-union --- Join two arrays and remove all the duplicates with the pipe operator (|). [ "a", "b", "c" ] | [ "c", "d", "a" ] # => ["a", "b", "c", "d"] This is taken from the ‘Programming Ruby’ Book, where you can find out more.
C#
UTF-8
429
2.53125
3
[]
no_license
using NUnit.Framework; namespace AlgoSolving.Task0322_Coin_Change { public class Tests { [Test] public void AcceptanceTest1() { Assert.That(new Solution().CoinChange(new[] { 1, 2, 5 }, 11), Is.EqualTo(3)); } [Test] public void AcceptanceTest2() { Assert.That(new Solution().CoinChange(new[] { 2 }, 3), Is.EqualTo(-1)); } } }
Java
UTF-8
1,151
3.34375
3
[]
no_license
package ch3; import java.util.Arrays; import java.util.stream.Collectors; public class SortSample { private int[] digits; public SortSample(int[] digits) { this.digits = new int[digits.length]; System.arraycopy(digits, 0, this.digits, 0, digits.length); } public void sort() { for (int x = 0; x < digits.length - 1; x++) { int m = x; for (int y = x + 1; y < digits.length; y++) { if (digits[m] > digits[y]) { m = y; } } assert isMin(m, x, digits.length); int v = digits[m]; digits[m] = digits[x]; digits[x] = v; assert isSorted(0, x + 1); } } @Override public String toString() { return Arrays.stream(digits).mapToObj(Integer::toString).collect(Collectors.joining(", ", "[ ", "]")); } private boolean isMin(int pos, int start, int end) { for (int i = start; i < end; i++) { if (digits[pos] > digits[i]) { return false; } } return true; } private boolean isSorted(int start, int end) { for (int i = start; i < end; i++) { if (digits[i] > digits[i + 1]) { return false; } } return true; } }
TypeScript
UTF-8
5,806
3.0625
3
[]
no_license
import { Record, StateRecord, InboundRecord, OutboundRecord, isStateRecord, isInboundRecord, isOutboundRecord, newStateRecord, newInboundRecord, newOutboundRecord, } from "./db"; import { Processor, Event } from "./processor"; export interface GetOutput<T> { record: Record; item: T; } export interface ChangeOutput<T> { seq: number; item: T; pastOutboundEvents: Array<Event<any>>; newOutboundEvents: Array<Event<any>>; } // DB is the database access required by Facet<T>. Use EventDB. export interface DB { getState(id: string): Promise<Record>; getRecords(id: string): Promise<Array<Record>>; putState( state: StateRecord, previousSeq: number, newInboundEvents: Array<InboundRecord>, newOutboundEvents: Array<OutboundRecord>, ): Promise<void>; } // recordsOutput is the return type of the records method. interface RecordsOutput { state: StateRecord | null; inboundEvents: Array<InboundRecord>; outboundEvents: Array<OutboundRecord>; } // A Facet is a type of record stored in a DynamoDB table. It's constructed of a // "state" record that contains a view of the up-to-date item, multiple inbound // event records that result in a changes to the item, and outbound event records that // are used to send messages asynchronously using DynamoDB Streams. This allows messages // to be queued for delivery at the same time as the transaction is comitted, removing // the risk of an item being updated, but a message not being sent (e.g. because SQS // was temporarily unavailable). export class Facet<T> { name: string; db: DB; processor: Processor<T>; constructor(name: string, db: DB, processor: Processor<T>) { this.name = name; this.db = db; this.processor = processor; } async get(id: string): Promise<GetOutput<T> | null> { const state = await this.db.getState(id); return state ? ({ record: state, item: JSON.parse(state._itm) as T, } as GetOutput<T>) : null; } private async records(id: string): Promise<RecordsOutput> { const records = await this.db.getRecords(id); const result = { inboundEvents: new Array<InboundRecord>(), outboundEvents: new Array<OutboundRecord>(), } as RecordsOutput; if (records) { records.forEach((r) => { if (isInboundRecord(r)) { result.inboundEvents.push(r); return; } if (isOutboundRecord(r)) { result.outboundEvents.push(r); return; } if (isStateRecord(r)) { result.state = r as StateRecord; } }); } result.inboundEvents = sortRecords(result.inboundEvents); return result; } // append new event(s) to an item. This method executes two database commands, // one to retrieve the current state value, and one to put the updated state back. async append(id: string, ...newInboundEvents: Array<Event<any>>): Promise<ChangeOutput<T>> { const stateRecord = await this.get(id); const state = stateRecord ? stateRecord.item : null; const seq = stateRecord ? stateRecord.record._seq : 1; return this.appendTo(id, state, seq, ...newInboundEvents); } // appendTo appends new events to an item that has already been retrieved from the // database. This method executes a single database command to update the state // record. async appendTo(id: string, state: T | null, seq: number, ...newInboundEvents: Array<Event<any>>) { return this.calculate(id, state, seq, new Array<InboundRecord>(), ...newInboundEvents); } // recalculate all the state by reading all previous records in the facet item and // processing each inbound event record. This method may execute multiple Query operations // and a single put operation. async recalculate(id: string, ...newInboundEvents: Array<Event<any>>): Promise<ChangeOutput<T>> { // Get the records. const records = await this.records(id); const seq = records.state ? records.state._seq : 0; return this.calculate(id, null, seq, records.inboundEvents, ...newInboundEvents); } // calculate the state. private async calculate( id: string, state: T | null, seq: number, pastInboundEvents: Array<InboundRecord>, ...newInboundEvents: Array<Event<any>> ): Promise<ChangeOutput<T>> { const pastEvents = pastInboundEvents.map((e) => new Event<any>(e._typ, JSON.parse(e._itm))); const newInboundEventsSequence = newInboundEvents.map((e) => new Event(e.type, e.event)); // Process the events. const processingResult = this.processor.process(state, pastEvents, newInboundEventsSequence); // Create new records. const now = new Date(); const hr = newStateRecord( this.name, id, seq + newInboundEvents.length, processingResult.state, now, ); const newInboundRecords = newInboundEvents.map((e, i) => newInboundRecord(this.name, id, seq + 1 + i, e.type, e.event, now), ); const newOutboundRecords = processingResult.newOutboundEvents.map((e, i) => newOutboundRecord(this.name, id, seq + newInboundEvents.length, i, e.type, e.event, now), ); // Write the new records to the database. await this.db.putState(hr, seq, newInboundRecords, newOutboundRecords); return { seq: hr._seq, item: processingResult.state, pastOutboundEvents: processingResult.pastOutboundEvents, newOutboundEvents: processingResult.newOutboundEvents, } as ChangeOutput<T>; } } // sortRecords sorts event records by their sequence number ascending. const sortRecords = (eventRecords: Array<Record>): Array<Record> => eventRecords.sort((a, b) => { if (a._seq < b._seq) { return -1; } if (a._seq === b._seq) { return 0; } return 1; });
C++
UTF-8
1,101
3.421875
3
[]
no_license
#include <iostream> #include <algorithm> #include <string> #include "Heap.h" using namespace std; template <class T> void heapSort1(T arr[], int n) { MaxHeap<T> maxHeap = MaxHeap<T>(n); for (int i = 0; i < n; ++i) { maxHeap.insert(arr[i]); } for (int i = n - 1; i >= 0; --i) { arr[i] = maxHeap.extractMax(); } } template <class T> void heapSort2(T arr[], int n) { MaxHeap<T> maxHeap = MaxHeap<T>(arr, n); for (int i = n - 1; i >= 0; --i) { arr[i] = maxHeap.extractMax(); } } template <class T> void shiftDown(T arr, int n, int k) { while (2 * k + 1 < n) { int j = 2 * k + 1; if (j + 1 < n && arr[j] < arr[j + 1]) ++j; if (arr[k] > arr[j]) break; swap(arr[k], arr[j]); k = j; } } template <class T> void heapSort(T arr[], int n) { for (int i = (n - 1) / 2; i >= 0; --i) { __shiftDown(arr, n, i); } for (int i = n - 1; i > 0; --i) { swap(arr[0], arr[i]); __shiftDown(arr, i, 0); } } int main() { int a[100]; for (int i = 0; i < 100; ++i) { a[i] = rand() % 1000; } heapSort1(a, 100); for (auto i : a) { cout << i << " "; } cout << endl; }