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
Markdown
UTF-8
4,962
2.546875
3
[ "MIT" ]
permissive
# Requerio: predictable client-side state + server-side testability [![Known Vulnerabilities][snyk-image]][snyk-url] [![Linux Build Status][linux-image]][linux-url] [![Mac Build Status][mac-image]][mac-url] [![Windows Build Status][windows-image]][windows-url] [![Coverage Status][coveralls-image]][coveralls-url] [![License][license-image]][license-url] While Requerio was named with Cheerio in mind, Cheerio is no longer recommended for server-side tests. Server-side tests should use jQuery with <a href="https://www.npmjs.com/package/jsdom" target="_blank">JSDOM</a>, or any other DOM emulator. #### Install: ```shell npm install requerio redux jquery jsdom ``` #### Declare `$`: ```javascript const {JSDOM} = require('jsdom'); const html = fs.readFileSync('./index.html'), 'utf8'); const {window} = new JSDOM(html); global.window = window; global.document = window.document; const $ = global.$ = require('jquery'); ``` ##### - or - ```html <script src="jquery.min.js"></script> ``` #### Declare `Redux`: ```javascript const Redux = global.Redux = require('redux'); ``` ##### - or - ```html <script src="redux.min.js"></script> ``` #### Declare `Requerio`: ```javascript const Requerio = require('requerio'); ``` ##### - or - ```html <script src="requerio.min.js"></script> ``` #### Declare `$organisms`: At declaration, organisms are just empty namespaces. ```javascript const $organisms = { '#yoda': null, '.midi-chlorian': null }; ``` #### Instantiate `requerio`: ```javascript const requerio = window.requerio = new Requerio($, Redux, $organisms); ``` #### Initialize `requerio`: ```javascript requerio.init(); ``` #### Use: ```javascript // During initialization, the null `$organisms['#yoda']` underwent // inception into Requerio organism `requerio.$orgs['#yoda']`. This // organism has properties, methods, and state. It is home to the // `.midi-chlorian` organisms. (A productive biome would want them to // be symbionts and not parasites!) To demonstrate that `#yoda` is // alive and stateful, let's dispatch a `css` action to give it a // `color:green` css property. requerio.$orgs['#yoda'].dispatchAction('css', {color: 'green'}); // This action will turn the organism's text green in the browser. // We can observe its state after dispatching the action. const mainState = requerio.$orgs['#main'].getState(); // In Node, we can test to ensure the action updated the state correctly. assert.equal(mainState.css.color, 'green'); ``` [Why Requerio?](docs/why-requerio.md) [API docs](docs/README.md) ### Methods supported: * [addClass](docs/methods.md#addclassclasses) * [after](docs/methods.md#aftercontent) * [append](docs/methods.md#appendcontent) * [attr](docs/methods.md#attrattributes) * [before](docs/methods.md#beforecontent) * [css](docs/methods.md#cssproperties) * [data](docs/methods.md#datakeyvalues) * [detach](docs/methods.md#detach) * [empty](docs/methods.md#empty) * [height](docs/methods.md#heightvalue) * [html](docs/methods.md#htmlhtmlstring) * [prepend](docs/methods.md#prependcontent) * [prop](docs/methods.md#propproperties) * [remove](docs/methods.md#remove) * [removeClass](docs/methods.md#removeclassclasses) * [removeData](docs/methods.md#removedataname) * [scrollLeft](docs/methods.md#scrollleftvalue) * [scrollTop](docs/methods.md#scrolltopvalue) * [setActiveOrganism](docs/methods.md#setactiveorganismselector) * [setBoundingClientRect](docs/methods.md#setboundingclientrectboundingclientrect) * [text](docs/methods.md#texttext) * [toggleClass](docs/methods.md#toggleclassclasses) * [val](docs/methods.md#valvalue) * [width](docs/methods.md#widthvalue) * [blur](docs/methods.md#blur) * [focus](docs/methods.md#focus) #### See also the <a href="https://github.com/electric-eloquence/requerio/tree/master/examples" target="_blank">code examples</a>. [snyk-image]: https://snyk.io/test/github/electric-eloquence/requerio/master/badge.svg [snyk-url]: https://snyk.io/test/github/electric-eloquence/requerio/master [linux-image]: https://github.com/electric-eloquence/requerio/workflows/Linux%20build/badge.svg?branch=master [linux-url]: https://github.com/electric-eloquence/requerio/actions?query=workflow%3A"Linux+build" [mac-image]: https://github.com/electric-eloquence/requerio/workflows/Mac%20build/badge.svg?branch=master [mac-url]: https://github.com/electric-eloquence/requerio/actions?query=workflow%3A"Mac+build" [windows-image]: https://github.com/electric-eloquence/requerio/workflows/Windows%20build/badge.svg?branch=master [windows-url]: https://github.com/electric-eloquence/requerio/actions?query=workflow%3A"Windows+build" [coveralls-image]: https://img.shields.io/coveralls/electric-eloquence/requerio/master.svg [coveralls-url]: https://coveralls.io/r/electric-eloquence/requerio [license-image]: https://img.shields.io/github/license/electric-eloquence/requerio.svg [license-url]: https://raw.githubusercontent.com/electric-eloquence/requerio/master/LICENSE
JavaScript
UTF-8
292
3.703125
4
[]
no_license
/* Exercise #1 Create a for loop that prints out the numbers 1 to 100 in the console. */ for(var i=0;i<100;i++){ console.log(i); } /* Exercise #2 Write a loop that makes seven calls to console.log to output the following triangle: for() # ## ### #### ##### ###### ####### */ for('#' * i)
Markdown
UTF-8
861
3.046875
3
[ "MIT" ]
permissive
--- title: Telegram Bot description: An ExpressJS server with a Telegram bot tags: - express - telegraf - typescript --- # Telegram bot example This example starts a [Telegram](https://telegram.org/) bot on an [ExpressJS](https://expressjs.com/) server. [![Deploy on Railway](https://railway.app/button.svg)](https://railway.app/new?template=https%3A%2F%2Fgithub.com%2Frailwayapp%2Fexamples%2Ftree%2Fmaster%2Fexamples%2Ftelegram-bot&envs=TELEGRAM_BOT_TOKEN) ## ✨ Features - Telegraf (library to interact with the Telegram bot API) - Express - TypeScript ## 💁‍♀️ How to use - Install dependencies `yarn` - Connect to your Railway project `railway link` - Start the development server `railway run yarn dev` ## 📝 Notes The server started launches a Telegram bot with a couple of basic commands. The code is located at `src/index.js`.
JavaScript
UTF-8
859
2.984375
3
[]
no_license
import moment from 'moment' const dateUtil = {} /** * 计算指定时间与今天的时间差 * @param time 指定时间 * @return 相差时间 (2天前) */ dateUtil.timeDifferenceToContent = (time) => { const nowDate = moment(moment(new Date()).format('YYYY-MM-DD HH:mm:ss')) let diff = nowDate.diff(time, 'years') if (diff > 0) { return diff + '年前' } diff = nowDate.diff(time, 'months') if (diff > 0) { return diff + '月前' } diff = nowDate.diff(time, 'day') if (diff > 0) { return diff + '天前' } diff = nowDate.diff(time, 'hours') if (diff > 0) { return diff + '小时前' } diff = nowDate.diff(time, 'minutes') if (diff > 0) { return diff + '分钟前' } diff = nowDate.diff(time, 'seconds') if (diff > 0) { return diff + '秒前' } return '刚刚' } export default dateUtil
Java
UTF-8
258
2.890625
3
[]
no_license
public class CashRebate extends CashSuper { private double moenyRebate; public CashRebate(String moneyRebate){ this.moenyRebate = Double.parseDouble(moneyRebate); } public double acceptCash(double money){ return money * this.moenyRebate; } }
Ruby
UTF-8
876
2.6875
3
[]
no_license
# frozen_string_literal: true class ViaCep include ::HTTParty def self.get(cep: nil) response = HTTParty.get("https://viacep.com.br/ws/#{cep}/json/") object = response.parsed_response ViaCep.serializer(object: object) rescue StandardError {} end def self.serializer(object: nil) # Retorno padrão da viacep para quando não encontra uma cidade if object['localidade'].present? state = ::Location::State.by_uf(object['uf']).first city = ::Location::City.by_state_id(state.id).by_name(object['localidade']).first end { zipcode: object.try(:[], 'cep'), street: object.try(:[], 'logradouro'), district: object.try(:[], 'bairro'), state: { id: state.try(:id), uf: state.try(:uf) }, city: { id: city.try(:id), name: city.try(:name) } } end end
TypeScript
UTF-8
844
2.59375
3
[]
no_license
import { expect } from 'chai'; import { of,} from 'rxjs'; import 'mocha'; import {UnderGrad, Class} from './app' describe('Test for observable.ts', () =>{ const student1 = new UnderGrad("Dan", 2779638); const class1 = new Class("CS44", "Fall 2019"); student1.addClass(class1); const student2 = new UnderGrad("Dyl", 2779639); var studentsArr = [student1, student2]; const students = of(studentsArr); it('should assert the students in the right order', () =>{ students.subscribe(item => { expect(item).to.equal(studentsArr) }); }) const student3 = new UnderGrad("Gabe", 2779640); studentsArr.push(student3); it('should assert the students in the right order', () =>{ students.subscribe(item => { expect(item).to.equal(studentsArr) }); }) });
Go
UTF-8
8,711
2.5625
3
[]
no_license
package datastore import ( "context" "errors" "github.com/AlekSi/pointer" "github.com/gocraft/dbr/v2" "github.com/videocoin/marketplace/internal/model" "github.com/videocoin/marketplace/pkg/dbrutil" "github.com/videocoin/marketplace/pkg/random" "strings" "time" ) var ( ErrAccountNotFound = errors.New("account not found") ) type UpdateAccountFields struct { Username *string Name *string Bio *string CustomURL *string YTUsername *string ImageCID *string CoverCID *string } func (f *UpdateAccountFields) IsEmpty() bool { return f != nil && f.Username == nil && f.Name == nil && f.ImageCID == nil && f.CoverCID == nil && f.Bio == nil && f.CustomURL == nil && f.YTUsername == nil } type AccountDatastore struct { conn *dbr.Connection table string } func NewAccountDatastore(ctx context.Context, conn *dbr.Connection) (*AccountDatastore, error) { return &AccountDatastore{ conn: conn, table: "accounts", }, nil } func (ds *AccountDatastore) Create(ctx context.Context, account *model.Account) error { var err error tx, ok := dbrutil.DbTxFromContext(ctx) if !ok { sess := ds.conn.NewSession(nil) tx, err = sess.Begin() if err != nil { return err } defer func() { err = tx.Commit() tx.RollbackUnlessCommitted() }() } if account.CreatedAt == nil || account.CreatedAt.IsZero() { account.CreatedAt = pointer.ToTime(time.Now()) } if account.Nonce.String == "" { account.Nonce = dbr.NewNullString(random.RandomString(20)) } cols := []string{"created_at", "address", "nonce", "username"} err = tx. InsertInto(ds.table). Columns(cols...). Record(account). Returning("id"). LoadContext(ctx, account) if err != nil { return err } return nil } func (ds *AccountDatastore) List(ctx context.Context, fltr *AccountsFilter, limit *LimitOpts) ([]*model.Account, error) { var tx *dbr.Tx var err error tx, ok := dbrutil.DbTxFromContext(ctx) if !ok { sess := ds.conn.NewSession(nil) tx, err = sess.Begin() if err != nil { return nil, err } defer func() { err = tx.Commit() tx.RollbackUnlessCommitted() }() } accounts := make([]*model.Account, 0) selectStmt := tx.Select("*").From(ds.table) if fltr != nil { if fltr.Query != nil { likeQ := "%" + *fltr.Query + "%" selectStmt = selectStmt.Where( "name ILIKE ? OR username ILIKE ?", likeQ, likeQ, ) } if fltr.Sort != nil && fltr.Sort.Field != "" { selectStmt = selectStmt.OrderDir(fltr.Sort.Field, fltr.Sort.IsAsc) } } if limit != nil { if limit.Offset != nil { selectStmt = selectStmt.Offset(*limit.Offset) } if limit.Limit != nil && *limit.Limit != 0 { selectStmt = selectStmt.Limit(*limit.Limit) } } _, err = selectStmt.LoadContext(ctx, &accounts) if err != nil { return nil, err } return accounts, nil } func (ds *AccountDatastore) ListByIds(ctx context.Context, ids []int64) ([]*model.Account, error) { var tx *dbr.Tx var err error if len(ids) <= 0 { return []*model.Account{}, nil } tx, ok := dbrutil.DbTxFromContext(ctx) if !ok || tx == nil { sess := ds.conn.NewSession(nil) tx, err = sess.Begin() if err != nil { return nil, err } defer func() { err = tx.Commit() tx.RollbackUnlessCommitted() }() } accounts := []*model.Account{} _, err = tx. Select("*"). From(ds.table). Where("id IN ?", ids). LoadContext(ctx, &accounts) if err != nil { return nil, err } return accounts, nil } func (ds *AccountDatastore) GetByID(ctx context.Context, id int64) (*model.Account, error) { var err error tx, ok := dbrutil.DbTxFromContext(ctx) if !ok { sess := ds.conn.NewSession(nil) tx, err = sess.Begin() if err != nil { return nil, err } defer func() { err = tx.Commit() tx.RollbackUnlessCommitted() }() } account := new(model.Account) err = tx. Select("*"). From(ds.table). Where("id = ?", id). LoadOneContext(ctx, account) if err != nil { if err == dbr.ErrNotFound { return nil, ErrAccountNotFound } return nil, err } return account, nil } func (ds *AccountDatastore) GetByAddress(ctx context.Context, address string) (*model.Account, error) { var err error tx, ok := dbrutil.DbTxFromContext(ctx) if !ok { sess := ds.conn.NewSession(nil) tx, err = sess.Begin() if err != nil { return nil, err } defer func() { err = tx.Commit() tx.RollbackUnlessCommitted() }() } account := new(model.Account) err = tx. Select("*"). From(ds.table). Where("address = ?", strings.ToLower(address)). LoadOneContext(ctx, account) if err != nil { if err == dbr.ErrNotFound { return nil, ErrAccountNotFound } return nil, err } return account, nil } func (ds *AccountDatastore) GetByUsername(ctx context.Context, username string) (*model.Account, error) { var err error tx, ok := dbrutil.DbTxFromContext(ctx) if !ok { sess := ds.conn.NewSession(nil) tx, err = sess.Begin() if err != nil { return nil, err } defer func() { err = tx.Commit() tx.RollbackUnlessCommitted() }() } account := new(model.Account) err = tx. Select("*"). From(ds.table). Where("username = ?", username). LoadOneContext(ctx, account) if err != nil { if err == dbr.ErrNotFound { return nil, ErrAccountNotFound } return nil, err } return account, nil } func (ds *AccountDatastore) RegenerateNonce(ctx context.Context, account *model.Account) error { var err error tx, ok := dbrutil.DbTxFromContext(ctx) if !ok { sess := ds.conn.NewSession(nil) tx, err = sess.Begin() if err != nil { return err } defer func() { err = tx.Commit() tx.RollbackUnlessCommitted() }() } nonce := dbr.NewNullString(random.RandomString(20)) _, err = tx. Update(ds.table). Set("nonce", nonce). Where("address = ?", account.Address). ExecContext(ctx) if err != nil { return err } account.Nonce = dbr.NewNullString(nonce) return nil } func (ds *AccountDatastore) UpdatePublicKey(ctx context.Context, account *model.Account, pk string) error { var err error tx, ok := dbrutil.DbTxFromContext(ctx) if !ok { sess := ds.conn.NewSession(nil) tx, err = sess.Begin() if err != nil { return err } defer func() { err = tx.Commit() tx.RollbackUnlessCommitted() }() } _, err = tx. Update(ds.table). Set("public_key", pk). Where("address = ?", account.Address). ExecContext(ctx) if err != nil { return err } account.PublicKey = dbr.NewNullString(pk) return nil } func (ds *AccountDatastore) Update(ctx context.Context, account *model.Account, fields UpdateAccountFields) error { var err error tx, ok := dbrutil.DbTxFromContext(ctx) if !ok { sess := ds.conn.NewSession(nil) tx, err = sess.Begin() if err != nil { return err } defer func() { err = tx.Commit() tx.RollbackUnlessCommitted() }() } stmt := tx.Update(ds.table) if fields.Username != nil { stmt.Set("username", dbr.NewNullString(*fields.Username)) account.Username = dbr.NewNullString(*fields.Username) } if fields.Name != nil { stmt.Set("name", dbr.NewNullString(*fields.Name)) account.Name = dbr.NewNullString(*fields.Name) } if fields.Bio != nil { stmt.Set("bio", dbr.NewNullString(*fields.Bio)) account.Bio = dbr.NewNullString(*fields.Bio) } if fields.CustomURL != nil { stmt.Set("custom_url", dbr.NewNullString(*fields.CustomURL)) account.CustomURL = dbr.NewNullString(*fields.CustomURL) } if fields.YTUsername != nil { stmt.Set("yt_username", dbr.NewNullString(*fields.YTUsername)) account.YTUsername = dbr.NewNullString(*fields.YTUsername) } if fields.ImageCID != nil { stmt.Set("image_cid", dbr.NewNullString(*fields.ImageCID)) account.ImageCID = dbr.NewNullString(*fields.ImageCID) } if fields.CoverCID != nil { stmt.Set("cover_cid", dbr.NewNullString(*fields.CoverCID)) account.CoverCID = dbr.NewNullString(*fields.CoverCID) } _, err = stmt.Where("id = ?", account.ID).ExecContext(ctx) if err != nil { return err } return nil } func (ds *AccountDatastore) Count(ctx context.Context, fltr *AccountsFilter) (int64, error) { var tx *dbr.Tx var err error tx, ok := dbrutil.DbTxFromContext(ctx) if !ok { sess := ds.conn.NewSession(nil) tx, err = sess.Begin() if err != nil { return 0, err } defer func() { err = tx.Commit() tx.RollbackUnlessCommitted() }() } count := int64(0) selectStmt := tx.Select("COUNT(id)").From(ds.table) if fltr.Query != nil { likeQ := "%" + *fltr.Query + "%" selectStmt = selectStmt.Where( "name ILIKE ? OR username ILIKE ?", likeQ, likeQ, ) } err = selectStmt.LoadOneContext(ctx, &count) if err != nil { return 0, err } return count, nil }
C#
UTF-8
858
3.59375
4
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; namespace Assignment3.Classes { //4-6-2021 Saung NEW 5L : Generic queue which can be serialized [Serializable] public class SerializableQueue<T>: Queue<T> { //4-6-2021 Saung NEW 5L : Generic method returns item at given index or default if not found public T this[int index] { get { int count = 0; foreach (T o in this) { if (count == index) return o; count++; } return default; } } // 4-6-2021 Saung NEW 5L : Generich method adds new item to the queue public void Add(T r) { Enqueue(r); } } }
Python
UTF-8
1,619
3.09375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Tue Nov 07 17:41:46 2017 @author: doug """ import pandas as pd import gMaps as gm def getSites(turbine_data): if turbine_data[0] == 0: print("bad data. please try again") return 0 else: tDB = turbine_data[1] stateDB = turbine_data[2] print('How would you like to select turbines?') print(' 1. By state') print(' 2. By state and county') print(' 3. By lat/long with radius') goodSelection = 0 while goodSelection == 0: userSelection = int(input("please select an option: ")) goodSelection = 1 if userSelection == 1: siteInfo = getStateSites(turbine_data) elif userSelection == 2: siteInfo = getCountySites(turbine_data) elif userSelection == 3: siteInfo = getGeoSites(turbine_data) else: print(" invalid selection. please try again.") goodSelection = 0 return siteInfo def getStateSites(turbine_data): return 1 def getCountySites(turbine_data): return 1 def getGeoSites(turbine_data): goodSearch = 0 while goodSearch == 0: search_string = input(" enter a search term to get lat/long coords: ") search_result = gm.getCoords(search_string) response = input(" google has returned " + search_result[0] + ". type N to try again.") response = response.upper() if response != "N": goodSearch = 1 coordResult = search_result[1] return coordResult
C#
UTF-8
1,922
2.703125
3
[]
no_license
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Zhenway.BatchRequestAggregrators; namespace UnitTest { [TestClass] public class BatchRequestAggregatorTest { [TestMethod] public async Task TestBatchRequestAggregator() { var btp = new BatchRequestAggregator(4); var sw = Stopwatch.StartNew(); var bag = new ConcurrentBag<int>(); var proxy = btp.GetBuilder<int, string>(async xs => { await Task.Delay(100); Console.WriteLine("batch size: {0}, @{1}, by thread:{2}", xs.Count, sw.ElapsedMilliseconds, Thread.CurrentThread.ManagedThreadId); bag.Add(xs.Count); return (from x in xs select x.ToString()).ToList(); }).WithMaxBatchSize(50).Create(); var tasks = (from t in Enumerable.Range(0, 100) select proxy.InvokeAsync(Enumerable.Range(t, 10).ToList())).ToArray(); await Task.WhenAll(tasks); Console.WriteLine("Total: {0}ms", sw.ElapsedMilliseconds); Console.WriteLine("Average size: {0}", bag.Average()); Assert.IsTrue(sw.ElapsedMilliseconds > 200, "Pool not effective!"); Assert.IsTrue(sw.ElapsedMilliseconds < 1000, "Merge not effective!"); Assert.IsTrue(bag.Average() > 30.0, "Merge not effective!"); for (int i = 0; i < tasks.Length; i++) { var results = tasks[i].Result; for (int j = 0; j < 10; j++) { Assert.AreEqual((i + j).ToString(), results[j], "Error at {0}-{1}, Expected:{2}, Actual:{3}", i, j, (i + j).ToString(), results[j]); } } } } }
Java
UTF-8
1,265
2.734375
3
[]
no_license
package com.finezoom.javatraining.filesystem; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; public class StreamRead { public static void main(String[] args) throws IOException { readstreamfile(); } public static void readstreamfile() throws IOException { FileInputStream inputfile = new FileInputStream("D:\\assignment\\name.txt"); InputStreamReader read = new InputStreamReader(inputfile); int s=read.read(); FileOutputStream fw = new FileOutputStream("D:\\assignment\\nameww.txt"); OutputStreamWriter pw =new OutputStreamWriter(fw); //BufferedWriter bw = new BufferedWriter(fw); /*String count; while ((count = brs.readLine()) != null) { pw.println(count); }*/ while(s!=-1) { char b = (char) s; System.out.print(b); //System.out.println("success"); s=read.read(); pw.write(b); } read.close(); pw.close(); } }
Python
UTF-8
2,148
3.390625
3
[]
no_license
# python3 시간초과 안나는 코드 # deque의 rotate 이용!!! import sys input = sys.stdin.readline from collections import deque n, k = map(int, input().split()) belt = deque(list(map(int, input().split()))) robot = deque([0]*n) res = 0 while 1: belt.rotate(1) # 시계방향으로 1칸 회전// -1일 경우 반시계 방향 robot.rotate(1) robot[-1]=0 # 마지막 로봇 내리기 if sum(robot): # 로봇이 있으면 for i in range(n-2, -1, -1): if robot[i] == 1 and robot[i+1] == 0 and belt[i+1]>=1: robot[i+1] = 1 robot[i] = 0 belt[i+1] -= 1 robot[-1]=0 if robot[0] == 0 and belt[0]>=1: # 로봇 올리기 robot[0] = 1 belt[0] -= 1 res += 1 if belt.count(0) >= k: break print(res) # pypy로 제출 # import sys # from collections import deque # input = sys.stdin.readline # n, k = map(int, input().split()) # 벨트 길이, 내구도 0인 칸의 개수 제한 # belt = list(map(int, input().split())) # 벨트 내구도 (0 ~ 2n-1) # q = deque() # for i in range(len(belt)): # q.append([belt[i], 0]) # [벨트 내구도, 로봇 유무] # belt = q # def four(belt): # zero = 0 # for i in range(len(belt)): # if(belt[i][0] == 0): # zero += 1 # if(zero >= k): # return True # return False # cnt = 0 # while(1): # cnt += 1 # belt.appendleft(belt[-1]) # belt.pop() # if(belt[n-1][1] == 1): # belt[n-1][1] = 0 # 로봇 내리기 # for i in range(n-2, -1, -1): # if(belt[i][1] == 1): # if(belt[i+1][1] == 0 and belt[i+1][0] >= 1): # 다음 칸이 비어있고 내구도 1 이상이면 # belt[i][1] = 0 # belt[i+1][1] = 1 # 로봇 이동 # belt[i+1][0] -= 1 # 내구도 감소 # if(belt[n-1][1] == 1): # belt[n-1][1] = 0 # if(belt[0][1] == 0 and belt[0][0] >= 1): # belt[0][1] = 1 # 로봇 올리기 # belt[0][0] -= 1 # 내구도 감소 # if(four(belt)): # print(cnt) # break
Markdown
UTF-8
1,356
3.25
3
[]
no_license
# Data-Wrangling-Challenge ## Objective This is a simple script uses Nodejs to normalize the “European Union Road Safety Facts and Figures” table from [Wikipedia](https://en.wikipedia.org/wiki/Road_safety_in_Europe). The script cleans the data and makes it very easy to process and conduct further analysis. ## How to run the Program on Your Computer You’ll need to have Node >= 8.10 on your local development machine (but it’s not required on the server). You can use [nvm](https://github.com/creationix/nvm#installation) (macOS/Linux) or [nvm-windows](https://github.com/coreybutler/nvm-windows#node-version-manager-nvm-for-windows) to switch Node versions between different projects. Locate the path of the project and install the dependencies with the command below ``` git clone https://github.com/kwabena53/front-end-challenge.git npm install or yarn install ``` Run the following command to start the app on your local service http://localhost:3000/ ``` npm start or yarn start ``` ### Input data The input data was extracted raw from the “European Union Road Safety Facts and Figures” table on [Wikipedia](https://en.wikipedia.org/wiki/Road_safety_in_Europe). This is can be found @ [data.csv](data.csv) ### Output data The output data is the result of the data normalized data in CSV format found at [output.csv](output.csv)
Shell
UTF-8
1,272
3.953125
4
[]
no_license
#!/bin/bash source ./utils.sh usage() { cat << EOF usage: $0 [options] deploys wheninmustang to AWS S3 bucket. OPTIONS: -e Environment name (e.g. dev, staging, prod or production) EOF } setupBucket(){ cat << EOF Bucket does not exist. Create a static web hosting bucket with the name ${S3_BUCKET_NAME} EOF } while getopts "e:" OPTION do case $OPTION in e) ENVIRONMENT_NAME=$OPTARG ;; *) usage; exit 1 ;; esac done if [ -z ${ENVIRONMENT_NAME} ]; then usage; exit 1; fi if ! is_valid_env_name ${ENVIRONMENT_NAME}; then echo "Invalid environment name."; exit 1; fi S3_BUCKET_NAME="${ENVIRONMENT_NAME}.wheninmustang.com" if [ ${ENVIRONMENT_NAME} == "prod" ] then ENVIRONMENT_NAME="production" ember build --environment production else ember build fi if [ ${ENVIRONMENT_NAME} == "production" ] then S3_BUCKET_NAME="wheninmustang.com" fi echo "Deploying wheninmustang fe" echo "Using profile ${AWS_PROFILE}" echo "Deploying to ${ENVIRONMENT_NAME} environment" if ! aws s3 ls s3://${S3_BUCKET_NAME} --profile ${AWS_PROFILE} --region ${AWS_REGION} >/dev/null 2>&1; then setupBucket; exit 1; else aws s3 sync --profile ${AWS_PROFILE} --region ${AWS_REGION} ./../dist/ s3://${S3_BUCKET_NAME} --delete fi
SQL
UTF-8
2,700
3.578125
4
[ "MIT" ]
permissive
-- MySQL Script generated by MySQL Workbench -- Wed Jul 8 02:30:20 2015 -- Model: New Model Version: 1.0 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 mydb -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ; USE `mydb` ; -- ----------------------------------------------------- -- Table `mydb`.`field` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`field` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `type` VARCHAR(255) NOT NULL, `value` TEXT NULL, `label` VARCHAR(255) NOT NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `mydb`.`option` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`option` ( `id` INT NOT NULL, `option` TEXT NULL, `field_id` INT NOT NULL, PRIMARY KEY (`id`), INDEX `fk_options_field_idx` (`field_id` ASC), CONSTRAINT `fk_options_field` FOREIGN KEY (`field_id`) REFERENCES `mydb`.`field` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `mydb`.`collection` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`collection` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `label` VARCHAR(255) NOT NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB; -- ----------------------------------------------------- -- Table `mydb`.`collectionfield` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `mydb`.`collectionfield` ( `collection_id` INT NOT NULL, `field_id` INT NOT NULL, `id` INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`, `collection_id`, `field_id`), INDEX `fk_collection_has_field_field1_idx` (`field_id` ASC), INDEX `fk_collection_has_field_collection1_idx` (`collection_id` ASC), CONSTRAINT `fk_collection_has_field_collection1` FOREIGN KEY (`collection_id`) REFERENCES `mydb`.`collection` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_collection_has_field_field1` FOREIGN KEY (`field_id`) REFERENCES `mydb`.`field` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
Swift
UTF-8
6,596
2.53125
3
[]
no_license
// // CustomListRow.swift // FeelBetter (iOS) // // Created by Jason on 10/10/20. // import SwiftUI import CareKitStore struct CustomListRow: View { @EnvironmentObject var store: ClericStore @GestureState private var dragDistance = CGSize.zero @State private var newReveal: Bool = false @State private var position = CGSize.zero @State var showDiagnosis: Bool = false @State var showMale: Bool = false @State var showFemale: Bool = false @State var profileLinkActive = true @Binding var showMenu: Bool var child: OCKPatient var body: some View { let image = store.childDetails2[child]!["PROFILE_IMAGE"] ZStack { GeometryReader { geo in HStack{ Button(action: { let gender = store.fetchChildGender(child: child) if gender == "Male" { self.showMale = true self.showFemale = false self.showDiagnosis = true } else { self.showMale = false self.showFemale = true self.showDiagnosis = true } }, label: { Text("New Event") .foregroundColor(.white) .bold() .font(.system(size: 24, weight: .bold, design: .rounded)) .padding() }) .navigationBarBackButtonHidden(true) .simultaneousGesture(TapGesture().onEnded(){self.position.width = 0.0}) .frame(width: .infinity, height: 80, alignment: .center) .background(Color(UIColor.systemRed)) .cornerRadius(10) } .frame(width: geo.size.width * 0.95, height: 80, alignment: .trailing) .background(Color.white) .cornerRadius(10) } GeometryReader { geo in HStack { Text("\(child.name.givenName!)") .bold() .font(.system(size: 30, weight: .bold, design: .rounded)) .padding() Text("\(String(showMale))\(String(showFemale))").frame(width: 1, height: 1, alignment: .center).hidden() //Circle to be replaced With User Profile GeometryReader { geo in if profileLinkActive { NavigationLink( destination: ChildScreen( showMenu: $showMenu, child: child).environmentObject(store)) { ProfileInRowImage(child: child, image: image).environmentObject(store) } .frame(width: geo.size.width * 0.9, height: geo.size.height * 0.9, alignment: .trailing).offset(x: 0, y: geo.size.height * 0.05) } else { ProfileInRowImage(child: child, image: image).frame(width: geo.size.width * 0.9, height: geo.size.height * 0.9, alignment: .trailing).offset(x: 0, y: geo.size.height * 0.05) } }.offset(x: 20, y: 0.0) } .frame(width: geo.size.width * 0.95, height: 80, alignment: .trailing) .background(Color.white) .cornerRadius(10) .offset(x: position.width + dragDistance.width, y: 0) .gesture(DragGesture().updating($dragDistance, body: { (value, state, transaction) in if value.translation.width < 0 { state = value.translation } }) .onEnded({ (value) in self.newReveal.toggle() self.profileLinkActive.toggle() if newReveal { self.position.width = -140 } else {self.position.width = 0.0} }) ) } } .frame(width: .infinity, height: 80, alignment: .center).offset(x: 10.0, y: 0.0) .shadow(radius: 3) .sheet(isPresented: $showDiagnosis, onDismiss: { self.profileLinkActive = true }, content : { if showMale { MaleBodySectionSelector(child: child).environmentObject(store) } if showFemale { FemaleBodySectionSelector(child: child).environmentObject(store) } }) } } struct ProfileInRowImage: View { @EnvironmentObject var store: ClericStore @State var child: OCKPatient @State var image: Any? var body: some View { if store.childDetails2[child] != nil { let theImage = store.childDetails2[child]!["PROFILE_IMAGE"] if let theImage = theImage as? String { if !theImage.isEmpty { Image(theImage) .resizable() .aspectRatio(contentMode: .fill) .clipShape(Circle()) .shadow(radius: 5) .overlay(Circle().stroke(Color.gray, lineWidth: 1)) .frame(width: 80, height: 80, alignment: .center) } else { Image("default_profile") .resizable() .aspectRatio(contentMode: .fill) .clipShape(Circle()) .shadow(radius: 5) .overlay(Circle().stroke(Color.gray, lineWidth: 1)) .frame(width: 80, height: 80, alignment: .center) } } else { (theImage as! Image) .resizable() .aspectRatio(contentMode: .fill) .clipShape(Circle()) .shadow(radius: 5) .overlay(Circle().stroke(Color.gray, lineWidth: 1)) .frame(width: 80, height: 80, alignment: .center) } } } } #if DEBUG struct CustomListRow_Previews: PreviewProvider { static var myPatient = OCKPatient(id: "jb", givenName: "Fred", familyName: "B") static var previews: some View { CustomListRow(showMenu: .constant(false), child: myPatient).environmentObject(ClericStore.shared) } } #endif
Markdown
UTF-8
2,072
3.03125
3
[]
no_license
Hello :) This is simple api that uses OAuth2 for authorization. Unauthenticated users can see all tags, articles and comments. Authenticated user can create an article (he needs to provide access token), edit and delete his own articles. Authenticated user can comment any article and comments can be deleted by user who created it or by user who created article. Endpoints are: All users: GET /api/tags - get the list of tags<br> GET /api/articles - get all articles paginated by default articles per page<br> GET /api/articles?per_page=integer - integer can be between 2 and 50<br> GET /api/articles/id - id of an article<br> POST /api/register - must provide name, email, password<br> POST /api/login - must provide email and password<br> Authenticated users:<br> headers: Authorization: Bearer acces_token<br> POST /api/articles - creates an aricle<br> headers: Content-Type: multipart/form-data<br> body: <br> {<br> "title": "some title",<br> "body": "some text",<br> "tags[]": id of some tag,<br> "tags[]": id of other tag,<br> "image": upload an image<br> }<br> <br> POST /api/articles/id - updates existing article by id<br> headers: Content-Type: multipart/form-data<br> body: <br> {<br> "title": "new title",<br> "body": "new text",<br> "tags[]": id of some tag,<br> "tags[]": id of other tag,<br> "image": upload an image<br> }<br> <br> POST /api/articles/delete/id - deletes this article (only owner can delete it)<br> <br> GET /api/my-articles - auth user can see his own articles<br> <br> POST /api/comment - creates a comment<br> headers: Content-Type: multipart/form-data<br> body:<br> {<br> "article_id": existing article id,<br> "body": "text of your comment"<br> }<br> <br> POST /api/delete-comment/id - deletes a comment if user is an owner of that comment or an owner of article that was commented<br> You can test it on: https://bozidar-simpleapi.000webhostapp.com <br> Cheers !
JavaScript
UTF-8
3,606
2.515625
3
[]
no_license
/** * Author: Arkady Zelensky */ import React, {Component} from "react"; import DatePicker from 'react-datepicker'; import 'react-datepicker/dist/react-datepicker.css'; import moment from 'moment'; export default class Item extends Component { constructor(props) { super(props); this.state = { title: '', id_author: 1, id_genre: 1, input_image: { file: null, url: null, }, input_date: moment(), }; this.handleChange = this.handleChange.bind(this); } initialize(){ this.setState({ title: '', id_author: 1, id_genre: 1, input_image: { file: null, url: null, }, input_date: moment(), }) } handleChange(e) { const name = e.target.name; const type = e.target.type; const value = type === 'file' ? { url: URL.createObjectURL(e.target.files[0]), file: e.target.files[0] } : e.target.value; this.setState({[name]: value}) } handleDateChange(date) { this.setState({ input_date: date }); } onSubmit(e){ e.preventDefault(); const { onAdd } = this.props; const { title, id_author, id_genre, input_image, input_date} = this.state; onAdd({ title, id_author, id_genre, image: input_image.file, pubdate: input_date.format('YYYY-MM-DD') }); this.initialize(); this.form.reset(); if(input_image.url) URL.revokeObjectURL(input_image.url); } render() { const { title, id_author, id_genre, input_image, input_date } = this.state; const { genres, authors } = this.props; return( <li class="list-group-item"> <form method="post" ref={r => {this.form = r;}} onSubmit={(e) => this.onSubmit(e)} className="row d-flex align-items-center"> <div className='col-10 d-flex align-items-center'> <div className="col col-8 d-flex align-items-center"> <div className='d-flex flex-column align-items-center'> <img style={{width: '50px', height: '75px', marginRight: '10px'}} src={input_image.url ? input_image.url : ''}/> <br/> <input type="file" class="form-control-file" name="input_image" onChange={this.handleChange}/> </div> <div> <input type='text' id='title' name='title' className="form-control" required maxLength={45} value={title} minLength={4} placeholder='Title' onChange={this.handleChange}/> <br/> <select value={id_genre} name='id_genre' class="form-control form-control-sm" onChange={this.handleChange}> { genres.map(e => <option value={e.id} selected={e.id === id_genre}>{e.name}</option>) } </select> <br/> <select value={id_author} name='id_author' class="form-control form-control-sm" onChange={this.handleChange}> { authors.map(e => <option value={e.id} selected={e.id === id_author}>{e.name}</option>) } </select> <br/> <DatePicker selected={input_date} onChange={(e) => this.handleDateChange(e)}/> </div> </div> </div> <button type="submit" class='btn btn-primary col-2'>Add</button> </form> </li> ) } }
C#
UTF-8
1,979
2.59375
3
[]
no_license
using System; using System.Diagnostics; using System.IdentityModel.Selectors; using System.Security.Cryptography.X509Certificates; using dk.nita.saml20.Properties; using Trace=dk.nita.saml20.Utils.Trace; namespace dk.nita.saml20.Specification { /// <summary> /// Validates a selfsigned certificate /// </summary> public class SelfIssuedCertificateSpecification : ICertificateSpecification { /// <summary> /// Determines whether the specified certificate is considered valid by this specification. /// Always returns true. No online validation attempted. /// </summary> /// <param name="certificate">The certificate to validate.</param> /// <param name="failureReason">If the process fails, the reason is outputted in this variable</param> /// <returns> /// <c>true</c>. /// </returns> public bool IsSatisfiedBy(X509Certificate2 certificate, out string failureReason) { X509ChainPolicy chainPolicy = new X509ChainPolicy(); chainPolicy.RevocationMode = X509RevocationMode.NoCheck; chainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; X509CertificateValidator defaultCertificateValidator = X509CertificateValidator.CreateChainTrustValidator(false, chainPolicy); try { defaultCertificateValidator.Validate(certificate); failureReason = null; return true; } catch (Exception e) { failureReason = $"Validating with no revocation check failed for certificate '{certificate.Thumbprint}': {e}"; Trace.TraceData(TraceEventType.Warning, string.Format(Tracing.CertificateIsNotRFC3280Valid, certificate.SubjectName.Name, certificate.Thumbprint, e)); } return false; } } }
Python
UTF-8
4,066
2.53125
3
[]
no_license
# -*- coding: utf-8 -*- import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import random import math import numpy as np # from pylab import * # rcParams['figure.figsize'] = 15,5 # Always display all the columns # pd.set_option('display.width', 5000) # pd.set_option('display.max_columns', 60) def expNoFinalRes(): df1 = pd.read_csv('ExpGrafosRandomNipoNuevo.csv') df2 = pd.read_csv('ExpGrafosRandomEmiNuevo.csv') df3 = pd.read_csv('ExpGrafosRandomGRASP60.csv') df4 = pd.read_csv('ExpGrafosRandomBL.csv') HeurNipo = df1[df1['Tipo'] == 'GrafoRandomDMediaHeurNipo'] HeurEmi = df2[df2['Tipo'] == 'GrafoRandomDMediaHeurEmi'] BLLinealEmi = df4[df4['Tipo'] == 'BLinealHeurEmi'] BLCuadraticaEmi = df4[df4['Tipo'] == 'BCuadraticaHeurEmi'] Grasp = df3[df3['Tipo'] == 'Grasp'] xdata = HeurNipo['cantNod'] ydataNipo = HeurNipo['Res'] ydataEmi = HeurEmi['Res'] ydataGrasp = Grasp['Res'] ydataBLLineal = BLLinealEmi['Res'] ydataBLCuadratica = BLCuadraticaEmi['Res'] plt.plot(xdata, ydataNipo, "r.", alpha = 0.5, label='Heuristica MFCGM') # plt.plot(xdata, ydataEmi, "g.", alpha = 0.5, label='Heuristica MCMF') plt.plot(xdata, ydataGrasp, "b.", alpha = 0.5, label='Grasp') # plt.plot(xdata, ydataBLLineal, "k.", alpha = 0.5, label='BL Lineal sobre MCMF') plt.plot(xdata, ydataBLCuadratica, "y.", alpha = 0.5, label='BL Cuadr sobre MCMF') plt.xlabel('Cantidad de nodos entrada') plt.ylabel('Frontera devuelta') plt.legend() plt.show() def expNoFinalTiempo(): df1 = pd.read_csv('ExpGrafosRandomNipoNuevo.csv') df2 = pd.read_csv('ExpGrafosRandomEmiNuevo.csv') df3 = pd.read_csv('ExpGrafosRandomGRASP60.csv') df4 = pd.read_csv('ExpGrafosRandomBL.csv') HeurNipo = df1[df1['Tipo'] == 'GrafoRandomDMediaHeurNipo'] HeurEmi = df2[df2['Tipo'] == 'GrafoRandomDMediaHeurEmi'] BLLinealEmi = df4[df4['Tipo'] == 'BLinealHeurEmi'] BLCuadraticaEmi = df4[df4['Tipo'] == 'BCuadraticaHeurEmi'] Grasp = df3[df3['Tipo'] == 'Grasp'] xdata = HeurNipo['cantNod'] ydataNipo = HeurNipo['Tiempo'] ydataEmi = HeurEmi['Tiempo'] ydataGrasp = Grasp['Tiempo'] ydataBLLineal = BLLinealEmi['Tiempo'] ydataBLCuadratica = BLCuadraticaEmi['Tiempo'] plt.plot(xdata, ydataNipo, "r.", alpha = 0.5, label='Heuristica MFCGM') plt.plot(xdata, ydataEmi, "g.", alpha = 0.5, label='Heuristica MCMF') plt.plot(xdata, ydataGrasp, "b.", alpha = 0.5, label='Grasp') plt.plot(xdata, ydataBLLineal, "k.", alpha = 0.5, label='BL Lineal sobre MCMF') plt.plot(xdata, ydataBLCuadratica, "y.", alpha = 0.5, label='BL Cuadr sobre MCMF') plt.xlabel('Cantidad de nodos entrada') plt.ylabel('Frontera devuelta') plt.yscale('log') plt.legend() plt.show() # expComplejNipoYEmi() # TodosvsTodosEne35Res() # TodosvsTodosEne35Tiempo() # RandomHasta400Res() # RandomHasta400Tiempo() # expComplejEmi() # expComplejNipo() expNoFinalRes() expNoFinalTiempo() # df = pd.read_csv('ruta/archivo.csv') > lee el archivo # df.head(n) > muestras los primeros n # df > muestra todo el archivo # df['LongEntrada'] > muestra los elementos de la columna LongEntrada. Podés seleccionar más columnas también # df['LongEntrada'][:5] > muestra los elementos de la column LongEntrada hasta el 5 # df[10:15] > muestra los elementos del 10 al 15 # contador = df['LongEntrada'].value_counts() > define a la variable contador como el conteo de cuántos hay según cada LongEntrada # var.plot(kind='bar') > te crea el plot en var, el tipo es una barra # plt.show() > te muestra el último plot que creaste # nes20 = df[df['Longitud_Entrada'] == 20] > cree una variable nes20 donde tengo solo los de long 20 """ tiempoMasQue40 = df["Tiempo_en_ms"] > 40 TMas40 = df[tiempoMasQue40] print TMas40['Longitud_Entrada'].value_counts()""" # me muestra cuántos tienen tiempo mayor que 40 según cada n """ a = TMas40['Longitud_Entrada'].value_counts() print a todo = df['Longitud_Entrada'].value_counts() asd = a / todo.astype(float) print asd""" # df.groupby('Longitud_Entrada').mean() > devuelve la mediana de todos los valores con long_entrada == 1, == 2 ....
Java
UTF-8
1,608
2.765625
3
[]
no_license
package com.bigcustard.blurp.ui; import com.badlogic.gdx.*; import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.graphics.g2d.*; import com.badlogic.gdx.math.*; import com.bigcustard.blurp.core.*; import com.bigcustard.blurp.model.*; public class SimpleButton { private final TextureRegion textureRegion; private final Colour colour; private float x, y; private float size; private Vector2 mousePos = new Vector2(); public SimpleButton(String filename, Colour colour) { textureRegion = new TextureRegion(new Texture(Gdx.files.classpath(filename), true)); textureRegion.getTexture().setFilter(Texture.TextureFilter.MipMapLinearNearest, Texture.TextureFilter.Linear); this.colour = colour; } public void setPosition(double x, double y, double size) { this.x = (float) x; this.y = (float) y; this.size = (float) size; } public void render(Batch batch) { batch.setColor((float) colour.red, (float) colour.green, (float) colour.blue, isMouseOver() ? 1 : 0.65f); batch.draw(textureRegion, x, y, size, size); batch.setColor(1, 1, 1, 1); } public boolean wasClicked() { return Gdx.input.justTouched() && isMouseOver(); } private boolean isMouseOver() { mousePos.set(Gdx.input.getX(), Gdx.input.getY()); BlurpStore.staticViewport.unproject(mousePos); return mousePos.x >= x && mousePos.x <= x + size && mousePos.y >= y && mousePos.y <= y + size; } public void dispose() { textureRegion.getTexture().dispose(); } }
Java
UTF-8
985
3.40625
3
[]
no_license
import java.util.LinkedList; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; public class MyIterableImpl { //Returns a view of unfiltered containing all elements that satisfy the input predicate retainIfTrue. public static <T> Iterable<T> filter(Iterable<T> unfiltered, Predicate<? super T> retainIfTrue) { List<T> result = new LinkedList<>(); for (T temp: unfiltered) { if (retainIfTrue.test(temp)) result.add(temp); } return result; } //Returns a view containing the result of applying function to each element of fromIterable. public static <F, T> Iterable<T> transform(Iterable<F> fromIterable, Function<? super F, ? extends T> function) { List<T> result = new LinkedList<>(); for (F temp: fromIterable) result.add(function.apply(temp)); return result; } }
Python
UTF-8
11,446
2.9375
3
[]
no_license
import urllib.request as urllib; from lxml import etree import numpy as np; import pandas as pd import time; import pickle; import datetime """ Author : Brandon Veber Date : 1/3/2014 email : veber001@umn.edu This python file contains all the modules required to obtain statistics for all players in a given season, and find the career statistics for all players who were active in the given season. All data collected from www.basketball-reference.com These programs have been tested and verified on Ubuntu 14.04 using Python 3.4 Library dependencies: urllib, time, pickle, datetime lxml version >= 3.3.3 numpy version >= 1.9.0 pandas version >= 0.13.1 Bug List: 1 - It is possible to skip a player if his webpage won't load """ def main(startSeason=2000,endSeason=2015,verbose=0): """ """ seasonStats = {} careerData,lookUp = {},None for year in np.arange(endSeason,startSeason-1,-1): seasonStats[year]=seasonStatsOnline(year) for index,row in seasonStats[year].iterrows(): careerData,lookUp = updateCareerStats(row['URL'],row['Player'],careerData,lookUp,verbose) pickle.dump(seasonStats,open('seasonStats.p','wb')) pickle.dump(careerData,open('careerData.p','wb')) pickle.dump(lookUp,open('careerKeyLookup.p','wb')) return(seasonStats,careerData,lookUp) def seasonStatsOnline(year=datetime.datetime.now().year,statType='totals'): """ This module opens the basketball-reference site to get the seasons stats and player URLs. Inputs: year - int, optional (default = current year) Specifies the desired year for the basketball-reference url. statType - string, optional (Default = 'totals') The type of season statistics to retrieve. The default is the season total ('totals') for basic stats. Alternatives are per game ('per_game'), per 36 minutes ('per_minute'), per 100 possessions ('per_poss') and advanced stats like PER, TS%, etc. ('advanced'). Output: seasonStats - Pandas DataFrame The data for all players based on the desired statistic type. The data is saved as a dataframe so it can be easily searched and sorted. """ print('Gathering season statistics for ',year) url = 'http://www.basketball-reference.com/leagues/NBA_'+str(year)+'_'+statType+'.html' try: table = extractHTML(url,'season',statType) except: print("Didn't read properly! Waiting 15s, then trying again"); time.sleep(15) headerNode = table[0].xpath('th') categories = ['URL']+[node.text for node in headerNode][1:] categories[11] = '3PM'; categories[13] = '3P%' rowsData = [] for i in range(1,len(table)): rowsData.append([node.text if node.text else node.xpath('a/@href')+node.xpath('a/text()') for node in table[i].xpath('td')][1:]) seasonStats = pd.DataFrame(columns=categories) for row in rowsData: if row: url = row[0][0] convertedRow = [url] for i in range(len(row)): if categories[i+1] in ['Player','Tm']: convertedRow.append(row[i][1]) elif categories[i+1] in ['Age','Pos']: convertedRow.append(row[i]) else: if not row[i]: convertedRow.append(np.nan) else: convertedRow.append(float(row[i])) if url in list(seasonStats['URL']): index = np.where(seasonStats['URL'] == url)[0][0] if seasonStats.loc[index]['Tm']=='O': seasonStats.loc[index]['Tm'] = [convertedRow[4]] else: seasonStats.ix[index]['Tm'] = seasonStats.ix[index]['Tm']+[convertedRow[4]] else: seasonStats.loc[len(seasonStats)] = convertedRow print(statType+' stats for all players found') return(seasonStats) def getCareerStats(seasonStats): """ This module finds ands saves all active players career data by season Inputs: seasonStats - Pandas DataFrame, required The dataframe containing the yearly data for a given season created by the seasonStatsOnline module Outputs: careerStats - dictionary This dictionary contains the career statistics of all active players during the season of interest. The keys are the player URL. lookUp - Pandas DataFrame This dataframe has a reference of the player name assosciated with the URL. This makes it possible to search the careerStats dictionary by player name rather than the slightly cryptic URL. """ careerStats={} lookUp=pd.DataFrame(columns=['url','Player']) for index in seasonStats.index: url = seasonStats.loc[index,'URL'] print(seasonStats.loc[index]['Player']) lookUp.loc[len(lookUp)]=[url,seasonStats.loc[index]['Player']] try: careerStats[url]=getPlayerCareerStats(url) except: print("Didn't read properly! Waiting 15s, then trying again") time.sleep(15) try: careerStats[url]=getPlayerCareerStats(url) except: print('Did not find data for ',seasonStats.loc[index]['Player']) continue return(careerStats,lookUp) def updateCareerStats(url,name,careerData={},lookUp=None,verbose=0): """ This module can create and update saved career data one player at a time Inputs: url - string, required name - string, required careerData - dictionary, optional (default = {}) lookUp - Pandas DataFrame, optional (default = None) verbose - int, optional (default=0) Outputs: careerStats - dictionary This dictionary contains the career statistics of all active players during the season of interest. The keys are the player URL. lookUp - Pandas DataFrame This dataframe has a reference of the player name assosciated with the URL. This makes it possible to search the careerStats dictionary by player name rather than the slightly cryptic URL. """ if not careerData: if verbose >=1: print('Getting career data for ',name) careerData[url] = getPlayerCareerStats(url) lookUp = pd.DataFrame(np.reshape([url,name],(1,2)),columns=['url','Player']) else: if url not in careerData: if verbose >=1: print('Getting career data for ',name) careerData[url] = getPlayerCareerStats(url) lookUp.loc[len(lookUp)] = [url,name] return(careerData,lookUp) def getPlayerCareerStats(url,type='totals'): """ This module reads all players career webpages and extracts the desired statistics by season Inputs: url - string, required This is the unique URL derived from the seasonStats dataframe that is generated in seasonStatsOnline module. It contains the last part of a url for the basketball-reference website. For example: Stephen Curry's URL is /players/c/curryst01.html type - string, optional (default = 'totals') The type of statistics to retrieve. The default is the season total ('totals') for basic stats. Alternatives are per game ('per_game'), per 36 minutes ('per_minute'), per 100 possessions ('per_poss') and advanced stats like PER, TS%, etc. ('advanced'). Outputs: careerStats - Pandas DataFrame This is the dataframe containing the players career statistics with each row corresponding to a particular season """ url = 'http://www.basketball-reference.com/'+url table=extractHTML(url,'career',type) headerNode = table[0].xpath('th') categories = [node.text for node in headerNode] rowsData=[] for i in range(1,len(table)): rowsData.append([node.text if node.text else node.xpath('a/@href')+node.xpath('a/text()') for node in table[i].xpath('td')]) careerStats = pd.DataFrame(columns=categories) for row in rowsData: if row and row[0] != 'Career' and row[2][:12] != 'Did Not Play': convertedRow = [] for i in range(len(row)): if categories[i] in ['Season','Tm','Lg']: convertedRow.append(row[i][1]) elif categories[i] in ['Age','Pos']: convertedRow.append(row[i]) else: if not row[i]: convertedRow.append(np.nan) else: convertedRow.append(float(row[i])) if convertedRow[0] in list(careerStats['Season']): index = np.where(careerStats['Season'] == convertedRow[0])[0][0] if careerStats.loc[index]['Tm']=='O': careerStats.loc[index,('Tm')] = [convertedRow[2]] else: careerStats.loc[index]['Tm'] = careerStats.loc[index]['Tm']+[convertedRow[2]] else: careerStats.loc[len(careerStats)] = convertedRow elif row[2][:12] == 'Did Not Play': continue else: break return(careerStats) def extractHTML(url,type='season',subType='totals'): """ This module returns specific HTML tables in a raw lxml format Inputs: url - string, required The full pro-basketball-reference URL type - string, optional (default = 'season') This is the main type of data that is being collected. The options are a season's worth of data for all players active during the given season ('season'), gamelog data that extracts information from every game ('gamelogs') and data for an entire player's career ('career') subType - string, optional (default = 'totals') This is the specific type of data that is being collected. if type == 'season': the options are 'totals','per_game','per_minutes','per_poss' and 'advanced' if type == 'gamelogs': the options are 'player' and 'team'. This returns a list of two tables, the first table is basic stats, and the second is advanced stats if type == 'career': the options are 'totals','per_game','per_minutes','per_poss', 'advanced' and 'shooting' Outputs: table - list of etree instances, or etree instance """ page = urllib.urlopen(url) s = page.read() html = etree.HTML(s) if type == 'season': return(html.xpath('//table[@id="'+subType+'"]//tr')) elif type == 'gamelogs': if subType == 'player': return([html.xpath('//table[@id="pgl_basic"]//tr'),html.xpath('//table[@id="pgl_advanced"]//tr')]) elif subType == 'team': return([html.xpath('//table[@id="tgl_basic"]//tr'),html.xpath('//table[@id="tgl_advanced"]//tr')]) elif type == 'career': return(html.xpath('//table[@id="'+subType+'"]//tr'))
Java
UTF-8
5,673
2.140625
2
[ "Apache-2.0" ]
permissive
package org.jitsi.util.swing; import org.jitsi.android.util.java.awt.Component; import org.jitsi.android.util.java.awt.Container; import org.jitsi.android.util.java.awt.Dimension; import org.jitsi.android.util.java.awt.LayoutManager; import org.jitsi.android.util.java.awt.Rectangle; public class FitLayout implements LayoutManager { protected static final int DEFAULT_HEIGHT_OR_WIDTH = 16; public void addLayoutComponent(String name, Component comp) { } /* access modifiers changed from: protected */ public Component getComponent(Container parent) { Component[] components = parent.getComponents(); return components.length > 0 ? components[0] : null; } /* access modifiers changed from: protected */ /* JADX WARNING: Removed duplicated region for block: B:13:0x002d */ /* JADX WARNING: Removed duplicated region for block: B:21:0x004a */ /* JADX WARNING: Removed duplicated region for block: B:24:0x0052 */ public void layoutComponent(org.jitsi.android.util.java.awt.Component r17, org.jitsi.android.util.java.awt.Rectangle r18, float r19, float r20) { /* r16 = this; r0 = r17; r9 = r0 instanceof org.jitsi.android.util.javax.swing.JPanel; if (r9 == 0) goto L_0x0017; L_0x0006: r9 = r17.isOpaque(); if (r9 != 0) goto L_0x0017; L_0x000c: r9 = r17; r9 = (org.jitsi.android.util.java.awt.Container) r9; r9 = r9.getComponentCount(); r12 = 1; if (r9 > r12) goto L_0x0023; L_0x0017: r0 = r17; r9 = r0 instanceof org.jitsi.util.swing.VideoContainer; if (r9 != 0) goto L_0x0023; L_0x001d: r8 = r17.getPreferredSize(); if (r8 != 0) goto L_0x0085; L_0x0023: r8 = r18.getSize(); L_0x0027: r9 = r17.isMaximumSizeSet(); if (r9 == 0) goto L_0x0045; L_0x002d: r4 = r17.getMaximumSize(); r9 = r8.width; r12 = r4.width; if (r9 <= r12) goto L_0x003b; L_0x0037: r9 = r4.width; r8.width = r9; L_0x003b: r9 = r8.height; r12 = r4.height; if (r9 <= r12) goto L_0x0045; L_0x0041: r9 = r4.height; r8.height = r9; L_0x0045: r9 = r8.height; r12 = 1; if (r9 >= r12) goto L_0x004d; L_0x004a: r9 = 1; r8.height = r9; L_0x004d: r9 = r8.width; r12 = 1; if (r9 >= r12) goto L_0x0055; L_0x0052: r9 = 1; r8.width = r9; L_0x0055: r0 = r18; r9 = r0.x; r0 = r18; r12 = r0.width; r13 = r8.width; r12 = r12 - r13; r12 = (float) r12; r12 = r12 * r19; r12 = java.lang.Math.round(r12); r9 = r9 + r12; r0 = r18; r12 = r0.y; r0 = r18; r13 = r0.height; r14 = r8.height; r13 = r13 - r14; r13 = (float) r13; r13 = r13 * r20; r13 = java.lang.Math.round(r13); r12 = r12 + r13; r13 = r8.width; r14 = r8.height; r0 = r17; r0.setBounds(r9, r12, r13, r14); return; L_0x0085: r5 = 0; r9 = r8.width; r0 = r18; r12 = r0.width; if (r9 == r12) goto L_0x00ca; L_0x008e: r9 = r8.width; if (r9 <= 0) goto L_0x00ca; L_0x0092: r5 = 1; r0 = r18; r9 = r0.width; r12 = (double) r9; r9 = r8.width; r14 = (double) r9; r10 = r12 / r14; L_0x009d: r9 = r8.height; r0 = r18; r12 = r0.height; if (r9 == r12) goto L_0x00cd; L_0x00a5: r9 = r8.height; if (r9 <= 0) goto L_0x00cd; L_0x00a9: r5 = 1; r0 = r18; r9 = r0.height; r12 = (double) r9; r9 = r8.height; r14 = (double) r9; r2 = r12 / r14; L_0x00b4: if (r5 == 0) goto L_0x0027; L_0x00b6: r6 = java.lang.Math.min(r10, r2); r9 = r8.width; r12 = (double) r9; r12 = r12 * r6; r9 = (int) r12; r8.width = r9; r9 = r8.height; r12 = (double) r9; r12 = r12 * r6; r9 = (int) r12; r8.height = r9; goto L_0x0027; L_0x00ca: r10 = 4607182418800017408; // 0x3ff0000000000000 float:0.0 double:1.0; goto L_0x009d; L_0x00cd: r2 = 4607182418800017408; // 0x3ff0000000000000 float:0.0 double:1.0; goto L_0x00b4; */ throw new UnsupportedOperationException("Method not decompiled: org.jitsi.util.swing.FitLayout.layoutComponent(org.jitsi.android.util.java.awt.Component, org.jitsi.android.util.java.awt.Rectangle, float, float):void"); } public void layoutContainer(Container parent) { layoutContainer(parent, 0.5f); } /* access modifiers changed from: protected */ public void layoutContainer(Container parent, float componentAlignmentX) { Component component = getComponent(parent); if (component != null) { layoutComponent(component, new Rectangle(parent.getSize()), componentAlignmentX, 0.5f); } } public Dimension minimumLayoutSize(Container parent) { Component component = getComponent(parent); return component != null ? component.getMinimumSize() : new Dimension(16, 16); } public Dimension preferredLayoutSize(Container parent) { Component component = getComponent(parent); return component != null ? component.getPreferredSize() : new Dimension(16, 16); } public void removeLayoutComponent(Component comp) { } }
Python
UTF-8
1,545
3.03125
3
[ "Apache-2.0" ]
permissive
import shutil import os import datetime import configparser # change dir to directory of this file so we can find the config file os.chdir(os.path.dirname(os.path.abspath(__file__))) config = configparser.ConfigParser() config.read(R'backup_config.ini') DB_LOCATION = config['DEFAULT']['db_location'] BACKUP_DIR = config['DEFAULT']['backup_dir'] def get_backup_file_list(backup_directory): ''' Get a list of the files currently in the backup directory ''' backup_files = [os.path.join(BACKUP_DIR, f) for f in os.listdir(BACKUP_DIR) if os.path.isfile(os.path.join(BACKUP_DIR, f))] return backup_files def delete_oldest_backup(backup_file_list): ''' Simply delete the oldest file in a list of files ''' oldest_file = min(backup_file_list, key=os.path.getctime) os.remove(oldest_file) def backup_db(db_location, backup_directory): ''' Copy the database over to the backup directory and rename it with the backup date ''' database_filename = os.path.basename(DB_LOCATION) backup_filename = '{}_{}'.format(datetime.date.today(), database_filename) backup_full_path = os.path.join(backup_directory, backup_filename) shutil.copy2(db_location, backup_full_path) def main(): backup_file_list = get_backup_file_list(BACKUP_DIR) backup_db(DB_LOCATION, BACKUP_DIR) if len(backup_file_list) > 4: # if there is more than 4 backup files in the backup directory delete_oldest_backup(backup_file_list) if __name__ == '__main__': main()
Shell
UTF-8
279
3
3
[]
no_license
function setBackground() { setuppath=$1 backgroundImage=$2 cp $setuppath${backgroundImage} /home/vagrant/Pictures gsettings set org.gnome.desktop.background picture-uri /home/vagrant/Pictures/${backgroundImage} } setBackground "/home/vagrant/setup/" "mr.robot.jpg"
Java
UTF-8
2,324
1.953125
2
[ "Apache-2.0" ]
permissive
package com.github.nijian.jkeel.concept.config; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.util.Map; @XmlAccessorType(XmlAccessType.FIELD) public class BehaviorsConfig { @XmlElement(name = "services") @XmlJavaTypeAdapter(ServicesConfigAdapter.class) private Map<String, ServiceConfig> serviceConfigMap; @XmlElement(name = "actions") @XmlJavaTypeAdapter(ActionsConfigAdapter.class) private Map<String, ActionConfig> actionConfigMap; @XmlElement(name = "algorithms") @XmlJavaTypeAdapter(AlgorithmsConfigAdapter.class) private Map<String, AlgorithmConfig> algorithmConfigMap; @XmlElement(name = "dataAccessors") @XmlJavaTypeAdapter(DataAccessorsConfigAdapter.class) private Map<String, DataAccessorConfig> dataAccessorConfigMap; @XmlElement(name = "codes") @XmlJavaTypeAdapter(CodesConfigAdapter.class) private Map<String, CodeConfig> codeConfigMap; public Map<String, ServiceConfig> getServiceConfigMap() { return serviceConfigMap; } public Map<String, ActionConfig> getActionConfigMap() { return actionConfigMap; } public Map<String, AlgorithmConfig> getAlgorithmConfigMap() { return algorithmConfigMap; } public void setAlgorithmConfigMap(Map<String, AlgorithmConfig> algorithmConfigMap) { this.algorithmConfigMap = algorithmConfigMap; } public Map<String, DataAccessorConfig> getDataAccessorConfigMap() { return dataAccessorConfigMap; } public void setServiceConfigMap(Map<String, ServiceConfig> serviceConfigMap) { this.serviceConfigMap = serviceConfigMap; } public void setActionConfigMap(Map<String, ActionConfig> actionConfigMap) { this.actionConfigMap = actionConfigMap; } public void setDataAccessorConfigMap(Map<String, DataAccessorConfig> dataAccessorConfigMap) { this.dataAccessorConfigMap = dataAccessorConfigMap; } public Map<String, CodeConfig> getCodeConfigMap() { return codeConfigMap; } public void setCodeConfigMap(Map<String, CodeConfig> codeConfigMap) { this.codeConfigMap = codeConfigMap; } }
Java
UTF-8
179
1.507813
2
[]
no_license
package com.online.movie.ticket.util; public abstract class RestFulPath { public static final String INCLUDE_REQUEST_URI_ATTRIBUTE = "javax.servlet.include.request_uri"; }
Markdown
UTF-8
2,973
2.609375
3
[ "MIT" ]
permissive
# Readmission Prediction [![Awesome](https://awesome.re/badge.svg)](https://awesome.re) ![size](https://img.shields.io/github/repo-size/freesinger/Readmission_Prediction.svg?style=plastic) ![stars](https://img.shields.io/github/stars/freesinger/Readmission_Prediction.svg?style=social) ![license](https://img.shields.io/github/license/freesinger/Readmission_Prediction.svg?style=plastic) [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Ffreesinger%2Freadmission_prediction.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Ffreesinger%2Freadmission_prediction?ref=badge_shield) ## 1. Dependencies `python>=3.6` Libraries: ``` - numpy - pandas - scipy - imbalanced-learn - seaborn - XGBoost - scikit-learn - matplotlib ``` ## 2. Datasets Raw dataset `Diabetes 130-US hospitals for years 1999-2008 Data Set` can be found [hear](https://archive.ics.uci.edu/ml/datasets/Diabetes+130-US+hospitals+for+years+1999-2008#). The dataset represents 10 years (1999-2008) of clinical care at 130 US hospitals and integrated delivery networks. It includes over 50 features representing patient and hospital outcomes. Information was extracted from the database for encounters that satisfied the following criteria. > (1) It is an inpatient encounter (a hospital admission). > > (2) It is a diabetic encounter, that is, one during which any kind of diabetes was entered to the system as a diagnosis. > > (3) The length of stay was at least 1 day and at most 14 days. > > (4) Laboratory tests were performed during the encounter. > > (5) Medications were administered during the encounter. The data contains such attributes as patient number, race, gender, age, admission type, time in hospital, medical specialty of admitting physician, number of lab test performed, HbA1c test result, diagnosis, number of medication, diabetic medications, number of outpatient, inpatient, and emergency visits in the year before the hospitalization, etc. ## 3. Files Readmission prediction task can be concluded by the figure below: ![](images/task.png) `preprocess.py`: used for preprocessing data, generate the processed data file `preprocessed_data.csv` which saved in folder `data`. `train.py`: used for training and output, test models are `XGBoost` and `Random Forest`. Accuracy, confusion matrix and overall report of models will shown after running. ## 4. Usage ``` >_ python3.6 preprocess.py >_ python3.6 train.py ``` ## 5. Performances ### XGBoost Confusion matrix: ![xgboost](./images/XGBoost.png) Top 10 importent features: ![](images/XGBfeatImportance.jpg) ### Random Forest Confusion matrix: ![](images/randomForest.png) Top 10 important features: ![](images/RFfeatImportance.jpg) ## 6. License [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Ffreesinger%2Freadmission_prediction.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Ffreesinger%2Freadmission_prediction?ref=badge_large)
C#
UTF-8
1,521
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataLayer { public class DB { public static string EmployeePortalString { get { return ConfigurationManager.ConnectionStrings["EmployeePortalString"].ConnectionString; //string constr = ConfigurationManager.ConnectionStrings["EmployeePortalString"].ConnectionString; //SqlConnectionStringBuilder s = new SqlConnectionStringBuilder(); //s.ApplicationName = applicationName;// ?? s.ApplicationName; //s.ConnectTimeout = connectionTimeout; ////s.ConnectTimeout = (connectionTimeout > 0) ? connectionTimeout : s.ConnectTimeout; //return s.ToString(); } } /// <summary> /// Property used to override the name of the application /// </summary> public static string applicationName; /// <summary> /// overrides the connection timeout /// </summary> public static int connectionTimeout; /// <summary> /// returns an open connection /// </summary> /// <returns></returns> public static SqlConnection GetSqlConn() { SqlConnection s = new SqlConnection(EmployeePortalString); s.Open(); return s; } } }
Java
UTF-8
5,127
3
3
[]
no_license
import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; /* * 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. */ /** * * @author hitarthk */ public class C_218_D { public static void main(String[] args) { FasterScanner in=new FasterScanner(); PrintWriter out=new PrintWriter(System.out); int n=in.nextInt(); int[] c=in.nextIntArray(n); int[] f=new int[n]; int[] parent=new int[n+1]; for(int i=0;i<=n;i++){ parent[i]=i; } int m=in.nextInt(); while(m>0){ m--; int q=in.nextInt(); if(q==1){ int p=in.nextInt()-1; int x=in.nextInt(); while(x>0 && p<n){ //System.out.println("x "+x); { int X=x; x-=Math.min(x, c[p]-f[p]); f[p]=Math.min(c[p], f[p]+X); if(f[p]==c[p]){ parent[p]=p+1; } while (p != parent[p]) { //System.out.println("Hre"); parent[p] = parent[parent[p]]; // path compression by halving p = parent[p]; } } } } else{ int k=in.nextInt()-1; System.out.println(f[k]); } } out.close(); } /* 10 71 59 88 55 18 98 38 73 53 58 20 1 5 93 1 7 69 2 3 1 1 20 2 10 1 6 74 1 7 100 1 9 14 2 3 2 4 2 7 1 3 31 2 4 1 6 64 2 2 2 2 1 3 54 2 9 2 1 1 6 86 */ public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Python
UTF-8
1,950
2.84375
3
[ "BSD-3-Clause" ]
permissive
import typing from contextlib import suppress import qtawesome as qta from qtpy import QtGui from qtpy.QtCore import QRect, Qt from qtpy.QtGui import QFont, QFontMetrics, QPainter from qtpy.QtWidgets import QCheckBox, QWidget class CollapseCheckbox(QCheckBox): """ Check box for hide widgets. It is painted as: ▶, {info_text}, line If triangle is ▶ then widgets are hidden If triangle is ▼ then widgets are shown :param info_text: optional text to be show """ def __init__(self, info_text: str = "", parent: typing.Optional[QWidget] = None): super().__init__(info_text or "-", parent) self.hide_list = [] self.stateChanged.connect(self.hide_element) metrics = QFontMetrics(QFont()) self.text_size = metrics.size(Qt.TextSingleLine, info_text) self.info_text = info_text def add_hide_element(self, val: QWidget): """ Add widget which visibility should be controlled by CollapseCheckbox """ self.hide_list.append(val) def remove_hide_element(self, val: QWidget): """ Stop controlling widget visibility by CollapseCheckbox """ with suppress(ValueError): self.hide_list.remove(val) def hide_element(self, a0: int): for el in self.hide_list: el.setHidden(bool(a0)) def paintEvent(self, event: QtGui.QPaintEvent): painter = QPainter(self) color = painter.pen().color() painter.save() rect = self.rect() top = int(rect.height() - (self.text_size.height() / 2)) painter.drawText(rect.height() + 5, top, self.info_text) if self.isChecked(): icon = qta.icon("fa5s.caret-right", color=color) else: icon = qta.icon("fa5s.caret-down", color=color) icon.paint(painter, QRect(0, int(-self.height() / 4), self.height(), self.height())) painter.restore()
Python
UTF-8
4,043
2.65625
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns get_ipython().run_line_magic('matplotlib', 'inline') # In[2]: df=pd.read_csv("C:/Users/Somay/Documents/heart.csv",encoding='ISO-8859-1') df.head() # In[3]: df.shape # In[4]: df.info() # In[5]: df.isnull().sum() # In[6]: df.describe() # In[7]: sns.countplot(df.target) # In[8]: plt.hist(df.age,bins=20) plt.xlabel("age") plt.ylabel("count") # In[9]: sns.pairplot(df) # In[10]: plt.figure(figsize=(12,8)) sns.heatmap(df.corr(),fmt="0%",annot=True) # In[11]: df_new=pd.get_dummies(df,columns=['sex','cp','fbs','restecg','exang','slope','ca','thal'],drop_first=True) # In[12]: df_new.columns # In[13]: df_new.head() # In[14]: from sklearn.preprocessing import StandardScaler sc=StandardScaler() columns_scaling=['age','trestbps','chol','thalach','oldpeak'] df_new[columns_scaling]=sc.fit_transform(df_new[columns_scaling]) # In[15]: from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import RandomizedSearchCV from scipy.stats import randint from sklearn.model_selection import train_test_split # In[16]: x=df_new.iloc[:,:-1] print(x.shape) # In[17]: y=df_new.iloc[:,-1] y.value_counts() # In[18]: x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25,random_state=42) print("x_train",x_train.shape) print("x_test",x_test.shape) print("y_train",y_train.shape) print("y_test",x_test.shape) # In[19]: rf=RandomForestClassifier(n_jobs=-1) param_rf={'n_estimators':[50,100,200,250],'criterion':['gini','entropy'],'max_depth':[3,5,10,None],'min_samples_leaf':randint(1,3),'max_features':['auto','sqrt','log2'],'bootstrap':[True,False]} # In[20]: rf_random_cv=RandomizedSearchCV(rf,param_distributions=param_rf,cv=5,n_jobs=-1,n_iter=10) # In[21]: rf_random_cv.fit(x_train,y_train) # In[22]: print("the best score is",rf_random_cv.best_score_) print("the best estimator is",rf_random_cv.best_estimator_) print("the best params is",rf_random_cv.best_params_) # In[23]: d_tree=DecisionTreeClassifier() # In[24]: param_d_tree=param_rf={'criterion':['gini','entropy'],'max_depth':[3,5,10,None],'min_samples_leaf':randint(1,3),'max_features':['auto','sqrt','log2']} # In[25]: rscv_tree=RandomizedSearchCV(d_tree,param_distributions=param_d_tree,cv=5,n_jobs=-1,n_iter=10,return_train_score=False) # In[26]: rscv_tree.fit(x_train,y_train) # In[27]: print("the best score is",rscv_tree.best_score_) print("the best estimator is",rscv_tree.best_estimator_) print("the best params is",rscv_tree.best_params_) # In[28]: lr=LogisticRegression() # In[29]: lr_param={'penalty':['none'],'C':[1,0.1,0.0,1],'solver':['lbfgs']} # In[30]: rscv_lr=RandomizedSearchCV(lr,param_distributions=lr_param,n_jobs=-1,n_iter=10,cv=5,return_train_score=False) # In[31]: rscv_lr.fit(x_train,y_train) # In[32]: print('the best score',rscv_lr.best_score_) print(' the best parameter is',rscv_lr.best_params_) # In[33]: print(pd.DataFrame([{'model':'RandomForest','Best Score':rf_random_cv.best_score_},{'model':'DecisionTree','Best Score':rf_random_cv.best_score_},{'model':'LogisticRegression','Best Score':rf_random_cv.best_score_}])) # In[34]: lr_new=LogisticRegression(penalty='none',C=1.0,solver='lbfgs') # In[35]: lr_new.fit(x_train,y_train) # In[44]: lr_new.score(x_test,y_test) # In[48]: y_pred=lr_new.predict(x_test) # In[49]: from sklearn.metrics import confusion_matrix,classification_report,accuracy_score print("classification report is") print(classification_report(y_test,y_pred)) print(accuracy_score(y_test,y_pred)) # In[51]: plt.figure(figsize=(6,3)) conf= confusion_matrix(y_test,y_pred) sns.heatmap(conf,annot=True,cmap='coolwarm') plt.title('confusion matrix') # In[ ]:
Shell
UTF-8
287
3.0625
3
[ "Apache-2.0" ]
permissive
#!/bin/sh set -eux origin=$(git remote get-url origin) name=$(printf '%s\n' "$origin" | sed -e 's,\.git/*$,,' -e 's,.*/,,') commit=$(git subtree split --annotate="(${name}) " --prefix=build-aux HEAD) git push git@github.com:datawire/build-aux.git "${commit}:master" "${0%-push}-pull" "$commit"
Markdown
UTF-8
846
3.015625
3
[]
no_license
蜗牛爱吃香蕉 有 N piles bananas 每一把香蕉上有不同数量的bananas [3,6,7,11] [30,11,23,4,20] 每个小时可以吃某一piles 里的N 只香蕉。规定H小时内一定要吃完,吃每把的时候,要不就是吃m只,要不就吃余下的。 koko bananas - 把香蕉吃完函数 canEatAllBananas h 来自于吃法规则 一小时mid 只,一次只吃一把 return h >= H; - while 去疯狂的试 1,2,3,4,5,6,.........Math,max(...piles) 能拿到结果,但是太慢了 最大的来吗? 中间 最大概率最快的,二分查找 二分查找优化查找的效率 简单查找 时间开销是n 二分查找的写法是有规律的 x y 要找的是最小可以的min 可以来优化的 找中间,min = x + ((y - x) >> 1), 中间的小了, mid + 1 新的x 如果大了 mid - 1 新的y 时间复杂度 log2 N
Python
UTF-8
434
2.546875
3
[ "MIT" ]
permissive
from pymongo import Connection, json_util import simplejson as json class Stops(object): def get_nearest_stops(self, lat, lon, limit): connection = Connection() db = connection.countdown stops = db.stops nearestStops = list( stops.find({ "loc": { "$near" : [ float(lat), float(lon) ] } }).limit(int(limit)) ) json_data = json.dumps(nearestStops, default=json_util.default) return json_data
JavaScript
UTF-8
3,312
3.59375
4
[]
no_license
// Versión 1: Ponle color a la corbata // const path = document.querySelectorAll("path"); // const boton = document.getElementById("dadContainer_boton") // console.log(path) // let paths = []; // for (let i = 0; i <= 172; i++) { // paths.push(path[i]); // } // function barajar(array) { // let n = array.length - 1; // for (let i = n; i > 1; i--) { // let random = Math.floor(i * Math.random()); // let temp = array[i]; // array[i] = array[random]; // array[random] = temp; // } // return array; // } // function apagarPaths() { // for (let i = 0; i <= paths.length - 1; i++) { // let randomOpacity = Math.random() // paths[i].style.opacity = randomOpacity; // } // } // function colorRandom() { // let set = "0123456789ABCDEF"; // let codigo = []; // for (let i = 0; i <= 5; i++) { // let num = Math.floor(Math.random() * 16); // codigo.push(set[num]); // } // let codigoColor = "#" + codigo.join(""); // return codigoColor; // } // function pintar() { // // barajar(paths); // apagarPaths() // let i = 0; // let timer = window.setInterval(function () { // paths[i].style.opacity = 1; // let color = colorRandom() // paths[130].style.fill = color; // paths[131].style.fill = color; // if (i === paths.length - 1) { // clearInterval(timer); // } // i++; // }, 10); // } // let ciclo // function pintarCiclo() { // // barajar(paths); // apagarPaths() // pintar(); // } // function pintarCiclos() { // pintarCiclo() // ciclo = setInterval(pintarCiclo, 1730 ) // } // function detenerPintarCiclos(){ // clearInterval(ciclo) // } // let control = 0 // function togglePintarCiclos() { // if (control===0) { // pintarCiclos() // control = 1 // boton.innerHTML = '<i class="far fa-pause-circle"></i>' // } // else { // detenerPintarCiclos() // control = 0 // boton.innerHTML = '<i class="far fa-play-circle"></i>' // } // } ////////////////////////////////////////////////////////////////////////////// // Versión 2 : Ponle color a la corbata const paths = document.querySelectorAll("path"); const boton = document.getElementById("dadContainer_boton") function activarPathsOriginales() { for (let i = 0; i <= paths.length - 1; i++) { paths[i].style.opacity = 1; paths[i].style.strokeWidth = .5; } } function colorRandom() { let set = "0123456789ABCDEF"; let codigo = []; for (let i = 0; i <= 5; i++) { let num = Math.floor(Math.random() * 16); codigo.push(set[num]); } let codigoColor = "#" + codigo.join(""); return codigoColor; } let ciclo function pintarPaths(){ for(let i=1; i<=172; i++){ let op = Math.random() paths[i].style.opacity= op let color = colorRandom() paths[130].style.fill = color; paths[131].style.fill = color; } } function pintarPathsCiclos(){ ciclo = setInterval(pintarPaths, 50) } function pararPintarPathsCiclos(){ clearInterval(ciclo) } let control = 0 function togglePintarPathsCiclos() { if (control===0) { pintarPathsCiclos() control = 1 boton.innerHTML = '<i class="far fa-pause-circle"></i>' } else { pararPintarPathsCiclos() activarPathsOriginales() control = 0 boton.innerHTML = '<i class="far fa-play-circle"></i>' } }
Java
UTF-8
474
1.8125
2
[]
no_license
package com.primary.service; import java.util.List; import com.primary.bean.TeacClassCourseGrade; import com.primary.bean.TeacClassCourseGradeExample; public interface TeacClassCourseGradeService { public int countByExample(TeacClassCourseGradeExample example); public List<TeacClassCourseGrade> selectByExample(TeacClassCourseGradeExample example); public TeacClassCourseGradeExample createDefaultExample(TeacClassCourseGrade record); }
C#
UTF-8
413
3.234375
3
[]
no_license
using System.Linq; public static class PermMissingElem { public static int Solution(int[] a) { if (a.Length <= 0) return 0; var size = a.Length + 1; var sum = size * (1 + size) / 2; //https://en.wikipedia.org/wiki/Arithmetic_progression#Sum var aSum = 0; for (int i = 0; i < a.Length; i++) aSum += a[i]; return sum - aSum; } }
Java
UTF-8
253
1.773438
2
[]
no_license
package spikes.sneer.kernel.container; import java.io.File; import basis.brickness.Brick; @Brick public interface SneerConfig extends ContainerConfig { File sneerDirectory(); File brickDirectory(Class<?> brickClass); File tmpDirectory(); }
Markdown
UTF-8
849
3.578125
4
[]
no_license
### What is Markdown? Markdown is a way to style text on the web. You control the display of the document; formatting words as bold or italic, adding images, and creating lists are just a few of the things we can do with Markdown. ### Syntax guide First Header | Second Header ------------ | ------------- Headers | ``` # This is an <h1> tag ``` italic | ``` *This text will be italic* ``` bold | ``` **This text will be bold** ``` Lists Unordered | ``` * Item 1``` Lists Ordered | ``` 1. Item 1``` Images | ``` ![GitHub Logo](/images/logo.png) ``` Links | ``` [GitHub](http://github.com) ``` Blockquotes | ``` > We're living the future so ``` Inline code | ``` I think you should use an `<addr>` element here instead. ``` Learn more [link](https://help.github.com/en/github/writing-on-github/basic-writing-and-formatting-syntax#styling-text)!
Java
UTF-8
1,883
2.875
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 e1; /** * * @author Brais */ public final class Cliente extends Persona { private final String code; private final int numCompras; public Cliente(String nome, String apellidos, String DNI,String code, int numCompras, String direccion, int telefono) { this.code = code; this.numCompras = numCompras; this.nome = nome; this.apellidos = apellidos; this.DNI = DNI; this.direccion = direccion; this.telefono = telefono; } public Cliente(String nome, String apellidos, String DNI,String code, int numCompras, int telefono) { this.code = code; this.numCompras = numCompras; this.nome = nome; this.apellidos = apellidos; this.DNI = DNI; this.telefono = telefono; this.direccion = "Sin direccion"; } public Cliente(String nome, String apellidos, String DNI,String code, int numCompras, String direccion) { this.code = code; this.numCompras = numCompras; this.nome = nome; this.apellidos = apellidos; this.DNI = DNI; this.direccion = direccion; } public Cliente(String nome, String apellidos, String DNI,String code, int numCompras) { this.code = code; this.numCompras = numCompras; this.nome = nome; this.apellidos = apellidos; this.DNI = DNI; this.direccion = "Sin direccion"; } @Override public String toString(){ return nome+" "+apellidos+" "+DNI+" "+code+" "+Integer.toString(numCompras)+" "+direccion+" "+Integer.toString(telefono); } }
Markdown
UTF-8
5,374
2.671875
3
[]
no_license
--- description: "Steps to Prepare Quick Crab Cream Gratin" title: "Steps to Prepare Quick Crab Cream Gratin" slug: 1241-steps-to-prepare-quick-crab-cream-gratin date: 2020-04-20T08:52:50.137Z image: https://img-global.cpcdn.com/recipes/32cc66a9aa3ba427/751x532cq70/crab-cream-gratin-recipe-main-photo.jpg thumbnail: https://img-global.cpcdn.com/recipes/32cc66a9aa3ba427/751x532cq70/crab-cream-gratin-recipe-main-photo.jpg cover: https://img-global.cpcdn.com/recipes/32cc66a9aa3ba427/751x532cq70/crab-cream-gratin-recipe-main-photo.jpg author: Hettie Hampton ratingvalue: 4.6 reviewcount: 3 recipeingredient: - " Crab Sticks Crab meat" - "1/2 Onion" - "50 g Butter" - "3 tbsp Flour" - "250 ml Milk" - "40 g Panko Japanese Bread Crumbs" - "1/2 cube Consomm or half a tsp" - " Pizza Cheese" - "to taste Parsley" - "to taste Salt and pepper" - "1 tbsp Olive Oil" recipeinstructions: - "First you will need a reasonably sized microwave safe container to put the ingredients in. I used a glass oven dish." - "Cut the onion into pieces and pull crab sticks apart to make thin strings of crab meat." - "Add the butter to the bowl and heat in the microwave at 600w for 1min or until completely melted." - "Take out the container and add the flour and milk, mix well and microwave for a further 2mins." - "Take out the container and mix well, add consommé, onion, crab sticks and salt and pepper to taste. Reheat in the microwave for a further 3 mins." - "Take out container and once again mix ingredients well, sprinkle pizza cheese on top and reheat for 1 minute." - "Heat a frying pan with the olive oil, add panko and lightly cook until slightly toasted, sprinkle on top of the dish and add parsley to taste, serve with bread or rice." categories: - Recipe tags: - crab - cream - gratin katakunci: crab cream gratin nutrition: 166 calories recipecuisine: American preptime: "PT23M" cooktime: "PT60M" recipeyield: "2" recipecategory: Dinner --- ![Crab Cream Gratin](https://img-global.cpcdn.com/recipes/32cc66a9aa3ba427/751x532cq70/crab-cream-gratin-recipe-main-photo.jpg) Hey everyone, it is Jim, welcome to our recipe site. Today, I will show you a way to make a special dish, crab cream gratin. One of my favorites. This time, I will make it a bit unique. This is gonna smell and look delicious. Crab Cream Gratin is one of the most popular of recent trending foods on earth. It is simple, it is quick, it tastes yummy. It is appreciated by millions every day. They're fine and they look wonderful. Crab Cream Gratin is something that I've loved my whole life. Red pepper sauce adds a little kick to a creamy crab mixture topped with crunchy bread crumbs. Instead of the heavy cream I use one can of evaporated milk and I also substitute the crab. Learn how to make Creamy Crabmeat au Gratin. To begin with this particular recipe, we have to prepare a few components. You can have crab cream gratin using 11 ingredients and 7 steps. Here is how you cook that. <!--inarticleads1--> ##### The ingredients needed to make Crab Cream Gratin: 1. Prepare Crab Sticks/ Crab meat 1. Take 1/2 Onion 1. Take 50 g Butter 1. Make ready 3 tbsp Flour 1. Prepare 250 ml Milk 1. Take 40 g Panko (Japanese Bread Crumbs) 1. Get 1/2 cube Consommé (or half a tsp) 1. Take Pizza Cheese 1. Make ready to taste Parsley 1. Prepare to taste Salt and pepper 1. Prepare 1 tbsp Olive Oil A crabmeat au gratin casserole made with a butter and cream sauce and topped with Velveeta. I picked up some crabmeat the other day, thinking that I would cook some pan fried crab cakes. This easy creamy crab dip is made with canned crab meat, but feel free to use freshly cooked crab if Either way, your seafood dip will be a hit! Cream cheese and mayonnaise are combined with the. <!--inarticleads2--> ##### Instructions to make Crab Cream Gratin: 1. First you will need a reasonably sized microwave safe container to put the ingredients in. I used a glass oven dish. 1. Cut the onion into pieces and pull crab sticks apart to make thin strings of crab meat. 1. Add the butter to the bowl and heat in the microwave at 600w for 1min or until completely melted. 1. Take out the container and add the flour and milk, mix well and microwave for a further 2mins. 1. Take out the container and mix well, add consommé, onion, crab sticks and salt and pepper to taste. Reheat in the microwave for a further 3 mins. 1. Take out container and once again mix ingredients well, sprinkle pizza cheese on top and reheat for 1 minute. 1. Heat a frying pan with the olive oil, add panko and lightly cook until slightly toasted, sprinkle on top of the dish and add parsley to taste, serve with bread or rice. Stir in half of the sherry, beat in the egg yolk well and remove from heat. Jumbo Lumb Gulf Crab Au Gratin. Add the flour to the skillet, and blend well into the vegetables to cream a white roux; don&#39;t let the flour brown. Pour mixture into a gratin dish, and top with cheese. Home » Casserole Recipes » Crab and Shrimp Au Gratin. So that is going to wrap this up for this exceptional food crab cream gratin recipe. Thanks so much for your time. I am sure that you will make this at home. There is gonna be more interesting food in home recipes coming up. Remember to bookmark this page in your browser, and share it to your family, friends and colleague. Thank you for reading. Go on get cooking!
Markdown
UTF-8
3,673
3.34375
3
[]
no_license
# Report *Please include a short, 300-word report that highlights three technical elements of your implementation that you find notable, explain what problem they solve and why you chose to implement it in this way. Include this in your repository as a report.md file.* ## rich console: Implemented *rich console*, very helpful for understanding the console at a quick glance. For example using: ``` else: console.print( f'[red]ERROR: {args.expiry} is not a valid date, enter in YYYY-MM-DD format.[/red]') ``` When you see a long bright red line that starts with ERROR it is very clear something is wrong and needs attention. Similarly when querying for the profits on a specific date it will print green for profit and red for loss. Even before you start to read the exact number you will know if you've made a profit or a loss: ``` if total_profit >= 0: console.print('[green]€ {:.2f}[/green]'.format(total_profit)) else: console.print('[red]€ {:.2f}[/red]'.format(total_profit)) ``` ## File handling Every function is called via main(), which is always run trough the ``` if __name__ == '__main__': main() ``` code at the bottom of main.py. By including some code at the start of main(), I have made sure there are some checks done before the CLI commands are run. ``` def main(): file_functions.checkdir() # this should execute before every CLI command ``` This code calls the checkdir() function in file_functions.py which has a few features. It checks if the current working dir is correct: ``` if directory == 'superpy': (...) else: raise Exception('\tERROR Change working directory to \\superpy') ``` And if some required files don't exist, it will create new ones in the correct format: ``` # create 'date.txt' if not found if file_found('date.txt') is False: with open('date.txt', 'a', newline='') as newfile: newfile.write( '') date_functions.write_date('today') # create 'bought.csv' if not found if file_found('bought.csv') is False: with open('bought.csv', 'a', newline='') as newfile: newfile.write( 'ID,product name,buy date,buy price,expiration date\n') ``` ## Home Automation and phone notifications Just for fun added a link that interacts with my Homey home automation controller. Inspired by the movie Middle Men (2009) I thought it would be funny that a sale would generate a doorbell sound (ding! ding!) inside my house. Akin to the buzzer sounding when they had a sale in the movie. I then added a little bit extra to teach myself how to pass information to Homey from superpy. This results in a bit of text being send through the Homey Telegram Bot; being the *product name, total revenue* and *total profit* for the day. It is not used by default and there are no extra commands required to leave it off. Only if you want to use it (novelty wears off quickly) you have to specify an extra command. This is handled in the following code <code>sell_parser.add_argument('--ding', default='off', (...))</code> Obviously I took out my private key from the code. You can insert your own Homey cloud ID in the *dingding()* function and then create the following flow in the Homey app: ![homey flow](https://github.com/CreateYourAccount-username/superpy/blob/CreateYourAccount-images/homey%20flow.png?raw=true) In combination with the Homey Telegram Bot this results in the following notification on your phone. ![phone notification](https://github.com/CreateYourAccount-username/superpy/blob/CreateYourAccount-images/notification.jpg?raw=true)
JavaScript
UTF-8
1,215
2.515625
3
[ "MIT" ]
permissive
(function(){ var map = L.map('map').setView([39.2500,-97.743061], 4); L.tileLayer('http://{s}.tiles.mapbox.com/v3/examples.map-i875mjb7/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>', maxZoom: 18 }).addTo(map); var locations = { 'austin':{ name:'Austin', lat:30.2500, lng:-97.743061, }, 'nyc':{ name:'New York City', lat:40.8075, lng:-73.9619, }, 'la':{ name:'Los Angeles', lat:34.052234, lng:-118.243685, }, 'chi':{ name:'Chicago', lat:41.878114, lng:-87.629798, } }; $('.option').on('click', function(){ var id = $(this).attr('data-which'); var latlng = L.latLng(locations[id].lat, locations[id].lng); map.setView(latlng, 11); }); $('#findMe').on('click',function(e){ map.locate({setView:true, maxZoom: 15}); $('.load').addClass('appear'); $('.image').addClass('disappear'); map.on('locationfound',function(){ $('.load').removeClass('appear'); $('.image').removeClass('disappear'); L.marker(e.latlng); }); }); }).call(this);
Shell
UTF-8
1,543
4.0625
4
[]
no_license
#!/bin/bash if [ -z "$2" ]; then echo "usage: $0 <site> <days> [-list]" echo " [-list] - generates list without archiving or removing." exit fi SITED=$1 DAYS=$2 LISTONLY=$3 LOGDIR="/web/$SITED/htdocs/sites/default/files/contentwatch" if [ -d $LOGDIR ]; then echo "$LISTONLY $LOGDIR in progress...." cd $LOGDIR else echo "Directory does not exist! $LOGDIR" exit 1 fi TIMESTAMP=`date +%s` # Generate list of "old" files `find . -name \*.txt -mtime +$DAYS -print > $TIMESTAMP"."contentwatch_cleanup.lst` #echo "find create -name \*.txt -mtime +$DAYS -print > $TIMESTAMP"."contentwatch_cleanup.lst" # Check to make sure we had permission if [ ! -f $TIMESTAMP."contentwatch_cleanup.lst" ]; then echo There was a problem generating the list of files to cleanup. exit 1 fi # Check to make sure the list is not empty. if [ ! -s $TIMESTAMP."contentwatch_cleanup.lst" ]; then echo No files were found to cleanup. rm $TIMESTAMP."contentwatch_cleanup.lst" exit else NUMFILES=`cat $TIMESTAMP."contentwatch_cleanup.lst" | wc -l ` fi if [ "$LISTONLY" != "-list" ]; then echo List: $TIMESTAMP."contentwatch_cleanup.lst" echo "Archiving $NUMFILES files..." `cat $TIMESTAMP."contentwatch_cleanup.lst" | xargs chmod 666` `cat $TIMESTAMP."contentwatch_cleanup.lst" | xargs chown duane.jennings` `tar -czvpf $TIMESTAMP."contentwatch.tgz" --remove-files --files-from $TIMESTAMP."contentwatch_cleanup.lst"` else cat $TIMESTAMP."contentwatch_cleanup.lst" echo $NUMFILES files are in the list. rm $TIMESTAMP."contentwatch_cleanup.lst" fi
Java
UTF-8
612
2.59375
3
[]
no_license
package com.qx.common.tools; import java.io.UnsupportedEncodingException; /** * * @author Administrator * */ public class StringTools { public static boolean isNotBlank(Object obj) { if (obj == null) { return false; } if (obj.toString().trim().equals("")) { return false; } return true; } public static String decodeMethod(String str) { String retStr = ""; try { if (isNotBlank(str)) { retStr = java.net.URLDecoder.decode(str, "UTF-8"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return retStr; } }
JavaScript
UTF-8
450
3.21875
3
[]
no_license
// Reflect.get方法查找并返回target对象的name属性,如果没有该属性,则返回undefined。 let obj = { a: 1, get g() { return this.a; }, }; console.log(Reflect.get(obj, 'a'), Reflect.get(obj, 'z')); // 取值器函数返回取出的值,其中的this是receiver||本身 console.log(Reflect.get(obj, 'g'), Reflect.get(obj, 'g', {a: 10})); // 如果第一个参数不是对象,Reflect.get方法会报错。
TypeScript
UTF-8
1,036
2.640625
3
[]
no_license
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; import { TodoModel } from '../../models/todo-model'; @Component({ selector: 'app-todo', templateUrl: './todo.component.html', styleUrls: ['./todo.component.css'] }) export class TodoComponent implements OnInit { // @Input : pour que le todo soit parametrable dans le composant parent AppComponent // app.component.html : <app-todo *ngFor="let todo of todoList" [todo]="todo" (deleteTriggered)="deleteTodo($event)"></app-todo> @Input() todo: TodoModel; // @Output : notifier le composant parent d'un changement au niveau du composant enfant // le bouton 'supprimer' se trouve dans TodoComponent et la liste des todos dans AppComponent // => combiner EventEmitter et @Output @Output() deleteTriggered: EventEmitter<TodoModel> = new EventEmitter<TodoModel>(); constructor() { } ngOnInit() { } deleteTodo() { console.log('deleteTriggered emit pour le todo', this.todo); this.deleteTriggered.emit(this.todo); } }
C++
UTF-8
2,437
3.203125
3
[]
no_license
#pragma once #include "converter.hpp" #include "format.hpp" enum color { red, green, blue }; inline const char* color_names[] = {"red", "green", "blue"}; template <class Char> struct lrstd::formatter<color, Char> : lrstd::formatter<const Char*, Char> { // TODO: the implementation of formatted_size and format_to_n use special // iterators, which requires this to be templated on the output iterator. is // that conforming? template <class Out> auto format(color c, basic_format_context<Out, Char>& ctx) { return formatter<const Char*, Char>::format( str_fn<Char>{}(color_names[c]), ctx); } }; struct S { int value; }; template <class Char> struct lrstd::formatter<S, Char> { size_t width_arg_id = 0; // Parses a width argument id in the format { digit }. constexpr auto parse(basic_format_parse_context<Char>& ctx) { auto iter = ctx.begin(); auto get_char = [&]() -> int { return iter != ctx.end() ? *iter : 0; }; if (get_char() != '{') return iter; ++iter; int c = get_char(); if (!isdigit(c) || (++iter, get_char()) != '}') throw format_error("invalid format"); width_arg_id = static_cast<std::size_t>(c - '0'); ctx.check_arg_id(width_arg_id); return ++iter; } template <class Int> static constexpr bool in_width_range(Int i) noexcept { if constexpr (std::is_signed_v<Int>) { if (i < 0) return false; } using Biggest = std::conditional_t<std::is_signed_v<Int>, long long, unsigned long long>; return i <= static_cast<Biggest>(std::numeric_limits<int>::max()); } // Formats an S with width given by the argument width_­arg_­id. template <class Out> auto format(S s, basic_format_context<Out, Char>& ctx) { int width = visit_format_arg( [](auto value) -> int { if constexpr (!std::is_integral_v<decltype(value)>) throw format_error("width is not integral"); else if (!in_width_range(value)) throw format_error("invalid width"); else return static_cast<int>(value); }, ctx.arg(width_arg_id)); return format_to(ctx.out(), "{0:x>{1}}", s.value, width); } };
Markdown
UTF-8
23,369
3.0625
3
[]
no_license
# Vue.js概述 [参考](https://cn.vuejs.org/v2/guide/installation.html) Vue.js(读音 /vjuː/, 类似于 view) 是一套构建用户界面的渐进式框架。 Vue 只关注视图层, 采用自底向上增量开发的设计。 Vue 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。 ## 安装 - 独立版本 ``` 在 Vue.js 的官网上直接下载 vue.min.js 并用 <script> 标签引入。 <script src="/static/js/vue.js"></script> ``` - 网络版本 ``` BootCDN(国内) : https://cdn.bootcss.com/vue/2.2.2/vue.min.js unpkg:https://unpkg.com/vue/dist/vue.js, 会保持和 npm 发布的最新的版本一致。 cdnjs : https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.min.js ``` - NPM方法 > 安装Node版本管理工具 ```shell // 版本管理工具 brew install nvm nvm ls-remote // 查看可安装版本 nvm ls // 列出可安装版本 nvm install xxx // 安装可用版本 nvm use xxx // 切换版本 nvm run 4.2.2 --version // 直接运行特定版本的 Node nvm exec 4.2.2 node --version //在当前终端的子进程中运行特定版本的 Node nvm which 4.2.2 //确认某个版本Node的路径 //从特定版本导入到我们将要安装的新版本 Node: nvm install v5.0.0 --reinstall-packages-from=4.2 ``` > 安装vue ```shell # 安装node.js brew install node # 使用淘宝镜像 npm install -g cnpm --registry=https://registry.npm.taobao.org # 安装vue cnpm install vue ``` ## 命令行 Vue.js 提供一个官方命令行工具,可用于快速搭建大型单页应用。 ```shell # 旧版 # 全局安装 vue-cli cnpm install -g vue-cli # 创建一个基于 webpack 模板的新项目(项目名不能大写) vue init webpack my-project # 这里需要进行一些配置,默认回车即可 ... # 新版 cnpm install -g @vue/cli vue create my-project ``` 进入项目,安装并运行 ```shell cd my-project cnpm install # 安装依赖 cnpm run dev # dev方式运行 ``` 项目打包 ```shell cnpm run build ``` ## 目录结构 使用npm安装项目,则目录结构汇总包含如下 | 目录/文件 | 说明 | | ------------ | ------------------------------------------------------------ | | build | 项目构建(webpack)相关代码 | | config | 配置目录,包括端口号等 | | node_modules | npm加载的项目依赖模块 | | src | 开发目录,包括:<br>assets:放置一些图片,如logo等<br>components:目录里面放了一个组件文件,可以不用<br>App.vue:项目入口文件,可以直接将组件写在这里,二不适用components目录<br>main.js:项目的核心文件 | | static | 静态资源目录,如图片、字体等 | | test | 初始测试目录,可删除 | | .xxx文件 | 配置文件,包括语法配置,git配置等 | | index.html | 首页入口文件,可添加一些meta信息或统计代码 | | package.json | 项目配置文件 | | README.md | 项目说明文档 | ## 介绍 ### 声明式渲染 [观看本节视频讲解](https://learning.dcloud.io/#/?vid=3) Vue.js 的核心是一个允许采用简洁的模板语法来声明式地将数据渲染进 DOM 的系统: ```js <div id="app"> {{ message }} </div> ``` ```js var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' } }) ``` 我们已经成功创建了第一个 Vue 应用!看起来这跟渲染一个字符串模板非常类似,但是 Vue 在背后做了大量工作。现在数据和 DOM 已经被建立了关联,所有东西都是**响应式的**。我们要怎么确认呢?打开你的浏览器的 JavaScript 控制台 (就在这个页面打开),并修改 `app.message` 的值,你将看到上例相应地更新。 除了文本插值,我们还可以像这样来绑定元素特性: ```html <div id="app-2"> <span v-bind:title="message"> 鼠标悬停几秒钟查看此处动态绑定的提示信息! </span> </div> ``` ```js var app2 = new Vue({ el: '#app-2', data: { message: '页面加载于 ' + new Date().toLocaleString() } }) ``` 这里我们遇到了一点新东西。你看到的 `v-bind` 特性被称为**指令**。指令带有前缀 `v-`,以表示它们是 Vue 提供的特殊特性。可能你已经猜到了,它们会在渲染的 DOM 上应用特殊的响应式行为。在这里,该指令的意思是:“将这个元素节点的 `title` 特性和 Vue 实例的 `message` 属性保持一致”。 如果你再次打开浏览器的 JavaScript 控制台,输入 `app2.message = '新消息'`,就会再一次看到这个绑定了 `title` 特性的 HTML 已经进行了更新。 ### 条件与循环 [观看本节视频讲解](https://learning.dcloud.io/#/?vid=8) 控制切换一个元素是否显示也相当简单: ```html <div id="app-3"> <p v-if="seen">现在你看到我了</p> </div> ``` ```js var app3 = new Vue({ el: '#app-3', data: { seen: true } }) ``` 这个例子演示了我们不仅可以把数据绑定到 DOM 文本或特性,还可以绑定到 DOM **结构**。此外,Vue 也提供一个强大的过渡效果系统,可以在 Vue 插入/更新/移除元素时自动应用[过渡效果](https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/guide/transitions.html)。 还有其它很多指令,每个都有特殊的功能。例如,`v-for` 指令可以绑定数组的数据来渲染一个项目列表: ```html <div id="app-4"> <ol> <li v-for="todo in todos"> {{ todo.text }} </li> </ol> </div> ``` ```js var app4 = new Vue({ el: '#app-4', data: { todos: [ { text: '学习 JavaScript' }, { text: '学习 Vue' }, { text: '整个牛项目' } ] } }) ``` 在控制台里,输入 `app4.todos.push({ text: '新项目' })`,你会发现列表最后添加了一个新项目。 ### 处理用户输入 [观看本节视频讲解](https://learning.dcloud.io/#/?vid=11) 为了让用户和你的应用进行交互,我们可以用 `v-on` 指令添加一个事件监听器,通过它调用在 Vue 实例中定义的方法: ```html <div id="app-5"> <p>{{ message }}</p> <button v-on:click="reverseMessage">反转消息</button> </div> ``` ```js var app5 = new Vue({ el: '#app-5', data: { message: 'Hello Vue.js!' }, methods: { reverseMessage: function () { this.message = this.message.split('').reverse().join('') } } }) ``` 注意在 `reverseMessage` 方法中,我们更新了应用的状态,但没有触碰 DOM——所有的 DOM 操作都由 Vue 来处理,你编写的代码只需要关注逻辑层面即可。 Vue 还提供了 `v-model` 指令,它能轻松实现表单输入和应用状态之间的双向绑定。 ```html <div id="app-6"> <p>{{ message }}</p> <input v-model="message"> </div> ``` ```js var app6 = new Vue({ el: '#app-6', data: { message: 'Hello Vue!' } }) ``` ### 组件化应用构建 [观看本节视频讲解](https://learning.dcloud.io/#/?vid=12) 组件系统是 Vue 的另一个重要概念,因为它是一种抽象,允许我们使用小型、独立和通常可复用的组件构建大型应用。仔细想想,几乎任意类型的应用界面都可以抽象为一个组件树: ![components](https://cn.vuejs.org/images/components.png) 在 Vue 里,一个组件本质上是一个拥有预定义选项的一个 Vue 实例。在 Vue 中注册组件很简单: ```js // 定义名为 todo-item 的新组件 Vue.component('todo-item', { template: '<li>这是个待办项</li>' }) var app = new Vue(...) ``` 现在你可以用它构建另一个组件模板: ```html <ol> <!-- 创建一个 todo-item 组件的实例 --> <todo-item></todo-item> </ol> ``` 但是这样会为每个待办项渲染同样的文本,这看起来并不炫酷。我们应该能从父作用域将数据传到子组件才对。让我们来修改一下组件的定义,使之能够接受一个 [prop](https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/guide/components.html#通过-Prop-向子组件传递数据): ```js Vue.component('todo-item', { // todo-item 组件现在接受一个 // "prop",类似于一个自定义特性。 // 这个 prop 名为 todo。 props: ['todo'], template: '<li>{{ todo.text }}</li>' }) ``` 现在,我们可以使用 `v-bind` 指令将待办项传到循环输出的每个组件中: ```html <div id="app-7"> <ol> <!-- 现在我们为每个 todo-item 提供 todo 对象 todo 对象是变量,即其内容可以是动态的。 我们也需要为每个组件提供一个“key”,稍后再 作详细解释。 --> <todo-item v-for="item in groceryList" v-bind:todo="item" v-bind:key="item.id" ></todo-item> </ol> </div> ``` ```js Vue.component('todo-item', { props: ['todo'], template: '<li>{{ todo.text }}</li>' }) var app7 = new Vue({ el: '#app-7', data: { groceryList: [ { id: 0, text: '蔬菜' }, { id: 1, text: '奶酪' }, { id: 2, text: '随便其它什么人吃的东西' } ] } }) ``` 尽管这只是一个刻意设计的例子,但是我们已经设法将应用分割成了两个更小的单元。子单元通过 prop 接口与父单元进行了良好的解耦。我们现在可以进一步改进 `` 组件,提供更为复杂的模板和逻辑,而不会影响到父单元。 在一个大型应用中,有必要将整个应用程序划分为组件,以使开发更易管理。在[后续教程](https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/guide/components.html)中我们将详述组件,不过这里有一个 (假想的) 例子,以展示使用了组件的应用模板是什么样的: ```html <div id="app"> <app-nav></app-nav> <app-view> <app-sidebar></app-sidebar> <app-content></app-content> </app-view> </div> ``` ### 与自定义元素的关系 你可能已经注意到 Vue 组件非常类似于**自定义元素**——它是 [Web 组件规范](https://www.w3.org/wiki/WebComponents/)的一部分,这是因为 Vue 的组件语法部分参考了该规范。例如 Vue 组件实现了 [Slot API](https://github.com/w3c/webcomponents/blob/gh-pages/proposals/Slots-Proposal.md) 与 `is` 特性。但是,还是有几个关键差别: 1. Web Components 规范已经完成并通过,但未被所有浏览器原生实现。目前 Safari 10.1+、Chrome 54+ 和 Firefox 63+ 原生支持 Web Components。相比之下,Vue 组件不需要任何 polyfill,并且在所有支持的浏览器 (IE9 及更高版本) 之下表现一致。必要时,Vue 组件也可以包装于原生自定义元素之内。 2. Vue 组件提供了纯自定义元素所不具备的一些重要功能,最突出的是跨组件数据流、自定义事件通信以及构建工具集成。 虽然 Vue 内部没有使用自定义元素,不过在应用使用自定义元素、或以自定义元素形式发布时,[依然有很好的互操作性](https://custom-elements-everywhere.com/#vue)。Vue CLI 也支持将 Vue 组件构建成为原生的自定义元素。 ## 实例 ### 创建一个 Vue 实例 [观看本节视频讲解](https://learning.dcloud.io/#/?vid=2) 每个 Vue 应用都是通过用 `Vue` 函数创建一个新的 **Vue 实例**开始的: ```js var vm = new Vue({ // 选项 }) ``` 虽然没有完全遵循 [MVVM 模型](https://zh.wikipedia.org/wiki/MVVM),但是 Vue 的设计也受到了它的启发。因此在文档中经常会使用 `vm` (ViewModel 的缩写) 这个变量名表示 Vue 实例。 当创建一个 Vue 实例时,你可以传入一个**选项对象**。这篇教程主要描述的就是如何使用这些选项来创建你想要的行为。作为参考,你也可以在 [API 文档](https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/api/#选项-数据) 中浏览完整的选项列表。 一个 Vue 应用由一个通过 `new Vue` 创建的**根 Vue 实例**,以及可选的嵌套的、可复用的组件树组成。举个例子,一个 todo 应用的组件树可以是这样的: ``` 根实例 └─ TodoList ├─ TodoItem │ ├─ DeleteTodoButton │ └─ EditTodoButton └─ TodoListFooter ├─ ClearTodosButton └─ TodoListStatistics ``` 我们会在稍后的[组件系统](https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/guide/components.html)章节具体展开。不过现在,你只需要明白所有的 Vue 组件都是 Vue 实例,并且接受相同的选项对象 (一些根实例特有的选项除外)。 ### 数据与方法 [观看本节视频讲解](https://learning.dcloud.io/#/?vid=3) 当一个 Vue 实例被创建时,它将 `data` 对象中的所有的属性加入到 Vue 的**响应式系统**中。当这些属性的值发生改变时,视图将会产生“响应”,即匹配更新为新的值。 ```js // 我们的数据对象 var data = { a: 1 } // 该对象被加入到一个 Vue 实例中 var vm = new Vue({ data: data }) // 获得这个实例上的属性 // 返回源数据中对应的字段 vm.a == data.a // => true // 设置属性也会影响到原始数据 vm.a = 2 data.a // => 2 // ……反之亦然 data.a = 3 vm.a // => 3 ``` 当这些数据改变时,视图会进行重渲染。值得注意的是只有当实例被创建时就已经存在于 `data` 中的属性才是**响应式**的。也就是说如果你添加一个新的属性,比如: ```js vm.b = 'hi' ``` 那么对 `b` 的改动将不会触发任何视图的更新。如果你知道你会在晚些时候需要一个属性,但是一开始它为空或不存在,那么你仅需要设置一些初始值。比如: ```js data: { newTodoText: '', visitCount: 0, hideCompletedTodos: false, todos: [], error: null } ``` 这里唯一的例外是使用 `Object.freeze()`,这会阻止修改现有的属性,也意味着响应系统无法再*追踪*变化。 ```js var obj = { foo: 'bar' } Object.freeze(obj) new Vue({ el: '#app', data: obj }) ``` ```html <div id="app"> <p>{{ foo }}</p> <!-- 这里的 `foo` 不会更新! --> <button v-on:click="foo = 'baz'">Change it</button> </div> ``` 除了数据属性,Vue 实例还暴露了一些有用的实例属性与方法。它们都有前缀 `$`,以便与用户定义的属性区分开来。例如: ```js var data = { a: 1 } var vm = new Vue({ el: '#example', data: data }) vm.$data === data // => true vm.$el === document.getElementById('example') // => true // $watch 是一个实例方法 vm.$watch('a', function (newValue, oldValue) { // 这个回调将在 `vm.a` 改变后调用 }) ``` 以后你可以在 [API 参考](https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/api/#实例属性)中查阅到完整的实例属性和方法的列表。 ## 生命周期 [观看本节视频讲解](https://learning.dcloud.io/#/?vid=4) 每个 Vue 实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到 DOM 并在数据变化时更新 DOM 等。同时在这个过程中也会运行一些叫做**生命周期钩子**的函数,这给了用户在不同阶段添加自己的代码的机会。 比如 [`created`](https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/api/#created) 钩子可以用来在一个实例被创建之后执行代码: ```js new Vue({ data: { a: 1 }, created: function () { // `this` 指向 vm 实例 console.log('a is: ' + this.a) } }) // => "a is: 1" ``` 也有一些其它的钩子,在实例生命周期的不同阶段被调用,如 [`mounted`](https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/api/#mounted)、[`updated`](https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/api/#updated) 和 [`destroyed`](https://github.com/vuejs/cn.vuejs.org/blob/master/src/v2/api/#destroyed)。生命周期钩子的 `this` 上下文指向调用它的 Vue 实例。 不要在选项属性或回调上使用[箭头函数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions),比如 `created: () => console.log(this.a)` 或 `vm.$watch('a', newValue => this.myMethod())`。因为箭头函数并没有 `this`,`this` 会作为变量一直向上级词法作用域查找,直至找到为止,经常导致 `Uncaught TypeError: Cannot read property of undefined` 或 `Uncaught TypeError: this.myMethod is not a function` 之类的错误。 ### 生命周期钩子 | vue2.0 | desc | | ------------- | ------------------------------------------------------------ | | beforeCreate | 组件实例刚被创建,组件属性计算之前,如data属性还未初始化 | | created | 组件示例刚创建完成,属性已绑定,但DOM还未生成,`$el`属性还不存在 | | beforeMount | 模版编译/挂载之前,使用虚拟DOM,占位不传值 | | mounted | 模版编译/挂载之后 | | beforeUpdate | 组件更新之前 | | updated | 组件更新之后 | | activated | for`keep-alive`,组件被激活时调用 | | deactivated | for`keep-alive`,组件被移除时调用 | | beforeDestory | 组件销毁前调用 | | Destroyed | 组件销毁后调用 | ### 生命周期图示 <img src="https://cn.vuejs.org/images/lifecycle.png" alt="lifecycle" style="zoom:50%;" /> ### 示例代码 ```html <!DOCTYPE html> <html> <head> <title></title> <script type="text/javascript" src="https://cdn.jsdelivr.net/vue/2.1.3/vue.js"></script> </head> <body> <div id="app"> <p>{{ message }}</p> </div> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { message : "xuxiao is boy" }, beforeCreate: function () { console.group('beforeCreate 创建前状态===============》'); console.log("%c%s", "color:red" , "el : " + this.$el); //undefined console.log("%c%s", "color:red","data : " + this.$data); //undefined console.log("%c%s", "color:red","message: " + this.message) }, created: function () { console.group('created 创建完毕状态===============》'); console.log("%c%s", "color:red","el : " + this.$el); //undefined console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 console.log("%c%s", "color:red","message: " + this.message); //已被初始化 }, beforeMount: function () { console.group('beforeMount 挂载前状态===============》'); console.log("%c%s", "color:red","el : " + (this.$el)); //已被初始化 console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 console.log("%c%s", "color:red","message: " + this.message); //已被初始化 }, mounted: function () { console.group('mounted 挂载结束状态===============》'); console.log("%c%s", "color:red","el : " + this.$el); //已被初始化 console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 console.log("%c%s", "color:red","message: " + this.message); //已被初始化 }, beforeUpdate: function () { console.group('beforeUpdate 更新前状态===============》'); console.log("%c%s", "color:red","el : " + this.$el); console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); console.log("%c%s", "color:red","message: " + this.message); }, updated: function () { console.group('updated 更新完成状态===============》'); console.log("%c%s", "color:red","el : " + this.$el); console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); console.log("%c%s", "color:red","message: " + this.message); }, beforeDestroy: function () { console.group('beforeDestroy 销毁前状态===============》'); console.log("%c%s", "color:red","el : " + this.$el); console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); console.log("%c%s", "color:red","message: " + this.message); }, destroyed: function () { console.group('destroyed 销毁完成状态===============》'); console.log("%c%s", "color:red","el : " + this.$el); console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); console.log("%c%s", "color:red","message: " + this.message) } }) </script> </body> </html> ``` 打开F12可直接查看`create`和`mounted`相关的加载情况 > `beforecreated`:el 和 data 并未初始化 > `created`:完成了 data 数据的初始化,el没有 > `beforeMount`:完成了 el 和 data 初始化 > `mounted` :完成挂载 > > 另外在标红处,我们能发现el还是 {{message}},这里就是应用的 `Virtual DOM`(虚拟Dom)技术,先把坑占住了。到后面`mounted`挂载的时候再把值渲染进去。 在console中执行 ``` app.message= 'yes !! I do'; ``` 下面就能看到data里的值被修改后,将会触发update的操作。 在console中执行 ``` app.$destroy(); ``` 销毁完成后,我们再重新改变message的值,vue不再对此动作进行响应了。但是原先生成的dom元素还存在,可以这么理解,执行了destroy操作,后续就不再受vue控制了。 ### 使用场景 `beforecreate` : 举个栗子:可以在这加个loading事件 `created` :在这结束loading,还做一些初始化,实现函数自执行 `mounted` : 在这发起后端请求,拿回数据,配合路由钩子做一些事情 `beforeDestroy`: 你确认删除XX吗? `destroyed` :当前组件已被删除,清空相关内容 > 注意 > > 不要在选项属性或回调上使用[箭头函数](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions),比如 `created: () => console.log(this.a)` 或 `vm.$watch('a', newValue => this.myMethod())`。因为箭头函数并没有 `this`,`this` 会作为变量一直向上级词法作用域查找,直至找到为止,经常导致 `Uncaught TypeError: Cannot read property of undefined` 或 `Uncaught TypeError: this.myMethod is not a function` 之类的错误。
Java
UTF-8
688
2.328125
2
[]
no_license
package service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import repository.MemberDao; import vo.Member; @Component public class MemberService { @Autowired private MemberDao dao; public void setMemberDao (MemberDao dao){ this.dao = dao; } public boolean loginCheck(String id, String password){ Member member = dao.selectMember(id); if(member==null||!member.getPassword().equals(password)){ return false; } else { return true; } } public boolean join(Member member){ System.out.println(member); if(dao.insertMember(member)>0){ return true; } else { return false; } } }
Markdown
UTF-8
9,905
2.875
3
[ "BSD-2-Clause" ]
permissive
![][digitaljs-logo] # DigitalJS This project is a digital circuit simulator implemented in Javascript. It is designed to simulate circuits synthesized by hardware design tools like [Yosys](https://yosyshq.net/yosys/) (Github repo [here](https://github.com/YosysHQ/yosys/)), and it has a companion project [yosys2digitaljs](https://github.com/tilk/yosys2digitaljs), which converts Yosys output files to DigitalJS. It is also intended to be a teaching tool, therefore readability and ease of inspection is one of top concerns for the project. You can [try it out online](https://digitaljs.tilk.eu/). The web app is [a separate Github project](https://github.com/tilk/digitaljs_online/). # Usage You can use DigitalJS in your project by installing it from NPM: ```bash npm install digitaljs ``` Or you can use the [Webpack bundle](https://tilk.github.io/digitaljs/main.js) directly. To simulate a circuit represented using the JSON input format (described later) and display it on a `div` named `#paper`, you need to run the following JS code ([see running example](https://tilk.github.io/digitaljs/test/fulladder.html)): ```javascript // create the simulation object const circuit = new digitaljs.Circuit(input_goes_here); // display on #paper const paper = circuit.displayOn($('#paper')); // activate real-time simulation circuit.start(); ``` # Input format Circuits are represented using JSON. The top-level object has three keys, `devices`, `connectors` and `subcircuits`. Under `devices` is a list of all devices forming the circuit, represented as an object, where keys are (unique and internal) device names. Each device has a number of properties, which are represented by an object. A mandatory property is `type`, which specifies the type of the device. Example device: ```javascript "dev1": { "type": "And", "label": "AND1" } ``` Under `connectors` is a list of connections between device ports, represented as an array of objects with two keys, `from` and `to`. Both keys map to an object with two keys, `id` and `port`; the first corresponds to a device name, and the second -- to a valid port name for the device. A connection must lead from an output port to an input port, and the bitwidth of both ports must be equal. Example connection: ```javascript { "from": { "id": "dev1", "port": "out" }, "to": { "id": "dev2", "port": "in" } } ``` Under `subcircuits` is a list of subcircuit definitions, represented as an object, where keys are unique subcircuit names. A subcircuit name can be used as a `celltype` for a device of type `Subcircuit`; this instantiates the subcircuit. A subcircuit definition follows the representation of whole circuits, with the exception that subcircuits cannot (currently) define their own subcircuits. A subcircuit can include `Input` and `Output` devices, these are mapped to ports on a subcircuit instance. ## Device types * Unary gates: `Not`, `Repeater` * Attributes: `bits` (natural number) * Inputs: `in` (`bits`-bit) * Outputs: `out` (`bits`-bit) * N-ary gates: `And`, `Nand`, `Or`, `Nor`, `Xor`, `Xnor` * Attributes: `bits` (natural number), `inputs` (natural number, default 2) * Inputs: `in1`, `in2` ... `inN` (`bits`-bit, `N` = `inputs`) * Outputs: `out` (`bits`-bit) * Reducing gates: `AndReduce`, `NandReduce`, `OrReduce`, `NorReduce`, `XorReduce`, `XnorReduce` * Attributes: `bits` (natural number) * Inputs: `in` (`bits`-bit) * Outputs: `out` (1-bit) * Bit shifts: `ShiftLeft`, `ShiftRight` * Attributes: `bits.in1`, `bits.in2` and `bits.out` (natural number), `signed.in1`, `signed.in2`, `signed.out` and `fillx` (boolean) * Inputs: `in1` (`bits.in1`-bit), `in2` (`bits.in2`-bit) * Outputs: `out` (`bits.out`-bit) * Comparisons: `Eq`, `Ne`, `Lt`, `Le`, `Gt`, `Ge` * Attributes: `bits.in1` and `bits.in2` (natural number), `signed.in1` and `signed.in2` (boolean) * Inputs: `in1` (`bits.in1`-bit), `in2` (`bits.in2`-bit) * Outputs: `out` (1-bit) * Number constant: `Constant` * Attributes: `constant` (binary string) * Outputs: `out` (`constant.length`-bit) * Unary arithmetic: `Negation`, `UnaryPlus` * Attributes: `bits.in` and `bits.out` (natural number), `signed` (boolean) * Inputs: `in` (`bits.in`-bit) * Outputs: `out` (`bits.out`-bit) * Binary arithmetic: `Addition`, `Subtraction`, `Multiplication`, `Division`, `Modulo`, `Power` * Attributes: `bits.in1`, `bits.in2` and `bits.out` (natural number), `signed.in1` and `signed.in2` (boolean) * Inputs: `in1` (`bits.in1`-bit), `in2` (`bits.in2`-bit) * Outputs: `out` (`bits.out`-bit) * Multiplexer: `Mux` * Attributes: `bits.in`, `bits.sel` (natural number) * Inputs: `in0` ... `inN` (`bits.in`-bit, `N` = 2**`bits.sel`-1), `sel` (`bits.sel`-bit) * Outputs: `out` (`bits.in`-bit) * One-hot multiplexer: `Mux1Hot` * Attributes: `bits.in`, `bits.sel` (natural number) * Inputs: `in0` ... `inN` (`bits.in`-bit, `N` = `bits.sel`), `sel` (`bits.sel`-bit) * Outputs: `out` (`bits.in`-bit) * Sparse multiplexer: `MuxSparse` * Attributes: `bits.in`, `bits.sel` (natural number), `inputs` (list of natural numbers), `default_input` (optional boolean) * Inputs: `in0` ... `inN` (`bits.in`-bit, `N` = `inputs.length`, +1 if `default_input` is true) * Outputs: `out` (`bits.in`-bit) * D flip-flop: `Dff` * Attributes: `bits` (natural number), `polarity.clock`, `polarity.arst`, `polarity.srst`, `polarity.aload`, `polarity.set`, `polarity.clr`, `polarity.enable`, `enable_srst` (optional booleans), `initial` (optional binary string), `arst_value`, `srst_value` (optional binary string), `no_data` (optional boolean) * Inputs: `in` (`bits`-bit), `clk` (1-bit, if `polarity.clock` is present), `arst` (1-bit, if `polarity.arst` is present), `srst` (1-bit, if `polarity.srst` is present), `en` (1-bit, if `polarity.enable` is present), `set` (1-bit, if `polarity.set` is present), `clr` (1-bit, if `polarity.clr` is present), `ain` (`bits`-bit, if `polarity.aload` is present), `aload` (1-bit, if `polarity.aload` is present) * Outputs: `out` (`bits`-bit) * Memory: `Memory` * Attributes: `bits`, `abits`, `words`, `offset` (natural number), `rdports` (array of read port descriptors), `wrports` (array of write port descriptors), `memdata` (memory contents description) * Read port descriptor attributes: `enable_polarity`, `clock_polarity`, `arst_polarity`, `srst_polarity` (optional booleans), `init_value`, `arst_value`, `srst_value` (optional binary strings), `transparent`, `collision` (optional booleans or arrays of booleans) * Write port descriptor attributes: `enable_polarity`, `clock_polarity`, `no_bit_enable` (optional booleans) * Inputs (per read port): `rdKaddr` (`abits`-bit), `rdKen` (1-bit, if `enable_polarity` is present), `rdKclk` (1-bit, if `clock_polarity` is present), `rdKarst` (1-bit, if `arst_polarity` is present), `rdKsrst` (1-bit, if `srst_polarity` is present) * Outputs (per read port): `rdKdata` (`bits`-bit) * Inputs (per write port): `wrKaddr` (`abits`-bit), `wrKdata` (`bits`-bit), `wrKen` (1-bit (when `no_bit_enable` is true) or `bits`-bit (otherwise), if `enable_polarity` is present), `wrKclk` (1-bit, if `clock_polarity` is present) * Clock source: `Clock` * Outputs: `out` (1-bit) * Button input: `Button` * Outputs: `out` (1-bit) * Lamp output: `Lamp` * Inputs: `in` (1-bit) * Number input: `NumEntry` * Attributes: `bits` (natural number), `numbase` (string) * Outputs: `out` (`bits`-bit) * Number output: `NumDisplay` * Attributes: `bits` (natural number), `numbase` (string) * Inputs: `in` (`bits`-bit) * Subcircuit input: `Input` * Attributes: `bits` (natural number) * Outputs: `out` (`bits`-bit) * Subcircuit output: `Output` * Attributes: `bits` (natural number) * Inputs: `in` (`bits`-bit) * 7 segment display output: `Display7` * Inputs: `bits` (8-bit only - most significant bit controls decimal point LED) * Bus grouping: `BusGroup` * Attributes: `groups` (array of natural numbers) * Inputs: `in0` (`groups[0]`-bit) ... `inN` (`groups[N]`-bit) * Outputs: `out` (sum-of-`groups`-bit) * Bus ungrouping: `BusUngroup` * Attributes: `groups` (array of natural numbers) * Inputs: `in` (sum-of-`groups`-bit) * Outputs: `out0` (`groups[0]`-bit) ... `outN` (`groups[N]`-bit) * Bus slicing: `BusSlice` * Attributes: `slice.first`, `slice.count`, `slice.total` (natural number) * Inputs: `in` (`slice.total`-bit) * Outputs: `out` (`slice.count`-bit) * Zero- and sign-extension: `ZeroExtend`, `SignExtend` * Attributes: `extend.input`, `extend.output` (natural number) * Inputs: `in` (`extend.input`-bit) * Outputs: `out` (`extend.output`-bit) * Finite state machines: `FSM` * Attributes: `bits.in`, `bits.out`, `states`, `init_state`, `current_state` (natural number), `trans_table` (array of transition descriptors) * Transition descriptor attributes: `ctrl_in`, `ctrl_out` (binary strings), `state_in`, `state_out` (natural numbers) * Inputs: `clk` (1-bit), `arst` (1-bit), `in` (`bits.in`-bit) * Outputs: `out` (`bits.out`-bit) # TODO Some ideas for further developing the simulator. * Use JointJS elementTools for configuring/removing gates. * RAM/ROM import/export for Verilog format and Intel HEX. * Framebuffer element with character/bitmap display. * More editing capability: adding and removing blocks, modifying some of blocks' properties. * Undo-redo capability. * Saving and loading circuits, including layout and state. * Generic handling of negation for unary/binary gates (negation on inputs/outputs) for better clarity. * SVG export. * Verilog export. * Smartphone and tablet compatible UI. [digitaljs-logo]: docs/resources/digitaljs_textpath_right.svg
Markdown
UTF-8
2,408
2.78125
3
[]
no_license
# Hand-Gesture-Reognition-using-Depth-Camera System Requirements CPU: Intel Core i5 RAM: 4GB Operating System: Ubuntu 16.04 LTS Language: Python 2.7 Libraries: Numpy, Scikit-Learn, OpenCV2, libfreenect, SimpleCV, cPickle, scipy, glob * Running the Project: ---------------------- Setting up the kinect: 1. Place kinect approximately 90-100 cm away from the person performing the gesture. 2. There should be no obstacle between the person and the camera. 3. The user should bring their hands forward only when they have to perform a gesture. 4. Test the camera view using the command 'freenect-glview'. While performing the gestures, only the hand should appear red while rest of the objects appear yellowish or green. The folder "newdata/Depth" contains the depth thresholded images and "newdata/FeatureDepth" contains the feature vectors used for training. These can be generated running the file 'newkinect.py' using the command 'python newkinect.py' For Training: 1. Run the file 'newkinect.py' using the command 'python newkinect.py'. Wait for a few seconds until a sequence of zeroes starts printing on the terminal and perform the gesture in front of kinect camera. This will generate depth thresholded images and save it in the specified subject and gesture folder. Change the Subject folder and gesture folder in line no. 127 of the code. For example: For 'subject 1' and gesture 'Palm', the address will be './newdata/Depth/Depthpalm/Sub1/1palm{:d}.jpg'. 2. Perform feature extraction by running the file 'featureExtraction.py' using the command 'python featureExtraction.py -featuresDir ./newdata/Depth/Depthpalm/Sub1 palm1' The third argument will be the path of the folder containing the depth images whose feature vector has to be generated. The fourth argument will be the name of the output file in which the feature vectors will be saved. 3. Repeat steps 1 and 2 for each gesture of each subject. 4. Train the classifier by running the file 'training.py' using the command 'python training.py'. For real-time testing: 1. To perform real-time testing, run the program 'realTimeTesting.py' using the command 'python realTimeTesting.py'. For batch testing: 1. Repeat steps 1 and 2 of training phase to collect data for batch testing. Instead of folder name 'newdata' the folder should be 'BatchTesting'. 2. Run the file 'batchTesting.py' using the command 'python batchTesting.py'.
C++
UTF-8
451
3.125
3
[]
no_license
#pragma once namespace lab1 { class Measurer { private: std::string name; double start; double end {}; public: Measurer(std::string name) : name {std::move(name)} , start {omp_get_wtime()} { } ~Measurer() { end = omp_get_wtime(); std::cout << "Measured time " << name << " " << end - start << std::endl; } }; }
Java
UTF-8
590
1.953125
2
[]
no_license
package com.project.operationvolcano.booking.api.model; import com.project.operationvolcano.booking.api.validators.ValidDateRangeConstraint; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.format.annotation.DateTimeFormat; import java.time.LocalDate; @ValidDateRangeConstraint @Data @AllArgsConstructor @NoArgsConstructor public class DateRangeDto { @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private LocalDate fromDate; @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private LocalDate untilDate; }
C#
UTF-8
1,411
2.65625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace ArathsBaby.Infrastructure { public class Users { [Key] public int Id { get; set; } [Required(ErrorMessage = "El campo {0} es requerido ")] public string Name { get; set; } [Required] public string LastName { get; set; } [Required] public string Phone { get; set; } [Required] public DateTime DateOfBirth { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Required] [MinLength(8, ErrorMessage = "La contraseña debe tener como minimo 8 caracteres")] public string Password { get; set; } public string Role { get; set; } [Required] public string Address { get; set; } [Required] public string Colony { get; set; } [Required] public string Street { get; set; } [Required] public int OutsideNumber { get; set; } [Required] public int InternalNumber { get; set; } [Required] public string City { get; set; } [Required] public int ZipCode { get; set; } [Required] public string State { get; set; } [Required] public string Country { get; set; } } }
PHP
UTF-8
1,637
2.71875
3
[ "MIT" ]
permissive
<?php function geraSelect($valor1,$valor2,$valor3,$valor4,$valor5){ echo $valor2."<br/>"; $id=0; $sql = 'SELECT * FROM '.$valor1; echo $sql."<br/>"; $result = mysqli_query($GLOBALS['conexao'],$sql); ?> <select name="<?php echo $valor5; ?>"> <?php while ($row = mysqli_fetch_array($result)) { ?> <option value="<?php echo $row[$valor3]; ?>" <?php if ($row[$valor3]==$valor2){ echo " selected"; } ?>> <?php echo $row[$valor4];?> </option> <?php } ?> </select> <?php } function codigoUsuario($nome){ $sql = "SELECT codigo FROM usuario WHERE usuario = '".$nome."'"; $result = mysqli_query($GLOBALS['conexao'],$sql); while ($row = mysqli_fetch_array($result)) { return $row['codigo']; } } function Query1paraN($tabela,$codigo,$coluna,$campoimprimir) { $sql = 'select * from '. $tabela.' where '. $coluna.' = '. $codigo; //echo $sql; $resultadoB = mysqli_query($GLOBALS['conexao'], $sql); while ($row = mysqli_fetch_array($resultadoB)) { echo $row[$campoimprimir]; } } function geraSelectReceita($valor1,$valor3,$valor4,$valor5){ $sql = "SELECT nome FROM receita WHERE Usuario_codigo = ".$valor1; echo $sql."<br/>"; $result = mysqli_query($GLOBALS['conexao'],$sql); ?> <select name="<?php echo $valor5; ?>"> <?php while ($row = mysqli_fetch_array($result)) { ?> <option value="<?php echo $row[$valor3]; ?>" <?php /*if ($row[$valor3]==$valor2){ echo " selected"; } */?>> <?php echo $row[$valor4];?> </option> <?php } ?> </select> <?php } ?>
PHP
UTF-8
4,222
2.8125
3
[ "Apache-2.0" ]
permissive
<?php require_once dirname( __DIR__ ) . "/bdd/Conection.php"; class Products { function Select() { $parametros = func_get_args(); $pdo = new Conection(); if(count($parametros) == 0) { $select = $pdo->prepare("SELECT * FROM productos"); if($select->execute()) { $res = $select->fetchAll(PDO::FETCH_ASSOC); return json_encode($res); } else { $error = array('error' => "Error al obtener la informacion"); return json_encode($error); } } elseif (count($parametros) == 1) { if(is_numeric($parametros[0])) { $select = $pdo->prepare("SELECT * FROM productos WHERE codigo_barras = ?"); $select->bindparam(1, $parametros[0]); if($select->execute()) { $res = $select->fetchAll(PDO::FETCH_ASSOC); return json_encode($res); } else { $error = array('error' => "Error al ejecutar la sentencia sql"); return json_encode($error); } } else { $error = array('error' => "Error, verifique la informacion enviada"); return json_encode($error); } } else { $error = array('error' => "Error, verifique que la informacion enviada sea correcta"); return json_encode($error); } } function Insert($datos = null) { if($datos != null) { $pdo = new Conection(); $insert = $pdo->prepare("INSERT INTO productos VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); $insert->bindparam(1, $datos["codigo_barras"]); $insert->bindparam(2, $datos["producto"]); $insert->bindparam(3, $datos["marca"]); $insert->bindparam(4, $datos["stock"]); $insert->bindparam(5, $datos["stock_control"]); $insert->bindparam(6, $datos["_id_medida"]); $insert->bindparam(7, $datos["_id_departamento"]); $insert->bindparam(8, $datos["costo_compra"]); $insert->bindparam(9, $datos["costo_venta"]); $insert->bindparam(10, $datos["status"]); if($insert->execute()) { $status = array('Message' => 'Operacion exitosa'); return json_encode($status); } else { $error = array('error' => 'No se pudo insertar el registro'); return json_encode($error); } } } function Update($datos = null) { if($datos != null) { $pdo = new Conection(); $update = $pdo->prepare("UPDATE productos SET producto=?, marca=?, stock=?, stock_control=?, ". "_id_medida=?, _id_departamento=?, costo_compra=?, costo_venta=?, status=? ". "WHERE codigo_barras=?"); $update->bindparam(1, $datos["producto"]); $update->bindparam(2, $datos["marca"]); $update->bindparam(3, $datos["stock"]); $update->bindparam(4, $datos["stock_control"]); $update->bindparam(5, $datos["_id_medida"]); $update->bindparam(6, $datos["_id_departamento"]); $update->bindparam(7, $datos["costo_compra"]); $update->bindparam(8, $datos["costo_venta"]); $update->bindparam(9, $datos["status"]); $update->bindparam(10, $datos["codigo_barras"]); if($update->execute()) { $status = array('Message' => 'Operacion exitosa'); return json_encode($status); } else { $error = array('error' => 'No se pudo actualizar el registro'); return json_encode($error); } } } function Delete($id = null) { if($id != null) { $pdo = new Conection(); $select = $pdo->prepare("UPDATE productos SET status=0 WHERE codigo_barras = ?"); $select->bindparam(1, $id); if($select->execute()) { $status = array('Message' => 'Operacion exitosa'); return json_encode($status); } else { $error = array('Error' => 'No se pudo deshabilitar el registro'); return json_encode($error); } } } }
Markdown
UTF-8
3,273
3.234375
3
[ "MIT" ]
permissive
# Lap.js > Lokua Audio Player. A SIY (style it yourself) HTML5 Audio Player implementation for modern (ES5) browsers with support for single-track, single-album, and mutliple-album player implementations. Selector, element, and event hooks are all baked in - you just have to make them come to life. ## Getting started ```html <!-- include lap.js --> <script src="lap/dist/lap.js"></script> <!-- provide a container and optional control elements --> <div id="player"> <button class="lap__play-pause">play/pause</button> <!-- ... more elements with proper `lap__<element>` classes --> </div> <!-- create your Lap instance --> <script> const lap = new Lap('#player', 'some-audio-url.mp3'); </script> ``` The above example is perhaps the lamest audio player imaginable, but there are a few things to note that should give you a better understanding of the big picture. When the Lap constructor is called, it traverses the container element (the `#player` div in the above example), and sets up appropriate dom, audio, and custom events hooks for children of that container that match a defined element>selector pattern. In this case, there is only a `playPause` element, so Lap will only set up `play`, `pause`, and a convenient `togglePlay` hook. Clicking the button for the first time will cause audio to play, clicking again will pause. For a few elements, like `playPause`, Lap will also add or remove appropriate state classes. In fact, immediately after the above Lap instance is created, the `playPause` element if given the state class of `lap--paused`, which is then replaced with `lap--playing` when the button is clicked. This is where "style it yourself" comes to play. Let's enhance our previous example ever so slightly: ```html <style> .lap--paused:after { content: 'play'; } .lap--playing:after { content: 'paused' } </style> <div id="player"> <button class="lap__play-pause lap--paused"></button> </div> ``` Because of the CSS psuedo elements, the text of the button will change automatically whenever the button is clicked. And just to note, we didn't need to add the `lap--paused` class to our markup as that class is added to a `lap__play-pause` element automatically. > Note: Lap uses BEM syntax for class selectors, where the "block" portion is always `lap`, and the element portion is a snake-case mirror of what their equivalent camelCase js representation would be, so the class `lap__prev-album` refers to the `prevAlbum` element located in the `Lap#els` object. Taking the example one step further, using font-awesome: ```html <link rel="stylesheet" type="text/css" href="font-awesome.css"></link> <style> #player i, #player i:before { display: inline-block; font: normal normal normal 14px/1 FontAwesome; } #player .lap--paused:before { content: '\f04b'; } #player .lap--playing:before { content: '\f04c'; } #player .lap__seek-backward:before { content: '\f049'; } #player .lap__seek-forward:before { content: '\f050'; } </style> <div id="player"> <i class="lap__seek-backward"></i> <i class="lap__play-pause"></i> <i class="lap__seek-forward"></i> </div ``` --- ...to be continued
JavaScript
UTF-8
111
2.953125
3
[]
no_license
let birthYear = 1989; let futureYear = 2025 console.log("I will be " + (futureYear - birthYear) + " in "+ sho);
Python
UTF-8
1,855
3.109375
3
[]
no_license
#!/usr/bin/env python3 """File that contains the function train_model""" import tensorflow.keras as K def train_model(network, data, labels, batch_size, epochs, validation_data=None, early_stopping=False, patience=0, learning_rate_decay=False, alpha=0.1, decay_rate=1, save_best=False, filepath=None, verbose=True, shuffle=False): """ Function That trains a model using mini-batch gradient descent Args: network is the model to train data is a numpy.ndarray of shape (m, nx) containing the input data labels is a one-hot numpy.ndarray of shape (m, classes) containing the labels of data batch_size is the size of the batch used for mini-batch gradient descent epochs is the number of passes through data for mini-batch gradient descent validation_data is the data to validate the model with, if not None """ def learning_rate_decay(epoch): """Function tha uses the learning rate""" alpha_0 = alpha / (1 + (decay_rate * epoch)) return alpha_0 callbacks = [] if validation_data: if early_stopping: early_stop = K.callbacks.EarlyStopping(patience=patience) callbacks.append(early_stop) if learning_rate_decay: decay = K.callbacks.LearningRateScheduler(learning_rate_decay, verbose=1) callbacks.append(decay) if save_best: save = K.callbacks.ModelCheckpoint(filepath, save_best_only=True) callbacks.append(save) train = network.fit(x=data, y=labels, batch_size=batch_size, epochs=epochs, validation_data=validation_data, callbacks=callbacks, verbose=verbose, shuffle=shuffle) return train
C++
UTF-8
823
3.015625
3
[]
no_license
#include <iostream> using namespace std; int fillHeight(int p[],int node,int visited[],int height[]){ if(p[node]==-1){ visited[node]=1; return 0; } if(visited[node]) return height[node]; visited[node]=1; height[node]=1+fillHeight(p,p[node],visited,height); return height[node]; } int findHeight(int parent[],int n){ int ma=0; int visited[n]; int height[n]; memset(visited,0,sizeof(visited)); memset(height,0,sizeof(height)); for (int i = 0; i < n; ++i) { if(!visited[i])height[i]=fillHeight(parent,i,visited,height); ma=max(ma,height[i]); } return ma; } int main(int argc, char const *argv[]) { int parent[]={-1,0,0,3,1,1,2}; int n=sizeof(parent)/sizeof(parent[0]); cout<<"Height of N-ary tree is = "<<findHeight(parent,n); cout<<endl; return 0; }
C++
UTF-8
1,143
3.71875
4
[]
no_license
#include <iostream> #include <stdexcept> #include <exception> using namespace std; class NegativeArraySizeException : public exception { virtual const char* what() const throw() { return "NegativeArraySizeException"; } } negException; int* copyOf(int* original, int oldLength, int newLength) { if (newLength < 0 || oldLength < 0) { //throw std::invalid_argument("NegativeArraySizeException"); throw negException; } int* newArray; newArray = new int[newLength]; for (int i = 0; i < newLength; i++) { if (i < oldLength) { newArray[i] = original[i]; } else newArray[i] = 0; } return newArray; } void printArray(int* arr, int length) { for (int i = 0; i < length; i++) { cout << arr[i] << endl; } } int main() { try { int original[5] = { 100, 2, 3, 4, 5 }; int* newArray = copyOf(original, 5, 10); printArray(newArray, 10); newArray = copyOf(original, 5, 0); printArray(newArray, 0); newArray = copyOf(original, 5, -1); printArray(newArray, -1); } //catch (const std::invalid_argument & e) { catch (exception & e) { cout << "Standard exception: " << e.what() << endl; } return 0; }
PHP
UTF-8
2,414
2.609375
3
[ "MIT" ]
permissive
<?php /** * Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. * * Windows10AssociatedApps File * PHP version 7 * * @category Library * @package Microsoft.Graph * @copyright (c) Microsoft Corporation. All rights reserved. * @license https://opensource.org/licenses/MIT MIT License * @link https://graph.microsoft.com */ namespace Beta\Microsoft\Graph\Model; /** * Windows10AssociatedApps class * * @category Model * @package Microsoft.Graph * @copyright (c) Microsoft Corporation. All rights reserved. * @license https://opensource.org/licenses/MIT MIT License * @link https://graph.microsoft.com */ class Windows10AssociatedApps extends Entity { /** * Gets the appType * Application type. Possible values are: desktop, universal. * * @return Windows10AppType|null The appType */ public function getAppType() { if (array_key_exists("appType", $this->_propDict)) { if (is_a($this->_propDict["appType"], "\Beta\Microsoft\Graph\Model\Windows10AppType") || is_null($this->_propDict["appType"])) { return $this->_propDict["appType"]; } else { $this->_propDict["appType"] = new Windows10AppType($this->_propDict["appType"]); return $this->_propDict["appType"]; } } return null; } /** * Sets the appType * Application type. Possible values are: desktop, universal. * * @param Windows10AppType $val The value to assign to the appType * * @return Windows10AssociatedApps The Windows10AssociatedApps */ public function setAppType($val) { $this->_propDict["appType"] = $val; return $this; } /** * Gets the identifier * Identifier. * * @return string|null The identifier */ public function getIdentifier() { if (array_key_exists("identifier", $this->_propDict)) { return $this->_propDict["identifier"]; } else { return null; } } /** * Sets the identifier * Identifier. * * @param string $val The value of the identifier * * @return Windows10AssociatedApps */ public function setIdentifier($val) { $this->_propDict["identifier"] = $val; return $this; } }
Markdown
UTF-8
3,311
2.84375
3
[]
no_license
# 手把手教你搭建DHCP服务器 ## 1、参考 https://blog.csdn.net/weixin_56903457/article/details/120391901 http://t.zoukankan.com/jpfss-p-10918222.html ## 2、DHCP定义 DHCP(Dynamic Host Configuration Protocol,动态主机配置协议)是一个局域网的网络协议,使用UDP协议工作。它是一种流行的Client/Server协议,一般用于为主机或者为路由器等指定相关的配置信息。DHCP服务在企业和家庭中得到了大量的应用,它能够自动分配ip地址以及一些其他的相关信息,整个过程对客户透明。 ## 3、DHCP分配方式 自动分配方式(Automatic Allocation),DHCP服务器为主机指定一个永久性的IP地址,一旦DHCP客户端第一次成功从DHCP服务器端租用到IP地址后,就可以永久性的使用该地址。 动态分配方式(Dynamic Allocation),DHCP服务器给主机指定一个具有时间限制的IP地址,时间到期或主机明确表示放弃该地址时,该地址可以被其他主机使用。 手工分配方式(Manual Allocation),客户端的IP地址是由网络管理员指定的,DHCP服务器只是将指定的IP地址告诉客户端主机。 ## 4、DMZ DMZ,是英文“demilitarized zone”的缩写,中文名称为“隔离区”,也称“非军事化区”。它是为了解决安装防火墙后外部网络的访问用户不能访问内部网络服务器的问题,而设立的一个非安全系统与安全系统之间的缓冲区。该缓冲区位于企业内部网络和外部网络之间的小网络区域内。在这个小网络区域内可以放置一些必须公开的服务器设施,如企业Web服务器、FTP服务器和论坛等。另一方面,通过这样一个DMZ区域,更加有效地保护了内部网络。因为这种网络部署,比起一般的防火墙方案,对来自外网的攻击者来说又多了一道关卡。 DMZ 是英文“Demilitarized Zone”的缩写,中文名称为“隔离区”, 与军事区和信任区相对应,也称“非军事化区”,是为了解决外部网络不能访问内部网络服务器的问题,而设立的一个非安全系统与安全系统之间的缓冲区。作用是把单位的 FTP服务器、E-Mail服务器等允许外部访问的服务器单独部署在此区域,使整个需要保护的内部网络接在信任区后,不允许任何外部网络的直接访问,实现内外网分离,满足用户的安全需求。 DMZ 区可以理解为一个不同于外网或内网的特殊网络区域,DMZ 内通常放置一些不含机密信息的公用服务器,比如 WEB 服务器、E-Mail 服务器、FTP 服务器等。这样来自外网的访问者只可以访问 DMZ 中的服务,但不可能接触到存放在内网中的信息等,即使 DMZ 中服务器受到破坏,也不会对内网中的信息造成影响。DMZ 区是信息安全纵深防护体系的第一道屏障,在企事业单位整体信息安全防护体系中具有举足轻重的作用。 1.内网可以访问外网 2.内网可以访问DMZ 3.外网不能访问内网 4.外网可以访问DMZ 5.DMZ访问内网有限制 6.DMZ不能访问外网 DHCP服务器查询:ipconfig /all DHCPv6 IPv6地址到底是一个什么东西
C
UTF-8
11,220
2.6875
3
[]
no_license
#include <stdio.h> #include <time.h> #include <conio.h> #include <stdlib.h> #include <windows.h> #define N (20) #define M (20) #define L (N * M) #define True 1 #define False 0 #define UP 0 #define DOWN 1 #define LEFT 2 #define RIGHT 3 typedef struct mark { int x; int y; } bodySnake; char scoreFile[] = "score.txt"; void drawMap(bodySnake snake[], char map[][M], const int headIndex, const int endIndex, const int food_x, const int food_y, int score, const int *maxScore); void initSnake(); void snakeMove(bodySnake snake[], char map[][M], int *headIndex, int *endIndex, int direction[], int *food_x, int *food_y, int *score, int *maxScore, int *pause); void move(bodySnake snake[], int *headIndex, int direction[], const int snakeHead); void artificialMove(bodySnake snake[], int *headIndex, int *endIndex, int direction[], char click, int snakeHead, int *pause); int snakeEatFood(bodySnake snake[], const int headIndex, const int food_x, const int food_y, int *score, int *maxScore); void markMap(bodySnake snake[], char map[][M], const int headIndex, const int endIndex, const int food_x, const int food_y); void foodConflictSnake(bodySnake snake[], int *food_x, int *food_y, const int headIndex, const int endIndex); void gameOver(int score); void snakeDead(bodySnake snake[], int headIndex, int endIndex, int *active); int viewScore(const char scoreFile[]); void updateScore(int score, int *maxScore); int readMaxScore(const char scoreFile[]); void help(); void returnMenu(); void menu(); void initFile(const char scoreFile[]); int main() { menu(); return 0; } void initSnake() { //地图 char map[N][M] = {0}; //初始蛇的身体 bodySnake snake[L]; //装蛇的数组 snake[0].x = 3, snake[0].y = 3; snake[1].x = 3, snake[1].y = 4; snake[2].x = 3, snake[2].y = 5; map[3][3] = 1, map[3][4] = 1, map[3][5] = 1; int endIndex = 0; //蛇尾 int headIndex = 2; //蛇头 //随机食物 srand((unsigned)time(NULL)); int food_x = rand() % N; int food_y = rand() % M; int direction[4] = {0, 0, 0, 1}; int maxScore = readMaxScore(scoreFile); int score = 0; int active = True; int pause = False; while (active) { drawMap(snake, map, headIndex, endIndex, food_x, food_y, score, &maxScore); snakeMove(snake, map, &headIndex, &endIndex, direction, &food_x, &food_y, &score, &maxScore, &pause); snakeDead(snake, headIndex, endIndex, &active); } gameOver(score); } void menu() { system("cls"); initFile(scoreFile); printf("*****************************************\n"); printf("* *\n"); printf("* 1.开始游戏. *\n"); printf("* 2.查看帮助. *\n"); printf("* 3.查看历史最高分. *\n"); printf("* *\n"); printf("*****************************************\n"); int choose; scanf("%1d", &choose); while (getchar() != '\n') { continue; } if (choose == 1) { initSnake(); } else if (choose == 2) { help(); returnMenu(); } else if (choose == 3) { viewScore(scoreFile); returnMenu(); } else { menu(); } } void help() { system("cls"); printf("w s a d对应上下左右,空格键暂停,q直接退出(不保存分数)\n"); printf("祝你好运!\n"); } void returnMenu() { int choose; printf("\n\n1.返回菜单\t\t\t2.退出\n"); scanf("%1d", &choose); while (getchar() != '\n') { continue; } menu(); } void initFile(const char scoreFile[]) { FILE *fp; if ((fp = fopen(scoreFile, "r")) == NULL) { int score = 0; fp = fopen(scoreFile, "w"); fprintf(fp, "%d\n", score); } fclose(fp); } int viewScore(const char scoreFile[]) { system("cls"); int score; FILE *fp; if ((fp = fopen(scoreFile, "r")) != NULL) { fscanf(fp, "%d", &score); printf("你的历史最高分为%d.", score); } fclose(fp); return score; } int readMaxScore(const char scoreFile[]) { int score = 0; FILE *fp; if ((fp = fopen(scoreFile, "r")) != NULL) { fscanf(fp, "%d", &score); } else { printf("打开失败!"); } fclose(fp); return score; } void markMap(bodySnake snake[], char map[][M], const int headIndex, const int endIndex, const int food_x, const int food_y) { if (headIndex > endIndex) { for (int i = endIndex; i <= headIndex; i++) { map[snake[i].x][snake[i].y] = 1; } } else { for (int i = endIndex; i < L; i++) { map[snake[i].x][snake[i].y] = 1; } for (int i = 0; i <= headIndex; i++) { map[snake[i].x][snake[i].y] = 1; } } map[food_x][food_y] = 2; } void drawMap(bodySnake snake[], char map[][M], const int headIndex, const int endIndex, const int food_x, const int food_y, int score, const int *maxScore) { markMap(snake, map, headIndex, endIndex, food_x, food_y); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (map[i][j] == 0) { printf("--"); } else if (map[i][j] == 1) { printf("★"); } else if (map[i][j] == 2) { printf("●"); } } putchar(10); } printf("你的当前分数:%d.\t\t\t历史最高分为:%d\n", score, *maxScore); Sleep(40); system("cls"); } void snakeMove(bodySnake snake[], char map[][M], int *headIndex, int *endIndex, int direction[], int *food_x, int *food_y, int *score, int *maxScore, int *pause) { int snakeHead = (*headIndex + 1) % L; if (kbhit()) { char click = getch(); artificialMove(snake, headIndex, endIndex, direction, click, snakeHead, pause); } else if (!*pause) { move(snake, headIndex, direction, snakeHead); } //是否吃了食物 int eat = snakeEatFood(snake, *headIndex, *food_x, *food_y, score, maxScore); if (eat) { *food_x = rand() % N; *food_y = rand() % M; foodConflictSnake(snake, food_x, food_y, *headIndex, *endIndex); } //没吃到食物且没暂停,才去掉尾巴。即暂停或吃到食物才不去掉尾巴 else if (!eat && !*pause) { int x = snake[*endIndex].x; int y = snake[*endIndex].y; //去掉尾巴 map[x][y] = 0; //尾巴前行 *endIndex = (*endIndex + 1) % L; } } void move(bodySnake snake[], int *headIndex, int direction[], const int snakeHead) { snake[snakeHead].x = (snake[*headIndex].x + direction[UP] + direction[DOWN] + N) % N; snake[snakeHead].y = (snake[*headIndex].y + direction[LEFT] + direction[RIGHT] + M) % M; *headIndex = snakeHead; } void artificialMove(bodySnake snake[], int *headIndex, int *endIndex, int direction[], char click, int snakeHead, int *pause) { if ((click == 'w' || click == 'W') && direction[DOWN] != 1) { direction[UP] = -1, direction[DOWN] = 0, direction[LEFT] = 0, direction[RIGHT] = 0; } else if ((click == 's' || click == 'S') && direction[UP] != -1) { direction[UP] = 0, direction[DOWN] = 1, direction[LEFT] = 0, direction[RIGHT] = 0; } else if ((click == 'a' || click == 'A') && direction[RIGHT] != 1) { direction[UP] = 0, direction[DOWN] = 0, direction[LEFT] = -1, direction[RIGHT] = 0; } else if ((click == 'd' || click == 'D') && direction[LEFT] != -1) { direction[UP] = 0, direction[DOWN] = 0, direction[LEFT] = 0, direction[RIGHT] = 1; } else if (click == ' ') { if (*pause == False) { *pause = True; } else { *pause = False; } } else if (click == 'q') { exit(0); } if (!*pause) { move(snake, headIndex, direction, snakeHead); } } int snakeEatFood(bodySnake snake[], const int headIndex, const int food_x, const int food_y, int *score, int *maxScore) { if (snake[headIndex].x == food_x && snake[headIndex].y == food_y) { *score += 10; updateScore(*score, maxScore); return True; } return False; } void updateScore(int score, int *maxScore) { if (score > *maxScore) { *maxScore = score; } } void foodConflictSnake(bodySnake snake[], int *food_x, int *food_y, const int headIndex, const int endIndex) { int conflict = False; do { conflict = False; if (headIndex > endIndex) { for (int i = endIndex; i <= headIndex; i++) { if (*food_x == snake[i].x && *food_y == snake[i].y) { conflict = True; break; } } } else { for (int i = endIndex; i < L; i++) { if (*food_x == snake[i].x && *food_y == snake[i].y) { conflict = True; break; } } for (int i = 0; i <= headIndex; i++) { if (*food_x == snake[i].x && *food_y == snake[i].y) { conflict = True; break; } } } if (conflict) { *food_x = rand() % N; *food_y = rand() % M; } } while (conflict); } void snakeDead(bodySnake snake[], int headIndex, int endIndex, int *active) { if (headIndex > endIndex) { for (int i = endIndex; i < headIndex; i++) { if (snake[i].x == snake[headIndex].x && snake[i].y == snake[headIndex].y) { *active = False; break; } } } else { for (int i = endIndex; i < L; i++) { if (snake[i].x == snake[headIndex].x && snake[i].y == snake[headIndex].y) { *active = False; break; } } for (int i = 0; i < headIndex; i++) { if (snake[i].x == snake[headIndex].x && snake[i].y == snake[headIndex].y) { *active = False; break; } } } } void gameOver(int score) { int historyScore = readMaxScore(scoreFile); if (score > historyScore) { FILE *fp; fp = fopen(scoreFile, "w"); fprintf(fp, "%d\n", score); fclose(fp); printf("\t\t\t恭喜你打破了历史记录!\t\t\t\n"); } printf("\t\t\tGame Over!\t\t\t\n"); }
Java
UTF-8
683
1.710938
2
[ "Apache-2.0" ]
permissive
package com.ctrip.xpipe.redis.console.notifier.cluster; import com.ctrip.xpipe.api.observer.Event; import com.ctrip.xpipe.api.observer.Observable; import com.ctrip.xpipe.cluster.ClusterType; import com.ctrip.xpipe.redis.console.notifier.EventType; import com.ctrip.xpipe.redis.console.notifier.shard.ShardEvent; import java.util.List; /** * @author chen.zhu * <p> * Feb 11, 2018 */ public interface ClusterEvent extends Event, Observable { List<ShardEvent> getShardEvents(); EventType getClusterEventType(); String getClusterName(); long getOrgId(); void addShardEvent(ShardEvent shardEvent); void onEvent(); ClusterType getClusterType(); }
SQL
UTF-8
1,110
3.984375
4
[]
no_license
/** Database Schema Creation Script for QSense application. In this version, added the device-type in the application. Default device-type is Android. Switch context to qsense_db **/ USE qsense_db; START TRANSACTION; SET foreign_key_checks = 0; /** Create device_type table This table will store information about the kind of device used to sync data viz. Android or Iphone **/ DROP TABLE IF EXISTS device_type; CREATE TABLE device_type ( id INT NOT NULL PRIMARY KEY, name VARCHAR(10) NOT NULL UNIQUE ); /** Inserting seed data for device-type **/ INSERT INTO `device_type` (`id`, `name`) VALUES ('1', 'ANDROID'); INSERT INTO `device_type` (`id`, `name`) VALUES ('2', 'IPHONE'); /** Alter tables for adding new column device_type, setting default device-type to ANDROID. **/ ALTER TABLE user_session ADD COLUMN device_type_id INT NOT NULL DEFAULT 1 , ADD FOREIGN KEY (device_type_id) REFERENCES device_type (id); ALTER TABLE user ADD COLUMN device_type_id INT NOT NULL DEFAULT 1 , ADD FOREIGN KEY (device_type_id) REFERENCES device_type (id); SET foreign_key_checks = 1; COMMIT;
JavaScript
UTF-8
1,492
2.984375
3
[]
no_license
export { Template }; class Template { // load all template HTML files static async loadTemplates () { Template.templates = {}; for (let templateName of ['navbar', 'filter', 'filter-option', 'tag', 'recipe', 'recipe-ingredient']) { Template.templates[templateName] = await Template.loadTemplate(templateName); } } // load template HTML file static async loadTemplate (templateName) { return fetch('./public/templates/' + templateName + '.html') .then(function(response) { if (response.status !== 200) { console.log('Bad response from server! Status Code: ' + response.status); return; } return response.text(); }).catch(function(err) { console.log('Error occurred!', err); }); } // load template HTML file and replace {attribute} tags static fillTemplate ( templateName, object ) { const templateContent = Template.templates[templateName]; return templateContent.replace( /{(\w*)}/g, function( m, key ) { if (Object.prototype.hasOwnProperty.call(object, key) && object[key] !== undefined) { return object[key]; } else { return ""; } } ); } }
Markdown
UTF-8
333
2.5625
3
[]
no_license
<H1>Simplistic Portfolio Website</H1> <P>This is a very basic and clean website design, which can be used as a simple portfolio page. You can add links to all of your social media and repository platforms, in a clean and intuitive design. Feel free to download it and use it as a template.</P> <P> New sections coming soon </P>
PHP
UTF-8
20,451
3.1875
3
[]
no_license
<?php //Define list of available units of measure $units_of_measure = ["cups","pints","gallons","tablespoons","teaspoons","pieces","liters","milliliters","handfuls","units"]; sort($units_of_measure); //Define list of recipe types $recipe_types = ["Meal","Snack","Dessert"]; //Function to verify log in credentials function verify_login($username, $password){ global $db; //Verify that username exists $admin = view_admin_by_username($username); if($admin){ //If username exists, verify the password is correct if(password_verify($password, $admin["password"])){ return $admin; } else{ return false; } }else{ return false; } } //Function to view administrator by username function view_admin_by_username($username){ global $db; //Escape strings to protect against SQL injection $username = mysqli_real_escape_string($db, $username); //Query the database for the provided username and password $query = "SELECT * FROM Administrators "; $query .= "WHERE username = '{$username}' "; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } $admin = mysqli_fetch_assoc($result); mysqli_free_result($result); return $admin; } //Function to view all administrators function view_admins(){ global $db; $query = "SELECT id, username, type FROM Administrators "; $query .= "ORDER BY username"; $result = mysqli_query($db, $query); if(!$result){ die("Database query failed."); } $output = "<table><th class=\"right\">Username</th><th class=\"left\">Access Type</th><th class=\"right\"></th>"; while($row = mysqli_fetch_assoc($result)){ $output .= "<tr><td class=\"right\">"; $output .= htmlentities($row["username"]); $output .= "</td><td class=\"left\">"; $output .= htmlentities($row["type"]); $output .= "</td><td class=\"right\">"; $output .= "<a href=\"editAdmin.php?id=".urlencode($row["id"])."\">Edit</a>"; } $output .= "</table>"; mysqli_free_result($result); return $output; } //Function to view administrator by id function view_admin_by_id($id){ global $db; //Escape strings to protect against SQL injection $id = mysqli_real_escape_string($db, $id); $query = "SELECT id, username, type FROM Administrators "; $query .= "WHERE id = '{$id}' "; $query .= "LIMIT 1"; $result = mysqli_query($db, $query); if(!$result){ die("Database query failed."); } $admin = mysqli_fetch_assoc($result); mysqli_free_result($result); return $admin; } //Function to add new administrator function add_admin($admin){ global $db; //Escape strings to protect against SQL injection $username = mysqli_real_escape_string($db, $admin["username"]); $password = mysqli_real_escape_string($db, $admin["password"]); $type = mysqli_real_escape_string($db, $admin["type"]); //Encrypt the password before adding to the database $hashed_password = password_hash($password, PASSWORD_BCRYPT); //Add new admin to database $query = "INSERT INTO Administrators(username, password, type) "; $query .= "VALUES('{$username}','{$hashed_password}','{$type}')"; $result = mysqli_query($db, $query); if(!$result){ die("Database query failed."); } return $result; } //Function to update an administrator function update_admin($admin, $id){ global $db; //Escape strings to protect against SQL injection $id = mysqli_real_escape_string($db, $id); $username = mysqli_real_escape_string($db, $admin["username"]); $password = mysqli_real_escape_string($db, $admin["password"]); $type = mysqli_real_escape_string($db, $admin["type"]); //Encrypt the password before adding to the database $hashed_password = password_hash($password, PASSWORD_BCRYPT); $query = "UPDATE Administrators "; $query .= "SET username = '{$username}', "; $query .= "password = '{$hashed_password}', "; $query .= "type = '{$type}' "; $query .= "WHERE id = '{$id}' "; $query .= "LIMIT 1"; $result = mysqli_query($db, $query); if(!$result){ die("Database query failed."); } return $result; } //Function to delete an administrator function delete_admin($id){ global $db; $id = mysqli_real_escape_string($db, $id); $query = "DELETE FROM Administrators "; $query .= "WHERE id = '{$id}' "; $query .= "LIMIT 1"; $result = mysqli_query($db, $query); if(!$result){ die("Database query failed."); } mysqli_free_result($result); //Redirect user to view admins page header("Location: ../public/admins.php"); exit; } //Function to get basic information about specified recipe function get_recipe_info($id){ global $db; //Escape strings to protect against SQL injection $id_safe = mysqli_real_escape_string($db, $id); //Query the Recipes table for specified id $query = "SELECT * FROM Recipes "; $query .= "WHERE id = '{$id_safe}' "; $query .= "LIMIT 1"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } $recipe_info = mysqli_fetch_assoc($result); mysqli_free_result($result); return $recipe_info; } //Function to view all recipes for selected type function view_recipes($type){ global $db; global $admin; //Escape strings to protect against SQL injection $type_safe = mysqli_real_escape_string($db, $type); //Query the Recipes table for all recipes with specified type $query = "SELECT * FROM Recipes "; $query .= "WHERE recipe_type = '{$type_safe}' "; if($admin != 'admin' && $admin != 'superadmin'){ $query .= "AND active = 1 "; } $query .= "ORDER BY recipe_name"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } //Output data $output = ''; while($row = mysqli_fetch_assoc($result)){ $picture = evaluate_name($row["recipe_name"]); $output .= "<div class=\"list\">"; $output .= "<div class=\"center floatLeft\">"; if(file_exists("images/".$picture.".jpg")){ $output .= "<div class=\"picture\">"; $output .= "<a href=\"view.php?id="; $output .= urlencode($row["id"])."\">"; $output .= "<img src=\"images/".$picture.".jpg\""; $output .= " alt=".$row["recipe_name"]; $output .= " height=\"200\" width=\"180\"></a></div>"; } else { $output .="<div class=\"picture border\">No picture</div>"; } $output .= "</div>"; $output .= "<div class=\"center floatLeft\">"; $output .= "<div class=\"left colMax\"><a href=\"view.php?id="; $output .= urlencode($row["id"]); $output .= "\">".htmlentities($row["recipe_name"])."</a>"; $output .= "</div><div class=\"left\">"; $output .= htmlentities($row["calories"])." calories"; $output .= "</div><div class=\"left\">"; $output .= count(get_ingredients_by_id($row["id"]))." ingredients"; $output .= "</div><div class=\"left\">"; $output .= get_total_time($row["id"])." minutes"; $output .= "</div>"; if($admin == 'admin' || $admin == 'superadmin'){ $output .= "<div class=\"left\">"; $output .= "<a href=\"edit.php?id="; $output .= urlencode($row["id"]); $output .= "\">Edit</a>"; $output .= "</div>"; } $output .= "</div>"; $output .= "</div>"; } mysqli_free_result($result); return $output; } //Function to get recipe ingredients by id function get_ingredients_by_id($id){ global $db; //Escape strings to protect against SQL injection $id_safe = mysqli_real_escape_string($db, $id); $query = "SELECT rec.id as rec_id, rec.recipe_name, rec.recipe_type, rec.calories, ing.id as ing_id, ing.ingredient_name, ing.amount, ing.unit "; $query .= "FROM Recipes rec "; $query .= "LEFT OUTER JOIN Recipe_Ingredients ing "; $query .= "ON rec.id = ing.recipe_id "; $query .= "WHERE rec.id = '{$id_safe}' "; $query .= "ORDER BY ing.id"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } $ingredients = []; while($row = mysqli_fetch_assoc($result)){ $ingredients[] = $row; } mysqli_free_result($result); return $ingredients; } //Function to view ingredients for specified recipe function view_recipe_ingredients($id){ //Get the ingredients for the selected recipe $row = get_ingredients_by_id($id); $count = count($row); //Output data $output = "<table class=\"center\">"; for($i=0; $i < $count; $i++){ $output .= "<tr><td class=\"right colMax\">"; $output .= htmlentities($row[$i]["ingredient_name"]); $output .= "</td><td class=\"left colMax\">"; $output .= htmlentities($row[$i]["amount"])." ". htmlentities($row[$i]["unit"]); $output .= "</td></tr>"; } $output .= "</table>"; return $output; } //Function to get recipe instructions by id function get_instructions_by_id($id){ global $db; //Escape strings to protect against SQL injection $id_safe = mysqli_real_escape_string($db, $id); $query = "SELECT rec.id as rec_id, rec.recipe_name, rec.recipe_type, rec.calories, ins.id as ins_id, ins.instruction_number, ins.time, ins.instruction "; $query .= "FROM Recipes rec "; $query .= "LEFT OUTER JOIN Recipe_Instructions ins "; $query .= "ON rec.id = ins.recipe_id "; $query .= "WHERE rec.id = '{$id_safe}' "; $query .= "ORDER BY ins.instruction_number"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } $instructions = []; while($row = mysqli_fetch_assoc($result)){ $instructions[] = $row; } mysqli_free_result($result); return $instructions; } //Function to calculate total time of recipe function get_total_time($id){ $ins_count = count(get_instructions_by_id($id)); $total_time = []; for($i = 0; $i < $ins_count; $i++){ $total_time[] = get_instructions_by_id($id)[$i]['time']; } $sum = array_sum($total_time); return $sum; } //Function to view instructions for specified recipe function view_recipe_instructions($id){ //Get instructions for the selected recipe $row = get_instructions_by_id($id); $count = count($row); $output = "<table class=\"center\">"; $output .= "<th></th><th>Instruction</th><th>Time (Minutes)</th>"; for($i=0; $i < $count; $i++){ $output .= "<tr><td class=\"left\">"; $output .= htmlentities($row[$i]["instruction_number"]); $output .= "</td><td class=\"left colMin\">"; $output .= htmlentities($row[$i]["instruction"]); $output .= "</td><td class=\"colMax\">"; $output .= htmlentities($row[$i]["time"]); $output .= "</td></tr>"; } $output .= "</table>"; return $output; } //Function to add recipe header record function add_recipe_header($recipe){ global $db; //Escape strings to protect against SQL injection $recipe_name = mysqli_real_escape_string($db, $recipe["recipe_name"]); $recipe_type = mysqli_real_escape_string($db, $recipe["recipe_type"]); $calories = mysqli_real_escape_string($db, $recipe["calories"]); $active = mysqli_real_escape_string($db, $recipe["active"]); //Add new recipe to the Recipes table $query = "INSERT INTO Recipes(recipe_name, recipe_type, calories, active) "; $query .= "VALUES('{$recipe_name}','{$recipe_type}','{$calories}','{$active}')"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } return $result; } //Function to add recipe ingredients function add_recipe_ingredients($ingredients, $rec_id, $end_h){ global $db; $rec_id_safe = mysqli_real_escape_string($db, $rec_id); for($m=1; $m < $end_h; $m++){ $ingredient_name = mysqli_real_escape_string($db, $ingredients["ingredient_name{$m}"]); $amount = mysqli_real_escape_string($db, $ingredients["amount{$m}"]); $unit = mysqli_real_escape_string($db, $ingredients["unit{$m}"]); $query = "INSERT INTO Recipe_Ingredients(recipe_id, ingredient_name, amount, unit) "; $query .= "VALUES('{$rec_id_safe}','{$ingredient_name}','{$amount}','{$unit}') "; $result = mysqli_query($db, $query); } //Test for errors in query if(!$result){ die("Database query failed"); } return $result; } //Function to add recipe instructions function add_recipe_instructions($instructions, $rec_id, $end_i){ global $db; $rec_id_safe = mysqli_real_escape_string($db, $rec_id); for($j = 1; $j < $end_i; $j++){ $time = mysqli_real_escape_string($db, $instructions["time{$j}"]); $instruction = mysqli_real_escape_string($db, $instructions["instruction{$j}"]); $query = "INSERT INTO Recipe_Instructions(recipe_id, instruction_number, time, instruction) "; $query .= "VALUES('{$rec_id_safe}','{$j}','{$time}','{$instruction}') "; $result = mysqli_query($db, $query); } //Test for errors in query if(!$result){ die("Database query failed"); } return $result; } //Function to add new recipe function add_recipe($recipe, $ingredients, $instructions, $end_h, $end_i){ global $db; //Add recipe header information add_recipe_header($recipe); //Get the id of the new recipe $rec_id = mysqli_insert_id($db); //Add recipe ingredients add_recipe_ingredients($ingredients, $rec_id, $end_h); //Add recipe instructions add_recipe_instructions($instructions, $rec_id, $end_i); //Reset session line count values to zero $_SESSION["i"] = 0; $_SESSION["h"] = 0; //Redirect user to view the newly added recipe header("Location: view.php?id=".urlencode($rec_id)); exit; } //Function to update recipe header record function update_recipe_header($recipe, $id){ global $db; //Escape strings to protect against SQL injection $id_safe = mysqli_real_escape_string($db, $id); $recipe_name = mysqli_real_escape_string($db, $recipe["recipe_name"]); $recipe_type = mysqli_real_escape_string($db, $recipe["recipe_type"]); $calories = mysqli_real_escape_string($db, $recipe["calories"]); $active = mysqli_real_escape_string($db, $recipe["active"]); //Add new recipe to the Recipes table $query = "UPDATE Recipes "; $query .= "SET recipe_name = '{$recipe_name}', "; $query .= "recipe_type = '{$recipe_type}', "; $query .= "calories = '{$calories}', "; $query .= "active = '{$active}' "; $query .= "WHERE id = '{$id_safe}' "; $query .= "LIMIT 1"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } return $result; } //Function to update recipe ingredients function update_ingredients($ingredients, $rec_id, $end_h){ global $db; $count = count(get_ingredients_by_id($rec_id)); $rec_id_safe = mysqli_real_escape_string($db, $rec_id); for($m=1; $m < $end_h; $m++){ $ingredient_id = mysqli_real_escape_string($db, $ingredients["ingredient_id{$m}"]); $ingredient_name = mysqli_real_escape_string($db, $ingredients["ingredient_name{$m}"]); $amount = mysqli_real_escape_string($db, $ingredients["amount{$m}"]); $unit = mysqli_real_escape_string($db, $ingredients["unit{$m}"]); $query = "SELECT count(*) as exist FROM Recipe_Ingredients "; $query .= "WHERE id = '{$ingredient_id}' "; $query .= "AND recipe_id = '{$rec_id_safe}'"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } $ingredient_exists = mysqli_fetch_assoc($result); //If database line for ingredient already exists, update it, else insert new line if($ingredient_exists['exist'] != 0){ $query = "UPDATE Recipe_Ingredients "; $query .= "SET ingredient_name = '{$ingredient_name}', "; $query .= "amount = '{$amount}', "; $query .= "unit = '{$unit}' "; $query .= "WHERE id = '{$ingredient_id}' "; $query .= "AND recipe_id = '{$rec_id_safe}'"; $result = mysqli_query($db, $query); } else{ $query = "INSERT INTO Recipe_Ingredients(recipe_id, ingredient_name, amount, unit) "; $query .= "VALUES('{$rec_id_safe}','{$ingredient_name}','{$amount}','{$unit}') "; $result = mysqli_query($db, $query); } } //If the total lines submitted is less than the current lines in the database, delete remaining db lines if($end_h - 1 < $count){ $query = "DELETE FROM Recipe_Ingredients "; $query .= "WHERE id > '{$ingredient_id}' "; $query .= "AND recipe_id = '{$rec_id_safe}'"; $result = mysqli_query($db, $query); } //Test for errors in query if(!$result){ die("Database query failed"); } return $result; } //Function to update recipe instructions function update_instructions($instructions, $rec_id, $end_i){ global $db; $count = count(get_instructions_by_id($rec_id)); $rec_id_safe = mysqli_real_escape_string($db, $rec_id); for($j = 1; $j < $end_i; $j++){ $instruction_id = mysqli_real_escape_string($db, $instructions["instruction_id{$j}"]); $ins_num = mysqli_real_escape_string($db, $instructions["ins_num{$j}"]); $time = mysqli_real_escape_string($db, $instructions["time{$j}"]); $instruction = mysqli_real_escape_string($db, $instructions["instruction{$j}"]); $query = "SELECT count(*) as exist FROM Recipe_Instructions "; $query .= "WHERE id = '{$instruction_id}' "; $query .= "AND recipe_id = '{$rec_id_safe}'"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } $instruction_exists = mysqli_fetch_assoc($result); //If database line for instruction already exists, update it, else insert new line if($instruction_exists['exist'] != 0){ $query = "UPDATE Recipe_Instructions "; $query .= "SET instruction_number = '{$ins_num}', "; $query .= "time = '{$time}', "; $query .= "instruction = '{$instruction}' "; $query .= "WHERE id = '{$instruction_id}' "; $query .= "AND recipe_id = '{$rec_id_safe}'"; echo $query; echo "<br />"; $result = mysqli_query($db, $query); } else{ $query = "INSERT INTO Recipe_Instructions(recipe_id, instruction_number, time, instruction) "; $query .= "VALUES('{$rec_id_safe}','{$j}','{$time}','{$instruction}') "; echo $query; echo "<br />"; $result = mysqli_query($db, $query); } } //If the total lines submitted is less than the current lines in the database, delete remaining db lines if($end_i - 1 < $count){ $query = "DELETE FROM Recipe_Instructions "; $query .= "WHERE id > '{$instruction_id}' "; $query .= "AND recipe_id = '{$rec_id_safe}'"; echo $query; echo "<br />"; $result = mysqli_query($db, $query); } //Test for errors in query if(!$result){ die("Database query failed"); } return $result; } //Function to update recipe function update_recipe($recipe, $ingredients, $instructions, $rec_id, $end_h, $end_i){ global $db; //Update recipe header information update_recipe_header($recipe, $rec_id); //Update recipe ingredients update_ingredients($ingredients, $rec_id, $end_h); //Update recipe instructions update_instructions($instructions, $rec_id, $end_i); //Reset session line count values to zero $_SESSION["i"] = 0; $_SESSION["h"] = 0; //Redirect user to view the newly added recipe header("Location: view.php?id=".urlencode($rec_id)); exit; } //Function to delete recipe instructions function delete_instructions($id){ global $db; $id_safe = mysqli_real_escape_string($db, $id); //Delete instructions $query = "DELETE FROM Recipe_Instructions "; $query .= "WHERE recipe_id = '{$id_safe}'"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } return $result; } //Function to delete recipe ingredients function delete_ingredients($id){ global $db; $id_safe = mysqli_real_escape_string($db, $id); //Delete instructions $query = "DELETE FROM Recipe_Ingredients "; $query .= "WHERE recipe_id = '{$id_safe}'"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } return $result; } //Function to delete entire recipe function delete_recipe($id, $type){ global $db; $id_safe = mysqli_real_escape_string($db, $id); //Delete instructions delete_instructions($id_safe); //Delete ingredients delete_ingredients($id_safe); //Delete recipe header information $query = "DELETE FROM Recipes "; $query .= "WHERE id = '{$id_safe}'"; $result = mysqli_query($db, $query); //Test for errors in query if(!$result){ die("Database query failed"); } mysqli_free_result($result); //Redirect user to list of recipes for specified type header("Location: ../public/index.php?type=".htmlentities(urlencode($type))); exit; }
Python
UTF-8
4,720
2.96875
3
[]
no_license
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf from matplotlib import pyplot as plt import PIL.Image import numpy as np base_model = tf.keras.applications.InceptionV3(include_top=False, weights='imagenet') # 选择最大激活的层 layer_names = ['mixed3', 'mixed5'] layers = [base_model.get_layer(name).output for name in layer_names] # 创建特征提取模型 dream_model = tf.keras.Model(inputs=base_model.input, outputs=layers) def read_image(file_name, max_dim=None): img = PIL.Image.open(file_name) if max_dim: img.thumbnail((max_dim, max_dim)) return np.array(img) # 将图像进行切割移动 def random_roll(image, max_roll): # 产生随机的shift值 shift = tf.random.uniform(shape=[2], minval=-max_roll, maxval=max_roll, dtype=tf.int32) shift_down, shift_right = shift[0], shift[1] # 按照随机的shift把图片的下面和上面部分进行交换,把左、右部分进行交换 img_rolled = tf.roll(tf.roll(image, shift_right, axis=1), shift_down, axis=0) return shift_down, shift_right, img_rolled # 损失是所选层中激活的总和。损耗在每一层均归一化,因此较大层的贡献不会超过较小层。在DeepDream中,通过梯度上升使这种损失最大化 def calc_loss(image, model): # 必须添加一个维度,batch_size,使图像变为(1, 150, 150, 3) img_batch = tf.expand_dims(image, axis=0) # 图像通过模型进行前向计算 layer_activations = model(img_batch) # 如果batch为一,则计算两次损失 if len(layer_activations) == 1: layer_activations = [layer_activations] losses = [] # 计算每层的计算结果的均值 for act in layer_activations: loss = tf.math.reduce_mean(act) losses.append(loss) return tf.reduce_sum(losses) def show(img): plt.imshow(img) # 返回卷积后的图片的梯度 class TiledGradients(tf.keras.models.Model): def __init__(self, model): super().__init__() self.model = model # 规定输入的图像的格式 @tf.function( input_signature=( tf.TensorSpec(shape=[None, None, 3], dtype=tf.float32), tf.TensorSpec(shape=[], dtype=tf.int32) ) ) # 定义call方法,来计算损失,应用梯度 def __call__(self, img, tile_size=512): shift_down, shift_right, img_rolled = random_roll(img, tile_size) # 初始化梯度为0 gradients = tf.zeros_like(img_rolled) print(img_rolled) # 产生分块坐标列表 xs = range(0, img_rolled.shape[0], tile_size) ys = range(0, img_rolled.shape[1], tile_size) for x in xs: for y in ys: # 计算图块的梯度 with tf.GradientTape() as tape: tape.watch(img_rolled) # 从图像中提取该图块 img_piece = img_rolled[x:x + tile_size, y:y + tile_size] loss = calc_loss(img_piece, self.model) # 更新梯度 gradients = gradients + tape.gradient(loss, img_rolled) # 将进行移动的图块放回原来的位置 gradients = tf.roll(tf.roll(gradients, -shift_right, axis=1), -shift_down, axis=0) # 归一化梯度 gradients /= tf.math.reduce_std(gradients) + 1e-8 print(gradients) return xs get_tiled_gradients = TiledGradients(dream_model) def render_deep_dream(img, step_size=0.01, step_per_octave=100, octaves=range(1), octave_scale=1.3): # 对输入图像进行标准化 base_shape = tf.shape(img) img = tf.keras.preprocessing.image.img_to_array(img) img = tf.keras.applications.inception_v3.preprocess_input(img) initial_shape = img.shape[:-1] img = tf.image.resize(img, initial_shape) for octave in octaves: # 进行图像缩放 new_size = tf.cast(tf.convert_to_tensor(base_shape[:-1]), tf.float32) * (octave_scale ** octave) img = tf.image.resize(img, tf.cast(new_size, tf.int32)) for step in range(step_per_octave): gradients = get_tiled_gradients(img) img = img + gradients * step_size img = tf.clip_by_value(img, -1, 1) if step % 10 == 0: print("Octave:{},Step:{}".format(octave, step)) # img = tf.image.resize(img, base_shape) img = tf.cast(255 * (img + 1.0) / 2.0, tf.uint8) # img = tf.image.convert_image_dtype(img/255.0, dtype=tf.uint8) return img original_img = read_image('19.jpg') # show(render_deep_dream(img=original_img)) a = get_tiled_gradients(img=original_img) print(a) plt.show()
PHP
UTF-8
6,731
2.953125
3
[]
no_license
<?php /** * Description of Meses del año * * Idiomas implementados: Inglés, Francés, Italiano, Alemán, Español, Ruso, Chino * * @author Sergio Pérez <sergio.perez@albatronic.com> * @copyright Informática ALBATRONIC, SL * @since 20-feb-2013 * */ class Meses extends Tipos { protected $tipos; public function __construct($IDTipo = null) { switch ($_SESSION['idiomas']['disponibles'][$_SESSION['idiomas']['actual']]['codigo']) { case 'en': // Inglés $this->tipos = array( array('Id' => '1', 'Value' => 'January'), array('Id' => '2', 'Value' => 'February'), array('Id' => '3', 'Value' => 'March'), array('Id' => '4', 'Value' => 'April'), array('Id' => '5', 'Value' => 'May'), array('Id' => '6', 'Value' => 'June'), array('Id' => '7', 'Value' => 'July'), array('Id' => '8', 'Value' => 'August'), array('Id' => '9', 'Value' => 'September'), array('Id' => '10', 'Value' => 'October'), array('Id' => '11', 'Value' => 'November'), array('Id' => '12', 'Value' => 'December'), ); break; case 'fr': // Francés $this->tipos = array( array('Id' => '1', 'Value' => 'Janvier'), array('Id' => '2', 'Value' => 'Février'), array('Id' => '3', 'Value' => 'Mars'), array('Id' => '4', 'Value' => 'Avril'), array('Id' => '5', 'Value' => 'Mai'), array('Id' => '6', 'Value' => 'Juin'), array('Id' => '7', 'Value' => 'Juillet'), array('Id' => '8', 'Value' => 'Août'), array('Id' => '9', 'Value' => 'September'), array('Id' => '10', 'Value' => 'Octobre'), array('Id' => '11', 'Value' => 'Novembre'), array('Id' => '12', 'Value' => 'Décembre'), ); break; case 'it': // Italiano $this->tipos = array( array('Id' => '1', 'Value' => 'Gennaio'), array('Id' => '2', 'Value' => 'Febbraio'), array('Id' => '3', 'Value' => 'Marzo'), array('Id' => '4', 'Value' => 'Aprile'), array('Id' => '5', 'Value' => 'Maggio'), array('Id' => '6', 'Value' => 'Giugno'), array('Id' => '7', 'Value' => 'Luglio'), array('Id' => '8', 'Value' => 'Agosto'), array('Id' => '9', 'Value' => 'Settembre'), array('Id' => '10', 'Value' => 'Ottobre'), array('Id' => '11', 'Value' => 'Novembre'), array('Id' => '12', 'Value' => 'Dicembre'), ); break; case 'de': // Alemán $this->tipos = array( array('Id' => '1', 'Value' => 'Januar'), array('Id' => '2', 'Value' => 'Februar'), array('Id' => '3', 'Value' => 'März'), array('Id' => '4', 'Value' => 'April'), array('Id' => '5', 'Value' => 'Mai'), array('Id' => '6', 'Value' => 'Juni'), array('Id' => '7', 'Value' => 'Juli'), array('Id' => '8', 'Value' => 'August'), array('Id' => '9', 'Value' => 'September'), array('Id' => '10', 'Value' => 'Oktober'), array('Id' => '11', 'Value' => 'November'), array('Id' => '12', 'Value' => 'Dezember'), ); break; case 'ru': // Ruso $this->tipos = array( array('Id' => '1', 'Value' => 'янва́рь'), array('Id' => '2', 'Value' => 'февра́ль'), array('Id' => '3', 'Value' => 'март'), array('Id' => '4', 'Value' => 'апре́ль'), array('Id' => '5', 'Value' => 'май'), array('Id' => '6', 'Value' => 'ию́нь'), array('Id' => '7', 'Value' => 'ию́ль'), array('Id' => '8', 'Value' => 'а́вгуст'), array('Id' => '9', 'Value' => 'сентя́брь'), array('Id' => '10', 'Value' => 'октя́брь'), array('Id' => '11', 'Value' => 'ноя́брь'), array('Id' => '12', 'Value' => 'дека́брь'), ); break; case 'zh': // Chino $this->tipos = array( array('Id' => '1', 'Value' => '一月'), array('Id' => '2', 'Value' => '二月'), array('Id' => '3', 'Value' => '三月'), array('Id' => '4', 'Value' => '四月'), array('Id' => '5', 'Value' => '五月'), array('Id' => '6', 'Value' => '六月'), array('Id' => '7', 'Value' => '七月'), array('Id' => '8', 'Value' => '八月'), array('Id' => '9', 'Value' => '九月'), array('Id' => '10', 'Value' => '十月'), array('Id' => '11', 'Value' => '十一月'), array('Id' => '12', 'Value' => '十二月'), ); break; default: // Español $this->tipos = array( array('Id' => '1', 'Value' => 'Enero'), array('Id' => '2', 'Value' => 'Febrero'), array('Id' => '3', 'Value' => 'Marzo'), array('Id' => '4', 'Value' => 'Abril'), array('Id' => '5', 'Value' => 'Mayo'), array('Id' => '6', 'Value' => 'Junio'), array('Id' => '7', 'Value' => 'Julio'), array('Id' => '8', 'Value' => 'Agosto'), array('Id' => '9', 'Value' => 'Septiembre'), array('Id' => '10', 'Value' => 'Octubre'), array('Id' => '11', 'Value' => 'Noviembre'), array('Id' => '12', 'Value' => 'Diciembre'), ); break; } parent::__construct($IDTipo); } } ?>
Java
UTF-8
3,754
2.890625
3
[]
no_license
package com.telogical.diff.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.jar.JarEntry; import java.util.zip.ZipOutputStream; public class ArchiveUtils { private static final int BUFFER = 4096; public static final int MAX_ARCHIVE_ENTRIES = 65500; private static void populateToBeJared(File dir, List<File> toJarList) { // look through the children of the directory File[] children = dir.listFiles(); for (int i = 0; i < children.length; i++) { // add files that exist to the jar list, if directory then recurse File child = children[i]; if (child != null && child.exists()) { if (!child.isDirectory()) { toJarList.add(new File(child.getPath())); } else { populateToBeJared(child, toJarList); } } } } public static void archive(File dir, String outputPrefix) throws IOException { archive(dir, outputPrefix, MAX_ARCHIVE_ENTRIES); } public static void archive(File dir, String outputPrefix, int maxFilesPerPart) throws IOException { // max zip file entries is 65536, I leave a little room if (maxFilesPerPart > MAX_ARCHIVE_ENTRIES) { maxFilesPerPart = MAX_ARCHIVE_ENTRIES; } // if the directory to jar doesn't exist or isn't a directory if (dir == null || !dir.isDirectory()) { throw new IllegalArgumentException("Input must be an existing directory."); } // get a listing of the files to be jared List<File> toBeJared = new ArrayList<File>(); populateToBeJared(dir, toBeJared); int numTotalFiles = toBeJared.size(); List<List<File>> archiveFileList = new ArrayList<List<File>>(); int start = 0; int end = 0; while (start < numTotalFiles) { end += maxFilesPerPart; if (end > numTotalFiles) { end = numTotalFiles; } List<File> curFileList = toBeJared.subList(start, end); archiveFileList.add(curFileList); start = end; } String archivePrefix = outputPrefix; if (archivePrefix.endsWith(".jar") || archivePrefix.endsWith(".zip")) { archivePrefix = archivePrefix.substring(0, (archivePrefix.length() - 4)); } int numArchives = archiveFileList.size(); for (int i = 0; i < numArchives; i++) { List<File> curArchive = archiveFileList.get(i); String curArchiveName = archivePrefix + (numArchives == 1 ? ".zip" : ".part." + i + ".zip"); byte buffer[] = new byte[BUFFER]; FileOutputStream stream = new FileOutputStream(curArchiveName); ZipOutputStream out = new ZipOutputStream(stream); // loop through the files for (int k = 0; k < curArchive.size(); k++) { // for each entry create the correct jar path name File toArchive = curArchive.get(k); File current = toArchive; String currentPath = null; while (!current.toString().equals(dir.toString())) { currentPath = current.getName() + (currentPath == null ? "" : File.separator + currentPath); current = current.getParentFile(); } // Add entry to the jar JarEntry jarAdd = new JarEntry(currentPath); jarAdd.setTime(toArchive.lastModified()); out.putNextEntry(jarAdd); // Write file to archive FileInputStream in = new FileInputStream(toArchive); while (true) { int nRead = in.read(buffer, 0, buffer.length); if (nRead <= 0) { break; } out.write(buffer, 0, nRead); } in.close(); } out.close(); stream.close(); } } }
C
UTF-8
8,137
3.203125
3
[]
no_license
#include "quicksort.h" #include "stretchy_buffer.h" //function to produce a random number between low and high ssize_t random_in_range(ssize_t low, ssize_t high) { ssize_t r = rand(); r = (r << 31) | rand(); return r % (high - low + 1) + low; } //function to swap two tuples void swap(tuple *tuples, ssize_t i, ssize_t j) { tuple tup = tuples[i]; tuples[i] = tuples[j]; tuples[j] = tup; } //function to define the partition ssize_t hoare_partition(tuple *tuples, ssize_t low, ssize_t high) { ssize_t i = low - 1; ssize_t j = high + 1; ssize_t random = random_in_range(low, high);//pick a random number swap(tuples, low, random); //swap tuple in index low with tuple in index random uint64_t pivot = tuples[high].key; while (1) { do { i++; } while (tuples[i].key < pivot); do { j--; } while (tuples[j].key > pivot); if (i >= j) { return j; } swap(tuples, i, j); } } //function to execute a quicksort void random_quicksort(tuple *tuples, ssize_t low, ssize_t high) { if (low >= high) { return; } ssize_t pivot = hoare_partition(tuples, low, high); random_quicksort(tuples, low, pivot); random_quicksort(tuples, pivot + 1, high); } static void *sort_job(void *argm) { sort_args args = *(sort_args *) argm; queue_node *current_queue = args.queue; uint32_t start = args.start; uint32_t end = args.end; int index = args.index; relation *relations[2] = {args.relations[0], args.relations[1]}; queue_node *temp_queue = NULL; bool swapped = false; for (ssize_t i = index ; i < 9 ; i++) { if (!(end > 0)) { break; } temp_queue = NULL; for (ssize_t z = start ; z < end ; z++) { queue_node *current_item = &(current_queue[z]); ssize_t base = current_item->base, size = current_item->size; if ( size*sizeof(tuple) + sizeof(uint64_t) < 32*1024) { random_quicksort(relations[(i+1)%2]->tuples, base, base + size - 1); for (ssize_t j = base; j < base + size; j++) { relations[i%2]->tuples[j] = relations[(i + 1) % 2]->tuples[j]; } } else { histogram new_h, new_p; build_histogram(relations[(i+1)%2], &new_h, i, base, size); build_psum(&new_h, &new_p); relations[i%2] = build_reordered_array(relations[i%2], relations[(i+1)%2], &new_h, &new_p, i, base, size); for (ssize_t j = 0; j < 256 && i != 8; j++) { if (new_h.array[j] != 0) { queue_node q_node; q_node.base = base + new_p.array[j]; q_node.size = new_h.array[j]; buf_push(temp_queue, q_node); } } } } if (swapped) { buf_free(current_queue); } current_queue = temp_queue; swapped = true; start = 0; end = buf_len(temp_queue); } if (swapped) { buf_free(temp_queue); } return NULL; } void iterative_sort(relation *rel, queue_node **retval, uint32_t *jobs_created, thr_pool_t *pool) { relation *reordered = allocate_reordered_array(rel); queue_node *q = NULL; relation *relations[2]; //to swap after each iteration histogram new_h, new_p; //build the first histogram and the first psum ( of all the array) build_histogram(rel, &new_h, 1, 0, rel->num_tuples); build_psum(&new_h, &new_p); //build the R' (reordered R) reordered = build_reordered_array(reordered, rel, &new_h, &new_p, 1, 0, rel->num_tuples); relations[0] = rel; relations[1] = reordered; //the byte take the values [0-255] , each value is a bucket //each bucket that found push it in the queue queue_node *q_to_return = NULL; bool check_queue = true; for (ssize_t j = 0; j < 256; j++) { if (new_h.array[j] != 0) { queue_node q_node; q_node.byte = j; q_node.base = new_p.array[j]; q_node.size = new_h.array[j]; buf_push(q, q_node); } } ssize_t i; int number_of_buckets = 0; //above we execute the routine for the first byte //now for all the other bytes for (i = 2; i <= 8 ; i++) { number_of_buckets = buf_len(q); if (check_queue && number_of_buckets >= 2) { for (ssize_t tmp_i = 0 ; tmp_i < buf_len(q) ; tmp_i++) { queue_node q_node = q[tmp_i]; buf_push(q_to_return, q_node); } check_queue = false; } #ifdef MULTITHREAD_SORT if (!(number_of_buckets > 0) || (number_of_buckets / MAX_JOBS) > 0) { break; } #else if (!(number_of_buckets > 0)) { break; } #endif //the size of the queue is the number of the buckets while (number_of_buckets) { //for each bucket queue_node *current_item = &(q[0]); ssize_t base = current_item->base, size = current_item->size; // base = start of bucket , size = the number of cells of the bucket buf_remove(q, 0); number_of_buckets--; //check if the bucket is smaller than 32 KB to execute quicksort if ( size*sizeof(tuple) + sizeof(uint64_t) < 32*1024) { random_quicksort(relations[(i+1)%2]->tuples, base, base + size - 1); for (ssize_t j = base; j < base + size; j++) { relations[i%2]->tuples[j] = relations[(i + 1)%2]->tuples[j]; } } else { // if the bucket is bigger than 32 KB , sort by the next byte histogram new_h, new_p; //build again histogram and psum of the next byte build_histogram(relations[(i+1)%2], &new_h, i, base, size); build_psum(&new_h, &new_p); //build the reordered array of the previous bucket relations[i%2] = build_reordered_array(relations[i%2], relations[(i+1)%2], &new_h, &new_p, i, base, size); //push the buckets to the queue for (ssize_t j = 0; j < 256 && i != 8; j++) { if (new_h.array[j] != 0) { queue_node q_node; q_node.byte = j; q_node.base = base + new_p.array[j]; q_node.size = new_h.array[j]; buf_push(q, q_node); } } } } } number_of_buckets = buf_len(q); //If it wasn't yet sorted, try multithreading if ((number_of_buckets / MAX_JOBS) > 0) { uint32_t jobs_to_create; if (number_of_buckets / MAX_JOBS > 20) { jobs_to_create = MAX_JOBS; } else { jobs_to_create = 2; } *jobs_created = jobs_to_create; sort_args *sort_job_args = MALLOC(sort_args, jobs_to_create); for (ssize_t j = 0 ; j < (ssize_t) jobs_to_create ; j++) { sort_args argm; argm.queue = q; argm.start = j * (number_of_buckets / jobs_to_create); argm.end = (j + 1) * (number_of_buckets / jobs_to_create); if (j == jobs_to_create - 1) { argm.end += number_of_buckets % jobs_to_create; } argm.index = i; argm.relations[0] = relations[0]; argm.relations[1] = relations[1]; sort_job_args[j] = argm; thr_pool_queue(pool, sort_job, (void *) &sort_job_args[j]); } thr_pool_barrier(pool); FREE(sort_job_args); } else { *jobs_created = 0; } *retval = q_to_return; free_reordered_array(reordered); buf_free(q); }
Java
UTF-8
1,322
2.734375
3
[]
no_license
package storage; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.google.gson.Gson; import common.model.Article; public class ArticleStorageManager { // LOAD ALL ARTICLES FROM FILE public ArrayList<Article> loadArticlesFromFile(String filePath) throws IOException{ FileReader file = new FileReader("articles.json"); try{ String articleJsons = new String(Files.readAllBytes(Paths.get(filePath))); Gson gson = new Gson(); ArrayList<Article> articles = new ArrayList(Arrays.asList(gson.fromJson(articleJsons, Article[].class))); System.out.println("[SUCCESS] read whole article file."); return articles; } catch (IOException e){ e.printStackTrace(); } finally { file.close(); } return null; } public void updateArticleFile(List<Article> articles, String filePath) throws IOException{ FileWriter file = new FileWriter(filePath); try{ Gson gson = new Gson(); String uJson = gson.toJson(articles); file.write(uJson); System.out.println("[SUCCESS] updated article file."); } catch (IOException e){ e.printStackTrace(); } finally { file.flush(); file.close(); } } }
JavaScript
UTF-8
686
2.84375
3
[]
no_license
var fs = require('fs'); const result = `'지점코드','지점명','품목코드','품목명','규격','단위','수량','단가','금액','세액','매입처코드','매입처명','비고','수정자','수정시간'`; const resultLength = result.split(',').length; let str ='\n'; console.log(resultLength); result.split(',').map((v,i)=>{ // fs.writeFile(__dirname+'/test.txt', v, 'utf8', function(error){ console.log('write end') }); if(result.length-1==i){ v=v.replace(/\'|\"/gi, ""); }else{ v=v.replace(/\'|\"/gi, "")+'\n'; } try{ fs.appendFileSync(__dirname+'/hubmke_array.txt', v); console.log(i); }catch(error){ console.error(error); } });
Java
UTF-8
8,603
1.6875
2
[]
no_license
package com.br.tiago.roupas.activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.br.tiago.roupas.R; import com.br.tiago.roupas.fragment.CameraFragment; import com.br.tiago.roupas.fragment.FragmentDownload; import com.br.tiago.roupas.fragment.FragmentIBGE; import com.br.tiago.roupas.fragment.FragmentNotificacao; import com.br.tiago.roupas.fragment.FragmentUpload; import com.br.tiago.roupas.fragment.FragmentUsuario; import com.br.tiago.roupas.fragment.WifiReceiverFragment; import com.br.tiago.roupas.fragment.cadastro.FragmentCadastro; import com.br.tiago.roupas.fragment.home.FragmentHome; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener ,GoogleApiClient.OnConnectionFailedListener { private FirebaseAuth mFirebaseAuth; private GoogleApiClient mGoogleApiClient; private GoogleSignInAccount account; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); /* INICIO AUTH */ GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); this.mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); /* FIM AUTH */ Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarMain); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, new FragmentHome()); ft.commit(); this.account = GoogleSignIn.getLastSignedInAccount(this); if( (this.account != null) ) { View headerView = navigationView.getHeaderView(0); TextView textViewUsuario = (TextView) headerView.findViewById(R.id.textViewUsuarioLabel); TextView textViewEmail = (TextView) headerView.findViewById(R.id.textViewEmail); ImageView imageViewUsuario = (ImageView) headerView.findViewById(R.id.imageViewUsuario); imageViewUsuario.setClipToOutline(true); textViewUsuario.setText(this.account.getDisplayName()); textViewEmail.setText(this.account.getEmail()); Glide.with(this) .load(this.account.getPhotoUrl().toString()) .into(imageViewUsuario); } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onNavigationItemSelected(MenuItem item) { int itemId = item.getItemId(); this.displaySelectedScreen(itemId); return true; } private void displaySelectedScreen(int itemId) { Fragment fragment = null; switch (itemId){ case R.id.nav_user: fragment = new FragmentUsuario(); break; /*case R.id.nav_medicine: fragment = new FragmentMedicamento(); break;*/ case R.id.nav_notificacoes: fragment = new FragmentNotificacao(); break; case R.id.nav_sair: signOut(); break; case R.id.nav_upload: fragment = new FragmentUpload(); break; case R.id.nav_map: Intent myIntent = new Intent(this, MapActivity.class); startActivity(myIntent); break; case R.id.nav_download: fragment = new FragmentDownload(); break; case R.id.nav_retrofit_ibge: fragment = new FragmentIBGE(); break; case R.id.nav_cadastro: fragment = new FragmentCadastro(); break; case R.id.nav_wifi: fragment = new WifiReceiverFragment(); break; case R.id.nav_home: fragment = new FragmentHome(); break; case R.id.nav_camera: fragment = new CameraFragment(); } if (fragment != null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content_frame, fragment); ft.commit(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); } @Override protected void onStart() { super.onStart(); this.mFirebaseAuth = FirebaseAuth.getInstance(); //FirebaseUser currentUser = this.mFirebaseAuth.getCurrentUser(); if( GoogleSignIn.getLastSignedInAccount(this) == null ){ startActivity(new Intent(this,LoginActivity.class)); } } @Override protected void onResume() { super.onResume(); } private void signOut(){ this.mFirebaseAuth.signOut(); Log.i("signOut","Desconectado do Firebase"); Auth.GoogleSignInApi.signOut( this.mGoogleApiClient ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { Log.i("signOut","Desconectado do Google"); } }); finish(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { if( connectionResult != null ) { Toast.makeText(MainActivity.this, "Falha na autenticação: " + connectionResult.getErrorMessage().toString(), Toast.LENGTH_LONG).show(); } } }
Ruby
UTF-8
7,778
3.078125
3
[ "MIT" ]
permissive
# mimeparse.rb # # This module provides basic functions for handling mime-types. It can # handle matching mime-types against a list of media-ranges. See section # 14.1 of the HTTP specification [RFC 2616] for a complete explanation. # # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 # # --------- # # This is a port of Joe Gregario's mimeparse.py, which can be found at # <http://code.google.com/p/mimeparse/>. # # ported from version 0.1.2 # # Comments are mostly excerpted from the original. module MIMEParse module_function # Carves up a mime-type and returns an Array of the # [type, subtype, params] where "params" is a Hash of all # the parameters for the media range. # # For example, the media range "application/xhtml;q=0.5" would # get parsed into: # # ["application", "xhtml", { "q" => "0.5" }] def parse_mime_type(mime_type) parts = mime_type.split(";") params = {} parts[1..-1].map do |param| k,v = param.split("=").map { |s| s.strip } params[k] = v end full_type = parts[0].strip # Java URLConnection class sends an Accept header that includes a single "*" # Turn it into a legal wildcard. full_type = "*/*" if full_type == "*" type, subtype = full_type.split("/") raise "malformed mime type" unless subtype [type.strip, subtype.strip, params] end # Carves up a media range and returns an Array of the # [type, subtype, params] where "params" is a Hash of all # the parameters for the media range. # # For example, the media range "application/*;q=0.5" would # get parsed into: # # ["application", "*", { "q", "0.5" }] # # In addition this function also guarantees that there # is a value for "q" in the params dictionary, filling it # in with a proper default if necessary. def parse_media_range(range) type, subtype, params = parse_mime_type(range) unless params.has_key?("q") and params["q"] and params["q"].to_f and params["q"].to_f <= 1 and params["q"].to_f >= 0 params["q"] = "1" end [type, subtype, params] end # Find the best match for a given mime-type against a list of # media_ranges that have already been parsed by #parse_media_range # # Returns the fitness and the "q" quality parameter of the best match, # or [-1, 0] if no match was found. Just as for #quality_parsed, # "parsed_ranges" must be an Enumerable of parsed media ranges. def fitness_and_quality_parsed(mime_type, parsed_ranges) best_fitness = -1 best_fit_q = 0 target_type, target_subtype, target_params = parse_media_range(mime_type) parsed_ranges.each do |type,subtype,params| if (type == target_type or type == "*" or target_type == "*") and (subtype == target_subtype or subtype == "*" or target_subtype == "*") param_matches = target_params.find_all { |k,v| k != "q" and params.has_key?(k) and v == params[k] }.length fitness = (type == target_type) ? 100 : 0 fitness += (subtype == target_subtype) ? 10 : 0 fitness += param_matches if fitness > best_fitness best_fitness = fitness best_fit_q = params["q"] end end end [best_fitness, best_fit_q.to_f] end # Find the best match for a given mime-type against a list of # media_ranges that have already been parsed by #parse_media_range # # Returns the "q" quality parameter of the best match, 0 if no match # was found. This function behaves the same as #quality except that # "parsed_ranges" must be an Enumerable of parsed media ranges. def quality_parsed(mime_type, parsed_ranges) fitness_and_quality_parsed(mime_type, parsed_ranges)[1] end # Returns the quality "q" of a mime_type when compared against # the media-ranges in ranges. For example: # # irb> quality("text/html", "text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5") # => 0.7 def quality(mime_type, ranges) parsed_ranges = ranges.split(",").map { |r| parse_media_range(r) } quality_parsed(mime_type, parsed_ranges) end # Takes a list of supported mime-types and finds the best match # for all the media-ranges listed in header. The value of header # must be a string that conforms to the format of the HTTP Accept: # header. The value of supported is an Enumerable of mime-types # # irb> best_match(["application/xbel+xml", "text/xml"], "text/*;q=0.5,*/*; q=0.1") # => "text/xml" def best_match(supported, header) parsed_header = header.split(",").map { |r| parse_media_range(r) } weighted_matches = supported.map do |mime_type| [fitness_and_quality_parsed(mime_type, parsed_header), mime_type] end weighted_matches.sort! weighted_matches.last[0][1].zero? ? nil : weighted_matches.last[1] end end if __FILE__ == $0 require "test/unit" class TestMimeParsing < Test::Unit::TestCase include MIMEParse def test_parse_media_range assert_equal [ "application", "xml", { "q" => "1" } ], parse_media_range("application/xml;q=1") assert_equal [ "application", "xml", { "q" => "1" } ], parse_media_range("application/xml") assert_equal [ "application", "xml", { "q" => "1" } ], parse_media_range("application/xml;q=") assert_equal [ "application", "xml", { "q" => "1", "b" => "other" } ], parse_media_range("application/xml ; q=1;b=other") assert_equal [ "application", "xml", { "q" => "1", "b" => "other" } ], parse_media_range("application/xml ; q=2;b=other") # Java URLConnection class sends an Accept header that includes a single "*" assert_equal [ "*", "*", { "q" => ".2" } ], parse_media_range(" *; q=.2") end def test_rfc_2616_example accept = "text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5" assert_equal 1, quality("text/html;level=1", accept) assert_equal 0.7, quality("text/html", accept) assert_equal 0.3, quality("text/plain", accept) assert_equal 0.5, quality("image/jpeg", accept) assert_equal 0.4, quality("text/html;level=2", accept) assert_equal 0.7, quality("text/html;level=3", accept) end def test_best_match @supported_mime_types = [ "application/xbel+xml", "application/xml" ] # direct match assert_best_match "application/xbel+xml", "application/xbel+xml" # direct match with a q parameter assert_best_match "application/xbel+xml", "application/xbel+xml; q=1" # direct match of our second choice with a q parameter assert_best_match "application/xml", "application/xml; q=1" # match using a subtype wildcard assert_best_match "application/xml", "application/*; q=1" # match using a type wildcard assert_best_match "application/xml", "*/*" @supported_mime_types = [ "application/xbel+xml", "text/xml" ] # match using a type versus a lower weighted subtype assert_best_match "text/xml", "text/*;q=0.5,*/*;q=0.1" # fail to match anything assert_best_match nil, "text/html,application/atom+xml; q=0.9" # common AJAX scenario @supported_mime_types = [ "application/json", "text/html" ] assert_best_match "application/json", "application/json, text/javascript, */*" # verify fitness sorting assert_best_match "application/json", "application/json, text/html;q=0.9" end def test_support_wildcards @supported_mime_types = ['image/*', 'application/xml'] # match using a type wildcard assert_best_match 'image/*', 'image/png' # match using a wildcard for both requested and supported assert_best_match 'image/*', 'image/*' end def assert_best_match(expected, header) assert_equal(expected, best_match(@supported_mime_types, header)) end end end
Go
UTF-8
1,979
2.53125
3
[ "MIT" ]
permissive
package main import ( "encoding/json" "fmt" "io/ioutil" "log" "os" "os/signal" "path/filepath" "syscall" "github.com/alexflint/go-arg" ) type ( configStruct struct { Title string `json:"title"` Runners []runnerStruct `json:"services"` } obj map[string]interface{} ) var ( wd, _ = os.Getwd() app struct { ConfigPath string `arg:"positional" help:"runner.json path"` Editor string `arg:"-e" help:"editor to use"` Port int `arg:"-p" help:"webserver port"` Gui bool `arg:"-g" help:"use gui window"` } ) func main() { signalChannel := make(chan os.Signal, 2) signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM) go func() { ret := <-signalChannel log.Println(ret) switch ret { case os.Interrupt, syscall.SIGTERM: for _, s := range activeServices { s.stop() } if wv != nil { wv.Exit() } } }() app.ConfigPath = dir(wd) app.Editor = "subl" app.Port = 31777 app.Gui = true arg.MustParse(&app) config := &configStruct{Runners: []runnerStruct{}} configPath := configpath(app.ConfigPath) if raw, err := ioutil.ReadFile(configPath); err == nil { if err = json.Unmarshal(raw, config); err != nil { exit("JSON error: " + err.Error()) } } else { exit("Can't read runner.json") } for id, service := range config.Runners { if !service.Ignore { makeService(id, filepath.Dir(configPath), service) } else { activeServices = append(activeServices, &serviceStruct{runnerStruct: service, ID: id, Status: statusIgnored}) } } webserver(config) } func exit(err string) { fmt.Println(err) os.Exit(1) } func dir(dir string) string { return filepath.Dir(dir+"/") + "/" } func configpath(path string) string { path, _ = filepath.Abs(path) if info, err := os.Stat(path); err == nil { if !info.IsDir() { return path } if path, err = filepath.Abs(path + "/runner.json"); err == nil { return path } } exit("runner.json not found") return "" }
Markdown
UTF-8
15,774
3.109375
3
[]
no_license
# Tema 4 - Gestión de procesos (I) Este tema trata sobre la gestión de procesos en ejecución. Un proceso puede ejecutarse en primer plano (*foreground*) o en segundo plano (*background*). Hay procesos que están diseñados para ejecutarse en *background*, y se les suele llamar **demonios**. usuarios y grupos de usuarios en sistemas CentOS 7. Pero la teoría y filosofía de trabajo es aplicable a cualquier sistema Linux. También describe quién es el usuario *root*. En los sistemas Linux, todo lo que un usuario puede o no puede hacer con un fichero está determinado por permisos y grupos. Si se dispone de los permisos necesarios, o si se pertenece al grupo con permisos necesarios, se podrá acceder a un fichero o directorio. ## Permisos de ficheros y directorios ```bash ls -l /etc/passwd -rw-r--r--. 1 root root 1395 sep 22 01:14 /etc/passwd ls -ld /etc/ drwxr-xr-x. 102 root root 8192 oct 13 05:21 /etc/ ``` Los listados anteriores muestran información sobre el propietario y los permisos de los ficheros. Hagamos un repaso: ```text drwxr-xr-x 102 root root 8192 oct 13 05:21 /etc/ __________ ____ _____ | | | | | -> Grupo con permisos sobre el fichero | | | -> Usuario propietario del fichero | | -> Permisos del fichero: - Tipo de fichero (regular, directorio, enlace, etc). - Permisos del usuario/propietario ( r w x ) - Permisos del grupo ( r - x ) - Permisos para el resto de usuarios ( r - x ) ``` Así que los permisos se agrupan para Usuario, Grupo y Otros: ```text - r w x r - x r - x _____ _____ _____ | | | | | -> Permisos para Otros usuarios | | | -> Permisos para el Grupo propietario | -> Permisos para el Usuario propietario ``` Normalmente, estos permisos se representan como 3 números en base octal. Para el ejemplo anterior, los permisos serían 755: ```text - r w x r - x r - x 1 1 1 1 0 1 1 0 1 \___/ \___/ \___/ 7 5 5 Otro ejemplo: - r w - r - - r - - 1 1 0 1 0 0 1 0 0 \___/ \___/ \___/ 6 4 4 ``` A modo de recordatorio, la siguiente tabla muestra la equivalencia entre valores expresados en base 2 (binarios) y valores expresados en base 8 (octal): | Octal | Binario | | :----- | :-------: | | 0 | 0 0 0 | | 1 | 0 0 1 | | 2 | 0 1 0 | | 3 | 0 1 1 | | 4 | 1 0 0 | | 5 | 1 0 1 | | 6 | 1 1 0 | | 7 | 1 1 1 | Hay una pequeña diferencia entre el significado de los permisos para ficheros y directorios: - **Ficheros** - **r**: El fichero puede ser leído (se lee su contenido). - **w**: El fichero puede ser escrito/modificado (se escribe/modifica su contenido). - **x**: El fichero puede ser ejecutado (el fichero es un programa o *script*). - **Directorios** - **r**: Se puede listar el contenido del directorio (hacer un *ls*, por ejemplo). - **w**: Se pueden crear o eliminar ficheros dentro del directorio. - **x**: Se puede acceder al directorio, y a sus subdirectorios (hacer un *cd*). Hay que tener en cuenta que, cuando no se tiene permiso de lectura de un directorio, no se pueden mostrar (listar) sus contenidos, pero sí se puede, por ejemplo, leer un fichero que esté dentro: tendríamos que usar la ruta absoluta para leer un fichero dentro de un diretcorio que no podemos listar. Esto implica que se debe conocer a priori el nombre completo del contenido de un directorio. Además, aunque no se pueda leer (**r**) o escribir (**w**) en un directorio, siempre que se pueda acceder a él (**x**), se podrá trabajar con los ficheros que contiene. Dicho de otra manera, los permisos de un directorio no son los permisos de los ficheros (y sub-directorios) que contiene. Recordatorio: al hacer un `ls -l` podemos ver de qué tipo es un fichero: | Código | Tipo de objeto | | :------- | :-----------------------------------: | | - | Fichero regular. | | d | Directorio. | | l | Enlace simbólico. | | c | Dispositivo (especial) de carácter. | | b | Dispositivo (especial) de bloque. | | p | FIFO. | | s | Socket. | ### Cambiar los permisos de ficheros y directorios Se usa la herramienta **`chmod`** (*change file mode bits*) para cambiar los permisos. Los argumentos con los que se invoca a *chmod* son: - ¿Para quién se cambian los permisos?: usuario, grupo, otros, todos. [ugoa]. - ¿Se conceden permisos [+] o se revocan permisos [-]? - ¿Qué permiso se configura?: lectura, escritura y/o ejecución [rwx] A continuación se muestran algunos ejemplos de permisos para ficheros: ```bash cd mkdir permisos cd permisos echo "Este es un fichero para jugar con chmod" > permisos.txt # Vamos a cambiar algunos permisos ls -l # -rw-rw-r--. 1 fabi fabi 40 oct 14 21:15 permisos.txt chmod o-r permisos.txt ls -l # -rw-rw----. 1 fabi fabi 40 oct 14 21:15 permisos.txt chmod g+x permisos.txt ls -l # -rw-rwx---. 1 fabi fabi 40 oct 14 21:15 permisos.txt chmod u-r permisos.txt ls -l # --w-rwx---. 1 fabi fabi 40 oct 14 21:15 permisos.txt # También podemos cambiar varios permisos a la vez chmod u+rx permisos.txt ls -l # -rwxrwx---. 1 fabi fabi 40 oct 14 21:15 permisos.txt chmod go-wx permisos.txt ls -l # -rwxr-----. 1 fabi fabi 40 oct 14 21:15 permisos.txt chmod a-x permisos.txt ls -l # -rw-r-----. 1 fabi fabi 40 oct 14 21:15 permisos.txt chmod a+rw permisos.txt ls -l # -rw-rw-rw-. 1 fabi fabi 40 oct 14 21:15 permisos.txt ``` También es común usar los valores expresados en base octal para cambiar los los permisos: ```bash chmod 755 permisos.txt ls -l # -rwxr-xr-x. 1 fabi fabi 40 oct 14 21:15 permisos.txt chmod 750 permisos.txt ls -l # -rwxr-x---. 1 fabi fabi 40 oct 14 21:15 permisos.txt chmod 644 permisos.txt ls -l # -rw-r--r--. 1 fabi fabi 40 oct 14 21:15 permisos.txt chmod 650 permisos.txt ls -l # -rw-r-x---. 1 fabi fabi 40 oct 14 21:15 permisos.txt chmod 666 permisos.txt ls -l # -rw-rw-rw-. 1 fabi fabi 40 oct 14 21:15 permisos.txt ``` Y para comprender mejor cómo funcionan los permisos en los directorios, veamos algunos ejemplos: ```bash cd ls -l permisos # -rwxr-xr-x. 1 fabi fabi 40 oct 14 21:15 permisos.txt ls -ld permisos # drwxrwxr-x. 2 fabi fabi 26 oct 14 21:15 permisos/ chmod 400 permisos ls -ld permisos # dr--------. 2 fabi fabi 26 oct 14 21:15 permisos/ cd permisos/ # bash: cd: permisos/: Permiso denegado ls permisos/ # ls: no se puede acceder a permisos/permisos.txt: Permiso denegado # permisos.txt chmod 100 permisos ls -ld permisos # d--x------. 2 fabi fabi 26 oct 14 21:15 permisos/ ls permisos # ls: no se puede abrir el directorio permisos/: Permiso denegado cd permisos ls # ls: no se puede abrir el directorio .: Permiso denegado pwd /#home/fabi/permisos cat permisos.txt # Este es un fichero para jugar con chmod ``` ### Propietarios de un fichero o un directorio Un fichero pertenece a un **usuario** y a un **grupo**. Los usuarios y los grupos tienen asociados un identificador numérico, llamados *Id. de usuario* (**UID**) e *Id. de grupo* (**GID**). Los usuarios del sistema están definidos en los ficheros `/etc/passwd` y `/etc/shadow`. Los grupos están definidos en los ficheros `/etc/group` y `/etc/gshadow`. ```bash cat /etc/group | grep fabi # El usuario fabi aparece en dos líneas: fabi:x:1000:fabi vboxsf:x:990:fabi ``` En el ejemplo anterior, se puede ver que el usuario *fabi* tiene *UID = 1000* y *GID = 1000*. El usuario *vboxsf* tiene *UID = 990* y *GID = 990*. También se puede ver que el usuario *fabi* pertenece al grupo *vboxsf*. ### Cambiar el propietario de un fichero o directorio ```bash su - # Cambia el usuario y el grupo de un fichero o directorio chown fabi:developers /home/fabi/license.txt chown fabi:developers /home/fabi/projects/ # Cambia el usuario y el grupo de un directorio y todo su contenido chown -R fabi:developers /home/fabi/projects ``` ## Usuarios Antes de nada, como usuario de un sistema Linux: ¿quién soy yo? ¿a qué grupos pertenezco? Ambas preguntas se responden con estos comandos: ```bash # ¿Qué usuario soy yo? whoami # ¿A qué grupos pertenezco? groups # Obteniendo toda la información a la vez id id -u id -n id -g man id ``` ### /etc/passwd y /etc/shadow Cuando se crea un usuario en el sistema, se alamcena la siguiente información en el fichero `/etc/passwd`. Esta información son 7 campos, separados por caracteres (`:`). ```bash username:x:UID:GID:comment:home_directory:login_shell 1 2 3 4 5 6 7 root:x:0:0:root:/root:/bin/bash fabi:x:1000:1000:Fabi:/home/fabi:/bin/bash ``` Los campos son: 1. Id. de usuario (se almacena en las variables $USER o $LOGNAME de la *shell*.) 2. Contraseña cifrada (o una x que indica que se usa `/etc/shadow`) 3. UID (código numérico del usuario) 4. GID (código numérico del grupo) - Aunque un usuario puede pertenecer a más de un grupo. 5. Comentarios: por ejemplo el nombre completo, o el nombre de la empresa, etc. 6. Directorio *home* (ruta absoluta): normalmente */home/$USER*. 7. *Shell* del usuario cuando hace *login*: por ejemplo, */bin/bash*. Normalmente, el fichero */etc/passwd* puede ser leido por todos los usuarios, pero sólo el usuario *root* puede modificar su contenido. Si el usuario tiene una **x**, quiere decir que su contraseña cifrada se encuentra almacenada en el fichero */etc/shadow*. Este fichero sólo puede ser leído y modificado por *root*. ### passwd Un usuario puede modificar su contraseña usando el comando `passwd`: ```bash su - passwd # Para cambiar la contraseña de un usuario en particular, se ejecuta: passwd fabi man passwd man shadow ``` ### Añadir usuarios Al añadir un usuario se crea su directorio personal en */home*. Por ejemplo, para la usuaria *peppa*, se creará el directorio */home/peppa*. Dentro de */home/peppa*, se copia una plantilla (que se encuentra en */etc/skel*). Tras crear al usuario, hay que asignarle una constraseña. ```bash sudo adduser peppa sudo passwd peppa ``` Algunas de las opciones más comunes al usar estos programas son: ```bash # Crea un usuario y establece el grupo inicial al que pertenece. (-g) # Por ejemplo, para un grupo llamado developers se haría: sudo adduser -g developers peppa # Para añadir más grupos se usa el flag (-G) sudo adduser -G grupo1,grupo2 peppa # Para no crear un directorio de usuario en /home (-M) sudo adduser -M peppa # Para crear una cuenta de sistema (tampoco crea nada en /home) (-r, --system) sudo adduser -r peppa # Se puede forzar la acción de cambio de contraseña (-f) sudo passwd -f peppa # Se puede borrar la contraseña de un usuario sudo passwd -d peppa man adduser man passwd ``` ### Eliminar usuarios ```bash # Elimina un usuario, pero conserva sus ficheros en /home/peppa sudo userdel peppa # Elimina un usuario, y elimina además el directorio /home/peppa. También se # elimina al usuario de los grupos a los que pertenecía. sudo userdel -r peppa man userdel ``` ### Añadir un usuario a un grupo Normalmente, sólo un usuario con privilegios puede añadir un otro usuario a uno o más grupos: ```bash su - # Añade un usuario a dos grupos con _usermod_ usermod -aG ungrupo,otrogrupo fabi # También se puede usar el comando _gpasswd_ gpasswd -a fabi ungrupo ``` ## Grupos: /etc/gpasswd y /etc/gshadow Un grupo es un conjunto de usuarios que comparten los mismos permisos. Hay dos tipos de grupos: - Primario - Secundarios En Linux, la información relativa a los grupos está en los ficheros `/etc/group` y `/etc/gshadow`. ### /etc/group Cada grupo está definido en una línea del fichero */etc/group*. Cada línea consta de 4 campos (separados por `:`) ```bash cat /etc/group | grep fabi # El usuario fabi aparece en dos líneas: fabi:x:1000:fabi 1 2 3 4 ``` 1. Nombre del grupo. 2. Contraseña cifrada (**x** indica que la contraseña se guarda en /etc/gpaswd). 3. GID. 4. Lista de miembros (separados por `,`). ### Añadir grupos ```bash groupadd developers ``` ### Modificar grupos ```bash # Se puede modificar el GID groupmod -g 1003 developers # Se puede modificar el nombre groupmod -n desarrolladores developers ``` ### Eliminar grupos Un grupo no se podrá eliminar si tiene algún miembro. ```bash groupdel developers ``` ## El usuario root El usuario *root* es un super-usuario que puede hacer todo lo que quiera en el sistema: es el usuario con más privilegios. Esto le permite poder mantener y administrar el sistema. Normalmente, sólo el dueño de un fichero/directorio puede modificar los permisos del mismo. Y normalmente un usuario sólo tiene total libertad dentro de su *home*. Sin embargo, el usuario *root* puede modificar los permisos de cualquier fichero del sistema, incluso aunque no sea el propietario. De igual forma que podemos acceder al sistema con nuestro usuario, también podemos acceder al sistema como *root*, para tener todos los privilegios. Si ya hemos accedido como un usuario pero queremos convertirnos en *root*, podemos usar el comando **su**. ```bash su - ``` También se usa *su* para convertirnos en otro usuario existente en el sistema: ```bash su - juanjo ``` ### El comando sudo Permite ejecutar comandos con permisos de *root* o super usuario. En CentOS 7, para que un usuario pueda ejecutar comandos con *sudo*, debe pertenecer al grupo *wheel*. Sólo un usuario con privilegios puede añadir a otro usuario al grupo de *sudoers*. Para gestionar los usuarios que pueden usar *sudo*, se usa el comando *visudo*. Este comando abre un editor (*vi*) para editar el fichero */etc/sudoers*. ```bash su - # Ya como root, ejecutamos: visudo ``` Al usar *visudo*, se debe buscar una línea similar a la siguiente: ```text %wheel ALL=(ALL) ALL ``` Si la línea estuviese comentada (comienza por #), habrá que descomentarla. Una vez hecho esto, se añade al usuario al grupo *wheel*: ```bash usermod -aG wheel fabi ``` Para que los cambios tengan efecto, se debe salir de la sesión y volver a entrar, o también se puede abrir una nueva *shell* con el usuario: ```bash su - fabi # Ya como el usuario fabi, se puede probar: sudo ls -laR / ``` ### Otra forma alternativa de añadir un usuario a /etc/sudoers En lugar de añadir el usuario al grupo *wheel* también se puede añadir el usuario usando visudo, e insertando una línea similar a esta: ```text fabi ALL=(ALL) ALL ``` ## Para ampliar Este ## Algunos recursos útiles - [Permissions - Ryans Tutorials](https://ryanstutorials.net/linuxtutorial/permissions.php) - [Permissions - IBM Developer](https://developer.ibm.com/tutorials/l-lpic1-104-5/)
PHP
UTF-8
1,966
2.71875
3
[ "Apache-2.0" ]
permissive
<?php declare (strict_types=1); namespace app; use app\common\core\interfaces\InterfaceModel; use think\Model; use app\ExceptionHandle; abstract class BaseModel extends Model implements InterfaceModel { /** * 查找单条数据 * @param array $where * @return array|string */ public static function findSingle(array $where = []) { try { $res = self::where($where)->find(); return empty($res) ? [] : $res->toArray(); } catch (\Exception $e) { return $e->getMessage(); } } /** * 查找全部数据 * @param array $where * @param array $order * @return array|string */ public static function findAll(array $where = [], array $order = ['create_time' => 'desc']) { try { $res = self::where($where)->order($order)->select(); return empty($res) ? [] : $res->toArray(); } catch (\Exception $e) { return $e->getMessage(); } } /** * 查找部分数据 * @param array $where * @param array $order * @param int $offset * @param int $length * @return array|string */ public static function findLimit(array $where = [], array $order = ['create_time' => 'desc'], int $offset = 0, int $length = 10) { try { $res = self::where($where)->order($order)->limit($offset, $length)->select(); return empty($res) ? [] : $res->toArray(); } catch (\Exception $e) { return $e->getMessage(); } } /** * 新增和更新 * @param array $data * @param array $where * @return array|string */ public static function saveData(array $data = [], array $where = []) { try { if (empty($where)) return self::create($data)->toArray(); else return self::update($data, $where)->toArray(); } catch (\Exception $e) { return $e->getMessage(); } } /** * 删除 * @param array $where * @return bool|string */ public static function del(array $where = []) { try { return self::where($where)->delete(); } catch (\Exception $e) { return $e->getMessage(); } } }
JavaScript
UTF-8
2,421
2.75
3
[ "MIT" ]
permissive
/** * preview-image.js * version 1.0 * Eric Olson * https://github.com/zpalffy/preview-image-jquery * * License: MIT - http://opensource.org/licenses/MIT * Original: http://cssglobe.com/easiest-tooltip-and-image-preview-using-jquery/ * by Alen Grakalic (http://cssglobe.com) */ (function($) { $.previewImage = function(options) { var element = $(document); var namespace = '.previewImage'; var opts = $.extend({ /* The following set of options are the ones that should most often be changed by passing an options object into this method. */ 'xOffset': -20, // the x offset from the cursor where the image will be overlayed. 'yOffset': -20, // the y offset from the cursor where the image will be overlayed. 'fadeIn': 'fast', // speed in ms to fade in, 'fast' and 'slow' also supported. 'css': { // css to use, may also be set to false. 'padding': '8px', // 'border': '1px solid gray', 'background-color': '#fff' }, /* The following options should normally not be changed - they are here for cases where this plugin causes problems with other plugins/javascript. */ 'eventSelector': '[data-preview-image]', // the selector for binding mouse events. 'dataKey': 'previewImage', // the key to the link data, should match the above value. 'overlayId': 'preview-image-plugin-overlay', // the id of the overlay that will be created. }, options); // unbind any previous event listeners: element.off(namespace); element.on('mouseover' + namespace, opts.eventSelector, function(e) { var p = $('<p>').attr('id', opts.overlayId).css('position', 'absolute') .css('display', 'none') .append($('<img>').attr('src', $(this).data(opts.dataKey))); if (opts.css) p.css(opts.css); $('body').append(p); p.css("top", (e.pageY + opts.yOffset) + "px").css("left", (e.pageX + opts.xOffset) + "px").fadeIn(opts.fadeIn); }); element.on('mouseout' + namespace, opts.eventSelector, function() { $('#' + opts.overlayId).remove(); }); element.on('mousemove' + namespace, opts.eventSelector, function(e) { $('#' + opts.overlayId).css("top", (e.pageY + opts.yOffset) + "px") .css("left", (e.pageX + opts.xOffset) + "px"); }); return this; }; // bind with defaults so that the plugin can be used immediately if defaults are taken: $.previewImage(); })(jQuery);
JavaScript
UTF-8
1,253
2.921875
3
[ "MIT" ]
permissive
import Vue from 'vue' import Main from './main.vue' import {isEmpty} from "@/util" let Constructor = Vue.extend(Main) export default function ({left, top} = {}) { const instance = new Constructor() const position = getPosition({height: instance.height + 130, width: instance.width + 20, left, top}) instance.positionTop = position.top instance.positionLeft = position.left instance.$mount() document.body.appendChild(instance.$el) instance.visible = true return new Promise((resolve, reject) => { instance.resolve = resolve instance.reject = reject }) } function getPosition({height, width, left, top} = {}) { const windowHeight = window.innerHeight const windowWidth = window.innerWidth //若任一位置信息为空,直接返回居中位置 if (isEmpty(left, top)) { return { top: center(windowHeight, height), left: center(windowWidth, width) } } //判断位置是否超出屏幕外 if (windowWidth < left + width) left = center(windowWidth, width) if (windowHeight < top + height) top = center(windowHeight, height) return {left, top} } function center(full, part) { return Math.round((full - part) / 2) }
Java
ISO-8859-1
5,239
3.265625
3
[]
no_license
import java.util.ArrayList; import java.util.List; public class CamelCaseToStringList { private static List<String> palavras = new ArrayList<>(); private static int index = 0; private static char anterior; private static String palavraMaiuscula = ""; private static String numero = ""; private CamelCaseToStringList() { super(); } private static void adicionaNaListaDePalavras(String palavra) { palavras.add(palavra); } public static void limparListaDePalavras() { palavras.clear(); } public static void setIndex(int i) { index = i; } public static void zerarIndex() { index = 0; } public static void setAnterior(char c) { anterior = c; } public static void limparPalavraMaiuscula() { palavraMaiuscula = ""; } public static void setPalavraMaiuscula(String s) { palavraMaiuscula = s; } public static void limparNumero() { numero = ""; } public static void setNumero(String s) { numero = s; } public static List<String> converterCamelCase(String original) throws ErroDeValidacao { validacaoInicial(original); for (int i = 1; i < original.length(); i++) { setAnterior(original.charAt(i - 1)); efetuaValidacoesEPopulaListaDePalavras(original, i); } if (palavras.isEmpty()) adicionaNaListaDePalavras(original.toLowerCase()); return palavras; } private static void efetuaValidacoesEPopulaListaDePalavras(String original, int i) { if (caracterAnteriorEAtualSaoMaiusculos(original, anterior, i)) setPalavraMaiuscula(validacoesParaPalavraMaiuscula(original, anterior, palavraMaiuscula, i)); else if (palavraMaiusculaDeveSerAdicionadaALista(original, anterior, palavraMaiuscula, i)) adicionaEAtualizaIndexELimpaPalavraMaiuscula(i); else if (original.length() - 1 == i) adicionaNaListaDePalavras(original.substring(index, i + 1).toLowerCase()); else if (Character.isUpperCase(original.charAt(i))) adicionaNaListaDePalavrasEAtualizaIndex(original, i); else if (Character.isDigit(original.charAt(i))) efetuaMovimentacaoParaNumero(original, i); else if (numeroNaoEstaVazioECharAnteriorEUmDigito(original, i)) adicionaNaListaDePalavrasELimpaNumero(); } private static void adicionaNaListaDePalavrasELimpaNumero() { adicionaNaListaDePalavras(numero); limparNumero(); } private static void efetuaMovimentacaoParaNumero(String original, int i) { if (numero.isEmpty()) adicionaNaListaDePalavrasEAtualizaIndex(original, i); setNumero(numero + original.charAt(i)); } private static boolean numeroNaoEstaVazioECharAnteriorEUmDigito(String original, int i) { return !numero.isEmpty() && Character.isDigit(original.charAt(i - 1)); } private static void adicionaNaListaDePalavrasEAtualizaIndex(String original, int i) { adicionaNaListaDePalavras(original.substring(index, i).toLowerCase()); setIndex(i); } private static void adicionaEAtualizaIndexELimpaPalavraMaiuscula(int i) { adicionaNaListaDePalavras(palavraMaiuscula.substring(0, palavraMaiuscula.length() - 1)); limparPalavraMaiuscula(); setIndex(i - 1); } private static boolean caracterAnteriorEAtualSaoMaiusculos(String original, char anterior, int i) { return Character.isUpperCase(anterior) && Character.isUpperCase(original.charAt(i)); } private static String validacoesParaPalavraMaiuscula(String original, char anterior, String palavraMaiuscula, int i) { String ret; if (palavraMaiuscula.length() == 0) ret = palavraMaiuscula + anterior + original.charAt(i); else ret = palavraMaiuscula + original.charAt(i); if (original.length() - 1 == i) adicionaNaListaDePalavrasELimpaPalavraMaiuscula(ret); return ret; } private static void adicionaNaListaDePalavrasELimpaPalavraMaiuscula(String palavraMaiuscula) { adicionaNaListaDePalavras(palavraMaiuscula); limparPalavraMaiuscula(); } private static void validacaoInicial(String original) throws StringVaziaException, CaracterEspecialException, IniciaComNumeroException { verificaStringVazia(original); verificaCaracterEspecial(original); verificaSeIniciaComNumero(original); } private static boolean palavraMaiusculaDeveSerAdicionadaALista(String original, char anterior, String palavraMaiuscula, int i) { return Character.isUpperCase(anterior) && !Character.isUpperCase(original.charAt(i)) && i > 1 && palavraMaiuscula.length() > 0; } private static void verificaCaracterEspecial(String original) throws CaracterEspecialException { for (int i = 0; i < original.length(); i++) { if (!Character.isLetterOrDigit(original.charAt(i))) throw new CaracterEspecialException( "Invlido - caracteres especiais no so permitidos, somente letras e nmeros"); } } private static void verificaStringVazia(String original) throws StringVaziaException { if (original.isEmpty()) throw new StringVaziaException("Invlido - a string est vazia"); } private static void verificaSeIniciaComNumero(String original) throws IniciaComNumeroException { if (Character.isDigit(original.charAt(0))) throw new IniciaComNumeroException("Invlido - no deve comear com nmeros"); } }
Python
UTF-8
4,554
3.359375
3
[ "BSD-3-Clause" ]
permissive
from __future__ import unicode_literals import six __all__ = [ 'to_formatted_text', 'is_formatted_text', 'Template', 'merge_formatted_text', 'FormattedText', ] def to_formatted_text(value, style='', auto_convert=False): """ Convert the given value (which can be formatted text) into a list of text fragments. (Which is the canonical form of formatted text.) The outcome is always a `FormattedText` instance, which is a list of (style, text) tuples. It can take an `HTML` object, a plain text string, or anything that implements `__pt_formatted_text__`. :param style: An additional style string which is applied to all text fragments. :param auto_convert: If `True`, also accept other types, and convert them to a string first. """ assert isinstance(style, six.text_type) if value is None: result = [] elif isinstance(value, six.text_type): result = [('', value)] elif isinstance(value, list): if len(value): assert isinstance(value[0][0], six.text_type), \ 'Expecting string, got: %r' % (value[0][0], ) assert isinstance(value[0][1], six.text_type), \ 'Expecting string, got: %r' % (value[0][1], ) result = value elif hasattr(value, '__pt_formatted_text__'): result = value.__pt_formatted_text__() elif callable(value): return to_formatted_text(value(), style=style) elif auto_convert: result = [('', '{}'.format(value))] else: raise ValueError('No formatted text. Expecting a unicode object, ' 'HTML, ANSI or a FormattedText instance. Got %r' % value) # Apply extra style. if style: try: result = [(style + ' ' + k, v) for k, v in result] except ValueError: # Too many values to unpack: # If the above failed, try the slower version (almost twice as # slow) which supports multiple items. This is used in the # `to_formatted_text` call in `FormattedTextControl` which also # accepts (style, text, mouse_handler) tuples. result = [(style + ' ' + item[0], ) + item[1:] for item in result] # Make sure the result is wrapped in a `FormattedText`. Among other # reasons, this is important for `print_formatted_text` to work correctly # and distinguish between lists and formatted text. if isinstance(result, FormattedText): return result else: return FormattedText(result) def is_formatted_text(value): """ Check whether the input is valid formatted text (for use in assert statements). In case of a callable, it doesn't check the return type. """ if callable(value): return True if isinstance(value, (six.text_type, list)): return True if hasattr(value, '__pt_formatted_text__'): return True return False class FormattedText(list): """ A list of ``(style, text)`` tuples. (In some situations, this can also be ``(style, text, mouse_handler)`` tuples.) """ def __pt_formatted_text__(self): return self def __repr__(self): return 'FormattedText(%s)' % ( super(FormattedText, self).__repr__()) class Template(object): """ Template for string interpolation with formatted text. Example:: Template(' ... {} ... ').format(HTML(...)) :param text: Plain text. """ def __init__(self, text): assert isinstance(text, six.text_type) assert '{0}' not in text self.text = text def format(self, *values): assert all(is_formatted_text(v) for v in values) def get_result(): # Split the template in parts. parts = self.text.split('{}') assert len(parts) - 1 == len(values) result = FormattedText() for part, val in zip(parts, values): result.append(('', part)) result.extend(to_formatted_text(val)) result.append(('', parts[-1])) return result return get_result def merge_formatted_text(items): """ Merge (Concatenate) several pieces of formatted text together. """ assert all(is_formatted_text(v) for v in items) def _merge_formatted_text(): result = FormattedText() for i in items: result.extend(to_formatted_text(i)) return result return _merge_formatted_text
TypeScript
UTF-8
740
2.953125
3
[ "MIT" ]
permissive
import File from '../../lib/java/io/File.js' import FileUtils from '../../lib/org/apache/commons/io/FileUtils.js' import * as YAML from 'yaml' export default class YAMLDatabase { file: File data: any = {} constructor(file: File) { this.file = file this.load() } load() { if (this.file.exists()) { const yamlStr = FileUtils.readFileToString(this.file, 'UTF-8') const data = YAML.parse(yamlStr) this.data = data } else { FileUtils.writeStringToFile(this.file, '{}', 'UTF-8') this.data = {} } } save() { const yamlStr = this.stringify() FileUtils.writeStringToFile(this.file, yamlStr, 'UTF-8') } stringify(): string { return YAML.stringify(this.data) } }
Java
UTF-8
795
2.234375
2
[ "MIT" ]
permissive
package TypewiseAlert.alert; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import TypewiseAlert.model.BreachType; import static org.junit.Assert.*; /** * @author Shrinidhi Muralidhar Karanam on 2021-04-13 */ public class ConsoleAlertControllerTest extends AlertControllerTest{ private final AlertController alertController; public ConsoleAlertControllerTest(BreachType breachType) { super(breachType); alertController = new ConsoleAlertController(); } @Test public void testReport() { String message = alertController.report(breachType); assertEquals(String.format("65261 : %s\n", breachType.getValue()), message); } }
Rust
UTF-8
121
3.203125
3
[ "Unlicense" ]
permissive
fn main() { let mut tot=0; for i in 1..1000 { if i%3==0||i%5==0 {tot+=i;} } println!("{}",tot); }
PHP
UTF-8
11,214
2.515625
3
[]
no_license
<?php namespace App\Service; use App\Jobs\WhoisStorage; use App\Utils\CommonUtil; use App\Utils\DomainUtil; use Carbon\Carbon; use Illuminate\Support\Facades\Redis; class WhoisService extends BaseService { /** * 域名Whois查询 * @param $domain * @param bool $fresh * @return array */ public function check($domain, $fresh = false) { $domain = DomainUtil::getTopDomain(trim($domain)); $domain = DomainUtil::punycode_encode($domain); $whois_info = $this->get_whois_info($domain, $fresh); $whois_info_arr = $this->whois_info_parse($whois_info['info']); return compact('domain', 'whois_info', 'whois_info_arr'); } /** * whois查询 * @param $domain * @param bool $fresh * @return array|mixed */ public function get_whois_info($domain, $fresh = false) { $updated_at = Carbon::now()->format('Y-m-d H:i'); if ($fresh) { $data = $this->execWhois($domain, $updated_at); return $data; } else { if (!$whois_info = Redis::hget('whois', $domain)) { $data = $this->execWhois($domain, $updated_at); return $data; } else { return json_decode($whois_info, 'true'); } } } /** * whois数据格式化 * @param $whoisInfoStr * @return array */ public function whois_info_parse($whoisInfoStr) { $infoData = []; $domainName = ''; if (preg_match("/Domain\s*Name:\s*(.*?)\\n/i", $whoisInfoStr, $matchs)) { $domainName = $matchs[1]; } $infoData['domain_name'] = DomainUtil::punycode_decode(trim(DomainUtil::getTopDomain($domainName))); $suffixSplit = explode('.', $domainName); $suffixStr = '.' . array_pop($suffixSplit); $whoisInfoList = explode("\n", $whoisInfoStr); if ($suffixStr == '.cn' || $suffixStr == '.中国') { foreach ($whoisInfoList as $key => $value) { $splitTemp = explode(':', $value, 2); $splitTemp[0] = str_replace(array("\r\n", "\n"), '', $splitTemp[0]); // 所有者联系邮箱 if (strpos($value, 'Contact Email') !== false && preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/', trim($splitTemp[1]))) { $infoData['Registrant_Email'] = trim($splitTemp[1]); } // 所有者联系电话 if (strpos($value, 'Contact Phone') !== false) { $temp = trim($splitTemp[1]); $infoData['Registrant_Phone'] = substr($temp, strpos($temp, '.') + 1); } //注册商 elseif (strpos($value, 'Sponsoring Registrar') !== false) { $infoData['Registrar'] = trim($splitTemp[1]); } //注册者 elseif ($splitTemp[0] == 'Registrant') { $infoData['Registrant_Name'] = trim($splitTemp[1]); } //注册日期 elseif (strpos($value, 'Registration Time') !== false) { $infoData['Creation_Date'] = trim($splitTemp[1]); } //到期日期 elseif (strpos($value, 'Expiration Time') !== false) { $infoData['Expiration_Date'] = trim($splitTemp[1]); } //DNS服务器 elseif (strpos($value, 'Name Server') !== false) { if (empty($infoData['Name_Server'])) $infoData['Name_Server'] = array(); $infoData['Name_Server'][] = trim($splitTemp[1]); } //域名状态 elseif (strpos($value, 'Domain Status') !== false) { if (empty($infoData['Domain_Status'])) $infoData['Domain_Status'] = array(); $value = trim($splitTemp[1]); if (strpos($value, 'clientDeleteProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_CLIENT_DELETE_PROHIBIT') . $value; //(注册商设置禁止删除) } elseif (strpos($value, 'clientTransferProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_CLIENT_TRANSFER_PROHIBIT') . $value; //(注册商设置禁止转移) } elseif (strpos($value, 'clientUpdateProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_CLIENT_UPDATE_PROHIBIT') . $value; //'(注册商设置禁止更新)' } elseif (strpos($value, 'serverDeleteProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_SERVER_DELETE_PROHIBIT') . $value; //(注册局设置禁止删除) } elseif (strpos($value, 'serverTransferProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_SERVER_TRANSFER_PROHIBIT') . $value; //(注册局设置禁止转移) } elseif (strpos($value, 'serverUpdateProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_SERVER_UPDATE_PROHIBIT') . $value; //'(注册局设置禁止更新)' } $infoData['Domain_Status'][] = $value; } } return $infoData; } else { foreach ($whoisInfoList as $key => $value) { $splitTemp = explode(':', $value, 2); // $splitTemp[0] = str_replace(array("\r\n","\n"), '', $splitTemp[0]); //所有者 if (strpos($value, 'Registrant Name') !== false && strpos($value, 'PRIVACY') === false) { if ($temp = trim($splitTemp[1])) { $infoData['Registrant_Name'] = $temp; } } // 所有者联系邮箱 elseif (strpos($value, 'Registrant Email') !== false && preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/', trim($splitTemp[1]))) { $infoData['Registrant_Email'] = trim($splitTemp[1]); } // 所有者联系电话 if (strpos($value, 'Registrant Phone:') !== false && strpos($value, 'PRIVACY') === false) { $temp = trim($splitTemp[1]); if ($phone = substr($temp, strpos($temp, '.') + 1)) { $infoData['Registrant_Phone'] = $phone; } } //注册商 elseif (strpos($value, 'Registrar:') !== false) { $infoData['Registrar'] = trim($splitTemp[1]); } //注册日期 elseif (strpos($value, 'Creation Date') !== false) { $data = trim($splitTemp[1]); $dataSplit = explode('T', $data); $infoData['Creation_Date'] = $dataSplit[0]; } //到期日期 elseif (strpos($value, 'Expiration Date') !== false) { $data = trim($splitTemp[1]); $dataSplit = explode('T', $data); $infoData['Expiration_Date'] = $dataSplit[0]; } elseif (strpos($value, 'Registry Expiry Date') !== false) { $data = trim($splitTemp[1]); $dataSplit = explode('T', $data); $infoData['Expiration_Date'] = $dataSplit[0]; } elseif (strpos($value, 'Updated Date') !== false) { $data = trim($splitTemp[1]); $dataSplit = explode('T', $data); $infoData['Updated_Date'] = $dataSplit[0]; } //域名状态 elseif (strpos($value, 'Domain Status') !== false) { if (empty($infoData['Domain_Status'])) $infoData['Domain_Status'] = array(); $value = trim($splitTemp[1]); if (strpos($value, 'clientDeleteProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_CLIENT_DELETE_PROHIBIT') . $value; //(注册局设置禁止删除) } elseif (strpos($value, 'clientTransferProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_CLIENT_TRANSFER_PROHIBIT') . $value; //(注册局设置禁止转移) } elseif (strpos($value, 'clientUpdateProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_CLIENT_UPDATE_PROHIBIT') . $value; //'(注册商设置禁止更新)' } elseif (strpos($value, 'serverDeleteProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_SERVER_DELETE_PROHIBIT') . $value; //(注册局设置禁止删除) } elseif (strpos($value, 'serverTransferProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_SERVER_TRANSFER_PROHIBIT') . $value; //(注册局设置禁止转移) } elseif (strpos($value, 'serverUpdateProhibited') !== false) { $value = __('status.WHOIS_DOMAIN_STATUS_SERVER_UPDATE_PROHIBIT') . $value; //'(注册商设置禁止更新)' } $infoData['Domain_Status'][] = $value; } //DNS服务器 elseif (strpos($value, 'Name Server') !== false) { if (empty($infoData['Name_Server'])) $infoData['Name_Server'] = array(); $infoData['Name_Server'][] = trim($splitTemp[1]); } } return $infoData; } } /** * 获取域名whois信息数组 * @param $domain * @param bool $fresh * @return array */ public function get_whois_info_arr($domain, $fresh = false) { $info = $this->get_whois_info($domain, $fresh); $info_arr = $this->whois_info_parse($info['info']); return $info_arr; } /** * 命令行查询whois * @param $domain * @param $updated_at * @return array */ private function execWhois($domain, $updated_at) { $whois_command = config('tool.whois_command'); $whois_info_str = CommonUtil::exec_timeout($whois_command . ' ' . $domain, 3); //截取whois原始信息,部分插件会整理出2种格式信息 $whois_info_str = substr($whois_info_str, strrpos($whois_info_str, 'Domain Name: ')); if (strpos($whois_info_str, 'Domain Name:') !== false) { Redis::hset('whois', $domain, json_encode(['updated_at' => $updated_at, 'info' => $whois_info_str])); } return ['updated_at' => $updated_at, 'info' => $whois_info_str]; } }
C++
UTF-8
7,950
3.28125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include <time.h> #include <iostream> #include <string> #define MAX_WIDTH 14 #define MAX_BOARD_SIZE (MAX_WIDTH * MAX_WIDTH) int g_Ply = 3; int g_Trials = 100; void tune_depth(int width) { if (width <= 7) g_Ply = 4; else g_Ply = 3; if (width <= 10) g_Trials = 100; else if (width <= 12) g_Trials = 75; else g_Trials = 50; } char opponent(char player) { return (player == '1') ? '2' : '1'; } class GameState { int rows, cols; int expected_result; char to_play; char board[MAX_BOARD_SIZE]; int run_length(char c, int row, int col, int dr, int dc) const { int length = 0; while(row >= 0 && row < rows && col >= 0 && col < cols && cell(row, col) == c) { if (++length == 3) break; row += dr; col += dc; } return length; } public: GameState() : rows(0), cols(0), to_play('0'), expected_result(-1) {} GameState(int _rows, int _cols, char _to_play) : rows(_rows), cols(_cols), to_play(_to_play), expected_result(-1) { memset(board, '0', rows * cols); } explicit GameState(const GameState& rhs) : rows(rhs.rows), cols(rhs.cols), expected_result(rhs.expected_result), to_play(rhs.to_play) { memcpy(board, rhs.board, rows * cols); } inline int width() const { return cols; } inline int height() const { return rows; } inline char turn() const { return to_play; } inline int test_value() const { return expected_result; } // protocol (newline separated) // [optional] !test_result (expected column to play in) // player # 1 or 2; 0 means exit (game over) // height // width // board (`height` lines of width `width` containing '0', '1', and '2') // the column to play in is returned bool read() { std::string line; std::getline(std::cin, line); if (line[0] == '!') { expected_result = atoi(line.c_str() + 1); std::getline(std::cin, line); } to_play = line[0]; if (to_play == '0') return false; std::getline(std::cin, line); rows = atoi(line.c_str()); std::getline(std::cin, line); cols = atoi(line.c_str()); if (cols > MAX_WIDTH || rows * cols > MAX_BOARD_SIZE) { std::cerr << "Board too large\n"; exit(1); } if (rows * cols == 0) return false; char *row_data = &board[0]; for(int row = 0; row < rows; ++row) { std::getline(std::cin, line); if (line.size() != cols) { std::cerr << "Invalid line length: expected " << cols << "columns:\n" << line << std::endl; exit(1); } memcpy(row_data, line.c_str(), cols); row_data += cols; } return true; } inline char cell(int row, int col) const { return board[row * cols + col]; } inline char &cell(int row, int col) { return board[row * cols + col]; } inline bool column_full(int col) const { return cell(0, col) != '0'; } // test whether the piece just played forms a win // return the player name ('1' or '2') or '0' otherwise char check_state(int play_row, int play_col) const { char c = cell(play_row, play_col); if (c != '0') { // horizontal if (1 + run_length(c, play_row, play_col - 1, 0, -1) + run_length(c, play_row, play_col + 1, 0, 1) >= 4) return c; // vertical if (1 + run_length(c, play_row - 1, play_col, -1, 0) + run_length(c, play_row + 1, play_col, 1, 0) >= 4) return c; // slash if (1 + run_length(c, play_row - 1, play_col + 1, -1, 1) + run_length(c, play_row + 1, play_col - 1, 1, -1) >= 4) return c; // backslash if (1 + run_length(c, play_row - 1, play_col - 1, -1, -1) + run_length(c, play_row + 1, play_col + 1, 1, 1) >= 4) return c; } return '0'; } // returns the row the piece landed in int make_play(int col) { int row = rows - 1; while (row >= 0) { if (cell(row, col) == '0') { cell(row, col) = to_play; to_play = opponent(to_play); return row; } --row; } std::cerr << "Invalid move attempted. :(\n"; exit(1); } // populates moves; returns number of moves int legal_moves(int moves[MAX_WIDTH]) const { int count = 0; for(int i = 0; i < cols; ++i) if (!column_full(i)) moves[count++] = i; return count; } int random_move() const { int moves[MAX_WIDTH]; int count = legal_moves(moves); if (count == 0) return -1; return moves[rand() % count]; } void print(std::ostream &str) const { str << "to play: " << to_play << '\n'; for(int i = 0; i < rows; ++i) { for(int j = 0; j < cols; ++j) { str << cell(i, j); } str << '\n'; } } }; // given the state, player, and move to make, return the probability of a win // examine all subgames to g_Ply and then do g_Trials random games from each leaf double evaluate_move(const GameState &game, int move, int depth = 0) { GameState sim(game); char me = sim.turn(); // apply move and check for endgame condition int row = sim.make_play(move); char res = sim.check_state(row, move); if (res == me) return 1.0; // win! else if (res != '0') return 0.0; // lose! if (depth < g_Ply) { // find opponent's best move double best_prob = 0.0; for(int col = 0; col < sim.width(); ++col) { if (sim.column_full(col)) continue; double prob = evaluate_move(sim, col, depth + 1); if (prob > best_prob) best_prob = prob; } // invert to return _my_ probability of winning return 1.0 - best_prob; } else { // play randomly from here to the end a bunch of times // and return the fraction of trials we win int wins = 0; for(int trial = 0; trial < g_Trials; ++trial) { GameState sub(sim); for(;;) { int col = sub.random_move(); if (col < 0) break; int row = sub.make_play(col); char result = sub.check_state(row, col); if (result == me) ++wins; if (result != '0') break; } } return (double)wins / g_Trials; } } struct ThreadState { pthread_t thread_id; const GameState *game; int col; double prob; }; void *thread_proc(void *param) { ThreadState *ts = (ThreadState *)param; ts->prob = evaluate_move(*(ts->game), ts->col); return NULL; } int play(const GameState &game) { ThreadState threads[MAX_WIDTH]; tune_depth(game.width()); for(int col = 0; col < game.width(); ++col) { threads[col].thread_id = 0; threads[col].game = &game; threads[col].col = col; threads[col].prob = -1.0; if (game.column_full(col)) continue; pthread_create(&threads[col].thread_id, NULL, thread_proc, &threads[col]); } int best_col = 0; for(int col = 0; col < game.width(); ++col) { if (threads[col].thread_id != 0) pthread_join(threads[col].thread_id, NULL); fprintf(stderr, "%1.2f ", threads[col].prob); if (threads[col].prob > threads[best_col].prob) best_col = col; } fprintf(stderr, "\n"); return best_col; } int main(int argc, char **argv) { srand(time(0)); if (argc >= 3 && 0 == strcmp(argv[1], "--benchmark")) { int size = atoi(argv[2]); if (size < 4 || size > MAX_WIDTH) { std::cerr << "invalid size; use --benchmark N, where 4 <= N <= " << MAX_WIDTH << std::endl; return 1; } GameState blank(size, size, '1'); play(blank); return 0; } GameState game; while(game.read()) { int move = play(game); int test = game.test_value(); if (test >= 0) { if (move != test) { std::cerr << "test failed: expected " << test << "; actual " << move << std::endl; game.print(std::cerr); } } std::cout << move << std::endl; } return 0; }
Markdown
UTF-8
829
2.640625
3
[]
no_license
--- layout: default title: 入职流程与训练 lang: zh-cn description: 如何快速上手工作! --- 当您在入职过程中,我们会提供您相关的资料让您熟悉工作并快速上手,请先完成以下的步骤: 1. 填写[背景调查表](https://forms.gle/Heimpw1gFko2k37Z6){:target="_blank"} 1. 认识你的队友。 1. 熟悉我们的[公司理念]({{ site.baseurl }}/{{ page.lang }}{{site.link_jd_culture}})和所有工作期望。 1. 工具和环境设置。 1. 如果是工程师,请检阅[工程流程]({{ site.baseurl }}/{{ page.lang }}{{ site.link_engineering }})。 1. 如果您是前端或后端工程师,我们会进行3到6个月的**[全端培训计划]({{ site.link_fullstack_training }})**。 [入职流程]({{ site.baseurl }}/{{ page.lang }}/people/onboarding.html){: .btn#page-btn}
Java
UTF-8
3,289
2.25
2
[]
no_license
package com.du.quartz.controller; import com.du.quartz.domain.AppQuartz; import com.du.quartz.service.JobService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @Title * @ClassName JobController * @Author jsb_pbk * @Date 2019/2/26 */ @RestController @RequestMapping(value = "job") public class JobController { @Autowired JobService jobService; //添加一个job @RequestMapping(value="/addJob",method= RequestMethod.POST) public String addJob(@RequestBody AppQuartz appQuartz) throws Exception { return jobService.addJob(appQuartz); } //暂停job @RequestMapping(value="/pauseJob",method=RequestMethod.POST) public String pauseJob(@RequestBody Integer[]quartzIds) throws Exception { AppQuartz appQuartz=null; if(quartzIds.length>0){ for(Integer quartzId:quartzIds) { jobService.pauseJob(appQuartz.getJobName(), appQuartz.getJobGroup()); } return "success pauseJob"; }else { return "fail pauseJob"; } } //恢复job @RequestMapping(value="/resumeJob",method=RequestMethod.POST) public String resumeJob(@RequestBody Integer[]quartzIds) throws Exception { AppQuartz appQuartz=null; if(quartzIds.length>0) { for(Integer quartzId:quartzIds) { //appQuartz=appQuartzService.selectAppQuartzByIdSer(quartzId).get(0); jobService.resumeJob(appQuartz.getJobName(), appQuartz.getJobGroup()); } return "success resumeJob"; }else { return "fail resumeJob"; } } //删除job @RequestMapping(value="/deletJob",method=RequestMethod.POST) public String deletJob(@RequestBody Integer[]quartzIds) throws Exception { AppQuartz appQuartz=null; for(Integer quartzId:quartzIds) { //appQuartz=appQuartzService.selectAppQuartzByIdSer(quartzId).get(0); String ret=jobService.deleteJob(appQuartz); if("success".equals(ret)) { //appQuartzService.deleteAppQuartzByIdSer(quartzId); } } return "success deleteJob"; } //修改 @RequestMapping(value="/updateJob",method=RequestMethod.POST) public String modifyJob(@RequestBody AppQuartz appQuartz) throws Exception { String ret= jobService.modifyJob(appQuartz); if("success".equals(ret)) { //appQuartzService.updateAppQuartzSer(appQuartz); return "success updateJob"; }else { return "fail updateJob"; } } //暂停所有 @RequestMapping(value="/pauseAll",method=RequestMethod.GET) public String pauseAllJob() throws Exception { jobService.pauseAllJob(); return "success pauseAll"; } //恢复所有 @RequestMapping(value="/repauseAll",method=RequestMethod.GET) public String repauseAllJob() throws Exception { jobService.resumeAllJob(); return "success"; } }
Python
UTF-8
4,044
2.828125
3
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license" ]
permissive
# Copyright The Lightning team. # # 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. from typing import Optional, Tuple import torch from torch import Tensor from torch.nn.functional import pad from torchmetrics.utilities.checks import _check_retrieval_functional_inputs from torchmetrics.utilities.data import _cumsum def retrieval_precision_recall_curve( preds: Tensor, target: Tensor, max_k: Optional[int] = None, adaptive_k: bool = False ) -> Tuple[Tensor, Tensor, Tensor]: """Compute precision-recall pairs for different k (from 1 to `max_k`). In a ranked retrieval context, appropriate sets of retrieved documents are naturally given by the top k retrieved documents. Recall is the fraction of relevant documents retrieved among all the relevant documents. Precision is the fraction of relevant documents among all the retrieved documents. For each such set, precision and recall values can be plotted to give a recall-precision curve. ``preds`` and ``target`` should be of the same shape and live on the same device. If no ``target`` is ``True``, ``0`` is returned. ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``, otherwise an error is raised. Args: preds: estimated probabilities of each document to be relevant. target: ground truth about each document being relevant or not. max_k: Calculate recall and precision for all possible top k from 1 to max_k (default: `None`, which considers all possible top k) adaptive_k: adjust `max_k` to `min(max_k, number of documents)` for each query Returns: Tensor with the precision values for each k (at ``top_k``) from 1 to `max_k` Tensor with the recall values for each k (at ``top_k``) from 1 to `max_k` Tensor with all possibles k Raises: ValueError: If ``max_k`` is not `None` or an integer larger than 0. ValueError: If ``adaptive_k`` is not boolean. Example: >>> from torch import tensor >>> from torchmetrics.functional import retrieval_precision_recall_curve >>> preds = tensor([0.2, 0.3, 0.5]) >>> target = tensor([True, False, True]) >>> precisions, recalls, top_k = retrieval_precision_recall_curve(preds, target, max_k=2) >>> precisions tensor([1.0000, 0.5000]) >>> recalls tensor([0.5000, 0.5000]) >>> top_k tensor([1, 2]) """ preds, target = _check_retrieval_functional_inputs(preds, target) if not isinstance(adaptive_k, bool): raise ValueError("`adaptive_k` has to be a boolean") if max_k is None: max_k = preds.shape[-1] if not (isinstance(max_k, int) and max_k > 0): raise ValueError("`max_k` has to be a positive integer or None") if adaptive_k and max_k > preds.shape[-1]: topk = torch.arange(1, preds.shape[-1] + 1, device=preds.device) topk = pad(topk, (0, max_k - preds.shape[-1]), "constant", float(preds.shape[-1])) else: topk = torch.arange(1, max_k + 1, device=preds.device) if not target.sum(): return torch.zeros(max_k, device=preds.device), torch.zeros(max_k, device=preds.device), topk relevant = target[preds.topk(min(max_k, preds.shape[-1]), dim=-1)[1]].float() relevant = _cumsum(pad(relevant, (0, max(0, max_k - len(relevant))), "constant", 0.0), dim=0) recall = relevant / target.sum() precision = relevant / topk return precision, recall, topk
Java
UTF-8
255
2.3125
2
[]
no_license
package cn.com.cootoo.design.proxy; /** * Created by system * Date 2020/1/17 4:11 下午 * Description */ public class RealSubject implements Subject { @Override public void request() { System.out.println("do real subject "); } }
Java
UTF-8
2,008
2.03125
2
[]
no_license
package com.sobjectparser; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Controller; import com.sobjectparser.directory.DirectoryReader; import com.sobjectparser.report.PDFReport; import com.sobjectparser.xml.DataloaderBeanBuilder; import com.sobjectparser.xml.XMLReader; @Controller public class BaseController { public static String SRCFOLDER = "Input/"; public static String DESTFOLDER = "Output/"; @Autowired PDFReport pdfReport; @Autowired DataloaderBeanBuilder beanBuilder; @Autowired DirectoryReader directoryReader; @Autowired XMLReader xmlReader; @Value("#{'${xmlExpressions}'.split(',')}") List<String> expressions; public BaseController(){ } public void resolveForPDF(){ System.out.println(expressions); List<String> filenames = directoryReader.read(SRCFOLDER); for(String fileName : filenames){ System.out.println(fileName); Map<String, List<String>> fieldsMapping = xmlReader.read(fileName, expressions); PDFReport.MakeFieldsPDF(fileName, fieldsMapping); } } public void resolveForDataloader(){ System.out.println(expressions); List<String> filenames = directoryReader.read(SRCFOLDER); for(String fileName : filenames){ System.out.println(fileName); Map<String, List<String>> fieldsMapping = xmlReader.read(fileName, expressions); beanBuilder.buildDocument(fileName, fieldsMapping); } beanBuilder.gustavo(); } public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("context.xml"); BaseController controller = (BaseController) context.getBean(BaseController.class); //controller.resolveForPDF(); controller.resolveForDataloader(); } }
C++
UTF-8
826
2.53125
3
[]
no_license
#include<iostream> #include<set> using namespace std; const int maxn = 5e4+ 10; int cnt[maxn]; struct node{ int num, cnt; node(int _num, int _cnt): num(_num), cnt(_cnt){} bool operator <(const node& a)const { if(cnt != a.cnt) return cnt > a.cnt; else return num < a.num; } }; set<node> ans; int n, t; int main(){ scanf("%d%d", &n, &t); int temp; scanf("%d", &temp); ans.insert(node{temp, 1}); ++cnt[temp]; for(int i = 1; i < n; ++i){ scanf("%d", &temp); printf("%d: ", temp); set<node>::iterator it; int count = 0; for(it = ans.begin(); it != ans.end() && count < t; ++it){ if(count++ != 0) printf(" "); printf("%d", it->num); } it = ans.find(node{temp, cnt[temp]}); if(it != ans.end()) ans.erase(it); ++cnt[temp]; ans.insert(node{temp, cnt[temp]}); printf("\n"); } return 0; }
SQL
UTF-8
1,278
3.703125
4
[]
no_license
create table individuals( id serial primary key, first_name varchar(25), last_name varchar(40), date_of_birth date, date_of_death date ); --not used create table relationships_types( relationship_type_code serial primary key, relationship_type_description varchar(40) ); create table roles( role_code serial primary key, role_description varchar(40) ); create table relationships( relationship_id serial primary key, individual_id serial references individuals(id), releationship_type_code serial references relationships_types(relationship_type_code), individual_1_role_code serial references roles(role_code) ); CREATE SEQUENCE primary_key_seq start 1 increment 1 NO MAXVALUE CACHE 1; insert into roles (role_code, role_description) values (1, 'Son'); insert into roles (role_code, role_description) values (2, 'Daughter'); insert into roles (role_code, role_description) values (3, 'Father'); insert into roles (role_code, role_description) values (5, 'Mother'); insert into roles (role_code, role_description) values (6, 'Grandfather'); insert into roles (role_code, role_description) values (7, 'Grandmother'); insert into roles (role_code, role_description) values (8, 'Wife'); insert into roles (role_code, role_description) values (9, 'Husband');